mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 11:06:28 +00:00
74 lines
2.8 KiB
JavaScript
74 lines
2.8 KiB
JavaScript
const counterTable = 'trx.t_transaction_number_counter';
|
|
const maxSequence = 999999;
|
|
const numberTypes = {
|
|
RBL: {
|
|
column: 'c_reservation_no',
|
|
claim: 'trx.t_d_reservation_no_validate',
|
|
history: ['trx.t_d_reservation_balance'],
|
|
},
|
|
LBL: {
|
|
column: 'c_load_balance_no',
|
|
claim: 'trx.t_d_load_balance_no_validate',
|
|
history: ['trx.t_d_load_balance', 'trx.t_d_load_balance_history'],
|
|
},
|
|
};
|
|
|
|
function createTransactionNumberAllocator(knex) {
|
|
return async function allocateTransactionNumber(type, partnerCode, date) {
|
|
const { column, claim, history } = numberTypes[type];
|
|
const prefix = `${type}${partnerCode || 'XXX'}${date}`;
|
|
const first = `${prefix}000000`;
|
|
const last = `${prefix}${maxSequence}`;
|
|
const sources = [claim, ...history];
|
|
const latestSequence = sources.map(() => `(
|
|
SELECT right(??, 6)::integer FROM ??
|
|
WHERE ?? BETWEEN ? AND ?
|
|
AND left(??, length(?)) = ?
|
|
AND length(??) = length(?) + 6
|
|
AND right(??, 6) ~ '^[0-9]{6}$'
|
|
ORDER BY ?? DESC LIMIT 1
|
|
)`).join(', ');
|
|
const historyBindings = sources.flatMap((table) => [
|
|
column, table, column, first, last, column, prefix, prefix, column, prefix, column, column,
|
|
]);
|
|
|
|
// PostgreSQL menyinkronkan counter per awalan yang terlihat di nomor.
|
|
// Riwayat hanya dibaca saat awalan itu pertama kali dialokasikan.
|
|
const sql = `
|
|
WITH starting_value AS (
|
|
SELECT CASE WHEN ? AND EXISTS (SELECT 1 FROM ?? WHERE number_prefix = ?)
|
|
THEN 1 ELSE GREATEST(0, ${latestSequence}) + 1 END AS value
|
|
), allocated AS (
|
|
INSERT INTO ?? AS counter (number_prefix, last_value)
|
|
SELECT ?, value FROM starting_value WHERE value <= ?
|
|
ON CONFLICT (number_prefix) DO UPDATE
|
|
SET last_value = GREATEST(counter.last_value + 1, EXCLUDED.last_value)
|
|
WHERE counter.last_value < ?
|
|
RETURNING last_value
|
|
), claimed AS (
|
|
INSERT INTO ?? (??)
|
|
SELECT ? || lpad(last_value::text, 6, '0') FROM allocated
|
|
ON CONFLICT (??) DO NOTHING
|
|
RETURNING ?? AS number
|
|
)
|
|
SELECT allocated.last_value AS sequence, claimed.number
|
|
FROM allocated LEFT JOIN claimed ON true
|
|
`;
|
|
const bindings = [
|
|
counterTable, prefix, ...historyBindings,
|
|
counterTable, prefix, maxSequence, maxSequence,
|
|
claim, column, prefix, column, column,
|
|
];
|
|
|
|
// Klaim lama tetap dihormati ketika masih ada replika versi sebelumnya.
|
|
for (let attempt = 0; attempt < 5; attempt++) {
|
|
const { rows: [allocation] } = await knex.raw(sql, [attempt === 0, ...bindings]);
|
|
if (!allocation) throw new Error(`Daily ${type} number sequence exhausted`);
|
|
if (allocation.number) return allocation;
|
|
}
|
|
throw new Error(`Could not claim a unique ${type} number`);
|
|
};
|
|
}
|
|
|
|
module.exports = createTransactionNumberAllocator;
|