mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 11:06:28 +00:00
Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 225fc644d3 | |||
| 85fa8843d8 | |||
| 005746e29f | |||
| 34610e9515 | |||
| 297c3d7323 | |||
| ebd97d4408 | |||
| d5d8ea1ce6 | |||
| d8267cc263 | |||
| 58ffbb6920 | |||
| 3d392d1e6f |
@@ -71,12 +71,22 @@ setelah dibuat dan event hasil menyertakannya, termasuk saat HSM timeout.
|
||||
Permintaan load balance ikut terhubung jika klien mengirim kode sesi yang sama.
|
||||
Setiap panggilan HTTP tetap punya `request_id` sendiri.
|
||||
|
||||
Untuk mengikuti reservasi hingga hasil Top Up, cari event
|
||||
`reservation_topup_link` berdasarkan `reservation_number`. Top Up Step 6
|
||||
mencatat satu event per reservasi dari detail yang berhasil disimpan bersama
|
||||
load balance. Gunakan `unique_code` dari event itu untuk melihat langkah 1–8.
|
||||
Sesi yang berhenti sebelum detail tersimpan belum memiliki hubungan ini.
|
||||
|
||||
```logql
|
||||
{app="topuponline"} | json | request_id="e6aa798c-c8c2-440e-a39b-66bcfbde2f58"
|
||||
{app="topuponline"} | json | route="/api/login" | message="Password is wrong."
|
||||
{app="topuponline"} | json | unique_code="1234567890121"
|
||||
{app="topuponline"} | json | event="reservation_topup_link" | reservation_number="RBLTEST261124000023"
|
||||
{app="topuponline"} | json | event=~"http_request|http_response|http_request_aborted|reservation_topup_link" | (reservation_number="RBLTEST261124000023" or unique_code="1234567890121")
|
||||
```
|
||||
|
||||
Lihat [panduan investigasi Grafana](docs/grafana/topup-observability.md)
|
||||
untuk menelusuri detail `application_log` saat ada error.
|
||||
|
||||
## Kapasitas koneksi PostgreSQL
|
||||
|
||||
Pengaturan pool utama dan pool tambahan ada di `knexfile.js`.
|
||||
|
||||
@@ -14,6 +14,14 @@ function getHsmUniqueCode(value) {
|
||||
return /^\d{1,14}$/.test(code) ? code : undefined;
|
||||
}
|
||||
|
||||
function getReservationNumber(value) {
|
||||
return typeof value === 'string' && /^RBL[a-z0-9-]{1,61}$/i.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function getLoadBalanceNumber(value) {
|
||||
return typeof value === 'string' && /^LBL[0-9A-Za-z-]{1,35}$/.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function logStatusCode(value) {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return 'UNKNOWN';
|
||||
const code = String(value);
|
||||
@@ -27,4 +35,4 @@ function logErrorCode(error) {
|
||||
return typeof name === 'string' && /^[A-Za-z]{1,30}Error$/.test(name) ? name : 'Error';
|
||||
}
|
||||
|
||||
module.exports = { getHsmUniqueCode, logCorrelation, logStatusCode, logErrorCode };
|
||||
module.exports = { getHsmUniqueCode, getReservationNumber, getLoadBalanceNumber, logCorrelation, logStatusCode, logErrorCode };
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
const { getReservationNumber } = require('./log-fields');
|
||||
|
||||
const validationFields = ['amount', 'mid', 'tid', 'card_number'];
|
||||
const customerFields = ['customer_name', 'phone_number'];
|
||||
const cancellationFields = ['reservation_number', 'mid', 'tid'];
|
||||
@@ -13,10 +15,6 @@ const fieldsByRoute = new Map([
|
||||
['/api/reservation/cancel/v2', ['cancel_reservation_data']],
|
||||
]);
|
||||
|
||||
function getReservationNumber(value) {
|
||||
return typeof value === 'string' && /^RBL[a-z0-9-]{1,61}$/i.test(value) ? value : undefined;
|
||||
}
|
||||
|
||||
function getAmount(value) {
|
||||
if (typeof value !== 'number' && typeof value !== 'string') return undefined;
|
||||
return /^-?\d{1,12}(?:\.\d{1,2})?$/.test(value) ? value : undefined;
|
||||
@@ -52,4 +50,4 @@ function summarizeReservationRequest(route, body) {
|
||||
return summary;
|
||||
}
|
||||
|
||||
module.exports = { fieldsByRoute, getReservationNumber, summarizeReservationRequest };
|
||||
module.exports = { fieldsByRoute, summarizeReservationRequest };
|
||||
|
||||
@@ -27,6 +27,8 @@ const searchableMessages = new Set([
|
||||
'partner is not match',
|
||||
'card number is not registered',
|
||||
"reservation doesn't exist",
|
||||
'bad request. reservation data is invalid.',
|
||||
'bad request. reservation data is empty.',
|
||||
'reservation exists',
|
||||
'amount must be greater than 0',
|
||||
'your card number has reached the maximum balance',
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
const { correlation } = require('./request-context.middleware');
|
||||
const { getHsmUniqueCode } = require('../helpers/log-fields');
|
||||
const { getHsmUniqueCode, getLoadBalanceNumber, getReservationNumber } = require('../helpers/log-fields');
|
||||
const { getSearchableResponseMessage, getResponseSummary } = require('../helpers/response-log-message');
|
||||
const {
|
||||
fieldsByRoute: reservationRequestRoutes,
|
||||
getReservationNumber,
|
||||
summarizeReservationRequest,
|
||||
} = require('../helpers/reservation-request-log');
|
||||
const responseAudit = require("../helpers/response-audit");
|
||||
@@ -68,12 +67,6 @@ const successfulCodes = new Set(['00', '01', '02', '03', '04']);
|
||||
const isTopupRoute = (route) => /^\/api\/topup[1-8]$/.test(route);
|
||||
const usesHsmRequestCode = (route) => /^\/api\/topup[2-8]$/.test(route) || route === '/api/loadbalance/request';
|
||||
|
||||
function getLoadBalanceNumber(responseNumber, requestNumber) {
|
||||
return [responseNumber, requestNumber].find((value) =>
|
||||
typeof value === 'string' && /^LBL[0-9A-Za-z-]{1,35}$/.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
const issuerCache = new Map();
|
||||
const issuerLookups = new Set();
|
||||
|
||||
@@ -221,7 +214,8 @@ function response(req, res, next) {
|
||||
statusCode,
|
||||
message: getSearchableResponseMessage(body?.message),
|
||||
trxId: getTransactionId(data?.trxID, req.body?.trxID),
|
||||
loadBalanceNumber: getLoadBalanceNumber(data?.load_balance_number, req.body?.load_balance_number),
|
||||
loadBalanceNumber: getLoadBalanceNumber(data?.load_balance_number)
|
||||
?? getLoadBalanceNumber(req.body?.load_balance_number),
|
||||
reservationNumber: getReservationNumber(data?.reservation_number),
|
||||
};
|
||||
return sendJson.call(this, body);
|
||||
@@ -255,6 +249,13 @@ function response(req, res, next) {
|
||||
}
|
||||
|
||||
event.message = summary.message ?? getResponseSummary(event);
|
||||
const failure = matchedRoute === '/api/reservation/v2' && statusCode === '500'
|
||||
? res.locals.reservationFailure
|
||||
: undefined;
|
||||
if (failure) {
|
||||
event.error_code = failure.code;
|
||||
event.error_stage = failure.stage;
|
||||
}
|
||||
if (!auditedRoutes.has(matchedRoute)) {
|
||||
writeStdoutLine(formatLog(event));
|
||||
return;
|
||||
|
||||
@@ -1,8 +1,31 @@
|
||||
const { logCorrelation, logErrorCode, logStatusCode } = require('../../helpers/log-fields');
|
||||
const {
|
||||
getHsmUniqueCode, getLoadBalanceNumber, getReservationNumber, logCorrelation, logErrorCode, logStatusCode,
|
||||
} = require('../../helpers/log-fields');
|
||||
const { formatLog, writeStdoutLine } = require('../../helpers/stdout-log');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./loadbalance.model');
|
||||
const moment = require('moment');
|
||||
|
||||
// Detail yang disimpan menjadi sumber hubungan reservasi, bukan daftar dari klien.
|
||||
function logReservationTopupLinks(requestId, uniqueCode, loadBalanceNumber, details) {
|
||||
const sessionCode = getHsmUniqueCode(uniqueCode);
|
||||
const balanceNumber = getLoadBalanceNumber(loadBalanceNumber);
|
||||
if (!sessionCode || !balanceNumber) return;
|
||||
|
||||
const reservations = new Set(details.map(detail => getReservationNumber(detail.c_reservation_no)));
|
||||
for (const reservationNumber of reservations) {
|
||||
if (!reservationNumber) continue;
|
||||
writeStdoutLine(formatLog({
|
||||
event: 'reservation_topup_link',
|
||||
level: 'info',
|
||||
request_id: requestId,
|
||||
reservation_number: reservationNumber,
|
||||
unique_code: sessionCode,
|
||||
load_balance_number: balanceNumber,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
// Alur tulis saldo dipakai oleh HSM dan proses permintaan saldo.
|
||||
const updateAllTransaction = async (
|
||||
reservationNumber,
|
||||
@@ -555,6 +578,7 @@ const loadingBalanceInsert = async (req, param) => {
|
||||
// )} [FLAG] : ${JSON.stringify(flag)}`
|
||||
// );
|
||||
if (insertLoadingBalance > 0) {
|
||||
logReservationTopupLinks(req.id, unique_code, loadBalanceNumber, detail);
|
||||
result = {
|
||||
code: '00',
|
||||
message: write_status
|
||||
|
||||
@@ -295,8 +295,20 @@ const validateReplacement = async (req, res) => {
|
||||
|
||||
// if (is_warranty == true) {
|
||||
let result = {};
|
||||
const ctsUrl = process.env.CTS_URL?.trim();
|
||||
if (!ctsUrl) {
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message: 'CTS connection has not been configured.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance'
|
||||
const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`;
|
||||
const baseUrl = `${ctsUrl}/v2/api/info/last-balance`;
|
||||
const payload = {
|
||||
card_number: card_number,
|
||||
};
|
||||
@@ -306,7 +318,22 @@ const validateReplacement = async (req, res) => {
|
||||
},
|
||||
};
|
||||
const url = baseUrl;
|
||||
const response = await postWithDeadline(url, payload, config);
|
||||
let response;
|
||||
try {
|
||||
response = await postWithDeadline(url, payload, config);
|
||||
} catch (error) {
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ CTS REQUEST FAILED ] error_code=${logErrorCode(error)}`
|
||||
);
|
||||
return res.status(200).json({
|
||||
code: '415',
|
||||
message: 'Failed to retrieve last balance from CTS.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
if (response.data.code == undefined || response.data.code != 200) {
|
||||
if (response.data.code == 404) {
|
||||
result = {
|
||||
@@ -324,7 +351,7 @@ const validateReplacement = async (req, res) => {
|
||||
}
|
||||
result = {
|
||||
code: '415',
|
||||
message: 'Last Balance not updated.',
|
||||
message: 'Failed to retrieve last balance from CTS.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
@@ -391,7 +418,6 @@ const validateReplacement = async (req, res) => {
|
||||
unique_code: uniqueCode,
|
||||
card_category: {
|
||||
id: dataCardReplacement.card_category_id,
|
||||
code: dataCardReplacement.card_category_code,
|
||||
name: dataCardReplacement.card_category_name
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1474,6 +1474,7 @@ const reservation = async (req, res) => {
|
||||
};
|
||||
|
||||
const reservationV2 = async (req, res) => {
|
||||
let stage = 'validate_request';
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
@@ -1521,13 +1522,16 @@ const reservationV2 = async (req, res) => {
|
||||
// `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking reservation data...`
|
||||
// );
|
||||
|
||||
stage = 'decode_reservation_data';
|
||||
let reservationData;
|
||||
|
||||
try {
|
||||
reservationData = helper.decryptText(reservation_data);
|
||||
} catch (error) { }
|
||||
const plaintext = helper.decryptText(reservation_data);
|
||||
if (typeof plaintext === 'string' && plaintext) reservationData = JSON.parse(plaintext);
|
||||
} catch {
|
||||
// Muatan yang gagal didekripsi atau diurai ditolak sebagai input yang tidak valid.
|
||||
}
|
||||
|
||||
if (!reservationData) {
|
||||
if (!reservationData || typeof reservationData !== 'object' || Array.isArray(reservationData)) {
|
||||
result = {
|
||||
code: '435',
|
||||
message: 'bad request. reservation data is invalid.',
|
||||
@@ -1542,9 +1546,6 @@ const reservationV2 = async (req, res) => {
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// parsing data to json format
|
||||
reservationData = JSON.parse(reservationData);
|
||||
|
||||
if (
|
||||
!reservationData.mid ||
|
||||
!reservationData.tid ||
|
||||
@@ -1584,6 +1585,7 @@ const reservationV2 = async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
stage = 'check_card_blacklist';
|
||||
let cardBlacklist = await model.getCardBlacklist(
|
||||
reservationData.card_number
|
||||
);
|
||||
@@ -1624,6 +1626,7 @@ const reservationV2 = async (req, res) => {
|
||||
let transactionDate = reservationData.transaction_date;
|
||||
let securityCode = reservationData.security_code;
|
||||
|
||||
stage = 'verify_reservation_data';
|
||||
if (securityCode) {
|
||||
// log debug
|
||||
// process enkripsi data reservasi dengan HMAC sebagai pembanding bahwa data yang di decrypt valid
|
||||
@@ -1724,6 +1727,7 @@ const reservationV2 = async (req, res) => {
|
||||
// );
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
stage = 'lookup_partner';
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
if (!getPartner) {
|
||||
result = {
|
||||
@@ -1757,6 +1761,7 @@ const reservationV2 = async (req, res) => {
|
||||
// );
|
||||
|
||||
// get parameter to check with card product cms or not
|
||||
stage = 'check_reservation_limits';
|
||||
let getCheckByCardProductStatusValue =
|
||||
await model.getCheckByCardProductStatusValue();
|
||||
let checkByCardProductStatusValue =
|
||||
@@ -2010,6 +2015,7 @@ const reservationV2 = async (req, res) => {
|
||||
let channelFee = 0;
|
||||
|
||||
// get issuer fee dan channel fee dari table public.t_c_partner_fee
|
||||
stage = 'lookup_issuer_fee';
|
||||
let getIssuer = await model.getIssuer(getPartner.i_partner, now);
|
||||
|
||||
if (getIssuer) {
|
||||
@@ -2046,6 +2052,7 @@ const reservationV2 = async (req, res) => {
|
||||
// `${uniqueCode} [ PROCESSING RESERVATION-V2 ] getting reservation expiration date on parameter...`
|
||||
// );
|
||||
|
||||
stage = 'lookup_reservation_expiration';
|
||||
const { time, measure } = await model.getReservationExpiration();
|
||||
let expired = moment(now).add(time, measure).format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
@@ -2062,6 +2069,7 @@ const reservationV2 = async (req, res) => {
|
||||
phoneNumber = mid + '_' + tid;
|
||||
}
|
||||
|
||||
stage = 'allocate_reservation_number';
|
||||
const { number: reservationNumber, sequence: reservationNoSequence } =
|
||||
await model.allocateReservationNumber(getPartner.partner_code, moment(now).format('YYMMDD'));
|
||||
|
||||
@@ -2123,6 +2131,7 @@ const reservationV2 = async (req, res) => {
|
||||
// (belum) ada issue disini, jadi ada case reservation number nya sama, terus error query harusnya ada handle response message nya, yg sekarang malah masuk ke blok reservation saved successfully.
|
||||
|
||||
// insert transaction
|
||||
stage = 'insert_reservation';
|
||||
let insert = await model.insertReservation(data);
|
||||
|
||||
// jika proses insert data semua yang berkaitan dengan reservasi saldo mengalami kegagalan, maka lakukan rollback
|
||||
@@ -2134,6 +2143,7 @@ const reservationV2 = async (req, res) => {
|
||||
// );
|
||||
|
||||
// log card history
|
||||
stage = 'write_reservation_history';
|
||||
await model.createReserveBalanceLog({
|
||||
i_log_name: 90,
|
||||
d_log: now,
|
||||
@@ -2192,9 +2202,11 @@ const reservationV2 = async (req, res) => {
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
} catch (error) {
|
||||
// create log
|
||||
// Simpan tahap dan kode aman tersedia di audit tanpa menyalin exception mentah.
|
||||
const errorCode = logErrorCode(error);
|
||||
res.locals.reservationFailure = { stage, code: errorCode };
|
||||
winston.logger.error(
|
||||
`[ RESPONSE RESERVATION-V2 ] code=500 error_code=${logErrorCode(error)}`
|
||||
`[ RESPONSE RESERVATION-V2 ] code=500 error_code=${errorCode} error_stage=${stage}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
const model = require('../modules/loadbalance/loadbalance.model');
|
||||
const { logger } = require('../helpers/winston.logger');
|
||||
const { writeStdoutLine } = require('../helpers/stdout-log');
|
||||
const { loadingBalanceInsert, loadingBalanceUpdate } = require('../modules/loadbalance/loadbalance.controller');
|
||||
|
||||
jest.mock('../helpers/helper', () => ({}));
|
||||
jest.mock('../helpers/winston.logger', () => ({ logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() } }));
|
||||
jest.mock('../helpers/stdout-log', () => ({
|
||||
...jest.requireActual('../helpers/stdout-log'),
|
||||
writeStdoutLine: jest.fn(),
|
||||
}));
|
||||
jest.mock('../modules/loadbalance/loadbalance.model', () => ({
|
||||
getPartner: jest.fn(),
|
||||
findReservationsWithLoadedBalance: jest.fn(),
|
||||
@@ -40,6 +45,7 @@ test('menolak terminal milik partner lain sebelum membaca atau menulis reservasi
|
||||
});
|
||||
expect(model.findReservationsWithLoadedBalance).not.toHaveBeenCalled();
|
||||
expect(model.insertLoadingBalance).not.toHaveBeenCalled();
|
||||
expect(writeStdoutLine).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('log layanan tidak menyimpan kode klien mentah atau data kartu', async () => {
|
||||
@@ -84,7 +90,7 @@ function setupPending() {
|
||||
model.allocateLoadBalanceNumber.mockResolvedValue({ number: 'LBLTEST261124000023', sequence: 23 });
|
||||
}
|
||||
|
||||
test('fetches pending details once and preserves the pending order and amounts', async () => {
|
||||
test('fetches pending details once and logs links from the committed details', async () => {
|
||||
setupPending();
|
||||
model.findReservationDetails.mockResolvedValue([
|
||||
{ c_reservation_no: 'RBL1', i_reservation_balance: 1, i_reservation_amount: 10 },
|
||||
@@ -92,7 +98,12 @@ test('fetches pending details once and preserves the pending order and amounts',
|
||||
]);
|
||||
model.insertLoadingBalance.mockResolvedValue(1);
|
||||
|
||||
await expect(loadingBalanceInsert(req, input)).resolves.toMatchObject({
|
||||
await expect(loadingBalanceInsert({ ...req, id: 'fixture-request-id' }, {
|
||||
...input,
|
||||
unique_code: '1234567890121',
|
||||
reservation_number: ['RBL1'],
|
||||
card_number: 'fixture-card',
|
||||
})).resolves.toMatchObject({
|
||||
code: '00',
|
||||
data: { load_balance_number: 'LBLTEST261124000023' },
|
||||
});
|
||||
@@ -106,6 +117,33 @@ test('fetches pending details once and preserves the pending order and amounts',
|
||||
{ c_reservation_no: 'RBL2', i_amount: 20 },
|
||||
{ c_reservation_no: 'RBL1', i_amount: 10 },
|
||||
]);
|
||||
const events = writeStdoutLine.mock.calls.map(([line]) => JSON.parse(line));
|
||||
expect(events).toEqual(['RBL2', 'RBL1'].map(reservationNumber => ({
|
||||
timestamp: expect.any(String),
|
||||
app: 'topuponline',
|
||||
pid: process.pid,
|
||||
level: 'info',
|
||||
event: 'reservation_topup_link',
|
||||
request_id: 'fixture-request-id',
|
||||
reservation_number: reservationNumber,
|
||||
unique_code: '1234567890121',
|
||||
load_balance_number: 'LBLTEST261124000023',
|
||||
})));
|
||||
});
|
||||
|
||||
test('does not log a link when the load balance write fails or the session code is invalid', async () => {
|
||||
setupPending();
|
||||
model.findReservationDetails.mockResolvedValue([
|
||||
{ c_reservation_no: 'RBL1', i_reservation_balance: 1, i_reservation_amount: 10 },
|
||||
{ c_reservation_no: 'RBL2', i_reservation_balance: 2, i_reservation_amount: 20 },
|
||||
]);
|
||||
model.insertLoadingBalance.mockResolvedValueOnce(0).mockResolvedValueOnce(1);
|
||||
|
||||
await expect(loadingBalanceInsert(req, { ...input, unique_code: '1234567890121' }))
|
||||
.resolves.toMatchObject({ code: '433' });
|
||||
await expect(loadingBalanceInsert(req, { ...input, unique_code: 'invalid-session' }))
|
||||
.resolves.toMatchObject({ code: '00' });
|
||||
expect(writeStdoutLine).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('preserves code 414 if a pending reservation is absent at the new read', async () => {
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const helper = require('../helpers/helper');
|
||||
const model = require('../modules/reservebalance/reservebalance.model');
|
||||
const audit = require('../helpers/response-audit');
|
||||
const validate = require('../modules/reservebalance/reservebalance.validation');
|
||||
const { reservationV2 } = require('../modules/reservebalance/reservation-create.handlers');
|
||||
const { correlation, response } = require('../middlewares/response-telemetry.middleware');
|
||||
|
||||
jest.mock('../../infrastructure/database/knex', () => jest.fn());
|
||||
jest.mock('../helpers/response-audit', () => ({ record: jest.fn() }));
|
||||
jest.mock('../helpers/helper', () => ({
|
||||
getUniqueCode: jest.fn(() => '123'),
|
||||
decryptText: jest.fn(),
|
||||
}));
|
||||
jest.mock('../helpers/winston.logger', () => ({
|
||||
logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() },
|
||||
}));
|
||||
jest.mock('../modules/reservebalance/reservebalance.model', () => ({
|
||||
getCardBlacklist: jest.fn(),
|
||||
getPartner: jest.fn(),
|
||||
getCheckByCardProductStatusValue: jest.fn(),
|
||||
getLastBalanceFromCardHistory: jest.fn(),
|
||||
getBIRegulationStatus: jest.fn(),
|
||||
getMaxReservation: jest.fn(),
|
||||
getReservationPendingV2: jest.fn(),
|
||||
getIssuer: jest.fn(),
|
||||
getReservationExpiration: jest.fn(),
|
||||
allocateReservationNumber: jest.fn(),
|
||||
insertReservation: jest.fn(),
|
||||
createReserveBalanceLog: jest.fn(),
|
||||
}));
|
||||
|
||||
const app = express();
|
||||
app.use(correlation, response, express.json());
|
||||
app.post('/api/reservation/v2', (req, res, next) => {
|
||||
req.partner_id_token = 'fixture-partner';
|
||||
next();
|
||||
}, validate('reservationV2'), reservationV2);
|
||||
|
||||
function createReservation() {
|
||||
return request(app).post('/api/reservation/v2')
|
||||
.send({ reservation_data: 'fixture-ciphertext', ref_no: 'fixture-ref' });
|
||||
}
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
test.each(['invalid JSON', 'null', '[]'])('payload reservasi %s ditolak tanpa akses database', async (plaintext) => {
|
||||
helper.decryptText.mockReturnValue(plaintext);
|
||||
const result = await createReservation().expect(200);
|
||||
expect(result.body).toEqual({ code: '435', message: 'bad request. reservation data is invalid.', data: {} });
|
||||
expect(model.getCardBlacklist).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('kegagalan alokasi mempertahankan respons dan mencatat tahap serta kode aman di audit', async () => {
|
||||
helper.decryptText.mockReturnValue(JSON.stringify({
|
||||
mid: 'A001', tid: 'B001', card_number: '0000000000000001', amount: 10000, transaction_date: '2026-11-25',
|
||||
}));
|
||||
model.getPartner.mockResolvedValue({ i_partner: 'fixture-partner', partner_code: 'P01' });
|
||||
model.getBIRegulationStatus.mockResolvedValue({ c_value: 'N' });
|
||||
model.getMaxReservation.mockResolvedValue({ c_value: '100000' });
|
||||
model.getReservationPendingV2.mockResolvedValue([]);
|
||||
model.getReservationExpiration.mockResolvedValue({ time: 1, measure: 'hours' });
|
||||
model.allocateReservationNumber.mockRejectedValue(Object.assign(new Error('private database detail'), { code: '42P01' }));
|
||||
|
||||
const result = await createReservation().expect(200);
|
||||
expect(result.body.code).toBe('500');
|
||||
expect(model.insertReservation).not.toHaveBeenCalled();
|
||||
const [event] = audit.record.mock.lastCall;
|
||||
expect(event).toMatchObject({
|
||||
request_id: result.headers['x-request-id'],
|
||||
status_code: '500',
|
||||
error_code: '42P01',
|
||||
error_stage: 'allocate_reservation_number',
|
||||
});
|
||||
expect(JSON.stringify(event)).not.toContain('private database detail');
|
||||
});
|
||||
@@ -16,8 +16,16 @@ headers {
|
||||
|
||||
body:json {
|
||||
{
|
||||
"email": "partner@example.test",
|
||||
"password": "SamplePassword-OnlyForLocal"
|
||||
"email": "{{process.env.BRUNO_PARTNER_EMAIL}}",
|
||||
"password": "{{process.env.BRUNO_PARTNER_PASSWORD}}"
|
||||
}
|
||||
}
|
||||
|
||||
script:post-response {
|
||||
const body = res.getBody();
|
||||
if (body?.code === '00' && body.data?.access_token && body.data?.refresh_token) {
|
||||
bru.setVar('accessToken', body.data.access_token);
|
||||
bru.setVar('refreshToken', body.data.refresh_token);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -20,25 +20,25 @@ auth:bearer {
|
||||
|
||||
body:json {
|
||||
{
|
||||
"card_number": "0000000000000001",
|
||||
"station_code": "TEST01"
|
||||
"card_number": "1003012302000000",
|
||||
"station_code": "JUA"
|
||||
}
|
||||
}
|
||||
|
||||
docs {
|
||||
### Deskripsi
|
||||
Memeriksa kelayakan kartu untuk penggantian dan menyiapkan data konfirmasi.
|
||||
|
||||
|
||||
### Request
|
||||
- Endpoint POST /api/pos/cardreplacement/validate
|
||||
- Kirim Authorization: Bearer dengan accessToken dari login.
|
||||
- Contoh JSON tersedia di tab Body.
|
||||
- Route tidak membaca query atau path parameter tambahan.
|
||||
|
||||
|
||||
### Respons
|
||||
|
||||
|
||||
Handler umumnya mengembalikan HTTP 200. Untuk hasil aplikasi, periksa field code, message, dan data. Gunakan header X-Request-Id untuk pencarian log.
|
||||
|
||||
|
||||
| Code | Message |
|
||||
| --- | --- |
|
||||
| 00 | Successfully. |
|
||||
@@ -60,10 +60,10 @@ docs {
|
||||
| 494 | No data found in CTS for the given card number |
|
||||
| 500 | *Pesan kegagalan dapat berasal dari exception atau dependensi.* |
|
||||
| 500 | 500 internal server error - backend server. |
|
||||
|
||||
|
||||
**Pesan validasi yang dapat dikembalikan**
|
||||
- Card number is required
|
||||
- Station Code is required
|
||||
|
||||
|
||||
Pesan yang dicetak miring bersifat dinamis. Nilai aktual dapat mengikuti input atau hasil dari service lain.
|
||||
}
|
||||
|
||||
@@ -18,7 +18,11 @@ Koleksi Bruno ini mengikuti route yang terpasang melalui `server/routes.js` dan
|
||||
|
||||
1. Buka Bruno, pilih **Open Collection**, lalu pilih folder `docs/api/bruno`.
|
||||
2. Pilih environment **Local**. Sesuaikan `baseUrl` dengan alamat dan port lokal service. Path `/api` sudah termasuk.
|
||||
3. Isi secret `accessToken` dengan `data.access_token` dan `refreshToken` dengan `data.refresh_token` dari respons login di lingkungan uji.
|
||||
3. Untuk **Log In as Partner User**, isi `BRUNO_PARTNER_EMAIL` dan
|
||||
`BRUNO_PARTNER_PASSWORD` pada file lokal `docs/api/bruno/.env`. Bruno
|
||||
membaca file tersebut dari folder koleksi. Setelah login berhasil, skrip
|
||||
menyimpan token sebagai variabel runtime. Untuk alur login lain, isi secret
|
||||
`accessToken` dan `refreshToken` dari respons login di lingkungan uji.
|
||||
4. Periksa tab **Body**, **Headers**, **Params**, dan **Auth** sesuai konfigurasi tiap request. Ganti nilai sintetis dengan data uji yang terdaftar bila diperlukan.
|
||||
5. Isi placeholder yang berasal dari respons sebelumnya atau perangkat uji sesuai petunjuk pada tab **Docs**. Jalankan request pada lingkungan lokal atau nonproduksi.
|
||||
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
vars {
|
||||
baseUrl: https://dev-topup.kci.id/api
|
||||
reservationData: ISI_DARI_LINGKUNGAN_UJI
|
||||
cancelReservationData: ISI_DARI_LINGKUNGAN_UJI
|
||||
replacementUniqueCode: SAMPLE-HSM-01
|
||||
replacementSecurityCode: ISI_DARI_LINGKUNGAN_UJI
|
||||
redeemSecurityCode: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep1Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep2Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupUniqueCode: SAMPLE-HSM-01
|
||||
topupTrxId: 0001
|
||||
topupStep3Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep4Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep5Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep6Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupStep7Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
topupLoadBalanceNumber: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep1Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep2Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearUniqueCode: SAMPLE-HSM-01
|
||||
clearTrxId: 0001
|
||||
clearStep3Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep4Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep5Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep6Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
clearStep7Data: ISI_DARI_LINGKUNGAN_UJI
|
||||
}
|
||||
vars:secret [
|
||||
accessToken,
|
||||
refreshToken
|
||||
]
|
||||
@@ -14,8 +14,9 @@ request ID, atau durasi minimum.
|
||||
`request_id` dari header. ID ini unik untuk satu request. ID HSM dapat dipakai
|
||||
oleh beberapa request, sehingga hasil `trx_id` bisa lebih dari satu baris.
|
||||
- Loki menyimpan `trx_id`, `request_id`, dan `response_time_ms` di isi JSON log.
|
||||
ID HSM dicatat dalam huruf kecil. Log respons sukses dipublikasikan di level
|
||||
`info`, sedangkan respons gagal dipublikasikan di level `error`.
|
||||
ID HSM dicatat dalam huruf kecil. Respons sukses pada route transaksi
|
||||
dicatat di level `info`. Penolakan aplikasi dicatat di `warn` dan kegagalan
|
||||
backend di `error`.
|
||||
- `http_status` memuat status HTTP, sedangkan `status_code` memuat kode aplikasi.
|
||||
|
||||
```logql
|
||||
@@ -30,14 +31,40 @@ request ID, atau durasi minimum.
|
||||
{app="topuponline"} |= "http_response" | json | event="http_response" | response_time_ms >= 1000 | __error__=""
|
||||
```
|
||||
|
||||
## Menelusuri reservasi sampai Top Up Step 8
|
||||
|
||||
1. Ambil `unique_code` dari event penghubung Step 6.
|
||||
|
||||
```logql
|
||||
{app="topuponline"} | json | event="reservation_topup_link" | reservation_number="<RBL>"
|
||||
```
|
||||
|
||||
2. Tampilkan timeline HTTP dan event penghubung dengan RBL serta kode sesi.
|
||||
|
||||
```logql
|
||||
{app="topuponline"}
|
||||
| json
|
||||
| event=~"http_request|http_response|http_request_aborted|reservation_topup_link"
|
||||
| (reservation_number="<RBL>" or unique_code="<KODE_SESI>")
|
||||
```
|
||||
|
||||
Respons Step 1 bisa ditemukan lewat kode sesi. Event request awal Step 1
|
||||
ditulis sebelum kode sesi dibuat. Cari langsung berdasarkan `request_id`
|
||||
untuk melihat baris awal tersebut. Tambahkan filter `event="application_log"`
|
||||
untuk melihat detail handler saat ada error.
|
||||
|
||||
```logql
|
||||
{app="topuponline"} | json | event="application_log" | request_id="<X-Request-Id>"
|
||||
```
|
||||
|
||||
## Mengambil stdout melalui Promtail
|
||||
|
||||
Aplikasi menulis satu objek JSON per baris ke stdout. URL tujuan Loki berada
|
||||
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. Field `timestamp`
|
||||
Respons terpantau menggunakan `event=http_response`. Awal request pada route
|
||||
tertentu menggunakan `event=http_request`. Log internal Winston menggunakan
|
||||
`event=application_log`. Field `timestamp`
|
||||
menggunakan WIB dengan offset `+07:00`, misalnya
|
||||
`2026-11-25T00:30:00.000+07:00`.
|
||||
|
||||
|
||||
@@ -14,6 +14,24 @@ Pada alokasi pertama untuk suatu awalan, aplikasi membaca nomor terakhir dari da
|
||||
|
||||
Format enam digit menyediakan 999.999 nomor per jenis, kode partner, dan tanggal. Jika kapasitas satu awalan habis, alokasi gagal dengan pesan diagnostik dan tetap mempertahankan format nomor.
|
||||
|
||||
## Diagnosis kode PostgreSQL 42P01
|
||||
|
||||
Jalankan pemeriksaan katalog berikut dengan koneksi PostgreSQL yang dipakai
|
||||
instance API. Nilai kosong berarti relasi tersebut tidak tersedia.
|
||||
|
||||
```sql
|
||||
SELECT
|
||||
to_regclass('trx.t_transaction_number_counter') AS counter_table,
|
||||
to_regclass('trx.t_d_reservation_no_validate') AS reservation_claims,
|
||||
to_regclass('trx.t_d_reservation_balance') AS reservations;
|
||||
```
|
||||
|
||||
Jika hanya `counter_table` yang kosong, jalankan migrasi
|
||||
`20261124000100_create_transaction_number_counter.js` melalui
|
||||
`knex migrate:up` pada environment Knex yang sama dengan proses API. Ulangi
|
||||
pemeriksaan katalog setelah migrasi. Jika tabel lain yang kosong, cocokkan
|
||||
target database dan skema aplikasi sebelum menjalankan migrasi tambahan.
|
||||
|
||||
## 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`.
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "onlinetopup-v1",
|
||||
"version": "1.6.6",
|
||||
"version": "1.6.7",
|
||||
"description": "optimize query and coding enhancement",
|
||||
"main": "index.js",
|
||||
"scripts": {
|
||||
@@ -24,7 +24,7 @@
|
||||
"homepage": "https://github.com/mohamadihsan/topuponline#readme",
|
||||
"dependencies": {
|
||||
"axios": "^1.7.7",
|
||||
"bcrypt": "^5.1.1",
|
||||
"bcrypt": "^4.0.1",
|
||||
"cors": "^2.8.5",
|
||||
"crypto-js": "^4.1.1",
|
||||
"dotenv": "^8.2.0",
|
||||
|
||||
Reference in New Issue
Block a user