SubscriptionController.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  1. const SessionManager = require('../Authentication/SessionManager')
  2. const SubscriptionHandler = require('./SubscriptionHandler')
  3. const PlansLocator = require('./PlansLocator')
  4. const SubscriptionViewModelBuilder = require('./SubscriptionViewModelBuilder')
  5. const LimitationsManager = require('./LimitationsManager')
  6. const RecurlyWrapper = require('./RecurlyWrapper')
  7. const Settings = require('@overleaf/settings')
  8. const logger = require('@overleaf/logger')
  9. const GeoIpLookup = require('../../infrastructure/GeoIpLookup')
  10. const FeaturesUpdater = require('./FeaturesUpdater')
  11. const planFeatures = require('./planFeatures')
  12. const plansConfig = require('./plansConfig')
  13. const interstitialPaymentConfig = require('./interstitialPaymentConfig')
  14. const GroupPlansData = require('./GroupPlansData')
  15. const V1SubscriptionManager = require('./V1SubscriptionManager')
  16. const Errors = require('../Errors/Errors')
  17. const HttpErrorHandler = require('../Errors/HttpErrorHandler')
  18. const SubscriptionErrors = require('./Errors')
  19. const AnalyticsManager = require('../Analytics/AnalyticsManager')
  20. const RecurlyEventHandler = require('./RecurlyEventHandler')
  21. const { expressify } = require('../../util/promises')
  22. const OError = require('@overleaf/o-error')
  23. const SplitTestHandler = require('../SplitTests/SplitTestHandler')
  24. const SubscriptionHelper = require('./SubscriptionHelper')
  25. const ManagedUsersManager = require('../../../../modules/managed-users/app/src/ManagedUsersManager')
  26. const groupPlanModalOptions = Settings.groupPlanModalOptions
  27. const validGroupPlanModalOptions = {
  28. plan_code: groupPlanModalOptions.plan_codes.map(item => item.code),
  29. currency: groupPlanModalOptions.currencies.map(item => item.code),
  30. size: groupPlanModalOptions.sizes,
  31. usage: groupPlanModalOptions.usages.map(item => item.code),
  32. }
  33. async function plansPage(req, res) {
  34. const plans = SubscriptionViewModelBuilder.buildPlansList()
  35. let currency = null
  36. const queryCurrency = req.query.currency?.toUpperCase()
  37. if (GeoIpLookup.isValidCurrencyParam(queryCurrency)) {
  38. currency = queryCurrency
  39. }
  40. const {
  41. recommendedCurrency,
  42. countryCode,
  43. geoPricingINRTestVariant,
  44. geoPricingLATAMTestVariant,
  45. } = await _getRecommendedCurrency(req, res)
  46. if (recommendedCurrency && currency == null) {
  47. currency = recommendedCurrency
  48. }
  49. function getDefault(param, category, defaultValue) {
  50. const v = req.query && req.query[param]
  51. if (v && validGroupPlanModalOptions[category].includes(v)) {
  52. return v
  53. }
  54. return defaultValue
  55. }
  56. const currentView = 'annual'
  57. let defaultGroupPlanModalCurrency = 'USD'
  58. if (validGroupPlanModalOptions.currency.includes(currency)) {
  59. defaultGroupPlanModalCurrency = currency
  60. }
  61. const groupPlanModalDefaults = {
  62. plan_code: getDefault('plan', 'plan_code', 'collaborator'),
  63. size: getDefault('number', 'size', '2'),
  64. currency: getDefault('currency', 'currency', defaultGroupPlanModalCurrency),
  65. usage: getDefault('usage', 'usage', 'enterprise'),
  66. }
  67. let showInrGeoBanner, inrGeoBannerSplitTestName
  68. let inrGeoBannerVariant = 'default'
  69. if (countryCode === 'IN') {
  70. inrGeoBannerSplitTestName =
  71. geoPricingINRTestVariant === 'inr'
  72. ? 'geo-banners-inr-2'
  73. : 'geo-banners-inr-1'
  74. try {
  75. const geoBannerAssignment = await SplitTestHandler.promises.getAssignment(
  76. req,
  77. res,
  78. inrGeoBannerSplitTestName
  79. )
  80. inrGeoBannerVariant = geoBannerAssignment.variant
  81. if (inrGeoBannerVariant !== 'default') {
  82. showInrGeoBanner = true
  83. }
  84. } catch (error) {
  85. logger.error(
  86. { err: error },
  87. `Failed to get INR geo banner lookup or assignment (${inrGeoBannerSplitTestName})`
  88. )
  89. }
  90. }
  91. // annual plans with the free trial option split test - nudge variant
  92. let annualTrialsAssignment = { variant: 'default' }
  93. try {
  94. annualTrialsAssignment = await SplitTestHandler.promises.getAssignment(
  95. req,
  96. res,
  97. 'annual-trials'
  98. )
  99. } catch (error) {
  100. logger.error(
  101. { err: error },
  102. 'failed to get "annualTrialsAssignment" split test assignment'
  103. )
  104. }
  105. const plansPageViewSegmentation = {
  106. currency: recommendedCurrency,
  107. countryCode,
  108. 'geo-pricing-inr-group': geoPricingINRTestVariant,
  109. 'geo-pricing-inr-page': currency === 'INR' ? 'inr' : 'default',
  110. 'geo-pricing-latam-group': geoPricingLATAMTestVariant,
  111. 'geo-pricing-latam-page': ['BRL', 'MXN', 'COP', 'CLP', 'PEN'].includes(
  112. currency
  113. )
  114. ? 'latam'
  115. : 'default',
  116. 'annual-trials': annualTrialsAssignment?.variant,
  117. }
  118. if (inrGeoBannerSplitTestName) {
  119. plansPageViewSegmentation[inrGeoBannerSplitTestName] = inrGeoBannerVariant
  120. }
  121. AnalyticsManager.recordEventForSession(
  122. req.session,
  123. 'plans-page-view',
  124. plansPageViewSegmentation
  125. )
  126. res.render('subscriptions/plans', {
  127. title: 'plans_and_pricing',
  128. currentView,
  129. plans,
  130. itm_content: req.query?.itm_content,
  131. itm_referrer: req.query?.itm_referrer,
  132. itm_campaign: 'plans',
  133. recommendedCurrency: currency,
  134. planFeatures,
  135. plansConfig,
  136. groupPlans: GroupPlansData,
  137. groupPlanModalOptions,
  138. groupPlanModalDefaults,
  139. initialLocalizedGroupPrice:
  140. SubscriptionHelper.generateInitialLocalizedGroupPrice(currency),
  141. showInrGeoBanner,
  142. annualTrialsAssignment: annualTrialsAssignment?.variant,
  143. })
  144. }
  145. /**
  146. * @param {import('express').Request} req
  147. * @param {import('express').Response} res
  148. * @returns {Promise<void>}
  149. */
  150. async function paymentPage(req, res) {
  151. const user = SessionManager.getSessionUser(req.session)
  152. const plan = PlansLocator.findLocalPlanInSettings(req.query.planCode)
  153. if (!plan) {
  154. return HttpErrorHandler.unprocessableEntity(req, res, 'Plan not found')
  155. }
  156. const hasSubscription =
  157. await LimitationsManager.promises.userHasV1OrV2Subscription(user)
  158. if (hasSubscription) {
  159. res.redirect('/user/subscription?hasSubscription=true')
  160. } else {
  161. // LimitationsManager.userHasV2Subscription only checks Mongo. Double check with
  162. // Recurly as well at this point (we don't do this most places for speed).
  163. const valid =
  164. await SubscriptionHandler.promises.validateNoSubscriptionInRecurly(
  165. user._id
  166. )
  167. if (!valid) {
  168. res.redirect('/user/subscription?hasSubscription=true')
  169. } else {
  170. let currency = null
  171. if (req.query.currency) {
  172. const queryCurrency = req.query.currency.toUpperCase()
  173. if (GeoIpLookup.isValidCurrencyParam(queryCurrency)) {
  174. currency = queryCurrency
  175. }
  176. }
  177. const { recommendedCurrency, countryCode } =
  178. await _getRecommendedCurrency(req, res)
  179. if (recommendedCurrency && currency == null) {
  180. currency = recommendedCurrency
  181. }
  182. // Block web sales to restricted countries
  183. if (['CU', 'IR', 'KP', 'RU', 'SY', 'VE'].includes(countryCode)) {
  184. return res.render('subscriptions/restricted-country', {
  185. title: 'restricted',
  186. })
  187. }
  188. res.render('subscriptions/new-react', {
  189. title: 'subscribe',
  190. currency,
  191. countryCode,
  192. plan,
  193. planCode: req.query.planCode,
  194. couponCode: req.query.cc,
  195. showCouponField: !!req.query.scf,
  196. itm_campaign: req.query.itm_campaign,
  197. itm_content: req.query.itm_content,
  198. itm_referrer: req.query.itm_referrer,
  199. })
  200. }
  201. }
  202. }
  203. function formatGroupPlansDataForDash() {
  204. return {
  205. plans: [...groupPlanModalOptions.plan_codes],
  206. sizes: [...groupPlanModalOptions.sizes],
  207. usages: [...groupPlanModalOptions.usages],
  208. priceByUsageTypeAndSize: JSON.parse(JSON.stringify(GroupPlansData)),
  209. }
  210. }
  211. /**
  212. * @param {import('express').Request} req
  213. * @param {import('express').Response} res
  214. * @returns {Promise<void>}
  215. */
  216. async function userSubscriptionPage(req, res) {
  217. const user = SessionManager.getSessionUser(req.session)
  218. const results =
  219. await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
  220. user
  221. )
  222. const {
  223. personalSubscription,
  224. memberGroupSubscriptions,
  225. managedGroupSubscriptions,
  226. currentInstitutionsWithLicence,
  227. managedInstitutions,
  228. managedPublishers,
  229. } = results
  230. const hasSubscription =
  231. await LimitationsManager.promises.userHasV1OrV2Subscription(user)
  232. const fromPlansPage = req.query.hasSubscription
  233. const plansData =
  234. SubscriptionViewModelBuilder.buildPlansListForSubscriptionDash(
  235. personalSubscription?.plan
  236. )
  237. AnalyticsManager.recordEventForSession(req.session, 'subscription-page-view')
  238. const cancelButtonAssignment = await SplitTestHandler.promises.getAssignment(
  239. req,
  240. res,
  241. 'subscription-cancel-button'
  242. )
  243. const cancelButtonNewCopy = cancelButtonAssignment?.variant === 'new-copy'
  244. const groupPlansDataForDash = formatGroupPlansDataForDash()
  245. // display the Group Settings button only to admins of group subscriptions with the Managed Users feature available
  246. const groupSettingsEnabledFor = (managedGroupSubscriptions || [])
  247. .filter(
  248. subscription =>
  249. ManagedUsersManager.hasManagedUsersFeature(subscription) &&
  250. (subscription.admin_id._id || subscription.admin_id).toString() ===
  251. user._id.toString()
  252. )
  253. .map(subscription => subscription._id.toString())
  254. const data = {
  255. title: 'your_subscription',
  256. plans: plansData?.plans,
  257. planCodesChangingAtTermEnd: plansData?.planCodesChangingAtTermEnd,
  258. user,
  259. hasSubscription,
  260. fromPlansPage,
  261. personalSubscription,
  262. memberGroupSubscriptions,
  263. managedGroupSubscriptions,
  264. managedInstitutions,
  265. managedPublishers,
  266. currentInstitutionsWithLicence,
  267. cancelButtonNewCopy,
  268. groupPlans: groupPlansDataForDash,
  269. groupSettingsEnabledFor,
  270. isManagedAccount: !!req.managedBy,
  271. userRestrictions: Array.from(req.userRestrictions || []),
  272. }
  273. res.render('subscriptions/dashboard-react', data)
  274. }
  275. async function interstitialPaymentPage(req, res) {
  276. const user = SessionManager.getSessionUser(req.session)
  277. const {
  278. recommendedCurrency,
  279. countryCode,
  280. geoPricingINRTestVariant,
  281. geoPricingLATAMTestVariant,
  282. } = await _getRecommendedCurrency(req, res)
  283. const hasSubscription =
  284. await LimitationsManager.promises.userHasV1OrV2Subscription(user)
  285. const showSkipLink = req.query?.skipLink === 'true'
  286. if (hasSubscription) {
  287. res.redirect('/user/subscription?hasSubscription=true')
  288. } else {
  289. let showInrGeoBanner, inrGeoBannerSplitTestName
  290. let inrGeoBannerVariant = 'default'
  291. if (countryCode === 'IN') {
  292. inrGeoBannerSplitTestName =
  293. geoPricingINRTestVariant === 'inr'
  294. ? 'geo-banners-inr-2'
  295. : 'geo-banners-inr-1'
  296. try {
  297. const geoBannerAssignment =
  298. await SplitTestHandler.promises.getAssignment(
  299. req,
  300. res,
  301. inrGeoBannerSplitTestName
  302. )
  303. inrGeoBannerVariant = geoBannerAssignment.variant
  304. if (inrGeoBannerVariant !== 'default') {
  305. showInrGeoBanner = true
  306. }
  307. } catch (error) {
  308. logger.error(
  309. { err: error },
  310. `Failed to get INR geo banner lookup or assignment (${inrGeoBannerSplitTestName})`
  311. )
  312. }
  313. }
  314. // annual plans with the free trial option split test - nudge variant
  315. let annualTrialsAssignment = { variant: 'default' }
  316. try {
  317. annualTrialsAssignment = await SplitTestHandler.promises.getAssignment(
  318. req,
  319. res,
  320. 'annual-trials'
  321. )
  322. } catch (error) {
  323. logger.error(
  324. { err: error },
  325. 'failed to get "annualTrialsAssignment" split test assignment'
  326. )
  327. }
  328. const paywallPlansPageViewSegmentation = {
  329. currency: recommendedCurrency,
  330. countryCode,
  331. 'geo-pricing-inr-group': geoPricingINRTestVariant,
  332. 'geo-pricing-inr-page': recommendedCurrency === 'INR' ? 'inr' : 'default',
  333. 'geo-pricing-latam-group': geoPricingLATAMTestVariant,
  334. 'geo-pricing-latam-page': ['BRL', 'MXN', 'COP', 'CLP', 'PEN'].includes(
  335. recommendedCurrency
  336. )
  337. ? 'latam'
  338. : 'default',
  339. 'annual-trials': annualTrialsAssignment?.variant,
  340. }
  341. if (inrGeoBannerSplitTestName) {
  342. paywallPlansPageViewSegmentation[inrGeoBannerSplitTestName] =
  343. inrGeoBannerVariant
  344. }
  345. AnalyticsManager.recordEventForSession(
  346. req.session,
  347. 'paywall-plans-page-view',
  348. paywallPlansPageViewSegmentation
  349. )
  350. res.render(
  351. annualTrialsAssignment?.variant == 'nudge'
  352. ? 'subscriptions/interstitial-payment_nudge_annual'
  353. : annualTrialsAssignment?.variant == 'no-nudge'
  354. ? 'subscriptions/interstitial-payment_no_nudge_monthly'
  355. : 'subscriptions/interstitial-payment',
  356. {
  357. title: 'subscribe',
  358. itm_content: req.query?.itm_content,
  359. itm_campaign: req.query?.itm_campaign,
  360. itm_referrer: req.query?.itm_referrer,
  361. recommendedCurrency,
  362. interstitialPaymentConfig,
  363. showSkipLink,
  364. showInrGeoBanner,
  365. }
  366. )
  367. }
  368. }
  369. async function createSubscription(req, res) {
  370. const user = SessionManager.getSessionUser(req.session)
  371. const recurlyTokenIds = {
  372. billing: req.body.recurly_token_id,
  373. threeDSecureActionResult:
  374. req.body.recurly_three_d_secure_action_result_token_id,
  375. }
  376. const { subscriptionDetails } = req.body
  377. const hasSubscription =
  378. await LimitationsManager.promises.userHasV1OrV2Subscription(user)
  379. if (hasSubscription) {
  380. logger.warn({ userId: user._id }, 'user already has subscription')
  381. return res.sendStatus(409) // conflict
  382. }
  383. try {
  384. await SubscriptionHandler.promises.createSubscription(
  385. user,
  386. subscriptionDetails,
  387. recurlyTokenIds
  388. )
  389. res.sendStatus(201)
  390. } catch (err) {
  391. if (
  392. err instanceof SubscriptionErrors.RecurlyTransactionError ||
  393. err instanceof Errors.InvalidError
  394. ) {
  395. logger.error({ err }, 'recurly transaction error, potential 422')
  396. HttpErrorHandler.unprocessableEntity(
  397. req,
  398. res,
  399. err.message,
  400. OError.getFullInfo(err).public
  401. )
  402. } else {
  403. logger.warn(
  404. { err, userId: user._id },
  405. 'something went wrong creating subscription'
  406. )
  407. throw err
  408. }
  409. }
  410. }
  411. /**
  412. * @param {import('express').Request} req
  413. * @param {import('express').Response} res
  414. * @returns {Promise<void>}
  415. */
  416. async function successfulSubscription(req, res) {
  417. const user = SessionManager.getSessionUser(req.session)
  418. const { personalSubscription } =
  419. await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
  420. user
  421. )
  422. const postCheckoutRedirect = req.session?.postCheckoutRedirect
  423. if (!personalSubscription) {
  424. res.redirect('/user/subscription/plans')
  425. } else {
  426. res.render('subscriptions/successful-subscription-react', {
  427. title: 'thank_you',
  428. personalSubscription,
  429. postCheckoutRedirect,
  430. })
  431. }
  432. }
  433. function cancelSubscription(req, res, next) {
  434. const user = SessionManager.getSessionUser(req.session)
  435. logger.debug({ userId: user._id }, 'canceling subscription')
  436. SubscriptionHandler.cancelSubscription(user, function (err) {
  437. if (err) {
  438. OError.tag(err, 'something went wrong canceling subscription', {
  439. user_id: user._id,
  440. })
  441. return next(err)
  442. }
  443. // Note: this redirect isn't used in the main flow as the redirection is
  444. // handled by Angular
  445. res.redirect('/user/subscription/canceled')
  446. })
  447. }
  448. /**
  449. * @param {import('express').Request} req
  450. * @param {import('express').Response} res
  451. * @param {import('express').NextFunction} next
  452. * @returns {Promise<void>}
  453. */
  454. function canceledSubscription(req, res, next) {
  455. return res.render('subscriptions/canceled-subscription-react', {
  456. title: 'subscription_canceled',
  457. })
  458. }
  459. function cancelV1Subscription(req, res, next) {
  460. const userId = SessionManager.getLoggedInUserId(req.session)
  461. logger.debug({ userId }, 'canceling v1 subscription')
  462. V1SubscriptionManager.cancelV1Subscription(userId, function (err) {
  463. if (err) {
  464. OError.tag(err, 'something went wrong canceling v1 subscription', {
  465. userId,
  466. })
  467. return next(err)
  468. }
  469. res.redirect('/user/subscription')
  470. })
  471. }
  472. function updateSubscription(req, res, next) {
  473. const origin = req && req.query ? req.query.origin : null
  474. const user = SessionManager.getSessionUser(req.session)
  475. const planCode = req.body.plan_code
  476. if (planCode == null) {
  477. const err = new Error('plan_code is not defined')
  478. logger.warn(
  479. { userId: user._id, err, planCode, origin, body: req.body },
  480. '[Subscription] error in updateSubscription form'
  481. )
  482. return next(err)
  483. }
  484. logger.debug({ planCode, userId: user._id }, 'updating subscription')
  485. SubscriptionHandler.updateSubscription(user, planCode, null, function (err) {
  486. if (err) {
  487. OError.tag(err, 'something went wrong updating subscription', {
  488. user_id: user._id,
  489. })
  490. return next(err)
  491. }
  492. res.redirect('/user/subscription')
  493. })
  494. }
  495. function cancelPendingSubscriptionChange(req, res, next) {
  496. const user = SessionManager.getSessionUser(req.session)
  497. logger.debug({ userId: user._id }, 'canceling pending subscription change')
  498. SubscriptionHandler.cancelPendingSubscriptionChange(user, function (err) {
  499. if (err) {
  500. OError.tag(
  501. err,
  502. 'something went wrong canceling pending subscription change',
  503. {
  504. user_id: user._id,
  505. }
  506. )
  507. return next(err)
  508. }
  509. res.redirect('/user/subscription')
  510. })
  511. }
  512. function updateAccountEmailAddress(req, res, next) {
  513. const user = SessionManager.getSessionUser(req.session)
  514. RecurlyWrapper.updateAccountEmailAddress(
  515. user._id,
  516. user.email,
  517. function (error) {
  518. if (error) {
  519. return next(error)
  520. }
  521. res.sendStatus(200)
  522. }
  523. )
  524. }
  525. function reactivateSubscription(req, res, next) {
  526. const user = SessionManager.getSessionUser(req.session)
  527. logger.debug({ userId: user._id }, 'reactivating subscription')
  528. try {
  529. if (req.isManagedGroupAdmin) {
  530. // allow admins to reactivate subscriptions
  531. } else {
  532. // otherwise require the user to have the reactivate-subscription permission
  533. req.assertPermission('reactivate-subscription')
  534. }
  535. } catch (error) {
  536. return next(error)
  537. }
  538. SubscriptionHandler.reactivateSubscription(user, function (err) {
  539. if (err) {
  540. OError.tag(err, 'something went wrong reactivating subscription', {
  541. user_id: user._id,
  542. })
  543. return next(err)
  544. }
  545. res.redirect('/user/subscription')
  546. })
  547. }
  548. function recurlyCallback(req, res, next) {
  549. logger.debug({ data: req.body }, 'received recurly callback')
  550. const event = Object.keys(req.body)[0]
  551. const eventData = req.body[event]
  552. RecurlyEventHandler.sendRecurlyAnalyticsEvent(event, eventData).catch(error =>
  553. logger.error(
  554. { err: error },
  555. 'Failed to process analytics event on Recurly webhook'
  556. )
  557. )
  558. if (
  559. [
  560. 'new_subscription_notification',
  561. 'updated_subscription_notification',
  562. 'expired_subscription_notification',
  563. ].includes(event)
  564. ) {
  565. const recurlySubscription = eventData.subscription
  566. SubscriptionHandler.syncSubscription(
  567. recurlySubscription,
  568. { ip: req.ip },
  569. function (err) {
  570. if (err) {
  571. return next(err)
  572. }
  573. res.sendStatus(200)
  574. }
  575. )
  576. } else if (event === 'billing_info_updated_notification') {
  577. const recurlyAccountCode = eventData.account.account_code
  578. SubscriptionHandler.attemptPaypalInvoiceCollection(
  579. recurlyAccountCode,
  580. function (err) {
  581. if (err) {
  582. return next(err)
  583. }
  584. res.sendStatus(200)
  585. }
  586. )
  587. } else {
  588. res.sendStatus(200)
  589. }
  590. }
  591. function renderUpgradeToAnnualPlanPage(req, res, next) {
  592. const user = SessionManager.getSessionUser(req.session)
  593. LimitationsManager.userHasV2Subscription(
  594. user,
  595. function (err, hasSubscription, subscription) {
  596. let planName
  597. if (err) {
  598. return next(err)
  599. }
  600. const planCode = subscription
  601. ? subscription.planCode.toLowerCase()
  602. : undefined
  603. if ((planCode ? planCode.indexOf('annual') : undefined) !== -1) {
  604. planName = 'annual'
  605. } else if ((planCode ? planCode.indexOf('student') : undefined) !== -1) {
  606. planName = 'student'
  607. } else if (
  608. (planCode ? planCode.indexOf('collaborator') : undefined) !== -1
  609. ) {
  610. planName = 'collaborator'
  611. }
  612. if (hasSubscription) {
  613. res.render('subscriptions/upgradeToAnnual', {
  614. title: 'Upgrade to annual',
  615. planName,
  616. })
  617. } else {
  618. res.redirect('/user/subscription/plans')
  619. }
  620. }
  621. )
  622. }
  623. function processUpgradeToAnnualPlan(req, res, next) {
  624. const user = SessionManager.getSessionUser(req.session)
  625. const { planName } = req.body
  626. const couponCode = Settings.coupon_codes.upgradeToAnnualPromo[planName]
  627. const annualPlanName = `${planName}-annual`
  628. logger.debug(
  629. { userId: user._id, planName: annualPlanName },
  630. 'user is upgrading to annual billing with discount'
  631. )
  632. return SubscriptionHandler.updateSubscription(
  633. user,
  634. annualPlanName,
  635. couponCode,
  636. function (err) {
  637. if (err) {
  638. OError.tag(err, 'error updating subscription', {
  639. user_id: user._id,
  640. })
  641. return next(err)
  642. }
  643. res.sendStatus(200)
  644. }
  645. )
  646. }
  647. async function extendTrial(req, res) {
  648. const user = SessionManager.getSessionUser(req.session)
  649. const { subscription } =
  650. await LimitationsManager.promises.userHasV2Subscription(user)
  651. try {
  652. await SubscriptionHandler.promises.extendTrial(subscription, 14)
  653. AnalyticsManager.recordEventForSession(
  654. req.session,
  655. 'subscription-trial-extended'
  656. )
  657. } catch (error) {
  658. return res.sendStatus(500)
  659. }
  660. res.sendStatus(200)
  661. }
  662. function recurlyNotificationParser(req, res, next) {
  663. let xml = ''
  664. req.on('data', chunk => (xml += chunk))
  665. req.on('end', () =>
  666. RecurlyWrapper._parseXml(xml, function (error, body) {
  667. if (error) {
  668. return next(error)
  669. }
  670. req.body = body
  671. next()
  672. })
  673. )
  674. }
  675. async function refreshUserFeatures(req, res) {
  676. const { user_id: userId } = req.params
  677. await FeaturesUpdater.promises.refreshFeatures(userId, 'acceptance-test')
  678. res.sendStatus(200)
  679. }
  680. async function redirectToHostedPage(req, res) {
  681. const userId = SessionManager.getLoggedInUserId(req.session)
  682. const { pageType } = req.params
  683. const url =
  684. await SubscriptionViewModelBuilder.promises.getRedirectToHostedPage(
  685. userId,
  686. pageType
  687. )
  688. logger.warn({ userId, pageType }, 'redirecting to recurly hosted page')
  689. res.redirect(url)
  690. }
  691. async function _getRecommendedCurrency(req, res) {
  692. const currencyLookup = await GeoIpLookup.promises.getCurrencyCode(
  693. req.query?.ip || req.ip
  694. )
  695. const countryCode = currencyLookup.countryCode
  696. let assignmentINR, assignmentLATAM
  697. let recommendedCurrency = currencyLookup.currencyCode
  698. // for #12703
  699. try {
  700. // Split test is kept active, but all users geolocated in India can
  701. // now use the INR currency (See #13507)
  702. assignmentINR = await SplitTestHandler.promises.getAssignment(
  703. req,
  704. res,
  705. 'geo-pricing-inr'
  706. )
  707. } catch (error) {
  708. logger.error(
  709. { err: error },
  710. 'Failed to get assignment for geo-pricing-inr test'
  711. )
  712. }
  713. // for #13559
  714. try {
  715. assignmentLATAM = await SplitTestHandler.promises.getAssignment(
  716. req,
  717. res,
  718. 'geo-pricing-latam'
  719. )
  720. } catch (error) {
  721. logger.error(
  722. { err: error },
  723. 'Failed to get assignment for geo-pricing-latam test'
  724. )
  725. }
  726. if (
  727. ['BRL', 'MXN', 'COP', 'CLP', 'PEN'].includes(recommendedCurrency) &&
  728. assignmentLATAM?.variant !== 'latam'
  729. ) {
  730. recommendedCurrency = GeoIpLookup.DEFAULT_CURRENCY_CODE
  731. }
  732. return {
  733. recommendedCurrency,
  734. countryCode,
  735. geoPricingINRTestVariant: assignmentINR?.variant,
  736. geoPricingLATAMTestVariant: assignmentLATAM?.variant,
  737. }
  738. }
  739. module.exports = {
  740. plansPage: expressify(plansPage),
  741. paymentPage: expressify(paymentPage),
  742. userSubscriptionPage: expressify(userSubscriptionPage),
  743. interstitialPaymentPage: expressify(interstitialPaymentPage),
  744. createSubscription: expressify(createSubscription),
  745. successfulSubscription: expressify(successfulSubscription),
  746. cancelSubscription,
  747. canceledSubscription,
  748. cancelV1Subscription,
  749. updateSubscription,
  750. cancelPendingSubscriptionChange,
  751. updateAccountEmailAddress,
  752. reactivateSubscription,
  753. recurlyCallback,
  754. renderUpgradeToAnnualPlanPage,
  755. processUpgradeToAnnualPlan,
  756. extendTrial: expressify(extendTrial),
  757. recurlyNotificationParser,
  758. refreshUserFeatures: expressify(refreshUserFeatures),
  759. redirectToHostedPage: expressify(redirectToHostedPage),
  760. }