@@ -12,6 +12,7 @@ import {
1212 resolveBillingInterval ,
1313} from '@/lib/billing/subscriptions/utils'
1414import { toDecimal } from '@/lib/billing/utils/decimal'
15+ import type { DbOrTx } from '@/lib/db/types'
1516
1617const 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' , {
0 commit comments