RecurlyClientTests.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. const sinon = require('sinon')
  2. const { expect } = require('chai')
  3. const recurly = require('recurly')
  4. const SandboxedModule = require('sandboxed-module')
  5. const {
  6. RecurlySubscription,
  7. RecurlySubscriptionChangeRequest,
  8. RecurlySubscriptionAddOnUpdate,
  9. RecurlyAccount,
  10. RecurlyCoupon,
  11. } = require('../../../../app/src/Features/Subscription/RecurlyEntities')
  12. const MODULE_PATH = '../../../../app/src/Features/Subscription/RecurlyClient'
  13. describe('RecurlyClient', function () {
  14. beforeEach(function () {
  15. this.settings = {
  16. apis: {
  17. recurly: {
  18. apiKey: 'nonsense',
  19. privateKey: 'private_nonsense',
  20. },
  21. },
  22. plans: [],
  23. features: [],
  24. }
  25. this.user = { _id: '123456', email: 'joe@example.com', first_name: 'Joe' }
  26. this.subscriptionChange = { id: 'subscription-change-123' }
  27. this.recurlyAccount = new recurly.Account()
  28. Object.assign(this.recurlyAccount, {
  29. code: this.user._id,
  30. email: this.user.email,
  31. })
  32. this.subscriptionAddOn = {
  33. code: 'addon-code',
  34. name: 'My Add-On',
  35. quantity: 1,
  36. unitPrice: 2,
  37. preTaxTotal: 2,
  38. }
  39. this.subscription = new RecurlySubscription({
  40. id: 'subscription-id',
  41. userId: 'user-id',
  42. currency: 'EUR',
  43. planCode: 'plan-code',
  44. planName: 'plan-name',
  45. planPrice: 13,
  46. addOns: [this.subscriptionAddOn],
  47. subtotal: 15,
  48. taxRate: 0.1,
  49. taxAmount: 1.5,
  50. total: 16.5,
  51. periodStart: new Date(),
  52. periodEnd: new Date(),
  53. collectionMethod: 'automatic',
  54. })
  55. this.recurlySubscription = {
  56. uuid: this.subscription.id,
  57. account: {
  58. code: this.subscription.userId,
  59. },
  60. plan: {
  61. code: this.subscription.planCode,
  62. name: this.subscription.planName,
  63. },
  64. addOns: [
  65. {
  66. addOn: {
  67. code: this.subscriptionAddOn.code,
  68. name: this.subscriptionAddOn.name,
  69. },
  70. quantity: this.subscriptionAddOn.quantity,
  71. unitAmount: this.subscriptionAddOn.unitPrice,
  72. },
  73. ],
  74. unitAmount: this.subscription.planPrice,
  75. subtotal: this.subscription.subtotal,
  76. taxInfo: { rate: this.subscription.taxRate },
  77. tax: this.subscription.taxAmount,
  78. total: this.subscription.total,
  79. currency: this.subscription.currency,
  80. currentPeriodStartedAt: this.subscription.periodStart,
  81. currentPeriodEndsAt: this.subscription.periodEnd,
  82. collectionMethod: this.subscription.collectionMethod,
  83. }
  84. this.recurlySubscriptionChange = new recurly.SubscriptionChange()
  85. Object.assign(this.recurlySubscriptionChange, this.subscriptionChange)
  86. this.UserGetter = {
  87. promises: {
  88. getUser: sinon.stub().callsFake(userId => {
  89. if (userId === this.user._id) {
  90. return this.user
  91. }
  92. }),
  93. },
  94. }
  95. let client
  96. this.client = client = {
  97. getAccount: sinon.stub(),
  98. getBillingInfo: sinon.stub(),
  99. listAccountSubscriptions: sinon.stub(),
  100. listActiveCouponRedemptions: sinon.stub(),
  101. previewSubscriptionChange: sinon.stub(),
  102. }
  103. this.recurly = {
  104. errors: recurly.errors,
  105. Client: function () {
  106. return client
  107. },
  108. }
  109. this.Errors = {
  110. MissingBillingInfoError: class extends Error {},
  111. SubtotalLimitExceededError: class extends Error {},
  112. }
  113. return (this.RecurlyClient = SandboxedModule.require(MODULE_PATH, {
  114. globals: {
  115. console,
  116. },
  117. requires: {
  118. '@overleaf/settings': this.settings,
  119. recurly: this.recurly,
  120. '@overleaf/logger': {
  121. err: sinon.stub(),
  122. error: sinon.stub(),
  123. warn: sinon.stub(),
  124. log: sinon.stub(),
  125. debug: sinon.stub(),
  126. },
  127. '../User/UserGetter': this.UserGetter,
  128. './Errors': this.Errors,
  129. },
  130. }))
  131. })
  132. describe('initalizing recurly client with undefined API key parameter', function () {
  133. it('should create a client without error', function () {
  134. let testClient
  135. expect(() => {
  136. testClient = new recurly.Client(undefined)
  137. }).to.not.throw()
  138. expect(testClient).to.be.instanceOf(recurly.Client)
  139. })
  140. })
  141. describe('getAccountForUserId', function () {
  142. it('should return an Account if one exists', async function () {
  143. this.client.getAccount = sinon.stub().resolves(this.recurlyAccount)
  144. const account = await this.RecurlyClient.promises.getAccountForUserId(
  145. this.user._id
  146. )
  147. const expectedAccount = new RecurlyAccount({
  148. code: this.user._id,
  149. email: this.user.email,
  150. hasPastDueInvoice: false,
  151. })
  152. expect(account).to.deep.equal(expectedAccount)
  153. })
  154. it('should return null if no account found', async function () {
  155. this.client.getAccount = sinon
  156. .stub()
  157. .throws(new recurly.errors.NotFoundError())
  158. const account =
  159. await this.RecurlyClient.promises.getAccountForUserId('nonsense')
  160. expect(account).to.equal(null)
  161. })
  162. it('should re-throw caught errors', async function () {
  163. this.client.getAccount = sinon.stub().throws()
  164. await expect(
  165. this.RecurlyClient.promises.getAccountForUserId(this.user._id)
  166. ).to.eventually.be.rejectedWith(Error)
  167. })
  168. })
  169. describe('createAccountForUserId', function () {
  170. it('should return the Account as created by recurly', async function () {
  171. this.client.createAccount = sinon.stub().resolves(this.recurlyAccount)
  172. await expect(
  173. this.RecurlyClient.promises.createAccountForUserId(this.user._id)
  174. )
  175. .to.eventually.be.an.instanceOf(recurly.Account)
  176. .that.has.property('code', this.user._id)
  177. })
  178. it('should throw any API errors', async function () {
  179. this.client.createAccount = sinon.stub().throws()
  180. await expect(
  181. this.RecurlyClient.promises.createAccountForUserId(this.user._id)
  182. ).to.eventually.be.rejectedWith(Error)
  183. })
  184. })
  185. describe('getActiveCouponsForUserId', function () {
  186. it('should return an empty array if no coupons returned', async function () {
  187. this.client.listActiveCouponRedemptions.returns({
  188. each: async function* () {},
  189. })
  190. const coupons =
  191. await this.RecurlyClient.promises.getActiveCouponsForUserId('some-user')
  192. expect(coupons).to.deep.equal([])
  193. })
  194. it('should return a coupons returned by recurly', async function () {
  195. const recurlyCoupon = {
  196. coupon: {
  197. code: 'coupon-code',
  198. name: 'Coupon Name',
  199. hostedPageDescription: 'hosted page description',
  200. invoiceDescription: 'invoice description',
  201. },
  202. }
  203. this.client.listActiveCouponRedemptions.returns({
  204. each: async function* () {
  205. yield recurlyCoupon
  206. },
  207. })
  208. const coupons =
  209. await this.RecurlyClient.promises.getActiveCouponsForUserId('some-user')
  210. const expectedCoupons = [
  211. new RecurlyCoupon({
  212. code: 'coupon-code',
  213. name: 'Coupon Name',
  214. description: 'hosted page description',
  215. }),
  216. ]
  217. expect(coupons).to.deep.equal(expectedCoupons)
  218. })
  219. it('should not throw for Recurly not found error', async function () {
  220. this.client.listActiveCouponRedemptions = sinon
  221. .stub()
  222. .throws(new recurly.errors.NotFoundError())
  223. const coupons =
  224. await this.RecurlyClient.promises.getActiveCouponsForUserId('some-user')
  225. expect(coupons).to.deep.equal([])
  226. })
  227. it('should throw any other API errors', async function () {
  228. this.client.listActiveCouponRedemptions = sinon.stub().throws()
  229. await expect(
  230. this.RecurlyClient.promises.getActiveCouponsForUserId('some-user')
  231. ).to.eventually.be.rejectedWith(Error)
  232. })
  233. })
  234. describe('getSubscription', function () {
  235. it('should return the subscription found by recurly', async function () {
  236. this.client.getSubscription = sinon
  237. .stub()
  238. .withArgs('uuid-subscription-id')
  239. .resolves(this.recurlySubscription)
  240. const subscription = await this.RecurlyClient.promises.getSubscription(
  241. this.subscription.id
  242. )
  243. expect(subscription).to.deep.equal(this.subscription)
  244. })
  245. it('should throw any API errors', async function () {
  246. this.client.getSubscription = sinon.stub().throws()
  247. await expect(
  248. this.RecurlyClient.promises.getSubscription(this.user._id)
  249. ).to.eventually.be.rejectedWith(Error)
  250. })
  251. })
  252. describe('getSubscriptionForUser', function () {
  253. it("should return null if the account doesn't exist", async function () {
  254. this.client.listAccountSubscriptions.returns({
  255. // eslint-disable-next-line require-yield
  256. each: async function* () {
  257. throw new recurly.errors.NotFoundError('account not found')
  258. },
  259. })
  260. const subscription =
  261. await this.RecurlyClient.promises.getSubscriptionForUser('some-user')
  262. expect(subscription).to.be.null
  263. })
  264. it("should return null if the account doesn't have subscriptions", async function () {
  265. this.client.listAccountSubscriptions.returns({
  266. each: async function* () {},
  267. })
  268. const subscription =
  269. await this.RecurlyClient.promises.getSubscriptionForUser('some-user')
  270. expect(subscription).to.be.null
  271. })
  272. it('should return the subscription if the account has one subscription', async function () {
  273. const recurlySubscription = this.recurlySubscription
  274. this.client.listAccountSubscriptions.returns({
  275. each: async function* () {
  276. yield recurlySubscription
  277. },
  278. })
  279. const subscription =
  280. await this.RecurlyClient.promises.getSubscriptionForUser('some-user')
  281. expect(subscription).to.deep.equal(this.subscription)
  282. })
  283. it('should throw an error if the account has more than one subscription', async function () {
  284. const recurlySubscription = this.recurlySubscription
  285. this.client.listAccountSubscriptions.returns({
  286. each: async function* () {
  287. yield recurlySubscription
  288. yield { another: 'subscription' }
  289. },
  290. })
  291. await expect(
  292. this.RecurlyClient.promises.getSubscriptionForUser('some-user')
  293. ).to.be.rejected
  294. })
  295. })
  296. describe('applySubscriptionChangeRequest', function () {
  297. beforeEach(function () {
  298. this.client.createSubscriptionChange = sinon
  299. .stub()
  300. .resolves(this.recurlySubscriptionChange)
  301. })
  302. it('handles plan changes', async function () {
  303. await this.RecurlyClient.promises.applySubscriptionChangeRequest(
  304. new RecurlySubscriptionChangeRequest({
  305. subscription: this.subscription,
  306. timeframe: 'now',
  307. planCode: 'new-plan',
  308. })
  309. )
  310. expect(this.client.createSubscriptionChange).to.be.calledWith(
  311. 'uuid-subscription-id',
  312. { timeframe: 'now', planCode: 'new-plan' }
  313. )
  314. })
  315. it('handles add-on changes', async function () {
  316. await this.RecurlyClient.promises.applySubscriptionChangeRequest(
  317. new RecurlySubscriptionChangeRequest({
  318. subscription: this.subscription,
  319. timeframe: 'now',
  320. addOnUpdates: [
  321. new RecurlySubscriptionAddOnUpdate({
  322. code: 'new-add-on',
  323. quantity: 2,
  324. unitPrice: 8.99,
  325. }),
  326. ],
  327. })
  328. )
  329. expect(this.client.createSubscriptionChange).to.be.calledWith(
  330. 'uuid-subscription-id',
  331. {
  332. timeframe: 'now',
  333. addOns: [{ code: 'new-add-on', quantity: 2, unitAmount: 8.99 }],
  334. }
  335. )
  336. })
  337. it('should throw any API errors', async function () {
  338. this.client.createSubscriptionChange = sinon.stub().throws()
  339. await expect(
  340. this.RecurlyClient.promises.applySubscriptionChangeRequest({
  341. subscription: this.subscription,
  342. })
  343. ).to.eventually.be.rejectedWith(Error)
  344. })
  345. it('should throw SubtotalLimitExceededError', async function () {
  346. class ValidationError extends recurly.errors.ValidationError {
  347. constructor() {
  348. super()
  349. this.params = [{ param: 'subtotal_amount_in_cents' }]
  350. }
  351. }
  352. this.client.createSubscriptionChange = sinon
  353. .stub()
  354. .throws(new ValidationError())
  355. await expect(
  356. this.RecurlyClient.promises.applySubscriptionChangeRequest({
  357. subscription: this.subscription,
  358. })
  359. ).to.be.rejectedWith(this.Errors.SubtotalLimitExceededError)
  360. })
  361. it('should rethrow errors different than SubtotalLimitExceededError', async function () {
  362. this.client.createSubscriptionChange = sinon.stub().throws(new Error())
  363. await expect(
  364. this.RecurlyClient.promises.applySubscriptionChangeRequest({
  365. subscription: this.subscription,
  366. })
  367. ).to.be.rejectedWith(Error)
  368. })
  369. })
  370. describe('removeSubscriptionChange', function () {
  371. beforeEach(function () {
  372. this.client.removeSubscriptionChange = sinon.stub().resolves()
  373. })
  374. it('should attempt to remove a pending subscription change', async function () {
  375. this.RecurlyClient.promises.removeSubscriptionChange(
  376. this.subscription.id,
  377. {}
  378. )
  379. expect(this.client.removeSubscriptionChange).to.be.calledWith(
  380. this.subscription.id
  381. )
  382. })
  383. it('should throw any API errors', async function () {
  384. this.client.removeSubscriptionChange = sinon.stub().throws()
  385. await expect(
  386. this.RecurlyClient.promises.removeSubscriptionChange(
  387. this.subscription.id,
  388. {}
  389. )
  390. ).to.eventually.be.rejectedWith(Error)
  391. })
  392. describe('removeSubscriptionChangeByUuid', function () {
  393. it('should attempt to remove a pending subscription change', async function () {
  394. this.RecurlyClient.promises.removeSubscriptionChangeByUuid(
  395. this.subscription.uuid,
  396. {}
  397. )
  398. expect(this.client.removeSubscriptionChange).to.be.calledWith(
  399. 'uuid-' + this.subscription.uuid
  400. )
  401. })
  402. it('should throw any API errors', async function () {
  403. this.client.removeSubscriptionChange = sinon.stub().throws()
  404. await expect(
  405. this.RecurlyClient.promises.removeSubscriptionChangeByUuid(
  406. this.subscription.id,
  407. {}
  408. )
  409. ).to.eventually.be.rejectedWith(Error)
  410. })
  411. })
  412. })
  413. describe('reactivateSubscriptionByUuid', function () {
  414. it('should attempt to reactivate the subscription', async function () {
  415. this.client.reactivateSubscription = sinon
  416. .stub()
  417. .resolves(this.recurlySubscription)
  418. const subscription =
  419. await this.RecurlyClient.promises.reactivateSubscriptionByUuid(
  420. this.subscription.uuid
  421. )
  422. expect(subscription).to.deep.equal(this.recurlySubscription)
  423. expect(this.client.reactivateSubscription).to.be.calledWith(
  424. 'uuid-' + this.subscription.uuid
  425. )
  426. })
  427. })
  428. describe('cancelSubscriptionByUuid', function () {
  429. it('should attempt to cancel the subscription', async function () {
  430. this.client.cancelSubscription = sinon
  431. .stub()
  432. .resolves(this.recurlySubscription)
  433. const subscription =
  434. await this.RecurlyClient.promises.cancelSubscriptionByUuid(
  435. this.subscription.uuid
  436. )
  437. expect(subscription).to.deep.equal(this.recurlySubscription)
  438. expect(this.client.cancelSubscription).to.be.calledWith(
  439. 'uuid-' + this.subscription.uuid
  440. )
  441. })
  442. })
  443. describe('pauseSubscriptionByUuid', function () {
  444. it('should attempt to pause the subscription', async function () {
  445. this.client.pauseSubscription = sinon
  446. .stub()
  447. .resolves(this.recurlySubscription)
  448. const subscription =
  449. await this.RecurlyClient.promises.pauseSubscriptionByUuid(
  450. this.subscription.uuid,
  451. 3
  452. )
  453. expect(subscription).to.deep.equal(this.recurlySubscription)
  454. expect(this.client.pauseSubscription).to.be.calledWith(
  455. 'uuid-' + this.subscription.uuid,
  456. { remainingPauseCycles: 3 }
  457. )
  458. })
  459. })
  460. describe('previewSubscriptionChange', function () {
  461. describe('compute immediate charge', function () {
  462. it('only has charge invoice', async function () {
  463. this.client.previewSubscriptionChange.resolves({
  464. plan: { code: 'test_code', name: 'test name' },
  465. unitAmount: 0,
  466. invoiceCollection: {
  467. chargeInvoice: {
  468. subtotal: 100,
  469. tax: 20,
  470. total: 120,
  471. },
  472. },
  473. })
  474. const { immediateCharge } =
  475. await this.RecurlyClient.promises.previewSubscriptionChange(
  476. new RecurlySubscriptionChangeRequest({
  477. subscription: this.subscription,
  478. timeframe: 'now',
  479. planCode: 'new-plan',
  480. })
  481. )
  482. expect(immediateCharge.subtotal).to.be.equal(100)
  483. expect(immediateCharge.tax).to.be.equal(20)
  484. expect(immediateCharge.total).to.be.equal(120)
  485. })
  486. it('credit invoice with imprecise float number', async function () {
  487. this.client.previewSubscriptionChange.resolves({
  488. plan: { code: 'test_code', name: 'test name' },
  489. unitAmount: 0,
  490. invoiceCollection: {
  491. chargeInvoice: {
  492. subtotal: 100.3,
  493. tax: 20.3,
  494. total: 120.3,
  495. },
  496. creditInvoices: [
  497. {
  498. subtotal: -20.1,
  499. tax: -4.1,
  500. total: -24.1,
  501. },
  502. ],
  503. },
  504. })
  505. const { immediateCharge } =
  506. await this.RecurlyClient.promises.previewSubscriptionChange(
  507. new RecurlySubscriptionChangeRequest({
  508. subscription: this.subscription,
  509. timeframe: 'now',
  510. planCode: 'new-plan',
  511. })
  512. )
  513. expect(immediateCharge.subtotal).to.be.equal(80.2)
  514. expect(immediateCharge.tax).to.be.equal(16.2)
  515. expect(immediateCharge.total).to.be.equal(96.2)
  516. })
  517. })
  518. it('should throw SubtotalLimitExceededError', async function () {
  519. class ValidationError extends recurly.errors.ValidationError {
  520. constructor() {
  521. super()
  522. this.params = [{ param: 'subtotal_amount_in_cents' }]
  523. }
  524. }
  525. this.client.previewSubscriptionChange = sinon
  526. .stub()
  527. .throws(new ValidationError())
  528. await expect(
  529. this.RecurlyClient.promises.previewSubscriptionChange(
  530. new RecurlySubscriptionChangeRequest({
  531. subscription: this.subscription,
  532. timeframe: 'now',
  533. planCode: 'new-plan',
  534. })
  535. )
  536. ).to.be.rejectedWith(this.Errors.SubtotalLimitExceededError)
  537. })
  538. it('should rethrow errors different than SubtotalLimitExceededError', async function () {
  539. this.client.previewSubscriptionChange = sinon.stub().throws(new Error())
  540. await expect(
  541. this.RecurlyClient.promises.previewSubscriptionChange(
  542. new RecurlySubscriptionChangeRequest({
  543. subscription: this.subscription,
  544. timeframe: 'now',
  545. planCode: 'new-plan',
  546. })
  547. )
  548. ).to.be.rejectedWith(Error)
  549. })
  550. })
  551. describe('getPaymentMethod', function () {
  552. it('should throw MissingBillingInfoError', async function () {
  553. this.client.getBillingInfo = sinon
  554. .stub()
  555. .throws(new recurly.errors.NotFoundError())
  556. await expect(
  557. this.RecurlyClient.promises.getPaymentMethod(this.user._id)
  558. ).to.be.rejectedWith(this.Errors.MissingBillingInfoError)
  559. })
  560. it('should rethrow errors different than MissingBillingInfoError', async function () {
  561. this.client.getBillingInfo = sinon.stub().throws(new Error())
  562. await expect(
  563. this.RecurlyClient.promises.getPaymentMethod(this.user._id)
  564. ).to.be.rejectedWith(Error)
  565. })
  566. })
  567. })