import { beforeEach, describe, expect, it, vi } from "vitest"; import { applyBillingDunningCycle, billingStatusFromStripeSubscription, createBillingDunningNotification, evaluateBillingDunning, processStripeBillingEvent, } from "./billingDunningService"; vi.mock("~/utils/db.server", () => ({ db: {}, })); const clearTenantSubscriptionCache = vi.fn(); const createNotificationDelivery = vi.fn(); vi.mock("./subscriptionService", () => ({ clearTenantSubscriptionCache: (...args: unknown[]) => clearTenantSubscriptionCache(...args), })); vi.mock("@hivegrid/db/notifications.server", () => ({ createNotificationDelivery: (...args: unknown[]) => createNotificationDelivery(...args), })); function createClient() { return { tenantSubscription: { findUnique: vi.fn(), findMany: vi.fn(), update: vi.fn(), }, tenantSubscriptionProduct: { findFirst: vi.fn(), update: vi.fn(), }, stripeWebhookLog: { findUnique: vi.fn(), upsert: vi.fn(), update: vi.fn(), }, }; } function stripeEvent(type: string, object: Record) { return { id: `evt_${type.replaceAll(".", "_")}`, type, data: { object }, } as never; } describe("billingDunningService", () => { beforeEach(() => { vi.clearAllMocks(); }); it("evaluates the day 1/3/7 dunning schedule before freezing", () => { const now = new Date("2026-07-10T00:00:00.000Z"); expect(evaluateBillingDunning({ status: "active", pastDueSince: now, dunningAttemptCount: 0 }, now)).toEqual({ kind: "noop" }); expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-09T00:00:00.000Z", dunningAttemptCount: 0 }, now)).toEqual({ kind: "send_dunning", attempt: 1, thresholdDays: 1, }); expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-07T00:00:00.000Z", dunningAttemptCount: 1 }, now)).toEqual({ kind: "send_dunning", attempt: 2, thresholdDays: 3, }); expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-03T00:00:00.000Z", dunningAttemptCount: 2 }, now)).toEqual({ kind: "send_dunning", attempt: 3, thresholdDays: 7, }); expect(evaluateBillingDunning({ status: "past_due", pastDueSince: "2026-07-03T00:00:00.000Z", dunningAttemptCount: 3 }, now)).toEqual({ kind: "freeze", thresholdDays: 7, }); }); it("applies due dunning notices and freezes exhausted subscriptions", async () => { const client = createClient(); const now = new Date("2026-07-10T00:00:00.000Z"); const sendDunningNotice = vi.fn(); client.tenantSubscription.findMany.mockResolvedValue([ { tenantId: "tenant_notice", status: "past_due", pastDueSince: new Date("2026-07-09T00:00:00.000Z"), dunningAttemptCount: 0 }, { tenantId: "tenant_freeze", status: "past_due", pastDueSince: new Date("2026-07-03T00:00:00.000Z"), dunningAttemptCount: 3 }, ]); const result = await applyBillingDunningCycle({ client, now, sendDunningNotice }); expect(result).toHaveLength(2); expect(sendDunningNotice).toHaveBeenCalledWith({ tenantId: "tenant_notice", attempt: 1, thresholdDays: 1 }); expect(client.tenantSubscription.update).toHaveBeenCalledWith({ where: { tenantId: "tenant_notice" }, data: { dunningAttemptCount: { increment: 1 }, lastDunningSentAt: now }, }); expect(client.tenantSubscription.update).toHaveBeenCalledWith({ where: { tenantId: "tenant_freeze" }, data: { status: "frozen", frozenAt: now }, }); expect(clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_notice"); expect(clearTenantSubscriptionCache).toHaveBeenCalledWith("tenant_freeze"); }); it("maps Billing provider subscription statuses to tenant billing statuses", () => { expect(billingStatusFromStripeSubscription("trialing")).toBe("trial"); expect(billingStatusFromStripeSubscription("active")).toBe("active"); expect(billingStatusFromStripeSubscription("past_due")).toBe("past_due"); expect(billingStatusFromStripeSubscription("unpaid")).toBe("past_due"); expect(billingStatusFromStripeSubscription("canceled")).toBe("cancelled"); }); it("creates dunning email notifications through the notification delivery boundary", async () => { await createBillingDunningNotification({ tenantId: "tenant_1", attempt: 2, thresholdDays: 3 }); expect(createNotificationDelivery).toHaveBeenCalledWith({ tenantId: "tenant_1", channel: "EMAIL", category: "billing", messageKey: "billing.notify.dunning.attempt2", sourceKey: "billing-dunning:tenant_1:attempt:2", payloadMetadata: { attempt: 2, thresholdDays: 3, }, }); }); it("processes Stripe invoice failures idempotently", async () => { const client = createClient(); const now = new Date("2026-07-10T00:00:00.000Z"); client.stripeWebhookLog.findUnique.mockResolvedValue(null); client.tenantSubscriptionProduct.findFirst.mockResolvedValue({ tenantSubscription: { tenantId: "tenant_1" } }); client.tenantSubscription.findUnique.mockResolvedValue({ pastDueSince: null }); const result = await processStripeBillingEvent(stripeEvent("invoice.payment_failed", { subscription: "sub_1" }), { client, now }); expect(result).toEqual({ replayed: false, relatedTenantId: "tenant_1" }); expect(client.tenantSubscription.update).toHaveBeenCalledWith({ where: { tenantId: "tenant_1" }, data: { status: "past_due", pastDueSince: now, frozenAt: null }, }); expect(client.stripeWebhookLog.update).toHaveBeenCalledWith({ where: { stripeEventId: "evt_invoice_payment_failed" }, data: { processedAt: now, relatedTenantId: "tenant_1", error: null }, }); client.stripeWebhookLog.findUnique.mockResolvedValueOnce({ processedAt: now, relatedTenantId: "tenant_1" }); await expect(processStripeBillingEvent(stripeEvent("invoice.payment_failed", { subscription: "sub_1" }), { client, now })).resolves.toEqual({ replayed: true, relatedTenantId: "tenant_1", }); }); it("keeps the original past-due timestamp on repeated Stripe failures", async () => { const client = createClient(); const now = new Date("2026-07-10T00:00:00.000Z"); const pastDueSince = new Date("2026-07-08T00:00:00.000Z"); client.stripeWebhookLog.findUnique.mockResolvedValue(null); client.tenantSubscriptionProduct.findFirst.mockResolvedValue({ tenantSubscription: { tenantId: "tenant_1" } }); client.tenantSubscription.findUnique.mockResolvedValue({ pastDueSince }); await processStripeBillingEvent(stripeEvent("invoice.payment_failed", { subscription: "sub_1" }), { client, now }); expect(client.tenantSubscription.update).toHaveBeenCalledWith({ where: { tenantId: "tenant_1" }, data: { status: "past_due", pastDueSince, frozenAt: null }, }); }); it("syncs Billing provider subscription period fields and clears dunning state when active", async () => { const client = createClient(); const now = new Date("2026-07-10T00:00:00.000Z"); client.stripeWebhookLog.findUnique.mockResolvedValue(null); client.tenantSubscriptionProduct.findFirst.mockResolvedValue({ id: "tenant_product_1", tenantSubscription: { tenantId: "tenant_1" } }); await processStripeBillingEvent( stripeEvent("customer.subscription.updated", { id: "sub_1", status: "active", current_period_start: 1783296000, current_period_end: 1785974400, }), { client, now } ); expect(client.tenantSubscriptionProduct.update).toHaveBeenCalledWith({ where: { id: "tenant_product_1" }, data: { currentPeriodStart: new Date(1783296000 * 1000), currentPeriodEnd: new Date(1785974400 * 1000), endsAt: null, cancelledAt: null, }, }); expect(client.tenantSubscription.update).toHaveBeenCalledWith({ where: { tenantId: "tenant_1" }, data: { status: "active", pastDueSince: null, frozenAt: null, cancelledAt: null, dunningAttemptCount: 0, lastDunningSentAt: null, }, }); }); });