import { strict as assert } from "node:assert"; import { describe, it } from "node:test"; import { buildRepresentativeInvoiceMap, type RepresentativeInvoiceRow, } from "../app/services/invoice/representativeInvoice"; const d = (iso: string) => new Date(iso); describe("buildRepresentativeInvoiceMap", () => { it("prefers the active invoice even when a cancelled row has a higher version (regression: order #1032)", () => { // Rows as returned by Prisma: version desc, then createdAt desc. // This mirrors the real #1032 state: a cancelled v8 sorted ahead of the // live, issued v7. The naive "first row wins" picked v8 and the order // rendered as if it had no invoice. const rows: RepresentativeInvoiceRow[] = [ { orderId: "gid://shopify/Order/1032", version: 8, cancelledAt: d("2026-05-31T08:59:05Z") }, { orderId: "gid://shopify/Order/1032", version: 7, cancelledAt: null }, { orderId: "gid://shopify/Order/1032", version: 1, cancelledAt: d("2026-05-15T13:05:14Z") }, ]; const map = buildRepresentativeInvoiceMap(rows); const rep = map.get("gid://shopify/Order/1032"); assert.ok(rep, "expected a representative invoice"); assert.equal(rep!.version, 7, "should select the active v7, not the cancelled v8"); assert.equal(rep!.cancelledAt, null); }); it("falls back to the latest cancelled invoice when none are active", () => { const rows: RepresentativeInvoiceRow[] = [ { orderId: "gid://shopify/Order/1", version: 3, cancelledAt: d("2026-05-31T10:00:00Z") }, { orderId: "gid://shopify/Order/1", version: 1, cancelledAt: d("2026-05-15T10:00:00Z") }, ]; const rep = buildRepresentativeInvoiceMap(rows).get("gid://shopify/Order/1"); assert.ok(rep); assert.equal(rep!.version, 3, "highest-version cancelled wins when nothing is active"); }); it("keeps the highest-version active invoice when multiple are active", () => { const rows: RepresentativeInvoiceRow[] = [ { orderId: "gid://shopify/Order/2", version: 5, cancelledAt: null }, { orderId: "gid://shopify/Order/2", version: 4, cancelledAt: null }, ]; const rep = buildRepresentativeInvoiceMap(rows).get("gid://shopify/Order/2"); assert.equal(rep!.version, 5); }); it("handles multiple orders independently", () => { const rows: RepresentativeInvoiceRow[] = [ { orderId: "A", version: 9, cancelledAt: d("2026-05-31T00:00:00Z") }, { orderId: "A", version: 2, cancelledAt: null }, { orderId: "B", version: 1, cancelledAt: null }, ]; const map = buildRepresentativeInvoiceMap(rows); assert.equal(map.get("A")!.version, 2); assert.equal(map.get("B")!.version, 1); }); });