Skip to content

Commit 0297579

Browse files
committed
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
1 parent 7ef574c commit 0297579

10 files changed

Lines changed: 316 additions & 74 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: 54 additions & 42 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,65 @@ 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 plan or interval no longer matches `basis`: a switch that finished between this request's
98+
* first read and its claim moved it, and computing from the stale read would count the new
99+
* allowance as headroom the payer chose. 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.plan !== basis.plan ||
116+
resolveBillingInterval(current) !== resolveBillingInterval(basis)
117+
) {
118+
return null
119+
}
120+
const [poolRow] =
121+
pool.type === 'organization'
122+
? await tx
123+
.select({
124+
limit: organization.orgUsageLimit,
125+
creditBalance: organization.creditBalance,
126+
})
127+
.from(organization)
128+
.where(eq(organization.id, pool.id))
129+
.limit(1)
130+
: await tx
131+
.select({
132+
limit: userStats.currentUsageLimit,
133+
creditBalance: userStats.creditBalance,
134+
})
135+
.from(userStats)
136+
.where(eq(userStats.userId, pool.id))
137+
.limit(1)
138+
return { subscription: current, pool: poolRow }
139+
},
140+
{ isolationLevel: 'repeatable read', accessMode: 'read only' }
141+
)
130142
}
131143

132144
/**

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

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import { eq, inArray } from 'drizzle-orm'
1111
import { afterAll, describe, expect, it, vi } from 'vitest'
1212
import { ON_DEMAND_UNLIMITED } from '@/lib/billing/constants'
1313
import { calculateSubscriptionOverage } from '@/lib/billing/core/billing'
14-
import { isSwitchBasisCurrent, recordPlanSwitch } from '@/lib/billing/core/plan-switch'
14+
import { readSwitchBasis, recordPlanSwitch } from '@/lib/billing/core/plan-switch'
1515
import { getOrgUsageLimit, syncUsageLimitsFromSubscription } from '@/lib/billing/core/usage'
1616
import { closeElapsedBillingPeriod } from '@/lib/billing/cycle-close'
1717
import { syncAnnualPlanUsageLimits } from '@/lib/billing/organization'
@@ -491,11 +491,11 @@ describe('recordPlanSwitch', () => {
491491
})
492492
})
493493

494-
describe('isSwitchBasisCurrent', () => {
494+
describe('readSwitchBasis', () => {
495495
it('refuses a switch computed from a plan another switch has since moved', async () => {
496496
const userId = await createUser(PRO_MONTHLY_DOLLARS)
497497
const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'month' })
498-
expect(await isSwitchBasisCurrent(sub)).toBe(true)
498+
expect(await readSwitchBasis(sub, { type: 'user', id: userId })).not.toBeNull()
499499

500500
// A concurrent request switched to Max after this one read the subscription.
501501
await recordPlanSwitch({
@@ -505,7 +505,7 @@ describe('isSwitchBasisCurrent', () => {
505505
orgScoped: false,
506506
})
507507

508-
expect(await isSwitchBasisCurrent(sub)).toBe(false)
508+
expect(await readSwitchBasis(sub, { type: 'user', id: userId })).toBeNull()
509509
})
510510

511511
it('refuses a switch computed from an interval another switch has since moved', async () => {
@@ -519,6 +519,38 @@ describe('isSwitchBasisCurrent', () => {
519519
orgScoped: false,
520520
})
521521

522-
expect(await isSwitchBasisCurrent(sub)).toBe(false)
522+
expect(await readSwitchBasis(sub, { type: 'user', id: userId })).toBeNull()
523+
})
524+
525+
it('computes a Team switch from seats a sync added after the request read the plan', async () => {
526+
const organizationId = await createOrganization()
527+
const sub = await addSubscription(organizationId, {
528+
plan: 'team_6000',
529+
billingInterval: 'month',
530+
seats: 5,
531+
})
532+
// After the request read five seats, a seat sync added a sixth and raised the limit with it,
533+
// keeping $50 of headroom the admin chose.
534+
await db.update(subscription).set({ seats: 6 }).where(eq(subscription.id, sub.id))
535+
await db
536+
.update(organization)
537+
.set({ orgUsageLimit: String(PRO_MONTHLY_DOLLARS * 6 + 50) })
538+
.where(eq(organization.id, organizationId))
539+
540+
const basis = await readSwitchBasis(sub, { type: 'organization', id: organizationId })
541+
if (!basis) throw new Error('expected the switch basis to still match')
542+
await recordPlanSwitch({
543+
subscription: basis.subscription,
544+
targetPlanName: 'team_25000',
545+
targetInterval: 'month',
546+
orgScoped: true,
547+
previous: basis.pool,
548+
})
549+
550+
const [org] = await db
551+
.select({ orgUsageLimit: organization.orgUsageLimit })
552+
.from(organization)
553+
.where(eq(organization.id, organizationId))
554+
expect(Number(org?.orgUsageLimit)).toBe(MAX_MONTHLY_DOLLARS * 6 + 50)
523555
})
524556
})

0 commit comments

Comments
 (0)