import { describe, expect, it, vi } from "vitest"; import { RECURRING_INVOICE_COLLECTION_EVENT, recurringInvoiceCollectionId, reserveRecurringInvoiceCollection } from "./recurring-invoice-collection.server"; function clientFixture( options: { existing?: Record | null; initialCheckout?: { id: string; providerPaymentId: string | null } | null; initialProductAcquisition?: { id: string; providerPaymentId: string | null } | null; subscription?: Record | null; } = {} ) { let stored = options.existing ?? null; const tx = { $queryRaw: vi.fn().mockResolvedValue([]), tenantSubscription: { findUnique: vi.fn().mockResolvedValue( options.subscription === undefined ? { status: "active", mollieCustomerId: "cst_customer", billingCadence: "annual_sepa", lastInvoiceExternalId: "different_invoice", products: [{ id: "tenant_product_1", fromCheckoutSessionId: null }], } : options.subscription ), update: vi.fn().mockResolvedValue({}), }, checkoutSessionStatus: { findUnique: vi.fn().mockImplementation(async () => stored), findFirst: vi.fn().mockResolvedValue(options.initialCheckout ?? null), create: vi.fn().mockImplementation(async ({ data }) => { stored = data; return { id: data.id }; }), createMany: vi.fn().mockImplementation(async ({ data }) => { if (stored) return { count: 0 }; stored = data; return { count: 1 }; }), updateMany: vi.fn().mockImplementation(async ({ data }) => { if (!stored) return { count: 0 }; stored = { ...stored, ...data }; return { count: 1 }; }), }, tenantProductAcquisition: { findFirst: vi.fn().mockResolvedValue(options.initialProductAcquisition ?? null), }, outboxEvent: { create: vi.fn().mockImplementation(async ({ data }) => ({ id: "outbox_1", ...data, status: "PENDING", createdAt: new Date(), processedAt: null, retries: 0, deliveryGeneration: 0, lastError: null, priority: data.priority ?? 0, lockedUntil: null, })), findUnique: vi.fn(), updateMany: vi.fn().mockResolvedValue({ count: 1 }), }, }; return { tx, client: { $transaction: async (callback: (value: typeof tx) => Promise) => callback(tx), }, }; } const input = { tenantId: "tenant_1", invoiceExternalId: "invoice_2026_08", lagoSubscriptionId: "subscription_1", billingProviderSubscriptionId: "lago_subscription_1", invoicingReason: "subscription_periodic" as const, invoiceCreatedAt: new Date("2026-08-01T00:00:00.000Z"), receivedAt: new Date("2026-08-01T00:00:05.000Z"), amountCents: 23_681, currency: "EUR", }; describe("reserveRecurringInvoiceCollection", () => { it("reserves a deterministic ledger and transactional delayed outbox event", async () => { const { client, tx } = clientFixture(); const result = await reserveRecurringInvoiceCollection(input, client as never); expect(result).toEqual({ collectionId: recurringInvoiceCollectionId(input.invoiceExternalId), disposition: "queued", }); expect(tx.checkoutSessionStatus.create).toHaveBeenCalledWith({ data: expect.objectContaining({ id: result.collectionId, tenantId: input.tenantId, invoiceExternalId: input.invoiceExternalId, amountCents: 23_681, billingCadence: "annual_sepa", status: "queued", }), }); expect(tx.outboxEvent.create).toHaveBeenCalledWith({ data: expect.objectContaining({ eventType: RECURRING_INVOICE_COLLECTION_EVENT, dispatchKey: `billing-recurring:${result.collectionId}`, scheduledAt: new Date("2026-08-01T00:02:05.000Z"), }), }); }); it("is idempotent for the exact same invoice economics", async () => { const collectionId = recurringInvoiceCollectionId(input.invoiceExternalId); const { client, tx } = clientFixture({ existing: { id: collectionId, tenantId: input.tenantId, invoiceExternalId: input.invoiceExternalId, lagoSubscriptionId: input.lagoSubscriptionId, scopeKey: input.billingProviderSubscriptionId, amountCents: input.amountCents, currency: input.currency, }, }); await expect(reserveRecurringInvoiceCollection(input, client as never)).resolves.toEqual({ collectionId, disposition: "replayed", }); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("defers until the paid base subscription and Mollie customer are available", async () => { const { client, tx } = clientFixture({ subscription: { status: "trial", mollieCustomerId: null, billingCadence: "monthly", products: [], }, }); await expect(reserveRecurringInvoiceCollection({ ...input, invoicingReason: "subscription_starting" }, client as never)).resolves.toMatchObject({ disposition: "not_ready", }); expect(tx.checkoutSessionStatus.create).not.toHaveBeenCalled(); }); it("does not double-collect an invoice covered by the initial checkout", async () => { const { client, tx } = clientFixture({ initialCheckout: { id: "hgco_initial", providerPaymentId: "tr_initial" }, subscription: { status: "active", mollieCustomerId: "cst_customer", billingCadence: "annual_sepa", lastInvoiceExternalId: input.invoiceExternalId, products: [{ id: "tenant_product_1", fromCheckoutSessionId: "hgco_initial" }], }, }); await expect( reserveRecurringInvoiceCollection({ ...input, invoicingReason: "subscription_starting" }, client as never) ).resolves.toMatchObject({ disposition: "initial_payment", }); expect(tx.checkoutSessionStatus.findFirst).toHaveBeenCalledWith({ where: { tenantId: input.tenantId, id: "hgco_initial", lagoSubscriptionId: input.lagoSubscriptionId, pending: false, status: "paid", providerPaymentId: { not: null }, amountCents: input.amountCents, currency: input.currency, }, select: { id: true, providerPaymentId: true }, }); expect(tx.tenantSubscription.update).toHaveBeenCalledWith({ where: { tenantId: input.tenantId }, data: { lastInvoiceExternalId: input.invoiceExternalId }, }); expect(tx.checkoutSessionStatus.createMany).toHaveBeenCalledWith({ data: expect.objectContaining({ id: recurringInvoiceCollectionId(input.invoiceExternalId), status: "skipped_initial", pending: false, scopeKey: input.billingProviderSubscriptionId, }), skipDuplicates: true, }); await expect( reserveRecurringInvoiceCollection({ ...input, invoicingReason: "subscription_starting" }, client as never) ).resolves.toMatchObject({ disposition: "replayed" }); expect(tx.checkoutSessionStatus.createMany).toHaveBeenCalledTimes(1); }); it("queues only a periodic invoice when an earlier checkout does not cover it", async () => { const { client, tx } = clientFixture({ initialCheckout: null, subscription: { status: "active", mollieCustomerId: "cst_customer", billingCadence: "annual_sepa", lastInvoiceExternalId: "previous_initial_invoice", products: [{ id: "tenant_product_1", fromCheckoutSessionId: "hgco_initial" }], }, }); await expect(reserveRecurringInvoiceCollection(input, client as never)).resolves.toMatchObject({ disposition: "queued" }); expect(tx.tenantSubscription.update).not.toHaveBeenCalled(); expect(tx.checkoutSessionStatus.create).toHaveBeenCalledOnce(); }); it("marks an exact paid product-acquisition start invoice without queueing a second payment", async () => { const { client, tx } = clientFixture({ initialProductAcquisition: { id: "acquisition_1", providerPaymentId: "tr_addon_initial" }, }); await expect( reserveRecurringInvoiceCollection({ ...input, invoicingReason: "subscription_starting" }, client as never) ).resolves.toMatchObject({ disposition: "initial_payment" }); expect(tx.tenantProductAcquisition.findFirst).toHaveBeenCalledWith({ where: expect.objectContaining({ tenantId: input.tenantId, tenantSubscriptionProductId: "tenant_product_1", lagoSubscriptionId: input.lagoSubscriptionId, lagoProviderSubscriptionId: input.billingProviderSubscriptionId, initialLagoInvoiceExternalId: input.invoiceExternalId, amountCents: input.amountCents, currency: input.currency, }), select: { id: true, providerPaymentId: true }, }); expect(tx.checkoutSessionStatus.createMany).toHaveBeenCalledWith({ data: expect.objectContaining({ providerPaymentId: "tr_addon_initial", status: "skipped_initial", pending: false, }), skipDuplicates: true, }); expect(tx.checkoutSessionStatus.create).not.toHaveBeenCalled(); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("returns not_ready for an unmirrored subscription-starting invoice instead of collecting it", async () => { const { client, tx } = clientFixture(); await expect( reserveRecurringInvoiceCollection({ ...input, invoicingReason: "subscription_starting" }, client as never) ).resolves.toMatchObject({ disposition: "not_ready" }); expect(tx.checkoutSessionStatus.create).not.toHaveBeenCalled(); expect(tx.outboxEvent.create).not.toHaveBeenCalled(); }); it("converts a legacy queued start marker to skipped_initial and cancels its stale outbox command", async () => { const collectionId = recurringInvoiceCollectionId(input.invoiceExternalId); const { client, tx } = clientFixture({ existing: { id: collectionId, tenantId: input.tenantId, pending: true, status: "queued", providerPaymentId: null, invoiceExternalId: input.invoiceExternalId, lagoSubscriptionId: input.lagoSubscriptionId, scopeKey: input.billingProviderSubscriptionId, amountCents: input.amountCents, currency: input.currency, }, initialProductAcquisition: { id: "acquisition_1", providerPaymentId: "tr_addon_initial" }, }); await expect( reserveRecurringInvoiceCollection({ ...input, invoicingReason: "subscription_starting" }, client as never) ).resolves.toMatchObject({ disposition: "initial_payment" }); expect(tx.checkoutSessionStatus.updateMany).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining({ id: collectionId, OR: [{ providerPaymentId: null }, { providerPaymentId: "tr_addon_initial" }], }), data: expect.objectContaining({ pending: false, providerPaymentId: "tr_addon_initial", status: "skipped_initial" }), })); expect(tx.outboxEvent.updateMany).toHaveBeenCalledWith({ where: { tenantId: input.tenantId, dispatchKey: `billing-recurring:${collectionId}`, eventType: RECURRING_INVOICE_COLLECTION_EVENT, status: { in: ["PENDING", "PROCESSING"] }, }, data: { status: "CANCELLED", processedAt: input.receivedAt, lockedUntil: null, lastError: "Initial invoice covered by the exact first payment", }, }); expect(tx.checkoutSessionStatus.create).not.toHaveBeenCalled(); }); });