SubscriptionController.mjs 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177
  1. // @ts-check
  2. import SessionManager from '../Authentication/SessionManager.mjs'
  3. import SubscriptionHandler from './SubscriptionHandler.mjs'
  4. import SubscriptionHelper from './SubscriptionHelper.mjs'
  5. import SubscriptionViewModelBuilder from './SubscriptionViewModelBuilder.mjs'
  6. import LimitationsManager from './LimitationsManager.mjs'
  7. import RecurlyWrapper from './RecurlyWrapper.mjs'
  8. import Settings from '@overleaf/settings'
  9. import logger from '@overleaf/logger'
  10. import GeoIpLookup from '../../infrastructure/GeoIpLookup.mjs'
  11. import FeaturesUpdater from './FeaturesUpdater.mjs'
  12. import GroupPlansData from './GroupPlansData.mjs'
  13. import V1SubscriptionManager from './V1SubscriptionManager.mjs'
  14. import AnalyticsManager from '../Analytics/AnalyticsManager.mjs'
  15. import RecurlyEventHandler from './RecurlyEventHandler.mjs'
  16. import { expressify } from '@overleaf/promise-utils'
  17. import OError from '@overleaf/o-error'
  18. import Errors from './Errors.mjs'
  19. import SplitTestHandler from '../SplitTests/SplitTestHandler.mjs'
  20. import AuthorizationManager from '../Authorization/AuthorizationManager.mjs'
  21. import Modules from '../../infrastructure/Modules.mjs'
  22. import async from 'async'
  23. import HttpErrorHandler from '../Errors/HttpErrorHandler.mjs'
  24. import RecurlyClient from './RecurlyClient.mjs'
  25. import {
  26. AI_ADD_ON_CODE,
  27. subscriptionChangeIsAiAssistUpgrade,
  28. } from './AiHelper.mjs'
  29. import PlansLocator from './PlansLocator.mjs'
  30. import { User } from '../../models/User.mjs'
  31. import UserGetter from '../User/UserGetter.mjs'
  32. import PermissionsManager from '../Authorization/PermissionsManager.mjs'
  33. import { sanitizeSessionUserForFrontEnd } from '../../infrastructure/FrontEndUser.mjs'
  34. import { z, parseReq } from '../../infrastructure/Validation.mjs'
  35. import SubscriptionLocator from './SubscriptionLocator.mjs'
  36. import { PaymentProviderSubscriptionChange } from './PaymentProviderEntities.mjs'
  37. const {
  38. DuplicateAddOnError,
  39. AddOnNotPresentError,
  40. PaymentActionRequiredError,
  41. PaymentFailedError,
  42. MissingBillingInfoError,
  43. MultiplePendingChangesError,
  44. } = Errors
  45. const SUBSCRIPTION_PAUSED_REDIRECT_PATH =
  46. '/user/subscription?redirect-reason=subscription-paused'
  47. /**
  48. * Check if a Stripe subscription is currently paused
  49. * @param {Object} subscription - The subscription object
  50. * @returns {Promise<boolean>}
  51. */
  52. async function _checkStripeSubscriptionPauseStatus(subscription) {
  53. if (
  54. !subscription.paymentProvider?.service?.includes('stripe') ||
  55. !subscription.paymentProvider.subscriptionId
  56. ) {
  57. return false
  58. }
  59. const [paymentRecord] = await Modules.promises.hooks.fire(
  60. 'getPaymentFromRecord',
  61. subscription
  62. )
  63. return !!(
  64. paymentRecord.subscription.remainingPauseCycles &&
  65. paymentRecord.subscription.remainingPauseCycles > 0
  66. )
  67. }
  68. /**
  69. * Check if a Recurly subscription is currently paused
  70. * @param {Object} subscription - The subscription object
  71. * @returns {Promise<boolean>}
  72. */
  73. async function _checkRecurlySubscriptionPauseStatus(subscription) {
  74. if (!subscription.recurlySubscription_id) {
  75. return false
  76. }
  77. if (subscription.recurlyStatus?.state === 'paused') {
  78. return true
  79. }
  80. // Get the recurly subscription as this may be a pending pause
  81. const recurlySubscription = await RecurlyWrapper.promises.getSubscription(
  82. subscription.recurlySubscription_id
  83. )
  84. return !!(
  85. recurlySubscription.remaining_pause_cycles &&
  86. recurlySubscription.remaining_pause_cycles > 0
  87. )
  88. }
  89. /** Check if a user's subscription is manual or custom
  90. * @param {Object} user - The user object
  91. * @returns {Promise<boolean>}
  92. */
  93. async function _isManualOrCustomSubscription(user) {
  94. const subscription = await SubscriptionLocator.promises.getUsersSubscription(
  95. user._id
  96. )
  97. if (!subscription) {
  98. return false
  99. }
  100. return (
  101. subscription.customAccount || subscription.collectionMethod === 'manual'
  102. )
  103. }
  104. /**
  105. * Check if a user's subscription is currently paused
  106. * @param {Object} user - The user object
  107. * @returns {Promise<{isPaused: boolean, redirectPath?: string}>}
  108. */
  109. async function checkSubscriptionPauseStatus(user) {
  110. try {
  111. const { subscription } =
  112. await LimitationsManager.promises.userHasSubscription(user)
  113. if (!subscription) {
  114. return { isPaused: false }
  115. }
  116. const isStripePaused =
  117. await _checkStripeSubscriptionPauseStatus(subscription)
  118. if (isStripePaused) {
  119. return {
  120. isPaused: true,
  121. redirectPath: SUBSCRIPTION_PAUSED_REDIRECT_PATH,
  122. }
  123. }
  124. const isRecurlyPaused =
  125. await _checkRecurlySubscriptionPauseStatus(subscription)
  126. if (isRecurlyPaused) {
  127. return {
  128. isPaused: true,
  129. redirectPath: SUBSCRIPTION_PAUSED_REDIRECT_PATH,
  130. }
  131. }
  132. } catch (err) {
  133. logger.warn(
  134. { err, userId: user._id },
  135. 'Failed to check user subscription for pause status'
  136. )
  137. }
  138. return { isPaused: false }
  139. }
  140. /**
  141. * @import { SubscriptionChangeDescription } from '../../../../types/subscription/subscription-change-preview'
  142. * @import { SubscriptionChangePreview } from '../../../../types/subscription/subscription-change-preview'
  143. * @import { PaymentMethod } from './types'
  144. */
  145. const groupPlanModalOptions = Settings.groupPlanModalOptions
  146. function formatGroupPlansDataForDash() {
  147. return {
  148. plans: [...groupPlanModalOptions.plan_codes],
  149. sizes: [...groupPlanModalOptions.sizes],
  150. usages: [...groupPlanModalOptions.usages],
  151. priceByUsageTypeAndSize: JSON.parse(JSON.stringify(GroupPlansData)),
  152. }
  153. }
  154. async function userSubscriptionPage(req, res) {
  155. const user = SessionManager.getSessionUser(req.session)
  156. await SplitTestHandler.promises.getAssignment(req, res, 'pause-subscription')
  157. await SplitTestHandler.promises.getAssignment(
  158. req,
  159. res,
  160. 'combined-user-management'
  161. )
  162. const groupPricingDiscount = await SplitTestHandler.promises.getAssignment(
  163. req,
  164. res,
  165. 'group-discount-10'
  166. )
  167. const showGroupDiscount = groupPricingDiscount.variant === 'enabled'
  168. const results =
  169. await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
  170. user,
  171. req.i18n.language
  172. )
  173. const {
  174. personalSubscription,
  175. memberGroupSubscriptions,
  176. managedGroupSubscriptions,
  177. currentInstitutionsWithLicence,
  178. managedInstitutions,
  179. managedPublishers,
  180. } = results
  181. const { hasSubscription } =
  182. await LimitationsManager.promises.userHasSubscription(user)
  183. const userCanExtendTrial = (
  184. await Modules.promises.hooks.fire('userCanExtendTrial', user)
  185. )?.[0]
  186. const fromPlansPage = req.query.hasSubscription
  187. const redirectedPaymentErrorCode = req.query.errorCode
  188. const isInTrial = SubscriptionHelper.isInTrial(
  189. personalSubscription?.payment?.trialEndsAt
  190. )
  191. const plansData =
  192. SubscriptionViewModelBuilder.buildPlansListForSubscriptionDash(
  193. personalSubscription?.plan,
  194. isInTrial
  195. )
  196. const host = req.headers.host
  197. const domain = host?.split('.')[0]
  198. AnalyticsManager.recordEventForSession(
  199. req.session,
  200. 'subscription-page-view',
  201. {
  202. domain,
  203. }
  204. )
  205. const groupPlansDataForDash = formatGroupPlansDataForDash()
  206. // display the Group settings button only to admins of group subscriptions with either/or the Managed Users or Group SSO feature available
  207. let groupSettingsEnabledFor
  208. try {
  209. const managedGroups = await async.filter(
  210. managedGroupSubscriptions || [],
  211. async subscription => {
  212. const managedUsersResults = await Modules.promises.hooks.fire(
  213. 'hasManagedUsersFeature',
  214. subscription
  215. )
  216. const groupSSOResults = await Modules.promises.hooks.fire(
  217. 'hasGroupSSOFeature',
  218. subscription
  219. )
  220. const isGroupAdmin =
  221. (subscription.admin_id._id || subscription.admin_id).toString() ===
  222. user._id.toString()
  223. return (
  224. (managedUsersResults?.[0] === true ||
  225. groupSSOResults?.[0] === true) &&
  226. isGroupAdmin
  227. )
  228. }
  229. )
  230. groupSettingsEnabledFor = managedGroups.map(subscription =>
  231. subscription._id.toString()
  232. )
  233. } catch (error) {
  234. logger.error(
  235. { err: error },
  236. 'Failed to list groups with group settings enabled'
  237. )
  238. }
  239. let groupSettingsAdvertisedFor
  240. try {
  241. const managedGroups = await async.filter(
  242. managedGroupSubscriptions || [],
  243. async subscription => {
  244. const managedUsersResults = await Modules.promises.hooks.fire(
  245. 'hasManagedUsersFeatureOnNonProfessionalPlan',
  246. subscription
  247. )
  248. const groupSSOResults = await Modules.promises.hooks.fire(
  249. 'hasGroupSSOFeatureOnNonProfessionalPlan',
  250. subscription
  251. )
  252. const isGroupAdmin =
  253. (subscription.admin_id._id || subscription.admin_id).toString() ===
  254. user._id.toString()
  255. const plan = PlansLocator.findLocalPlanInSettings(subscription.planCode)
  256. return (
  257. (managedUsersResults?.[0] === true ||
  258. groupSSOResults?.[0] === true) &&
  259. isGroupAdmin &&
  260. plan?.canUseFlexibleLicensing
  261. )
  262. }
  263. )
  264. groupSettingsAdvertisedFor = managedGroups.map(subscription =>
  265. subscription._id.toString()
  266. )
  267. } catch (error) {
  268. logger.error(
  269. { err: error },
  270. 'Failed to list groups with group settings enabled for advertising'
  271. )
  272. }
  273. const {
  274. isPremium: hasAiAssistViaWritefull,
  275. premiumSource: aiAssistViaWritefullSource,
  276. } = await UserGetter.promises.getWritefullData(user._id)
  277. const data = {
  278. title: 'your_subscriptions',
  279. plans: plansData?.plans,
  280. planCodesChangingAtTermEnd: plansData?.planCodesChangingAtTermEnd,
  281. user,
  282. hasSubscription,
  283. fromPlansPage,
  284. redirectedPaymentErrorCode,
  285. personalSubscription,
  286. userCanExtendTrial,
  287. memberGroupSubscriptions,
  288. managedGroupSubscriptions,
  289. managedInstitutions,
  290. managedPublishers,
  291. showGroupDiscount,
  292. currentInstitutionsWithLicence,
  293. canUseFlexibleLicensing:
  294. personalSubscription?.plan?.canUseFlexibleLicensing,
  295. groupPlans: groupPlansDataForDash,
  296. groupSettingsAdvertisedFor,
  297. groupSettingsEnabledFor,
  298. isManagedAccount: !!req.managedBy,
  299. userRestrictions: Array.from(req.userRestrictions || []),
  300. hasAiAssistViaWritefull,
  301. aiAssistViaWritefullSource,
  302. }
  303. res.render('subscriptions/dashboard-react', data)
  304. }
  305. async function successfulSubscription(req, res) {
  306. const user = SessionManager.getSessionUser(req.session)
  307. if (!user) {
  308. throw new Error('User is not logged in')
  309. }
  310. const { personalSubscription } =
  311. await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
  312. user,
  313. req.i18n.language
  314. )
  315. const postCheckoutRedirect = req.session?.postCheckoutRedirect
  316. if (!personalSubscription) {
  317. res.redirect('/user/subscription/plans')
  318. } else {
  319. const userInDb = await User.findById(user._id, {
  320. _id: 1,
  321. features: 1,
  322. })
  323. if (!userInDb) {
  324. throw new Error('User not found')
  325. }
  326. res.render('subscriptions/successful-subscription-react', {
  327. title: 'thank_you',
  328. personalSubscription,
  329. postCheckoutRedirect,
  330. user: {
  331. _id: user._id,
  332. features: userInDb.features,
  333. },
  334. })
  335. }
  336. }
  337. const pauseSubscriptionSchema = z.object({
  338. params: z.object({
  339. pauseCycles: z.coerce.number().int().max(12),
  340. }),
  341. })
  342. async function pauseSubscription(req, res, next) {
  343. const user = SessionManager.getSessionUser(req.session)
  344. const { params } = parseReq(req, pauseSubscriptionSchema)
  345. const pauseCycles = params.pauseCycles
  346. if (pauseCycles < 0) {
  347. return HttpErrorHandler.badRequest(
  348. req,
  349. res,
  350. `'pauseCycles' should be a number of billing cycles to pause for, or 0 to cancel a pending pause`
  351. )
  352. }
  353. logger.debug(
  354. { userId: user._id },
  355. `pausing subscription for ${pauseCycles} billing cycles`
  356. )
  357. try {
  358. await SubscriptionHandler.promises.pauseSubscription(user, pauseCycles)
  359. const { subscription } =
  360. await LimitationsManager.promises.userHasSubscription(user)
  361. AnalyticsManager.recordEventForUserInBackground(
  362. user._id,
  363. 'subscription-pause-scheduled',
  364. {
  365. pause_length: pauseCycles,
  366. plan_code: subscription?.planCode,
  367. subscriptionId:
  368. SubscriptionHelper.getPaymentProviderSubscriptionId(subscription),
  369. }
  370. )
  371. return res.sendStatus(200)
  372. } catch (err) {
  373. if (err instanceof Error) {
  374. OError.tag(err, 'something went wrong pausing subscription', {
  375. user_id: user._id,
  376. })
  377. }
  378. return next(err)
  379. }
  380. }
  381. async function resumeSubscription(req, res, next) {
  382. const user = SessionManager.getSessionUser(req.session)
  383. logger.debug({ userId: user._id }, `resuming subscription`)
  384. try {
  385. await SubscriptionHandler.promises.resumeSubscription(user)
  386. return res.sendStatus(200)
  387. } catch (err) {
  388. if (err instanceof Error) {
  389. OError.tag(err, 'something went wrong resuming subscription', {
  390. user_id: user._id,
  391. })
  392. }
  393. return next(err)
  394. }
  395. }
  396. async function cancelSubscription(req, res, next) {
  397. const user = SessionManager.getSessionUser(req.session)
  398. logger.debug({ userId: user._id }, 'canceling subscription')
  399. try {
  400. await SubscriptionHandler.promises.cancelSubscription(user)
  401. return res.sendStatus(200)
  402. } catch (err) {
  403. OError.tag(err, 'something went wrong canceling subscription', {
  404. user_id: user._id,
  405. })
  406. return next(err)
  407. }
  408. }
  409. /**
  410. * @returns {Promise<void>}
  411. */
  412. async function canceledSubscription(req, res, next) {
  413. return res.render('subscriptions/canceled-subscription-react', {
  414. title: 'subscription_canceled',
  415. user: sanitizeSessionUserForFrontEnd(
  416. SessionManager.getSessionUser(req.session)
  417. ),
  418. })
  419. }
  420. function cancelV1Subscription(req, res, next) {
  421. const userId = SessionManager.getLoggedInUserId(req.session)
  422. logger.debug({ userId }, 'canceling v1 subscription')
  423. V1SubscriptionManager.cancelV1Subscription(userId, function (err) {
  424. if (err) {
  425. OError.tag(err, 'something went wrong canceling v1 subscription', {
  426. userId,
  427. })
  428. return next(err)
  429. }
  430. res.redirect('/user/subscription')
  431. })
  432. }
  433. async function previewAddonPurchase(req, res) {
  434. const user = SessionManager.getSessionUser(req.session)
  435. const userId = user._id
  436. const addOnCode = req.params.addOnCode
  437. const purchaseReferrer = req.query.purchaseReferrer
  438. const redirectedPaymentErrorCode = req.query.errorCode
  439. if (addOnCode !== AI_ADD_ON_CODE) {
  440. return HttpErrorHandler.notFound(req, res, `Unknown add-on: ${addOnCode}`)
  441. }
  442. const canUseAi = await PermissionsManager.promises.checkUserPermissions(
  443. user,
  444. ['use-ai']
  445. )
  446. if (!canUseAi) {
  447. return res.redirect(
  448. '/user/subscription?redirect-reason=ai-assist-unavailable'
  449. )
  450. }
  451. const isManualOrCustom = await _isManualOrCustomSubscription(user)
  452. if (isManualOrCustom) {
  453. return res.redirect(
  454. '/user/subscription?redirect-reason=ai-assist-unavailable'
  455. )
  456. }
  457. const { isPaused, redirectPath } = await checkSubscriptionPauseStatus(user)
  458. if (isPaused) {
  459. return res.redirect(redirectPath)
  460. }
  461. let paymentMethod
  462. try {
  463. /** @type {PaymentMethod[]} */
  464. paymentMethod = await Modules.promises.hooks.fire(
  465. 'getPaymentMethod',
  466. userId
  467. )
  468. } catch (err) {
  469. if (err instanceof MissingBillingInfoError) {
  470. // We will get MissingBillingInfoError if a manual subscription doesn't have billing info
  471. // but doesn't marked as manual on the Overleaf side
  472. logger.error(
  473. { err },
  474. 'User has no billing info, cannot preview add-on purchase'
  475. )
  476. return res.redirect(
  477. '/user/subscription?redirect-reason=ai-assist-unavailable'
  478. )
  479. }
  480. if (
  481. err instanceof Error &&
  482. err.constructor.name === 'PaymentServiceResourceNotFoundError'
  483. ) {
  484. return res.redirect('/user/subscription/plans#ai-assist')
  485. }
  486. throw err
  487. }
  488. let subscriptionChange
  489. try {
  490. subscriptionChange =
  491. await SubscriptionHandler.promises.previewAddonPurchase(userId, addOnCode)
  492. const { isPremium: hasAiAssistViaWritefull } =
  493. await UserGetter.promises.getWritefullData(userId)
  494. const isAiUpgrade = subscriptionChangeIsAiAssistUpgrade(subscriptionChange)
  495. if (hasAiAssistViaWritefull && isAiUpgrade) {
  496. return res.redirect(
  497. '/user/subscription?redirect-reason=writefull-entitled'
  498. )
  499. }
  500. } catch (err) {
  501. if (err instanceof DuplicateAddOnError) {
  502. return res.redirect('/user/subscription?redirect-reason=double-buy')
  503. }
  504. if (
  505. err instanceof Error &&
  506. err.constructor.name === 'PaymentServiceResourceNotFoundError'
  507. ) {
  508. return res.redirect('/user/subscription/plans#ai-assist')
  509. }
  510. throw err
  511. }
  512. const subscription = subscriptionChange.subscription
  513. const addOn = await RecurlyClient.promises.getAddOn(
  514. subscription.planCode,
  515. addOnCode
  516. )
  517. /** @type {SubscriptionChangePreview} */
  518. const changePreview = makeChangePreview(
  519. {
  520. type: 'add-on-purchase',
  521. addOn: {
  522. code: addOn.code,
  523. name: addOn.name,
  524. },
  525. },
  526. subscriptionChange,
  527. paymentMethod[0]
  528. )
  529. await SplitTestHandler.promises.getAssignment(
  530. req,
  531. res,
  532. 'overleaf-assist-bundle'
  533. )
  534. res.render('subscriptions/preview-change', {
  535. changePreview,
  536. purchaseReferrer,
  537. redirectedPaymentErrorCode,
  538. })
  539. }
  540. const purchaseAddonSchema = z.object({
  541. params: z.object({
  542. addOnCode: z.string(),
  543. }),
  544. })
  545. async function purchaseAddon(req, res, next) {
  546. const user = SessionManager.getSessionUser(req.session)
  547. const { params } = parseReq(req, purchaseAddonSchema)
  548. const addOnCode = params.addOnCode
  549. // currently we only support having a quantity of 1
  550. const quantity = 1
  551. // currently we only support one add-on, the Ai add-on
  552. if (addOnCode !== AI_ADD_ON_CODE) {
  553. return res.sendStatus(404)
  554. }
  555. const { isPaused } = await checkSubscriptionPauseStatus(user)
  556. if (isPaused) {
  557. return HttpErrorHandler.badRequest(
  558. req,
  559. res,
  560. 'Cannot purchase add-ons while subscription is paused.'
  561. )
  562. }
  563. logger.debug({ userId: user._id, addOnCode }, 'purchasing add-ons')
  564. try {
  565. await SubscriptionHandler.promises.purchaseAddon(
  566. user._id,
  567. addOnCode,
  568. quantity
  569. )
  570. } catch (err) {
  571. if (err instanceof DuplicateAddOnError) {
  572. HttpErrorHandler.badRequest(
  573. req,
  574. res,
  575. 'Your subscription already includes this add-on',
  576. { addon: addOnCode }
  577. )
  578. } else if (err instanceof PaymentActionRequiredError) {
  579. logger.debug(
  580. { userId: user._id },
  581. 'Customer needs to perform payment action to complete transaction'
  582. )
  583. return res.status(402).json({
  584. message: 'Payment action required',
  585. clientSecret: err.info.clientSecret,
  586. publicKey: err.info.publicKey,
  587. })
  588. } else if (err instanceof PaymentFailedError) {
  589. logger.debug(
  590. {
  591. userId: user._id,
  592. reason: err.info.reason,
  593. adviceCode: err.info.adviceCode,
  594. },
  595. 'Payment failed for transaction'
  596. )
  597. return res.status(402).json({
  598. message: 'Payment failed',
  599. reason: err.info.reason,
  600. adviceCode: err.info.adviceCode,
  601. })
  602. } else if (err instanceof MultiplePendingChangesError) {
  603. logger.warn(
  604. { userId: user._id, err, addOnCode },
  605. 'Cannot purchase add-on: multiple pending changes'
  606. )
  607. return res.status(422).json({
  608. code: 'multiple_pending_changes',
  609. message:
  610. 'Cannot complete purchase while there are multiple pending subscription changes. Please contact support.',
  611. })
  612. } else {
  613. if (err instanceof Error) {
  614. OError.tag(err, 'something went wrong purchasing add-ons', {
  615. user_id: user._id,
  616. addOnCode,
  617. })
  618. }
  619. return next(err)
  620. }
  621. }
  622. try {
  623. await FeaturesUpdater.promises.refreshFeatures(user._id, 'add-on-purchase')
  624. } catch (err) {
  625. logger.error({ err }, 'Failed to refresh features after add-on purchase')
  626. }
  627. return res.sendStatus(200)
  628. }
  629. const removeAddonSchema = z.object({
  630. params: z.object({
  631. addOnCode: z.string(),
  632. }),
  633. })
  634. async function removeAddon(req, res, next) {
  635. const user = SessionManager.getSessionUser(req.session)
  636. const { params } = parseReq(req, removeAddonSchema)
  637. const addOnCode = params.addOnCode
  638. if (addOnCode !== AI_ADD_ON_CODE) {
  639. return res.sendStatus(404)
  640. }
  641. logger.debug({ userId: user._id, addOnCode }, 'removing add-ons')
  642. try {
  643. await SubscriptionHandler.promises.removeAddon(user, addOnCode)
  644. res.sendStatus(200)
  645. } catch (err) {
  646. if (err instanceof AddOnNotPresentError) {
  647. HttpErrorHandler.badRequest(
  648. req,
  649. res,
  650. 'Your subscription does not contain the requested add-on',
  651. { addon: addOnCode }
  652. )
  653. } else if (err instanceof MultiplePendingChangesError) {
  654. logger.warn(
  655. { userId: user._id, err, addOnCode },
  656. 'Cannot remove add-on: multiple pending changes'
  657. )
  658. return res.status(422).json({
  659. code: 'multiple_pending_changes',
  660. message:
  661. 'Cannot remove add-on while there are multiple pending subscription changes. Please contact support.',
  662. })
  663. } else {
  664. if (err instanceof Error) {
  665. OError.tag(err, 'something went wrong removing add-ons', {
  666. user_id: user._id,
  667. addOnCode,
  668. })
  669. }
  670. return next(err)
  671. }
  672. }
  673. }
  674. const reactivateAddonSchema = z.object({
  675. params: z.object({
  676. addOnCode: z.string(),
  677. }),
  678. })
  679. /**
  680. * Reactivate an add-on pending cancellation
  681. *
  682. * This "cancels" the cancellation.
  683. */
  684. async function reactivateAddon(req, res) {
  685. const user = SessionManager.getSessionUser(req.session)
  686. const { params } = parseReq(req, reactivateAddonSchema)
  687. const addOnCode = params.addOnCode
  688. if (addOnCode !== AI_ADD_ON_CODE) {
  689. return res.sendStatus(404)
  690. }
  691. try {
  692. await SubscriptionHandler.promises.reactivateAddon(user._id, addOnCode)
  693. res.sendStatus(200)
  694. } catch (err) {
  695. if (err instanceof AddOnNotPresentError) {
  696. HttpErrorHandler.badRequest(
  697. req,
  698. res,
  699. 'The requested add-on is not pending cancellation',
  700. { addon: addOnCode }
  701. )
  702. } else {
  703. throw err
  704. }
  705. }
  706. }
  707. async function previewSubscription(req, res, next) {
  708. const planCode = req.query.planCode
  709. if (!planCode) {
  710. return HttpErrorHandler.notFound(req, res, 'Missing plan code')
  711. }
  712. // TODO: use PaymentService to fetch plan information
  713. const plan = await RecurlyClient.promises.getPlan(planCode)
  714. const user = SessionManager.getSessionUser(req.session)
  715. const userId = user?._id
  716. let trialDisabledReason
  717. if (planCode.includes('_free_trial')) {
  718. const trialEligibility = (
  719. await Modules.promises.hooks.fire('userCanStartTrial', user)
  720. )?.[0]
  721. if (!trialEligibility.canStartTrial) {
  722. trialDisabledReason = trialEligibility.disabledReason
  723. }
  724. }
  725. const subscriptionChange =
  726. await SubscriptionHandler.promises.previewSubscriptionChange(
  727. userId,
  728. planCode
  729. )
  730. /** @type {PaymentMethod[]} */
  731. const paymentMethod = await Modules.promises.hooks.fire(
  732. 'getPaymentMethod',
  733. userId
  734. )
  735. const changePreview = makeChangePreview(
  736. {
  737. type: 'premium-subscription',
  738. plan: { code: plan.code, name: plan.name },
  739. },
  740. subscriptionChange,
  741. paymentMethod[0]
  742. )
  743. res.render('subscriptions/preview-change', {
  744. changePreview,
  745. redirectedPaymentErrorCode: req.query.errorCode,
  746. trialDisabledReason,
  747. })
  748. }
  749. function cancelPendingSubscriptionChange(req, res, next) {
  750. const user = SessionManager.getSessionUser(req.session)
  751. logger.debug({ userId: user._id }, 'canceling pending subscription change')
  752. SubscriptionHandler.cancelPendingSubscriptionChange(user, function (err) {
  753. if (err) {
  754. OError.tag(
  755. err,
  756. 'something went wrong canceling pending subscription change',
  757. {
  758. user_id: user._id,
  759. }
  760. )
  761. return next(err)
  762. }
  763. res.redirect('/user/subscription')
  764. })
  765. }
  766. async function updateAccountEmailAddress(req, res, next) {
  767. const user = SessionManager.getSessionUser(req.session)
  768. try {
  769. await Modules.promises.hooks.fire(
  770. 'updateAccountEmailAddress',
  771. user._id,
  772. user.email
  773. )
  774. return res.sendStatus(200)
  775. } catch (error) {
  776. return next(error)
  777. }
  778. }
  779. function reactivateSubscription(req, res, next) {
  780. const user = SessionManager.getSessionUser(req.session)
  781. logger.debug({ userId: user._id }, 'reactivating subscription')
  782. try {
  783. if (req.isManagedGroupAdmin) {
  784. // allow admins to reactivate subscriptions
  785. } else {
  786. // otherwise require the user to have the reactivate-subscription permission
  787. req.assertPermission('reactivate-subscription')
  788. }
  789. } catch (error) {
  790. return next(error)
  791. }
  792. SubscriptionHandler.reactivateSubscription(user, function (err) {
  793. if (err) {
  794. OError.tag(err, 'something went wrong reactivating subscription', {
  795. user_id: user._id,
  796. })
  797. return next(err)
  798. }
  799. res.redirect('/user/subscription')
  800. })
  801. }
  802. function recurlyCallback(req, res, next) {
  803. logger.debug({ data: req.body }, 'received recurly callback')
  804. const event = Object.keys(req.body)[0]
  805. const eventData = req.body[event]
  806. RecurlyEventHandler.sendRecurlyAnalyticsEvent(event, eventData).catch(error =>
  807. logger.error(
  808. { err: error },
  809. 'Failed to process analytics event on Recurly webhook'
  810. )
  811. )
  812. if (
  813. [
  814. 'new_subscription_notification',
  815. 'updated_subscription_notification',
  816. 'expired_subscription_notification',
  817. 'subscription_paused_notification',
  818. 'subscription_resumed_notification',
  819. ].includes(event)
  820. ) {
  821. const recurlySubscription = eventData.subscription
  822. SubscriptionHandler.syncSubscription(
  823. recurlySubscription,
  824. { ip: req.ip },
  825. function (err) {
  826. if (err) {
  827. return next(err)
  828. }
  829. res.sendStatus(200)
  830. }
  831. )
  832. } else if (event === 'billing_info_updated_notification') {
  833. const recurlyAccountCode = eventData.account.account_code
  834. SubscriptionHandler.attemptPaypalInvoiceCollection(
  835. recurlyAccountCode,
  836. function (err) {
  837. if (err) {
  838. return next(err)
  839. }
  840. res.sendStatus(200)
  841. }
  842. )
  843. } else {
  844. res.sendStatus(200)
  845. }
  846. }
  847. async function extendTrial(req, res) {
  848. const user = SessionManager.getSessionUser(req.session)
  849. const { subscription } =
  850. await LimitationsManager.promises.userHasSubscription(user)
  851. const allowed = (
  852. await Modules.promises.hooks.fire('userCanExtendTrial', user)
  853. )?.[0]
  854. if (!allowed) {
  855. logger.warn({ userId: user._id }, 'user can not extend trial')
  856. return res.sendStatus(403)
  857. }
  858. try {
  859. await SubscriptionHandler.promises.extendTrial(subscription, 14)
  860. AnalyticsManager.recordEventForSession(
  861. req.session,
  862. 'subscription-trial-extended'
  863. )
  864. } catch (error) {
  865. return res.sendStatus(500)
  866. }
  867. res.sendStatus(200)
  868. }
  869. function recurlyNotificationParser(req, res, next) {
  870. let xml = ''
  871. req.on('data', chunk => (xml += chunk))
  872. req.on('end', () =>
  873. RecurlyWrapper._parseXml(xml, function (error, body) {
  874. if (error) {
  875. return next(error)
  876. }
  877. req.body = body
  878. next()
  879. })
  880. )
  881. }
  882. async function refreshUserFeatures(req, res) {
  883. const { user_id: userId } = req.params
  884. await FeaturesUpdater.promises.refreshFeatures(userId, 'acceptance-test')
  885. res.sendStatus(200)
  886. }
  887. async function getRecommendedCurrency(req, res) {
  888. const userId = SessionManager.getLoggedInUserId(req.session)
  889. let ip = req.ip
  890. if (
  891. req.query?.ip &&
  892. (await AuthorizationManager.promises.isUserSiteAdmin(userId))
  893. ) {
  894. ip = req.query.ip
  895. }
  896. const currencyLookup = await GeoIpLookup.promises.getCurrencyCode(ip)
  897. const countryCode = currencyLookup.countryCode
  898. const recommendedCurrency = currencyLookup.currencyCode
  899. let currency = null
  900. const queryCurrency = req.query.currency?.toUpperCase()
  901. if (queryCurrency && GeoIpLookup.isValidCurrencyParam(queryCurrency)) {
  902. currency = queryCurrency
  903. } else if (recommendedCurrency) {
  904. currency = recommendedCurrency
  905. }
  906. return {
  907. currency,
  908. recommendedCurrency,
  909. countryCode,
  910. }
  911. }
  912. async function getLatamCountryBannerDetails(req, res) {
  913. const userId = SessionManager.getLoggedInUserId(req.session)
  914. let ip = req.ip
  915. if (
  916. req.query?.ip &&
  917. (await AuthorizationManager.promises.isUserSiteAdmin(userId))
  918. ) {
  919. ip = req.query.ip
  920. }
  921. const currencyLookup = await GeoIpLookup.promises.getCurrencyCode(ip)
  922. const countryCode = currencyLookup.countryCode
  923. const latamCountryBannerDetails = {}
  924. switch (countryCode) {
  925. case `MX`:
  926. latamCountryBannerDetails.latamCountryFlag = '🇲🇽'
  927. latamCountryBannerDetails.country = 'Mexico'
  928. latamCountryBannerDetails.discount = '25%'
  929. latamCountryBannerDetails.currency = 'Mexican Pesos'
  930. break
  931. case `CO`:
  932. latamCountryBannerDetails.latamCountryFlag = '🇨🇴'
  933. latamCountryBannerDetails.country = 'Colombia'
  934. latamCountryBannerDetails.discount = '60%'
  935. latamCountryBannerDetails.currency = 'Colombian Pesos'
  936. break
  937. case `CL`:
  938. latamCountryBannerDetails.latamCountryFlag = '🇨🇱'
  939. latamCountryBannerDetails.country = 'Chile'
  940. latamCountryBannerDetails.discount = '30%'
  941. latamCountryBannerDetails.currency = 'Chilean Pesos'
  942. break
  943. case `PE`:
  944. latamCountryBannerDetails.latamCountryFlag = '🇵🇪'
  945. latamCountryBannerDetails.country = 'Peru'
  946. latamCountryBannerDetails.currency = 'Peruvian Soles'
  947. latamCountryBannerDetails.discount = '40%'
  948. break
  949. }
  950. return latamCountryBannerDetails
  951. }
  952. /**
  953. * There are two sets of group plans: legacy plans and consolidated plans,
  954. * and their naming conventions differ.
  955. * This helper method computes the name of legacy group plans to ensure
  956. * consistency with the naming of consolidated group plans.
  957. *
  958. * @param {string} planName
  959. * @param {string} planCode
  960. * @return {string}
  961. */
  962. function getPlanNameForDisplay(planName, planCode) {
  963. const match = planCode.match(
  964. /^group_(collaborator|professional)_\d+_(enterprise|educational)$/
  965. )
  966. if (!match) return planName
  967. const [, type, category] = match
  968. const prefix = type === 'collaborator' ? 'Standard' : 'Professional'
  969. const suffix = category === 'educational' ? ' Educational' : ''
  970. return `Overleaf ${prefix} Group${suffix}`
  971. }
  972. /**
  973. * Build a subscription change preview for display purposes
  974. *
  975. * @param {SubscriptionChangeDescription} subscriptionChangeDescription A description of the change for the frontend
  976. * @param {PaymentProviderSubscriptionChange} subscriptionChange The subscription change object coming from Recurly
  977. * @param {PaymentMethod} [paymentMethod] The payment method associated to the user
  978. * @return {SubscriptionChangePreview}
  979. */
  980. function makeChangePreview(
  981. subscriptionChangeDescription,
  982. subscriptionChange,
  983. paymentMethod
  984. ) {
  985. const subscription = subscriptionChange.subscription
  986. // For the future invoice display, if there's a pending change scheduled,
  987. // we should show what will happen at renewal (the pending change state)
  988. // merged with any new changes from this immediate update
  989. const pendingChange = subscription.pendingChange
  990. let futureInvoiceChange
  991. if (pendingChange) {
  992. const pendingAddOnCodes = new Set(pendingChange.nextAddOns.map(a => a.code))
  993. const mergedAddOns = [...pendingChange.nextAddOns]
  994. for (const addOn of subscriptionChange.nextAddOns) {
  995. if (!pendingAddOnCodes.has(addOn.code)) {
  996. mergedAddOns.push(addOn)
  997. }
  998. }
  999. futureInvoiceChange = new PaymentProviderSubscriptionChange({
  1000. subscription,
  1001. nextPlanCode: pendingChange.nextPlanCode,
  1002. nextPlanName: pendingChange.nextPlanName,
  1003. nextPlanPrice: pendingChange.nextPlanPrice,
  1004. nextAddOns: mergedAddOns,
  1005. })
  1006. } else {
  1007. futureInvoiceChange = subscriptionChange
  1008. }
  1009. const nextPlan = PlansLocator.findLocalPlanInSettings(
  1010. futureInvoiceChange.nextPlanCode
  1011. )
  1012. return {
  1013. change: subscriptionChangeDescription,
  1014. currency: subscription.currency,
  1015. immediateCharge: { ...subscriptionChange.immediateCharge },
  1016. paymentMethod: paymentMethod?.toString(),
  1017. netTerms: subscription.netTerms,
  1018. nextPlan: {
  1019. annual: nextPlan?.annual ?? false,
  1020. },
  1021. nextInvoice: {
  1022. date: subscription.periodEnd.toISOString(),
  1023. plan: {
  1024. name: getPlanNameForDisplay(
  1025. futureInvoiceChange.nextPlanName,
  1026. futureInvoiceChange.nextPlanCode
  1027. ),
  1028. amount: futureInvoiceChange.nextPlanPrice,
  1029. },
  1030. addOns: futureInvoiceChange.nextAddOns.map(addOn => ({
  1031. code: addOn.code,
  1032. name: addOn.name,
  1033. quantity: addOn.quantity,
  1034. unitAmount: addOn.unitPrice,
  1035. amount: addOn.preTaxTotal,
  1036. })),
  1037. subtotal: futureInvoiceChange.subtotal,
  1038. tax: {
  1039. rate: subscription.taxRate,
  1040. amount: futureInvoiceChange.tax,
  1041. },
  1042. total: futureInvoiceChange.total,
  1043. },
  1044. }
  1045. }
  1046. export default {
  1047. userSubscriptionPage: expressify(userSubscriptionPage),
  1048. successfulSubscription: expressify(successfulSubscription),
  1049. cancelSubscription,
  1050. pauseSubscription,
  1051. resumeSubscription,
  1052. canceledSubscription: expressify(canceledSubscription),
  1053. cancelV1Subscription,
  1054. previewSubscription: expressify(previewSubscription),
  1055. cancelPendingSubscriptionChange,
  1056. updateAccountEmailAddress: expressify(updateAccountEmailAddress),
  1057. reactivateSubscription,
  1058. recurlyCallback,
  1059. extendTrial: expressify(extendTrial),
  1060. recurlyNotificationParser,
  1061. refreshUserFeatures: expressify(refreshUserFeatures),
  1062. previewAddonPurchase: expressify(previewAddonPurchase),
  1063. purchaseAddon,
  1064. removeAddon,
  1065. reactivateAddon,
  1066. makeChangePreview,
  1067. getRecommendedCurrency,
  1068. getLatamCountryBannerDetails,
  1069. getPlanNameForDisplay,
  1070. checkSubscriptionPauseStatus,
  1071. }