From f4cd4960e5da2e9f4a4a768ff338e276c7887ef3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 11:24:40 -0800 Subject: [PATCH 1/4] fix(billing): release audit follow-ups for v0.9.66 - migrations 0471, 0473 and 0474 are replay-safe after 0470's embedded COMMIT - a Team upgrade is refused while the personal Pro plan is still trialing - ending a trial early never starts a past-due plan on a declined card, and refuses a cancelled trial - a credit balance that can't be read fails a hosted-key run as a fault, not as the free plan, so a schedule is not disabled for it - the Web Search refusal no longer offers BYOK, which Search does not support - annual seat-months advance only from the count they were computed from, so racing syncs cannot rebase twice - a plan switch keeps the headroom read before Stripe applied it, and records the period Stripe restarted on an interval change - payment-succeeded skips the open-invoice listing for an unblocked payer - reuse formatMonthlyPlanPrice, AVERAGE_MONTH_MS and the deletion's owner id; parallel independent reads --- apps/sim/app/api/billing/switch-plan/route.ts | 22 ++++++- .../settings/components/billing/billing.tsx | 12 +--- apps/sim/hooks/queries/subscription.ts | 2 +- apps/sim/lib/api-key/byok.ts | 6 +- apps/sim/lib/auth/auth.ts | 2 +- apps/sim/lib/billing/application/pro-trial.ts | 29 +++++++-- apps/sim/lib/billing/authorization.ts | 27 +++++++- apps/sim/lib/billing/constants.ts | 3 + apps/sim/lib/billing/core/chat-access.ts | 8 ++- .../sim/lib/billing/core/hosted-key-access.ts | 19 ++++-- apps/sim/lib/billing/core/plan-switch.ts | 63 ++++++++++++++++--- apps/sim/lib/billing/core/usage.ts | 39 ++++++------ apps/sim/lib/billing/cycle-close.ts | 4 +- apps/sim/lib/billing/free-plan.integration.ts | 40 ++++++++++-- apps/sim/lib/billing/organization.ts | 45 ++++++++++--- .../lib/billing/plan-allowance.integration.ts | 35 +++++++++++ .../lib/billing/subscriptions/utils.test.ts | 8 --- apps/sim/lib/billing/trial.integration.ts | 19 ++++++ .../sim/lib/billing/webhooks/invoices.test.ts | 6 ++ apps/sim/lib/billing/webhooks/invoices.ts | 42 ++++++++----- apps/sim/lib/billing/webhooks/plan-notices.ts | 33 ++++------ apps/sim/lib/billing/webhooks/subscription.ts | 2 +- apps/sim/lib/internal/search/execute-tool.ts | 2 +- .../workflows/schedules/disable-reasons.ts | 2 +- apps/sim/tools/index.test.ts | 4 +- .../db/migrations/0471_pro_trial_card.sql | 10 ++- .../migrations/0473_enterprise_self_serve.sql | 24 ++++--- .../migrations/0474_annual_seat_allowance.sql | 8 ++- 28 files changed, 380 insertions(+), 136 deletions(-) diff --git a/apps/sim/app/api/billing/switch-plan/route.ts b/apps/sim/app/api/billing/switch-plan/route.ts index 6edfb2efa7e..aa702812b02 100644 --- a/apps/sim/app/api/billing/switch-plan/route.ts +++ b/apps/sim/app/api/billing/switch-plan/route.ts @@ -12,7 +12,7 @@ import { getHighestPriorityPersonalSubscription, getHighestPrioritySubscription, } from '@/lib/billing/core/plan' -import { recordPlanSwitch } from '@/lib/billing/core/plan-switch' +import { readPoolUsageLimit, recordPlanSwitch } from '@/lib/billing/core/plan-switch' import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers' import { getPlanByName } from '@/lib/billing/plans' import { requireStripeClient } from '@/lib/billing/stripe-client' @@ -178,10 +178,17 @@ export const POST = withRouteHandler(async (request: NextRequest) => { targetPriceId, }) + const orgScoped = await isSubscriptionOrgScoped(sub) + // Read before Stripe applies the switch: its webhook can move the live limit first. + const previousLimit = await readPoolUsageLimit({ + type: orgScoped ? 'organization' : 'user', + id: sub.referenceId, + }) + let period: { start: Date; end: Date } | undefined if (!alreadyOnStripePrice) { const currentQuantity = subscriptionItem.quantity ?? 1 - await stripe.subscriptions.update(sub.stripeSubscriptionId, { + const updated = await stripe.subscriptions.update(sub.stripeSubscriptionId, { items: [ { id: subscriptionItem.id, @@ -191,13 +198,22 @@ export const POST = withRouteHandler(async (request: NextRequest) => { ], proration_behavior: 'always_invoice', }) + const switchedItem = updated.items.data.find((item) => item.id === subscriptionItem.id) + if (switchedItem) { + period = { + start: new Date(switchedItem.current_period_start * 1000), + end: new Date(switchedItem.current_period_end * 1000), + } + } } await recordPlanSwitch({ subscription: sub, targetPlanName, targetInterval: targetInterval as 'month' | 'year', - orgScoped: await isSubscriptionOrgScoped(sub), + orgScoped, + period, + previousLimit, }) logger.info('Subscription switched successfully', { diff --git a/apps/sim/app/workspace/[workspaceId]/settings/components/billing/billing.tsx b/apps/sim/app/workspace/[workspaceId]/settings/components/billing/billing.tsx index 4161cb274dc..384a7ed4749 100644 --- a/apps/sim/app/workspace/[workspaceId]/settings/components/billing/billing.tsx +++ b/apps/sim/app/workspace/[workspaceId]/settings/components/billing/billing.tsx @@ -19,7 +19,7 @@ import { getErrorMessage } from '@sim/utils/errors' import { formatDate } from '@sim/utils/formatting' import { useRouter } from 'next/navigation' import { useSession, useSubscription } from '@/lib/auth/client' -import { ANNUAL_DISCOUNT_RATE, ON_DEMAND_UNLIMITED } from '@/lib/billing/constants' +import { ON_DEMAND_UNLIMITED } from '@/lib/billing/constants' import { formatCreditCost } from '@/lib/billing/credits/conversion' import { getCoveredUsage, @@ -28,6 +28,7 @@ import { isOnDemandOffDisabled, } from '@/lib/billing/on-demand' import { + formatMonthlyPlanPrice, getDisplayPlanName, getPlanTierDollars, isEnterprise, @@ -84,13 +85,6 @@ const INVOICE_STATUS_BADGES: Record = { void: { variant: 'gray', label: 'Void' }, } -/** A plan's effective monthly price: the annual price spread over twelve months on annual billing. */ -function formatMonthlyPrice(plan: string, billingInterval: string | undefined): string { - const monthly = - getPlanTierDollars(plan) * (billingInterval === 'year' ? 1 - ANNUAL_DISCOUNT_RATE : 1) - return `$${Number.isInteger(monthly) ? monthly : monthly.toFixed(2)}` -} - function getPeriodEndLabel(isCancelledAtPeriodEnd: boolean, isTrialing: boolean): string { if (isCancelledAtPeriodEnd) return 'Access until' if (isTrialing) return 'Free trial ends' @@ -498,7 +492,7 @@ export function Billing({ scope, organizationId, creditUsageHref }: BillingProps ? 'Choose a new plan for this organization' : subscription.isEnterprise ? 'Custom pricing' - : `${formatMonthlyPrice(subscription.plan, billingInterval)}${isOrganizationScope ? ' per user' : ''}/month, ${billingPeriod}` + : `${formatMonthlyPlanPrice(getPlanTierDollars(subscription.plan), billingInterval === 'year')}${isOrganizationScope ? ' per user' : ''}/month, ${billingPeriod}` const periodEnd = isOrganizationScope ? (organizationBilling?.billingPeriodEnd ?? null) diff --git a/apps/sim/hooks/queries/subscription.ts b/apps/sim/hooks/queries/subscription.ts index 3c49be5f8ef..3bae633d91e 100644 --- a/apps/sim/hooks/queries/subscription.ts +++ b/apps/sim/hooks/queries/subscription.ts @@ -228,7 +228,7 @@ export function useEndProTrial() { const queryClient = useQueryClient() return useMutation({ mutationFn: () => requestJson(billingEndTrialContract, { body: {} }), - onSettled: () => + onSuccess: () => Promise.all([ queryClient.invalidateQueries({ queryKey: subscriptionKeys.all }), invalidateWorkspaceUsage(queryClient), diff --git a/apps/sim/lib/api-key/byok.ts b/apps/sim/lib/api-key/byok.ts index 0eb5eb3d7b3..30cd02e0a00 100644 --- a/apps/sim/lib/api-key/byok.ts +++ b/apps/sim/lib/api-key/byok.ts @@ -244,7 +244,11 @@ async function resolveHostedModelKey( userProvidedKey: string | undefined, billingAttribution: UsageUpgradePayer | undefined ): Promise<{ apiKey: string; isBYOK: boolean }> { - if (!(await mayUseHostedKey(workspaceId, billingAttribution))) { + const hostedKeyAllowed = await mayUseHostedKey(workspaceId, billingAttribution).catch((error) => { + if (userProvidedKey) return false + throw error + }) + if (!hostedKeyAllowed) { if (userProvidedKey) return { apiKey: userProvidedKey, isBYOK: true } throw new HostedKeyRequiresPaidPlanError(model) } diff --git a/apps/sim/lib/auth/auth.ts b/apps/sim/lib/auth/auth.ts index 159405ec3c6..3e375dc2ef2 100644 --- a/apps/sim/lib/auth/auth.ts +++ b/apps/sim/lib/auth/auth.ts @@ -1221,7 +1221,7 @@ export const auth = betterAuth({ const checkoutAdmissionClaim = await claimCheckoutAdmission(referenceId) try { if (isPersonalCheckoutRequest(requestBody, sessionUserId)) { - await assertPersonalCheckoutAllowed(sessionUserId) + await assertPersonalCheckoutAllowed(sessionUserId, requestBody.plan) } } catch (error) { await releaseCheckoutAdmission(checkoutAdmissionClaim) diff --git a/apps/sim/lib/billing/application/pro-trial.ts b/apps/sim/lib/billing/application/pro-trial.ts index b00a030b23d..a12d7a4738e 100644 --- a/apps/sim/lib/billing/application/pro-trial.ts +++ b/apps/sim/lib/billing/application/pro-trial.ts @@ -1,3 +1,4 @@ +import Stripe from 'stripe' import { getHighestPriorityPersonalSubscription } from '@/lib/billing/core/plan' import { requireStripeClient } from '@/lib/billing/stripe-client' import { isTrialingSubscription } from '@/lib/billing/subscriptions/utils' @@ -40,15 +41,31 @@ export const endProTrial: OperationUseCase< !subscription || subscription.referenceId !== userId || !isTrialingSubscription(subscription) || - !subscription.stripeSubscriptionId + !subscription.stripeSubscriptionId || + subscription.cancelAtPeriodEnd ) { throw new OrchestrationError('conflict', 'There is no free trial to end on this account') } - await requireStripeClient().subscriptions.update( - subscription.stripeSubscriptionId, - { trial_end: 'now' }, - { idempotencyKey: `end-trial-early:${subscription.stripeSubscriptionId}` } - ) + try { + // A failed first charge leaves the trial running instead of starting a past-due plan. The + // key absorbs a double click but not a retry a minute later, since Stripe replays a stored + // decline for a day and the payer may have just fixed their card. + await requireStripeClient().subscriptions.update( + subscription.stripeSubscriptionId, + { trial_end: 'now', payment_behavior: 'error_if_incomplete' }, + { + idempotencyKey: `end-trial-early:${subscription.stripeSubscriptionId}:${Math.floor(Date.now() / 60_000)}`, + } + ) + } catch (error) { + if (error instanceof Stripe.errors.StripeCardError) { + throw new OrchestrationError( + 'conflict', + 'Your card could not be charged. Update your payment method, then try again.' + ) + } + throw error + } return { success: true } }, } diff --git a/apps/sim/lib/billing/authorization.ts b/apps/sim/lib/billing/authorization.ts index ceb36948e0a..ead47f3b374 100644 --- a/apps/sim/lib/billing/authorization.ts +++ b/apps/sim/lib/billing/authorization.ts @@ -74,6 +74,22 @@ async function assertNotBilledThroughMarketplace(referenceId: string): Promise { + const [trialing] = await db + .select({ id: subscription.id }) + .from(subscription) + .where(and(eq(subscription.referenceId, userId), eq(subscription.status, 'trialing'))) + .limit(1) + if (!trialing) return + + logger.warn('Blocking team upgrade - personal plan is in its free trial', { userId }) + throw new APIError('CONFLICT', { + message: + 'Your Pro free trial has to end before you can move to a Team plan. End the trial now from Settings > Billing, then upgrade.', + }) +} + /** * Classify a `/subscription/upgrade` request as a personal checkout using * the same reference resolution as the Better Auth Stripe plugin @@ -101,8 +117,10 @@ export function isPersonalCheckoutRequest( * Guard for personal (user-referenced) checkouts on `/subscription/upgrade`. * * Blocks an account AWS Marketplace bills, a bound, incomplete Stripe - * subscription, and a member already covered by an entitled organization - * subscription. Throws {@link APIError} with a user-facing message; the + * subscription, a member already covered by an entitled organization + * subscription, and a Team upgrade of a Pro free trial: Stripe keeps the trial + * across the price change, so the team would run free without the trial's + * capped allowance. Throws {@link APIError} with a user-facing message; the * checkout UI surfaces it as-is. * * Called from the Better Auth `hooks.before` middleware, NOT from @@ -113,9 +131,12 @@ export function isPersonalCheckoutRequest( * Fails closed: when coverage cannot be determined, the checkout is * rejected rather than risking a duplicate subscription. */ -export async function assertPersonalCheckoutAllowed(userId: string): Promise { +export async function assertPersonalCheckoutAllowed(userId: string, plan?: unknown): Promise { await assertNotBilledThroughMarketplace(userId) await assertNoBoundIncompleteSubscription(userId) + if (typeof plan === 'string' && isOrgPlan(plan)) { + await assertNoPersonalTrial(userId) + } const coverage = await getOrganizationCoverageForMember(userId) diff --git a/apps/sim/lib/billing/constants.ts b/apps/sim/lib/billing/constants.ts index 497cea3f57f..fdf89b4790b 100644 --- a/apps/sim/lib/billing/constants.ts +++ b/apps/sim/lib/billing/constants.ts @@ -127,3 +127,6 @@ export const USAGE_UNAVAILABLE_MESSAGE = * contracts, and the overage, true-up, and final invoices billed on top of them. */ export const INVOICE_DAYS_UNTIL_DUE = 30 + +/** Average calendar month in milliseconds, for pricing a billing period by its months. */ +export const AVERAGE_MONTH_MS = 30.44 * 24 * 60 * 60 * 1000 diff --git a/apps/sim/lib/billing/core/chat-access.ts b/apps/sim/lib/billing/core/chat-access.ts index 4cb205c6ae9..3ac92d7fc70 100644 --- a/apps/sim/lib/billing/core/chat-access.ts +++ b/apps/sim/lib/billing/core/chat-access.ts @@ -11,9 +11,10 @@ interface PaidAccessOptions { /** * The verdict for a free payer whose credit balance cannot be read. Chat admits, because a * database blip must not lock a paying customer out and every turn is bounded by the usage - * check that follows. A hosted key denies, because nothing after acquisition bounds it. + * check that follows. A hosted key throws: nothing after acquisition bounds it, and a refusal + * would read as the payer's plan, which disables a schedule at once. */ - onBalanceUnavailable: 'admit' | 'deny' + onBalanceUnavailable: 'admit' | 'throw' } /** @@ -44,7 +45,8 @@ export async function payerHasPaidAccess( verdict: options.onBalanceUnavailable, error: getErrorMessage(error), }) - return options.onBalanceUnavailable === 'admit' + if (options.onBalanceUnavailable === 'throw') throw error + return true } } diff --git a/apps/sim/lib/billing/core/hosted-key-access.ts b/apps/sim/lib/billing/core/hosted-key-access.ts index 8ed028e9927..aad9157269d 100644 --- a/apps/sim/lib/billing/core/hosted-key-access.ts +++ b/apps/sim/lib/billing/core/hosted-key-access.ts @@ -23,10 +23,16 @@ export function isHostedKeyPaidPlanFailure(message: string | null | undefined): export class HostedKeyRequiresPaidPlanError extends HttpError { readonly statusCode = 402 - /** @param subject - what asked for the key: a tool's name or a model id */ - constructor(subject: string) { + /** + * @param subject - what asked for the key: a tool's name or a model id + * @param options.byok - whether the payer's own key can stand in; Web Search has none + */ + constructor(subject: string, options: { byok?: boolean } = {}) { + const upgrade = `Upgrade your plan (Pro starts with a ${PRO_TRIAL_DAYS}-day free trial for new subscribers)` super( - `${subject} ${HOSTED_KEY_PAID_PLAN_PHRASE}. Upgrade your plan (Pro starts with a ${PRO_TRIAL_DAYS}-day free trial for new subscribers), or add your own API key under Settings > BYOK.` + options.byok === false + ? `${subject} ${HOSTED_KEY_PAID_PLAN_PHRASE}. ${upgrade}.` + : `${subject} ${HOSTED_KEY_PAID_PLAN_PHRASE}. ${upgrade}, or add your own API key under Settings > BYOK.` ) this.name = 'HostedKeyRequiresPaidPlanError' } @@ -35,8 +41,9 @@ export class HostedKeyRequiresPaidPlanError extends HttpError { /** * Whether a run may spend on Sim's hosted provider keys, for models and tools alike: only a payer * with paid access ({@link payerHasPaidAccess}) may. The payer is the run's admitted attribution, - * or the workspace's payer for a surface that carries none; a workspace without a payer, or a free - * payer whose credit balance cannot be read, is refused. + * or the workspace's payer for a surface that carries none; a workspace without a payer is refused. + * A free payer whose credit balance cannot be read throws, so the run fails as a fault and not as + * the payer's plan. */ export async function mayUseHostedKey( workspaceId: string | null | undefined, @@ -59,5 +66,5 @@ export async function mayUseHostedKey( } } - return payer !== null && payerHasPaidAccess(payer, { onBalanceUnavailable: 'deny' }) + return payer !== null && payerHasPaidAccess(payer, { onBalanceUnavailable: 'throw' }) } diff --git a/apps/sim/lib/billing/core/plan-switch.ts b/apps/sim/lib/billing/core/plan-switch.ts index 324cf9df325..f7b8948686b 100644 --- a/apps/sim/lib/billing/core/plan-switch.ts +++ b/apps/sim/lib/billing/core/plan-switch.ts @@ -31,6 +31,10 @@ interface SwitchedSubscription extends OrgAllowanceInput { * untouched limit lands on the new amount and never reads as on-demand usage nobody turned on. A * limit already at the new amount is untouched too: the Stripe webhook's floor sync can raise it * there first. An unlimited limit stays unlimited. + * + * `previousLimit` is the limit read before Stripe applied the change ({@link readPoolUsageLimit}). + * Given it, the headroom comes from that value, so a webhook that raised the live limit to the new + * floor first cannot erase headroom the payer chose. */ export async function rebaseUsageLimit( params: { @@ -38,15 +42,20 @@ export async function rebaseUsageLimit( previousIncluded: number nextIncluded: number headroomScale?: number + previousLimit?: string | null }, executor: DbOrTx = db ): Promise { - const { pool, previousIncluded, nextIncluded, headroomScale = 1 } = params + const { pool, previousIncluded, nextIncluded, headroomScale = 1, previousLimit } = params const rebased = (limit: AnyColumn, creditBalance: AnyColumn) => { const previousCovered = sql`(${toDecimal(previousIncluded).toString()}::numeric + ${creditBalance})` const nextCovered = sql`(${toDecimal(nextIncluded).toString()}::numeric + ${creditBalance})` - const headroom = sql`case when ${limit} = ${nextCovered} then 0 else greatest(0, coalesce(${limit}, ${previousCovered}) - ${previousCovered}) end` - return sql`case when ${limit} >= ${ON_DEMAND_UNLIMITED} then ${limit} else ${nextCovered} + ${headroom} * ${headroomScale}::numeric end` + const before = previousLimit === undefined ? sql`${limit}` : sql`${previousLimit}::numeric` + const headroom = + previousLimit === undefined + ? sql`case when ${limit} = ${nextCovered} then 0 else greatest(0, coalesce(${limit}, ${previousCovered}) - ${previousCovered}) end` + : sql`greatest(0, coalesce(${before}, ${previousCovered}) - ${previousCovered})` + return sql`case when ${before} >= ${ON_DEMAND_UNLIMITED} then ${before} else round(${nextCovered} + ${headroom} * ${headroomScale}::numeric, 2) end` } if (pool.type === 'organization') { @@ -68,6 +77,27 @@ export async function rebaseUsageLimit( } } +/** A usage pool's current limit, as stored: read before a plan switch for {@link rebaseUsageLimit}. */ +export async function readPoolUsageLimit(pool: { + type: 'user' | 'organization' + id: string +}): Promise { + if (pool.type === 'organization') { + const [row] = await db + .select({ limit: organization.orgUsageLimit }) + .from(organization) + .where(eq(organization.id, pool.id)) + .limit(1) + return row?.limit ?? null + } + const [row] = await db + .select({ limit: userStats.currentUsageLimit }) + .from(userStats) + .where(eq(userStats.userId, pool.id)) + .limit(1) + return row?.limit ?? null +} + /** * Records a tier or billing-interval change Stripe has already applied: the plan, the interval, * and the payer's usage limit. @@ -75,18 +105,31 @@ export async function rebaseUsageLimit( * The limit moves with the plan's included usage ({@link rebaseUsageLimit}): an untouched limit * left at a pricier allowance would read as on-demand usage nobody turned on. A personal trial * keeps its fixed allowance. + * + * An interval change also restarts Stripe's period, which `period` carries from the update. It is + * written with the interval: until the subscription webhook lands, the old period with the new + * interval would price a year of usage against a month's allowance, and threshold billing would + * collect overage the old year's close then finds it never owed. */ export async function recordPlanSwitch(params: { subscription: SwitchedSubscription targetPlanName: string targetInterval: 'month' | 'year' orgScoped: boolean + period?: { start: Date; end: Date } + previousLimit?: string | null }): Promise { - const { subscription, targetPlanName, targetInterval, orgScoped } = params + const { subscription, targetPlanName, targetInterval, orgScoped, period, previousLimit } = params const trialing = !orgScoped && isTrialingSubscription(subscription) const previousInterval = resolveBillingInterval(subscription) - const target = { ...subscription, plan: targetPlanName, billingInterval: targetInterval } + const restartedPeriod = previousInterval !== targetInterval ? period : undefined + const target = { + ...subscription, + plan: targetPlanName, + billingInterval: targetInterval, + ...(restartedPeriod ? { periodStart: restartedPeriod.start } : {}), + } const previousBase = orgScoped ? getOrgIncludedUsageDollars(subscription) : getPlanPricing(subscription).basePrice @@ -97,10 +140,15 @@ export async function recordPlanSwitch(params: { // One transaction: a retry of a half-recorded switch finds the plan already matching and would // never rebase the limit. await db.transaction(async (tx) => { - if (subscription.plan !== targetPlanName) { + if (subscription.plan !== targetPlanName || restartedPeriod) { await tx .update(subscriptionTable) - .set({ plan: targetPlanName }) + .set({ + plan: targetPlanName, + ...(restartedPeriod + ? { periodStart: restartedPeriod.start, periodEnd: restartedPeriod.end } + : {}), + }) .where(eq(subscriptionTable.id, subscription.id)) } await writeBillingInterval(subscription.id, targetInterval, tx) @@ -113,6 +161,7 @@ export async function recordPlanSwitch(params: { previousIncluded: previousBase, nextIncluded: nextBase, headroomScale, + previousLimit, }, tx ) diff --git a/apps/sim/lib/billing/core/usage.ts b/apps/sim/lib/billing/core/usage.ts index 49502071be7..92a7ac1bbee 100644 --- a/apps/sim/lib/billing/core/usage.ts +++ b/apps/sim/lib/billing/core/usage.ts @@ -137,30 +137,31 @@ async function findOrgUsageLimit( subscription: OrgLimitSubscription, executor: DbClient = db ): Promise { - const [orgData] = await executor - .select({ orgUsageLimit: organization.orgUsageLimit }) - .from(organization) - .where(eq(organization.id, organizationId)) - .limit(1) - - if (!orgData) return null - const needsRecordedAllowance = subscription.id !== undefined && subscription.allowanceSeatMonths === undefined && isTeam(subscription.plan) && resolveBillingInterval(subscription) === 'year' - const [recordedAllowance] = needsRecordedAllowance - ? await executor - .select({ - periodStart: subscriptionTable.periodStart, - allowancePeriodStart: subscriptionTable.allowancePeriodStart, - allowanceSeatMonths: subscriptionTable.allowanceSeatMonths, - }) - .from(subscriptionTable) - .where(eq(subscriptionTable.id, subscription.id ?? '')) - .limit(1) - : [] + const [[orgData], [recordedAllowance]] = await Promise.all([ + executor + .select({ orgUsageLimit: organization.orgUsageLimit }) + .from(organization) + .where(eq(organization.id, organizationId)) + .limit(1), + needsRecordedAllowance + ? executor + .select({ + periodStart: subscriptionTable.periodStart, + allowancePeriodStart: subscriptionTable.allowancePeriodStart, + allowanceSeatMonths: subscriptionTable.allowanceSeatMonths, + }) + .from(subscriptionTable) + .where(eq(subscriptionTable.id, subscription.id ?? '')) + .limit(1) + : Promise.resolve([]), + ]) + + if (!orgData) return null return calculateOrgUsageLimit( organizationId, diff --git a/apps/sim/lib/billing/cycle-close.ts b/apps/sim/lib/billing/cycle-close.ts index ec893c41090..e4b2cbe9c03 100644 --- a/apps/sim/lib/billing/cycle-close.ts +++ b/apps/sim/lib/billing/cycle-close.ts @@ -11,7 +11,7 @@ import { createLogger } from '@sim/logger' import { mapWithConcurrency } from '@sim/utils/concurrency' import { getErrorMessage } from '@sim/utils/errors' import { and, asc, eq, gt, inArray, isNull, lt, or, sql } from 'drizzle-orm' -import { BILLING_LOCK_TIMEOUT_MS } from '@/lib/billing/constants' +import { AVERAGE_MONTH_MS, BILLING_LOCK_TIMEOUT_MS } from '@/lib/billing/constants' import { computeOrgOverageAmount, isSubscriptionOrgScoped } from '@/lib/billing/core/billing' import { resolveSubscriptionUsagePeriod } from '@/lib/billing/core/reporting-period' import { @@ -35,8 +35,6 @@ import { captureServerEvent } from '@/lib/posthog/server' const logger = createLogger('BillingCycleClose') -const AVERAGE_MONTH_MS = 30.44 * 24 * 60 * 60 * 1000 - /** * The usage a closed period included, from the period itself rather than the subscription's * current terms: an interval switch moves the subscription onto the new interval before the old diff --git a/apps/sim/lib/billing/free-plan.integration.ts b/apps/sim/lib/billing/free-plan.integration.ts index 3b1e45d6816..6fb202a9ac0 100644 --- a/apps/sim/lib/billing/free-plan.integration.ts +++ b/apps/sim/lib/billing/free-plan.integration.ts @@ -9,6 +9,7 @@ import { subscription, user, userStats, workflowSchedule, workspace } from '@sim import { deleteWorkspaceFixture, insertWorkspaceFixture } from '@sim/db/testing/workspace-fixtures' import { generateId } from '@sim/utils/id' import { eq, inArray } from 'drizzle-orm' +import Stripe from 'stripe' import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' import { endProTrial } from '@/lib/billing/application/pro-trial' import { HostedKeyRequiresPaidPlanError } from '@/lib/billing/core/hosted-key-access' @@ -77,7 +78,11 @@ async function createWorkspace(ownerId: string): Promise { return id } -async function addSubscription(referenceId: string, status: string) { +async function addSubscription( + referenceId: string, + status: string, + options: { cancelAtPeriodEnd?: boolean } = {} +) { const stripeSubscriptionId = `sub_${generateId()}` const now = Date.now() await db.insert(subscription).values({ @@ -90,6 +95,7 @@ async function addSubscription(referenceId: string, status: string) { periodEnd: new Date(now + 13 * DAY_MS), trialStart: status === 'trialing' ? new Date(now - DAY_MS) : null, trialEnd: status === 'trialing' ? new Date(now + 13 * DAY_MS) : null, + cancelAtPeriodEnd: options.cancelAtPeriodEnd ?? false, }) return stripeSubscriptionId } @@ -170,9 +176,10 @@ describe('web search', () => { const response = await search(userId, workspaceId) expect(response.status).toBe(402) - expect((await response.json()).error).toBe( - new HostedKeyRequiresPaidPlanError('Web Search').message - ) + const { error } = await response.json() + expect(error).toBe(new HostedKeyRequiresPaidPlanError('Web Search', { byok: false }).message) + // Search has no BYOK option, so the refusal must not offer one. + expect(error).not.toContain('BYOK') }) it('lets a paid payer through to the search provider', async () => { @@ -288,11 +295,34 @@ describe('endProTrial', () => { expect(stripeStub.subscriptions.update).toHaveBeenCalledWith( stripeSubscriptionId, - { trial_end: 'now' }, + // A declined first charge must leave the trial running, not start a past-due plan. + { trial_end: 'now', payment_behavior: 'error_if_incomplete' }, expect.anything() ) }) + it('refuses a trial already cancelled at period end', async () => { + const userId = await createUser() + await addSubscription(userId, 'trialing', { cancelAtPeriodEnd: true }) + + await expect(endProTrial.execute({ principal: asSession(userId), input: {} })).rejects.toThrow( + 'There is no free trial to end' + ) + expect(stripeStub.subscriptions.update).not.toHaveBeenCalled() + }) + + it('reports a declined card as a payer error and keeps the trial', async () => { + const userId = await createUser() + await addSubscription(userId, 'trialing') + stripeStub.subscriptions.update.mockRejectedValueOnce( + new Stripe.errors.StripeCardError({ type: 'card_error', message: 'Your card was declined.' }) + ) + + await expect(endProTrial.execute({ principal: asSession(userId), input: {} })).rejects.toThrow( + 'Your card could not be charged' + ) + }) + it('refuses an account whose plan is already paid', async () => { const userId = await createUser() await addSubscription(userId, 'active') diff --git a/apps/sim/lib/billing/organization.ts b/apps/sim/lib/billing/organization.ts index b01623756ef..611ec47db46 100644 --- a/apps/sim/lib/billing/organization.ts +++ b/apps/sim/lib/billing/organization.ts @@ -3,7 +3,8 @@ import { member, organization, subscription as subscriptionTable, user } from '@ import { createLogger } from '@sim/logger' import { isOrgAdminRole } from '@sim/platform-authz/workspace' import { generateId } from '@sim/utils/id' -import { and, eq, inArray, ne, sql } from 'drizzle-orm' +import { and, eq, inArray, isNull, ne, sql } from 'drizzle-orm' +import { AVERAGE_MONTH_MS } from '@/lib/billing/constants' import { isSubscriptionOrgScoped } from '@/lib/billing/core/billing' import { rebaseUsageLimit } from '@/lib/billing/core/plan-switch' import { getOrganizationIdForSubscriptionReference } from '@/lib/billing/core/subscription' @@ -581,8 +582,6 @@ export async function syncSubscriptionUsageLimits(subscription: SubscriptionData /** Annual subscriptions read per page of the hourly sweep. */ const ANNUAL_SWEEP_PAGE_SIZE = 200 -const AVERAGE_MONTH_MS = 30.44 * 24 * 60 * 60 * 1000 - /** Months left in a period at `now`, as a fraction: what Stripe prorates a seat change against. */ function monthsRemaining(periodEnd: Date | null, now: Date): number { if (!periodEnd) return 12 @@ -639,10 +638,13 @@ export async function syncAnnualPlanUsageLimits(): Promise { if (annual.billingInterval !== 'year') { // Older checkouts kept the interval only in metadata; readers of the column alone (the // billing attribution snapshot) then priced the plan as monthly. + // Only an unset column: a switch to monthly committed since the re-read must stand. await db .update(subscriptionTable) .set({ billingInterval: 'year' }) - .where(eq(subscriptionTable.id, annual.id)) + .where( + and(eq(subscriptionTable.id, annual.id), isNull(subscriptionTable.billingInterval)) + ) } await syncSubscriptionUsageLimits({ ...annual, billingInterval: 'year' }) synced++ @@ -711,22 +713,47 @@ async function reconcileAnnualSeatMonths( const previousIncluded = getOrgIncludedUsageDollars(annual) const nextIncluded = getOrgIncludedUsageDollars(next) - // One transaction: a limit left unrebased after the count advanced would never be retried. - await db.transaction(async (tx) => { - await tx + // One transaction: a limit left unrebased after the count advanced would never be retried. The + // count advances only from the one it was computed from, because the rebase moves the limit + // relative to its live value: a concurrent seat sync, webhook, or sweep that read the same count + // would otherwise apply the same delta twice. + const advanced = await db.transaction(async (tx) => { + const [claimed] = await tx .update(subscriptionTable) .set({ allowancePeriodStart: next.allowancePeriodStart, allowanceSeats: next.allowanceSeats, allowanceSeatMonths: next.allowanceSeatMonths, }) - .where(eq(subscriptionTable.id, annual.id)) + .where( + and( + eq(subscriptionTable.id, annual.id), + annual.allowancePeriodStart === null + ? isNull(subscriptionTable.allowancePeriodStart) + : eq(subscriptionTable.allowancePeriodStart, annual.allowancePeriodStart), + annual.allowanceSeats === null + ? isNull(subscriptionTable.allowanceSeats) + : eq(subscriptionTable.allowanceSeats, annual.allowanceSeats), + annual.allowanceSeatMonths === null + ? isNull(subscriptionTable.allowanceSeatMonths) + : eq(subscriptionTable.allowanceSeatMonths, annual.allowanceSeatMonths) + ) + ) + .returning({ id: subscriptionTable.id }) + if (!claimed) return false if (previousIncluded !== nextIncluded) { await rebaseUsageLimit( { pool: { type: 'organization', id: organizationId }, previousIncluded, nextIncluded }, tx ) } + return true }) - return next + if (advanced) return next + const [current] = await db + .select() + .from(subscriptionTable) + .where(eq(subscriptionTable.id, annual.id)) + .limit(1) + return current ?? null } diff --git a/apps/sim/lib/billing/plan-allowance.integration.ts b/apps/sim/lib/billing/plan-allowance.integration.ts index 2bf0bd202ba..bef38baa1ee 100644 --- a/apps/sim/lib/billing/plan-allowance.integration.ts +++ b/apps/sim/lib/billing/plan-allowance.integration.ts @@ -375,6 +375,41 @@ describe('recordPlanSwitch', () => { expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS * 12) }) + it('keeps headroom chosen before the switch when the webhook raised the limit first', async () => { + // $10 of on-demand headroom over the monthly plan; the webhook then raised it to the annual floor. + const userId = await createUser(PRO_MONTHLY_DOLLARS * 12) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'month' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'year', + orgScoped: false, + previousLimit: String(PRO_MONTHLY_DOLLARS + 10), + }) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS * 12 + 120) + }) + + it('records the period Stripe restarted with an interval switch, before the webhook', async () => { + const userId = await createUser(PRO_MONTHLY_DOLLARS * 12) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'year' }) + const start = new Date(Date.UTC(2026, 10, 20)) + const end = new Date(Date.UTC(2026, 11, 20)) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'month', + orgScoped: false, + period: { start, end }, + }) + + const [row] = await db.select().from(subscription).where(eq(subscription.id, sub.id)) + expect(row?.periodStart?.getTime()).toBe(start.getTime()) + expect(row?.periodEnd?.getTime()).toBe(end.getTime()) + }) + it('keeps an unlimited limit unlimited', async () => { const userId = await createUser(ON_DEMAND_UNLIMITED) const sub = await addSubscription(userId, { plan: 'pro_25000', billingInterval: 'month' }) diff --git a/apps/sim/lib/billing/subscriptions/utils.test.ts b/apps/sim/lib/billing/subscriptions/utils.test.ts index 61f7cced481..e01131c9c30 100644 --- a/apps/sim/lib/billing/subscriptions/utils.test.ts +++ b/apps/sim/lib/billing/subscriptions/utils.test.ts @@ -6,7 +6,6 @@ import { checkProPlan, checkTeamPlan, getEffectiveSeats, - getSubscriptionWeeklyRefreshDollars, hasPaidSubscriptionStatus, hasUsableSubscriptionAccess, hasUsableSubscriptionStatus, @@ -61,11 +60,4 @@ describe('billing subscription status helpers', () => { expect(getEffectiveSeats({ plan: 'team_8000', status: 'past_due', seats: undefined })).toBe(1) expect(getEffectiveSeats({ plan: 'team_8000', status: 'canceled', seats: null })).toBe(0) }) - - it('earns no weekly refresh during a trial', () => { - expect(getSubscriptionWeeklyRefreshDollars({ plan: 'pro_6000', status: 'trialing' })).toBe(0) - expect( - getSubscriptionWeeklyRefreshDollars({ plan: 'pro_6000', status: 'active' }) - ).toBeGreaterThan(0) - }) }) diff --git a/apps/sim/lib/billing/trial.integration.ts b/apps/sim/lib/billing/trial.integration.ts index 6d76ec74c8b..84bc3cd2191 100644 --- a/apps/sim/lib/billing/trial.integration.ts +++ b/apps/sim/lib/billing/trial.integration.ts @@ -9,6 +9,7 @@ import { generateId } from '@sim/utils/id' import { eq, inArray } from 'drizzle-orm' import type Stripe from 'stripe' import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { assertPersonalCheckoutAllowed } from '@/lib/billing/authorization' import { PRO_TRIAL_DAYS, PRO_TRIAL_USAGE_LIMIT_DOLLARS } from '@/lib/billing/constants' import { syncUsageLimitsFromSubscription, updateUserUsageLimit } from '@/lib/billing/core/usage' import { setUsageLimitForCredits } from '@/lib/billing/credits/purchase' @@ -564,3 +565,21 @@ describe('the usage limit card', () => { expect(card.action).toBe('increase_limit') }) }) + +describe('a Team upgrade during a Pro trial', () => { + it('is refused while the personal Pro plan is still trialing', async () => { + const userId = await createUser() + await addSubscription(userId, { status: 'trialing', trialStart: new Date() }) + + await expect(assertPersonalCheckoutAllowed(userId, 'team_8000')).rejects.toMatchObject({ + status: 'CONFLICT', + }) + }) + + it('is allowed once the trial has converted to a paid plan', async () => { + const userId = await createUser() + await addSubscription(userId, { status: 'active' }) + + await expect(assertPersonalCheckoutAllowed(userId, 'team_8000')).resolves.toBeUndefined() + }) +}) diff --git a/apps/sim/lib/billing/webhooks/invoices.test.ts b/apps/sim/lib/billing/webhooks/invoices.test.ts index c101c024b62..10281b6d666 100644 --- a/apps/sim/lib/billing/webhooks/invoices.test.ts +++ b/apps/sim/lib/billing/webhooks/invoices.test.ts @@ -1,3 +1,4 @@ +import { billingAccessMock, billingAccessMockFns } from '@sim/testing/mocks/billing-access.mock' import { billingCoreMock, billingCoreMockFns } from '@sim/testing/mocks/billing-core.mock' import { billingPlanHelpersMock, @@ -26,6 +27,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest' vi.mock('@/components/emails', () => emailTemplatesMock) +vi.mock('@/lib/billing/core/access', () => billingAccessMock) vi.mock('@/lib/billing/core/billing', () => billingCoreMock) vi.mock('@/lib/billing/core/usage-log', () => billingUsageLogMock) @@ -143,6 +145,10 @@ describe('invoice billing recovery', () => { urlsMockFns.mockGetBaseUrl.mockReturnValue('https://sim.test') mockBlockOrgMembers.mockResolvedValue(2) mockUnblockOrgMembers.mockResolvedValue(2) + billingAccessMockFns.mockGetBillingEntityBlockStatus.mockResolvedValue({ + billingBlocked: true, + billingBlockedReason: 'payment_failed', + }) }) it('blocks org members when a metadata-backed invoice payment fails', async () => { diff --git a/apps/sim/lib/billing/webhooks/invoices.ts b/apps/sim/lib/billing/webhooks/invoices.ts index 7f291a4a4c7..a7e42455732 100644 --- a/apps/sim/lib/billing/webhooks/invoices.ts +++ b/apps/sim/lib/billing/webhooks/invoices.ts @@ -10,6 +10,7 @@ import { renderCreditPurchaseEmail, renderPaymentFailedEmail, } from '@/components/emails' +import { getBillingEntityBlockStatus } from '@/lib/billing/core/access' import { isSubscriptionOrgScoped } from '@/lib/billing/core/billing' import { addCredits, getCreditBalanceForEntity } from '@/lib/billing/credits/balance' import { setUsageLimitForCredits } from '@/lib/billing/credits/purchase' @@ -589,10 +590,6 @@ async function handleCreditPurchaseSuccess(invoice: Stripe.Invoice): Promise 0 // A paid invoice restores access only when no other charge is still failing: overage and // seat true-up invoices are separate from renewals, so one can stay unpaid while another - // succeeds. - const shouldUnblock = - (!isProrationInvoice || (invoice.amount_paid ?? 0) > 0) && - !(await hasOtherFailedInvoice(invoice, resolvedInvoice.stripeSubscriptionId)) + // succeeds. An unblocked payer skips the Stripe invoice listing. + const otherInvoiceFailing = + billingBlocked && + paysSomething && + (await hasOtherFailedInvoice(invoice, resolvedInvoice.stripeSubscriptionId)) - if (shouldUnblock) { + if (billingBlocked && paysSomething && !otherInvoiceFailing) { if (subIsOrgScoped) { await unblockOrgMembers(sub.referenceId, 'payment_failed') } else { @@ -667,12 +674,17 @@ export async function handleInvoicePaymentSucceeded(event: Stripe.Event) { ) ) } - } else { - logger.info('Skipping unblock for zero-amount proration invoice', { - invoiceId: invoice.id, - billingReason: invoice.billing_reason, - amountPaid: invoice.amount_paid, - }) + } else if (billingBlocked) { + logger.info( + otherInvoiceFailing + ? 'Skipping unblock while another invoice is still failing' + : 'Skipping unblock for zero-amount proration invoice', + { + invoiceId: invoice.id, + billingReason: invoice.billing_reason, + amountPaid: invoice.amount_paid, + } + ) } const entityType = subIsOrgScoped ? 'organization' : 'user' diff --git a/apps/sim/lib/billing/webhooks/plan-notices.ts b/apps/sim/lib/billing/webhooks/plan-notices.ts index 238a41c0538..ea3ea9e2231 100644 --- a/apps/sim/lib/billing/webhooks/plan-notices.ts +++ b/apps/sim/lib/billing/webhooks/plan-notices.ts @@ -1,8 +1,8 @@ import { db } from '@sim/db' -import { member, subscription, user } from '@sim/db/schema' +import { subscription, user } from '@sim/db/schema' import { createLogger } from '@sim/logger' import { getErrorMessage } from '@sim/utils/errors' -import { and, eq } from 'drizzle-orm' +import { eq } from 'drizzle-orm' import { getHighestPrioritySubscription } from '@/lib/billing/core/plan' import { getDisplayPlanName, isPaid } from '@/lib/billing/plan-helpers' import { requireStripeClient } from '@/lib/billing/stripe-client' @@ -91,8 +91,10 @@ export async function handleTrialWillEnd( 'trial-ending-reminder', `${stripeSubscription.id}:${trialEnd}`, async () => { - const recipient = await readRecipient(recorded.referenceId) - const price = await readRenewalCharge(stripeSubscription) + const [recipient, price] = await Promise.all([ + readRecipient(recorded.referenceId), + readRenewalCharge(stripeSubscription), + ]) if (!recipient || !price) return { sent: false } const { getTrialEndingSubject, renderTrialEndingEmail } = await import('@/components/emails') @@ -119,30 +121,21 @@ export async function handleTrialWillEnd( ) } -/** The account a plan's emails go to: the user on a personal plan, the owner on an organization's. */ -async function resolvePlanOwnerId(referenceId: string): Promise { - const [owner] = await db - .select({ userId: member.userId }) - .from(member) - .where(and(eq(member.organizationId, referenceId), eq(member.role, 'owner'))) - .limit(1) - return owner?.userId ?? referenceId -} - /** * Tells a payer whose paid plan just ended that Sim-hosted models, tools, and Chat stopped, and * how to keep workflows running. Skipped when the owner is still covered by another paid plan, such * as an organization's or a restored personal Pro. Never throws: a missed notice must not fail * the deletion webhook that settles the final invoice. + * + * @param ownerId - the account the plan's emails go to: the user on a personal plan, the owner on + * an organization's */ -export async function sendPlanEndedEmail(ended: { - id: string - plan: string | null - referenceId: string -}) { +export async function sendPlanEndedEmail( + ended: { id: string; plan: string | null; referenceId: string }, + ownerId: string +) { try { if (!isPaid(ended.plan)) return - const ownerId = await resolvePlanOwnerId(ended.referenceId) const current = await getHighestPrioritySubscription(ownerId, { onError: 'throw' }) const stillPaid = current && diff --git a/apps/sim/lib/billing/webhooks/subscription.ts b/apps/sim/lib/billing/webhooks/subscription.ts index 521d8205700..1a3c2e1725a 100644 --- a/apps/sim/lib/billing/webhooks/subscription.ts +++ b/apps/sim/lib/billing/webhooks/subscription.ts @@ -603,7 +603,7 @@ export async function handleSubscriptionDeleted( plan: subscription.plan ?? 'unknown', reference_id: subscription.referenceId, }) - await sendPlanEndedEmail(subscription) + await sendPlanEndedEmail(subscription, cancelActorId) return { totalOverage, remainingOverage, restoredProCount, workspacesDetached } } diff --git a/apps/sim/lib/internal/search/execute-tool.ts b/apps/sim/lib/internal/search/execute-tool.ts index 61ffb74a8b0..36a0af57077 100644 --- a/apps/sim/lib/internal/search/execute-tool.ts +++ b/apps/sim/lib/internal/search/execute-tool.ts @@ -30,7 +30,7 @@ export const executeSearchTool: InternalToolOperationHandler = async ({ // Search always runs on Sim's own key, so it is reserved for paid payers like every hosted tool. if (!(await mayUseHostedKey(context.workspaceId, context.billingAttribution))) { - const refusal = new HostedKeyRequiresPaidPlanError('Web Search') + const refusal = new HostedKeyRequiresPaidPlanError('Web Search', { byok: false }) return Response.json({ success: false, error: refusal.message }, { status: refusal.statusCode }) } diff --git a/apps/sim/lib/workflows/schedules/disable-reasons.ts b/apps/sim/lib/workflows/schedules/disable-reasons.ts index 13849ff86fc..017ba1aa486 100644 --- a/apps/sim/lib/workflows/schedules/disable-reasons.ts +++ b/apps/sim/lib/workflows/schedules/disable-reasons.ts @@ -22,5 +22,5 @@ export const SCHEDULE_DISABLE_REASON_COPY: Record workflow_not_found: 'The workflow could not be found.', invalid_schedule: 'The schedule is no longer valid.', paid_plan_required: - "It uses Sim's hosted models or tools, which need a paid plan. Add your own API key under Settings > BYOK or upgrade, then turn the schedule back on.", + "It uses Sim's hosted models or tools, which need a paid plan. Upgrade, or add your own API key under Settings > BYOK where the block supports one, then turn the schedule back on.", } diff --git a/apps/sim/tools/index.test.ts b/apps/sim/tools/index.test.ts index 894680ce006..12e8f893fbd 100644 --- a/apps/sim/tools/index.test.ts +++ b/apps/sim/tools/index.test.ts @@ -8107,7 +8107,7 @@ describe('Hosted Key Injection', () => { expect(result.success).toBe(false) expect(result.error).toContain('available on paid plans') expect(mockPayerHasPaidAccess).toHaveBeenCalledWith(TEST_BILLING_ATTRIBUTION, { - onBalanceUnavailable: 'deny', + onBalanceUnavailable: 'throw', }) expect(mockRateLimiterFns.acquireKey).not.toHaveBeenCalled() expect(request).not.toHaveBeenCalled() @@ -8160,7 +8160,7 @@ describe('Hosted Key Injection', () => { billingEntity: { type: 'organization', id: 'org-1' }, payerSubscription: { plan: 'team' }, }, - { onBalanceUnavailable: 'deny' } + { onBalanceUnavailable: 'throw' } ) expect(request).toHaveBeenCalledTimes(1) }) diff --git a/packages/db/migrations/0471_pro_trial_card.sql b/packages/db/migrations/0471_pro_trial_card.sql index e2fec0f0c2c..307d48358ca 100644 --- a/packages/db/migrations/0471_pro_trial_card.sql +++ b/packages/db/migrations/0471_pro_trial_card.sql @@ -1,8 +1,14 @@ -CREATE TABLE "trial_card" ( +-- Replay-safe: 0470's embedded COMMIT leaves this file in autocommit, and a lock-timeout retry +-- replays every unjournaled file from the top. +CREATE TABLE IF NOT EXISTS "trial_card" ( "fingerprint" text PRIMARY KEY NOT NULL, "user_id" text, "stripe_subscription_id" text NOT NULL, "created_at" timestamp DEFAULT now() NOT NULL ); --> statement-breakpoint -ALTER TABLE "trial_card" ADD CONSTRAINT "trial_card_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action; \ No newline at end of file +DO $$ BEGIN +IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'trial_card_user_id_user_id_fk' AND conrelid = 'trial_card'::regclass) THEN +ALTER TABLE "trial_card" ADD CONSTRAINT "trial_card_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action; +END IF; +END $$; diff --git a/packages/db/migrations/0473_enterprise_self_serve.sql b/packages/db/migrations/0473_enterprise_self_serve.sql index 1cb3de1fbfc..b0469843d28 100644 --- a/packages/db/migrations/0473_enterprise_self_serve.sql +++ b/packages/db/migrations/0473_enterprise_self_serve.sql @@ -1,4 +1,6 @@ -CREATE TABLE "enterprise_seat_true_up" ( +-- Replay-safe: 0470's embedded COMMIT leaves this file in autocommit, and a lock-timeout retry +-- replays every unjournaled file from the top. +CREATE TABLE IF NOT EXISTS "enterprise_seat_true_up" ( "id" text PRIMARY KEY NOT NULL, "subscription_id" text NOT NULL, "organization_id" text NOT NULL, @@ -12,9 +14,17 @@ CREATE TABLE "enterprise_seat_true_up" ( "updated_at" timestamp DEFAULT now() NOT NULL ); --> statement-breakpoint -ALTER TABLE "organization" ADD COLUMN "self_serve_usage_limit" numeric;--> statement-breakpoint -ALTER TABLE "enterprise_seat_true_up" ADD CONSTRAINT "enterprise_seat_true_up_subscription_id_subscription_id_fk" FOREIGN KEY ("subscription_id") REFERENCES "public"."subscription"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "enterprise_seat_true_up" ADD CONSTRAINT "enterprise_seat_true_up_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -CREATE UNIQUE INDEX "enterprise_seat_true_up_subscription_window_unique" ON "enterprise_seat_true_up" USING btree ("subscription_id","window_start");--> statement-breakpoint -CREATE INDEX "enterprise_seat_true_up_organization_id_idx" ON "enterprise_seat_true_up" USING btree ("organization_id");--> statement-breakpoint -CREATE INDEX "enterprise_seat_true_up_unbilled_idx" ON "enterprise_seat_true_up" USING btree ("window_end") WHERE billed_at IS NULL; +ALTER TABLE "organization" ADD COLUMN IF NOT EXISTS "self_serve_usage_limit" numeric;--> statement-breakpoint +DO $$ BEGIN +IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'enterprise_seat_true_up_subscription_id_subscription_id_fk' AND conrelid = 'enterprise_seat_true_up'::regclass) THEN +ALTER TABLE "enterprise_seat_true_up" ADD CONSTRAINT "enterprise_seat_true_up_subscription_id_subscription_id_fk" FOREIGN KEY ("subscription_id") REFERENCES "public"."subscription"("id") ON DELETE cascade ON UPDATE no action; +END IF; +END $$;--> statement-breakpoint +DO $$ BEGIN +IF NOT EXISTS (SELECT 1 FROM pg_constraint WHERE conname = 'enterprise_seat_true_up_organization_id_organization_id_fk' AND conrelid = 'enterprise_seat_true_up'::regclass) THEN +ALTER TABLE "enterprise_seat_true_up" ADD CONSTRAINT "enterprise_seat_true_up_organization_id_organization_id_fk" FOREIGN KEY ("organization_id") REFERENCES "public"."organization"("id") ON DELETE cascade ON UPDATE no action; +END IF; +END $$;--> statement-breakpoint +CREATE UNIQUE INDEX IF NOT EXISTS "enterprise_seat_true_up_subscription_window_unique" ON "enterprise_seat_true_up" USING btree ("subscription_id","window_start");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "enterprise_seat_true_up_organization_id_idx" ON "enterprise_seat_true_up" USING btree ("organization_id");--> statement-breakpoint +CREATE INDEX IF NOT EXISTS "enterprise_seat_true_up_unbilled_idx" ON "enterprise_seat_true_up" USING btree ("window_end") WHERE billed_at IS NULL; diff --git a/packages/db/migrations/0474_annual_seat_allowance.sql b/packages/db/migrations/0474_annual_seat_allowance.sql index fe75002e2a3..cad4c890232 100644 --- a/packages/db/migrations/0474_annual_seat_allowance.sql +++ b/packages/db/migrations/0474_annual_seat_allowance.sql @@ -1,3 +1,5 @@ -ALTER TABLE "subscription" ADD COLUMN "allowance_period_start" timestamp;--> statement-breakpoint -ALTER TABLE "subscription" ADD COLUMN "allowance_seats" integer;--> statement-breakpoint -ALTER TABLE "subscription" ADD COLUMN "allowance_seat_months" numeric; \ No newline at end of file +-- Replay-safe: 0470's embedded COMMIT leaves this file in autocommit, and a lock-timeout retry +-- replays every unjournaled file from the top. +ALTER TABLE "subscription" ADD COLUMN IF NOT EXISTS "allowance_period_start" timestamp;--> statement-breakpoint +ALTER TABLE "subscription" ADD COLUMN IF NOT EXISTS "allowance_seats" integer;--> statement-breakpoint +ALTER TABLE "subscription" ADD COLUMN IF NOT EXISTS "allowance_seat_months" numeric; From 0d91936399a3d967fc4fbba60c061efa26dbd2d3 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 11:38:27 -0800 Subject: [PATCH 2/4] fix(billing): snapshot credit with the pre-switch limit, period on retries, tighter seat-month claim - the plan-switch rebase reads headroom from the limit and credit balance read before Stripe, keeping the exact-floor guard for a retry - a retry that finds Stripe already on the target price records the retrieved item's period - the annual seat-month claim also matches plan, period, seats and interval - only a personal Pro trial blocks a Team upgrade - end-trial refetches on settle, since a lost response can hide a completed charge --- apps/sim/app/api/billing/switch-plan/route.ts | 20 +++--- apps/sim/hooks/queries/subscription.ts | 3 +- apps/sim/lib/billing/authorization.ts | 9 ++- apps/sim/lib/billing/core/plan-switch.ts | 72 ++++++++++--------- apps/sim/lib/billing/organization.ts | 14 +++- .../lib/billing/plan-allowance.integration.ts | 34 ++++++++- .../migrations/0473_enterprise_self_serve.sql | 2 +- .../migrations/0474_annual_seat_allowance.sql | 2 +- 8 files changed, 101 insertions(+), 55 deletions(-) diff --git a/apps/sim/app/api/billing/switch-plan/route.ts b/apps/sim/app/api/billing/switch-plan/route.ts index aa702812b02..8fc8cd5f0d4 100644 --- a/apps/sim/app/api/billing/switch-plan/route.ts +++ b/apps/sim/app/api/billing/switch-plan/route.ts @@ -12,7 +12,7 @@ import { getHighestPriorityPersonalSubscription, getHighestPrioritySubscription, } from '@/lib/billing/core/plan' -import { readPoolUsageLimit, recordPlanSwitch } from '@/lib/billing/core/plan-switch' +import { readPoolUsageSnapshot, recordPlanSwitch } from '@/lib/billing/core/plan-switch' import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers' import { getPlanByName } from '@/lib/billing/plans' import { requireStripeClient } from '@/lib/billing/stripe-client' @@ -180,11 +180,13 @@ export const POST = withRouteHandler(async (request: NextRequest) => { const orgScoped = await isSubscriptionOrgScoped(sub) // Read before Stripe applies the switch: its webhook can move the live limit first. - const previousLimit = await readPoolUsageLimit({ + const previous = await readPoolUsageSnapshot({ type: orgScoped ? 'organization' : 'user', id: sub.referenceId, }) - let period: { start: Date; end: Date } | undefined + // The item's period after the switch: Stripe's response, or the retrieved item on a retry + // that finds Stripe already on the target price. + let switchedItem: typeof subscriptionItem | undefined = subscriptionItem if (!alreadyOnStripePrice) { const currentQuantity = subscriptionItem.quantity ?? 1 @@ -198,14 +200,14 @@ export const POST = withRouteHandler(async (request: NextRequest) => { ], proration_behavior: 'always_invoice', }) - const switchedItem = updated.items.data.find((item) => item.id === subscriptionItem.id) - if (switchedItem) { - period = { + switchedItem = updated.items.data.find((item) => item.id === subscriptionItem.id) + } + const period = switchedItem + ? { start: new Date(switchedItem.current_period_start * 1000), end: new Date(switchedItem.current_period_end * 1000), } - } - } + : undefined await recordPlanSwitch({ subscription: sub, @@ -213,7 +215,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => { targetInterval: targetInterval as 'month' | 'year', orgScoped, period, - previousLimit, + previous, }) logger.info('Subscription switched successfully', { diff --git a/apps/sim/hooks/queries/subscription.ts b/apps/sim/hooks/queries/subscription.ts index 3bae633d91e..9c8e03e6b6e 100644 --- a/apps/sim/hooks/queries/subscription.ts +++ b/apps/sim/hooks/queries/subscription.ts @@ -228,7 +228,8 @@ export function useEndProTrial() { const queryClient = useQueryClient() return useMutation({ mutationFn: () => requestJson(billingEndTrialContract, { body: {} }), - onSuccess: () => + // Settled, not success: a lost response can hide a charge that went through. + onSettled: () => Promise.all([ queryClient.invalidateQueries({ queryKey: subscriptionKeys.all }), invalidateWorkspaceUsage(queryClient), diff --git a/apps/sim/lib/billing/authorization.ts b/apps/sim/lib/billing/authorization.ts index ead47f3b374..d758674b0c2 100644 --- a/apps/sim/lib/billing/authorization.ts +++ b/apps/sim/lib/billing/authorization.ts @@ -14,7 +14,7 @@ import { assertNoUnresolvedEnterpriseIssuance, EnterpriseIssuanceInProgressError, } from '@/lib/billing/enterprise-outbox' -import { isOrgPlan } from '@/lib/billing/plan-helpers' +import { isOrgPlan, isPro } from '@/lib/billing/plan-helpers' import { isOrgScopedSubscription } from '@/lib/billing/subscriptions/utils' const logger = createLogger('BillingAuthorization') @@ -76,12 +76,11 @@ async function assertNotBilledThroughMarketplace(referenceId: string): Promise { - const [trialing] = await db - .select({ id: subscription.id }) + const trialing = await db + .select({ plan: subscription.plan }) .from(subscription) .where(and(eq(subscription.referenceId, userId), eq(subscription.status, 'trialing'))) - .limit(1) - if (!trialing) return + if (!trialing.some((row) => isPro(row.plan))) return logger.warn('Blocking team upgrade - personal plan is in its free trial', { userId }) throw new APIError('CONFLICT', { diff --git a/apps/sim/lib/billing/core/plan-switch.ts b/apps/sim/lib/billing/core/plan-switch.ts index f7b8948686b..4ca9d068e75 100644 --- a/apps/sim/lib/billing/core/plan-switch.ts +++ b/apps/sim/lib/billing/core/plan-switch.ts @@ -1,7 +1,7 @@ import { db } from '@sim/db' import { organization, subscription as subscriptionTable, userStats } from '@sim/db/schema' import { createLogger } from '@sim/logger' -import { type AnyColumn, eq, sql } from 'drizzle-orm' +import { type AnyColumn, eq, type SQL, sql } from 'drizzle-orm' import { ON_DEMAND_UNLIMITED } from '@/lib/billing/constants' import { writeBillingInterval } from '@/lib/billing/core/subscription' import { @@ -32,9 +32,9 @@ interface SwitchedSubscription extends OrgAllowanceInput { * limit already at the new amount is untouched too: the Stripe webhook's floor sync can raise it * there first. An unlimited limit stays unlimited. * - * `previousLimit` is the limit read before Stripe applied the change ({@link readPoolUsageLimit}). - * Given it, the headroom comes from that value, so a webhook that raised the live limit to the new - * floor first cannot erase headroom the payer chose. + * `previous` is the pool read before Stripe applied the change ({@link readPoolUsageSnapshot}). + * Given it, the headroom comes from that limit and that credit balance, so neither a webhook that + * raised the live limit first nor credit granted meanwhile changes the headroom the payer chose. */ export async function rebaseUsageLimit( params: { @@ -42,20 +42,19 @@ export async function rebaseUsageLimit( previousIncluded: number nextIncluded: number headroomScale?: number - previousLimit?: string | null + previous?: PoolUsageSnapshot }, executor: DbOrTx = db ): Promise { - const { pool, previousIncluded, nextIncluded, headroomScale = 1, previousLimit } = params + const { pool, previousIncluded, nextIncluded, headroomScale = 1, previous } = params + const covered = (included: number, credit: SQL) => + sql`(${toDecimal(included).toString()}::numeric + ${credit})` const rebased = (limit: AnyColumn, creditBalance: AnyColumn) => { - const previousCovered = sql`(${toDecimal(previousIncluded).toString()}::numeric + ${creditBalance})` - const nextCovered = sql`(${toDecimal(nextIncluded).toString()}::numeric + ${creditBalance})` - const before = previousLimit === undefined ? sql`${limit}` : sql`${previousLimit}::numeric` - const headroom = - previousLimit === undefined - ? sql`case when ${limit} = ${nextCovered} then 0 else greatest(0, coalesce(${limit}, ${previousCovered}) - ${previousCovered}) end` - : sql`greatest(0, coalesce(${before}, ${previousCovered}) - ${previousCovered})` - return sql`case when ${before} >= ${ON_DEMAND_UNLIMITED} then ${before} else round(${nextCovered} + ${headroom} * ${headroomScale}::numeric, 2) end` + const before = previous ? sql`${previous.limit}::numeric` : sql`${limit}` + const creditBefore = previous ? sql`${previous.creditBalance}::numeric` : sql`${creditBalance}` + const previousCovered = covered(previousIncluded, creditBefore) + const headroom = sql`case when ${before} = ${covered(nextIncluded, creditBefore)} then 0 else greatest(0, coalesce(${before}, ${previousCovered}) - ${previousCovered}) end` + return sql`case when ${before} >= ${ON_DEMAND_UNLIMITED} then ${before} else round(${covered(nextIncluded, sql`${creditBalance}`)} + ${headroom} * ${headroomScale}::numeric, 2) end` } if (pool.type === 'organization') { @@ -77,25 +76,30 @@ export async function rebaseUsageLimit( } } -/** A usage pool's current limit, as stored: read before a plan switch for {@link rebaseUsageLimit}. */ -export async function readPoolUsageLimit(pool: { +/** A usage pool's limit and prepaid credit as stored, read together before a plan switch. */ +export interface PoolUsageSnapshot { + limit: string | null + creditBalance: string +} + +/** Reads a pool's {@link PoolUsageSnapshot} before a plan switch, for {@link rebaseUsageLimit}. */ +export async function readPoolUsageSnapshot(pool: { type: 'user' | 'organization' id: string -}): Promise { - if (pool.type === 'organization') { - const [row] = await db - .select({ limit: organization.orgUsageLimit }) - .from(organization) - .where(eq(organization.id, pool.id)) - .limit(1) - return row?.limit ?? null - } - const [row] = await db - .select({ limit: userStats.currentUsageLimit }) - .from(userStats) - .where(eq(userStats.userId, pool.id)) - .limit(1) - return row?.limit ?? null +}): Promise { + const [row] = + pool.type === 'organization' + ? await db + .select({ limit: organization.orgUsageLimit, creditBalance: organization.creditBalance }) + .from(organization) + .where(eq(organization.id, pool.id)) + .limit(1) + : await db + .select({ limit: userStats.currentUsageLimit, creditBalance: userStats.creditBalance }) + .from(userStats) + .where(eq(userStats.userId, pool.id)) + .limit(1) + return row } /** @@ -117,9 +121,9 @@ export async function recordPlanSwitch(params: { targetInterval: 'month' | 'year' orgScoped: boolean period?: { start: Date; end: Date } - previousLimit?: string | null + previous?: PoolUsageSnapshot }): Promise { - const { subscription, targetPlanName, targetInterval, orgScoped, period, previousLimit } = params + const { subscription, targetPlanName, targetInterval, orgScoped, period, previous } = params const trialing = !orgScoped && isTrialingSubscription(subscription) const previousInterval = resolveBillingInterval(subscription) @@ -161,7 +165,7 @@ export async function recordPlanSwitch(params: { previousIncluded: previousBase, nextIncluded: nextBase, headroomScale, - previousLimit, + previous, }, tx ) diff --git a/apps/sim/lib/billing/organization.ts b/apps/sim/lib/billing/organization.ts index 611ec47db46..d6e6228e5eb 100644 --- a/apps/sim/lib/billing/organization.ts +++ b/apps/sim/lib/billing/organization.ts @@ -714,9 +714,9 @@ async function reconcileAnnualSeatMonths( const nextIncluded = getOrgIncludedUsageDollars(next) // One transaction: a limit left unrebased after the count advanced would never be retried. The - // count advances only from the one it was computed from, because the rebase moves the limit - // relative to its live value: a concurrent seat sync, webhook, or sweep that read the same count - // would otherwise apply the same delta twice. + // count advances only from the row it was computed from, because the rebase moves the limit + // relative to its live value: a concurrent seat sync, webhook, sweep, or plan switch that changed + // any input since the read would otherwise be rebased over, or the same delta applied twice. const advanced = await db.transaction(async (tx) => { const [claimed] = await tx .update(subscriptionTable) @@ -728,6 +728,14 @@ async function reconcileAnnualSeatMonths( .where( and( eq(subscriptionTable.id, annual.id), + eq(subscriptionTable.plan, annual.plan), + eq(subscriptionTable.periodStart, next.allowancePeriodStart), + annual.seats === null + ? isNull(subscriptionTable.seats) + : eq(subscriptionTable.seats, annual.seats), + annual.billingInterval === null + ? isNull(subscriptionTable.billingInterval) + : eq(subscriptionTable.billingInterval, annual.billingInterval), annual.allowancePeriodStart === null ? isNull(subscriptionTable.allowancePeriodStart) : eq(subscriptionTable.allowancePeriodStart, annual.allowancePeriodStart), diff --git a/apps/sim/lib/billing/plan-allowance.integration.ts b/apps/sim/lib/billing/plan-allowance.integration.ts index bef38baa1ee..f9d49c50541 100644 --- a/apps/sim/lib/billing/plan-allowance.integration.ts +++ b/apps/sim/lib/billing/plan-allowance.integration.ts @@ -385,12 +385,44 @@ describe('recordPlanSwitch', () => { targetPlanName: 'pro_6000', targetInterval: 'year', orgScoped: false, - previousLimit: String(PRO_MONTHLY_DOLLARS + 10), + previous: { limit: String(PRO_MONTHLY_DOLLARS + 10), creditBalance: '0' }, }) expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS * 12 + 120) }) + it('keeps chosen headroom when credit is granted while the switch is in flight', async () => { + // $70 of headroom over Pro before the switch; $50 of credit landed (raising the limit) since. + const userId = await createUser(100 + 50, 50) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'month' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_25000', + targetInterval: 'month', + orgScoped: false, + previous: { limit: '100', creditBalance: '0' }, + }) + + expect(await readLimit(userId)).toBe(MAX_MONTHLY_DOLLARS + 50 + 70) + }) + + it('reads a retry snapshot already at the new floor as untouched', async () => { + // A retry reads the pool after Stripe and its webhook already moved it to the annual floor. + const userId = await createUser(PRO_MONTHLY_DOLLARS * 12) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'month' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'year', + orgScoped: false, + previous: { limit: String(PRO_MONTHLY_DOLLARS * 12), creditBalance: '0' }, + }) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS * 12) + }) + it('records the period Stripe restarted with an interval switch, before the webhook', async () => { const userId = await createUser(PRO_MONTHLY_DOLLARS * 12) const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'year' }) diff --git a/packages/db/migrations/0473_enterprise_self_serve.sql b/packages/db/migrations/0473_enterprise_self_serve.sql index b0469843d28..29c590cf6df 100644 --- a/packages/db/migrations/0473_enterprise_self_serve.sql +++ b/packages/db/migrations/0473_enterprise_self_serve.sql @@ -1,4 +1,4 @@ --- Replay-safe: 0470's embedded COMMIT leaves this file in autocommit, and a lock-timeout retry +-- Replay-safe: the embedded COMMITs in 0470 and 0472 leave this file in autocommit, and a lock-timeout retry -- replays every unjournaled file from the top. CREATE TABLE IF NOT EXISTS "enterprise_seat_true_up" ( "id" text PRIMARY KEY NOT NULL, diff --git a/packages/db/migrations/0474_annual_seat_allowance.sql b/packages/db/migrations/0474_annual_seat_allowance.sql index cad4c890232..a9b279dd64d 100644 --- a/packages/db/migrations/0474_annual_seat_allowance.sql +++ b/packages/db/migrations/0474_annual_seat_allowance.sql @@ -1,4 +1,4 @@ --- Replay-safe: 0470's embedded COMMIT leaves this file in autocommit, and a lock-timeout retry +-- Replay-safe: the embedded COMMITs in 0470 and 0472 leave this file in autocommit, and a lock-timeout retry -- replays every unjournaled file from the top. ALTER TABLE "subscription" ADD COLUMN IF NOT EXISTS "allowance_period_start" timestamp;--> statement-breakpoint ALTER TABLE "subscription" ADD COLUMN IF NOT EXISTS "allowance_seats" integer;--> statement-breakpoint From 715bd5f3fafee97f151998ad444180b0a3585614 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 11:56:22 -0800 Subject: [PATCH 3/4] fix(billing): apply the exact-floor guard only to a limit read after the Stripe switch A pre-switch snapshot predates any webhook, so a limit in it at the new allowance is headroom the payer chose. A retry that finds Stripe already switched takes no snapshot and keeps the live-limit guard. --- apps/sim/app/api/billing/switch-plan/route.ts | 13 ++++++++----- apps/sim/lib/billing/core/plan-switch.ts | 8 ++++++-- .../lib/billing/plan-allowance.integration.ts | 16 +++++++++------- 3 files changed, 23 insertions(+), 14 deletions(-) diff --git a/apps/sim/app/api/billing/switch-plan/route.ts b/apps/sim/app/api/billing/switch-plan/route.ts index 8fc8cd5f0d4..ef783e3d620 100644 --- a/apps/sim/app/api/billing/switch-plan/route.ts +++ b/apps/sim/app/api/billing/switch-plan/route.ts @@ -179,11 +179,14 @@ export const POST = withRouteHandler(async (request: NextRequest) => { }) const orgScoped = await isSubscriptionOrgScoped(sub) - // Read before Stripe applies the switch: its webhook can move the live limit first. - const previous = await readPoolUsageSnapshot({ - type: orgScoped ? 'organization' : 'user', - id: sub.referenceId, - }) + // Read before Stripe applies the switch, since its webhook can move the live limit first. A + // retry finds Stripe already switched, so it has no pre-switch reading to take. + const previous = alreadyOnStripePrice + ? undefined + : await readPoolUsageSnapshot({ + type: orgScoped ? 'organization' : 'user', + id: sub.referenceId, + }) // The item's period after the switch: Stripe's response, or the retrieved item on a retry // that finds Stripe already on the target price. let switchedItem: typeof subscriptionItem | undefined = subscriptionItem diff --git a/apps/sim/lib/billing/core/plan-switch.ts b/apps/sim/lib/billing/core/plan-switch.ts index 4ca9d068e75..4ed0cccfd80 100644 --- a/apps/sim/lib/billing/core/plan-switch.ts +++ b/apps/sim/lib/billing/core/plan-switch.ts @@ -34,7 +34,8 @@ interface SwitchedSubscription extends OrgAllowanceInput { * * `previous` is the pool read before Stripe applied the change ({@link readPoolUsageSnapshot}). * Given it, the headroom comes from that limit and that credit balance, so neither a webhook that - * raised the live limit first nor credit granted meanwhile changes the headroom the payer chose. + * raised the live limit first nor credit granted meanwhile changes the headroom the payer chose; + * a snapshot predates any webhook, so a limit in it at the new amount is chosen headroom. */ export async function rebaseUsageLimit( params: { @@ -53,7 +54,10 @@ export async function rebaseUsageLimit( const before = previous ? sql`${previous.limit}::numeric` : sql`${limit}` const creditBefore = previous ? sql`${previous.creditBalance}::numeric` : sql`${creditBalance}` const previousCovered = covered(previousIncluded, creditBefore) - const headroom = sql`case when ${before} = ${covered(nextIncluded, creditBefore)} then 0 else greatest(0, coalesce(${before}, ${previousCovered}) - ${previousCovered}) end` + const chosen = sql`greatest(0, coalesce(${before}, ${previousCovered}) - ${previousCovered})` + const headroom = previous + ? chosen + : sql`case when ${limit} = ${covered(nextIncluded, sql`${creditBalance}`)} then 0 else ${chosen} end` return sql`case when ${before} >= ${ON_DEMAND_UNLIMITED} then ${before} else round(${covered(nextIncluded, sql`${creditBalance}`)} + ${headroom} * ${headroomScale}::numeric, 2) end` } diff --git a/apps/sim/lib/billing/plan-allowance.integration.ts b/apps/sim/lib/billing/plan-allowance.integration.ts index f9d49c50541..0451e781774 100644 --- a/apps/sim/lib/billing/plan-allowance.integration.ts +++ b/apps/sim/lib/billing/plan-allowance.integration.ts @@ -407,20 +407,22 @@ describe('recordPlanSwitch', () => { expect(await readLimit(userId)).toBe(MAX_MONTHLY_DOLLARS + 50 + 70) }) - it('reads a retry snapshot already at the new floor as untouched', async () => { - // A retry reads the pool after Stripe and its webhook already moved it to the annual floor. - const userId = await createUser(PRO_MONTHLY_DOLLARS * 12) + it('keeps headroom a payer chose that happens to equal the new plan allowance', async () => { + // Raised to Max's allowance on Pro before the switch: that is chosen headroom, not a webhook's. + const userId = await createUser(MAX_MONTHLY_DOLLARS) const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'month' }) await recordPlanSwitch({ subscription: sub, - targetPlanName: 'pro_6000', - targetInterval: 'year', + targetPlanName: 'pro_25000', + targetInterval: 'month', orgScoped: false, - previous: { limit: String(PRO_MONTHLY_DOLLARS * 12), creditBalance: '0' }, + previous: { limit: String(MAX_MONTHLY_DOLLARS), creditBalance: '0' }, }) - expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS * 12) + expect(await readLimit(userId)).toBe( + MAX_MONTHLY_DOLLARS + (MAX_MONTHLY_DOLLARS - PRO_MONTHLY_DOLLARS) + ) }) it('records the period Stripe restarted with an interval switch, before the webhook', async () => { From 97840daf2776e50d1c95e29642b47d25f877a5f9 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 12:14:54 -0800 Subject: [PATCH 4/4] fix(billing): serialize plan switches per billing reference A switch takes the billing reference's checkout admission claim and re-checks that the subscription still holds the plan and interval it computed from, so a concurrent switch cannot snapshot another's new allowance as chosen headroom. --- apps/sim/app/api/billing/switch-plan/route.ts | 33 +++++++++++++++++- apps/sim/lib/billing/core/plan-switch.ts | 23 +++++++++++++ .../lib/billing/plan-allowance.integration.ts | 34 ++++++++++++++++++- 3 files changed, 88 insertions(+), 2 deletions(-) diff --git a/apps/sim/app/api/billing/switch-plan/route.ts b/apps/sim/app/api/billing/switch-plan/route.ts index ef783e3d620..e80969a7e15 100644 --- a/apps/sim/app/api/billing/switch-plan/route.ts +++ b/apps/sim/app/api/billing/switch-plan/route.ts @@ -1,10 +1,16 @@ import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit' import { createLogger } from '@sim/logger' import { getErrorMessage, toError } from '@sim/utils/errors' +import { APIError } from 'better-auth/api' import { type NextRequest, NextResponse } from 'next/server' import { billingSwitchPlanContract } from '@/lib/api/contracts/subscription' import { parseRequest } from '@/lib/api/server' import { getSession } from '@/lib/auth' +import { + type CheckoutAdmissionClaim, + claimCheckoutAdmission, + releaseCheckoutAdmission, +} from '@/lib/billing/checkout-admission' import { getEffectiveBillingStatus } from '@/lib/billing/core/access' import { getOrganizationSubscription, isSubscriptionOrgScoped } from '@/lib/billing/core/billing' import { isOrganizationOwnerOrAdmin } from '@/lib/billing/core/organization' @@ -12,7 +18,11 @@ import { getHighestPriorityPersonalSubscription, getHighestPrioritySubscription, } from '@/lib/billing/core/plan' -import { readPoolUsageSnapshot, recordPlanSwitch } from '@/lib/billing/core/plan-switch' +import { + isSwitchBasisCurrent, + readPoolUsageSnapshot, + recordPlanSwitch, +} from '@/lib/billing/core/plan-switch' import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers' import { getPlanByName } from '@/lib/billing/plans' import { requireStripeClient } from '@/lib/billing/stripe-client' @@ -42,6 +52,7 @@ const logger = createLogger('SwitchPlan') */ export const POST = withRouteHandler(async (request: NextRequest) => { const session = await getSession() + let admission: CheckoutAdmissionClaim | null = null try { if (!session?.user?.id) { @@ -120,6 +131,24 @@ export const POST = withRouteHandler(async (request: NextRequest) => { } } + // One plan change or checkout per billing reference at a time, each computed from the plan + // as it stands once admitted: a second switch must not snapshot the first one's new allowance. + try { + admission = await claimCheckoutAdmission(sub.referenceId) + } catch (error) { + if (!(error instanceof APIError)) throw error + return NextResponse.json( + { error: 'A plan change is already in progress. Please wait a moment and try again.' }, + { status: 409 } + ) + } + if (!(await isSwitchBasisCurrent(sub))) { + return NextResponse.json( + { error: 'Your plan just changed. Refresh the page and try again.' }, + { status: 409 } + ) + } + const stripe = requireStripeClient() const stripeSubscription = await stripe.subscriptions.retrieve(sub.stripeSubscriptionId) @@ -269,5 +298,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => { { error: getErrorMessage(error, 'Failed to switch plan') }, { status: 500 } ) + } finally { + if (admission) await releaseCheckoutAdmission(admission) } }) diff --git a/apps/sim/lib/billing/core/plan-switch.ts b/apps/sim/lib/billing/core/plan-switch.ts index 4ed0cccfd80..1e5fb33212e 100644 --- a/apps/sim/lib/billing/core/plan-switch.ts +++ b/apps/sim/lib/billing/core/plan-switch.ts @@ -80,6 +80,29 @@ export async function rebaseUsageLimit( } } +/** + * Whether a subscription still holds the plan and billing interval a switch was computed from. + * Read under the switch's admission claim: a switch that finished between this request's first + * read and its claim moved the plan, and computing from the stale read would count the new + * allowance as headroom the payer chose. + */ +export async function isSwitchBasisCurrent(basis: SwitchedSubscription): Promise { + const [row] = await db + .select({ + plan: subscriptionTable.plan, + billingInterval: subscriptionTable.billingInterval, + metadata: subscriptionTable.metadata, + }) + .from(subscriptionTable) + .where(eq(subscriptionTable.id, basis.id)) + .limit(1) + return ( + row !== undefined && + row.plan === basis.plan && + resolveBillingInterval(row) === resolveBillingInterval(basis) + ) +} + /** A usage pool's limit and prepaid credit as stored, read together before a plan switch. */ export interface PoolUsageSnapshot { limit: string | null diff --git a/apps/sim/lib/billing/plan-allowance.integration.ts b/apps/sim/lib/billing/plan-allowance.integration.ts index 0451e781774..86cfff6ae25 100644 --- a/apps/sim/lib/billing/plan-allowance.integration.ts +++ b/apps/sim/lib/billing/plan-allowance.integration.ts @@ -11,7 +11,7 @@ import { eq, inArray } from 'drizzle-orm' import { afterAll, describe, expect, it, vi } from 'vitest' import { ON_DEMAND_UNLIMITED } from '@/lib/billing/constants' import { calculateSubscriptionOverage } from '@/lib/billing/core/billing' -import { recordPlanSwitch } from '@/lib/billing/core/plan-switch' +import { isSwitchBasisCurrent, recordPlanSwitch } from '@/lib/billing/core/plan-switch' import { getOrgUsageLimit, syncUsageLimitsFromSubscription } from '@/lib/billing/core/usage' import { closeElapsedBillingPeriod } from '@/lib/billing/cycle-close' import { syncAnnualPlanUsageLimits } from '@/lib/billing/organization' @@ -490,3 +490,35 @@ describe('recordPlanSwitch', () => { expect(await readLimit(userId)).toBe(10) }) }) + +describe('isSwitchBasisCurrent', () => { + it('refuses a switch computed from a plan another switch has since moved', async () => { + const userId = await createUser(PRO_MONTHLY_DOLLARS) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'month' }) + expect(await isSwitchBasisCurrent(sub)).toBe(true) + + // A concurrent request switched to Max after this one read the subscription. + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_25000', + targetInterval: 'month', + orgScoped: false, + }) + + expect(await isSwitchBasisCurrent(sub)).toBe(false) + }) + + it('refuses a switch computed from an interval another switch has since moved', async () => { + const userId = await createUser(PRO_MONTHLY_DOLLARS) + const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'month' }) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'year', + orgScoped: false, + }) + + expect(await isSwitchBasisCurrent(sub)).toBe(false) + }) +})