Skip to content

Commit 5a2c3fa

Browse files
committed
fix(billing): fractional seat-months, chosen headroom kept on upgrades, allowance and limit writes in one transaction
1 parent dadaa27 commit 5a2c3fa

13 files changed

Lines changed: 117 additions & 68 deletions

File tree

‎apps/sim/ee/access-requests/lib/application/flow.integration.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ beforeAll(async () => {
8787
period_start timestamp, period_end timestamp, cancel_at_period_end boolean,
8888
cancel_at timestamp, canceled_at timestamp, ended_at timestamp, seats integer,
8989
trial_start timestamp, trial_end timestamp, billing_interval text,
90-
stripe_schedule_id text, metadata json, last_closed_period_start timestamp, allowance_period_start timestamp, allowance_seats integer, allowance_seat_months integer
90+
stripe_schedule_id text, metadata json, last_closed_period_start timestamp, allowance_period_start timestamp, allowance_seats integer, allowance_seat_months numeric
9191
);
9292
CREATE TABLE workspace (
9393
id text PRIMARY KEY, name text NOT NULL, owner_id text REFERENCES "user"(id),

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,7 @@ export async function calculateSubscriptionOverage(sub: {
175175
periodEnd?: Date | null
176176
trialEnd?: Date | null
177177
allowancePeriodStart?: Date | null
178-
allowanceSeatMonths?: number | null
178+
allowanceSeatMonths?: number | string | null
179179
}): Promise<number> {
180180
if (isHardCappedEnterprise(sub)) {
181181
logger.info('Enterprise plan has no overages', {

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

Lines changed: 45 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
resolveBillingInterval,
1313
} from '@/lib/billing/subscriptions/utils'
1414
import { toDecimal } from '@/lib/billing/utils/decimal'
15+
import type { DbOrTx } from '@/lib/db/types'
1516

1617
const logger = createLogger('PlanSwitch')
1718

@@ -24,35 +25,40 @@ interface SwitchedSubscription extends OrgAllowanceInput {
2425
}
2526

2627
/**
27-
* Moves a usage pool's limit from one included-usage amount to another. A limit at or below what
28-
* either amount covers (with prepaid credit) lands on the new one, so an untouched limit never
29-
* reads as on-demand usage nobody turned on, even when a webhook already raised it to the new
30-
* amount. A limit raised above both keeps that headroom, scaled by `headroomScale` (an interval
31-
* change turns a year's headroom into a month's twelfth). An unlimited limit stays unlimited.
28+
* Moves a usage pool's limit from one included-usage amount to another. The on-demand headroom
29+
* the payer chose above the old amount (with prepaid credit) carries over, scaled by
30+
* `headroomScale` (an interval change turns a year's headroom into a month's twelfth), so an
31+
* untouched limit lands on the new amount and never reads as on-demand usage nobody turned on. A
32+
* limit already at the new amount is untouched too: the Stripe webhook's floor sync can raise it
33+
* there first. An unlimited limit stays unlimited.
3234
*/
33-
export async function rebaseUsageLimit(params: {
34-
pool: { type: 'user' | 'organization'; id: string }
35-
previousIncluded: number
36-
nextIncluded: number
37-
headroomScale?: number
38-
}): Promise<void> {
35+
export async function rebaseUsageLimit(
36+
params: {
37+
pool: { type: 'user' | 'organization'; id: string }
38+
previousIncluded: number
39+
nextIncluded: number
40+
headroomScale?: number
41+
},
42+
executor: DbOrTx = db
43+
): Promise<void> {
3944
const { pool, previousIncluded, nextIncluded, headroomScale = 1 } = params
4045
const rebased = (limit: AnyColumn, creditBalance: AnyColumn) => {
41-
const covered = sql`(${toDecimal(Math.max(previousIncluded, nextIncluded)).toString()}::numeric + ${creditBalance})`
42-
const headroom = sql`greatest(0, coalesce(${limit}, ${covered}) - ${covered})`
43-
return sql`case when ${limit} >= ${ON_DEMAND_UNLIMITED} then ${limit} else ${toDecimal(nextIncluded).toString()}::numeric + ${creditBalance} + ${headroom} * ${headroomScale}::numeric end`
46+
const previousCovered = sql`(${toDecimal(previousIncluded).toString()}::numeric + ${creditBalance})`
47+
const nextCovered = sql`(${toDecimal(nextIncluded).toString()}::numeric + ${creditBalance})`
48+
const headroom = sql`case when ${limit} = ${nextCovered} then 0 else greatest(0, coalesce(${limit}, ${previousCovered}) - ${previousCovered}) end`
49+
return sql`case when ${limit} >= ${ON_DEMAND_UNLIMITED} then ${limit} else ${nextCovered} + ${headroom} * ${headroomScale}::numeric end`
4450
}
4551

4652
if (pool.type === 'organization') {
47-
await db
53+
await executor
4854
.update(organization)
4955
.set({
5056
orgUsageLimit: rebased(organization.orgUsageLimit, organization.creditBalance),
5157
updatedAt: new Date(),
5258
})
5359
.where(eq(organization.id, pool.id))
5460
} else {
55-
await db
61+
await executor
5662
.update(userStats)
5763
.set({
5864
currentUsageLimit: rebased(userStats.currentUsageLimit, userStats.creditBalance),
@@ -78,16 +84,7 @@ export async function recordPlanSwitch(params: {
7884
}): Promise<void> {
7985
const { subscription, targetPlanName, targetInterval, orgScoped } = params
8086

81-
if (subscription.plan !== targetPlanName) {
82-
await db
83-
.update(subscriptionTable)
84-
.set({ plan: targetPlanName })
85-
.where(eq(subscriptionTable.id, subscription.id))
86-
}
87-
await writeBillingInterval(subscription.id, targetInterval)
88-
89-
if (!orgScoped && isTrialingSubscription(subscription)) return
90-
87+
const trialing = !orgScoped && isTrialingSubscription(subscription)
9188
const previousInterval = resolveBillingInterval(subscription)
9289
const target = { ...subscription, plan: targetPlanName, billingInterval: targetInterval }
9390
const previousBase = orgScoped
@@ -97,13 +94,28 @@ export async function recordPlanSwitch(params: {
9794
const headroomScale =
9895
previousInterval === targetInterval ? 1 : targetInterval === 'year' ? 12 : 1 / 12
9996

100-
await rebaseUsageLimit({
101-
pool: orgScoped
102-
? { type: 'organization', id: subscription.referenceId }
103-
: { type: 'user', id: subscription.referenceId },
104-
previousIncluded: previousBase,
105-
nextIncluded: nextBase,
106-
headroomScale,
97+
// One transaction: a retry of a half-recorded switch finds the plan already matching and would
98+
// never rebase the limit.
99+
await db.transaction(async (tx) => {
100+
if (subscription.plan !== targetPlanName) {
101+
await tx
102+
.update(subscriptionTable)
103+
.set({ plan: targetPlanName })
104+
.where(eq(subscriptionTable.id, subscription.id))
105+
}
106+
await writeBillingInterval(subscription.id, targetInterval, tx)
107+
if (trialing) return
108+
await rebaseUsageLimit(
109+
{
110+
pool: orgScoped
111+
? { type: 'organization', id: subscription.referenceId }
112+
: { type: 'user', id: subscription.referenceId },
113+
previousIncluded: previousBase,
114+
nextIncluded: nextBase,
115+
headroomScale,
116+
},
117+
tx
118+
)
107119
})
108120

109121
logger.info('Recorded plan switch', {

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

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,10 +54,11 @@ export interface HasPaidSubscriptionOptions {
5454
*/
5555
export async function writeBillingInterval(
5656
subscriptionId: string,
57-
interval: 'month' | 'year'
57+
interval: 'month' | 'year',
58+
executor: DbOrTx = db
5859
): Promise<void> {
5960
const patch = JSON.stringify({ billingInterval: interval })
60-
await db
61+
await executor
6162
.update(subscription)
6263
.set({
6364
billingInterval: interval,

‎apps/sim/lib/billing/core/usage-log.integration.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ describe('Cumulative billing with PostgreSQL', () => {
143143
CREATE TABLE driver_probe (id text PRIMARY KEY);
144144
CREATE TABLE subscription (
145145
id text PRIMARY KEY, period_start timestamp, period_end timestamp,
146-
last_closed_period_start timestamp, allowance_period_start timestamp, allowance_seats integer, allowance_seat_months integer, metadata json
146+
last_closed_period_start timestamp, allowance_period_start timestamp, allowance_seats integer, allowance_seat_months numeric, metadata json
147147
)
148148
`)
149149
transaction.mockImplementation(async (callback: (tx: Transaction) => Promise<unknown>) => {

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

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ type SubscriptionData = {
3939
metadata?: unknown
4040
periodStart?: Date | null
4141
allowancePeriodStart?: Date | null
42-
allowanceSeatMonths?: number | null
42+
allowanceSeatMonths?: number | string | null
4343
/** Correlation copied from Stripe metadata by the generic webhook callback. */
4444
enterpriseOperationId?: string | null
4545
}
@@ -698,33 +698,35 @@ async function reconcileAnnualSeatMonths(
698698
samePeriod && annual.allowanceSeats !== null && annual.allowanceSeatMonths !== null
699699
? Math.max(
700700
0,
701-
annual.allowanceSeatMonths +
702-
Math.round((seats - annual.allowanceSeats) * monthsRemaining(annual.periodEnd, now))
701+
Number(annual.allowanceSeatMonths) +
702+
(seats - annual.allowanceSeats) * monthsRemaining(annual.periodEnd, now)
703703
)
704704
: seats * 12
705705
const next = {
706706
...annual,
707707
allowancePeriodStart: annual.periodStart,
708708
allowanceSeats: seats,
709-
allowanceSeatMonths,
709+
allowanceSeatMonths: allowanceSeatMonths.toFixed(4),
710710
}
711-
await db
712-
.update(subscriptionTable)
713-
.set({
714-
allowancePeriodStart: next.allowancePeriodStart,
715-
allowanceSeats: next.allowanceSeats,
716-
allowanceSeatMonths: next.allowanceSeatMonths,
717-
})
718-
.where(eq(subscriptionTable.id, annual.id))
719-
720711
const previousIncluded = getOrgIncludedUsageDollars(annual)
721712
const nextIncluded = getOrgIncludedUsageDollars(next)
722-
if (previousIncluded !== nextIncluded) {
723-
await rebaseUsageLimit({
724-
pool: { type: 'organization', id: organizationId },
725-
previousIncluded,
726-
nextIncluded,
727-
})
728-
}
713+
714+
// One transaction: a limit left unrebased after the count advanced would never be retried.
715+
await db.transaction(async (tx) => {
716+
await tx
717+
.update(subscriptionTable)
718+
.set({
719+
allowancePeriodStart: next.allowancePeriodStart,
720+
allowanceSeats: next.allowanceSeats,
721+
allowanceSeatMonths: next.allowanceSeatMonths,
722+
})
723+
.where(eq(subscriptionTable.id, annual.id))
724+
if (previousIncluded !== nextIncluded) {
725+
await rebaseUsageLimit(
726+
{ pool: { type: 'organization', id: organizationId }, previousIncluded, nextIncluded },
727+
tx
728+
)
729+
}
730+
})
729731
return next
730732
}

‎apps/sim/lib/billing/organizations/seats.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,7 +82,7 @@ export async function reconcileOrganizationSeats({
8282
metadata: unknown
8383
periodStart: Date | null
8484
allowancePeriodStart: Date | null
85-
allowanceSeatMonths: number | null
85+
allowanceSeatMonths: string | null
8686
}
8787
}
8888

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

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -182,9 +182,29 @@ describe('annual plan allowance', () => {
182182
await syncAnnualPlanUsageLimits()
183183

184184
const [row] = await db.select().from(subscription).where(eq(subscription.id, sub.id))
185-
expect(row?.allowanceSeatMonths).toBe(3 * 12 + 2 * 2)
185+
const recorded = Number(row?.allowanceSeatMonths)
186+
expect(recorded).toBeCloseTo(3 * 12 + 2 * (60 / 30.44), 3)
186187
const { minimum } = await getOrgUsageLimit(organizationId, row as NonNullable<typeof row>)
187-
expect(minimum).toBe((3 * 12 + 2 * 2) * PRO_MONTHLY_DOLLARS)
188+
expect(minimum).toBeCloseTo(recorded * PRO_MONTHLY_DOLLARS, 2)
189+
})
190+
191+
it('credits a seat added in the last days of the year for the days left', async () => {
192+
const organizationId = await createOrganization()
193+
const sub = await addSubscription(organizationId, {
194+
plan: 'team_6000',
195+
billingInterval: 'year',
196+
seats: 1,
197+
})
198+
await syncAnnualPlanUsageLimits()
199+
await db
200+
.update(subscription)
201+
.set({ seats: 2, periodEnd: new Date(Date.now() + 10 * DAY_MS) })
202+
.where(eq(subscription.id, sub.id))
203+
204+
await syncAnnualPlanUsageLimits()
205+
206+
const [row] = await db.select().from(subscription).where(eq(subscription.id, sub.id))
207+
expect(Number(row?.allowanceSeatMonths)).toBeCloseTo(12 + 10 / 30.44, 3)
188208
})
189209

190210
it('lowers an untouched Team limit when a seat leaves partway through the year', async () => {
@@ -206,7 +226,7 @@ describe('annual plan allowance', () => {
206226
.select({ orgUsageLimit: organization.orgUsageLimit })
207227
.from(organization)
208228
.where(eq(organization.id, organizationId))
209-
expect(Number(org?.orgUsageLimit)).toBe((2 * 12 - 6) * PRO_MONTHLY_DOLLARS)
229+
expect(Number(org?.orgUsageLimit)).toBeCloseTo((2 * 12 - 182 / 30.44) * PRO_MONTHLY_DOLLARS, 1)
210230
})
211231

212232
it('raises annual subscriptions still capped at one month and leaves monthly ones alone', async () => {
@@ -282,6 +302,20 @@ describe('recordPlanSwitch', () => {
282302
expect(row?.plan).toBe('pro_6000')
283303
})
284304

305+
it('keeps chosen headroom on an upgrade to a pricier tier', async () => {
306+
const userId = await createUser(100)
307+
const sub = await addSubscription(userId, { plan: 'pro_6000', billingInterval: 'month' })
308+
309+
await recordPlanSwitch({
310+
subscription: sub,
311+
targetPlanName: 'pro_25000',
312+
targetInterval: 'month',
313+
orgScoped: false,
314+
})
315+
316+
expect(await readLimit(userId)).toBe(MAX_MONTHLY_DOLLARS + (100 - PRO_MONTHLY_DOLLARS))
317+
})
318+
285319
it('keeps the on-demand headroom a payer raised above the old plan', async () => {
286320
const userId = await createUser(500)
287321
const sub = await addSubscription(userId, { plan: 'pro_25000', billingInterval: 'month' })

‎apps/sim/lib/billing/storage/project-accounting.integration.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ describe('Project storage admission, transfer, and reconciliation in PostgreSQL'
9494
stripe_customer_id text, stripe_subscription_id text, status text, period_start timestamp,
9595
period_end timestamp, cancel_at_period_end boolean, cancel_at timestamp, canceled_at timestamp,
9696
ended_at timestamp, seats integer, trial_start timestamp, trial_end timestamp,
97-
billing_interval text, stripe_schedule_id text, metadata json, last_closed_period_start timestamp, allowance_period_start timestamp, allowance_seats integer, allowance_seat_months integer);
97+
billing_interval text, stripe_schedule_id text, metadata json, last_closed_period_start timestamp, allowance_period_start timestamp, allowance_seats integer, allowance_seat_months numeric);
9898
CREATE TABLE project (id text PRIMARY KEY, owner_id text NOT NULL, organization_id text,
9999
organization_scope_key text GENERATED ALWAYS AS (CASE WHEN organization_id IS NULL THEN 'personal' ELSE 'organization:' || organization_id END) STORED,
100100
name text NOT NULL DEFAULT 'Project', created_at timestamp NOT NULL DEFAULT now(),

‎apps/sim/lib/billing/subscriptions/utils.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ export interface OrgAllowanceInput extends PlanPricingInput {
130130
seats?: number | null
131131
periodStart?: Date | null
132132
allowancePeriodStart?: Date | null
133-
allowanceSeatMonths?: number | null
133+
allowanceSeatMonths?: number | string | null
134134
}
135135

136136
/**
@@ -144,7 +144,7 @@ function getAnnualSeatMonths(subscription: OrgAllowanceInput): number {
144144
subscription.periodStart != null &&
145145
subscription.allowancePeriodStart.getTime() === subscription.periodStart.getTime()
146146
return recordedForThisPeriod
147-
? (subscription.allowanceSeatMonths ?? 0)
147+
? Number(subscription.allowanceSeatMonths)
148148
: (subscription.seats || 1) * 12
149149
}
150150

0 commit comments

Comments
 (0)