SubscriptionController.js 22 KB

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