Compare commits

..

32 Commits

Author SHA1 Message Date
ihsan c5b75058d3 backup env 2023-05-22 13:48:19 +07:00
ihsan 18cab4b93b add version on index 2023-05-22 13:38:34 +07:00
ihsan 40990b3498 update customer name 2023-05-22 13:31:00 +07:00
ihsan fa43d34c90 update bugs 2023-05-19 16:12:50 +07:00
ihsan 5a0d579405 update bugs 2023-05-19 16:10:15 +07:00
ihsan 8e9f9dca82 update bugs 2023-05-19 16:04:26 +07:00
ihsan c8755f9e2d debug 3 2023-05-19 15:58:12 +07:00
ihsan f2e6b31b82 update 2023-05-19 15:48:23 +07:00
ihsan 751191e10e debug 2 2023-05-19 15:20:00 +07:00
ihsan 33039fab21 debug 1 2023-05-19 15:10:10 +07:00
ihsan 2c31a4e425 update 2023-05-17 10:26:23 +07:00
ihsan b5b72ecf6c update 2023-05-17 10:15:46 +07:00
ihsan b7e5d0c426 Merge branch 'feature_log_monitoring' into develop_v1.3.7 2023-05-16 14:01:17 +07:00
tedbearr 82bd1c5276 update 2023-05-16 13:57:08 +07:00
ihsan c39675b1ac Merge branch 'feature_log_monitoring' into develop_v1.3.7 2023-05-15 13:11:40 +07:00
ihsan 146e64fc63 update response code 432 to 424 2023-05-12 17:23:02 +07:00
tedbearr 058cd6edfc update 2023-05-12 16:10:32 +07:00
ihsan 3fb2124534 Merge branch 'feature_log_monitoring' into develop_v1.3.7 2023-05-10 13:36:33 +07:00
ihsan c4f276289a add validation date range list inquiry max 1 month 2023-05-10 13:23:58 +07:00
tedbearr f8aacae0ea update 2023-05-10 12:31:48 +07:00
ihsan 0e237bd66d add customer name and phone number 2023-05-09 13:56:24 +07:00
ihsan 8e8704a1a2 handling reset flag counting if it alrady got 255 2023-05-05 14:01:53 +07:00
ihsan 25c3d03761 update response load balance request 2023-05-04 17:04:02 +07:00
ihsan 3be8c88db4 update bugs cancel reservation v2 2023-05-04 12:42:46 +07:00
ihsan 983902d08e update partial topup logic 2023-05-04 12:38:25 +07:00
ihsan 7a09320404 add partial topup logic 2023-05-04 12:26:48 +07:00
ihsan ff245148f6 add load balance number resp in autocomplete case 2023-05-04 11:52:48 +07:00
tedbearr 5a4870408c update cara log monitoring 2023-04-17 12:31:50 +07:00
tedbearr e3ef16753e update cara log monitoring 2023-04-17 00:19:40 +07:00
ihsan 90aaf3f6f6 update cancel reserve v2 with ref no, disable v2.1 2023-04-14 16:05:41 +07:00
tedbearr 0437eaab25 update middleware monitoring 2023-04-12 15:42:31 +07:00
tedbearr 4a98a1c5cd update middleware monitoring 2023-04-12 14:48:13 +07:00
16 changed files with 914 additions and 247 deletions
+209 -8
View File
@@ -3,6 +3,13 @@ require("winston-daily-rotate-file");
const expressWinston = require("express-winston"); const expressWinston = require("express-winston");
const fs = require("fs"); const fs = require("fs");
const moment = require("moment"); const moment = require("moment");
const winstonLoki = require("../helpers/loki");
const knex = require("../../infrastructure/database/knex");
const {
topuponline_metrics,
topuponline_metrics_response_time,
topuponline_metrics_load_balance,
} = require("../helpers/prometheusmetrics");
const filename = () => { const filename = () => {
if (!fs.existsSync(`./expresswinstonlog`)) { if (!fs.existsSync(`./expresswinstonlog`)) {
@@ -28,6 +35,20 @@ const filename = () => {
filename(); filename();
const routes = [
"/api/reservation",
"/api/reservation/v2",
"/api/loadbalance/request",
"/api/topup1",
"/api/topup2",
"/api/topup3",
"/api/topup4",
"/api/topup5",
"/api/topup6",
"/api/topup7",
"/api/topup8",
];
const logger = { const logger = {
response: expressWinston.logger({ response: expressWinston.logger({
transports: [ transports: [
@@ -35,13 +56,12 @@ const logger = {
filename: "./expresswinstonlog/%DATE%.log", filename: "./expresswinstonlog/%DATE%.log",
frequency: "24h", frequency: "24h",
datePattern: "YYYY/MM/DD", datePattern: "YYYY/MM/DD",
zippedArchive: true,
maxFiles: "1d", maxFiles: "1d",
}), }),
], ],
format: winston.format.combine( format: winston.format.combine(
winston.format.timestamp(), winston.format.timestamp(),
winston.format.printf((info) => { winston.format.printf(async (info) => {
let body = {}; let body = {};
body.id = info.meta.req.id; body.id = info.meta.req.id;
body.tag = "RES"; body.tag = "RES";
@@ -51,16 +71,192 @@ const logger = {
body.time = moment().format(); body.time = moment().format();
body.responseTime = `${info.meta.responseTime} ms`; body.responseTime = `${info.meta.responseTime} ms`;
var header_auth = info.meta.req.headers["authorization"]; let issuerName;
var issuer_name = "Web"
if (!issuer_name) let partnerId = info.meta.req.partner_id_token;
return `[${moment().format()}] | ${JSON.stringify(body)}`;
if (!partnerId) {
issuerName = "UNDEFINED";
} else {
let getIssuerName = await getPartner(info.meta.req.partner_id_token);
if (!getIssuerName.c_name) {
issuerName = "UNDEFINED";
} else {
issuerName = getIssuerName.c_name;
}
}
let statusCode = info.meta.res.body.code;
let message = info.meta.res.body.message;
let url = info.meta.req.originalUrl;
let date = moment().format("D");
let month = moment().format("M");
let year = moment().format("Y");
// Topup Metrics
if (
url == "/api/topup1" ||
url == "/api/topup2" ||
url == "/api/topup3" ||
url == "/api/topup4" ||
url == "/api/topup5" ||
url == "/api/topup6" ||
url == "/api/topup7" ||
url == "/api/topup8"
) {
let trxId = info.meta.res.body.data.trxID;
if (!trxId) {
trxId = "UNDEFINED";
}
topuponline_metrics_load_balance
.labels({
trxId: trxId,
route: url,
issuer_name: issuerName,
date: date,
month: month,
year: year,
})
.observe(info.meta.responseTime);
}
// Reservation Loki Logs
if (url == "/api/reservation" || url == "/api/reservation/v2") {
if (
statusCode != "00" &&
statusCode != "01" &&
statusCode != "02" &&
statusCode != "03" &&
statusCode != "04"
) {
console.log(statusCode);
winstonLoki.log.error({
message: message,
labels: {
route: url,
status_code: statusCode,
issuer_name: issuerName,
},
});
} else {
let reservation_number = info.meta.res.body.data.reservation_number;
let card_number = info.meta.res.body.data.card_number;
winstonLoki.log.info({
message: message,
labels: {
route: url,
status_code: statusCode,
issuer_name: issuerName,
reservation_number: reservation_number,
card_number: card_number,
},
});
}
} else if (url == "/api/topup6" || url == "/api/topup7") {
let card_number = info.meta.req.body.card_number;
let uid = info.meta.req.body.uid;
let trxID = info.meta.res.body.data.trxID;
if (
statusCode != "00" &&
statusCode != "01" &&
statusCode != "02" &&
statusCode != "03" &&
statusCode != "04"
) {
winstonLoki.log.error({
message: message,
labels: {
route: url,
status_code: statusCode,
issuer_name: issuerName,
card_number: card_number,
uid: uid,
trxID: trxID,
},
});
} else {
winstonLoki.log.info({
message: message,
labels: {
route: url,
status_code: statusCode,
issuer_name: issuerName,
card_number: card_number,
uid: uid,
trxID: trxID,
},
});
}
} else {
let trxID = info.meta.res.body.data.trxID;
if (
statusCode != "00" &&
statusCode != "01" &&
statusCode != "02" &&
statusCode != "03" &&
statusCode != "04"
) {
winstonLoki.log.error({
message: message,
labels: {
route: url,
status_code: statusCode,
issuer_name: issuerName,
trxID: trxID,
},
});
} else {
winstonLoki.log.info({
message: message,
labels: {
route: url,
status_code: statusCode,
issuer_name: issuerName,
trxID: trxID,
},
});
}
}
topuponline_metrics
.labels({
issuer_name: issuerName,
route: url,
status_code: statusCode,
date: date,
month: month,
year: year,
})
.observe(info.meta.responseTime);
topuponline_metrics_response_time
.labels({
issuer_name: issuerName,
route: url,
status_code: statusCode,
date: date,
month: month,
year: year,
response_time: info.meta.responseTime,
})
.observe(info.meta.responseTime);
return `[${moment().format()}] | ${JSON.stringify(body)}`; return `[${moment().format()}] | ${JSON.stringify(body)}`;
}) })
), ),
skip: (req, res) => {
return routes.indexOf(req.originalUrl) === -1;
},
responseWhitelist: [...expressWinston.responseWhitelist, "body"], responseWhitelist: [...expressWinston.responseWhitelist, "body"],
requestWhitelist: [...expressWinston.requestWhitelist, "body", "id", "ip"], requestWhitelist: [
...expressWinston.requestWhitelist,
"body",
"id",
"ip",
"partner_id_token",
],
}), }),
request: expressWinston.logger({ request: expressWinston.logger({
transports: [ transports: [
@@ -68,7 +264,6 @@ const logger = {
filename: "./expresswinstonlog/%DATE%.log", filename: "./expresswinstonlog/%DATE%.log",
frequency: "24h", frequency: "24h",
datePattern: "YYYY/MM/DD", datePattern: "YYYY/MM/DD",
zippedArchive: true,
maxFiles: "1d", maxFiles: "1d",
}), }),
], ],
@@ -89,4 +284,10 @@ const logger = {
}), }),
}; };
const getPartner = async (id) => {
let result = await knex("t_m_partner").where("i_partner", "=", id).first();
return result;
};
module.exports = { logger, filename }; module.exports = { logger, filename };
+3 -2
View File
@@ -4,6 +4,7 @@ const loki = require("winston-loki");
require("winston-daily-rotate-file"); require("winston-daily-rotate-file");
require("dotenv").config(); require("dotenv").config();
const { combine, timestamp, printf, colorize, align, json } = winston.format; const { combine, timestamp, printf, colorize, align, json } = winston.format;
let lokiUrl = process.env.LOKI_URL;
const logLevels = { const logLevels = {
fatal: 0, fatal: 0,
@@ -41,7 +42,7 @@ if (
defaultMeta: { service: "topuponline" }, defaultMeta: { service: "topuponline" },
transports: [ transports: [
new loki({ new loki({
host: "http://localhost:3100", host: lokiUrl,
labels: { app: "topuponline" }, labels: { app: "topuponline" },
json: true, json: true,
format: json(), format: json(),
@@ -57,7 +58,7 @@ if (
log = winston.createLogger({ log = winston.createLogger({
transports: [ transports: [
new loki({ new loki({
host: "http://localhost:3100", host: lokiUrl,
labels: { app: "topuponline" }, labels: { app: "topuponline" },
handleExceptions: true, handleExceptions: true,
handleRejections: true, handleRejections: true,
+29 -2
View File
@@ -3,12 +3,39 @@ const client = require("prom-client");
const topuponline_metrics = new client.Histogram({ const topuponline_metrics = new client.Histogram({
name: "topuponline", name: "topuponline",
help: "this is the metric for getting request data based on code status", help: "this is the metric for getting request data based on code status",
labelNames: ["route", "status_code", "issuer_name", "date", "month", "year"],
});
const topuponline_metrics_response_time = new client.Histogram({
name: "topuponline_response_time",
help: "this is the metric for getting request data based on response time",
labelNames: [ labelNames: [
"route", "route",
"status_code", "status_code",
"issuer_name", "issuer_name",
"method", "date",
"month",
"year",
"response_time",
], ],
}); });
module.exports = { topuponline_metrics }; const topuponline_metrics_load_balance = new client.Histogram({
name: "topuponline_load_balance",
help: "this is the metric for getting request data based on response time",
labelNames: [
"route",
"status_code",
"issuer_name",
"date",
"month",
"year",
"trxId",
],
});
module.exports = {
topuponline_metrics,
topuponline_metrics_response_time,
topuponline_metrics_load_balance,
};
@@ -1,43 +0,0 @@
const winstonLoki = require("../helpers/loki");
const lokiMiddleware = (req, res, next) => {
// return console.log(res)
res.on("finish", () => {
// return console.log(res.body.code)
// console.log(`request url = ${req.originalUrl}`);
// console.log(res.getHeader("x-response-time"));
// console.log(res.statusCode);
let url = req.originalUrl;
let responseTime = Math.round(parseInt(res.getHeader("x-response-time")));
let statusCode = res.body.code;
let method = req.method;
if (statusCode != "200" && statusCode != "204") {
winstonLoki.log.error({
message: "error",
labels: {
method: method,
url: url,
responseTime: responseTime,
status: statusCode,
// data: res.body.data,
},
});
} else {
winstonLoki.log.info({
message: "success",
labels: {
method: method,
url: url,
responseTime: responseTime,
status: statusCode,
// data: res.body.data,
},
});
}
});
next();
};
module.exports = lokiMiddleware;
@@ -1,33 +0,0 @@
const { topuponline_metrics } = require("../helpers/prometheusmetrics");
const prometheusMiddleware = (req, res, next) => {
res.on("finish", () => {
let url = req.originalUrl;
let responseTime = Math.round(parseInt(res.getHeader("x-response-time")));
let statusCode = res.body.code;
let method = req.method;
if (statusCode != "200" && statusCode != "204") {
topuponline_metrics
.labels({
issuer_name: "CMS",
method: method,
route: url,
status_code: statusCode,
})
.observe(responseTime);
} else {
topuponline_metrics
.labels({
issuer_name: "CMS",
method: method,
route: url,
status_code: statusCode,
})
.observe(responseTime);
}
});
next();
};
module.exports = { prometheusMiddleware };
+10 -2
View File
@@ -13,13 +13,21 @@ let redisClient;
password: '', password: '',
}); });
redisClient.on('error', (error) => console.error(`Error : ${error}`)); redisClient.on('error', (error) =>
process.env.NODE_ENV.toUpperCase() != 'PRODUCTION'
? console.error(`Error : ${error}`)
: ''
);
redisClient.on('connect', () => console.log('Redis is Connected')); redisClient.on('connect', () => console.log('Redis is Connected'));
redisClient.on('ready', () => console.log('Redis is Ready')); redisClient.on('ready', () => console.log('Redis is Ready'));
redisClient.on('reconnecting', () => console.log('Redis is Reconnecting')); redisClient.on('reconnecting', () =>
process.env.NODE_ENV.toUpperCase() != 'PRODUCTION'
? console.log('Redis is Reconnecting')
: ''
);
await redisClient.connect(); await redisClient.connect();
})(); })();
+47 -42
View File
@@ -1,55 +1,55 @@
const { param, body, validationResult } = require("express-validator"); const { param, body, validationResult } = require('express-validator');
const winston = require("../../helpers/winston.logger"); const winston = require('../../helpers/winston.logger');
const generate = require("./utils/utils"); const generate = require('./utils/utils');
const loadBalance = require("../loadbalance/loadbalance.controller"); const loadBalance = require('../loadbalance/loadbalance.controller');
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
require("dotenv").config(); require('dotenv').config();
let useClient; let useClient;
// set connection HSM server // set connection HSM server
if (process.env.NUMBER_SERVER_ACTIVE == "1") { if (process.env.NUMBER_SERVER_ACTIVE == '1') {
var { client } = require("./services/webSocket"); var { client } = require('./services/webSocket');
useClient = client; useClient = client;
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") { } else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
var { client2 } = require("./services/webSocket2"); var { client2 } = require('./services/webSocket2');
useClient = client2; useClient = client2;
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") { } else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
var { client } = require("./services/webSocket"); var { client } = require('./services/webSocket');
var { client2 } = require("./services/webSocket2"); var { client2 } = require('./services/webSocket2');
} }
// VALIDATION // VALIDATION
const validate = (method) => { const validate = (method) => {
switch (method) { switch (method) {
case "topupResponse": case 'topupResponse':
return [ return [
body("mid").not().isEmpty().withMessage("MID is required"), body('mid').not().isEmpty().withMessage('MID is required'),
body("tid").not().isEmpty().withMessage("TID is required"), body('tid').not().isEmpty().withMessage('TID is required'),
body("uid").not().isEmpty().withMessage("UID is required"), body('uid').not().isEmpty().withMessage('UID is required'),
body("flag").not().isEmpty().withMessage("Flag is required"), body('flag').not().isEmpty().withMessage('Flag is required'),
body("card_number") body('card_number')
.not() .not()
.isEmpty() .isEmpty()
.withMessage("Card Number is required"), .withMessage('Card Number is required'),
body("amount") body('amount')
.not() .not()
.isEmpty() .isEmpty()
.withMessage("Amount is required") .withMessage('Amount is required')
.isNumeric() .isNumeric()
.withMessage("Amount is invalid format"), .withMessage('Amount is invalid format'),
body("reservation_number") body('reservation_number')
.not() .not()
.isEmpty() .isEmpty()
.withMessage("Reservation Number is required") .withMessage('Reservation Number is required')
.isArray() .isArray()
.withMessage("Reservation Number is invalid request format"), .withMessage('Reservation Number is invalid request format'),
body("load_balance_number") body('load_balance_number')
.not() .not()
.isEmpty() .isEmpty()
.withMessage("Load Balance Number is required"), .withMessage('Load Balance Number is required'),
]; ];
default: default:
break; break;
@@ -79,7 +79,7 @@ const controller = async (req, res) => {
let result = {}; let result = {};
// set connection HSM server // set connection HSM server
if (process.env.NUMBER_SERVER_ACTIVE == "12") { if (process.env.NUMBER_SERVER_ACTIVE == '12') {
// set request to HSM server 2 // set request to HSM server 2
if (uniqueCode) { if (uniqueCode) {
if (parseInt(uniqueCode) % 2 == 0) { if (parseInt(uniqueCode) % 2 == 0) {
@@ -119,8 +119,8 @@ const controller = async (req, res) => {
let _stopMessage = 1; let _stopMessage = 1;
if (packet[0] != 0x47) { if (packet[0] != 0x47) {
result = { result = {
code: "03", code: '03',
message: "Respone Card Wrong", message: 'Respone Card Wrong',
data: {}, data: {},
}; };
@@ -140,7 +140,7 @@ const controller = async (req, res) => {
let respData = null; let respData = null;
let respData1 = null; let respData1 = null;
useClient.ws.on("message", (message) => { useClient.ws.on('message', (message) => {
while ( while (
message[2] == 5 && message[2] == 5 &&
message[0] == transactionId[0] && message[0] == transactionId[0] &&
@@ -186,7 +186,7 @@ const controller = async (req, res) => {
amount: amount, amount: amount,
reservation_number: reservation_number, reservation_number: reservation_number,
ref_no: ref_no, ref_no: ref_no,
write_status: "FW", write_status: 'FW',
uid: uid, uid: uid,
balance: parseInt(balance) + parseInt(amount), balance: parseInt(balance) + parseInt(amount),
flag: parseInt(flag), flag: parseInt(flag),
@@ -203,8 +203,8 @@ const controller = async (req, res) => {
await loadBalance.loadingBalanceUpdate(data); await loadBalance.loadingBalanceUpdate(data);
result = { result = {
code: "5002", code: '5002',
message: "failed from HSM", message: 'failed from HSM',
data: { data: {
trxID: generate.buf2hex(transactionId), trxID: generate.buf2hex(transactionId),
responseCode: respData1.slice(6, 10), responseCode: respData1.slice(6, 10),
@@ -213,6 +213,11 @@ const controller = async (req, res) => {
}, },
}; };
} else { } else {
// jika sudah mencapai maksimum counting flag, maka reset flag ke awal
if (flag >= 255) {
flag = -1;
}
data = { data = {
mid: mid, mid: mid,
tid: tid, tid: tid,
@@ -236,10 +241,10 @@ const controller = async (req, res) => {
// update data load balance // update data load balance
let update = await loadBalance.loadingBalanceUpdate(data); let update = await loadBalance.loadingBalanceUpdate(data);
if (update) { if (update) {
if (update.code == "00") { if (update.code == '00') {
result = { result = {
code: "00", code: '00',
message: "Topup Succeess", message: 'Topup Succeess',
data: { data: {
trxID: generate.buf2hex(transactionId), trxID: generate.buf2hex(transactionId),
responseCode: respCode, responseCode: respCode,
@@ -257,8 +262,8 @@ const controller = async (req, res) => {
} }
} else { } else {
result = { result = {
code: "423", code: '423',
message: "update/insert failed", message: 'update/insert failed',
data: {}, data: {},
}; };
} }
@@ -277,11 +282,11 @@ const controller = async (req, res) => {
); );
return res.status(200).send({ return res.status(200).send({
code: "5001", code: '5001',
message: message:
process.env.NODE_ENV != "production" process.env.NODE_ENV != 'production'
? error.message ? error.message
: "500 internal server error - backend server.", : '500 internal server error - backend server.',
data: {}, data: {},
}); });
} }
@@ -505,6 +505,24 @@ const loadingBalanceRequest = async (req, res) => {
// get parameter setting pengecekkan nomor kartu dengan card product di CMS // get parameter setting pengecekkan nomor kartu dengan card product di CMS
let getCheckByCardProductStatusValue = let getCheckByCardProductStatusValue =
await model.getCheckByCardProductStatusValue(); await model.getCheckByCardProductStatusValue();
// check value global parameter
if (!getCheckByCardProductStatusValue) {
result = {
code: '439',
message: 'HSM_CHECK_BY_CARD_PRODUCT_STAT in global parameter not found',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
let checkByCardProductStatusValue = let checkByCardProductStatusValue =
getCheckByCardProductStatusValue.c_value; getCheckByCardProductStatusValue.c_value;
@@ -692,7 +710,13 @@ const loadingBalanceRequest = async (req, res) => {
result = { result = {
code: '01', code: '01',
message: 'your card number has been cleared successfully', message: 'your card number has been cleared successfully',
data: {}, data: {
load_balance_number: loadBalanceNumberPendingSuccessLoaded[0],
amount: parseInt(totalReservationAmount),
total_reservation: getReservationPendingWithFlagCounter.length,
reservation_number: reservationNumberPendingSuccessLoaded,
partial_topup: false,
},
}; };
} else { } else {
result = { result = {
@@ -751,6 +775,7 @@ const loadingBalanceRequest = async (req, res) => {
return res.status(200).json(result); return res.status(200).json(result);
} }
let partialTopup = false;
let totalReservation = 0; let totalReservation = 0;
let amountTopup = 0; let amountTopup = 0;
let reservationNumber = []; let reservationNumber = [];
@@ -816,7 +841,48 @@ const loadingBalanceRequest = async (req, res) => {
// get BI regulation status // get BI regulation status
const getBIRegulationStatus = await model.getBIRegulationStatus(); const getBIRegulationStatus = await model.getBIRegulationStatus();
// check value global parameter
if (!getBIRegulationStatus) {
result = {
code: '439',
message: 'HSM_BI_REGULATION_STAT in global parameter not found',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
if (getBIRegulationStatus.c_value == 'A') { if (getBIRegulationStatus.c_value == 'A') {
// log debug
winston.logger.debug(`${uniqueCode} checking topup partial status...`);
// check topup partial status
const getTopupPartialStatus = await model.getTopupPartialStatus();
// check value global parameter
if (!getTopupPartialStatus) {
result = {
code: '439',
message: 'HSM_TOPUP_PARTIAL_STAT in global parameter not found',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
// log debug // log debug
winston.logger.debug( winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max balance on the card...` `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max balance on the card...`
@@ -824,25 +890,97 @@ const loadingBalanceRequest = async (req, res) => {
// get max saldo on the card // get max saldo on the card
const getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); const getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
// check value global parameter
if (!getMaxAmountOnTheCard) {
result = {
code: '439',
message:
'HSM_BI_MAX_AMOUNT_ON_THE_CARD in global parameter not found',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
if (getMaxAmountOnTheCard.c_value) { if (getMaxAmountOnTheCard.c_value) {
if ( if (
parseInt(balance) + parseInt(amountTopup) > parseInt(balance) + parseInt(amountTopup) >
parseInt(getMaxAmountOnTheCard.c_value) parseInt(getMaxAmountOnTheCard.c_value)
) { ) {
result = { // if topup partial is active
code: '416', if (getTopupPartialStatus.c_value == 'A') {
message: 'your card number has reached the maximum balance', // reset reservation data
data: {}, partialTopup = true;
}; totalReservation = 0;
amountTopup = 0;
reservationNumber = [];
reservationNumberTemp = [];
i = 0;
// log warn // sum amount can be topup
winston.logger.warn( getReservationPending.forEach((rsv) => {
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( if (
result parseInt(balance) + parseInt(amountTopup) <=
)}` parseInt(getMaxAmountOnTheCard.c_value)
); ) {
amountTopup += parseInt(rsv.i_reservation_amount);
if (
amountTopup > parseInt(getMaxAmountOnTheCard.c_value) ||
parseInt(balance) + amountTopup >
parseInt(getMaxAmountOnTheCard.c_value)
) {
amountTopup =
amountTopup - parseInt(rsv.i_reservation_amount);
i--;
} else {
reservationNumber.push(rsv.c_reservation_no);
reservationNumberTemp.push(rsv.c_reservation_no);
}
}
i++;
});
return res.status(200).json(result); totalReservation = i;
if (totalReservation == 0) {
result = {
code: '414',
message:
"reservation doesn't exist. Lowest amount exceeds the maximum balance",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
} else {
result = {
code: '416',
message: 'your card number has reached the maximum balance',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
} }
} }
@@ -866,25 +1004,96 @@ const loadingBalanceRequest = async (req, res) => {
// validate max topup per month // validate max topup per month
const getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); const getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
// check value global parameter
if (!getMaxTopupPerMonth) {
result = {
code: '439',
message: 'HSM_BI_MAX_TOPUP_PER_MONTH in global parameter not found',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
if (getMaxTopupPerMonth.c_value) { if (getMaxTopupPerMonth.c_value) {
if ( if (
parseInt(accumulatedBalance) + parseInt(amountTopup) > parseInt(accumulatedBalance) + parseInt(amountTopup) >
parseInt(getMaxTopupPerMonth.c_value) parseInt(getMaxTopupPerMonth.c_value)
) { ) {
result = { // if topup partial is active
code: '417', if (getTopupPartialStatus.c_value == 'A') {
message: 'your card number has been limit top up for this month', // reset reservation data
data: {}, partialTopup = true;
}; totalReservation = 0;
amountTopup = 0;
reservationNumber = [];
reservationNumberTemp = [];
i = 0;
// log warn // sum amount can be topup
winston.logger.warn( getReservationPending.forEach((rsv) => {
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( if (
result parseInt(balance) + parseInt(amountTopup) <=
)}` parseInt(getMaxAmountOnTheCard.c_value)
); ) {
amountTopup += parseInt(rsv.i_reservation_amount);
if (
amountTopup > parseInt(getMaxAmountOnTheCard.c_value) ||
parseInt(balance) + amountTopup >
parseInt(getMaxAmountOnTheCard.c_value)
) {
amountTopup =
amountTopup - parseInt(rsv.i_reservation_amount);
i--;
} else {
reservationNumber.push(rsv.c_reservation_no);
reservationNumberTemp.push(rsv.c_reservation_no);
}
}
i++;
});
return res.status(200).json(result); totalReservation = i;
if (totalReservation == 0) {
result = {
code: '417',
message:
"reservation doesn't exist. Lowest amount exceeds the limit top up for this month",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
} else {
result = {
code: '417',
message: 'your card number has been limit top up for this month',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
} }
} }
} }
@@ -909,6 +1118,7 @@ const loadingBalanceRequest = async (req, res) => {
amount: parseInt(amountTopup), amount: parseInt(amountTopup),
total_reservation: totalReservation, total_reservation: totalReservation,
reservation_number: reservationNumber, reservation_number: reservationNumber,
partial_topup: partialTopup,
}, },
}; };
@@ -926,6 +1136,7 @@ const loadingBalanceRequest = async (req, res) => {
amount: parseInt(amountTopup), amount: parseInt(amountTopup),
total_reservation: totalReservation, total_reservation: totalReservation,
reservation_number: reservationNumber, reservation_number: reservationNumber,
partial_topup: partialTopup,
}, },
}; };
@@ -386,7 +386,7 @@ const insertLoadingBalance = async (
return result.rowCount; return result.rowCount;
}) })
.catch((error) => { .catch((error) => {
console.log(error.message); // console.log(error.message);
return error.message; return error.message;
}); });
}; };
@@ -457,7 +457,7 @@ const updateLoadingBalance = async (
return result; return result;
}) })
.catch((error) => { .catch((error) => {
console.log(error.message); // console.log(error.message);
return error.message; return error.message;
}); });
}; };
@@ -548,7 +548,7 @@ const insertLoadingBalanceHistoryOnly = async (
return result; return result;
}) })
.catch((error) => { .catch((error) => {
console.log(error.message); // console.log(error.message);
return error.message; return error.message;
}); });
}; };
@@ -665,7 +665,7 @@ const updateReservationAndLoadingBalance = async (
return result.rowCount; return result.rowCount;
}) })
.catch((error) => { .catch((error) => {
console.log(error.message); // console.log(error.message);
return error.message; return error.message;
}); });
}; };
@@ -745,7 +745,7 @@ const updateFlag = async (now, cardNumber, uid, balance, flag) => {
return result; return result;
}) })
.catch((error) => { .catch((error) => {
console.log(error.message); // console.log(error.message);
return error.message; return error.message;
}); });
}; };
@@ -793,14 +793,14 @@ const getReservationPendingWithoutFraud = (
reservationNumber = [] reservationNumber = []
) => { ) => {
if (reservationNumber.length > 0) { if (reservationNumber.length > 0) {
let rsv = ``; let rsv = '';
if (reservationNumber.length > 0) { if (reservationNumber.length > 0) {
for (let index = 0; index < reservationNumber.length; index++) { for (let index = 0; index < reservationNumber.length; index++) {
if (index > 0) { if (index > 0) {
rsv = rsv + `,`; rsv = rsv + ',';
} }
rsv = `'` + rsv + reservationNumber[index] + `'`; rsv = rsv + "'" + reservationNumber[index] + "'";
} }
} }
@@ -862,14 +862,14 @@ const getLastHistory = (cardNumber) => {
// INSERT FRAUD TRANSACTION // INSERT FRAUD TRANSACTION
const insertFraudTransaction = (reservationNumber) => { const insertFraudTransaction = (reservationNumber) => {
let rsv = ``; let rsv = '';
if (reservationNumber.length > 0) { if (reservationNumber.length > 0) {
for (let index = 0; index < reservationNumber.length; index++) { for (let index = 0; index < reservationNumber.length; index++) {
if (index > 0) { if (index > 0) {
rsv = rsv + `,`; rsv = rsv + ',';
} }
rsv = `'` + rsv + reservationNumber[index] + `'`; rsv = rsv + "'" + reservationNumber[index] + "'";
} }
} }
@@ -1019,15 +1019,25 @@ const updateReservationAndInsertLoadingBalance = async (
.catch(trx.rollback); .catch(trx.rollback);
}) })
.then((result) => { .then((result) => {
console.log(result); // console.log(result);
return result.rowCount; return result.rowCount;
}) })
.catch((error) => { .catch((error) => {
console.log(error.message); // console.log(error.message);
return error.message; return error.message;
}); });
}; };
// GET TOPUP PARTIAL STATUS FROM GLOBAL PARAMETER
const getTopupPartialStatus = () => {
let result = knex('t_m_global_parameter')
.select('c_value')
.where('c_code', '=', 'HSM_TOPUP_PARTIAL_STAT')
.first();
return result;
};
module.exports = { module.exports = {
checkCardNumber, checkCardNumber,
getPartner, getPartner,
@@ -1072,4 +1082,5 @@ module.exports = {
getReservationPendingWithFlagV2, getReservationPendingWithFlagV2,
createDetailLoadBalanceFromReservation, createDetailLoadBalanceFromReservation,
updateReservationAndInsertLoadingBalance, updateReservationAndInsertLoadingBalance,
getTopupPartialStatus,
}; };
@@ -73,6 +73,11 @@ const validate = (method) => {
.isEmpty() .isEmpty()
.withMessage('Reservation Number is required'), .withMessage('Reservation Number is required'),
]; ];
case 'cancelReservationValidateV2':
return [
body('mid').not().isEmpty().withMessage('MID is required'),
body('tid').not().isEmpty().withMessage('TID is required'),
];
case 'cancelReservationV2': case 'cancelReservationV2':
return [ return [
body('cancel_reservation_data') body('cancel_reservation_data')
@@ -1106,7 +1111,7 @@ const reservationValidateV2 = async (req, res) => {
} }
}; };
// ================================================================= RESERVATION ================================================================= // ================================================================= RESERVATION V1 =================================================================
// *Created By: Mohamad Ihsan* // *Created By: Mohamad Ihsan*
// *Description:* // *Description:*
// proses insert data transaksi reservasi saldo. Proses ini dilakukan setelah melakukan reservation validate dengan response code 00. Output dari proses ini adalah kode reservation number dan informasi reservasi saldo yang dilakukan // proses insert data transaksi reservasi saldo. Proses ini dilakukan setelah melakukan reservation validate dengan response code 00. Output dari proses ini adalah kode reservation number dan informasi reservasi saldo yang dilakukan
@@ -1119,7 +1124,8 @@ const reservation = async (req, res) => {
let result = {}; let result = {};
// param // param
let { mid, tid, card_number, amount, ref_no } = req.body; let { mid, tid, card_number, amount, ref_no, customer_name, phone_number } =
req.body;
// log info // log info
winston.logger.info( winston.logger.info(
@@ -1561,6 +1567,19 @@ const reservation = async (req, res) => {
let expired = moment(now).add(time, measure).format('YYYY-MM-DD HH:mm:ss'); let expired = moment(now).add(time, measure).format('YYYY-MM-DD HH:mm:ss');
// -------------------------------- NOTES --------------------------------
// for LRT JABO => customer_name diisi Device Name (versi penamaan LRT Jabo) dan phone_number diisi Device Code (versi kode LRT Jabo) sesuai MOM BI-WEEKLY MEETING (08/05/2023)
let customerName = customer_name;
let phoneNumber = phone_number;
if (!customerName || customerName == '' || customerName == '-') {
customerName = getPartner ? getPartner.terminal_name : '';
}
if (!phoneNumber || phoneNumber == '' || phoneNumber == '-') {
phoneNumber = mid + '_' + tid;
}
// binding data // binding data
let data = { let data = {
c_reservation_no: reservationNumber, c_reservation_no: reservationNumber,
@@ -1607,6 +1626,8 @@ const reservation = async (req, res) => {
c_delete_username: null, c_delete_username: null,
c_delete_fullname: null, c_delete_fullname: null,
c_flag: '-1', c_flag: '-1',
c_customer_name: customerName,
c_phone_number: phoneNumber,
}; };
// log debug // log debug
@@ -1629,7 +1650,7 @@ const reservation = async (req, res) => {
await model.deleteReservationNumberValidate(reservationNumber); await model.deleteReservationNumberValidate(reservationNumber);
result = { result = {
code: '432', code: '424',
message: 'refno is duplicate', message: 'refno is duplicate',
data: {}, data: {},
}; };
@@ -1723,7 +1744,7 @@ const reservationV2 = async (req, res) => {
let result = {}; let result = {};
// param // param
let { reservation_data, ref_no } = req.body; let { reservation_data, ref_no, customer_name, phone_number } = req.body;
// log info // log info
winston.logger.info( winston.logger.info(
@@ -2297,6 +2318,19 @@ const reservationV2 = async (req, res) => {
let expired = moment(now).add(time, measure).format('YYYY-MM-DD HH:mm:ss'); let expired = moment(now).add(time, measure).format('YYYY-MM-DD HH:mm:ss');
// -------------------------------- NOTES --------------------------------
// for LRT JABO => customer_name diisi Device Name (versi penamaan LRT Jabo) dan phone_number diisi Device Code (versi kode LRT Jabo) sesuai MOM BI-WEEKLY MEETING (08/05/2023)
let customerName = customer_name;
let phoneNumber = phone_number;
if (!customerName || customerName == '' || customerName == '-') {
customerName = getPartner ? getPartner.terminal_name : '';
}
if (!phoneNumber || phoneNumber == '' || phoneNumber == '-') {
phoneNumber = mid + '_' + tid;
}
// binding data // binding data
let data = { let data = {
c_reservation_no: reservationNumber, c_reservation_no: reservationNumber,
@@ -2343,6 +2377,8 @@ const reservationV2 = async (req, res) => {
c_delete_username: null, c_delete_username: null,
c_delete_fullname: null, c_delete_fullname: null,
c_flag: '-1', c_flag: '-1',
c_customer_name: customerName,
c_phone_number: phoneNumber,
}; };
// log debug // log debug
@@ -2365,7 +2401,7 @@ const reservationV2 = async (req, res) => {
await model.deleteReservationNumberValidate(reservationNumber); await model.deleteReservationNumberValidate(reservationNumber);
result = { result = {
code: '432', code: '424',
message: 'refno is duplicate', message: 'refno is duplicate',
data: {}, data: {},
}; };
@@ -3086,6 +3122,18 @@ const inquiryListReservationByReservation = async (req, res) => {
}); });
} }
// check date range max 1 month
let diff = moment(end_date).diff(moment(start_date), 'months', true);
if (diff >= 1) {
return res.status(200).json({
code: '400',
message:
'bad request. We only allow data requests for 1 month. please change your date range parameter request!',
data: {},
});
}
// check reservation // check reservation
let listReservation = await model.inquiryListReservation( let listReservation = await model.inquiryListReservation(
req.partner_id_token, req.partner_id_token,
@@ -3130,11 +3178,11 @@ const cancelReservationValidateV2 = async (req, res) => {
let result = {}; let result = {};
// param // param
let { mid, tid, reservation_number } = req.body; let { mid, tid, reservation_number, ref_no } = req.body;
// log info // log info
winston.logger.info( winston.logger.info(
`${uniqueCode} [ REQUEST CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ REQUEST CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
req.body req.body
)}` )}`
); );
@@ -3150,7 +3198,7 @@ const cancelReservationValidateV2 = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -3161,7 +3209,7 @@ const cancelReservationValidateV2 = async (req, res) => {
// log debug // log debug
// proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak
winston.logger.debug( winston.logger.debug(
`${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE ]: checking partner...` `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ]: checking partner...`
); );
// get partner, merchant, terminal from tid // get partner, merchant, terminal from tid
@@ -3175,53 +3223,122 @@ const cancelReservationValidateV2 = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
return res.status(200).json(result); return res.status(200).json(result);
} }
// log debug let getReservationCanBeCanceled;
// proses pengecekkan status reservation number yang di request
winston.logger.debug(
`${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE ]: getting reservation by reservation number...`
);
// get reservation berdasarkan reservation number yang di request // jika cancelation reservation dilakukan dengan menggunakan ref no
let getReservationCanBeCanceled = await model.getReservationCanBeCanceled( if (ref_no) {
reservation_number if (!ref_no) {
); result = {
code: '400',
message: 'Ref no is required',
data: {},
};
if (!getReservationCanBeCanceled) { // log warn
result = { winston.logger.warn(
code: '414', `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
message: "Reservation doesn't exist.", result
data: {}, )}`
}; );
// log warn return res.status(200).json(result);
winston.logger.warn( }
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
result // log debug
)}` // proses pengecekkan status reservation number yang di request
winston.logger.debug(
`${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ]: getting reservation by ref no...`
); );
return res.status(200).json(result);
// get reservation berdasarkan ref_no yang di request
getReservationCanBeCanceled =
await model.getReservationCanBeCanceledByRefno(ref_no);
if (!getReservationCanBeCanceled) {
result = {
code: '440',
message: "Ref no doesn't exist.",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
} else {
if (!reservation_number) {
result = {
code: '400',
message: 'Reservation number is required',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
// log debug
// proses pengecekkan status reservation number yang di request
winston.logger.debug(
`${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ]: getting reservation by reservation number...`
);
// get reservation berdasarkan reservation number yang di request
getReservationCanBeCanceled = await model.getReservationCanBeCanceled(
reservation_number
);
if (!getReservationCanBeCanceled) {
result = {
code: '414',
message: "Reservation doesn't exist.",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
} }
let reservationNumber = getReservationCanBeCanceled?.c_reservation_no;
let cardNumber = getReservationCanBeCanceled?.c_card_number;
let amount = getReservationCanBeCanceled?.i_reservation_amount;
// get value global parameter // get value global parameter
let getGlobalParameter = await model.getGlobalParameter(); let getGlobalParameter = await model.getGlobalParameter();
// check value global parameter // check value global parameter
if (!getGlobalParameter) { if (!getGlobalParameter) {
result = { result = {
code: '493', code: '439',
message: 'HSM_CANCEL_RESERVATION_LEVEL in global parameter not found', message: 'HSM_CANCEL_RESERVATION_LEVEL in global parameter not found',
data: {}, data: {},
}; };
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -3238,7 +3355,7 @@ const cancelReservationValidateV2 = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -3255,7 +3372,7 @@ const cancelReservationValidateV2 = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -3272,7 +3389,7 @@ const cancelReservationValidateV2 = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -3296,7 +3413,7 @@ const cancelReservationValidateV2 = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -3317,7 +3434,7 @@ const cancelReservationValidateV2 = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} RESPONSE cancel reservation validate: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -3333,7 +3450,7 @@ const cancelReservationValidateV2 = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -3350,7 +3467,7 @@ const cancelReservationValidateV2 = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -3363,13 +3480,13 @@ const cancelReservationValidateV2 = async (req, res) => {
// create security code yang isinya data reservasi yang akan di compare nantinya saat melakukan insert reservation // create security code yang isinya data reservasi yang akan di compare nantinya saat melakukan insert reservation
let securityCode = await helper.createHMAC( let securityCode = await helper.createHMAC(
mid + '|' + tid + '|' + reservation_number mid + '|' + tid + '|' + reservationNumber
); );
let reservationData = { let reservationData = {
mid: mid, mid: mid,
tid: tid, tid: tid,
reservation_number: reservation_number, reservation_number: reservationNumber,
transaction_date: now, transaction_date: now,
security_code: securityCode, security_code: securityCode,
}; };
@@ -3377,7 +3494,7 @@ const cancelReservationValidateV2 = async (req, res) => {
// log debug // log debug
// process enkripsi data reservasi dengan AES yang nanti nya akan di kirim ke end point reservation api untuk menyimpan data reservasi // process enkripsi data reservasi dengan AES yang nanti nya akan di kirim ke end point reservation api untuk menyimpan data reservasi
winston.logger.debug( winston.logger.debug(
`${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] encrypting data reservation: ${JSON.stringify( `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ] encrypting data reservation: ${JSON.stringify(
reservationData reservationData
)}` )}`
); );
@@ -3390,12 +3507,17 @@ const cancelReservationValidateV2 = async (req, res) => {
message: 'reservation can be canceled.', message: 'reservation can be canceled.',
data: { data: {
cancel_reservation_data: hash, cancel_reservation_data: hash,
cancel_reservation_detail: {
reservation_number: reservationNumber,
card_number: cardNumber,
amount: amount,
},
}, },
}; };
// log info // log info
winston.logger.info( winston.logger.info(
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -3404,7 +3526,7 @@ const cancelReservationValidateV2 = async (req, res) => {
} catch (error) { } catch (error) {
// create log // create log
winston.logger.error( winston.logger.error(
`[ RESPONSE CANCEL-RESERVATION-VALIDATE ]: 500 internal server error - backend server | ${error.message}` `[ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: 500 internal server error - backend server | ${error.message}`
); );
return res.status(200).json({ return res.status(200).json({
@@ -378,6 +378,14 @@ const getReservationCanBeCanceled = (reservation_number) => {
return result; return result;
}; };
// GET RESERVATION PENDING AND NOT YET PAYMENT RECON
const getReservationCanBeCanceledByRefno = (ref_no) => {
let result = knex('trx.t_d_reservation_balance')
.where('c_ref_no', ref_no)
.first();
return result;
};
const insertReservationNumber = (reservationNumber) => { const insertReservationNumber = (reservationNumber) => {
let result = knex('trx.t_d_reservation_no_validate') let result = knex('trx.t_d_reservation_no_validate')
.insert({ .insert({
@@ -545,6 +553,7 @@ module.exports = {
createReserveBalanceLog, createReserveBalanceLog,
getReservationWithPendingAndInProgressStatus, getReservationWithPendingAndInProgressStatus,
getReservationCanBeCanceled, getReservationCanBeCanceled,
getReservationCanBeCanceledByRefno,
insertReservationNumber, insertReservationNumber,
cancelReservation, cancelReservation,
deleteReservationNumberValidate, deleteReservationNumberValidate,
+7 -15
View File
@@ -1,10 +1,6 @@
const express = require('express'); const express = require('express');
const router = express.Router(); const router = express.Router();
const auth = require('../middlewares/jwt.middleware'); const auth = require('../middlewares/jwt.middleware');
const lokiMiddleware = require('../middlewares/loki.middleware');
const {
prometheusMiddleware,
} = require('../middlewares/prometheus.middleware');
const { const {
getReservationNumberSequence, getReservationNumberSequence,
} = require('../middlewares/redis.middleware'); } = require('../middlewares/redis.middleware');
@@ -28,8 +24,6 @@ router.post(
router.post( router.post(
'/reservation', '/reservation',
auth.authenticateToken, auth.authenticateToken,
prometheusMiddleware,
lokiMiddleware,
getReservationNumberSequence, getReservationNumberSequence,
controller.validate('reservation'), controller.validate('reservation'),
controller.reservation controller.reservation
@@ -78,8 +72,6 @@ router.post(
router.post( router.post(
'/reservation/v2', '/reservation/v2',
auth.authenticateToken, auth.authenticateToken,
prometheusMiddleware,
lokiMiddleware,
getReservationNumberSequence, getReservationNumberSequence,
controller.validate('reservationV2'), controller.validate('reservationV2'),
controller.reservationV2 controller.reservationV2
@@ -88,7 +80,7 @@ router.post(
router.post( router.post(
'/reservation/cancel/validate/v2', '/reservation/cancel/validate/v2',
auth.authenticateToken, auth.authenticateToken,
controller.validate('cancelReservation'), controller.validate('cancelReservationValidateV2'),
controller.cancelReservationValidateV2 controller.cancelReservationValidateV2
); );
@@ -99,11 +91,11 @@ router.post(
controller.cancelReservationV2 controller.cancelReservationV2
); );
router.post( // router.post(
'/reservation/cancel/v2.1', // '/reservation/cancel/v2.1',
auth.authenticateToken, // auth.authenticateToken,
controller.validate('cancelReservation'), // controller.validate('cancelReservation'),
controller.cancelReservationV2_1 // controller.cancelReservationV2_1
); // );
module.exports = router; module.exports = router;
+6
View File
@@ -21,6 +21,12 @@ DB_PASSWORD_LOCAL=postgres
REDIS_URL=redis://localhost:6379 REDIS_URL=redis://localhost:6379
REDIS_PASSWORD= REDIS_PASSWORD=
# ==================================== LOKI =====================================
LOKI_URL=http://10.20.14.30:3100
# ==================================== APP PROMETHEUS =====================================
PROM_APP = topuponline
# ================================== SECRET KEY ================================== # ================================== SECRET KEY ==================================
# FOR PRODUCTION # FOR PRODUCTION
#SECRET_KEY=U2FsdGVkX19keaNhiBfdNSWnKA2a8Z5deBu/KkU6BNg= #SECRET_KEY=U2FsdGVkX19keaNhiBfdNSWnKA2a8Z5deBu/KkU6BNg=
+145
View File
@@ -0,0 +1,145 @@
# ================================= ENVIRONMENT =================================
#NODE_ENV=production
NODE_ENV=development
#NODE_ENV=testing
PORT=3000
VERSION=v1.3.7
# =========================== KONFIGURASI UNTUK SERVER ===========================
# SERVER_FOR=development
#SERVER_FOR=production
SERVER_FOR=local
# =============================== DATABASE LOCAL =================================
# DB_URL=postgresql://postgres:postgres@localhost:5432/CMS_DEV
DB_HOST_LOCAL=localhost
DB_NAME_LOCAL=CMS_DEV
DB_PORT_LOCAL=5432
DB_USER_LOCAL=postgres
DB_PASSWORD_LOCAL=postgres
# ==================================== REDIS =====================================
REDIS_URL=redis://localhost:6379
REDIS_PASSWORD=
# ==================================== LOKI =====================================
LOKI_URL=http://localhost:3100
# =============================== APP PROMETHEUS =================================
PROM_APP = topuponline
# ================================== SECRET KEY ==================================
# FOR PRODUCTION
#SECRET_KEY=U2FsdGVkX19keaNhiBfdNSWnKA2a8Z5deBu/KkU6BNg=
# FOR DEVELOPMENT
SECRET_KEY=U2FsdGVkX18tPlf9nVJEx7KwTdFsGPO/RK6A0HRYDeg=
# ===================================== JWT =======================================
JWT_EXPIRATION=30d
JWT_REFRESH_EXPIRATION=40d
# FOR PRODUCTION
#TOKEN_SECRET=101001D00C2001D0483001D0
#REFRESH_TOKEN_SECRET=101001D00C2001D0483001D0800082008300800081008200
# FOR DEVELOPMENT
TOKEN_SECRET=101001A00C2001A0483001A0883001A0
REFRESH_TOKEN_SECRET=101001A00C2001A0483001A0883001A0800082008300800081008200
# ===================== CHANGE TO DRC SERVER (YES or NO) ===========================
CHANGE_TO_DRC=YES
# HIGH AVABILITY (1 = SERVER_HSM_1 ONLY RUNNING, 2 = SERVER_HSM_2 ONLY RUNNING, 12 = SERVER_HSM_1 && SERVER_HSM_2 RUNNING)
NUMBER_SERVER_ACTIVE=1
# ================================ KONFIGURASI HSM =================================
# system code kci profile
# FOR PRODUCTION & DEVELOPMENT
SYSTEM_CODE=90B7
#SERVICE BLOCK
# FOR PRODUCTION
# SERVICEBLOCK_SERVICE_MUTUAL="101001D00C2001D0483001D0"
# FOR DEVELOPMENT
SERVICEBLOCK_SERVICE_MUTUAL="101001A00C2001A0483001A0883001A0"
SERVICEBLOCK_BLOCK_READ="800082008300"
SERVICEBLOCK_BLOCK_WRITE="800081008200"
# HSM DC (DATA CENTER)
# HSM SERVER
# URL_HSM_SERVER_1="ws://182.253.34.129/feliqserver/v1/wsapi"
# APIKEY_HSM_SERVER_1="bc391562-f880-3b57-9868-36dfa5cbf954-0TC"
# SECRETKEY_HSM_SERVER_1="xWW2o+lpAqDLIN85uHZdfuDQhhd7jCXp4w1rXhCkYEk="
# URL_HSM_SERVER_2="ws://182.253.34.129:88/feliqserver/v1/wsapi"
# APIKEY_HSM_SERVER_2="bc391562-f880-3b57-9868-36dfa5cbf954-0TC"
# SECRETKEY_HSM_SERVER_2="xWW2o+lpAqDLIN85uHZdfuDQhhd7jCXp4w1rXhCkYEk="
# # HSM DRC (DISASTER RECOVERY CENTER)
# # HSM SERVER
# URL_HSM_SERVER_BACKUP_1="ws://182.253.34.129/feliqserver/v1/wsapi"
# APIKEY_HSM_SERVER_BACKUP_1="bc391562-f880-3b57-9868-36dfa5cbf954-0TC"
# SECRETKEY_HSM_SERVER_BACKUP_1="xWW2o+lpAqDLIN85uHZdfuDQhhd7jCXp4w1rXhCkYEk="
# URL_HSM_SERVER_BACKUP_2="ws://182.253.34.129:88/feliqserver/v1/wsapi"
# APIKEY_HSM_SERVER_BACKUP_2="bc391562-f880-3b57-9868-36dfa5cbf954-0TC"
# SECRETKEY_HSM_SERVER_BACKUP_2="xWW2o+lpAqDLIN85uHZdfuDQhhd7jCXp4w1rXhCkYEk="
# HSM DC (DATA CENTER)
# HSM SERVER
IP_HSM_SERVER_1="10.1.201.222"
URL_HSM_SERVER_1="ws://10.1.201.222/feliqserver/v1/wsapi"
APIKEY_HSM_SERVER_1="bc391562-f880-3b57-9868-36dfa5cbf954-0TC"
SECRETKEY_HSM_SERVER_1="xWW2o+lpAqDLIN85uHZdfuDQhhd7jCXp4w1rXhCkYEk="
IP_HSM_SERVER_2="10.1.201.215"
URL_HSM_SERVER_2="ws://10.1.201.215:88/feliqserver/v1/wsapi"
APIKEY_HSM_SERVER_2="bc391562-f880-3b57-9868-36dfa5cbf954-0TC"
SECRETKEY_HSM_SERVER_2="xWW2o+lpAqDLIN85uHZdfuDQhhd7jCXp4w1rXhCkYEk="
# HSM DRC (DISASTER RECOVERY CENTER)
# HSM SERVER
IP_HSM_SERVER_BACKUP_1="10.1.201.222"
URL_HSM_SERVER_BACKUP_1="ws://10.1.201.215/feliqserver/v1/wsapi"
APIKEY_HSM_SERVER_BACKUP_1="bc391562-f880-3b57-9868-36dfa5cbf954-0TC"
SECRETKEY_HSM_SERVER_BACKUP_1="xWW2o+lpAqDLIN85uHZdfuDQhhd7jCXp4w1rXhCkYEk="
IP_HSM_SERVER_BACKUP_2="10.1.201.215"
URL_HSM_SERVER_BACKUP_2="ws://10.1.201.215:88/feliqserver/v1/wsapi"
APIKEY_HSM_SERVER_BACKUP_2="bc391562-f880-3b57-9868-36dfa5cbf954-0TC"
SECRETKEY_HSM_SERVER_BACKUP_2="xWW2o+lpAqDLIN85uHZdfuDQhhd7jCXp4w1rXhCkYEk="
# ============================= KONFIGURASI HSM NUTECH =============================
# SYSTEM CODE IN HEXA STRING
# system code nutech profile
# SYSTEM_CODE=939E
#SERVICE BLOCK
# SERVICEBLOCK_SERVICE_MUTUAL="102001A04C2001A0882001A0"
# SERVICEBLOCK_BLOCK_READ="80008200"
# SERVICEBLOCK_BLOCK_WRITE="800081008200"
# HSM DC (DATA CENTER)
# HSM SERVER
# URL_HSM_SERVER_1="ws://10.1.201.215/feliqserver/v1/wsapi"
# APIKEY_HSM_SERVER_1="d54ff5c4-9709-3bac-9a6e-04b2f4deebae-0TC"
# SECRETKEY_HSM_SERVER_1="W8ZiN1o2tNkb1svNlj5Kl8PNohhujaTxeNaGEq2rOWY="
# JEPANG
# URL_HSM_SERVER_1="wss://gateway04.cyberware.co.jp/feliqserver/v1/wsapi"
# APIKEY_HSM_SERVER_1="4c6dd075-dbcb-375f-81f7-62990a5d7000-0TC"
# SECRETKEY_HSM_SERVER_1="U5xs7nVonhtbQ+XiYATRSg8Nk5sPu1IpVx7X40KyWiw="
# URL_HSM_SERVER_2="wss://gateway04.cyberware.co.jp/feliqserver/v1/wsapi"
# APIKEY_HSM_SERVER_2="4c6dd075-dbcb-375f-81f7-62990a5d7000-0TC"
# SECRETKEY_HSM_SERVER_2="U5xs7nVonhtbQ+XiYATRSg8Nk5sPu1IpVx7X40KyWiw="
# HSM DRC (DISASTER RECOVERY CENTER)
# HSM SERVER
# URL_HSM_SERVER_BACKUP_1="ws://10.1.201.215/feliqserver/v1/wsapi"
# APIKEY_HSM_SERVER_BACKUP_1="d54ff5c4-9709-3bac-9a6e-04b2f4deebae-0TC"
# SECRETKEY_HSM_SERVER_BACKUP_1="W8ZiN1o2tNkb1svNlj5Kl8PNohhujaTxeNaGEq2rOWY="
# JEPANG
# URL_HSM_SERVER_BACKUP_2="wss://gateway04.cyberware.co.jp/feliqserver/v1/wsapi"
# APIKEY_HSM_SERVER_BACKUP_2="4c6dd075-dbcb-375f-81f7-62990a5d7000-0TC"
# SECRETKEY_HSM_SERVER_BACKUP_2="U5xs7nVonhtbQ+XiYATRSg8Nk5sPu1IpVx7X40KyWiw="
+16 -14
View File
@@ -1,33 +1,35 @@
require("dotenv").config(); require('dotenv').config();
const winston = require("./application/helpers/winston.logger"); const winston = require('./application/helpers/winston.logger');
const server = require("./server"); const server = require('./server');
// set port, listen for requests // set port, listen for requests
const PORT = process.env.PORT || 3000; const PORT = process.env.PORT || 3000;
var serverHSMStatus = "HSM SERVER NOT CONNECTED"; var serverHSMStatus = 'HSM SERVER NOT CONNECTED';
if (process.env.NUMBER_SERVER_ACTIVE == "1") { if (process.env.NUMBER_SERVER_ACTIVE == '1') {
serverHSMStatus = `SERVER 1 CONNECTED on ip ${process.env.IP_HSM_SERVER_1}`; serverHSMStatus = `SERVER 1 CONNECTED on ip ${process.env.IP_HSM_SERVER_1}`;
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") { } else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
serverHSMStatus = `SERVER 2 CONNECTED on ip ${process.env.IP_HSM_SERVER_2}`; serverHSMStatus = `SERVER 2 CONNECTED on ip ${process.env.IP_HSM_SERVER_2}`;
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") { } else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
serverHSMStatus = `SERVER 1 on ip ${process.env.IP_HSM_SERVER_1} AND SERVER 2 on ip ${process.env.IP_HSM_SERVER_2} CONNECTED`; serverHSMStatus = `SERVER 1 on ip ${process.env.IP_HSM_SERVER_1} AND SERVER 2 on ip ${process.env.IP_HSM_SERVER_2} CONNECTED`;
} }
var serverActive = "DC (DATA CENTER)"; var serverActive = 'DC (DATA CENTER)';
if (process.env.CHANGE_TO_DRC == "YES" || process.env.CHANGE_TO_DRC == "yes") { if (process.env.CHANGE_TO_DRC == 'YES' || process.env.CHANGE_TO_DRC == 'yes') {
serverActive = "DRC (DISASTER RECOVERY CENTER)"; serverActive = 'DRC (DISASTER RECOVERY CENTER)';
if (process.env.NUMBER_SERVER_ACTIVE == "1") { if (process.env.NUMBER_SERVER_ACTIVE == '1') {
serverHSMStatus = `SERVER 1 CONNECTED on ip ${process.env.IP_HSM_SERVER_BACKUP_1}`; serverHSMStatus = `SERVER 1 CONNECTED on ip ${process.env.IP_HSM_SERVER_BACKUP_1}`;
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") { } else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
serverHSMStatus = `SERVER 2 CONNECTED on ip ${process.env.IP_HSM_SERVER_BACKUP_2}`; serverHSMStatus = `SERVER 2 CONNECTED on ip ${process.env.IP_HSM_SERVER_BACKUP_2}`;
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") { } else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
serverHSMStatus = `SERVER 1 on ip ${process.env.IP_HSM_SERVER_BACKUP_1} AND SERVER 2 on ip ${process.env.IP_HSM_SERVER_BACKUP_2} CONNECTED`; serverHSMStatus = `SERVER 1 on ip ${process.env.IP_HSM_SERVER_BACKUP_1} AND SERVER 2 on ip ${process.env.IP_HSM_SERVER_BACKUP_2} CONNECTED`;
} }
} }
server.listen(PORT, () => { server.listen(PORT, () => {
winston.logger.info( winston.logger.info(
`Server is running on environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} ` `Server is running on version ${
process.env.VERSION
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `
); );
}); });
+5 -2
View File
@@ -21,14 +21,17 @@ const { logger } = require('../application/helpers/getbodyrequest');
const client = require('prom-client'); const client = require('prom-client');
const register = new client.Registry(); const register = new client.Registry();
const { const {
topuponline_metrics, topuponline_metrics, topuponline_metrics_response_time,topuponline_metrics_load_balance
} = require('../application/helpers/prometheusmetrics'); } = require('../application/helpers/prometheusmetrics');
const app = express(); const app = express();
register.setDefaultLabels({ app: 'topuponline' }); let promApp = process.env.PROM_APP || "topuponline";
register.setDefaultLabels({ app: promApp });
client.collectDefaultMetrics({ register }); client.collectDefaultMetrics({ register });
register.registerMetric(topuponline_metrics); register.registerMetric(topuponline_metrics);
register.registerMetric(topuponline_metrics_response_time);
register.registerMetric(topuponline_metrics_load_balance);
app.get('/metrics', (req, res) => { app.get('/metrics', (req, res) => {
res.setHeader('Content-Type', register.contentType); res.setHeader('Content-Type', register.contentType);