Merge pull request 'feat: refactor genInvoiceNumber to use database query for unique invoice numbers' (#13) from dev into main
Reviewed-on: #13
This commit is contained in:
commit
ca422037d7
@ -1,13 +1,23 @@
|
|||||||
const pool = require('../../database/database');
|
const pool = require('../../database/database');
|
||||||
const Invoice = require('../../models/Invoice');
|
const Invoice = require('../../models/Invoice');
|
||||||
|
|
||||||
function genInvoiceNumber() {
|
async function genInvoiceNumber() {
|
||||||
const now = new Date();
|
const year = new Date().getFullYear();
|
||||||
const y = now.getFullYear();
|
const prefix = `RE-${year}-`;
|
||||||
const m = String(now.getMonth() + 1).padStart(2, '0');
|
const [rows] = await pool.query(
|
||||||
const d = String(now.getDate()).padStart(2, '0');
|
`SELECT invoice_number FROM invoices
|
||||||
const rand = Math.floor(Math.random() * 1e6).toString().padStart(6, '0');
|
WHERE invoice_number LIKE ?
|
||||||
return `INV-${y}${m}${d}-${rand}`;
|
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 {
|
class InvoiceRepository {
|
||||||
@ -32,7 +42,7 @@ class InvoiceRepository {
|
|||||||
const conn = await pool.getConnection();
|
const conn = await pool.getConnection();
|
||||||
try {
|
try {
|
||||||
await conn.beginTransaction();
|
await conn.beginTransaction();
|
||||||
const invoice_number = genInvoiceNumber();
|
const invoice_number = await genInvoiceNumber();
|
||||||
|
|
||||||
// compute totals
|
// compute totals
|
||||||
let total_net = 0;
|
let total_net = 0;
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user