From 0685387b469a805f926571bf4727112c4e3263dd Mon Sep 17 00:00:00 2001 From: Mohamad Ihsan Date: Mon, 12 Sep 2022 16:11:10 +0700 Subject: [PATCH] fixed bugs --- application/helpers/helper.js | 17 + application/helpers/winston.logger.js | 2 +- application/modules/auth/auth.controller.js | 20 +- .../dongleorder/dongleorder.controller.js | 11 +- .../modules/history/history.controller.js | 17 +- application/modules/hsm/authenticate1.js | 7 +- application/modules/hsm/authenticate2.js | 7 +- application/modules/hsm/authenticateResp.js | 7 +- application/modules/hsm/endTranscation.js | 7 +- application/modules/hsm/readData.js | 7 +- application/modules/hsm/readDataResp.js | 7 +- application/modules/hsm/topup.js | 7 +- application/modules/hsm/topupResp.js | 7 +- .../invoiceonline/invoice.controller.js | 367 +++++++++++------- .../invoicesemionline/invoice.controller.js | 367 +++++++++++------- .../loadbalance/loadbalance.controller.js | 46 +-- .../paymentrecon/paymentrecon.controller.js | 82 +++- .../paymentrecon/paymentrecon.model.js | 16 +- .../reservebalance.controller.js | 30 +- application/routes/paymentrecon.routes.js | 5 + 20 files changed, 634 insertions(+), 402 deletions(-) diff --git a/application/helpers/helper.js b/application/helpers/helper.js index 5d671f4..04378d5 100644 --- a/application/helpers/helper.js +++ b/application/helpers/helper.js @@ -27,6 +27,22 @@ function getUniqueCode() { return timestamp; } +function getRandomArbitrary(min, max) { + return Math.floor(Math.random() * (max - min) + min) + 1; +} + +function randomNumberInt() { + const result = []; + while (result.length !== 3) { + let random = getRandomArbitrary(0, 9); + if (!result.includes(random)) result.push(random); + + // To check if the first no is not zero + if (result.length === 1 && random === 0) result.pop(); + } + return parseInt( result.join("") ); +} + // GENERATE XML REQUEST function generateXMLRequest(urn, headers, items) { let xmlRequest = '' @@ -265,6 +281,7 @@ module.exports = { encryptText, decryptText, getUniqueCode, + randomNumberInt, generateXMLRequest, postingSAP, getXMLData diff --git a/application/helpers/winston.logger.js b/application/helpers/winston.logger.js index daa3610..617328d 100644 --- a/application/helpers/winston.logger.js +++ b/application/helpers/winston.logger.js @@ -103,7 +103,7 @@ if ( }); } -if (process.env.NODE_ENV == "testing" || process.env.NODE_ENV == "TESTING") { +if (process.env.NODE_ENV != "testing" && process.env.NODE_ENV != "TESTING") { logger.add( new winston.transports.Console({ // format: winston.format.cli(), diff --git a/application/modules/auth/auth.controller.js b/application/modules/auth/auth.controller.js index 15c5a59..cf49598 100644 --- a/application/modules/auth/auth.controller.js +++ b/application/modules/auth/auth.controller.js @@ -8,9 +8,6 @@ const { body, validationResult } = require("express-validator"); const moment = require("moment"); moment.locale("id"); -var result = {}; -var uniqueCode; - // VALIDATION const validate = (method) => { switch (method) { @@ -67,7 +64,8 @@ const validate = (method) => { const loginPartnerUser = async (req, res, next) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; let { email, password } = req.body; @@ -201,7 +199,8 @@ const loginPartnerUser = async (req, res, next) => { const loginTerminal = async (req, res, next) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; let { mid, tid, password } = req.body; @@ -350,7 +349,8 @@ const loginTerminal = async (req, res, next) => { const register = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; let { mid, tid, password } = req.body; @@ -477,7 +477,8 @@ const register = async (req, res) => { const refreshTokenTerminal = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; const { mid, tid } = req.body; const refresh_token = req.header("refresh_token"); @@ -597,7 +598,8 @@ const refreshTokenTerminal = async (req, res) => { const refreshTokenPartnerUser = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; const { email } = req.body; const refresh_token = req.header("refresh_token"); @@ -738,6 +740,7 @@ const refreshTokenPartnerUser = async (req, res) => { // GET TID MID const getTIDMID = async (req, res) => { try { + let result = {}; let partner_id = req.partner_id_token; // get partner, merchant, terminal from tid @@ -772,6 +775,7 @@ const getTIDMID = async (req, res) => { // GET PARTNER USER const getPartnerUser = async (req, res) => { try { + let result = {}; let partner_user_id = req.partner_user_id_token; // get partner user detail diff --git a/application/modules/dongleorder/dongleorder.controller.js b/application/modules/dongleorder/dongleorder.controller.js index f37caf5..ba5cf72 100644 --- a/application/modules/dongleorder/dongleorder.controller.js +++ b/application/modules/dongleorder/dongleorder.controller.js @@ -5,9 +5,6 @@ const model = require("./dongleorder.model"); const moment = require("moment"); moment.locale("id"); -var result = {}; -var uniqueCode; - // VALIDATION const validate = (method) => { switch (method) { @@ -24,8 +21,9 @@ const validate = (method) => { const getDongleOrder = async (req, res) => { try { - uniqueCode = await helper.getUniqueCode(); - + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + // param let year = req.query.year; @@ -92,7 +90,8 @@ const updateDongleOrder = async (req, res) => { dongle_id, status } = req.body; - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; // log info winston.logger.info( diff --git a/application/modules/history/history.controller.js b/application/modules/history/history.controller.js index d8227d7..ca0819d 100644 --- a/application/modules/history/history.controller.js +++ b/application/modules/history/history.controller.js @@ -5,9 +5,6 @@ const model = require("./history.model"); const moment = require("moment"); moment.locale("id"); -var result = {}; -var uniqueCode; - // VALIDATION const validate = (method) => { switch (method) { @@ -39,7 +36,8 @@ const validate = (method) => { const cardHistory = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; // param let { data } = req.body; @@ -82,7 +80,6 @@ const cardHistory = async (req, res) => { element = data[index]; if (element != "00000000000000000000000000000000") { - date = moment( new Date((parseInt(element.slice(0, 8), 16) + 946684800) * 1000) ).format("YYYY-MM-DD HH:mm:ss"); @@ -95,18 +92,20 @@ const cardHistory = async (req, res) => { if (checkReskaFormat == "000000") { istopup = "Deduct"; - + // get terminal name terminalName = "PARKIR RESKA"; } else if (checkKCIFormat == "00") { - istopup = parseInt(element.slice(24, 26), 16) == 0 ? "Topup" : "Deduct"; + istopup = + parseInt(element.slice(24, 26), 16) == 0 ? "Topup" : "Deduct"; // get terminal name terminalName = await model.getTerminalKCIExisting(mid); terminalName = terminalName ? terminalName.merchant_name : ""; } else { - istopup = parseInt(element.slice(24, 26), 16) == 0 ? "Topup" : "Deduct"; - + istopup = + parseInt(element.slice(24, 26), 16) == 0 ? "Topup" : "Deduct"; + // get terminal name terminalName = await model.getPartnerPartialMIDTID(mid, tid); terminalName = terminalName ? terminalName.merchant_name : ""; diff --git a/application/modules/hsm/authenticate1.js b/application/modules/hsm/authenticate1.js index f89b6ba..53464a8 100644 --- a/application/modules/hsm/authenticate1.js +++ b/application/modules/hsm/authenticate1.js @@ -4,9 +4,7 @@ const generate = require("./utils/utils"); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); require("dotenv").config(); -var result = {}; -var uniqueCode; -var useClient; +let useClient; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "1") { @@ -26,7 +24,8 @@ const controller = async (req, res) => { try { let { body } = req; // uniqueCode = body.unique_code; - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "12") { diff --git a/application/modules/hsm/authenticate2.js b/application/modules/hsm/authenticate2.js index 0c02f67..7d618ca 100644 --- a/application/modules/hsm/authenticate2.js +++ b/application/modules/hsm/authenticate2.js @@ -3,9 +3,7 @@ const generate = require("./utils/utils"); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); require("dotenv").config(); -var result = {}; -var uniqueCode; -var useClient; +let useClient; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "1") { @@ -24,7 +22,8 @@ if (process.env.NUMBER_SERVER_ACTIVE == "1") { const controller = async (req, res) => { try { let { body } = req; - uniqueCode = body.unique_code; + let uniqueCode = body.unique_code; + let result = {}; // log debug winston.logger.debug( diff --git a/application/modules/hsm/authenticateResp.js b/application/modules/hsm/authenticateResp.js index 9f06084..9c52a51 100644 --- a/application/modules/hsm/authenticateResp.js +++ b/application/modules/hsm/authenticateResp.js @@ -3,9 +3,7 @@ const generate = require("./utils/utils"); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); require("dotenv").config(); -var result = {}; -var uniqueCode; -var useClient; +let useClient; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "1") { @@ -24,7 +22,8 @@ if (process.env.NUMBER_SERVER_ACTIVE == "1") { const controller = async (req, res) => { try { let { body } = req; - uniqueCode = body.unique_code; + let uniqueCode = body.unique_code; + let result = {}; // log debug winston.logger.debug( diff --git a/application/modules/hsm/endTranscation.js b/application/modules/hsm/endTranscation.js index 2c55862..ca7294b 100644 --- a/application/modules/hsm/endTranscation.js +++ b/application/modules/hsm/endTranscation.js @@ -3,9 +3,7 @@ const generate = require("./utils/utils"); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); require("dotenv").config(); -var result = {}; -var uniqueCode; -var useClient; +let useClient; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "1") { @@ -24,7 +22,8 @@ if (process.env.NUMBER_SERVER_ACTIVE == "1") { const controller = async (req, res) => { try { let { body } = req; - uniqueCode = body.unique_code; + let uniqueCode = body.unique_code; + let result = {}; // log debug winston.logger.debug( diff --git a/application/modules/hsm/readData.js b/application/modules/hsm/readData.js index 617c64e..7c34b78 100644 --- a/application/modules/hsm/readData.js +++ b/application/modules/hsm/readData.js @@ -3,9 +3,7 @@ const generate = require("./utils/utils"); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); require("dotenv").config(); -var result = {}; -var uniqueCode; -var useClient; +let useClient; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "1") { @@ -24,7 +22,8 @@ if (process.env.NUMBER_SERVER_ACTIVE == "1") { const controller = async (req, res) => { try { let { body } = req; - uniqueCode = body.unique_code; + let uniqueCode = body.unique_code; + let result = {}; // log debug winston.logger.debug( diff --git a/application/modules/hsm/readDataResp.js b/application/modules/hsm/readDataResp.js index 1aad7e5..8a6a68d 100644 --- a/application/modules/hsm/readDataResp.js +++ b/application/modules/hsm/readDataResp.js @@ -3,9 +3,7 @@ const generate = require("./utils/utils"); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); require("dotenv").config(); -var result = {}; -var uniqueCode; -var useClient; +let useClient; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "1") { @@ -24,7 +22,8 @@ if (process.env.NUMBER_SERVER_ACTIVE == "1") { const controller = async (req, res) => { try { let { body } = req; - uniqueCode = body.unique_code; + let uniqueCode = body.unique_code; + let result = {}; // log debug winston.logger.debug( diff --git a/application/modules/hsm/topup.js b/application/modules/hsm/topup.js index cc4e89c..2584dfa 100644 --- a/application/modules/hsm/topup.js +++ b/application/modules/hsm/topup.js @@ -5,9 +5,7 @@ const loadBalance = require("../loadbalance/loadbalance.controller"); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); require("dotenv").config(); -var result = {}; -var uniqueCode; -var useClient; +let useClient; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "1") { @@ -73,7 +71,8 @@ const controller = async (req, res) => { requestData, } = req.body; - uniqueCode = unique_code; + let uniqueCode = unique_code; + let result = {}; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "12") { diff --git a/application/modules/hsm/topupResp.js b/application/modules/hsm/topupResp.js index a9ca602..8b68c38 100644 --- a/application/modules/hsm/topupResp.js +++ b/application/modules/hsm/topupResp.js @@ -5,9 +5,7 @@ const loadBalance = require("../loadbalance/loadbalance.controller"); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); require("dotenv").config(); -var result = {}; -var uniqueCode; -var useClient; +let useClient; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "1") { @@ -77,7 +75,8 @@ const controller = async (req, res) => { requestData, } = req.body; - uniqueCode = unique_code; + let uniqueCode = unique_code; + let result = {}; // set connection HSM server if (process.env.NUMBER_SERVER_ACTIVE == "12") { diff --git a/application/modules/invoiceonline/invoice.controller.js b/application/modules/invoiceonline/invoice.controller.js index 7b81c84..096475b 100644 --- a/application/modules/invoiceonline/invoice.controller.js +++ b/application/modules/invoiceonline/invoice.controller.js @@ -4,23 +4,37 @@ const winston = require("../../helpers/winston.logger"); const model = require("./invoice.model"); const moment = require("moment"); const knex = require("../../../infrastructure/database/knex"); - moment.locale("id"); -var result = {}; -var uniqueCode; - // VALIDATION const validate = (method) => { switch (method) { case "generateInvoice": return [ - body('trx_date').notEmpty().withMessage('trx_date is required!').isISO8601().withMessage('invalid trx_date format YYYY-MM-DD !').escape().trim(), - body('repost').notEmpty().withMessage('repost is required!').isBoolean().withMessage('repost must boolean!').escape().trim(), + body("trx_date") + .notEmpty() + .withMessage("trx_date is required!") + .isISO8601() + .withMessage("invalid trx_date format YYYY-MM-DD !") + .escape() + .trim(), + body("repost") + .notEmpty() + .withMessage("repost is required!") + .isBoolean() + .withMessage("repost must boolean!") + .escape() + .trim(), ]; case "postingInvoice": return [ - body('trx_date').notEmpty().withMessage('trx_date is required!').isISO8601().withMessage('invalid trx_date format YYYY-MM-DD !').escape().trim(), + body("trx_date") + .notEmpty() + .withMessage("trx_date is required!") + .isISO8601() + .withMessage("invalid trx_date format YYYY-MM-DD !") + .escape() + .trim(), ]; default: break; @@ -29,11 +43,10 @@ const validate = (method) => { // POSTING INVOICE const apiGenerateInvoice = async (req, res) => { - try { // generate unique code - uniqueCode = helper.getUniqueCode(); - // return uniqueCode + let uniqueCode = helper.getUniqueCode(); + let result = {}; // log info winston.logger.info( @@ -58,41 +71,44 @@ const apiGenerateInvoice = async (req, res) => { } // time - let invoiceDate = moment(req.body.trx_date).format("YYYY-MM-DD") + let invoiceDate = moment(req.body.trx_date).format("YYYY-MM-DD"); + + let invoice = await _generateInvoice( + invoiceDate, + uniqueCode, + req.body.repost + ); - let invoice = await _generateInvoice(invoiceDate, uniqueCode, req.body.repost) - result = { code: "200", message: "Succes posting", - data: invoice + data: invoice, }; return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `500 internal server error - backend server | ${error.message}` - ); - - return res.status(200).json({ - code: "500", - message: - process.env.NODE_ENV != "production" - ? error.message - : "500 internal server error - backend server.", - data: {}, - }); - } + // create log + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); + return res.status(200).json({ + code: "500", + message: + process.env.NODE_ENV != "production" + ? error.message + : "500 internal server error - backend server.", + data: {}, + }); + } }; // RETRY POSTING INVOICE const apiPostingInvoice = async (req, res) => { try { // generate unique code - uniqueCode = helper.getUniqueCode() + let uniqueCode = helper.getUniqueCode(); + let result = {}; // log info winston.logger.info( @@ -117,197 +133,258 @@ const apiPostingInvoice = async (req, res) => { } // 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) + const invoice = await _postingInvoice(uniqueCode); result = { code: "200", message: "Succes", data: invoice, - } + }; return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `500 internal server error - backend server | ${error.message}` - ); - - return res.status(200).json({ - code: "500", - message: - process.env.NODE_ENV != "production" - ? error.message - : "500 internal server error - backend server.", - data: {}, - }); + // create log + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); + + return res.status(200).json({ + code: "500", + message: + process.env.NODE_ENV != "production" + ? error.message + : "500 internal server error - backend server.", + data: {}, + }); } -} +}; const _generateInvoice = async (invoiceDate, uniqueCode, repost) => { + let invoice = []; - let invoice = [] - - await knex.transaction(async trx => { - + await knex.transaction(async (trx) => { winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} execute payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`); + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} execute payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})` + ); - invoice = await model.generateInvoice(invoiceDate, repost, trx) + invoice = await model.generateInvoice(invoiceDate, repost, trx); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} result payment.sp_payment_req_topup_online ${JSON.stringify(invoice)}`); - - if(invoice.length > 0) for (const key in invoice) { + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} result payment.sp_payment_req_topup_online ${JSON.stringify( + invoice + )}` + ); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} insert payment history et : ${JSON.stringify(invoice)}`) + if (invoice.length > 0) + for (const key in invoice) { + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} insert payment history et : ${JSON.stringify( + invoice + )}` + ); - let history = await model.writePaynentHistory(invoice[key], trx) + let history = await model.writePaynentHistory(invoice[key], trx); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} result insert payment history et : ${JSON.stringify(history)}`) + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} result insert payment history et : ${JSON.stringify( + history + )}` + ); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify(invoice[key])}`) + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify( + invoice[key] + )}` + ); - let postingEt = await model.insertPostingEt(invoice[key], trx) - - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} success insert posting et : ${JSON.stringify(postingEt)}`) - } + let postingEt = await model.insertPostingEt(invoice[key], trx); + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} success insert posting et : ${JSON.stringify( + postingEt + )}` + ); + } + }); - }) + if (invoice.length > 0) { + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP` + ); - if(invoice.length > 0){ - - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`); - - const url = 'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2' + const url = + "http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2"; for (const key in invoice) { - let xmlHeader = { - doc_header_text : invoice[key].doc_header_text ? invoice[key].doc_header_text : "", + doc_header_text: invoice[key].doc_header_text + ? invoice[key].doc_header_text + : "", ba: invoice[key].ba ? invoice[key].ba : "", - doc_date : invoice[key].doc_date ? invoice[key].doc_date : "", - posting_date : invoice[key].posting_date ? invoice[key].posting_date : "", - fisc_year : invoice[key].fisc_year ? invoice[key].fisc_year : "", - fisc_period : invoice[key].fisc_period ? invoice[key].fisc_period: "", + doc_date: invoice[key].doc_date ? invoice[key].doc_date : "", + posting_date: invoice[key].posting_date + ? invoice[key].posting_date + : "", + fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : "", + fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : "", doc_type: invoice[key].doc_type ? invoice[key].doc_type : "", - c_invoice_no : invoice[key].c_invoice_no ? invoice[key].c_invoice_no : "" - } + c_invoice_no: invoice[key].c_invoice_no + ? invoice[key].c_invoice_no + : "", + }; - let xmlItem = ['S', 'H'].map(item => { + let xmlItem = ["S", "H"].map((item) => { return { - c_account_code_topup : item == 'S' ? invoice[key].c_account_code_topup : "", - c_account_topup : item == 'H' ? invoice[key].c_account_topup : "", - ba : invoice[key].ba, - amount : invoice[key].amount, - posting_date : invoice[key].posting_date, - c_invoice_no : invoice[key].c_invoice_no, - item_text : `${item == 'S' ? "DEBIT" : "KREDIT"} INVOICE CMS ${invoice[key].doc_header_text}`, - de_cre : item - } + c_account_code_topup: + item == "S" ? invoice[key].c_account_code_topup : "", + c_account_topup: item == "H" ? invoice[key].c_account_topup : "", + ba: invoice[key].ba, + amount: invoice[key].amount, + posting_date: invoice[key].posting_date, + c_invoice_no: invoice[key].c_invoice_no, + item_text: `${item == "S" ? "DEBIT" : "KREDIT"} INVOICE CMS ${ + invoice[key].doc_header_text + }`, + de_cre: item, + }; }); - let xmlRequest = helper.generateXMLRequest('ZFMCMS_FI_001', xmlHeader, xmlItem) + let xmlRequest = helper.generateXMLRequest( + "ZFMCMS_FI_001", + xmlHeader, + xmlItem + ); - winston.logger.debug(`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}`); - - const response = await helper.postingSAP(url, xmlRequest) + winston.logger.debug( + `SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}` + ); - winston.logger.debug(`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${invoice[key].c_invoice_no} to SAP : ${JSON.stringify(response)}`); + const response = await helper.postingSAP(url, xmlRequest); + + winston.logger.debug( + `SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${ + invoice[key].c_invoice_no + } to SAP : ${JSON.stringify(response)}` + ); // new transaction - await knex.transaction(async trx => { - - const resSAP = helper.getXMLData(response) + await knex.transaction(async (trx) => { + const resSAP = helper.getXMLData(response); winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 2`); // UPDATE CMS - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(resSAP)}`) + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify( + resSAP + )}` + ); - const cms = await model.setReturnSAP(invoice[key], resSAP, trx) + const cms = await model.setReturnSAP(invoice[key], resSAP, trx); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`) - - }) + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}` + ); + }); } } - return invoice - -} + return invoice; +}; const _postingInvoice = async (uniqueCode) => { - let postingEt = [] - await knex.transaction(async trx => { + let postingEt = []; + await knex.transaction(async (trx) => { + postingEt = await model.getPostingEt(trx); - postingEt = await model.getPostingEt(trx) - - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify(postingEt)}`) + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify( + postingEt + )}` + ); for (const item of postingEt) { - 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 : "", - 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_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 : "" - } + c_invoice_no: item.reference ? item.reference : "", + }; - let xmlItem = ['S', 'H'].map(key => { + let xmlItem = ["S", "H"].map((key) => { return { - c_account_code_topup : key == 'S' ? item.customer : "", - c_account_topup : key == 'H' ? item.account : "", - 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 - } + c_account_code_topup: key == "S" ? item.customer : "", + c_account_topup: key == "H" ? item.account : "", + ba: item.ba, + amount: item.amount, + posting_date: item.posting_date, + c_invoice_no: item.reference, + item_text: key == "S" ? item.text1 : item.text2, + de_cre: key, + }; }); - let xmlRequest = helper.generateXMLRequest('ZFMCMS_FI_001', xmlHeader, xmlItem) + let xmlRequest = helper.generateXMLRequest( + "ZFMCMS_FI_001", + xmlHeader, + xmlItem + ); - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`); - - const url = 'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2' + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}` + ); - const response = await helper.postingSAP(url, xmlRequest) + const url = + "http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2"; - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${item.reference} to SAP : ${JSON.stringify(response)}`); + const response = await helper.postingSAP(url, xmlRequest); + + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${ + item.reference + } to SAP : ${JSON.stringify(response)}` + ); // new transaction // await knex.transaction(async trx => { - const resSAP = helper.getXMLData(response) + const resSAP = helper.getXMLData(response); winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`); // UPDATE CMS - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(resSAP)}`) + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify( + resSAP + )}` + ); - const cms = await model.setReturnSAP({c_invoice_no : item.reference}, resSAP, trx) + const cms = await model.setReturnSAP( + { c_invoice_no: item.reference }, + resSAP, + trx + ); - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`) + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}` + ); // }) } - - }) + }); - return postingEt - -} + return postingEt; +}; module.exports = { validate, apiPostingInvoice, apiGenerateInvoice, _postingInvoice, - _generateInvoice -}; \ No newline at end of file + _generateInvoice, +}; diff --git a/application/modules/invoicesemionline/invoice.controller.js b/application/modules/invoicesemionline/invoice.controller.js index 7b81c84..096475b 100644 --- a/application/modules/invoicesemionline/invoice.controller.js +++ b/application/modules/invoicesemionline/invoice.controller.js @@ -4,23 +4,37 @@ const winston = require("../../helpers/winston.logger"); const model = require("./invoice.model"); const moment = require("moment"); const knex = require("../../../infrastructure/database/knex"); - moment.locale("id"); -var result = {}; -var uniqueCode; - // VALIDATION const validate = (method) => { switch (method) { case "generateInvoice": return [ - body('trx_date').notEmpty().withMessage('trx_date is required!').isISO8601().withMessage('invalid trx_date format YYYY-MM-DD !').escape().trim(), - body('repost').notEmpty().withMessage('repost is required!').isBoolean().withMessage('repost must boolean!').escape().trim(), + body("trx_date") + .notEmpty() + .withMessage("trx_date is required!") + .isISO8601() + .withMessage("invalid trx_date format YYYY-MM-DD !") + .escape() + .trim(), + body("repost") + .notEmpty() + .withMessage("repost is required!") + .isBoolean() + .withMessage("repost must boolean!") + .escape() + .trim(), ]; case "postingInvoice": return [ - body('trx_date').notEmpty().withMessage('trx_date is required!').isISO8601().withMessage('invalid trx_date format YYYY-MM-DD !').escape().trim(), + body("trx_date") + .notEmpty() + .withMessage("trx_date is required!") + .isISO8601() + .withMessage("invalid trx_date format YYYY-MM-DD !") + .escape() + .trim(), ]; default: break; @@ -29,11 +43,10 @@ const validate = (method) => { // POSTING INVOICE const apiGenerateInvoice = async (req, res) => { - try { // generate unique code - uniqueCode = helper.getUniqueCode(); - // return uniqueCode + let uniqueCode = helper.getUniqueCode(); + let result = {}; // log info winston.logger.info( @@ -58,41 +71,44 @@ const apiGenerateInvoice = async (req, res) => { } // time - let invoiceDate = moment(req.body.trx_date).format("YYYY-MM-DD") + let invoiceDate = moment(req.body.trx_date).format("YYYY-MM-DD"); + + let invoice = await _generateInvoice( + invoiceDate, + uniqueCode, + req.body.repost + ); - let invoice = await _generateInvoice(invoiceDate, uniqueCode, req.body.repost) - result = { code: "200", message: "Succes posting", - data: invoice + data: invoice, }; return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `500 internal server error - backend server | ${error.message}` - ); - - return res.status(200).json({ - code: "500", - message: - process.env.NODE_ENV != "production" - ? error.message - : "500 internal server error - backend server.", - data: {}, - }); - } + // create log + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); + return res.status(200).json({ + code: "500", + message: + process.env.NODE_ENV != "production" + ? error.message + : "500 internal server error - backend server.", + data: {}, + }); + } }; // RETRY POSTING INVOICE const apiPostingInvoice = async (req, res) => { try { // generate unique code - uniqueCode = helper.getUniqueCode() + let uniqueCode = helper.getUniqueCode(); + let result = {}; // log info winston.logger.info( @@ -117,197 +133,258 @@ const apiPostingInvoice = async (req, res) => { } // 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) + const invoice = await _postingInvoice(uniqueCode); result = { code: "200", message: "Succes", data: invoice, - } + }; return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `500 internal server error - backend server | ${error.message}` - ); - - return res.status(200).json({ - code: "500", - message: - process.env.NODE_ENV != "production" - ? error.message - : "500 internal server error - backend server.", - data: {}, - }); + // create log + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); + + return res.status(200).json({ + code: "500", + message: + process.env.NODE_ENV != "production" + ? error.message + : "500 internal server error - backend server.", + data: {}, + }); } -} +}; const _generateInvoice = async (invoiceDate, uniqueCode, repost) => { + let invoice = []; - let invoice = [] - - await knex.transaction(async trx => { - + await knex.transaction(async (trx) => { winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} execute payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`); + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} execute payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})` + ); - invoice = await model.generateInvoice(invoiceDate, repost, trx) + invoice = await model.generateInvoice(invoiceDate, repost, trx); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} result payment.sp_payment_req_topup_online ${JSON.stringify(invoice)}`); - - if(invoice.length > 0) for (const key in invoice) { + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} result payment.sp_payment_req_topup_online ${JSON.stringify( + invoice + )}` + ); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} insert payment history et : ${JSON.stringify(invoice)}`) + if (invoice.length > 0) + for (const key in invoice) { + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} insert payment history et : ${JSON.stringify( + invoice + )}` + ); - let history = await model.writePaynentHistory(invoice[key], trx) + let history = await model.writePaynentHistory(invoice[key], trx); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} result insert payment history et : ${JSON.stringify(history)}`) + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} result insert payment history et : ${JSON.stringify( + history + )}` + ); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify(invoice[key])}`) + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify( + invoice[key] + )}` + ); - let postingEt = await model.insertPostingEt(invoice[key], trx) - - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} success insert posting et : ${JSON.stringify(postingEt)}`) - } + let postingEt = await model.insertPostingEt(invoice[key], trx); + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} success insert posting et : ${JSON.stringify( + postingEt + )}` + ); + } + }); - }) + if (invoice.length > 0) { + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP` + ); - if(invoice.length > 0){ - - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`); - - const url = 'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2' + const url = + "http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2"; for (const key in invoice) { - let xmlHeader = { - doc_header_text : invoice[key].doc_header_text ? invoice[key].doc_header_text : "", + doc_header_text: invoice[key].doc_header_text + ? invoice[key].doc_header_text + : "", ba: invoice[key].ba ? invoice[key].ba : "", - doc_date : invoice[key].doc_date ? invoice[key].doc_date : "", - posting_date : invoice[key].posting_date ? invoice[key].posting_date : "", - fisc_year : invoice[key].fisc_year ? invoice[key].fisc_year : "", - fisc_period : invoice[key].fisc_period ? invoice[key].fisc_period: "", + doc_date: invoice[key].doc_date ? invoice[key].doc_date : "", + posting_date: invoice[key].posting_date + ? invoice[key].posting_date + : "", + fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : "", + fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : "", doc_type: invoice[key].doc_type ? invoice[key].doc_type : "", - c_invoice_no : invoice[key].c_invoice_no ? invoice[key].c_invoice_no : "" - } + c_invoice_no: invoice[key].c_invoice_no + ? invoice[key].c_invoice_no + : "", + }; - let xmlItem = ['S', 'H'].map(item => { + let xmlItem = ["S", "H"].map((item) => { return { - c_account_code_topup : item == 'S' ? invoice[key].c_account_code_topup : "", - c_account_topup : item == 'H' ? invoice[key].c_account_topup : "", - ba : invoice[key].ba, - amount : invoice[key].amount, - posting_date : invoice[key].posting_date, - c_invoice_no : invoice[key].c_invoice_no, - item_text : `${item == 'S' ? "DEBIT" : "KREDIT"} INVOICE CMS ${invoice[key].doc_header_text}`, - de_cre : item - } + c_account_code_topup: + item == "S" ? invoice[key].c_account_code_topup : "", + c_account_topup: item == "H" ? invoice[key].c_account_topup : "", + ba: invoice[key].ba, + amount: invoice[key].amount, + posting_date: invoice[key].posting_date, + c_invoice_no: invoice[key].c_invoice_no, + item_text: `${item == "S" ? "DEBIT" : "KREDIT"} INVOICE CMS ${ + invoice[key].doc_header_text + }`, + de_cre: item, + }; }); - let xmlRequest = helper.generateXMLRequest('ZFMCMS_FI_001', xmlHeader, xmlItem) + let xmlRequest = helper.generateXMLRequest( + "ZFMCMS_FI_001", + xmlHeader, + xmlItem + ); - winston.logger.debug(`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}`); - - const response = await helper.postingSAP(url, xmlRequest) + winston.logger.debug( + `SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}` + ); - winston.logger.debug(`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${invoice[key].c_invoice_no} to SAP : ${JSON.stringify(response)}`); + const response = await helper.postingSAP(url, xmlRequest); + + winston.logger.debug( + `SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${ + invoice[key].c_invoice_no + } to SAP : ${JSON.stringify(response)}` + ); // new transaction - await knex.transaction(async trx => { - - const resSAP = helper.getXMLData(response) + await knex.transaction(async (trx) => { + const resSAP = helper.getXMLData(response); winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 2`); // UPDATE CMS - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(resSAP)}`) + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify( + resSAP + )}` + ); - const cms = await model.setReturnSAP(invoice[key], resSAP, trx) + const cms = await model.setReturnSAP(invoice[key], resSAP, trx); - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`) - - }) + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}` + ); + }); } } - return invoice - -} + return invoice; +}; const _postingInvoice = async (uniqueCode) => { - let postingEt = [] - await knex.transaction(async trx => { + let postingEt = []; + await knex.transaction(async (trx) => { + postingEt = await model.getPostingEt(trx); - postingEt = await model.getPostingEt(trx) - - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify(postingEt)}`) + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify( + postingEt + )}` + ); for (const item of postingEt) { - 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 : "", - 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_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 : "" - } + c_invoice_no: item.reference ? item.reference : "", + }; - let xmlItem = ['S', 'H'].map(key => { + let xmlItem = ["S", "H"].map((key) => { return { - c_account_code_topup : key == 'S' ? item.customer : "", - c_account_topup : key == 'H' ? item.account : "", - 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 - } + c_account_code_topup: key == "S" ? item.customer : "", + c_account_topup: key == "H" ? item.account : "", + ba: item.ba, + amount: item.amount, + posting_date: item.posting_date, + c_invoice_no: item.reference, + item_text: key == "S" ? item.text1 : item.text2, + de_cre: key, + }; }); - let xmlRequest = helper.generateXMLRequest('ZFMCMS_FI_001', xmlHeader, xmlItem) + let xmlRequest = helper.generateXMLRequest( + "ZFMCMS_FI_001", + xmlHeader, + xmlItem + ); - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`); - - const url = 'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2' + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}` + ); - const response = await helper.postingSAP(url, xmlRequest) + const url = + "http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2"; - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${item.reference} to SAP : ${JSON.stringify(response)}`); + const response = await helper.postingSAP(url, xmlRequest); + + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${ + item.reference + } to SAP : ${JSON.stringify(response)}` + ); // new transaction // await knex.transaction(async trx => { - const resSAP = helper.getXMLData(response) + const resSAP = helper.getXMLData(response); winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`); // UPDATE CMS - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(resSAP)}`) + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify( + resSAP + )}` + ); - const cms = await model.setReturnSAP({c_invoice_no : item.reference}, resSAP, trx) + const cms = await model.setReturnSAP( + { c_invoice_no: item.reference }, + resSAP, + trx + ); - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`) + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}` + ); // }) } - - }) + }); - return postingEt - -} + return postingEt; +}; module.exports = { validate, apiPostingInvoice, apiGenerateInvoice, _postingInvoice, - _generateInvoice -}; \ No newline at end of file + _generateInvoice, +}; diff --git a/application/modules/loadbalance/loadbalance.controller.js b/application/modules/loadbalance/loadbalance.controller.js index a7cc999..0a4c8da 100644 --- a/application/modules/loadbalance/loadbalance.controller.js +++ b/application/modules/loadbalance/loadbalance.controller.js @@ -5,9 +5,6 @@ const model = require("./loadbalance.model"); const moment = require("moment"); moment.locale("id"); -var result = {}; -var uniqueCode; - // VALIDATION const validate = (method) => { switch (method) { @@ -57,7 +54,8 @@ const loadingBalanceRequest = async (req, res) => { let { mid, tid, card_number, uid, balance, flag, unique_code } = req.body; // uniqueCode = await helper.getUniqueCode(); - uniqueCode = unique_code; + let uniqueCode = unique_code; + let result = {}; // log info winston.logger.info( @@ -377,7 +375,8 @@ const loadingBalanceRequest = async (req, res) => { const getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); if (getMaxTopupPerMonth.c_value) { if ( - parseInt(accumulatedBalance) + parseInt(amountTopup) > parseInt(getMaxTopupPerMonth.c_value) + parseInt(accumulatedBalance) + parseInt(amountTopup) > + parseInt(getMaxTopupPerMonth.c_value) ) { result = { code: "417", @@ -448,7 +447,8 @@ const loadingBalance = async (req, res) => { unique_code, } = req.body; - uniqueCode = unique_code ? unique_code : 9999999999999; + let uniqueCode = unique_code ? unique_code : 9999999999999; + let result = {}; // log info winston.logger.info( @@ -490,9 +490,7 @@ const loadingBalance = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify( - result - )}` + `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}` ); return res.status(200).json(result); @@ -570,9 +568,7 @@ const loadingBalance = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify( - result - )}` + `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}` ); return res.status(200).json(result); @@ -596,9 +592,7 @@ const loadingBalance = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify( - result - )}` + `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}` ); return res.status(200).json(result); @@ -860,7 +854,8 @@ const loadingBalanceInsert = async (param) => { let flag = param.flag; let unique_code = param.unique_code; - uniqueCode = unique_code ? unique_code : 9999999999999; + let uniqueCode = unique_code ? unique_code : 9999999999999; + let result = {}; // log info winston.logger.info( @@ -885,9 +880,7 @@ const loadingBalanceInsert = async (param) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify( - result - )}` + `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}` ); return result; @@ -965,9 +958,7 @@ const loadingBalanceInsert = async (param) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify( - result - )}` + `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}` ); return result; @@ -991,9 +982,7 @@ const loadingBalanceInsert = async (param) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify( - result - )}` + `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}` ); return result; @@ -1214,7 +1203,8 @@ const loadingBalanceUpdate = async (param) => { let unique_code = param.unique_code; let loadBalanceNumber = param.load_balance_number; - uniqueCode = unique_code ? unique_code : 9999999999999; + let uniqueCode = unique_code ? unique_code : 9999999999999; + let result = {}; // log info winston.logger.info( @@ -1239,9 +1229,7 @@ const loadingBalanceUpdate = async (param) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE load balance update: ${JSON.stringify( - result - )}` + `${uniqueCode} RESPONSE load balance update: ${JSON.stringify(result)}` ); return result; diff --git a/application/modules/paymentrecon/paymentrecon.controller.js b/application/modules/paymentrecon/paymentrecon.controller.js index fc2db4f..6a012c4 100644 --- a/application/modules/paymentrecon/paymentrecon.controller.js +++ b/application/modules/paymentrecon/paymentrecon.controller.js @@ -3,10 +3,11 @@ const helper = require("../../helpers/helper"); const winston = require("../../helpers/winston.logger"); const model = require("./paymentrecon.model"); const moment = require("moment"); +const { default: axios } = require("axios"); +const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); moment.locale("id"); -var result = {}; -var uniqueCode; +var maxLoopParameter = 100; // VALIDATION const validate = (method) => { @@ -74,7 +75,8 @@ const validate = (method) => { const paymentRecon = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = helper.getUniqueCode(); + let result = {}; // param let { date, bank_ref, reservation_number, amount } = req.body; @@ -129,20 +131,19 @@ const paymentRecon = async (req, res) => { let PaymentReconNumber; let maxLoop = 0; do { + await _sleep(helper.randomNumberInt()); + // await _sleep(1000); PaymentReconNumber = await generatePaymentReconNumber(partnerCode, now); - if (maxLoop > 20) { + if (maxLoop > maxLoopParameter) { // create log winston.logger.error( - `500 internal server error (max loop) - backend server | ${error.message}` + `500 internal server error (max loop) - backend server` ); return { code: "500", - message: - process.env.NODE_ENV != "production" - ? error.message - : "500 internal server error (max loop) - backend server.", + message: "500 internal server error (max loop) - backend server.", data: {}, }; } @@ -437,7 +438,8 @@ const paymentRecon = async (req, res) => { const paymentReconSemiTopupOnline = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = helper.getUniqueCode(); + let result = {}; // param let { date, bank_ref, reservation_number, amount } = req.body; @@ -492,9 +494,10 @@ const paymentReconSemiTopupOnline = async (req, res) => { let PaymentReconNumber; let maxLoop = 0; do { + await _sleep(helper.randomNumberInt()); PaymentReconNumber = await generatePaymentReconNumber(partnerCode, now); - if (maxLoop > 20) { + if (maxLoop > maxLoopParameter) { // create log winston.logger.error( `500 internal server error (max loop) - backend server | ${error.message}` @@ -748,7 +751,8 @@ const paymentReconSemiTopupOnline = async (req, res) => { const paymentReconBulk = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = helper.getUniqueCode(); + let result = {}; // param let { log } = req.body; @@ -871,15 +875,67 @@ const generatePaymentReconNumber = async (partnerCode, reconDate) => { // insert to tempPaymentReconNumber let insert = await model.insertPaymentReconNumber(paymentReconNumber); - if (!insert) { + if (insert.rowCount < 1) { paymentReconNumber = "XX"; } + return paymentReconNumber; }; +const paymentReconToCMS = async (req, res) => { + let { date } = req.body; + + if (!date) { + date = moment().format("YYYY-MM-DD"); + } + + let recon = await model.getReservationToRecon(date); + + let token = + "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJwYXJ0bmVyX2lkIjoiVTJGc2RHVmtYMS9sNnJ6a1BQdjZseHQ3cEhqdFBHVDVRVVllT0hOQzc0Yz0iLCJwYXJ0bmVyX3VzZXJfaWQiOiJVMkZzZEdWa1gxL0sxcGp6K2luREhYTnFxdW9lZHNxR29HSlRTdHRyQnNZPSIsImlhdCI6MTY2MjYyOTQyMSwiZXhwIjoxNjY1MjIxNDIxLCJpc3MiOiJDTVMgS2VyZXRhIENvbW11dGVyIEluZG9uZXNpYSJ9.U-140oWsEFhbiZ4kpEf243Ng5UppttOm5iv85H7g49c"; + + const config = { + headers: { + Authorization: `Bearer ${token}`, + "Content-Type": "application/json", + }, + }; + + let bodyParameters = { + date: "", + bank_ref: "", + reservation_number: "", + amount: "", + }; + + recon.forEach((element) => { + bodyParameters = { + date: date, + bank_ref: "BR_TEST_01", + reservation_number: element.c_reservation_no, + amount: element.i_reservation_amount, + }; + + axios.post( + "http://localhost:4000/api/payment-recon", + bodyParameters, + config + ); + }); + + let result = { + code: "00", + message: "payment recon sent successfully.", + data: {}, + }; + + return res.status(200).json(result); +}; + module.exports = { validate, paymentRecon, paymentReconSemiTopupOnline, paymentReconBulk, + paymentReconToCMS, }; diff --git a/application/modules/paymentrecon/paymentrecon.model.js b/application/modules/paymentrecon/paymentrecon.model.js index ef6e4a1..868bff1 100644 --- a/application/modules/paymentrecon/paymentrecon.model.js +++ b/application/modules/paymentrecon/paymentrecon.model.js @@ -102,7 +102,7 @@ const insertPaymentReconTransaction = ( statusName, responseCode, responseMessage, - responseData, + responseData ) => { let result = knex("payment.t_d_payment_recon").insert({ d_payment: date, @@ -136,13 +136,22 @@ const insertPaymentReconNumber = (paymentReconNumber) => { const getLastCounterPaymentReconNo = (partnerCode, reconDate) => { let result = knex("payment.t_d_payment_recon") .select("c_payment_recon_no", "d_payment_recon") - .whereRaw("??::date = ?", ['d_payment_recon', reconDate]) + .whereRaw("??::date = ?", ["d_payment_recon", reconDate]) .where("c_partner_code", partnerCode) - .orderBy("d_payment_recon", "desc") + // .orderBy("d_payment_recon", "desc") + .orderBy("c_payment_recon_no", "desc") .first(); return result; }; +const getReservationToRecon = (date) => { + let result = knex("trx.t_d_reservation_balance") + .select("c_reservation_no", "i_reservation_amount") + .whereNull('c_payment_recon_no') + .whereRaw("??::date = ?", ["d_reservation", date]); + return result; +}; + module.exports = { getPartner, getPartnerByID, @@ -153,4 +162,5 @@ module.exports = { insertPaymentReconTransaction, insertPaymentReconNumber, getLastCounterPaymentReconNo, + getReservationToRecon, }; diff --git a/application/modules/reservebalance/reservebalance.controller.js b/application/modules/reservebalance/reservebalance.controller.js index afc1642..b899823 100644 --- a/application/modules/reservebalance/reservebalance.controller.js +++ b/application/modules/reservebalance/reservebalance.controller.js @@ -2,11 +2,11 @@ const { param, body, validationResult } = require("express-validator"); const helper = require("../../helpers/helper"); const winston = require("../../helpers/winston.logger"); const model = require("./reservebalance.model"); +const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const moment = require("moment"); moment.locale("id"); -var result = {}; -var uniqueCode; +var maxLoopParameter = 100; // VALIDATION const validate = (method) => { @@ -69,7 +69,8 @@ const validate = (method) => { const checkReservation = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; // param let { mid, tid, card_number } = req.body; @@ -150,7 +151,8 @@ const checkReservation = async (req, res) => { const reservationValidate = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; // param let { mid, tid, card_number, amount } = req.body; @@ -416,10 +418,11 @@ const reservationValidate = async (req, res) => { // RESERVATION const reservation = async (req, res) => { - try { - // generate unique code - uniqueCode = await helper.getUniqueCode(); + // generate unique code + let uniqueCode = helper.getUniqueCode(); + let result = {}; + try { // param let { mid, tid, card_number, amount, ref_no } = req.body; @@ -683,7 +686,10 @@ const reservation = async (req, res) => { let getReservationNumberSequence; let reservationNoSequence; let maxLoop = 0; + do { + await _sleep(helper.randomNumberInt()); + // log debug winston.logger.debug(`${uniqueCode} checking reservation sequence...`); @@ -705,7 +711,7 @@ const reservation = async (req, res) => { reservationNoSequence ); - if (maxLoop > 20) { + if (maxLoop > maxLoopParameter) { // create log winston.logger.error( `500 internal server error (max loop) - backend server | ${error.message}` @@ -995,7 +1001,7 @@ const generateReservationNumber = async (data, date, counter) => { // insert to temp reservation number let insert = await model.insertReservationNumber(reservationNumber); - if (!insert) { + if (insert.rowCount < 1) { reservationNumber = "XX"; } @@ -1006,7 +1012,8 @@ const generateReservationNumber = async (data, date, counter) => { const cancelReservationValidate = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; // param let { mid, tid, reservation_number } = req.body; @@ -1170,7 +1177,8 @@ const cancelReservationValidate = async (req, res) => { const cancelReservation = async (req, res) => { try { // generate unique code - uniqueCode = await helper.getUniqueCode(); + let uniqueCode = await helper.getUniqueCode(); + let result = {}; // param let { mid, tid, reservation_number } = req.body; diff --git a/application/routes/paymentrecon.routes.js b/application/routes/paymentrecon.routes.js index a38a3a5..8fc75c0 100644 --- a/application/routes/paymentrecon.routes.js +++ b/application/routes/paymentrecon.routes.js @@ -17,4 +17,9 @@ router.post( controller.paymentReconSemiTopupOnline ); +router.post( + "/payment-recon/to-cms", + controller.paymentReconToCMS +); + module.exports = router;