Skip to content

Commit 1c07331

Browse files
committed
fix(billing): spend final prepaid credit after a lagging close, open-window rate, final invoice payment method
1 parent 0538995 commit 1c07331

3 files changed

Lines changed: 31 additions & 17 deletions

File tree

‎apps/sim/hooks/queries/organization.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@ const BILLING_A: OrganizationPlanSeatsResponse = {
7777
usedSeats: 2,
7878
membersTotal: 2,
7979
hasEnterprisePlan: true,
80+
seatCapKind: 'fixed',
8081
},
8182
}
8283

‎apps/sim/lib/billing/application/organization-billing/get-organization-billing-summary.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ import {
44
organization,
55
subscription as subscriptionTable,
66
} from '@sim/db/schema'
7-
import { and, desc, eq, isNull } from 'drizzle-orm'
7+
import { and, desc, eq, gt, isNull } from 'drizzle-orm'
88
import { defineAuthorizedOrganizationBillingUseCase } from '@/lib/billing/application/organization-billing/authorized-organization-billing-use-case'
99
import { organizationBillingOperations } from '@/lib/billing/application/organization-billing/operations'
1010
import { getOrganizationSubscription } from '@/lib/billing/core/billing'
@@ -73,7 +73,9 @@ async function getOpenTrueUpWindow(subscriptionId: string) {
7373
.where(
7474
and(
7575
eq(enterpriseSeatTrueUp.subscriptionId, subscriptionId),
76-
isNull(enterpriseSeatTrueUp.billedAt)
76+
isNull(enterpriseSeatTrueUp.billedAt),
77+
// A closed window awaiting the hourly sweep is not the open one.
78+
gt(enterpriseSeatTrueUp.windowEnd, new Date())
7779
)
7880
)
7981
.orderBy(desc(enterpriseSeatTrueUp.windowStart))

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

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ import {
1414
import { restoreUserProSubscription } from '@/lib/billing/organizations/membership'
1515
import { isEnterprise, isPaid, isPro, isTeam } from '@/lib/billing/plan-helpers'
1616
import { requireStripeClient } from '@/lib/billing/stripe-client'
17+
import { getPaymentMethodId } from '@/lib/billing/stripe-payment-method'
1718
import { ENTITLED_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/utils'
1819
import { toDecimal, toNumber } from '@/lib/billing/utils/decimal'
1920
import { 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
*/
256259
async 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

Comments
 (0)