Merge pull request #26934 from overleaf/ls-support-individual-to-group-plan-upgrade

Support individual to group plan upgrade in Stripe

GitOrigin-RevId: 24cbe7bd6de86a4d9410e1abc49b6457e0871f40
This commit is contained in:
Liangjun Song
2025-07-16 08:05:20 +00:00
committed by Copybot
parent 1375f695d3
commit 9e22ed9c3f
12 changed files with 364 additions and 91 deletions
@@ -94,7 +94,7 @@ class PaymentProviderSubscription {
* @return {boolean}
*/
isGroupSubscription() {
return isGroupPlanCode(this.planCode)
return PlansLocator.isGroupPlanCode(this.planCode)
}
/**
@@ -118,33 +118,32 @@ class PaymentProviderSubscription {
/**
* Change this subscription's plan
*
* @param {string} planCode - the new plan code
* @param {number} [quantity] - the quantity of the plan
* @param {boolean} [shouldChangeAtTermEnd] - whether the change should be applied at the end of the term
* @return {PaymentProviderSubscriptionChangeRequest}
*/
getRequestForPlanChange(planCode) {
const currentPlan = PlansLocator.findLocalPlanInSettings(this.planCode)
if (currentPlan == null) {
throw new OError('Unable to find plan in settings', {
planCode: this.planCode,
})
}
const newPlan = PlansLocator.findLocalPlanInSettings(planCode)
if (newPlan == null) {
throw new OError('Unable to find plan in settings', { planCode })
}
const isInTrial = SubscriptionHelper.isInTrial(this.trialPeriodEnd)
const shouldChangeAtTermEnd = SubscriptionHelper.shouldPlanChangeAtTermEnd(
currentPlan,
newPlan,
isInTrial
)
getRequestForPlanChange(planCode, quantity, shouldChangeAtTermEnd) {
const changeRequest = new PaymentProviderSubscriptionChangeRequest({
subscription: this,
timeframe: shouldChangeAtTermEnd ? 'term_end' : 'now',
planCode,
})
if (quantity !== 1) {
// Only group plans in Stripe can have larger than 1 quantity
// This is because in Stripe, the group plans are configued with per-seat pricing
// and the quantity is the number of seats
// Setting the members limit add-on quantity accordingly
// so it is compitible with Recurly's group plan model (1 base plan + add-on for each member)
changeRequest.addOnUpdates = [
new PaymentProviderSubscriptionAddOnUpdate({
code: MEMBERS_LIMIT_ADD_ON_CODE,
quantity,
}),
]
}
// Carry the AI add-on to the new plan if applicable
if (
this.isStandaloneAiAddOn() ||
@@ -155,7 +154,9 @@ class PaymentProviderSubscription {
code: AI_ADD_ON_CODE,
quantity: 1,
})
changeRequest.addOnUpdates = [addOnUpdate]
changeRequest.addOnUpdates = changeRequest.addOnUpdates
? [...changeRequest.addOnUpdates, addOnUpdate]
: [addOnUpdate]
}
return changeRequest
@@ -360,6 +361,31 @@ class PaymentProviderSubscription {
get isCollectionMethodManual() {
return this.collectionMethod === 'manual'
}
/**
* Determine if a plan change should be applied at the end of the term
*
* @param {string} newPlanCode
* @returns {boolean}
*/
shouldPlanChangeAtTermEnd(newPlanCode) {
const currentPlan = PlansLocator.findLocalPlanInSettings(this.planCode)
if (currentPlan == null) {
throw new OError('Unable to find plan in settings', {
planCode: this.planCode,
})
}
const newPlan = PlansLocator.findLocalPlanInSettings(newPlanCode)
if (newPlan == null) {
throw new OError('Unable to find plan in settings', { newPlanCode })
}
const isInTrial = SubscriptionHelper.isInTrial(this.trialPeriodEnd)
return SubscriptionHelper.shouldPlanChangeAtTermEnd(
currentPlan,
newPlan,
isInTrial
)
}
}
/**
@@ -584,15 +610,6 @@ class PaymentProviderAccount {
}
}
/**
* Returns whether the given plan code is a group plan
*
* @param {string} planCode
*/
function isGroupPlanCode(planCode) {
return planCode.includes('group')
}
module.exports = {
MEMBERS_LIMIT_ADD_ON_CODE,
PaymentProviderSubscription,
@@ -607,6 +624,5 @@ module.exports = {
PaymentProviderPlan,
PaymentProviderCoupon,
PaymentProviderAccount,
isGroupPlanCode,
PaymentProviderImmediateCharge,
}
@@ -137,9 +137,47 @@ function findLocalPlanInSettings(planCode) {
return null
}
/**
* Returns whether the given plan code is a group plan
*
* @param {string} planCode
*/
function isGroupPlanCode(planCode) {
return planCode.includes('group')
}
/**
* Adapts a legacy Recurly group plan code (e.g., `group_professional_5_educational`)
* into its corresponding Stripe-compatible plan code (e.g., `group_professional_educational`),
* extracting the license quantity where applicable.
*
* @param {RecurlyPlanCode} planCode
* @returns {{ planCode: RecurlyPlanCode, quantity: number }}
*/
function convertLegacyGroupPlanCodeToConsolidatedGroupPlanCodeIfNeeded(
planCode
) {
const pattern =
/^group_(collaborator|professional)_(2|3|4|5|10|20|50)_(educational|enterprise)$/
const match = planCode.match(pattern)
if (match == null) {
return { planCode, quantity: 1 }
}
const [, tier, size, usage] = match
const newPlanCode = /** @type {RecurlyPlanCode} */ (
usage === 'enterprise' ? `group_${tier}` : `group_${tier}_${usage}`
)
return { planCode: newPlanCode, quantity: Number(size) }
}
module.exports = {
ensurePlansAreSetupCorrectly,
findLocalPlanInSettings,
buildStripeLookupKey,
getPlanTypeAndPeriodFromRecurlyPlanCode,
isGroupPlanCode,
convertLegacyGroupPlanCodeToConsolidatedGroupPlanCodeIfNeeded,
}
@@ -425,6 +425,21 @@ async function subtotalLimitExceeded(req, res) {
}
}
async function getGroupPlanPerUserPrices(req, res) {
try {
const userId = SessionManager.getLoggedInUserId(req.session)
const prices = await Modules.promises.hooks.fire(
'getGroupPlanPerUserPrices',
userId,
req.query.currency
)
return res.json(prices[0])
} catch (error) {
logger.err({ error }, 'error trying to get websale group product prices')
return res.sendStatus(500)
}
}
export default {
removeUserFromGroup: expressify(removeUserFromGroup),
removeSelfFromGroup: expressify(removeSelfFromGroup),
@@ -441,4 +456,5 @@ export default {
missingBillingInformation: expressify(missingBillingInformation),
manuallyCollectedSubscription: expressify(manuallyCollectedSubscription),
subtotalLimitExceeded: expressify(subtotalLimitExceeded),
getGroupPlanPerUserPrices: expressify(getGroupPlanPerUserPrices),
}
@@ -106,6 +106,13 @@ export default {
SubscriptionGroupController.subscriptionUpgradePage
)
webRouter.get(
'/user/subscription/group/group-plan-per-user-prices',
AuthenticationController.requireLogin(),
RateLimiterMiddleware.rateLimit(subscriptionRateLimiter),
SubscriptionGroupController.getGroupPlanPerUserPrices
)
webRouter.post(
'/user/subscription/group/upgrade-subscription',
AuthenticationController.requireLogin(),
@@ -34,6 +34,20 @@ function serializeMongooseObject(object) {
: object
}
async function isEligibleForGroupPlan(service, isInTrial) {
if (isInTrial) {
return false
}
if (service === 'recurly') {
return true
}
const [result] = await Modules.promises.hooks.fire(
'canUpgradeFromIndividualToGroup'
)
return result
}
async function buildUsersSubscriptionViewModel(user, locale = 'en') {
let {
personalSubscription,
@@ -112,9 +126,7 @@ async function buildUsersSubscriptionViewModel(user, locale = 'en') {
_id: group._id,
planCode: group.planCode,
teamName: group.teamName,
admin_id: {
email: group.admin_id.email,
},
admin_id: { email: group.admin_id.email },
userIsGroupManager,
}
@@ -141,10 +153,7 @@ async function buildUsersSubscriptionViewModel(user, locale = 'en') {
planCode: group.planCode,
groupPlan: group.groupPlan,
teamName: group.teamName,
admin_id: {
_id: group.admin_id._id,
email: group.admin_id.email,
},
admin_id: { _id: group.admin_id._id, email: group.admin_id.email },
features: group.features,
userIsGroupMember,
}
@@ -221,6 +230,8 @@ async function buildUsersSubscriptionViewModel(user, locale = 'en') {
if (personalSubscription && paymentRecord && paymentRecord.subscription) {
// don't return subscription payment information
personalSubscription.service =
personalSubscription.paymentProvider?.service ?? 'recurly'
delete personalSubscription.paymentProvider
delete personalSubscription.recurly
delete personalSubscription.recurlySubscription_id
@@ -277,8 +288,10 @@ async function buildUsersSubscriptionViewModel(user, locale = 'en') {
!isInTrial &&
!paymentRecord.subscription.planCode.includes('ann') &&
!paymentRecord.subscription.addOns?.length > 0,
isEligibleForGroupPlan:
paymentRecord.subscription.service === 'recurly' && !isInTrial,
isEligibleForGroupPlan: await isEligibleForGroupPlan(
paymentRecord.subscription.service,
isInTrial
),
}
const isMonthlyCollaboratorPlan =
@@ -405,9 +418,7 @@ async function getUsersSubscriptionDetails(user) {
individualSubscription =
await SubscriptionLocator.promises.getUsersSubscription(user)
}
let bestSubscription = {
type: 'free',
}
let bestSubscription = { type: 'free' }
if (currentInstitutionsWithLicence?.length) {
for (const institutionMembership of currentInstitutionsWithLicence) {
const plan = PlansLocator.findLocalPlanInSettings(
@@ -601,8 +612,5 @@ module.exports = {
buildUsersSubscriptionViewModel: callbackify(buildUsersSubscriptionViewModel),
buildPlansList,
buildPlansListForSubscriptionDash,
promises: {
buildUsersSubscriptionViewModel,
getUsersSubscriptionDetails,
},
promises: { buildUsersSubscriptionViewModel, getUsersSubscriptionDetails },
}