mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:46:28 +00:00
Align transaction and log timestamps with Jakarta time
Keep recovered Load Balance writes and card audit atomic, and isolate Payment Recon tests.
This commit is contained in:
@@ -1,5 +1,7 @@
|
||||
const { Counter } = require('prom-client');
|
||||
|
||||
const WIB_OFFSET_MS = 7 * 60 * 60 * 1000;
|
||||
|
||||
const skipped = new Counter({
|
||||
name: 'topuponline_stdout_copies_skipped_total',
|
||||
help: 'Log copies skipped while stdout was unavailable or under backpressure',
|
||||
@@ -42,7 +44,8 @@ function formatLog(event, time = Date.now()) {
|
||||
.slice(0, 512);
|
||||
}
|
||||
return JSON.stringify({
|
||||
timestamp: new Date(time).toISOString(),
|
||||
// Bentuk timestamp WIB dari epoch supaya hasilnya sama di semua host.
|
||||
timestamp: new Date(time + WIB_OFFSET_MS).toISOString().replace(/Z$/, '+07:00'),
|
||||
app: 'topuponline',
|
||||
pid: process.pid,
|
||||
...safeEvent,
|
||||
|
||||
@@ -101,46 +101,31 @@ const updateAllTransaction = async (
|
||||
`${logCorrelation(uniqueCode)} updating reservation and load balance transaction...`
|
||||
);
|
||||
|
||||
// update reservation and load balance transaction
|
||||
const update = await model.updateReservationAndLoadingBalance(
|
||||
reservationNumber,
|
||||
data,
|
||||
dataLoadingBalanceDetail,
|
||||
now,
|
||||
flag
|
||||
const cardHistory = {
|
||||
i_log_name: 21,
|
||||
d_log: dataLoadingBalance.d_load_balance,
|
||||
c_card_number: cardNumber,
|
||||
c_source: 'CMS',
|
||||
c_location: getPartner ? getPartner.partner_name : null,
|
||||
m_balance_before: parseInt(dataLoadingBalance.m_balance),
|
||||
m_amount: parseInt(dataLoadingBalance.i_topup_amount),
|
||||
m_balance_after: parseInt(balance),
|
||||
j_new_data: { data: data, detail: dataLoadingBalanceDetail },
|
||||
j_old_data: null,
|
||||
c_note: `LOAD BALANCE ${dataLoadingBalance.i_topup_amount} FROM ${
|
||||
getPartner ? getPartner.partner_name : null
|
||||
} SUCCESSFULLY`,
|
||||
c_status: 'S',
|
||||
d_created: now,
|
||||
i_create: null,
|
||||
c_create_username: 'HSM',
|
||||
c_create_fullname: 'HARDWARE SECURE MODULE',
|
||||
c_category: 'T',
|
||||
};
|
||||
|
||||
return await model.updateReservationAndLoadingBalance(
|
||||
reservationNumber, data, dataLoadingBalanceDetail, now, flag, cardHistory
|
||||
);
|
||||
|
||||
if (update) {
|
||||
// log debug
|
||||
winston.logger.debug(`${logCorrelation(uniqueCode)} inserting log for card history...`);
|
||||
|
||||
// log card history
|
||||
await model.createLoadBalanceLog({
|
||||
i_log_name: 21,
|
||||
d_log: dataLoadingBalance.d_load_balance,
|
||||
c_card_number: cardNumber,
|
||||
c_source: 'CMS',
|
||||
c_location: getPartner ? getPartner.partner_name : null,
|
||||
m_balance_before: parseInt(dataLoadingBalance.m_balance),
|
||||
m_amount: parseInt(dataLoadingBalance.i_topup_amount),
|
||||
m_balance_after: parseInt(balance),
|
||||
j_new_data: { data: data, detail: dataLoadingBalanceDetail },
|
||||
j_old_data: null,
|
||||
c_note: `LOAD BALANCE ${dataLoadingBalance.i_topup_amount} FROM ${
|
||||
getPartner ? getPartner.partner_name : null
|
||||
} SUCCESSFULLY`,
|
||||
c_status: 'S',
|
||||
d_created: now,
|
||||
i_create: null,
|
||||
c_create_username: 'HSM',
|
||||
c_create_fullname: 'HARDWARE SECURE MODULE',
|
||||
c_category: 'T',
|
||||
});
|
||||
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// insert new load balance transaction by data on card and update data reservation
|
||||
|
||||
@@ -200,74 +185,13 @@ const updateAllTransaction = async (
|
||||
// )}`
|
||||
// );
|
||||
|
||||
if (detailLoadBalance.length > 0) {
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} AAAAAAAAAAAAAAAAAA1111 [DATA] : ${JSON.stringify(
|
||||
// reservationNumber
|
||||
// )} [LB] : ${JSON.stringify(dataLoadBalance)} [LBD] : ${JSON.stringify(
|
||||
// detailLoadBalance
|
||||
// )} [NOW] : ${JSON.stringify(now)} [FLAG] : ${JSON.stringify(flag)}`
|
||||
// );
|
||||
if (detailLoadBalance.length === 0) return false;
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} updating reservation and insert new load balance transaction...`
|
||||
// );
|
||||
const updated = await model.updateReservationAndInsertLoadingBalance(
|
||||
reservationNumber, dataLoadBalance, detailLoadBalance, now, flag
|
||||
);
|
||||
return typeof updated === 'number' && updated > 0;
|
||||
|
||||
// update reservation and load balance transaction
|
||||
let updateReservationAndInsertLoadingBalance =
|
||||
await model.updateReservationAndInsertLoadingBalance(
|
||||
reservationNumber,
|
||||
dataLoadBalance,
|
||||
detailLoadBalance,
|
||||
now,
|
||||
flag
|
||||
);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} status insert new load balance and update reservation : ${JSON.stringify(
|
||||
// updateReservationAndInsertLoadingBalance
|
||||
// )}`
|
||||
// );
|
||||
|
||||
// if (updateReservationAndInsertLoadingBalance > 0) {
|
||||
// // log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} inserting log for card history...`
|
||||
// );
|
||||
|
||||
// // log card history
|
||||
// await model.createLoadBalanceLog({
|
||||
// i_log_name:21,
|
||||
// d_log: dataLoadingBalance.d_load_balance,
|
||||
// c_card_number: cardNumber,
|
||||
// c_source: 'CMS',
|
||||
// c_location: getPartner ? getPartner.partner_name : null,
|
||||
// m_balance_before: parseInt(dataLoadingBalance.m_balance),
|
||||
// m_amount: parseInt(dataLoadingBalance.i_topup_amount),
|
||||
// m_balance_after: parseInt(balance),
|
||||
// j_new_data: { data: data, detail: dataLoadingBalanceDetail },
|
||||
// j_old_data: null,
|
||||
// c_note: `LOAD BALANCE ${dataLoadingBalance.i_topup_amount} FROM ${
|
||||
// getPartner ? getPartner.partner_name : null
|
||||
// } SUCCESSFULLY`,
|
||||
// c_status: 'S',
|
||||
// d_created: now,
|
||||
// i_create: null,
|
||||
// c_create_username: 'HSM',
|
||||
// c_create_fullname: 'HARDWARE SECURE MODULE',
|
||||
// c_category: 'T',
|
||||
// });
|
||||
// } else {
|
||||
// return false;
|
||||
// }
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
// create log
|
||||
|
||||
@@ -535,15 +535,18 @@ const checkFlag = (cardNumber, uid) => {
|
||||
};
|
||||
|
||||
// UPDATE RESERVATION AND LOADING BALANCE CASE FAILED WRITE BEFORE
|
||||
const updateReservationAndLoadingBalance = async (reservationNumber, data, detail, now, flag) => {
|
||||
const updateReservationAndLoadingBalance = async (reservationNumber, data, detail, now, flag, cardHistory) => {
|
||||
try {
|
||||
await knex.transaction(async (trx) => {
|
||||
await trx('trx.t_d_load_balance').update(data).where('c_load_balance_no', data.c_load_balance_no);
|
||||
const updated = await trx('trx.t_d_load_balance').update(data).where('c_load_balance_no', data.c_load_balance_no);
|
||||
if (updated === 0) throw new Error('Load balance was not found for recovery');
|
||||
const [history] = await trx('trx.t_d_load_balance_history').insert(data).returning('i_load_balance');
|
||||
await trx('trx.t_d_load_balance_history_detail').insert(
|
||||
mapLoadBalanceDetails(detail, getInsertedLoadBalanceId(history))
|
||||
);
|
||||
await markReservationsLoaded(trx, reservationNumber, data, now, flag);
|
||||
// Audit pemulihan harus berhasil sebelum status saldo dan reservasi di-commit.
|
||||
await createLoadBalanceLog(cardHistory, trx);
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
@@ -861,7 +864,9 @@ const updateReservationAndInsertLoadingBalance = async (
|
||||
await trx('trx.t_d_load_balance_detail').insert(
|
||||
mapLoadBalanceDetails(detailLoadBalance, getInsertedLoadBalanceId(header), 'i_reservation_amount')
|
||||
);
|
||||
return markReservationsLoaded(trx, reservationNumber, dataLoadBalance, now, flag);
|
||||
const updated = await markReservationsLoaded(trx, reservationNumber, dataLoadBalance, now, flag);
|
||||
if (updated === 0) throw new Error('No reservations found for load balance recovery');
|
||||
return updated;
|
||||
});
|
||||
} catch (error) {
|
||||
logTransactionFailure('insert_balance_from_reservations', error);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const { pooling: poolingConfig } = require("../../../knexfile");
|
||||
const dbPooling = require("knex")(poolingConfig);
|
||||
const { withTransactionTimeZone } = require("../../../infrastructure/transaction-time");
|
||||
const dbPooling = require("knex")(withTransactionTimeZone(poolingConfig));
|
||||
const { observePool } = require("../../../infrastructure/database/pool-metrics");
|
||||
observePool("pooling", dbPooling.client.pool);
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
|
||||
@@ -13,7 +13,7 @@ const detail = {
|
||||
i_reservation_amount: 10000,
|
||||
};
|
||||
|
||||
function captureTransaction(failTable) {
|
||||
function captureTransaction(failTable, updatedReservations = 1) {
|
||||
const writes = [];
|
||||
const failure = Object.assign(new Error('fixture write failure'), { code: '23514' });
|
||||
const trx = jest.fn((table) => {
|
||||
@@ -30,7 +30,7 @@ function captureTransaction(failTable) {
|
||||
if (table === failTable) return Promise.reject(failure).then(resolve, reject);
|
||||
const result = table === 'trx.t_d_load_balance' ? [{ i_load_balance: 10 }]
|
||||
: table === 'trx.t_d_load_balance_history' ? [{ i_load_balance: 20 }]
|
||||
: table === 'trx.t_d_reservation_balance' ? 1
|
||||
: table === 'trx.t_d_reservation_balance' ? updatedReservations
|
||||
: { rowCount: 1 };
|
||||
return Promise.resolve(result).then(resolve, reject);
|
||||
};
|
||||
@@ -91,3 +91,12 @@ test('pemulihan saldo memakai nominal reservasi dan mengembalikan jumlah reserva
|
||||
'trx.t_d_reservation_balance', 'update', expect.objectContaining({ c_status: 'A', c_status_name: 'LOADED' }),
|
||||
]);
|
||||
});
|
||||
|
||||
test('pembuatan saldo pemulihan dibatalkan jika tidak ada reservasi yang diperbarui', async () => {
|
||||
captureTransaction(undefined, 0);
|
||||
|
||||
await expect(model.updateReservationAndInsertLoadingBalance(
|
||||
['RBL1'], header, [detail], '2026-11-24', 1
|
||||
)).resolves.toBe('No reservations found for load balance recovery');
|
||||
await expect(db.transaction.mock.results[0].value).rejects.toThrow('No reservations found');
|
||||
});
|
||||
|
||||
@@ -9,9 +9,14 @@ jest.mock('../../infrastructure/database/knex', () => {
|
||||
|
||||
let mockTransaction;
|
||||
|
||||
jest.mock('../helpers/winston.logger', () => ({
|
||||
logger: { info: jest.fn(), debug: jest.fn(), warn: jest.fn(), error: jest.fn() },
|
||||
}));
|
||||
|
||||
integration('pembaruan Load Balance di PostgreSQL', () => {
|
||||
let db;
|
||||
let update;
|
||||
let recover;
|
||||
|
||||
beforeAll(() => {
|
||||
const url = new URL(testDatabaseUrl);
|
||||
@@ -19,10 +24,22 @@ integration('pembaruan Load Balance di PostgreSQL', () => {
|
||||
throw new Error('Gunakan database lokal topup_loadbalance_test khusus pengujian.');
|
||||
}
|
||||
|
||||
db = require('knex')({ client: 'pg', connection: testDatabaseUrl, pool: { min: 0, max: 1 } });
|
||||
const { withTransactionTimeZone } = require('../../infrastructure/transaction-time');
|
||||
db = require('knex')(withTransactionTimeZone({
|
||||
client: 'pg',
|
||||
connection: testDatabaseUrl,
|
||||
pool: {
|
||||
min: 0,
|
||||
max: 1,
|
||||
afterCreate(connection, done) {
|
||||
connection.query("SET TIME ZONE 'UTC'", (error) => done(error, connection));
|
||||
},
|
||||
},
|
||||
}));
|
||||
const model = require('../modules/loadbalance/loadbalance.model');
|
||||
jest.spyOn(model, 'getPartner').mockResolvedValue({ partner_name: 'Fixture Partner' });
|
||||
({ loadingBalanceUpdate: update } = require('../modules/loadbalance/loadbalance.controller'));
|
||||
({ updateAllTransaction: recover } = require('../modules/loadbalance/load-balance-write.service'));
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
@@ -37,8 +54,7 @@ integration('pembaruan Load Balance di PostgreSQL', () => {
|
||||
c_return_sap text, c_status text, c_status_name text,
|
||||
d_modify timestamp, i_modify integer, c_modify_username text, c_modify_fullname text
|
||||
);
|
||||
CREATE TABLE trx.t_d_load_balance_history (LIKE trx.t_d_load_balance INCLUDING DEFAULTS);
|
||||
ALTER TABLE trx.t_d_load_balance_history
|
||||
ALTER TABLE trx.t_d_load_balance
|
||||
ADD COLUMN i_partner integer, ADD COLUMN c_partner_code text, ADD COLUMN c_partner_name text,
|
||||
ADD COLUMN i_merchant integer, ADD COLUMN c_merchant_code text, ADD COLUMN c_merchant_name text,
|
||||
ADD COLUMN c_mid text, ADD COLUMN i_terminal integer, ADD COLUMN c_terminal_code text,
|
||||
@@ -47,6 +63,7 @@ integration('pembaruan Load Balance di PostgreSQL', () => {
|
||||
ADD COLUMN d_create timestamp, ADD COLUMN i_create integer, ADD COLUMN c_create_username text,
|
||||
ADD COLUMN c_create_fullname text, ADD COLUMN d_delete timestamp, ADD COLUMN i_delete integer,
|
||||
ADD COLUMN c_delete_username text, ADD COLUMN c_delete_fullname text;
|
||||
CREATE TABLE trx.t_d_load_balance_history (LIKE trx.t_d_load_balance INCLUDING DEFAULTS);
|
||||
CREATE TABLE trx.t_d_load_balance_detail (
|
||||
i_load_balance integer, i_reservation_balance integer, c_reservation_no text, i_amount integer,
|
||||
i_issuer integer, c_issuer_code text, c_issuer_name text, i_issuer_fee integer,
|
||||
@@ -59,7 +76,7 @@ integration('pembaruan Load Balance di PostgreSQL', () => {
|
||||
);
|
||||
CREATE TABLE trx.t_d_reservation_balance (
|
||||
c_reservation_no text, c_load_balance_no text, c_status text, c_status_name text,
|
||||
c_flag_code text, d_load_balance timestamp, d_modify timestamp, i_modify integer,
|
||||
c_flag text, c_flag_code text, d_load_balance timestamp, d_modify timestamp, i_modify integer,
|
||||
c_modify_username text, c_modify_fullname text
|
||||
);
|
||||
CREATE TABLE trx.t_d_flag_counting (
|
||||
@@ -125,4 +142,37 @@ integration('pembaruan Load Balance di PostgreSQL', () => {
|
||||
await expect(mockTransaction('log.t_log_card').first('i_log_name'))
|
||||
.resolves.toEqual({ i_log_name: 21 });
|
||||
});
|
||||
|
||||
test('gagal menulis audit pemulihan membatalkan pembaruan saldo dan reservasi', async () => {
|
||||
await mockTransaction.raw(`
|
||||
INSERT INTO trx.t_d_load_balance_history
|
||||
(i_load_balance, c_load_balance_no, d_load_balance, c_status, m_balance, i_topup_amount)
|
||||
VALUES (20, 'LBL1', '2026-11-25 00:30:00', 'I', 50, 20);
|
||||
INSERT INTO trx.t_d_load_balance_history_detail VALUES (20, 7, 'RBL1', 20);
|
||||
ALTER TABLE log.t_log_card ADD CHECK (i_log_name <> 21)
|
||||
`);
|
||||
|
||||
await expect(recover(
|
||||
['RBL1'], ['LBL1'], 'fixture-mid', 'fixture-tid', 'card-fixture', 70, '2', '123', 20, 'UID'
|
||||
)).resolves.toBe(false);
|
||||
|
||||
const { logger } = require('../helpers/winston.logger');
|
||||
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining(
|
||||
'operation=update_reservations_and_balance sqlstate=23514'
|
||||
));
|
||||
await expect(mockTransaction('trx.t_d_load_balance').first('c_status')).resolves.toEqual({ c_status: 'I' });
|
||||
await expect(mockTransaction('trx.t_d_reservation_balance').first('c_status')).resolves.toEqual({ c_status: 'I' });
|
||||
await expect(mockTransaction('trx.t_d_load_balance_history').select('i_load_balance'))
|
||||
.resolves.toEqual([{ i_load_balance: 20 }]);
|
||||
await expect(mockTransaction('log.t_log_card').select('i_log_name')).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
test('sesi PostgreSQL memakai tanggal Jakarta ketika UTC masih sehari sebelumnya', async () => {
|
||||
const { rows: [row] } = await mockTransaction.raw(`
|
||||
SELECT current_setting('TimeZone') AS zone,
|
||||
(TIMESTAMPTZ '2026-11-24 17:30:00+00')::date::text AS business_date
|
||||
`);
|
||||
|
||||
expect(row).toEqual({ zone: 'Asia/Jakarta', business_date: '2026-11-25' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,14 @@ const createAuditArchive = require('../helpers/audit-archive');
|
||||
const { createStdoutWriter, formatLog } = require('../helpers/stdout-log');
|
||||
const createRedisOperations = require('../helpers/redis-operations');
|
||||
|
||||
test('timestamp log mengikuti WIB dan mempertahankan waktu kejadian saat tanggal berganti', () => {
|
||||
const time = Date.parse('2026-11-24T17:30:00.123Z');
|
||||
const { timestamp } = JSON.parse(formatLog({ event: 'http_response' }, time));
|
||||
|
||||
expect(timestamp).toBe('2026-11-25T00:30:00.123+07:00');
|
||||
expect(Date.parse(timestamp)).toBe(time);
|
||||
});
|
||||
|
||||
test('stdout backpressure preserves every audit and a stale Loki URL does not trigger HTTP', () => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'topup-audit-'));
|
||||
const audit = createAuditArchive(directory);
|
||||
@@ -38,6 +46,8 @@ test('stdout backpressure preserves every audit and a stale Loki URL does not tr
|
||||
const [file] = fs.readdirSync(directory);
|
||||
const archived = fs.readFileSync(path.join(directory, file), 'utf8').trim().split('\n').map(JSON.parse);
|
||||
expect(archived.map(({ request_id }) => request_id)).toEqual(['first', 'slow-console', 'recovered']);
|
||||
expect(archived[0].timestamp).toBe(emitted[0].timestamp);
|
||||
expect(archived[0].timestamp).toMatch(/\+07:00$/);
|
||||
} finally {
|
||||
jest.dontMock('../helpers/audit-archive');
|
||||
jest.dontMock('../helpers/stdout-log');
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const model = require('../modules/paymentrecon/paymentrecon.model');
|
||||
const { paymentRecon, validate } = require('../modules/paymentrecon/paymentrecon.controller');
|
||||
|
||||
jest.mock('../middlewares/jwt.middleware', () => ({
|
||||
authenticateToken(req, res, next) {
|
||||
req.partner_id_token = '1';
|
||||
next();
|
||||
},
|
||||
}));
|
||||
jest.mock('../helpers/helper', () => ({ getUniqueCode: () => 'fixture', randomNumberInt: () => 0 }));
|
||||
jest.mock('../helpers/winston.logger', () => ({ logger: {
|
||||
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
|
||||
@@ -21,10 +26,7 @@ jest.mock('../modules/paymentrecon/paymentrecon.model', () => ({
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.post('/api/payment-recon', (req, res, next) => {
|
||||
req.partner_id_token = '1';
|
||||
next();
|
||||
}, validate('paymentRecon'), paymentRecon);
|
||||
app.use('/api', require('../routes/paymentrecon.routes'));
|
||||
const body = { date: '2026-11-23', reservation_number: 'RBL1', bank_ref: 'BANK1', amount: 1000 };
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -35,6 +37,22 @@ beforeEach(() => {
|
||||
model.checkReservationNumberAndAmount.mockResolvedValue({ total_transaction: 1, total_amount: '1000' });
|
||||
});
|
||||
|
||||
test('Payment Recon berhasil menyimpan transaksi dan mengembalikan nomor rekonsiliasi', async () => {
|
||||
model.completePaymentRecon.mockResolvedValue(true);
|
||||
|
||||
const response = await request(app).post('/api/payment-recon').send(body);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({
|
||||
code: '00',
|
||||
data: { payment_recon_no: expect.stringMatching(/^RCTST\d{12}$/) },
|
||||
});
|
||||
expect(model.completePaymentRecon).toHaveBeenCalledWith(expect.objectContaining({
|
||||
paymentReconNumber: response.body.data.payment_recon_no,
|
||||
time: response.body.data.recon_date,
|
||||
}));
|
||||
});
|
||||
|
||||
test('the loser of a concurrent reconciliation returns the winner’s number and code 04', async () => {
|
||||
const winner = { c_payment_recon_no: 'RC-WINNER', d_payment_recon: '2026-11-23 10:00:00' };
|
||||
model.checkReservationNumberAndAmountAlreadyRecon
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
const request = require("supertest");
|
||||
const app = require("../../server");
|
||||
require("dotenv").config();
|
||||
|
||||
let token = process.env.TOKEN_TESTING;
|
||||
|
||||
describe("POST Payment Recon", () => {
|
||||
it("should create new post payment recon", async () => {
|
||||
const res = await request(app)
|
||||
.post("/api/payment-recon")
|
||||
.send({
|
||||
date: "2022-08-30",
|
||||
bank_ref: "BR220830",
|
||||
reservation_number: "RSVMP1401620220707002",
|
||||
amount: "10000",
|
||||
})
|
||||
.set("Authorization", `Bearer ${token}`);
|
||||
expect(res.statusCode).toBe(200);
|
||||
if (
|
||||
res.body.code != "00" &&
|
||||
res.body.code != "01" &&
|
||||
res.body.code != "02" &&
|
||||
res.body.code != "03" &&
|
||||
res.body.code != "04"
|
||||
) {
|
||||
expect(res.body.code).toContain(
|
||||
"response code must be : 00 | 01 | 02 | 03 | 04"
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
test('jam bisnis Jakarta konsisten saat host diawali dengan zona UTC', () => {
|
||||
const script = `
|
||||
require('./infrastructure/transaction-time').configureTransactionClock();
|
||||
const moment = require('moment');
|
||||
const instant = new Date('2026-11-24T17:30:00.000Z');
|
||||
const transactionTime = moment(instant);
|
||||
process.stdout.write(JSON.stringify({
|
||||
dateTime: transactionTime.format('YYYY-MM-DD HH:mm:ss'),
|
||||
numberDate: transactionTime.format('YYMMDD'),
|
||||
utc: instant.toISOString(),
|
||||
}));
|
||||
`;
|
||||
const output = execFileSync(process.execPath, ['-e', script], {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, TZ: 'UTC' },
|
||||
});
|
||||
|
||||
expect(JSON.parse(output)).toEqual({
|
||||
dateTime: '2026-11-25 00:30:00',
|
||||
numberDate: '261125',
|
||||
utc: '2026-11-24T17:30:00.000Z',
|
||||
});
|
||||
});
|
||||
@@ -37,7 +37,9 @@ di konfigurasi Promtail. Tambahkan label stream `app=topuponline` di target
|
||||
scrape agar dashboard dan kueri di atas tetap menemukan log.
|
||||
Respons terpantau menggunakan `event=http_response`; log Winston menggunakan
|
||||
`event=application_log`. Request tidak dicatat sebagai event terpisah karena
|
||||
ID request dan statusnya tersedia pada event respons.
|
||||
ID request dan statusnya tersedia pada event respons. Field `timestamp`
|
||||
menggunakan WIB dengan offset `+07:00`, misalnya
|
||||
`2026-11-25T00:30:00.000+07:00`.
|
||||
|
||||
Untuk service yang menulis stdout ke file, arahkan `__path__` ke file stdout
|
||||
yang sebenarnya. Contoh ini berlaku untuk file yang memuat pesan aplikasi
|
||||
|
||||
@@ -11,8 +11,9 @@ dapat dicari dengan `request_id`, `trx_id`,
|
||||
transaksi PostgreSQL tetap menjadi sumber status bisnis.
|
||||
|
||||
Gunakan `TOPUP_AUDIT_DIR` pada volume persisten yang dapat ditulis oleh proses
|
||||
aplikasi. Path bawaan adalah `./lokiLog/audit`. File dibagi per tanggal UTC dan
|
||||
proses. Secara default aplikasi tidak menghapus file JSONL. Tetapkan
|
||||
aplikasi. Path bawaan adalah `./lokiLog/audit`. Timestamp di dalam JSONL memakai
|
||||
WIB. Nama dan pergantian file mengikuti tanggal UTC per proses. Secara default
|
||||
aplikasi tidak menghapus file JSONL. Tetapkan
|
||||
`TOPUP_AUDIT_RETENTION_DAYS` sebagai bilangan hari positif sesuai kebijakan
|
||||
retensi audit organisasi untuk mengaktifkan penghapusan file yang melewati usia
|
||||
tersebut. Pembersihan berjalan
|
||||
|
||||
@@ -17,3 +17,9 @@ Format enam digit menyediakan 999.999 nomor per jenis, kode partner, dan tanggal
|
||||
## Pengujian lokal
|
||||
|
||||
Suite `application/tests/transaction-number.integration.test.js` memakai PostgreSQL lokal yang dapat dibuang dengan nama database `topup_test` dan skema `trx` yang belum ada. Isi `TOPUP_TEST_NUMBER_DB_URL` dengan URL database uji itu, lalu jalankan `npm test -- --runInBand application/tests/transaction-number.integration.test.js`.
|
||||
## Jam transaksi
|
||||
|
||||
Proses Node.js dan sesi PostgreSQL aplikasi menggunakan `Asia/Jakarta`. Jam
|
||||
transaksi dan tanggal pada nomor transaksi mengikuti WIB. Timestamp JSON log
|
||||
juga memakai WIB dengan offset `+07:00`. Nilai waktu transaksi lama tidak
|
||||
diubah oleh konfigurasi ini.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
require('dotenv').config();
|
||||
require('./infrastructure/transaction-time').configureTransactionClock();
|
||||
const cluster = require('node:cluster');
|
||||
const { createServer } = require('node:http');
|
||||
const { clusterWorkerCount } = require('./infrastructure/runtime-config');
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const knex = require("knex");
|
||||
const { observePool } = require("./pool-metrics");
|
||||
const { withTransactionTimeZone } = require("../transaction-time");
|
||||
require("dotenv").config();
|
||||
|
||||
const knexfile = require("../../knexfile");
|
||||
@@ -12,6 +13,6 @@ const configOptions = knexfile[env];
|
||||
// const configOptions = knexfile["testing"];
|
||||
|
||||
|
||||
const db = knex(configOptions);
|
||||
const db = knex(withTransactionTimeZone(configOptions));
|
||||
observePool('primary', db.client.pool);
|
||||
module.exports = db;
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
const TRANSACTION_TIME_ZONE = 'Asia/Jakarta';
|
||||
|
||||
// Samakan jam bisnis aplikasi dengan sesi PostgreSQL.
|
||||
function configureTransactionClock() {
|
||||
process.env.TZ = TRANSACTION_TIME_ZONE;
|
||||
}
|
||||
|
||||
function withTransactionTimeZone(config) {
|
||||
const afterCreate = config.pool?.afterCreate;
|
||||
|
||||
return {
|
||||
...config,
|
||||
pool: {
|
||||
...config.pool,
|
||||
afterCreate(connection, done) {
|
||||
function setTimeZone(error) {
|
||||
if (error) return done(error, connection);
|
||||
connection.query("SET TIME ZONE 'Asia/Jakarta'", (queryError) => done(queryError, connection));
|
||||
}
|
||||
|
||||
if (afterCreate) afterCreate(connection, setTimeZone);
|
||||
else setTimeZone();
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = { configureTransactionClock, withTransactionTimeZone };
|
||||
@@ -1,3 +1,4 @@
|
||||
require('../infrastructure/transaction-time').configureTransactionClock();
|
||||
const express = require('express');
|
||||
const bodyParser = require('body-parser');
|
||||
const cors = require('cors');
|
||||
|
||||
Reference in New Issue
Block a user