RecurlyClientTests.js 16 KB

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