@@ -5,7 +5,12 @@ import { eq } from 'drizzle-orm'
55import type Stripe from 'stripe'
66import { requireStripeClient } from '@/lib/billing/stripe-client'
77import { 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
1015const 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,
0 commit comments