// @vitest-environment node import { beforeEach, describe, expect, it, vi } from "vitest"; import { AdminBillingError, listAdminBillingRows, requestManualBillingSync, setTenantBillingPlanSeats, type AdminBillingDeps } from "./billing-admin.server"; function createDeps(overrides: Partial = {}): AdminBillingDeps { const tx = { tenantSubscription: { upsert: vi.fn(async () => ({ id: "sub_1" })), }, tenantSubscriptionProduct: { updateMany: vi.fn(async () => ({ count: 0 })), findFirst: vi.fn(async () => null), update: vi.fn(async () => ({})), create: vi.fn(async () => ({})), }, }; const db = { tenant: { findMany: vi.fn(async () => [{ id: "tenant_1", name: "Acme", slug: "acme" }]), findUnique: vi.fn(async () => ({ id: "tenant_1", name: "Acme", slug: "acme" })), }, subscriptionProduct: { findFirst: vi.fn(async () => ({ id: "product_1" })), }, $transaction: vi.fn(async (callback) => callback(tx)), __tx: tx, }; return { db: db as never, resolveBillingState: vi.fn(async () => ({ tenantId: "tenant_1", status: "active", readOnly: false, planCode: "starter", seatQuantity: 3, lagoCustomerId: "lago_1", mollieCustomerId: "mollie_1", lastInvoiceExternalId: "inv_1", lastPaymentExternalId: "pay_1", trialStartsAt: null, trialEndsAt: null, pastDueSince: null, frozenAt: null, cancelledAt: null, currentPeriodStart: new Date("2026-07-01T00:00:00.000Z"), currentPeriodEnd: new Date("2026-08-01T00:00:00.000Z"), entitlements: [ { featureKey: "crm", title: "CRM", enabled: true, limitType: 1, limit: 1, quotaValue: null, accumulate: false, sourceProductId: "product_1", sourcePlanCode: "starter", }, ], })), invalidateModuleCache: vi.fn(), clearSubscriptionCache: vi.fn(), recordAction: vi.fn(async () => undefined), lagoGateway: { createCustomer: vi.fn(), getCustomer: vi.fn(async () => ({ provider: "lago", externalId: "tenant_1", providerCustomerId: "lago_1", name: "Acme", email: "billing@example.test", currency: "EUR", createdAt: "2026-07-01T00:00:00Z", })), createSubscription: vi.fn(), getSubscription: vi.fn(), listInvoices: vi.fn(async () => [ { provider: "lago", providerInvoiceId: "invoice_1", number: "HIV-001", externalCustomerId: "tenant_1", status: "finalized", paymentStatus: "pending", invoiceType: "one_off", currency: "EUR", totalAmountCents: 11900, issuingDate: "2026-07-04", fileUrl: "https://files.example.test/invoice_1.pdf", }, ]), downloadInvoice: vi.fn(), }, mollieGateway: { createPayment: vi.fn(), getPayment: vi.fn(async () => ({ provider: "mollie", providerPaymentId: "pay_1", externalId: "pay_1", status: "paid", amountCents: 11900, amountRefundedCents: null, amountRemainingCents: 0, currency: "EUR", checkoutUrl: null, paidAt: "2026-07-04T00:00:00Z", expiresAt: null, metadata: { tenantId: "tenant_1", invoiceExternalId: "inv_1", paymentExternalId: "pay_1", lagoCustomerId: null, lagoSubscriptionId: null, planCode: null, seatQuantity: null, }, })), }, applyLagoSync: vi.fn(async (input) => ({ tenantId: input.tenantId, provider: "lago", idempotencyKey: input.eventKey, replayed: false, status: "active", })), applyMollieSync: vi.fn(async (input) => ({ tenantId: input.tenantId, provider: "mollie", idempotencyKey: input.eventKey, replayed: false, status: "active", })), now: () => new Date("2026-07-04T00:00:00.000Z"), ...overrides, }; } describe("listAdminBillingRows", () => { it("maps tenants and billing state into loader rows", async () => { const deps = createDeps(); await expect(listAdminBillingRows(deps)).resolves.toMatchObject([ { tenantId: "tenant_1", tenantName: "Acme", planCode: "starter", seatQuantity: 3, entitlementCount: 1, currentPeriodStart: "2026-07-01T00:00:00.000Z", }, ]); }); }); describe("setTenantBillingPlanSeats", () => { it("sets plan/seats, attaches matching catalog product, invalidates caches, and audits the reason", async () => { const deps = createDeps(); await setTenantBillingPlanSeats( { tenantId: "tenant_1", planCode: "starter", seatQuantity: "5", reason: "Sonderkunde", actorUserId: "user_1", actorEmail: "ops@hivegrid.de", }, deps ); expect(deps.db.tenant.findUnique).toHaveBeenCalledWith({ where: { id: "tenant_1" }, select: { id: true, name: true, slug: true } }); expect(deps.db.subscriptionProduct.findFirst).toHaveBeenCalled(); expect( ( deps.db as never as { __tx: { tenantSubscription: { upsert: ReturnType }; tenantSubscriptionProduct: { create: ReturnType } }; } ).__tx.tenantSubscription.upsert ).toHaveBeenCalledWith( expect.objectContaining({ create: expect.objectContaining({ planCode: "starter", seatQuantity: 5, status: "active" }), update: expect.objectContaining({ planCode: "starter", seatQuantity: 5, status: "active" }), }) ); expect( (deps.db as never as { __tx: { tenantSubscriptionProduct: { create: ReturnType } } }).__tx.tenantSubscriptionProduct.create ).toHaveBeenCalledWith( expect.objectContaining({ data: expect.objectContaining({ subscriptionProductId: "product_1", planCode: "starter", seatQuantity: 5, quantity: 5 }), }) ); expect(deps.clearSubscriptionCache).toHaveBeenCalledWith("tenant_1"); expect(deps.invalidateModuleCache).toHaveBeenCalledWith("tenant_1"); expect(deps.recordAction).toHaveBeenCalledWith(expect.objectContaining({ action: "subscription.overridden", reason: "Sonderkunde" })); }); it("rejects invalid seats before writing", async () => { const deps = createDeps(); await expect( setTenantBillingPlanSeats({ tenantId: "tenant_1", planCode: "starter", seatQuantity: "0", reason: "Sonderkunde", actorUserId: "user_1" }, deps) ).rejects.toMatchObject({ code: "INVALID_SEATS" }); expect(deps.db.$transaction).not.toHaveBeenCalled(); }); }); describe("requestManualBillingSync", () => { it("refreshes Lago state directly and audits it", async () => { const deps = createDeps(); await requestManualBillingSync({ tenantId: "tenant_1", provider: "lago", actorUserId: "user_1" }, deps); expect(deps.lagoGateway?.getCustomer).toHaveBeenCalledWith("tenant_1"); expect(deps.lagoGateway?.listInvoices).toHaveBeenCalledWith({ tenantId: "tenant_1", perPage: 1 }); expect(deps.applyLagoSync).toHaveBeenCalledWith( expect.objectContaining({ tenantId: "tenant_1", eventKey: "admin:lago:tenant_1:2026-07-04T00:00:00.000Z", lagoCustomerId: "lago_1", invoiceExternalId: "invoice_1", planCode: "starter", seatQuantity: 3, status: "active", }), ); expect(deps.clearSubscriptionCache).toHaveBeenCalledWith("tenant_1"); expect(deps.invalidateModuleCache).toHaveBeenCalledWith("tenant_1"); expect(deps.recordAction).toHaveBeenCalledWith(expect.objectContaining({ action: "subscription.syncRequested", reason: "manual-lago-sync" })); }); it("refreshes Mollie payment state directly and audits it", async () => { const deps = createDeps(); await requestManualBillingSync({ tenantId: "tenant_1", provider: "mollie", actorUserId: "user_1" }, deps); expect(deps.mollieGateway?.getPayment).toHaveBeenCalledWith("pay_1"); expect(deps.applyMollieSync).toHaveBeenCalledWith( expect.objectContaining({ tenantId: "tenant_1", eventKey: "admin:mollie:tenant_1:pay_1:2026-07-04T00:00:00.000Z", mollieCustomerId: "mollie_1", paymentExternalId: "pay_1", invoiceExternalId: "inv_1", status: "paid", }), ); expect(deps.recordAction).toHaveBeenCalledWith(expect.objectContaining({ action: "subscription.syncRequested", reason: "manual-mollie-sync" })); }); it("requires payment references before requesting Mollie sync", async () => { const deps = createDeps({ resolveBillingState: vi.fn(async () => ({ ...(await createDeps().resolveBillingState("tenant_1")), lastInvoiceExternalId: null, lastPaymentExternalId: null, })), }); await expect(requestManualBillingSync({ tenantId: "tenant_1", provider: "mollie", actorUserId: "user_1" }, deps)).rejects.toBeInstanceOf(AdminBillingError); expect(deps.db.$transaction).not.toHaveBeenCalled(); expect(deps.mollieGateway?.getPayment).not.toHaveBeenCalled(); }); });