SubscriptionController.js 17 KB

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