SubscriptionController.mjs 36 KB

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