Skip to content

Commit 6b6da31

Browse files
committed
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.
1 parent 360933d commit 6b6da31

3 files changed

Lines changed: 74 additions & 31 deletions

File tree

‎apps/sim/lib/billing/core/plan-switch.ts‎

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,11 @@ export async function readSwitchBasis(
153153
* written with the interval: until the subscription webhook lands, the old period with the new
154154
* interval would price a year of usage against a month's allowance, and threshold billing would
155155
* collect overage the old year's close then finds it never owed.
156+
*
157+
* The new allowance comes from the subscription row as locked here, since a seat sync takes no
158+
* switch claim and can land while Stripe applies the change. The old allowance is the one the limit
159+
* read was taken against: `subscription`'s, which `previous` was read with, or the locked row's
160+
* for the live limit.
156161
*/
157162
export async function recordPlanSwitch(params: {
158163
subscription: SwitchedSubscription
@@ -167,22 +172,26 @@ export async function recordPlanSwitch(params: {
167172
const trialing = !orgScoped && isTrialingSubscription(subscription)
168173
const previousInterval = resolveBillingInterval(subscription)
169174
const restartedPeriod = previousInterval !== targetInterval ? period : undefined
170-
const target = {
171-
...subscription,
172-
plan: targetPlanName,
173-
billingInterval: targetInterval,
174-
...(restartedPeriod ? { periodStart: restartedPeriod.start } : {}),
175-
}
176-
const previousBase = orgScoped
177-
? getOrgIncludedUsageDollars(subscription)
178-
: getPlanPricing(subscription).basePrice
179-
const nextBase = orgScoped ? getOrgIncludedUsageDollars(target) : getPlanPricing(target).basePrice
175+
const includedUsage = (sub: SwitchedSubscription) =>
176+
orgScoped ? getOrgIncludedUsageDollars(sub) : getPlanPricing(sub).basePrice
180177
const headroomScale =
181178
previousInterval === targetInterval ? 1 : targetInterval === 'year' ? 12 : 1 / 12
182179

183180
// One transaction: a retry of a half-recorded switch finds the plan already matching and would
184181
// never rebase the limit.
185182
await db.transaction(async (tx) => {
183+
const [locked] = await tx
184+
.select()
185+
.from(subscriptionTable)
186+
.where(eq(subscriptionTable.id, subscription.id))
187+
.for('update')
188+
const current = locked ?? subscription
189+
const target = {
190+
...current,
191+
plan: targetPlanName,
192+
billingInterval: targetInterval,
193+
...(restartedPeriod ? { periodStart: restartedPeriod.start } : {}),
194+
}
186195
if (subscription.plan !== targetPlanName || restartedPeriod) {
187196
await tx
188197
.update(subscriptionTable)
@@ -201,8 +210,8 @@ export async function recordPlanSwitch(params: {
201210
pool: orgScoped
202211
? { type: 'organization', id: subscription.referenceId }
203212
: { type: 'user', id: subscription.referenceId },
204-
previousIncluded: previousBase,
205-
nextIncluded: nextBase,
213+
previousIncluded: includedUsage(previous ? subscription : current),
214+
nextIncluded: includedUsage(target),
206215
headroomScale,
207216
previous,
208217
},
@@ -215,7 +224,5 @@ export async function recordPlanSwitch(params: {
215224
fromPlan: subscription.plan,
216225
toPlan: targetPlanName,
217226
interval: targetInterval,
218-
previousBase,
219-
nextBase,
220227
})
221228
}

‎apps/sim/lib/billing/plan-allowance.integration.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,4 +553,40 @@ describe('readSwitchBasis', () => {
553553
.where(eq(organization.id, organizationId))
554554
expect(Number(org?.orgUsageLimit)).toBe(MAX_MONTHLY_DOLLARS * 6 + 50)
555555
})
556+
557+
it('prices a Team switch for a seat a sync added while Stripe applied it', async () => {
558+
const organizationId = await createOrganization()
559+
await db
560+
.update(organization)
561+
.set({ orgUsageLimit: String(PRO_MONTHLY_DOLLARS * 5 + 50) })
562+
.where(eq(organization.id, organizationId))
563+
const sub = await addSubscription(organizationId, {
564+
plan: 'team_6000',
565+
billingInterval: 'month',
566+
seats: 5,
567+
})
568+
const basis = await readSwitchBasis(sub, { type: 'organization', id: organizationId })
569+
if (!basis) throw new Error('expected the switch basis to match')
570+
571+
// Between that read and recording the switch, a seat sync added a sixth seat.
572+
await db.update(subscription).set({ seats: 6 }).where(eq(subscription.id, sub.id))
573+
await db
574+
.update(organization)
575+
.set({ orgUsageLimit: String(PRO_MONTHLY_DOLLARS * 6 + 50) })
576+
.where(eq(organization.id, organizationId))
577+
578+
await recordPlanSwitch({
579+
subscription: basis.subscription,
580+
targetPlanName: 'team_25000',
581+
targetInterval: 'month',
582+
orgScoped: true,
583+
previous: basis.pool,
584+
})
585+
586+
const [org] = await db
587+
.select({ orgUsageLimit: organization.orgUsageLimit })
588+
.from(organization)
589+
.where(eq(organization.id, organizationId))
590+
expect(Number(org?.orgUsageLimit)).toBe(MAX_MONTHLY_DOLLARS * 6 + 50)
591+
})
556592
})

‎apps/sim/lib/billing/webhooks/invoices.integration.ts‎

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
*/
55
import { db } from '@sim/db'
66
import { member, organization, subscription, user, userStats } from '@sim/db/schema'
7+
import { createMockStripeEvent } from '@sim/testing/mocks/stripe.mock'
78
import { generateId } from '@sim/utils/id'
89
import { inArray } from 'drizzle-orm'
910
import type Stripe from 'stripe'
@@ -81,24 +82,23 @@ async function createTeam(ownerBlocked: boolean, membersBlocked: boolean) {
8182
}
8283

8384
function paidOverageInvoice(stripeSubscriptionId: string): Stripe.Event {
84-
const invoice = {
85-
id: `in_${generateId()}`,
86-
object: 'invoice',
87-
amount_paid: 3582,
88-
billing_reason: 'manual',
89-
customer: `cus_${generateId()}`,
90-
currency: 'usd',
91-
metadata: {
92-
billingPeriod: '2026-10',
93-
subscriptionId: stripeSubscriptionId,
94-
type: 'overage_threshold_billing_org',
85+
return createMockStripeEvent(
86+
'invoice.payment_succeeded',
87+
{
88+
id: `in_${generateId()}`,
89+
object: 'invoice',
90+
amount_paid: 3582,
91+
billing_reason: 'manual',
92+
customer: `cus_${generateId()}`,
93+
currency: 'usd',
94+
metadata: {
95+
billingPeriod: '2026-10',
96+
subscriptionId: stripeSubscriptionId,
97+
type: 'overage_threshold_billing_org',
98+
},
9599
},
96-
}
97-
return {
98-
id: `evt_${generateId()}`,
99-
type: 'invoice.payment_succeeded',
100-
data: { object: invoice },
101-
} as unknown as Stripe.Event
100+
{ id: `evt_${generateId()}` }
101+
)
102102
}
103103

104104
async function blockedUserIds(ids: string[]): Promise<string[]> {

0 commit comments

Comments
 (0)