SubscriptionControllerTests.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038
  1. const SandboxedModule = require('sandboxed-module')
  2. const sinon = require('sinon')
  3. const { assert, expect } = require('chai')
  4. const MockRequest = require('../helpers/MockRequest')
  5. const MockResponse = require('../helpers/MockResponse')
  6. const modulePath =
  7. '../../../../app/src/Features/Subscription/SubscriptionController'
  8. const Errors = require('../../../../app/src/Features/Errors/Errors')
  9. const SubscriptionErrors = require('../../../../app/src/Features/Subscription/Errors')
  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(function () {
  27. this.user = {
  28. email: 'tom@yahoo.com',
  29. _id: 'one',
  30. signUpDate: new Date('2000-10-01'),
  31. emails: [{ email: 'tom@yahoo.com', confirmedAt: new Date('2000-10-02') }],
  32. }
  33. this.activeRecurlySubscription =
  34. mockSubscriptions['subscription-123-active']
  35. this.SessionManager = {
  36. getLoggedInUser: sinon.stub().callsArgWith(1, null, this.user),
  37. getLoggedInUserId: sinon.stub().returns(this.user._id),
  38. getSessionUser: sinon.stub().returns(this.user),
  39. isUserLoggedIn: sinon.stub().returns(true),
  40. }
  41. this.SubscriptionHandler = {
  42. createSubscription: sinon.stub().callsArgWith(3),
  43. updateSubscription: sinon.stub().callsArgWith(3),
  44. reactivateSubscription: sinon.stub().callsArgWith(1),
  45. cancelSubscription: sinon.stub().callsArgWith(1),
  46. syncSubscription: sinon.stub().yields(),
  47. attemptPaypalInvoiceCollection: sinon.stub().yields(),
  48. startFreeTrial: sinon.stub(),
  49. promises: {
  50. createSubscription: sinon.stub().resolves(),
  51. updateSubscription: sinon.stub().resolves(),
  52. reactivateSubscription: sinon.stub().resolves(),
  53. cancelSubscription: sinon.stub().resolves(),
  54. syncSubscription: sinon.stub().resolves(),
  55. attemptPaypalInvoiceCollection: sinon.stub().resolves(),
  56. startFreeTrial: sinon.stub().resolves(),
  57. },
  58. }
  59. this.PlansLocator = { findLocalPlanInSettings: sinon.stub() }
  60. this.LimitationsManager = {
  61. hasPaidSubscription: sinon.stub(),
  62. userHasV1OrV2Subscription: sinon.stub(),
  63. userHasV2Subscription: sinon.stub(),
  64. promises: {
  65. hasPaidSubscription: sinon.stub().resolves(),
  66. userHasV1OrV2Subscription: sinon.stub().resolves(),
  67. userHasV2Subscription: sinon.stub().resolves(),
  68. },
  69. }
  70. this.SubscriptionViewModelBuilder = {
  71. buildUsersSubscriptionViewModel: sinon.stub().callsArgWith(1, null, {}),
  72. buildPlansList: sinon.stub(),
  73. promises: {
  74. buildUsersSubscriptionViewModel: sinon.stub().resolves({}),
  75. getBestSubscription: sinon.stub().resolves({}),
  76. },
  77. buildPlansListForSubscriptionDash: sinon
  78. .stub()
  79. .returns({ plans: [], planCodesChangingAtTermEnd: [] }),
  80. }
  81. this.settings = {
  82. coupon_codes: {
  83. upgradeToAnnualPromo: {
  84. student: 'STUDENTCODEHERE',
  85. collaborator: 'COLLABORATORCODEHERE',
  86. },
  87. },
  88. groupPlanModalOptions: {
  89. plan_codes: [],
  90. currencies: [
  91. {
  92. display: 'GBP (£)',
  93. code: 'GBP',
  94. },
  95. ],
  96. sizes: ['42'],
  97. usages: [{ code: 'foo', display: 'Foo' }],
  98. },
  99. apis: {
  100. recurly: {
  101. subdomain: 'sl',
  102. },
  103. },
  104. siteUrl: 'http://de.sharelatex.dev:3000',
  105. }
  106. this.AuthorizationManager = {
  107. promises: {
  108. isUserSiteAdmin: sinon.stub().resolves(false),
  109. },
  110. }
  111. this.GeoIpLookup = {
  112. isValidCurrencyParam: sinon.stub().returns(true),
  113. getCurrencyCode: sinon.stub(),
  114. promises: {
  115. getCurrencyCode: sinon.stub(),
  116. },
  117. }
  118. this.UserGetter = {
  119. getUser: sinon.stub().callsArgWith(2, null, this.user),
  120. promises: {
  121. getUser: sinon.stub().resolves(this.user),
  122. },
  123. }
  124. this.SplitTestV2Hander = {
  125. promises: {
  126. getAssignment: sinon.stub().resolves({ variant: 'default' }),
  127. },
  128. }
  129. this.SubscriptionHelper = {
  130. generateInitialLocalizedGroupPrice: sinon.stub(),
  131. }
  132. this.Features = {
  133. hasFeature: sinon.stub().returns(false),
  134. }
  135. this.SubscriptionController = SandboxedModule.require(modulePath, {
  136. requires: {
  137. '../Authorization/AuthorizationManager': this.AuthorizationManager,
  138. '../SplitTests/SplitTestHandler': this.SplitTestV2Hander,
  139. '../Authentication/SessionManager': this.SessionManager,
  140. './SubscriptionHandler': this.SubscriptionHandler,
  141. './SubscriptionHelper': this.SubscriptionHelper,
  142. './PlansLocator': this.PlansLocator,
  143. './SubscriptionViewModelBuilder': this.SubscriptionViewModelBuilder,
  144. './LimitationsManager': this.LimitationsManager,
  145. '../../infrastructure/GeoIpLookup': this.GeoIpLookup,
  146. '@overleaf/settings': this.settings,
  147. '../User/UserGetter': this.UserGetter,
  148. './RecurlyWrapper': (this.RecurlyWrapper = {
  149. updateAccountEmailAddress: sinon.stub().yields(),
  150. }),
  151. './RecurlyEventHandler': {
  152. sendRecurlyAnalyticsEvent: sinon.stub().resolves(),
  153. },
  154. './FeaturesUpdater': (this.FeaturesUpdater = {}),
  155. './GroupPlansData': (this.GroupPlansData = {}),
  156. './V1SubscriptionManager': (this.V1SubscriptionManager = {}),
  157. '../Errors/HttpErrorHandler': (this.HttpErrorHandler = {
  158. unprocessableEntity: sinon.stub(),
  159. }),
  160. './Errors': SubscriptionErrors,
  161. '../Analytics/AnalyticsManager': (this.AnalyticsManager = {
  162. recordEventForUser: sinon.stub(),
  163. recordEventForSession: sinon.stub(),
  164. setUserPropertyForUser: sinon.stub(),
  165. }),
  166. '../../infrastructure/Features': this.Features,
  167. },
  168. })
  169. this.res = new MockResponse()
  170. this.req = new MockRequest()
  171. this.req.body = {}
  172. this.req.query = { planCode: '123123' }
  173. this.stubbedCurrencyCode = 'GBP'
  174. })
  175. describe('plansPage', function () {
  176. beforeEach(function () {
  177. this.req.ip = '1234.3123.3131.333 313.133.445.666 653.5345.5345.534'
  178. this.GeoIpLookup.promises.getCurrencyCode.resolves({
  179. currencyCode: this.stubbedCurrencyCode,
  180. })
  181. })
  182. describe('ip override', function () {
  183. beforeEach(function () {
  184. this.req.ip = '1.2.3.4'
  185. this.req.query = { ip: '5.6.7.8' }
  186. this.GeoIpLookup.promises.getCurrencyCode.withArgs('1.2.3.4').resolves({
  187. currencyCode: 'GBP',
  188. })
  189. this.GeoIpLookup.promises.getCurrencyCode.withArgs('5.6.7.8').resolves({
  190. currencyCode: 'USD',
  191. })
  192. })
  193. it('should ignore override for non admin', function (done) {
  194. this.res.render = (page, opts) => {
  195. opts.recommendedCurrency.should.equal('GBP')
  196. done()
  197. }
  198. this.AuthorizationManager.promises.isUserSiteAdmin.resolves(false)
  199. this.SubscriptionController.plansPage(this.req, this.res)
  200. })
  201. it('should accept override for admin', function (done) {
  202. this.res.render = (page, opts) => {
  203. opts.recommendedCurrency.should.equal('USD')
  204. done()
  205. }
  206. this.AuthorizationManager.promises.isUserSiteAdmin.resolves(true)
  207. this.SubscriptionController.plansPage(this.req, this.res)
  208. })
  209. })
  210. describe('groupPlanModal data', function () {
  211. it('should pass local currency if valid', function (done) {
  212. this.res.render = (page, opts) => {
  213. page.should.equal('subscriptions/plans')
  214. opts.groupPlanModalDefaults.currency.should.equal('GBP')
  215. done()
  216. }
  217. this.GeoIpLookup.promises.getCurrencyCode.resolves({
  218. currencyCode: 'GBP',
  219. })
  220. this.SubscriptionController.plansPage(this.req, this.res)
  221. })
  222. it('should fallback to USD when valid', function (done) {
  223. this.res.render = (page, opts) => {
  224. page.should.equal('subscriptions/plans')
  225. opts.groupPlanModalDefaults.currency.should.equal('USD')
  226. done()
  227. }
  228. this.GeoIpLookup.promises.getCurrencyCode.resolves({
  229. currencyCode: 'FOO',
  230. })
  231. this.SubscriptionController.plansPage(this.req, this.res)
  232. })
  233. it('should pass valid options for group plan modal and discard invalid', function (done) {
  234. this.res.render = (page, opts) => {
  235. page.should.equal('subscriptions/plans')
  236. opts.groupPlanModalDefaults.size.should.equal('42')
  237. opts.groupPlanModalDefaults.plan_code.should.equal('collaborator')
  238. opts.groupPlanModalDefaults.currency.should.equal('GBP')
  239. opts.groupPlanModalDefaults.usage.should.equal('foo')
  240. done()
  241. }
  242. this.GeoIpLookup.isValidCurrencyParam.returns(false)
  243. this.req.query = {
  244. number: '42',
  245. currency: 'ABC',
  246. plan: 'does-not-exist',
  247. usage: 'foo',
  248. }
  249. this.SubscriptionController.plansPage(this.req, this.res)
  250. })
  251. })
  252. })
  253. describe('interstitialPaymentPage', function () {
  254. beforeEach(function () {
  255. this.req.ip = '1234.3123.3131.333 313.133.445.666 653.5345.5345.534'
  256. this.GeoIpLookup.promises.getCurrencyCode.resolves({
  257. currencyCode: this.stubbedCurrencyCode,
  258. })
  259. })
  260. describe('with a user without subscription', function () {
  261. it('should render the interstitial payment page', function (done) {
  262. this.res.render = (page, opts) => {
  263. page.should.equal('subscriptions/interstitial-payment')
  264. done()
  265. }
  266. this.SubscriptionController.interstitialPaymentPage(this.req, this.res)
  267. })
  268. })
  269. describe('with a user with subscription', function () {
  270. it('should redirect to the subscription dashboard', function (done) {
  271. this.PlansLocator.findLocalPlanInSettings.returns({})
  272. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(
  273. true
  274. )
  275. this.res.redirect = url => {
  276. url.should.equal('/user/subscription?hasSubscription=true')
  277. done()
  278. }
  279. this.SubscriptionController.interstitialPaymentPage(this.req, this.res)
  280. })
  281. })
  282. })
  283. describe('paymentPage', function () {
  284. beforeEach(function () {
  285. this.req.headers = {}
  286. this.SubscriptionHandler.promises.validateNoSubscriptionInRecurly = sinon
  287. .stub()
  288. .resolves(true)
  289. this.GeoIpLookup.promises.getCurrencyCode.resolves({
  290. currencyCode: this.stubbedCurrencyCode,
  291. })
  292. })
  293. describe('with a user without a subscription', function () {
  294. beforeEach(function () {
  295. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(
  296. false
  297. )
  298. this.PlansLocator.findLocalPlanInSettings.returns({})
  299. })
  300. describe('with a valid plan code', function () {
  301. it('should render the new subscription page', function (done) {
  302. this.res.render = (page, opts) => {
  303. page.should.equal('subscriptions/new-react')
  304. done()
  305. }
  306. this.SubscriptionController.paymentPage(this.req, this.res, done)
  307. })
  308. })
  309. })
  310. describe('with a user with subscription', function () {
  311. it('should redirect to the subscription dashboard', function (done) {
  312. this.PlansLocator.findLocalPlanInSettings.returns({})
  313. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(
  314. true
  315. )
  316. this.res.redirect = url => {
  317. url.should.equal('/user/subscription?hasSubscription=true')
  318. done()
  319. }
  320. this.SubscriptionController.paymentPage(this.req, this.res)
  321. })
  322. })
  323. describe('with an invalid plan code', function () {
  324. it('should return 422 error - Unprocessable Entity', function (done) {
  325. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(
  326. false
  327. )
  328. this.PlansLocator.findLocalPlanInSettings.returns(null)
  329. this.HttpErrorHandler.unprocessableEntity = sinon.spy(
  330. (req, res, message) => {
  331. expect(req).to.exist
  332. expect(res).to.exist
  333. expect(message).to.deep.equal('Plan not found')
  334. done()
  335. }
  336. )
  337. this.SubscriptionController.paymentPage(this.req, this.res)
  338. })
  339. })
  340. describe('which currency to use', function () {
  341. beforeEach(function () {
  342. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(
  343. false
  344. )
  345. this.PlansLocator.findLocalPlanInSettings.returns({})
  346. })
  347. it('should use the set currency from the query string', function (done) {
  348. this.req.query.currency = 'EUR'
  349. this.res.render = (page, opts) => {
  350. opts.currency.should.equal('EUR')
  351. opts.currency.should.not.equal(this.stubbedCurrencyCode)
  352. done()
  353. }
  354. this.SubscriptionController.paymentPage(this.req, this.res)
  355. })
  356. it('should upercase the currency code', function (done) {
  357. this.req.query.currency = 'eur'
  358. this.res.render = (page, opts) => {
  359. opts.currency.should.equal('EUR')
  360. done()
  361. }
  362. this.SubscriptionController.paymentPage(this.req, this.res)
  363. })
  364. it('should use the geo ip currency if non is provided', function (done) {
  365. this.req.query.currency = null
  366. this.res.render = (page, opts) => {
  367. opts.currency.should.equal(this.stubbedCurrencyCode)
  368. done()
  369. }
  370. this.SubscriptionController.paymentPage(this.req, this.res)
  371. })
  372. it('should use the geo ip currency if not valid', function (done) {
  373. this.req.query.currency = 'WAT'
  374. this.GeoIpLookup.isValidCurrencyParam.returns(false)
  375. this.res.render = (page, opts) => {
  376. opts.currency.should.equal(this.stubbedCurrencyCode)
  377. done()
  378. }
  379. this.SubscriptionController.paymentPage(this.req, this.res)
  380. })
  381. })
  382. describe('with a recurly subscription already', function () {
  383. it('should redirect to the subscription dashboard', function (done) {
  384. this.PlansLocator.findLocalPlanInSettings.returns({})
  385. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(
  386. false
  387. )
  388. this.SubscriptionHandler.promises.validateNoSubscriptionInRecurly.resolves(
  389. false
  390. )
  391. this.res.redirect = url => {
  392. url.should.equal('/user/subscription?hasSubscription=true')
  393. done()
  394. }
  395. this.SubscriptionController.paymentPage(this.req, this.res)
  396. })
  397. })
  398. describe('with a user from a restricted country', function () {
  399. beforeEach(function () {
  400. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(
  401. false
  402. )
  403. this.PlansLocator.findLocalPlanInSettings.returns({})
  404. this.GeoIpLookup.promises.getCurrencyCode.resolves({
  405. currencyCode: this.stubbedCurrencyCode,
  406. countryCode: 'KP',
  407. })
  408. })
  409. it('should render the restricted country page', function (done) {
  410. this.res.render = (page, opts) => {
  411. page.should.equal('subscriptions/restricted-country')
  412. done()
  413. }
  414. this.SubscriptionController.paymentPage(this.req, this.res, done)
  415. })
  416. })
  417. })
  418. describe('successfulSubscription', function () {
  419. it('without a personal subscription', function (done) {
  420. this.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  421. {}
  422. )
  423. this.res.redirect = url => {
  424. url.should.equal('/user/subscription/plans')
  425. done()
  426. }
  427. this.SubscriptionController.successfulSubscription(this.req, this.res)
  428. })
  429. it('with a personal subscription', function (done) {
  430. this.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  431. {
  432. personalSubscription: 'foo',
  433. }
  434. )
  435. this.res.render = (url, variables) => {
  436. url.should.equal('subscriptions/successful-subscription-react')
  437. assert.deepEqual(variables, {
  438. title: 'thank_you',
  439. personalSubscription: 'foo',
  440. postCheckoutRedirect: undefined,
  441. })
  442. done()
  443. }
  444. this.SubscriptionController.successfulSubscription(this.req, this.res)
  445. })
  446. it('with an error', function (done) {
  447. this.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  448. undefined
  449. )
  450. this.SubscriptionController.successfulSubscription(
  451. this.req,
  452. this.res,
  453. error => {
  454. assert.isNotNull(error)
  455. done()
  456. }
  457. )
  458. })
  459. })
  460. describe('userSubscriptionPage', function () {
  461. beforeEach(function (done) {
  462. this.SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel.resolves(
  463. {
  464. personalSubscription: (this.personalSubscription = {
  465. 'personal-subscription': 'mock',
  466. }),
  467. memberGroupSubscriptions: (this.memberGroupSubscriptions = {
  468. 'group-subscriptions': 'mock',
  469. }),
  470. }
  471. )
  472. this.SubscriptionViewModelBuilder.buildPlansList.returns(
  473. (this.plans = { plans: 'mock' })
  474. )
  475. this.SubscriptionViewModelBuilder.buildPlansListForSubscriptionDash.returns(
  476. {
  477. plans: this.plans,
  478. planCodesChangingAtTermEnd: [],
  479. }
  480. )
  481. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(false)
  482. this.res.render = (view, data) => {
  483. this.data = data
  484. expect(view).to.equal('subscriptions/dashboard-react')
  485. done()
  486. }
  487. this.SubscriptionController.userSubscriptionPage(this.req, this.res, done)
  488. })
  489. it('should load the personal, groups and v1 subscriptions', function () {
  490. expect(this.data.personalSubscription).to.deep.equal(
  491. this.personalSubscription
  492. )
  493. expect(this.data.memberGroupSubscriptions).to.deep.equal(
  494. this.memberGroupSubscriptions
  495. )
  496. })
  497. it('should load the user', function () {
  498. expect(this.data.user).to.deep.equal(this.user)
  499. })
  500. it('should load the plans', function () {
  501. expect(this.data.plans).to.deep.equal(this.plans)
  502. })
  503. it('should load an empty list of groups with settings available', function () {
  504. expect(this.data.groupSettingsEnabledFor).to.deep.equal([])
  505. })
  506. })
  507. describe('createSubscription', function () {
  508. beforeEach(function (done) {
  509. this.res = {
  510. sendStatus() {
  511. done()
  512. },
  513. }
  514. sinon.spy(this.res, 'sendStatus')
  515. this.subscriptionDetails = {
  516. card: '1234',
  517. cvv: '123',
  518. }
  519. this.recurlyTokenIds = {
  520. billing: '1234',
  521. threeDSecureActionResult: '5678',
  522. }
  523. this.req.body.recurly_token_id = this.recurlyTokenIds.billing
  524. this.req.body.recurly_three_d_secure_action_result_token_id =
  525. this.recurlyTokenIds.threeDSecureActionResult
  526. this.req.body.subscriptionDetails = this.subscriptionDetails
  527. this.LimitationsManager.userHasV1OrV2Subscription.yields(null, false)
  528. this.SubscriptionController.createSubscription(this.req, this.res)
  529. })
  530. it('should send the user and subscriptionId to the handler', function (done) {
  531. this.SubscriptionHandler.promises.createSubscription
  532. .calledWithMatch(
  533. this.user,
  534. this.subscriptionDetails,
  535. this.recurlyTokenIds
  536. )
  537. .should.equal(true)
  538. done()
  539. })
  540. it('should redirect to the subscription page', function (done) {
  541. this.res.sendStatus.calledWith(201).should.equal(true)
  542. done()
  543. })
  544. })
  545. describe('createSubscription with errors', function () {
  546. it('should handle users with subscription', function (done) {
  547. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(true)
  548. this.SubscriptionController.createSubscription(this.req, {
  549. sendStatus: status => {
  550. expect(status).to.equal(409)
  551. this.SubscriptionHandler.promises.createSubscription.called.should.equal(
  552. false
  553. )
  554. done()
  555. },
  556. })
  557. })
  558. it('should handle 3DSecure errors/recurly transaction errors', function (done) {
  559. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(false)
  560. this.SubscriptionHandler.promises.createSubscription.rejects(
  561. new SubscriptionErrors.RecurlyTransactionError({})
  562. )
  563. this.HttpErrorHandler.unprocessableEntity = sinon.spy(
  564. (req, res, message) => {
  565. expect(req).to.exist
  566. expect(res).to.exist
  567. expect(message).to.deep.equal('Unknown transaction error')
  568. done()
  569. }
  570. )
  571. this.SubscriptionController.createSubscription(this.req, this.res)
  572. })
  573. it('should handle validation errors', function (done) {
  574. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(false)
  575. this.SubscriptionHandler.promises.createSubscription.rejects(
  576. new Errors.InvalidError('invalid error test')
  577. )
  578. this.HttpErrorHandler.unprocessableEntity = sinon.spy(
  579. (req, res, message) => {
  580. expect(req).to.exist
  581. expect(res).to.exist
  582. expect(message).to.deep.equal('invalid error test')
  583. done()
  584. }
  585. )
  586. this.SubscriptionController.createSubscription(this.req, this.res)
  587. })
  588. it('should throw errors from createSubscription that are not handled', function (done) {
  589. const genericError = new Error('generic error')
  590. this.LimitationsManager.promises.userHasV1OrV2Subscription.resolves(false)
  591. this.SubscriptionHandler.promises.createSubscription.rejects(genericError)
  592. this.SubscriptionController.createSubscription(
  593. this.req,
  594. this.res,
  595. error => {
  596. expect(error).to.be.instanceof(Error)
  597. expect(error.message).to.equal(genericError.message)
  598. done()
  599. }
  600. )
  601. })
  602. })
  603. describe('updateSubscription via post', function () {
  604. beforeEach(function (done) {
  605. this.res = {
  606. redirect() {
  607. done()
  608. },
  609. }
  610. sinon.spy(this.res, 'redirect')
  611. this.plan_code = '1234'
  612. this.req.body.plan_code = this.plan_code
  613. this.SubscriptionController.updateSubscription(this.req, this.res)
  614. })
  615. it('should send the user and subscriptionId to the handler', function (done) {
  616. this.SubscriptionHandler.updateSubscription
  617. .calledWith(this.user, this.plan_code)
  618. .should.equal(true)
  619. done()
  620. })
  621. it('should redurect to the subscription page', function (done) {
  622. this.res.redirect.calledWith('/user/subscription').should.equal(true)
  623. done()
  624. })
  625. })
  626. describe('updateAccountEmailAddress via put', function () {
  627. it('should send the user and subscriptionId to RecurlyWrapper', function () {
  628. this.res.sendStatus = sinon.spy()
  629. this.SubscriptionController.updateAccountEmailAddress(this.req, this.res)
  630. this.RecurlyWrapper.updateAccountEmailAddress
  631. .calledWith(this.user._id, this.user.email)
  632. .should.equal(true)
  633. })
  634. it('should respond with 200', function () {
  635. this.res.sendStatus = sinon.spy()
  636. this.SubscriptionController.updateAccountEmailAddress(this.req, this.res)
  637. this.res.sendStatus.calledWith(200).should.equal(true)
  638. })
  639. it('should send the error to the next handler when updating recurly account email fails', function (done) {
  640. this.RecurlyWrapper.updateAccountEmailAddress.yields(new Error())
  641. this.next = sinon.spy(error => {
  642. expect(error).instanceOf(Error)
  643. done()
  644. })
  645. this.SubscriptionController.updateAccountEmailAddress(
  646. this.req,
  647. this.res,
  648. this.next
  649. )
  650. })
  651. })
  652. describe('reactivateSubscription', function () {
  653. describe('when the user has permission', function () {
  654. beforeEach(function (done) {
  655. this.res = {
  656. redirect() {
  657. done()
  658. },
  659. }
  660. this.req.assertPermission = sinon.stub()
  661. this.next = sinon.stub().callsFake(error => {
  662. done(error)
  663. })
  664. sinon.spy(this.res, 'redirect')
  665. this.SubscriptionController.reactivateSubscription(
  666. this.req,
  667. this.res,
  668. this.next
  669. )
  670. })
  671. it('should assert the user has permission to reactivate their subscription', function (done) {
  672. this.req.assertPermission
  673. .calledWith('reactivate-subscription')
  674. .should.equal(true)
  675. done()
  676. })
  677. it('should tell the handler to reactivate this user', function (done) {
  678. this.SubscriptionHandler.reactivateSubscription
  679. .calledWith(this.user)
  680. .should.equal(true)
  681. done()
  682. })
  683. it('should redurect to the subscription page', function (done) {
  684. this.res.redirect.calledWith('/user/subscription').should.equal(true)
  685. done()
  686. })
  687. })
  688. describe('when the user does not have permission', function () {
  689. beforeEach(function (done) {
  690. this.res = {
  691. redirect() {
  692. done()
  693. },
  694. }
  695. this.req.assertPermission = sinon.stub().throws()
  696. this.next = sinon.stub().callsFake(() => {
  697. done()
  698. })
  699. sinon.spy(this.res, 'redirect')
  700. this.SubscriptionController.reactivateSubscription(
  701. this.req,
  702. this.res,
  703. this.next
  704. )
  705. })
  706. it('should not reactivate the user', function (done) {
  707. this.req.assertPermission = sinon.stub().throws()
  708. this.SubscriptionHandler.reactivateSubscription.called.should.equal(
  709. false
  710. )
  711. done()
  712. })
  713. it('should call next with an error', function (done) {
  714. this.next.calledWith(sinon.match.instanceOf(Error)).should.equal(true)
  715. done()
  716. })
  717. })
  718. })
  719. describe('cancelSubscription', function () {
  720. beforeEach(function (done) {
  721. this.res = {
  722. redirect() {
  723. done()
  724. },
  725. }
  726. sinon.spy(this.res, 'redirect')
  727. this.SubscriptionController.cancelSubscription(this.req, this.res)
  728. })
  729. it('should tell the handler to cancel this user', function (done) {
  730. this.SubscriptionHandler.cancelSubscription
  731. .calledWith(this.user)
  732. .should.equal(true)
  733. done()
  734. })
  735. it('should redurect to the subscription page', function (done) {
  736. this.res.redirect
  737. .calledWith('/user/subscription/canceled')
  738. .should.equal(true)
  739. done()
  740. })
  741. })
  742. describe('recurly callback', function () {
  743. describe('with a sync subscription request', function () {
  744. beforeEach(function (done) {
  745. this.req = {
  746. body: {
  747. expired_subscription_notification: {
  748. account: {
  749. account_code: this.user._id,
  750. },
  751. subscription: {
  752. uuid: this.activeRecurlySubscription.uuid,
  753. plan: {
  754. plan_code: 'collaborator',
  755. state: 'active',
  756. },
  757. },
  758. },
  759. },
  760. }
  761. this.res = {
  762. sendStatus() {
  763. done()
  764. },
  765. }
  766. sinon.spy(this.res, 'sendStatus')
  767. this.SubscriptionController.recurlyCallback(this.req, this.res)
  768. })
  769. it('should tell the SubscriptionHandler to process the recurly callback', function (done) {
  770. this.SubscriptionHandler.syncSubscription.called.should.equal(true)
  771. done()
  772. })
  773. it('should send a 200', function (done) {
  774. this.res.sendStatus.calledWith(200)
  775. done()
  776. })
  777. })
  778. describe('with a billing info updated request', function () {
  779. beforeEach(function (done) {
  780. this.req = {
  781. body: {
  782. billing_info_updated_notification: {
  783. account: {
  784. account_code: 'mock-account-code',
  785. },
  786. },
  787. },
  788. }
  789. this.res = {
  790. sendStatus() {
  791. done()
  792. },
  793. }
  794. sinon.spy(this.res, 'sendStatus')
  795. this.SubscriptionController.recurlyCallback(this.req, this.res)
  796. })
  797. it('should call attemptPaypalInvoiceCollection', function (done) {
  798. this.SubscriptionHandler.attemptPaypalInvoiceCollection
  799. .calledWith('mock-account-code')
  800. .should.equal(true)
  801. done()
  802. })
  803. it('should send a 200', function (done) {
  804. this.res.sendStatus.calledWith(200)
  805. done()
  806. })
  807. })
  808. describe('with a non-actionable request', function () {
  809. beforeEach(function (done) {
  810. this.user.id = this.activeRecurlySubscription.account.account_code
  811. this.req = {
  812. body: {
  813. renewed_subscription_notification: {
  814. account: {
  815. account_code: this.user._id,
  816. },
  817. subscription: {
  818. uuid: this.activeRecurlySubscription.uuid,
  819. plan: {
  820. plan_code: 'collaborator',
  821. state: 'active',
  822. },
  823. },
  824. },
  825. },
  826. }
  827. this.res = {
  828. sendStatus() {
  829. done()
  830. },
  831. }
  832. sinon.spy(this.res, 'sendStatus')
  833. this.SubscriptionController.recurlyCallback(this.req, this.res)
  834. })
  835. it('should not call the subscriptionshandler', function () {
  836. this.SubscriptionHandler.syncSubscription.called.should.equal(false)
  837. this.SubscriptionHandler.attemptPaypalInvoiceCollection.called.should.equal(
  838. false
  839. )
  840. })
  841. it('should respond with a 200 status', function () {
  842. this.res.sendStatus.calledWith(200)
  843. })
  844. })
  845. })
  846. describe('renderUpgradeToAnnualPlanPage', function () {
  847. it('should redirect to the plans page if the user does not have a subscription', function (done) {
  848. this.LimitationsManager.userHasV2Subscription.callsArgWith(1, null, false)
  849. this.res.redirect = function (url) {
  850. url.should.equal('/user/subscription/plans')
  851. done()
  852. }
  853. this.SubscriptionController.renderUpgradeToAnnualPlanPage(
  854. this.req,
  855. this.res
  856. )
  857. })
  858. it('should pass the plan code to the view - student', function (done) {
  859. this.LimitationsManager.userHasV2Subscription.callsArgWith(
  860. 1,
  861. null,
  862. true,
  863. { planCode: 'Student free trial 14 days' }
  864. )
  865. this.res.render = function (view, opts) {
  866. view.should.equal('subscriptions/upgradeToAnnual')
  867. opts.planName.should.equal('student')
  868. done()
  869. }
  870. this.SubscriptionController.renderUpgradeToAnnualPlanPage(
  871. this.req,
  872. this.res
  873. )
  874. })
  875. it('should pass the plan code to the view - collaborator', function (done) {
  876. this.LimitationsManager.userHasV2Subscription.callsArgWith(
  877. 1,
  878. null,
  879. true,
  880. { planCode: 'free trial for Collaborator free trial 14 days' }
  881. )
  882. this.res.render = function (view, opts) {
  883. opts.planName.should.equal('collaborator')
  884. done()
  885. }
  886. this.SubscriptionController.renderUpgradeToAnnualPlanPage(
  887. this.req,
  888. this.res
  889. )
  890. })
  891. it('should pass annual as the plan name if the user is already on an annual plan', function (done) {
  892. this.LimitationsManager.userHasV2Subscription.callsArgWith(
  893. 1,
  894. null,
  895. true,
  896. { planCode: 'student annual with free trial' }
  897. )
  898. this.res.render = function (view, opts) {
  899. opts.planName.should.equal('annual')
  900. done()
  901. }
  902. this.SubscriptionController.renderUpgradeToAnnualPlanPage(
  903. this.req,
  904. this.res
  905. )
  906. })
  907. })
  908. describe('processUpgradeToAnnualPlan', function () {
  909. beforeEach(function () {})
  910. it('should tell the subscription handler to update the subscription with the annual plan and apply a coupon code', function (done) {
  911. this.req.body = { planName: 'student' }
  912. this.res.sendStatus = () => {
  913. this.SubscriptionHandler.updateSubscription
  914. .calledWith(this.user, 'student-annual', 'STUDENTCODEHERE')
  915. .should.equal(true)
  916. done()
  917. }
  918. this.SubscriptionController.processUpgradeToAnnualPlan(this.req, this.res)
  919. })
  920. it('should get the collaborator coupon code', function (done) {
  921. this.req.body = { planName: 'collaborator' }
  922. this.res.sendStatus = url => {
  923. this.SubscriptionHandler.updateSubscription
  924. .calledWith(this.user, 'collaborator-annual', 'COLLABORATORCODEHERE')
  925. .should.equal(true)
  926. done()
  927. }
  928. this.SubscriptionController.processUpgradeToAnnualPlan(this.req, this.res)
  929. })
  930. })
  931. describe('requireConfirmedPrimaryEmailAddress', function () {
  932. describe('when user does not have confirmed email address', function () {
  933. beforeEach(function () {
  934. this.req.user = { _id: 'testing' }
  935. this.UserGetter.promises.getUser.resolves({
  936. email: 'test@example.com',
  937. emails: [{ email: 'test@example.com' }],
  938. })
  939. })
  940. it('should show unconfirmed primary email page', function (done) {
  941. this.res.render = (page, opts) => {
  942. page.should.equal('subscriptions/unconfirmed-primary-email')
  943. opts.email.should.equal('test@example.com')
  944. done()
  945. }
  946. this.SubscriptionController.requireConfirmedPrimaryEmailAddress(
  947. this.req,
  948. this.res
  949. )
  950. })
  951. })
  952. })
  953. })