SubscriptionController.test.mjs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652
  1. import { vi, assert, expect } from 'vitest'
  2. import sinon from 'sinon'
  3. import MockRequest from '../helpers/MockRequest.js'
  4. import MockResponse from '../helpers/MockResponse.js'
  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()
  344. ctx.req = new MockRequest()
  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()
  601. ctx.req = new MockRequest()
  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()
  609. ctx.req = new MockRequest()
  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()
  621. ctx.req = new MockRequest()
  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()
  635. ctx.req = new MockRequest()
  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).to.have.been.calledWith(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. ctx.res.status.calledWith(402).should.equal(true)
  982. ctx.res.json
  983. .calledWith({
  984. message: 'Payment action required',
  985. clientSecret: 'secret123',
  986. publicKey: 'pubkey456',
  987. })
  988. .should.equal(true)
  989. expect(ctx.FeaturesUpdater.promises.refreshFeatures).to.not.have.been
  990. .called
  991. })
  992. it('should refresh features', async function (ctx) {
  993. ctx.req.params.addOnCode = 'assistant'
  994. ctx.SubscriptionHandler.promises.purchaseAddon = sinon.stub().resolves()
  995. ctx.FeaturesUpdater.promises.refreshFeatures = sinon.stub().resolves()
  996. await ctx.SubscriptionController.purchaseAddon(ctx.req, ctx.res)
  997. expect(
  998. ctx.FeaturesUpdater.promises.refreshFeatures.calledWith(
  999. ctx.user._id,
  1000. 'add-on-purchase'
  1001. )
  1002. ).to.be.true
  1003. })
  1004. it('should respond with a bad request if the subscription already includes the addOn', async function (ctx) {
  1005. ctx.req.params.addOnCode = 'assistant'
  1006. ctx.SubscriptionHandler.promises.purchaseAddon = sinon
  1007. .stub()
  1008. .rejects(new SubscriptionErrors.DuplicateAddOnError())
  1009. await ctx.SubscriptionController.purchaseAddon(ctx.req, ctx.res)
  1010. expect(
  1011. ctx.HttpErrorHandler.badRequest.calledWith(
  1012. ctx.req,
  1013. ctx.res,
  1014. 'Your subscription already includes this add-on',
  1015. { addon: 'assistant' }
  1016. )
  1017. ).to.be.true
  1018. })
  1019. })
  1020. describe('removeAddon', function () {
  1021. beforeEach(function (ctx) {
  1022. ctx.SessionManager.getSessionUser.returns(ctx.user)
  1023. ctx.next = sinon.stub()
  1024. ctx.req.params = { addOnCode: AI_ADD_ON_CODE }
  1025. ctx.SubscriptionHandler.promises.removeAddon = sinon.stub().resolves()
  1026. })
  1027. it('should return 200 on successful removal of AI add-on', async function (ctx) {
  1028. ctx.res.sendStatus = sinon.spy()
  1029. await ctx.SubscriptionController.removeAddon(ctx.req, ctx.res, ctx.next)
  1030. expect(ctx.SubscriptionHandler.promises.removeAddon).to.have.been.called
  1031. expect(
  1032. ctx.SubscriptionHandler.promises.removeAddon
  1033. ).to.have.been.calledWith(ctx.user, AI_ADD_ON_CODE)
  1034. expect(ctx.res.sendStatus).to.have.been.calledWith(200)
  1035. expect(ctx.logger.debug).to.have.been.calledWith(
  1036. { userId: ctx.user._id, addOnCode: AI_ADD_ON_CODE },
  1037. 'removing add-ons'
  1038. )
  1039. })
  1040. it('should return 404 if the add-on code is not AI_ADD_ON_CODE', async function (ctx) {
  1041. ctx.req.params = { addOnCode: 'some-other-addon' }
  1042. ctx.res.sendStatus = sinon.spy()
  1043. await ctx.SubscriptionController.removeAddon(ctx.req, ctx.res, ctx.next)
  1044. expect(ctx.SubscriptionHandler.promises.removeAddon).to.not.have.been
  1045. .called
  1046. expect(ctx.res.sendStatus).to.have.been.calledWith(404)
  1047. })
  1048. it('should handle AddOnNotPresentError and send badRequest', async function (ctx) {
  1049. ctx.SubscriptionHandler.promises.removeAddon.rejects(
  1050. new SubscriptionErrors.AddOnNotPresentError()
  1051. )
  1052. await ctx.SubscriptionController.removeAddon(ctx.req, ctx.res, ctx.next)
  1053. expect(ctx.HttpErrorHandler.badRequest).to.have.been.calledWith(
  1054. ctx.req,
  1055. ctx.res,
  1056. 'Your subscription does not contain the requested add-on',
  1057. { addon: AI_ADD_ON_CODE }
  1058. )
  1059. })
  1060. })
  1061. describe('checkSubscriptionPauseStatus', function () {
  1062. beforeEach(function (ctx) {
  1063. ctx.user = {
  1064. _id: 'user-id-123',
  1065. email: 'test@example.com',
  1066. }
  1067. })
  1068. it('should return isPaused: false when user has no subscription', async function (ctx) {
  1069. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1070. subscription: null,
  1071. })
  1072. const result =
  1073. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1074. expect(result).to.deep.equal({ isPaused: false })
  1075. })
  1076. it('should return isPaused: false when subscription has no paymentProvider', async function (ctx) {
  1077. const subscription = {
  1078. planCode: 'professional',
  1079. }
  1080. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1081. subscription,
  1082. })
  1083. const result =
  1084. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1085. expect(result).to.deep.equal({ isPaused: false })
  1086. })
  1087. it('should return isPaused: false when subscription has no subscriptionId', async function (ctx) {
  1088. const subscription = {
  1089. paymentProvider: {
  1090. service: 'stripe',
  1091. subscriptionId: null,
  1092. },
  1093. }
  1094. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1095. subscription,
  1096. })
  1097. const result =
  1098. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1099. expect(result).to.deep.equal({ isPaused: false })
  1100. })
  1101. it('should return isPaused: false when Stripe subscription has no remaining pause cycles', async function (ctx) {
  1102. const subscription = {
  1103. paymentProvider: {
  1104. service: 'stripe',
  1105. subscriptionId: 'sub-123',
  1106. },
  1107. }
  1108. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1109. subscription,
  1110. })
  1111. const paymentRecord = {
  1112. subscription: {
  1113. remainingPauseCycles: 0,
  1114. },
  1115. }
  1116. ctx.Modules.promises.hooks.fire
  1117. .withArgs('getPaymentFromRecord', subscription)
  1118. .resolves([paymentRecord])
  1119. const result =
  1120. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1121. expect(result).to.deep.equal({ isPaused: false })
  1122. })
  1123. it('should return isPaused: false when Stripe subscription has no remainingPauseCycles property', async function (ctx) {
  1124. const subscription = {
  1125. paymentProvider: {
  1126. service: 'stripe',
  1127. subscriptionId: 'sub-123',
  1128. },
  1129. }
  1130. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1131. subscription,
  1132. })
  1133. const paymentRecord = {
  1134. subscription: {},
  1135. }
  1136. ctx.Modules.promises.hooks.fire
  1137. .withArgs('getPaymentFromRecord', subscription)
  1138. .resolves([paymentRecord])
  1139. const result =
  1140. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1141. expect(result).to.deep.equal({ isPaused: false })
  1142. })
  1143. it('should return isPaused: true with redirect path when Stripe subscription has remaining pause cycles', async function (ctx) {
  1144. const subscription = {
  1145. paymentProvider: {
  1146. service: 'stripe',
  1147. subscriptionId: 'sub-123',
  1148. },
  1149. }
  1150. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1151. subscription,
  1152. })
  1153. const paymentRecord = {
  1154. subscription: {
  1155. remainingPauseCycles: 2,
  1156. },
  1157. }
  1158. ctx.Modules.promises.hooks.fire
  1159. .withArgs('getPaymentFromRecord', subscription)
  1160. .resolves([paymentRecord])
  1161. const result =
  1162. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1163. expect(result).to.deep.equal({
  1164. isPaused: true,
  1165. redirectPath: '/user/subscription?redirect-reason=subscription-paused',
  1166. })
  1167. })
  1168. it('should return isPaused: true when remainingPauseCycles is exactly 1', async function (ctx) {
  1169. const subscription = {
  1170. paymentProvider: {
  1171. service: 'stripe',
  1172. subscriptionId: 'sub-123',
  1173. },
  1174. }
  1175. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1176. subscription,
  1177. })
  1178. const paymentRecord = {
  1179. subscription: {
  1180. remainingPauseCycles: 1,
  1181. },
  1182. }
  1183. ctx.Modules.promises.hooks.fire
  1184. .withArgs('getPaymentFromRecord', subscription)
  1185. .resolves([paymentRecord])
  1186. const result =
  1187. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1188. expect(result).to.deep.equal({
  1189. isPaused: true,
  1190. redirectPath: '/user/subscription?redirect-reason=subscription-paused',
  1191. })
  1192. })
  1193. it('should return isPaused: false when userHasSubscription throws error', async function (ctx) {
  1194. const error = new Error('Something bad happened')
  1195. ctx.LimitationsManager.promises.userHasSubscription.rejects(error)
  1196. const result =
  1197. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1198. expect(result).to.deep.equal({ isPaused: false })
  1199. })
  1200. it('should return isPaused: false when getPaymentFromRecord throws error', async function (ctx) {
  1201. const subscription = {
  1202. paymentProvider: {
  1203. service: 'stripe',
  1204. subscriptionId: 'sub-123',
  1205. },
  1206. }
  1207. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1208. subscription,
  1209. })
  1210. const error = new Error('Something bad happened')
  1211. ctx.Modules.promises.hooks.fire
  1212. .withArgs('getPaymentFromRecord', subscription)
  1213. .rejects(error)
  1214. const result =
  1215. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1216. expect(result).to.deep.equal({ isPaused: false })
  1217. })
  1218. it('should return isPaused: false when Recurly subscription is not paused', async function (ctx) {
  1219. const subscription = {
  1220. recurlySubscription_id: 'uuid-123',
  1221. recurlyStatus: {
  1222. state: 'active',
  1223. },
  1224. }
  1225. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1226. subscription,
  1227. })
  1228. const result =
  1229. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1230. expect(result).to.deep.equal({ isPaused: false })
  1231. })
  1232. it('should return isPaused: true when Recurly subscription is paused', async function (ctx) {
  1233. const subscription = {
  1234. recurlySubscription_id: 'uuid-123',
  1235. recurlyStatus: {
  1236. state: 'paused',
  1237. },
  1238. }
  1239. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1240. subscription,
  1241. })
  1242. const result =
  1243. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1244. expect(result).to.deep.equal({
  1245. isPaused: true,
  1246. redirectPath: '/user/subscription?redirect-reason=subscription-paused',
  1247. })
  1248. })
  1249. it('should return isPaused: true when Recurly subscription has pending pause cycles', async function (ctx) {
  1250. const subscription = {
  1251. recurlySubscription_id: 'uuid-123',
  1252. recurlyStatus: {
  1253. state: 'active',
  1254. },
  1255. }
  1256. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1257. subscription,
  1258. })
  1259. const recurlySubscriptionData = {
  1260. remaining_pause_cycles: 2,
  1261. }
  1262. ctx.RecurlyWrapper.promises.getSubscription.resolves(
  1263. recurlySubscriptionData
  1264. )
  1265. const result =
  1266. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1267. expect(result).to.deep.equal({
  1268. isPaused: true,
  1269. redirectPath: '/user/subscription?redirect-reason=subscription-paused',
  1270. })
  1271. expect(
  1272. ctx.RecurlyWrapper.promises.getSubscription
  1273. ).to.have.been.calledWith('uuid-123')
  1274. })
  1275. it('should return isPaused: false when Recurly subscription has no remaining pause cycles', async function (ctx) {
  1276. const subscription = {
  1277. recurlySubscription_id: 'uuid-123',
  1278. recurlyStatus: {
  1279. state: 'active',
  1280. },
  1281. }
  1282. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1283. subscription,
  1284. })
  1285. const recurlySubscriptionData = {
  1286. remaining_pause_cycles: 0,
  1287. }
  1288. ctx.RecurlyWrapper.promises.getSubscription.resolves(
  1289. recurlySubscriptionData
  1290. )
  1291. const result =
  1292. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1293. expect(result).to.deep.equal({ isPaused: false })
  1294. })
  1295. it('should return isPaused: false when Recurly subscription has no remaining_pause_cycles property', async function (ctx) {
  1296. const subscription = {
  1297. recurlySubscription_id: 'uuid-123',
  1298. recurlyStatus: {
  1299. state: 'active',
  1300. },
  1301. }
  1302. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1303. subscription,
  1304. })
  1305. const recurlySubscriptionData = {}
  1306. ctx.RecurlyWrapper.promises.getSubscription.resolves(
  1307. recurlySubscriptionData
  1308. )
  1309. const result =
  1310. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1311. expect(result).to.deep.equal({ isPaused: false })
  1312. })
  1313. it('should return isPaused: false when Recurly API call fails', async function (ctx) {
  1314. const subscription = {
  1315. recurlySubscription_id: 'uuid-123',
  1316. recurlyStatus: {
  1317. state: 'active',
  1318. },
  1319. }
  1320. ctx.LimitationsManager.promises.userHasSubscription.resolves({
  1321. subscription,
  1322. })
  1323. const error = new Error('Recurly API failed')
  1324. ctx.RecurlyWrapper.promises.getSubscription.rejects(error)
  1325. const result =
  1326. await ctx.SubscriptionController.checkSubscriptionPauseStatus(ctx.user)
  1327. expect(result).to.deep.equal({ isPaused: false })
  1328. })
  1329. })
  1330. describe('previewAddonPurchase', function () {
  1331. beforeEach(function (ctx) {
  1332. ctx.req = new MockRequest()
  1333. ctx.req.params = { addOnCode: 'assistant' }
  1334. ctx.req.query = { purchaseReferrer: 'fake-referrer' }
  1335. ctx.res = new MockResponse()
  1336. ctx.Modules.promises.hooks.fire
  1337. .withArgs('getPaymentMethod')
  1338. .resolves(['fake-method'])
  1339. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(null)
  1340. })
  1341. describe('when user has manual or custom subscription', function () {
  1342. it('should redirect with ai-assist-unavailable when subscription has customAccount = true', async function (ctx) {
  1343. const customSubscription = {
  1344. _id: 'sub-123',
  1345. customAccount: true,
  1346. collectionMethod: 'automatic',
  1347. }
  1348. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1349. customSubscription
  1350. )
  1351. ctx.res.redirect = sinon.stub()
  1352. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1353. expect(ctx.res.redirect).to.have.been.calledWith(
  1354. '/user/subscription?redirect-reason=ai-assist-unavailable'
  1355. )
  1356. })
  1357. it('should redirect with ai-assist-unavailable when subscription has collectionMethod = manual', async function (ctx) {
  1358. const manualSubscription = {
  1359. _id: 'sub-123',
  1360. customAccount: false,
  1361. collectionMethod: 'manual',
  1362. }
  1363. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1364. manualSubscription
  1365. )
  1366. ctx.res.redirect = sinon.stub()
  1367. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1368. expect(ctx.res.redirect).to.have.been.calledWith(
  1369. '/user/subscription?redirect-reason=ai-assist-unavailable'
  1370. )
  1371. })
  1372. it('should redirect with ai-assist-unavailable when subscription has both customAccount and manual collection', async function (ctx) {
  1373. const customManualSubscription = {
  1374. _id: 'sub-123',
  1375. customAccount: true,
  1376. collectionMethod: 'manual',
  1377. }
  1378. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1379. customManualSubscription
  1380. )
  1381. ctx.res.redirect = sinon.stub()
  1382. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1383. expect(ctx.res.redirect).to.have.been.calledWith(
  1384. '/user/subscription?redirect-reason=ai-assist-unavailable'
  1385. )
  1386. })
  1387. })
  1388. describe('when user has normal subscription', function () {
  1389. it('should proceed with preview when subscription is not manual or custom', async function (ctx) {
  1390. const normalSubscription = {
  1391. _id: 'sub-123',
  1392. customAccount: false,
  1393. collectionMethod: 'automatic',
  1394. }
  1395. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1396. normalSubscription
  1397. )
  1398. ctx.res.render = sinon.stub()
  1399. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1400. expect(ctx.res.render).to.have.been.calledWith(
  1401. 'subscriptions/preview-change',
  1402. sinon.match({
  1403. changePreview: sinon.match.object,
  1404. purchaseReferrer: 'fake-referrer',
  1405. redirectedPaymentErrorCode: undefined,
  1406. })
  1407. )
  1408. expect(
  1409. ctx.SubscriptionHandler.promises.previewAddonPurchase
  1410. ).to.have.been.calledWith(ctx.user._id, 'assistant')
  1411. })
  1412. it('should pass redirectedPaymentErrorCode to the view when errorCode query param is present', async function (ctx) {
  1413. const normalSubscription = {
  1414. _id: 'sub-123',
  1415. customAccount: false,
  1416. collectionMethod: 'automatic',
  1417. }
  1418. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1419. normalSubscription
  1420. )
  1421. ctx.req.query.errorCode = 'payment_failed'
  1422. ctx.res.render = sinon.stub()
  1423. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1424. expect(ctx.res.render).to.have.been.calledWith(
  1425. 'subscriptions/preview-change',
  1426. sinon.match({
  1427. changePreview: sinon.match.object,
  1428. purchaseReferrer: 'fake-referrer',
  1429. redirectedPaymentErrorCode: 'payment_failed',
  1430. })
  1431. )
  1432. })
  1433. it('should proceed with preview when customAccount is undefined and collectionMethod is automatic', async function (ctx) {
  1434. const normalSubscription = {
  1435. _id: 'sub-123',
  1436. // customAccount: undefined (not set)
  1437. collectionMethod: 'automatic',
  1438. }
  1439. ctx.SubscriptionLocator.promises.getUsersSubscription.resolves(
  1440. normalSubscription
  1441. )
  1442. ctx.res.render = sinon.stub()
  1443. await ctx.SubscriptionController.previewAddonPurchase(ctx.req, ctx.res)
  1444. expect(ctx.res.render).to.have.been.calledWith(
  1445. 'subscriptions/preview-change'
  1446. )
  1447. expect(
  1448. ctx.SubscriptionHandler.promises.previewAddonPurchase
  1449. ).to.have.been.calledWith(ctx.user._id, 'assistant')
  1450. })
  1451. })
  1452. })
  1453. })