mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 11:36:27 +00:00
Compare commits
77 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 481858117d | |||
| 1fd9940706 | |||
| 5d8f4d086e | |||
| 409fe6f0ce | |||
| d0e3fb289e | |||
| fc28f4e767 | |||
| 4f69c84b5f | |||
| 44f81586e3 | |||
| e51a7bc98c | |||
| af52b6916b | |||
| ad0942a93d | |||
| 4828a230fb | |||
| 933e83cd1a | |||
| 97860df622 | |||
| 40bd4b97e2 | |||
| 59d77f838f | |||
| 91f759e994 | |||
| 2130890909 | |||
| edc1f35e8b | |||
| ceb17a5999 | |||
| de01a058eb | |||
| 23ed7baf76 | |||
| 98c9fbe577 | |||
| dcea11420b | |||
| ff84e687ed | |||
| 2c132afdb1 | |||
| 6df951da14 | |||
| d3d28e496f | |||
| 11b5d2317c | |||
| fb5565f399 | |||
| 0df4fc0091 | |||
| 05c69b0e1d | |||
| 7ca95e17c0 | |||
| b07e9eda89 | |||
| 920284f07d | |||
| f97c9e6c66 | |||
| c885c49925 | |||
| 04128c8b86 | |||
| 663b92c759 | |||
| ff1582e50d | |||
| 0b921f3dc6 | |||
| ee9fa58b94 | |||
| 625ad19907 | |||
| f1e659c64a | |||
| df7d6909a3 | |||
| c5b75058d3 | |||
| 18cab4b93b | |||
| 40990b3498 | |||
| fa43d34c90 | |||
| 5a0d579405 | |||
| 8e9f9dca82 | |||
| c8755f9e2d | |||
| f2e6b31b82 | |||
| 751191e10e | |||
| 33039fab21 | |||
| 2c31a4e425 | |||
| b5b72ecf6c | |||
| b7e5d0c426 | |||
| 82bd1c5276 | |||
| c39675b1ac | |||
| 146e64fc63 | |||
| 058cd6edfc | |||
| 3fb2124534 | |||
| c4f276289a | |||
| f8aacae0ea | |||
| 0e237bd66d | |||
| 8e8704a1a2 | |||
| 25c3d03761 | |||
| 3be8c88db4 | |||
| 983902d08e | |||
| 7a09320404 | |||
| ff245148f6 | |||
| 5a4870408c | |||
| e3ef16753e | |||
| 90aaf3f6f6 | |||
| 0437eaab25 | |||
| 4a98a1c5cd |
@@ -3,6 +3,13 @@ require("winston-daily-rotate-file");
|
||||
const expressWinston = require("express-winston");
|
||||
const fs = require("fs");
|
||||
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 = () => {
|
||||
if (!fs.existsSync(`./expresswinstonlog`)) {
|
||||
@@ -28,6 +35,20 @@ const 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 = {
|
||||
response: expressWinston.logger({
|
||||
transports: [
|
||||
@@ -35,13 +56,12 @@ const logger = {
|
||||
filename: "./expresswinstonlog/%DATE%.log",
|
||||
frequency: "24h",
|
||||
datePattern: "YYYY/MM/DD",
|
||||
zippedArchive: true,
|
||||
maxFiles: "1d",
|
||||
}),
|
||||
],
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.printf((info) => {
|
||||
winston.format.printf(async (info) => {
|
||||
let body = {};
|
||||
body.id = info.meta.req.id;
|
||||
body.tag = "RES";
|
||||
@@ -51,16 +71,192 @@ const logger = {
|
||||
body.time = moment().format();
|
||||
body.responseTime = `${info.meta.responseTime} ms`;
|
||||
|
||||
var header_auth = info.meta.req.headers["authorization"];
|
||||
var issuer_name = "Web"
|
||||
if (!issuer_name)
|
||||
return `[${moment().format()}] | ${JSON.stringify(body)}`;
|
||||
let issuerName;
|
||||
|
||||
let partnerId = info.meta.req.partner_id_token;
|
||||
|
||||
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)}`;
|
||||
})
|
||||
),
|
||||
skip: (req, res) => {
|
||||
return routes.indexOf(req.originalUrl) === -1;
|
||||
},
|
||||
responseWhitelist: [...expressWinston.responseWhitelist, "body"],
|
||||
requestWhitelist: [...expressWinston.requestWhitelist, "body", "id", "ip"],
|
||||
requestWhitelist: [
|
||||
...expressWinston.requestWhitelist,
|
||||
"body",
|
||||
"id",
|
||||
"ip",
|
||||
"partner_id_token",
|
||||
],
|
||||
}),
|
||||
request: expressWinston.logger({
|
||||
transports: [
|
||||
@@ -68,7 +264,6 @@ const logger = {
|
||||
filename: "./expresswinstonlog/%DATE%.log",
|
||||
frequency: "24h",
|
||||
datePattern: "YYYY/MM/DD",
|
||||
zippedArchive: true,
|
||||
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 };
|
||||
|
||||
@@ -31,8 +31,8 @@ const createHMAC = async (payload) => {
|
||||
|
||||
// RANDOM UNIQUE CODE
|
||||
function getUniqueCode() {
|
||||
const maxDate = Date.now();
|
||||
const timestamp = Math.floor(Math.random() * maxDate).toString();
|
||||
let maxDate = Date.now();
|
||||
let timestamp = Math.floor(Math.random() * maxDate).toString();
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ function getRandomArbitrary(min, max) {
|
||||
}
|
||||
|
||||
function randomNumberInt() {
|
||||
const result = [];
|
||||
let result = [];
|
||||
while (result.length !== 3) {
|
||||
let random = getRandomArbitrary(0, 9);
|
||||
if (!result.includes(random)) result.push(random);
|
||||
@@ -181,9 +181,9 @@ function generateXMLRequest(urn, headers, items) {
|
||||
// POSTING SAP
|
||||
async function postingSAP(url, body, credential) {
|
||||
try {
|
||||
const axios = require('axios');
|
||||
let axios = require('axios');
|
||||
|
||||
const config = {
|
||||
let config = {
|
||||
headers: {
|
||||
'Content-Type': 'text/xml',
|
||||
responseType: 'text',
|
||||
@@ -194,7 +194,7 @@ async function postingSAP(url, body, credential) {
|
||||
},
|
||||
};
|
||||
|
||||
const resp = await axios.post(url, body, config);
|
||||
let resp = await axios.post(url, body, config);
|
||||
|
||||
return {
|
||||
status: resp.status,
|
||||
@@ -238,7 +238,7 @@ async function postingSAP(url, body, credential) {
|
||||
|
||||
// GET SOAP RESPONSE DATA
|
||||
function getXMLData(response) {
|
||||
const xml2js = require('xml2js');
|
||||
let xml2js = require('xml2js');
|
||||
// console.log(xmlString)
|
||||
let resSAP = {
|
||||
type: '',
|
||||
@@ -251,7 +251,7 @@ function getXMLData(response) {
|
||||
};
|
||||
|
||||
if (response.status == 200) {
|
||||
const options = {
|
||||
let options = {
|
||||
explicitArray: false,
|
||||
tagNameProcessors: [xml2js.processors.stripPrefix],
|
||||
};
|
||||
@@ -293,7 +293,7 @@ function getXMLData(response) {
|
||||
resSAP.type =
|
||||
soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][0]['TYPE'];
|
||||
|
||||
const indexMessage =
|
||||
let indexMessage =
|
||||
soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'].length - 1;
|
||||
let message =
|
||||
'[SAP] ' +
|
||||
|
||||
@@ -4,6 +4,7 @@ const loki = require("winston-loki");
|
||||
require("winston-daily-rotate-file");
|
||||
require("dotenv").config();
|
||||
const { combine, timestamp, printf, colorize, align, json } = winston.format;
|
||||
let lokiUrl = process.env.LOKI_URL;
|
||||
|
||||
const logLevels = {
|
||||
fatal: 0,
|
||||
@@ -41,7 +42,7 @@ if (
|
||||
defaultMeta: { service: "topuponline" },
|
||||
transports: [
|
||||
new loki({
|
||||
host: "http://localhost:3100",
|
||||
host: lokiUrl,
|
||||
labels: { app: "topuponline" },
|
||||
json: true,
|
||||
format: json(),
|
||||
@@ -57,7 +58,7 @@ if (
|
||||
log = winston.createLogger({
|
||||
transports: [
|
||||
new loki({
|
||||
host: "http://localhost:3100",
|
||||
host: lokiUrl,
|
||||
labels: { app: "topuponline" },
|
||||
handleExceptions: true,
|
||||
handleRejections: true,
|
||||
|
||||
@@ -3,12 +3,39 @@ const client = require("prom-client");
|
||||
const topuponline_metrics = new client.Histogram({
|
||||
name: "topuponline",
|
||||
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: [
|
||||
"route",
|
||||
"status_code",
|
||||
"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 };
|
||||
@@ -13,13 +13,23 @@ let redisClient;
|
||||
password: '',
|
||||
});
|
||||
|
||||
redisClient.on('error', (error) => console.error(`Error : ${error}`));
|
||||
redisClient.on('error', (error) =>
|
||||
// process.env.NODE_ENV.toUpperCase() != 'PRODUCTION'
|
||||
// ? console.error(`Error : ${error}`)
|
||||
// : ''
|
||||
process.env.NODE_ENV.toUpperCase() != 'PRODUCTION' ? '' : ''
|
||||
);
|
||||
|
||||
redisClient.on('connect', () => console.log('Redis is Connected'));
|
||||
|
||||
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')
|
||||
// : ''
|
||||
process.env.NODE_ENV.toUpperCase() != 'PRODUCTION' ? '' : ''
|
||||
);
|
||||
|
||||
await redisClient.connect();
|
||||
})();
|
||||
@@ -111,8 +121,71 @@ const setReservationNumberSequence = async (partner_id, sequence) => {
|
||||
}
|
||||
};
|
||||
|
||||
const getLoadBalanceNumberSequence = async (req, res, next) => {
|
||||
// set default load_balance_number_sequence dari partner apapun is null
|
||||
req.load_balance_number_sequence = null;
|
||||
|
||||
// cek jika redis is connect
|
||||
let isRedisReady = await redisClient.isReady;
|
||||
// jika tidak connect
|
||||
if (isRedisReady) {
|
||||
// jika connect maka cari sequence dari reservation number sesuai partner yg merequest
|
||||
// format value nya harusnya seperti ini = { date: '2023-01-01', sequence: 1 }
|
||||
// data req.partner_id_token di dapat dari authenticateToken di jwt middleware
|
||||
let getValue = await redisClient.GET(
|
||||
'load_balance_number_sequence_' + req.partner_id_token
|
||||
);
|
||||
|
||||
if (getValue) {
|
||||
// parsing data menjadi json format
|
||||
let parsedValue = JSON.parse(getValue);
|
||||
|
||||
// cek apakah tanggal sequence yang di redis sama dengan hari ini atau bukan
|
||||
if (parsedValue.date == moment().format('YYYY-MM-DD')) {
|
||||
// jika tanggal nya sama dengan hari ini maka ambil sequence untuk reservation number yang di generate dari redis
|
||||
req.load_balance_number_sequence = parseInt(parsedValue.sequence);
|
||||
|
||||
// langsung update sequence walaupun transaksi insert nya belum selesai
|
||||
// impact menggunakan redis, untuk nomor sequence bisa saja ada yg loncat karena bisa saja ada transaksi insert reservation yang gagal
|
||||
let setValue = {
|
||||
date: moment().format('YYYY-MM-DD'),
|
||||
sequence: parseInt(parsedValue.sequence) + 1,
|
||||
};
|
||||
|
||||
await redisClient.SET(
|
||||
`load_balance_number_sequence_${req.partner_id_token}`,
|
||||
JSON.stringify(setValue)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
next();
|
||||
};
|
||||
|
||||
const setLoadBalanceNumberSequence = async (partner_id, sequence) => {
|
||||
// cek jika redis is connect
|
||||
let isRedisReady = await redisClient.isReady;
|
||||
// jika tidak connect
|
||||
if (isRedisReady) {
|
||||
// jika connect maka cari sequence dari reservation number sesuai partner yg merequest
|
||||
// format value nya harusnya seperti ini = { date: '2023-01-01', sequence: 1 }
|
||||
|
||||
let setValue = {
|
||||
date: moment().format('YYYY-MM-DD'),
|
||||
sequence: parseInt(sequence),
|
||||
};
|
||||
|
||||
await redisClient.SET(
|
||||
`load_balance_number_sequence_${partner_id}`,
|
||||
JSON.stringify(setValue)
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
redisMiddleware,
|
||||
getReservationNumberSequence,
|
||||
setReservationNumberSequence,
|
||||
getLoadBalanceNumberSequence,
|
||||
setLoadBalanceNumberSequence,
|
||||
};
|
||||
|
||||
@@ -76,13 +76,13 @@ const loginPartnerUser = async (req, res, next) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST LOGIN-PARTNER-USER ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
`${uniqueCode} [ REQUEST LOGIN-PARTNER-USER ]: ${JSON.stringify({
|
||||
email: email,
|
||||
})}`
|
||||
);
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
let err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -239,11 +239,14 @@ const loginTerminal = async (req, res, next) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST LOGIN-TERMINAL ]: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOGIN-TERMINAL ]: ${JSON.stringify({
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
})}`
|
||||
);
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
let err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -410,11 +413,14 @@ const register = async (req, res) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST REGISTER ]: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST REGISTER ]: ${JSON.stringify({
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
})}`
|
||||
);
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
let err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -482,7 +488,7 @@ const register = async (req, res) => {
|
||||
);
|
||||
|
||||
// encrypt password
|
||||
const saltRounds = 10;
|
||||
let saltRounds = 10;
|
||||
let salt = bcrypt.genSaltSync(saltRounds);
|
||||
let passwordHash = bcrypt.hashSync(password, salt);
|
||||
|
||||
@@ -549,8 +555,8 @@ const refreshTokenTerminal = async (req, res) => {
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
const { mid, tid } = req.body;
|
||||
const refresh_token = req.header('refresh_token');
|
||||
let { mid, tid } = req.body;
|
||||
let refresh_token = req.header('refresh_token');
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
@@ -560,7 +566,7 @@ const refreshTokenTerminal = async (req, res) => {
|
||||
);
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
let err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -695,8 +701,8 @@ const refreshTokenPartnerUser = async (req, res) => {
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
const { email } = req.body;
|
||||
const refresh_token = req.header('refresh_token');
|
||||
let { email } = req.body;
|
||||
let refresh_token = req.header('refresh_token');
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
@@ -706,7 +712,7 @@ const refreshTokenPartnerUser = async (req, res) => {
|
||||
);
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
let err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
const helper = require("../../helpers/helper");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const model = require("./dongleorder.model");
|
||||
const moment = require("moment");
|
||||
moment.locale("id");
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./dongleorder.model');
|
||||
const moment = require('moment');
|
||||
moment.locale('id');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "dongleOrderUpdate":
|
||||
case 'dongleOrderUpdate':
|
||||
return [
|
||||
body("dongle_id").not().isEmpty().withMessage("Dongle ID is required"),
|
||||
body('dongle_id').not().isEmpty().withMessage('Dongle ID is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
@@ -20,12 +20,11 @@ const validate = (method) => {
|
||||
// GET DONGLE ORDER
|
||||
const getDongleOrder = async (req, res) => {
|
||||
try {
|
||||
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
// param
|
||||
let year = req.query.year;
|
||||
let year = req.query.year;
|
||||
|
||||
if (!year) {
|
||||
year = moment().format('YYYY');
|
||||
@@ -34,11 +33,11 @@ const getDongleOrder = async (req, res) => {
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} get RO...`);
|
||||
|
||||
// get RO
|
||||
// get RO
|
||||
let getRO = await model.getRO(year);
|
||||
if (getRO.length == 0) {
|
||||
result = {
|
||||
code: "422",
|
||||
code: '422',
|
||||
message: "data doesn't exists'",
|
||||
data: [],
|
||||
};
|
||||
@@ -54,14 +53,16 @@ const getDongleOrder = async (req, res) => {
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "success",
|
||||
code: '00',
|
||||
message: 'success',
|
||||
data: getRO,
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} RESPONSE get RO and dongle order: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} RESPONSE get RO and dongle order: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.json(result);
|
||||
@@ -72,11 +73,11 @@ const getDongleOrder = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
@@ -86,9 +87,7 @@ const getDongleOrder = async (req, res) => {
|
||||
const updateDongleOrder = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let {
|
||||
dongle_id, status
|
||||
} = req.body;
|
||||
let { dongle_id, status } = req.body;
|
||||
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
@@ -99,10 +98,10 @@ const updateDongleOrder = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: "400",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
@@ -116,39 +115,40 @@ const updateDongleOrder = async (req, res) => {
|
||||
}
|
||||
|
||||
// time
|
||||
let now = moment().format("YYYY-MM-DD HH:mm:ss");
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} updating dongle order...`);
|
||||
|
||||
let data = {
|
||||
c_status: status == "C" ? "C" : "I",
|
||||
c_status_name: status == "C" ? "CREATED" : "INJECTED",
|
||||
c_status: status == 'C' ? 'C' : 'I',
|
||||
c_status_name: status == 'C' ? 'CREATED' : 'INJECTED',
|
||||
d_modify: now,
|
||||
}
|
||||
};
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let updateDongleOrderStatus = await model.updateDongleOrderStatus(data, dongle_id);
|
||||
let updateDongleOrderStatus = await model.updateDongleOrderStatus(
|
||||
data,
|
||||
dongle_id
|
||||
);
|
||||
if (!updateDongleOrderStatus) {
|
||||
result = {
|
||||
code: "423",
|
||||
message: "update failed",
|
||||
code: '423',
|
||||
message: 'update failed',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE update dongle order: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
`${uniqueCode} RESPONSE update dongle order: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "updated successfully",
|
||||
code: '00',
|
||||
message: 'updated successfully',
|
||||
data: {},
|
||||
};
|
||||
|
||||
@@ -165,11 +165,11 @@ const updateDongleOrder = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ const cardHistory = async (req, res) => {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
let result = [];
|
||||
|
||||
// param
|
||||
let { data } = req.body;
|
||||
@@ -53,12 +53,12 @@ const cardHistory = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
data: [],
|
||||
};
|
||||
|
||||
// log warn
|
||||
@@ -178,7 +178,7 @@ const cardHistory = async (req, res) => {
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -206,7 +206,7 @@ const history = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
|
||||
@@ -1,24 +1,24 @@
|
||||
const helper = require("../../helpers/helper");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
var counterDirect = 0;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -31,11 +31,11 @@ const controller = async (req, res) => {
|
||||
let { body } = req;
|
||||
// uniqueCode = body.unique_code;
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
uniqueCode = uniqueCode+''+counterDirect;
|
||||
uniqueCode = uniqueCode + '' + counterDirect;
|
||||
let result = {};
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -74,11 +74,15 @@ const controller = async (req, res) => {
|
||||
}
|
||||
|
||||
// log info
|
||||
winston.logger.info(`${uniqueCode} REQUEST load balance - STARTING...`);
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-1 ]: STARTING TOP UP...`
|
||||
);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - auth1v2: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-1 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
let felicaPollingResponse = Buffer.from(
|
||||
@@ -107,7 +111,7 @@ const controller = async (req, res) => {
|
||||
_timeOut = true;
|
||||
}, 10000);
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14, 30);
|
||||
while (
|
||||
message[2] == 1 &&
|
||||
@@ -119,7 +123,9 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message Auth1v2: ${generate.buf2hex(message)}`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-1 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
@@ -155,8 +161,8 @@ const controller = async (req, res) => {
|
||||
|
||||
if (respData1) {
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Request Authenticate 1 Success",
|
||||
code: '00',
|
||||
message: 'Request Authenticate 1 Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -167,8 +173,8 @@ const controller = async (req, res) => {
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: "5004",
|
||||
message: "Empty Data from HSM",
|
||||
code: '5004',
|
||||
message: 'Empty Data from HSM',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -181,22 +187,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - auth1v2: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-1 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-1 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -27,11 +27,13 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - auth2v2: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-2 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -57,17 +59,20 @@ const controller = async (req, res) => {
|
||||
let _validationTrxID = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
let _timeOut = false;
|
||||
|
||||
if (auth2v2requestData[0] != 0x41) {
|
||||
result = {
|
||||
code: "5003",
|
||||
message: "Wrong Respone from Card",
|
||||
code: '5003',
|
||||
message: 'Wrong Respone from Card',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} response HSM - auth2v2: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
@@ -84,7 +89,13 @@ const controller = async (req, res) => {
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
useClient.ws.on("message", (message) => {
|
||||
|
||||
setInterval(function () {
|
||||
respData = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
|
||||
_timeOut = true;
|
||||
}, 10000);
|
||||
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 2 &&
|
||||
message[0] == _validationTrxID[0] &&
|
||||
@@ -96,7 +107,9 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message Auth2v2: ${generate.buf2hex(message)}`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-2 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
@@ -108,6 +121,23 @@ const controller = async (req, res) => {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
if (_timeOut) {
|
||||
result = {
|
||||
code: '5001',
|
||||
message: 'Timeout',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-2 ]: message from HSM ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
@@ -116,8 +146,8 @@ const controller = async (req, res) => {
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Request Authenticate 2 Success",
|
||||
code: '00',
|
||||
message: 'Request Authenticate 2 Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -128,22 +158,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - auth2v2: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-2 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -27,11 +27,13 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request auth2v2 Resp: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-3 ]: request to HSM ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -62,14 +64,16 @@ const controller = async (req, res) => {
|
||||
|
||||
if (auth2v2responseSetData[0] != 0x43) {
|
||||
result = {
|
||||
code: "5003",
|
||||
message: "Wrong Respone from Card",
|
||||
code: '5003',
|
||||
message: 'Wrong Respone from Card',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} response HSM - auth2v2 resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-3 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
@@ -87,7 +91,7 @@ const controller = async (req, res) => {
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 3 &&
|
||||
message[0] == transactionId[0] &&
|
||||
@@ -99,7 +103,7 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message auth2v2 Resp: ${generate.buf2hex(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-3 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
@@ -121,8 +125,8 @@ const controller = async (req, res) => {
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Request Authenticate Resp Success",
|
||||
code: '00',
|
||||
message: 'Request Authenticate Resp Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -133,22 +137,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - auth2v2 resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-3 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-3 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -27,11 +27,13 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - end transaction: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-8 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -70,7 +72,7 @@ const controller = async (req, res) => {
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 6 &&
|
||||
message[0] == transactionId[0] &&
|
||||
@@ -82,7 +84,7 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message end transaction: ${generate.buf2hex(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-8 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
@@ -104,35 +106,34 @@ const controller = async (req, res) => {
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "End Transaction Success",
|
||||
code: '00',
|
||||
message: 'End Transaction Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(`${uniqueCode} RESPONSE load balance - END...`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - end transaction: ${JSON.stringify(result)}`
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-8 ]: ENDING TOP UP... ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-8 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -27,11 +27,13 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - read data: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-4 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -70,7 +72,7 @@ const controller = async (req, res) => {
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 4 &&
|
||||
message[0] == transactionId[0] &&
|
||||
@@ -84,7 +86,9 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message read data: ${generate.buf2hex(message)}`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-4 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
@@ -104,8 +108,8 @@ const controller = async (req, res) => {
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Read Succeess",
|
||||
code: '00',
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -116,22 +120,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - read data: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-4 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-4 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -27,11 +27,13 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - read data resp: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-5 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -58,14 +60,16 @@ const controller = async (req, res) => {
|
||||
let _stopMessage = 1;
|
||||
if (packet[0] != 0x45) {
|
||||
result = {
|
||||
code: "03",
|
||||
message: "Respone Card Wrong",
|
||||
code: '03',
|
||||
message: 'Respone Card Wrong',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} response HSM - read data resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-5 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
@@ -79,7 +83,7 @@ const controller = async (req, res) => {
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 5 &&
|
||||
message[0] == transactionId[0] &&
|
||||
@@ -93,7 +97,7 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message read data resp: ${generate.buf2hex(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-5 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
@@ -115,8 +119,8 @@ const controller = async (req, res) => {
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Read Succeess",
|
||||
code: '00',
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -127,22 +131,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - read data resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-5 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-5 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
const WebSocket = require("ws");
|
||||
const checkInternetConnected = require("check-internet-connected");
|
||||
const winston = require("../../../helpers/winston.logger");
|
||||
const fs = require("fs");
|
||||
const WebSocket = require('ws');
|
||||
const checkInternetConnected = require('check-internet-connected');
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const fs = require('fs');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const generate = require("../utils/utils");
|
||||
require("dotenv").config();
|
||||
const generate = require('../utils/utils');
|
||||
require('dotenv').config();
|
||||
|
||||
let ssl_ca_crt = "./application/assets/cert/CACerts.pem";
|
||||
let ssl_client_pfx = "./application/assets/cert/FeliqClient0002-03.pfx";
|
||||
let ssl_ca_crt = './application/assets/cert/CACerts.pem';
|
||||
let ssl_client_pfx = './application/assets/cert/FeliqClient0002-03.pfx';
|
||||
|
||||
let options = {
|
||||
ca: fs.readFileSync(ssl_ca_crt),
|
||||
agent: false,
|
||||
passphrase: "GPqs+Uia78",
|
||||
passphrase: 'GPqs+Uia78',
|
||||
pfx: fs.readFileSync(ssl_client_pfx),
|
||||
};
|
||||
|
||||
// check config HSM
|
||||
if (
|
||||
process.env.URL_HSM_SERVER_1 == "" ||
|
||||
process.env.APIKEY_HSM_SERVER_1 == "" ||
|
||||
process.env.SECRETKEY_HSM_SERVER_1 == ""
|
||||
process.env.URL_HSM_SERVER_1 == '' ||
|
||||
process.env.APIKEY_HSM_SERVER_1 == '' ||
|
||||
process.env.SECRETKEY_HSM_SERVER_1 == ''
|
||||
) {
|
||||
// create log
|
||||
winston.logger.error(`PLEASE CONFIGURE HSM SERVER ON THE ENVIRONMENT!`);
|
||||
}
|
||||
|
||||
// check system code
|
||||
if (process.env.SYSTEM_CODE == "") {
|
||||
if (process.env.SYSTEM_CODE == '') {
|
||||
// create log
|
||||
winston.logger.error(`PLEASE CONFIGURE SYSTEM CODE ON THE ENVIRONMENT!`);
|
||||
}
|
||||
@@ -38,7 +38,7 @@ var apiKeyBytes;
|
||||
var secretBytes;
|
||||
var systemCode = Buffer.from(generate.hexToBytes(process.env.SYSTEM_CODE));
|
||||
|
||||
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') {
|
||||
// config for DRC
|
||||
url = process.env.URL_HSM_SERVER_BACKUP_1;
|
||||
apiKeyBytes = Buffer.from(process.env.APIKEY_HSM_SERVER_BACKUP_1);
|
||||
@@ -53,7 +53,7 @@ if (process.env.CHANGE_TO_DRC == "YES" || process.env.CHANGE_TO_DRC == "yes") {
|
||||
const config = {
|
||||
timeout: 1000, //timeout connecting to each server, each try
|
||||
retries: 5, //number of retries to do before failing
|
||||
domain: "https://google.com", //the domain to check DNS record of
|
||||
domain: 'https://google.com', //the domain to check DNS record of
|
||||
};
|
||||
|
||||
var interval;
|
||||
@@ -62,16 +62,16 @@ function startInterval() {
|
||||
interval = setInterval(function () {
|
||||
checkInternetConnected(config)
|
||||
.then((result) => {
|
||||
// console.log(result); //successfully connected to a server
|
||||
console.log(`retry open websocket server 1`); //successfully connected to a server
|
||||
// log debug
|
||||
winston.logger.debug(`retry open websocket server 1`);
|
||||
// winston.logger.debug(`retry open websocket server 1`);
|
||||
client.open();
|
||||
stopInterval();
|
||||
})
|
||||
.catch((ex) => {
|
||||
// console.log(ex); // cannot connect to a server or error occurred.
|
||||
console.log(`error start interval server 1 : ${ex}`); // cannot connect to a server or error occurred.
|
||||
// log error
|
||||
winston.logger.error(`error start interval server 1 : ${ex}`);
|
||||
// winston.logger.error(`error start interval server 1 : ${ex}`);
|
||||
});
|
||||
}, 5900);
|
||||
}
|
||||
@@ -91,9 +91,9 @@ class WebSocketClient {
|
||||
if (this.ws == null) {
|
||||
this.ws = new WebSocket(url, [], options);
|
||||
|
||||
this.ws.on("open", this.onOpen);
|
||||
this.ws.on("close", this.onClose);
|
||||
this.ws.on("error", this.onError);
|
||||
this.ws.on('open', this.onOpen);
|
||||
this.ws.on('close', this.onClose);
|
||||
this.ws.on('error', this.onError);
|
||||
|
||||
this.ws.setMaxListeners(0);
|
||||
}
|
||||
@@ -106,37 +106,41 @@ class WebSocketClient {
|
||||
// Disconnection of WebSocket
|
||||
close = () => {
|
||||
this.ws.close();
|
||||
// console.log('WebSocket Close');
|
||||
console.log(`websocket server 1 close`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 1 close`);
|
||||
// winston.logger.debug(`websocket server 1 close`);
|
||||
};
|
||||
|
||||
// Open event
|
||||
onOpen = () => {
|
||||
// console.log("WebSocket Open");
|
||||
console.log(`opening websocket server 1`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`opening websocket server 1`);
|
||||
// winston.logger.debug(`opening websocket server 1`);
|
||||
|
||||
if (this.isOpened()) {
|
||||
console.log(`websocket server 1 open successfully`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 1 open successfully`);
|
||||
// winston.logger.debug(`websocket server 1 open successfully`);
|
||||
|
||||
if (!this.clientAuthenticated) {
|
||||
this.clientAuth();
|
||||
}
|
||||
} else {
|
||||
console.log(`websocket server 1 open failed`);
|
||||
|
||||
// log error
|
||||
winston.logger.error(`websocket server 1 open failed`);
|
||||
// winston.logger.error(`websocket server 1 open failed`);
|
||||
}
|
||||
};
|
||||
|
||||
onClose = () => {
|
||||
// console.log("WebSocket Close");
|
||||
console.log(`websocket server 1 close`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 1 close`);
|
||||
// winston.logger.debug(`websocket server 1 close`);
|
||||
|
||||
this.clientAuthenticated = false;
|
||||
this.ws = null;
|
||||
@@ -144,10 +148,10 @@ class WebSocketClient {
|
||||
};
|
||||
|
||||
onError = () => {
|
||||
// console.log("WebSocket Error");
|
||||
console.log(`websocket server 1 error`);
|
||||
|
||||
// log error
|
||||
winston.logger.error(`websocket server 1 error`);
|
||||
// winston.logger.error(`websocket server 1 error`);
|
||||
|
||||
this.clientAuthenticated = false;
|
||||
};
|
||||
@@ -196,7 +200,7 @@ class WebSocketClient {
|
||||
|
||||
this.sendData(reqData);
|
||||
|
||||
this.ws.on("message", (message) => {
|
||||
this.ws.on('message', (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14, 30);
|
||||
while (
|
||||
message[2] == 0 &&
|
||||
@@ -205,13 +209,15 @@ class WebSocketClient {
|
||||
message[1] == 0
|
||||
) {
|
||||
respData = null;
|
||||
// console.log("*WS MESSAGE Tenan: " + generate.buf2hex(message));
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
console.log(
|
||||
`websocket server 1 message tenant: ${generate.buf2hex(message)}`
|
||||
);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `websocket server 1 message tenant: ${generate.buf2hex(message)}`
|
||||
// );
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
@@ -221,30 +227,36 @@ class WebSocketClient {
|
||||
await _sleep(10);
|
||||
}
|
||||
let respCode = generate.getResponseCode(respData);
|
||||
// console.log(`Resp Data Tenant = ${respCode}`);
|
||||
console.log(`websocket server 1 resp data tenant: ${respCode}`);
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 1 resp data tenant: ${respCode}`);
|
||||
// winston.logger.debug(`websocket server 1 resp data tenant: ${respCode}`);
|
||||
|
||||
if (respCode == "0000" || respCode == "0502") {
|
||||
if (respCode == '0000' || respCode == '0502') {
|
||||
this.clientAuthenticated = true;
|
||||
}
|
||||
// console.log(`clientAuthenticated = ${this.clientAuthenticated}`);
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
console.log(
|
||||
`websocket server 1 client authenticate: ${this.clientAuthenticated}`
|
||||
);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `websocket server 1 client authenticate: ${this.clientAuthenticated}`
|
||||
// );
|
||||
} catch (error) {
|
||||
// console.log(`error ${error}`);
|
||||
console.log(`websocket error: ${error}`);
|
||||
|
||||
// log error
|
||||
winston.logger.error(`websocket error: ${error}`);
|
||||
// winston.logger.error(`websocket error: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var client = new WebSocketClient();
|
||||
if (!client.openWebSocketStatus) {
|
||||
console.log(`first open websocket server 1`);
|
||||
|
||||
// log info
|
||||
winston.logger.info(`first open websocket server 1`);
|
||||
// winston.logger.info(`first open websocket server 1`);
|
||||
client.open();
|
||||
}
|
||||
|
||||
@@ -252,6 +264,8 @@ setInterval(function () {
|
||||
// let statusConnection = client.clientAuthenticated;
|
||||
// if (!statusConnection) {
|
||||
if (!this.ws) {
|
||||
console.log(`websocket server 1 retry call client Auth`);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(`retry call client Auth`);
|
||||
client.clientAuth();
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
const WebSocket = require("ws");
|
||||
const checkInternetConnected = require("check-internet-connected");
|
||||
const winston = require("../../../helpers/winston.logger");
|
||||
const fs = require("fs");
|
||||
const WebSocket = require('ws');
|
||||
const checkInternetConnected = require('check-internet-connected');
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const fs = require('fs');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const generate = require("../utils/utils");
|
||||
require("dotenv").config();
|
||||
const generate = require('../utils/utils');
|
||||
require('dotenv').config();
|
||||
|
||||
let ssl_ca_crt = "./application/assets/cert/CACerts.pem";
|
||||
let ssl_client_pfx = "./application/assets/cert/FeliqClient0002-03.pfx";
|
||||
let ssl_ca_crt = './application/assets/cert/CACerts.pem';
|
||||
let ssl_client_pfx = './application/assets/cert/FeliqClient0002-03.pfx';
|
||||
|
||||
let options = {
|
||||
ca: fs.readFileSync(ssl_ca_crt),
|
||||
agent: false,
|
||||
passphrase: "GPqs+Uia78",
|
||||
passphrase: 'GPqs+Uia78',
|
||||
pfx: fs.readFileSync(ssl_client_pfx),
|
||||
};
|
||||
|
||||
// check config HSM
|
||||
if (
|
||||
process.env.URL_HSM_SERVER_2 == "" ||
|
||||
process.env.APIKEY_HSM_SERVER_2 == "" ||
|
||||
process.env.SECRETKEY_HSM_SERVER_2 == ""
|
||||
process.env.URL_HSM_SERVER_2 == '' ||
|
||||
process.env.APIKEY_HSM_SERVER_2 == '' ||
|
||||
process.env.SECRETKEY_HSM_SERVER_2 == ''
|
||||
) {
|
||||
// create log
|
||||
winston.logger.error(`PLEASE CONFIGURE HSM SERVER ON THE ENVIRONMENT!`);
|
||||
}
|
||||
|
||||
// check system code
|
||||
if (process.env.SYSTEM_CODE == "") {
|
||||
if (process.env.SYSTEM_CODE == '') {
|
||||
// create log
|
||||
winston.logger.error(`PLEASE CONFIGURE SYSTEM CODE ON THE ENVIRONMENT!`);
|
||||
}
|
||||
@@ -38,7 +38,7 @@ var apiKeyBytes;
|
||||
var secretBytes;
|
||||
var systemCode = Buffer.from(generate.hexToBytes(process.env.SYSTEM_CODE));
|
||||
|
||||
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') {
|
||||
// config for DRC
|
||||
url = process.env.URL_HSM_SERVER_BACKUP_2;
|
||||
apiKeyBytes = Buffer.from(process.env.APIKEY_HSM_SERVER_BACKUP_2);
|
||||
@@ -53,7 +53,7 @@ if (process.env.CHANGE_TO_DRC == "YES" || process.env.CHANGE_TO_DRC == "yes") {
|
||||
const config = {
|
||||
timeout: 1000, //timeout connecting to each server, each try
|
||||
retries: 5, //number of retries to do before failing
|
||||
domain: "https://google.com", //the domain to check DNS record of
|
||||
domain: 'https://google.com', //the domain to check DNS record of
|
||||
};
|
||||
|
||||
var interval;
|
||||
@@ -62,16 +62,17 @@ function startInterval() {
|
||||
interval = setInterval(function () {
|
||||
checkInternetConnected(config)
|
||||
.then((result) => {
|
||||
// console.log(result); //successfully connected to a server
|
||||
console.log(`retry open websocket server 2`); //successfully connected to a server
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`retry open websocket server 2`);
|
||||
// winston.logger.debug(`retry open websocket server 2`);
|
||||
client2.open();
|
||||
stopInterval();
|
||||
})
|
||||
.catch((ex) => {
|
||||
// console.log(ex); // cannot connect to a server or error occurred.
|
||||
console.log(`error start interval server 2 : ${ex}`); // cannot connect to a server or error occurred.
|
||||
// log error
|
||||
winston.logger.error(`error start interval server 2 : ${ex}`);
|
||||
// winston.logger.error(`error start interval server 2 : ${ex}`);
|
||||
});
|
||||
}, 5900);
|
||||
}
|
||||
@@ -91,9 +92,9 @@ class WebSocketClient {
|
||||
if (this.ws == null) {
|
||||
this.ws = new WebSocket(url, [], options);
|
||||
|
||||
this.ws.on("open", this.onOpen);
|
||||
this.ws.on("close", this.onClose);
|
||||
this.ws.on("error", this.onError);
|
||||
this.ws.on('open', this.onOpen);
|
||||
this.ws.on('close', this.onClose);
|
||||
this.ws.on('error', this.onError);
|
||||
|
||||
this.ws.setMaxListeners(0);
|
||||
}
|
||||
@@ -106,37 +107,41 @@ class WebSocketClient {
|
||||
// Disconnection of WebSocket
|
||||
close = () => {
|
||||
this.ws.close();
|
||||
// console.log('WebSocket Close');
|
||||
console.log(`websocket server 2 close`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 2 close`);
|
||||
// winston.logger.debug(`websocket server 2 close`);
|
||||
};
|
||||
|
||||
// Open event
|
||||
onOpen = () => {
|
||||
// console.log("WebSocket Open");
|
||||
console.log(`opening server 2 websocket`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`opening server 2 websocket`);
|
||||
// winston.logger.debug(`opening server 2 websocket`);
|
||||
|
||||
if (this.isOpened()) {
|
||||
console.log(`websocket server 2 open successfully`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 2 open successfully`);
|
||||
// winston.logger.debug(`websocket server 2 open successfully`);
|
||||
|
||||
if (!this.clientAuthenticated) {
|
||||
this.clientAuth();
|
||||
}
|
||||
} else {
|
||||
console.log(`websocket server 2 open failed`);
|
||||
|
||||
// log error
|
||||
winston.logger.error(`websocket server 2 open failed`);
|
||||
// winston.logger.error(`websocket server 2 open failed`);
|
||||
}
|
||||
};
|
||||
|
||||
onClose = () => {
|
||||
// console.log("WebSocket Close");
|
||||
console.log(`websocket server 2 close`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 2 close`);
|
||||
// winston.logger.debug(`websocket server 2 close`);
|
||||
|
||||
this.clientAuthenticated = false;
|
||||
this.ws = null;
|
||||
@@ -144,10 +149,10 @@ class WebSocketClient {
|
||||
};
|
||||
|
||||
onError = () => {
|
||||
// console.log("WebSocket Error");
|
||||
console.log(`websocket server 2 error`);
|
||||
|
||||
// log error
|
||||
winston.logger.error(`websocket server 2 error`);
|
||||
// winston.logger.error(`websocket server 2 error`);
|
||||
|
||||
this.clientAuthenticated = false;
|
||||
};
|
||||
@@ -196,7 +201,7 @@ class WebSocketClient {
|
||||
|
||||
this.sendData(reqData);
|
||||
|
||||
this.ws.on("message", (message) => {
|
||||
this.ws.on('message', (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14, 30);
|
||||
while (
|
||||
message[2] == 0 &&
|
||||
@@ -205,13 +210,15 @@ class WebSocketClient {
|
||||
message[1] == 0
|
||||
) {
|
||||
respData = null;
|
||||
// console.log("*WS MESSAGE Tenan: " + generate.buf2hex(message));
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
console.log(
|
||||
`websocket server 2 message tenant: ${generate.buf2hex(message)}`
|
||||
);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `websocket server 2 message tenant: ${generate.buf2hex(message)}`
|
||||
// );
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
@@ -221,30 +228,37 @@ class WebSocketClient {
|
||||
await _sleep(10);
|
||||
}
|
||||
let respCode = generate.getResponseCode(respData);
|
||||
// console.log(`Resp Data Tenant = ${respCode}`);
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 2 resp data tenant: ${respCode}`);
|
||||
console.log(`websocket server 2 resp data tenant: ${respCode}`);
|
||||
|
||||
if (respCode == "0000" || respCode == "0502") {
|
||||
// log debug
|
||||
// winston.logger.debug(`websocket server 2 resp data tenant: ${respCode}`);
|
||||
|
||||
if (respCode == '0000' || respCode == '0502') {
|
||||
this.clientAuthenticated = true;
|
||||
}
|
||||
// console.log(`clientAuthenticated = ${this.clientAuthenticated}`);
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
console.log(
|
||||
`websocket server 2 client authenticate: ${this.clientAuthenticated}`
|
||||
);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `websocket server 2 client authenticate: ${this.clientAuthenticated}`
|
||||
// );
|
||||
} catch (error) {
|
||||
// console.log(`error ${error}`);
|
||||
console.log(`websocket server 2 error: ${error}`);
|
||||
|
||||
// log error
|
||||
winston.logger.error(`websocket server 2 error: ${error}`);
|
||||
// winston.logger.error(`websocket server 2 error: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var client2 = new WebSocketClient();
|
||||
if (!client2.openWebSocketStatus) {
|
||||
console.log(`first open websocket server 2`);
|
||||
|
||||
// log info
|
||||
winston.logger.info(`first open websocket server 2`);
|
||||
// winston.logger.info(`first open websocket server 2`);
|
||||
client2.open();
|
||||
}
|
||||
|
||||
@@ -252,6 +266,8 @@ setInterval(function () {
|
||||
// let statusConnection = client2.clientAuthenticated;
|
||||
// if (!statusConnection) {
|
||||
if (!this.ws) {
|
||||
console.log(`websocket server 2 retry call client Auth`);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(`retry call client Auth`);
|
||||
client2.clientAuth();
|
||||
|
||||
@@ -98,8 +98,15 @@ const controller = async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-6 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -109,17 +116,14 @@ const controller = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} response HSM - write topup: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-6 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - write topup: ${JSON.stringify(req.body)}`
|
||||
);
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(trxID));
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(requestData));
|
||||
let _stopMessage = 1;
|
||||
@@ -159,7 +163,7 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message write topup: ${generate.buf2hex(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-6 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
@@ -182,7 +186,7 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - inserting load balance transaction...`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-6 ]: inserting load balance transaction...`
|
||||
);
|
||||
|
||||
let data = {
|
||||
@@ -201,7 +205,7 @@ const controller = async (req, res) => {
|
||||
};
|
||||
|
||||
// insert data load balance
|
||||
let insert = await loadBalance.loadingBalanceInsert(data);
|
||||
let insert = await loadBalance.loadingBalanceInsert(req, data);
|
||||
if (insert) {
|
||||
if (insert.code == '00') {
|
||||
result = {
|
||||
@@ -232,14 +236,16 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - write topup: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-6 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-6 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
|
||||
@@ -1,55 +1,55 @@
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const loadBalance = require("../loadbalance/loadbalance.controller");
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const loadBalance = require('../loadbalance/loadbalance.controller');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "topupResponse":
|
||||
case 'topupResponse':
|
||||
return [
|
||||
body("mid").not().isEmpty().withMessage("MID is required"),
|
||||
body("tid").not().isEmpty().withMessage("TID is required"),
|
||||
body("uid").not().isEmpty().withMessage("UID is required"),
|
||||
body("flag").not().isEmpty().withMessage("Flag is required"),
|
||||
body("card_number")
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('uid').not().isEmpty().withMessage('UID is required'),
|
||||
body('flag').not().isEmpty().withMessage('Flag is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Card Number is required"),
|
||||
body("amount")
|
||||
.withMessage('Card Number is required'),
|
||||
body('amount')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Amount is required")
|
||||
.withMessage('Amount is required')
|
||||
.isNumeric()
|
||||
.withMessage("Amount is invalid format"),
|
||||
body("reservation_number")
|
||||
.withMessage('Amount is invalid format'),
|
||||
body('reservation_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Reservation Number is required")
|
||||
.withMessage('Reservation Number is required')
|
||||
.isArray()
|
||||
.withMessage("Reservation Number is invalid request format"),
|
||||
body("load_balance_number")
|
||||
.withMessage('Reservation Number is invalid request format'),
|
||||
body('load_balance_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Load Balance Number is required"),
|
||||
.withMessage('Load Balance Number is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
@@ -79,7 +79,7 @@ const controller = async (req, res) => {
|
||||
let result = {};
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -111,7 +111,9 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - topup resp: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-7 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(trxID));
|
||||
@@ -119,14 +121,16 @@ const controller = async (req, res) => {
|
||||
let _stopMessage = 1;
|
||||
if (packet[0] != 0x47) {
|
||||
result = {
|
||||
code: "03",
|
||||
message: "Respone Card Wrong",
|
||||
code: '03',
|
||||
message: 'Respone Card Wrong',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} response HSM - topup resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-7 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
@@ -140,7 +144,7 @@ const controller = async (req, res) => {
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 5 &&
|
||||
message[0] == transactionId[0] &&
|
||||
@@ -154,7 +158,9 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message topup resp: ${generate.buf2hex(message)}`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
@@ -186,7 +192,7 @@ const controller = async (req, res) => {
|
||||
amount: amount,
|
||||
reservation_number: reservation_number,
|
||||
ref_no: ref_no,
|
||||
write_status: "FW",
|
||||
write_status: 'FW',
|
||||
uid: uid,
|
||||
balance: parseInt(balance) + parseInt(amount),
|
||||
flag: parseInt(flag),
|
||||
@@ -196,23 +202,43 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - updating load balance transaction...`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: updating load balance transaction is FW...`
|
||||
);
|
||||
|
||||
// update data load balance
|
||||
await loadBalance.loadingBalanceUpdate(data);
|
||||
|
||||
result = {
|
||||
code: "5002",
|
||||
message: "failed from HSM",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respData1.slice(6, 10),
|
||||
transcode: null,
|
||||
load_balance_number: update.data.load_balance_number,
|
||||
},
|
||||
};
|
||||
let update = await loadBalance.loadingBalanceUpdate(data);
|
||||
if (update) {
|
||||
if (update.code == '00') {
|
||||
result = {
|
||||
code: '5002',
|
||||
message: 'failed from HSM',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respData1.slice(6, 10),
|
||||
transcode: null,
|
||||
load_balance_number: update.data.load_balance_number,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: update.code,
|
||||
message: update.message,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '423',
|
||||
message: 'update/insert failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// jika sudah mencapai maksimum counting flag, maka reset flag ke awal
|
||||
if (flag >= 255) {
|
||||
flag = -1;
|
||||
}
|
||||
|
||||
data = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
@@ -230,16 +256,16 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - updating load balance transaction...`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: updating load balance transaction...`
|
||||
);
|
||||
|
||||
// update data load balance
|
||||
let update = await loadBalance.loadingBalanceUpdate(data);
|
||||
if (update) {
|
||||
if (update.code == "00") {
|
||||
if (update.code == '00') {
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Topup Succeess",
|
||||
code: '00',
|
||||
message: 'Topup Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -257,8 +283,8 @@ const controller = async (req, res) => {
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: "423",
|
||||
message: "update/insert failed",
|
||||
code: '423',
|
||||
message: 'update/insert failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
@@ -266,22 +292,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message topup resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-7 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-7 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,157 +1,172 @@
|
||||
const { Buffer } = require("buffer")
|
||||
const fs = require('fs')
|
||||
const { Buffer } = require('buffer');
|
||||
const fs = require('fs');
|
||||
|
||||
// Generate request data for FeliQ Server
|
||||
function makeRequestData(transactionId, apiId, data){
|
||||
let request = Buffer.alloc(2 + 1 + 1 + data.length)
|
||||
let dataSize = Buffer.alloc(1)
|
||||
dataSize[0] = data.length
|
||||
request = Buffer.concat([transactionId, apiId, dataSize, data])
|
||||
return request;
|
||||
function makeRequestData(transactionId, apiId, data) {
|
||||
let request = Buffer.alloc(2 + 1 + 1 + data.length);
|
||||
let dataSize = Buffer.alloc(1);
|
||||
dataSize[0] = data.length;
|
||||
request = Buffer.concat([transactionId, apiId, dataSize, data]);
|
||||
return request;
|
||||
}
|
||||
|
||||
|
||||
// Extract response code from API response data
|
||||
function getResponseCode(data){
|
||||
let respCode = Buffer.alloc(2)
|
||||
respCode[0] = data[3]
|
||||
respCode[1] = data[4]
|
||||
return buf2hex(respCode)
|
||||
function getResponseCode(data) {
|
||||
let respCode = Buffer.alloc(2);
|
||||
respCode[0] = data[3];
|
||||
respCode[1] = data[4];
|
||||
return buf2hex(respCode);
|
||||
}
|
||||
|
||||
// Extract response data from API response data
|
||||
function getResponseData(apiData){
|
||||
let data = Buffer.alloc(apiData[5])
|
||||
apiData.copy(data, 0, 6, apiData[5]+6)
|
||||
return buf2hex(data);
|
||||
}
|
||||
function getResponseData(apiData) {
|
||||
let data = Buffer.alloc(apiData[5]);
|
||||
apiData.copy(data, 0, 6, apiData[5] + 6);
|
||||
return buf2hex(data);
|
||||
}
|
||||
|
||||
|
||||
function buf2hex(buffer){ // buffer is an ArrayBuffer
|
||||
return [...new Uint8Array(buffer)]
|
||||
.map(x => x.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
}
|
||||
function buf2hex(buffer) {
|
||||
// buffer is an ArrayBuffer
|
||||
return [...new Uint8Array(buffer)]
|
||||
.map((x) => x.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
function hexToBytes(hex) {
|
||||
for (var bytes = [], c = 0; c < hex.length; c += 2)
|
||||
bytes.push(parseInt(hex.substr(c, 2), 16))
|
||||
return bytes
|
||||
}
|
||||
|
||||
for (var bytes = [], c = 0; c < hex.length; c += 2)
|
||||
bytes.push(parseInt(hex.substr(c, 2), 16));
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function hex2ascii(hexx) {
|
||||
let hex = hexx.toString();//force conversion
|
||||
let str = ''
|
||||
for (var i = 0; i < hex.length; i += 2)
|
||||
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16))
|
||||
return str
|
||||
let hex = hexx.toString(); //force conversion
|
||||
let str = '';
|
||||
for (var i = 0; i < hex.length; i += 2)
|
||||
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
|
||||
return str;
|
||||
}
|
||||
|
||||
const formatDate = (date, type) => {
|
||||
var inputDate = new Date(date);
|
||||
var inputDate = new Date(date);
|
||||
|
||||
let tanggal = inputDate.getDate()
|
||||
let bulan = inputDate.getMonth() + 1
|
||||
let tahun = inputDate.getFullYear()
|
||||
let tanggal = inputDate.getDate();
|
||||
let bulan = inputDate.getMonth() + 1;
|
||||
let tahun = inputDate.getFullYear();
|
||||
|
||||
let jam = inputDate.getHours()
|
||||
let menit = inputDate.getMinutes()
|
||||
let detik = inputDate.getSeconds()
|
||||
|
||||
if (bulan.toString().length < 2) bulan = '0' + bulan
|
||||
if (tanggal.toString().length < 2) tanggal = '0' + tanggal
|
||||
if (jam.toString().length < 2) jam = '0' + jam
|
||||
if (menit.toString().length < 2) menit = '0' + menit
|
||||
if (detik.toString().length < 2) detik = '0' + detik
|
||||
let jam = inputDate.getHours();
|
||||
let menit = inputDate.getMinutes();
|
||||
let detik = inputDate.getSeconds();
|
||||
|
||||
let formatTanggal = [tahun, bulan, tanggal].join('')
|
||||
let formatWaktu = [jam, menit, detik].join('')
|
||||
if (bulan.toString().length < 2) bulan = '0' + bulan;
|
||||
if (tanggal.toString().length < 2) tanggal = '0' + tanggal;
|
||||
if (jam.toString().length < 2) jam = '0' + jam;
|
||||
if (menit.toString().length < 2) menit = '0' + menit;
|
||||
if (detik.toString().length < 2) detik = '0' + detik;
|
||||
|
||||
return [formatTanggal, formatWaktu].join('')
|
||||
}
|
||||
let formatTanggal = [tahun, bulan, tanggal].join('');
|
||||
let formatWaktu = [jam, menit, detik].join('');
|
||||
|
||||
function getTranscode(cardData, nominal){
|
||||
let trxType = Buffer.from([0x02])
|
||||
let uid = Buffer.alloc(8)
|
||||
let cardType = Buffer.alloc(2)
|
||||
return [formatTanggal, formatWaktu].join('');
|
||||
};
|
||||
|
||||
var cardNumber = Buffer.alloc(16)
|
||||
cardData.copy(cardNumber, 0, 12+16, 12+16+16)
|
||||
function getTranscode(cardData, nominal) {
|
||||
let trxType = Buffer.from([0x02]);
|
||||
let uid = Buffer.alloc(8);
|
||||
let cardType = Buffer.alloc(2);
|
||||
|
||||
cardNumber = cardNumber.toString()
|
||||
var cardNumber = Buffer.alloc(16);
|
||||
cardData.copy(cardNumber, 0, 12 + 16, 12 + 16 + 16);
|
||||
|
||||
cardData.copy(uid, 0, 1,9)
|
||||
let _cardNumber = Buffer.from(hexToBytes(cardNumber))
|
||||
cardNumber = cardNumber.toString();
|
||||
|
||||
var balanceArray = Buffer.alloc(4)
|
||||
var balanceArrayExis = Buffer.alloc(4)
|
||||
var exec_idArray = Buffer.alloc(2)
|
||||
|
||||
cardData.copy(balanceArray, 0, 12+16+16, 12+16+16+4)
|
||||
cardData.copy(balanceArrayExis, 0, 12+16+16, 12+16+16+4)
|
||||
exec_idArray[1] = cardData[cardData.length -1]
|
||||
exec_idArray[0] = cardData[cardData.length -2]
|
||||
cardData.copy(uid, 0, 1, 9);
|
||||
let _cardNumber = Buffer.from(hexToBytes(cardNumber));
|
||||
|
||||
let balanceExisting = balanceArrayExis.reverse()
|
||||
let nominalStr = Buffer.from(hexToBytes(String(nominal).padStart(8, '0')))
|
||||
var balanceArray = Buffer.alloc(4);
|
||||
var balanceArrayExis = Buffer.alloc(4);
|
||||
var exec_idArray = Buffer.alloc(2);
|
||||
|
||||
let balance = Buffer.from(balanceArray).readInt32LE()
|
||||
balance += parseInt(nominal)
|
||||
balanceArray.writeInt32LE(balance)
|
||||
let balanceAfter = balanceArray.reverse()
|
||||
cardData.copy(balanceArray, 0, 12 + 16 + 16, 12 + 16 + 16 + 4);
|
||||
cardData.copy(balanceArrayExis, 0, 12 + 16 + 16, 12 + 16 + 16 + 4);
|
||||
exec_idArray[1] = cardData[cardData.length - 1];
|
||||
exec_idArray[0] = cardData[cardData.length - 2];
|
||||
|
||||
let dateTime = Buffer.from(hexToBytes(formatDate(new Date())))
|
||||
let balanceExisting = balanceArrayExis.reverse();
|
||||
let nominalStr = Buffer.from(hexToBytes(String(nominal).padStart(8, '0')));
|
||||
|
||||
cardData.copy(cardType,0, 1 + 8 + 3 + 1, 1 + 8 + 3 + 1 + 2)
|
||||
let balance = Buffer.from(balanceArray).readInt32LE();
|
||||
balance += parseInt(nominal);
|
||||
balanceArray.writeInt32LE(balance);
|
||||
let balanceAfter = balanceArray.reverse();
|
||||
|
||||
let samID = Buffer.alloc(8)
|
||||
let samBalBefore = Buffer.alloc(4)
|
||||
let samBalAfter = Buffer.alloc(4)
|
||||
let dateTime = Buffer.from(hexToBytes(formatDate(new Date())));
|
||||
|
||||
let exec_id = exec_idArray.readUInt16BE()
|
||||
exec_id++
|
||||
cardData.copy(cardType, 0, 1 + 8 + 3 + 1, 1 + 8 + 3 + 1 + 2);
|
||||
|
||||
exec_idArray.writeUInt16BE(exec_id)
|
||||
let samID = Buffer.alloc(8);
|
||||
let samBalBefore = Buffer.alloc(4);
|
||||
let samBalAfter = Buffer.alloc(4);
|
||||
|
||||
let _transcode = Buffer.concat([trxType, _cardNumber, balanceExisting, nominalStr, balanceAfter,dateTime,
|
||||
cardType, uid, samID, samBalBefore, samBalAfter, exec_idArray])
|
||||
return _transcode
|
||||
let exec_id = exec_idArray.readUInt16BE();
|
||||
exec_id++;
|
||||
|
||||
exec_idArray.writeUInt16BE(exec_id);
|
||||
|
||||
let _transcode = Buffer.concat([
|
||||
trxType,
|
||||
_cardNumber,
|
||||
balanceExisting,
|
||||
nominalStr,
|
||||
balanceAfter,
|
||||
dateTime,
|
||||
cardType,
|
||||
uid,
|
||||
samID,
|
||||
samBalBefore,
|
||||
samBalAfter,
|
||||
exec_idArray,
|
||||
]);
|
||||
return _transcode;
|
||||
}
|
||||
|
||||
const logging = (date, title, message, id = 0) => {
|
||||
let month = date.getMonth() + 1;
|
||||
let month = date.getMonth() + 1;
|
||||
|
||||
try {
|
||||
//create folder/file if not exists
|
||||
if (!fs.existsSync(`./logs`)) {
|
||||
fs.mkdirSync(`./logs`)
|
||||
}
|
||||
if (!fs.existsSync(`./logs/log-${month}`)) {
|
||||
fs.mkdirSync(`./logs/log-${month}`)
|
||||
}
|
||||
|
||||
if (message.command) {
|
||||
message.command = buf2hex(message.command)
|
||||
}
|
||||
|
||||
let content = `[${formatDate(date)}] | { "id": ${id}, "title": ${title}, "message": ${message} }`;
|
||||
|
||||
fs.writeFileSync(`./logs/log-${month}/log.txt`, '\n' + content, {flag: 'a+'});
|
||||
|
||||
return
|
||||
} catch (err) {
|
||||
console.error("Error from logging: ", err.message);
|
||||
return
|
||||
try {
|
||||
//create folder/file if not exists
|
||||
if (!fs.existsSync(`./logs`)) {
|
||||
fs.mkdirSync(`./logs`);
|
||||
}
|
||||
}
|
||||
if (!fs.existsSync(`./logs/log-${month}`)) {
|
||||
fs.mkdirSync(`./logs/log-${month}`);
|
||||
}
|
||||
|
||||
if (message.command) {
|
||||
message.command = buf2hex(message.command);
|
||||
}
|
||||
|
||||
let content = `[${formatDate(
|
||||
date
|
||||
)}] | { "id": ${id}, "title": ${title}, "message": ${message} }`;
|
||||
|
||||
fs.writeFileSync(`./logs/log-${month}/log.txt`, '\n' + content, {
|
||||
flag: 'a+',
|
||||
});
|
||||
|
||||
return;
|
||||
} catch (err) {
|
||||
console.error('Error from logging: ', err.message);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
makeRequestData,
|
||||
getResponseCode,
|
||||
getResponseData,
|
||||
buf2hex,
|
||||
hexToBytes,
|
||||
hex2ascii,
|
||||
getTranscode,
|
||||
logging
|
||||
}
|
||||
makeRequestData,
|
||||
getResponseCode,
|
||||
getResponseData,
|
||||
buf2hex,
|
||||
hexToBytes,
|
||||
hex2ascii,
|
||||
getTranscode,
|
||||
logging,
|
||||
};
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
const helper = require("../../helpers/helper");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const model = require("./invoice.model");
|
||||
const moment = require("moment");
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
moment.locale("id");
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./invoice.model');
|
||||
const moment = require('moment');
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
moment.locale('id');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "generateInvoice":
|
||||
case 'generateInvoice':
|
||||
return [
|
||||
body("trx_date")
|
||||
body('trx_date')
|
||||
.notEmpty()
|
||||
.withMessage("trx_date is required!")
|
||||
.withMessage('trx_date is required!')
|
||||
.isISO8601()
|
||||
.withMessage("invalid trx_date format YYYY-MM-DD !")
|
||||
.withMessage('invalid trx_date format YYYY-MM-DD !')
|
||||
.escape()
|
||||
.trim(),
|
||||
body("repost")
|
||||
body('repost')
|
||||
.notEmpty()
|
||||
.withMessage("repost is required!")
|
||||
.withMessage('repost is required!')
|
||||
.isBoolean()
|
||||
.withMessage("repost must boolean!")
|
||||
.withMessage('repost must boolean!')
|
||||
.escape()
|
||||
.trim(),
|
||||
];
|
||||
case "postingInvoice":
|
||||
case 'postingInvoice':
|
||||
return [
|
||||
body("trx_date")
|
||||
body('trx_date')
|
||||
.notEmpty()
|
||||
.withMessage("trx_date is required!")
|
||||
.withMessage('trx_date is required!')
|
||||
.isISO8601()
|
||||
.withMessage("invalid trx_date format YYYY-MM-DD !")
|
||||
.withMessage('invalid trx_date format YYYY-MM-DD !')
|
||||
.escape()
|
||||
.trim(),
|
||||
];
|
||||
@@ -54,10 +54,10 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: "400",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
@@ -71,7 +71,7 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
}
|
||||
|
||||
// time
|
||||
let invoiceDate = moment(req.body.trx_date).format("YYYY-MM-DD");
|
||||
let invoiceDate = moment(req.body.trx_date).format('YYYY-MM-DD');
|
||||
|
||||
let invoice = await _generateInvoice(
|
||||
invoiceDate,
|
||||
@@ -80,8 +80,8 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
result = {
|
||||
code: "200",
|
||||
message: "Succes posting",
|
||||
code: '200',
|
||||
message: 'Succes posting',
|
||||
data: invoice,
|
||||
};
|
||||
|
||||
@@ -93,11 +93,11 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
@@ -116,10 +116,10 @@ const apiPostingInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: "400",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
@@ -135,11 +135,11 @@ const apiPostingInvoice = async (req, res) => {
|
||||
// return uniqueCode
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING INVOICE`);
|
||||
|
||||
const invoice = await _postingInvoice(uniqueCode);
|
||||
let invoice = await _postingInvoice(uniqueCode);
|
||||
|
||||
result = {
|
||||
code: "200",
|
||||
message: "Succes",
|
||||
code: '200',
|
||||
message: 'Succes',
|
||||
data: invoice,
|
||||
};
|
||||
|
||||
@@ -151,11 +151,11 @@ const apiPostingInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
@@ -163,7 +163,7 @@ const apiPostingInvoice = async (req, res) => {
|
||||
|
||||
const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
let invoice = [];
|
||||
const collection = []
|
||||
let collection = [];
|
||||
await knex.transaction(async (trx) => {
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`);
|
||||
|
||||
@@ -179,17 +179,15 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
)}`
|
||||
);
|
||||
if (invoice.length > 0) {
|
||||
|
||||
for (const key in invoice) {
|
||||
|
||||
for (let key in invoice) {
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify(
|
||||
invoice[key]
|
||||
)}`
|
||||
);
|
||||
|
||||
|
||||
let postingEt = await model.insertPostingEt(invoice[key], trx);
|
||||
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} success insert posting et : ${JSON.stringify(
|
||||
postingEt
|
||||
@@ -199,150 +197,175 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`
|
||||
);
|
||||
|
||||
const credUsername = await model.getParameterSetting(knex, "SAP_AUTH_USERNAME")
|
||||
const credPassword = await model.getParameterSetting(knex, "SAP_AUTH_PASSWORD")
|
||||
const parameter = await model.getParameterSetting(knex, "SAP_FI_URL_FOR_FB70")
|
||||
|
||||
for (const key in invoice) {
|
||||
|
||||
let credUsername = await model.getParameterSetting(
|
||||
knex,
|
||||
'SAP_AUTH_USERNAME'
|
||||
);
|
||||
let credPassword = await model.getParameterSetting(
|
||||
knex,
|
||||
'SAP_AUTH_PASSWORD'
|
||||
);
|
||||
let parameter = await model.getParameterSetting(
|
||||
knex,
|
||||
'SAP_FI_URL_FOR_FB70'
|
||||
);
|
||||
|
||||
for (let key in invoice) {
|
||||
let prepare = {
|
||||
status : true,
|
||||
cms : true,
|
||||
message: "Success",
|
||||
status: true,
|
||||
cms: true,
|
||||
message: 'Success',
|
||||
};
|
||||
|
||||
if (!credUsername) {
|
||||
prepare = {
|
||||
status: false,
|
||||
cms: false,
|
||||
message: '[CMS] FAILED GET SETTING FOR SAP_AUTH_USERNAME',
|
||||
};
|
||||
}
|
||||
|
||||
if(!credUsername) {
|
||||
prepare = {
|
||||
status : false,
|
||||
cms : false,
|
||||
message: "[CMS] FAILED GET SETTING FOR SAP_AUTH_USERNAME",
|
||||
}
|
||||
|
||||
if (!credPassword) {
|
||||
prepare = {
|
||||
status: false,
|
||||
cms: false,
|
||||
message: '[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
|
||||
};
|
||||
}
|
||||
|
||||
if(!credPassword) {
|
||||
prepare = {
|
||||
status : false,
|
||||
cms : false,
|
||||
message: "[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD",
|
||||
}
|
||||
|
||||
if (!parameter) {
|
||||
prepare = {
|
||||
status: false,
|
||||
cms: false,
|
||||
message: '[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
|
||||
};
|
||||
}
|
||||
|
||||
if(!parameter) {
|
||||
prepare = {
|
||||
status : false,
|
||||
cms : false,
|
||||
message: "[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD",
|
||||
}
|
||||
}
|
||||
|
||||
const credential = {
|
||||
|
||||
let credential = {
|
||||
username: credUsername.c_value,
|
||||
password: credPassword.c_value
|
||||
password: credPassword.c_value,
|
||||
};
|
||||
|
||||
if (
|
||||
invoice[key].c_account_code_topup == null ||
|
||||
invoice[key].c_account_topup == null
|
||||
) {
|
||||
prepare = {
|
||||
status: false,
|
||||
cms: false,
|
||||
message:
|
||||
'[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP',
|
||||
};
|
||||
}
|
||||
|
||||
if(invoice[key].c_account_code_topup == null || invoice[key].c_account_topup == null) {
|
||||
prepare = {
|
||||
status : false,
|
||||
cms : false,
|
||||
message: "[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP",
|
||||
}
|
||||
if (
|
||||
invoice[key].c_account_code_topup == '' ||
|
||||
invoice[key].c_account_topup == ''
|
||||
) {
|
||||
prepare = {
|
||||
status: false,
|
||||
cms: false,
|
||||
message:
|
||||
'[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP',
|
||||
};
|
||||
}
|
||||
|
||||
if(invoice[key].c_account_code_topup == "" || invoice[key].c_account_topup == "") {
|
||||
prepare = {
|
||||
status : false,
|
||||
cms : false,
|
||||
message: "[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP",
|
||||
}
|
||||
}
|
||||
|
||||
let xmlHeader = {
|
||||
doc_header_text: invoice[key].doc_header_text
|
||||
? invoice[key].doc_header_text
|
||||
: "",
|
||||
ba: invoice[key].ba ? invoice[key].ba : "",
|
||||
doc_date: invoice[key].doc_date ? invoice[key].doc_date : "",
|
||||
: '',
|
||||
ba: invoice[key].ba ? invoice[key].ba : '',
|
||||
doc_date: invoice[key].doc_date ? invoice[key].doc_date : '',
|
||||
posting_date: invoice[key].posting_date
|
||||
? invoice[key].posting_date
|
||||
: "",
|
||||
fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : "",
|
||||
fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : "",
|
||||
doc_type: invoice[key].doc_type ? invoice[key].doc_type : "",
|
||||
: '',
|
||||
fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : '',
|
||||
fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : '',
|
||||
doc_type: invoice[key].doc_type ? invoice[key].doc_type : '',
|
||||
c_invoice_no: invoice[key].c_invoice_no
|
||||
? invoice[key].c_invoice_no
|
||||
: "",
|
||||
: '',
|
||||
};
|
||||
|
||||
let xmlItem = ["S", "H"].map((item) => {
|
||||
|
||||
let xmlItem = ['S', 'H'].map((item) => {
|
||||
return {
|
||||
c_account_code_topup:
|
||||
item == "S" ? invoice[key].c_account_code_topup : "",
|
||||
c_account_topup: item == "H" ? invoice[key].c_account_topup : "",
|
||||
item == 'S' ? invoice[key].c_account_code_topup : '',
|
||||
c_account_topup: item == 'H' ? invoice[key].c_account_topup : '',
|
||||
ba: invoice[key].ba,
|
||||
amount: invoice[key].amount,
|
||||
posting_date: invoice[key].posting_date,
|
||||
c_invoice_no: invoice[key].c_invoice_no,
|
||||
item_text: `${item == "S" ? "DEBIT" : "KREDIT"} INVOICE CMS ${
|
||||
item_text: `${item == 'S' ? 'DEBIT' : 'KREDIT'} INVOICE CMS ${
|
||||
invoice[key].doc_header_text
|
||||
}`,
|
||||
de_cre: item,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
let xmlRequest = helper.generateXMLRequest(
|
||||
"ZFMCMS_FI_001",
|
||||
'ZFMCMS_FI_001',
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}`
|
||||
);
|
||||
|
||||
let response = {}
|
||||
|
||||
if(prepare.status){
|
||||
|
||||
response = await helper.postingSAP(parameter.c_value, xmlRequest, credential);
|
||||
|
||||
let response = {};
|
||||
|
||||
if (prepare.status) {
|
||||
response = await helper.postingSAP(
|
||||
parameter.c_value,
|
||||
xmlRequest,
|
||||
credential
|
||||
);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
|
||||
invoice[key].c_invoice_no
|
||||
} to SAP : ${JSON.stringify(response)}`
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
// new transaction
|
||||
// await knex.transaction(async (trx) => {
|
||||
|
||||
let resSAP
|
||||
if(prepare.status){
|
||||
resSAP = helper.getXMLData(response);
|
||||
}else {
|
||||
resSAP = {
|
||||
type: 'E',
|
||||
message : prepare?.message || "FAILED GET PARAMETER SETTING",
|
||||
data : {}
|
||||
}
|
||||
}
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
|
||||
resSAP
|
||||
)}`
|
||||
);
|
||||
await wait(1000)
|
||||
const cms = await model.setReturnSAP(invoice[key], resSAP, trx, true, invoice[key].c_invoice_no);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
|
||||
);
|
||||
|
||||
collection.push(cms.invoice[0])
|
||||
|
||||
|
||||
let resSAP;
|
||||
if (prepare.status) {
|
||||
resSAP = helper.getXMLData(response);
|
||||
} else {
|
||||
resSAP = {
|
||||
type: 'E',
|
||||
message: prepare?.message || 'FAILED GET PARAMETER SETTING',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
|
||||
resSAP
|
||||
)}`
|
||||
);
|
||||
await wait(1000);
|
||||
let cms = await model.setReturnSAP(
|
||||
invoice[key],
|
||||
resSAP,
|
||||
trx,
|
||||
true,
|
||||
invoice[key].c_invoice_no
|
||||
);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
|
||||
);
|
||||
|
||||
collection.push(cms.invoice[0]);
|
||||
|
||||
// });
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
@@ -351,7 +374,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
|
||||
const _postingInvoice = async (uniqueCode) => {
|
||||
let postingEt = [];
|
||||
const collection = []
|
||||
let collection = [];
|
||||
postingEt = await model.getPostingEt(knex);
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify(
|
||||
@@ -359,140 +382,144 @@ const _postingInvoice = async (uniqueCode) => {
|
||||
)}`
|
||||
);
|
||||
|
||||
const credUsername = await model.getParameterSetting(knex, "SAP_AUTH_USERNAME")
|
||||
const credPassword = await model.getParameterSetting(knex, "SAP_AUTH_PASSWORD")
|
||||
const parameter = await model.getParameterSetting(knex, "SAP_FI_URL_FOR_FB70")
|
||||
let credUsername = await model.getParameterSetting(knex, 'SAP_AUTH_USERNAME');
|
||||
let credPassword = await model.getParameterSetting(knex, 'SAP_AUTH_PASSWORD');
|
||||
let parameter = await model.getParameterSetting(knex, 'SAP_FI_URL_FOR_FB70');
|
||||
|
||||
let prepare = {
|
||||
status : true,
|
||||
message: "Success",
|
||||
status: true,
|
||||
message: 'Success',
|
||||
};
|
||||
|
||||
if (!credUsername) {
|
||||
prepare = {
|
||||
status: false,
|
||||
message: 'FAILED GET SETTING FOR SAP_AUTH_USERNAME',
|
||||
};
|
||||
}
|
||||
|
||||
if(!credUsername) {
|
||||
prepare = {
|
||||
status : false,
|
||||
message: "FAILED GET SETTING FOR SAP_AUTH_USERNAME",
|
||||
}
|
||||
if (!credPassword) {
|
||||
prepare = {
|
||||
status: false,
|
||||
message: 'FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
|
||||
};
|
||||
}
|
||||
|
||||
if(!credPassword) {
|
||||
prepare = {
|
||||
status : false,
|
||||
message: "FAILED GET SETTING FOR SAP_AUTH_PASSWORD",
|
||||
}
|
||||
if (!parameter) {
|
||||
prepare = {
|
||||
status: false,
|
||||
message: 'FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
|
||||
};
|
||||
}
|
||||
|
||||
if(!parameter) {
|
||||
prepare = {
|
||||
status : false,
|
||||
message: "FAILED GET SETTING FOR SAP_AUTH_PASSWORD",
|
||||
}
|
||||
}
|
||||
|
||||
const credential = {
|
||||
let credential = {
|
||||
username: credUsername.c_value,
|
||||
password: credPassword.c_value
|
||||
}
|
||||
password: credPassword.c_value,
|
||||
};
|
||||
|
||||
for (const item of postingEt) {
|
||||
for (let item of postingEt) {
|
||||
await knex.transaction(async (trx) => {
|
||||
let response = {};
|
||||
|
||||
await knex.transaction(async (trx) => {
|
||||
let resSAP = {};
|
||||
|
||||
let response = {}
|
||||
if (prepare.status) {
|
||||
let xmlHeader = {
|
||||
doc_header_text: item.doc_header_text ? item.doc_header_text : '',
|
||||
ba: item.ba ? item.ba : '',
|
||||
doc_date: item.doc_date ? item.doc_date : '',
|
||||
posting_date: item.posting_date ? item.posting_date : '',
|
||||
fisc_year: item.fiscal_year ? item.fiscal_year : '',
|
||||
fisc_period: item.fis_period ? item.fis_period : '',
|
||||
doc_type: item.doc_type ? item.doc_type : '',
|
||||
c_invoice_no: item.reference ? item.reference : '',
|
||||
};
|
||||
|
||||
let resSAP = {}
|
||||
|
||||
if(prepare.status){
|
||||
|
||||
let xmlHeader = {
|
||||
doc_header_text: item.doc_header_text ? item.doc_header_text : "",
|
||||
ba: item.ba ? item.ba : "",
|
||||
doc_date: item.doc_date ? item.doc_date : "",
|
||||
posting_date: item.posting_date ? item.posting_date : "",
|
||||
fisc_year: item.fiscal_year ? item.fiscal_year : "",
|
||||
fisc_period: item.fis_period ? item.fis_period : "",
|
||||
doc_type: item.doc_type ? item.doc_type : "",
|
||||
c_invoice_no: item.reference ? item.reference : "",
|
||||
let xmlItem = ['S', 'H'].map((key) => {
|
||||
return {
|
||||
c_account_code_topup: key == 'S' ? item.customer : '',
|
||||
c_account_topup: key == 'H' ? item.account : '',
|
||||
ba: item.ba,
|
||||
amount: item.amount,
|
||||
posting_date: item.posting_date,
|
||||
c_invoice_no: item.reference,
|
||||
item_text: key == 'S' ? item.text1 : item.text2,
|
||||
de_cre: key,
|
||||
};
|
||||
|
||||
let xmlItem = ["S", "H"].map((key) => {
|
||||
return {
|
||||
c_account_code_topup: key == "S" ? item.customer : "",
|
||||
c_account_topup: key == "H" ? item.account : "",
|
||||
ba: item.ba,
|
||||
amount: item.amount,
|
||||
posting_date: item.posting_date,
|
||||
c_invoice_no: item.reference,
|
||||
item_text: key == "S" ? item.text1 : item.text2,
|
||||
de_cre: key,
|
||||
};
|
||||
});
|
||||
|
||||
let xmlRequest = helper.generateXMLRequest(
|
||||
"ZFMCMS_FI_001",
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
});
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`
|
||||
);
|
||||
let xmlRequest = helper.generateXMLRequest(
|
||||
'ZFMCMS_FI_001',
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
|
||||
response = await helper.postingSAP(parameter.c_value, xmlRequest, credential);
|
||||
|
||||
winston.logger.debug(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
|
||||
item.reference
|
||||
} to SAP : ${JSON.stringify(response)}`
|
||||
);
|
||||
|
||||
resSAP = helper.getXMLData(response);
|
||||
|
||||
}else{
|
||||
resSAP = {
|
||||
type: 'E',
|
||||
message : prepare?.message || "FAILED GET PARAMETER SETTING",
|
||||
data : {}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`);
|
||||
// UPDATE CMS
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
|
||||
`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`
|
||||
);
|
||||
|
||||
response = await helper.postingSAP(
|
||||
parameter.c_value,
|
||||
xmlRequest,
|
||||
credential
|
||||
);
|
||||
|
||||
winston.logger.debug(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
|
||||
item.reference
|
||||
} to SAP : ${JSON.stringify(response)}`
|
||||
);
|
||||
|
||||
resSAP = helper.getXMLData(response);
|
||||
} else {
|
||||
resSAP = {
|
||||
type: 'E',
|
||||
message: prepare?.message || 'FAILED GET PARAMETER SETTING',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`);
|
||||
// UPDATE CMS
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
|
||||
resSAP
|
||||
)}`
|
||||
);
|
||||
)}`
|
||||
);
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} ITEM REFERENCE ${item.reference}`);
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} URL SAP ${parameter.c_value}`);
|
||||
let invoice = await model.getInvoice(item.reference, trx)
|
||||
await wait(1000)
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RETRY INVOICE ${JSON.stringify(invoice)}`);
|
||||
const cms = await model.setReturnSAP(
|
||||
invoice,
|
||||
resSAP,
|
||||
trx,
|
||||
false,
|
||||
item.reference
|
||||
);
|
||||
await wait(1000)
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} ITEM REFERENCE ${item.reference}`
|
||||
);
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} URL SAP ${parameter.c_value}`
|
||||
);
|
||||
let invoice = await model.getInvoice(item.reference, trx);
|
||||
await wait(1000);
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} RETRY INVOICE ${JSON.stringify(invoice)}`
|
||||
);
|
||||
let cms = await model.setReturnSAP(
|
||||
invoice,
|
||||
resSAP,
|
||||
trx,
|
||||
false,
|
||||
item.reference
|
||||
);
|
||||
await wait(1000);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
|
||||
);
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
|
||||
);
|
||||
|
||||
collection.push(cms.invoice[0])
|
||||
|
||||
})
|
||||
collection.push(cms.invoice[0]);
|
||||
});
|
||||
}
|
||||
|
||||
return collection;
|
||||
};
|
||||
|
||||
function wait(milliseconds) {
|
||||
return new Promise(resolve => setTimeout(resolve, milliseconds));
|
||||
return new Promise((resolve) => setTimeout(resolve, milliseconds));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -1,38 +1,38 @@
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
const helper = require("../../helpers/helper");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const model = require("./invoice.model");
|
||||
const moment = require("moment");
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
moment.locale("id");
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./invoice.model');
|
||||
const moment = require('moment');
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
moment.locale('id');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "generateInvoice":
|
||||
case 'generateInvoice':
|
||||
return [
|
||||
body("trx_date")
|
||||
body('trx_date')
|
||||
.notEmpty()
|
||||
.withMessage("trx_date is required!")
|
||||
.withMessage('trx_date is required!')
|
||||
.isISO8601()
|
||||
.withMessage("invalid trx_date format YYYY-MM-DD !")
|
||||
.withMessage('invalid trx_date format YYYY-MM-DD !')
|
||||
.escape()
|
||||
.trim(),
|
||||
body("repost")
|
||||
body('repost')
|
||||
.notEmpty()
|
||||
.withMessage("repost is required!")
|
||||
.withMessage('repost is required!')
|
||||
.isBoolean()
|
||||
.withMessage("repost must boolean!")
|
||||
.withMessage('repost must boolean!')
|
||||
.escape()
|
||||
.trim(),
|
||||
];
|
||||
case "postingInvoice":
|
||||
case 'postingInvoice':
|
||||
return [
|
||||
body("trx_date")
|
||||
body('trx_date')
|
||||
.notEmpty()
|
||||
.withMessage("trx_date is required!")
|
||||
.withMessage('trx_date is required!')
|
||||
.isISO8601()
|
||||
.withMessage("invalid trx_date format YYYY-MM-DD !")
|
||||
.withMessage('invalid trx_date format YYYY-MM-DD !')
|
||||
.escape()
|
||||
.trim(),
|
||||
];
|
||||
@@ -54,10 +54,10 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: "400",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
@@ -71,7 +71,7 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
}
|
||||
|
||||
// time
|
||||
let invoiceDate = moment(req.body.trx_date).format("YYYY-MM-DD");
|
||||
let invoiceDate = moment(req.body.trx_date).format('YYYY-MM-DD');
|
||||
|
||||
let invoice = await _generateInvoice(
|
||||
invoiceDate,
|
||||
@@ -80,8 +80,8 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
result = {
|
||||
code: "200",
|
||||
message: "Succes posting",
|
||||
code: '200',
|
||||
message: 'Succes posting',
|
||||
data: invoice,
|
||||
};
|
||||
|
||||
@@ -93,11 +93,11 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
@@ -116,10 +116,10 @@ const apiPostingInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: "400",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
@@ -135,11 +135,11 @@ const apiPostingInvoice = async (req, res) => {
|
||||
// return uniqueCode
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING INVOICE`);
|
||||
|
||||
const invoice = await _postingInvoice(uniqueCode);
|
||||
let invoice = await _postingInvoice(uniqueCode);
|
||||
|
||||
result = {
|
||||
code: "200",
|
||||
message: "Succes",
|
||||
code: '200',
|
||||
message: 'Succes',
|
||||
data: invoice,
|
||||
};
|
||||
|
||||
@@ -151,11 +151,11 @@ const apiPostingInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
@@ -180,7 +180,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
);
|
||||
|
||||
if (invoice.length > 0)
|
||||
for (const key in invoice) {
|
||||
for (let key in invoice) {
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} insert payment history et : ${JSON.stringify(
|
||||
invoice
|
||||
@@ -216,37 +216,37 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`
|
||||
);
|
||||
|
||||
const url =
|
||||
"http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2";
|
||||
let url =
|
||||
'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2';
|
||||
|
||||
for (const key in invoice) {
|
||||
for (let key in invoice) {
|
||||
let xmlHeader = {
|
||||
doc_header_text: invoice[key].doc_header_text
|
||||
? invoice[key].doc_header_text
|
||||
: "",
|
||||
ba: invoice[key].ba ? invoice[key].ba : "",
|
||||
doc_date: invoice[key].doc_date ? invoice[key].doc_date : "",
|
||||
: '',
|
||||
ba: invoice[key].ba ? invoice[key].ba : '',
|
||||
doc_date: invoice[key].doc_date ? invoice[key].doc_date : '',
|
||||
posting_date: invoice[key].posting_date
|
||||
? invoice[key].posting_date
|
||||
: "",
|
||||
fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : "",
|
||||
fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : "",
|
||||
doc_type: invoice[key].doc_type ? invoice[key].doc_type : "",
|
||||
: '',
|
||||
fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : '',
|
||||
fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : '',
|
||||
doc_type: invoice[key].doc_type ? invoice[key].doc_type : '',
|
||||
c_invoice_no: invoice[key].c_invoice_no
|
||||
? invoice[key].c_invoice_no
|
||||
: "",
|
||||
: '',
|
||||
};
|
||||
|
||||
let xmlItem = ["S", "H"].map((item) => {
|
||||
let xmlItem = ['S', 'H'].map((item) => {
|
||||
return {
|
||||
c_account_code_topup:
|
||||
item == "S" ? invoice[key].c_account_code_topup : "",
|
||||
c_account_topup: item == "H" ? invoice[key].c_account_topup : "",
|
||||
item == 'S' ? invoice[key].c_account_code_topup : '',
|
||||
c_account_topup: item == 'H' ? invoice[key].c_account_topup : '',
|
||||
ba: invoice[key].ba,
|
||||
amount: invoice[key].amount,
|
||||
posting_date: invoice[key].posting_date,
|
||||
c_invoice_no: invoice[key].c_invoice_no,
|
||||
item_text: `${item == "S" ? "DEBIT" : "KREDIT"} INVOICE CMS ${
|
||||
item_text: `${item == 'S' ? 'DEBIT' : 'KREDIT'} INVOICE CMS ${
|
||||
invoice[key].doc_header_text
|
||||
}`,
|
||||
de_cre: item,
|
||||
@@ -254,7 +254,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
});
|
||||
|
||||
let xmlRequest = helper.generateXMLRequest(
|
||||
"ZFMCMS_FI_001",
|
||||
'ZFMCMS_FI_001',
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
@@ -263,7 +263,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}`
|
||||
);
|
||||
|
||||
const response = await helper.postingSAP(url, xmlRequest);
|
||||
let response = await helper.postingSAP(url, xmlRequest);
|
||||
|
||||
winston.logger.debug(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
|
||||
@@ -273,7 +273,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
|
||||
// new transaction
|
||||
await knex.transaction(async (trx) => {
|
||||
const resSAP = helper.getXMLData(response);
|
||||
let resSAP = helper.getXMLData(response);
|
||||
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 2`);
|
||||
// UPDATE CMS
|
||||
@@ -283,7 +283,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
)}`
|
||||
);
|
||||
|
||||
const cms = await model.setReturnSAP(invoice[key], resSAP, trx);
|
||||
let cms = await model.setReturnSAP(invoice[key], resSAP, trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
|
||||
@@ -306,33 +306,33 @@ const _postingInvoice = async (uniqueCode) => {
|
||||
)}`
|
||||
);
|
||||
|
||||
for (const item of postingEt) {
|
||||
for (let item of postingEt) {
|
||||
let xmlHeader = {
|
||||
doc_header_text: item.doc_header_text ? item.doc_header_text : "",
|
||||
ba: item.ba ? item.ba : "",
|
||||
doc_date: item.doc_date ? item.doc_date : "",
|
||||
posting_date: item.posting_date ? item.posting_date : "",
|
||||
fisc_year: item.fiscal_year ? item.fiscal_year : "",
|
||||
fisc_period: item.fis_period ? item.fis_period : "",
|
||||
doc_type: item.doc_type ? item.doc_type : "",
|
||||
c_invoice_no: item.reference ? item.reference : "",
|
||||
doc_header_text: item.doc_header_text ? item.doc_header_text : '',
|
||||
ba: item.ba ? item.ba : '',
|
||||
doc_date: item.doc_date ? item.doc_date : '',
|
||||
posting_date: item.posting_date ? item.posting_date : '',
|
||||
fisc_year: item.fiscal_year ? item.fiscal_year : '',
|
||||
fisc_period: item.fis_period ? item.fis_period : '',
|
||||
doc_type: item.doc_type ? item.doc_type : '',
|
||||
c_invoice_no: item.reference ? item.reference : '',
|
||||
};
|
||||
|
||||
let xmlItem = ["S", "H"].map((key) => {
|
||||
let xmlItem = ['S', 'H'].map((key) => {
|
||||
return {
|
||||
c_account_code_topup: key == "S" ? item.customer : "",
|
||||
c_account_topup: key == "H" ? item.account : "",
|
||||
c_account_code_topup: key == 'S' ? item.customer : '',
|
||||
c_account_topup: key == 'H' ? item.account : '',
|
||||
ba: item.ba,
|
||||
amount: item.amount,
|
||||
posting_date: item.posting_date,
|
||||
c_invoice_no: item.reference,
|
||||
item_text: key == "S" ? item.text1 : item.text2,
|
||||
item_text: key == 'S' ? item.text1 : item.text2,
|
||||
de_cre: key,
|
||||
};
|
||||
});
|
||||
|
||||
let xmlRequest = helper.generateXMLRequest(
|
||||
"ZFMCMS_FI_001",
|
||||
'ZFMCMS_FI_001',
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
@@ -341,10 +341,10 @@ const _postingInvoice = async (uniqueCode) => {
|
||||
`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`
|
||||
);
|
||||
|
||||
const url =
|
||||
"http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2";
|
||||
let url =
|
||||
'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2';
|
||||
|
||||
const response = await helper.postingSAP(url, xmlRequest);
|
||||
let response = await helper.postingSAP(url, xmlRequest);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${
|
||||
@@ -355,7 +355,7 @@ const _postingInvoice = async (uniqueCode) => {
|
||||
// new transaction
|
||||
// await knex.transaction(async trx => {
|
||||
|
||||
const resSAP = helper.getXMLData(response);
|
||||
let resSAP = helper.getXMLData(response);
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`);
|
||||
// UPDATE CMS
|
||||
@@ -365,7 +365,7 @@ const _postingInvoice = async (uniqueCode) => {
|
||||
)}`
|
||||
);
|
||||
|
||||
const cms = await model.setReturnSAP(
|
||||
let cms = await model.setReturnSAP(
|
||||
{ c_invoice_no: item.reference },
|
||||
resSAP,
|
||||
trx
|
||||
|
||||
@@ -2,9 +2,16 @@ const { param, body, validationResult } = require('express-validator');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./loadbalance.model');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const moment = require('moment');
|
||||
const {
|
||||
setLoadBalanceNumberSequence,
|
||||
} = require('../../middlewares/redis.middleware');
|
||||
moment.locale('id');
|
||||
|
||||
// variable yang digunakan untuk melakukan perulangan proses generate reservation number jika reservation number yang di generate sudah digunakan orang lain
|
||||
var maxLoopParameter = 1000;
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
@@ -61,7 +68,7 @@ const generateLoadBalanceNumber = async (data, date, counter) => {
|
||||
|
||||
// insert to temp load balance number
|
||||
let insert = await model.insertLoadBalanceNumber(loadBalanceNumber);
|
||||
if (!insert) {
|
||||
if (insert.rowCount < 1) {
|
||||
loadBalanceNumber = 'XX';
|
||||
}
|
||||
return loadBalanceNumber;
|
||||
@@ -218,14 +225,12 @@ const updateAllTransaction = async (
|
||||
// generate load balance number
|
||||
let newLoadBalanceNumber;
|
||||
let getLoadBalanceSequence;
|
||||
let loadBalanceNoSequence;
|
||||
let maxLoop = 0;
|
||||
do {
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} getting loading balance sequence...`
|
||||
);
|
||||
let loadBalanceNoSequence = req.load_balance_number_sequence;
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} getting loading balance sequence...`);
|
||||
|
||||
if (!loadBalanceNoSequence) {
|
||||
// get loading balance
|
||||
getLoadBalanceSequence = await model.getLoadBalanceSequence(
|
||||
getPartner,
|
||||
@@ -234,6 +239,15 @@ const updateAllTransaction = async (
|
||||
loadBalanceNoSequence = getLoadBalanceSequence
|
||||
? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1
|
||||
: 1;
|
||||
}
|
||||
|
||||
let maxLoop = 0;
|
||||
do {
|
||||
// await _sleep(helper.randomNumberInt());
|
||||
|
||||
if (maxLoop > 0) {
|
||||
loadBalanceNoSequence++;
|
||||
}
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(`${uniqueCode} generating load balance number...`);
|
||||
@@ -244,15 +258,23 @@ const updateAllTransaction = async (
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
|
||||
if (newLoadBalanceNumber != 'XX') {
|
||||
// set sequence to redis
|
||||
await setLoadBalanceNumberSequence(
|
||||
req.partner_id_token,
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
}
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} load balance number is ${newLoadBalanceNumber}.`
|
||||
);
|
||||
|
||||
if (maxLoop > 20) {
|
||||
if (maxLoop > maxLoopParameter) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error (max loop) - backend server | ${error.message}`
|
||||
`500 internal server error. Server is busy. please try again`
|
||||
);
|
||||
|
||||
return false;
|
||||
@@ -410,7 +432,7 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -505,6 +527,24 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
// get parameter setting pengecekkan nomor kartu dengan card product di CMS
|
||||
let 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 =
|
||||
getCheckByCardProductStatusValue.c_value;
|
||||
|
||||
@@ -569,15 +609,15 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
);
|
||||
|
||||
// cek disini apakah sebelumnya topup
|
||||
const cardHistory = await model.checkCardHistory(card_number);
|
||||
let cardHistory = await model.checkCardHistory(card_number);
|
||||
|
||||
if (cardHistory.length > 0) {
|
||||
if (cardHistory.i_log_name == 21 && cardHistory.c_source == 'CMS') {
|
||||
if (getReservationPending.length > 0) {
|
||||
// insert semua reserve balance ke fraud
|
||||
const dataFraud = [];
|
||||
const rsv = [];
|
||||
for (const item of getReservationPending) {
|
||||
let dataFraud = [];
|
||||
let rsv = [];
|
||||
for (let item of getReservationPending) {
|
||||
rsv.push(item.c_reservation_no);
|
||||
dataFraud.push({
|
||||
c_card_number: item.c_card_number,
|
||||
@@ -591,7 +631,7 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} INSERT TO trx.t_d_froud ${JSON.stringify(dataFraud)}`
|
||||
);
|
||||
const fraud = await model.insertFraud(dataFraud);
|
||||
let fraud = await model.insertFraud(dataFraud);
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} RESERVE NUMBER FROM trx.t_d_froud ${JSON.stringify(
|
||||
@@ -692,7 +732,13 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
result = {
|
||||
code: '01',
|
||||
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 {
|
||||
result = {
|
||||
@@ -751,6 +797,7 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let partialTopup = false;
|
||||
let totalReservation = 0;
|
||||
let amountTopup = 0;
|
||||
let reservationNumber = [];
|
||||
@@ -815,34 +862,147 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
);
|
||||
|
||||
// get BI regulation status
|
||||
const getBIRegulationStatus = await model.getBIRegulationStatus();
|
||||
let 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') {
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} checking topup partial status...`);
|
||||
|
||||
// check topup partial status
|
||||
let 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
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max balance on the card...`
|
||||
);
|
||||
|
||||
// get max saldo on the card
|
||||
const getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
|
||||
let 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 (
|
||||
parseInt(balance) + parseInt(amountTopup) >
|
||||
parseInt(getMaxAmountOnTheCard.c_value)
|
||||
) {
|
||||
result = {
|
||||
code: '416',
|
||||
message: 'your card number has reached the maximum balance',
|
||||
data: {},
|
||||
};
|
||||
// if topup partial is active
|
||||
if (getTopupPartialStatus.c_value == 'A') {
|
||||
// reset reservation data
|
||||
partialTopup = true;
|
||||
totalReservation = 0;
|
||||
amountTopup = 0;
|
||||
reservationNumber = [];
|
||||
reservationNumberTemp = [];
|
||||
i = 0;
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
// sum amount can be topup
|
||||
getReservationPending.forEach((rsv) => {
|
||||
if (
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -865,26 +1025,97 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
}
|
||||
|
||||
// validate max topup per month
|
||||
const getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
|
||||
let 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 (
|
||||
parseInt(accumulatedBalance) + parseInt(amountTopup) >
|
||||
parseInt(getMaxTopupPerMonth.c_value)
|
||||
) {
|
||||
result = {
|
||||
code: '417',
|
||||
message: 'your card number has been limit top up for this month',
|
||||
data: {},
|
||||
};
|
||||
// if topup partial is active
|
||||
if (getTopupPartialStatus.c_value == 'A') {
|
||||
// reset reservation data
|
||||
partialTopup = true;
|
||||
totalReservation = 0;
|
||||
amountTopup = 0;
|
||||
reservationNumber = [];
|
||||
reservationNumberTemp = [];
|
||||
i = 0;
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
// sum amount can be topup
|
||||
getReservationPending.forEach((rsv) => {
|
||||
if (
|
||||
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 +1140,7 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
amount: parseInt(amountTopup),
|
||||
total_reservation: totalReservation,
|
||||
reservation_number: reservationNumber,
|
||||
partial_topup: partialTopup,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -926,6 +1158,7 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
amount: parseInt(amountTopup),
|
||||
total_reservation: totalReservation,
|
||||
reservation_number: reservationNumber,
|
||||
partial_topup: partialTopup,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -960,7 +1193,7 @@ const loadingBalanceRequest = async (req, res) => {
|
||||
// *Description:*
|
||||
// proses insert data topup atau load balance ke sistem CMS
|
||||
|
||||
const loadingBalanceInsert = async (param) => {
|
||||
const loadingBalanceInsert = async (req, param) => {
|
||||
try {
|
||||
// param
|
||||
let mid = param.mid;
|
||||
@@ -981,7 +1214,9 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST load balance insert: ${JSON.stringify(param)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
param
|
||||
)}`
|
||||
);
|
||||
|
||||
// time
|
||||
@@ -1002,14 +1237,18 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(`${uniqueCode} checking reservation status...`);
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation status...`
|
||||
);
|
||||
|
||||
// check reservation status
|
||||
for (let index = 0; index < reservation_number.length; index++) {
|
||||
@@ -1027,7 +1266,7 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -1057,7 +1296,7 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -1068,7 +1307,9 @@ const loadingBalanceInsert = async (param) => {
|
||||
}
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(`${uniqueCode} checking last log history...`);
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking last log history...`
|
||||
);
|
||||
|
||||
// get last history by card number
|
||||
let lastHistory = await model.getLastHistory(card_number);
|
||||
@@ -1077,13 +1318,17 @@ const loadingBalanceInsert = async (param) => {
|
||||
// if last history card is topup (21 = log name id for topup)
|
||||
if (lastHistory.i_log_name == 21 && lastHistory.c_source == 'CMS') {
|
||||
// log warn
|
||||
winston.logger.warn(`${uniqueCode} inserting fraud transaction...`);
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting fraud transaction...`
|
||||
);
|
||||
|
||||
// insert reservation transaction to fraud table
|
||||
await model.insertFraudTransaction(reservation_number);
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(`${uniqueCode} suspending reservation...`);
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: suspending reservation...`
|
||||
);
|
||||
|
||||
// update reservation with suspend status
|
||||
await model.suspendReservation(reservation_number, now);
|
||||
@@ -1096,7 +1341,7 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -1106,7 +1351,9 @@ const loadingBalanceInsert = async (param) => {
|
||||
}
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(`${uniqueCode} checking fraud transaction...`);
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking fraud transaction...`
|
||||
);
|
||||
|
||||
// get data fraud by card number and status fraud is not closed
|
||||
let fraudTransaction = await model.getFraudTransaction(card_number);
|
||||
@@ -1119,7 +1366,9 @@ const loadingBalanceInsert = async (param) => {
|
||||
}
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(`${uniqueCode} checking reservation pending...`);
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation pending...`
|
||||
);
|
||||
|
||||
// get total reservation pending without fraud
|
||||
let getReservationPending = await model.getReservationPendingWithoutFraud(
|
||||
@@ -1137,14 +1386,18 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(`${uniqueCode} checking total topup amount...`);
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking total topup amount...`
|
||||
);
|
||||
|
||||
// check total topup and request topup
|
||||
let amountTopup = 0;
|
||||
@@ -1161,7 +1414,9 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
@@ -1170,12 +1425,14 @@ const loadingBalanceInsert = async (param) => {
|
||||
// generate load balance number
|
||||
let loadBalanceNumber;
|
||||
let getLoadBalanceSequence;
|
||||
let loadBalanceNoSequence;
|
||||
let maxLoop = 0;
|
||||
do {
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} getting loading balance sequence...`);
|
||||
let loadBalanceNoSequence = req.load_balance_number_sequence;
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting loading balance sequence...`
|
||||
);
|
||||
|
||||
if (!loadBalanceNoSequence) {
|
||||
// get loading balance
|
||||
getLoadBalanceSequence = await model.getLoadBalanceSequence(
|
||||
getPartner,
|
||||
@@ -1184,9 +1441,20 @@ const loadingBalanceInsert = async (param) => {
|
||||
loadBalanceNoSequence = getLoadBalanceSequence
|
||||
? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1
|
||||
: 1;
|
||||
}
|
||||
|
||||
let maxLoop = 0;
|
||||
do {
|
||||
// await _sleep(helper.randomNumberInt());
|
||||
|
||||
if (maxLoop > 0) {
|
||||
loadBalanceNoSequence++;
|
||||
}
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(`${uniqueCode} generating load balance number...`);
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: generating load balance number...`
|
||||
);
|
||||
|
||||
loadBalanceNumber = await generateLoadBalanceNumber(
|
||||
getPartner,
|
||||
@@ -1194,15 +1462,23 @@ const loadingBalanceInsert = async (param) => {
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
|
||||
if (loadBalanceNumber != 'XX') {
|
||||
// set sequence to redis
|
||||
await setLoadBalanceNumberSequence(
|
||||
req.partner_id_token,
|
||||
loadBalanceNoSequence
|
||||
);
|
||||
}
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} load balance number is ${loadBalanceNumber}.`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: load balance number is ${loadBalanceNumber}.`
|
||||
);
|
||||
|
||||
if (maxLoop > 20) {
|
||||
if (maxLoop > maxLoopParameter) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error (max loop) - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE-INSERT ]: 500 internal server error. Server is busy. please try again`
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -1257,7 +1533,9 @@ const loadingBalanceInsert = async (param) => {
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} getting reservation detail...`);
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting reservation detail...`
|
||||
);
|
||||
|
||||
let detail = [];
|
||||
reservation_number = [];
|
||||
@@ -1277,7 +1555,7 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -1324,11 +1602,13 @@ const loadingBalanceInsert = async (param) => {
|
||||
// check data load balance by reservation_number exist or not
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} checking load balance transaction has been exists or not...`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking load balance transaction has been exists or not...`
|
||||
);
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(`${uniqueCode} inserting load balance transaction...`);
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting load balance transaction...`
|
||||
);
|
||||
|
||||
// insert transaction
|
||||
let insertLoadingBalance = await model.insertLoadingBalance(
|
||||
@@ -1345,7 +1625,7 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} AAAAAAAAAAAAAAAAAA [DATA] : ${JSON.stringify(
|
||||
`${uniqueCode} [DATA] : ${JSON.stringify(
|
||||
data
|
||||
)} [DETAIL] : ${JSON.stringify(detail)} [RSV] : ${JSON.stringify(
|
||||
reservation_number
|
||||
@@ -1371,7 +1651,9 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
} else {
|
||||
result = {
|
||||
@@ -1384,7 +1666,9 @@ const loadingBalanceInsert = async (param) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1392,7 +1676,7 @@ const loadingBalanceInsert = async (param) => {
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE-INSERT ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return {
|
||||
@@ -1432,7 +1716,9 @@ const loadingBalanceUpdate = async (param) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST load balance update: ${JSON.stringify(param)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE-UPDATE ]: ${JSON.stringify(
|
||||
param
|
||||
)}`
|
||||
);
|
||||
|
||||
// time
|
||||
@@ -1440,7 +1726,9 @@ const loadingBalanceUpdate = async (param) => {
|
||||
let today = moment().format('YYYY-MM-DD');
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} checking partner...`);
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: checking partner...`
|
||||
);
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
@@ -1453,7 +1741,9 @@ const loadingBalanceUpdate = async (param) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE load balance update: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-UPDATE ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
@@ -1473,7 +1763,9 @@ const loadingBalanceUpdate = async (param) => {
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} updating load balance transaction...`);
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: updating load balance transaction...`
|
||||
);
|
||||
|
||||
// update transaction
|
||||
await model.updateLoadingBalance(
|
||||
@@ -1489,7 +1781,7 @@ const loadingBalanceUpdate = async (param) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} inserting load balance transaction history ${loadBalanceNumber}...`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: inserting load balance transaction history ${loadBalanceNumber}...`
|
||||
);
|
||||
|
||||
let findDataLoadBalance = await model.findLoadBalance(loadBalanceNumber);
|
||||
@@ -1574,7 +1866,9 @@ const loadingBalanceUpdate = async (param) => {
|
||||
|
||||
if (!write_status) {
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} inserting log for card history...`);
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: inserting log for card history...`
|
||||
);
|
||||
|
||||
// log card history
|
||||
await model.createLoadBalanceLog({
|
||||
@@ -1612,14 +1906,16 @@ const loadingBalanceUpdate = async (param) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE-UPDATE ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return {
|
||||
|
||||
@@ -44,7 +44,12 @@ const getPartner = (mid, tid) => {
|
||||
// GET ISSUER
|
||||
const getIssuer = (id) => {
|
||||
let result = knex('t_c_partner_fee')
|
||||
.select('i_issuer_fee_perc', 'i_channel_fee_perc')
|
||||
.select(
|
||||
'i_issuer_fee_perc',
|
||||
'i_channel_fee_perc',
|
||||
'i_issuer_fee_nominal',
|
||||
'i_channel_fee_nominal'
|
||||
)
|
||||
.where('i_partner', id)
|
||||
.where('c_status', 'A')
|
||||
.first();
|
||||
@@ -386,7 +391,7 @@ const insertLoadingBalance = async (
|
||||
return result.rowCount;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
};
|
||||
@@ -457,7 +462,7 @@ const updateLoadingBalance = async (
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
};
|
||||
@@ -548,7 +553,7 @@ const insertLoadingBalanceHistoryOnly = async (
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
};
|
||||
@@ -665,7 +670,7 @@ const updateReservationAndLoadingBalance = async (
|
||||
return result.rowCount;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
};
|
||||
@@ -745,7 +750,7 @@ const updateFlag = async (now, cardNumber, uid, balance, flag) => {
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
};
|
||||
@@ -793,14 +798,14 @@ const getReservationPendingWithoutFraud = (
|
||||
reservationNumber = []
|
||||
) => {
|
||||
if (reservationNumber.length > 0) {
|
||||
let rsv = ``;
|
||||
let rsv = '';
|
||||
if (reservationNumber.length > 0) {
|
||||
for (let index = 0; index < reservationNumber.length; index++) {
|
||||
if (index > 0) {
|
||||
rsv = rsv + `,`;
|
||||
rsv = rsv + ',';
|
||||
}
|
||||
|
||||
rsv = `'` + rsv + reservationNumber[index] + `'`;
|
||||
rsv = rsv + "'" + reservationNumber[index] + "'";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -862,14 +867,14 @@ const getLastHistory = (cardNumber) => {
|
||||
|
||||
// INSERT FRAUD TRANSACTION
|
||||
const insertFraudTransaction = (reservationNumber) => {
|
||||
let rsv = ``;
|
||||
let rsv = '';
|
||||
if (reservationNumber.length > 0) {
|
||||
for (let index = 0; index < reservationNumber.length; index++) {
|
||||
if (index > 0) {
|
||||
rsv = rsv + `,`;
|
||||
rsv = rsv + ',';
|
||||
}
|
||||
|
||||
rsv = `'` + rsv + reservationNumber[index] + `'`;
|
||||
rsv = rsv + "'" + reservationNumber[index] + "'";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1019,15 +1024,25 @@ const updateReservationAndInsertLoadingBalance = async (
|
||||
.catch(trx.rollback);
|
||||
})
|
||||
.then((result) => {
|
||||
console.log(result);
|
||||
// console.log(result);
|
||||
return result.rowCount;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
// console.log(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 = {
|
||||
checkCardNumber,
|
||||
getPartner,
|
||||
@@ -1072,4 +1087,5 @@ module.exports = {
|
||||
getReservationPendingWithFlagV2,
|
||||
createDetailLoadBalanceFromReservation,
|
||||
updateReservationAndInsertLoadingBalance,
|
||||
getTopupPartialStatus,
|
||||
};
|
||||
|
||||
@@ -95,7 +95,7 @@ const paymentRecon = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
|
||||
@@ -0,0 +1,442 @@
|
||||
const moment = require("moment");
|
||||
moment.locale("id");
|
||||
const model = require("../pooling/pooling.model");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
|
||||
const pooling = async (req, res) => {
|
||||
try {
|
||||
let { batch } = req.body;
|
||||
// return console.log(batch);
|
||||
let dataInsert = [];
|
||||
if (batch) {
|
||||
let { data } = req.body;
|
||||
|
||||
if (!data) {
|
||||
return res.status(200).json({
|
||||
code: "409",
|
||||
message: "Data is required",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
let resObj = {
|
||||
c_card_number: data[i].card_number,
|
||||
c_idm: data[i].uid,
|
||||
};
|
||||
dataInsert.push(resObj);
|
||||
}
|
||||
|
||||
await model.insertDataPooling("raw", dataInsert);
|
||||
} else {
|
||||
let { card_number, uid } = req.body;
|
||||
|
||||
if (!card_number) {
|
||||
return res.status(200).json({
|
||||
code: "409",
|
||||
message: "Card Number is required",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
if (!uid) {
|
||||
return res.status(200).json({
|
||||
code: "409",
|
||||
message: "uid is required",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
let obj = {
|
||||
c_card_number: card_number,
|
||||
c_idm: uid,
|
||||
};
|
||||
|
||||
await model.insertDataPooling("raw", obj);
|
||||
}
|
||||
|
||||
let dataPooling = await model.getDataPooling();
|
||||
|
||||
if (dataPooling.length == 0) {
|
||||
return res.status(200).json({
|
||||
code: "00",
|
||||
message: "No Pooling Data",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
let valid = [];
|
||||
let invalid = [];
|
||||
let validCardNo = [];
|
||||
let invalidCardNo = [];
|
||||
|
||||
// Validate data
|
||||
for (let i = 0; i < dataPooling.length; i++) {
|
||||
let cardno = dataPooling[i].c_card_number;
|
||||
let uid = dataPooling[i].c_idm;
|
||||
// Check duplikat card number
|
||||
let checkCardNo = await model.checkCardProduct(cardno, uid);
|
||||
let dataObject = {
|
||||
c_card_number: cardno,
|
||||
c_idm: uid,
|
||||
};
|
||||
|
||||
if (!checkCardNo) {
|
||||
valid.push(dataObject);
|
||||
validCardNo.push(cardno);
|
||||
} else {
|
||||
invalid.push(dataObject);
|
||||
invalidCardNo.push(cardno);
|
||||
}
|
||||
}
|
||||
|
||||
if (valid.length > 0) {
|
||||
await model.insertDataPooling("valid", valid, validCardNo);
|
||||
}
|
||||
|
||||
if (invalid.length > 0) {
|
||||
await model.insertDataPooling("invalid", invalid, invalidCardNo);
|
||||
}
|
||||
|
||||
let dataInsertCardNumber = await model.getDataValid();
|
||||
|
||||
if (dataInsertCardNumber.length == 0) {
|
||||
return res.status(200).json({
|
||||
code: "409",
|
||||
message: "No data valid",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
let insertCardProduct = [];
|
||||
let cardNumber = [];
|
||||
for (let i = 0; i < dataInsertCardNumber.length; i++) {
|
||||
let cardno = dataInsertCardNumber[i].c_card_number;
|
||||
let uid = dataInsertCardNumber[i].c_idm;
|
||||
let obj = {
|
||||
c_card_number: cardno,
|
||||
c_idm: uid,
|
||||
};
|
||||
cardNumber.push(cardno);
|
||||
insertCardProduct.push(obj);
|
||||
}
|
||||
|
||||
let insertingCardNumber = await model.insertCardNumber(insertCardProduct);
|
||||
if (insertingCardNumber == "success") {
|
||||
let flagValid = await model.updateDataValid(dataCardNumber);
|
||||
if (flagValid == "error") {
|
||||
await model.deleteCardNumber(dataCardNumber);
|
||||
}
|
||||
}
|
||||
console.log(insertingCardNumber);
|
||||
if (insertingCardNumber == "error") {
|
||||
return res.status(200).json({
|
||||
code: "409",
|
||||
message: "Fail insert data card product",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
return res.status(200).json({
|
||||
code: "00",
|
||||
message: "Success",
|
||||
data: [],
|
||||
});
|
||||
} catch (error) {
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const validateData = async (req, res) => {
|
||||
let result = {};
|
||||
try {
|
||||
let data = await model.getDataPooling();
|
||||
|
||||
if (data.length == 0) {
|
||||
result = {
|
||||
code: "00",
|
||||
message: "No Pooling Data",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`[ RESPONSE VALIDATE-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let valid = [];
|
||||
let invalid = [];
|
||||
let validCardNo = [];
|
||||
let invalidCardNo = [];
|
||||
|
||||
winston.logger.debug(
|
||||
`[ PROCESSING VALIDATE-POOLING ]: checking and separating valid and invalid data...`
|
||||
);
|
||||
|
||||
// Validate data
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
let cardno = data[i].c_card_number;
|
||||
let uid = data[i].c_idm;
|
||||
// Check duplikat card number
|
||||
let checkCardNo = await model.checkCardProduct(cardno, uid);
|
||||
let dataObject = {
|
||||
c_card_number: cardno,
|
||||
c_idm: uid,
|
||||
};
|
||||
|
||||
if (!checkCardNo) {
|
||||
valid.push(dataObject);
|
||||
validCardNo.push(cardno);
|
||||
} else {
|
||||
invalid.push(dataObject);
|
||||
invalidCardNo.push(cardno);
|
||||
}
|
||||
}
|
||||
|
||||
winston.logger.debug(`[ PROCESSING VALIDATE-POOLING ]: inserting data...`);
|
||||
|
||||
if (valid.length > 0) {
|
||||
await model.insertDataPooling("valid", valid, validCardNo);
|
||||
}
|
||||
|
||||
if (invalid.length > 0) {
|
||||
await model.insertDataPooling("invalid", invalid, invalidCardNo);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Validate success",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`[ RESPONSE VALIDATE-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
result = {
|
||||
code: "500",
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.error(
|
||||
`[ RESPONSE VALIDATE-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
};
|
||||
|
||||
const insertCardProduct = async (req, res) => {
|
||||
let result = {};
|
||||
try {
|
||||
let data = await model.getDataValid();
|
||||
|
||||
if (data.length == 0) {
|
||||
result = {
|
||||
code: "409",
|
||||
message: "No data valid",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`[ RESPONSE INSERT-CARD-PRODUCT ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let dataInsert = [];
|
||||
let dataCardNumber = [];
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
let cardno = data[i].c_card_number;
|
||||
let uid = data[i].c_idm;
|
||||
let obj = {
|
||||
c_card_number: cardno,
|
||||
c_idm: uid,
|
||||
};
|
||||
dataCardNumber.push(cardno);
|
||||
dataInsert.push(obj);
|
||||
}
|
||||
|
||||
winston.logger.debug(
|
||||
`[ PROCESSING INSERT-CARD-PRODUCT ]: inserting data...`
|
||||
);
|
||||
|
||||
let insertCardNumber = await model.insertCardNumber(dataInsert);
|
||||
if (insertCardNumber == "success") {
|
||||
let flagValid = await model.updateDataValid(dataCardNumber);
|
||||
if (flagValid == "error") {
|
||||
await model.deleteCardNumber(dataCardNumber);
|
||||
}
|
||||
}
|
||||
|
||||
if (insertCardNumber == "error") {
|
||||
result = {
|
||||
code: "409",
|
||||
message: "Fail insert data card product",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`[ RESPONSE INSERT-CARD-PRODUCT ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Success",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`[ RESPONSE INSERT-CARD-PRODUCT ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
result = {
|
||||
code: "500",
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.error(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
};
|
||||
|
||||
const insertPooling = async (req, res) => {
|
||||
let result = {};
|
||||
try {
|
||||
let { batch } = req.body;
|
||||
|
||||
let dataInsert = [];
|
||||
if (batch) {
|
||||
let { data } = req.body;
|
||||
|
||||
winston.logger.warn(
|
||||
`[ REQUEST INSERT-POOLING ]: ${JSON.stringify(req.body)}`
|
||||
);
|
||||
|
||||
if (!data) {
|
||||
result = {
|
||||
code: "409",
|
||||
message: "Data is required",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
for (let i = 0; i < data.length; i++) {
|
||||
let resObj = {
|
||||
c_card_number: data[i].card_number,
|
||||
c_idm: data[i].uid,
|
||||
};
|
||||
dataInsert.push(resObj);
|
||||
}
|
||||
|
||||
winston.logger.debug(`[ PROCESSING INSERT-POOLING ]: inserting data...`);
|
||||
|
||||
await model.insertDataPooling("raw", dataInsert);
|
||||
} else {
|
||||
let { card_number, uid } = req.body;
|
||||
|
||||
winston.logger.warn(
|
||||
`[ REQUEST INSERT-POOLING ]: ${JSON.stringify(req.body)}`
|
||||
);
|
||||
|
||||
if (!card_number) {
|
||||
result = {
|
||||
code: "409",
|
||||
message: "Card Number is required",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
if (!uid) {
|
||||
result = {
|
||||
code: "409",
|
||||
message: "uid is required",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let obj = {
|
||||
c_card_number: card_number,
|
||||
c_idm: uid,
|
||||
};
|
||||
|
||||
winston.logger.debug(`[ PROCESSING INSERT-POOLING ]: inserting data...`);
|
||||
|
||||
await model.insertDataPooling("raw", obj);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Success insert data",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
result = {
|
||||
code: "500",
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
data: [],
|
||||
};
|
||||
|
||||
winston.logger.error(
|
||||
`[ RESPONSE INSERT-POOLING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { pooling, validateData, insertCardProduct, insertPooling };
|
||||
@@ -0,0 +1,155 @@
|
||||
require("dotenv").config();
|
||||
let host = process.env.DB_HOST_POOLING;
|
||||
let user = process.env.DB_USER_POOLING;
|
||||
let name = process.env.DB_NAME_POOLING;
|
||||
let password = process.env.DB_PASSWORD_POOLING;
|
||||
const dbPooling = require("knex")({
|
||||
client: "pg",
|
||||
connection: {
|
||||
host: host,
|
||||
user: user,
|
||||
password: password,
|
||||
database: name,
|
||||
},
|
||||
});
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
const moment = require("moment");
|
||||
moment.locale("id");
|
||||
|
||||
const insertData = (table, data) => {
|
||||
let result = knex(table).insert(data);
|
||||
return result;
|
||||
};
|
||||
|
||||
const insertDataPooling = async (table, data, cardno) => {
|
||||
if (table == "raw") {
|
||||
await dbPooling(table).insert(data);
|
||||
} else if (table == "valid") {
|
||||
await dbPooling.transaction(async (trx) => {
|
||||
try {
|
||||
await trx(table).insert(data);
|
||||
await trx("raw")
|
||||
.whereIn("c_card_number", cardno)
|
||||
.update({
|
||||
b_validate: true,
|
||||
d_validate: moment().format("YYYY-MM-DD HH:mm:ss"),
|
||||
});
|
||||
await trx.commit();
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
}
|
||||
});
|
||||
} else if (table == "invalid") {
|
||||
await dbPooling.transaction(async (trx) => {
|
||||
try {
|
||||
await trx(table).insert(data);
|
||||
await trx("raw")
|
||||
.whereIn("c_card_number", cardno)
|
||||
.update({
|
||||
b_validate: true,
|
||||
d_validate: moment().format("YYYY-MM-DD HH:mm:ss"),
|
||||
});
|
||||
await trx.commit();
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
}
|
||||
});
|
||||
} else {
|
||||
await dbPooling(table).insert(data);
|
||||
}
|
||||
};
|
||||
|
||||
const checkCardProduct = (card_number, uid) => {
|
||||
let result = knex("t_m_card_product")
|
||||
.where("c_card_number", "=", card_number)
|
||||
.where("c_idm", "=", uid)
|
||||
.first();
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const pooling = async (valid, invalid, dataDelete) => {
|
||||
let sts;
|
||||
await dbPooling.transaction(async (trx2) => {
|
||||
try {
|
||||
if (valid.length > 0) {
|
||||
await trx2("valid").insert(valid);
|
||||
}
|
||||
if (invalid.length > 0) {
|
||||
await trx2("invalid").insert(invalid);
|
||||
}
|
||||
await trx2("pooling").whereIn("c_card_number", dataDelete).del();
|
||||
|
||||
await trx2.commit();
|
||||
sts = "success";
|
||||
} catch (error) {
|
||||
sts = "error";
|
||||
await trx2.rollback();
|
||||
}
|
||||
});
|
||||
return sts;
|
||||
};
|
||||
|
||||
const insertCardNumber = async (data) => {
|
||||
let sts;
|
||||
await knex.transaction(async (trx) => {
|
||||
try {
|
||||
await trx("t_m_card_product").insert(data);
|
||||
await trx.commit();
|
||||
sts = "success";
|
||||
} catch (error) {
|
||||
sts = "error";
|
||||
await trx.rollback();
|
||||
}
|
||||
});
|
||||
return sts;
|
||||
};
|
||||
|
||||
const updateDataValid = async (data) => {
|
||||
let sts;
|
||||
await dbPooling.transaction(async (trx) => {
|
||||
try {
|
||||
await trx("valid")
|
||||
.whereIn("c_card_number", data)
|
||||
.update({
|
||||
b_sync: true,
|
||||
d_sync: moment().format("YYYY-MM-DD HH:mm:ss"),
|
||||
});
|
||||
await trx.commit();
|
||||
sts = "success";
|
||||
} catch (error) {
|
||||
await trx.rollback();
|
||||
sts = "error";
|
||||
}
|
||||
});
|
||||
return sts;
|
||||
};
|
||||
|
||||
const getDataPooling = () => {
|
||||
let result = dbPooling("raw").where("b_validate", "=", false);
|
||||
return result;
|
||||
};
|
||||
|
||||
const getDataValid = () => {
|
||||
let result = dbPooling("valid").where("b_sync", "=", false);
|
||||
return result;
|
||||
};
|
||||
|
||||
const deleteCardNumber = (data) => {
|
||||
let result = knex("t_m_card_product")
|
||||
.whereIn("c_card_number", "=", data)
|
||||
.del();
|
||||
return result;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
deleteCardNumber,
|
||||
updateDataValid,
|
||||
getDataValid,
|
||||
insertDataPooling,
|
||||
insertCardNumber,
|
||||
pooling,
|
||||
insertData,
|
||||
checkCardProduct,
|
||||
getDataPooling,
|
||||
};
|
||||
@@ -10,7 +10,7 @@ const {
|
||||
moment.locale('id');
|
||||
|
||||
// variable yang digunakan untuk melakukan perulangan proses generate reservation number jika reservation number yang di generate sudah digunakan orang lain
|
||||
var maxLoopParameter = 100;
|
||||
var maxLoopParameter = 1000;
|
||||
|
||||
// VALIDATION
|
||||
// define parameter-parameter request untuk setiap end point
|
||||
@@ -73,6 +73,11 @@ const validate = (method) => {
|
||||
.isEmpty()
|
||||
.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':
|
||||
return [
|
||||
body('cancel_reservation_data')
|
||||
@@ -80,6 +85,11 @@ const validate = (method) => {
|
||||
.isEmpty()
|
||||
.withMessage('Cancel Reservation data is required'),
|
||||
];
|
||||
case 'getFeeSharing':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
@@ -106,7 +116,7 @@ const checkReservation = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -271,7 +281,7 @@ const reservationValidate = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -455,7 +465,7 @@ const reservationValidate = async (req, res) => {
|
||||
);
|
||||
|
||||
// get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak
|
||||
const getBIRegulationStatus = await model.getBIRegulationStatus();
|
||||
let getBIRegulationStatus = await model.getBIRegulationStatus();
|
||||
|
||||
// jika pengecekkan regulasi BI diaktifkan
|
||||
if (getBIRegulationStatus.c_value == 'A') {
|
||||
@@ -466,7 +476,7 @@ const reservationValidate = async (req, res) => {
|
||||
);
|
||||
|
||||
// get max saldo on the card
|
||||
const getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
|
||||
let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
|
||||
|
||||
// jika settingan paremeter maksimum saldo di dalam kartu ditemukan
|
||||
if (getMaxAmountOnTheCard.c_value) {
|
||||
@@ -514,7 +524,7 @@ const reservationValidate = async (req, res) => {
|
||||
}
|
||||
|
||||
// validate max topup per month berdasarkan parameter setting
|
||||
const getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
|
||||
let getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
|
||||
|
||||
// jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan
|
||||
if (getMaxTopupPerMonth.c_value) {
|
||||
@@ -605,11 +615,19 @@ const reservationValidate = async (req, res) => {
|
||||
|
||||
// get issuer fee dan channel fee dari table public.t_c_partner_fee
|
||||
let getIssuer = await model.getIssuer(getPartner.i_partner, now);
|
||||
|
||||
if (getIssuer) {
|
||||
issuerFee =
|
||||
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
channelFee =
|
||||
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
// ======================= KHUSUS LRT JABODEBEK =============================
|
||||
if (getPartner.partner_code == 'P05') {
|
||||
issuerFee = getIssuer.i_issuer_fee_nominal;
|
||||
channelFee = getIssuer.i_channel_fee_nominal;
|
||||
} else {
|
||||
// SELAIN LRT JABODEBEK
|
||||
issuerFee =
|
||||
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
channelFee =
|
||||
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
}
|
||||
}
|
||||
// if (!getIssuer) {
|
||||
// return res.status(200).json({
|
||||
@@ -622,7 +640,10 @@ const reservationValidate = async (req, res) => {
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'validation successfully.',
|
||||
data: {},
|
||||
data: {
|
||||
issuer_fee: issuerFee,
|
||||
channel_fee: channelFee,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
@@ -674,7 +695,7 @@ const reservationValidateV2 = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -858,7 +879,7 @@ const reservationValidateV2 = async (req, res) => {
|
||||
);
|
||||
|
||||
// get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak
|
||||
const getBIRegulationStatus = await model.getBIRegulationStatus();
|
||||
let getBIRegulationStatus = await model.getBIRegulationStatus();
|
||||
|
||||
// jika pengecekkan regulasi BI diaktifkan
|
||||
if (getBIRegulationStatus.c_value == 'A') {
|
||||
@@ -869,7 +890,7 @@ const reservationValidateV2 = async (req, res) => {
|
||||
);
|
||||
|
||||
// get max saldo on the card
|
||||
const getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
|
||||
let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
|
||||
|
||||
// jika settingan paremeter maksimum saldo di dalam kartu ditemukan
|
||||
if (getMaxAmountOnTheCard.c_value) {
|
||||
@@ -917,7 +938,7 @@ const reservationValidateV2 = async (req, res) => {
|
||||
}
|
||||
|
||||
// validate max topup per month berdasarkan parameter setting
|
||||
const getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
|
||||
let getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
|
||||
|
||||
// jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan
|
||||
if (getMaxTopupPerMonth.c_value) {
|
||||
@@ -973,7 +994,7 @@ const reservationValidateV2 = async (req, res) => {
|
||||
let dataReservationPending = [];
|
||||
let totalNominalReservationPending = 0;
|
||||
if (getReservationPending.length > 0) {
|
||||
for (const item of getReservationPending) {
|
||||
for (let item of getReservationPending) {
|
||||
// hitung total reservasi yang masih pending / belum di topup
|
||||
totalNominalReservationPending =
|
||||
totalNominalReservationPending + parseInt(item.i_reservation_amount);
|
||||
@@ -1023,12 +1044,21 @@ const reservationValidateV2 = async (req, res) => {
|
||||
|
||||
// get issuer fee dan channel fee dari table public.t_c_partner_fee
|
||||
let getIssuer = await model.getIssuer(getPartner.i_partner, now);
|
||||
|
||||
if (getIssuer) {
|
||||
issuerFee =
|
||||
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
channelFee =
|
||||
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
// ======================= KHUSUS LRT JABODEBEK =============================
|
||||
if (getPartner.partner_code == 'P05') {
|
||||
issuerFee = getIssuer.i_issuer_fee_nominal;
|
||||
channelFee = getIssuer.i_channel_fee_nominal;
|
||||
} else {
|
||||
// SELAIN LRT JABODEBEK
|
||||
issuerFee =
|
||||
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
channelFee =
|
||||
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
}
|
||||
}
|
||||
|
||||
// if (!getIssuer) {
|
||||
// return res.status(200).json({
|
||||
// code: "403",
|
||||
@@ -1076,6 +1106,8 @@ const reservationValidateV2 = async (req, res) => {
|
||||
reservation_detail: {
|
||||
card_number: card_number,
|
||||
amount: amount,
|
||||
issuer_fee: issuerFee,
|
||||
channel_fee: channelFee,
|
||||
},
|
||||
reservation_pending: dataReservationPending,
|
||||
},
|
||||
@@ -1106,7 +1138,7 @@ const reservationValidateV2 = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
// ================================================================= RESERVATION =================================================================
|
||||
// ================================================================= RESERVATION V1 =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *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
|
||||
@@ -1119,7 +1151,8 @@ const reservation = async (req, res) => {
|
||||
let result = {};
|
||||
|
||||
// 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
|
||||
winston.logger.info(
|
||||
@@ -1127,7 +1160,7 @@ const reservation = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -1295,7 +1328,7 @@ const reservation = async (req, res) => {
|
||||
);
|
||||
|
||||
// get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak
|
||||
const getBIRegulationStatus = await model.getBIRegulationStatus();
|
||||
let getBIRegulationStatus = await model.getBIRegulationStatus();
|
||||
if (getBIRegulationStatus.c_value == 'A') {
|
||||
// log debug
|
||||
// get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS
|
||||
@@ -1304,7 +1337,7 @@ const reservation = async (req, res) => {
|
||||
);
|
||||
|
||||
// get max saldo on the card
|
||||
const getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
|
||||
let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
|
||||
// jika settingan paremeter maksimum saldo di dalam kartu ditemukan
|
||||
if (getMaxAmountOnTheCard.c_value) {
|
||||
// jika saldo dalam kartu diakumulasikan dengan amount reservasi dan jumlah nya ternyata melebihi jumlah maksimum saldo berdasarkan settingan parameter, maka akan transaksi akan di tolak
|
||||
@@ -1349,7 +1382,7 @@ const reservation = async (req, res) => {
|
||||
}
|
||||
|
||||
// validate max topup per month berdasarkan parameter setting
|
||||
const getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
|
||||
let getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
|
||||
|
||||
// jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan
|
||||
if (getMaxTopupPerMonth.c_value) {
|
||||
@@ -1462,12 +1495,21 @@ const reservation = async (req, res) => {
|
||||
|
||||
// get issuer fee dan channel fee dari table public.t_c_partner_fee
|
||||
let getIssuer = await model.getIssuer(getPartner.i_partner, now);
|
||||
|
||||
if (getIssuer) {
|
||||
issuerFee =
|
||||
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
channelFee =
|
||||
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
// ======================= KHUSUS LRT JABODEBEK =============================
|
||||
if (getPartner.partner_code == 'P05') {
|
||||
issuerFee = getIssuer.i_issuer_fee_nominal;
|
||||
channelFee = getIssuer.i_channel_fee_nominal;
|
||||
} else {
|
||||
// SELAIN LRT JABODEBEK
|
||||
issuerFee =
|
||||
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
channelFee =
|
||||
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
}
|
||||
}
|
||||
|
||||
// if (!getIssuer) {
|
||||
// return res.status(200).json({
|
||||
// code: "403",
|
||||
@@ -1484,7 +1526,11 @@ const reservation = async (req, res) => {
|
||||
let maxLoop = 0;
|
||||
|
||||
do {
|
||||
await _sleep(helper.randomNumberInt());
|
||||
// await _sleep(helper.randomNumberInt());
|
||||
|
||||
if (maxLoop > 0) {
|
||||
reservationNoSequence++;
|
||||
}
|
||||
|
||||
// log debug
|
||||
// proses pencarian sequence terakhir dari transaksi reservasi saldo berdasarkan partner di hari ini
|
||||
@@ -1515,6 +1561,14 @@ const reservation = async (req, res) => {
|
||||
reservationNoSequence
|
||||
);
|
||||
|
||||
if (reservationNumber != 'XX') {
|
||||
// set sequence to redis
|
||||
await setReservationNumberSequence(
|
||||
req.partner_id_token,
|
||||
reservationNoSequence
|
||||
);
|
||||
}
|
||||
|
||||
// kondisi jika reservasi number yang digenerate selalu mendapatkan kode yang sudha digunakan / tidak unique
|
||||
if (maxLoop > maxLoopParameter) {
|
||||
// create log
|
||||
@@ -1522,10 +1576,7 @@ const reservation = async (req, res) => {
|
||||
|
||||
return {
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: 'server is busy. please try again.',
|
||||
message: 'server is busy. please try again.',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
@@ -1561,6 +1612,19 @@ const reservation = async (req, res) => {
|
||||
|
||||
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
|
||||
let data = {
|
||||
c_reservation_no: reservationNumber,
|
||||
@@ -1607,6 +1671,8 @@ const reservation = async (req, res) => {
|
||||
c_delete_username: null,
|
||||
c_delete_fullname: null,
|
||||
c_flag: '-1',
|
||||
c_customer_name: customerName,
|
||||
c_phone_number: phoneNumber,
|
||||
};
|
||||
|
||||
// log debug
|
||||
@@ -1629,7 +1695,7 @@ const reservation = async (req, res) => {
|
||||
await model.deleteReservationNumberValidate(reservationNumber);
|
||||
|
||||
result = {
|
||||
code: '432',
|
||||
code: '424',
|
||||
message: 'refno is duplicate',
|
||||
data: {},
|
||||
};
|
||||
@@ -1723,7 +1789,14 @@ const reservationV2 = async (req, res) => {
|
||||
let result = {};
|
||||
|
||||
// param
|
||||
let { reservation_data, ref_no } = req.body;
|
||||
let {
|
||||
reservation_data,
|
||||
ref_no,
|
||||
customer_name,
|
||||
phone_number,
|
||||
amount,
|
||||
card_number,
|
||||
} = req.body;
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
@@ -1731,7 +1804,7 @@ const reservationV2 = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -1798,11 +1871,47 @@ const reservationV2 = async (req, res) => {
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
if (card_number) {
|
||||
if (reservationData.card_number != card_number) {
|
||||
result = {
|
||||
code: '441',
|
||||
message:
|
||||
'bad request. card number requested is different with reservation data.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
if (amount) {
|
||||
if (reservationData.amount != amount) {
|
||||
result = {
|
||||
code: '442',
|
||||
message:
|
||||
'bad request. amount requested is different with reservation data.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
// extract reseravtion data
|
||||
let mid = reservationData.mid;
|
||||
let tid = reservationData.tid;
|
||||
let card_number = reservationData.card_number;
|
||||
let amount = reservationData.amount;
|
||||
card_number = reservationData.card_number;
|
||||
amount = reservationData.amount;
|
||||
let transactionDate = reservationData.transaction_date;
|
||||
let securityCode = reservationData.security_code;
|
||||
|
||||
@@ -2001,7 +2110,7 @@ const reservationV2 = async (req, res) => {
|
||||
);
|
||||
|
||||
// get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak
|
||||
const getBIRegulationStatus = await model.getBIRegulationStatus();
|
||||
let getBIRegulationStatus = await model.getBIRegulationStatus();
|
||||
if (getBIRegulationStatus.c_value == 'A') {
|
||||
// log debug
|
||||
// get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS
|
||||
@@ -2010,7 +2119,7 @@ const reservationV2 = async (req, res) => {
|
||||
);
|
||||
|
||||
// get max saldo on the card
|
||||
const getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
|
||||
let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
|
||||
// jika settingan paremeter maksimum saldo di dalam kartu ditemukan
|
||||
if (getMaxAmountOnTheCard.c_value) {
|
||||
// jika saldo dalam kartu diakumulasikan dengan amount reservasi dan jumlah nya ternyata melebihi jumlah maksimum saldo berdasarkan settingan parameter, maka akan transaksi akan di tolak
|
||||
@@ -2057,7 +2166,7 @@ const reservationV2 = async (req, res) => {
|
||||
}
|
||||
|
||||
// validate max topup per month berdasarkan parameter setting
|
||||
const getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
|
||||
let getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
|
||||
|
||||
// jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan
|
||||
if (getMaxTopupPerMonth.c_value) {
|
||||
@@ -2139,7 +2248,7 @@ const reservationV2 = async (req, res) => {
|
||||
let dataReservationPending = [];
|
||||
let totalNominalReservationPending = 0;
|
||||
if (getReservationPending.length > 0) {
|
||||
for (const item of getReservationPending) {
|
||||
for (let item of getReservationPending) {
|
||||
// hitung total reservasi yang masih pending / belum di topup
|
||||
totalNominalReservationPending =
|
||||
totalNominalReservationPending + parseInt(item.i_reservation_amount);
|
||||
@@ -2187,12 +2296,21 @@ const reservationV2 = async (req, res) => {
|
||||
|
||||
// get issuer fee dan channel fee dari table public.t_c_partner_fee
|
||||
let getIssuer = await model.getIssuer(getPartner.i_partner, now);
|
||||
|
||||
if (getIssuer) {
|
||||
issuerFee =
|
||||
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
channelFee =
|
||||
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
// ======================= KHUSUS LRT JABODEBEK =============================
|
||||
if (getPartner.partner_code == 'P05') {
|
||||
issuerFee = getIssuer.i_issuer_fee_nominal;
|
||||
channelFee = getIssuer.i_channel_fee_nominal;
|
||||
} else {
|
||||
// SELAIN LRT JABODEBEK
|
||||
issuerFee =
|
||||
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
channelFee =
|
||||
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
}
|
||||
}
|
||||
|
||||
// if (!getIssuer) {
|
||||
// return res.status(200).json({
|
||||
// code: "403",
|
||||
@@ -2210,10 +2328,10 @@ const reservationV2 = async (req, res) => {
|
||||
let maxLoop = 0;
|
||||
|
||||
do {
|
||||
await _sleep(helper.randomNumberInt());
|
||||
// await _sleep(helper.randomNumberInt());
|
||||
|
||||
if (maxLoop > 0) {
|
||||
reservationNoSequence = null;
|
||||
reservationNoSequence++;
|
||||
}
|
||||
|
||||
// log debug
|
||||
@@ -2231,12 +2349,6 @@ const reservationV2 = async (req, res) => {
|
||||
reservationNoSequence = getReservationNumberSequence
|
||||
? parseInt(getReservationNumberSequence.i_reservation_no_seq) + 1
|
||||
: 1;
|
||||
|
||||
// set sequence to redis
|
||||
await setReservationNumberSequence(
|
||||
req.partner_id_token,
|
||||
reservationNoSequence
|
||||
);
|
||||
}
|
||||
|
||||
// log debug
|
||||
@@ -2251,6 +2363,18 @@ const reservationV2 = async (req, res) => {
|
||||
reservationNoSequence
|
||||
);
|
||||
|
||||
if (reservationNumber != 'XX') {
|
||||
// set sequence to redis
|
||||
await setReservationNumberSequence(
|
||||
req.partner_id_token,
|
||||
reservationNoSequence
|
||||
);
|
||||
}
|
||||
|
||||
console.log(
|
||||
'OKKKKKKKKKKKKKKKKKKKK INI RESERVER SEQ: ' + reservationNoSequence
|
||||
);
|
||||
|
||||
// kondisi jika reservasi number yang digenerate selalu mendapatkan kode yang sudha digunakan / tidak unique
|
||||
if (maxLoop > maxLoopParameter) {
|
||||
// create log
|
||||
@@ -2258,10 +2382,7 @@ const reservationV2 = async (req, res) => {
|
||||
|
||||
return {
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: 'server is busy. please try again.',
|
||||
message: 'server is busy. please try again.',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
@@ -2297,6 +2418,19 @@ const reservationV2 = async (req, res) => {
|
||||
|
||||
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
|
||||
let data = {
|
||||
c_reservation_no: reservationNumber,
|
||||
@@ -2343,6 +2477,8 @@ const reservationV2 = async (req, res) => {
|
||||
c_delete_username: null,
|
||||
c_delete_fullname: null,
|
||||
c_flag: '-1',
|
||||
c_customer_name: customerName,
|
||||
c_phone_number: phoneNumber,
|
||||
};
|
||||
|
||||
// log debug
|
||||
@@ -2365,7 +2501,7 @@ const reservationV2 = async (req, res) => {
|
||||
await model.deleteReservationNumberValidate(reservationNumber);
|
||||
|
||||
result = {
|
||||
code: '432',
|
||||
code: '424',
|
||||
message: 'refno is duplicate',
|
||||
data: {},
|
||||
};
|
||||
@@ -2490,7 +2626,7 @@ const cancelReservationValidate = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -2675,7 +2811,7 @@ const cancelReservation = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -3086,6 +3222,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
|
||||
let listReservation = await model.inquiryListReservation(
|
||||
req.partner_id_token,
|
||||
@@ -3130,17 +3278,17 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
let result = {};
|
||||
|
||||
// param
|
||||
let { mid, tid, reservation_number } = req.body;
|
||||
let { mid, tid, reservation_number, ref_no } = req.body;
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${uniqueCode} [ REQUEST CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -3150,7 +3298,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -3161,7 +3309,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
// log debug
|
||||
// proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE ]: checking partner...`
|
||||
`${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ]: checking partner...`
|
||||
);
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
@@ -3175,53 +3323,122 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${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 ]: getting reservation by reservation number...`
|
||||
);
|
||||
let getReservationCanBeCanceled;
|
||||
|
||||
// get reservation berdasarkan reservation number yang di request
|
||||
let getReservationCanBeCanceled = await model.getReservationCanBeCanceled(
|
||||
reservation_number
|
||||
);
|
||||
// jika cancelation reservation dilakukan dengan menggunakan ref no
|
||||
if (ref_no) {
|
||||
if (!ref_no) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'Ref no is required',
|
||||
data: {},
|
||||
};
|
||||
|
||||
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
|
||||
)}`
|
||||
);
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${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 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
|
||||
let getGlobalParameter = await model.getGlobalParameter();
|
||||
// check value global parameter
|
||||
if (!getGlobalParameter) {
|
||||
result = {
|
||||
code: '493',
|
||||
code: '439',
|
||||
message: 'HSM_CANCEL_RESERVATION_LEVEL in global parameter not found',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -3238,7 +3455,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -3255,7 +3472,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -3272,7 +3489,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -3296,7 +3513,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -3317,7 +3534,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE cancel reservation validate: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -3333,7 +3550,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -3350,7 +3567,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -3363,13 +3580,13 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
|
||||
// create security code yang isinya data reservasi yang akan di compare nantinya saat melakukan insert reservation
|
||||
let securityCode = await helper.createHMAC(
|
||||
mid + '|' + tid + '|' + reservation_number
|
||||
mid + '|' + tid + '|' + reservationNumber
|
||||
);
|
||||
|
||||
let reservationData = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
reservation_number: reservation_number,
|
||||
reservation_number: reservationNumber,
|
||||
transaction_date: now,
|
||||
security_code: securityCode,
|
||||
};
|
||||
@@ -3377,7 +3594,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
// log debug
|
||||
// process enkripsi data reservasi dengan AES yang nanti nya akan di kirim ke end point reservation api untuk menyimpan data reservasi
|
||||
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
|
||||
)}`
|
||||
);
|
||||
@@ -3390,12 +3607,17 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
message: 'reservation can be canceled.',
|
||||
data: {
|
||||
cancel_reservation_data: hash,
|
||||
cancel_reservation_detail: {
|
||||
reservation_number: reservationNumber,
|
||||
card_number: cardNumber,
|
||||
amount: amount,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify(
|
||||
`${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
@@ -3404,7 +3626,7 @@ const cancelReservationValidateV2 = async (req, res) => {
|
||||
} catch (error) {
|
||||
// create log
|
||||
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({
|
||||
@@ -3436,7 +3658,7 @@ const cancelReservationV2 = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -3729,7 +3951,7 @@ const cancelReservationV2_1 = async (req, res) => {
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -3977,6 +4199,104 @@ const cancelReservationV2_1 = async (req, res) => {
|
||||
}
|
||||
};
|
||||
|
||||
// ================================================================= GET FEE SHARING =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *Description:*
|
||||
// proses fee sharing
|
||||
|
||||
const getFeeSharing = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
// param
|
||||
let { datetime, mid, tid } = req.body;
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST GET-FEE-SHARING ]: ${JSON.stringify(req.body)}`
|
||||
);
|
||||
|
||||
// datetime
|
||||
if (!datetime) {
|
||||
datetime = moment().format('YYYY-MM-DD');
|
||||
}
|
||||
|
||||
// log debug
|
||||
// proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING GET-FEE-SHARING ] checking partner...`
|
||||
);
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
|
||||
// jika partner (mid atau tid) tidak ditemukan atau tidak terdaftar di sistem CMS
|
||||
if (!getPartner) {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'terminal id is not valid',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE GET-FEE-SHARING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// set default issuer fee
|
||||
let issuerFee = 0;
|
||||
let channelFee = 0;
|
||||
|
||||
// get issuer fee dan channel fee dari table public.t_c_partner_fee
|
||||
let getIssuer = await model.getIssuer(getPartner.i_partner, datetime);
|
||||
|
||||
if (getIssuer) {
|
||||
// ======================= KHUSUS LRT JABODEBEK =============================
|
||||
if (getPartner.partner_code == 'P05') {
|
||||
issuerFee = getIssuer.i_issuer_fee_nominal;
|
||||
channelFee = getIssuer.i_channel_fee_nominal;
|
||||
} else {
|
||||
// SELAIN LRT JABODEBEK
|
||||
issuerFee =
|
||||
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
channelFee =
|
||||
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
}
|
||||
}
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'fee sharing has been found.',
|
||||
data: {
|
||||
issuer_fee: issuerFee,
|
||||
channel_fee: channelFee,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE GET-FEE-SHARING ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
checkReservation,
|
||||
@@ -3992,4 +4312,5 @@ module.exports = {
|
||||
cancelReservationValidateV2,
|
||||
cancelReservationV2,
|
||||
cancelReservationV2_1,
|
||||
getFeeSharing,
|
||||
};
|
||||
|
||||
@@ -57,7 +57,13 @@ const getPartner = (mid, tid) => {
|
||||
// GET ISSUER FEE
|
||||
const getIssuer = (id, time) => {
|
||||
let result = knex('t_c_partner_fee')
|
||||
.select('i_issuer_fee_perc', 'i_channel_fee_perc', 'i_amount')
|
||||
.select(
|
||||
'i_issuer_fee_perc',
|
||||
'i_channel_fee_perc',
|
||||
'i_amount',
|
||||
'i_issuer_fee_nominal',
|
||||
'i_channel_fee_nominal'
|
||||
)
|
||||
.where('i_partner', id)
|
||||
.where('c_status', 'A')
|
||||
.where('d_valid', '<=', time)
|
||||
@@ -378,6 +384,14 @@ const getReservationCanBeCanceled = (reservation_number) => {
|
||||
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) => {
|
||||
let result = knex('trx.t_d_reservation_no_validate')
|
||||
.insert({
|
||||
@@ -545,6 +559,7 @@ module.exports = {
|
||||
createReserveBalanceLog,
|
||||
getReservationWithPendingAndInProgressStatus,
|
||||
getReservationCanBeCanceled,
|
||||
getReservationCanBeCanceledByRefno,
|
||||
insertReservationNumber,
|
||||
cancelReservation,
|
||||
deleteReservationNumberValidate,
|
||||
|
||||
@@ -2,10 +2,14 @@ const express = require('express');
|
||||
const router = express.Router();
|
||||
const auth = require('../middlewares/jwt.middleware');
|
||||
const controller = require('../modules/loadbalance/loadbalance.controller');
|
||||
const {
|
||||
getLoadBalanceNumberSequence,
|
||||
} = require('../middlewares/redis.middleware');
|
||||
|
||||
router.post(
|
||||
'/loadbalance/request',
|
||||
auth.authenticateToken,
|
||||
getLoadBalanceNumberSequence,
|
||||
controller.validate('loadingBalanceRequest'),
|
||||
controller.loadingBalanceRequest
|
||||
);
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const auth = require("../middlewares/jwt.middleware");
|
||||
const controller = require("../modules/pooling/pooling.controller");
|
||||
|
||||
router.post(
|
||||
"/validate-pooling",
|
||||
auth.authenticateToken,
|
||||
controller.validateData
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/insert-pooling",
|
||||
auth.authenticateToken,
|
||||
controller.insertPooling
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/insert-card-product",
|
||||
auth.authenticateToken,
|
||||
controller.insertCardProduct
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,10 +1,6 @@
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const auth = require('../middlewares/jwt.middleware');
|
||||
const lokiMiddleware = require('../middlewares/loki.middleware');
|
||||
const {
|
||||
prometheusMiddleware,
|
||||
} = require('../middlewares/prometheus.middleware');
|
||||
const {
|
||||
getReservationNumberSequence,
|
||||
} = require('../middlewares/redis.middleware');
|
||||
@@ -28,8 +24,6 @@ router.post(
|
||||
router.post(
|
||||
'/reservation',
|
||||
auth.authenticateToken,
|
||||
prometheusMiddleware,
|
||||
lokiMiddleware,
|
||||
getReservationNumberSequence,
|
||||
controller.validate('reservation'),
|
||||
controller.reservation
|
||||
@@ -78,8 +72,6 @@ router.post(
|
||||
router.post(
|
||||
'/reservation/v2',
|
||||
auth.authenticateToken,
|
||||
prometheusMiddleware,
|
||||
lokiMiddleware,
|
||||
getReservationNumberSequence,
|
||||
controller.validate('reservationV2'),
|
||||
controller.reservationV2
|
||||
@@ -88,7 +80,7 @@ router.post(
|
||||
router.post(
|
||||
'/reservation/cancel/validate/v2',
|
||||
auth.authenticateToken,
|
||||
controller.validate('cancelReservation'),
|
||||
controller.validate('cancelReservationValidateV2'),
|
||||
controller.cancelReservationValidateV2
|
||||
);
|
||||
|
||||
@@ -100,10 +92,17 @@ router.post(
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/reservation/cancel/v2.1',
|
||||
'/reservation/fee-sharing',
|
||||
auth.authenticateToken,
|
||||
controller.validate('cancelReservation'),
|
||||
controller.cancelReservationV2_1
|
||||
controller.validate('getFeeSharing'),
|
||||
controller.getFeeSharing
|
||||
);
|
||||
|
||||
// router.post(
|
||||
// '/reservation/cancel/v2.1',
|
||||
// auth.authenticateToken,
|
||||
// controller.validate('cancelReservation'),
|
||||
// controller.cancelReservationV2_1
|
||||
// );
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -21,6 +21,19 @@ DB_PASSWORD_LOCAL=postgres
|
||||
REDIS_URL=redis://localhost:6379
|
||||
REDIS_PASSWORD=
|
||||
|
||||
# ==================================== DB POOLING =====================================
|
||||
DB_HOST_POOLING=10.20.14.14
|
||||
DB_NAME_POOLING=postgres
|
||||
DB_PORT_POOLING=5432
|
||||
DB_USER_POOLING=postgres
|
||||
DB_PASSWORD_POOLING=inhc0mmute_cms
|
||||
|
||||
# ==================================== LOKI =====================================
|
||||
LOKI_URL=http://10.20.14.30:3100
|
||||
|
||||
# ==================================== APP PROMETHEUS =====================================
|
||||
PROM_APP = topuponline
|
||||
|
||||
# ================================== SECRET KEY ==================================
|
||||
# FOR PRODUCTION
|
||||
#SECRET_KEY=U2FsdGVkX19keaNhiBfdNSWnKA2a8Z5deBu/KkU6BNg=
|
||||
|
||||
@@ -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="
|
||||
|
||||
|
||||
|
||||
@@ -1,33 +1,60 @@
|
||||
require("dotenv").config();
|
||||
const winston = require("./application/helpers/winston.logger");
|
||||
const server = require("./server");
|
||||
require('dotenv').config();
|
||||
const cluster = require('node:cluster');
|
||||
const totalCPUs = require('node:os').cpus().length;
|
||||
const process = require('node:process');
|
||||
const winston = require('./application/helpers/winston.logger');
|
||||
const server = require('./server');
|
||||
|
||||
// set port, listen for requests
|
||||
const PORT = process.env.PORT || 3000;
|
||||
var serverHSMStatus = "HSM SERVER NOT CONNECTED";
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var serverHSMStatus = 'HSM SERVER NOT CONNECTED';
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '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}`;
|
||||
} 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`;
|
||||
}
|
||||
|
||||
var serverActive = "DC (DATA CENTER)";
|
||||
if (process.env.CHANGE_TO_DRC == "YES" || process.env.CHANGE_TO_DRC == "yes") {
|
||||
serverActive = "DRC (DISASTER RECOVERY CENTER)";
|
||||
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var serverActive = 'DC (DATA CENTER)';
|
||||
if (process.env.CHANGE_TO_DRC == 'YES' || process.env.CHANGE_TO_DRC == 'yes') {
|
||||
serverActive = 'DRC (DISASTER RECOVERY CENTER)';
|
||||
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '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}`;
|
||||
} 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`;
|
||||
}
|
||||
}
|
||||
|
||||
server.listen(PORT, () => {
|
||||
winston.logger.info(
|
||||
`Server is running on environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `
|
||||
);
|
||||
});
|
||||
if (cluster.isMaster) {
|
||||
console.log(`Number of CPUs is ${totalCPUs}`);
|
||||
console.log(`Master ${process.pid} is running`);
|
||||
|
||||
// Fork workers.
|
||||
for (let i = 0; i < totalCPUs; i++) {
|
||||
cluster.fork();
|
||||
}
|
||||
|
||||
cluster.on('exit', (worker, code, signal) => {
|
||||
console.log(`worker ${worker.process.pid} died`);
|
||||
console.log("Let's fork another worker!");
|
||||
cluster.fork();
|
||||
});
|
||||
} else {
|
||||
startExpress();
|
||||
}
|
||||
|
||||
console.log(`worker pid=${process.pid}`);
|
||||
|
||||
function startExpress() {
|
||||
server.listen(PORT, () => {
|
||||
winston.logger.info(
|
||||
`Server is running on version ${
|
||||
process.env.VERSION
|
||||
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
+2
-2
@@ -46,7 +46,7 @@ module.exports = {
|
||||
// connection: process.env.DB_URL,
|
||||
pool: {
|
||||
min: 2,
|
||||
max: 10,
|
||||
max: 30,
|
||||
},
|
||||
migrations: {
|
||||
directory: './infrastructure/database/migrations',
|
||||
@@ -73,7 +73,7 @@ module.exports = {
|
||||
// connection: process.env.DB_URL,
|
||||
pool: {
|
||||
min: 2,
|
||||
max: 10,
|
||||
max: 20,
|
||||
},
|
||||
migrations: {
|
||||
directory: './infrastructure/database/migrations',
|
||||
|
||||
+139
-146
@@ -12,6 +12,7 @@ const historyRoute = require('../application/routes/history.routes');
|
||||
const paymentReconRoute = require('../application/routes/paymentrecon.routes');
|
||||
const invoiceRoute = require('../application/routes/invoiceonline.routes');
|
||||
const cashinRoute = require('../application/routes/cahsin.routes');
|
||||
const pooling = require('../application/routes/pooling.routes');
|
||||
const cron = require('node-cron');
|
||||
const moment = require('moment');
|
||||
require('dotenv').config();
|
||||
@@ -22,13 +23,18 @@ const client = require('prom-client');
|
||||
const register = new client.Registry();
|
||||
const {
|
||||
topuponline_metrics,
|
||||
topuponline_metrics_response_time,
|
||||
topuponline_metrics_load_balance,
|
||||
} = require('../application/helpers/prometheusmetrics');
|
||||
|
||||
const app = express();
|
||||
|
||||
register.setDefaultLabels({ app: 'topuponline' });
|
||||
let promApp = process.env.PROM_APP || 'topuponline';
|
||||
register.setDefaultLabels({ app: promApp });
|
||||
client.collectDefaultMetrics({ register });
|
||||
register.registerMetric(topuponline_metrics);
|
||||
register.registerMetric(topuponline_metrics_response_time);
|
||||
register.registerMetric(topuponline_metrics_load_balance);
|
||||
|
||||
app.get('/metrics', (req, res) => {
|
||||
res.setHeader('Content-Type', register.contentType);
|
||||
@@ -55,23 +61,9 @@ app.use(responseTime());
|
||||
|
||||
// ============================== ROUTES API ==============================
|
||||
app.get('/', async (req, res) => {
|
||||
let data = {
|
||||
card_number: '1234567890',
|
||||
amount: 10000,
|
||||
};
|
||||
|
||||
let chipperData = helper.encryptText(JSON.stringify(data));
|
||||
let decrypData = JSON.parse(helper.decryptText(chipperData));
|
||||
res.json({
|
||||
message: 'Welcome to Topup Online Service.',
|
||||
data: {
|
||||
text: '0nlinet0pupkci',
|
||||
chiper_text: helper.encryptText('0nlinet0pupkci'),
|
||||
chipper_data: chipperData,
|
||||
decrypt_data: decrypData,
|
||||
date: moment().format('YYYYMMDDHHmm'),
|
||||
secret_key: helper.encryptText('0nlinetopupDev'),
|
||||
},
|
||||
data: {},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -87,6 +79,7 @@ app.use('/api/', paymentReconRoute);
|
||||
app.use('/api/', reservationRoute);
|
||||
app.use('/api/', invoiceRoute);
|
||||
app.use('/api/', cashinRoute);
|
||||
app.use('/api/', pooling);
|
||||
|
||||
// ============================== SAP SCHEDULLER =============================
|
||||
|
||||
@@ -96,150 +89,150 @@ app.use('/api/', cashinRoute);
|
||||
// SCHEDULER FOR GENERATE INVOICE
|
||||
// ===================================================
|
||||
|
||||
const {
|
||||
_generateInvoice,
|
||||
_postingInvoice,
|
||||
} = require('../application/modules/invoiceonline/invoice.controller');
|
||||
// const {
|
||||
// _generateInvoice,
|
||||
// _postingInvoice,
|
||||
// } = require('../application/modules/invoiceonline/invoice.controller');
|
||||
|
||||
// GENERATE + POSTING INVOICE
|
||||
cron.schedule('0 1 * * *', async () => {
|
||||
try {
|
||||
// let ivoiceDate = moment().add(1, 'days').format("YYYY-MM-DD");
|
||||
let ivoiceDate = moment().format('YYYY-MM-DD');
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
winston.logger.debug(
|
||||
`STARTING SCHEDULER-FB70 GENERATE INVOICE ${ivoiceDate} `
|
||||
);
|
||||
const generate = await _generateInvoice(ivoiceDate, uniqueCode, false);
|
||||
winston.logger.debug(
|
||||
`END SCHEDULER-FB70 GENERATE INVOICE ${ivoiceDate} : ${JSON.stringify(
|
||||
generate
|
||||
)}`
|
||||
);
|
||||
const reGenerate = await _generateInvoice(ivoiceDate, uniqueCode, true);
|
||||
winston.logger.debug(
|
||||
`END SCHEDULER-FB70 RE-GENERATE INVOICE THAT HAVE BEEN DELETED ${ivoiceDate} : ${JSON.stringify(
|
||||
generate
|
||||
)}`
|
||||
);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
}
|
||||
});
|
||||
// cron.schedule('0 1 * * *', async () => {
|
||||
// try {
|
||||
// // let ivoiceDate = moment().add(1, 'days').format("YYYY-MM-DD");
|
||||
// let ivoiceDate = moment().format('YYYY-MM-DD');
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.debug(
|
||||
// `STARTING SCHEDULER-FB70 GENERATE INVOICE ${ivoiceDate} `
|
||||
// );
|
||||
// const generate = await _generateInvoice(ivoiceDate, uniqueCode, false);
|
||||
// winston.logger.debug(
|
||||
// `END SCHEDULER-FB70 GENERATE INVOICE ${ivoiceDate} : ${JSON.stringify(
|
||||
// generate
|
||||
// )}`
|
||||
// );
|
||||
// const reGenerate = await _generateInvoice(ivoiceDate, uniqueCode, true);
|
||||
// winston.logger.debug(
|
||||
// `END SCHEDULER-FB70 RE-GENERATE INVOICE THAT HAVE BEEN DELETED ${ivoiceDate} : ${JSON.stringify(
|
||||
// generate
|
||||
// )}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
// RE-TRY POSTING
|
||||
cron.schedule('0 7 * * *', async () => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
winston.logger.debug(`STARTING SCHEDULER-FB70 RE-TRY POSTING INVOICE`);
|
||||
const posting = await _postingInvoice(uniqueCode);
|
||||
winston.logger.debug(
|
||||
`END SCHEDULER-FB70 RE-TRY POSTING INVOICE : ${JSON.stringify(posting)}`
|
||||
);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
}
|
||||
});
|
||||
// cron.schedule('0 7 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.debug(`STARTING SCHEDULER-FB70 RE-TRY POSTING INVOICE`);
|
||||
// const posting = await _postingInvoice(uniqueCode);
|
||||
// winston.logger.debug(
|
||||
// `END SCHEDULER-FB70 RE-TRY POSTING INVOICE : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
cron.schedule('0 12 * * *', async () => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
winston.logger.debug(`STARTING SCHEDULER-FB70 RE-TRY POSTING INVOICE`);
|
||||
const posting = await _postingInvoice(uniqueCode);
|
||||
winston.logger.debug(
|
||||
`END SCHEDULER-FB70 RE-TRY POSTING INVOICE : ${JSON.stringify(posting)}`
|
||||
);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
}
|
||||
});
|
||||
// cron.schedule('0 12 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.debug(`STARTING SCHEDULER-FB70 RE-TRY POSTING INVOICE`);
|
||||
// const posting = await _postingInvoice(uniqueCode);
|
||||
// winston.logger.debug(
|
||||
// `END SCHEDULER-FB70 RE-TRY POSTING INVOICE : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
cron.schedule('0 17 * * *', async () => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
winston.logger.debug(`STARTING SCHEDULER-FB70 RE-TRY POSTING INVOICE`);
|
||||
const posting = await _postingInvoice(uniqueCode);
|
||||
winston.logger.debug(
|
||||
`END SCHEDULER-FB70 RE-TRY POSTING INVOICE : ${JSON.stringify(posting)}`
|
||||
);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
}
|
||||
});
|
||||
// cron.schedule('0 17 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.debug(`STARTING SCHEDULER-FB70 RE-TRY POSTING INVOICE`);
|
||||
// const posting = await _postingInvoice(uniqueCode);
|
||||
// winston.logger.debug(
|
||||
// `END SCHEDULER-FB70 RE-TRY POSTING INVOICE : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
// ===================================================
|
||||
// SCHEDULER FOR GENERATE INVOICE
|
||||
// ===================================================
|
||||
// cash in
|
||||
const {
|
||||
_generateCashIn,
|
||||
} = require('../application/modules/cashin/cahsin.controller');
|
||||
// const {
|
||||
// _generateCashIn,
|
||||
// } = require('../application/modules/cashin/cahsin.controller');
|
||||
|
||||
cron.schedule('30 7 * * *', async () => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
winston.logger.info(
|
||||
`STARTING SCHEDULER-FB70 GENERATE CASH IN ${uniqueCode}`
|
||||
);
|
||||
const posting = await _generateCashIn(uniqueCode);
|
||||
winston.logger.info(
|
||||
`END SCHEDULER-FB70 GENERATE CASH IN : ${JSON.stringify(posting)}`
|
||||
);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 SCHEDULER-FB70 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
}
|
||||
});
|
||||
// cron.schedule('30 7 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.info(
|
||||
// `STARTING SCHEDULER-FB70 GENERATE CASH IN ${uniqueCode}`
|
||||
// );
|
||||
// const posting = await _generateCashIn(uniqueCode);
|
||||
// winston.logger.info(
|
||||
// `END SCHEDULER-FB70 GENERATE CASH IN : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 SCHEDULER-FB70 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
cron.schedule('30 12 * * *', async () => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
winston.logger.info(
|
||||
`STARTING SCHEDULER-FB70 GENERATE CASH IN ${uniqueCode}`
|
||||
);
|
||||
const posting = await _generateCashIn(uniqueCode);
|
||||
winston.logger.info(
|
||||
`END SCHEDULER-FB70 GENERATE CASH IN : ${JSON.stringify(posting)}`
|
||||
);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 SCHEDULER-FB70 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
}
|
||||
});
|
||||
// cron.schedule('30 12 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.info(
|
||||
// `STARTING SCHEDULER-FB70 GENERATE CASH IN ${uniqueCode}`
|
||||
// );
|
||||
// const posting = await _generateCashIn(uniqueCode);
|
||||
// winston.logger.info(
|
||||
// `END SCHEDULER-FB70 GENERATE CASH IN : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 SCHEDULER-FB70 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
cron.schedule('30 17 * * *', async () => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
winston.logger.info(
|
||||
`STARTING SCHEDULER-FB70 GENERATE CASH IN ${uniqueCode}`
|
||||
);
|
||||
const posting = await _generateCashIn(uniqueCode);
|
||||
winston.logger.info(
|
||||
`END SCHEDULER-FB70 GENERATE CASH IN : ${JSON.stringify(posting)}`
|
||||
);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 SCHEDULER-FB70 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
}
|
||||
});
|
||||
// cron.schedule('30 17 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.info(
|
||||
// `STARTING SCHEDULER-FB70 GENERATE CASH IN ${uniqueCode}`
|
||||
// );
|
||||
// const posting = await _generateCashIn(uniqueCode);
|
||||
// winston.logger.info(
|
||||
// `END SCHEDULER-FB70 GENERATE CASH IN : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 SCHEDULER-FB70 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
// }
|
||||
|
||||
|
||||
Reference in New Issue
Block a user