diff --git a/repositories/invoice/InvoiceRepository.js b/repositories/invoice/InvoiceRepository.js index 580814b..0d30f30 100644 --- a/repositories/invoice/InvoiceRepository.js +++ b/repositories/invoice/InvoiceRepository.js @@ -1,13 +1,23 @@ const pool = require('../../database/database'); const Invoice = require('../../models/Invoice'); -function genInvoiceNumber() { - const now = new Date(); - const y = now.getFullYear(); - const m = String(now.getMonth() + 1).padStart(2, '0'); - const d = String(now.getDate()).padStart(2, '0'); - const rand = Math.floor(Math.random() * 1e6).toString().padStart(6, '0'); - return `INV-${y}${m}${d}-${rand}`; +async function genInvoiceNumber() { + const year = new Date().getFullYear(); + const prefix = `RE-${year}-`; + const [rows] = await pool.query( + `SELECT invoice_number FROM invoices + WHERE invoice_number LIKE ? + ORDER BY CAST(SUBSTRING_INDEX(invoice_number, '-', -1) AS UNSIGNED) DESC + LIMIT 1`, + [`${prefix}%`], + ); + let next = 1; + if (rows.length) { + const last = rows[0].invoice_number; // e.g. RE-2026-01032026 + const num = parseInt(last.split('-').pop(), 10); + if (!isNaN(num)) next = num + 1; + } + return `${prefix}${String(next).padStart(8, '0')}`; } class InvoiceRepository { @@ -32,7 +42,7 @@ class InvoiceRepository { const conn = await pool.getConnection(); try { await conn.beginTransaction(); - const invoice_number = genInvoiceNumber(); + const invoice_number = await genInvoiceNumber(); // compute totals let total_net = 0;