import { beforeEach, describe, expect, it, vi } from "vitest"; const mocks = vi.hoisted(() => ({ withTenantRLS: vi.fn(), invoiceFindFirst: vi.fn(), invoiceUpdate: vi.fn(), requireAccess: vi.fn(), })); vi.mock("~/utils/db/.server/tenantRls.server", () => ({ withTenantRLS: mocks.withTenantRLS })); vi.mock("@hivegrid/activity", () => ({ logActivity: vi.fn() })); import { updateProjectInvoiceStatus } from "./auftragService.server"; const tx = { rechnung: { findFirst: mocks.invoiceFindFirst, update: mocks.invoiceUpdate }, projekt: { findFirst: mocks.requireAccess }, projektMitglied: { findFirst: vi.fn().mockResolvedValue(null) }, }; const ctx = { tenantId: "tenant-1", userId: "user-1", permissions: ["projects.read_all", "projects.write", "projects.admin"] }; function invoice(overrides: Record = {}) { return { id: "invoice-1", tenantId: "tenant-1", projektId: "project-1", status: "gestellt", bezahltAm: null, ...overrides }; } beforeEach(() => { vi.clearAllMocks(); mocks.withTenantRLS.mockImplementation(async (_tenantId: string, callback: (client: unknown) => unknown) => callback(tx)); mocks.requireAccess.mockResolvedValue({ id: "project-1", tenantId: "tenant-1", archivedAt: null }); mocks.invoiceUpdate.mockImplementation(async ({ data }: { data: Record }) => ({ ...invoice(), ...data })); }); describe("invoice payment date", () => { it("stamps the payment date when an invoice is marked paid", async () => { mocks.invoiceFindFirst.mockResolvedValue(invoice()); const before = Date.now(); const row = await updateProjectInvoiceStatus({ tenantId: "tenant-1", invoiceId: "invoice-1", ctx: ctx as never, userId: "user-1", status: "bezahlt", }); const stamped = mocks.invoiceUpdate.mock.calls[0]![0].data.bezahltAm as Date; expect(stamped).toBeInstanceOf(Date); expect(stamped.getTime()).toBeGreaterThanOrEqual(before); expect(row.bezahltAm).toBe(stamped); }); it("keeps the original payment date when a paid invoice is saved as paid again", async () => { const paidAt = new Date("2026-07-01T10:00:00.000Z"); mocks.invoiceFindFirst.mockResolvedValue(invoice({ status: "bezahlt", bezahltAm: paidAt })); await updateProjectInvoiceStatus({ tenantId: "tenant-1", invoiceId: "invoice-1", ctx: ctx as never, userId: "user-1", status: "bezahlt", }); expect(mocks.invoiceUpdate.mock.calls[0]![0].data.bezahltAm).toBe(paidAt); }); it("clears the payment date when a paid invoice moves back to unpaid", async () => { mocks.invoiceFindFirst.mockResolvedValue(invoice({ status: "bezahlt", bezahltAm: new Date("2026-07-01T10:00:00.000Z") })); for (const status of ["gestellt", "storniert", "entwurf"] as const) { mocks.invoiceUpdate.mockClear(); await updateProjectInvoiceStatus({ tenantId: "tenant-1", invoiceId: "invoice-1", ctx: ctx as never, userId: "user-1", status, }); expect(mocks.invoiceUpdate.mock.calls[0]![0].data).toEqual({ status, bezahltAm: null }); } }); });