PaymentProviderEntities.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628
  1. // @ts-check
  2. /**
  3. * @import { PaymentProvider } from '../../../../types/subscription/dashboard/subscription'
  4. * @import { CurrencyCode, StripeCurrencyCode } from '../../../../types/subscription/currency'
  5. * @import { AddOn } from '../../../../types/subscription/plan'
  6. */
  7. const OError = require('@overleaf/o-error')
  8. const { DuplicateAddOnError, AddOnNotPresentError } = require('./Errors')
  9. const PlansLocator = require('./PlansLocator')
  10. const SubscriptionHelper = require('./SubscriptionHelper')
  11. const { AI_ADD_ON_CODE, isStandaloneAiAddOnPlanCode } = require('./AiHelper')
  12. const MEMBERS_LIMIT_ADD_ON_CODE = 'additional-license'
  13. class PaymentProviderSubscription {
  14. /**
  15. * @param {object} props
  16. * @param {string} props.id
  17. * @param {string} props.userId
  18. * @param {string} props.planCode
  19. * @param {string} props.planName
  20. * @param {number} props.planPrice
  21. * @param {PaymentProviderSubscriptionAddOn[]} [props.addOns]
  22. * @param {number} props.subtotal
  23. * @param {number} [props.taxRate]
  24. * @param {number} [props.taxAmount]
  25. * // Recurly uses uppercase currency codes, but Stripe uses lowercase
  26. * @param {CurrencyCode | StripeCurrencyCode} props.currency
  27. * @param {number} props.total
  28. * @param {Date} props.periodStart
  29. * @param {Date} props.periodEnd
  30. * @param {string} props.collectionMethod
  31. * @param {number} [props.netTerms]
  32. * @param {string} [props.poNumber]
  33. * @param {string} [props.termsAndConditions]
  34. * @param {PaymentProviderSubscriptionChange} [props.pendingChange]
  35. * @param {PaymentProvider['service']} [props.service]
  36. * @param {string} [props.state]
  37. * @param {Date|null} [props.trialPeriodStart]
  38. * @param {Date|null} [props.trialPeriodEnd]
  39. * @param {Date|null} [props.pausePeriodStart]
  40. * @param {number|null} [props.remainingPauseCycles]
  41. */
  42. constructor(props) {
  43. this.id = props.id
  44. this.userId = props.userId
  45. this.planCode = props.planCode
  46. this.planName = props.planName
  47. this.planPrice = props.planPrice
  48. this.addOns = props.addOns ?? []
  49. this.subtotal = props.subtotal
  50. this.taxRate = props.taxRate ?? 0
  51. this.taxAmount = props.taxAmount ?? 0
  52. this.currency = props.currency.toUpperCase() // ensure that currency codes are always uppercase
  53. this.total = props.total
  54. this.periodStart = props.periodStart
  55. this.periodEnd = props.periodEnd
  56. this.collectionMethod = props.collectionMethod
  57. this.netTerms = props.netTerms ?? 0
  58. this.poNumber = props.poNumber ?? ''
  59. this.termsAndConditions = props.termsAndConditions ?? ''
  60. this.pendingChange = props.pendingChange ?? null
  61. this.service = props.service ?? 'recurly'
  62. this.state = props.state ?? 'active'
  63. this.trialPeriodStart = props.trialPeriodStart ?? null
  64. this.trialPeriodEnd = props.trialPeriodEnd ?? null
  65. this.pausePeriodStart = props.pausePeriodStart ?? null
  66. this.remainingPauseCycles = props.remainingPauseCycles ?? null
  67. }
  68. /**
  69. * Returns whether this subscription currently has the given add-on
  70. *
  71. * @param {string} code
  72. * @return {boolean}
  73. */
  74. hasAddOn(code) {
  75. return this.addOns.some(addOn => addOn.code === code)
  76. }
  77. /**
  78. * Returns whether this subscription is a standalone AI add-on subscription
  79. *
  80. * @return {boolean}
  81. */
  82. isStandaloneAiAddOn() {
  83. return isStandaloneAiAddOnPlanCode(this.planCode)
  84. }
  85. /**
  86. * Returns whether this subscription is a group subscription
  87. *
  88. * @return {boolean}
  89. */
  90. isGroupSubscription() {
  91. return PlansLocator.isGroupPlanCode(this.planCode)
  92. }
  93. /**
  94. * Returns whether this subcription will have the given add-on next billing
  95. * period.
  96. *
  97. * There are two cases: either the subscription already has the add-on and
  98. * won't change next period, or the subscription will change next period and
  99. * the change includes the add-on.
  100. *
  101. * @param {string} code
  102. * @return {boolean}
  103. */
  104. hasAddOnNextPeriod(code) {
  105. if (this.pendingChange != null) {
  106. return this.pendingChange.nextAddOns.some(addOn => addOn.code === code)
  107. } else {
  108. return this.hasAddOn(code)
  109. }
  110. }
  111. /**
  112. * Change this subscription's plan
  113. * @param {string} planCode - the new plan code
  114. * @param {number} [quantity] - the quantity of the plan
  115. * @param {boolean} [shouldChangeAtTermEnd] - whether the change should be applied at the end of the term
  116. * @return {PaymentProviderSubscriptionChangeRequest}
  117. */
  118. getRequestForPlanChange(planCode, quantity, shouldChangeAtTermEnd) {
  119. const changeRequest = new PaymentProviderSubscriptionChangeRequest({
  120. subscription: this,
  121. timeframe: shouldChangeAtTermEnd ? 'term_end' : 'now',
  122. planCode,
  123. })
  124. if (quantity !== 1) {
  125. // Only group plans in Stripe can have larger than 1 quantity
  126. // This is because in Stripe, the group plans are configued with per-seat pricing
  127. // and the quantity is the number of seats
  128. // Setting the members limit add-on quantity accordingly
  129. // so it is compitible with Recurly's group plan model (1 base plan + add-on for each member)
  130. changeRequest.addOnUpdates = [
  131. new PaymentProviderSubscriptionAddOnUpdate({
  132. code: MEMBERS_LIMIT_ADD_ON_CODE,
  133. quantity,
  134. }),
  135. ]
  136. }
  137. // Carry the AI add-on to the new plan if applicable
  138. if (
  139. this.isStandaloneAiAddOn() ||
  140. (!shouldChangeAtTermEnd && this.hasAddOn(AI_ADD_ON_CODE)) ||
  141. (shouldChangeAtTermEnd && this.hasAddOnNextPeriod(AI_ADD_ON_CODE))
  142. ) {
  143. const addOnUpdate = new PaymentProviderSubscriptionAddOnUpdate({
  144. code: AI_ADD_ON_CODE,
  145. quantity: 1,
  146. })
  147. changeRequest.addOnUpdates = changeRequest.addOnUpdates
  148. ? [...changeRequest.addOnUpdates, addOnUpdate]
  149. : [addOnUpdate]
  150. }
  151. return changeRequest
  152. }
  153. /**
  154. * Purchase an add-on on this subscription
  155. *
  156. * @param {string} code
  157. * @param {number} [quantity]
  158. * @param {number} [unitPrice]
  159. * @return {PaymentProviderSubscriptionChangeRequest} - the change request to send to
  160. * Recurly
  161. *
  162. * @throws {DuplicateAddOnError} if the add-on is already present on the subscription
  163. */
  164. getRequestForAddOnPurchase(code, quantity = 1, unitPrice) {
  165. if (this.hasAddOn(code)) {
  166. throw new DuplicateAddOnError('Subscription already has add-on', {
  167. subscriptionId: this.id,
  168. addOnCode: code,
  169. })
  170. }
  171. const addOnUpdates = this.addOns.map(addOn => addOn.toAddOnUpdate())
  172. addOnUpdates.push(
  173. new PaymentProviderSubscriptionAddOnUpdate({ code, quantity, unitPrice })
  174. )
  175. return new PaymentProviderSubscriptionChangeRequest({
  176. subscription: this,
  177. timeframe: 'now',
  178. addOnUpdates,
  179. })
  180. }
  181. /**
  182. * Update an add-on on this subscription
  183. *
  184. * @param {string} code
  185. * @param {number} quantity
  186. * @return {PaymentProviderSubscriptionChangeRequest} - the change request to send to
  187. * Recurly
  188. *
  189. * @throws {AddOnNotPresentError} if the subscription doesn't have the add-on
  190. */
  191. getRequestForAddOnUpdate(code, quantity) {
  192. if (!this.hasAddOn(code)) {
  193. throw new AddOnNotPresentError(
  194. 'Subscription does not have add-on to update',
  195. {
  196. subscriptionId: this.id,
  197. addOnCode: code,
  198. }
  199. )
  200. }
  201. const addOnUpdates = this.addOns.map(addOn => {
  202. const update = addOn.toAddOnUpdate()
  203. if (update.code === code) {
  204. update.quantity = quantity
  205. }
  206. return update
  207. })
  208. return new PaymentProviderSubscriptionChangeRequest({
  209. subscription: this,
  210. timeframe: 'now',
  211. addOnUpdates,
  212. })
  213. }
  214. /**
  215. * Remove an add-on from this subscription
  216. *
  217. * @param {string} code
  218. * @return {PaymentProviderSubscriptionChangeRequest}
  219. *
  220. * @throws {AddOnNotPresentError} if the subscription doesn't have the add-on
  221. */
  222. getRequestForAddOnRemoval(code) {
  223. if (!this.hasAddOn(code)) {
  224. throw new AddOnNotPresentError(
  225. 'Subscription does not have add-on to remove',
  226. {
  227. subscriptionId: this.id,
  228. addOnCode: code,
  229. }
  230. )
  231. }
  232. const addOnUpdates = this.addOns
  233. .filter(addOn => addOn.code !== code)
  234. .map(addOn => addOn.toAddOnUpdate())
  235. const isInTrial = SubscriptionHelper.isInTrial(this.trialPeriodEnd)
  236. return new PaymentProviderSubscriptionChangeRequest({
  237. subscription: this,
  238. timeframe: isInTrial ? 'now' : 'term_end',
  239. addOnUpdates,
  240. })
  241. }
  242. /**
  243. * Form a request to revert the plan to it's last saved backup state
  244. *
  245. * @param {string} previousPlanCode
  246. * @param {Array<AddOn> | null} previousAddOns
  247. * @return {PaymentProviderSubscriptionChangeRequest}
  248. *
  249. * @throws {OError} if the restore point plan doesnt exist
  250. */
  251. getRequestForPlanRevert(previousPlanCode, previousAddOns) {
  252. const lastSuccessfulPlan =
  253. PlansLocator.findLocalPlanInSettings(previousPlanCode)
  254. if (lastSuccessfulPlan == null) {
  255. throw new OError('Unable to find plan in settings', { previousPlanCode })
  256. }
  257. const changeRequest = new PaymentProviderSubscriptionChangeRequest({
  258. subscription: this,
  259. timeframe: 'now',
  260. planCode: previousPlanCode,
  261. })
  262. // defaulting to empty array is important, as that will wipe away any add-ons that were added in the failed payment
  263. // but were not part of the last successful subscription
  264. const addOns = []
  265. for (const previousAddon of previousAddOns || []) {
  266. const addOnUpdate = new PaymentProviderSubscriptionAddOnUpdate({
  267. code: previousAddon.addOnCode,
  268. quantity: previousAddon.quantity,
  269. unitPrice: previousAddon.unitAmountInCents / 100,
  270. })
  271. addOns.push(addOnUpdate)
  272. }
  273. changeRequest.addOnUpdates = addOns
  274. return changeRequest
  275. }
  276. /**
  277. * Upgrade group plan with the plan code provided
  278. *
  279. * @param {string} newPlanCode
  280. * @return {PaymentProviderSubscriptionChangeRequest}
  281. */
  282. getRequestForGroupPlanUpgrade(newPlanCode) {
  283. // Ensure all the existing add-ons are added to the new plan
  284. const addOns = this.addOns.map(
  285. addOn =>
  286. new PaymentProviderSubscriptionAddOnUpdate({
  287. code: addOn.code,
  288. quantity: addOn.quantity,
  289. })
  290. )
  291. return new PaymentProviderSubscriptionChangeRequest({
  292. subscription: this,
  293. timeframe: 'now',
  294. addOnUpdates: addOns,
  295. planCode: newPlanCode,
  296. })
  297. }
  298. /**
  299. * Update the "PO number" and "Terms and conditions" in a subscription
  300. *
  301. * @param {string} poNumber
  302. * @param {string} termsAndConditions
  303. * @return {PaymentProviderSubscriptionUpdateRequest} - the update request to send to
  304. * Recurly
  305. */
  306. getRequestForPoNumberAndTermsAndConditionsUpdate(
  307. poNumber,
  308. termsAndConditions
  309. ) {
  310. return new PaymentProviderSubscriptionUpdateRequest({
  311. subscription: this,
  312. poNumber,
  313. termsAndConditions,
  314. })
  315. }
  316. /**
  317. * Update the "Terms and conditions" in a subscription
  318. *
  319. * @param {string} termsAndConditions
  320. * @return {PaymentProviderSubscriptionUpdateRequest} - the update request to send to
  321. * Recurly
  322. */
  323. getRequestForTermsAndConditionsUpdate(termsAndConditions) {
  324. return new PaymentProviderSubscriptionUpdateRequest({
  325. subscription: this,
  326. termsAndConditions,
  327. })
  328. }
  329. /**
  330. * Returns whether this subscription is manually collected
  331. *
  332. * @return {boolean}
  333. */
  334. get isCollectionMethodManual() {
  335. return this.collectionMethod === 'manual'
  336. }
  337. /**
  338. * Determine if a plan change should be applied at the end of the term
  339. *
  340. * @param {string} newPlanCode
  341. * @returns {boolean}
  342. */
  343. shouldPlanChangeAtTermEnd(newPlanCode) {
  344. const currentPlan = PlansLocator.findLocalPlanInSettings(this.planCode)
  345. if (currentPlan == null) {
  346. throw new OError('Unable to find plan in settings', {
  347. planCode: this.planCode,
  348. })
  349. }
  350. const newPlan = PlansLocator.findLocalPlanInSettings(newPlanCode)
  351. if (newPlan == null) {
  352. throw new OError('Unable to find plan in settings', { newPlanCode })
  353. }
  354. const isInTrial = SubscriptionHelper.isInTrial(this.trialPeriodEnd)
  355. return SubscriptionHelper.shouldPlanChangeAtTermEnd(
  356. currentPlan,
  357. newPlan,
  358. isInTrial
  359. )
  360. }
  361. }
  362. /**
  363. * An add-on attached to a subscription
  364. */
  365. class PaymentProviderSubscriptionAddOn {
  366. /**
  367. * @param {object} props
  368. * @param {string} props.code
  369. * @param {string} props.name
  370. * @param {number} props.quantity
  371. * @param {number} props.unitPrice
  372. */
  373. constructor(props) {
  374. this.code = props.code
  375. this.name = props.name
  376. this.quantity = props.quantity
  377. this.unitPrice = props.unitPrice
  378. this.preTaxTotal = this.quantity * this.unitPrice
  379. }
  380. /**
  381. * Return an add-on update that doesn't modify the add-on
  382. */
  383. toAddOnUpdate() {
  384. return new PaymentProviderSubscriptionAddOnUpdate({
  385. code: this.code,
  386. quantity: this.quantity,
  387. unitPrice: this.unitPrice,
  388. })
  389. }
  390. }
  391. class PaymentProviderSubscriptionUpdateRequest {
  392. /**
  393. * @param {object} props
  394. * @param {PaymentProviderSubscription} props.subscription
  395. * @param {string} [props.poNumber]
  396. * @param {string} [props.termsAndConditions]
  397. */
  398. constructor(props) {
  399. this.subscription = props.subscription
  400. this.poNumber = props.poNumber ?? ''
  401. this.termsAndConditions = props.termsAndConditions ?? ''
  402. }
  403. }
  404. class PaymentProviderSubscriptionChangeRequest {
  405. /**
  406. * @param {object} props
  407. * @param {PaymentProviderSubscription} props.subscription
  408. * @param {"now" | "term_end"} props.timeframe
  409. * @param {string} [props.planCode]
  410. * @param {PaymentProviderSubscriptionAddOnUpdate[]} [props.addOnUpdates]
  411. */
  412. constructor(props) {
  413. if (props.planCode == null && props.addOnUpdates == null) {
  414. throw new OError('Invalid PaymentProviderSubscriptionChangeRequest', {
  415. props,
  416. })
  417. }
  418. this.subscription = props.subscription
  419. this.timeframe = props.timeframe
  420. this.planCode = props.planCode ?? null
  421. this.addOnUpdates = props.addOnUpdates ?? null
  422. }
  423. }
  424. class PaymentProviderSubscriptionAddOnUpdate {
  425. /**
  426. * @param {object} props
  427. * @param {string} props.code
  428. * @param {number} [props.quantity]
  429. * @param {number} [props.unitPrice]
  430. */
  431. constructor(props) {
  432. this.code = props.code
  433. this.quantity = props.quantity
  434. this.unitPrice = props.unitPrice ?? null
  435. }
  436. }
  437. class PaymentProviderSubscriptionChange {
  438. /**
  439. * @param {object} props
  440. * @param {PaymentProviderSubscription} props.subscription
  441. * @param {string} props.nextPlanCode
  442. * @param {string} props.nextPlanName
  443. * @param {number} props.nextPlanPrice
  444. * @param {PaymentProviderSubscriptionAddOn[]} props.nextAddOns
  445. * @param {PaymentProviderImmediateCharge} [props.immediateCharge]
  446. */
  447. constructor(props) {
  448. this.subscription = props.subscription
  449. this.nextPlanCode = props.nextPlanCode
  450. this.nextPlanName = props.nextPlanName
  451. this.nextPlanPrice = props.nextPlanPrice
  452. this.nextAddOns = props.nextAddOns
  453. this.immediateCharge =
  454. props.immediateCharge ??
  455. new PaymentProviderImmediateCharge({
  456. subtotal: 0,
  457. tax: 0,
  458. total: 0,
  459. discount: 0,
  460. })
  461. this.subtotal = this.nextPlanPrice
  462. for (const addOn of this.nextAddOns) {
  463. this.subtotal += addOn.preTaxTotal
  464. }
  465. this.tax = Math.round(this.subtotal * 100 * this.subscription.taxRate) / 100
  466. this.total = this.subtotal + this.tax
  467. }
  468. getAddOn(addOnCode) {
  469. return this.nextAddOns.find(addOn => addOn.code === addOnCode)
  470. }
  471. }
  472. class PaypalPaymentMethod {
  473. toString() {
  474. return 'Paypal'
  475. }
  476. }
  477. class CreditCardPaymentMethod {
  478. /**
  479. * @param {object} props
  480. * @param {string} props.cardType
  481. * @param {string} props.lastFour
  482. */
  483. constructor(props) {
  484. this.cardType = props.cardType
  485. this.lastFour = props.lastFour
  486. }
  487. toString() {
  488. return `${this.cardType} **** ${this.lastFour}`
  489. }
  490. }
  491. class PaymentProviderImmediateCharge {
  492. /**
  493. * @param {object} props
  494. * @param {number} props.subtotal
  495. * @param {number} props.tax
  496. * @param {number} props.total
  497. * @param {number} props.discount
  498. */
  499. constructor(props) {
  500. this.subtotal = props.subtotal
  501. this.tax = props.tax
  502. this.total = props.total
  503. this.discount = props.discount
  504. }
  505. }
  506. /**
  507. * An add-on configuration, independent of any subscription
  508. */
  509. class PaymentProviderAddOn {
  510. /**
  511. * @param {object} props
  512. * @param {string} props.code
  513. * @param {string} props.name
  514. */
  515. constructor(props) {
  516. this.code = props.code
  517. this.name = props.name
  518. }
  519. }
  520. /**
  521. * A plan configuration
  522. */
  523. class PaymentProviderPlan {
  524. /**
  525. * @param {object} props
  526. * @param {string} props.code
  527. * @param {string} props.name
  528. */
  529. constructor(props) {
  530. this.code = props.code
  531. this.name = props.name
  532. }
  533. }
  534. /**
  535. * A coupon in the payment provider
  536. */
  537. class PaymentProviderCoupon {
  538. /**
  539. * @param {object} props
  540. * @param {string} props.code
  541. * @param {string} props.name
  542. * @param {string} [props.description]
  543. */
  544. constructor(props) {
  545. this.code = props.code
  546. this.name = props.name
  547. this.description = props.description
  548. }
  549. }
  550. /**
  551. * An account in the payment provider
  552. */
  553. class PaymentProviderAccount {
  554. /**
  555. * @param {object} props
  556. * @param {string} props.code
  557. * @param {string} props.email
  558. * @param {boolean} props.hasPastDueInvoice
  559. */
  560. constructor(props) {
  561. this.code = props.code
  562. this.email = props.email
  563. this.hasPastDueInvoice = props.hasPastDueInvoice ?? false
  564. }
  565. }
  566. module.exports = {
  567. MEMBERS_LIMIT_ADD_ON_CODE,
  568. PaymentProviderSubscription,
  569. PaymentProviderSubscriptionAddOn,
  570. PaymentProviderSubscriptionChange,
  571. PaymentProviderSubscriptionChangeRequest,
  572. PaymentProviderSubscriptionUpdateRequest,
  573. PaymentProviderSubscriptionAddOnUpdate,
  574. PaypalPaymentMethod,
  575. CreditCardPaymentMethod,
  576. PaymentProviderAddOn,
  577. PaymentProviderPlan,
  578. PaymentProviderCoupon,
  579. PaymentProviderAccount,
  580. PaymentProviderImmediateCharge,
  581. }