SubscriptionControllerTests.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606
  1. const SandboxedModule = require('sandboxed-module')
  2. const sinon = require('sinon')
  3. const { assert, expect } = require('chai')
  4. const MockRequest = require('../helpers/MockRequest')
  5. const MockResponse = require('../helpers/MockResponse')
  6. const modulePath =
  7. '../../../../app/src/Features/Subscription/SubscriptionController'
  8. const SubscriptionErrors = require('../../../../app/src/Features/Subscription/Errors')
  9. const mockSubscriptions = {
  10. 'subscription-123-active': {
  11. uuid: 'subscription-123-active',
  12. plan: {
  13. name: 'Gold',
  14. plan_code: 'gold',
  15. },
  16. current_period_ends_at: new Date(),
  17. state: 'active',
  18. unit_amount_in_cents: 999,
  19. account: {
  20. account_code: 'user-123',
  21. },
  22. },
  23. }
  24. describe('SubscriptionController', function () {
  25. beforeEach(function () {
  26. this.user = {
  27. email: 'tom@yahoo.com',
  28. _id: 'one',
  29. signUpDate: new Date('2000-10-01'),
  30. emails: [{ email: 'tom@yahoo.com', confirmedAt: new Date('2000-10-02') }],
  31. }
  32. this.activeRecurlySubscription =
  33. mockSubscriptions['subscription-123-active']
  34. this.SessionManager = {
  35. getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user),
  36. getLoggedInUserId: sinon.stub().returns(this.user._id),
  37. getSessionUser: sinon.stub().returns(this.user),
  38. isUserLoggedIn: sinon.stub().returns(true),
  39. }
  40. this.SubscriptionHandler = {
  41. createSubscription: sinon.stub().callsArgWith(3),
  42. updateSubscription: sinon.stub().callsArgWith(3),
  43. reactivateSubscription: sinon.stub().callsArgWith(1),
  44. cancelSubscription: sinon.stub().callsArgWith(1),
  45. syncSubscription: sinon.stub().yields(),
  46. attemptPaypalInvoiceCollection: sinon.stub().yields(),
  47. startFreeTrial: sinon.stub(),
  48. promises: {
  49. createSubscription: sinon.stub().resolves(),
  50. updateSubscription: sinon.stub().resolves(),
  51. reactivateSubscription: sinon.stub().resolves(),
  52. cancelSubscription: sinon.stub().resolves(),
  53. pauseSubscription: sinon.stub().resolves(),
  54. resumeSubscription: sinon.stub().resolves(),
  55. syncSubscription: sinon.stub().resolves(),
  56. attemptPaypalInvoiceCollection: sinon.stub().resolves(),
  57. startFreeTrial: sinon.stub().resolves(),
  58. },
  59. }
  60. this.LimitationsManager = {
  61. hasPaidSubscription: sinon.stub(),
  62. userHasSubscription: sinon
  63. .stub()
  64. .yields(null, { hasSubscription: false }),
  65. promises: {
  66. hasPaidSubscription: sinon.stub().resolves(),
  67. userHasSubscription: sinon.stub().resolves({ hasSubscription: false }),
  68. },
  69. }
  70. this.SubscriptionViewModelBuilder = {
  71. buildUsersSubscriptionViewModel: sinon.stub().callsArgWith(1, null, {}),
  72. buildPlansList: sinon.stub(),
  73. promises: {
  74. buildUsersSubscriptionViewModel: sinon.stub().resolves({}),
  75. getBestSubscription: sinon.stub().resolves({}),
  76. },
  77. buildPlansListForSubscriptionDash: sinon
  78. .stub()
  79. .returns({ plans: [], planCodesChangingAtTermEnd: [] }),
  80. }
  81. this.settings = {
  82. coupon_codes: {
  83. upgradeToAnnualPromo: {
  84. student: 'STUDENTCODEHERE',
  85. collaborator: 'COLLABORATORCODEHERE',
  86. },
  87. },
  88. groupPlanModalOptions: {
  89. plan_codes: [],
  90. currencies: [
  91. {
  92. display: 'GBP (£)',
  93. code: 'GBP',
  94. },
  95. ],
  96. sizes: ['42'],
  97. usages: [{ code: 'foo', display: 'Foo' }],
  98. },
  99. apis: {
  100. recurly: {
  101. subdomain: 'sl',
  102. },
  103. },
  104. siteUrl: 'http://de.overleaf.dev:3000',
  105. }
  106. this.AuthorizationManager = {
  107. promises: {
  108. isUserSiteAdmin: sinon.stub().resolves(false),
  109. },
  110. }
  111. this.GeoIpLookup = {
  112. isValidCurrencyParam: sinon.stub().returns(true),
  113. getCurrencyCode: sinon.stub().yields('USD', 'US'),
  114. promises: {
  115. getCurrencyCode: sinon.stub().resolves({
  116. countryCode: 'US',
  117. currencyCode: 'USD',
  118. }),
  119. },
  120. }
  121. this.UserGetter = {
  122. getUser: sinon.stub().callsArgWith(2, null, this.user),
  123. promises: {
  124. getUser: sinon.stub().resolves(this.user),
  125. getWritefullData: sinon
  126. .stub()
  127. .resolves({ isPremium: false, premiumSource: null }),
  128. },
  129. }
  130. this.SplitTestV2Hander = {
  131. promises: {
  132. getAssignment: sinon.stub().resolves({ variant: 'default' }),
  133. },
  134. }
  135. this.Features = {
  136. hasFeature: sinon.stub().returns(false),
  137. }
  138. this.SubscriptionController = SandboxedModule.require(modulePath, {
  139. requires: {
  140. '../Authorization/AuthorizationManager': this.AuthorizationManager,
  141. '../SplitTests/SplitTestHandler': this.SplitTestV2Hander,
  142. '../Authentication/SessionManager': this.SessionManager,
  143. './SubscriptionHandler': this.SubscriptionHandler,
  144. './SubscriptionHelper': this.SubscriptionHelper,
  145. './SubscriptionViewModelBuilder': this.SubscriptionViewModelBuilder,
  146. './LimitationsManager': this.LimitationsManager,
  147. '../../infrastructure/GeoIpLookup': this.GeoIpLookup,
  148. '@overleaf/settings': this.settings,
  149. '../User/UserGetter': this.UserGetter,
  150. './RecurlyWrapper': (this.RecurlyWrapper = {
  151. updateAccountEmailAddress: sinon.stub().yields(),
  152. }),
  153. './RecurlyEventHandler': {
  154. sendRecurlyAnalyticsEvent: sinon.stub().resolves(),
  155. },
  156. './FeaturesUpdater': (this.FeaturesUpdater = {
  157. promises: {
  158. refreshFeatures: sinon.stub().resolves({ features: {} }),
  159. },
  160. }),
  161. './GroupPlansData': (this.GroupPlansData = {}),
  162. './V1SubscriptionManager': (this.V1SubscriptionManager = {}),
  163. '../Errors/HttpErrorHandler': (this.HttpErrorHandler = {
  164. unprocessableEntity: sinon.stub().callsFake((req, res, message) => {
  165. res.status(422)
  166. res.json({ message })
  167. }),
  168. badRequest: sinon.stub().callsFake((req, res, message) => {
  169. res.status(400)
  170. res.json({ message })
  171. }),
  172. }),
  173. './Errors': SubscriptionErrors,
  174. '../Analytics/AnalyticsManager': (this.AnalyticsManager = {
  175. recordEventForUser: sinon.stub(),
  176. recordEventForUserInBackground: sinon.stub(),
  177. recordEventForSession: sinon.stub(),
  178. setUserPropertyForUser: sinon.stub(),
  179. }),
  180. '../../infrastructure/Modules': (this.Modules = {
  181. promises: { hooks: { fire: sinon.stub().resolves() } },
  182. }),
  183. '../../infrastructure/Features': this.Features,
  184. '../../util/currency': (this.currency = {
  185. formatCurrency: sinon.stub(),
  186. }),
  187. '../../models/User': {
  188. User: {
  189. findById: sinon.stub().resolves(this.user),
  190. },
  191. },
  192. },
  193. })
  194. this.res = new MockResponse()
  195. this.req = new MockRequest()
  196. this.req.body = {}
  197. this.req.query = { planCode: '123123' }
  198. this.stubbedCurrencyCode = 'GBP'
  199. })
  200. describe('successfulSubscription', function () {
  201. it('without a personal subscription', function (done) {
  202. this.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  203. {}
  204. )
  205. this.res.redirect = url => {
  206. url.should.equal('/user/subscription/plans')
  207. done()
  208. }
  209. this.SubscriptionController.successfulSubscription(this.req, this.res)
  210. })
  211. it('with a personal subscription', function (done) {
  212. this.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  213. {
  214. personalSubscription: 'foo',
  215. }
  216. )
  217. this.res.render = (url, variables) => {
  218. url.should.equal('subscriptions/successful-subscription-react')
  219. assert.deepEqual(variables, {
  220. title: 'thank_you',
  221. personalSubscription: 'foo',
  222. postCheckoutRedirect: undefined,
  223. user: {
  224. _id: this.user._id,
  225. features: this.user.features,
  226. },
  227. })
  228. done()
  229. }
  230. this.SubscriptionController.successfulSubscription(this.req, this.res)
  231. })
  232. it('with an error', function (done) {
  233. this.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  234. undefined
  235. )
  236. this.SubscriptionController.successfulSubscription(
  237. this.req,
  238. this.res,
  239. error => {
  240. assert.isNotNull(error)
  241. done()
  242. }
  243. )
  244. })
  245. })
  246. describe('userSubscriptionPage', function () {
  247. beforeEach(function (done) {
  248. this.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  249. {
  250. personalSubscription: (this.personalSubscription = {
  251. 'personal-subscription': 'mock',
  252. }),
  253. memberGroupSubscriptions: (this.memberGroupSubscriptions = {
  254. 'group-subscriptions': 'mock',
  255. }),
  256. }
  257. )
  258. this.SubscriptionViewModelBuilder.buildPlansList.returns(
  259. (this.plans = { plans: 'mock' })
  260. )
  261. this.SubscriptionViewModelBuilder.buildPlansListForSubscriptionDash.returns(
  262. {
  263. plans: this.plans,
  264. planCodesChangingAtTermEnd: [],
  265. }
  266. )
  267. this.LimitationsManager.promises.userHasSubscription.resolves({
  268. hasSubscription: false,
  269. })
  270. this.res.render = (view, data) => {
  271. this.data = data
  272. expect(view).to.equal('subscriptions/dashboard-react')
  273. done()
  274. }
  275. this.SubscriptionController.userSubscriptionPage(this.req, this.res, done)
  276. })
  277. it('should load the personal, groups and v1 subscriptions', function () {
  278. expect(this.data.personalSubscription).to.deep.equal(
  279. this.personalSubscription
  280. )
  281. expect(this.data.memberGroupSubscriptions).to.deep.equal(
  282. this.memberGroupSubscriptions
  283. )
  284. })
  285. it('should load the user', function () {
  286. expect(this.data.user).to.deep.equal(this.user)
  287. })
  288. it('should load the plans', function () {
  289. expect(this.data.plans).to.deep.equal(this.plans)
  290. })
  291. it('should load an empty list of groups with settings available', function () {
  292. expect(this.data.groupSettingsEnabledFor).to.deep.equal([])
  293. })
  294. })
  295. describe('updateAccountEmailAddress via put', function () {
  296. it('should send the user and subscriptionId to RecurlyWrapper', function () {
  297. this.res.sendStatus = sinon.spy()
  298. this.SubscriptionController.updateAccountEmailAddress(this.req, this.res)
  299. this.RecurlyWrapper.updateAccountEmailAddress
  300. .calledWith(this.user._id, this.user.email)
  301. .should.equal(true)
  302. })
  303. it('should respond with 200', function () {
  304. this.res.sendStatus = sinon.spy()
  305. this.SubscriptionController.updateAccountEmailAddress(this.req, this.res)
  306. this.res.sendStatus.calledWith(200).should.equal(true)
  307. })
  308. it('should send the error to the next handler when updating recurly account email fails', function (done) {
  309. this.RecurlyWrapper.updateAccountEmailAddress.yields(new Error())
  310. this.next = sinon.spy(error => {
  311. expect(error).instanceOf(Error)
  312. done()
  313. })
  314. this.SubscriptionController.updateAccountEmailAddress(
  315. this.req,
  316. this.res,
  317. this.next
  318. )
  319. })
  320. })
  321. describe('reactivateSubscription', function () {
  322. describe('when the user has permission', function () {
  323. beforeEach(function (done) {
  324. this.res = {
  325. redirect() {
  326. done()
  327. },
  328. }
  329. this.req.assertPermission = sinon.stub()
  330. this.next = sinon.stub().callsFake(error => {
  331. done(error)
  332. })
  333. sinon.spy(this.res, 'redirect')
  334. this.SubscriptionController.reactivateSubscription(
  335. this.req,
  336. this.res,
  337. this.next
  338. )
  339. })
  340. it('should assert the user has permission to reactivate their subscription', function (done) {
  341. this.req.assertPermission
  342. .calledWith('reactivate-subscription')
  343. .should.equal(true)
  344. done()
  345. })
  346. it('should tell the handler to reactivate this user', function (done) {
  347. this.SubscriptionHandler.reactivateSubscription
  348. .calledWith(this.user)
  349. .should.equal(true)
  350. done()
  351. })
  352. it('should redurect to the subscription page', function (done) {
  353. this.res.redirect.calledWith('/user/subscription').should.equal(true)
  354. done()
  355. })
  356. })
  357. describe('when the user does not have permission', function () {
  358. beforeEach(function (done) {
  359. this.res = {
  360. redirect() {
  361. done()
  362. },
  363. }
  364. this.req.assertPermission = sinon.stub().throws()
  365. this.next = sinon.stub().callsFake(() => {
  366. done()
  367. })
  368. sinon.spy(this.res, 'redirect')
  369. this.SubscriptionController.reactivateSubscription(
  370. this.req,
  371. this.res,
  372. this.next
  373. )
  374. })
  375. it('should not reactivate the user', function (done) {
  376. this.req.assertPermission = sinon.stub().throws()
  377. this.SubscriptionHandler.reactivateSubscription.called.should.equal(
  378. false
  379. )
  380. done()
  381. })
  382. it('should call next with an error', function (done) {
  383. this.next.calledWith(sinon.match.instanceOf(Error)).should.equal(true)
  384. done()
  385. })
  386. })
  387. })
  388. describe('pauseSubscription', function () {
  389. it('should throw an error if no pause length is provided', async function () {
  390. this.res = new MockResponse()
  391. this.req = new MockRequest()
  392. this.next = sinon.stub()
  393. await this.SubscriptionController.pauseSubscription(
  394. this.req,
  395. this.res,
  396. this.next
  397. )
  398. expect(this.res.statusCode).to.equal(400)
  399. })
  400. it('should throw an error if an invalid pause length is provided', async function () {
  401. this.res = new MockResponse()
  402. this.req = new MockRequest()
  403. this.req.params = { pauseCycles: -10 }
  404. this.next = sinon.stub()
  405. await this.SubscriptionController.pauseSubscription(
  406. this.req,
  407. this.res,
  408. this.next
  409. )
  410. expect(this.res.statusCode).to.equal(400)
  411. })
  412. it('should return a 200 when requesting a pause', async function () {
  413. this.res = new MockResponse()
  414. this.req = new MockRequest()
  415. this.req.params = { pauseCycles: 3 }
  416. this.next = sinon.stub()
  417. await this.SubscriptionController.pauseSubscription(
  418. this.req,
  419. this.res,
  420. this.next
  421. )
  422. expect(this.res.statusCode).to.equal(200)
  423. })
  424. })
  425. describe('resumeSubscription', function () {
  426. it('should return a 200 when resuming a subscription', async function () {
  427. this.res = new MockResponse()
  428. this.req = new MockRequest()
  429. this.next = sinon.stub()
  430. await this.SubscriptionController.resumeSubscription(
  431. this.req,
  432. this.res,
  433. this.next
  434. )
  435. expect(this.res.statusCode).to.equal(200)
  436. })
  437. })
  438. describe('cancelSubscription', function () {
  439. beforeEach(function (done) {
  440. this.res = {
  441. redirect() {
  442. done()
  443. },
  444. }
  445. sinon.spy(this.res, 'redirect')
  446. this.SubscriptionController.cancelSubscription(this.req, this.res)
  447. })
  448. it('should tell the handler to cancel this user', function (done) {
  449. this.SubscriptionHandler.cancelSubscription
  450. .calledWith(this.user)
  451. .should.equal(true)
  452. done()
  453. })
  454. it('should redurect to the subscription page', function (done) {
  455. this.res.redirect
  456. .calledWith('/user/subscription/canceled')
  457. .should.equal(true)
  458. done()
  459. })
  460. })
  461. describe('recurly callback', function () {
  462. describe('with a sync subscription request', function () {
  463. beforeEach(function (done) {
  464. this.req = {
  465. body: {
  466. expired_subscription_notification: {
  467. account: {
  468. account_code: this.user._id,
  469. },
  470. subscription: {
  471. uuid: this.activeRecurlySubscription.uuid,
  472. plan: {
  473. plan_code: 'collaborator',
  474. state: 'active',
  475. },
  476. },
  477. },
  478. },
  479. }
  480. this.res = {
  481. sendStatus() {
  482. done()
  483. },
  484. }
  485. sinon.spy(this.res, 'sendStatus')
  486. this.SubscriptionController.recurlyCallback(this.req, this.res)
  487. })
  488. it('should tell the SubscriptionHandler to process the recurly callback', function (done) {
  489. this.SubscriptionHandler.syncSubscription.called.should.equal(true)
  490. done()
  491. })
  492. it('should send a 200', function (done) {
  493. this.res.sendStatus.calledWith(200)
  494. done()
  495. })
  496. })
  497. describe('with a billing info updated request', function () {
  498. beforeEach(function (done) {
  499. this.req = {
  500. body: {
  501. billing_info_updated_notification: {
  502. account: {
  503. account_code: 'mock-account-code',
  504. },
  505. },
  506. },
  507. }
  508. this.res = {
  509. sendStatus() {
  510. done()
  511. },
  512. }
  513. sinon.spy(this.res, 'sendStatus')
  514. this.SubscriptionController.recurlyCallback(this.req, this.res)
  515. })
  516. it('should call attemptPaypalInvoiceCollection', function (done) {
  517. this.SubscriptionHandler.attemptPaypalInvoiceCollection
  518. .calledWith('mock-account-code')
  519. .should.equal(true)
  520. done()
  521. })
  522. it('should send a 200', function (done) {
  523. this.res.sendStatus.calledWith(200)
  524. done()
  525. })
  526. })
  527. describe('with a non-actionable request', function () {
  528. beforeEach(function (done) {
  529. this.user.id = this.activeRecurlySubscription.account.account_code
  530. this.req = {
  531. body: {
  532. renewed_subscription_notification: {
  533. account: {
  534. account_code: this.user._id,
  535. },
  536. subscription: {
  537. uuid: this.activeRecurlySubscription.uuid,
  538. plan: {
  539. plan_code: 'collaborator',
  540. state: 'active',
  541. },
  542. },
  543. },
  544. },
  545. }
  546. this.res = {
  547. sendStatus() {
  548. done()
  549. },
  550. }
  551. sinon.spy(this.res, 'sendStatus')
  552. this.SubscriptionController.recurlyCallback(this.req, this.res)
  553. })
  554. it('should not call the subscriptionshandler', function () {
  555. this.SubscriptionHandler.syncSubscription.called.should.equal(false)
  556. this.SubscriptionHandler.attemptPaypalInvoiceCollection.called.should.equal(
  557. false
  558. )
  559. })
  560. it('should respond with a 200 status', function () {
  561. this.res.sendStatus.calledWith(200)
  562. })
  563. })
  564. })
  565. })