Skip to content

Commit c42155c

Browse files
committed
fix(billing): recheck self-serve under the contract lease before auto-pay; route true-up payment events
1 parent 923e55b commit c42155c

3 files changed

Lines changed: 56 additions & 12 deletions

File tree

‎apps/sim/lib/billing/enterprise-self-serve.integration.ts‎

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ const { stripeStub } = vi.hoisted(() => ({
4343
stripeStub: {
4444
setupIntents: { retrieve: vi.fn() },
4545
customers: { update: vi.fn() },
46-
subscriptions: { update: vi.fn() },
46+
subscriptions: { retrieve: vi.fn(), update: vi.fn() },
4747
},
4848
}))
4949

@@ -377,6 +377,7 @@ describe('auto-pay', () => {
377377
stripeStub.setupIntents.retrieve.mockReset()
378378
stripeStub.customers.update.mockReset()
379379
stripeStub.subscriptions.update.mockReset()
380+
stripeStub.subscriptions.retrieve.mockReset()
380381
stripeStub.setupIntents.retrieve.mockResolvedValue({
381382
status: 'succeeded',
382383
payment_method: 'pm_saved',
@@ -414,6 +415,7 @@ describe('auto-pay', () => {
414415
periodStart: monthsAgo(1),
415416
})
416417
if (!sub) throw new Error('subscription missing')
418+
stripeStub.subscriptions.retrieve.mockResolvedValue({ metadata: sub.metadata })
417419

418420
await handleEnterpriseAutoPaySetup(setupSession(sub))
419421

@@ -424,6 +426,23 @@ describe('auto-pay', () => {
424426
)
425427
})
426428

429+
it('does not switch a contract that left self-serve after the session was checked', async () => {
430+
const org = await createOrganization(1)
431+
const sub = await addEnterpriseSubscription(org.id, {
432+
selfServe: true,
433+
seats: 2,
434+
periodStart: monthsAgo(1),
435+
})
436+
if (!sub) throw new Error('subscription missing')
437+
stripeStub.subscriptions.retrieve.mockResolvedValue({
438+
metadata: { ...(sub.metadata as Record<string, string>), selfServe: '' },
439+
})
440+
441+
await handleEnterpriseAutoPaySetup(setupSession(sub))
442+
443+
expect(stripeStub.subscriptions.update).not.toHaveBeenCalled()
444+
})
445+
427446
it("ignores another customer's session and a contract outside self-serve", async () => {
428447
const org = await createOrganization(1)
429448
const sub = await addEnterpriseSubscription(org.id, {

‎apps/sim/lib/billing/webhooks/enterprise-auto-pay.ts‎

Lines changed: 35 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,12 @@ import { eq } from 'drizzle-orm'
55
import type Stripe from 'stripe'
66
import { requireStripeClient } from '@/lib/billing/stripe-client'
77
import { getCustomerId, getPaymentMethodId } from '@/lib/billing/stripe-payment-method'
8-
import { hasPaidSubscriptionStatus, isEnterpriseSelfServe } from '@/lib/billing/subscriptions/utils'
8+
import {
9+
hasPaidSubscriptionStatus,
10+
isEnterpriseSelfServe,
11+
isSelfServeEnterpriseMetadata,
12+
} from '@/lib/billing/subscriptions/utils'
13+
import { withEnterpriseReconciliationLease } from '@/lib/billing/webhooks/enterprise-reconciliation-lease'
914

1015
const logger = createLogger('EnterpriseAutoPay')
1116

@@ -65,16 +70,35 @@ export async function handleEnterpriseAutoPaySetup(session: Stripe.Checkout.Sess
6570
}
6671

6772
const customerId = contract.stripeCustomerId
68-
await stripe.customers.update(
69-
customerId,
70-
{ invoice_settings: { default_payment_method: paymentMethodId } },
71-
{ idempotencyKey: `enterprise-auto-pay:${session.id}:customer` }
72-
)
73-
await stripe.subscriptions.update(
74-
stripeSubscriptionId,
75-
{ collection_method: 'charge_automatically', default_payment_method: paymentMethodId },
76-
{ idempotencyKey: `enterprise-auto-pay:${session.id}:subscription` }
77-
)
73+
// Admin changes to the contract hold this lease while they write Stripe, so re-reading Stripe's
74+
// terms under it sees a self-serve shutdown that landed after the local check above.
75+
const switched = await withEnterpriseReconciliationLease(stripeSubscriptionId, async () => {
76+
const current = await stripe.subscriptions.retrieve(stripeSubscriptionId)
77+
if (
78+
current.metadata?.referenceId !== organizationId ||
79+
!isSelfServeEnterpriseMetadata(current.metadata)
80+
) {
81+
return false
82+
}
83+
await stripe.customers.update(
84+
customerId,
85+
{ invoice_settings: { default_payment_method: paymentMethodId } },
86+
{ idempotencyKey: `enterprise-auto-pay:${session.id}:customer` }
87+
)
88+
await stripe.subscriptions.update(
89+
stripeSubscriptionId,
90+
{ collection_method: 'charge_automatically', default_payment_method: paymentMethodId },
91+
{ idempotencyKey: `enterprise-auto-pay:${session.id}:subscription` }
92+
)
93+
return true
94+
})
95+
if (!switched) {
96+
logger.warn('Enterprise contract left self-serve before auto-pay could switch', {
97+
sessionId: session.id,
98+
organizationId,
99+
})
100+
return
101+
}
78102

79103
logger.info('Enterprise contract switched to automatic payment', {
80104
organizationId,

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ const METADATA_SUBSCRIPTION_INVOICE_TYPES = new Set<string>([
6767
'overage_billing',
6868
'overage_threshold_billing',
6969
'overage_threshold_billing_org',
70+
'enterprise_seat_true_up',
7071
])
7172

7273
type InvoiceSubscriptionResolutionSource =

0 commit comments

Comments
 (0)