Skip to content

Commit e691123

Browse files
authored
fix(billing): release audit follow-ups for v0.9.66 billing (#10457)
* 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 * 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. * 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.
1 parent 2e84e9b commit e691123

10 files changed

Lines changed: 400 additions & 88 deletions

File tree

‎apps/sim/app/api/billing/switch-plan/route.ts‎

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,7 @@ import {
1818
getHighestPriorityPersonalSubscription,
1919
getHighestPrioritySubscription,
2020
} from '@/lib/billing/core/plan'
21-
import {
22-
isSwitchBasisCurrent,
23-
readPoolUsageSnapshot,
24-
recordPlanSwitch,
25-
} from '@/lib/billing/core/plan-switch'
21+
import { readSwitchBasis, recordPlanSwitch } from '@/lib/billing/core/plan-switch'
2622
import { getPlanTierCredits, getPlanType, isEnterprise } from '@/lib/billing/plan-helpers'
2723
import { getPlanByName } from '@/lib/billing/plans'
2824
import { requireStripeClient } from '@/lib/billing/stripe-client'
@@ -142,7 +138,12 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
142138
{ status: 409 }
143139
)
144140
}
145-
if (!(await isSwitchBasisCurrent(sub))) {
141+
const orgScoped = await isSubscriptionOrgScoped(sub)
142+
const basis = await readSwitchBasis(sub, {
143+
type: orgScoped ? 'organization' : 'user',
144+
id: sub.referenceId,
145+
})
146+
if (!basis) {
146147
return NextResponse.json(
147148
{ error: 'Your plan just changed. Refresh the page and try again.' },
148149
{ status: 409 }
@@ -207,15 +208,9 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
207208
targetPriceId,
208209
})
209210

210-
const orgScoped = await isSubscriptionOrgScoped(sub)
211-
// Read before Stripe applies the switch, since its webhook can move the live limit first. A
212-
// retry finds Stripe already switched, so it has no pre-switch reading to take.
213-
const previous = alreadyOnStripePrice
214-
? undefined
215-
: await readPoolUsageSnapshot({
216-
type: orgScoped ? 'organization' : 'user',
217-
id: sub.referenceId,
218-
})
211+
// The pool was read before the Stripe update, since its webhook can move the live limit first.
212+
// A retry finds Stripe already switched, so that read is not from before the switch.
213+
const previous = alreadyOnStripePrice ? undefined : basis.pool
219214
// The item's period after the switch: Stripe's response, or the retrieved item on a retry
220215
// that finds Stripe already on the target price.
221216
let switchedItem: typeof subscriptionItem | undefined = subscriptionItem
@@ -242,7 +237,7 @@ export const POST = withRouteHandler(async (request: NextRequest) => {
242237
: undefined
243238

244239
await recordPlanSwitch({
245-
subscription: sub,
240+
subscription: basis.subscription,
246241
targetPlanName,
247242
targetInterval: targetInterval as 'month' | 'year',
248243
orgScoped,

‎apps/sim/lib/billing/authorization.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ async function assertNoPersonalTrial(userId: string): Promise<void> {
8585
logger.warn('Blocking team upgrade - personal plan is in its free trial', { userId })
8686
throw new APIError('CONFLICT', {
8787
message:
88-
'Your Pro free trial has to end before you can move to a Team plan. End the trial now from Settings > Billing, then upgrade.',
88+
'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.',
8989
})
9090
}
9191

‎apps/sim/lib/billing/core/access.ts‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,38 @@ export async function getBillingEntityBlockStatus(
6767
}
6868
}
6969

70+
/**
71+
* Whether any account a payer's unblock clears is still marked blocked for `reason`: the user's
72+
* own row, or any member's row of an organization. Unlike {@link getBillingEntityBlockStatus},
73+
* which reads an organization through its owner, this sees members a fan-out blocked while the
74+
* owner's row was cleared some other way (by another organization's recovery, or an ownership
75+
* transfer to an unmarked member).
76+
*/
77+
export async function hasBillingBlockFor(
78+
payer: { type: 'user' | 'organization'; id: string },
79+
reason: NonNullable<BillingEntityBlockStatus['billingBlockedReason']>,
80+
executor: DbOrTx = db
81+
): Promise<boolean> {
82+
const blockedFor = and(
83+
eq(userStats.billingBlocked, true),
84+
eq(userStats.billingBlockedReason, reason)
85+
)
86+
const [row] =
87+
payer.type === 'user'
88+
? await executor
89+
.select({ userId: userStats.userId })
90+
.from(userStats)
91+
.where(and(eq(userStats.userId, payer.id), blockedFor))
92+
.limit(1)
93+
: await executor
94+
.select({ userId: userStats.userId })
95+
.from(member)
96+
.innerJoin(userStats, eq(userStats.userId, member.userId))
97+
.where(and(eq(member.organizationId, payer.id), blockedFor))
98+
.limit(1)
99+
return row !== undefined
100+
}
101+
70102
/**
71103
* Gets the effective billing blocked status for a user.
72104
* If the user belongs to an organization, also checks whether the org owner is blocked.

‎apps/sim/lib/billing/core/chat-access.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,11 @@ export async function payerHasPaidAccess(
4545
verdict: options.onBalanceUnavailable,
4646
error: getErrorMessage(error),
4747
})
48-
if (options.onBalanceUnavailable === 'throw') throw error
48+
if (options.onBalanceUnavailable === 'throw') {
49+
throw new Error("Couldn't verify the plan for Sim's hosted key. Try again in a moment.", {
50+
cause: error,
51+
})
52+
}
4953
return true
5054
}
5155
}

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

Lines changed: 79 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ interface SwitchedSubscription extends OrgAllowanceInput {
3232
* limit already at the new amount is untouched too: the Stripe webhook's floor sync can raise it
3333
* there first. An unlimited limit stays unlimited.
3434
*
35-
* `previous` is the pool read before Stripe applied the change ({@link readPoolUsageSnapshot}).
35+
* `previous` is the pool read before Stripe applied the change ({@link readSwitchBasis}).
3636
* Given it, the headroom comes from that limit and that credit balance, so neither a webhook that
3737
* raised the live limit first nor credit granted meanwhile changes the headroom the payer chose;
3838
* a snapshot predates any webhook, so a limit in it at the new amount is chosen headroom.
@@ -80,53 +80,66 @@ export async function rebaseUsageLimit(
8080
}
8181
}
8282

83-
/**
84-
* Whether a subscription still holds the plan and billing interval a switch was computed from.
85-
* Read under the switch's admission claim: a switch that finished between this request's first
86-
* read and its claim moved the plan, and computing from the stale read would count the new
87-
* allowance as headroom the payer chose.
88-
*/
89-
export async function isSwitchBasisCurrent(basis: SwitchedSubscription): Promise<boolean> {
90-
const [row] = await db
91-
.select({
92-
plan: subscriptionTable.plan,
93-
billingInterval: subscriptionTable.billingInterval,
94-
metadata: subscriptionTable.metadata,
95-
})
96-
.from(subscriptionTable)
97-
.where(eq(subscriptionTable.id, basis.id))
98-
.limit(1)
99-
return (
100-
row !== undefined &&
101-
row.plan === basis.plan &&
102-
resolveBillingInterval(row) === resolveBillingInterval(basis)
103-
)
104-
}
105-
10683
/** A usage pool's limit and prepaid credit as stored, read together before a plan switch. */
10784
export interface PoolUsageSnapshot {
10885
limit: string | null
10986
creditBalance: string
11087
}
11188

112-
/** Reads a pool's {@link PoolUsageSnapshot} before a plan switch, for {@link rebaseUsageLimit}. */
113-
export async function readPoolUsageSnapshot(pool: {
114-
type: 'user' | 'organization'
115-
id: string
116-
}): Promise<PoolUsageSnapshot | undefined> {
117-
const [row] =
118-
pool.type === 'organization'
119-
? await db
120-
.select({ limit: organization.orgUsageLimit, creditBalance: organization.creditBalance })
121-
.from(organization)
122-
.where(eq(organization.id, pool.id))
123-
.limit(1)
124-
: await db
125-
.select({ limit: userStats.currentUsageLimit, creditBalance: userStats.creditBalance })
126-
.from(userStats)
127-
.where(eq(userStats.userId, pool.id))
128-
.limit(1)
129-
return row
89+
/** What a plan switch computes from: the subscription and its usage pool, read in one snapshot. */
90+
export interface SwitchBasis {
91+
subscription: typeof subscriptionTable.$inferSelect
92+
pool: PoolUsageSnapshot | undefined
93+
}
94+
95+
/**
96+
* Reads a plan switch's {@link SwitchBasis} under its admission claim, in one snapshot. Null when
97+
* the payer, plan or interval no longer matches `basis`: a switch that finished between this
98+
* request's first read and its claim moved it, and computing from the stale read would count the
99+
* new allowance as headroom the payer chose, or rebase the wrong pool. A seat sync takes no claim, so the seats and allowance
100+
* come from this read too, consistent with the pool limit they produced.
101+
*/
102+
export async function readSwitchBasis(
103+
basis: SwitchedSubscription,
104+
pool: { type: 'user' | 'organization'; id: string }
105+
): Promise<SwitchBasis | null> {
106+
return db.transaction(
107+
async (tx) => {
108+
const [current] = await tx
109+
.select()
110+
.from(subscriptionTable)
111+
.where(eq(subscriptionTable.id, basis.id))
112+
.limit(1)
113+
if (
114+
!current ||
115+
current.referenceId !== basis.referenceId ||
116+
current.plan !== basis.plan ||
117+
resolveBillingInterval(current) !== resolveBillingInterval(basis)
118+
) {
119+
return null
120+
}
121+
const [poolRow] =
122+
pool.type === 'organization'
123+
? await tx
124+
.select({
125+
limit: organization.orgUsageLimit,
126+
creditBalance: organization.creditBalance,
127+
})
128+
.from(organization)
129+
.where(eq(organization.id, pool.id))
130+
.limit(1)
131+
: await tx
132+
.select({
133+
limit: userStats.currentUsageLimit,
134+
creditBalance: userStats.creditBalance,
135+
})
136+
.from(userStats)
137+
.where(eq(userStats.userId, pool.id))
138+
.limit(1)
139+
return { subscription: current, pool: poolRow }
140+
},
141+
{ isolationLevel: 'repeatable read', accessMode: 'read only' }
142+
)
130143
}
131144

132145
/**
@@ -141,6 +154,12 @@ export async function readPoolUsageSnapshot(pool: {
141154
* written with the interval: until the subscription webhook lands, the old period with the new
142155
* interval would price a year of usage against a month's allowance, and threshold billing would
143156
* collect overage the old year's close then finds it never owed.
157+
*
158+
* Seats come from the subscription row as locked here, since a seat sync takes no switch claim and
159+
* can land while Stripe applies the change; the old plan and interval always come from
160+
* `subscription`, since the subscription webhook can record the new plan first. The old allowance
161+
* is priced for the seats the limit read was taken with: `subscription`'s, which `previous` was
162+
* read with, or the locked row's for the live limit.
144163
*/
145164
export async function recordPlanSwitch(params: {
146165
subscription: SwitchedSubscription
@@ -155,22 +174,26 @@ export async function recordPlanSwitch(params: {
155174
const trialing = !orgScoped && isTrialingSubscription(subscription)
156175
const previousInterval = resolveBillingInterval(subscription)
157176
const restartedPeriod = previousInterval !== targetInterval ? period : undefined
158-
const target = {
159-
...subscription,
160-
plan: targetPlanName,
161-
billingInterval: targetInterval,
162-
...(restartedPeriod ? { periodStart: restartedPeriod.start } : {}),
163-
}
164-
const previousBase = orgScoped
165-
? getOrgIncludedUsageDollars(subscription)
166-
: getPlanPricing(subscription).basePrice
167-
const nextBase = orgScoped ? getOrgIncludedUsageDollars(target) : getPlanPricing(target).basePrice
177+
const includedUsage = (sub: SwitchedSubscription) =>
178+
orgScoped ? getOrgIncludedUsageDollars(sub) : getPlanPricing(sub).basePrice
168179
const headroomScale =
169180
previousInterval === targetInterval ? 1 : targetInterval === 'year' ? 12 : 1 / 12
170181

171182
// One transaction: a retry of a half-recorded switch finds the plan already matching and would
172183
// never rebase the limit.
173184
await db.transaction(async (tx) => {
185+
const [locked] = await tx
186+
.select()
187+
.from(subscriptionTable)
188+
.where(eq(subscriptionTable.id, subscription.id))
189+
.for('update')
190+
const current = locked ?? subscription
191+
const target = {
192+
...current,
193+
plan: targetPlanName,
194+
billingInterval: targetInterval,
195+
...(restartedPeriod ? { periodStart: restartedPeriod.start } : {}),
196+
}
174197
if (subscription.plan !== targetPlanName || restartedPeriod) {
175198
await tx
176199
.update(subscriptionTable)
@@ -189,8 +212,10 @@ export async function recordPlanSwitch(params: {
189212
pool: orgScoped
190213
? { type: 'organization', id: subscription.referenceId }
191214
: { type: 'user', id: subscription.referenceId },
192-
previousIncluded: previousBase,
193-
nextIncluded: nextBase,
215+
previousIncluded: includedUsage(
216+
previous ? subscription : { ...subscription, seats: current.seats }
217+
),
218+
nextIncluded: includedUsage(target),
194219
headroomScale,
195220
previous,
196221
},
@@ -203,7 +228,5 @@ export async function recordPlanSwitch(params: {
203228
fromPlan: subscription.plan,
204229
toPlan: targetPlanName,
205230
interval: targetInterval,
206-
previousBase,
207-
nextBase,
208231
})
209232
}

0 commit comments

Comments
 (0)