SubscriptionHandlerTests.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  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.SubscriptionHandler = SandboxedModule.require(MODULE_PATH, {
  123. requires: {
  124. './RecurlyWrapper': this.RecurlyWrapper,
  125. './RecurlyClient': this.RecurlyClient,
  126. '@overleaf/settings': this.Settings,
  127. '../../models/User': {
  128. User: this.User,
  129. },
  130. './SubscriptionUpdater': this.SubscriptionUpdater,
  131. './LimitationsManager': this.LimitationsManager,
  132. '../Email/EmailHandler': this.EmailHandler,
  133. '../Analytics/AnalyticsManager': this.AnalyticsManager,
  134. './PlansLocator': this.PlansLocator,
  135. './SubscriptionHelper': this.SubscriptionHelper,
  136. },
  137. })
  138. })
  139. describe('createSubscription', function () {
  140. beforeEach(function () {
  141. this.subscriptionDetails = {
  142. cvv: '123',
  143. number: '12345',
  144. }
  145. this.recurlyTokenIds = { billing: '45555666' }
  146. })
  147. describe('successfully', function () {
  148. beforeEach(async function () {
  149. await this.SubscriptionHandler.promises.createSubscription(
  150. this.user,
  151. this.subscriptionDetails,
  152. this.recurlyTokenIds
  153. )
  154. })
  155. it('should create the subscription with the wrapper', function () {
  156. this.RecurlyWrapper.promises.createSubscription
  157. .calledWith(this.user, this.subscriptionDetails, this.recurlyTokenIds)
  158. .should.equal(true)
  159. })
  160. it('should sync the subscription to the user', function () {
  161. this.SubscriptionUpdater.promises.syncSubscription.calledOnce.should.equal(
  162. true
  163. )
  164. this.SubscriptionUpdater.promises.syncSubscription.args[0][0].should.deep.equal(
  165. this.activeRecurlySubscription
  166. )
  167. this.SubscriptionUpdater.promises.syncSubscription.args[0][1].should.deep.equal(
  168. this.user._id
  169. )
  170. })
  171. })
  172. describe('when there is already a subscription in Recurly', function () {
  173. beforeEach(function () {
  174. this.RecurlyWrapper.promises.listAccountActiveSubscriptions.resolves([
  175. this.subscription,
  176. ])
  177. })
  178. it('should an error', function () {
  179. expect(
  180. this.SubscriptionHandler.promises.createSubscription(
  181. this.user,
  182. this.subscriptionDetails,
  183. this.recurlyTokenIds
  184. )
  185. ).to.be.rejectedWith('user already has subscription in recurly')
  186. })
  187. })
  188. })
  189. function shouldUpdateSubscription() {
  190. it('should update the subscription', function () {
  191. expect(
  192. this.RecurlyClient.promises.changeSubscriptionByUuid
  193. ).to.have.been.calledWith(this.subscription.recurlySubscription_id)
  194. const updateOptions =
  195. this.RecurlyClient.promises.changeSubscriptionByUuid.args[0][1]
  196. updateOptions.planCode.should.equal(this.plan_code)
  197. })
  198. }
  199. function shouldSyncSubscription() {
  200. it('should sync the new subscription to the user', function () {
  201. expect(this.SubscriptionUpdater.promises.syncSubscription).to.have.been
  202. .called
  203. this.SubscriptionUpdater.promises.syncSubscription.args[0][0].should.deep.equal(
  204. this.activeRecurlySubscription
  205. )
  206. this.SubscriptionUpdater.promises.syncSubscription.args[0][1].should.deep.equal(
  207. this.user._id
  208. )
  209. })
  210. }
  211. function testUserWithASubscription(shouldPlanChangeAtTermEnd, timeframe) {
  212. describe(
  213. 'when change should happen with timeframe ' + timeframe,
  214. function () {
  215. beforeEach(async function () {
  216. this.user.id = this.activeRecurlySubscription.account.account_code
  217. this.User.findById = (userId, projection) => ({
  218. exec: () => {
  219. userId.should.equal(this.user.id)
  220. return Promise.resolve(this.user)
  221. },
  222. })
  223. this.plan_code = 'collaborator'
  224. this.SubscriptionHelper.shouldPlanChangeAtTermEnd.returns(
  225. shouldPlanChangeAtTermEnd
  226. )
  227. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  228. hasSubscription: true,
  229. subscription: this.subscription,
  230. })
  231. await this.SubscriptionHandler.promises.updateSubscription(
  232. this.user,
  233. this.plan_code,
  234. null
  235. )
  236. })
  237. shouldUpdateSubscription()
  238. shouldSyncSubscription()
  239. it('should update with timeframe ' + timeframe, function () {
  240. const updateOptions =
  241. this.RecurlyClient.promises.changeSubscriptionByUuid.args[0][1]
  242. updateOptions.timeframe.should.equal(timeframe)
  243. })
  244. }
  245. )
  246. }
  247. describe('updateSubscription', function () {
  248. describe('with a user with a subscription', function () {
  249. testUserWithASubscription(false, 'now')
  250. testUserWithASubscription(true, 'term_end')
  251. describe('when plan(s) could not be located in settings', function () {
  252. beforeEach(async function () {
  253. this.user.id = this.activeRecurlySubscription.account.account_code
  254. this.User.findById = (userId, projection) => ({
  255. exec: () => {
  256. userId.should.equal(this.user.id)
  257. return Promise.resolve(this.user)
  258. },
  259. })
  260. this.plan_code = 'collaborator'
  261. this.PlansLocator.findLocalPlanInSettings.returns(null)
  262. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  263. hasSubscription: true,
  264. subscription: this.subscription,
  265. })
  266. })
  267. it('should be rejected and should not update the subscription', function () {
  268. expect(
  269. this.SubscriptionHandler.promises.updateSubscription(
  270. this.user,
  271. this.plan_code,
  272. null
  273. )
  274. ).to.be.rejected
  275. this.RecurlyClient.promises.changeSubscriptionByUuid.called.should.equal(
  276. false
  277. )
  278. })
  279. })
  280. })
  281. describe('with a user without a subscription', function () {
  282. beforeEach(async function () {
  283. this.LimitationsManager.promises.userHasV2Subscription.resolves(false)
  284. await this.SubscriptionHandler.promises.updateSubscription(
  285. this.user,
  286. this.plan_code,
  287. null
  288. )
  289. })
  290. it('should redirect to the subscription dashboard', function () {
  291. this.RecurlyClient.promises.changeSubscriptionByUuid.called.should.equal(
  292. false
  293. )
  294. this.SubscriptionUpdater.promises.syncSubscription.called.should.equal(
  295. false
  296. )
  297. })
  298. })
  299. describe('with a coupon code', function () {
  300. beforeEach(async function () {
  301. this.user.id = this.activeRecurlySubscription.account.account_code
  302. this.User.findById = (userId, projection) => ({
  303. exec: () => {
  304. userId.should.equal(this.user.id)
  305. return Promise.resolve(this.user)
  306. },
  307. })
  308. this.plan_code = 'collaborator'
  309. this.coupon_code = '1231312'
  310. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  311. hasSubscription: true,
  312. subscription: this.subscription,
  313. })
  314. await this.SubscriptionHandler.promises.updateSubscription(
  315. this.user,
  316. this.plan_code,
  317. this.coupon_code
  318. )
  319. })
  320. it('should get the users account', function () {
  321. this.RecurlyWrapper.promises.getSubscription
  322. .calledWith(this.activeRecurlySubscription.uuid)
  323. .should.equal(true)
  324. })
  325. it('should redeem the coupon', function () {
  326. this.RecurlyWrapper.promises.redeemCoupon
  327. .calledWith(
  328. this.activeRecurlySubscription.account.account_code,
  329. this.coupon_code
  330. )
  331. .should.equal(true)
  332. })
  333. it('should update the subscription', function () {
  334. expect(
  335. this.RecurlyClient.promises.changeSubscriptionByUuid
  336. ).to.be.calledWith(this.subscription.recurlySubscription_id)
  337. const updateOptions =
  338. this.RecurlyClient.promises.changeSubscriptionByUuid.args[0][1]
  339. updateOptions.planCode.should.equal(this.plan_code)
  340. })
  341. })
  342. })
  343. describe('cancelSubscription', function () {
  344. describe('with a user without a subscription', function () {
  345. beforeEach(async function () {
  346. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  347. hasSubscription: false,
  348. subscription: this.subscription,
  349. })
  350. await this.SubscriptionHandler.promises.cancelSubscription(this.user)
  351. })
  352. it('should redirect to the subscription dashboard', function () {
  353. this.RecurlyClient.promises.cancelSubscriptionByUuid.called.should.equal(
  354. false
  355. )
  356. })
  357. })
  358. describe('with a user with a subscription', function () {
  359. beforeEach(async function () {
  360. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  361. hasSubscription: true,
  362. subscription: this.subscription,
  363. })
  364. await this.SubscriptionHandler.promises.cancelSubscription(this.user)
  365. })
  366. it('should cancel the subscription', function () {
  367. this.RecurlyClient.promises.cancelSubscriptionByUuid.called.should.equal(
  368. true
  369. )
  370. this.RecurlyClient.promises.cancelSubscriptionByUuid
  371. .calledWith(this.subscription.recurlySubscription_id)
  372. .should.equal(true)
  373. })
  374. it('should send the email after 1 hour', function () {
  375. const ONE_HOUR_IN_MS = 1000 * 60 * 60
  376. expect(this.EmailHandler.sendDeferredEmail).to.have.been.calledWith(
  377. 'canceledSubscription',
  378. { to: this.user.email, first_name: this.user.first_name },
  379. ONE_HOUR_IN_MS
  380. )
  381. })
  382. })
  383. })
  384. describe('reactivateSubscription', function () {
  385. describe('with a user without a subscription', function () {
  386. beforeEach(async function () {
  387. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  388. hasSubscription: false,
  389. subscription: this.subscription,
  390. })
  391. await this.SubscriptionHandler.promises.reactivateSubscription(
  392. this.user
  393. )
  394. })
  395. it('should redirect to the subscription dashboard', function () {
  396. this.RecurlyClient.promises.reactivateSubscriptionByUuid.called.should.equal(
  397. false
  398. )
  399. })
  400. it('should not send a notification email', function () {
  401. sinon.assert.notCalled(this.EmailHandler.sendEmail)
  402. })
  403. })
  404. describe('with a user with a subscription', function () {
  405. beforeEach(async function () {
  406. this.LimitationsManager.promises.userHasV2Subscription.resolves({
  407. hasSubscription: true,
  408. subscription: this.subscription,
  409. })
  410. await this.SubscriptionHandler.promises.reactivateSubscription(
  411. this.user
  412. )
  413. })
  414. it('should reactivate the subscription', function () {
  415. this.RecurlyClient.promises.reactivateSubscriptionByUuid.called.should.equal(
  416. true
  417. )
  418. this.RecurlyClient.promises.reactivateSubscriptionByUuid
  419. .calledWith(this.subscription.recurlySubscription_id)
  420. .should.equal(true)
  421. })
  422. it('should send a notification email', function () {
  423. sinon.assert.calledWith(
  424. this.EmailHandler.sendEmail,
  425. 'reactivatedSubscription'
  426. )
  427. })
  428. })
  429. })
  430. describe('syncSubscription', function () {
  431. describe('with an actionable request', function () {
  432. beforeEach(async function () {
  433. this.user.id = this.activeRecurlySubscription.account.account_code
  434. this.User.findById = (userId, projection) => ({
  435. exec: () => {
  436. userId.should.equal(this.user.id)
  437. return Promise.resolve(this.user)
  438. },
  439. })
  440. await this.SubscriptionHandler.promises.syncSubscription(
  441. this.activeRecurlySubscription,
  442. {}
  443. )
  444. })
  445. it('should request the affected subscription from the API', function () {
  446. this.RecurlyWrapper.promises.getSubscription
  447. .calledWith(this.activeRecurlySubscription.uuid)
  448. .should.equal(true)
  449. })
  450. it('should request the account details of the subscription', function () {
  451. const options = this.RecurlyWrapper.promises.getSubscription.args[0][1]
  452. options.includeAccount.should.equal(true)
  453. })
  454. it('should sync the subscription to the user', function () {
  455. this.SubscriptionUpdater.promises.syncSubscription.calledOnce.should.equal(
  456. true
  457. )
  458. this.SubscriptionUpdater.promises.syncSubscription.args[0][0].should.deep.equal(
  459. this.activeRecurlySubscription
  460. )
  461. this.SubscriptionUpdater.promises.syncSubscription.args[0][1].should.deep.equal(
  462. this.user._id
  463. )
  464. })
  465. })
  466. })
  467. describe('attemptPaypalInvoiceCollection', function () {
  468. describe('for credit card users', function () {
  469. beforeEach(async function () {
  470. this.RecurlyWrapper.promises.getBillingInfo.resolves({
  471. paypal_billing_agreement_id: null,
  472. })
  473. await this.SubscriptionHandler.promises.attemptPaypalInvoiceCollection(
  474. this.activeRecurlySubscription.account.account_code
  475. )
  476. })
  477. it('gets billing infos', function () {
  478. sinon.assert.calledWith(
  479. this.RecurlyWrapper.promises.getBillingInfo,
  480. this.activeRecurlySubscription.account.account_code
  481. )
  482. })
  483. it('skips user', function () {
  484. sinon.assert.notCalled(
  485. this.RecurlyWrapper.promises.getAccountPastDueInvoices
  486. )
  487. })
  488. })
  489. describe('for paypal users', function () {
  490. beforeEach(async function () {
  491. this.RecurlyWrapper.promises.getBillingInfo.resolves({
  492. paypal_billing_agreement_id: 'mock-billing-agreement',
  493. })
  494. this.RecurlyWrapper.promises.getAccountPastDueInvoices.resolves([
  495. { invoice_number: 'mock-invoice-number' },
  496. ])
  497. await this.SubscriptionHandler.promises.attemptPaypalInvoiceCollection(
  498. this.activeRecurlySubscription.account.account_code
  499. )
  500. })
  501. it('gets past due invoices', function () {
  502. sinon.assert.calledWith(
  503. this.RecurlyWrapper.promises.getAccountPastDueInvoices,
  504. this.activeRecurlySubscription.account.account_code
  505. )
  506. })
  507. it('calls attemptInvoiceCollection', function () {
  508. sinon.assert.calledWith(
  509. this.RecurlyWrapper.promises.attemptInvoiceCollection,
  510. 'mock-invoice-number'
  511. )
  512. })
  513. })
  514. })
  515. describe('validateNoSubscriptionInRecurly', function () {
  516. describe('with a subscription in recurly', function () {
  517. beforeEach(async function () {
  518. this.RecurlyWrapper.promises.listAccountActiveSubscriptions.resolves([
  519. this.subscription,
  520. ])
  521. this.isValid =
  522. await this.SubscriptionHandler.promises.validateNoSubscriptionInRecurly(
  523. this.user_id
  524. )
  525. })
  526. it('should call RecurlyWrapper.promises.listAccountActiveSubscriptions with the user id', function () {
  527. this.RecurlyWrapper.promises.listAccountActiveSubscriptions
  528. .calledWith(this.user_id)
  529. .should.equal(true)
  530. })
  531. it('should sync the subscription', function () {
  532. this.SubscriptionUpdater.promises.syncSubscription
  533. .calledWith(this.subscription, this.user_id)
  534. .should.equal(true)
  535. })
  536. it('should return false', function () {
  537. expect(this.isValid).to.equal(false)
  538. })
  539. })
  540. describe('with no subscription in recurly', function () {
  541. beforeEach(async function () {
  542. this.isValid =
  543. await this.SubscriptionHandler.promises.validateNoSubscriptionInRecurly(
  544. this.user_id
  545. )
  546. })
  547. it('should be rejected and not sync the subscription', function () {
  548. this.SubscriptionUpdater.promises.syncSubscription.called.should.equal(
  549. false
  550. )
  551. })
  552. it('should return true', function () {
  553. expect(this.isValid).to.equal(true)
  554. })
  555. })
  556. })
  557. })