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 */
56import { db } from '@sim/db'
67import { member, organization, subscription, user, userStats } from '@sim/db/schema'
@@ -9,7 +10,10 @@ import { generateId } from '@sim/utils/id'
910import { inArray } from 'drizzle-orm'
1011import type Stripe from 'stripe'
1112import { 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
1418const { 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+
2329const userIds: string[] = []
2430const organizationIds: string[] = []
31+ const personalPayerIds: string[] = []
2532
2633async function createUser(blocked: boolean): Promise<string> {
2734 const id = `invoice-recovery-${generateId()}`
@@ -119,6 +126,9 @@ beforeEach(() => {
119126})
120127
121128afterAll(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+ })
0 commit comments