diff --git a/.71c131f2ce727b13210eef32232709400762e5fb-audit.json b/.71c131f2ce727b13210eef32232709400762e5fb-audit.json index bed3bd7..0850aca 100644 --- a/.71c131f2ce727b13210eef32232709400762e5fb-audit.json +++ b/.71c131f2ce727b13210eef32232709400762e5fb-audit.json @@ -6,9 +6,9 @@ "auditLog": ".71c131f2ce727b13210eef32232709400762e5fb-audit.json", "files": [ { - "date": 1655704904492, - "name": "2022-06-20-onlinetopup.log", - "hash": "f333a5acec96d32f18bc18c20ca1246699a624431553cf8fe7e7e79bc541c313" + "date": 1655959753576, + "name": "2022-06-23-onlinetopup.log", + "hash": "c16eb42e22299ad373e9de900a0cafdb6acbaf4313336a9b5e65b295776076ef" } ], "hashType": "sha256" diff --git a/application/modules/hsm/authenticate1.js b/application/modules/hsm/authenticate1.js index 175569d..c94751e 100644 --- a/application/modules/hsm/authenticate1.js +++ b/application/modules/hsm/authenticate1.js @@ -86,16 +86,30 @@ const controller = async (req, res) => { respCode = generate.getResponseCode(respData); respData1 = generate.getResponseData(respData); - result = { - code: "00", - message: "Request Authenticate 1 Success", - data: { - trxID: generate.buf2hex(transactionId), - responseCode: respCode, - responseData: respData1, - responseLength: respData1.length / 2, - }, - }; + if (respData1) { + result = { + code: "00", + message: "Request Authenticate 1 Success", + data: { + trxID: generate.buf2hex(transactionId), + responseCode: respCode, + responseData: respData1, + responseLength: respData1.length / 2, + }, + }; + } else{ + result = { + code: "5004", + message: "Empty Data from HSM", + data: { + trxID: generate.buf2hex(transactionId), + responseCode: respCode, + responseData: respData1, + responseLength: respData1.length / 2, + }, + }; + } + // log debug winston.logger.debug( diff --git a/application/modules/hsm/services/webSocket.js b/application/modules/hsm/services/webSocket.js index 2bb4d70..d2207d2 100644 --- a/application/modules/hsm/services/webSocket.js +++ b/application/modules/hsm/services/webSocket.js @@ -17,44 +17,69 @@ let url = "wss://gateway04.cyberware.co.jp/feliqserver/v1/wsapi"; class WebSocketClient { ws = null; clientAuthenticated = false; + openWebSocketStatus = false; // Connection of WebSocket open = () => { - this.ws = new WebSocket(url, [], options); - this.ws.on("open", this.onOpen); - this.ws.on("close", this.onClose); + try { + if (this.ws == null) { + this.ws = new WebSocket(url, [], options); + + this.ws.on("open", this.onOpen); + this.ws.on("close", this.onClose); + this.ws.on("error", this.onError); + } + + this.openWebSocketStatus = true; + } catch (error) { + this.openWebSocketStatus = false; + } }; // Disconnection of WebSocket close = () => { this.ws.close(); // console.log('WebSocket Close'); - // log debug - winston.logger.debug(`websocket close`); + // log info + winston.logger.info(`websocket close`); }; // Open event onOpen = () => { // console.log("WebSocket Open"); - - // log debug - winston.logger.debug(`websocket open`); - this.isOpened(); - if (!this.clientAuthenticated) { - this.clientAuth(); + // log debug + winston.logger.debug(`opening websocket`); + + if (this.isOpened()) { + // log info + winston.logger.info(`websocket open successfully`); + + if (!this.clientAuthenticated) { + this.clientAuth(); + } + } else { + // log error + winston.logger.error(`websocket open failed`); } }; onClose = () => { // console.log("WebSocket Close"); - - // log debug - winston.logger.debug(`websocket close`); + + // log info + winston.logger.info(`websocket close`); + + this.clientAuthenticated = false; + }; + + onError = () => { + // console.log("WebSocket Error"); + + // log info + winston.logger.info(`websocket error`); this.clientAuthenticated = false; - this.isOpened(); - this.open(); }; // Connection check @@ -139,8 +164,9 @@ class WebSocketClient { // log debug winston.logger.debug(`websocket resp data tenant: ${respCode}`); - if (respCode == "0000" || respCode == "0502") + if (respCode == "0000" || respCode == "0502") { this.clientAuthenticated = true; + } // console.log(`clientAuthenticated = ${this.clientAuthenticated}`); // log debug winston.logger.debug( @@ -155,10 +181,19 @@ class WebSocketClient { } const client = new WebSocketClient(); -client.open(); +if (!client.openWebSocketStatus) { + // log info + winston.logger.info(`first open websocket`); + client.open(); +} setInterval(function () { + // let statusConnection = client.clientAuthenticated; + // if (!statusConnection) { + // log debug + winston.logger.debug(`retry open websocket`); client.clientAuth(); + // } }, 59000); module.exports = { diff --git a/application/modules/loadbalance/loadbalance.controller.js b/application/modules/loadbalance/loadbalance.controller.js index 477fe58..e2f94bd 100644 --- a/application/modules/loadbalance/loadbalance.controller.js +++ b/application/modules/loadbalance/loadbalance.controller.js @@ -1102,24 +1102,6 @@ const loadingBalanceInsert = async (param) => { flag ); - // log debug - winston.logger.debug( - `${uniqueCode} inserting load balance transaction history...` - ); - - // insert transaction - await model.insertLoadingBalanceHistoryOnly( - data, - detail, - reservation_number, - now, - write_status, - card_number, - uid.toUpperCase(), - balance, - flag - ); - result = { code: "00", message: write_status diff --git a/application/modules/loadbalance/loadbalance.model.js b/application/modules/loadbalance/loadbalance.model.js index fc5b866..ccfcd5e 100644 --- a/application/modules/loadbalance/loadbalance.model.js +++ b/application/modules/loadbalance/loadbalance.model.js @@ -316,8 +316,7 @@ const updateLoadingBalance = async ( // insert load balance history return knex("trx.t_d_load_balance_history") .transacting(trx) - .update(data) - .where('c_load_balance_no', loadBalanceNumber); + .insert(data); }) .then(() => { // update reservation diff --git a/application/modules/reservebalance/reservebalance.controller.js b/application/modules/reservebalance/reservebalance.controller.js index 6f22647..eacbe48 100644 --- a/application/modules/reservebalance/reservebalance.controller.js +++ b/application/modules/reservebalance/reservebalance.controller.js @@ -11,6 +11,21 @@ var uniqueCode; // VALIDATION const validate = (method) => { switch (method) { + case "reservationValidate": + return [ + body("mid").not().isEmpty().withMessage("MID is required"), + body("tid").not().isEmpty().withMessage("TID is required"), + body("card_number") + .not() + .isEmpty() + .withMessage("Card Number is required"), + body("amount") + .not() + .isEmpty() + .withMessage("Amount is required") + .isNumeric() + .withMessage("Amount is invalid format"), + ]; case "reservation": return [ body("mid").not().isEmpty().withMessage("MID is required"), @@ -26,12 +41,275 @@ const validate = (method) => { .isNumeric() .withMessage("Amount is invalid format"), ]; - default: break; } }; +// RESERVATION VALIDATE +const reservationValidate = async (req, res) => { + try { + // generate unique code + uniqueCode = await helper.getUniqueCode(); + + // param + let { mid, tid, card_number, amount } = req.body; + + // log info + winston.logger.info( + `${uniqueCode} REQUEST reservation validate: ${JSON.stringify(req.body)}` + ); + + // check validator + const err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: "400", + message: err.errors[0].msg, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation validate: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // time + let now = moment().format("YYYY-MM-DD HH:mm:ss"); + let today = moment().format("YYYY-MM-DD"); + let year = moment().format("Y"); + let month = moment().format("M"); + + // log debug + winston.logger.debug(`${uniqueCode} checking partner...`); + + // get partner, merchant, terminal from tid + let getPartner = await model.getPartner(mid, tid); + if (!getPartner) { + result = { + code: "412", + message: "terminal id is not valid", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation validate: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // check card number + let checkCardNumber = await model.checkCardNumber(card_number); + if (!checkCardNumber) { + result = { + code: "413", + message: "card number is not registered", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation validate: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + // log debug + winston.logger.debug(`${uniqueCode} checking reservation amount...`); + + // check reservation amount + if (parseInt(amount) <= 0) { + result = { + code: "415", + message: "amount must be greater than 0", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation validate: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // log debug + winston.logger.debug( + `${uniqueCode} getting last balance on the card by card history...` + ); + + // get last balance on the card + let balance = 0; + let getLastBalanceFromCardHistory = + await model.getLastBalanceFromCardHistory(card_number); + if (getLastBalanceFromCardHistory) { + balance = getLastBalanceFromCardHistory.m_balance_after; + } + + // log debug + winston.logger.debug(`${uniqueCode} checking BI regulation status...`); + + // get BI regulation status + const getBIRegulationStatus = await model.getBIRegulationStatus(); + if (getBIRegulationStatus.c_value == "A") { + // log debug + winston.logger.debug(`${uniqueCode} checking max balance on the card...`); + + // get max saldo on the card + const getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); + if (getMaxAmountOnTheCard.c_value) { + if ( + parseInt(balance) + parseInt(amount) > + parseInt(getMaxAmountOnTheCard.c_value) + ) { + result = { + code: "416", + message: "your card number has reached the maximum balance", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation validate: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } + + // log debug + winston.logger.debug(`${uniqueCode} checking max topup per month...`); + + // get accumulated balance in this month + let accumulatedBalance = 0; + let getAccumulationBalanceInThisMonthFromCardHistory = + await model.getAccumulationBalanceInThisMonthFromCardHistory( + card_number, + year, + month + ); + if (getAccumulationBalanceInThisMonthFromCardHistory) { + accumulatedBalance = + getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; + } + + // validate max topup per month + const getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); + if (getMaxTopupPerMonth.c_value) { + if ( + parseInt(accumulatedBalance) + parseInt(amount) > + parseInt(getMaxTopupPerMonth.c_value) + ) { + result = { + code: "417", + message: "your card number has been limit top up for this month", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation validate: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } + } + + // log debug + winston.logger.debug(`${uniqueCode} checking max reservation...`); + + // get max reservation + let getMaxReservation = await model.getMaxReservation(); + let maxReservation = getMaxReservation.c_value + ? getMaxReservation.c_value + : 1; + + // log debug + winston.logger.debug(`${uniqueCode} checking total reservation pending...`); + + // get total reservation pending + let getReservationPending = await model.getReservationPending( + card_number, + now + ); + let totalReservationPending = + getReservationPending.total_reservation > 0 + ? getReservationPending.total_reservation + : 0; + + if (totalReservationPending >= maxReservation) { + result = { + code: "421", + message: + "your card number has some pending transaction. Please finished it!", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation validate: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // log debug + winston.logger.debug(`${uniqueCode} getting issuer fee and channel fee...`); + + // get issuer fee + let issuerFee = 0; + let channelFee = 0; + let getIssuer = await model.getIssuer(getPartner.i_partner); + if (getIssuer) { + issuerFee = (getIssuer.i_issuer_fee_perc / 100) * 1500; + channelFee = (getIssuer.i_channel_fee_perc / 100) * 1500; + } + // if (!getIssuer) { + // return res.status(200).json({ + // code: "403", + // message: "issuer doesn't exist", + // data: {}, + // }); + // } + + // log debug + winston.logger.debug(`${uniqueCode} checking reservation sequence...`); + + result = { + code: "00", + message: "validation successfully.", + data: {}, + }; + + // log info + winston.logger.info( + `${uniqueCode} RESPONSE reservation validate: ${JSON.stringify(result)}` + ); + + 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: {}, + }); + } +}; + // RESERVATION const reservation = async (req, res) => { try { @@ -57,7 +335,7 @@ const reservation = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE reservation insert: ${JSON.stringify(result)}` ); return res.status(200).json(result); @@ -530,6 +808,7 @@ const inquiryReservation = async (req, res) => { module.exports = { validate, + reservationValidate, reservation, inquiryReservation, }; diff --git a/application/routes/reservebalance.routes.js b/application/routes/reservebalance.routes.js index 79ebc26..d12d4aa 100644 --- a/application/routes/reservebalance.routes.js +++ b/application/routes/reservebalance.routes.js @@ -3,6 +3,13 @@ const router = express.Router(); const auth = require("../middlewares/jwt.middleware"); const controller = require("../modules/reservebalance/reservebalance.controller"); +router.post( + "/reservation/validate", + auth.authenticateToken, + controller.validate("reservationValidate"), + controller.reservationValidate +); + router.post( "/reservation", auth.authenticateToken, diff --git a/docs/error_code b/docs/error_code index 4b477b4..3767f14 100644 --- a/docs/error_code +++ b/docs/error_code @@ -28,4 +28,5 @@ # ERROR MESSAGE CODE CORE HSM 5001 error catch HSM 5002 failed from HSM - 5003 wrong response from card \ No newline at end of file + 5003 wrong response from card + 5004 Empty Data from HSM \ No newline at end of file