SubscriptionHandlerTests.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662
  1. const SandboxedModule = require('sandboxed-module')
  2. const sinon = require('sinon')
  3. const chai = require('chai')
  4. const { expect } = chai
  5. const MODULE_PATH =
  6. '../../../../app/src/Features/Subscription/SubscriptionHandler'
  7. const mockRecurlySubscriptions = {
  8. 'subscription-123-active': {
  9. uuid: 'subscription-123-active',
  10. plan: {
  11. name: 'Gold',
  12. plan_code: 'gold',
  13. },
  14. current_period_ends_at: new Date(),
  15. state: 'active',
  16. unit_amount_in_cents: 999,
  17. account: {
  18. account_code: 'user-123',
  19. },
  20. },
  21. }
  22. const mockRecurlyClientSubscriptions = {
  23. 'subscription-123-active': {
  24. id: 'subscription-123-recurly-id',
  25. uuid: 'subscription-123-active',
  26. plan: {
  27. name: 'Gold',
  28. code: 'gold',
  29. },
  30. currentPeriodEndsAt: new Date(),
  31. state: 'active',
  32. unitAmount: 10,
  33. account: {
  34. code: 'user-123',
  35. },
  36. },
  37. }
  38. const mockSubscriptionChanges = {
  39. 'subscription-123-active': {
  40. id: 'subscription-change-id',
  41. subscriptionId: 'subscription-123-recurly-id', // not the UUID
  42. },
  43. }
  44. describe('SubscriptionHandler', function () {
  45. beforeEach(function () {
  46. this.Settings = {
  47. plans: [
  48. {
  49. planCode: 'collaborator',
  50. name: 'Collaborator',
  51. features: {
  52. collaborators: -1,
  53. versioning: true,
  54. },
  55. },
  56. ],
  57. defaultPlanCode: {
  58. collaborators: 0,
  59. versioning: false,
  60. },
  61. }
  62. this.activeRecurlySubscription =
  63. mockRecurlySubscriptions['subscription-123-active']
  64. this.activeRecurlyClientSubscription =
  65. mockRecurlyClientSubscriptions['subscription-123-active']
  66. this.activeRecurlySubscriptionChange =
  67. mockSubscriptionChanges['subscription-123-active']
  68. this.User = {}
  69. this.user = { _id: (this.user_id = 'user_id_here_') }
  70. this.subscription = {
  71. recurlySubscription_id: this.activeRecurlySubscription.uuid,
  72. }
  73. this.RecurlyWrapper = {
  74. promises: {
  75. getSubscription: sinon.stub().resolves(this.activeRecurlySubscription),
  76. redeemCoupon: sinon.stub().resolves(),
  77. createSubscription: sinon
  78. .stub()
  79. .resolves(this.activeRecurlySubscription),
  80. getBillingInfo: sinon.stub().resolves(),
  81. getAccountPastDueInvoices: sinon.stub().resolves(),
  82. attemptInvoiceCollection: sinon.stub().resolves(),
  83. listAccountActiveSubscriptions: sinon.stub().resolves([]),
  84. },
  85. }
  86. this.RecurlyClient = {
  87. promises: {
  88. reactivateSubscriptionByUuid: sinon
  89. .stub()
  90. .resolves(this.activeRecurlyClientSubscription),
  91. cancelSubscriptionByUuid: sinon.stub().resolves(),
  92. changeSubscriptionByUuid: sinon
  93. .stub()
  94. .resolves(this.activeRecurlySubscriptionChange),
  95. getSubscription: sinon
  96. .stub()
  97. .resolves(this.activeRecurlyClientSubscription),
  98. },
  99. }
  100. this.SubscriptionUpdater = {
  101. promises: {
  102. updateSubscriptionFromRecurly: sinon.stub().resolves(),
  103. syncSubscription: sinon.stub().resolves(),
  104. startFreeTrial: sinon.stub().resolves(),
  105. },
  106. }
  107. this.LimitationsManager = {
  108. promises: {
  109. userHasV2Subscription: sinon.stub().resolves(),
  110. },
  111. }
  112. this.EmailHandler = {
  113. sendEmail: sinon.stub(),
  114. sendDeferredEmail: sinon.stub(),
  115. }
  116. this.PlansLocator = {
  117. findLocalPlanInSettings: sinon.stub().returns({ planCode: 'plan' }),
  118. }
  119. this.SubscriptionHelper = {
  120. shouldPlanChangeAtTermEnd: sinon.stub(),
  121. }
  122. this.UserUpdater = {
  123. promises: {
  124. updateUser: sinon.stub().resolves(),
  125. },
  126. }
  127. this.SubscriptionHandler = SandboxedModule.require(MODULE_PATH, {
  128. requires: {
  129. './RecurlyWrapper': this.RecurlyWrapper,
  130. './RecurlyClient': this.RecurlyClient,
  131. '@overleaf/settings': this.Settings,
  132. '../../models/User': {
  133. User: this.User,
  134. },
  135. './SubscriptionUpdater': this.SubscriptionUpdater,
  136. './LimitationsManager': this.LimitationsManager,
  137. '../Email/EmailHandler': this.EmailHandler,
  138. '../Analytics/AnalyticsManager': this.AnalyticsManager,
  139. './PlansLocator': this.PlansLocator,
  140. './SubscriptionHelper': this.SubscriptionHelper,
  141. '../User/UserUpdater': this.UserUpdater,
  142. },
  143. })
  144. })
  145. describe('createSubscription', function () {
  146. beforeEach(function () {
  147. this.subscriptionDetails = {
  148. cvv: '123',
  149. number: '12345',
  150. }
  151. this.recurlyTokenIds = { billing: '45555666' }
  152. })
  153. describe('successfully', function () {
  154. beforeEach(async function () {
  155. await this.SubscriptionHandler.promises.createSubscription(
  156. this.user,
  157. this.subscriptionDetails,
  158. this.recurlyTokenIds
  159. )
  160. })
  161. it('should create the subscription with the wrapper', function () {
  162. this.RecurlyWrapper.promises.createSubscription
  163. .calledWith(this.user, this.subscriptionDetails, this.recurlyTokenIds)
  164. .should.equal(true)
  165. })
  166. it('should sync the subscription to the user', function () {
  167. this.SubscriptionUpdater.promises.syncSubscription.calledOnce.should.equal(
  168. true
  169. )
  170. this.SubscriptionUpdater.promises.syncSubscription.args[0][0].should.deep.equal(
  171. this.activeRecurlySubscription
  172. )
  173. this.SubscriptionUpdater.promises.syncSubscription.args[0][1].should.deep.equal(
  174. this.user._id
  175. )
  176. })
  177. it('should not set last trial date if not a trial/the trial_started_at is not set', function () {
  178. this.UserUpdater.promises.updateUser.should.not.have.been.called
  179. })
  180. })
  181. describe('when the subscription is a trial and has a trial_started_at date', function () {
  182. beforeEach(async function () {
  183. this.activeRecurlySubscription.trial_started_at =
  184. '2024-01-01T09:58:35.531+00:00'
  185. await this.SubscriptionHandler.promises.createSubscription(
  186. this.user,
  187. this.subscriptionDetails,
  188. this.recurlyTokenIds
  189. )
  190. })
  191. it('should set the users lastTrial date', function () {
  192. this.UserUpdater.promises.updateUser.should.have.been.calledOnce
  193. expect(this.UserUpdater.promises.updateUser.args[0][0]).to.deep.equal({
  194. _id: this.user_id,
  195. lastTrial: {
  196. $not: {
  197. $gt: new Date(this.activeRecurlySubscription.trial_started_at),
  198. },
  199. },
  200. })
  201. expect(this.UserUpdater.promises.updateUser.args[0][1]).to.deep.equal({
  202. $set: {
  203. lastTrial: new Date(
  204. this.activeRecurlySubscription.trial_started_at
  205. ),
  206. },
  207. })
  208. })
  209. })
  210. describe('when there is already a subscription in Recurly', function () {
  211. beforeEach(function () {
  212. this.RecurlyWrapper.promises.listAccountActiveSubscriptions.resolves([
  213. this.subscription,
  214. ])
  215. })
  216. it('should an error', function () {
  217. expect(
  218. this.SubscriptionHandler.promises.createSubscription(
  219. this.user,
  220. this.subscriptionDetails,
  221. this.recurlyTokenIds
  222. )
  223. ).to.be.rejectedWith('user already has subscription in recurly')
  224. })
  225. })
  226. })
  227. function shouldUpdateSubscription() {
  228. it('should update the subscription', function () {
  229. expect(
  230. this.RecurlyClient.promises.changeSubscriptionByUuid
  231. ).to.have.been.calledWith(this.subscription.recurlySubscription_id)
  232. const updateOptions =
  233. this.RecurlyClient.promises.changeSubscriptionByUuid.args[0][1]
  234. updateOptions.planCode.should.equal(this.plan_code)
  235. })
  236. }
  237. function shouldSyncSubscription() {
  238. it('should sync the new subscription to the user', function () {
  239. expect(this.SubscriptionUpdater.promises.syncSubscription).to.have.been
  240. .called
  241. this.SubscriptionUpdater.promises.syncSubscription.args[0][0].should.deep.equal(
  242. this.activeRecurlySubscription
  243. )
  244. this.SubscriptionUpdater.promises.syncSubscription.args[0][1].should.deep.equal(
  245. this.user._id
  246. )
  247. })
  248. }
  249. function testUserWithASubscription(shouldPlanChangeAtTermEnd, timeframe) {
  250. describe(
  251. 'when change should happen with timeframe ' + timeframe,
  252. function () {
  253. beforeEach(async function () {
  254. this.user.id = this.activeRecurlySubscription.account.account_code
  255. this.User.findById = (userId, projection) => ({
  256. exec: () => {
  257. userId.should.equal(this.user.id)
  258. return Promise.resolve(this.user)
  259. },
  260. })
  261. this.plan_code = 'collaborator'
  262. this.SubscriptionHelper.shouldPlanChangeAtTermEnd.returns(
  263. shouldPlanChangeAtTermEnd
  264. )
  265. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  266. hasSubscription: true,
  267. subscription: this.subscription,
  268. })
  269. await this.SubscriptionHandler.promises.updateSubscription(
  270. this.user,
  271. this.plan_code,
  272. null
  273. )
  274. })
  275. shouldUpdateSubscription()
  276. shouldSyncSubscription()
  277. it('should update with timeframe ' + timeframe, function () {
  278. const updateOptions =
  279. this.RecurlyClient.promises.changeSubscriptionByUuid.args[0][1]
  280. updateOptions.timeframe.should.equal(timeframe)
  281. })
  282. }
  283. )
  284. }
  285. describe('updateSubscription', function () {
  286. describe('with a user with a subscription', function () {
  287. testUserWithASubscription(false, 'now')
  288. testUserWithASubscription(true, 'term_end')
  289. describe('when plan(s) could not be located in settings', function () {
  290. beforeEach(async function () {
  291. this.user.id = this.activeRecurlySubscription.account.account_code
  292. this.User.findById = (userId, projection) => ({
  293. exec: () => {
  294. userId.should.equal(this.user.id)
  295. return Promise.resolve(this.user)
  296. },
  297. })
  298. this.plan_code = 'collaborator'
  299. this.PlansLocator.findLocalPlanInSettings.returns(null)
  300. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  301. hasSubscription: true,
  302. subscription: this.subscription,
  303. })
  304. })
  305. it('should be rejected and should not update the subscription', function () {
  306. expect(
  307. this.SubscriptionHandler.promises.updateSubscription(
  308. this.user,
  309. this.plan_code,
  310. null
  311. )
  312. ).to.be.rejected
  313. this.RecurlyClient.promises.changeSubscriptionByUuid.called.should.equal(
  314. false
  315. )
  316. })
  317. })
  318. })
  319. describe('with a user without a subscription', function () {
  320. beforeEach(async function () {
  321. this.LimitationsManager.promises.userHasV2Subscription.resolves(false)
  322. await this.SubscriptionHandler.promises.updateSubscription(
  323. this.user,
  324. this.plan_code,
  325. null
  326. )
  327. })
  328. it('should redirect to the subscription dashboard', function () {
  329. this.RecurlyClient.promises.changeSubscriptionByUuid.called.should.equal(
  330. false
  331. )
  332. this.SubscriptionUpdater.promises.syncSubscription.called.should.equal(
  333. false
  334. )
  335. })
  336. })
  337. describe('with a coupon code', function () {
  338. beforeEach(async function () {
  339. this.user.id = this.activeRecurlySubscription.account.account_code
  340. this.User.findById = (userId, projection) => ({
  341. exec: () => {
  342. userId.should.equal(this.user.id)
  343. return Promise.resolve(this.user)
  344. },
  345. })
  346. this.plan_code = 'collaborator'
  347. this.coupon_code = '1231312'
  348. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  349. hasSubscription: true,
  350. subscription: this.subscription,
  351. })
  352. await this.SubscriptionHandler.promises.updateSubscription(
  353. this.user,
  354. this.plan_code,
  355. this.coupon_code
  356. )
  357. })
  358. it('should get the users account', function () {
  359. this.RecurlyWrapper.promises.getSubscription
  360. .calledWith(this.activeRecurlySubscription.uuid)
  361. .should.equal(true)
  362. })
  363. it('should redeem the coupon', function () {
  364. this.RecurlyWrapper.promises.redeemCoupon
  365. .calledWith(
  366. this.activeRecurlySubscription.account.account_code,
  367. this.coupon_code
  368. )
  369. .should.equal(true)
  370. })
  371. it('should update the subscription', function () {
  372. expect(
  373. this.RecurlyClient.promises.changeSubscriptionByUuid
  374. ).to.be.calledWith(this.subscription.recurlySubscription_id)
  375. const updateOptions =
  376. this.RecurlyClient.promises.changeSubscriptionByUuid.args[0][1]
  377. updateOptions.planCode.should.equal(this.plan_code)
  378. })
  379. })
  380. })
  381. describe('cancelSubscription', function () {
  382. describe('with a user without a subscription', function () {
  383. beforeEach(async function () {
  384. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  385. hasSubscription: false,
  386. subscription: this.subscription,
  387. })
  388. await this.SubscriptionHandler.promises.cancelSubscription(this.user)
  389. })
  390. it('should redirect to the subscription dashboard', function () {
  391. this.RecurlyClient.promises.cancelSubscriptionByUuid.called.should.equal(
  392. false
  393. )
  394. })
  395. })
  396. describe('with a user with a subscription', function () {
  397. beforeEach(async function () {
  398. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  399. hasSubscription: true,
  400. subscription: this.subscription,
  401. })
  402. await this.SubscriptionHandler.promises.cancelSubscription(this.user)
  403. })
  404. it('should cancel the subscription', function () {
  405. this.RecurlyClient.promises.cancelSubscriptionByUuid.called.should.equal(
  406. true
  407. )
  408. this.RecurlyClient.promises.cancelSubscriptionByUuid
  409. .calledWith(this.subscription.recurlySubscription_id)
  410. .should.equal(true)
  411. })
  412. it('should send the email after 1 hour', function () {
  413. const ONE_HOUR_IN_MS = 1000 * 60 * 60
  414. expect(this.EmailHandler.sendDeferredEmail).to.have.been.calledWith(
  415. 'canceledSubscription',
  416. { to: this.user.email, first_name: this.user.first_name },
  417. ONE_HOUR_IN_MS
  418. )
  419. })
  420. })
  421. })
  422. describe('reactivateSubscription', function () {
  423. describe('with a user without a subscription', function () {
  424. beforeEach(async function () {
  425. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  426. hasSubscription: false,
  427. subscription: this.subscription,
  428. })
  429. await this.SubscriptionHandler.promises.reactivateSubscription(
  430. this.user
  431. )
  432. })
  433. it('should redirect to the subscription dashboard', function () {
  434. this.RecurlyClient.promises.reactivateSubscriptionByUuid.called.should.equal(
  435. false
  436. )
  437. })
  438. it('should not send a notification email', function () {
  439. sinon.assert.notCalled(this.EmailHandler.sendEmail)
  440. })
  441. })
  442. describe('with a user with a subscription', function () {
  443. beforeEach(async function () {
  444. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  445. hasSubscription: true,
  446. subscription: this.subscription,
  447. })
  448. await this.SubscriptionHandler.promises.reactivateSubscription(
  449. this.user
  450. )
  451. })
  452. it('should reactivate the subscription', function () {
  453. this.RecurlyClient.promises.reactivateSubscriptionByUuid.called.should.equal(
  454. true
  455. )
  456. this.RecurlyClient.promises.reactivateSubscriptionByUuid
  457. .calledWith(this.subscription.recurlySubscription_id)
  458. .should.equal(true)
  459. })
  460. it('should send a notification email', function () {
  461. sinon.assert.calledWith(
  462. this.EmailHandler.sendEmail,
  463. 'reactivatedSubscription'
  464. )
  465. })
  466. })
  467. })
  468. describe('syncSubscription', function () {
  469. describe('with an actionable request', function () {
  470. beforeEach(async function () {
  471. this.user.id = this.activeRecurlySubscription.account.account_code
  472. this.User.findById = (userId, projection) => ({
  473. exec: () => {
  474. userId.should.equal(this.user.id)
  475. return Promise.resolve(this.user)
  476. },
  477. })
  478. await this.SubscriptionHandler.promises.syncSubscription(
  479. this.activeRecurlySubscription,
  480. {}
  481. )
  482. })
  483. it('should request the affected subscription from the API', function () {
  484. this.RecurlyWrapper.promises.getSubscription
  485. .calledWith(this.activeRecurlySubscription.uuid)
  486. .should.equal(true)
  487. })
  488. it('should request the account details of the subscription', function () {
  489. const options = this.RecurlyWrapper.promises.getSubscription.args[0][1]
  490. options.includeAccount.should.equal(true)
  491. })
  492. it('should sync the subscription to the user', function () {
  493. this.SubscriptionUpdater.promises.syncSubscription.calledOnce.should.equal(
  494. true
  495. )
  496. this.SubscriptionUpdater.promises.syncSubscription.args[0][0].should.deep.equal(
  497. this.activeRecurlySubscription
  498. )
  499. this.SubscriptionUpdater.promises.syncSubscription.args[0][1].should.deep.equal(
  500. this.user._id
  501. )
  502. })
  503. })
  504. })
  505. describe('attemptPaypalInvoiceCollection', function () {
  506. describe('for credit card users', function () {
  507. beforeEach(async function () {
  508. this.RecurlyWrapper.promises.getBillingInfo.resolves({
  509. paypal_billing_agreement_id: null,
  510. })
  511. await this.SubscriptionHandler.promises.attemptPaypalInvoiceCollection(
  512. this.activeRecurlySubscription.account.account_code
  513. )
  514. })
  515. it('gets billing infos', function () {
  516. sinon.assert.calledWith(
  517. this.RecurlyWrapper.promises.getBillingInfo,
  518. this.activeRecurlySubscription.account.account_code
  519. )
  520. })
  521. it('skips user', function () {
  522. sinon.assert.notCalled(
  523. this.RecurlyWrapper.promises.getAccountPastDueInvoices
  524. )
  525. })
  526. })
  527. describe('for paypal users', function () {
  528. beforeEach(async function () {
  529. this.RecurlyWrapper.promises.getBillingInfo.resolves({
  530. paypal_billing_agreement_id: 'mock-billing-agreement',
  531. })
  532. this.RecurlyWrapper.promises.getAccountPastDueInvoices.resolves([
  533. { invoice_number: 'mock-invoice-number' },
  534. ])
  535. await this.SubscriptionHandler.promises.attemptPaypalInvoiceCollection(
  536. this.activeRecurlySubscription.account.account_code
  537. )
  538. })
  539. it('gets past due invoices', function () {
  540. sinon.assert.calledWith(
  541. this.RecurlyWrapper.promises.getAccountPastDueInvoices,
  542. this.activeRecurlySubscription.account.account_code
  543. )
  544. })
  545. it('calls attemptInvoiceCollection', function () {
  546. sinon.assert.calledWith(
  547. this.RecurlyWrapper.promises.attemptInvoiceCollection,
  548. 'mock-invoice-number'
  549. )
  550. })
  551. })
  552. })
  553. describe('validateNoSubscriptionInRecurly', function () {
  554. describe('with a subscription in recurly', function () {
  555. beforeEach(async function () {
  556. this.RecurlyWrapper.promises.listAccountActiveSubscriptions.resolves([
  557. this.subscription,
  558. ])
  559. this.isValid =
  560. await this.SubscriptionHandler.promises.validateNoSubscriptionInRecurly(
  561. this.user_id
  562. )
  563. })
  564. it('should call RecurlyWrapper.promises.listAccountActiveSubscriptions with the user id', function () {
  565. this.RecurlyWrapper.promises.listAccountActiveSubscriptions
  566. .calledWith(this.user_id)
  567. .should.equal(true)
  568. })
  569. it('should sync the subscription', function () {
  570. this.SubscriptionUpdater.promises.syncSubscription
  571. .calledWith(this.subscription, this.user_id)
  572. .should.equal(true)
  573. })
  574. it('should return false', function () {
  575. expect(this.isValid).to.equal(false)
  576. })
  577. })
  578. describe('with no subscription in recurly', function () {
  579. beforeEach(async function () {
  580. this.isValid =
  581. await this.SubscriptionHandler.promises.validateNoSubscriptionInRecurly(
  582. this.user_id
  583. )
  584. })
  585. it('should be rejected and not sync the subscription', function () {
  586. this.SubscriptionUpdater.promises.syncSubscription.called.should.equal(
  587. false
  588. )
  589. })
  590. it('should return true', function () {
  591. expect(this.isValid).to.equal(true)
  592. })
  593. })
  594. })
  595. })