SubscriptionController.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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 { formatCurrencyLocalized } = require('../../util/currency')
  25. const SubscriptionFormatters = require('./SubscriptionFormatters')
  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 language = req.i18n.language || 'en'
  35. const plans = SubscriptionViewModelBuilder.buildPlansList()
  36. let currency = null
  37. const queryCurrency = req.query.currency?.toUpperCase()
  38. if (GeoIpLookup.isValidCurrencyParam(queryCurrency)) {
  39. currency = queryCurrency
  40. }
  41. const { recommendedCurrency, countryCode, geoPricingLATAMTestVariant } =
  42. await _getRecommendedCurrency(req, res)
  43. const latamCountryBannerDetails = await getLatamCountryBannerDetails(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. const plansPageViewSegmentation = {
  66. currency: recommendedCurrency,
  67. countryCode,
  68. 'geo-pricing-latam-v2': geoPricingLATAMTestVariant,
  69. }
  70. AnalyticsManager.recordEventForSession(
  71. req.session,
  72. 'plans-page-view',
  73. plansPageViewSegmentation
  74. )
  75. const showLATAMBanner =
  76. geoPricingLATAMTestVariant === 'latam' &&
  77. ['MX', 'CO', 'CL', 'PE'].includes(countryCode)
  78. const localCcyAssignment = await SplitTestHandler.promises.getAssignment(
  79. req,
  80. res,
  81. 'local-ccy-format'
  82. )
  83. const formatCurrency =
  84. localCcyAssignment.variant === 'enabled'
  85. ? formatCurrencyLocalized
  86. : SubscriptionHelper.formatCurrencyDefault
  87. res.render('subscriptions/plans', {
  88. title: 'plans_and_pricing',
  89. currentView,
  90. plans,
  91. itm_content: req.query?.itm_content,
  92. itm_referrer: req.query?.itm_referrer,
  93. itm_campaign: 'plans',
  94. language,
  95. formatCurrency,
  96. recommendedCurrency: currency,
  97. planFeatures,
  98. plansConfig,
  99. groupPlans: GroupPlansData,
  100. groupPlanModalOptions,
  101. groupPlanModalDefaults,
  102. initialLocalizedGroupPrice:
  103. SubscriptionHelper.generateInitialLocalizedGroupPrice(
  104. currency ?? 'USD',
  105. language,
  106. formatCurrency
  107. ),
  108. showInrGeoBanner: countryCode === 'IN',
  109. showBrlGeoBanner: countryCode === 'BR',
  110. showLATAMBanner,
  111. latamCountryBannerDetails,
  112. })
  113. }
  114. function formatGroupPlansDataForDash() {
  115. return {
  116. plans: [...groupPlanModalOptions.plan_codes],
  117. sizes: [...groupPlanModalOptions.sizes],
  118. usages: [...groupPlanModalOptions.usages],
  119. priceByUsageTypeAndSize: JSON.parse(JSON.stringify(GroupPlansData)),
  120. }
  121. }
  122. /**
  123. * @param {import('express').Request} req
  124. * @param {import('express').Response} res
  125. * @returns {Promise<void>}
  126. */
  127. async function userSubscriptionPage(req, res) {
  128. const user = SessionManager.getSessionUser(req.session)
  129. const localCcyAssignment = await SplitTestHandler.promises.getAssignment(
  130. req,
  131. res,
  132. 'local-ccy-format'
  133. )
  134. const results =
  135. await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
  136. user,
  137. req.i18n.language,
  138. localCcyAssignment.variant === 'enabled'
  139. ? SubscriptionFormatters.formatPriceLocalized
  140. : SubscriptionFormatters.formatPriceDefault
  141. )
  142. const {
  143. personalSubscription,
  144. memberGroupSubscriptions,
  145. managedGroupSubscriptions,
  146. currentInstitutionsWithLicence,
  147. managedInstitutions,
  148. managedPublishers,
  149. } = results
  150. const hasSubscription =
  151. await LimitationsManager.promises.userHasV1OrV2Subscription(user)
  152. const fromPlansPage = req.query.hasSubscription
  153. const plansData =
  154. SubscriptionViewModelBuilder.buildPlansListForSubscriptionDash(
  155. personalSubscription?.plan
  156. )
  157. AnalyticsManager.recordEventForSession(req.session, 'subscription-page-view')
  158. const groupPlansDataForDash = formatGroupPlansDataForDash()
  159. // display the Group Settings button only to admins of group subscriptions with either/or the Managed Users or Group SSO feature available
  160. let groupSettingsEnabledFor
  161. try {
  162. const managedGroups = await async.filter(
  163. managedGroupSubscriptions || [],
  164. async subscription => {
  165. const managedUsersResults = await Modules.promises.hooks.fire(
  166. 'hasManagedUsersFeature',
  167. subscription
  168. )
  169. const groupSSOResults = await Modules.promises.hooks.fire(
  170. 'hasGroupSSOFeature',
  171. subscription
  172. )
  173. const isGroupAdmin =
  174. (subscription.admin_id._id || subscription.admin_id).toString() ===
  175. user._id.toString()
  176. return (
  177. (managedUsersResults?.[0] === true ||
  178. groupSSOResults?.[0] === true) &&
  179. isGroupAdmin
  180. )
  181. }
  182. )
  183. groupSettingsEnabledFor = managedGroups.map(subscription =>
  184. subscription._id.toString()
  185. )
  186. } catch (error) {
  187. logger.error(
  188. { err: error },
  189. 'Failed to list groups with group settings enabled'
  190. )
  191. }
  192. const data = {
  193. title: 'your_subscription',
  194. plans: plansData?.plans,
  195. planCodesChangingAtTermEnd: plansData?.planCodesChangingAtTermEnd,
  196. user,
  197. hasSubscription,
  198. fromPlansPage,
  199. personalSubscription,
  200. memberGroupSubscriptions,
  201. managedGroupSubscriptions,
  202. managedInstitutions,
  203. managedPublishers,
  204. currentInstitutionsWithLicence,
  205. groupPlans: groupPlansDataForDash,
  206. groupSettingsEnabledFor,
  207. isManagedAccount: !!req.managedBy,
  208. userRestrictions: Array.from(req.userRestrictions || []),
  209. }
  210. res.render('subscriptions/dashboard-react', data)
  211. }
  212. async function interstitialPaymentPage(req, res) {
  213. const user = SessionManager.getSessionUser(req.session)
  214. const { recommendedCurrency, countryCode, geoPricingLATAMTestVariant } =
  215. await _getRecommendedCurrency(req, res)
  216. const latamCountryBannerDetails = await getLatamCountryBannerDetails(req, res)
  217. const hasSubscription =
  218. await LimitationsManager.promises.userHasV1OrV2Subscription(user)
  219. const showSkipLink = req.query?.skipLink === 'true'
  220. if (hasSubscription) {
  221. res.redirect('/user/subscription?hasSubscription=true')
  222. } else {
  223. const paywallPlansPageViewSegmentation = {
  224. currency: recommendedCurrency,
  225. countryCode,
  226. 'geo-pricing-latam-v2': geoPricingLATAMTestVariant,
  227. }
  228. AnalyticsManager.recordEventForSession(
  229. req.session,
  230. 'paywall-plans-page-view',
  231. paywallPlansPageViewSegmentation
  232. )
  233. const showLATAMBanner =
  234. geoPricingLATAMTestVariant === 'latam' &&
  235. ['MX', 'CO', 'CL', 'PE'].includes(countryCode)
  236. const localCcyAssignment = await SplitTestHandler.promises.getAssignment(
  237. req,
  238. res,
  239. 'local-ccy-format'
  240. )
  241. res.render('subscriptions/interstitial-payment', {
  242. title: 'subscribe',
  243. itm_content: req.query?.itm_content,
  244. itm_campaign: req.query?.itm_campaign,
  245. itm_referrer: req.query?.itm_referrer,
  246. recommendedCurrency,
  247. interstitialPaymentConfig,
  248. showSkipLink,
  249. formatCurrency:
  250. localCcyAssignment.variant === 'enabled'
  251. ? formatCurrencyLocalized
  252. : SubscriptionHelper.formatCurrencyDefault,
  253. showCurrencyAndPaymentMethods: localCcyAssignment.variant === 'enabled',
  254. showInrGeoBanner: countryCode === 'IN',
  255. showBrlGeoBanner: countryCode === 'BR',
  256. showLATAMBanner,
  257. latamCountryBannerDetails,
  258. skipLinkTarget: req.session?.postCheckoutRedirect || '/project',
  259. })
  260. }
  261. }
  262. /**
  263. * @param {import('express').Request} req
  264. * @param {import('express').Response} res
  265. * @returns {Promise<void>}
  266. */
  267. async function successfulSubscription(req, res) {
  268. const user = SessionManager.getSessionUser(req.session)
  269. const localCcyAssignment = await SplitTestHandler.promises.getAssignment(
  270. req,
  271. res,
  272. 'local-ccy-format'
  273. )
  274. const { personalSubscription } =
  275. await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
  276. user,
  277. req.i18n.language,
  278. localCcyAssignment.variant === 'enabled'
  279. ? SubscriptionFormatters.formatPriceLocalized
  280. : SubscriptionFormatters.formatPriceDefault
  281. )
  282. const postCheckoutRedirect = req.session?.postCheckoutRedirect
  283. if (!personalSubscription) {
  284. res.redirect('/user/subscription/plans')
  285. } else {
  286. res.render('subscriptions/successful-subscription-react', {
  287. title: 'thank_you',
  288. personalSubscription,
  289. postCheckoutRedirect,
  290. })
  291. }
  292. }
  293. function cancelSubscription(req, res, next) {
  294. const user = SessionManager.getSessionUser(req.session)
  295. logger.debug({ userId: user._id }, 'canceling subscription')
  296. SubscriptionHandler.cancelSubscription(user, function (err) {
  297. if (err) {
  298. OError.tag(err, 'something went wrong canceling subscription', {
  299. user_id: user._id,
  300. })
  301. return next(err)
  302. }
  303. // Note: this redirect isn't used in the main flow as the redirection is
  304. // handled by Angular
  305. res.redirect('/user/subscription/canceled')
  306. })
  307. }
  308. /**
  309. * @param {import('express').Request} req
  310. * @param {import('express').Response} res
  311. * @param {import('express').NextFunction} next
  312. * @returns {Promise<void>}
  313. */
  314. function canceledSubscription(req, res, next) {
  315. return res.render('subscriptions/canceled-subscription-react', {
  316. title: 'subscription_canceled',
  317. })
  318. }
  319. function cancelV1Subscription(req, res, next) {
  320. const userId = SessionManager.getLoggedInUserId(req.session)
  321. logger.debug({ userId }, 'canceling v1 subscription')
  322. V1SubscriptionManager.cancelV1Subscription(userId, function (err) {
  323. if (err) {
  324. OError.tag(err, 'something went wrong canceling v1 subscription', {
  325. userId,
  326. })
  327. return next(err)
  328. }
  329. res.redirect('/user/subscription')
  330. })
  331. }
  332. function updateSubscription(req, res, next) {
  333. const origin = req && req.query ? req.query.origin : null
  334. const user = SessionManager.getSessionUser(req.session)
  335. const planCode = req.body.plan_code
  336. if (planCode == null) {
  337. const err = new Error('plan_code is not defined')
  338. logger.warn(
  339. { userId: user._id, err, planCode, origin, body: req.body },
  340. '[Subscription] error in updateSubscription form'
  341. )
  342. return next(err)
  343. }
  344. logger.debug({ planCode, userId: user._id }, 'updating subscription')
  345. SubscriptionHandler.updateSubscription(user, planCode, null, function (err) {
  346. if (err) {
  347. OError.tag(err, 'something went wrong updating subscription', {
  348. user_id: user._id,
  349. })
  350. return next(err)
  351. }
  352. res.redirect('/user/subscription')
  353. })
  354. }
  355. function cancelPendingSubscriptionChange(req, res, next) {
  356. const user = SessionManager.getSessionUser(req.session)
  357. logger.debug({ userId: user._id }, 'canceling pending subscription change')
  358. SubscriptionHandler.cancelPendingSubscriptionChange(user, function (err) {
  359. if (err) {
  360. OError.tag(
  361. err,
  362. 'something went wrong canceling pending subscription change',
  363. {
  364. user_id: user._id,
  365. }
  366. )
  367. return next(err)
  368. }
  369. res.redirect('/user/subscription')
  370. })
  371. }
  372. function updateAccountEmailAddress(req, res, next) {
  373. const user = SessionManager.getSessionUser(req.session)
  374. RecurlyWrapper.updateAccountEmailAddress(
  375. user._id,
  376. user.email,
  377. function (error) {
  378. if (error) {
  379. return next(error)
  380. }
  381. res.sendStatus(200)
  382. }
  383. )
  384. }
  385. function reactivateSubscription(req, res, next) {
  386. const user = SessionManager.getSessionUser(req.session)
  387. logger.debug({ userId: user._id }, 'reactivating subscription')
  388. try {
  389. if (req.isManagedGroupAdmin) {
  390. // allow admins to reactivate subscriptions
  391. } else {
  392. // otherwise require the user to have the reactivate-subscription permission
  393. req.assertPermission('reactivate-subscription')
  394. }
  395. } catch (error) {
  396. return next(error)
  397. }
  398. SubscriptionHandler.reactivateSubscription(user, function (err) {
  399. if (err) {
  400. OError.tag(err, 'something went wrong reactivating subscription', {
  401. user_id: user._id,
  402. })
  403. return next(err)
  404. }
  405. res.redirect('/user/subscription')
  406. })
  407. }
  408. function recurlyCallback(req, res, next) {
  409. logger.debug({ data: req.body }, 'received recurly callback')
  410. const event = Object.keys(req.body)[0]
  411. const eventData = req.body[event]
  412. RecurlyEventHandler.sendRecurlyAnalyticsEvent(event, eventData).catch(error =>
  413. logger.error(
  414. { err: error },
  415. 'Failed to process analytics event on Recurly webhook'
  416. )
  417. )
  418. if (
  419. [
  420. 'new_subscription_notification',
  421. 'updated_subscription_notification',
  422. 'expired_subscription_notification',
  423. ].includes(event)
  424. ) {
  425. const recurlySubscription = eventData.subscription
  426. SubscriptionHandler.syncSubscription(
  427. recurlySubscription,
  428. { ip: req.ip },
  429. function (err) {
  430. if (err) {
  431. return next(err)
  432. }
  433. res.sendStatus(200)
  434. }
  435. )
  436. } else if (event === 'billing_info_updated_notification') {
  437. const recurlyAccountCode = eventData.account.account_code
  438. SubscriptionHandler.attemptPaypalInvoiceCollection(
  439. recurlyAccountCode,
  440. function (err) {
  441. if (err) {
  442. return next(err)
  443. }
  444. res.sendStatus(200)
  445. }
  446. )
  447. } else {
  448. res.sendStatus(200)
  449. }
  450. }
  451. async function extendTrial(req, res) {
  452. const user = SessionManager.getSessionUser(req.session)
  453. const { subscription } =
  454. await LimitationsManager.promises.userHasV2Subscription(user)
  455. try {
  456. await SubscriptionHandler.promises.extendTrial(subscription, 14)
  457. AnalyticsManager.recordEventForSession(
  458. req.session,
  459. 'subscription-trial-extended'
  460. )
  461. } catch (error) {
  462. return res.sendStatus(500)
  463. }
  464. res.sendStatus(200)
  465. }
  466. function recurlyNotificationParser(req, res, next) {
  467. let xml = ''
  468. req.on('data', chunk => (xml += chunk))
  469. req.on('end', () =>
  470. RecurlyWrapper._parseXml(xml, function (error, body) {
  471. if (error) {
  472. return next(error)
  473. }
  474. req.body = body
  475. next()
  476. })
  477. )
  478. }
  479. async function refreshUserFeatures(req, res) {
  480. const { user_id: userId } = req.params
  481. await FeaturesUpdater.promises.refreshFeatures(userId, 'acceptance-test')
  482. res.sendStatus(200)
  483. }
  484. async function redirectToHostedPage(req, res) {
  485. const userId = SessionManager.getLoggedInUserId(req.session)
  486. const { pageType } = req.params
  487. const url =
  488. await SubscriptionViewModelBuilder.promises.getRedirectToHostedPage(
  489. userId,
  490. pageType
  491. )
  492. logger.warn({ userId, pageType }, 'redirecting to recurly hosted page')
  493. res.redirect(url)
  494. }
  495. async function _getRecommendedCurrency(req, res) {
  496. const userId = SessionManager.getLoggedInUserId(req.session)
  497. let ip = req.ip
  498. if (
  499. req.query?.ip &&
  500. (await AuthorizationManager.promises.isUserSiteAdmin(userId))
  501. ) {
  502. ip = req.query.ip
  503. }
  504. const currencyLookup = await GeoIpLookup.promises.getCurrencyCode(ip)
  505. const countryCode = currencyLookup.countryCode
  506. let recommendedCurrency = currencyLookup.currencyCode
  507. const assignmentLATAM = await SplitTestHandler.promises.getAssignment(
  508. req,
  509. res,
  510. 'geo-pricing-latam-v2'
  511. )
  512. if (
  513. ['MXN', 'COP', 'CLP', 'PEN'].includes(recommendedCurrency) &&
  514. assignmentLATAM?.variant === 'default'
  515. ) {
  516. recommendedCurrency = GeoIpLookup.DEFAULT_CURRENCY_CODE
  517. }
  518. return {
  519. recommendedCurrency,
  520. countryCode,
  521. geoPricingLATAMTestVariant: assignmentLATAM?.variant,
  522. }
  523. }
  524. async function getLatamCountryBannerDetails(req, res) {
  525. const userId = SessionManager.getLoggedInUserId(req.session)
  526. let ip = req.ip
  527. if (
  528. req.query?.ip &&
  529. (await AuthorizationManager.promises.isUserSiteAdmin(userId))
  530. ) {
  531. ip = req.query.ip
  532. }
  533. const currencyLookup = await GeoIpLookup.promises.getCurrencyCode(ip)
  534. const countryCode = currencyLookup.countryCode
  535. const latamCountryBannerDetails = {}
  536. switch (countryCode) {
  537. case `MX`:
  538. latamCountryBannerDetails.latamCountryFlag = '🇲🇽'
  539. latamCountryBannerDetails.country = 'Mexico'
  540. latamCountryBannerDetails.discount = '25%'
  541. latamCountryBannerDetails.currency = 'Mexican Pesos'
  542. break
  543. case `CO`:
  544. latamCountryBannerDetails.latamCountryFlag = '🇨🇴'
  545. latamCountryBannerDetails.country = 'Colombia'
  546. latamCountryBannerDetails.discount = '60%'
  547. latamCountryBannerDetails.currency = 'Colombian Pesos'
  548. break
  549. case `CL`:
  550. latamCountryBannerDetails.latamCountryFlag = '🇨🇱'
  551. latamCountryBannerDetails.country = 'Chile'
  552. latamCountryBannerDetails.discount = '30%'
  553. latamCountryBannerDetails.currency = 'Chilean Pesos'
  554. break
  555. case `PE`:
  556. latamCountryBannerDetails.latamCountryFlag = '🇵🇪'
  557. latamCountryBannerDetails.country = 'Peru'
  558. latamCountryBannerDetails.currency = 'Peruvian Soles'
  559. latamCountryBannerDetails.discount = '40%'
  560. break
  561. }
  562. return latamCountryBannerDetails
  563. }
  564. module.exports = {
  565. plansPage: expressify(plansPage),
  566. userSubscriptionPage: expressify(userSubscriptionPage),
  567. interstitialPaymentPage: expressify(interstitialPaymentPage),
  568. successfulSubscription: expressify(successfulSubscription),
  569. cancelSubscription,
  570. canceledSubscription,
  571. cancelV1Subscription,
  572. updateSubscription,
  573. cancelPendingSubscriptionChange,
  574. updateAccountEmailAddress,
  575. reactivateSubscription,
  576. recurlyCallback,
  577. extendTrial: expressify(extendTrial),
  578. recurlyNotificationParser,
  579. refreshUserFeatures: expressify(refreshUserFeatures),
  580. redirectToHostedPage: expressify(redirectToHostedPage),
  581. promises: {
  582. getRecommendedCurrency: _getRecommendedCurrency,
  583. },
  584. }