mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:46:28 +00:00
Handle invalid reservation V2 data and improve failure diagnostics
This commit is contained in:
@@ -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',
|
||||
|
||||
@@ -255,6 +255,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;
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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`.
|
||||
|
||||
Reference in New Issue
Block a user