SubscriptionController.test.mjs 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650
  1. import { vi, assert, expect } from 'vitest'
  2. import sinon from 'sinon'
  3. import MockRequest from '../helpers/MockRequest.mjs'
  4. import MockResponse from '../helpers/MockResponse.mjs'
  5. import SubscriptionErrors from '../../../../app/src/Features/Subscription/Errors.mjs'
  6. import SubscriptionHelper from '../../../../app/src/Features/Subscription/SubscriptionHelper.mjs'
  7. import { AI_ADD_ON_CODE } from '../../../../app/src/Features/Subscription/AiHelper.mjs'
  8. const modulePath =
  9. '../../../../app/src/Features/Subscription/SubscriptionController.mjs'
  10. const mockSubscriptions = {
  11. 'subscription-123-active': {
  12. uuid: 'subscription-123-active',
  13. plan: {
  14. name: 'Gold',
  15. plan_code: 'gold',
  16. },
  17. current_period_ends_at: new Date(),
  18. state: 'active',
  19. unit_amount_in_cents: 999,
  20. account: {
  21. account_code: 'user-123',
  22. },
  23. },
  24. }
  25. describe('SubscriptionController', function () {
  26. beforeEach(async function (ctx) {
  27. ctx.logger = {
  28. debug: sinon.stub(),
  29. warn: sinon.stub(),
  30. }
  31. vi.doMock('@overleaf/logger', () => ({
  32. default: ctx.logger,
  33. }))
  34. ctx.user = {
  35. email: 'tom@yahoo.com',
  36. _id: 'one',
  37. signUpDate: new Date('2000-10-01'),
  38. emails: [{ email: 'tom@yahoo.com', confirmedAt: new Date('2000-10-02') }],
  39. }
  40. ctx.activeRecurlySubscription = mockSubscriptions['subscription-123-active']
  41. ctx.SessionManager = {
  42. getLoggedInUser: sinon.stub().callsArgWith(1, null, ctx.user),
  43. getLoggedInUserId: sinon.stub().returns(ctx.user._id),
  44. getSessionUser: sinon.stub().returns(ctx.user),
  45. isUserLoggedIn: sinon.stub().returns(true),
  46. }
  47. ctx.SubscriptionHandler = {
  48. createSubscription: sinon.stub().callsArgWith(3),
  49. updateSubscription: sinon.stub().callsArgWith(3),
  50. reactivateSubscription: sinon.stub().callsArgWith(1),
  51. cancelSubscription: sinon.stub().callsArgWith(1),
  52. syncSubscription: sinon.stub().yields(),
  53. attemptPaypalInvoiceCollection: sinon.stub().yields(),
  54. startFreeTrial: sinon.stub(),
  55. revertPlanChange: sinon.stub(),
  56. promises: {
  57. createSubscription: sinon.stub().resolves(),
  58. updateSubscription: sinon.stub().resolves(),
  59. reactivateSubscription: sinon.stub().resolves(),
  60. cancelSubscription: sinon.stub().resolves(),
  61. pauseSubscription: sinon.stub().resolves(),
  62. resumeSubscription: sinon.stub().resolves(),
  63. syncSubscription: sinon.stub().resolves(),
  64. attemptPaypalInvoiceCollection: sinon.stub().resolves(),
  65. startFreeTrial: sinon.stub().resolves(),
  66. purchaseAddon: sinon.stub().resolves(),
  67. previewAddonPurchase: sinon.stub().resolves({
  68. subscription: {
  69. currency: 'USD',
  70. netTerms: 0,
  71. periodEnd: new Date(),
  72. taxRate: 0,
  73. },
  74. immediateCharge: { amount: 0 },
  75. nextPlanCode: 'professional',
  76. nextPlanName: 'Professional',
  77. nextPlanPrice: 2000,
  78. nextAddOns: [],
  79. subtotal: 2000,
  80. tax: 0,
  81. total: 2000,
  82. }),
  83. revertPlanChange: sinon.stub().resolves(),
  84. },
  85. }
  86. ctx.LimitationsManager = {
  87. hasPaidSubscription: sinon.stub(),
  88. userHasSubscription: sinon
  89. .stub()
  90. .yields(null, { hasSubscription: false }),
  91. promises: {
  92. hasPaidSubscription: sinon.stub().resolves(),
  93. userHasSubscription: sinon.stub().resolves({ hasSubscription: false }),
  94. },
  95. }
  96. ctx.SubscriptionViewModelBuilder = {
  97. buildUsersSubscriptionViewModel: sinon.stub().callsArgWith(1, null, {}),
  98. buildPlansList: sinon.stub(),
  99. promises: {
  100. buildUsersSubscriptionViewModel: sinon.stub().resolves({}),
  101. },
  102. buildPlansListForSubscriptionDash: sinon
  103. .stub()
  104. .returns({ plans: [], planCodesChangingAtTermEnd: [] }),
  105. }
  106. ctx.settings = {
  107. coupon_codes: {
  108. upgradeToAnnualPromo: {
  109. student: 'STUDENTCODEHERE',
  110. collaborator: 'COLLABORATORCODEHERE',
  111. },
  112. },
  113. groupPlanModalOptions: {
  114. plan_codes: [],
  115. currencies: [
  116. {
  117. display: 'GBP (£)',
  118. code: 'GBP',
  119. },
  120. ],
  121. sizes: ['42'],
  122. usages: [{ code: 'foo', display: 'Foo' }],
  123. },
  124. apis: {
  125. recurly: {
  126. subdomain: 'sl',
  127. },
  128. },
  129. planReverts: {
  130. enabled: false,
  131. },
  132. siteUrl: 'http://de.overleaf.dev:3000',
  133. }
  134. ctx.AuthorizationManager = {
  135. promises: {
  136. isUserSiteAdmin: sinon.stub().resolves(false),
  137. },
  138. }
  139. ctx.GeoIpLookup = {
  140. isValidCurrencyParam: sinon.stub().returns(true),
  141. getCurrencyCode: sinon.stub().yields('USD', 'US'),
  142. promises: {
  143. getCurrencyCode: sinon.stub().resolves({
  144. countryCode: 'US',
  145. currencyCode: 'USD',
  146. }),
  147. },
  148. }
  149. ctx.UserGetter = {
  150. getUser: sinon.stub().callsArgWith(2, null, ctx.user),
  151. promises: {
  152. getUser: sinon.stub().resolves(ctx.user),
  153. getWritefullData: sinon
  154. .stub()
  155. .resolves({ isPremium: false, premiumSource: null }),
  156. },
  157. }
  158. ctx.SplitTestV2Hander = {
  159. promises: {
  160. getAssignment: sinon.stub().resolves({ variant: 'default' }),
  161. },
  162. }
  163. ctx.Features = {
  164. hasFeature: sinon.stub().returns(false),
  165. }
  166. vi.doMock(
  167. '../../../../app/src/Features/Authorization/AuthorizationManager',
  168. () => ({
  169. default: ctx.AuthorizationManager,
  170. })
  171. )
  172. vi.doMock(
  173. '../../../../app/src/Features/SplitTests/SplitTestHandler',
  174. () => ({
  175. default: ctx.SplitTestV2Hander,
  176. })
  177. )
  178. vi.doMock(
  179. '../../../../app/src/Features/Authentication/SessionManager',
  180. () => ({
  181. default: ctx.SessionManager,
  182. })
  183. )
  184. vi.doMock(
  185. '../../../../app/src/Features/Subscription/SubscriptionHandler',
  186. () => ({
  187. default: ctx.SubscriptionHandler,
  188. })
  189. )
  190. vi.doMock(
  191. '../../../../app/src/Features/Subscription/SubscriptionHelper',
  192. () => ({
  193. default: SubscriptionHelper,
  194. })
  195. )
  196. vi.doMock(
  197. '../../../../app/src/Features/Subscription/SubscriptionViewModelBuilder',
  198. () => ({
  199. default: ctx.SubscriptionViewModelBuilder,
  200. })
  201. )
  202. vi.doMock(
  203. '../../../../app/src/Features/Subscription/LimitationsManager',
  204. () => ({
  205. default: ctx.LimitationsManager,
  206. })
  207. )
  208. vi.doMock('../../../../app/src/infrastructure/GeoIpLookup', () => ({
  209. default: ctx.GeoIpLookup,
  210. }))
  211. vi.doMock('@overleaf/settings', () => ({
  212. default: ctx.settings,
  213. }))
  214. vi.doMock('../../../../app/src/Features/User/UserGetter', () => ({
  215. default: ctx.UserGetter,
  216. }))
  217. vi.doMock(
  218. '../../../../app/src/Features/Subscription/RecurlyWrapper',
  219. () => ({
  220. default: (ctx.RecurlyWrapper = {
  221. promises: {
  222. updateAccountEmailAddress: sinon.stub().resolves(),
  223. getSubscription: sinon.stub().resolves({}),
  224. },
  225. }),
  226. })
  227. )
  228. vi.doMock(
  229. '../../../../app/src/Features/Subscription/RecurlyEventHandler',
  230. () => ({
  231. default: {
  232. sendRecurlyAnalyticsEvent: sinon.stub().resolves(),
  233. },
  234. })
  235. )
  236. vi.doMock(
  237. '../../../../app/src/Features/Subscription/FeaturesUpdater',
  238. () => ({
  239. default: (ctx.FeaturesUpdater = {
  240. promises: {
  241. refreshFeatures: sinon.stub().resolves({ features: {} }),
  242. },
  243. }),
  244. })
  245. )
  246. vi.doMock(
  247. '../../../../app/src/Features/Subscription/GroupPlansData',
  248. () => ({
  249. default: (ctx.GroupPlansData = {}),
  250. })
  251. )
  252. vi.doMock(
  253. '../../../../app/src/Features/Subscription/V1SubscriptionManager',
  254. () => ({
  255. default: (ctx.V1SubscriptionManager = {}),
  256. })
  257. )
  258. vi.doMock('../../../../app/src/Features/Errors/HttpErrorHandler', () => ({
  259. default: (ctx.HttpErrorHandler = {
  260. unprocessableEntity: sinon.stub().callsFake((req, res, message) => {
  261. res.status(422)
  262. res.json({ message })
  263. }),
  264. badRequest: sinon.stub().callsFake((req, res, message) => {
  265. res.status(400)
  266. res.json({ message })
  267. }),
  268. }),
  269. }))
  270. vi.doMock('../../../../app/src/Features/Subscription/Errors', () => ({
  271. default: SubscriptionErrors,
  272. }))
  273. vi.doMock(
  274. '../../../../app/src/Features/Analytics/AnalyticsManager',
  275. () => ({
  276. default: (ctx.AnalyticsManager = {
  277. recordEventForUser: sinon.stub(),
  278. recordEventForUserInBackground: sinon.stub(),
  279. recordEventForSession: sinon.stub(),
  280. setUserPropertyForUser: sinon.stub(),
  281. }),
  282. })
  283. )
  284. vi.doMock('../../../../app/src/infrastructure/Modules', () => ({
  285. default: (ctx.Modules = {
  286. promises: { hooks: { fire: sinon.stub().resolves() } },
  287. }),
  288. }))
  289. vi.doMock('../../../../app/src/infrastructure/Features', () => ({
  290. default: ctx.Features,
  291. }))
  292. vi.doMock('../../../../app/src/util/currency', () => ({
  293. default: (ctx.currency = {
  294. formatCurrency: sinon.stub(),
  295. }),
  296. }))
  297. vi.doMock('../../../../app/src/models/User', () => ({
  298. User: {
  299. findById: sinon.stub().resolves(ctx.user),
  300. },
  301. }))
  302. vi.doMock(
  303. '../../../../app/src/Features/Subscription/SubscriptionLocator',
  304. () => ({
  305. default: (ctx.SubscriptionLocator = {
  306. promises: {
  307. getUsersSubscription: sinon.stub().resolves(null),
  308. },
  309. }),
  310. })
  311. )
  312. vi.doMock(
  313. '../../../../app/src/Features/Authorization/PermissionsManager',
  314. () => ({
  315. default: (ctx.PermissionsManager = {
  316. promises: {
  317. checkUserPermissions: sinon.stub().resolves(true),
  318. },
  319. }),
  320. })
  321. )
  322. vi.doMock(
  323. '../../../../app/src/Features/Subscription/RecurlyClient',
  324. () => ({
  325. default: (ctx.RecurlyClient = {
  326. promises: {
  327. getAddOn: sinon.stub().resolves({
  328. code: 'ai-assistant',
  329. name: 'AI Assistant',
  330. }),
  331. },
  332. }),
  333. })
  334. )
  335. vi.doMock('../../../../app/src/Features/Subscription/PlansLocator', () => ({
  336. default: (ctx.PlansLocator = {
  337. findLocalPlanInSettings: sinon.stub().returns({
  338. annual: false,
  339. }),
  340. }),
  341. }))
  342. ctx.SubscriptionController = (await import(modulePath)).default
  343. ctx.res = new MockResponse(vi)
  344. ctx.req = new MockRequest(vi)
  345. ctx.req.body = {}
  346. ctx.req.query = { planCode: '123123' }
  347. ctx.stubbedCurrencyCode = 'GBP'
  348. })
  349. describe('successfulSubscription', function () {
  350. it('without a personal subscription', async function (ctx) {
  351. await new Promise(resolve => {
  352. ctx.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  353. {}
  354. )
  355. ctx.res.redirect = url => {
  356. url.should.equal('/user/subscription/plans')
  357. resolve()
  358. }
  359. ctx.SubscriptionController.successfulSubscription(ctx.req, ctx.res)
  360. })
  361. })
  362. it('with a personal subscription', async function (ctx) {
  363. await new Promise(resolve => {
  364. ctx.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  365. {
  366. personalSubscription: 'foo',
  367. }
  368. )
  369. ctx.res.render = (url, variables) => {
  370. url.should.equal('subscriptions/successful-subscription-react')
  371. assert.deepEqual(variables, {
  372. title: 'thank_you',
  373. personalSubscription: 'foo',
  374. postCheckoutRedirect: undefined,
  375. user: {
  376. _id: ctx.user._id,
  377. features: ctx.user.features,
  378. },
  379. })
  380. resolve()
  381. }
  382. ctx.SubscriptionController.successfulSubscription(ctx.req, ctx.res)
  383. })
  384. })
  385. it('with an error', async function (ctx) {
  386. await new Promise(resolve => {
  387. ctx.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  388. undefined
  389. )
  390. ctx.SubscriptionController.successfulSubscription(
  391. ctx.req,
  392. ctx.res,
  393. error => {
  394. assert.isNotNull(error)
  395. resolve()
  396. }
  397. )
  398. })
  399. })
  400. })
  401. describe('userSubscriptionPage', function () {
  402. beforeEach(async function (ctx) {
  403. await new Promise((resolve, reject) => {
  404. ctx.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  405. {
  406. personalSubscription: (ctx.personalSubscription = {
  407. 'personal-subscription': 'mock',
  408. }),
  409. memberGroupSubscriptions: (ctx.memberGroupSubscriptions = {
  410. 'group-subscriptions': 'mock',
  411. }),
  412. }
  413. )
  414. ctx.SubscriptionViewModelBuilder.buildPlansList.returns(
  415. (ctx.plans = { plans: 'mock' })
  416. )
  417. ctx.SubscriptionViewModelBuilder.buildPlansListForSubscriptionDash.returns(
  418. {
  419. plans: ctx.plans,
  420. planCodesChangingAtTermEnd: [],
  421. }
  422. )
  423. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  424. hasSubscription: false,
  425. })
  426. ctx.res.render = (view, data) => {
  427. ctx.data = data
  428. expect(view).to.equal('subscriptions/dashboard-react')
  429. resolve()
  430. }
  431. ctx.SubscriptionController.userSubscriptionPage(
  432. ctx.req,
  433. ctx.res,
  434. ctx.rejectOnError(reject)
  435. )
  436. })
  437. })
  438. it('should load the personal, groups and v1 subscriptions', function (ctx) {
  439. expect(ctx.data.personalSubscription).to.deep.equal(
  440. ctx.personalSubscription
  441. )
  442. expect(ctx.data.memberGroupSubscriptions).to.deep.equal(
  443. ctx.memberGroupSubscriptions
  444. )
  445. })
  446. it('should load the user', function (ctx) {
  447. expect(ctx.data.user).to.deep.equal(ctx.user)
  448. })
  449. it('should load the plans', function (ctx) {
  450. expect(ctx.data.plans).to.deep.equal(ctx.plans)
  451. })
  452. it('should load an empty list of groups with settings available', function (ctx) {
  453. expect(ctx.data.groupSettingsEnabledFor).to.deep.equal([])
  454. })
  455. describe('when errorCode query param is present', function () {
  456. beforeEach(async function (ctx) {
  457. ctx.req.query.errorCode = 'payment_failed'
  458. await new Promise((resolve, reject) => {
  459. ctx.res.render = (view, data) => {
  460. ctx.data = data
  461. expect(view).to.equal('subscriptions/dashboard-react')
  462. resolve()
  463. }
  464. ctx.SubscriptionController.userSubscriptionPage(
  465. ctx.req,
  466. ctx.res,
  467. ctx.rejectOnError(reject)
  468. )
  469. })
  470. })
  471. it('should pass redirectedPaymentErrorCode to the view', function (ctx) {
  472. expect(ctx.data.redirectedPaymentErrorCode).to.equal('payment_failed')
  473. })
  474. })
  475. })
  476. describe('updateAccountEmailAddress via put', function () {
  477. beforeEach(function (ctx) {
  478. ctx.req.body = {
  479. account_email: 'current_account_email@overleaf.com',
  480. }
  481. })
  482. it('should send the user and subscriptionId to "updateAccountEmailAddress" hooks', async function (ctx) {
  483. ctx.res.sendStatus = sinon.spy()
  484. await ctx.SubscriptionController.updateAccountEmailAddress(
  485. ctx.req,
  486. ctx.res
  487. )
  488. expect(ctx.Modules.promises.hooks.fire).to.have.been.calledWith(
  489. 'updateAccountEmailAddress',
  490. ctx.user._id,
  491. ctx.user.email
  492. )
  493. })
  494. it('should respond with 200', async function (ctx) {
  495. ctx.res.sendStatus = sinon.spy()
  496. await ctx.SubscriptionController.updateAccountEmailAddress(
  497. ctx.req,
  498. ctx.res
  499. )
  500. ctx.res.sendStatus.calledWith(200).should.equal(true)
  501. })
  502. it('should send the error to the next handler when updating recurly account email fails', async function (ctx) {
  503. ctx.Modules.promises.hooks.fire
  504. .withArgs('updateAccountEmailAddress', ctx.user._id, ctx.user.email)
  505. .rejects(new Error())
  506. ctx.next = sinon.spy(error => {
  507. expect(error).to.be.instanceOf(Error)
  508. })
  509. await ctx.SubscriptionController.updateAccountEmailAddress(
  510. ctx.req,
  511. ctx.res,
  512. ctx.next
  513. )
  514. expect(ctx.next.calledOnce).to.be.true
  515. })
  516. })
  517. describe('reactivateSubscription', function () {
  518. describe('when the user has permission', function () {
  519. beforeEach(async function (ctx) {
  520. await new Promise(resolve => {
  521. ctx.res = {
  522. redirect() {
  523. resolve()
  524. },
  525. }
  526. ctx.req.assertPermission = sinon.stub()
  527. ctx.next = sinon.stub().callsFake(error => {
  528. resolve(error)
  529. })
  530. sinon.spy(ctx.res, 'redirect')
  531. ctx.SubscriptionController.reactivateSubscription(
  532. ctx.req,
  533. ctx.res,
  534. ctx.next
  535. )
  536. })
  537. })
  538. it('should assert the user has permission to reactivate their subscription', async function (ctx) {
  539. await new Promise(resolve => {
  540. ctx.req.assertPermission
  541. .calledWith('reactivate-subscription')
  542. .should.equal(true)
  543. resolve()
  544. })
  545. })
  546. it('should tell the handler to reactivate this user', async function (ctx) {
  547. await new Promise(resolve => {
  548. ctx.SubscriptionHandler.reactivateSubscription
  549. .calledWith(ctx.user)
  550. .should.equal(true)
  551. resolve()
  552. })
  553. })
  554. it('should redurect to the subscription page', async function (ctx) {
  555. await new Promise(resolve => {
  556. ctx.res.redirect.calledWith('/user/subscription').should.equal(true)
  557. resolve()
  558. })
  559. })
  560. })
  561. describe('when the user does not have permission', function () {
  562. beforeEach(async function (ctx) {
  563. await new Promise(resolve => {
  564. ctx.res = {
  565. redirect() {
  566. resolve()
  567. },
  568. }
  569. ctx.req.assertPermission = sinon.stub().throws()
  570. ctx.next = sinon.stub().callsFake(() => {
  571. resolve()
  572. })
  573. sinon.spy(ctx.res, 'redirect')
  574. ctx.SubscriptionController.reactivateSubscription(
  575. ctx.req,
  576. ctx.res,
  577. ctx.next
  578. )
  579. })
  580. })
  581. it('should not reactivate the user', async function (ctx) {
  582. await new Promise(resolve => {
  583. ctx.req.assertPermission = sinon.stub().throws()
  584. ctx.SubscriptionHandler.reactivateSubscription.called.should.equal(
  585. false
  586. )
  587. resolve()
  588. })
  589. })
  590. it('should call next with an error', async function (ctx) {
  591. await new Promise(resolve => {
  592. ctx.next.calledWith(sinon.match.instanceOf(Error)).should.equal(true)
  593. resolve()
  594. })
  595. })
  596. })
  597. })
  598. describe('pauseSubscription', function () {
  599. it('should throw an error if no pause length is provided', async function (ctx) {
  600. ctx.res = new MockResponse(vi)
  601. ctx.req = new MockRequest(vi)
  602. ctx.next = sinon.stub()
  603. await expect(
  604. ctx.SubscriptionController.pauseSubscription(ctx.req, ctx.res, ctx.next)
  605. ).to.be.rejectedWith('Not found')
  606. })
  607. it('should throw an error if an invalid pause length is provided', async function (ctx) {
  608. ctx.res = new MockResponse(vi)
  609. ctx.req = new MockRequest(vi)
  610. ctx.req.params = { pauseCycles: '-10' }
  611. ctx.next = sinon.stub()
  612. await ctx.SubscriptionController.pauseSubscription(
  613. ctx.req,
  614. ctx.res,
  615. ctx.next
  616. )
  617. expect(ctx.res.statusCode).to.equal(400)
  618. })
  619. it('should return a 200 when requesting a pause', async function (ctx) {
  620. ctx.res = new MockResponse(vi)
  621. ctx.req = new MockRequest(vi)
  622. ctx.req.params = { pauseCycles: '3' }
  623. ctx.next = sinon.stub()
  624. await ctx.SubscriptionController.pauseSubscription(
  625. ctx.req,
  626. ctx.res,
  627. ctx.next
  628. )
  629. expect(ctx.res.statusCode).to.equal(200)
  630. })
  631. })
  632. describe('resumeSubscription', function () {
  633. it('should return a 200 when resuming a subscription', async function (ctx) {
  634. ctx.res = new MockResponse(vi)
  635. ctx.req = new MockRequest(vi)
  636. ctx.next = sinon.stub()
  637. await ctx.SubscriptionController.resumeSubscription(
  638. ctx.req,
  639. ctx.res,
  640. ctx.next
  641. )
  642. expect(ctx.res.statusCode).to.equal(200)
  643. })
  644. })
  645. describe('cancelSubscription', function () {
  646. it('should tell the handler to cancel this user', async function (ctx) {
  647. ctx.next = sinon.stub()
  648. await ctx.SubscriptionController.cancelSubscription(
  649. ctx.req,
  650. ctx.res,
  651. ctx.next
  652. )
  653. ctx.SubscriptionHandler.promises.cancelSubscription
  654. .calledWith(ctx.user)
  655. .should.equal(true)
  656. })
  657. it('should return a 200 on success', async function (ctx) {
  658. ctx.next = sinon.stub()
  659. await ctx.SubscriptionController.cancelSubscription(
  660. ctx.req,
  661. ctx.res,
  662. ctx.next
  663. )
  664. expect(ctx.res.statusCode).to.equal(200)
  665. })
  666. it('should call next with error', async function (ctx) {
  667. ctx.SubscriptionHandler.promises.cancelSubscription.rejects(
  668. new Error('cancel error')
  669. )
  670. ctx.next = sinon.stub()
  671. await ctx.SubscriptionController.cancelSubscription(
  672. ctx.req,
  673. ctx.res,
  674. ctx.next
  675. )
  676. ctx.next.calledWith(sinon.match.instanceOf(Error)).should.equal(true)
  677. })
  678. })
  679. describe('recurly callback', function () {
  680. describe('with a sync subscription request', function () {
  681. beforeEach(async function (ctx) {
  682. await new Promise(resolve => {
  683. ctx.req = {
  684. body: {
  685. expired_subscription_notification: {
  686. account: {
  687. account_code: ctx.user._id,
  688. },
  689. subscription: {
  690. uuid: ctx.activeRecurlySubscription.uuid,
  691. plan: {
  692. plan_code: 'collaborator',
  693. state: 'active',
  694. },
  695. },
  696. },
  697. },
  698. }
  699. ctx.res = {
  700. sendStatus() {
  701. resolve()
  702. },
  703. }
  704. sinon.spy(ctx.res, 'sendStatus')
  705. ctx.SubscriptionController.recurlyCallback(ctx.req, ctx.res)
  706. })
  707. })
  708. it('should tell the SubscriptionHandler to process the recurly callback', async function (ctx) {
  709. await new Promise(resolve => {
  710. ctx.SubscriptionHandler.syncSubscription.called.should.equal(true)
  711. resolve()
  712. })
  713. })
  714. it('should send a 200', async function (ctx) {
  715. await new Promise(resolve => {
  716. ctx.res.sendStatus.calledWith(200)
  717. resolve()
  718. })
  719. })
  720. })
  721. describe('with a billing info updated request', function () {
  722. beforeEach(async function (ctx) {
  723. await new Promise(resolve => {
  724. ctx.req = {
  725. body: {
  726. billing_info_updated_notification: {
  727. account: {
  728. account_code: 'mock-account-code',
  729. },
  730. },
  731. },
  732. }
  733. ctx.res = {
  734. sendStatus() {
  735. resolve()
  736. },
  737. }
  738. sinon.spy(ctx.res, 'sendStatus')
  739. ctx.SubscriptionController.recurlyCallback(ctx.req, ctx.res)
  740. })
  741. })
  742. it('should call attemptPaypalInvoiceCollection', async function (ctx) {
  743. await new Promise(resolve => {
  744. ctx.SubscriptionHandler.attemptPaypalInvoiceCollection
  745. .calledWith('mock-account-code')
  746. .should.equal(true)
  747. resolve()
  748. })
  749. })
  750. it('should send a 200', async function (ctx) {
  751. await new Promise(resolve => {
  752. ctx.res.sendStatus.calledWith(200)
  753. resolve()
  754. })
  755. })
  756. })
  757. describe('with a non-actionable request', function () {
  758. beforeEach(async function (ctx) {
  759. await new Promise(resolve => {
  760. ctx.user.id = ctx.activeRecurlySubscription.account.account_code
  761. ctx.req = {
  762. body: {
  763. renewed_subscription_notification: {
  764. account: {
  765. account_code: ctx.user._id,
  766. },
  767. subscription: {
  768. uuid: ctx.activeRecurlySubscription.uuid,
  769. plan: {
  770. plan_code: 'collaborator',
  771. state: 'active',
  772. },
  773. },
  774. },
  775. },
  776. }
  777. ctx.res = {
  778. sendStatus() {
  779. resolve()
  780. },
  781. }
  782. sinon.spy(ctx.res, 'sendStatus')
  783. ctx.SubscriptionController.recurlyCallback(ctx.req, ctx.res)
  784. })
  785. })
  786. it('should not call the subscriptionshandler', function (ctx) {
  787. ctx.SubscriptionHandler.syncSubscription.called.should.equal(false)
  788. ctx.SubscriptionHandler.attemptPaypalInvoiceCollection.called.should.equal(
  789. false
  790. )
  791. })
  792. it('should respond with a 200 status', function (ctx) {
  793. ctx.res.sendStatus.calledWith(200)
  794. })
  795. })
  796. describe('with a failed payment notification', function () {
  797. describe('with planReverts disabled in settings', function () {
  798. beforeEach(async function (ctx) {
  799. await new Promise(resolve => {
  800. ctx.settings.planReverts = { enabled: false }
  801. ctx.SubscriptionHandler.revertPlanChange = sinon.stub()
  802. ctx.req.body = {
  803. failed_payment_notification: {
  804. transaction: {
  805. subscription_id: 'subscription-123',
  806. },
  807. },
  808. }
  809. ctx.res = {
  810. sendStatus() {
  811. resolve()
  812. },
  813. }
  814. sinon.spy(ctx.res, 'sendStatus')
  815. ctx.SubscriptionController.recurlyCallback(ctx.req, ctx.res)
  816. })
  817. })
  818. it('should not call revertPlanChange', function (ctx) {
  819. expect(ctx.SubscriptionHandler.revertPlanChange.called).to.be.false
  820. })
  821. it('should respond with 200', async function (ctx) {
  822. await new Promise(resolve => {
  823. ctx.res.sendStatus.calledWith(200)
  824. resolve()
  825. })
  826. })
  827. })
  828. describe('with planReverts enabled in settings', function () {
  829. beforeEach(function (ctx) {
  830. ctx.settings.planReverts = { enabled: true }
  831. })
  832. describe('with no valid restore point', function () {
  833. beforeEach(async function (ctx) {
  834. await new Promise(resolve => {
  835. ctx.SubscriptionHandler.getSubscriptionRestorePoint = sinon
  836. .stub()
  837. .yields(null, null)
  838. ctx.SubscriptionHandler.revertPlanChange = sinon.stub()
  839. ctx.req.body = {
  840. failed_payment_notification: {
  841. transaction: {
  842. subscription_id: 'subscription-123',
  843. },
  844. },
  845. }
  846. ctx.res = {
  847. sendStatus() {
  848. resolve()
  849. },
  850. }
  851. sinon.spy(ctx.res, 'sendStatus')
  852. ctx.SubscriptionController.recurlyCallback(ctx.req, ctx.res)
  853. })
  854. })
  855. it('should not call revertPlanChange()', function (ctx) {
  856. expect(ctx.SubscriptionHandler.revertPlanChange.called).to.be.false
  857. })
  858. it('should respond with 200', function (ctx) {
  859. ctx.res.sendStatus.calledWith(200)
  860. })
  861. })
  862. describe('with a valid restore point', function () {
  863. beforeEach(async function (ctx) {
  864. await new Promise(resolve => {
  865. ctx.addOns = [
  866. {
  867. addOnCode: 'addon-1',
  868. quantity: 2,
  869. unitAmountInCents: 500,
  870. },
  871. {
  872. addOnCode: 'addon-2',
  873. quantity: 1,
  874. unitAmountInCents: 600,
  875. },
  876. ]
  877. ctx.lastSubscription = {
  878. planCode: 'gold',
  879. addOns: ctx.addOns,
  880. }
  881. ctx.SubscriptionHandler.getSubscriptionRestorePoint = sinon
  882. .stub()
  883. .yields(null, ctx.lastSubscription)
  884. ctx.SubscriptionHandler.revertPlanChange = sinon.stub().yields()
  885. ctx.req.body = {
  886. failed_payment_notification: {
  887. transaction: {
  888. subscription_id: 'subscription-123',
  889. },
  890. },
  891. }
  892. ctx.res = {
  893. sendStatus() {
  894. resolve()
  895. },
  896. }
  897. sinon.spy(ctx.res, 'sendStatus')
  898. ctx.SubscriptionController.recurlyCallback(ctx.req, ctx.res)
  899. })
  900. })
  901. it('should get the subscription restore point', function (ctx) {
  902. expect(
  903. ctx.SubscriptionHandler.getSubscriptionRestorePoint.calledWith(
  904. 'subscription-123'
  905. )
  906. ).to.be.true
  907. })
  908. it('should call revertPlanChange()', function (ctx) {
  909. expect(
  910. ctx.SubscriptionHandler.revertPlanChange.calledWith(
  911. 'subscription-123',
  912. ctx.lastSubscription
  913. )
  914. ).to.be.true
  915. })
  916. it('should respond with 200', function (ctx) {
  917. ctx.res.sendStatus.calledWith(200)
  918. })
  919. })
  920. })
  921. })
  922. })
  923. describe('purchaseAddon', function () {
  924. beforeEach(function (ctx) {
  925. ctx.SessionManager.getSessionUser.returns(ctx.user) // Make sure getSessionUser returns the user
  926. ctx.next = sinon.stub()
  927. ctx.req.params = { addOnCode: AI_ADD_ON_CODE } // Mock add-on code
  928. })
  929. it('should return 200 on successful purchase of AI add-on', async function (ctx) {
  930. await ctx.SubscriptionController.purchaseAddon(ctx.req, ctx.res, ctx.next)
  931. ctx.res.sendStatus = sinon.spy()
  932. await ctx.SubscriptionController.purchaseAddon(ctx.req, ctx.res, ctx.next)
  933. expect(ctx.SubscriptionHandler.promises.purchaseAddon).to.have.been.called
  934. expect(
  935. ctx.SubscriptionHandler.promises.purchaseAddon
  936. ).to.have.been.calledWith(ctx.user._id, AI_ADD_ON_CODE, 1)
  937. expect(
  938. ctx.FeaturesUpdater.promises.refreshFeatures
  939. ).to.have.been.calledWith(ctx.user._id, 'add-on-purchase')
  940. expect(ctx.res.sendStatus).to.have.been.calledWith(200)
  941. expect(ctx.logger.debug).to.have.been.calledWith(
  942. { userId: ctx.user._id, addOnCode: AI_ADD_ON_CODE },
  943. 'purchasing add-ons'
  944. )
  945. })
  946. it('should return 404 if the add-on code is not AI_ADD_ON_CODE', async function (ctx) {
  947. ctx.req.params = { addOnCode: 'some-other-addon' }
  948. ctx.res.sendStatus = sinon.spy()
  949. await ctx.SubscriptionController.purchaseAddon(ctx.req, ctx.res, ctx.next)
  950. expect(ctx.SubscriptionHandler.promises.purchaseAddon).to.not.have.been
  951. .called
  952. expect(ctx.FeaturesUpdater.promises.refreshFeatures).to.not.have.been
  953. .called
  954. expect(ctx.res.sendStatus).to.have.been.calledWith(404)
  955. })
  956. it('should handle DuplicateAddOnError and send badRequest while sending 200', async function (ctx) {
  957. ctx.req.params.addOnCode = AI_ADD_ON_CODE
  958. ctx.SubscriptionHandler.promises.purchaseAddon.rejects(
  959. new SubscriptionErrors.DuplicateAddOnError()
  960. )
  961. await ctx.SubscriptionController.purchaseAddon(ctx.req, ctx.res, ctx.next)
  962. expect(ctx.HttpErrorHandler.badRequest).to.have.been.calledWith(
  963. ctx.req,
  964. ctx.res,
  965. 'Your subscription already includes this add-on',
  966. { addon: AI_ADD_ON_CODE }
  967. )
  968. expect(
  969. ctx.FeaturesUpdater.promises.refreshFeatures
  970. ).to.have.been.calledWith(ctx.user._id, 'add-on-purchase')
  971. expect(ctx.res.sendStatus).toHaveBeenCalledWith(200)
  972. })
  973. it('should handle PaymentActionRequiredError and return 402 with details', async function (ctx) {
  974. ctx.req.params.addOnCode = AI_ADD_ON_CODE
  975. const paymentError = new SubscriptionErrors.PaymentActionRequiredError({
  976. clientSecret: 'secret123',
  977. publicKey: 'pubkey456',
  978. })
  979. ctx.SubscriptionHandler.promises.purchaseAddon.rejects(paymentError)
  980. await ctx.SubscriptionController.purchaseAddon(ctx.req, ctx.res, ctx.next)
  981. expect(ctx.res.status).toHaveBeenCalledWith(402)
  982. expect(ctx.res.json).toHaveBeenCalledWith({
  983. message: 'Payment action required',
  984. clientSecret: 'secret123',
  985. publicKey: 'pubkey456',
  986. })
  987. expect(ctx.FeaturesUpdater.promises.refreshFeatures).to.not.have.been
  988. .called
  989. })
  990. it('should refresh features', async function (ctx) {
  991. ctx.req.params.addOnCode = 'assistant'
  992. ctx.SubscriptionHandler.promises.purchaseAddon = sinon.stub().resolves()
  993. ctx.FeaturesUpdater.promises.refreshFeatures = sinon.stub().resolves()
  994. await ctx.SubscriptionController.purchaseAddon(ctx.req, ctx.res)
  995. expect(
  996. ctx.FeaturesUpdater.promises.refreshFeatures.calledWith(
  997. ctx.user._id,
  998. 'add-on-purchase'
  999. )
  1000. ).to.be.true
  1001. })
  1002. it('should respond with a bad request if the subscription already includes the addOn', async function (ctx) {
  1003. ctx.req.params.addOnCode = 'assistant'
  1004. ctx.SubscriptionHandler.promises.purchaseAddon = sinon
  1005. .stub()
  1006. .rejects(new SubscriptionErrors.DuplicateAddOnError())
  1007. await ctx.SubscriptionController.purchaseAddon(ctx.req, ctx.res)
  1008. expect(
  1009. ctx.HttpErrorHandler.badRequest.calledWith(
  1010. ctx.req,
  1011. ctx.res,
  1012. 'Your subscription already includes this add-on',
  1013. { addon: 'assistant' }
  1014. )
  1015. ).to.be.true
  1016. })
  1017. })
  1018. describe('removeAddon', function () {
  1019. beforeEach(function (ctx) {
  1020. ctx.SessionManager.getSessionUser.returns(ctx.user)
  1021. ctx.next = sinon.stub()
  1022. ctx.req.params = { addOnCode: AI_ADD_ON_CODE }
  1023. ctx.SubscriptionHandler.promises.removeAddon = sinon.stub().resolves()
  1024. })
  1025. it('should return 200 on successful removal of AI add-on', async function (ctx) {
  1026. ctx.res.sendStatus = sinon.spy()
  1027. await ctx.SubscriptionController.removeAddon(ctx.req, ctx.res, ctx.next)
  1028. expect(ctx.SubscriptionHandler.promises.removeAddon).to.have.been.called
  1029. expect(
  1030. ctx.SubscriptionHandler.promises.removeAddon
  1031. ).to.have.been.calledWith(ctx.user, AI_ADD_ON_CODE)
  1032. expect(ctx.res.sendStatus).to.have.been.calledWith(200)
  1033. expect(ctx.logger.debug).to.have.been.calledWith(
  1034. { userId: ctx.user._id, addOnCode: AI_ADD_ON_CODE },
  1035. 'removing add-ons'
  1036. )
  1037. })
  1038. it('should return 404 if the add-on code is not AI_ADD_ON_CODE', async function (ctx) {
  1039. ctx.req.params = { addOnCode: 'some-other-addon' }
  1040. ctx.res.sendStatus = sinon.spy()
  1041. await ctx.SubscriptionController.removeAddon(ctx.req, ctx.res, ctx.next)
  1042. expect(ctx.SubscriptionHandler.promises.removeAddon).to.not.have.been
  1043. .called
  1044. expect(ctx.res.sendStatus).to.have.been.calledWith(404)
  1045. })
  1046. it('should handle AddOnNotPresentError and send badRequest', async function (ctx) {
  1047. ctx.SubscriptionHandler.promises.removeAddon.rejects(
  1048. new SubscriptionErrors.AddOnNotPresentError()
  1049. )
  1050. await ctx.SubscriptionController.removeAddon(ctx.req, ctx.res, ctx.next)
  1051. expect(ctx.HttpErrorHandler.badRequest).to.have.been.calledWith(
  1052. ctx.req,
  1053. ctx.res,
  1054. 'Your subscription does not contain the requested add-on',
  1055. { addon: AI_ADD_ON_CODE }
  1056. )
  1057. })
  1058. })
  1059. describe('checkSubscriptionPauseStatus', function () {
  1060. beforeEach(function (ctx) {
  1061. ctx.user = {
  1062. _id: 'user-id-123',
  1063. email: 'test@example.com',
  1064. }
  1065. })
  1066. it('should return isPaused: false when user has no subscription', async function (ctx) {
  1067. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1068. subscription: null,
  1069. })
  1070. const result =
  1071. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1072. expect(result).to.deep.equal({ isPaused: false })
  1073. })
  1074. it('should return isPaused: false when subscription has no paymentProvider', async function (ctx) {
  1075. const subscription = {
  1076. planCode: 'professional',
  1077. }
  1078. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1079. subscription,
  1080. })
  1081. const result =
  1082. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1083. expect(result).to.deep.equal({ isPaused: false })
  1084. })
  1085. it('should return isPaused: false when subscription has no subscriptionId', async function (ctx) {
  1086. const subscription = {
  1087. paymentProvider: {
  1088. service: 'stripe',
  1089. subscriptionId: null,
  1090. },
  1091. }
  1092. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1093. subscription,
  1094. })
  1095. const result =
  1096. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1097. expect(result).to.deep.equal({ isPaused: false })
  1098. })
  1099. it('should return isPaused: false when Stripe subscription has no remaining pause cycles', async function (ctx) {
  1100. const subscription = {
  1101. paymentProvider: {
  1102. service: 'stripe',
  1103. subscriptionId: 'sub-123',
  1104. },
  1105. }
  1106. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1107. subscription,
  1108. })
  1109. const paymentRecord = {
  1110. subscription: {
  1111. remainingPauseCycles: 0,
  1112. },
  1113. }
  1114. ctx.Modules.promises.hooks.fire
  1115. .withArgs('getPaymentFromRecord', subscription)
  1116. .resolves([paymentRecord])
  1117. const result =
  1118. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1119. expect(result).to.deep.equal({ isPaused: false })
  1120. })
  1121. it('should return isPaused: false when Stripe subscription has no remainingPauseCycles property', async function (ctx) {
  1122. const subscription = {
  1123. paymentProvider: {
  1124. service: 'stripe',
  1125. subscriptionId: 'sub-123',
  1126. },
  1127. }
  1128. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1129. subscription,
  1130. })
  1131. const paymentRecord = {
  1132. subscription: {},
  1133. }
  1134. ctx.Modules.promises.hooks.fire
  1135. .withArgs('getPaymentFromRecord', subscription)
  1136. .resolves([paymentRecord])
  1137. const result =
  1138. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1139. expect(result).to.deep.equal({ isPaused: false })
  1140. })
  1141. it('should return isPaused: true with redirect path when Stripe subscription has remaining pause cycles', async function (ctx) {
  1142. const subscription = {
  1143. paymentProvider: {
  1144. service: 'stripe',
  1145. subscriptionId: 'sub-123',
  1146. },
  1147. }
  1148. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1149. subscription,
  1150. })
  1151. const paymentRecord = {
  1152. subscription: {
  1153. remainingPauseCycles: 2,
  1154. },
  1155. }
  1156. ctx.Modules.promises.hooks.fire
  1157. .withArgs('getPaymentFromRecord', subscription)
  1158. .resolves([paymentRecord])
  1159. const result =
  1160. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1161. expect(result).to.deep.equal({
  1162. isPaused: true,
  1163. redirectPath: '/user/subscription?redirect-reason=subscription-paused',
  1164. })
  1165. })
  1166. it('should return isPaused: true when remainingPauseCycles is exactly 1', async function (ctx) {
  1167. const subscription = {
  1168. paymentProvider: {
  1169. service: 'stripe',
  1170. subscriptionId: 'sub-123',
  1171. },
  1172. }
  1173. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1174. subscription,
  1175. })
  1176. const paymentRecord = {
  1177. subscription: {
  1178. remainingPauseCycles: 1,
  1179. },
  1180. }
  1181. ctx.Modules.promises.hooks.fire
  1182. .withArgs('getPaymentFromRecord', subscription)
  1183. .resolves([paymentRecord])
  1184. const result =
  1185. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1186. expect(result).to.deep.equal({
  1187. isPaused: true,
  1188. redirectPath: '/user/subscription?redirect-reason=subscription-paused',
  1189. })
  1190. })
  1191. it('should return isPaused: false when userHasSubscription throws error', async function (ctx) {
  1192. const error = new Error('Something bad happened')
  1193. ctx.LimitationsManager.promises.userHasSubscription.rejects(error)
  1194. const result =
  1195. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1196. expect(result).to.deep.equal({ isPaused: false })
  1197. })
  1198. it('should return isPaused: false when getPaymentFromRecord throws error', async function (ctx) {
  1199. const subscription = {
  1200. paymentProvider: {
  1201. service: 'stripe',
  1202. subscriptionId: 'sub-123',
  1203. },
  1204. }
  1205. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1206. subscription,
  1207. })
  1208. const error = new Error('Something bad happened')
  1209. ctx.Modules.promises.hooks.fire
  1210. .withArgs('getPaymentFromRecord', subscription)
  1211. .rejects(error)
  1212. const result =
  1213. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1214. expect(result).to.deep.equal({ isPaused: false })
  1215. })
  1216. it('should return isPaused: false when Recurly subscription is not paused', async function (ctx) {
  1217. const subscription = {
  1218. recurlySubscription_id: 'uuid-123',
  1219. recurlyStatus: {
  1220. state: 'active',
  1221. },
  1222. }
  1223. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1224. subscription,
  1225. })
  1226. const result =
  1227. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1228. expect(result).to.deep.equal({ isPaused: false })
  1229. })
  1230. it('should return isPaused: true when Recurly subscription is paused', async function (ctx) {
  1231. const subscription = {
  1232. recurlySubscription_id: 'uuid-123',
  1233. recurlyStatus: {
  1234. state: 'paused',
  1235. },
  1236. }
  1237. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1238. subscription,
  1239. })
  1240. const result =
  1241. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1242. expect(result).to.deep.equal({
  1243. isPaused: true,
  1244. redirectPath: '/user/subscription?redirect-reason=subscription-paused',
  1245. })
  1246. })
  1247. it('should return isPaused: true when Recurly subscription has pending pause cycles', async function (ctx) {
  1248. const subscription = {
  1249. recurlySubscription_id: 'uuid-123',
  1250. recurlyStatus: {
  1251. state: 'active',
  1252. },
  1253. }
  1254. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1255. subscription,
  1256. })
  1257. const recurlySubscriptionData = {
  1258. remaining_pause_cycles: 2,
  1259. }
  1260. ctx.RecurlyWrapper.promises.getSubscription.resolves(
  1261. recurlySubscriptionData
  1262. )
  1263. const result =
  1264. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1265. expect(result).to.deep.equal({
  1266. isPaused: true,
  1267. redirectPath: '/user/subscription?redirect-reason=subscription-paused',
  1268. })
  1269. expect(
  1270. ctx.RecurlyWrapper.promises.getSubscription
  1271. ).to.have.been.calledWith('uuid-123')
  1272. })
  1273. it('should return isPaused: false when Recurly subscription has no remaining pause cycles', async function (ctx) {
  1274. const subscription = {
  1275. recurlySubscription_id: 'uuid-123',
  1276. recurlyStatus: {
  1277. state: 'active',
  1278. },
  1279. }
  1280. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1281. subscription,
  1282. })
  1283. const recurlySubscriptionData = {
  1284. remaining_pause_cycles: 0,
  1285. }
  1286. ctx.RecurlyWrapper.promises.getSubscription.resolves(
  1287. recurlySubscriptionData
  1288. )
  1289. const result =
  1290. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1291. expect(result).to.deep.equal({ isPaused: false })
  1292. })
  1293. it('should return isPaused: false when Recurly subscription has no remaining_pause_cycles property', async function (ctx) {
  1294. const subscription = {
  1295. recurlySubscription_id: 'uuid-123',
  1296. recurlyStatus: {
  1297. state: 'active',
  1298. },
  1299. }
  1300. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1301. subscription,
  1302. })
  1303. const recurlySubscriptionData = {}
  1304. ctx.RecurlyWrapper.promises.getSubscription.resolves(
  1305. recurlySubscriptionData
  1306. )
  1307. const result =
  1308. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1309. expect(result).to.deep.equal({ isPaused: false })
  1310. })
  1311. it('should return isPaused: false when Recurly API call fails', async function (ctx) {
  1312. const subscription = {
  1313. recurlySubscription_id: 'uuid-123',
  1314. recurlyStatus: {
  1315. state: 'active',
  1316. },
  1317. }
  1318. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1319. subscription,
  1320. })
  1321. const error = new Error('Recurly API failed')
  1322. ctx.RecurlyWrapper.promises.getSubscription.rejects(error)
  1323. const result =
  1324. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1325. expect(result).to.deep.equal({ isPaused: false })
  1326. })
  1327. })
  1328. describe('previewAddonPurchase', function () {
  1329. beforeEach(function (ctx) {
  1330. ctx.req = new MockRequest(vi)
  1331. ctx.req.params = { addOnCode: 'assistant' }
  1332. ctx.req.query = { purchaseReferrer: 'fake-referrer' }
  1333. ctx.res = new MockResponse(vi)
  1334. ctx.Modules.promises.hooks.fire
  1335. .withArgs('getPaymentMethod')
  1336. .resolves(['fake-method'])
  1337. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(null)
  1338. })
  1339. describe('when user has manual or custom subscription', function () {
  1340. it('should redirect with ai-assist-unavailable when subscription has customAccount = true', async function (ctx) {
  1341. const customSubscription = {
  1342. _id: 'sub-123',
  1343. customAccount: true,
  1344. collectionMethod: 'automatic',
  1345. }
  1346. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1347. customSubscription
  1348. )
  1349. ctx.res.redirect = sinon.stub()
  1350. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1351. expect(ctx.res.redirect).to.have.been.calledWith(
  1352. '/user/subscription?redirect-reason=ai-assist-unavailable'
  1353. )
  1354. })
  1355. it('should redirect with ai-assist-unavailable when subscription has collectionMethod = manual', async function (ctx) {
  1356. const manualSubscription = {
  1357. _id: 'sub-123',
  1358. customAccount: false,
  1359. collectionMethod: 'manual',
  1360. }
  1361. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1362. manualSubscription
  1363. )
  1364. ctx.res.redirect = sinon.stub()
  1365. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1366. expect(ctx.res.redirect).to.have.been.calledWith(
  1367. '/user/subscription?redirect-reason=ai-assist-unavailable'
  1368. )
  1369. })
  1370. it('should redirect with ai-assist-unavailable when subscription has both customAccount and manual collection', async function (ctx) {
  1371. const customManualSubscription = {
  1372. _id: 'sub-123',
  1373. customAccount: true,
  1374. collectionMethod: 'manual',
  1375. }
  1376. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1377. customManualSubscription
  1378. )
  1379. ctx.res.redirect = sinon.stub()
  1380. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1381. expect(ctx.res.redirect).to.have.been.calledWith(
  1382. '/user/subscription?redirect-reason=ai-assist-unavailable'
  1383. )
  1384. })
  1385. })
  1386. describe('when user has normal subscription', function () {
  1387. it('should proceed with preview when subscription is not manual or custom', async function (ctx) {
  1388. const normalSubscription = {
  1389. _id: 'sub-123',
  1390. customAccount: false,
  1391. collectionMethod: 'automatic',
  1392. }
  1393. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1394. normalSubscription
  1395. )
  1396. ctx.res.render = sinon.stub()
  1397. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1398. expect(ctx.res.render).to.have.been.calledWith(
  1399. 'subscriptions/preview-change',
  1400. sinon.match({
  1401. changePreview: sinon.match.object,
  1402. purchaseReferrer: 'fake-referrer',
  1403. redirectedPaymentErrorCode: undefined,
  1404. })
  1405. )
  1406. expect(
  1407. ctx.SubscriptionHandler.promises.previewAddonPurchase
  1408. ).to.have.been.calledWith(ctx.user._id, 'assistant')
  1409. })
  1410. it('should pass redirectedPaymentErrorCode to the view when errorCode query param is present', async function (ctx) {
  1411. const normalSubscription = {
  1412. _id: 'sub-123',
  1413. customAccount: false,
  1414. collectionMethod: 'automatic',
  1415. }
  1416. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1417. normalSubscription
  1418. )
  1419. ctx.req.query.errorCode = 'payment_failed'
  1420. ctx.res.render = sinon.stub()
  1421. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1422. expect(ctx.res.render).to.have.been.calledWith(
  1423. 'subscriptions/preview-change',
  1424. sinon.match({
  1425. changePreview: sinon.match.object,
  1426. purchaseReferrer: 'fake-referrer',
  1427. redirectedPaymentErrorCode: 'payment_failed',
  1428. })
  1429. )
  1430. })
  1431. it('should proceed with preview when customAccount is undefined and collectionMethod is automatic', async function (ctx) {
  1432. const normalSubscription = {
  1433. _id: 'sub-123',
  1434. // customAccount: undefined (not set)
  1435. collectionMethod: 'automatic',
  1436. }
  1437. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1438. normalSubscription
  1439. )
  1440. ctx.res.render = sinon.stub()
  1441. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1442. expect(ctx.res.render).to.have.been.calledWith(
  1443. 'subscriptions/preview-change'
  1444. )
  1445. expect(
  1446. ctx.SubscriptionHandler.promises.previewAddonPurchase
  1447. ).to.have.been.calledWith(ctx.user._id, 'assistant')
  1448. })
  1449. })
  1450. })
  1451. })