import db from "../../db.server"; import type { ShopSettings } from "@prisma/client"; /** * Returns the canonical remittance reference for an order — i.e. the * exact string that should appear: * - on the printed invoice PDF (`invoice.number`), * - in the GiroCode QR payload, * - and in the customer-facing payment instructions on the * thank-you / customer-account pages. * * Banking systems treat each unique reference string as a separate * payment, so all three surfaces MUST use this single source of truth. * * Resolution order: * 1. The latest non-cancelled `Invoice` row for the order — guaranteed * to match what's printed on the PDF. * 2. Predicted default-mode number (`${prefix}${orderNumber}`). Safe * for the default `order_number` numbering mode and a sensible * best-guess for `prefix_sequential` before the invoice has been * generated (the customer just sees the order number with the * shop's invoice prefix instead of the bare Shopify "#1004"). */ export async function resolveOrderRemittance(args: { shopDomain: string; orderGid: string; orderNumber: number | null | undefined; settings: Pick; }): Promise { const invoice = await db.invoice.findFirst({ where: { shopDomain: args.shopDomain, orderId: args.orderGid, kind: "invoice", cancelledAt: null, }, orderBy: [{ version: "desc" }, { createdAt: "desc" }], select: { invoiceNumber: true }, }); if (invoice?.invoiceNumber) return invoice.invoiceNumber; const prefix = args.settings.invoicePrefix || ""; if (args.orderNumber != null) return `${prefix}${args.orderNumber}`; // Last-ditch: derive numeric tail from the GID. const tail = args.orderGid.split("/").pop() ?? ""; return `${prefix}${tail}`; }