SubscriptionController.mjs 35 KB

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