fix: invoice numbering — use MAX from invoices table instead of sequence counter
This commit is contained in:
@@ -1,8 +1,6 @@
|
|||||||
import prisma from '../config/database';
|
import prisma from '../config/database';
|
||||||
import { generateInvoiceNumber } from './numbering.service';
|
|
||||||
|
|
||||||
// Re-export for convenience
|
// Re-export for convenience
|
||||||
export { generateInvoiceNumber as getNextInvoiceNumber } from './numbering.service';
|
|
||||||
|
|
||||||
// Status transition rules matching PHP
|
// Status transition rules matching PHP
|
||||||
const VALID_TRANSITIONS: Record<string, string[]> = {
|
const VALID_TRANSITIONS: Record<string, string[]> = {
|
||||||
@@ -100,11 +98,18 @@ export async function listInvoices(params: ListInvoicesParams) {
|
|||||||
export async function getNextInvoiceNumberFormatted() {
|
export async function getNextInvoiceNumberFormatted() {
|
||||||
const settings = await prisma.company_settings.findFirst({ select: { invoice_type_code: true } });
|
const settings = await prisma.company_settings.findFirst({ select: { invoice_type_code: true } });
|
||||||
const typeCode = settings?.invoice_type_code || '81';
|
const typeCode = settings?.invoice_type_code || '81';
|
||||||
const year = new Date().getFullYear();
|
const yy = String(new Date().getFullYear()).slice(-2);
|
||||||
const yy = String(year).slice(-2);
|
|
||||||
const prefix = `${yy}${typeCode}`;
|
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')}`;
|
const number = `${prefix}${String(nextNum).padStart(4, '0')}`;
|
||||||
return { number, next_number: number };
|
return { number, next_number: number };
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user