| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284 |
- // @ts-check
- import SessionManager from '../Authentication/SessionManager.mjs'
- import SubscriptionHandler from './SubscriptionHandler.mjs'
- import SubscriptionHelper from './SubscriptionHelper.mjs'
- import SubscriptionViewModelBuilder from './SubscriptionViewModelBuilder.mjs'
- import LimitationsManager from './LimitationsManager.mjs'
- import RecurlyWrapper from './RecurlyWrapper.mjs'
- import Settings from '@overleaf/settings'
- import logger from '@overleaf/logger'
- import GeoIpLookup from '../../infrastructure/GeoIpLookup.mjs'
- import FeaturesUpdater from './FeaturesUpdater.mjs'
- import GroupPlansData from './GroupPlansData.mjs'
- import V1SubscriptionManager from './V1SubscriptionManager.mjs'
- import AnalyticsManager from '../Analytics/AnalyticsManager.mjs'
- import RecurlyEventHandler from './RecurlyEventHandler.mjs'
- import { expressify } from '@overleaf/promise-utils'
- import OError from '@overleaf/o-error'
- import Errors from './Errors.mjs'
- import SplitTestHandler from '../SplitTests/SplitTestHandler.mjs'
- import AuthorizationManager from '../Authorization/AuthorizationManager.mjs'
- import Modules from '../../infrastructure/Modules.mjs'
- import async from 'async'
- import HttpErrorHandler from '../Errors/HttpErrorHandler.mjs'
- import RecurlyClient from './RecurlyClient.mjs'
- import {
- AI_ADD_ON_CODE,
- subscriptionChangeIsAiAssistUpgrade,
- } from './AiHelper.mjs'
- import PlansLocator from './PlansLocator.mjs'
- import { User } from '../../models/User.mjs'
- import UserGetter from '../User/UserGetter.mjs'
- import PermissionsManager from '../Authorization/PermissionsManager.mjs'
- import { sanitizeSessionUserForFrontEnd } from '../../infrastructure/FrontEndUser.mjs'
- import { z, parseReq } from '../../infrastructure/Validation.mjs'
- import SubscriptionLocator from './SubscriptionLocator.mjs'
- import { PaymentProviderSubscriptionChange } from './PaymentProviderEntities.mjs'
- const {
- DuplicateAddOnError,
- AddOnNotPresentError,
- PaymentActionRequiredError,
- PaymentFailedError,
- MissingBillingInfoError,
- MultiplePendingChangesError,
- } = Errors
- const SUBSCRIPTION_PAUSED_REDIRECT_PATH =
- '/user/subscription?redirect-reason=subscription-paused'
- /**
- * @typedef {import('../../../../types/subscription/currency').CurrencyCode} CurrencyCode
- */
- /**
- * Check if a Stripe subscription is currently paused
- * @param {Record<string, any>} subscription - The subscription object
- * @returns {Promise<boolean>}
- */
- async function _checkStripeSubscriptionPauseStatus(subscription) {
- if (
- !subscription.paymentProvider?.service?.includes('stripe') ||
- !subscription.paymentProvider.subscriptionId
- ) {
- return false
- }
- const [paymentRecord] = await Modules.promises.hooks.fire(
- 'getPaymentFromRecord',
- subscription
- )
- return !!(
- paymentRecord.subscription.remainingPauseCycles &&
- paymentRecord.subscription.remainingPauseCycles > 0
- )
- }
- /**
- * Check if a Recurly subscription is currently paused
- * @param {Record<string, any>} subscription - The subscription object
- * @returns {Promise<boolean>}
- */
- async function _checkRecurlySubscriptionPauseStatus(subscription) {
- if (!subscription.recurlySubscription_id) {
- return false
- }
- if (subscription.recurlyStatus?.state === 'paused') {
- return true
- }
- // Get the recurly subscription as this may be a pending pause
- const recurlySubscription = await RecurlyWrapper.promises.getSubscription(
- subscription.recurlySubscription_id
- )
- return !!(
- recurlySubscription.remaining_pause_cycles &&
- recurlySubscription.remaining_pause_cycles > 0
- )
- }
- /** Check if a user's subscription is manual or custom
- * @param {Record<string, any>} user - The user object
- * @returns {Promise<boolean>}
- */
- async function _isManualOrCustomSubscription(user) {
- const subscription = await SubscriptionLocator.promises.getUsersSubscription(
- user._id
- )
- if (!subscription) {
- return false
- }
- return (
- subscription.customAccount || subscription.collectionMethod === 'manual'
- )
- }
- /**
- * Check if a user's subscription is currently paused
- * @param {Record<string, any>} user - The user object
- * @returns {Promise<{isPaused: boolean, redirectPath?: string}>}
- */
- async function checkSubscriptionPauseStatus(user) {
- try {
- const { subscription } =
- await LimitationsManager.promises.userHasSubscription(user)
- if (!subscription) {
- return { isPaused: false }
- }
- const isStripePaused =
- await _checkStripeSubscriptionPauseStatus(subscription)
- if (isStripePaused) {
- return {
- isPaused: true,
- redirectPath: SUBSCRIPTION_PAUSED_REDIRECT_PATH,
- }
- }
- const isRecurlyPaused =
- await _checkRecurlySubscriptionPauseStatus(subscription)
- if (isRecurlyPaused) {
- return {
- isPaused: true,
- redirectPath: SUBSCRIPTION_PAUSED_REDIRECT_PATH,
- }
- }
- } catch (err) {
- logger.warn(
- { err, userId: user._id },
- 'Failed to check user subscription for pause status'
- )
- }
- return { isPaused: false }
- }
- /**
- * @import { SubscriptionChangeDescription } from '../../../../types/subscription/subscription-change-preview'
- * @import { SubscriptionChangePreview } from '../../../../types/subscription/subscription-change-preview'
- * @import { PaymentMethod } from './types'
- */
- const groupPlanModalOptions = Settings.groupPlanModalOptions
- function formatGroupPlansDataForDash() {
- return {
- plans: [...groupPlanModalOptions.plan_codes],
- sizes: [...groupPlanModalOptions.sizes],
- usages: [...groupPlanModalOptions.usages],
- priceByUsageTypeAndSize: JSON.parse(JSON.stringify(GroupPlansData)),
- }
- }
- /**
- * @param {any} req
- * @param {any} res
- */
- async function userSubscriptionPage(req, res) {
- const user = SessionManager.getSessionUser(req.session)
- await SplitTestHandler.promises.getAssignment(req, res, 'sharing-updates')
- await SplitTestHandler.promises.getAssignment(req, res, 'pause-subscription')
- await SplitTestHandler.promises.getAssignment(
- req,
- res,
- 'combined-user-management'
- )
- await SplitTestHandler.promises.getAssignment(req, res, 'plans-2026-phase-1')
- const groupPricingDiscount = await SplitTestHandler.promises.getAssignment(
- req,
- res,
- 'group-discount-10'
- )
- const showGroupDiscount = groupPricingDiscount.variant === 'enabled'
- const results =
- await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
- user,
- req.i18n.language
- )
- const {
- personalSubscription,
- memberGroupSubscriptions,
- managedGroupSubscriptions,
- currentInstitutionsWithLicence,
- managedInstitutions,
- managedPublishers,
- } = results
- const { hasSubscription } =
- await LimitationsManager.promises.userHasSubscription(user)
- const userCanExtendTrial = (
- await Modules.promises.hooks.fire('userCanExtendTrial', user)
- )?.[0]
- const fromPlansPage = req.query.hasSubscription
- const redirectedPaymentErrorCode = req.query.errorCode
- const isInTrial = SubscriptionHelper.isInTrial(
- personalSubscription?.payment?.trialEndsAt
- )
- const plansData =
- SubscriptionViewModelBuilder.buildPlansListForSubscriptionDash(
- personalSubscription?.plan,
- isInTrial
- )
- const host = req.headers.host
- const domain = host?.split('.')[0]
- AnalyticsManager.recordEventForSession(
- req.session,
- 'subscription-page-view',
- {
- domain,
- }
- )
- const groupPlansDataForDash = formatGroupPlansDataForDash()
- // display the Group settings button only to admins of group subscriptions with either/or the Managed Users or Group SSO feature available
- let groupSettingsEnabledFor
- try {
- const managedGroups = await async.filter(
- managedGroupSubscriptions || [],
- /** @param {any} subscription */
- async subscription => {
- const managedUsersResults = await Modules.promises.hooks.fire(
- 'hasManagedUsersFeature',
- subscription
- )
- const groupSSOResults = await Modules.promises.hooks.fire(
- 'hasGroupSSOFeature',
- subscription
- )
- const isGroupAdmin =
- (subscription.admin_id._id || subscription.admin_id).toString() ===
- user._id.toString()
- return (
- (managedUsersResults?.[0] === true ||
- groupSSOResults?.[0] === true) &&
- isGroupAdmin
- )
- }
- )
- groupSettingsEnabledFor = managedGroups.map(
- (/** @type {any} */ subscription) => subscription._id.toString()
- )
- } catch (error) {
- logger.error(
- { err: error },
- 'Failed to list groups with group settings enabled'
- )
- }
- let groupSettingsAdvertisedFor
- try {
- const managedGroups = await async.filter(
- managedGroupSubscriptions || [],
- async (/** @type {any} */ subscription) => {
- const managedUsersResults = await Modules.promises.hooks.fire(
- 'hasManagedUsersFeatureOnNonProfessionalPlan',
- subscription
- )
- const groupSSOResults = await Modules.promises.hooks.fire(
- 'hasGroupSSOFeatureOnNonProfessionalPlan',
- subscription
- )
- const isGroupAdmin =
- (subscription.admin_id._id || subscription.admin_id).toString() ===
- user._id.toString()
- const plan = PlansLocator.findLocalPlanInSettings(subscription.planCode)
- return (
- (managedUsersResults?.[0] === true ||
- groupSSOResults?.[0] === true) &&
- isGroupAdmin &&
- plan?.canUseFlexibleLicensing
- )
- }
- )
- groupSettingsAdvertisedFor = managedGroups.map(
- (/** @type {any} */ subscription) => subscription._id.toString()
- )
- } catch (error) {
- logger.error(
- { err: error },
- 'Failed to list groups with group settings enabled for advertising'
- )
- }
- const {
- isPremium: hasAiAssistViaWritefull,
- premiumSource: aiAssistViaWritefullSource,
- } = await UserGetter.promises.getWritefullData(user._id)
- const data = {
- title: 'your_subscriptions',
- plans: plansData?.plans,
- planCodesChangingAtTermEnd: plansData?.planCodesChangingAtTermEnd,
- user,
- hasSubscription,
- fromPlansPage,
- redirectedPaymentErrorCode,
- personalSubscription,
- userCanExtendTrial,
- memberGroupSubscriptions,
- managedGroupSubscriptions,
- managedInstitutions,
- managedPublishers,
- showGroupDiscount,
- currentInstitutionsWithLicence,
- canUseFlexibleLicensing:
- personalSubscription?.plan?.canUseFlexibleLicensing,
- groupPlans: groupPlansDataForDash,
- groupSettingsAdvertisedFor,
- groupSettingsEnabledFor,
- isManagedAccount: !!req.managedBy,
- userRestrictions: Array.from(req.userRestrictions || []),
- hasAiAssistViaWritefull,
- aiAssistViaWritefullSource,
- }
- res.render('subscriptions/dashboard-react', data)
- }
- /**
- * @param {any} req
- * @param {any} res
- */
- async function successfulSubscription(req, res) {
- const user = SessionManager.getSessionUser(req.session)
- if (!user) {
- throw new Error('User is not logged in')
- }
- const { personalSubscription } =
- await SubscriptionViewModelBuilder.promises.buildUsersSubscriptionViewModel(
- user,
- req.i18n.language
- )
- const postCheckoutRedirect = req.session?.postCheckoutRedirect
- if (!personalSubscription) {
- res.redirect('/user/subscription/plans')
- } else {
- const userInDb = await User.findById(user._id, {
- _id: 1,
- features: 1,
- })
- if (!userInDb) {
- throw new Error('User not found')
- }
- res.render('subscriptions/successful-subscription-react', {
- title: 'thank_you',
- personalSubscription,
- postCheckoutRedirect,
- user: {
- _id: user._id,
- features: userInDb.features,
- },
- })
- }
- }
- const pauseSubscriptionSchema = z.object({
- params: z.object({
- pauseCycles: z.coerce.number().int().max(12),
- }),
- })
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- async function pauseSubscription(req, res, next) {
- const user = SessionManager.getSessionUser(req.session)
- const { params } = parseReq(req, pauseSubscriptionSchema)
- const pauseCycles = params.pauseCycles
- if (pauseCycles < 0) {
- return HttpErrorHandler.badRequest(
- req,
- res,
- `'pauseCycles' should be a number of billing cycles to pause for, or 0 to cancel a pending pause`
- )
- }
- logger.debug(
- { userId: user._id },
- `pausing subscription for ${pauseCycles} billing cycles`
- )
- try {
- await SubscriptionHandler.promises.pauseSubscription(user, pauseCycles)
- const { subscription } =
- await LimitationsManager.promises.userHasSubscription(user)
- AnalyticsManager.recordEventForUserInBackground(
- user._id,
- 'subscription-pause-scheduled',
- {
- pause_length: pauseCycles,
- plan_code: subscription?.planCode,
- subscriptionId:
- SubscriptionHelper.getPaymentProviderSubscriptionId(subscription),
- }
- )
- return res.sendStatus(200)
- } catch (err) {
- if (err instanceof Error) {
- OError.tag(err, 'something went wrong pausing subscription', {
- user_id: user._id,
- })
- }
- return next(err)
- }
- }
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- async function resumeSubscription(req, res, next) {
- const user = SessionManager.getSessionUser(req.session)
- logger.debug({ userId: user._id }, `resuming subscription`)
- try {
- await SubscriptionHandler.promises.resumeSubscription(user)
- return res.sendStatus(200)
- } catch (err) {
- if (err instanceof Error) {
- OError.tag(err, 'something went wrong resuming subscription', {
- user_id: user._id,
- })
- }
- return next(err)
- }
- }
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- async function cancelSubscription(req, res, next) {
- const user = SessionManager.getSessionUser(req.session)
- logger.debug({ userId: user._id }, 'canceling subscription')
- try {
- await SubscriptionHandler.promises.cancelSubscription(user)
- return res.sendStatus(200)
- } catch (err) {
- OError.tag(err, 'something went wrong canceling subscription', {
- user_id: user._id,
- })
- return next(err)
- }
- }
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- * @returns {Promise<void>}
- */
- async function canceledSubscription(req, res, next) {
- return res.render('subscriptions/canceled-subscription-react', {
- title: 'subscription_canceled',
- user: sanitizeSessionUserForFrontEnd(
- SessionManager.getSessionUser(req.session)
- ),
- })
- }
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- function cancelV1Subscription(req, res, next) {
- const userId = SessionManager.getLoggedInUserId(req.session)
- logger.debug({ userId }, 'canceling v1 subscription')
- V1SubscriptionManager.cancelV1Subscription(
- userId,
- /** @param {any} err */ function (err) {
- if (err) {
- OError.tag(err, 'something went wrong canceling v1 subscription', {
- userId,
- })
- return next(err)
- }
- res.redirect('/user/subscription')
- }
- )
- }
- /**
- * @param {any} req
- * @param {any} res
- */
- async function previewAddonPurchase(req, res) {
- const user = SessionManager.getSessionUser(req.session)
- const userId = user._id
- const addOnCode = req.params.addOnCode
- const purchaseReferrer = req.query.purchaseReferrer
- const redirectedPaymentErrorCode = req.query.errorCode
- if (addOnCode !== AI_ADD_ON_CODE) {
- return HttpErrorHandler.notFound(req, res, `Unknown add-on: ${addOnCode}`)
- }
- const canUseAi = await PermissionsManager.promises.checkUserPermissions(
- user,
- ['use-ai']
- )
- if (!canUseAi) {
- return res.redirect(
- '/user/subscription?redirect-reason=ai-assist-unavailable'
- )
- }
- const isManualOrCustom = await _isManualOrCustomSubscription(user)
- if (isManualOrCustom) {
- return res.redirect(
- '/user/subscription?redirect-reason=ai-assist-unavailable'
- )
- }
- const { isPaused, redirectPath } = await checkSubscriptionPauseStatus(user)
- if (isPaused) {
- return res.redirect(redirectPath)
- }
- let paymentMethod
- try {
- /** @type {PaymentMethod[]} */
- paymentMethod = await Modules.promises.hooks.fire(
- 'getPaymentMethod',
- userId
- )
- } catch (err) {
- if (err instanceof MissingBillingInfoError) {
- // We will get MissingBillingInfoError if a manual subscription doesn't have billing info
- // but doesn't marked as manual on the Overleaf side
- logger.error(
- { err },
- 'User has no billing info, cannot preview add-on purchase'
- )
- return res.redirect(
- '/user/subscription?redirect-reason=ai-assist-unavailable'
- )
- }
- if (
- err instanceof Error &&
- err.constructor.name === 'PaymentServiceResourceNotFoundError'
- ) {
- return res.redirect('/user/subscription/plans#ai-assist')
- }
- throw err
- }
- let subscriptionChange
- try {
- subscriptionChange =
- await SubscriptionHandler.promises.previewAddonPurchase(userId, addOnCode)
- const { isPremium: hasAiAssistViaWritefull } =
- await UserGetter.promises.getWritefullData(userId)
- const isAiUpgrade = subscriptionChangeIsAiAssistUpgrade(subscriptionChange)
- if (hasAiAssistViaWritefull && isAiUpgrade) {
- return res.redirect(
- '/user/subscription?redirect-reason=writefull-entitled'
- )
- }
- } catch (err) {
- if (err instanceof DuplicateAddOnError) {
- return res.redirect('/user/subscription?redirect-reason=double-buy')
- }
- if (
- err instanceof Error &&
- err.constructor.name === 'PaymentServiceResourceNotFoundError'
- ) {
- return res.redirect('/user/subscription/plans#ai-assist')
- }
- throw err
- }
- const subscription = subscriptionChange.subscription
- const addOn = await RecurlyClient.promises.getAddOn(
- subscription.planCode,
- addOnCode
- )
- /** @type {SubscriptionChangePreview} */
- const changePreview = makeChangePreview(
- {
- type: 'add-on-purchase',
- addOn: {
- code: addOn.code,
- name: addOn.name,
- },
- },
- subscriptionChange,
- paymentMethod[0]
- )
- res.render('subscriptions/preview-change', {
- changePreview,
- purchaseReferrer,
- redirectedPaymentErrorCode,
- })
- }
- const purchaseAddonSchema = z.object({
- params: z.object({
- addOnCode: z.string(),
- }),
- })
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- async function purchaseAddon(req, res, next) {
- const user = SessionManager.getSessionUser(req.session)
- const { params } = parseReq(req, purchaseAddonSchema)
- const addOnCode = params.addOnCode
- // currently we only support having a quantity of 1
- const quantity = 1
- // currently we only support one add-on, the Ai add-on
- if (addOnCode !== AI_ADD_ON_CODE) {
- return res.sendStatus(404)
- }
- const { isPaused } = await checkSubscriptionPauseStatus(user)
- if (isPaused) {
- return HttpErrorHandler.badRequest(
- req,
- res,
- 'Cannot purchase add-ons while subscription is paused.'
- )
- }
- logger.debug({ userId: user._id, addOnCode }, 'purchasing add-ons')
- try {
- await SubscriptionHandler.promises.purchaseAddon(
- user._id,
- addOnCode,
- quantity
- )
- } catch (err) {
- if (err instanceof DuplicateAddOnError) {
- HttpErrorHandler.badRequest(
- req,
- res,
- 'Your subscription already includes this add-on',
- { addon: addOnCode }
- )
- } else if (err instanceof PaymentActionRequiredError) {
- logger.debug(
- { userId: user._id },
- 'Customer needs to perform payment action to complete transaction'
- )
- return res.status(402).json({
- message: 'Payment action required',
- clientSecret: /** @type {any} */ (err).info.clientSecret,
- publicKey: /** @type {any} */ (err).info.publicKey,
- })
- } else if (err instanceof PaymentFailedError) {
- logger.debug(
- {
- userId: user._id,
- reason: /** @type {any} */ (err).info.reason,
- adviceCode: /** @type {any} */ (err).info.adviceCode,
- },
- 'Payment failed for transaction'
- )
- return res.status(402).json({
- message: 'Payment failed',
- reason: /** @type {any} */ (err).info.reason,
- adviceCode: /** @type {any} */ (err).info.adviceCode,
- })
- } else if (err instanceof MultiplePendingChangesError) {
- logger.warn(
- { userId: user._id, err, addOnCode },
- 'Cannot purchase add-on: multiple pending changes'
- )
- return res.status(422).json({
- code: 'multiple_pending_changes',
- message:
- 'Cannot complete purchase while there are multiple pending subscription changes. Please contact support.',
- })
- } else {
- if (err instanceof Error) {
- OError.tag(err, 'something went wrong purchasing add-ons', {
- user_id: user._id,
- addOnCode,
- })
- }
- return next(err)
- }
- }
- try {
- await FeaturesUpdater.promises.refreshFeatures(user._id, 'add-on-purchase')
- } catch (err) {
- logger.error({ err }, 'Failed to refresh features after add-on purchase')
- }
- return res.sendStatus(200)
- }
- const removeAddonSchema = z.object({
- params: z.object({
- addOnCode: z.string(),
- }),
- })
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- async function removeAddon(req, res, next) {
- const user = SessionManager.getSessionUser(req.session)
- const { params } = parseReq(req, removeAddonSchema)
- const addOnCode = params.addOnCode
- if (addOnCode !== AI_ADD_ON_CODE) {
- return res.sendStatus(404)
- }
- logger.debug({ userId: user._id, addOnCode }, 'removing add-ons')
- try {
- await SubscriptionHandler.promises.removeAddon(user, addOnCode)
- res.sendStatus(200)
- } catch (err) {
- if (err instanceof AddOnNotPresentError) {
- HttpErrorHandler.badRequest(
- req,
- res,
- 'Your subscription does not contain the requested add-on',
- { addon: addOnCode }
- )
- } else if (err instanceof MultiplePendingChangesError) {
- logger.warn(
- { userId: user._id, err, addOnCode },
- 'Cannot remove add-on: multiple pending changes'
- )
- return res.status(422).json({
- code: 'multiple_pending_changes',
- message:
- 'Cannot remove add-on while there are multiple pending subscription changes. Please contact support.',
- })
- } else {
- if (err instanceof Error) {
- OError.tag(err, 'something went wrong removing add-ons', {
- user_id: user._id,
- addOnCode,
- })
- }
- return next(err)
- }
- }
- }
- const reactivateAddonSchema = z.object({
- params: z.object({
- addOnCode: z.string(),
- }),
- })
- /**
- * Reactivate an add-on pending cancellation
- *
- * This "cancels" the cancellation.
- * @param {any} req
- * @param {any} res
- */
- async function reactivateAddon(req, res) {
- const user = SessionManager.getSessionUser(req.session)
- const { params } = parseReq(req, reactivateAddonSchema)
- const addOnCode = params.addOnCode
- if (addOnCode !== AI_ADD_ON_CODE) {
- return res.sendStatus(404)
- }
- try {
- await SubscriptionHandler.promises.reactivateAddon(user._id, addOnCode)
- res.sendStatus(200)
- } catch (err) {
- if (err instanceof AddOnNotPresentError) {
- HttpErrorHandler.badRequest(
- req,
- res,
- 'The requested add-on is not pending cancellation',
- { addon: addOnCode }
- )
- } else {
- throw err
- }
- }
- }
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- async function previewSubscription(req, res, next) {
- const planCode = req.query.planCode
- if (!planCode) {
- return HttpErrorHandler.notFound(req, res, 'Missing plan code')
- }
- // TODO: use PaymentService to fetch plan information
- const plan = await RecurlyClient.promises.getPlan(planCode)
- const user = SessionManager.getSessionUser(req.session)
- const userId = user?._id
- let trialDisabledReason
- if (planCode.includes('_free_trial')) {
- const trialEligibility = (
- await Modules.promises.hooks.fire('userCanStartTrial', user)
- )?.[0]
- if (!trialEligibility.canStartTrial) {
- trialDisabledReason = trialEligibility.disabledReason
- }
- }
- const subscriptionChange =
- await SubscriptionHandler.promises.previewSubscriptionChange(
- userId,
- planCode
- )
- /** @type {PaymentMethod[]} */
- const paymentMethod = await Modules.promises.hooks.fire(
- 'getPaymentMethod',
- userId
- )
- const changePreview = makeChangePreview(
- {
- type: 'premium-subscription',
- plan: { code: plan.code, name: plan.name },
- },
- subscriptionChange,
- paymentMethod[0]
- )
- res.render('subscriptions/preview-change', {
- changePreview,
- redirectedPaymentErrorCode: req.query.errorCode,
- trialDisabledReason,
- })
- }
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- function cancelPendingSubscriptionChange(req, res, next) {
- const user = SessionManager.getSessionUser(req.session)
- logger.debug({ userId: user._id }, 'canceling pending subscription change')
- SubscriptionHandler.cancelPendingSubscriptionChange(
- user,
- /** @param {any} err */ function (err) {
- if (err) {
- OError.tag(
- err,
- 'something went wrong canceling pending subscription change',
- {
- user_id: user._id,
- }
- )
- return next(err)
- }
- res.redirect('/user/subscription')
- }
- )
- }
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- async function updateAccountEmailAddress(req, res, next) {
- const user = SessionManager.getSessionUser(req.session)
- try {
- await Modules.promises.hooks.fire(
- 'updateAccountEmailAddress',
- user._id,
- user.email
- )
- return res.sendStatus(200)
- } catch (error) {
- return next(error)
- }
- }
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- function reactivateSubscription(req, res, next) {
- const user = SessionManager.getSessionUser(req.session)
- logger.debug({ userId: user._id }, 'reactivating subscription')
- try {
- if (req.isManagedGroupAdmin) {
- // allow admins to reactivate subscriptions
- } else {
- // otherwise require the user to have the reactivate-subscription permission
- req.assertPermission('reactivate-subscription')
- }
- } catch (error) {
- return next(error)
- }
- SubscriptionHandler.reactivateSubscription(user, function (err) {
- if (err) {
- OError.tag(err, 'something went wrong reactivating subscription', {
- user_id: user._id,
- })
- return next(err)
- }
- res.redirect('/user/subscription')
- })
- }
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- function recurlyCallback(req, res, next) {
- logger.debug({ data: req.body }, 'received recurly callback')
- const event = Object.keys(req.body)[0]
- const eventData = req.body[event]
- RecurlyEventHandler.sendRecurlyAnalyticsEvent(event, eventData).catch(error =>
- logger.error(
- { err: error },
- 'Failed to process analytics event on Recurly webhook'
- )
- )
- if (
- [
- 'new_subscription_notification',
- 'updated_subscription_notification',
- 'expired_subscription_notification',
- 'subscription_paused_notification',
- 'subscription_resumed_notification',
- ].includes(event)
- ) {
- const recurlySubscription = eventData.subscription
- SubscriptionHandler.syncSubscription(
- recurlySubscription,
- { ip: req.ip },
- function (err) {
- if (err) {
- return next(err)
- }
- res.sendStatus(200)
- }
- )
- } else if (event === 'billing_info_updated_notification') {
- const recurlyAccountCode = eventData.account.account_code
- SubscriptionHandler.attemptPaypalInvoiceCollection(
- recurlyAccountCode,
- function (err) {
- if (err) {
- return next(err)
- }
- res.sendStatus(200)
- }
- )
- } else {
- res.sendStatus(200)
- }
- }
- /**
- * @param {any} req
- * @param {any} res
- */
- async function extendTrial(req, res) {
- const user = SessionManager.getSessionUser(req.session)
- const { subscription } =
- await LimitationsManager.promises.userHasSubscription(user)
- const allowed = (
- await Modules.promises.hooks.fire('userCanExtendTrial', user)
- )?.[0]
- if (!allowed) {
- logger.warn({ userId: user._id }, 'user can not extend trial')
- return res.sendStatus(403)
- }
- try {
- await SubscriptionHandler.promises.extendTrial(subscription, 14)
- AnalyticsManager.recordEventForSession(
- req.session,
- 'subscription-trial-extended'
- )
- } catch (error) {
- return res.sendStatus(500)
- }
- res.sendStatus(200)
- }
- /**
- * @param {any} req
- * @param {any} res
- * @param {any} next
- */
- function recurlyNotificationParser(req, res, next) {
- let xml = ''
- req.on('data', /** @param {any} chunk */ chunk => (xml += chunk))
- req.on('end', () =>
- RecurlyWrapper._parseXml(
- xml,
- /**
- * @param {any} error
- * @param {any} body
- */
- function (error, body) {
- if (error) {
- return next(error)
- }
- req.body = body
- next()
- }
- )
- )
- }
- /**
- * @param {any} req
- * @param {any} res
- */
- async function refreshUserFeatures(req, res) {
- const { user_id: userId } = req.params
- await FeaturesUpdater.promises.refreshFeatures(userId, 'acceptance-test')
- res.sendStatus(200)
- }
- /**
- * @param {any} req
- * @param {any} res
- * @returns {Promise<{currency: CurrencyCode, recommendedCurrency: CurrencyCode, countryCode: string|undefined}>}
- */
- async function getRecommendedCurrency(req, res) {
- const userId = SessionManager.getLoggedInUserId(req.session)
- let ip = req.ip
- if (
- req.query?.ip &&
- (await AuthorizationManager.promises.isUserSiteAdmin(userId))
- ) {
- ip = req.query.ip
- }
- const currencyLookup = await GeoIpLookup.promises.getCurrencyCode(ip)
- const countryCode = currencyLookup.countryCode
- const recommendedCurrency = currencyLookup.currencyCode
- let currency = null
- const queryCurrency = req.query.currency?.toUpperCase()
- if (queryCurrency && GeoIpLookup.isValidCurrencyParam(queryCurrency)) {
- currency = queryCurrency
- } else if (recommendedCurrency) {
- currency = recommendedCurrency
- }
- return {
- currency,
- recommendedCurrency,
- countryCode,
- }
- }
- /**
- * @param {any} req
- * @param {any} res
- */
- async function getLatamCountryBannerDetails(req, res) {
- const userId = SessionManager.getLoggedInUserId(req.session)
- let ip = req.ip
- if (
- req.query?.ip &&
- (await AuthorizationManager.promises.isUserSiteAdmin(userId))
- ) {
- ip = req.query.ip
- }
- const currencyLookup = await GeoIpLookup.promises.getCurrencyCode(ip)
- const countryCode = currencyLookup.countryCode
- const latamCountryBannerDetails = {}
- switch (countryCode) {
- case `MX`:
- latamCountryBannerDetails.latamCountryFlag = '🇲🇽'
- latamCountryBannerDetails.country = 'Mexico'
- latamCountryBannerDetails.discount = '25%'
- latamCountryBannerDetails.currency = 'Mexican Pesos'
- break
- case `CO`:
- latamCountryBannerDetails.latamCountryFlag = '🇨🇴'
- latamCountryBannerDetails.country = 'Colombia'
- latamCountryBannerDetails.discount = '60%'
- latamCountryBannerDetails.currency = 'Colombian Pesos'
- break
- case `CL`:
- latamCountryBannerDetails.latamCountryFlag = '🇨🇱'
- latamCountryBannerDetails.country = 'Chile'
- latamCountryBannerDetails.discount = '30%'
- latamCountryBannerDetails.currency = 'Chilean Pesos'
- break
- case `PE`:
- latamCountryBannerDetails.latamCountryFlag = '🇵🇪'
- latamCountryBannerDetails.country = 'Peru'
- latamCountryBannerDetails.currency = 'Peruvian Soles'
- latamCountryBannerDetails.discount = '40%'
- break
- }
- return latamCountryBannerDetails
- }
- /**
- * There are two sets of group plans: legacy plans and consolidated plans,
- * and their naming conventions differ.
- * This helper method computes the name of legacy group plans to ensure
- * consistency with the naming of consolidated group plans.
- *
- * @param {string} planName
- * @param {string} planCode
- * @return {string}
- */
- function getPlanNameForDisplay(planName, planCode) {
- const match = planCode.match(
- /^group_(collaborator|professional)_\d+_(enterprise|educational)$/
- )
- if (!match) return planName
- const [, type, category] = match
- const prefix = type === 'collaborator' ? 'Standard' : 'Professional'
- const suffix = category === 'educational' ? ' Educational' : ''
- return `Overleaf ${prefix} Group${suffix}`
- }
- /**
- * Build a subscription change preview for display purposes
- *
- * @param {SubscriptionChangeDescription} subscriptionChangeDescription A description of the change for the frontend
- * @param {PaymentProviderSubscriptionChange} subscriptionChange The subscription change object coming from Recurly
- * @param {PaymentMethod} [paymentMethod] The payment method associated to the user
- * @return {SubscriptionChangePreview}
- */
- function makeChangePreview(
- subscriptionChangeDescription,
- subscriptionChange,
- paymentMethod
- ) {
- const subscription = subscriptionChange.subscription
- // For the future invoice display, if there's a pending change scheduled,
- // we should show what will happen at renewal (the pending change state)
- // merged with any new changes from this immediate update
- const pendingChange = subscription.pendingChange
- let futureInvoiceChange
- if (pendingChange) {
- const pendingAddOnCodes = new Set(pendingChange.nextAddOns.map(a => a.code))
- const mergedAddOns = [...pendingChange.nextAddOns]
- for (const addOn of subscriptionChange.nextAddOns) {
- if (!pendingAddOnCodes.has(addOn.code)) {
- mergedAddOns.push(addOn)
- }
- }
- futureInvoiceChange = new PaymentProviderSubscriptionChange({
- subscription,
- nextPlanCode: pendingChange.nextPlanCode,
- nextPlanName: pendingChange.nextPlanName,
- nextPlanPrice: pendingChange.nextPlanPrice,
- nextAddOns: mergedAddOns,
- })
- } else {
- futureInvoiceChange = subscriptionChange
- }
- const nextPlan = PlansLocator.findLocalPlanInSettings(
- futureInvoiceChange.nextPlanCode
- )
- return {
- change: subscriptionChangeDescription,
- currency: subscription.currency,
- immediateCharge: { ...subscriptionChange.immediateCharge },
- paymentMethod: paymentMethod?.toString(),
- netTerms: subscription.netTerms,
- nextPlan: {
- annual: nextPlan?.annual ?? false,
- },
- nextInvoice: {
- date: subscription.periodEnd.toISOString(),
- plan: {
- name: getPlanNameForDisplay(
- futureInvoiceChange.nextPlanName,
- futureInvoiceChange.nextPlanCode
- ),
- amount: futureInvoiceChange.nextPlanPrice,
- },
- addOns: futureInvoiceChange.nextAddOns.map(addOn => ({
- code: addOn.code,
- name: addOn.name,
- quantity: addOn.quantity,
- unitAmount: addOn.unitPrice,
- amount: addOn.preTaxTotal,
- })),
- subtotal: futureInvoiceChange.subtotal,
- tax: {
- rate: subscription.taxRate,
- amount: futureInvoiceChange.tax,
- },
- total: futureInvoiceChange.total,
- },
- }
- }
- export default {
- userSubscriptionPage: expressify(userSubscriptionPage),
- successfulSubscription: expressify(successfulSubscription),
- cancelSubscription,
- pauseSubscription,
- resumeSubscription,
- canceledSubscription: expressify(canceledSubscription),
- cancelV1Subscription,
- previewSubscription: expressify(previewSubscription),
- cancelPendingSubscriptionChange,
- updateAccountEmailAddress: expressify(updateAccountEmailAddress),
- reactivateSubscription,
- recurlyCallback,
- extendTrial: expressify(extendTrial),
- recurlyNotificationParser,
- refreshUserFeatures: expressify(refreshUserFeatures),
- previewAddonPurchase: expressify(previewAddonPurchase),
- purchaseAddon,
- removeAddon,
- reactivateAddon,
- makeChangePreview,
- getRecommendedCurrency,
- getLatamCountryBannerDetails,
- getPlanNameForDisplay,
- checkSubscriptionPauseStatus,
- }
|