From 31db25269a0187061b20895f3af86bf3787bd2f7 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 19:37:07 -0800 Subject: [PATCH 1/3] fix(billing): release audit follow-ups for v0.9.66 billing - a paid invoice unblocks every member still blocked for payment, not only when the org owner is - a plan switch reads the subscription and its usage pool in one snapshot under its claim, so a seat sync cannot price one seat count against a limit set for another - a hosted-key plan check that cannot read the balance fails with a plain message, not the raw database error - the Team-during-trial message covers a canceled trial --- apps/sim/app/api/billing/switch-plan/route.ts | 27 ++- apps/sim/lib/billing/authorization.ts | 2 +- apps/sim/lib/billing/core/access.ts | 32 ++++ apps/sim/lib/billing/core/chat-access.ts | 6 +- apps/sim/lib/billing/core/plan-switch.ts | 96 +++++----- .../lib/billing/plan-allowance.integration.ts | 42 ++++- .../billing/webhooks/invoices.integration.ts | 168 ++++++++++++++++++ .../sim/lib/billing/webhooks/invoices.test.ts | 5 +- apps/sim/lib/billing/webhooks/invoices.ts | 10 +- .../testing/src/mocks/billing-access.mock.ts | 2 + 10 files changed, 316 insertions(+), 74 deletions(-) create mode 100644 apps/sim/lib/billing/webhooks/invoices.integration.ts diff --git a/apps/sim/app/api/billing/switch-plan/route.ts b/apps/sim/app/api/billing/switch-plan/route.ts index e80969a7e15..925105078b0 100644 --- a/apps/sim/app/api/billing/switch-plan/route.ts +++ b/apps/sim/app/api/billing/switch-plan/route.ts @@ -18,11 +18,7 @@ import { getHighestPriorityPersonalSubscription, getHighestPrioritySubscription, } from '@/lib/billing/core/plan' -import { - isSwitchBasisCurrent, - readPoolUsageSnapshot, - recordPlanSwitch, -} from '@/lib/billing/core/plan-switch' +import { readSwitchBasis, 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' @@ -142,7 +138,12 @@ export const POST = withRouteHandler(async (request: NextRequest) => { { status: 409 } ) } - if (!(await isSwitchBasisCurrent(sub))) { + const orgScoped = await isSubscriptionOrgScoped(sub) + const basis = await readSwitchBasis(sub, { + type: orgScoped ? 'organization' : 'user', + id: sub.referenceId, + }) + if (!basis) { return NextResponse.json( { error: 'Your plan just changed. Refresh the page and try again.' }, { status: 409 } @@ -207,15 +208,9 @@ export const POST = withRouteHandler(async (request: NextRequest) => { targetPriceId, }) - const orgScoped = await isSubscriptionOrgScoped(sub) - // 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 pool was read before the Stripe update, since its webhook can move the live limit first. + // A retry finds Stripe already switched, so that read is not from before the switch. + const previous = alreadyOnStripePrice ? undefined : basis.pool // 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 @@ -242,7 +237,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => { : undefined await recordPlanSwitch({ - subscription: sub, + subscription: basis.subscription, targetPlanName, targetInterval: targetInterval as 'month' | 'year', orgScoped, diff --git a/apps/sim/lib/billing/authorization.ts b/apps/sim/lib/billing/authorization.ts index d758674b0c2..3a255e09d2c 100644 --- a/apps/sim/lib/billing/authorization.ts +++ b/apps/sim/lib/billing/authorization.ts @@ -85,7 +85,7 @@ async function assertNoPersonalTrial(userId: string): Promise { 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.', + 'Your Pro free trial has to end before you can move to a Team plan. End it from Settings > Billing (restore it first if you canceled it), or wait for it to end, then upgrade.', }) } diff --git a/apps/sim/lib/billing/core/access.ts b/apps/sim/lib/billing/core/access.ts index 07832f99ecc..22511d52027 100644 --- a/apps/sim/lib/billing/core/access.ts +++ b/apps/sim/lib/billing/core/access.ts @@ -67,6 +67,38 @@ export async function getBillingEntityBlockStatus( } } +/** + * Whether any account a payer's unblock clears is still marked blocked for `reason`: the user's + * own row, or any member's row of an organization. Unlike {@link getBillingEntityBlockStatus}, + * which reads an organization through its owner, this sees members a fan-out blocked while the + * owner's row was cleared some other way (by another organization's recovery, or an ownership + * transfer to an unmarked member). + */ +export async function hasBillingBlockFor( + payer: { type: 'user' | 'organization'; id: string }, + reason: NonNullable, + executor: DbOrTx = db +): Promise { + const blockedFor = and( + eq(userStats.billingBlocked, true), + eq(userStats.billingBlockedReason, reason) + ) + const [row] = + payer.type === 'user' + ? await executor + .select({ userId: userStats.userId }) + .from(userStats) + .where(and(eq(userStats.userId, payer.id), blockedFor)) + .limit(1) + : await executor + .select({ userId: userStats.userId }) + .from(member) + .innerJoin(userStats, eq(userStats.userId, member.userId)) + .where(and(eq(member.organizationId, payer.id), blockedFor)) + .limit(1) + return row !== undefined +} + /** * Gets the effective billing blocked status for a user. * If the user belongs to an organization, also checks whether the org owner is blocked. diff --git a/apps/sim/lib/billing/core/chat-access.ts b/apps/sim/lib/billing/core/chat-access.ts index 3ac92d7fc70..1a9ccc5c3eb 100644 --- a/apps/sim/lib/billing/core/chat-access.ts +++ b/apps/sim/lib/billing/core/chat-access.ts @@ -45,7 +45,11 @@ export async function payerHasPaidAccess( verdict: options.onBalanceUnavailable, error: getErrorMessage(error), }) - if (options.onBalanceUnavailable === 'throw') throw error + if (options.onBalanceUnavailable === 'throw') { + throw new Error("Couldn't verify the plan for Sim's hosted key. Try again in a moment.", { + cause: error, + }) + } return true } } diff --git a/apps/sim/lib/billing/core/plan-switch.ts b/apps/sim/lib/billing/core/plan-switch.ts index 1e5fb33212e..d3b0d9e1302 100644 --- a/apps/sim/lib/billing/core/plan-switch.ts +++ b/apps/sim/lib/billing/core/plan-switch.ts @@ -32,7 +32,7 @@ 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. * - * `previous` is the pool read before Stripe applied the change ({@link readPoolUsageSnapshot}). + * `previous` is the pool read before Stripe applied the change ({@link readSwitchBasis}). * 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; * a snapshot predates any webhook, so a limit in it at the new amount is chosen headroom. @@ -80,53 +80,65 @@ 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 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 { - 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 +/** What a plan switch computes from: the subscription and its usage pool, read in one snapshot. */ +export interface SwitchBasis { + subscription: typeof subscriptionTable.$inferSelect + pool: PoolUsageSnapshot | undefined +} + +/** + * Reads a plan switch's {@link SwitchBasis} under its admission claim, in one snapshot. Null when + * the plan or interval no longer matches `basis`: a switch that finished between this request's + * first read and its claim moved it, and computing from the stale read would count the new + * allowance as headroom the payer chose. A seat sync takes no claim, so the seats and allowance + * come from this read too, consistent with the pool limit they produced. + */ +export async function readSwitchBasis( + basis: SwitchedSubscription, + pool: { type: 'user' | 'organization'; id: string } +): Promise { + return db.transaction( + async (tx) => { + const [current] = await tx + .select() + .from(subscriptionTable) + .where(eq(subscriptionTable.id, basis.id)) + .limit(1) + if ( + !current || + current.plan !== basis.plan || + resolveBillingInterval(current) !== resolveBillingInterval(basis) + ) { + return null + } + const [poolRow] = + pool.type === 'organization' + ? await tx + .select({ + limit: organization.orgUsageLimit, + creditBalance: organization.creditBalance, + }) + .from(organization) + .where(eq(organization.id, pool.id)) + .limit(1) + : await tx + .select({ + limit: userStats.currentUsageLimit, + creditBalance: userStats.creditBalance, + }) + .from(userStats) + .where(eq(userStats.userId, pool.id)) + .limit(1) + return { subscription: current, pool: poolRow } + }, + { isolationLevel: 'repeatable read', accessMode: 'read only' } + ) } /** diff --git a/apps/sim/lib/billing/plan-allowance.integration.ts b/apps/sim/lib/billing/plan-allowance.integration.ts index 86cfff6ae25..f0d98dc6367 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 { isSwitchBasisCurrent, recordPlanSwitch } from '@/lib/billing/core/plan-switch' +import { readSwitchBasis, 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' @@ -491,11 +491,11 @@ describe('recordPlanSwitch', () => { }) }) -describe('isSwitchBasisCurrent', () => { +describe('readSwitchBasis', () => { 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) + expect(await readSwitchBasis(sub, { type: 'user', id: userId })).not.toBeNull() // A concurrent request switched to Max after this one read the subscription. await recordPlanSwitch({ @@ -505,7 +505,7 @@ describe('isSwitchBasisCurrent', () => { orgScoped: false, }) - expect(await isSwitchBasisCurrent(sub)).toBe(false) + expect(await readSwitchBasis(sub, { type: 'user', id: userId })).toBeNull() }) it('refuses a switch computed from an interval another switch has since moved', async () => { @@ -519,6 +519,38 @@ describe('isSwitchBasisCurrent', () => { orgScoped: false, }) - expect(await isSwitchBasisCurrent(sub)).toBe(false) + expect(await readSwitchBasis(sub, { type: 'user', id: userId })).toBeNull() + }) + + it('computes a Team switch from seats a sync added after the request read the plan', async () => { + const organizationId = await createOrganization() + const sub = await addSubscription(organizationId, { + plan: 'team_6000', + billingInterval: 'month', + seats: 5, + }) + // After the request read five seats, a seat sync added a sixth and raised the limit with it, + // keeping $50 of headroom the admin chose. + await db.update(subscription).set({ seats: 6 }).where(eq(subscription.id, sub.id)) + await db + .update(organization) + .set({ orgUsageLimit: String(PRO_MONTHLY_DOLLARS * 6 + 50) }) + .where(eq(organization.id, organizationId)) + + const basis = await readSwitchBasis(sub, { type: 'organization', id: organizationId }) + if (!basis) throw new Error('expected the switch basis to still match') + await recordPlanSwitch({ + subscription: basis.subscription, + targetPlanName: 'team_25000', + targetInterval: 'month', + orgScoped: true, + previous: basis.pool, + }) + + const [org] = await db + .select({ orgUsageLimit: organization.orgUsageLimit }) + .from(organization) + .where(eq(organization.id, organizationId)) + expect(Number(org?.orgUsageLimit)).toBe(MAX_MONTHLY_DOLLARS * 6 + 50) }) }) diff --git a/apps/sim/lib/billing/webhooks/invoices.integration.ts b/apps/sim/lib/billing/webhooks/invoices.integration.ts new file mode 100644 index 00000000000..c29c0836d3a --- /dev/null +++ b/apps/sim/lib/billing/webhooks/invoices.integration.ts @@ -0,0 +1,168 @@ +/** + * Payment recovery against real PostgreSQL: a paid invoice lifts the payment-failed block from + * every member its failure blocked, whoever the organization's owner is by then. + */ +import { db } from '@sim/db' +import { member, organization, subscription, user, userStats } from '@sim/db/schema' +import { generateId } from '@sim/utils/id' +import { inArray } from 'drizzle-orm' +import type Stripe from 'stripe' +import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { handleInvoicePaymentSucceeded } from '@/lib/billing/webhooks/invoices' + +const { stripeStub } = vi.hoisted(() => ({ + stripeStub: { invoices: { list: vi.fn() } }, +})) + +vi.mock('@/lib/billing/stripe-client', () => ({ + requireStripeClient: () => stripeStub, + getStripeClient: () => stripeStub, +})) + +const userIds: string[] = [] +const organizationIds: string[] = [] + +async function createUser(blocked: boolean): Promise { + const id = `invoice-recovery-${generateId()}` + const now = new Date() + await db.insert(user).values({ + id, + name: 'Invoice Recovery Test', + email: `${id}@invoice-recovery.test`, + emailVerified: true, + createdAt: now, + updatedAt: now, + }) + await db.insert(userStats).values({ + id: generateId(), + userId: id, + billingBlocked: blocked, + billingBlockedReason: blocked ? 'payment_failed' : null, + }) + userIds.push(id) + return id +} + +/** A Team organization whose owner is `ownerBlocked` and whose other members are `membersBlocked`. */ +async function createTeam(ownerBlocked: boolean, membersBlocked: boolean) { + const organizationId = `invoice-recovery-org-${generateId()}` + await db.insert(organization).values({ + id: organizationId, + name: 'Invoice Recovery Org', + slug: organizationId, + createdAt: new Date(), + updatedAt: new Date(), + }) + organizationIds.push(organizationId) + const ownerId = await createUser(ownerBlocked) + const memberIds = [await createUser(membersBlocked), await createUser(membersBlocked)] + for (const [index, userId] of [ownerId, ...memberIds].entries()) { + await db.insert(member).values({ + id: generateId(), + userId, + organizationId, + role: index === 0 ? 'owner' : 'member', + createdAt: new Date(), + }) + } + const stripeSubscriptionId = `sub_${generateId()}` + await db.insert(subscription).values({ + id: generateId(), + plan: 'team_6000', + referenceId: organizationId, + stripeCustomerId: `cus_${generateId()}`, + stripeSubscriptionId, + status: 'active', + seats: 3, + periodStart: new Date(Date.now() - 86_400_000), + periodEnd: new Date(Date.now() + 29 * 86_400_000), + }) + return { organizationId, ownerId, memberIds, stripeSubscriptionId } +} + +function paidOverageInvoice(stripeSubscriptionId: string): Stripe.Event { + const invoice = { + id: `in_${generateId()}`, + object: 'invoice', + amount_paid: 3582, + billing_reason: 'manual', + customer: `cus_${generateId()}`, + currency: 'usd', + metadata: { + billingPeriod: '2026-10', + subscriptionId: stripeSubscriptionId, + type: 'overage_threshold_billing_org', + }, + } + return { + id: `evt_${generateId()}`, + type: 'invoice.payment_succeeded', + data: { object: invoice }, + } as unknown as Stripe.Event +} + +async function blockedUserIds(ids: string[]): Promise { + const rows = await db + .select({ userId: userStats.userId, billingBlocked: userStats.billingBlocked }) + .from(userStats) + .where(inArray(userStats.userId, ids)) + return rows.filter((row) => row.billingBlocked).map((row) => row.userId) +} + +beforeEach(() => { + stripeStub.invoices.list.mockReset() + stripeStub.invoices.list.mockImplementation(async function* () {}) +}) + +afterAll(async () => { + if (organizationIds.length > 0) { + await db.delete(subscription).where(inArray(subscription.referenceId, organizationIds)) + await db.delete(member).where(inArray(member.organizationId, organizationIds)) + await db.delete(organization).where(inArray(organization.id, organizationIds)) + } + if (userIds.length > 0) { + await db.delete(userStats).where(inArray(userStats.userId, userIds)) + await db.delete(user).where(inArray(user.id, userIds)) + } +}) + +describe('a paid invoice after a failed one', () => { + it('unblocks members still blocked when the owner was already unblocked', async () => { + // The owner's row was cleared by another organization's recovery, or ownership moved to a + // member who joined after the block. + const team = await createTeam(false, true) + + await handleInvoicePaymentSucceeded(paidOverageInvoice(team.stripeSubscriptionId)) + + expect(await blockedUserIds([team.ownerId, ...team.memberIds])).toEqual([]) + }) + + it('keeps members blocked while another invoice for the plan is still failing', async () => { + const team = await createTeam(true, true) + stripeStub.invoices.list.mockImplementation(async function* () { + yield { + id: `in_${generateId()}`, + collection_method: 'charge_automatically', + attempt_count: 1, + metadata: { + subscriptionId: team.stripeSubscriptionId, + type: 'overage_threshold_billing_org', + }, + } + }) + + await handleInvoicePaymentSucceeded(paidOverageInvoice(team.stripeSubscriptionId)) + + expect((await blockedUserIds([team.ownerId, ...team.memberIds])).sort()).toEqual( + [team.ownerId, ...team.memberIds].sort() + ) + }) + + it('skips the Stripe invoice listing for an organization nobody is blocked in', async () => { + const team = await createTeam(false, false) + + await handleInvoicePaymentSucceeded(paidOverageInvoice(team.stripeSubscriptionId)) + + expect(stripeStub.invoices.list).not.toHaveBeenCalled() + }) +}) diff --git a/apps/sim/lib/billing/webhooks/invoices.test.ts b/apps/sim/lib/billing/webhooks/invoices.test.ts index 10281b6d666..60038e0b712 100644 --- a/apps/sim/lib/billing/webhooks/invoices.test.ts +++ b/apps/sim/lib/billing/webhooks/invoices.test.ts @@ -145,10 +145,7 @@ describe('invoice billing recovery', () => { urlsMockFns.mockGetBaseUrl.mockReturnValue('https://sim.test') mockBlockOrgMembers.mockResolvedValue(2) mockUnblockOrgMembers.mockResolvedValue(2) - billingAccessMockFns.mockGetBillingEntityBlockStatus.mockResolvedValue({ - billingBlocked: true, - billingBlockedReason: 'payment_failed', - }) + billingAccessMockFns.mockHasBillingBlockFor.mockResolvedValue(true) }) 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 a7e42455732..c7ae5253a78 100644 --- a/apps/sim/lib/billing/webhooks/invoices.ts +++ b/apps/sim/lib/billing/webhooks/invoices.ts @@ -10,7 +10,7 @@ import { renderCreditPurchaseEmail, renderPaymentFailedEmail, } from '@/components/emails' -import { getBillingEntityBlockStatus } from '@/lib/billing/core/access' +import { hasBillingBlockFor } 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' @@ -647,10 +647,10 @@ export async function handleInvoicePaymentSucceeded(event: Stripe.Event) { const subIsOrgScoped = await isSubscriptionOrgScoped(sub) const isProrationInvoice = invoice.billing_reason === 'subscription_update' - const { billingBlocked } = await getBillingEntityBlockStatus({ - type: subIsOrgScoped ? 'organization' : 'user', - id: sub.referenceId, - }) + const billingBlocked = await hasBillingBlockFor( + { type: subIsOrgScoped ? 'organization' : 'user', id: sub.referenceId }, + 'payment_failed' + ) const paysSomething = !isProrationInvoice || (invoice.amount_paid ?? 0) > 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 diff --git a/packages/testing/src/mocks/billing-access.mock.ts b/packages/testing/src/mocks/billing-access.mock.ts index 284fb2b6608..c86fbd13086 100644 --- a/packages/testing/src/mocks/billing-access.mock.ts +++ b/packages/testing/src/mocks/billing-access.mock.ts @@ -18,6 +18,7 @@ export const billingAccessMockFns = { mockGetBillingEntityBlockStatus: vi.fn(), mockGetEffectiveBillingStatus: vi.fn(), mockIsOrganizationBillingBlocked: vi.fn(), + mockHasBillingBlockFor: vi.fn(), } /** @@ -32,4 +33,5 @@ export const billingAccessMock = { getBillingEntityBlockStatus: billingAccessMockFns.mockGetBillingEntityBlockStatus, getEffectiveBillingStatus: billingAccessMockFns.mockGetEffectiveBillingStatus, isOrganizationBillingBlocked: billingAccessMockFns.mockIsOrganizationBillingBlocked, + hasBillingBlockFor: billingAccessMockFns.mockHasBillingBlockFor, } From 92f669b9a4a4b7c12d095db126eaa82ebeb5ee92 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 19:49:11 -0800 Subject: [PATCH 2/3] fix(billing): price a plan switch from the seats locked at record time A seat sync takes no switch claim and can land while Stripe applies the change, so the new allowance comes from the subscription row locked in the recording transaction. The integration fixture builds its event with the shared Stripe event helper. --- apps/sim/lib/billing/core/plan-switch.ts | 35 ++++++++++-------- .../lib/billing/plan-allowance.integration.ts | 36 +++++++++++++++++++ .../billing/webhooks/invoices.integration.ts | 34 +++++++++--------- 3 files changed, 74 insertions(+), 31 deletions(-) diff --git a/apps/sim/lib/billing/core/plan-switch.ts b/apps/sim/lib/billing/core/plan-switch.ts index d3b0d9e1302..ac6c33c5d37 100644 --- a/apps/sim/lib/billing/core/plan-switch.ts +++ b/apps/sim/lib/billing/core/plan-switch.ts @@ -153,6 +153,11 @@ export async function readSwitchBasis( * 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. + * + * The new allowance comes from the subscription row as locked here, since a seat sync takes no + * switch claim and can land while Stripe applies the change. The old allowance is the one the limit + * read was taken against: `subscription`'s, which `previous` was read with, or the locked row's + * for the live limit. */ export async function recordPlanSwitch(params: { subscription: SwitchedSubscription @@ -167,22 +172,26 @@ export async function recordPlanSwitch(params: { const trialing = !orgScoped && isTrialingSubscription(subscription) const previousInterval = resolveBillingInterval(subscription) 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 - const nextBase = orgScoped ? getOrgIncludedUsageDollars(target) : getPlanPricing(target).basePrice + const includedUsage = (sub: SwitchedSubscription) => + orgScoped ? getOrgIncludedUsageDollars(sub) : getPlanPricing(sub).basePrice const headroomScale = previousInterval === targetInterval ? 1 : targetInterval === 'year' ? 12 : 1 / 12 // 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) => { + const [locked] = await tx + .select() + .from(subscriptionTable) + .where(eq(subscriptionTable.id, subscription.id)) + .for('update') + const current = locked ?? subscription + const target = { + ...current, + plan: targetPlanName, + billingInterval: targetInterval, + ...(restartedPeriod ? { periodStart: restartedPeriod.start } : {}), + } if (subscription.plan !== targetPlanName || restartedPeriod) { await tx .update(subscriptionTable) @@ -201,8 +210,8 @@ export async function recordPlanSwitch(params: { pool: orgScoped ? { type: 'organization', id: subscription.referenceId } : { type: 'user', id: subscription.referenceId }, - previousIncluded: previousBase, - nextIncluded: nextBase, + previousIncluded: includedUsage(previous ? subscription : current), + nextIncluded: includedUsage(target), headroomScale, previous, }, @@ -215,7 +224,5 @@ export async function recordPlanSwitch(params: { fromPlan: subscription.plan, toPlan: targetPlanName, interval: targetInterval, - previousBase, - nextBase, }) } diff --git a/apps/sim/lib/billing/plan-allowance.integration.ts b/apps/sim/lib/billing/plan-allowance.integration.ts index f0d98dc6367..5b39c544f58 100644 --- a/apps/sim/lib/billing/plan-allowance.integration.ts +++ b/apps/sim/lib/billing/plan-allowance.integration.ts @@ -553,4 +553,40 @@ describe('readSwitchBasis', () => { .where(eq(organization.id, organizationId)) expect(Number(org?.orgUsageLimit)).toBe(MAX_MONTHLY_DOLLARS * 6 + 50) }) + + it('prices a Team switch for a seat a sync added while Stripe applied it', async () => { + const organizationId = await createOrganization() + await db + .update(organization) + .set({ orgUsageLimit: String(PRO_MONTHLY_DOLLARS * 5 + 50) }) + .where(eq(organization.id, organizationId)) + const sub = await addSubscription(organizationId, { + plan: 'team_6000', + billingInterval: 'month', + seats: 5, + }) + const basis = await readSwitchBasis(sub, { type: 'organization', id: organizationId }) + if (!basis) throw new Error('expected the switch basis to match') + + // Between that read and recording the switch, a seat sync added a sixth seat. + await db.update(subscription).set({ seats: 6 }).where(eq(subscription.id, sub.id)) + await db + .update(organization) + .set({ orgUsageLimit: String(PRO_MONTHLY_DOLLARS * 6 + 50) }) + .where(eq(organization.id, organizationId)) + + await recordPlanSwitch({ + subscription: basis.subscription, + targetPlanName: 'team_25000', + targetInterval: 'month', + orgScoped: true, + previous: basis.pool, + }) + + const [org] = await db + .select({ orgUsageLimit: organization.orgUsageLimit }) + .from(organization) + .where(eq(organization.id, organizationId)) + expect(Number(org?.orgUsageLimit)).toBe(MAX_MONTHLY_DOLLARS * 6 + 50) + }) }) diff --git a/apps/sim/lib/billing/webhooks/invoices.integration.ts b/apps/sim/lib/billing/webhooks/invoices.integration.ts index c29c0836d3a..cf3a91a7464 100644 --- a/apps/sim/lib/billing/webhooks/invoices.integration.ts +++ b/apps/sim/lib/billing/webhooks/invoices.integration.ts @@ -4,6 +4,7 @@ */ import { db } from '@sim/db' import { member, organization, subscription, user, userStats } from '@sim/db/schema' +import { createMockStripeEvent } from '@sim/testing/mocks/stripe.mock' import { generateId } from '@sim/utils/id' import { inArray } from 'drizzle-orm' import type Stripe from 'stripe' @@ -81,24 +82,23 @@ async function createTeam(ownerBlocked: boolean, membersBlocked: boolean) { } function paidOverageInvoice(stripeSubscriptionId: string): Stripe.Event { - const invoice = { - id: `in_${generateId()}`, - object: 'invoice', - amount_paid: 3582, - billing_reason: 'manual', - customer: `cus_${generateId()}`, - currency: 'usd', - metadata: { - billingPeriod: '2026-10', - subscriptionId: stripeSubscriptionId, - type: 'overage_threshold_billing_org', + return createMockStripeEvent( + 'invoice.payment_succeeded', + { + id: `in_${generateId()}`, + object: 'invoice', + amount_paid: 3582, + billing_reason: 'manual', + customer: `cus_${generateId()}`, + currency: 'usd', + metadata: { + billingPeriod: '2026-10', + subscriptionId: stripeSubscriptionId, + type: 'overage_threshold_billing_org', + }, }, - } - return { - id: `evt_${generateId()}`, - type: 'invoice.payment_succeeded', - data: { object: invoice }, - } as unknown as Stripe.Event + { id: `evt_${generateId()}` } + ) } async function blockedUserIds(ids: string[]): Promise { From 6524d2204974f082507374c3096a7c51bd30631c Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Thu, 26 Nov 2026 20:00:51 -0800 Subject: [PATCH 3/3] fix(billing): price a retried switch's old allowance from the plan it left A retry finds the subscription webhook may already have recorded the new plan, so the old allowance always comes from the request's plan and interval, with the locked seat count for the live limit. A switch is refused when the subscription moved to another payer since it was read. The invoice fixture pays from the subscription's own Stripe customer. --- apps/sim/lib/billing/core/plan-switch.ts | 20 +++++++++------- .../lib/billing/plan-allowance.integration.ts | 16 +++++++++++++ .../billing/webhooks/invoices.integration.ts | 23 ++++++++++++------- 3 files changed, 43 insertions(+), 16 deletions(-) diff --git a/apps/sim/lib/billing/core/plan-switch.ts b/apps/sim/lib/billing/core/plan-switch.ts index ac6c33c5d37..6bae6ec8d21 100644 --- a/apps/sim/lib/billing/core/plan-switch.ts +++ b/apps/sim/lib/billing/core/plan-switch.ts @@ -94,9 +94,9 @@ export interface SwitchBasis { /** * Reads a plan switch's {@link SwitchBasis} under its admission claim, in one snapshot. Null when - * the plan or interval no longer matches `basis`: a switch that finished between this request's - * first read and its claim moved it, and computing from the stale read would count the new - * allowance as headroom the payer chose. A seat sync takes no claim, so the seats and allowance + * the payer, plan or interval no longer matches `basis`: a switch that finished between this + * request's first read and its claim moved it, and computing from the stale read would count the + * new allowance as headroom the payer chose, or rebase the wrong pool. A seat sync takes no claim, so the seats and allowance * come from this read too, consistent with the pool limit they produced. */ export async function readSwitchBasis( @@ -112,6 +112,7 @@ export async function readSwitchBasis( .limit(1) if ( !current || + current.referenceId !== basis.referenceId || current.plan !== basis.plan || resolveBillingInterval(current) !== resolveBillingInterval(basis) ) { @@ -154,10 +155,11 @@ export async function readSwitchBasis( * 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. * - * The new allowance comes from the subscription row as locked here, since a seat sync takes no - * switch claim and can land while Stripe applies the change. The old allowance is the one the limit - * read was taken against: `subscription`'s, which `previous` was read with, or the locked row's - * for the live limit. + * Seats come from the subscription row as locked here, since a seat sync takes no switch claim and + * can land while Stripe applies the change; the old plan and interval always come from + * `subscription`, since the subscription webhook can record the new plan first. The old allowance + * is priced for the seats the limit read was taken with: `subscription`'s, which `previous` was + * read with, or the locked row's for the live limit. */ export async function recordPlanSwitch(params: { subscription: SwitchedSubscription @@ -210,7 +212,9 @@ export async function recordPlanSwitch(params: { pool: orgScoped ? { type: 'organization', id: subscription.referenceId } : { type: 'user', id: subscription.referenceId }, - previousIncluded: includedUsage(previous ? subscription : current), + previousIncluded: includedUsage( + previous ? subscription : { ...subscription, seats: current.seats } + ), nextIncluded: includedUsage(target), headroomScale, previous, diff --git a/apps/sim/lib/billing/plan-allowance.integration.ts b/apps/sim/lib/billing/plan-allowance.integration.ts index 5b39c544f58..d3934365ce1 100644 --- a/apps/sim/lib/billing/plan-allowance.integration.ts +++ b/apps/sim/lib/billing/plan-allowance.integration.ts @@ -522,6 +522,22 @@ describe('readSwitchBasis', () => { expect(await readSwitchBasis(sub, { type: 'user', id: userId })).toBeNull() }) + it('reads the old allowance from the plan the request switched from on a retry', async () => { + // Untouched Max limit; a retry finds Stripe on Pro and the webhook already recorded Pro. + const userId = await createUser(MAX_MONTHLY_DOLLARS) + const sub = await addSubscription(userId, { plan: 'pro_25000', billingInterval: 'month' }) + await db.update(subscription).set({ plan: 'pro_6000' }).where(eq(subscription.id, sub.id)) + + await recordPlanSwitch({ + subscription: sub, + targetPlanName: 'pro_6000', + targetInterval: 'month', + orgScoped: false, + }) + + expect(await readLimit(userId)).toBe(PRO_MONTHLY_DOLLARS) + }) + it('computes a Team switch from seats a sync added after the request read the plan', async () => { const organizationId = await createOrganization() const sub = await addSubscription(organizationId, { diff --git a/apps/sim/lib/billing/webhooks/invoices.integration.ts b/apps/sim/lib/billing/webhooks/invoices.integration.ts index cf3a91a7464..a0ef4975931 100644 --- a/apps/sim/lib/billing/webhooks/invoices.integration.ts +++ b/apps/sim/lib/billing/webhooks/invoices.integration.ts @@ -67,21 +67,25 @@ async function createTeam(ownerBlocked: boolean, membersBlocked: boolean) { }) } const stripeSubscriptionId = `sub_${generateId()}` + const stripeCustomerId = `cus_${generateId()}` await db.insert(subscription).values({ id: generateId(), plan: 'team_6000', referenceId: organizationId, - stripeCustomerId: `cus_${generateId()}`, + stripeCustomerId, stripeSubscriptionId, status: 'active', seats: 3, periodStart: new Date(Date.now() - 86_400_000), periodEnd: new Date(Date.now() + 29 * 86_400_000), }) - return { organizationId, ownerId, memberIds, stripeSubscriptionId } + return { organizationId, ownerId, memberIds, stripeSubscriptionId, stripeCustomerId } } -function paidOverageInvoice(stripeSubscriptionId: string): Stripe.Event { +function paidOverageInvoice(team: { + stripeSubscriptionId: string + stripeCustomerId: string +}): Stripe.Event { return createMockStripeEvent( 'invoice.payment_succeeded', { @@ -89,11 +93,11 @@ function paidOverageInvoice(stripeSubscriptionId: string): Stripe.Event { object: 'invoice', amount_paid: 3582, billing_reason: 'manual', - customer: `cus_${generateId()}`, + customer: team.stripeCustomerId, currency: 'usd', metadata: { billingPeriod: '2026-10', - subscriptionId: stripeSubscriptionId, + subscriptionId: team.stripeSubscriptionId, type: 'overage_threshold_billing_org', }, }, @@ -132,7 +136,7 @@ describe('a paid invoice after a failed one', () => { // member who joined after the block. const team = await createTeam(false, true) - await handleInvoicePaymentSucceeded(paidOverageInvoice(team.stripeSubscriptionId)) + await handleInvoicePaymentSucceeded(paidOverageInvoice(team)) expect(await blockedUserIds([team.ownerId, ...team.memberIds])).toEqual([]) }) @@ -151,8 +155,11 @@ describe('a paid invoice after a failed one', () => { } }) - await handleInvoicePaymentSucceeded(paidOverageInvoice(team.stripeSubscriptionId)) + await handleInvoicePaymentSucceeded(paidOverageInvoice(team)) + expect(stripeStub.invoices.list).toHaveBeenCalledWith( + expect.objectContaining({ customer: team.stripeCustomerId, status: 'open' }) + ) expect((await blockedUserIds([team.ownerId, ...team.memberIds])).sort()).toEqual( [team.ownerId, ...team.memberIds].sort() ) @@ -161,7 +168,7 @@ describe('a paid invoice after a failed one', () => { it('skips the Stripe invoice listing for an organization nobody is blocked in', async () => { const team = await createTeam(false, false) - await handleInvoicePaymentSucceeded(paidOverageInvoice(team.stripeSubscriptionId)) + await handleInvoicePaymentSucceeded(paidOverageInvoice(team)) expect(stripeStub.invoices.list).not.toHaveBeenCalled() })