@@ -14,6 +14,7 @@ import {
1414import { restoreUserProSubscription } from '@/lib/billing/organizations/membership'
1515import { isEnterprise , isPaid , isPro , isTeam } from '@/lib/billing/plan-helpers'
1616import { requireStripeClient } from '@/lib/billing/stripe-client'
17+ import { getPaymentMethodId } from '@/lib/billing/stripe-payment-method'
1718import { ENTITLED_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/utils'
1819import { toDecimal , toNumber } from '@/lib/billing/utils/decimal'
1920import { stripeWebhookIdempotency } from '@/lib/billing/webhooks/idempotency'
@@ -249,13 +250,16 @@ export async function handleSubscriptionCreated(
249250
250251/**
251252 * Spends an organization's prepaid credit on its final-period overage and returns the overage now
252- * covered: what threshold billing already collected plus the credit spent. The credit is recorded
253- * in the same billed-overage tracker threshold billing uses, under the same row locks, so a
254- * replayed deletion finds it already covered and spends nothing twice.
253+ * covered: what threshold billing already collected this period plus the credit spent. The tracker
254+ * ends holding exactly that sum, under the same row locks threshold billing takes, so a replayed
255+ * deletion finds the credit already counted and spends nothing twice. When the tracker belongs to
256+ * an elapsed, forgiven period (`trackerIsCurrent` false) its collections count for nothing here and
257+ * are replaced, but the credit still covers the final period.
255258 */
256259async function spendFinalPrepaidCredit (
257260 organizationId : string ,
258- totalOverage : number
261+ totalOverage : number ,
262+ trackerIsCurrent : boolean
259263) : Promise < number > {
260264 return db . transaction ( async ( tx ) => {
261265 const [ owner ] = await tx
@@ -279,22 +283,22 @@ async function spendFinalPrepaidCredit(
279283 . where ( eq ( organization . id , organizationId ) )
280284 . for ( 'update' )
281285 . limit ( 1 )
282- const billed = toNumber ( toDecimal ( tracker ?. billedOverageThisPeriod ) )
286+ const collected = trackerIsCurrent ? toNumber ( toDecimal ( tracker ?. billedOverageThisPeriod ) ) : 0
283287 const credit = Math . min (
284- Math . max ( 0 , totalOverage - billed ) ,
288+ Math . max ( 0 , totalOverage - collected ) ,
285289 toNumber ( toDecimal ( org ?. creditBalance ) )
286290 )
287- if ( credit <= 0 || ! tracker ) return billed
291+ if ( credit <= 0 || ! tracker ) return collected
288292 await tx
289293 . update ( organization )
290294 . set ( { creditBalance : sql `GREATEST(0, ${ organization . creditBalance } - ${ credit } )` } )
291295 . where ( eq ( organization . id , organizationId ) )
292296 await tx
293297 . update ( userStats )
294- . set ( { billedOverageThisPeriod : sql ` ${ userStats . billedOverageThisPeriod } + ${ credit } ` } )
298+ . set ( { billedOverageThisPeriod : String ( collected + credit ) } )
295299 . where ( eq ( userStats . userId , owner . userId ) )
296300 logger . info ( 'Spent prepaid credit on final overage' , { organizationId, credit } )
297- return billed + credit
301+ return collected + credit
298302 } )
299303}
300304
@@ -320,11 +324,11 @@ async function invoiceFinalOverage(params: {
320324
321325 // An Enterprise contract's prepaid credit is part of what it already paid for, so it covers the
322326 // final period's usage before anything is invoiced.
323- const billedOverage = ! params . markerWasCurrent
324- ? 0
325- : isEnterprise ( subscription . plan )
326- ? await spendFinalPrepaidCredit ( subscription . referenceId , totalOverage )
327- : await getBilledOverageForSubscription ( subscription )
327+ const billedOverage = isEnterprise ( subscription . plan )
328+ ? await spendFinalPrepaidCredit ( subscription . referenceId , totalOverage , params . markerWasCurrent )
329+ : params . markerWasCurrent
330+ ? await getBilledOverageForSubscription ( subscription )
331+ : 0
328332 const remainingOverage = Math . max ( 0 , totalOverage - billedOverage )
329333
330334 logger . info ( 'Subscription deleted overage calculation' , {
@@ -343,6 +347,7 @@ async function invoiceFinalOverage(params: {
343347 const endedAt = stripeSubscription . ended_at || Math . floor ( Date . now ( ) / 1000 )
344348 const billingPeriod = new Date ( endedAt * 1000 ) . toISOString ( ) . slice ( 0 , 7 )
345349 const sendInvoice = stripeSubscription . collection_method === 'send_invoice'
350+ const subscriptionPaymentMethod = getPaymentMethodId ( stripeSubscription . default_payment_method )
346351
347352 const itemIdemKey = `final-overage-item:${ customerId } :${ stripeSubscriptionId } :${ billingPeriod } `
348353 const invoiceIdemKey = `final-overage-invoice:${ customerId } :${ stripeSubscriptionId } :${ billingPeriod } `
@@ -354,7 +359,13 @@ async function invoiceFinalOverage(params: {
354359 customer : customerId ,
355360 ...( sendInvoice
356361 ? { collection_method : 'send_invoice' , days_until_due : INVOICE_DAYS_UNTIL_DUE }
357- : { collection_method : 'charge_automatically' } ) ,
362+ : {
363+ collection_method : 'charge_automatically' ,
364+ // An unlinked invoice otherwise falls back to the customer's default method only.
365+ ...( subscriptionPaymentMethod
366+ ? { default_payment_method : subscriptionPaymentMethod }
367+ : { } ) ,
368+ } ) ,
358369 auto_advance : true ,
359370 description : `Final overage charges for ${ subscription . plan } subscription (${ billingPeriod } )` ,
360371 metadata : {
0 commit comments