import db from "../../db.server"; import type { ShopSettings } from "@prisma/client"; /** * Allocates an invoice number for the given order, using the shop's * configured numbering mode. For `prefix_sequential`, allocation is atomic * across concurrent requests via Prisma's interactive transaction (with the * counter row acting as the lock). */ export async function allocateInvoiceNumber( settings: ShopSettings, orderNumber: number, ): Promise { const prefix = settings.invoicePrefix || ""; if (settings.numberingMode === "prefix_sequential") { const next = await db.$transaction(async (tx) => { const counter = await tx.invoiceCounter.upsert({ where: { shopDomain: settings.shopDomain }, create: { shopDomain: settings.shopDomain, lastValue: settings.invoiceSeed, }, update: {}, }); const newValue = counter.lastValue + 1; await tx.invoiceCounter.update({ where: { shopDomain: settings.shopDomain }, data: { lastValue: newValue }, }); return newValue; }); return `${prefix}${next}`; } // Default: reuse the Shopify order number with the configured prefix. return `${prefix}${orderNumber}`; }