SubscriptionControllerTests.js 34 KB

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