Compare commits

..

8 Commits

Author SHA1 Message Date
ihsan 40bd4b97e2 clear log debug 2023-08-30 12:38:18 +07:00
ihsan 59d77f838f update issuer fee and channel fee by nominal 2023-08-29 19:03:55 +07:00
ihsan 91f759e994 update 2023-08-25 11:12:54 +07:00
ihsan 2130890909 update 2023-08-25 10:55:04 +07:00
ihsan edc1f35e8b update 2023-08-25 10:54:11 +07:00
ihsan ceb17a5999 update 2023-08-25 10:41:54 +07:00
ihsan de01a058eb update const to let and winston to console log 2023-07-27 19:12:53 +07:00
ihsan 23ed7baf76 add max pool 2023-07-26 16:15:29 +07:00
17 changed files with 809 additions and 653 deletions
+9 -9
View File
@@ -31,8 +31,8 @@ const createHMAC = async (payload) => {
// RANDOM UNIQUE CODE // RANDOM UNIQUE CODE
function getUniqueCode() { function getUniqueCode() {
const maxDate = Date.now(); let maxDate = Date.now();
const timestamp = Math.floor(Math.random() * maxDate).toString(); let timestamp = Math.floor(Math.random() * maxDate).toString();
return timestamp; return timestamp;
} }
@@ -41,7 +41,7 @@ function getRandomArbitrary(min, max) {
} }
function randomNumberInt() { function randomNumberInt() {
const result = []; let result = [];
while (result.length !== 3) { while (result.length !== 3) {
let random = getRandomArbitrary(0, 9); let random = getRandomArbitrary(0, 9);
if (!result.includes(random)) result.push(random); if (!result.includes(random)) result.push(random);
@@ -181,9 +181,9 @@ function generateXMLRequest(urn, headers, items) {
// POSTING SAP // POSTING SAP
async function postingSAP(url, body, credential) { async function postingSAP(url, body, credential) {
try { try {
const axios = require('axios'); let axios = require('axios');
const config = { let config = {
headers: { headers: {
'Content-Type': 'text/xml', 'Content-Type': 'text/xml',
responseType: 'text', 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 { return {
status: resp.status, status: resp.status,
@@ -238,7 +238,7 @@ async function postingSAP(url, body, credential) {
// GET SOAP RESPONSE DATA // GET SOAP RESPONSE DATA
function getXMLData(response) { function getXMLData(response) {
const xml2js = require('xml2js'); let xml2js = require('xml2js');
// console.log(xmlString) // console.log(xmlString)
let resSAP = { let resSAP = {
type: '', type: '',
@@ -251,7 +251,7 @@ function getXMLData(response) {
}; };
if (response.status == 200) { if (response.status == 200) {
const options = { let options = {
explicitArray: false, explicitArray: false,
tagNameProcessors: [xml2js.processors.stripPrefix], tagNameProcessors: [xml2js.processors.stripPrefix],
}; };
@@ -293,7 +293,7 @@ function getXMLData(response) {
resSAP.type = resSAP.type =
soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][0]['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; soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'].length - 1;
let message = let message =
'[SAP] ' + '[SAP] ' +
+21 -15
View File
@@ -76,13 +76,13 @@ const loginPartnerUser = async (req, res, next) => {
// log info // log info
winston.logger.info( winston.logger.info(
`${uniqueCode} [ REQUEST LOGIN-PARTNER-USER ]: ${JSON.stringify( `${uniqueCode} [ REQUEST LOGIN-PARTNER-USER ]: ${JSON.stringify({
req.body email: email,
)}` })}`
); );
// validate // validate
const err = validationResult(req); let err = validationResult(req);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -239,11 +239,14 @@ const loginTerminal = async (req, res, next) => {
// log info // log info
winston.logger.info( winston.logger.info(
`${uniqueCode} [ REQUEST LOGIN-TERMINAL ]: ${JSON.stringify(req.body)}` `${uniqueCode} [ REQUEST LOGIN-TERMINAL ]: ${JSON.stringify({
mid: mid,
tid: tid,
})}`
); );
// validate // validate
const err = validationResult(req); let err = validationResult(req);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -410,11 +413,14 @@ const register = async (req, res) => {
// log info // log info
winston.logger.info( winston.logger.info(
`${uniqueCode} [ REQUEST REGISTER ]: ${JSON.stringify(req.body)}` `${uniqueCode} [ REQUEST REGISTER ]: ${JSON.stringify({
mid: mid,
tid: tid,
})}`
); );
// validate // validate
const err = validationResult(req); let err = validationResult(req);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -482,7 +488,7 @@ const register = async (req, res) => {
); );
// encrypt password // encrypt password
const saltRounds = 10; let saltRounds = 10;
let salt = bcrypt.genSaltSync(saltRounds); let salt = bcrypt.genSaltSync(saltRounds);
let passwordHash = bcrypt.hashSync(password, salt); let passwordHash = bcrypt.hashSync(password, salt);
@@ -549,8 +555,8 @@ const refreshTokenTerminal = async (req, res) => {
let uniqueCode = await helper.getUniqueCode(); let uniqueCode = await helper.getUniqueCode();
let result = {}; let result = {};
const { mid, tid } = req.body; let { mid, tid } = req.body;
const refresh_token = req.header('refresh_token'); let refresh_token = req.header('refresh_token');
// log info // log info
winston.logger.info( winston.logger.info(
@@ -560,7 +566,7 @@ const refreshTokenTerminal = async (req, res) => {
); );
// validate // validate
const err = validationResult(req); let err = validationResult(req);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -695,8 +701,8 @@ const refreshTokenPartnerUser = async (req, res) => {
let uniqueCode = await helper.getUniqueCode(); let uniqueCode = await helper.getUniqueCode();
let result = {}; let result = {};
const { email } = req.body; let { email } = req.body;
const refresh_token = req.header('refresh_token'); let refresh_token = req.header('refresh_token');
// log info // log info
winston.logger.info( winston.logger.info(
@@ -706,7 +712,7 @@ const refreshTokenPartnerUser = async (req, res) => {
); );
// validate // validate
const err = validationResult(req); let err = validationResult(req);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -1,16 +1,16 @@
const { param, body, validationResult } = require("express-validator"); const { param, body, validationResult } = require('express-validator');
const helper = require("../../helpers/helper"); const helper = require('../../helpers/helper');
const winston = require("../../helpers/winston.logger"); const winston = require('../../helpers/winston.logger');
const model = require("./dongleorder.model"); const model = require('./dongleorder.model');
const moment = require("moment"); const moment = require('moment');
moment.locale("id"); moment.locale('id');
// VALIDATION // VALIDATION
const validate = (method) => { const validate = (method) => {
switch (method) { switch (method) {
case "dongleOrderUpdate": case 'dongleOrderUpdate':
return [ return [
body("dongle_id").not().isEmpty().withMessage("Dongle ID is required"), body('dongle_id').not().isEmpty().withMessage('Dongle ID is required'),
]; ];
default: default:
break; break;
@@ -20,12 +20,11 @@ const validate = (method) => {
// GET DONGLE ORDER // GET DONGLE ORDER
const getDongleOrder = async (req, res) => { const getDongleOrder = async (req, res) => {
try { try {
let uniqueCode = await helper.getUniqueCode(); let uniqueCode = await helper.getUniqueCode();
let result = {}; let result = {};
// param // param
let year = req.query.year; let year = req.query.year;
if (!year) { if (!year) {
year = moment().format('YYYY'); year = moment().format('YYYY');
@@ -38,7 +37,7 @@ const getDongleOrder = async (req, res) => {
let getRO = await model.getRO(year); let getRO = await model.getRO(year);
if (getRO.length == 0) { if (getRO.length == 0) {
result = { result = {
code: "422", code: '422',
message: "data doesn't exists'", message: "data doesn't exists'",
data: [], data: [],
}; };
@@ -54,14 +53,16 @@ const getDongleOrder = async (req, res) => {
} }
result = { result = {
code: "00", code: '00',
message: "success", message: 'success',
data: getRO, data: getRO,
}; };
// log info // log info
winston.logger.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); return res.json(result);
@@ -72,11 +73,11 @@ const getDongleOrder = async (req, res) => {
); );
return res.status(200).json({ return res.status(200).json({
code: "500", code: '500',
message: message:
process.env.NODE_ENV != "production" process.env.NODE_ENV != 'production'
? error.message ? error.message
: "500 internal server error - backend server.", : '500 internal server error - backend server.',
data: {}, data: {},
}); });
} }
@@ -86,9 +87,7 @@ const getDongleOrder = async (req, res) => {
const updateDongleOrder = async (req, res) => { const updateDongleOrder = async (req, res) => {
try { try {
// param // param
let { let { dongle_id, status } = req.body;
dongle_id, status
} = req.body;
let uniqueCode = await helper.getUniqueCode(); let uniqueCode = await helper.getUniqueCode();
let result = {}; let result = {};
@@ -99,10 +98,10 @@ const updateDongleOrder = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: "400", code: '400',
message: err.errors[0].msg, message: err.errors[0].msg,
data: {}, data: {},
}; };
@@ -116,39 +115,40 @@ const updateDongleOrder = async (req, res) => {
} }
// time // time
let now = moment().format("YYYY-MM-DD HH:mm:ss"); let now = moment().format('YYYY-MM-DD HH:mm:ss');
// log debug // log debug
winston.logger.debug(`${uniqueCode} updating dongle order...`); winston.logger.debug(`${uniqueCode} updating dongle order...`);
let data = { let data = {
c_status: status == "C" ? "C" : "I", c_status: status == 'C' ? 'C' : 'I',
c_status_name: status == "C" ? "CREATED" : "INJECTED", c_status_name: status == 'C' ? 'CREATED' : 'INJECTED',
d_modify: now, d_modify: now,
} };
// get partner, merchant, terminal from tid // get partner, merchant, terminal from tid
let updateDongleOrderStatus = await model.updateDongleOrderStatus(data, dongle_id); let updateDongleOrderStatus = await model.updateDongleOrderStatus(
data,
dongle_id
);
if (!updateDongleOrderStatus) { if (!updateDongleOrderStatus) {
result = { result = {
code: "423", code: '423',
message: "update failed", message: 'update failed',
data: {}, data: {},
}; };
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} RESPONSE update dongle order: ${JSON.stringify( `${uniqueCode} RESPONSE update dongle order: ${JSON.stringify(result)}`
result
)}`
); );
return res.status(200).json(result); return res.status(200).json(result);
} }
result = { result = {
code: "00", code: '00',
message: "updated successfully", message: 'updated successfully',
data: {}, data: {},
}; };
@@ -165,11 +165,11 @@ const updateDongleOrder = async (req, res) => {
); );
return res.status(200).json({ return res.status(200).json({
code: "500", code: '500',
message: message:
process.env.NODE_ENV != "production" process.env.NODE_ENV != 'production'
? error.message ? error.message
: "500 internal server error - backend server.", : '500 internal server error - backend server.',
data: {}, data: {},
}); });
} }
@@ -53,7 +53,7 @@ const cardHistory = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -206,7 +206,7 @@ const history = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
+24
View File
@@ -59,6 +59,7 @@ const controller = async (req, res) => {
let _validationTrxID = Buffer.from(generate.hexToBytes(body.trxID)); let _validationTrxID = Buffer.from(generate.hexToBytes(body.trxID));
let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData)); let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData));
let _stopMessage = 1; let _stopMessage = 1;
let _timeOut = false;
if (auth2v2requestData[0] != 0x41) { if (auth2v2requestData[0] != 0x41) {
result = { result = {
@@ -88,6 +89,12 @@ const controller = async (req, res) => {
let respData = null; let respData = null;
let respData1 = null; let respData1 = null;
setInterval(function () {
respData = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
_timeOut = true;
}, 10000);
useClient.ws.on('message', (message) => { useClient.ws.on('message', (message) => {
while ( while (
message[2] == 2 && message[2] == 2 &&
@@ -114,6 +121,23 @@ const controller = async (req, res) => {
await _sleep(10); 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; _stopMessage = 0;
transactionId[0] = respData[0]; transactionId[0] = respData[0];
+60 -46
View File
@@ -1,33 +1,33 @@
const WebSocket = require("ws"); const WebSocket = require('ws');
const checkInternetConnected = require("check-internet-connected"); const checkInternetConnected = require('check-internet-connected');
const winston = require("../../../helpers/winston.logger"); const winston = require('../../../helpers/winston.logger');
const fs = require("fs"); const fs = require('fs');
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const generate = require("../utils/utils"); const generate = require('../utils/utils');
require("dotenv").config(); require('dotenv').config();
let ssl_ca_crt = "./application/assets/cert/CACerts.pem"; let ssl_ca_crt = './application/assets/cert/CACerts.pem';
let ssl_client_pfx = "./application/assets/cert/FeliqClient0002-03.pfx"; let ssl_client_pfx = './application/assets/cert/FeliqClient0002-03.pfx';
let options = { let options = {
ca: fs.readFileSync(ssl_ca_crt), ca: fs.readFileSync(ssl_ca_crt),
agent: false, agent: false,
passphrase: "GPqs+Uia78", passphrase: 'GPqs+Uia78',
pfx: fs.readFileSync(ssl_client_pfx), pfx: fs.readFileSync(ssl_client_pfx),
}; };
// check config HSM // check config HSM
if ( if (
process.env.URL_HSM_SERVER_1 == "" || process.env.URL_HSM_SERVER_1 == '' ||
process.env.APIKEY_HSM_SERVER_1 == "" || process.env.APIKEY_HSM_SERVER_1 == '' ||
process.env.SECRETKEY_HSM_SERVER_1 == "" process.env.SECRETKEY_HSM_SERVER_1 == ''
) { ) {
// create log // create log
winston.logger.error(`PLEASE CONFIGURE HSM SERVER ON THE ENVIRONMENT!`); winston.logger.error(`PLEASE CONFIGURE HSM SERVER ON THE ENVIRONMENT!`);
} }
// check system code // check system code
if (process.env.SYSTEM_CODE == "") { if (process.env.SYSTEM_CODE == '') {
// create log // create log
winston.logger.error(`PLEASE CONFIGURE SYSTEM CODE ON THE ENVIRONMENT!`); winston.logger.error(`PLEASE CONFIGURE SYSTEM CODE ON THE ENVIRONMENT!`);
} }
@@ -38,7 +38,7 @@ var apiKeyBytes;
var secretBytes; var secretBytes;
var systemCode = Buffer.from(generate.hexToBytes(process.env.SYSTEM_CODE)); 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 // config for DRC
url = process.env.URL_HSM_SERVER_BACKUP_1; url = process.env.URL_HSM_SERVER_BACKUP_1;
apiKeyBytes = Buffer.from(process.env.APIKEY_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 = { const config = {
timeout: 1000, //timeout connecting to each server, each try timeout: 1000, //timeout connecting to each server, each try
retries: 5, //number of retries to do before failing 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; var interval;
@@ -62,16 +62,16 @@ function startInterval() {
interval = setInterval(function () { interval = setInterval(function () {
checkInternetConnected(config) checkInternetConnected(config)
.then((result) => { .then((result) => {
// console.log(result); //successfully connected to a server console.log(`retry open websocket server 1`); //successfully connected to a server
// log debug // log debug
winston.logger.debug(`retry open websocket server 1`); // winston.logger.debug(`retry open websocket server 1`);
client.open(); client.open();
stopInterval(); stopInterval();
}) })
.catch((ex) => { .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 // log error
winston.logger.error(`error start interval server 1 : ${ex}`); // winston.logger.error(`error start interval server 1 : ${ex}`);
}); });
}, 5900); }, 5900);
} }
@@ -91,9 +91,9 @@ class WebSocketClient {
if (this.ws == null) { if (this.ws == null) {
this.ws = new WebSocket(url, [], options); this.ws = new WebSocket(url, [], options);
this.ws.on("open", this.onOpen); this.ws.on('open', this.onOpen);
this.ws.on("close", this.onClose); this.ws.on('close', this.onClose);
this.ws.on("error", this.onError); this.ws.on('error', this.onError);
this.ws.setMaxListeners(0); this.ws.setMaxListeners(0);
} }
@@ -106,37 +106,41 @@ class WebSocketClient {
// Disconnection of WebSocket // Disconnection of WebSocket
close = () => { close = () => {
this.ws.close(); this.ws.close();
// console.log('WebSocket Close'); console.log(`websocket server 1 close`);
// log debug // log debug
winston.logger.debug(`websocket server 1 close`); // winston.logger.debug(`websocket server 1 close`);
}; };
// Open event // Open event
onOpen = () => { onOpen = () => {
// console.log("WebSocket Open"); console.log(`opening websocket server 1`);
// log debug // log debug
winston.logger.debug(`opening websocket server 1`); // winston.logger.debug(`opening websocket server 1`);
if (this.isOpened()) { if (this.isOpened()) {
console.log(`websocket server 1 open successfully`);
// log debug // log debug
winston.logger.debug(`websocket server 1 open successfully`); // winston.logger.debug(`websocket server 1 open successfully`);
if (!this.clientAuthenticated) { if (!this.clientAuthenticated) {
this.clientAuth(); this.clientAuth();
} }
} else { } else {
console.log(`websocket server 1 open failed`);
// log error // log error
winston.logger.error(`websocket server 1 open failed`); // winston.logger.error(`websocket server 1 open failed`);
} }
}; };
onClose = () => { onClose = () => {
// console.log("WebSocket Close"); console.log(`websocket server 1 close`);
// log debug // log debug
winston.logger.debug(`websocket server 1 close`); // winston.logger.debug(`websocket server 1 close`);
this.clientAuthenticated = false; this.clientAuthenticated = false;
this.ws = null; this.ws = null;
@@ -144,10 +148,10 @@ class WebSocketClient {
}; };
onError = () => { onError = () => {
// console.log("WebSocket Error"); console.log(`websocket server 1 error`);
// log error // log error
winston.logger.error(`websocket server 1 error`); // winston.logger.error(`websocket server 1 error`);
this.clientAuthenticated = false; this.clientAuthenticated = false;
}; };
@@ -196,7 +200,7 @@ class WebSocketClient {
this.sendData(reqData); this.sendData(reqData);
this.ws.on("message", (message) => { this.ws.on('message', (message) => {
let __validasi = generate.buf2hex(message).slice(14, 30); let __validasi = generate.buf2hex(message).slice(14, 30);
while ( while (
message[2] == 0 && message[2] == 0 &&
@@ -205,13 +209,15 @@ class WebSocketClient {
message[1] == 0 message[1] == 0
) { ) {
respData = null; respData = null;
// console.log("*WS MESSAGE Tenan: " + generate.buf2hex(message)); console.log(
// log debug
winston.logger.debug(
`websocket server 1 message tenant: ${generate.buf2hex(message)}` `websocket server 1 message tenant: ${generate.buf2hex(message)}`
); );
// log debug
// winston.logger.debug(
// `websocket server 1 message tenant: ${generate.buf2hex(message)}`
// );
respData = message; respData = message;
_stopMessage = 2; _stopMessage = 2;
} }
@@ -221,30 +227,36 @@ class WebSocketClient {
await _sleep(10); await _sleep(10);
} }
let respCode = generate.getResponseCode(respData); let respCode = generate.getResponseCode(respData);
// console.log(`Resp Data Tenant = ${respCode}`); console.log(`websocket server 1 resp data tenant: ${respCode}`);
// log debug // 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; this.clientAuthenticated = true;
} }
// console.log(`clientAuthenticated = ${this.clientAuthenticated}`); console.log(
// log debug
winston.logger.debug(
`websocket server 1 client authenticate: ${this.clientAuthenticated}` `websocket server 1 client authenticate: ${this.clientAuthenticated}`
); );
// log debug
// winston.logger.debug(
// `websocket server 1 client authenticate: ${this.clientAuthenticated}`
// );
} catch (error) { } catch (error) {
// console.log(`error ${error}`); console.log(`websocket error: ${error}`);
// log error // log error
winston.logger.error(`websocket error: ${error}`); // winston.logger.error(`websocket error: ${error}`);
} }
} }
} }
var client = new WebSocketClient(); var client = new WebSocketClient();
if (!client.openWebSocketStatus) { if (!client.openWebSocketStatus) {
console.log(`first open websocket server 1`);
// log info // log info
winston.logger.info(`first open websocket server 1`); // winston.logger.info(`first open websocket server 1`);
client.open(); client.open();
} }
@@ -252,6 +264,8 @@ setInterval(function () {
// let statusConnection = client.clientAuthenticated; // let statusConnection = client.clientAuthenticated;
// if (!statusConnection) { // if (!statusConnection) {
if (!this.ws) { if (!this.ws) {
console.log(`websocket server 1 retry call client Auth`);
// log debug // log debug
// winston.logger.debug(`retry call client Auth`); // winston.logger.debug(`retry call client Auth`);
client.clientAuth(); client.clientAuth();
+63 -47
View File
@@ -1,33 +1,33 @@
const WebSocket = require("ws"); const WebSocket = require('ws');
const checkInternetConnected = require("check-internet-connected"); const checkInternetConnected = require('check-internet-connected');
const winston = require("../../../helpers/winston.logger"); const winston = require('../../../helpers/winston.logger');
const fs = require("fs"); const fs = require('fs');
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const generate = require("../utils/utils"); const generate = require('../utils/utils');
require("dotenv").config(); require('dotenv').config();
let ssl_ca_crt = "./application/assets/cert/CACerts.pem"; let ssl_ca_crt = './application/assets/cert/CACerts.pem';
let ssl_client_pfx = "./application/assets/cert/FeliqClient0002-03.pfx"; let ssl_client_pfx = './application/assets/cert/FeliqClient0002-03.pfx';
let options = { let options = {
ca: fs.readFileSync(ssl_ca_crt), ca: fs.readFileSync(ssl_ca_crt),
agent: false, agent: false,
passphrase: "GPqs+Uia78", passphrase: 'GPqs+Uia78',
pfx: fs.readFileSync(ssl_client_pfx), pfx: fs.readFileSync(ssl_client_pfx),
}; };
// check config HSM // check config HSM
if ( if (
process.env.URL_HSM_SERVER_2 == "" || process.env.URL_HSM_SERVER_2 == '' ||
process.env.APIKEY_HSM_SERVER_2 == "" || process.env.APIKEY_HSM_SERVER_2 == '' ||
process.env.SECRETKEY_HSM_SERVER_2 == "" process.env.SECRETKEY_HSM_SERVER_2 == ''
) { ) {
// create log // create log
winston.logger.error(`PLEASE CONFIGURE HSM SERVER ON THE ENVIRONMENT!`); winston.logger.error(`PLEASE CONFIGURE HSM SERVER ON THE ENVIRONMENT!`);
} }
// check system code // check system code
if (process.env.SYSTEM_CODE == "") { if (process.env.SYSTEM_CODE == '') {
// create log // create log
winston.logger.error(`PLEASE CONFIGURE SYSTEM CODE ON THE ENVIRONMENT!`); winston.logger.error(`PLEASE CONFIGURE SYSTEM CODE ON THE ENVIRONMENT!`);
} }
@@ -38,7 +38,7 @@ var apiKeyBytes;
var secretBytes; var secretBytes;
var systemCode = Buffer.from(generate.hexToBytes(process.env.SYSTEM_CODE)); 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 // config for DRC
url = process.env.URL_HSM_SERVER_BACKUP_2; url = process.env.URL_HSM_SERVER_BACKUP_2;
apiKeyBytes = Buffer.from(process.env.APIKEY_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 = { const config = {
timeout: 1000, //timeout connecting to each server, each try timeout: 1000, //timeout connecting to each server, each try
retries: 5, //number of retries to do before failing 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; var interval;
@@ -62,16 +62,17 @@ function startInterval() {
interval = setInterval(function () { interval = setInterval(function () {
checkInternetConnected(config) checkInternetConnected(config)
.then((result) => { .then((result) => {
// console.log(result); //successfully connected to a server console.log(`retry open websocket server 2`); //successfully connected to a server
// log debug // log debug
winston.logger.debug(`retry open websocket server 2`); // winston.logger.debug(`retry open websocket server 2`);
client2.open(); client2.open();
stopInterval(); stopInterval();
}) })
.catch((ex) => { .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 // log error
winston.logger.error(`error start interval server 2 : ${ex}`); // winston.logger.error(`error start interval server 2 : ${ex}`);
}); });
}, 5900); }, 5900);
} }
@@ -91,9 +92,9 @@ class WebSocketClient {
if (this.ws == null) { if (this.ws == null) {
this.ws = new WebSocket(url, [], options); this.ws = new WebSocket(url, [], options);
this.ws.on("open", this.onOpen); this.ws.on('open', this.onOpen);
this.ws.on("close", this.onClose); this.ws.on('close', this.onClose);
this.ws.on("error", this.onError); this.ws.on('error', this.onError);
this.ws.setMaxListeners(0); this.ws.setMaxListeners(0);
} }
@@ -106,37 +107,41 @@ class WebSocketClient {
// Disconnection of WebSocket // Disconnection of WebSocket
close = () => { close = () => {
this.ws.close(); this.ws.close();
// console.log('WebSocket Close'); console.log(`websocket server 2 close`);
// log debug // log debug
winston.logger.debug(`websocket server 2 close`); // winston.logger.debug(`websocket server 2 close`);
}; };
// Open event // Open event
onOpen = () => { onOpen = () => {
// console.log("WebSocket Open"); console.log(`opening server 2 websocket`);
// log debug // log debug
winston.logger.debug(`opening server 2 websocket`); // winston.logger.debug(`opening server 2 websocket`);
if (this.isOpened()) { if (this.isOpened()) {
console.log(`websocket server 2 open successfully`);
// log debug // log debug
winston.logger.debug(`websocket server 2 open successfully`); // winston.logger.debug(`websocket server 2 open successfully`);
if (!this.clientAuthenticated) { if (!this.clientAuthenticated) {
this.clientAuth(); this.clientAuth();
} }
} else { } else {
console.log(`websocket server 2 open failed`);
// log error // log error
winston.logger.error(`websocket server 2 open failed`); // winston.logger.error(`websocket server 2 open failed`);
} }
}; };
onClose = () => { onClose = () => {
// console.log("WebSocket Close"); console.log(`websocket server 2 close`);
// log debug // log debug
winston.logger.debug(`websocket server 2 close`); // winston.logger.debug(`websocket server 2 close`);
this.clientAuthenticated = false; this.clientAuthenticated = false;
this.ws = null; this.ws = null;
@@ -144,10 +149,10 @@ class WebSocketClient {
}; };
onError = () => { onError = () => {
// console.log("WebSocket Error"); console.log(`websocket server 2 error`);
// log error // log error
winston.logger.error(`websocket server 2 error`); // winston.logger.error(`websocket server 2 error`);
this.clientAuthenticated = false; this.clientAuthenticated = false;
}; };
@@ -196,7 +201,7 @@ class WebSocketClient {
this.sendData(reqData); this.sendData(reqData);
this.ws.on("message", (message) => { this.ws.on('message', (message) => {
let __validasi = generate.buf2hex(message).slice(14, 30); let __validasi = generate.buf2hex(message).slice(14, 30);
while ( while (
message[2] == 0 && message[2] == 0 &&
@@ -205,13 +210,15 @@ class WebSocketClient {
message[1] == 0 message[1] == 0
) { ) {
respData = null; respData = null;
// console.log("*WS MESSAGE Tenan: " + generate.buf2hex(message)); console.log(
// log debug
winston.logger.debug(
`websocket server 2 message tenant: ${generate.buf2hex(message)}` `websocket server 2 message tenant: ${generate.buf2hex(message)}`
); );
// log debug
// winston.logger.debug(
// `websocket server 2 message tenant: ${generate.buf2hex(message)}`
// );
respData = message; respData = message;
_stopMessage = 2; _stopMessage = 2;
} }
@@ -221,30 +228,37 @@ class WebSocketClient {
await _sleep(10); await _sleep(10);
} }
let respCode = generate.getResponseCode(respData); let respCode = generate.getResponseCode(respData);
// console.log(`Resp Data Tenant = ${respCode}`); console.log(`websocket server 2 resp data tenant: ${respCode}`);
// log debug
winston.logger.debug(`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; this.clientAuthenticated = true;
} }
// console.log(`clientAuthenticated = ${this.clientAuthenticated}`); console.log(
// log debug
winston.logger.debug(
`websocket server 2 client authenticate: ${this.clientAuthenticated}` `websocket server 2 client authenticate: ${this.clientAuthenticated}`
); );
// log debug
// winston.logger.debug(
// `websocket server 2 client authenticate: ${this.clientAuthenticated}`
// );
} catch (error) { } catch (error) {
// console.log(`error ${error}`); console.log(`websocket server 2 error: ${error}`);
// log error // log error
winston.logger.error(`websocket server 2 error: ${error}`); // winston.logger.error(`websocket server 2 error: ${error}`);
} }
} }
} }
var client2 = new WebSocketClient(); var client2 = new WebSocketClient();
if (!client2.openWebSocketStatus) { if (!client2.openWebSocketStatus) {
console.log(`first open websocket server 2`);
// log info // log info
winston.logger.info(`first open websocket server 2`); // winston.logger.info(`first open websocket server 2`);
client2.open(); client2.open();
} }
@@ -252,6 +266,8 @@ setInterval(function () {
// let statusConnection = client2.clientAuthenticated; // let statusConnection = client2.clientAuthenticated;
// if (!statusConnection) { // if (!statusConnection) {
if (!this.ws) { if (!this.ws) {
console.log(`websocket server 2 retry call client Auth`);
// log debug // log debug
// winston.logger.debug(`retry call client Auth`); // winston.logger.debug(`retry call client Auth`);
client2.clientAuth(); client2.clientAuth();
+1 -1
View File
@@ -106,7 +106,7 @@ const controller = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
+129 -114
View File
@@ -1,157 +1,172 @@
const { Buffer } = require("buffer") const { Buffer } = require('buffer');
const fs = require('fs') const fs = require('fs');
// Generate request data for FeliQ Server // Generate request data for FeliQ Server
function makeRequestData(transactionId, apiId, data){ function makeRequestData(transactionId, apiId, data) {
let request = Buffer.alloc(2 + 1 + 1 + data.length) let request = Buffer.alloc(2 + 1 + 1 + data.length);
let dataSize = Buffer.alloc(1) let dataSize = Buffer.alloc(1);
dataSize[0] = data.length dataSize[0] = data.length;
request = Buffer.concat([transactionId, apiId, dataSize, data]) request = Buffer.concat([transactionId, apiId, dataSize, data]);
return request; return request;
} }
// Extract response code from API response data // Extract response code from API response data
function getResponseCode(data){ function getResponseCode(data) {
let respCode = Buffer.alloc(2) let respCode = Buffer.alloc(2);
respCode[0] = data[3] respCode[0] = data[3];
respCode[1] = data[4] respCode[1] = data[4];
return buf2hex(respCode) return buf2hex(respCode);
} }
// Extract response data from API response data // Extract response data from API response data
function getResponseData(apiData){ function getResponseData(apiData) {
let data = Buffer.alloc(apiData[5]) let data = Buffer.alloc(apiData[5]);
apiData.copy(data, 0, 6, apiData[5]+6) apiData.copy(data, 0, 6, apiData[5] + 6);
return buf2hex(data); return buf2hex(data);
} }
function buf2hex(buffer) {
function buf2hex(buffer){ // buffer is an ArrayBuffer // buffer is an ArrayBuffer
return [...new Uint8Array(buffer)] return [...new Uint8Array(buffer)]
.map(x => x.toString(16).padStart(2, '0')) .map((x) => x.toString(16).padStart(2, '0'))
.join('') .join('');
} }
function hexToBytes(hex) { function hexToBytes(hex) {
for (var bytes = [], c = 0; c < hex.length; c += 2) for (var bytes = [], c = 0; c < hex.length; c += 2)
bytes.push(parseInt(hex.substr(c, 2), 16)) bytes.push(parseInt(hex.substr(c, 2), 16));
return bytes return bytes;
} }
function hex2ascii(hexx) { function hex2ascii(hexx) {
let hex = hexx.toString();//force conversion let hex = hexx.toString(); //force conversion
let str = '' let str = '';
for (var i = 0; i < hex.length; i += 2) for (var i = 0; i < hex.length; i += 2)
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16)) str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
return str return str;
} }
const formatDate = (date, type) => { const formatDate = (date, type) => {
var inputDate = new Date(date); var inputDate = new Date(date);
let tanggal = inputDate.getDate() let tanggal = inputDate.getDate();
let bulan = inputDate.getMonth() + 1 let bulan = inputDate.getMonth() + 1;
let tahun = inputDate.getFullYear() let tahun = inputDate.getFullYear();
let jam = inputDate.getHours() let jam = inputDate.getHours();
let menit = inputDate.getMinutes() let menit = inputDate.getMinutes();
let detik = inputDate.getSeconds() let detik = inputDate.getSeconds();
if (bulan.toString().length < 2) bulan = '0' + bulan if (bulan.toString().length < 2) bulan = '0' + bulan;
if (tanggal.toString().length < 2) tanggal = '0' + tanggal if (tanggal.toString().length < 2) tanggal = '0' + tanggal;
if (jam.toString().length < 2) jam = '0' + jam if (jam.toString().length < 2) jam = '0' + jam;
if (menit.toString().length < 2) menit = '0' + menit if (menit.toString().length < 2) menit = '0' + menit;
if (detik.toString().length < 2) detik = '0' + detik if (detik.toString().length < 2) detik = '0' + detik;
let formatTanggal = [tahun, bulan, tanggal].join('') let formatTanggal = [tahun, bulan, tanggal].join('');
let formatWaktu = [jam, menit, detik].join('') let formatWaktu = [jam, menit, detik].join('');
return [formatTanggal, formatWaktu].join('') return [formatTanggal, formatWaktu].join('');
} };
function getTranscode(cardData, nominal){ function getTranscode(cardData, nominal) {
let trxType = Buffer.from([0x02]) let trxType = Buffer.from([0x02]);
let uid = Buffer.alloc(8) let uid = Buffer.alloc(8);
let cardType = Buffer.alloc(2) let cardType = Buffer.alloc(2);
var cardNumber = Buffer.alloc(16) var cardNumber = Buffer.alloc(16);
cardData.copy(cardNumber, 0, 12+16, 12+16+16) cardData.copy(cardNumber, 0, 12 + 16, 12 + 16 + 16);
cardNumber = cardNumber.toString() cardNumber = cardNumber.toString();
cardData.copy(uid, 0, 1,9) cardData.copy(uid, 0, 1, 9);
let _cardNumber = Buffer.from(hexToBytes(cardNumber)) let _cardNumber = Buffer.from(hexToBytes(cardNumber));
var balanceArray = Buffer.alloc(4) var balanceArray = Buffer.alloc(4);
var balanceArrayExis = Buffer.alloc(4) var balanceArrayExis = Buffer.alloc(4);
var exec_idArray = Buffer.alloc(2) var exec_idArray = Buffer.alloc(2);
cardData.copy(balanceArray, 0, 12+16+16, 12+16+16+4) cardData.copy(balanceArray, 0, 12 + 16 + 16, 12 + 16 + 16 + 4);
cardData.copy(balanceArrayExis, 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[1] = cardData[cardData.length - 1];
exec_idArray[0] = cardData[cardData.length -2] exec_idArray[0] = cardData[cardData.length - 2];
let balanceExisting = balanceArrayExis.reverse() let balanceExisting = balanceArrayExis.reverse();
let nominalStr = Buffer.from(hexToBytes(String(nominal).padStart(8, '0'))) let nominalStr = Buffer.from(hexToBytes(String(nominal).padStart(8, '0')));
let balance = Buffer.from(balanceArray).readInt32LE() let balance = Buffer.from(balanceArray).readInt32LE();
balance += parseInt(nominal) balance += parseInt(nominal);
balanceArray.writeInt32LE(balance) balanceArray.writeInt32LE(balance);
let balanceAfter = balanceArray.reverse() let balanceAfter = balanceArray.reverse();
let dateTime = Buffer.from(hexToBytes(formatDate(new Date()))) let dateTime = Buffer.from(hexToBytes(formatDate(new Date())));
cardData.copy(cardType,0, 1 + 8 + 3 + 1, 1 + 8 + 3 + 1 + 2) cardData.copy(cardType, 0, 1 + 8 + 3 + 1, 1 + 8 + 3 + 1 + 2);
let samID = Buffer.alloc(8) let samID = Buffer.alloc(8);
let samBalBefore = Buffer.alloc(4) let samBalBefore = Buffer.alloc(4);
let samBalAfter = Buffer.alloc(4) let samBalAfter = Buffer.alloc(4);
let exec_id = exec_idArray.readUInt16BE() let exec_id = exec_idArray.readUInt16BE();
exec_id++ exec_id++;
exec_idArray.writeUInt16BE(exec_id) exec_idArray.writeUInt16BE(exec_id);
let _transcode = Buffer.concat([trxType, _cardNumber, balanceExisting, nominalStr, balanceAfter,dateTime, let _transcode = Buffer.concat([
cardType, uid, samID, samBalBefore, samBalAfter, exec_idArray]) trxType,
return _transcode _cardNumber,
balanceExisting,
nominalStr,
balanceAfter,
dateTime,
cardType,
uid,
samID,
samBalBefore,
samBalAfter,
exec_idArray,
]);
return _transcode;
} }
const logging = (date, title, message, id = 0) => { const logging = (date, title, message, id = 0) => {
let month = date.getMonth() + 1; let month = date.getMonth() + 1;
try { try {
//create folder/file if not exists //create folder/file if not exists
if (!fs.existsSync(`./logs`)) { if (!fs.existsSync(`./logs`)) {
fs.mkdirSync(`./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
} }
} 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 = { module.exports = {
makeRequestData, makeRequestData,
getResponseCode, getResponseCode,
getResponseData, getResponseData,
buf2hex, buf2hex,
hexToBytes, hexToBytes,
hex2ascii, hex2ascii,
getTranscode, getTranscode,
logging logging,
} };
@@ -1,38 +1,38 @@
const { param, body, validationResult } = require("express-validator"); const { param, body, validationResult } = require('express-validator');
const helper = require("../../helpers/helper"); const helper = require('../../helpers/helper');
const winston = require("../../helpers/winston.logger"); const winston = require('../../helpers/winston.logger');
const model = require("./invoice.model"); const model = require('./invoice.model');
const moment = require("moment"); const moment = require('moment');
const knex = require("../../../infrastructure/database/knex"); const knex = require('../../../infrastructure/database/knex');
moment.locale("id"); moment.locale('id');
// VALIDATION // VALIDATION
const validate = (method) => { const validate = (method) => {
switch (method) { switch (method) {
case "generateInvoice": case 'generateInvoice':
return [ return [
body("trx_date") body('trx_date')
.notEmpty() .notEmpty()
.withMessage("trx_date is required!") .withMessage('trx_date is required!')
.isISO8601() .isISO8601()
.withMessage("invalid trx_date format YYYY-MM-DD !") .withMessage('invalid trx_date format YYYY-MM-DD !')
.escape() .escape()
.trim(), .trim(),
body("repost") body('repost')
.notEmpty() .notEmpty()
.withMessage("repost is required!") .withMessage('repost is required!')
.isBoolean() .isBoolean()
.withMessage("repost must boolean!") .withMessage('repost must boolean!')
.escape() .escape()
.trim(), .trim(),
]; ];
case "postingInvoice": case 'postingInvoice':
return [ return [
body("trx_date") body('trx_date')
.notEmpty() .notEmpty()
.withMessage("trx_date is required!") .withMessage('trx_date is required!')
.isISO8601() .isISO8601()
.withMessage("invalid trx_date format YYYY-MM-DD !") .withMessage('invalid trx_date format YYYY-MM-DD !')
.escape() .escape()
.trim(), .trim(),
]; ];
@@ -54,10 +54,10 @@ const apiGenerateInvoice = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: "400", code: '400',
message: err.errors[0].msg, message: err.errors[0].msg,
data: {}, data: {},
}; };
@@ -71,7 +71,7 @@ const apiGenerateInvoice = async (req, res) => {
} }
// time // 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( let invoice = await _generateInvoice(
invoiceDate, invoiceDate,
@@ -80,8 +80,8 @@ const apiGenerateInvoice = async (req, res) => {
); );
result = { result = {
code: "200", code: '200',
message: "Succes posting", message: 'Succes posting',
data: invoice, data: invoice,
}; };
@@ -93,11 +93,11 @@ const apiGenerateInvoice = async (req, res) => {
); );
return res.status(200).json({ return res.status(200).json({
code: "500", code: '500',
message: message:
process.env.NODE_ENV != "production" process.env.NODE_ENV != 'production'
? error.message ? error.message
: "500 internal server error - backend server.", : '500 internal server error - backend server.',
data: {}, data: {},
}); });
} }
@@ -116,10 +116,10 @@ const apiPostingInvoice = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: "400", code: '400',
message: err.errors[0].msg, message: err.errors[0].msg,
data: {}, data: {},
}; };
@@ -135,11 +135,11 @@ const apiPostingInvoice = async (req, res) => {
// return uniqueCode // return uniqueCode
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING INVOICE`); winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING INVOICE`);
const invoice = await _postingInvoice(uniqueCode); let invoice = await _postingInvoice(uniqueCode);
result = { result = {
code: "200", code: '200',
message: "Succes", message: 'Succes',
data: invoice, data: invoice,
}; };
@@ -151,11 +151,11 @@ const apiPostingInvoice = async (req, res) => {
); );
return res.status(200).json({ return res.status(200).json({
code: "500", code: '500',
message: message:
process.env.NODE_ENV != "production" process.env.NODE_ENV != 'production'
? error.message ? error.message
: "500 internal server error - backend server.", : '500 internal server error - backend server.',
data: {}, data: {},
}); });
} }
@@ -163,7 +163,7 @@ const apiPostingInvoice = async (req, res) => {
const _generateInvoice = async (invoiceDate, uniqueCode, repost) => { const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
let invoice = []; let invoice = [];
const collection = [] let collection = [];
await knex.transaction(async (trx) => { await knex.transaction(async (trx) => {
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`); winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`);
@@ -179,9 +179,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
)}` )}`
); );
if (invoice.length > 0) { if (invoice.length > 0) {
for (let key in invoice) {
for (const key in invoice) {
winston.logger.info( winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify( `SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify(
invoice[key] invoice[key]
@@ -200,89 +198,106 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP` `SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`
); );
const credUsername = await model.getParameterSetting(knex, "SAP_AUTH_USERNAME") let credUsername = await model.getParameterSetting(
const credPassword = await model.getParameterSetting(knex, "SAP_AUTH_PASSWORD") knex,
const parameter = await model.getParameterSetting(knex, "SAP_FI_URL_FOR_FB70") 'SAP_AUTH_USERNAME'
);
let credPassword = await model.getParameterSetting(
knex,
'SAP_AUTH_PASSWORD'
);
let parameter = await model.getParameterSetting(
knex,
'SAP_FI_URL_FOR_FB70'
);
for (const key in invoice) { for (let key in invoice) {
let prepare = { let prepare = {
status : true, status: true,
cms : true, cms: true,
message: "Success", message: 'Success',
};
if (!credUsername) {
prepare = {
status: false,
cms: false,
message: '[CMS] FAILED GET SETTING FOR SAP_AUTH_USERNAME',
};
} }
if(!credUsername) { if (!credPassword) {
prepare = { prepare = {
status : false, status: false,
cms : false, cms: false,
message: "[CMS] FAILED GET SETTING FOR SAP_AUTH_USERNAME", message: '[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
} };
} }
if(!credPassword) { if (!parameter) {
prepare = { prepare = {
status : false, status: false,
cms : false, cms: false,
message: "[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD", message: '[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
} };
} }
if(!parameter) { let credential = {
prepare = {
status : false,
cms : false,
message: "[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD",
}
}
const credential = {
username: credUsername.c_value, 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) { if (
prepare = { invoice[key].c_account_code_topup == '' ||
status : false, invoice[key].c_account_topup == ''
cms : false, ) {
message: "[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP", prepare = {
} status: false,
} cms: false,
message:
if(invoice[key].c_account_code_topup == "" || invoice[key].c_account_topup == "") { '[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP',
prepare = { };
status : false,
cms : false,
message: "[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP",
}
} }
let xmlHeader = { let xmlHeader = {
doc_header_text: invoice[key].doc_header_text doc_header_text: invoice[key].doc_header_text
? invoice[key].doc_header_text ? invoice[key].doc_header_text
: "", : '',
ba: invoice[key].ba ? invoice[key].ba : "", ba: invoice[key].ba ? invoice[key].ba : '',
doc_date: invoice[key].doc_date ? invoice[key].doc_date : "", doc_date: invoice[key].doc_date ? invoice[key].doc_date : '',
posting_date: invoice[key].posting_date posting_date: invoice[key].posting_date
? invoice[key].posting_date ? invoice[key].posting_date
: "", : '',
fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : "", fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : '',
fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : "", fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : '',
doc_type: invoice[key].doc_type ? invoice[key].doc_type : "", doc_type: invoice[key].doc_type ? invoice[key].doc_type : '',
c_invoice_no: invoice[key].c_invoice_no c_invoice_no: invoice[key].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 { return {
c_account_code_topup: c_account_code_topup:
item == "S" ? invoice[key].c_account_code_topup : "", item == 'S' ? invoice[key].c_account_code_topup : '',
c_account_topup: item == "H" ? invoice[key].c_account_topup : "", c_account_topup: item == 'H' ? invoice[key].c_account_topup : '',
ba: invoice[key].ba, ba: invoice[key].ba,
amount: invoice[key].amount, amount: invoice[key].amount,
posting_date: invoice[key].posting_date, posting_date: invoice[key].posting_date,
c_invoice_no: invoice[key].c_invoice_no, 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 invoice[key].doc_header_text
}`, }`,
de_cre: item, de_cre: item,
@@ -290,7 +305,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
}); });
let xmlRequest = helper.generateXMLRequest( let xmlRequest = helper.generateXMLRequest(
"ZFMCMS_FI_001", 'ZFMCMS_FI_001',
xmlHeader, xmlHeader,
xmlItem xmlItem
); );
@@ -299,11 +314,14 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}` `SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}`
); );
let response = {} let response = {};
if(prepare.status){ if (prepare.status) {
response = await helper.postingSAP(
response = await helper.postingSAP(parameter.c_value, xmlRequest, credential); parameter.c_value,
xmlRequest,
credential
);
winston.logger.info( winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${ `SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
@@ -315,34 +333,39 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
// new transaction // new transaction
// await knex.transaction(async (trx) => { // await knex.transaction(async (trx) => {
let resSAP let resSAP;
if(prepare.status){ if (prepare.status) {
resSAP = helper.getXMLData(response); resSAP = helper.getXMLData(response);
}else { } else {
resSAP = { resSAP = {
type: 'E', type: 'E',
message : prepare?.message || "FAILED GET PARAMETER SETTING", message: prepare?.message || 'FAILED GET PARAMETER SETTING',
data : {} data: {},
} };
} }
winston.logger.info( winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify( `SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
resSAP resSAP
)}` )}`
); );
await wait(1000) await wait(1000);
const cms = await model.setReturnSAP(invoice[key], resSAP, trx, true, invoice[key].c_invoice_no); let cms = await model.setReturnSAP(
invoice[key],
resSAP,
trx,
true,
invoice[key].c_invoice_no
);
winston.logger.info( winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}` `SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
); );
collection.push(cms.invoice[0]) collection.push(cms.invoice[0]);
// }); // });
} }
} }
}); });
@@ -351,7 +374,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
const _postingInvoice = async (uniqueCode) => { const _postingInvoice = async (uniqueCode) => {
let postingEt = []; let postingEt = [];
const collection = [] let collection = [];
postingEt = await model.getPostingEt(knex); postingEt = await model.getPostingEt(knex);
winston.logger.info( winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify( `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") let credUsername = await model.getParameterSetting(knex, 'SAP_AUTH_USERNAME');
const credPassword = await model.getParameterSetting(knex, "SAP_AUTH_PASSWORD") let credPassword = await model.getParameterSetting(knex, 'SAP_AUTH_PASSWORD');
const parameter = await model.getParameterSetting(knex, "SAP_FI_URL_FOR_FB70") let parameter = await model.getParameterSetting(knex, 'SAP_FI_URL_FOR_FB70');
let prepare = { let prepare = {
status : true, status: true,
message: "Success", message: 'Success',
};
if (!credUsername) {
prepare = {
status: false,
message: 'FAILED GET SETTING FOR SAP_AUTH_USERNAME',
};
} }
if(!credUsername) { if (!credPassword) {
prepare = { prepare = {
status : false, status: false,
message: "FAILED GET SETTING FOR SAP_AUTH_USERNAME", message: 'FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
} };
} }
if(!credPassword) { if (!parameter) {
prepare = { prepare = {
status : false, status: false,
message: "FAILED GET SETTING FOR SAP_AUTH_PASSWORD", message: 'FAILED GET SETTING FOR SAP_AUTH_PASSWORD',
} };
} }
if(!parameter) { let credential = {
prepare = {
status : false,
message: "FAILED GET SETTING FOR SAP_AUTH_PASSWORD",
}
}
const credential = {
username: credUsername.c_value, 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 = {} let xmlItem = ['S', 'H'].map((key) => {
return {
if(prepare.status){ c_account_code_topup: key == 'S' ? item.customer : '',
c_account_topup: key == 'H' ? item.account : '',
let xmlHeader = { ba: item.ba,
doc_header_text: item.doc_header_text ? item.doc_header_text : "", amount: item.amount,
ba: item.ba ? item.ba : "", posting_date: item.posting_date,
doc_date: item.doc_date ? item.doc_date : "", c_invoice_no: item.reference,
posting_date: item.posting_date ? item.posting_date : "", item_text: key == 'S' ? item.text1 : item.text2,
fisc_year: item.fiscal_year ? item.fiscal_year : "", de_cre: key,
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 xmlRequest = helper.generateXMLRequest(
return { 'ZFMCMS_FI_001',
c_account_code_topup: key == "S" ? item.customer : "", xmlHeader,
c_account_topup: key == "H" ? item.account : "", xmlItem
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}`
);
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( 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 resSAP
)}` )}`
); );
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} ITEM REFERENCE ${item.reference}`); winston.logger.info(
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} URL SAP ${parameter.c_value}`); `SCHEDULER-RETRY-${uniqueCode} ITEM REFERENCE ${item.reference}`
let invoice = await model.getInvoice(item.reference, trx) );
await wait(1000) winston.logger.info(
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RETRY INVOICE ${JSON.stringify(invoice)}`); `SCHEDULER-RETRY-${uniqueCode} URL SAP ${parameter.c_value}`
const cms = await model.setReturnSAP( );
invoice, let invoice = await model.getInvoice(item.reference, trx);
resSAP, await wait(1000);
trx, winston.logger.info(
false, `SCHEDULER-RETRY-${uniqueCode} RETRY INVOICE ${JSON.stringify(invoice)}`
item.reference );
); let cms = await model.setReturnSAP(
await wait(1000) invoice,
resSAP,
trx,
false,
item.reference
);
await wait(1000);
winston.logger.info( winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}` `SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
); );
collection.push(cms.invoice[0]) collection.push(cms.invoice[0]);
});
})
} }
return collection; return collection;
}; };
function wait(milliseconds) { function wait(milliseconds) {
return new Promise(resolve => setTimeout(resolve, milliseconds)); return new Promise((resolve) => setTimeout(resolve, milliseconds));
} }
module.exports = { module.exports = {
@@ -1,38 +1,38 @@
const { param, body, validationResult } = require("express-validator"); const { param, body, validationResult } = require('express-validator');
const helper = require("../../helpers/helper"); const helper = require('../../helpers/helper');
const winston = require("../../helpers/winston.logger"); const winston = require('../../helpers/winston.logger');
const model = require("./invoice.model"); const model = require('./invoice.model');
const moment = require("moment"); const moment = require('moment');
const knex = require("../../../infrastructure/database/knex"); const knex = require('../../../infrastructure/database/knex');
moment.locale("id"); moment.locale('id');
// VALIDATION // VALIDATION
const validate = (method) => { const validate = (method) => {
switch (method) { switch (method) {
case "generateInvoice": case 'generateInvoice':
return [ return [
body("trx_date") body('trx_date')
.notEmpty() .notEmpty()
.withMessage("trx_date is required!") .withMessage('trx_date is required!')
.isISO8601() .isISO8601()
.withMessage("invalid trx_date format YYYY-MM-DD !") .withMessage('invalid trx_date format YYYY-MM-DD !')
.escape() .escape()
.trim(), .trim(),
body("repost") body('repost')
.notEmpty() .notEmpty()
.withMessage("repost is required!") .withMessage('repost is required!')
.isBoolean() .isBoolean()
.withMessage("repost must boolean!") .withMessage('repost must boolean!')
.escape() .escape()
.trim(), .trim(),
]; ];
case "postingInvoice": case 'postingInvoice':
return [ return [
body("trx_date") body('trx_date')
.notEmpty() .notEmpty()
.withMessage("trx_date is required!") .withMessage('trx_date is required!')
.isISO8601() .isISO8601()
.withMessage("invalid trx_date format YYYY-MM-DD !") .withMessage('invalid trx_date format YYYY-MM-DD !')
.escape() .escape()
.trim(), .trim(),
]; ];
@@ -54,10 +54,10 @@ const apiGenerateInvoice = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: "400", code: '400',
message: err.errors[0].msg, message: err.errors[0].msg,
data: {}, data: {},
}; };
@@ -71,7 +71,7 @@ const apiGenerateInvoice = async (req, res) => {
} }
// time // 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( let invoice = await _generateInvoice(
invoiceDate, invoiceDate,
@@ -80,8 +80,8 @@ const apiGenerateInvoice = async (req, res) => {
); );
result = { result = {
code: "200", code: '200',
message: "Succes posting", message: 'Succes posting',
data: invoice, data: invoice,
}; };
@@ -93,11 +93,11 @@ const apiGenerateInvoice = async (req, res) => {
); );
return res.status(200).json({ return res.status(200).json({
code: "500", code: '500',
message: message:
process.env.NODE_ENV != "production" process.env.NODE_ENV != 'production'
? error.message ? error.message
: "500 internal server error - backend server.", : '500 internal server error - backend server.',
data: {}, data: {},
}); });
} }
@@ -116,10 +116,10 @@ const apiPostingInvoice = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: "400", code: '400',
message: err.errors[0].msg, message: err.errors[0].msg,
data: {}, data: {},
}; };
@@ -135,11 +135,11 @@ const apiPostingInvoice = async (req, res) => {
// return uniqueCode // return uniqueCode
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING INVOICE`); winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING INVOICE`);
const invoice = await _postingInvoice(uniqueCode); let invoice = await _postingInvoice(uniqueCode);
result = { result = {
code: "200", code: '200',
message: "Succes", message: 'Succes',
data: invoice, data: invoice,
}; };
@@ -151,11 +151,11 @@ const apiPostingInvoice = async (req, res) => {
); );
return res.status(200).json({ return res.status(200).json({
code: "500", code: '500',
message: message:
process.env.NODE_ENV != "production" process.env.NODE_ENV != 'production'
? error.message ? error.message
: "500 internal server error - backend server.", : '500 internal server error - backend server.',
data: {}, data: {},
}); });
} }
@@ -180,7 +180,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
); );
if (invoice.length > 0) if (invoice.length > 0)
for (const key in invoice) { for (let key in invoice) {
winston.logger.info( winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} insert payment history et : ${JSON.stringify( `SCHEDULER-FB70-${uniqueCode} insert payment history et : ${JSON.stringify(
invoice invoice
@@ -216,37 +216,37 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP` `SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`
); );
const url = 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"; '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 = { let xmlHeader = {
doc_header_text: invoice[key].doc_header_text doc_header_text: invoice[key].doc_header_text
? invoice[key].doc_header_text ? invoice[key].doc_header_text
: "", : '',
ba: invoice[key].ba ? invoice[key].ba : "", ba: invoice[key].ba ? invoice[key].ba : '',
doc_date: invoice[key].doc_date ? invoice[key].doc_date : "", doc_date: invoice[key].doc_date ? invoice[key].doc_date : '',
posting_date: invoice[key].posting_date posting_date: invoice[key].posting_date
? invoice[key].posting_date ? invoice[key].posting_date
: "", : '',
fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : "", fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : '',
fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : "", fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : '',
doc_type: invoice[key].doc_type ? invoice[key].doc_type : "", doc_type: invoice[key].doc_type ? invoice[key].doc_type : '',
c_invoice_no: invoice[key].c_invoice_no c_invoice_no: invoice[key].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 { return {
c_account_code_topup: c_account_code_topup:
item == "S" ? invoice[key].c_account_code_topup : "", item == 'S' ? invoice[key].c_account_code_topup : '',
c_account_topup: item == "H" ? invoice[key].c_account_topup : "", c_account_topup: item == 'H' ? invoice[key].c_account_topup : '',
ba: invoice[key].ba, ba: invoice[key].ba,
amount: invoice[key].amount, amount: invoice[key].amount,
posting_date: invoice[key].posting_date, posting_date: invoice[key].posting_date,
c_invoice_no: invoice[key].c_invoice_no, 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 invoice[key].doc_header_text
}`, }`,
de_cre: item, de_cre: item,
@@ -254,7 +254,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
}); });
let xmlRequest = helper.generateXMLRequest( let xmlRequest = helper.generateXMLRequest(
"ZFMCMS_FI_001", 'ZFMCMS_FI_001',
xmlHeader, xmlHeader,
xmlItem xmlItem
); );
@@ -263,7 +263,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}` `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( winston.logger.debug(
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${ `SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
@@ -273,7 +273,7 @@ const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
// new transaction // new transaction
await knex.transaction(async (trx) => { await knex.transaction(async (trx) => {
const resSAP = helper.getXMLData(response); let resSAP = helper.getXMLData(response);
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 2`); winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 2`);
// UPDATE CMS // 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( winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}` `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 = { let xmlHeader = {
doc_header_text: item.doc_header_text ? item.doc_header_text : "", doc_header_text: item.doc_header_text ? item.doc_header_text : '',
ba: item.ba ? item.ba : "", ba: item.ba ? item.ba : '',
doc_date: item.doc_date ? item.doc_date : "", doc_date: item.doc_date ? item.doc_date : '',
posting_date: item.posting_date ? item.posting_date : "", posting_date: item.posting_date ? item.posting_date : '',
fisc_year: item.fiscal_year ? item.fiscal_year : "", fisc_year: item.fiscal_year ? item.fiscal_year : '',
fisc_period: item.fis_period ? item.fis_period : "", fisc_period: item.fis_period ? item.fis_period : '',
doc_type: item.doc_type ? item.doc_type : "", doc_type: item.doc_type ? item.doc_type : '',
c_invoice_no: item.reference ? item.reference : "", c_invoice_no: item.reference ? item.reference : '',
}; };
let xmlItem = ["S", "H"].map((key) => { let xmlItem = ['S', 'H'].map((key) => {
return { return {
c_account_code_topup: key == "S" ? item.customer : "", c_account_code_topup: key == 'S' ? item.customer : '',
c_account_topup: key == "H" ? item.account : "", c_account_topup: key == 'H' ? item.account : '',
ba: item.ba, ba: item.ba,
amount: item.amount, amount: item.amount,
posting_date: item.posting_date, posting_date: item.posting_date,
c_invoice_no: item.reference, c_invoice_no: item.reference,
item_text: key == "S" ? item.text1 : item.text2, item_text: key == 'S' ? item.text1 : item.text2,
de_cre: key, de_cre: key,
}; };
}); });
let xmlRequest = helper.generateXMLRequest( let xmlRequest = helper.generateXMLRequest(
"ZFMCMS_FI_001", 'ZFMCMS_FI_001',
xmlHeader, xmlHeader,
xmlItem xmlItem
); );
@@ -341,10 +341,10 @@ const _postingInvoice = async (uniqueCode) => {
`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}` `SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`
); );
const url = 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"; '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( winston.logger.info(
`SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${ `SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${
@@ -355,7 +355,7 @@ const _postingInvoice = async (uniqueCode) => {
// new transaction // new transaction
// await knex.transaction(async trx => { // await knex.transaction(async trx => {
const resSAP = helper.getXMLData(response); let resSAP = helper.getXMLData(response);
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`); winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`);
// UPDATE CMS // 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 }, { c_invoice_no: item.reference },
resSAP, resSAP,
trx trx
@@ -410,7 +410,7 @@ const loadingBalanceRequest = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -587,15 +587,15 @@ const loadingBalanceRequest = async (req, res) => {
); );
// cek disini apakah sebelumnya topup // 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.length > 0) {
if (cardHistory.i_log_name == 21 && cardHistory.c_source == 'CMS') { if (cardHistory.i_log_name == 21 && cardHistory.c_source == 'CMS') {
if (getReservationPending.length > 0) { if (getReservationPending.length > 0) {
// insert semua reserve balance ke fraud // insert semua reserve balance ke fraud
const dataFraud = []; let dataFraud = [];
const rsv = []; let rsv = [];
for (const item of getReservationPending) { for (let item of getReservationPending) {
rsv.push(item.c_reservation_no); rsv.push(item.c_reservation_no);
dataFraud.push({ dataFraud.push({
c_card_number: item.c_card_number, c_card_number: item.c_card_number,
@@ -609,7 +609,7 @@ const loadingBalanceRequest = async (req, res) => {
winston.logger.debug( winston.logger.debug(
`${uniqueCode} INSERT TO trx.t_d_froud ${JSON.stringify(dataFraud)}` `${uniqueCode} INSERT TO trx.t_d_froud ${JSON.stringify(dataFraud)}`
); );
const fraud = await model.insertFraud(dataFraud); let fraud = await model.insertFraud(dataFraud);
// log debug // log debug
winston.logger.debug( winston.logger.debug(
`${uniqueCode} RESERVE NUMBER FROM trx.t_d_froud ${JSON.stringify( `${uniqueCode} RESERVE NUMBER FROM trx.t_d_froud ${JSON.stringify(
@@ -840,7 +840,7 @@ const loadingBalanceRequest = async (req, res) => {
); );
// get BI regulation status // get BI regulation status
const getBIRegulationStatus = await model.getBIRegulationStatus(); let getBIRegulationStatus = await model.getBIRegulationStatus();
// check value global parameter // check value global parameter
if (!getBIRegulationStatus) { if (!getBIRegulationStatus) {
@@ -864,7 +864,7 @@ const loadingBalanceRequest = async (req, res) => {
winston.logger.debug(`${uniqueCode} checking topup partial status...`); winston.logger.debug(`${uniqueCode} checking topup partial status...`);
// check topup partial status // check topup partial status
const getTopupPartialStatus = await model.getTopupPartialStatus(); let getTopupPartialStatus = await model.getTopupPartialStatus();
// check value global parameter // check value global parameter
if (!getTopupPartialStatus) { if (!getTopupPartialStatus) {
@@ -889,7 +889,7 @@ const loadingBalanceRequest = async (req, res) => {
); );
// get max saldo on the card // get max saldo on the card
const getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
// check value global parameter // check value global parameter
if (!getMaxAmountOnTheCard) { if (!getMaxAmountOnTheCard) {
@@ -1003,7 +1003,7 @@ const loadingBalanceRequest = async (req, res) => {
} }
// validate max topup per month // validate max topup per month
const getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); let getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
// check value global parameter // check value global parameter
if (!getMaxTopupPerMonth) { if (!getMaxTopupPerMonth) {
@@ -44,7 +44,12 @@ const getPartner = (mid, tid) => {
// GET ISSUER // GET ISSUER
const getIssuer = (id) => { const getIssuer = (id) => {
let result = knex('t_c_partner_fee') 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('i_partner', id)
.where('c_status', 'A') .where('c_status', 'A')
.first(); .first();
@@ -95,7 +95,7 @@ const paymentRecon = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -116,7 +116,7 @@ const checkReservation = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -281,7 +281,7 @@ const reservationValidate = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -465,7 +465,7 @@ const reservationValidate = async (req, res) => {
); );
// get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak // 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 // jika pengecekkan regulasi BI diaktifkan
if (getBIRegulationStatus.c_value == 'A') { if (getBIRegulationStatus.c_value == 'A') {
@@ -476,7 +476,7 @@ const reservationValidate = async (req, res) => {
); );
// get max saldo on the card // 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 // jika settingan paremeter maksimum saldo di dalam kartu ditemukan
if (getMaxAmountOnTheCard.c_value) { if (getMaxAmountOnTheCard.c_value) {
@@ -524,7 +524,7 @@ const reservationValidate = async (req, res) => {
} }
// validate max topup per month berdasarkan parameter setting // 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 // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan
if (getMaxTopupPerMonth.c_value) { if (getMaxTopupPerMonth.c_value) {
@@ -615,11 +615,19 @@ const reservationValidate = async (req, res) => {
// get issuer fee dan channel fee dari table public.t_c_partner_fee // get issuer fee dan channel fee dari table public.t_c_partner_fee
let getIssuer = await model.getIssuer(getPartner.i_partner, now); let getIssuer = await model.getIssuer(getPartner.i_partner, now);
if (getIssuer) { if (getIssuer) {
issuerFee = // ======================= KHUSUS LRT JABODEBEK =============================
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); if (getPartner.partner_code == 'P05') {
channelFee = issuerFee = getIssuer.i_issuer_fee_nominal;
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); 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) { // if (!getIssuer) {
// return res.status(200).json({ // return res.status(200).json({
@@ -687,7 +695,7 @@ const reservationValidateV2 = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -871,7 +879,7 @@ const reservationValidateV2 = async (req, res) => {
); );
// get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak // 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 // jika pengecekkan regulasi BI diaktifkan
if (getBIRegulationStatus.c_value == 'A') { if (getBIRegulationStatus.c_value == 'A') {
@@ -882,7 +890,7 @@ const reservationValidateV2 = async (req, res) => {
); );
// get max saldo on the card // 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 // jika settingan paremeter maksimum saldo di dalam kartu ditemukan
if (getMaxAmountOnTheCard.c_value) { if (getMaxAmountOnTheCard.c_value) {
@@ -930,7 +938,7 @@ const reservationValidateV2 = async (req, res) => {
} }
// validate max topup per month berdasarkan parameter setting // 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 // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan
if (getMaxTopupPerMonth.c_value) { if (getMaxTopupPerMonth.c_value) {
@@ -986,7 +994,7 @@ const reservationValidateV2 = async (req, res) => {
let dataReservationPending = []; let dataReservationPending = [];
let totalNominalReservationPending = 0; let totalNominalReservationPending = 0;
if (getReservationPending.length > 0) { if (getReservationPending.length > 0) {
for (const item of getReservationPending) { for (let item of getReservationPending) {
// hitung total reservasi yang masih pending / belum di topup // hitung total reservasi yang masih pending / belum di topup
totalNominalReservationPending = totalNominalReservationPending =
totalNominalReservationPending + parseInt(item.i_reservation_amount); totalNominalReservationPending + parseInt(item.i_reservation_amount);
@@ -1036,12 +1044,21 @@ const reservationValidateV2 = async (req, res) => {
// get issuer fee dan channel fee dari table public.t_c_partner_fee // get issuer fee dan channel fee dari table public.t_c_partner_fee
let getIssuer = await model.getIssuer(getPartner.i_partner, now); let getIssuer = await model.getIssuer(getPartner.i_partner, now);
if (getIssuer) { if (getIssuer) {
issuerFee = // ======================= KHUSUS LRT JABODEBEK =============================
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); if (getPartner.partner_code == 'P05') {
channelFee = issuerFee = getIssuer.i_issuer_fee_nominal;
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); 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) { // if (!getIssuer) {
// return res.status(200).json({ // return res.status(200).json({
// code: "403", // code: "403",
@@ -1143,7 +1160,7 @@ const reservation = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -1311,7 +1328,7 @@ const reservation = async (req, res) => {
); );
// get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak // 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') { if (getBIRegulationStatus.c_value == 'A') {
// log debug // log debug
// get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS // get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS
@@ -1320,7 +1337,7 @@ const reservation = async (req, res) => {
); );
// get max saldo on the card // 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 // jika settingan paremeter maksimum saldo di dalam kartu ditemukan
if (getMaxAmountOnTheCard.c_value) { 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 // 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
@@ -1365,7 +1382,7 @@ const reservation = async (req, res) => {
} }
// validate max topup per month berdasarkan parameter setting // 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 // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan
if (getMaxTopupPerMonth.c_value) { if (getMaxTopupPerMonth.c_value) {
@@ -1478,12 +1495,21 @@ const reservation = async (req, res) => {
// get issuer fee dan channel fee dari table public.t_c_partner_fee // get issuer fee dan channel fee dari table public.t_c_partner_fee
let getIssuer = await model.getIssuer(getPartner.i_partner, now); let getIssuer = await model.getIssuer(getPartner.i_partner, now);
if (getIssuer) { if (getIssuer) {
issuerFee = // ======================= KHUSUS LRT JABODEBEK =============================
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); if (getPartner.partner_code == 'P05') {
channelFee = issuerFee = getIssuer.i_issuer_fee_nominal;
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); 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) { // if (!getIssuer) {
// return res.status(200).json({ // return res.status(200).json({
// code: "403", // code: "403",
@@ -1769,7 +1795,7 @@ const reservationV2 = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -2075,7 +2101,7 @@ const reservationV2 = async (req, res) => {
); );
// get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak // 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') { if (getBIRegulationStatus.c_value == 'A') {
// log debug // log debug
// get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS // get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS
@@ -2084,7 +2110,7 @@ const reservationV2 = async (req, res) => {
); );
// get max saldo on the card // 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 // jika settingan paremeter maksimum saldo di dalam kartu ditemukan
if (getMaxAmountOnTheCard.c_value) { 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 // 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
@@ -2131,7 +2157,7 @@ const reservationV2 = async (req, res) => {
} }
// validate max topup per month berdasarkan parameter setting // 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 // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan
if (getMaxTopupPerMonth.c_value) { if (getMaxTopupPerMonth.c_value) {
@@ -2213,7 +2239,7 @@ const reservationV2 = async (req, res) => {
let dataReservationPending = []; let dataReservationPending = [];
let totalNominalReservationPending = 0; let totalNominalReservationPending = 0;
if (getReservationPending.length > 0) { if (getReservationPending.length > 0) {
for (const item of getReservationPending) { for (let item of getReservationPending) {
// hitung total reservasi yang masih pending / belum di topup // hitung total reservasi yang masih pending / belum di topup
totalNominalReservationPending = totalNominalReservationPending =
totalNominalReservationPending + parseInt(item.i_reservation_amount); totalNominalReservationPending + parseInt(item.i_reservation_amount);
@@ -2261,12 +2287,21 @@ const reservationV2 = async (req, res) => {
// get issuer fee dan channel fee dari table public.t_c_partner_fee // get issuer fee dan channel fee dari table public.t_c_partner_fee
let getIssuer = await model.getIssuer(getPartner.i_partner, now); let getIssuer = await model.getIssuer(getPartner.i_partner, now);
if (getIssuer) { if (getIssuer) {
issuerFee = // ======================= KHUSUS LRT JABODEBEK =============================
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); if (getPartner.partner_code == 'P05') {
channelFee = issuerFee = getIssuer.i_issuer_fee_nominal;
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); 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) { // if (!getIssuer) {
// return res.status(200).json({ // return res.status(200).json({
// code: "403", // code: "403",
@@ -2579,7 +2614,7 @@ const cancelReservationValidate = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -2764,7 +2799,7 @@ const cancelReservation = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -3241,7 +3276,7 @@ const cancelReservationValidateV2 = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -3611,7 +3646,7 @@ const cancelReservationV2 = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -3904,7 +3939,7 @@ const cancelReservationV2_1 = async (req, res) => {
); );
// check validator // check validator
const err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
result = { result = {
code: '400', code: '400',
@@ -4208,11 +4243,19 @@ const getFeeSharing = async (req, res) => {
// get issuer fee dan channel fee dari table public.t_c_partner_fee // get issuer fee dan channel fee dari table public.t_c_partner_fee
let getIssuer = await model.getIssuer(getPartner.i_partner, datetime); let getIssuer = await model.getIssuer(getPartner.i_partner, datetime);
if (getIssuer) { if (getIssuer) {
issuerFee = // ======================= KHUSUS LRT JABODEBEK =============================
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); if (getPartner.partner_code == 'P05') {
channelFee = issuerFee = getIssuer.i_issuer_fee_nominal;
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); 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 = { result = {
@@ -57,7 +57,13 @@ const getPartner = (mid, tid) => {
// GET ISSUER FEE // GET ISSUER FEE
const getIssuer = (id, time) => { const getIssuer = (id, time) => {
let result = knex('t_c_partner_fee') 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('i_partner', id)
.where('c_status', 'A') .where('c_status', 'A')
.where('d_valid', '<=', time) .where('d_valid', '<=', time)
+1 -1
View File
@@ -73,7 +73,7 @@ module.exports = {
// connection: process.env.DB_URL, // connection: process.env.DB_URL,
pool: { pool: {
min: 2, min: 2,
max: 10, max: 20,
}, },
migrations: { migrations: {
directory: './infrastructure/database/migrations', directory: './infrastructure/database/migrations',