diff --git a/apps/sim/lib/billing/webhooks/invoices.integration.ts b/apps/sim/lib/billing/webhooks/invoices.integration.ts index a0ef4975931..108a16c722c 100644 --- a/apps/sim/lib/billing/webhooks/invoices.integration.ts +++ b/apps/sim/lib/billing/webhooks/invoices.integration.ts @@ -1,6 +1,7 @@ /** - * Payment recovery against real PostgreSQL: a paid invoice lifts the payment-failed block from - * every member its failure blocked, whoever the organization's owner is by then. + * Payment failure and recovery against real PostgreSQL: a failed invoice blocks its payer, and a + * paid invoice lifts the payment-failed block from every member its failure blocked, whoever the + * organization's owner is by then. */ import { db } from '@sim/db' import { member, organization, subscription, user, userStats } from '@sim/db/schema' @@ -9,7 +10,10 @@ import { generateId } from '@sim/utils/id' import { inArray } from 'drizzle-orm' import type Stripe from 'stripe' import { afterAll, beforeEach, describe, expect, it, vi } from 'vitest' -import { handleInvoicePaymentSucceeded } from '@/lib/billing/webhooks/invoices' +import { + handleInvoicePaymentFailed, + handleInvoicePaymentSucceeded, +} from '@/lib/billing/webhooks/invoices' const { stripeStub } = vi.hoisted(() => ({ stripeStub: { invoices: { list: vi.fn() } }, @@ -20,8 +24,11 @@ vi.mock('@/lib/billing/stripe-client', () => ({ getStripeClient: () => stripeStub, })) +vi.mock('@/lib/messaging/email/mailer', () => ({ sendEmail: vi.fn() })) + const userIds: string[] = [] const organizationIds: string[] = [] +const personalPayerIds: string[] = [] async function createUser(blocked: boolean): Promise { const id = `invoice-recovery-${generateId()}` @@ -119,6 +126,9 @@ beforeEach(() => { }) afterAll(async () => { + if (personalPayerIds.length > 0) { + await db.delete(subscription).where(inArray(subscription.referenceId, personalPayerIds)) + } if (organizationIds.length > 0) { await db.delete(subscription).where(inArray(subscription.referenceId, organizationIds)) await db.delete(member).where(inArray(member.organizationId, organizationIds)) @@ -173,3 +183,99 @@ describe('a paid invoice after a failed one', () => { expect(stripeStub.invoices.list).not.toHaveBeenCalled() }) }) + +describe('a failed invoice', () => { + /** A personal Pro plan whose first charge Stripe just failed, as when an ineligible trial ends. */ + async function createPastDuePro() { + const userId = await createUser(false) + const stripeSubscriptionId = `sub_${generateId()}` + const stripeCustomerId = `cus_${generateId()}` + await db.insert(subscription).values({ + id: generateId(), + plan: 'pro_6000', + referenceId: userId, + stripeCustomerId, + stripeSubscriptionId, + status: 'past_due', + periodStart: new Date(), + periodEnd: new Date(Date.now() + 365 * 86_400_000), + }) + personalPayerIds.push(userId) + return { userId, stripeSubscriptionId, stripeCustomerId } + } + + it.each([ + { label: 'on its first scheduled attempt', attemptCount: 1 }, + { label: 'with no attempt counted, as a charge outside the retry schedule', attemptCount: 0 }, + ])('blocks its payer $label', async ({ attemptCount }) => { + const payer = await createPastDuePro() + + await handleInvoicePaymentFailed( + createMockStripeEvent( + 'invoice.payment_failed', + { + id: `in_${generateId()}`, + object: 'invoice', + amount_due: 25500, + attempt_count: attemptCount, + billing_reason: 'subscription_update', + customer: payer.stripeCustomerId, + currency: 'usd', + parent: { + type: 'subscription_details', + subscription_details: { subscription: payer.stripeSubscriptionId }, + }, + }, + { id: `evt_${generateId()}` } + ) + ) + + expect(await blockedUserIds([payer.userId])).toEqual([payer.userId]) + }) + + it('keeps its payer blocked when another invoice for the plan is paid while it stays unpaid', async () => { + const payer = await createPastDuePro() + const failed = { + id: `in_${generateId()}`, + object: 'invoice', + amount_due: 25500, + attempt_count: 0, + attempted: true, + billing_reason: 'subscription_update', + collection_method: 'charge_automatically', + customer: payer.stripeCustomerId, + currency: 'usd', + parent: { + type: 'subscription_details', + subscription_details: { subscription: payer.stripeSubscriptionId }, + }, + } + await handleInvoicePaymentFailed( + createMockStripeEvent('invoice.payment_failed', failed, { id: `evt_${generateId()}` }) + ) + stripeStub.invoices.list.mockImplementation(async function* () { + yield failed + }) + + await handleInvoicePaymentSucceeded( + createMockStripeEvent( + 'invoice.payment_succeeded', + { + id: `in_${generateId()}`, + object: 'invoice', + amount_paid: 1200, + billing_reason: 'manual', + customer: payer.stripeCustomerId, + currency: 'usd', + metadata: { + subscriptionId: payer.stripeSubscriptionId, + type: 'overage_threshold_billing', + }, + }, + { id: `evt_${generateId()}` } + ) + ) + + expect(await blockedUserIds([payer.userId])).toEqual([payer.userId]) + }) +}) diff --git a/apps/sim/lib/billing/webhooks/invoices.ts b/apps/sim/lib/billing/webhooks/invoices.ts index c7ae5253a78..544352bfcc7 100644 --- a/apps/sim/lib/billing/webhooks/invoices.ts +++ b/apps/sim/lib/billing/webhooks/invoices.ts @@ -592,8 +592,10 @@ async function handleCreditPurchaseSuccess(invoice: Stripe.Invoice): Promise 0 && + (open.attempted || (open.attempt_count ?? 0) > 0) && resolveInvoiceSubscriptionContext(open).stripeSubscriptionId === stripeSubscriptionId ) { return true @@ -803,55 +805,55 @@ export async function handleInvoicePaymentFailed(event: Stripe.Event) { logger.warn('Failed to record payment_failed instrumentation', { auditError }) } - if (attemptCount >= 1) { - logger.error('Payment failure - blocking users', { - customerId, - attemptCount, - invoiceId: invoice.id, + // Any failed payment blocks, whatever Stripe's retry count: a charge made outside Stripe's + // retry schedule, such as ending a trial at once, fails with no attempts counted. + logger.error('Payment failure - blocking users', { + customerId, + attemptCount, + invoiceId: invoice.id, + invoiceType: invoiceType ?? 'subscription', + resolutionSource, + stripeSubscriptionId, + }) + + if (await isSubscriptionOrgScoped(sub)) { + const memberCount = await blockOrgMembers(sub.referenceId, 'payment_failed') + logger.info('Blocked org members due to payment failure', { invoiceType: invoiceType ?? 'subscription', - resolutionSource, - stripeSubscriptionId, + memberCount, + organizationId: sub.referenceId, }) - - if (await isSubscriptionOrgScoped(sub)) { - const memberCount = await blockOrgMembers(sub.referenceId, 'payment_failed') - logger.info('Blocked org members due to payment failure', { - invoiceType: invoiceType ?? 'subscription', - memberCount, - organizationId: sub.referenceId, - }) - } else { - await db - .update(userStats) - .set({ billingBlocked: true, billingBlockedReason: 'payment_failed' }) - .where( - and( - eq(userStats.userId, sub.referenceId), - or( - ne(userStats.billingBlockedReason, 'dispute'), - isNull(userStats.billingBlockedReason) - ) + } else { + await db + .update(userStats) + .set({ billingBlocked: true, billingBlockedReason: 'payment_failed' }) + .where( + and( + eq(userStats.userId, sub.referenceId), + or( + ne(userStats.billingBlockedReason, 'dispute'), + isNull(userStats.billingBlockedReason) ) ) - logger.info('Blocked user due to payment failure', { - invoiceType: invoiceType ?? 'subscription', - userId: sub.referenceId, - }) - } + ) + logger.info('Blocked user due to payment failure', { + invoiceType: invoiceType ?? 'subscription', + userId: sub.referenceId, + }) + } - if (attemptCount === 1) { - await sendPaymentFailureEmails(sub, invoice, customerId) - logger.info('Payment failure email sent on first attempt', { - customerId, - invoiceId: invoice.id, - }) - } else { - logger.info('Skipping payment failure email on retry attempt', { - attemptCount, - customerId, - invoiceId: invoice.id, - }) - } + if (attemptCount <= 1) { + await sendPaymentFailureEmails(sub, invoice, customerId) + logger.info('Payment failure email sent on first attempt', { + customerId, + invoiceId: invoice.id, + }) + } else { + logger.info('Skipping payment failure email on retry attempt', { + attemptCount, + customerId, + invoiceId: invoice.id, + }) } } )