Skip to content

Commit f54e29d

Browse files
authored
fix(billing): block a payer on every failed invoice payment (#10579)
* fix(billing): block a payer on every failed invoice payment A charge made outside Stripe's retry schedule, such as the one that ends an ineligible trial at once, fails with attempt_count 0. The handler only blocked from attempt 1, so the payer kept the plan's full allowance while past due. Block on any failure, and send the failure email on attempt 0 or 1. * fix(billing): hold a payment block while an attempted invoice stays unpaid
1 parent 28da16b commit f54e29d

2 files changed

Lines changed: 158 additions & 50 deletions

File tree

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

Lines changed: 109 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
/**
2-
* Payment recovery against real PostgreSQL: a paid invoice lifts the payment-failed block from
3-
* every member its failure blocked, whoever the organization's owner is by then.
2+
* Payment failure and recovery against real PostgreSQL: a failed invoice blocks its payer, and a
3+
* paid invoice lifts the payment-failed block from every member its failure blocked, whoever the
4+
* organization's owner is by then.
45
*/
56
import { db } from '@sim/db'
67
import { member, organization, subscription, user, userStats } from '@sim/db/schema'
@@ -9,7 +10,10 @@ import { generateId } from '@sim/utils/id'
910
import { inArray } from 'drizzle-orm'
1011
import type Stripe from 'stripe'
1112
import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest'
12-
import { handleInvoicePaymentSucceeded } from '@/lib/billing/webhooks/invoices'
13+
import {
14+
handleInvoicePaymentFailed,
15+
handleInvoicePaymentSucceeded,
16+
} from '@/lib/billing/webhooks/invoices'
1317

1418
const { stripeStub } = vi.hoisted(() => ({
1519
stripeStub: { invoices: { list: vi.fn() } },
@@ -20,8 +24,11 @@ vi.mock('@/lib/billing/stripe-client', () => ({
2024
getStripeClient: () => stripeStub,
2125
}))
2226

27+
vi.mock('@/lib/messaging/email/mailer', () => ({ sendEmail: vi.fn() }))
28+
2329
const userIds: string[] = []
2430
const organizationIds: string[] = []
31+
const personalPayerIds: string[] = []
2532

2633
async function createUser(blocked: boolean): Promise<string> {
2734
const id = `invoice-recovery-${generateId()}`
@@ -119,6 +126,9 @@ beforeEach(() => {
119126
})
120127

121128
afterAll(async () => {
129+
if (personalPayerIds.length > 0) {
130+
await db.delete(subscription).where(inArray(subscription.referenceId, personalPayerIds))
131+
}
122132
if (organizationIds.length > 0) {
123133
await db.delete(subscription).where(inArray(subscription.referenceId, organizationIds))
124134
await db.delete(member).where(inArray(member.organizationId, organizationIds))
@@ -173,3 +183,99 @@ describe('a paid invoice after a failed one', () => {
173183
expect(stripeStub.invoices.list).not.toHaveBeenCalled()
174184
})
175185
})
186+
187+
describe('a failed invoice', () => {
188+
/** A personal Pro plan whose first charge Stripe just failed, as when an ineligible trial ends. */
189+
async function createPastDuePro() {
190+
const userId = await createUser(false)
191+
const stripeSubscriptionId = `sub_${generateId()}`
192+
const stripeCustomerId = `cus_${generateId()}`
193+
await db.insert(subscription).values({
194+
id: generateId(),
195+
plan: 'pro_6000',
196+
referenceId: userId,
197+
stripeCustomerId,
198+
stripeSubscriptionId,
199+
status: 'past_due',
200+
periodStart: new Date(),
201+
periodEnd: new Date(Date.now() + 365 * 86_400_000),
202+
})
203+
personalPayerIds.push(userId)
204+
return { userId, stripeSubscriptionId, stripeCustomerId }
205+
}
206+
207+
it.each([
208+
{ label: 'on its first scheduled attempt', attemptCount: 1 },
209+
{ label: 'with no attempt counted, as a charge outside the retry schedule', attemptCount: 0 },
210+
])('blocks its payer $label', async ({ attemptCount }) => {
211+
const payer = await createPastDuePro()
212+
213+
await handleInvoicePaymentFailed(
214+
createMockStripeEvent(
215+
'invoice.payment_failed',
216+
{
217+
id: `in_${generateId()}`,
218+
object: 'invoice',
219+
amount_due: 25500,
220+
attempt_count: attemptCount,
221+
billing_reason: 'subscription_update',
222+
customer: payer.stripeCustomerId,
223+
currency: 'usd',
224+
parent: {
225+
type: 'subscription_details',
226+
subscription_details: { subscription: payer.stripeSubscriptionId },
227+
},
228+
},
229+
{ id: `evt_${generateId()}` }
230+
)
231+
)
232+
233+
expect(await blockedUserIds([payer.userId])).toEqual([payer.userId])
234+
})
235+
236+
it('keeps its payer blocked when another invoice for the plan is paid while it stays unpaid', async () => {
237+
const payer = await createPastDuePro()
238+
const failed = {
239+
id: `in_${generateId()}`,
240+
object: 'invoice',
241+
amount_due: 25500,
242+
attempt_count: 0,
243+
attempted: true,
244+
billing_reason: 'subscription_update',
245+
collection_method: 'charge_automatically',
246+
customer: payer.stripeCustomerId,
247+
currency: 'usd',
248+
parent: {
249+
type: 'subscription_details',
250+
subscription_details: { subscription: payer.stripeSubscriptionId },
251+
},
252+
}
253+
await handleInvoicePaymentFailed(
254+
createMockStripeEvent('invoice.payment_failed', failed, { id: `evt_${generateId()}` })
255+
)
256+
stripeStub.invoices.list.mockImplementation(async function* () {
257+
yield failed
258+
})
259+
260+
await handleInvoicePaymentSucceeded(
261+
createMockStripeEvent(
262+
'invoice.payment_succeeded',
263+
{
264+
id: `in_${generateId()}`,
265+
object: 'invoice',
266+
amount_paid: 1200,
267+
billing_reason: 'manual',
268+
customer: payer.stripeCustomerId,
269+
currency: 'usd',
270+
metadata: {
271+
subscriptionId: payer.stripeSubscriptionId,
272+
type: 'overage_threshold_billing',
273+
},
274+
},
275+
{ id: `evt_${generateId()}` }
276+
)
277+
)
278+
279+
expect(await blockedUserIds([payer.userId])).toEqual([payer.userId])
280+
})
281+
})

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

Lines changed: 49 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -592,8 +592,10 @@ async function handleCreditPurchaseSuccess(invoice: Stripe.Invoice): Promise<voi
592592

593593
/**
594594
* Whether the same subscription still has another open, automatically charged invoice that failed:
595-
* its renewals and its metadata-linked overage and seat true-up invoices. A Stripe customer can
596-
* pay for several subscriptions, so invoices for any other one never hold this one's access.
595+
* its renewals and its metadata-linked overage and seat true-up invoices. An open invoice Stripe
596+
* has attempted is unpaid, including a charge outside the retry schedule, which counts no
597+
* attempts. A Stripe customer can pay for several subscriptions, so invoices for any other one
598+
* never hold this one's access.
597599
*/
598600
async function hasOtherFailedInvoice(
599601
invoice: Stripe.Invoice,
@@ -609,7 +611,7 @@ async function hasOtherFailedInvoice(
609611
if (
610612
open.id !== invoice.id &&
611613
open.collection_method === 'charge_automatically' &&
612-
(open.attempt_count ?? 0) > 0 &&
614+
(open.attempted || (open.attempt_count ?? 0) > 0) &&
613615
resolveInvoiceSubscriptionContext(open).stripeSubscriptionId === stripeSubscriptionId
614616
) {
615617
return true
@@ -803,55 +805,55 @@ export async function handleInvoicePaymentFailed(event: Stripe.Event) {
803805
logger.warn('Failed to record payment_failed instrumentation', { auditError })
804806
}
805807

806-
if (attemptCount >= 1) {
807-
logger.error('Payment failure - blocking users', {
808-
customerId,
809-
attemptCount,
810-
invoiceId: invoice.id,
808+
// Any failed payment blocks, whatever Stripe's retry count: a charge made outside Stripe's
809+
// retry schedule, such as ending a trial at once, fails with no attempts counted.
810+
logger.error('Payment failure - blocking users', {
811+
customerId,
812+
attemptCount,
813+
invoiceId: invoice.id,
814+
invoiceType: invoiceType ?? 'subscription',
815+
resolutionSource,
816+
stripeSubscriptionId,
817+
})
818+
819+
if (await isSubscriptionOrgScoped(sub)) {
820+
const memberCount = await blockOrgMembers(sub.referenceId, 'payment_failed')
821+
logger.info('Blocked org members due to payment failure', {
811822
invoiceType: invoiceType ?? 'subscription',
812-
resolutionSource,
813-
stripeSubscriptionId,
823+
memberCount,
824+
organizationId: sub.referenceId,
814825
})
815-
816-
if (await isSubscriptionOrgScoped(sub)) {
817-
const memberCount = await blockOrgMembers(sub.referenceId, 'payment_failed')
818-
logger.info('Blocked org members due to payment failure', {
819-
invoiceType: invoiceType ?? 'subscription',
820-
memberCount,
821-
organizationId: sub.referenceId,
822-
})
823-
} else {
824-
await db
825-
.update(userStats)
826-
.set({ billingBlocked: true, billingBlockedReason: 'payment_failed' })
827-
.where(
828-
and(
829-
eq(userStats.userId, sub.referenceId),
830-
or(
831-
ne(userStats.billingBlockedReason, 'dispute'),
832-
isNull(userStats.billingBlockedReason)
833-
)
826+
} else {
827+
await db
828+
.update(userStats)
829+
.set({ billingBlocked: true, billingBlockedReason: 'payment_failed' })
830+
.where(
831+
and(
832+
eq(userStats.userId, sub.referenceId),
833+
or(
834+
ne(userStats.billingBlockedReason, 'dispute'),
835+
isNull(userStats.billingBlockedReason)
834836
)
835837
)
836-
logger.info('Blocked user due to payment failure', {
837-
invoiceType: invoiceType ?? 'subscription',
838-
userId: sub.referenceId,
839-
})
840-
}
838+
)
839+
logger.info('Blocked user due to payment failure', {
840+
invoiceType: invoiceType ?? 'subscription',
841+
userId: sub.referenceId,
842+
})
843+
}
841844

842-
if (attemptCount === 1) {
843-
await sendPaymentFailureEmails(sub, invoice, customerId)
844-
logger.info('Payment failure email sent on first attempt', {
845-
customerId,
846-
invoiceId: invoice.id,
847-
})
848-
} else {
849-
logger.info('Skipping payment failure email on retry attempt', {
850-
attemptCount,
851-
customerId,
852-
invoiceId: invoice.id,
853-
})
854-
}
845+
if (attemptCount <= 1) {
846+
await sendPaymentFailureEmails(sub, invoice, customerId)
847+
logger.info('Payment failure email sent on first attempt', {
848+
customerId,
849+
invoiceId: invoice.id,
850+
})
851+
} else {
852+
logger.info('Skipping payment failure email on retry attempt', {
853+
attemptCount,
854+
customerId,
855+
invoiceId: invoice.id,
856+
})
855857
}
856858
}
857859
)

0 commit comments

Comments
 (0)