fix: invoice numbering — use MAX from invoices table instead of sequence counter

This commit is contained in:
BOHA
2026-03-23 19:25:16 +01:00
parent 93ea9911f8
commit d33c2b3416

View File

@@ -1,8 +1,6 @@
import prisma from '../config/database';
import { generateInvoiceNumber } from './numbering.service';
// Re-export for convenience
export { generateInvoiceNumber as getNextInvoiceNumber } from './numbering.service';
// Status transition rules matching PHP
const VALID_TRANSITIONS: Record<string, string[]> = {
@@ -100,11 +98,18 @@ export async function listInvoices(params: ListInvoicesParams) {
export async function getNextInvoiceNumberFormatted() {
const settings = await prisma.company_settings.findFirst({ select: { invoice_type_code: true } });
const typeCode = settings?.invoice_type_code || '81';
const year = new Date().getFullYear();
const yy = String(year).slice(-2);
const yy = String(new Date().getFullYear()).slice(-2);
const prefix = `${yy}${typeCode}`;
const prefixLen = prefix.length;
const likePattern = `${prefix}%`;
const nextNum = await generateInvoiceNumber(year);
// MAX from existing invoices — same approach as offers/orders
const result = await prisma.$queryRaw<[{ max_num: bigint | null }]>`
SELECT COALESCE(MAX(CAST(SUBSTRING(invoice_number, ${prefixLen} + 1) AS UNSIGNED)), 0) as max_num
FROM invoices
WHERE invoice_number LIKE ${likePattern}
`;
const nextNum = Number(result[0]?.max_num ?? 0) + 1;
const number = `${prefix}${String(nextNum).padStart(4, '0')}`;
return { number, next_number: number };
}