From b399ae4938243d25d424f3535719952196aa37d4 Mon Sep 17 00:00:00 2001 From: Mohamad Ihsan Date: Tue, 24 Nov 2026 18:51:00 +0700 Subject: [PATCH] Split reservation, load balance, and POS workflows --- .../load-balance-request.handler.js | 847 ++++ .../loadbalance/load-balance-write.service.js | 943 ++++ .../loadbalance/loadbalance.controller.js | 1807 +------ .../modules/pos/card-balance.handlers.js | 228 + .../modules/pos/card-redeem.handlers.js | 551 +++ .../modules/pos/card-replacement.handlers.js | 972 ++++ .../modules/pos/card-sales.handlers.js | 443 ++ .../modules/pos/card-topup.handlers.js | 231 + .../modules/pos/card-validation.service.js | 383 ++ .../modules/pos/pos-diagnostics.handler.js | 42 + application/modules/pos/pos.controller.js | 2935 +---------- .../reservation-cancel.handlers.js | 1392 ++++++ .../reservation-create.handlers.js | 2250 +++++++++ .../reservation-decrypt.handler.js | 33 + .../reservation-inquiry.handlers.js | 563 +++ .../reservebalance.controller.js | 4315 +---------------- .../tests/loadbalance-reservations.test.js | 12 + .../tests/pos-reservation-handlers.test.js | 71 + 18 files changed, 9015 insertions(+), 9003 deletions(-) create mode 100644 application/modules/loadbalance/load-balance-request.handler.js create mode 100644 application/modules/loadbalance/load-balance-write.service.js create mode 100644 application/modules/pos/card-balance.handlers.js create mode 100644 application/modules/pos/card-redeem.handlers.js create mode 100644 application/modules/pos/card-replacement.handlers.js create mode 100644 application/modules/pos/card-sales.handlers.js create mode 100644 application/modules/pos/card-topup.handlers.js create mode 100644 application/modules/pos/card-validation.service.js create mode 100644 application/modules/pos/pos-diagnostics.handler.js create mode 100644 application/modules/reservebalance/reservation-cancel.handlers.js create mode 100644 application/modules/reservebalance/reservation-create.handlers.js create mode 100644 application/modules/reservebalance/reservation-decrypt.handler.js create mode 100644 application/modules/reservebalance/reservation-inquiry.handlers.js create mode 100644 application/tests/pos-reservation-handlers.test.js diff --git a/application/modules/loadbalance/load-balance-request.handler.js b/application/modules/loadbalance/load-balance-request.handler.js new file mode 100644 index 0000000..5b174bd --- /dev/null +++ b/application/modules/loadbalance/load-balance-request.handler.js @@ -0,0 +1,847 @@ +const winston = require('../../helpers/winston.logger'); +const { validationResult } = require('express-validator'); +const model = require('./loadbalance.model'); +const moment = require('moment'); +const { updateAllTransaction } = require('./load-balance-write.service'); + +// Tangani permintaan saldo dan jalankan pembaruan reservasi sesuai hasil pengecekan. +const loadingBalanceRequest = async (req, res) => { + try { + // param + // let { mid, tid, card_number, uid, balance, flag, unique_code } = req.body; + + let mid = req.body.mid; + let tid = req.body.tid; + let card_number = req.body.card_number; + let uid = req.body.uid; + let balance = req.body.balance; + let flag = req.body.flag; + let unique_code = req.body.unique_code; + + // uniqueCode = await helper.getUniqueCode(); + let uniqueCode = unique_code; + let result = {}; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + req.body + )}` + ); + + // check validator + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + let cardBlacklist = await model.getCardBlacklist(card_number); + if (cardBlacklist) { + if (cardBlacklist.c_status == 'B') { + result = { + code: '445', + message: 'Card is Blacklisted', + data: {}, + }; + return res.status(200).json(result); + } + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking production card number or not...` + // ); + + // jika settingan untuk server adalah production + // if (process.env.SERVER_FOR == 'production') { + // // jika settingan production maka nomor kartu yang di request harus berawalan angka 1, jika bukan angka 1 maka ditolak + // if (card_number.substring(0, 1) != '1') { + // result = { + // code: '400', + // message: "It's not production card number.", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + // result + // )}` + // ); + + // return res.status(200).json(result); + // } + // } else { + // // jika settingan bukan production, bisa development atau local maka jika ada nomor kartu berawalan angka 1 maka ditolak + // if (card_number.substring(0, 1) == '1') { + // result = { + // code: '400', + // message: + // "It's production card number. Please use the development card number.", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + // result + // )}` + // ); + + // return res.status(200).json(result); + // } + // } + + // time + let now = moment().format('YYYY-MM-DD HH:mm:ss'); + let year = moment().format('Y'); + let month = moment().format('M'); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: 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 LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + // get parameter setting pengecekkan nomor kartu dengan card product di CMS + let getCheckByCardProductStatusValue = + await model.getCheckByCardProductStatusValue(); + + // check value global parameter + if (!getCheckByCardProductStatusValue) { + result = { + code: '439', + message: 'HSM_CHECK_BY_CARD_PRODUCT_STAT in global parameter not found', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + let checkByCardProductStatusValue = + getCheckByCardProductStatusValue.c_value; + + // jika settingan pengecekkan nomor kartu dengan card product CMS aktif + if (checkByCardProductStatusValue == 'A') { + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking card number...` + // ); + + // check card number request dengan list card number yang terdaftar di CMS + let checkCardNumber = await model.checkCardNumber(card_number); + + // jika nomor kartu yang di request di terdaftar di CMS maka di tolak + if (!checkCardNumber) { + result = { + code: '413', + message: 'card number is not registered', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking flag on the card and the server...` + // ); + + // check last flag untuk nomor kartu dan uid yang di request di sistem CMS + let checkFlag = await model.checkFlag(card_number, uid.toUpperCase()); + let lastFlag = null; + + // jika flag atas nomor kartu dan uid yang di request ditemukan di CMS maka set flag terkahir kartu seperti data dari CMS + if (checkFlag) { + lastFlag = checkFlag.c_flag; + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending...` + // ); + + // get total reservation pending + let getReservationPending = await model.getReservationPendingV2( + card_number, + now, + flag + ); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking fraud transaction...` + // ); + + // cek disini apakah sebelumnya topup + let cardHistory = await model.checkCardHistory(card_number); + + if (cardHistory.length > 0) { + if (cardHistory.i_log_name == 21 && cardHistory.c_source == 'CMS') { + if (getReservationPending.length > 0) { + // insert semua reserve balance ke fraud + let dataFraud = []; + let rsv = []; + for (let item of getReservationPending) { + rsv.push(item.c_reservation_no); + dataFraud.push({ + c_card_number: item.c_card_number, + c_reservation_no: item.c_reservation_no, + i_reservation_amount: parseInt(item.i_reservation_amount), + c_reservation_status: item.c_status, + c_reservation_flag: item.c_flag, + c_reservation_ref_no: item.c_ref_no, + }); + } + winston.logger.debug( + `${uniqueCode} INSERT TO trx.t_d_froud ${JSON.stringify(dataFraud)}` + ); + let fraud = await model.insertFraud(dataFraud); + // log debug + winston.logger.debug( + `${uniqueCode} RESERVE NUMBER FROM trx.t_d_froud ${JSON.stringify( + fraud + )}` + ); + winston.logger.debug( + `${uniqueCode} reserve number ${JSON.stringify(rsv)}` + ); + + // update reserve balance + await model.updateFraudToReserve(rsv); + } else { + result = { + code: '414', + message: "reservation doesn't exist", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST updateFraudToReserve ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } + } + + // get total reservation pending with compare flag counter on card and the reservation transaction + // where status != -1 + let getReservationPendingWithFlagCounter = + await model.getReservationPendingWithFlagCounter(card_number, now, flag); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending with flag...` + // ); + // get total reservation pending + // let getReservationPendingWithFlag = + // await model.getReservationPendingWithFlag(card_number, now); + + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG X ]: ${JSON.stringify( + getReservationPendingWithFlagCounter + )}` + ); + + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 1.1 ]: ${JSON.stringify( + // getReservationPending + // )}` + // ); + + + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 2 ]: ${JSON.stringify(req.body)}` + // ); + + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 2.1 ]: ${flag}` + // ); + + if (getReservationPendingWithFlagCounter.length > 0) { + if (lastFlag) { + + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG Y ]: ${card_number}` + ); + + // manipulasi last flag jika flag kartu sudah kembali ke 0 + if (parseInt(lastFlag) == 255 && parseInt(flag) == 0) { + lastFlag = -1 + } + + if (parseInt(lastFlag) < parseInt(flag)) { + + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG Z ]: ${card_number}` + ); + + let reservationNumberPendingSuccessLoaded = []; + let loadBalanceNumberPendingSuccessLoaded = []; + let totalReservationAmount = 0; + + getReservationPendingWithFlagCounter.forEach((element) => { + reservationNumberPendingSuccessLoaded.push( + element.c_reservation_no + ); + if (element.c_load_balance_no) { + loadBalanceNumberPendingSuccessLoaded.push( + element.c_load_balance_no + ); + } + totalReservationAmount += parseInt(element.i_reservation_amount); + }); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: updating reservation and load balance transaction...` + // ); + + // update + let insertUpdate = await updateAllTransaction( + reservationNumberPendingSuccessLoaded, + loadBalanceNumberPendingSuccessLoaded, + mid, + tid, + card_number, + balance, + flag, + uniqueCode, + totalReservationAmount, + uid + ); + + if (insertUpdate) { + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSINGE LOADING-BALANCE-REQUEST ]: updating flag to server...` + // ); + + // update flag from Server + await model.updateFlag( + now, + card_number, + uid.toUpperCase(), + balance, + flag + ); + + result = { + code: '01', + message: 'your card number has been cleared successfully', + data: { + load_balance_number: loadBalanceNumberPendingSuccessLoaded[0], + amount: parseInt(totalReservationAmount), + total_reservation: getReservationPendingWithFlagCounter.length, + reservation_number: reservationNumberPendingSuccessLoaded, + partial_topup: false, + }, + }; + } else { + result = { + code: '423', + message: 'updated failed', + data: {}, + }; + } + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + + if (getReservationPending.length < 1) { + return res.status(200).json(result); + } + } + } + } + + // log debug + // winston.logger.debug(`${uniqueCode} updating flag to server...`); + + // // update flag from Server + // await model.updateFlag(now, card_number, uid.toUpperCase(), balance, flag); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending...` + // ); + + // reget total reservation pending + getReservationPending = await model.getReservationPendingV2( + card_number, + now, + flag + ); + + if (getReservationPending.length < 1) { + result = { + code: '414', + message: "reservation doesn't exist", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST getReservationPending ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + let partialTopup = false; + let totalReservation = 0; + let amountTopup = 0; + let reservationNumber = []; + let reservationNumberTemp = []; + let i = 0; + getReservationPending.forEach((rsv) => { + amountTopup += parseInt(rsv.i_reservation_amount); + reservationNumber.push(rsv.c_reservation_no); + reservationNumberTemp.push(rsv.c_reservation_no); + i++; + }); + + totalReservation = i; + if (totalReservation == 0) { + result = { + code: '414', + message: "reservation doesn't exist", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST totalReservation ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking the card number in list fraud transaction or not...XXXXXXXXXXXXXXXXXXXX` + // ); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking total topup amount...` + // ); + + // check total amount topup + if (parseInt(amountTopup) <= 0) { + result = { + code: '415', + message: 'amount must be greater than 0', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking BI regulation status...` + // ); + + // get BI regulation status + let getBIRegulationStatus = await model.getBIRegulationStatus(); + + // check value global parameter + if (!getBIRegulationStatus) { + result = { + code: '439', + message: 'HSM_BI_REGULATION_STAT in global parameter not found', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + if (getBIRegulationStatus.c_value == 'A') { + // log debug + // winston.logger.debug(`${uniqueCode} checking topup partial status...`); + + // check topup partial status + let getTopupPartialStatus = await model.getTopupPartialStatus(); + + // check value global parameter + if (!getTopupPartialStatus) { + result = { + code: '439', + message: 'HSM_TOPUP_PARTIAL_STAT in global parameter not found', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max balance on the card...` + // ); + + // get max saldo on the card + let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); + + // check value global parameter + if (!getMaxAmountOnTheCard) { + result = { + code: '439', + message: + 'HSM_BI_MAX_AMOUNT_ON_THE_CARD in global parameter not found', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + if (getMaxAmountOnTheCard.c_value) { + if ( + parseInt(balance) + parseInt(amountTopup) > + parseInt(getMaxAmountOnTheCard.c_value) + ) { + // if topup partial is active + if (getTopupPartialStatus.c_value == 'A') { + // reset reservation data + partialTopup = true; + totalReservation = 0; + amountTopup = 0; + reservationNumber = []; + reservationNumberTemp = []; + i = 0; + + // sum amount can be topup + getReservationPending.forEach((rsv) => { + if ( + parseInt(balance) + parseInt(amountTopup) <= + parseInt(getMaxAmountOnTheCard.c_value) + ) { + amountTopup += parseInt(rsv.i_reservation_amount); + if ( + amountTopup > parseInt(getMaxAmountOnTheCard.c_value) || + parseInt(balance) + amountTopup > + parseInt(getMaxAmountOnTheCard.c_value) + ) { + amountTopup = + amountTopup - parseInt(rsv.i_reservation_amount); + i--; + } else { + reservationNumber.push(rsv.c_reservation_no); + reservationNumberTemp.push(rsv.c_reservation_no); + } + } + i++; + }); + + totalReservation = i; + if (totalReservation == 0) { + result = { + code: '414', + message: + "reservation doesn't exist. Lowest amount exceeds the maximum balance", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } else { + result = { + code: '416', + message: 'your card number has reached the maximum balance', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: 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 + let getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); + + // check value global parameter + if (!getMaxTopupPerMonth) { + result = { + code: '439', + message: 'HSM_BI_MAX_TOPUP_PER_MONTH in global parameter not found', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + if (getMaxTopupPerMonth.c_value) { + if ( + parseInt(accumulatedBalance) + parseInt(amountTopup) > + parseInt(getMaxTopupPerMonth.c_value) + ) { + // if topup partial is active + if (getTopupPartialStatus.c_value == 'A') { + // reset reservation data + partialTopup = true; + totalReservation = 0; + amountTopup = 0; + reservationNumber = []; + reservationNumberTemp = []; + i = 0; + + // sum amount can be topup + getReservationPending.forEach((rsv) => { + if ( + parseInt(balance) + parseInt(amountTopup) <= + parseInt(getMaxAmountOnTheCard.c_value) + ) { + amountTopup += parseInt(rsv.i_reservation_amount); + if ( + amountTopup > parseInt(getMaxAmountOnTheCard.c_value) || + parseInt(balance) + amountTopup > + parseInt(getMaxAmountOnTheCard.c_value) + ) { + amountTopup = + amountTopup - parseInt(rsv.i_reservation_amount); + i--; + } else { + reservationNumber.push(rsv.c_reservation_no); + reservationNumberTemp.push(rsv.c_reservation_no); + } + } + i++; + }); + + totalReservation = i; + if (totalReservation == 0) { + result = { + code: '417', + message: + "reservation doesn't exist. Lowest amount exceeds the limit top up for this month", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } else { + result = { + code: '417', + message: 'your card number has been limit top up for this month', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } + } + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: updating status reservation to in progress...${reservationNumberTemp}, ${now}, ${flag}` + // ); + + // update status to in progress + let updateStatusReservation = await model.updateStatusReservation( + reservationNumberTemp, + now, + flag + ); + + if (updateStatusReservation) { + result = { + code: '00', + message: 'reservation exists', + data: { + amount: parseInt(amountTopup), + total_reservation: totalReservation, + reservation_number: reservationNumber, + partial_topup: partialTopup, + }, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + } else { + result = { + code: '434', + message: '[434] Failed, please try again later', + data: { + amount: parseInt(amountTopup), + total_reservation: totalReservation, + reservation_number: reservationNumber, + partial_topup: partialTopup, + }, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( + result + )}` + ); + } + + return res.json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE LOADING-BALANCE-REQUEST ]: 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: {}, + }); + } +}; + +module.exports = { loadingBalanceRequest }; diff --git a/application/modules/loadbalance/load-balance-write.service.js b/application/modules/loadbalance/load-balance-write.service.js new file mode 100644 index 0000000..2d5f465 --- /dev/null +++ b/application/modules/loadbalance/load-balance-write.service.js @@ -0,0 +1,943 @@ +const winston = require('../../helpers/winston.logger'); +const model = require('./loadbalance.model'); +const moment = require('moment'); + +// Alur tulis saldo dipakai oleh HSM dan proses permintaan saldo. +const updateAllTransaction = async ( + reservationNumber, + loadBalanceNumber, + mid, + tid, + cardNumber, + balance, + flag, + uniqueCode, + totalReservationAmount, + uid +) => { + try { + // log debug + winston.logger.debug(`${uniqueCode} getting last reservation with flag...`); + + // log debug + winston.logger.debug( + `${uniqueCode} getting last load balance transaction...` + ); + + // get load balance + let dataLoadingBalance = null; + let dataLoadingBalanceDetail = []; + + if (loadBalanceNumber.length > 0) { + let getLastLoadingBalanceFlag = await model.getLastLoadingBalanceFlag( + loadBalanceNumber + ); + if (getLastLoadingBalanceFlag) { + dataLoadingBalance = getLastLoadingBalanceFlag; + } + } + + // get detail load balance + if (dataLoadingBalance) { + // log debug + winston.logger.debug( + `${uniqueCode} getting last load balance detail transaction...` + ); + + let getLastLoadingBalanceDetailFlag = + await model.getLastLoadingBalanceDetailFlag( + dataLoadingBalance.i_load_balance + ); + if (getLastLoadingBalanceDetailFlag) { + dataLoadingBalanceDetail = getLastLoadingBalanceDetailFlag; + } + } + + // time + let now = moment().format('YYYY-MM-DD HH:mm:ss'); + let getPartner = await model.getPartner(mid, tid); + + if (dataLoadingBalance && dataLoadingBalanceDetail.length > 0) { + let data = { + c_load_balance_no: dataLoadingBalance.c_load_balance_no, + d_load_balance: dataLoadingBalance.d_load_balance, + c_ref_no: dataLoadingBalance.c_ref_no, + i_partner: dataLoadingBalance.i_partner, + c_partner_code: dataLoadingBalance.c_partner_code, + c_partner_name: dataLoadingBalance.c_partner_name, + i_merchant: dataLoadingBalance.i_merchant, + c_merchant_code: dataLoadingBalance.c_merchant_code, + c_merchant_name: dataLoadingBalance.c_merchant_name, + c_mid: dataLoadingBalance.c_mid, + i_terminal: dataLoadingBalance.i_terminal, + c_terminal_code: dataLoadingBalance.c_terminal_code, + c_terminal_name: dataLoadingBalance.c_terminal_name, + c_tid: dataLoadingBalance.c_tid, + c_card_number: dataLoadingBalance.c_card_number, + i_topup_amount: dataLoadingBalance.i_topup_amount, + m_balance: dataLoadingBalance.m_balance, + c_return_sap: null, + i_load_balance_no_seq: dataLoadingBalance.i_load_balance_no_seq, + c_idm: dataLoadingBalance.c_idm, + c_status: 'A', + c_status_name: 'SUCCESS', + d_create: now, + i_create: null, + c_create_username: null, + c_create_fullname: null, + d_modify: null, + i_modify: null, + c_modify_username: null, + c_modify_fullname: null, + d_delete: null, + i_delete: null, + c_delete_username: null, + c_delete_fullname: null, + }; + + // log debug + winston.logger.debug( + `${uniqueCode} updating reservation and load balance transaction...` + ); + + // update reservation and load balance transaction + const update = await model.updateReservationAndLoadingBalance( + reservationNumber, + data, + dataLoadingBalanceDetail, + now, + flag + ); + + if (update) { + // log debug + winston.logger.debug(`${uniqueCode} inserting log for card history...`); + + // log card history + await model.createLoadBalanceLog({ + i_log_name: 21, + d_log: dataLoadingBalance.d_load_balance, + c_card_number: cardNumber, + c_source: 'CMS', + c_location: getPartner ? getPartner.partner_name : null, + m_balance_before: parseInt(dataLoadingBalance.m_balance), + m_amount: parseInt(dataLoadingBalance.i_topup_amount), + m_balance_after: parseInt(balance), + j_new_data: { data: data, detail: dataLoadingBalanceDetail }, + j_old_data: null, + c_note: `LOAD BALANCE ${dataLoadingBalance.i_topup_amount} FROM ${ + getPartner ? getPartner.partner_name : null + } SUCCESSFULLY`, + c_status: 'S', + d_created: now, + i_create: null, + c_create_username: 'HSM', + c_create_fullname: 'HARDWARE SECURE MODULE', + c_category: 'T', + }); + + return true; + } else { + return false; + } + } else { + // insert new load balance transaction by data on card and update data reservation + + // log debug + winston.logger.debug( + `${uniqueCode} generating and insert new data load balance...` + ); + + const { number: newLoadBalanceNumber, sequence: loadBalanceNoSequence } = + await model.allocateLoadBalanceNumber(getPartner.partner_code, moment(now).format('YYMMDD')); + + let dataLoadBalance = { + c_load_balance_no: newLoadBalanceNumber, + d_load_balance: now, + c_ref_no: null, + i_partner: getPartner.i_partner, + c_partner_code: getPartner.partner_code, + c_partner_name: getPartner.partner_name, + i_merchant: getPartner.i_merchant, + c_merchant_code: getPartner.merchant_code, + c_merchant_name: getPartner.merchant_name, + c_mid: getPartner.mid, + i_terminal: getPartner.i_terminal, + c_terminal_code: getPartner.terminal_code, + c_terminal_name: getPartner.terminal_name, + c_tid: getPartner.tid, + c_card_number: cardNumber, + i_topup_amount: totalReservationAmount, + m_balance: balance, + c_return_sap: null, + i_load_balance_no_seq: loadBalanceNoSequence, + c_idm: uid, + c_status: 'A', + c_status_name: 'SUCCESS', + d_create: now, + i_create: null, + c_create_username: null, + c_create_fullname: null, + d_modify: null, + i_modify: null, + c_modify_username: null, + c_modify_fullname: null, + d_delete: null, + i_delete: null, + c_delete_username: null, + c_delete_fullname: null, + }; + + // create detaial load balance + let detailLoadBalance = + await model.createDetailLoadBalanceFromReservation(reservationNumber); + + // log debug + // winston.logger.debug( + // `${uniqueCode} detail load balance with reservation no : ${JSON.stringify( + // reservationNumber + // )}` + // ); + + if (detailLoadBalance.length > 0) { + // log warn + // winston.logger.warn( + // `${uniqueCode} AAAAAAAAAAAAAAAAAA1111 [DATA] : ${JSON.stringify( + // reservationNumber + // )} [LB] : ${JSON.stringify(dataLoadBalance)} [LBD] : ${JSON.stringify( + // detailLoadBalance + // )} [NOW] : ${JSON.stringify(now)} [FLAG] : ${JSON.stringify(flag)}` + // ); + + // log debug + // winston.logger.debug( + // `${uniqueCode} updating reservation and insert new load balance transaction...` + // ); + + // update reservation and load balance transaction + let updateReservationAndInsertLoadingBalance = + await model.updateReservationAndInsertLoadingBalance( + reservationNumber, + dataLoadBalance, + detailLoadBalance, + now, + flag + ); + + // log debug + // winston.logger.debug( + // `${uniqueCode} status insert new load balance and update reservation : ${JSON.stringify( + // updateReservationAndInsertLoadingBalance + // )}` + // ); + + // if (updateReservationAndInsertLoadingBalance > 0) { + // // log debug + // winston.logger.debug( + // `${uniqueCode} inserting log for card history...` + // ); + + // // log card history + // await model.createLoadBalanceLog({ + // i_log_name:21, + // d_log: dataLoadingBalance.d_load_balance, + // c_card_number: cardNumber, + // c_source: 'CMS', + // c_location: getPartner ? getPartner.partner_name : null, + // m_balance_before: parseInt(dataLoadingBalance.m_balance), + // m_amount: parseInt(dataLoadingBalance.i_topup_amount), + // m_balance_after: parseInt(balance), + // j_new_data: { data: data, detail: dataLoadingBalanceDetail }, + // j_old_data: null, + // c_note: `LOAD BALANCE ${dataLoadingBalance.i_topup_amount} FROM ${ + // getPartner ? getPartner.partner_name : null + // } SUCCESSFULLY`, + // c_status: 'S', + // d_created: now, + // i_create: null, + // c_create_username: 'HSM', + // c_create_fullname: 'HARDWARE SECURE MODULE', + // c_category: 'T', + // }); + // } else { + // return false; + // } + } else { + return false; + } + + return true; + } + } catch (error) { + // create log + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); + + return false; + } +}; + +const loadingBalanceInsert = async (req, param) => { + try { + // param + let mid = param.mid; + let tid = param.tid; + let card_number = param.card_number; + let amount = param.amount; + let reservation_number = param.reservation_number; + let ref_no = param.ref_no; + let write_status = param.write_status; + let uid = param.uid; + let balance = param.balance; + let flag = param.flag; + let unique_code = param.unique_code; + let execution_id = param.execution_id; + + let uniqueCode = unique_code ? unique_code : 9999999999999; + let result = {}; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST LOADING-BALANCE-INSERT ]: ${JSON.stringify( + param + )}` + ); + + // time + let now = moment().format('YYYY-MM-DD HH:mm:ss'); + + // log warn + winston.logger.warn(`${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 LOADING-BALANCE-INSERT ]: ${JSON.stringify( + result + )}` + ); + + return result; + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + // Pemanggil HSM yang mengirim respons HTTP. + return result; + } + + // log warn + // winston.logger.warn( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation status...` + // ); + + const statuses = await model.findReservationsWithLoadedBalance(reservation_number); + const statusByNumber = new Map(statuses.map((status) => [status.c_reservation_no, status])); + // Urutan input menentukan respons pertama, walaupun PostgreSQL mengurutkan hasilnya. + for (const number of reservation_number) { + const reservationStatus = statusByNumber.get(String(number)); + + // if reservation doesn't exist or has been canceled + if (!reservationStatus) { + result = { + code: '414', + message: "reservation doesn't exist", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( + result + )}` + ); + + return result; + } + + if (reservationStatus.loaded_id != null) { + result = { + code: '00', + message: + 'reservation has been successfully loaded on ' + + moment(reservationStatus.loaded_at).format('DD MMM YYYY HH:mm:ss'), + data: { load_balance_number: reservationStatus.loaded_number }, + }; + winston.logger.info( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(result)}` + ); + return result; + } + } + + // log warn + // winston.logger.warn( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking last log history...` + // ); + + // get last history by card number + let lastHistory = await model.getLastHistory(card_number); + + if (lastHistory) { + // if last history card is topup (21 = log name id for topup) + if (lastHistory.i_log_name == 21 && lastHistory.c_source == 'CMS') { + // log warn + // winston.logger.warn( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting fraud transaction...` + // ); + + // insert reservation transaction to fraud table + await model.insertFraudTransaction(reservation_number); + + // log warn + // winston.logger.warn( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: suspending reservation...` + // ); + + // update reservation with suspend status + await model.suspendReservation(reservation_number, now); + + result = { + code: '432', + message: 'your card number has fraud transaction', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( + result + )}` + ); + + return result; + } + } + + // log warn + // winston.logger.warn( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking fraud transaction...` + // ); + + // get data fraud by card number and status fraud is not closed + let fraudTransaction = await model.getFraudTransaction(card_number); + let fraudReservationNumber = []; + + if (fraudTransaction.length > 0) { + fraudTransaction.forEach((rsv) => { + fraudReservationNumber.push(rsv.c_reservation_no); + }); + } + + // log warn + // winston.logger.warn( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation pending...` + // ); + + // get total reservation pending without fraud + let getReservationPending = await model.getReservationPendingWithoutFraud( + card_number, + flag, + fraudReservationNumber + ); + + if (getReservationPending.length < 1) { + result = { + code: '414', + message: "reservation doesn't exist", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( + result + )}` + ); + + return result; + } + + // log warn + // winston.logger.warn( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking total topup amount...` + // ); + + // check total topup and request topup + let amountTopup = 0; + getReservationPending.forEach((rsv) => { + amountTopup += parseInt(rsv.i_reservation_amount); + }); + + if (parseInt(amount) != parseInt(amountTopup)) { + result = { + code: '418', + message: 'topup amount is different', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( + result + )}` + ); + + return result; + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting reservation detail...` + // ); + + const detail = []; + reservation_number = getReservationPending.map((pending) => pending.c_reservation_no); + const reservations = await model.findReservationDetails(reservation_number); + const detailByNumber = new Map(reservations.map((reservation) => [reservation.c_reservation_no, reservation])); + for (const number of reservation_number) { + const reservation = detailByNumber.get(String(number)); + + if (!reservation) { + result = { + code: '414', + message: "reservation doesn't exist", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( + result + )}` + ); + + return result; + } + detail.push({ + i_reservation_balance: reservation.i_reservation_balance + ? reservation.i_reservation_balance + : null, + c_reservation_no: reservation.i_reservation_balance + ? reservation.c_reservation_no + : null, + i_amount: reservation.i_reservation_balance + ? reservation.i_reservation_amount + : null, + i_issuer: reservation.i_reservation_balance + ? reservation.i_issuer + : null, + i_issuer_code: reservation.i_reservation_balance + ? reservation.c_issuer_code + : null, + i_issuer_name: reservation.i_reservation_balance + ? reservation.c_issuer_name + : null, + i_issuer_fee: reservation.i_reservation_balance + ? reservation.i_issuer_fee + : null, + i_channel: reservation.i_reservation_balance + ? reservation.i_channel + : null, + i_channel_code: reservation.i_reservation_balance + ? reservation.c_channel_code + : null, + i_channel_name: reservation.i_reservation_balance + ? reservation.c_channel_name + : null, + i_channel_fee: reservation.i_reservation_balance + ? reservation.i_channel_fee + : null, + }); + } + + const { number: loadBalanceNumber, sequence: loadBalanceNoSequence } = + await model.allocateLoadBalanceNumber(getPartner.partner_code, moment(now).format('YYMMDD')); + + let data = { + c_load_balance_no: loadBalanceNumber, + d_load_balance: now, + c_ref_no: ref_no, + i_partner: getPartner ? getPartner.i_partner : null, + c_partner_code: getPartner ? getPartner.partner_code : null, + c_partner_name: getPartner ? getPartner.partner_name : null, + i_merchant: getPartner ? getPartner.i_merchant : null, + c_merchant_code: getPartner ? getPartner.merchant_code : null, + c_merchant_name: getPartner ? getPartner.merchant_name : null, + c_mid: getPartner ? getPartner.mid : null, + i_terminal: getPartner ? getPartner.i_terminal : null, + c_terminal_code: getPartner ? getPartner.terminal_code : null, + c_terminal_name: getPartner ? getPartner.terminal_name : null, + c_tid: getPartner ? getPartner.tid : null, + c_card_number: card_number, + i_execution_id: execution_id, + i_topup_amount: amount ? parseInt(amount) : amount, + m_balance: balance ? parseInt(balance) : balance, + c_return_sap: null, + i_load_balance_no_seq: loadBalanceNoSequence, + c_idm: uid, + c_status: write_status ? 'F' : 'P', + c_status_name: write_status ? 'FAILED' : 'PENDING', + d_create: now, + i_create: null, + c_create_username: null, + c_create_fullname: null, + d_modify: null, + i_modify: null, + c_modify_username: null, + c_modify_fullname: null, + d_delete: null, + i_delete: null, + c_delete_username: null, + c_delete_fullname: null, + }; + + // check data load balance by reservation_number exist or not + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking load balance transaction has been exists or not...` + // ); + + // log warn + // winston.logger.warn( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting load balance transaction...` + // ); + + // insert transaction + let insertLoadingBalance = await model.insertLoadingBalance( + data, + detail, + reservation_number, + now, + write_status, + card_number, + uid.toUpperCase(), + balance, + flag + ); + + // log warn + // winston.logger.warn( + // `${uniqueCode} [DATA] : ${JSON.stringify( + // data + // )} [DETAIL] : ${JSON.stringify(detail)} [RSV] : ${JSON.stringify( + // reservation_number + // )} [NOW] : ${JSON.stringify(now)} [WRITE STATUS] : ${JSON.stringify( + // write_status + // )} [CARD NUMBER] : ${JSON.stringify( + // card_number + // )} [UID] : ${JSON.stringify(uid)} [BALANCE] : ${JSON.stringify( + // balance + // )} [FLAG] : ${JSON.stringify(flag)}` + // ); + if (insertLoadingBalance > 0) { + result = { + code: '00', + message: write_status + ? 'transaction saved successfully. Err: failed write to the card' + : 'balance loaded successfully', + data: { + load_balance_number: loadBalanceNumber, + }, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( + result + )}` + ); + } else { + result = { + code: '433', + message: '[433] Failed, please try again later', + data: { + load_balance_number: loadBalanceNumber, + }, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( + result + )}` + ); + } + + return result; + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE LOADING-BALANCE-INSERT ]: 500 internal server error - backend server | ${error.message}` + ); + + return { + code: '500', + message: + process.env.NODE_ENV != 'production' + ? error.message + : '500 internal server error - backend server.', + data: {}, + }; + } +}; + +const loadingBalanceUpdate = async (param) => { + try { + // param + let mid = param.mid; + let tid = param.tid; + let card_number = param.card_number; + let amount = param.amount; + let reservation_number = param.reservation_number; + let ref_no = param.ref_no; + let write_status = param.write_status; + let uid = param.uid; + let balance = param.balance; + let flag = param.flag; + let unique_code = param.unique_code; + let loadBalanceNumber = param.load_balance_number; + + let uniqueCode = unique_code ? unique_code : 9999999999999; + let result = {}; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST LOADING-BALANCE-UPDATE ]: ${JSON.stringify( + param + )}` + ); + + // time + let now = moment().format('YYYY-MM-DD HH:mm:ss'); + let today = moment().format('YYYY-MM-DD'); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: 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 LOADING-BALANCE-UPDATE ]: ${JSON.stringify( + result + )}` + ); + + return result; + } + + // if (getPartner.i_partner != req.partner_id_token) { + // result = { + // code: '412', + // message: 'partner is not match', + // data: {}, + // }; + + // return res.status(200).json(result); + // } + + let data = { + d_load_balance: now, + c_ref_no: ref_no, + m_balance: balance, + c_return_sap: null, + c_status: write_status ? 'F' : 'A', + c_status_name: write_status ? 'FAILED' : 'SUCCESS', + d_modify: now, + i_modify: null, + c_modify_username: null, + c_modify_fullname: null, + }; + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: updating load balance transaction...` + // ); + + // update transaction + await model.updateLoadingBalance( + data, + now, + write_status, + card_number, + uid.toUpperCase(), + balance, + flag, + loadBalanceNumber + ); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: inserting load balance transaction history ${loadBalanceNumber}...` + // ); + + let findDataLoadBalance = await model.findLoadBalance(loadBalanceNumber); + let dataLoadBalance = {}; + let detailLoadBalance = []; + + if (findDataLoadBalance) { + let findDataLoadBalanceDetail = await model.findLoadBalanceDetail( + findDataLoadBalance.i_load_balance + ); + + if (findDataLoadBalance) { + dataLoadBalance = { + c_load_balance_no: findDataLoadBalance.c_load_balance_no, + d_load_balance: now, + c_ref_no: findDataLoadBalance.c_ref_no, + i_partner: findDataLoadBalance.i_partner, + c_partner_code: findDataLoadBalance.c_partner_code, + c_partner_name: findDataLoadBalance.c_partner_name, + i_merchant: findDataLoadBalance.i_merchant, + c_merchant_code: findDataLoadBalance.c_merchant_code, + c_merchant_name: findDataLoadBalance.c_merchant_name, + c_mid: findDataLoadBalance.c_mid, + i_terminal: findDataLoadBalance.i_terminal, + c_terminal_code: findDataLoadBalance.c_terminal_code, + c_terminal_name: findDataLoadBalance.c_terminal_name, + c_tid: findDataLoadBalance.c_tid, + c_card_number: findDataLoadBalance.c_card_number, + i_topup_amount: findDataLoadBalance.i_topup_amount, + m_balance: findDataLoadBalance.m_balance, + c_return_sap: findDataLoadBalance.c_return_sap, + i_load_balance_no_seq: findDataLoadBalance.i_load_balance_no_seq, + c_idm: findDataLoadBalance.c_idm, + c_status: write_status ? 'F' : 'A', + c_status_name: write_status ? 'FAILED' : 'SUCCESS', + d_create: findDataLoadBalance.d_create, + i_create: findDataLoadBalance.i_create, + c_create_username: findDataLoadBalance.c_create_username, + c_create_fullname: findDataLoadBalance.c_create_fullname, + d_modify: now, + i_modify: findDataLoadBalance.i_modify, + c_modify_username: findDataLoadBalance.c_modify_username, + c_modify_fullname: findDataLoadBalance.c_modify_fullname, + d_delete: findDataLoadBalance.d_delete, + i_delete: findDataLoadBalance.i_delete, + c_delete_username: findDataLoadBalance.c_delete_username, + c_delete_fullname: findDataLoadBalance.c_delete_fullname, + }; + + let i = 0; + findDataLoadBalanceDetail.forEach((element) => { + detailLoadBalance[i] = { + i_reservation_balance: element.i_reservation_balance, + c_reservation_no: element.c_reservation_no, + i_amount: element.i_amount, + i_issuer: element.i_issuer, + i_issuer_code: element.c_issuer_code, + i_issuer_name: element.c_issuer_name, + i_issuer_fee: element.i_issuer_fee, + i_channel: element.i_channel, + i_channel_code: element.c_channel_code, + i_channel_name: element.c_channel_name, + i_channel_fee: element.i_channel_fee, + }; + i++; + }); + + // insert transaction + await model.insertLoadingBalanceHistoryOnly( + dataLoadBalance, + detailLoadBalance, + reservation_number, + now, + write_status, + card_number, + uid.toUpperCase(), + balance, + flag + ); + } + } + + if (!write_status) { + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: inserting log for card history...` + // ); + + // log card history + await model.createLoadBalanceLog({ + i_log_name: 21, + d_log: now, + c_card_number: card_number, + c_source: 'CMS', + c_location: getPartner ? getPartner.partner_name : null, + m_balance_before: parseInt(balance) > 0 ? parseInt(balance) : 0, + m_amount: parseInt(amount), + m_balance_after: parseInt(balance) + parseInt(amount), + j_new_data: { data: dataLoadBalance, detail: detailLoadBalance }, + j_old_data: null, + c_note: `LOAD BALANCE ${amount} FROM ${ + getPartner ? getPartner.partner_name : null + } SUCCESSFULLY`, + c_status: 'S', + d_created: now, + i_create: null, + c_create_username: 'HSM', + c_create_fullname: 'HARDWARE SECURE MODULE', + c_category: 'T', + }); + } + + result = { + code: '00', + message: write_status + ? 'transaction saved successfully. Err: failed write to the card' + : 'balance loaded successfully', + data: { + load_balance_number: loadBalanceNumber, + }, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE LOADING-BALANCE-UPDATE ]: ${JSON.stringify( + result + )}` + ); + + return result; + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE LOADING-BALANCE-UPDATE ]: 500 internal server error - backend server | ${error.message}` + ); + + return { + code: '500', + message: + process.env.NODE_ENV != 'production' + ? error.message + : '500 internal server error - backend server.', + data: {}, + }; + } +}; + +module.exports = { updateAllTransaction, loadingBalanceInsert, loadingBalanceUpdate }; diff --git a/application/modules/loadbalance/loadbalance.controller.js b/application/modules/loadbalance/loadbalance.controller.js index b58b058..5b7d06e 100644 --- a/application/modules/loadbalance/loadbalance.controller.js +++ b/application/modules/loadbalance/loadbalance.controller.js @@ -1,1808 +1,13 @@ -const { validationResult } = require('express-validator'); const validate = require('./loadbalance.validation'); -const helper = require('../../helpers/helper'); -const winston = require('../../helpers/winston.logger'); -const model = require('./loadbalance.model'); const moment = require('moment'); +const { loadingBalanceRequest } = require('./load-balance-request.handler'); +const { + loadingBalanceInsert, + loadingBalanceUpdate, +} = require('./load-balance-write.service'); + moment.locale('id'); - -// ==================================================== FUNCTION UPDATE ALL TRANSACTION ====================================================== -// *Created By: Mohamad Ihsan* -// *Description:* -// function yang digunakan untuk meng-update data reservasi dan data load balance saat sebelum library frontend melakukan topup ke kartu -// atau saat library frontend meminta untuk melakukan topup ke dalam kartu - -const updateAllTransaction = async ( - reservationNumber, - loadBalanceNumber, - mid, - tid, - cardNumber, - balance, - flag, - uniqueCode, - totalReservationAmount, - uid -) => { - try { - // log debug - winston.logger.debug(`${uniqueCode} getting last reservation with flag...`); - - // log debug - winston.logger.debug( - `${uniqueCode} getting last load balance transaction...` - ); - - // get load balance - let dataLoadingBalance = null; - let dataLoadingBalanceDetail = []; - - if (loadBalanceNumber.length > 0) { - let getLastLoadingBalanceFlag = await model.getLastLoadingBalanceFlag( - loadBalanceNumber - ); - if (getLastLoadingBalanceFlag) { - dataLoadingBalance = getLastLoadingBalanceFlag; - } - } - - // get detail load balance - if (dataLoadingBalance) { - // log debug - winston.logger.debug( - `${uniqueCode} getting last load balance detail transaction...` - ); - - let getLastLoadingBalanceDetailFlag = - await model.getLastLoadingBalanceDetailFlag( - dataLoadingBalance.i_load_balance - ); - if (getLastLoadingBalanceDetailFlag) { - dataLoadingBalanceDetail = getLastLoadingBalanceDetailFlag; - } - } - - // time - let now = moment().format('YYYY-MM-DD HH:mm:ss'); - let getPartner = await model.getPartner(mid, tid); - - if (dataLoadingBalance && dataLoadingBalanceDetail.length > 0) { - let data = { - c_load_balance_no: dataLoadingBalance.c_load_balance_no, - d_load_balance: dataLoadingBalance.d_load_balance, - c_ref_no: dataLoadingBalance.c_ref_no, - i_partner: dataLoadingBalance.i_partner, - c_partner_code: dataLoadingBalance.c_partner_code, - c_partner_name: dataLoadingBalance.c_partner_name, - i_merchant: dataLoadingBalance.i_merchant, - c_merchant_code: dataLoadingBalance.c_merchant_code, - c_merchant_name: dataLoadingBalance.c_merchant_name, - c_mid: dataLoadingBalance.c_mid, - i_terminal: dataLoadingBalance.i_terminal, - c_terminal_code: dataLoadingBalance.c_terminal_code, - c_terminal_name: dataLoadingBalance.c_terminal_name, - c_tid: dataLoadingBalance.c_tid, - c_card_number: dataLoadingBalance.c_card_number, - i_topup_amount: dataLoadingBalance.i_topup_amount, - m_balance: dataLoadingBalance.m_balance, - c_return_sap: null, - i_load_balance_no_seq: dataLoadingBalance.i_load_balance_no_seq, - c_idm: dataLoadingBalance.c_idm, - c_status: 'A', - c_status_name: 'SUCCESS', - d_create: now, - i_create: null, - c_create_username: null, - c_create_fullname: null, - d_modify: null, - i_modify: null, - c_modify_username: null, - c_modify_fullname: null, - d_delete: null, - i_delete: null, - c_delete_username: null, - c_delete_fullname: null, - }; - - // log debug - winston.logger.debug( - `${uniqueCode} updating reservation and load balance transaction...` - ); - - // update reservation and load balance transaction - const update = await model.updateReservationAndLoadingBalance( - reservationNumber, - data, - dataLoadingBalanceDetail, - now, - flag - ); - - if (update) { - // log debug - winston.logger.debug(`${uniqueCode} inserting log for card history...`); - - // log card history - await model.createLoadBalanceLog({ - i_log_name: 21, - d_log: dataLoadingBalance.d_load_balance, - c_card_number: cardNumber, - c_source: 'CMS', - c_location: getPartner ? getPartner.partner_name : null, - m_balance_before: parseInt(dataLoadingBalance.m_balance), - m_amount: parseInt(dataLoadingBalance.i_topup_amount), - m_balance_after: parseInt(balance), - j_new_data: { data: data, detail: dataLoadingBalanceDetail }, - j_old_data: null, - c_note: `LOAD BALANCE ${dataLoadingBalance.i_topup_amount} FROM ${ - getPartner ? getPartner.partner_name : null - } SUCCESSFULLY`, - c_status: 'S', - d_created: now, - i_create: null, - c_create_username: 'HSM', - c_create_fullname: 'HARDWARE SECURE MODULE', - c_category: 'T', - }); - - return true; - } else { - return false; - } - } else { - // insert new load balance transaction by data on card and update data reservation - - // log debug - winston.logger.debug( - `${uniqueCode} generating and insert new data load balance...` - ); - - const { number: newLoadBalanceNumber, sequence: loadBalanceNoSequence } = - await model.allocateLoadBalanceNumber(getPartner.partner_code, moment(now).format('YYMMDD')); - - let dataLoadBalance = { - c_load_balance_no: newLoadBalanceNumber, - d_load_balance: now, - c_ref_no: null, - i_partner: getPartner.i_partner, - c_partner_code: getPartner.partner_code, - c_partner_name: getPartner.partner_name, - i_merchant: getPartner.i_merchant, - c_merchant_code: getPartner.merchant_code, - c_merchant_name: getPartner.merchant_name, - c_mid: getPartner.mid, - i_terminal: getPartner.i_terminal, - c_terminal_code: getPartner.terminal_code, - c_terminal_name: getPartner.terminal_name, - c_tid: getPartner.tid, - c_card_number: cardNumber, - i_topup_amount: totalReservationAmount, - m_balance: balance, - c_return_sap: null, - i_load_balance_no_seq: loadBalanceNoSequence, - c_idm: uid, - c_status: 'A', - c_status_name: 'SUCCESS', - d_create: now, - i_create: null, - c_create_username: null, - c_create_fullname: null, - d_modify: null, - i_modify: null, - c_modify_username: null, - c_modify_fullname: null, - d_delete: null, - i_delete: null, - c_delete_username: null, - c_delete_fullname: null, - }; - - // create detaial load balance - let detailLoadBalance = - await model.createDetailLoadBalanceFromReservation(reservationNumber); - - // log debug - // winston.logger.debug( - // `${uniqueCode} detail load balance with reservation no : ${JSON.stringify( - // reservationNumber - // )}` - // ); - - if (detailLoadBalance.length > 0) { - // log warn - // winston.logger.warn( - // `${uniqueCode} AAAAAAAAAAAAAAAAAA1111 [DATA] : ${JSON.stringify( - // reservationNumber - // )} [LB] : ${JSON.stringify(dataLoadBalance)} [LBD] : ${JSON.stringify( - // detailLoadBalance - // )} [NOW] : ${JSON.stringify(now)} [FLAG] : ${JSON.stringify(flag)}` - // ); - - // log debug - // winston.logger.debug( - // `${uniqueCode} updating reservation and insert new load balance transaction...` - // ); - - // update reservation and load balance transaction - let updateReservationAndInsertLoadingBalance = - await model.updateReservationAndInsertLoadingBalance( - reservationNumber, - dataLoadBalance, - detailLoadBalance, - now, - flag - ); - - // log debug - // winston.logger.debug( - // `${uniqueCode} status insert new load balance and update reservation : ${JSON.stringify( - // updateReservationAndInsertLoadingBalance - // )}` - // ); - - // if (updateReservationAndInsertLoadingBalance > 0) { - // // log debug - // winston.logger.debug( - // `${uniqueCode} inserting log for card history...` - // ); - - // // log card history - // await model.createLoadBalanceLog({ - // i_log_name:21, - // d_log: dataLoadingBalance.d_load_balance, - // c_card_number: cardNumber, - // c_source: 'CMS', - // c_location: getPartner ? getPartner.partner_name : null, - // m_balance_before: parseInt(dataLoadingBalance.m_balance), - // m_amount: parseInt(dataLoadingBalance.i_topup_amount), - // m_balance_after: parseInt(balance), - // j_new_data: { data: data, detail: dataLoadingBalanceDetail }, - // j_old_data: null, - // c_note: `LOAD BALANCE ${dataLoadingBalance.i_topup_amount} FROM ${ - // getPartner ? getPartner.partner_name : null - // } SUCCESSFULLY`, - // c_status: 'S', - // d_created: now, - // i_create: null, - // c_create_username: 'HSM', - // c_create_fullname: 'HARDWARE SECURE MODULE', - // c_category: 'T', - // }); - // } else { - // return false; - // } - } else { - return false; - } - - return true; - } - } catch (error) { - // create log - winston.logger.error( - `500 internal server error - backend server | ${error.message}` - ); - - return false; - } -}; - -// ======================================================= LOADING BALANCE REQUEST =========================================================== -// *Created By: Mohamad Ihsan* -// *Description:* -// proses yang digunakan untuk meminta data reservasi beserta amount nya yang akan di topup ke dalam kartu - -const loadingBalanceRequest = async (req, res) => { - try { - // param - // let { mid, tid, card_number, uid, balance, flag, unique_code } = req.body; - - let mid = req.body.mid; - let tid = req.body.tid; - let card_number = req.body.card_number; - let uid = req.body.uid; - let balance = req.body.balance; - let flag = req.body.flag; - let unique_code = req.body.unique_code; - - // uniqueCode = await helper.getUniqueCode(); - let uniqueCode = unique_code; - let result = {}; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - req.body - )}` - ); - - // check validator - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - let cardBlacklist = await model.getCardBlacklist(card_number); - if (cardBlacklist) { - if (cardBlacklist.c_status == 'B') { - result = { - code: '445', - message: 'Card is Blacklisted', - data: {}, - }; - return res.status(200).json(result); - } - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking production card number or not...` - // ); - - // jika settingan untuk server adalah production - // if (process.env.SERVER_FOR == 'production') { - // // jika settingan production maka nomor kartu yang di request harus berawalan angka 1, jika bukan angka 1 maka ditolak - // if (card_number.substring(0, 1) != '1') { - // result = { - // code: '400', - // message: "It's not production card number.", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - // result - // )}` - // ); - - // return res.status(200).json(result); - // } - // } else { - // // jika settingan bukan production, bisa development atau local maka jika ada nomor kartu berawalan angka 1 maka ditolak - // if (card_number.substring(0, 1) == '1') { - // result = { - // code: '400', - // message: - // "It's production card number. Please use the development card number.", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - // result - // )}` - // ); - - // return res.status(200).json(result); - // } - // } - - // time - let now = moment().format('YYYY-MM-DD HH:mm:ss'); - let year = moment().format('Y'); - let month = moment().format('M'); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: 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 LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // get parameter setting pengecekkan nomor kartu dengan card product di CMS - let getCheckByCardProductStatusValue = - await model.getCheckByCardProductStatusValue(); - - // check value global parameter - if (!getCheckByCardProductStatusValue) { - result = { - code: '439', - message: 'HSM_CHECK_BY_CARD_PRODUCT_STAT in global parameter not found', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - let checkByCardProductStatusValue = - getCheckByCardProductStatusValue.c_value; - - // jika settingan pengecekkan nomor kartu dengan card product CMS aktif - if (checkByCardProductStatusValue == 'A') { - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking card number...` - // ); - - // check card number request dengan list card number yang terdaftar di CMS - let checkCardNumber = await model.checkCardNumber(card_number); - - // jika nomor kartu yang di request di terdaftar di CMS maka di tolak - if (!checkCardNumber) { - result = { - code: '413', - message: 'card number is not registered', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking flag on the card and the server...` - // ); - - // check last flag untuk nomor kartu dan uid yang di request di sistem CMS - let checkFlag = await model.checkFlag(card_number, uid.toUpperCase()); - let lastFlag = null; - - // jika flag atas nomor kartu dan uid yang di request ditemukan di CMS maka set flag terkahir kartu seperti data dari CMS - if (checkFlag) { - lastFlag = checkFlag.c_flag; - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending...` - // ); - - // get total reservation pending - let getReservationPending = await model.getReservationPendingV2( - card_number, - now, - flag - ); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking fraud transaction...` - // ); - - // cek disini apakah sebelumnya topup - let cardHistory = await model.checkCardHistory(card_number); - - if (cardHistory.length > 0) { - if (cardHistory.i_log_name == 21 && cardHistory.c_source == 'CMS') { - if (getReservationPending.length > 0) { - // insert semua reserve balance ke fraud - let dataFraud = []; - let rsv = []; - for (let item of getReservationPending) { - rsv.push(item.c_reservation_no); - dataFraud.push({ - c_card_number: item.c_card_number, - c_reservation_no: item.c_reservation_no, - i_reservation_amount: parseInt(item.i_reservation_amount), - c_reservation_status: item.c_status, - c_reservation_flag: item.c_flag, - c_reservation_ref_no: item.c_ref_no, - }); - } - winston.logger.debug( - `${uniqueCode} INSERT TO trx.t_d_froud ${JSON.stringify(dataFraud)}` - ); - let fraud = await model.insertFraud(dataFraud); - // log debug - winston.logger.debug( - `${uniqueCode} RESERVE NUMBER FROM trx.t_d_froud ${JSON.stringify( - fraud - )}` - ); - winston.logger.debug( - `${uniqueCode} reserve number ${JSON.stringify(rsv)}` - ); - - // update reserve balance - await model.updateFraudToReserve(rsv); - } else { - result = { - code: '414', - message: "reservation doesn't exist", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST updateFraudToReserve ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } - } - - // get total reservation pending with compare flag counter on card and the reservation transaction - // where status != -1 - let getReservationPendingWithFlagCounter = - await model.getReservationPendingWithFlagCounter(card_number, now, flag); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending with flag...` - // ); - // get total reservation pending - // let getReservationPendingWithFlag = - // await model.getReservationPendingWithFlag(card_number, now); - - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG X ]: ${JSON.stringify( - getReservationPendingWithFlagCounter - )}` - ); - - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 1.1 ]: ${JSON.stringify( - // getReservationPending - // )}` - // ); - - - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 2 ]: ${JSON.stringify(req.body)}` - // ); - - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 2.1 ]: ${flag}` - // ); - - if (getReservationPendingWithFlagCounter.length > 0) { - if (lastFlag) { - - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG Y ]: ${card_number}` - ); - - // manipulasi last flag jika flag kartu sudah kembali ke 0 - if (parseInt(lastFlag) == 255 && parseInt(flag) == 0) { - lastFlag = -1 - } - - if (parseInt(lastFlag) < parseInt(flag)) { - - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG Z ]: ${card_number}` - ); - - let reservationNumberPendingSuccessLoaded = []; - let loadBalanceNumberPendingSuccessLoaded = []; - let totalReservationAmount = 0; - - getReservationPendingWithFlagCounter.forEach((element) => { - reservationNumberPendingSuccessLoaded.push( - element.c_reservation_no - ); - if (element.c_load_balance_no) { - loadBalanceNumberPendingSuccessLoaded.push( - element.c_load_balance_no - ); - } - totalReservationAmount += parseInt(element.i_reservation_amount); - }); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: updating reservation and load balance transaction...` - // ); - - // update - let insertUpdate = await updateAllTransaction( - reservationNumberPendingSuccessLoaded, - loadBalanceNumberPendingSuccessLoaded, - mid, - tid, - card_number, - balance, - flag, - uniqueCode, - totalReservationAmount, - uid - ); - - if (insertUpdate) { - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSINGE LOADING-BALANCE-REQUEST ]: updating flag to server...` - // ); - - // update flag from Server - await model.updateFlag( - now, - card_number, - uid.toUpperCase(), - balance, - flag - ); - - result = { - code: '01', - message: 'your card number has been cleared successfully', - data: { - load_balance_number: loadBalanceNumberPendingSuccessLoaded[0], - amount: parseInt(totalReservationAmount), - total_reservation: getReservationPendingWithFlagCounter.length, - reservation_number: reservationNumberPendingSuccessLoaded, - partial_topup: false, - }, - }; - } else { - result = { - code: '423', - message: 'updated failed', - data: {}, - }; - } - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - - if (getReservationPending.length < 1) { - return res.status(200).json(result); - } - } - } - } - - // log debug - // winston.logger.debug(`${uniqueCode} updating flag to server...`); - - // // update flag from Server - // await model.updateFlag(now, card_number, uid.toUpperCase(), balance, flag); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending...` - // ); - - // reget total reservation pending - getReservationPending = await model.getReservationPendingV2( - card_number, - now, - flag - ); - - if (getReservationPending.length < 1) { - result = { - code: '414', - message: "reservation doesn't exist", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST getReservationPending ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - let partialTopup = false; - let totalReservation = 0; - let amountTopup = 0; - let reservationNumber = []; - let reservationNumberTemp = []; - let i = 0; - getReservationPending.forEach((rsv) => { - amountTopup += parseInt(rsv.i_reservation_amount); - reservationNumber.push(rsv.c_reservation_no); - reservationNumberTemp.push(rsv.c_reservation_no); - i++; - }); - - totalReservation = i; - if (totalReservation == 0) { - result = { - code: '414', - message: "reservation doesn't exist", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST totalReservation ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking the card number in list fraud transaction or not...XXXXXXXXXXXXXXXXXXXX` - // ); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking total topup amount...` - // ); - - // check total amount topup - if (parseInt(amountTopup) <= 0) { - result = { - code: '415', - message: 'amount must be greater than 0', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking BI regulation status...` - // ); - - // get BI regulation status - let getBIRegulationStatus = await model.getBIRegulationStatus(); - - // check value global parameter - if (!getBIRegulationStatus) { - result = { - code: '439', - message: 'HSM_BI_REGULATION_STAT in global parameter not found', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - if (getBIRegulationStatus.c_value == 'A') { - // log debug - // winston.logger.debug(`${uniqueCode} checking topup partial status...`); - - // check topup partial status - let getTopupPartialStatus = await model.getTopupPartialStatus(); - - // check value global parameter - if (!getTopupPartialStatus) { - result = { - code: '439', - message: 'HSM_TOPUP_PARTIAL_STAT in global parameter not found', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max balance on the card...` - // ); - - // get max saldo on the card - let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); - - // check value global parameter - if (!getMaxAmountOnTheCard) { - result = { - code: '439', - message: - 'HSM_BI_MAX_AMOUNT_ON_THE_CARD in global parameter not found', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - if (getMaxAmountOnTheCard.c_value) { - if ( - parseInt(balance) + parseInt(amountTopup) > - parseInt(getMaxAmountOnTheCard.c_value) - ) { - // if topup partial is active - if (getTopupPartialStatus.c_value == 'A') { - // reset reservation data - partialTopup = true; - totalReservation = 0; - amountTopup = 0; - reservationNumber = []; - reservationNumberTemp = []; - i = 0; - - // sum amount can be topup - getReservationPending.forEach((rsv) => { - if ( - parseInt(balance) + parseInt(amountTopup) <= - parseInt(getMaxAmountOnTheCard.c_value) - ) { - amountTopup += parseInt(rsv.i_reservation_amount); - if ( - amountTopup > parseInt(getMaxAmountOnTheCard.c_value) || - parseInt(balance) + amountTopup > - parseInt(getMaxAmountOnTheCard.c_value) - ) { - amountTopup = - amountTopup - parseInt(rsv.i_reservation_amount); - i--; - } else { - reservationNumber.push(rsv.c_reservation_no); - reservationNumberTemp.push(rsv.c_reservation_no); - } - } - i++; - }); - - totalReservation = i; - if (totalReservation == 0) { - result = { - code: '414', - message: - "reservation doesn't exist. Lowest amount exceeds the maximum balance", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } else { - result = { - code: '416', - message: 'your card number has reached the maximum balance', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: 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 - let getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); - - // check value global parameter - if (!getMaxTopupPerMonth) { - result = { - code: '439', - message: 'HSM_BI_MAX_TOPUP_PER_MONTH in global parameter not found', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - if (getMaxTopupPerMonth.c_value) { - if ( - parseInt(accumulatedBalance) + parseInt(amountTopup) > - parseInt(getMaxTopupPerMonth.c_value) - ) { - // if topup partial is active - if (getTopupPartialStatus.c_value == 'A') { - // reset reservation data - partialTopup = true; - totalReservation = 0; - amountTopup = 0; - reservationNumber = []; - reservationNumberTemp = []; - i = 0; - - // sum amount can be topup - getReservationPending.forEach((rsv) => { - if ( - parseInt(balance) + parseInt(amountTopup) <= - parseInt(getMaxAmountOnTheCard.c_value) - ) { - amountTopup += parseInt(rsv.i_reservation_amount); - if ( - amountTopup > parseInt(getMaxAmountOnTheCard.c_value) || - parseInt(balance) + amountTopup > - parseInt(getMaxAmountOnTheCard.c_value) - ) { - amountTopup = - amountTopup - parseInt(rsv.i_reservation_amount); - i--; - } else { - reservationNumber.push(rsv.c_reservation_no); - reservationNumberTemp.push(rsv.c_reservation_no); - } - } - i++; - }); - - totalReservation = i; - if (totalReservation == 0) { - result = { - code: '417', - message: - "reservation doesn't exist. Lowest amount exceeds the limit top up for this month", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } else { - result = { - code: '417', - message: 'your card number has been limit top up for this month', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } - } - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: updating status reservation to in progress...${reservationNumberTemp}, ${now}, ${flag}` - // ); - - // update status to in progress - let updateStatusReservation = await model.updateStatusReservation( - reservationNumberTemp, - now, - flag - ); - - if (updateStatusReservation) { - result = { - code: '00', - message: 'reservation exists', - data: { - amount: parseInt(amountTopup), - total_reservation: totalReservation, - reservation_number: reservationNumber, - partial_topup: partialTopup, - }, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - } else { - result = { - code: '434', - message: '[434] Failed, please try again later', - data: { - amount: parseInt(amountTopup), - total_reservation: totalReservation, - reservation_number: reservationNumber, - partial_topup: partialTopup, - }, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( - result - )}` - ); - } - - return res.json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE LOADING-BALANCE-REQUEST ]: 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: {}, - }); - } -}; - -// ========================================================= LOADING BALANCE INSERT ========================================================== -// *Created By: Mohamad Ihsan* -// *Description:* -// proses insert data topup atau load balance ke sistem CMS - -const loadingBalanceInsert = async (req, param) => { - try { - // param - let mid = param.mid; - let tid = param.tid; - let card_number = param.card_number; - let amount = param.amount; - let reservation_number = param.reservation_number; - let ref_no = param.ref_no; - let write_status = param.write_status; - let uid = param.uid; - let balance = param.balance; - let flag = param.flag; - let unique_code = param.unique_code; - let execution_id = param.execution_id; - - let uniqueCode = unique_code ? unique_code : 9999999999999; - let result = {}; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST LOADING-BALANCE-INSERT ]: ${JSON.stringify( - param - )}` - ); - - // time - let now = moment().format('YYYY-MM-DD HH:mm:ss'); - - // log warn - winston.logger.warn(`${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 LOADING-BALANCE-INSERT ]: ${JSON.stringify( - result - )}` - ); - - return result; - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // log warn - // winston.logger.warn( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation status...` - // ); - - const statuses = await model.findReservationsWithLoadedBalance(reservation_number); - const statusByNumber = new Map(statuses.map((status) => [status.c_reservation_no, status])); - // Urutan input menentukan respons pertama, walaupun PostgreSQL mengurutkan hasilnya. - for (const number of reservation_number) { - const reservationStatus = statusByNumber.get(String(number)); - - // if reservation doesn't exist or has been canceled - if (!reservationStatus) { - result = { - code: '414', - message: "reservation doesn't exist", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( - result - )}` - ); - - return result; - } - - if (reservationStatus.loaded_id != null) { - result = { - code: '00', - message: - 'reservation has been successfully loaded on ' + - moment(reservationStatus.loaded_at).format('DD MMM YYYY HH:mm:ss'), - data: { load_balance_number: reservationStatus.loaded_number }, - }; - winston.logger.info( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify(result)}` - ); - return result; - } - } - - // log warn - // winston.logger.warn( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking last log history...` - // ); - - // get last history by card number - let lastHistory = await model.getLastHistory(card_number); - - if (lastHistory) { - // if last history card is topup (21 = log name id for topup) - if (lastHistory.i_log_name == 21 && lastHistory.c_source == 'CMS') { - // log warn - // winston.logger.warn( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting fraud transaction...` - // ); - - // insert reservation transaction to fraud table - await model.insertFraudTransaction(reservation_number); - - // log warn - // winston.logger.warn( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: suspending reservation...` - // ); - - // update reservation with suspend status - await model.suspendReservation(reservation_number, now); - - result = { - code: '432', - message: 'your card number has fraud transaction', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( - result - )}` - ); - - return result; - } - } - - // log warn - // winston.logger.warn( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking fraud transaction...` - // ); - - // get data fraud by card number and status fraud is not closed - let fraudTransaction = await model.getFraudTransaction(card_number); - let fraudReservationNumber = []; - - if (fraudTransaction.length > 0) { - fraudTransaction.forEach((rsv) => { - fraudReservationNumber.push(rsv.c_reservation_no); - }); - } - - // log warn - // winston.logger.warn( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation pending...` - // ); - - // get total reservation pending without fraud - let getReservationPending = await model.getReservationPendingWithoutFraud( - card_number, - flag, - fraudReservationNumber - ); - - if (getReservationPending.length < 1) { - result = { - code: '414', - message: "reservation doesn't exist", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( - result - )}` - ); - - return result; - } - - // log warn - // winston.logger.warn( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking total topup amount...` - // ); - - // check total topup and request topup - let amountTopup = 0; - getReservationPending.forEach((rsv) => { - amountTopup += parseInt(rsv.i_reservation_amount); - }); - - if (parseInt(amount) != parseInt(amountTopup)) { - result = { - code: '418', - message: 'topup amount is different', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( - result - )}` - ); - - return result; - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting reservation detail...` - // ); - - const detail = []; - reservation_number = getReservationPending.map((pending) => pending.c_reservation_no); - const reservations = await model.findReservationDetails(reservation_number); - const detailByNumber = new Map(reservations.map((reservation) => [reservation.c_reservation_no, reservation])); - for (const number of reservation_number) { - const reservation = detailByNumber.get(String(number)); - - if (!reservation) { - result = { - code: '414', - message: "reservation doesn't exist", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( - result - )}` - ); - - return result; - } - detail.push({ - i_reservation_balance: reservation.i_reservation_balance - ? reservation.i_reservation_balance - : null, - c_reservation_no: reservation.i_reservation_balance - ? reservation.c_reservation_no - : null, - i_amount: reservation.i_reservation_balance - ? reservation.i_reservation_amount - : null, - i_issuer: reservation.i_reservation_balance - ? reservation.i_issuer - : null, - i_issuer_code: reservation.i_reservation_balance - ? reservation.c_issuer_code - : null, - i_issuer_name: reservation.i_reservation_balance - ? reservation.c_issuer_name - : null, - i_issuer_fee: reservation.i_reservation_balance - ? reservation.i_issuer_fee - : null, - i_channel: reservation.i_reservation_balance - ? reservation.i_channel - : null, - i_channel_code: reservation.i_reservation_balance - ? reservation.c_channel_code - : null, - i_channel_name: reservation.i_reservation_balance - ? reservation.c_channel_name - : null, - i_channel_fee: reservation.i_reservation_balance - ? reservation.i_channel_fee - : null, - }); - } - - const { number: loadBalanceNumber, sequence: loadBalanceNoSequence } = - await model.allocateLoadBalanceNumber(getPartner.partner_code, moment(now).format('YYMMDD')); - - let data = { - c_load_balance_no: loadBalanceNumber, - d_load_balance: now, - c_ref_no: ref_no, - i_partner: getPartner ? getPartner.i_partner : null, - c_partner_code: getPartner ? getPartner.partner_code : null, - c_partner_name: getPartner ? getPartner.partner_name : null, - i_merchant: getPartner ? getPartner.i_merchant : null, - c_merchant_code: getPartner ? getPartner.merchant_code : null, - c_merchant_name: getPartner ? getPartner.merchant_name : null, - c_mid: getPartner ? getPartner.mid : null, - i_terminal: getPartner ? getPartner.i_terminal : null, - c_terminal_code: getPartner ? getPartner.terminal_code : null, - c_terminal_name: getPartner ? getPartner.terminal_name : null, - c_tid: getPartner ? getPartner.tid : null, - c_card_number: card_number, - i_execution_id: execution_id, - i_topup_amount: amount ? parseInt(amount) : amount, - m_balance: balance ? parseInt(balance) : balance, - c_return_sap: null, - i_load_balance_no_seq: loadBalanceNoSequence, - c_idm: uid, - c_status: write_status ? 'F' : 'P', - c_status_name: write_status ? 'FAILED' : 'PENDING', - d_create: now, - i_create: null, - c_create_username: null, - c_create_fullname: null, - d_modify: null, - i_modify: null, - c_modify_username: null, - c_modify_fullname: null, - d_delete: null, - i_delete: null, - c_delete_username: null, - c_delete_fullname: null, - }; - - // check data load balance by reservation_number exist or not - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking load balance transaction has been exists or not...` - // ); - - // log warn - // winston.logger.warn( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting load balance transaction...` - // ); - - // insert transaction - let insertLoadingBalance = await model.insertLoadingBalance( - data, - detail, - reservation_number, - now, - write_status, - card_number, - uid.toUpperCase(), - balance, - flag - ); - - // log warn - // winston.logger.warn( - // `${uniqueCode} [DATA] : ${JSON.stringify( - // data - // )} [DETAIL] : ${JSON.stringify(detail)} [RSV] : ${JSON.stringify( - // reservation_number - // )} [NOW] : ${JSON.stringify(now)} [WRITE STATUS] : ${JSON.stringify( - // write_status - // )} [CARD NUMBER] : ${JSON.stringify( - // card_number - // )} [UID] : ${JSON.stringify(uid)} [BALANCE] : ${JSON.stringify( - // balance - // )} [FLAG] : ${JSON.stringify(flag)}` - // ); - if (insertLoadingBalance > 0) { - result = { - code: '00', - message: write_status - ? 'transaction saved successfully. Err: failed write to the card' - : 'balance loaded successfully', - data: { - load_balance_number: loadBalanceNumber, - }, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( - result - )}` - ); - } else { - result = { - code: '433', - message: '[433] Failed, please try again later', - data: { - load_balance_number: loadBalanceNumber, - }, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( - result - )}` - ); - } - - return result; - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE LOADING-BALANCE-INSERT ]: 500 internal server error - backend server | ${error.message}` - ); - - return { - code: '500', - message: - process.env.NODE_ENV != 'production' - ? error.message - : '500 internal server error - backend server.', - data: {}, - }; - } -}; - -// ========================================================= LOADING BALANCE UPDATE ========================================================== -// *Created By: Mohamad Ihsan* -// *Description:* -// proses update data topup atau load balance ke sistem CMS - -const loadingBalanceUpdate = async (param) => { - try { - // param - let mid = param.mid; - let tid = param.tid; - let card_number = param.card_number; - let amount = param.amount; - let reservation_number = param.reservation_number; - let ref_no = param.ref_no; - let write_status = param.write_status; - let uid = param.uid; - let balance = param.balance; - let flag = param.flag; - let unique_code = param.unique_code; - let loadBalanceNumber = param.load_balance_number; - - let uniqueCode = unique_code ? unique_code : 9999999999999; - let result = {}; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST LOADING-BALANCE-UPDATE ]: ${JSON.stringify( - param - )}` - ); - - // time - let now = moment().format('YYYY-MM-DD HH:mm:ss'); - let today = moment().format('YYYY-MM-DD'); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: 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 LOADING-BALANCE-UPDATE ]: ${JSON.stringify( - result - )}` - ); - - return result; - } - - // if (getPartner.i_partner != req.partner_id_token) { - // result = { - // code: '412', - // message: 'partner is not match', - // data: {}, - // }; - - // return res.status(200).json(result); - // } - - let data = { - d_load_balance: now, - c_ref_no: ref_no, - m_balance: balance, - c_return_sap: null, - c_status: write_status ? 'F' : 'A', - c_status_name: write_status ? 'FAILED' : 'SUCCESS', - d_modify: now, - i_modify: null, - c_modify_username: null, - c_modify_fullname: null, - }; - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: updating load balance transaction...` - // ); - - // update transaction - await model.updateLoadingBalance( - data, - now, - write_status, - card_number, - uid.toUpperCase(), - balance, - flag, - loadBalanceNumber - ); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: inserting load balance transaction history ${loadBalanceNumber}...` - // ); - - let findDataLoadBalance = await model.findLoadBalance(loadBalanceNumber); - let dataLoadBalance = {}; - let detailLoadBalance = []; - - if (findDataLoadBalance) { - let findDataLoadBalanceDetail = await model.findLoadBalanceDetail( - findDataLoadBalance.i_load_balance - ); - - if (findDataLoadBalance) { - dataLoadBalance = { - c_load_balance_no: findDataLoadBalance.c_load_balance_no, - d_load_balance: now, - c_ref_no: findDataLoadBalance.c_ref_no, - i_partner: findDataLoadBalance.i_partner, - c_partner_code: findDataLoadBalance.c_partner_code, - c_partner_name: findDataLoadBalance.c_partner_name, - i_merchant: findDataLoadBalance.i_merchant, - c_merchant_code: findDataLoadBalance.c_merchant_code, - c_merchant_name: findDataLoadBalance.c_merchant_name, - c_mid: findDataLoadBalance.c_mid, - i_terminal: findDataLoadBalance.i_terminal, - c_terminal_code: findDataLoadBalance.c_terminal_code, - c_terminal_name: findDataLoadBalance.c_terminal_name, - c_tid: findDataLoadBalance.c_tid, - c_card_number: findDataLoadBalance.c_card_number, - i_topup_amount: findDataLoadBalance.i_topup_amount, - m_balance: findDataLoadBalance.m_balance, - c_return_sap: findDataLoadBalance.c_return_sap, - i_load_balance_no_seq: findDataLoadBalance.i_load_balance_no_seq, - c_idm: findDataLoadBalance.c_idm, - c_status: write_status ? 'F' : 'A', - c_status_name: write_status ? 'FAILED' : 'SUCCESS', - d_create: findDataLoadBalance.d_create, - i_create: findDataLoadBalance.i_create, - c_create_username: findDataLoadBalance.c_create_username, - c_create_fullname: findDataLoadBalance.c_create_fullname, - d_modify: now, - i_modify: findDataLoadBalance.i_modify, - c_modify_username: findDataLoadBalance.c_modify_username, - c_modify_fullname: findDataLoadBalance.c_modify_fullname, - d_delete: findDataLoadBalance.d_delete, - i_delete: findDataLoadBalance.i_delete, - c_delete_username: findDataLoadBalance.c_delete_username, - c_delete_fullname: findDataLoadBalance.c_delete_fullname, - }; - - let i = 0; - findDataLoadBalanceDetail.forEach((element) => { - detailLoadBalance[i] = { - i_reservation_balance: element.i_reservation_balance, - c_reservation_no: element.c_reservation_no, - i_amount: element.i_amount, - i_issuer: element.i_issuer, - i_issuer_code: element.c_issuer_code, - i_issuer_name: element.c_issuer_name, - i_issuer_fee: element.i_issuer_fee, - i_channel: element.i_channel, - i_channel_code: element.c_channel_code, - i_channel_name: element.c_channel_name, - i_channel_fee: element.i_channel_fee, - }; - i++; - }); - - // insert transaction - await model.insertLoadingBalanceHistoryOnly( - dataLoadBalance, - detailLoadBalance, - reservation_number, - now, - write_status, - card_number, - uid.toUpperCase(), - balance, - flag - ); - } - } - - if (!write_status) { - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: inserting log for card history...` - // ); - - // log card history - await model.createLoadBalanceLog({ - i_log_name: 21, - d_log: now, - c_card_number: card_number, - c_source: 'CMS', - c_location: getPartner ? getPartner.partner_name : null, - m_balance_before: parseInt(balance) > 0 ? parseInt(balance) : 0, - m_amount: parseInt(amount), - m_balance_after: parseInt(balance) + parseInt(amount), - j_new_data: { data: dataLoadBalance, detail: detailLoadBalance }, - j_old_data: null, - c_note: `LOAD BALANCE ${amount} FROM ${ - getPartner ? getPartner.partner_name : null - } SUCCESSFULLY`, - c_status: 'S', - d_created: now, - i_create: null, - c_create_username: 'HSM', - c_create_fullname: 'HARDWARE SECURE MODULE', - c_category: 'T', - }); - } - - result = { - code: '00', - message: write_status - ? 'transaction saved successfully. Err: failed write to the card' - : 'balance loaded successfully', - data: { - load_balance_number: loadBalanceNumber, - }, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE LOADING-BALANCE-UPDATE ]: ${JSON.stringify( - result - )}` - ); - - return result; - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE LOADING-BALANCE-UPDATE ]: 500 internal server error - backend server | ${error.message}` - ); - - return { - code: '500', - message: - process.env.NODE_ENV != 'production' - ? error.message - : '500 internal server error - backend server.', - data: {}, - }; - } -}; - module.exports = { validate, loadingBalanceRequest, diff --git a/application/modules/pos/card-balance.handlers.js b/application/modules/pos/card-balance.handlers.js new file mode 100644 index 0000000..70688fa --- /dev/null +++ b/application/modules/pos/card-balance.handlers.js @@ -0,0 +1,228 @@ +const helper = require('../../helpers/helper'); +const model = require('./pos.model'); +const winston = require('../../helpers/winston.logger'); +const { postWithDeadline } = require('./cts-client'); +const { validateBlacklist } = require('./card-validation.service'); + +// Pengecekan saldo lokal dan pengambilan saldo melalui CTS. +const checkLastBalance = async (req, res) => { + let result = {}; + let { card_number } = req.body; + let uniqueCode = helper.getUniqueCode(); + + //CHECK IS CARD BLACKLISTED + let cardBlacklist = await validateBlacklist(card_number, uniqueCode); + if (cardBlacklist) { + return res.status(200).json(cardBlacklist); + } + + let last_balance = 0; + let getLastBalanceFromCardHistory = await model.getLastBalanceFromCardHistory( + card_number + ); + if (getLastBalanceFromCardHistory) { + last_balance = getLastBalanceFromCardHistory.m_balance_after; + } + + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + detail: { + card_number: card_number, + last_balance: last_balance, + }, + }, + }; + return res.status(200).json(result); +}; + +const checkLastBalanceCTS = async (card_number, uniqueCode, req) => { + let token_api; + let result = {}; + + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ card_number ]: ${JSON.stringify(card_number)}` + ); + + let last_balance = 0; + let getLastBalanceFromCardHistory = await model.getLastBalanceFromCardHistory( + card_number + ); + + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ getLastBalanceFromCardHistory ]: ${JSON.stringify( + getLastBalanceFromCardHistory + )}` + ); + + if (getLastBalanceFromCardHistory) { + last_balance = getLastBalanceFromCardHistory.m_balance_after; + } + + let auth = req.header('Authorization'); + token_api = auth.replace('Bearer ', ''); + + const protocol = req.protocol; + const host = req.headers.host; + const current_url = protocol + '://' + host; + + let config = { + headers: { + 'Content-Type': 'application/json', + Authorization: 'Bearer ' + token_api, + }, + }; + const dataPost = { card_number: card_number }; + const url = current_url + `/api/pos/card-lastbalance`; + const resp = await postWithDeadline(url, dataPost, config); + + if ( + resp.data.data == undefined || + resp.data.data.detail.last_balance == undefined + ) { + result = { + code: '446', + message: 'Card number not exist in CTS to get last balance', + data: { + status: false, + detail: { + last_balance: last_balance, + }, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE GET LAST-BALANCE FROM CTS ]: ${JSON.stringify( + result + )}` + ); + return result; + } + + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + detail: { + last_balance: last_balance, + }, + }, + }; + + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE GET LAST-BALANCE FROM CTS ]: ${JSON.stringify( + result + )}` + ); + return result; +}; + +const getLastBalanceCTS = async (req, res) => { + let last_balance; + try { + let uniqueCode = helper.getUniqueCode(); + let result = {}; + // const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance' + const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`; + + winston.logger.info(`${uniqueCode} [ REQUEST GET LAST BALANCE CTS ]`); + + //CARD REPLACEMENT VALIDATION + const dataCard = await model.getCardReplacementScheduler(); + + for (const card of dataCard) { + const payload = { + card_number: card.c_card_no, + }; + + let config = { + headers: { + 'Content-Type': 'application/json', + }, + }; + const url = baseUrl; + const response = await postWithDeadline(url, payload, config); + if (response.data.code == undefined || response.data.code != 200) { + if (response.data.code == 404) { + result = { + code: '494', + message: 'No data found in CTS for the given card number', + data: { + status: false, + detail: {}, + }, + }; + winston.logger.info( + `${uniqueCode} [ FAILED HIT - card_number : ${card.c_card_no} ]: ${response.data.message}` + ); + return res.status(200).json(result); + } + result = { + code: '500', + message: 'CTS service not avaliable', + data: { + status: false, + detail: {}, + }, + }; + winston.logger.info( + `${uniqueCode} [ FAILED HIT - card_number : ${card.c_card_no} ]: ${response.data.message}` + ); + return res.status(200).json(result); + } + last_balance = response.data.data.balance_after; + let dataReplacementUpdate = { + i_last_balance: last_balance, + }; + // update card_replacement + await model.updateReplacementByCardNumber( + card.c_card_no, + dataReplacementUpdate + ); + // log debug + winston.logger.info( + `${uniqueCode} [ GET LAST BALANCE CTS ${card.c_card_no} ]: ${last_balance}` + ); + } + + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE GET LAST BALANCE CTS ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE GET LAST BALANCE CTS ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +module.exports = { checkLastBalance, getLastBalanceCTS }; diff --git a/application/modules/pos/card-redeem.handlers.js b/application/modules/pos/card-redeem.handlers.js new file mode 100644 index 0000000..a3b340a --- /dev/null +++ b/application/modules/pos/card-redeem.handlers.js @@ -0,0 +1,551 @@ +const helper = require('../../helpers/helper'); +const winston = require('../../helpers/winston.logger'); +const { validationResult } = require('express-validator'); +const moment = require('moment'); +const { postWithDeadline } = require('./cts-client'); +const model = require('./pos.model'); +const { + validateEnvironment, + validateBlacklist, + validateCardProduct, + checkCardReplacement, +} = require('./card-validation.service'); + +// Validasi dan konfirmasi redeem untuk kartu yang memenuhi syarat. +const validateRedeem = async (req, res) => { + let dataCard; + try { + let uniqueCode = helper.getUniqueCode(); + let result = {}; + let last_balance = null; + let dataCardReplacement = {}; + let { card_number, station_code } = req.body; + + winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-REDEEM ]`); + + //CHECK VALIDATOR + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + //TRIM CARD NUMBER + card_number = card_number.trim(); + + //CHECK IS CARD ALLOW + const validEnv = await validateEnvironment(card_number, uniqueCode); + if (validEnv) { + res.status(200).json(validEnv); + } + + //CHECK IS CARD BLACKLISTED + let cardBlacklist = await validateBlacklist(card_number, uniqueCode); + if (cardBlacklist) { + return res.status(200).json(cardBlacklist); + } + + //CARD PRODUCT VALIDATION + const validCardProduct = await validateCardProduct(card_number, uniqueCode); + if (validCardProduct) { + dataCard = validCardProduct.data; + //CARD NOT REGISTERED IN CARD_PRODUCT + if (dataCard.status == false) { + return res.status(200).json(validCardProduct); + } + + dataCard = dataCard.detail; + const card_status = dataCard.c_status; + + // Status valid => Active (A) + if (card_status != 'A') { + if (card_status == 'R') { + result = { + code: '451', + message: 'Card is redeemed or replaced.', + data: { + status: false, + detail: {}, + }, + }; + } else if (card_status == 'B') { + result = { + code: '445', + message: 'Card is blacklisted.', + data: { + status: false, + detail: {}, + }, + }; + } else if (card_status == 'N') { + result = { + code: '463', + message: 'Card is not activated.', + data: { + status: false, + detail: {}, + }, + }; + } else if (card_status == 'P') { + result = { + code: '458', + message: 'Card is persoed and not yet active.', + data: { + status: false, + detail: {}, + }, + }; + } + + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-REDEEM ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + } + + //CARD REPLACEMENT VALIDATION + const validCardReplacement = await checkCardReplacement( + card_number, + uniqueCode + ); + if (validCardReplacement) { + dataCardReplacement = validCardReplacement.data; + //CARD NOT REGISTERED IN CARD_REPLACEMENT + if (dataCardReplacement.status == false) { + return res.status(200).json(validCardReplacement); + } + dataCardReplacement = dataCardReplacement.detail; + + let replacement_redeem_category = + dataCardReplacement.c_replace_redeem_category_code.trim(); + //replacement_redeem_category: R - REDEEM | w - REPLACEMENT WARRANTY | N - REPLACEMENT NON-WARRANTY + if (replacement_redeem_category != 'R') { + result = { + code: '491', + message: 'Card not registered as redeem.', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REDEEM-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + let replacement_station_code = + dataCardReplacement.c_org_dept_station_code.trim(); + if (replacement_station_code != station_code) { + result = { + code: '411', + message: 'Station code not match.', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REDEEM-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + let replacement_status = dataCardReplacement.c_status.trim(); + //replacement_status: N - NEW | X - CANCELLED | A - COMPLETED + if (replacement_status != 'N') { + if (replacement_status == 'X') { + result = { + code: '406', + message: 'Replacement or redeem Card Status is cancelled.', + data: { + status: false, + detail: {}, + }, + }; + } else if (replacement_status == 'A') { + result = { + code: '407', + message: 'Card has been replaced or redeemed.', + data: { + status: false, + detail: {}, + }, + }; + } else { + result = { + code: '408', + message: 'Redeem or replacement card status not defined.', + data: { + status: false, + detail: {}, + }, + }; + } + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-REDEEM ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + //Cek tanggal d_valid_date + + //Update Data Replacement + let date_request = dataCardReplacement.d_request; + let date_valid = dataCardReplacement.d_valid_date; + + let now = moment().format('YYYY-MM-DD'); + date_valid = moment(date_valid).format('YYYY-MM-DD'); + date_request = moment(date_request).format('YYYY-MM-DD'); + + if (now < date_valid) { + //other status + result = { + code: '456', + message: 'The valid replacement date is insufficient.', + data: { + status: false, + detail: { + date_now: now, + date_request: date_request, + date_valid: date_valid, + }, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + } + + last_balance = dataCardReplacement.i_last_balance; + if (last_balance == null) { + let result = {}; + // const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance' + const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`; + const payload = { + card_number: card_number, + }; + let config = { + headers: { + 'Content-Type': 'application/json', + }, + }; + const url = baseUrl; + const response = await postWithDeadline(url, payload, config); + if (response.data.code == undefined || response.data.code != 200) { + if (response.data.code == 404) { + result = { + code: '494', + message: 'No data found in CTS for the given card number', + data: { + status: false, + detail: {}, + }, + }; + winston.logger.info( + `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}` + ); + return res.status(200).json(result); + } + result = { + code: '415', + message: 'Last Balance not updated.', + data: { + status: false, + detail: {}, + }, + }; + winston.logger.info( + `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}` + ); + return res.status(200).json(result); + } + + last_balance = response.data.data.balance_after; + } + + let security_code = await helper.createHMAC(card_number); + + //CARD VALID TO REDEEM + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + detail: { + security_code: security_code, + last_balance: last_balance, + card_number: card_number, + unique_code: uniqueCode, + }, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-REDEEM ]: ${JSON.stringify(result)}` + ); + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE VALIDATE-REDEEM ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +const confirmRedeem = async (req, res) => { + try { + let uniqueCode = helper.getUniqueCode(); + let result = {}; + let { card_number, security_code } = req.body; + let dataCardRedeem = {}; + + winston.logger.info(`${uniqueCode} [ REQUEST REDEEM-CONFIRM ]`); + + //CHECK VALIDATOR + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + //CHECK SECURITY-CODE + if (security_code) { + let securityCodeCompare = await helper.createHMAC(card_number); + + if (security_code !== securityCodeCompare) { + result = { + code: '437', + message: 'bad request. security code does not match.', + data: {}, + }; + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE REDEEM-CONFIRM ]: ${JSON.stringify(result)}` + ); + return res.status(200).json(result); + } + } + + //TRIM CARD NUMBER + card_number = card_number.trim(); + + //CHECK IS CARD ALLOW + const validEnv = await validateEnvironment(card_number, uniqueCode); + if (validEnv) { + // log warn + winston.logger.warn( + `${uniqueCode} [ VALIDATE ENV CARD NUMBER ]: ${JSON.stringify( + validEnv + )}` + ); + res.status(200).json(validEnv); + } + + //CHECK IS CARD BLACKLISTED + let cardBlacklist = await validateBlacklist(card_number, uniqueCode); + if (cardBlacklist) { + // log warn + winston.logger.warn( + `${uniqueCode} [ VALIDATE BLACKLIST CARD NUMBER ]: ${JSON.stringify( + cardBlacklist + )}` + ); + return res.status(200).json(cardBlacklist); + } + + //CARD REPLACEMENT VALIDATION + const validCardReplacement = await checkCardReplacement( + card_number, + uniqueCode + ); + if (validCardReplacement) { + dataCardRedeem = validCardReplacement.data; + //CARD NOT REGISTERED IN CARD_REPLACEMENT + if (dataCardRedeem.status == false) { + return res.status(200).json(validCardReplacement); + } + dataCardRedeem = dataCardRedeem.detail; + + let replacement_redeem_category = + dataCardRedeem.c_replace_redeem_category_code.trim(); + //replacement_redeem_category: R - REDEEM | w - REPLACEMENT WARRANTY | N - REPLACEMENT NON-WARRANTY + if (replacement_redeem_category != 'R') { + result = { + code: '491', + message: 'Card not registered as redeem.', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REDEEM-CONFIRM ]: ${JSON.stringify(result)}` + ); + return res.status(200).json(result); + } + + let redeem_status = dataCardRedeem.c_status.trim(); + //redeem_status: N - NEW | X - CANCELLED | A - COMPLETED + if (redeem_status != 'N') { + if (redeem_status == 'X') { + result = { + code: '406', + message: 'Card replacement status is cancelled.', + data: { + status: false, + detail: {}, + }, + }; + } else if (redeem_status == 'A') { + result = { + code: '407', + message: 'Card has been replaced or redeemed.', + data: { + status: false, + detail: {}, + }, + }; + } else { + result = { + code: '408', + message: 'Redeem or replacement card status not defined.', + data: { + status: false, + detail: {}, + }, + }; + } + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REDEEM-CONFIRM ]: ${JSON.stringify(result)}` + ); + return res.status(200).json(result); + } + } + + //Cek tanggal d_valid_date + //Update Data Replacement + let date_request = dataCardRedeem.d_request; + let date_valid = dataCardRedeem.d_valid_date; + + let now = moment().format('YYYY-MM-DD'); + date_valid = moment(date_valid).format('YYYY-MM-DD'); + date_request = moment(date_request).format('YYYY-MM-DD'); + + if (now < date_valid) { + //other status + result = { + code: '456', + message: 'The valid replacement date is insufficient.', + data: { + status: false, + detail: { + date_now: now, + date_request: date_request, + date_valid: date_valid, + }, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REDEEM-CONFIRM ]: ${JSON.stringify(result)}` + ); + return res.status(200).json(result); + } + + let i_card_replacement = dataCardRedeem.i_card_replacement; + let dataReplacementUpdate = { + c_status: 'A', + c_status_name: 'COMPLETED', + }; + //Update Data Card Card Replacement + await model.updateReplacement(i_card_replacement, dataReplacementUpdate); + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ UPDATE DATA REDEEM ]: ${JSON.stringify( + dataReplacementUpdate + )}` + ); + + //CARD VALID TO REPLACEMENT + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + detail: { + card_number: card_number, + }, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE REPLACEMENT-CONFIRM ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +module.exports = { validateRedeem, confirmRedeem }; diff --git a/application/modules/pos/card-replacement.handlers.js b/application/modules/pos/card-replacement.handlers.js new file mode 100644 index 0000000..04f4b9c --- /dev/null +++ b/application/modules/pos/card-replacement.handlers.js @@ -0,0 +1,972 @@ +const helper = require('../../helpers/helper'); +const winston = require('../../helpers/winston.logger'); +const { validationResult } = require('express-validator'); +const moment = require('moment'); +const { postWithDeadline } = require('./cts-client'); +const model = require('./pos.model'); +const { + validateEnvironment, + validateBlacklist, + validateCardProduct, + checkCardReplacement, +} = require('./card-validation.service'); + +// Validasi kartu lama dan baru sebelum konfirmasi penggantian. +const validateReplacement = async (req, res) => { + let dataCard; + try { + let uniqueCode = helper.getUniqueCode(); + let result = {}; + let { card_number, station_code } = req.body; + let dataCardReplacement = {}; + let last_balance = null; + let is_warranty = false; + + winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-REPLACEMENT ]`); + + //CHECK VALIDATOR + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + //TRIM CARD NUMBER + card_number = card_number.trim(); + + //CHECK IS CARD ALLOW + const validEnv = await validateEnvironment(card_number, uniqueCode); + if (validEnv) { + return res.status(200).json(validEnv); + } + + //CHECK IS CARD BLACKLISTED + let cardBlacklist = await validateBlacklist(card_number, uniqueCode); + if (cardBlacklist) { + return res.status(200).json(cardBlacklist); + } + + //CARD PRODUCT VALIDATION + const validCardProduct = await validateCardProduct(card_number, uniqueCode); + if (validCardProduct) { + dataCard = validCardProduct.data; + //CARD NOT REGISTERED IN CARD_PRODUCT + if (dataCard.status == false) { + return res.status(200).json(validCardProduct); + } + + dataCard = dataCard.detail; + const card_status = dataCard.c_status; + + // Status valid => Active (A) + if (card_status != 'A') { + if (card_status == 'R') { + result = { + code: '451', + message: 'Card is redeemed or replaced.', + data: { + status: false, + detail: {}, + }, + }; + } else if (card_status == 'B') { + result = { + code: '445', + message: 'Card is blacklisted.', + data: { + status: false, + detail: {}, + }, + }; + } else if (card_status == 'N') { + result = { + code: '463', + message: 'Card is not activated.', + data: { + status: false, + detail: {}, + }, + }; + } else if (card_status == 'P') { + result = { + code: '458', + message: 'Card is persoed and not yet active.', + data: { + status: false, + detail: {}, + }, + }; + } + + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-REPLACEMENT ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + } + + //CARD REPLACEMENT VALIDATION + const validCardReplacement = await checkCardReplacement( + card_number, + uniqueCode + ); + if (validCardReplacement) { + dataCardReplacement = validCardReplacement.data; + //CARD NOT REGISTERED IN CARD_REPLACEMENT + if (dataCardReplacement.status == false) { + return res.status(200).json(validCardReplacement); + } + dataCardReplacement = dataCardReplacement.detail; + + let category_replacement = + dataCardReplacement.c_replace_redeem_category_code; + //replacement_redeem_category: R - REDEEM | w - REPLACEMENT WARRANTY | N - REPLACEMENT NON-WARRANTY + if (category_replacement == 'R') { + result = { + code: '492', + message: 'Card not registered as replacement.', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REPLACEMENT-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + //is warranty + if (category_replacement == 'W') { + is_warranty = true; + } + + let replacement_station_code = + dataCardReplacement.c_org_dept_station_code.trim(); + if (replacement_station_code != station_code) { + result = { + code: '411', + message: 'Station code not match.', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REPLACEMENT-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + let replacement_status = dataCardReplacement.c_status.trim(); + //replacement_status: N - NEW | X - CANCELLED | A - COMPLETED + if (replacement_status != 'N') { + if (replacement_status == 'X') { + result = { + code: '406', + message: 'Replacement or redeem Card Status is cancelled.', + data: { + status: false, + detail: {}, + }, + }; + } else if (replacement_status == 'A') { + result = { + code: '407', + message: 'Card has been replaced or redeemed.', + data: { + status: false, + detail: {}, + }, + }; + } else { + result = { + code: '408', + message: 'Redeem or replacement card status not defined.', + data: { + status: false, + detail: {}, + }, + }; + } + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-REPLACEMENT ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + //Cek tanggal d_valid_date + + let date_request = dataCardReplacement.d_request; + let date_valid = dataCardReplacement.d_valid_date; + + let now = moment().format('YYYY-MM-DD'); + date_valid = moment(date_valid).format('YYYY-MM-DD'); + date_request = moment(date_request).format('YYYY-MM-DD'); + + if (now < date_valid) { + //other status + result = { + code: '456', + message: 'The valid replacement date is insufficient.', + data: { + status: false, + detail: { + date_now: now, + date_request: date_request, + date_valid: date_valid, + }, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + } + + last_balance = dataCardReplacement.i_last_balance; + if (last_balance == null) { + // if (is_warranty == true) { + // let result = {}; + // const baseUrl = 'http://127.0.0.1:3000'; + // const payload = { + // card_number: card_number, + // }; + // const response = await axios.post(baseUrl + '/api/pos/test', payload); + // if ( + // !response.data.code == undefined || + // response.data.data.status == false + // ) { + // result = { + // code: '415', + // message: 'Last Balance not updated.', + // data: { + // status: false, + // detail: {}, + // }, + // }; + // winston.logger.info( + // `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}` + // ); + // return res.status(200).json(result); + // } + // last_balance = response.data.data.detail.last_balance; + // let dataReplacementUpdate = { + // i_last_balance: last_balance, + // }; + // // update card_replacement + // await model.updateReplacementByCardNumber( + // card_number, + // dataReplacementUpdate + // ); + // // log debug + // winston.logger.info( + // `${uniqueCode} [ GET LAST BALANCE CTS ${card_number} ]: ${last_balance}` + // ); + // } else { + // result = { + // code: '415', + // message: 'Last Balance not updated.', + // data: { + // status: false, + // detail: {}, + // }, + // }; + // //LOG-INFO + // winston.logger.info( + // `${uniqueCode} [ RESPONSE VALIDATE-REPLACEMENT ]: ${JSON.stringify( + // result + // )}` + // ); + // return res.status(200).json(result); + + // if (is_warranty == true) { + let result = {}; + // const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance' + const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`; + const payload = { + card_number: card_number, + }; + let config = { + headers: { + 'Content-Type': 'application/json', + }, + }; + const url = baseUrl; + const response = await postWithDeadline(url, payload, config); + if (response.data.code == undefined || response.data.code != 200) { + if (response.data.code == 404) { + result = { + code: '494', + message: 'No data found in CTS for the given card number', + data: { + status: false, + detail: {}, + }, + }; + winston.logger.info( + `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}` + ); + return res.status(200).json(result); + } + result = { + code: '415', + message: 'Last Balance not updated.', + data: { + status: false, + detail: {}, + }, + }; + winston.logger.info( + `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}` + ); + return res.status(200).json(result); + } + last_balance = response.data.data.balance_after; + let dataReplacementUpdate = { + i_last_balance: last_balance, + }; + // update card_replacement + await model.updateReplacementByCardNumber( + card_number, + dataReplacementUpdate + ); + // log debug + winston.logger.info( + `${uniqueCode} [ GET LAST BALANCE CTS ${card_number} ]: ${last_balance}` + ); + // } + } + + // ==================== Contoh service Scheduller get last balance from CTS ==================== + // if (last_balance == null) { + // //CHECK CARD LAST_BALANCE + // const dataLastBalance = await checkLastBalanceCTS(card_number, uniqueCode, req); + // if (!dataLastBalance.data.status || dataLastBalance.data.status == false) { + // return res.status(200).json(dataLastBalance); + // } + // last_balance = dataLastBalance.data.detail.last_balance; + + // let dataReplacementUpdate = { + // i_last_balance: last_balance + // }; + // // update card_replacement + // await model.updateReplacement(dataCardReplacement.i_card_replacement, dataReplacementUpdate); + + // // log debug + // winston.logger.debug( + // `${uniqueCode} [ UPDATE LAST BALANCE CARD ${card_number} ]: ${last_balance}` + // ); + + // } + + // create security code + let security_code = await helper.createHMAC( + card_number + '|' + last_balance + ); + + //CARD VALID TO REPLACEMENT + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + detail: { + security_code: security_code, + last_balance: last_balance, + is_warranty: is_warranty, + unique_code: uniqueCode, + card_category: { + id: dataCardReplacement.card_category_id, + code: dataCardReplacement.card_category_code, + name: dataCardReplacement.card_category_name + } + }, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-REPLACEMENT ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE VALIDATE-REPLACEMENT ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +const validateNewCardReplacement = async (req, res) => { + let dataCardNew; + try { + let uniqueCode = helper.getUniqueCode(); + let result = {}; + let { card_number } = req.body; + + winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]`); + + //CHECK VALIDATOR + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + //TRIM CARD NUMBER + card_number = card_number.trim(); + + //CHECK IS CARD ALLOW + const validEnv = await validateEnvironment(card_number, uniqueCode); + if (validEnv) { + return res.status(200).json(validEnv); + } + + //CHECK IS CARD BLACKLISTED + let cardBlacklist = await validateBlacklist(card_number, uniqueCode); + if (cardBlacklist) { + result = { + code: '457', + message: 'New card is blacklisted.', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + //CARD REPLACEMENT VALIDATION + const validCardReplacement = await checkCardReplacement( + card_number, + uniqueCode + ); + //CARD REGISTERED IN CARD_REPLACEMENT + if (validCardReplacement.data.status == true) { + result = { + code: '461', + message: + 'New card number exists in the card replacement data and cannot be used for card replacement.', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + const validCardProductNew = await validateCardProduct( + card_number, + uniqueCode + ); + if (validCardProductNew) { + dataCardNew = validCardProductNew.data; + //CARD NOT REGISTERED IN CARD_PRODUCT + if (dataCardNew.status == false) { + return res.status(200).json(validCardProductNew); + } + + dataCardNew = dataCardNew.detail; + const card_new_status = dataCardNew.c_status; + // Status valid => Active (A) + + if (card_new_status != 'P') { + if (card_new_status == 'A') { + result = { + code: '453', + message: 'New card is already activated.', + data: { + status: false, + perso_status: true, + detail: {}, + }, + }; + return res.status(200).json(result); + } else if (card_new_status == 'R') { + result = { + code: '454', + message: 'New card is redeemed or replaced.', + data: { + status: false, + perso_status: true, + detail: {}, + }, + }; + return res.status(200).json(result); + } else if (card_new_status == 'B') { + result = { + code: '457', + message: 'New card is blacklisted.', + data: { + status: false, + perso_status: true, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + //other status + result = { + code: '455', + message: 'New Card not valid for replacement.', + data: { + status: false, + perso_status: true, + detail: {}, + }, + }; + return res.status(200).json(result); + } + } + + //CARD VALID TO REPLACEMENT + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +const replacementConfirm = async (req, res) => { + let dataCardNew; + try { + // let uniqueCode = helper.getUniqueCode(); + let result = {}; + let { + card_number, + new_card_number, + last_balance, + security_code, + unique_code, + } = req.body; + let uniqueCode = unique_code; + let dataCardReplacement = {}; + + winston.logger.info(`${uniqueCode} [ REQUEST REPLACEMENT-CONFIRM ]`); + + //CHECK VALIDATOR + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + if (card_number == new_card_number) { + result = { + code: '493', + message: 'bad request. new card number cannot be same.', + data: {}, + }; + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + //CHECK SECURITY-CODE + if (security_code) { + let securityCodeCompare = await helper.createHMAC( + card_number + '|' + last_balance + ); + + if (security_code !== securityCodeCompare) { + result = { + code: '437', + message: 'bad request. security code does not match.', + data: {}, + }; + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + } + + //TRIM CARD NUMBER + card_number = card_number.trim(); + new_card_number = new_card_number.trim(); + + //CHECK IS CARD ALLOW + const validEnv = await validateEnvironment(card_number, uniqueCode); + if (validEnv) { + // log warn + winston.logger.warn( + `${uniqueCode} [ VALIDATE ENV OLD CARD NUMBER ]: ${JSON.stringify( + validEnv + )}` + ); + return res.status(200).json(validEnv); + } + + //CHECK IS CARD ALLOW + const validEnvNew = await validateEnvironment(new_card_number, uniqueCode); + if (validEnvNew) { + // log warn + winston.logger.warn( + `${uniqueCode} [ VALIDATE ENV NEW CARD NUMBER ]: ${JSON.stringify( + validEnvNew + )}` + ); + return res.status(200).json(validEnv); + } + + //CHECK IS CARD BLACKLISTED + let cardBlacklist = await validateBlacklist(card_number, uniqueCode); + if (cardBlacklist) { + // log warn + winston.logger.warn( + `${uniqueCode} [ VALIDATE BLACKLIST OLD CARD NUMBER ]: ${JSON.stringify( + cardBlacklist + )}` + ); + return res.status(200).json(cardBlacklist); + } + let cardBlacklistNew = await validateBlacklist(new_card_number, uniqueCode); + if (cardBlacklistNew) { + cardBlacklistNew.message = 'New Card is blacklisted.'; + // log warn + winston.logger.warn( + `${uniqueCode} [ VALIDATE BLACKLIST NEW CARD NUMBER ]: ${JSON.stringify( + cardBlacklistNew + )}` + ); + return res.status(200).json(cardBlacklistNew); + } + + //CARD REPLACEMENT VALIDATION + const validCardReplacement = await checkCardReplacement( + card_number, + uniqueCode + ); + if (validCardReplacement) { + dataCardReplacement = validCardReplacement.data; + //CARD NOT REGISTERED IN CARD_REPLACEMENT + if (dataCardReplacement.status == false) { + return res.status(200).json(validCardReplacement); + } + dataCardReplacement = dataCardReplacement.detail; + + let replacement_status = dataCardReplacement.c_status.trim(); + //replacement_status: N - NEW | X - CANCELLED | A - COMPLETED + if (replacement_status != 'N') { + if (replacement_status == 'X') { + result = { + code: '406', + message: 'Replacement or redeem Card Status is cancelled.', + data: { + status: false, + detail: {}, + }, + }; + } else if (replacement_status == 'A') { + result = { + code: '458', + message: 'Card has been replaced.', + data: { + status: false, + detail: {}, + }, + }; + } else { + result = { + code: '408', + message: 'Redeem or replacement card status not defined.', + data: { + status: false, + detail: {}, + }, + }; + } + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + } + + //CHECK NEW CARD + const newCardReplacement = await checkCardReplacement( + new_card_number, + uniqueCode + ); + if (newCardReplacement.data.status == true) { + result = { + code: '461', + message: + 'New card number exists in the card replacement data and cannot be used for card replacement.', + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + //CHECK NEW CARD + const validCardProductNew = await validateCardProduct( + new_card_number, + uniqueCode + ); + if (validCardProductNew) { + dataCardNew = validCardProductNew.data; + //CARD NOT REGISTERED IN CARD_PRODUCT + if (dataCardNew.status == false) { + return res.status(200).json(validCardProductNew); + } + + dataCardNew = dataCardNew.detail; + const card_new_status = dataCardNew.c_status; + // Status valid => Active (A) + + if (card_new_status != 'P') { + if (card_new_status == 'A') { + result = { + code: '453', + message: 'New card is already activated.', + data: { + status: false, + perso_status: true, + detail: {}, + }, + }; + return res.status(200).json(result); + } else if (card_new_status == 'R') { + result = { + code: '454', + message: 'New card is redeemed or replaced.', + data: { + status: false, + perso_status: true, + detail: {}, + }, + }; + return res.status(200).json(result); + } else if (card_new_status == 'B') { + result = { + code: '457', + message: 'New card is blacklisted.', + data: { + status: false, + perso_status: true, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + //other status + result = { + code: '455', + message: 'New Card not valid for replacement.', + data: { + status: false, + perso_status: true, + detail: {}, + }, + }; + return res.status(200).json(result); + } + } + + //Cek tanggal d_valid_date + + //Update Data Replacement + let date_request = dataCardReplacement.d_request; + let date_valid = dataCardReplacement.d_valid_date; + + let now = moment().format('YYYY-MM-DD'); + date_valid = moment(date_valid).format('YYYY-MM-DD'); + date_request = moment(date_request).format('YYYY-MM-DD'); + + if (now < date_valid) { + //other status + result = { + code: '456', + message: 'The valid replacement date is insufficient.', + data: { + status: false, + detail: { + date_now: now, + date_request: date_request, + date_valid: date_valid, + }, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + let i_card_replacement = dataCardReplacement.i_card_replacement; + let dataReplacementUpdate = { + c_status: 'A', + c_status_name: 'COMPLETED', + c_replace_card_no: new_card_number, + }; + //Update Data Card Card Replacement + await model.updateReplacement(i_card_replacement, dataReplacementUpdate); + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ UPDATE DATA REPLACEMENT ]: ${JSON.stringify( + dataReplacementUpdate + )}` + ); + + //Insert Data Detail Replacement + let dataDetailReplacement = { + i_card_replacement: i_card_replacement, + c_old_card_no: card_number, + c_new_card_no: new_card_number, + i_amount: last_balance, + unique_code: uniqueCode, + }; + await model.insertReplacementDetail(dataDetailReplacement); + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ INSERT DATA REPLACEMENT DETAIL ]: ${JSON.stringify( + dataReplacementUpdate + )}` + ); + + //CARD VALID TO REPLACEMENT + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + detail: { + old_card_number: card_number, + new_card_number: new_card_number, + balance: last_balance, + }, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE REPLACEMENT-CONFIRM ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +module.exports = { validateReplacement, validateNewCardReplacement, replacementConfirm }; diff --git a/application/modules/pos/card-sales.handlers.js b/application/modules/pos/card-sales.handlers.js new file mode 100644 index 0000000..537688d --- /dev/null +++ b/application/modules/pos/card-sales.handlers.js @@ -0,0 +1,443 @@ +const helper = require('../../helpers/helper'); +const winston = require('../../helpers/winston.logger'); +const { validationResult } = require('express-validator'); +const model = require('./pos.model'); +const { + validateEnvironment, + validateBlacklist, + validateCardProduct, + checkCardSales, +} = require('./card-validation.service'); + +// Validasi dan konfirmasi penjualan, termasuk pelengkapan data sales internal. +const validateSales = async (req, res) => { + try { + let uniqueCode = helper.getUniqueCode(); + let dataCard = {}; + let result = {}; + let detail_card = {}; + let card_product = false; + + let { card_number } = req.body; + winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-SALES ]`); + + // CHECK VALIDATOR + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + // TRIM CARD NUMBER + card_number = card_number.trim(); + + //CHECK IS CARD ALLOW + const validEnv = await validateEnvironment(card_number, uniqueCode); + if (validEnv) { + return res.status(200).json(validEnv); + } + + //CHECK IS CARD BLACKLISTED + let cardBlacklist = await validateBlacklist(card_number, uniqueCode); + if (cardBlacklist) { + return res.status(200).json(cardBlacklist); + } + + //CARD PRODUCT VALIDATION + const validCardProduct = await validateCardProduct(card_number, uniqueCode); + + if (validCardProduct) { + //CARD NOT REGISTERED IN CARD_PRODUCT + if (validCardProduct.data.status == false) { + return res.status(200).json(validCardProduct); + } + + card_product = true; + dataCard = validCardProduct.data.detail; + //A: ACTIVED | N: GENERATED | P: PERSOED | B: BLACKLISTED | R: REDEEMED -> harus N/Generated + const card_status = dataCard.c_status; + detail_card = { + card_number: dataCard.c_card_number, + card_theme: dataCard.i_card_theme, + card_theme_code: dataCard.c_card_theme_code, + card_theme_name: dataCard.c_card_theme_name, + card_theme_card_digit_key: dataCard.c_card_theme_card_digit_key, + card_type: dataCard.i_card_type, + card_type_code: dataCard.c_card_type_code, + card_type_name: dataCard.c_card_type_name, + variant: dataCard.i_variant, + variant_code: dataCard.c_variant_code, + variant_name: dataCard.c_variant_name, + status: dataCard.c_status, + status_name: dataCard.c_status_name, + }; + + if (card_status != 'N' && card_status != 'P') { + if (card_status == 'A') { + result = { + code: '450', + message: 'Card is already activated.', + data: { + status: false, + perso_status: true, + detail: detail_card, + }, + }; + return res.status(200).json(result); + } else if (card_status == 'R') { + result = { + code: '451', + message: 'Card is redeemed.', + data: { + status: false, + perso_status: true, + detail: detail_card, + }, + }; + return res.status(200).json(result); + } else if (card_status == 'B') { + result = { + code: '445', + message: 'Card is blacklisted.', + data: { + status: false, + perso_status: true, + detail: detail_card, + }, + }; + return res.status(200).json(result); + } + + //other status + result = { + code: '462', + message: 'Card not valid to sales.', + data: { + status: false, + perso_status: true, + detail: detail_card, + }, + }; + return res.status(200).json(result); + } + } + + //CARD SALES VALIDATION + const validCardSales = await checkCardSales(card_number, uniqueCode); + if (validCardSales) { + let dataCardSales = validCardSales.data; + if (dataCardSales.status == false) { + return res.status(200).json(validCardSales); + } + // let detailCardSales = dataCardSales.detail; + + // if (detailCardSales.sales_status != 'SUCCESS') { + // //Update Data Sales Temp + // let updateDataSales = { + // sales_status: sales_status, + // device_code: device_code, + // station_code: station_code, + // station_name: station_name, + // created_by: created_by, + // device_time: device_time + // } + // // update card_sales + // await model.updateSales(detailCardSales.i_sales_kmt_temp, updateDataSales); + // // log debug + // winston.logger.debug( + // `${uniqueCode} [ UPDATE SALES ${card_number} ]: ${updateDataSales}` + // ); + + // result = { + // code: '00', + // message: 'Successfully.', + // data: { + // status: true, + // }, + // }; + // return res.status(200).json(result); + // } + } + + //Card Sales Validation OK + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + perso_status: false, + card_product: card_product, + detail: detail_card, + }, + }; + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE VALIDATE-SALES ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +const confirmSales = async (req, res) => { + try { + let uniqueCode = helper.getUniqueCode(); + let result = {}; + + let { + card_number, + sales_status, + device_code, + station_code, + station_name, + created_by, + device_time, + } = req.body; + winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-SALES ]`); + + // CHECK VALIDATOR + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + //CARD SALES VALIDATION + const validCardSales = await checkCardSales(card_number, uniqueCode); + if (validCardSales) { + let dataCardSales = validCardSales.data; + if (dataCardSales.status == false) { + return res.status(200).json(validCardSales); + } + let detailCardSales = dataCardSales.detail; + + if (detailCardSales.sales_status != 'SUCCESS') { + //Update Data Sales Temp + let updateDataSales = { + sales_status: sales_status, + device_code: device_code, + station_code: station_code, + station_name: station_name, + created_by: created_by, + device_time: device_time, + }; + // update card_sales + await model.updateSales( + detailCardSales.i_sales_kmt_temp, + updateDataSales + ); + // log debug + winston.logger.debug( + `${uniqueCode} [ UPDATE SALES ${card_number} ]: ${updateDataSales}` + ); + + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + }, + }; + return res.status(200).json(result); + } + } + + //Insert Data Sales Temp + let dataSales = { + card_number: card_number, + sales_status: sales_status, + device_code: device_code, + station_code: station_code, + station_name: station_name, + created_by: created_by, + device_time: device_time, + }; + await model.insertSales(dataSales); + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ INSERT DATA REPLACEMENT DETAIL ]: ${JSON.stringify( + dataSales + )}` + ); + + //Card Sales Confirm OK + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + }, + }; + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE CONFIRM-SALES ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +const completeDataSalesInternal = async (req, res) => { + try { + let uniqueCode = helper.getUniqueCode(); + let result = {}; + + winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL ]`); + + // GET PPN FROM GLOBAL PARAMETER + let ppn = await model.getPPNCardSales(); + if (!ppn) { + result = { + code: '400', + message: 'value pajak belum di set', + data: {}, + }; + winston.logger.warn( + `${uniqueCode} [ VALIDATE COMPLETING DATA SALES INTERNAL ] : ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL - PPN ${ppn.c_value} % ]`); + + ppn = parseFloat(ppn.c_value); + + winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL - UPDATE DATA ]`); + + //COMPLETING DATA SALES INTERNAL + const response = await model.completingDataSalesInternal(ppn); + + if (!response.success) { + result = { + code: '400', + message: 'failed update data sales', + data: {}, + }; + winston.logger.warn( + `${uniqueCode} [ VALIDATE COMPLETING DATA SALES INTERNAL ] : ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + result = { + code: '00', + message: 'Successfully.', + data: {}, + }; + + winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL SUCCESS ] code=${result.code}`); + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE COMPLETING DATA SALES INTERNAL ]: 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 completeDataSalesInternalV2 = async (req, res) => { + try { + let uniqueCode = helper.getUniqueCode(); + let result = {}; + + winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL V2 ]`); + + // GET PPN FROM GLOBAL PARAMETER + let ppn = await model.getPPNCardSales(); + if (!ppn) { + result = { + code: '400', + message: 'value pajak belum di set', + data: {}, + }; + winston.logger.warn( + `${uniqueCode} [ VALIDATE COMPLETING DATA SALES INTERNAL V2 ] : ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + ppn = parseFloat(ppn.c_value); + + //COMPLETING DATA SALES INTERNAL + await model.completingDataSalesNewCard(ppn); + await model.completingDataSalesOldCard(ppn); + await model.updateDataSalesIsComplete(); + + result = { + code: '00', + message: 'Successfully.', + data: {}, + }; + + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE COMPLETING DATA SALES INTERNAL V2 ]: 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: {}, + }); + } +}; + +module.exports = { validateSales, confirmSales, completeDataSalesInternal, completeDataSalesInternalV2 }; diff --git a/application/modules/pos/card-topup.handlers.js b/application/modules/pos/card-topup.handlers.js new file mode 100644 index 0000000..485bcf9 --- /dev/null +++ b/application/modules/pos/card-topup.handlers.js @@ -0,0 +1,231 @@ +const helper = require('../../helpers/helper'); +const winston = require('../../helpers/winston.logger'); +const { validationResult } = require('express-validator'); +const { + validateEnvironment, + validateBlacklist, + validateCardProduct, + validateBIRegulation, +} = require('./card-validation.service'); + +// Validasi top up dan pengecekan blacklist untuk endpoint POS. +const validateTopup = async (req, res) => { + try { + let uniqueCode = helper.getUniqueCode(); + let dataCard = {}; + let result = {}; + let { card_number, amount, last_balance } = req.body; + winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-TOPUP ]`); + + // CHECK VALIDATOR + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + // TRIM CARD NUMBER + card_number = card_number.trim(); + + //CHECK IS CARD ALLOW + const validEnv = await validateEnvironment(card_number, uniqueCode); + if (validEnv) { + return res.status(200).json(validEnv); + } + + //CHECK IS CARD BLACKLISTED + let cardBlacklist = await validateBlacklist(card_number, uniqueCode); + if (cardBlacklist) { + return res.status(200).json(cardBlacklist); + } + + //CARD PRODUCT VALIDATION + const validCardProduct = await validateCardProduct(card_number, uniqueCode); + if (validCardProduct) { + dataCard = validCardProduct.data; + //CARD NOT REGISTERED IN CARD_PRODUCT + if (dataCard.status == false) { + return res.status(200).json(validCardProduct); + } + + dataCard = dataCard.detail; + const card_status = dataCard.c_status; + winston.logger.debug(`${uniqueCode} [ VALIDATE-TOPUP CARD STATUS ] status=${card_status}`); + + // Status valid => Persoed (P) atau Active (A) + if (card_status != 'P' && card_status != 'A') { + if (card_status == 'B') { + result = { + code: '445', + message: 'Card is blacklisted.', + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } else if (card_status == 'R') { + result = { + code: '451', + message: 'Card is redeemed or replaced.', + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } else if (card_status == 'N') { + result = { + code: '463', + message: 'Card is not activated.', + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } else { + result = { + code: '412', + message: 'Card status: ' + card_status, + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + } + } + + // if (last_balance) { + // let getLastBalanceFromCardHistory = await model.getLastBalanceFromCardHistory(card_number); + // if (getLastBalanceFromCardHistory) { + // last_balance = getLastBalanceFromCardHistory.m_balance_after; + // } + // } + // last_balance = 2000000; + + // CHECK POS_BI_REGULATION_STAT + const validBIRegulation = await validateBIRegulation( + card_number, + amount, + last_balance, + uniqueCode + ); + if (validBIRegulation) { + return res.status(200).json(validBIRegulation); + } + + //Card Topup Validation OK + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + detail: { + card_number: card_number, + last_balance: last_balance, + amount: amount, + }, + }, + }; + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE VALIDATE-TOPUP ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +const checkBlacklist = async (req, res) => { + try { + let uniqueCode = helper.getUniqueCode(); + let result = {}; + let { card_number } = req.body; + + winston.logger.info(`${uniqueCode} [ REQUEST CHECK-BLACKLIST ]`); + + //CHECK VALIDATOR + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: { + status: false, + detail: {}, + }, + }; + return res.status(200).json(result); + } + + //TRIM CARD NUMBER + card_number = card_number.trim(); + + //CHECK IS CARD ALLOW + const validEnv = await validateEnvironment(card_number, uniqueCode); + if (validEnv) { + res.status(200).json(validEnv); + } + + //CHECK IS CARD BLACKLISTED + let cardBlacklist = await validateBlacklist(card_number, uniqueCode); + if (cardBlacklist) { + return res.status(200).json(cardBlacklist); + } + + //CARD IS NOT BLACKLISTED + result = { + code: '00', + message: 'Card is not blacklisted.', + data: { + status: true, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE CHECK-BLACKLIST ]: ${JSON.stringify(result)}` + ); + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE CHECK-BLACKLIST ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +module.exports = { validateTopup, checkBlacklist }; diff --git a/application/modules/pos/card-validation.service.js b/application/modules/pos/card-validation.service.js new file mode 100644 index 0000000..eae41b2 --- /dev/null +++ b/application/modules/pos/card-validation.service.js @@ -0,0 +1,383 @@ +const model = require('./pos.model'); +const winston = require('../../helpers/winston.logger'); +const moment = require('moment'); + +// Pengecekan kartu dipakai bersama oleh alur penjualan, top up, redeem, dan penggantian. +const validateEnvironment = async (card_number, uniqueCode) => { + let result = {}; + const validateEnvStatus = await model.getGlobalParameterData( + 'POS_CARD_VALIDATE_ENV' + ); + + if (validateEnvStatus.c_value) { + if (validateEnvStatus.c_value == 'A') { + // jika settingan diperuntukan untuk production + if (process.env.SERVER_FOR == 'production') { + // kartu yang di request bukan kartu production maka akan di tolak + if (card_number.substring(0, 1) != '1') { + result = { + code: '400', + message: "It's not production card number.", + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: ${JSON.stringify( + result + )}` + ); + return result; + } + } else { + // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak + if (card_number.substring(0, 1) == '1') { + result = { + code: '400', + message: + "It's production card number. Please use the development card number.", + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: ${JSON.stringify( + result + )}` + ); + return result; + } + } + } else { + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: skip.` + ); + } + } else { + result = { + code: '400', + message: 'POS_CARD_VALIDATE_ENV in global parameter not found', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: ${JSON.stringify(result)}` + ); + return result; + } +}; + +const validateBlacklist = async (card_number, uniqueCode) => { + let result = {}; + const validateBlacklistStatus = await model.getGlobalParameterData( + 'POS_VALIDATE_CARD_BLACKLIST' + ); + if (validateBlacklistStatus.c_value) { + if (validateBlacklistStatus.c_value == 'A') { + let cardBlacklist = await model.getCardBlacklist(card_number); + if (cardBlacklist) { + if (cardBlacklist.c_status == 'B') { + result = { + code: '445', + message: 'Card is blacklisted.', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE CHECK-BLACKLIST ]: ${JSON.stringify( + result + )}` + ); + return result; + } + } + } else { + //LOG-INFO + winston.logger.info(`${uniqueCode} [ RESPONSE CHECK-BLACKLIST ]: skip.`); + } + } else { + result = { + code: '400', + message: 'POS_VALIDATE_CARD_BLACKLIST in global parameter not found', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: ${JSON.stringify(result)}` + ); + return result; + } +}; + +const validateCardProduct = async (card_number, uniqueCode) => { + let resultCP = {}; + const validateCardProductStatus = await model.getGlobalParameterData( + 'POS_VALIDATE_CARD_PRODUCT' + ); + if (validateCardProductStatus.c_value) { + if (validateCardProductStatus.c_value == 'A') { + //SALES VALIDATION + const dataCard = await model.getCardProduct(card_number); + //No Card Product + if (!dataCard) { + resultCP = { + code: '447', + message: 'Card number is not registered in card product.', + data: { + status: false, + detail: {}, + }, + }; + } else { + resultCP = { + code: '00', + message: 'Card number is registered in card product.', + data: { + status: true, + detail: dataCard, + }, + }; + } + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-CARD PRODUCT ]: ${JSON.stringify( + resultCP + )}` + ); + return resultCP; + } else { + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-CARD PRODUCT ]: skip.` + ); + } + } else { + resultCP = { + code: '400', + message: 'POS_VALIDATE_CARD_PRODUCT in global parameter not found', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-CARD PRODUCT ]: ${resultCP.code}` + ); + return resultCP; + } +}; + +const checkCardReplacement = async (card_number, uniqueCode) => { + let resultCR = {}; + + //SALES VALIDATION + const dataCard = await model.getCardReplacement(card_number); + //No Card Product + if (!dataCard) { + resultCR = { + code: '448', + message: 'Card number is not exist in card replacement.', + data: { + status: false, + detail: {}, + }, + }; + } else { + resultCR = { + code: '00', + message: 'Card number is registered in card replacement.', + data: { + status: true, + detail: dataCard, + }, + }; + } + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-CARD REPLACEMENT ]: ${JSON.stringify( + resultCR + )}` + ); + return resultCR; +}; + +const checkCardSales = async (card_number, uniqueCode) => { + const dataCard = await model.getCardSales(card_number); + let resultCR = null; + + if (dataCard) { + const isSold = dataCard.sales_status === 'SUCCESS'; + resultCR = { + code: isSold ? '444' : '00', + message: isSold ? 'Card has been sold.' : 'Success', + data: { + status: !isSold, + detail: isSold ? {} : dataCard, + }, + }; + } + + winston.logger.info( + `${uniqueCode} [ RESPONSE CHECK-CARD SALES ]: ${JSON.stringify(resultCR)}` + ); + + return resultCR; +}; + +const validateBIRegulation = async ( + card_number, + amount, + last_balance, + uniqueCode +) => { + let results = {}; + const validateBIRegulation = await model.getGlobalParameterData( + 'POS_BI_REGULATION_STAT' + ); + if (validateBIRegulation.c_value) { + if (validateBIRegulation.c_value == 'A') { + // 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'); + + // CHECK MAX AMOUNT ON CARD + let checkMaxAmountOnTheCard = await model.getGlobalParameterData( + 'HSM_BI_MAX_AMOUNT_ON_THE_CARD' + ); + if (checkMaxAmountOnTheCard.c_value) { + if ( + parseInt(last_balance) + parseInt(amount) > + parseInt(checkMaxAmountOnTheCard.c_value) + ) { + results = { + code: '416', + message: 'Card number has reached the maximum balance', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION: MAX AMOUNT ]: ${JSON.stringify( + results + )}` + ); + return results; + } + } else { + results = { + code: '400', + message: + 'HSM_BI_MAX_AMOUNT_ON_THE_CARD in global parameter not found', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: ${results.code}` + ); + return results; + } + + // VALIDATE MAX TOPUP PER MONTH + let checkMaxTopupPerMonth = await model.getGlobalParameterData( + 'HSM_BI_MAX_TOPUP_PER_MONTH' + ); + if (checkMaxTopupPerMonth.c_value) { + // get accumulated balance in this month dari nomor kartu yang di request + let accumulatedBalance = 0; + let getAccumulationBalanceInThisMonthFromCardHistory = + await model.getAccumulationBalanceInThisMonthFromCardHistory( + card_number, + year, + month + ); + + if (getAccumulationBalanceInThisMonthFromCardHistory) { + accumulatedBalance = + getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; + } + + if ( + parseInt(accumulatedBalance) + parseInt(amount) > + parseInt(checkMaxTopupPerMonth.c_value) + ) { + results = { + code: '417', + message: 'card number has been limit top up for this month', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION: MAX TOPUP PER MONTH ]: ${JSON.stringify( + results + )}` + ); + return results; + } + } else { + results = { + code: '400', + message: 'HSM_BI_MAX_TOPUP_PER_MONTH in global parameter not found', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: ${results.code}` + ); + return results; + } + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: pass` + ); + } else { + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: skip` + ); + } + } else { + results = { + code: '400', + message: 'POS_BI_REGULATION_STAT in global parameter not found', + data: { + status: false, + detail: {}, + }, + }; + //LOG-INFO + winston.logger.info( + `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: ${results.code}` + ); + return results; + } +}; + +module.exports = { validateEnvironment, validateBlacklist, validateCardProduct, checkCardReplacement, checkCardSales, validateBIRegulation }; diff --git a/application/modules/pos/pos-diagnostics.handler.js b/application/modules/pos/pos-diagnostics.handler.js new file mode 100644 index 0000000..3486168 --- /dev/null +++ b/application/modules/pos/pos-diagnostics.handler.js @@ -0,0 +1,42 @@ +const winston = require('../../helpers/winston.logger'); + +// Endpoint diagnostik POS. +const testAPI = async (req, res) => { + try { + let result = {}; + let { card_number } = req.body; + let last_balance = '10000'; + + //CARD VALID TO REPLACEMENT + result = { + code: '00', + message: 'Successfully.', + data: { + status: true, + detail: { + card_number: card_number, + last_balance: last_balance, + }, + }, + }; + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE VALIDATE-REPLACEMENT ]: 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: { + status: false, + detail: {}, + }, + }); + } +}; + +module.exports = { testAPI }; diff --git a/application/modules/pos/pos.controller.js b/application/modules/pos/pos.controller.js index 045fd5a..57ca450 100644 --- a/application/modules/pos/pos.controller.js +++ b/application/modules/pos/pos.controller.js @@ -1,2916 +1,33 @@ -const { postWithDeadline } = require('./cts-client'); -const knex = require('../../../infrastructure/database/knex'); - -const { validationResult } = require('express-validator'); const validate = require('./pos.validation'); -const helper = require('../../helpers/helper'); -const winston = require('../../helpers/winston.logger'); -const model = require('./pos.model'); const moment = require('moment'); +const { + validateSales, + confirmSales, + completeDataSalesInternal, + completeDataSalesInternalV2, +} = require('./card-sales.handlers'); +const { + validateTopup, + checkBlacklist, +} = require('./card-topup.handlers'); +const { + validateRedeem, + confirmRedeem, +} = require('./card-redeem.handlers'); +const { checkCardSales } = require('./card-validation.service'); +const { + validateReplacement, + validateNewCardReplacement, + replacementConfirm, +} = require('./card-replacement.handlers'); +const { + checkLastBalance, + getLastBalanceCTS, +} = require('./card-balance.handlers'); +const { testAPI } = require('./pos-diagnostics.handler'); + moment.locale('id'); - -/****************** */ -/* GLOBAL PARAMETER */ -// POS_CARD_VALIDATE_ENV -// POS_VALIDATE_CARD_BLACKLIST -// POS_VALIDATE_CARD_PRODUCT -// POS_VALIDATE_CARD_REPLACEMENT - -const checkLastBalance = async (req, res) => { - let result = {}; - let { card_number } = req.body; - let uniqueCode = helper.getUniqueCode(); - - //CHECK IS CARD BLACKLISTED - let cardBlacklist = await validateBlacklist(card_number, uniqueCode); - if (cardBlacklist) { - return res.status(200).json(cardBlacklist); - } - - let last_balance = 0; - let getLastBalanceFromCardHistory = await model.getLastBalanceFromCardHistory( - card_number - ); - if (getLastBalanceFromCardHistory) { - last_balance = getLastBalanceFromCardHistory.m_balance_after; - } - - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - detail: { - card_number: card_number, - last_balance: last_balance, - }, - }, - }; - return res.status(200).json(result); -}; - -const validateEnvironment = async (card_number, uniqueCode) => { - let result = {}; - const validateEnvStatus = await model.getGlobalParameterData( - 'POS_CARD_VALIDATE_ENV' - ); - - if (validateEnvStatus.c_value) { - if (validateEnvStatus.c_value == 'A') { - // jika settingan diperuntukan untuk production - if (process.env.SERVER_FOR == 'production') { - // kartu yang di request bukan kartu production maka akan di tolak - if (card_number.substring(0, 1) != '1') { - result = { - code: '400', - message: "It's not production card number.", - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: ${JSON.stringify( - result - )}` - ); - return result; - } - } else { - // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak - if (card_number.substring(0, 1) == '1') { - result = { - code: '400', - message: - "It's production card number. Please use the development card number.", - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: ${JSON.stringify( - result - )}` - ); - return result; - } - } - } else { - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: skip.` - ); - } - } else { - result = { - code: '400', - message: 'POS_CARD_VALIDATE_ENV in global parameter not found', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: ${JSON.stringify(result)}` - ); - return result; - } -}; - -//START -const validateBlacklist = async (card_number, uniqueCode) => { - let result = {}; - const validateBlacklistStatus = await model.getGlobalParameterData( - 'POS_VALIDATE_CARD_BLACKLIST' - ); - if (validateBlacklistStatus.c_value) { - if (validateBlacklistStatus.c_value == 'A') { - let cardBlacklist = await model.getCardBlacklist(card_number); - if (cardBlacklist) { - if (cardBlacklist.c_status == 'B') { - result = { - code: '445', - message: 'Card is blacklisted.', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE CHECK-BLACKLIST ]: ${JSON.stringify( - result - )}` - ); - return result; - } - } - } else { - //LOG-INFO - winston.logger.info(`${uniqueCode} [ RESPONSE CHECK-BLACKLIST ]: skip.`); - } - } else { - result = { - code: '400', - message: 'POS_VALIDATE_CARD_BLACKLIST in global parameter not found', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: ${JSON.stringify(result)}` - ); - return result; - } -}; - -//CHECK LAST BALANCE CTR -const checkLastBalanceCTS = async (card_number, uniqueCode, req) => { - let token_api; - let result = {}; - - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ card_number ]: ${JSON.stringify(card_number)}` - ); - - let last_balance = 0; - let getLastBalanceFromCardHistory = await model.getLastBalanceFromCardHistory( - card_number - ); - - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ getLastBalanceFromCardHistory ]: ${JSON.stringify( - getLastBalanceFromCardHistory - )}` - ); - - if (getLastBalanceFromCardHistory) { - last_balance = getLastBalanceFromCardHistory.m_balance_after; - } - - let auth = req.header('Authorization'); - token_api = auth.replace('Bearer ', ''); - - const protocol = req.protocol; - const host = req.headers.host; - const current_url = protocol + '://' + host; - - let config = { - headers: { - 'Content-Type': 'application/json', - Authorization: 'Bearer ' + token_api, - }, - }; - const dataPost = { card_number: card_number }; - const url = current_url + `/api/pos/card-lastbalance`; - const resp = await postWithDeadline(url, dataPost, config); - - if ( - resp.data.data == undefined || - resp.data.data.detail.last_balance == undefined - ) { - result = { - code: '446', - message: 'Card number not exist in CTS to get last balance', - data: { - status: false, - detail: { - last_balance: last_balance, - }, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE GET LAST-BALANCE FROM CTS ]: ${JSON.stringify( - result - )}` - ); - return result; - } - - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - detail: { - last_balance: last_balance, - }, - }, - }; - - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE GET LAST-BALANCE FROM CTS ]: ${JSON.stringify( - result - )}` - ); - return result; -}; - -//VALIDATE CARD PRODUCT -const validateCardProduct = async (card_number, uniqueCode) => { - let resultCP = {}; - const validateCardProductStatus = await model.getGlobalParameterData( - 'POS_VALIDATE_CARD_PRODUCT' - ); - if (validateCardProductStatus.c_value) { - if (validateCardProductStatus.c_value == 'A') { - //SALES VALIDATION - const dataCard = await model.getCardProduct(card_number); - //No Card Product - if (!dataCard) { - resultCP = { - code: '447', - message: 'Card number is not registered in card product.', - data: { - status: false, - detail: {}, - }, - }; - } else { - resultCP = { - code: '00', - message: 'Card number is registered in card product.', - data: { - status: true, - detail: dataCard, - }, - }; - } - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-CARD PRODUCT ]: ${JSON.stringify( - resultCP - )}` - ); - return resultCP; - } else { - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-CARD PRODUCT ]: skip.` - ); - } - } else { - resultCP = { - code: '400', - message: 'POS_VALIDATE_CARD_PRODUCT in global parameter not found', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-CARD PRODUCT ]: ${JSON.stringify( - result - )}` - ); - return resultCP; - } -}; - -//VALIDATE CARD PRODUCT -const checkCardReplacement = async (card_number, uniqueCode) => { - let resultCR = {}; - - //SALES VALIDATION - const dataCard = await model.getCardReplacement(card_number); - //No Card Product - if (!dataCard) { - resultCR = { - code: '448', - message: 'Card number is not exist in card replacement.', - data: { - status: false, - detail: {}, - }, - }; - } else { - resultCR = { - code: '00', - message: 'Card number is registered in card replacement.', - data: { - status: true, - detail: dataCard, - }, - }; - } - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-CARD REPLACEMENT ]: ${JSON.stringify( - resultCR - )}` - ); - return resultCR; -}; - -//CHECK CARD SALES -const checkCardSales = async (card_number, uniqueCode) => { - const dataCard = await model.getCardSales(card_number); - let resultCR = null; - - if (dataCard) { - const isSold = dataCard.sales_status === 'SUCCESS'; - resultCR = { - code: isSold ? '444' : '00', - message: isSold ? 'Card has been sold.' : 'Success', - data: { - status: !isSold, - detail: isSold ? {} : dataCard, - }, - }; - } - - winston.logger.info( - `${uniqueCode} [ RESPONSE CHECK-CARD SALES ]: ${JSON.stringify(resultCR)}` - ); - - return resultCR; -}; - -//VALIDATE BI REGULATION -const validateBIRegulation = async ( - card_number, - amount, - last_balance, - uniqueCode -) => { - let results = {}; - const validateBIRegulation = await model.getGlobalParameterData( - 'POS_BI_REGULATION_STAT' - ); - if (validateBIRegulation.c_value) { - if (validateBIRegulation.c_value == 'A') { - // 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'); - - // CHECK MAX AMOUNT ON CARD - let checkMaxAmountOnTheCard = await model.getGlobalParameterData( - 'HSM_BI_MAX_AMOUNT_ON_THE_CARD' - ); - if (checkMaxAmountOnTheCard.c_value) { - if ( - parseInt(last_balance) + parseInt(amount) > - parseInt(checkMaxAmountOnTheCard.c_value) - ) { - results = { - code: '416', - message: 'Card number has reached the maximum balance', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION: MAX AMOUNT ]: ${JSON.stringify( - results - )}` - ); - return results; - } - } else { - results = { - code: '400', - message: - 'HSM_BI_MAX_AMOUNT_ON_THE_CARD in global parameter not found', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: ${JSON.stringify( - result - )}` - ); - return results; - } - - // VALIDATE MAX TOPUP PER MONTH - let checkMaxTopupPerMonth = await model.getGlobalParameterData( - 'HSM_BI_MAX_TOPUP_PER_MONTH' - ); - if (checkMaxTopupPerMonth.c_value) { - // get accumulated balance in this month dari nomor kartu yang di request - let accumulatedBalance = 0; - let getAccumulationBalanceInThisMonthFromCardHistory = - await model.getAccumulationBalanceInThisMonthFromCardHistory( - card_number, - year, - month - ); - - if (getAccumulationBalanceInThisMonthFromCardHistory) { - accumulatedBalance = - getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; - } - - if ( - parseInt(accumulatedBalance) + parseInt(amount) > - parseInt(checkMaxTopupPerMonth.c_value) - ) { - results = { - code: '417', - message: 'card number has been limit top up for this month', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION: MAX TOPUP PER MONTH ]: ${JSON.stringify( - results - )}` - ); - return results; - } - } else { - results = { - code: '400', - message: 'HSM_BI_MAX_TOPUP_PER_MONTH in global parameter not found', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: ${JSON.stringify( - result - )}` - ); - return results; - } - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: pass` - ); - } else { - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: skip` - ); - } - } else { - results = { - code: '400', - message: 'POS_BI_REGULATION_STAT in global parameter not found', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: ${JSON.stringify( - result - )}` - ); - return results; - } -}; - -const validateSales = async (req, res) => { - try { - let uniqueCode = helper.getUniqueCode(); - let dataCard = {}; - let result = {}; - let detail_card = {}; - let card_product = false; - - let { card_number } = req.body; - winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-SALES ]`); - - // CHECK VALIDATOR - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - - // TRIM CARD NUMBER - card_number = card_number.trim(); - - //CHECK IS CARD ALLOW - const validEnv = await validateEnvironment(card_number, uniqueCode); - if (validEnv) { - return res.status(200).json(validEnv); - } - - //CHECK IS CARD BLACKLISTED - let cardBlacklist = await validateBlacklist(card_number, uniqueCode); - if (cardBlacklist) { - return res.status(200).json(cardBlacklist); - } - - //CARD PRODUCT VALIDATION - const validCardProduct = await validateCardProduct(card_number, uniqueCode); - - if (validCardProduct) { - //CARD NOT REGISTERED IN CARD_PRODUCT - if (validCardProduct.data.status == false) { - return res.status(200).json(validCardProduct); - } - - card_product = true; - dataCard = validCardProduct.data.detail; - //A: ACTIVED | N: GENERATED | P: PERSOED | B: BLACKLISTED | R: REDEEMED -> harus N/Generated - const card_status = dataCard.c_status; - detail_card = { - card_number: dataCard.c_card_number, - card_theme: dataCard.i_card_theme, - card_theme_code: dataCard.c_card_theme_code, - card_theme_name: dataCard.c_card_theme_name, - card_theme_card_digit_key: dataCard.c_card_theme_card_digit_key, - card_type: dataCard.i_card_type, - card_type_code: dataCard.c_card_type_code, - card_type_name: dataCard.c_card_type_name, - variant: dataCard.i_variant, - variant_code: dataCard.c_variant_code, - variant_name: dataCard.c_variant_name, - status: dataCard.c_status, - status_name: dataCard.c_status_name, - }; - - if (card_status != 'N' && card_status != 'P') { - if (card_status == 'A') { - result = { - code: '450', - message: 'Card is already activated.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } else if (card_status == 'R') { - result = { - code: '451', - message: 'Card is redeemed.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } else if (card_status == 'B') { - result = { - code: '445', - message: 'Card is blacklisted.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } - - //other status - result = { - code: '462', - message: 'Card not valid to sales.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } - } - - //CARD SALES VALIDATION - const validCardSales = await checkCardSales(card_number, uniqueCode); - if (validCardSales) { - let dataCardSales = validCardSales.data; - if (dataCardSales.status == false) { - return res.status(200).json(validCardSales); - } - // let detailCardSales = dataCardSales.detail; - - // if (detailCardSales.sales_status != 'SUCCESS') { - // //Update Data Sales Temp - // let updateDataSales = { - // sales_status: sales_status, - // device_code: device_code, - // station_code: station_code, - // station_name: station_name, - // created_by: created_by, - // device_time: device_time - // } - // // update card_sales - // await model.updateSales(detailCardSales.i_sales_kmt_temp, updateDataSales); - // // log debug - // winston.logger.debug( - // `${uniqueCode} [ UPDATE SALES ${card_number} ]: ${updateDataSales}` - // ); - - // result = { - // code: '00', - // message: 'Successfully.', - // data: { - // status: true, - // }, - // }; - // return res.status(200).json(result); - // } - } - - //Card Sales Validation OK - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - perso_status: false, - card_product: card_product, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE VALIDATE-SALES ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; - -const validateTopup = async (req, res) => { - try { - let uniqueCode = helper.getUniqueCode(); - let dataCard = {}; - let result = {}; - let { card_number, amount, last_balance } = req.body; - winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-TOPUP ]`); - - // CHECK VALIDATOR - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - - // TRIM CARD NUMBER - card_number = card_number.trim(); - - //CHECK IS CARD ALLOW - const validEnv = await validateEnvironment(card_number, uniqueCode); - if (validEnv) { - return res.status(200).json(validEnv); - } - - //CHECK IS CARD BLACKLISTED - let cardBlacklist = await validateBlacklist(card_number, uniqueCode); - if (cardBlacklist) { - return res.status(200).json(cardBlacklist); - } - - //CARD PRODUCT VALIDATION - const validCardProduct = await validateCardProduct(card_number, uniqueCode); - if (validCardProduct) { - dataCard = validCardProduct.data; - //CARD NOT REGISTERED IN CARD_PRODUCT - if (dataCard.status == false) { - return res.status(200).json(validCardProduct); - } - - dataCard = dataCard.detail; - const card_status = dataCard.c_status; - winston.logger.debug(`${uniqueCode} [ VALIDATE-TOPUP CARD STATUS ] status=${card_status}`); - - // Status valid => Persoed (P) atau Active (A) - if (card_status != 'P' && card_status != 'A') { - if (card_status == 'B') { - result = { - code: '445', - message: 'Card is blacklisted.', - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } else if (card_status == 'R') { - result = { - code: '451', - message: 'Card is redeemed or replaced.', - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } else if (card_status == 'N') { - result = { - code: '463', - message: 'Card is not activated.', - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } else { - result = { - code: '412', - message: 'Card status: ' + card_status, - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - } - } - - // if (last_balance) { - // let getLastBalanceFromCardHistory = await model.getLastBalanceFromCardHistory(card_number); - // if (getLastBalanceFromCardHistory) { - // last_balance = getLastBalanceFromCardHistory.m_balance_after; - // } - // } - // last_balance = 2000000; - - // CHECK POS_BI_REGULATION_STAT - const validBIRegulation = await validateBIRegulation( - card_number, - amount, - last_balance, - uniqueCode - ); - if (validBIRegulation) { - return res.status(200).json(validBIRegulation); - } - - //Card Topup Validation OK - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - detail: { - card_number: card_number, - last_balance: last_balance, - amount: amount, - }, - }, - }; - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE VALIDATE-TOPUP ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; - -const checkBlacklist = async (req, res) => { - try { - let uniqueCode = helper.getUniqueCode(); - let result = {}; - let { card_number } = req.body; - - winston.logger.info(`${uniqueCode} [ REQUEST CHECK-BLACKLIST ]`); - - //CHECK VALIDATOR - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - - //TRIM CARD NUMBER - card_number = card_number.trim(); - - //CHECK IS CARD ALLOW - const validEnv = await validateEnvironment(card_number, uniqueCode); - if (validEnv) { - res.status(200).json(validEnv); - } - - //CHECK IS CARD BLACKLISTED - let cardBlacklist = await validateBlacklist(card_number, uniqueCode); - if (cardBlacklist) { - return res.status(200).json(cardBlacklist); - } - - //CARD IS NOT BLACKLISTED - result = { - code: '00', - message: 'Card is not blacklisted.', - data: { - status: true, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE CHECK-BLACKLIST ]: ${JSON.stringify(result)}` - ); - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE CHECK-BLACKLIST ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; - -const validateRedeem = async (req, res) => { - let dataCard; - try { - let uniqueCode = helper.getUniqueCode(); - let result = {}; - let last_balance = null; - let dataCardReplacement = {}; - let { card_number, station_code } = req.body; - - winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-REDEEM ]`); - - //CHECK VALIDATOR - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - - //TRIM CARD NUMBER - card_number = card_number.trim(); - - //CHECK IS CARD ALLOW - const validEnv = await validateEnvironment(card_number, uniqueCode); - if (validEnv) { - res.status(200).json(validEnv); - } - - //CHECK IS CARD BLACKLISTED - let cardBlacklist = await validateBlacklist(card_number, uniqueCode); - if (cardBlacklist) { - return res.status(200).json(cardBlacklist); - } - - //CARD PRODUCT VALIDATION - const validCardProduct = await validateCardProduct(card_number, uniqueCode); - if (validCardProduct) { - dataCard = validCardProduct.data; - //CARD NOT REGISTERED IN CARD_PRODUCT - if (dataCard.status == false) { - return res.status(200).json(validCardProduct); - } - - dataCard = dataCard.detail; - const card_status = dataCard.c_status; - - // Status valid => Active (A) - if (card_status != 'A') { - if (card_status == 'R') { - result = { - code: '451', - message: 'Card is redeemed or replaced.', - data: { - status: false, - detail: {}, - }, - }; - } else if (card_status == 'B') { - result = { - code: '445', - message: 'Card is blacklisted.', - data: { - status: false, - detail: {}, - }, - }; - } else if (card_status == 'N') { - result = { - code: '463', - message: 'Card is not activated.', - data: { - status: false, - detail: {}, - }, - }; - } else if (card_status == 'P') { - result = { - code: '458', - message: 'Card is persoed and not yet active.', - data: { - status: false, - detail: {}, - }, - }; - } - - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-REDEEM ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - } - - //CARD REPLACEMENT VALIDATION - const validCardReplacement = await checkCardReplacement( - card_number, - uniqueCode - ); - if (validCardReplacement) { - dataCardReplacement = validCardReplacement.data; - //CARD NOT REGISTERED IN CARD_REPLACEMENT - if (dataCardReplacement.status == false) { - return res.status(200).json(validCardReplacement); - } - dataCardReplacement = dataCardReplacement.detail; - - let replacement_redeem_category = - dataCardReplacement.c_replace_redeem_category_code.trim(); - //replacement_redeem_category: R - REDEEM | w - REPLACEMENT WARRANTY | N - REPLACEMENT NON-WARRANTY - if (replacement_redeem_category != 'R') { - result = { - code: '491', - message: 'Card not registered as redeem.', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REDEEM-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - let replacement_station_code = - dataCardReplacement.c_org_dept_station_code.trim(); - if (replacement_station_code != station_code) { - result = { - code: '411', - message: 'Station code not match.', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REDEEM-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - let replacement_status = dataCardReplacement.c_status.trim(); - //replacement_status: N - NEW | X - CANCELLED | A - COMPLETED - if (replacement_status != 'N') { - if (replacement_status == 'X') { - result = { - code: '406', - message: 'Replacement or redeem Card Status is cancelled.', - data: { - status: false, - detail: {}, - }, - }; - } else if (replacement_status == 'A') { - result = { - code: '407', - message: 'Card has been replaced or redeemed.', - data: { - status: false, - detail: {}, - }, - }; - } else { - result = { - code: '408', - message: 'Redeem or replacement card status not defined.', - data: { - status: false, - detail: {}, - }, - }; - } - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-REDEEM ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - //Cek tanggal d_valid_date - - //Update Data Replacement - let date_request = dataCardReplacement.d_request; - let date_valid = dataCardReplacement.d_valid_date; - - let now = moment().format('YYYY-MM-DD'); - date_valid = moment(date_valid).format('YYYY-MM-DD'); - date_request = moment(date_request).format('YYYY-MM-DD'); - - if (now < date_valid) { - //other status - result = { - code: '456', - message: 'The valid replacement date is insufficient.', - data: { - status: false, - detail: { - date_now: now, - date_request: date_request, - date_valid: date_valid, - }, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - } - - last_balance = dataCardReplacement.i_last_balance; - if (last_balance == null) { - let result = {}; - // const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance' - const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`; - const payload = { - card_number: card_number, - }; - let config = { - headers: { - 'Content-Type': 'application/json', - }, - }; - const url = baseUrl; - const response = await postWithDeadline(url, payload, config); - if (response.data.code == undefined || response.data.code != 200) { - if (response.data.code == 404) { - result = { - code: '494', - message: 'No data found in CTS for the given card number', - data: { - status: false, - detail: {}, - }, - }; - winston.logger.info( - `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}` - ); - return res.status(200).json(result); - } - result = { - code: '415', - message: 'Last Balance not updated.', - data: { - status: false, - detail: {}, - }, - }; - winston.logger.info( - `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}` - ); - return res.status(200).json(result); - } - - last_balance = response.data.data.balance_after; - } - - let security_code = await helper.createHMAC(card_number); - - //CARD VALID TO REDEEM - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - detail: { - security_code: security_code, - last_balance: last_balance, - card_number: card_number, - unique_code: uniqueCode, - }, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-REDEEM ]: ${JSON.stringify(result)}` - ); - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE VALIDATE-REDEEM ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; - -const validateReplacement = async (req, res) => { - let dataCard; - try { - let uniqueCode = helper.getUniqueCode(); - let result = {}; - let { card_number, station_code } = req.body; - let dataCardReplacement = {}; - let last_balance = null; - let is_warranty = false; - - winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-REPLACEMENT ]`); - - //CHECK VALIDATOR - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - - //TRIM CARD NUMBER - card_number = card_number.trim(); - - //CHECK IS CARD ALLOW - const validEnv = await validateEnvironment(card_number, uniqueCode); - if (validEnv) { - res.status(200).json(validEnv); - } - - //CHECK IS CARD BLACKLISTED - let cardBlacklist = await validateBlacklist(card_number, uniqueCode); - if (cardBlacklist) { - return res.status(200).json(cardBlacklist); - } - - //CARD PRODUCT VALIDATION - const validCardProduct = await validateCardProduct(card_number, uniqueCode); - if (validCardProduct) { - dataCard = validCardProduct.data; - //CARD NOT REGISTERED IN CARD_PRODUCT - if (dataCard.status == false) { - return res.status(200).json(validCardProduct); - } - - dataCard = dataCard.detail; - const card_status = dataCard.c_status; - - // Status valid => Active (A) - if (card_status != 'A') { - if (card_status == 'R') { - result = { - code: '451', - message: 'Card is redeemed or replaced.', - data: { - status: false, - detail: {}, - }, - }; - } else if (card_status == 'B') { - result = { - code: '445', - message: 'Card is blacklisted.', - data: { - status: false, - detail: {}, - }, - }; - } else if (card_status == 'N') { - result = { - code: '463', - message: 'Card is not activated.', - data: { - status: false, - detail: {}, - }, - }; - } else if (card_status == 'P') { - result = { - code: '458', - message: 'Card is persoed and not yet active.', - data: { - status: false, - detail: {}, - }, - }; - } - - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-REPLACEMENT ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - } - - //CARD REPLACEMENT VALIDATION - const validCardReplacement = await checkCardReplacement( - card_number, - uniqueCode - ); - if (validCardReplacement) { - dataCardReplacement = validCardReplacement.data; - //CARD NOT REGISTERED IN CARD_REPLACEMENT - if (dataCardReplacement.status == false) { - return res.status(200).json(validCardReplacement); - } - dataCardReplacement = dataCardReplacement.detail; - - let category_replacement = - dataCardReplacement.c_replace_redeem_category_code; - //replacement_redeem_category: R - REDEEM | w - REPLACEMENT WARRANTY | N - REPLACEMENT NON-WARRANTY - if (category_replacement == 'R') { - result = { - code: '492', - message: 'Card not registered as replacement.', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REPLACEMENT-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - //is warranty - if (category_replacement == 'W') { - is_warranty = true; - } - - let replacement_station_code = - dataCardReplacement.c_org_dept_station_code.trim(); - if (replacement_station_code != station_code) { - result = { - code: '411', - message: 'Station code not match.', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REPLACEMENT-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - let replacement_status = dataCardReplacement.c_status.trim(); - //replacement_status: N - NEW | X - CANCELLED | A - COMPLETED - if (replacement_status != 'N') { - if (replacement_status == 'X') { - result = { - code: '406', - message: 'Replacement or redeem Card Status is cancelled.', - data: { - status: false, - detail: {}, - }, - }; - } else if (replacement_status == 'A') { - result = { - code: '407', - message: 'Card has been replaced or redeemed.', - data: { - status: false, - detail: {}, - }, - }; - } else { - result = { - code: '408', - message: 'Redeem or replacement card status not defined.', - data: { - status: false, - detail: {}, - }, - }; - } - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-REPLACEMENT ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - //Cek tanggal d_valid_date - - let date_request = dataCardReplacement.d_request; - let date_valid = dataCardReplacement.d_valid_date; - - let now = moment().format('YYYY-MM-DD'); - date_valid = moment(date_valid).format('YYYY-MM-DD'); - date_request = moment(date_request).format('YYYY-MM-DD'); - - if (now < date_valid) { - //other status - result = { - code: '456', - message: 'The valid replacement date is insufficient.', - data: { - status: false, - detail: { - date_now: now, - date_request: date_request, - date_valid: date_valid, - }, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - } - - last_balance = dataCardReplacement.i_last_balance; - if (last_balance == null) { - // if (is_warranty == true) { - // let result = {}; - // const baseUrl = 'http://127.0.0.1:3000'; - // const payload = { - // card_number: card_number, - // }; - // const response = await axios.post(baseUrl + '/api/pos/test', payload); - // if ( - // !response.data.code == undefined || - // response.data.data.status == false - // ) { - // result = { - // code: '415', - // message: 'Last Balance not updated.', - // data: { - // status: false, - // detail: {}, - // }, - // }; - // winston.logger.info( - // `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}` - // ); - // return res.status(200).json(result); - // } - // last_balance = response.data.data.detail.last_balance; - // let dataReplacementUpdate = { - // i_last_balance: last_balance, - // }; - // // update card_replacement - // await model.updateReplacementByCardNumber( - // card_number, - // dataReplacementUpdate - // ); - // // log debug - // winston.logger.info( - // `${uniqueCode} [ GET LAST BALANCE CTS ${card_number} ]: ${last_balance}` - // ); - // } else { - // result = { - // code: '415', - // message: 'Last Balance not updated.', - // data: { - // status: false, - // detail: {}, - // }, - // }; - // //LOG-INFO - // winston.logger.info( - // `${uniqueCode} [ RESPONSE VALIDATE-REPLACEMENT ]: ${JSON.stringify( - // result - // )}` - // ); - // return res.status(200).json(result); - - // if (is_warranty == true) { - let result = {}; - // const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance' - const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`; - const payload = { - card_number: card_number, - }; - let config = { - headers: { - 'Content-Type': 'application/json', - }, - }; - const url = baseUrl; - const response = await postWithDeadline(url, payload, config); - if (response.data.code == undefined || response.data.code != 200) { - if (response.data.code == 404) { - result = { - code: '494', - message: 'No data found in CTS for the given card number', - data: { - status: false, - detail: {}, - }, - }; - winston.logger.info( - `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}` - ); - return res.status(200).json(result); - } - result = { - code: '415', - message: 'Last Balance not updated.', - data: { - status: false, - detail: {}, - }, - }; - winston.logger.info( - `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}` - ); - return res.status(200).json(result); - } - last_balance = response.data.data.balance_after; - let dataReplacementUpdate = { - i_last_balance: last_balance, - }; - // update card_replacement - await model.updateReplacementByCardNumber( - card_number, - dataReplacementUpdate - ); - // log debug - winston.logger.info( - `${uniqueCode} [ GET LAST BALANCE CTS ${card_number} ]: ${last_balance}` - ); - // } - } - - // ==================== Contoh service Scheduller get last balance from CTS ==================== - // if (last_balance == null) { - // //CHECK CARD LAST_BALANCE - // const dataLastBalance = await checkLastBalanceCTS(card_number, uniqueCode, req); - // if (!dataLastBalance.data.status || dataLastBalance.data.status == false) { - // return res.status(200).json(dataLastBalance); - // } - // last_balance = dataLastBalance.data.detail.last_balance; - - // let dataReplacementUpdate = { - // i_last_balance: last_balance - // }; - // // update card_replacement - // await model.updateReplacement(dataCardReplacement.i_card_replacement, dataReplacementUpdate); - - // // log debug - // winston.logger.debug( - // `${uniqueCode} [ UPDATE LAST BALANCE CARD ${card_number} ]: ${last_balance}` - // ); - - // } - - // create security code - let security_code = await helper.createHMAC( - card_number + '|' + last_balance - ); - - //CARD VALID TO REPLACEMENT - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - detail: { - security_code: security_code, - last_balance: last_balance, - is_warranty: is_warranty, - unique_code: uniqueCode, - card_category: { - id: dataCardReplacement.card_category_id, - code: dataCardReplacement.card_category_code, - name: dataCardReplacement.card_category_name - } - }, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE VALIDATE-REPLACEMENT ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE VALIDATE-REPLACEMENT ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; - -const validateNewCardReplacement = async (req, res) => { - let dataCardNew; - try { - let uniqueCode = helper.getUniqueCode(); - let result = {}; - let { card_number } = req.body; - - winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]`); - - //CHECK VALIDATOR - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - - //TRIM CARD NUMBER - card_number = card_number.trim(); - - //CHECK IS CARD ALLOW - const validEnv = await validateEnvironment(card_number, uniqueCode); - if (validEnv) { - res.status(200).json(validEnv); - } - - //CHECK IS CARD BLACKLISTED - let cardBlacklist = await validateBlacklist(card_number, uniqueCode); - if (cardBlacklist) { - result = { - code: '457', - message: 'New card is blacklisted.', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - //CARD REPLACEMENT VALIDATION - const validCardReplacement = await checkCardReplacement( - card_number, - uniqueCode - ); - //CARD REGISTERED IN CARD_REPLACEMENT - if (validCardReplacement.data.status == true) { - result = { - code: '461', - message: - 'New card number exists in the card replacement data and cannot be used for card replacement.', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - const validCardProductNew = await validateCardProduct( - card_number, - uniqueCode - ); - if (validCardProductNew) { - dataCardNew = validCardProductNew.data; - //CARD NOT REGISTERED IN CARD_PRODUCT - if (dataCardNew.status == false) { - return res.status(200).json(validCardProductNew); - } - - dataCardNew = dataCardNew.detail; - const card_new_status = dataCardNew.c_status; - // Status valid => Active (A) - - if (card_new_status != 'P') { - if (card_new_status == 'A') { - result = { - code: '453', - message: 'New card is already activated.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } else if (card_new_status == 'R') { - result = { - code: '454', - message: 'New card is redeemed or replaced.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } else if (card_new_status == 'B') { - result = { - code: '457', - message: 'New card is blacklisted.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } - - //other status - result = { - code: '455', - message: 'New Card not valid for replacement.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } - } - - //CARD VALID TO REPLACEMENT - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; - -const replacementConfirm = async (req, res) => { - let dataCardNew; - try { - // let uniqueCode = helper.getUniqueCode(); - let result = {}; - let { - card_number, - new_card_number, - last_balance, - security_code, - unique_code, - } = req.body; - let uniqueCode = unique_code; - let dataCardReplacement = {}; - - winston.logger.info(`${uniqueCode} [ REQUEST REPLACEMENT-CONFIRM ]`); - - //CHECK VALIDATOR - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - - if (card_number == new_card_number) { - result = { - code: '493', - message: 'bad request. new card number cannot be same.', - data: {}, - }; - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - //CHECK SECURITY-CODE - if (security_code) { - let securityCodeCompare = await helper.createHMAC( - card_number + '|' + last_balance - ); - - if (security_code !== securityCodeCompare) { - result = { - code: '437', - message: 'bad request. security code does not match.', - data: {}, - }; - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - } - - //TRIM CARD NUMBER - card_number = card_number.trim(); - new_card_number = new_card_number.trim(); - - //CHECK IS CARD ALLOW - const validEnv = await validateEnvironment(card_number, uniqueCode); - if (validEnv) { - // log warn - winston.logger.warn( - `${uniqueCode} [ VALIDATE ENV OLD CARD NUMBER ]: ${JSON.stringify( - validEnv - )}` - ); - res.status(200).json(validEnv); - } - - //CHECK IS CARD ALLOW - const validEnvNew = await validateEnvironment(new_card_number, uniqueCode); - if (validEnvNew) { - // log warn - winston.logger.warn( - `${uniqueCode} [ VALIDATE ENV NEW CARD NUMBER ]: ${JSON.stringify( - validEnvNew - )}` - ); - res.status(200).json(validEnv); - } - - //CHECK IS CARD BLACKLISTED - let cardBlacklist = await validateBlacklist(card_number, uniqueCode); - if (cardBlacklist) { - // log warn - winston.logger.warn( - `${uniqueCode} [ VALIDATE BLACKLIST OLD CARD NUMBER ]: ${JSON.stringify( - cardBlacklist - )}` - ); - return res.status(200).json(cardBlacklist); - } - let cardBlacklistNew = await validateBlacklist(new_card_number, uniqueCode); - if (cardBlacklistNew) { - cardBlacklistNew.message = 'New Card is blacklisted.'; - // log warn - winston.logger.warn( - `${uniqueCode} [ VALIDATE BLACKLIST NEW CARD NUMBER ]: ${JSON.stringify( - cardBlacklistNew - )}` - ); - return res.status(200).json(cardBlacklistNew); - } - - //CARD REPLACEMENT VALIDATION - const validCardReplacement = await checkCardReplacement( - card_number, - uniqueCode - ); - if (validCardReplacement) { - dataCardReplacement = validCardReplacement.data; - //CARD NOT REGISTERED IN CARD_REPLACEMENT - if (dataCardReplacement.status == false) { - return res.status(200).json(validCardReplacement); - } - dataCardReplacement = dataCardReplacement.detail; - - let replacement_status = dataCardReplacement.c_status.trim(); - //replacement_status: N - NEW | X - CANCELLED | A - COMPLETED - if (replacement_status != 'N') { - if (replacement_status == 'X') { - result = { - code: '406', - message: 'Replacement or redeem Card Status is cancelled.', - data: { - status: false, - detail: {}, - }, - }; - } else if (replacement_status == 'A') { - result = { - code: '458', - message: 'Card has been replaced.', - data: { - status: false, - detail: {}, - }, - }; - } else { - result = { - code: '408', - message: 'Redeem or replacement card status not defined.', - data: { - status: false, - detail: {}, - }, - }; - } - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - } - - //CHECK NEW CARD - const newCardReplacement = await checkCardReplacement( - new_card_number, - uniqueCode - ); - if (newCardReplacement.data.status == true) { - result = { - code: '461', - message: - 'New card number exists in the card replacement data and cannot be used for card replacement.', - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - - //CHECK NEW CARD - const validCardProductNew = await validateCardProduct( - new_card_number, - uniqueCode - ); - if (validCardProductNew) { - dataCardNew = validCardProductNew.data; - //CARD NOT REGISTERED IN CARD_PRODUCT - if (dataCardNew.status == false) { - return res.status(200).json(validCardProductNew); - } - - dataCardNew = dataCardNew.detail; - const card_new_status = dataCardNew.c_status; - // Status valid => Active (A) - - if (card_new_status != 'P') { - if (card_new_status == 'A') { - result = { - code: '453', - message: 'New card is already activated.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } else if (card_new_status == 'R') { - result = { - code: '454', - message: 'New card is redeemed or replaced.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } else if (card_new_status == 'B') { - result = { - code: '457', - message: 'New card is blacklisted.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } - - //other status - result = { - code: '455', - message: 'New Card not valid for replacement.', - data: { - status: false, - perso_status: true, - detail: detail_card, - }, - }; - return res.status(200).json(result); - } - } - - //Cek tanggal d_valid_date - - //Update Data Replacement - let date_request = dataCardReplacement.d_request; - let date_valid = dataCardReplacement.d_valid_date; - - let now = moment().format('YYYY-MM-DD'); - date_valid = moment(date_valid).format('YYYY-MM-DD'); - date_request = moment(date_request).format('YYYY-MM-DD'); - - if (now < date_valid) { - //other status - result = { - code: '456', - message: 'The valid replacement date is insufficient.', - data: { - status: false, - detail: { - date_now: now, - date_request: date_request, - date_valid: date_valid, - }, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - let i_card_replacement = dataCardReplacement.i_card_replacement; - let dataReplacementUpdate = { - c_status: 'A', - c_status_name: 'COMPLETED', - c_replace_card_no: new_card_number, - }; - //Update Data Card Card Replacement - await model.updateReplacement(i_card_replacement, dataReplacementUpdate); - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ UPDATE DATA REPLACEMENT ]: ${JSON.stringify( - dataReplacementUpdate - )}` - ); - - //Insert Data Detail Replacement - let dataDetailReplacement = { - i_card_replacement: i_card_replacement, - c_old_card_no: card_number, - c_new_card_no: new_card_number, - i_amount: last_balance, - unique_code: uniqueCode, - }; - await model.insertReplacementDetail(dataDetailReplacement); - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ INSERT DATA REPLACEMENT DETAIL ]: ${JSON.stringify( - dataReplacementUpdate - )}` - ); - - //CARD VALID TO REPLACEMENT - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - detail: { - old_card_number: card_number, - new_card_number: new_card_number, - balance: last_balance, - }, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE REPLACEMENT-CONFIRM ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; -const confirmRedeem = async (req, res) => { - try { - let uniqueCode = helper.getUniqueCode(); - let result = {}; - let { card_number, security_code } = req.body; - let dataCardRedeem = {}; - - winston.logger.info(`${uniqueCode} [ REQUEST REDEEM-CONFIRM ]`); - - //CHECK VALIDATOR - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - - //CHECK SECURITY-CODE - if (security_code) { - let securityCodeCompare = await helper.createHMAC(card_number); - - if (security_code !== securityCodeCompare) { - result = { - code: '437', - message: 'bad request. security code does not match.', - data: {}, - }; - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE REDEEM-CONFIRM ]: ${JSON.stringify(result)}` - ); - return res.status(200).json(result); - } - } - - //TRIM CARD NUMBER - card_number = card_number.trim(); - - //CHECK IS CARD ALLOW - const validEnv = await validateEnvironment(card_number, uniqueCode); - if (validEnv) { - // log warn - winston.logger.warn( - `${uniqueCode} [ VALIDATE ENV CARD NUMBER ]: ${JSON.stringify( - validEnv - )}` - ); - res.status(200).json(validEnv); - } - - //CHECK IS CARD BLACKLISTED - let cardBlacklist = await validateBlacklist(card_number, uniqueCode); - if (cardBlacklist) { - // log warn - winston.logger.warn( - `${uniqueCode} [ VALIDATE BLACKLIST CARD NUMBER ]: ${JSON.stringify( - cardBlacklist - )}` - ); - return res.status(200).json(cardBlacklist); - } - - //CARD REPLACEMENT VALIDATION - const validCardReplacement = await checkCardReplacement( - card_number, - uniqueCode - ); - if (validCardReplacement) { - dataCardRedeem = validCardReplacement.data; - //CARD NOT REGISTERED IN CARD_REPLACEMENT - if (dataCardRedeem.status == false) { - return res.status(200).json(validCardReplacement); - } - dataCardRedeem = dataCardRedeem.detail; - - let replacement_redeem_category = - dataCardRedeem.c_replace_redeem_category_code.trim(); - //replacement_redeem_category: R - REDEEM | w - REPLACEMENT WARRANTY | N - REPLACEMENT NON-WARRANTY - if (replacement_redeem_category != 'R') { - result = { - code: '491', - message: 'Card not registered as redeem.', - data: { - status: false, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REDEEM-CONFIRM ]: ${JSON.stringify(result)}` - ); - return res.status(200).json(result); - } - - let redeem_status = dataCardRedeem.c_status.trim(); - //redeem_status: N - NEW | X - CANCELLED | A - COMPLETED - if (redeem_status != 'N') { - if (redeem_status == 'X') { - result = { - code: '406', - message: 'Card replacement status is cancelled.', - data: { - status: false, - detail: {}, - }, - }; - } else if (redeem_status == 'A') { - result = { - code: '407', - message: 'Card has been replaced or redeemed.', - data: { - status: false, - detail: {}, - }, - }; - } else { - result = { - code: '408', - message: 'Redeem or replacement card status not defined.', - data: { - status: false, - detail: {}, - }, - }; - } - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REDEEM-CONFIRM ]: ${JSON.stringify(result)}` - ); - return res.status(200).json(result); - } - } - - //Cek tanggal d_valid_date - //Update Data Replacement - let date_request = dataCardRedeem.d_request; - let date_valid = dataCardRedeem.d_valid_date; - - let now = moment().format('YYYY-MM-DD'); - date_valid = moment(date_valid).format('YYYY-MM-DD'); - date_request = moment(date_request).format('YYYY-MM-DD'); - - if (now < date_valid) { - //other status - result = { - code: '456', - message: 'The valid replacement date is insufficient.', - data: { - status: false, - detail: { - date_now: now, - date_request: date_request, - date_valid: date_valid, - }, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REDEEM-CONFIRM ]: ${JSON.stringify(result)}` - ); - return res.status(200).json(result); - } - - let i_card_replacement = dataCardRedeem.i_card_replacement; - let dataReplacementUpdate = { - c_status: 'A', - c_status_name: 'COMPLETED', - }; - //Update Data Card Card Replacement - await model.updateReplacement(i_card_replacement, dataReplacementUpdate); - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ UPDATE DATA REDEEM ]: ${JSON.stringify( - dataReplacementUpdate - )}` - ); - - //CARD VALID TO REPLACEMENT - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - detail: { - card_number: card_number, - }, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE REPLACEMENT-CONFIRM ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; - -const confirmSales = async (req, res) => { - try { - let uniqueCode = helper.getUniqueCode(); - let result = {}; - - let { - card_number, - sales_status, - device_code, - station_code, - station_name, - created_by, - device_time, - } = req.body; - winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-SALES ]`); - - // CHECK VALIDATOR - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: { - status: false, - detail: {}, - }, - }; - return res.status(200).json(result); - } - - //CARD SALES VALIDATION - const validCardSales = await checkCardSales(card_number, uniqueCode); - if (validCardSales) { - let dataCardSales = validCardSales.data; - if (dataCardSales.status == false) { - return res.status(200).json(validCardSales); - } - let detailCardSales = dataCardSales.detail; - - if (detailCardSales.sales_status != 'SUCCESS') { - //Update Data Sales Temp - let updateDataSales = { - sales_status: sales_status, - device_code: device_code, - station_code: station_code, - station_name: station_name, - created_by: created_by, - device_time: device_time, - }; - // update card_sales - await model.updateSales( - detailCardSales.i_sales_kmt_temp, - updateDataSales - ); - // log debug - winston.logger.debug( - `${uniqueCode} [ UPDATE SALES ${card_number} ]: ${updateDataSales}` - ); - - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - }, - }; - return res.status(200).json(result); - } - } - - //Insert Data Sales Temp - let dataSales = { - card_number: card_number, - sales_status: sales_status, - device_code: device_code, - station_code: station_code, - station_name: station_name, - created_by: created_by, - device_time: device_time, - }; - await model.insertSales(dataSales); - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ INSERT DATA REPLACEMENT DETAIL ]: ${JSON.stringify( - dataSales - )}` - ); - - //Card Sales Confirm OK - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - }, - }; - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE CONFIRM-SALES ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; - -const getLastBalanceCTS = async (req, res) => { - let last_balance; - try { - let uniqueCode = helper.getUniqueCode(); - let result = {}; - // const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance' - const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`; - - winston.logger.info(`${uniqueCode} [ REQUEST GET LAST BALANCE CTS ]`); - - //CARD REPLACEMENT VALIDATION - const dataCard = await model.getCardReplacementScheduler(); - - for (const card of dataCard) { - const payload = { - card_number: card.c_card_no, - }; - - let config = { - headers: { - 'Content-Type': 'application/json', - }, - }; - const url = baseUrl; - const response = await postWithDeadline(url, payload, config); - if (response.data.code == undefined || response.data.code != 200) { - if (response.data.code == 404) { - result = { - code: '494', - message: 'No data found in CTS for the given card number', - data: { - status: false, - detail: {}, - }, - }; - winston.logger.info( - `${uniqueCode} [ FAILED HIT - card_number : ${card.c_card_no} ]: ${response.data.message}` - ); - return res.status(200).json(result); - } - result = { - code: '500', - message: 'CTS service not avaliable', - data: { - status: false, - detail: {}, - }, - }; - winston.logger.info( - `${uniqueCode} [ FAILED HIT - card_number : ${card.c_card_no} ]: ${response.data.message}` - ); - return res.status(200).json(result); - } - last_balance = response.data.data.balance_after; - let dataReplacementUpdate = { - i_last_balance: last_balance, - }; - // update card_replacement - await model.updateReplacementByCardNumber( - card.c_card_no, - dataReplacementUpdate - ); - // log debug - winston.logger.info( - `${uniqueCode} [ GET LAST BALANCE CTS ${card.c_card_no} ]: ${last_balance}` - ); - } - - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - detail: {}, - }, - }; - //LOG-INFO - winston.logger.info( - `${uniqueCode} [ RESPONSE GET LAST BALANCE CTS ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE GET LAST BALANCE CTS ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; -// const getLastBalanceCTS = async (req, res) => { -// try { -// let uniqueCode = helper.getUniqueCode(); -// let result = {}; -// const baseUrl = 'http://127.0.0.1:3000'; - -// console.log( -// `${uniqueCode} [ REQUEST GET LAST BALANCE CTS ]: ${JSON.stringify( -// req.body -// )}` -// ); - -// //CARD REPLACEMENT VALIDATION -// const dataCard = await model.getCardReplacementScheduler(); - -// for (const card of dataCard) { -// const payload = { -// card_number: card.c_card_no, -// }; - -// // ==================== Kalo butuh auth ==================== -// // let auth = req.header('Authorization'); -// // token_api = auth.replace('Bearer ', ''); - -// // const protocol = req.protocol; -// // const host = req.headers.host; -// // const current_url = protocol + '://' + host; - -// // let config = { -// // headers: { -// // 'Content-Type': 'application/json', -// // 'Authorization': 'Bearer ' + token_api -// // }, -// // }; -// // const dataPost = { 'card_number': card_number } -// // const url = current_url + `/api/pos/card-lastbalance`; -// // const resp = await axios.post(url, dataPost, config); - -// const response = await axios.post(baseUrl + '/api/pos/test', payload); -// if ( -// !response.data.code == undefined || -// response.data.data.status == false -// ) { -// result = { -// code: '500', -// message: 'CTS service not avaliable', -// data: { -// status: false, -// detail: {}, -// }, -// }; -// winston.logger.info( -// `${uniqueCode} [ FAILED HIT - card_number : ${card.c_card_no} ]: ${response.data.message}` -// ); -// return res.status(200).json(result); -// } -// last_balance = response.data.data.detail.last_balance; -// let dataReplacementUpdate = { -// i_last_balance: last_balance, -// }; -// // update card_replacement -// await model.updateReplacementByCardNumber( -// card.c_card_no, -// dataReplacementUpdate -// ); -// // log debug -// winston.logger.info( -// `${uniqueCode} [ GET LAST BALANCE CTS ${card.c_card_no} ]: ${last_balance}` -// ); -// } - -// result = { -// code: '00', -// message: 'Successfully.', -// data: { -// status: true, -// detail: {}, -// }, -// }; -// //LOG-INFO -// winston.logger.info( -// `${uniqueCode} [ RESPONSE GET LAST BALANCE CTS ]: ${JSON.stringify( -// result -// )}` -// ); -// return res.status(200).json(result); -// } catch (error) { -// // create log -// winston.logger.error( -// `[ RESPONSE GET LAST BALANCE CTS ]: 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: { -// status: false, -// detail: {}, -// }, -// }); -// } -// }; - -const completeDataSalesInternal = async (req, res) => { - try { - let uniqueCode = helper.getUniqueCode(); - let result = {}; - - winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL ]`); - - // GET PPN FROM GLOBAL PARAMETER - let ppn = await model.getPPNCardSales(); - if (!ppn) { - result = { - code: '400', - message: 'value pajak belum di set', - data: {}, - }; - winston.logger.warn( - `${uniqueCode} [ VALIDATE COMPLETING DATA SALES INTERNAL ] : ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL - PPN ${ppn.c_value} % ]`); - - ppn = parseFloat(ppn.c_value); - - winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL - UPDATE DATA ]`); - - //COMPLETING DATA SALES INTERNAL - const response = await model.completingDataSalesInternal(ppn); - - if (!response.success) { - result = { - code: '400', - message: 'failed update data sales', - data: {}, - }; - winston.logger.warn( - `${uniqueCode} [ VALIDATE COMPLETING DATA SALES INTERNAL ] : ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - result = { - code: '00', - message: 'Successfully.', - data: {}, - }; - - winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL SUCCESS ] code=${result.code}`); - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE COMPLETING DATA SALES INTERNAL ]: 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 completeDataSalesInternalV2 = async (req, res) => { - try { - let uniqueCode = helper.getUniqueCode(); - let result = {}; - - winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL V2 ]`); - - // GET PPN FROM GLOBAL PARAMETER - let ppn = await model.getPPNCardSales(); - if (!ppn) { - result = { - code: '400', - message: 'value pajak belum di set', - data: {}, - }; - winston.logger.warn( - `${uniqueCode} [ VALIDATE COMPLETING DATA SALES INTERNAL V2 ] : ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - ppn = parseFloat(ppn.c_value); - - //COMPLETING DATA SALES INTERNAL - await model.completingDataSalesNewCard(ppn); - await model.completingDataSalesOldCard(ppn); - await model.updateDataSalesIsComplete(); - - result = { - code: '00', - message: 'Successfully.', - data: {}, - }; - - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE COMPLETING DATA SALES INTERNAL V2 ]: 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 testAPI = async (req, res) => { - try { - let result = {}; - let { card_number } = req.body; - let last_balance = '10000'; - - //CARD VALID TO REPLACEMENT - result = { - code: '00', - message: 'Successfully.', - data: { - status: true, - detail: { - card_number: card_number, - last_balance: last_balance, - }, - }, - }; - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE VALIDATE-REPLACEMENT ]: 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: { - status: false, - detail: {}, - }, - }); - } -}; - module.exports = { validate, validateSales, diff --git a/application/modules/reservebalance/reservation-cancel.handlers.js b/application/modules/reservebalance/reservation-cancel.handlers.js new file mode 100644 index 0000000..b446f2f --- /dev/null +++ b/application/modules/reservebalance/reservation-cancel.handlers.js @@ -0,0 +1,1392 @@ +const helper = require('../../helpers/helper'); +const winston = require('../../helpers/winston.logger'); +const { validationResult } = require('express-validator'); +const model = require('./reservebalance.model'); +const moment = require('moment'); + +// Validasi dan eksekusi pembatalan mengikuti aturan masing-masing versi. +const cancelReservationValidate = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { mid, tid, reservation_number } = req.body; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( + req.body + )}` + ); + + // check validator + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE ]: checking partner...` + // ); + + // 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 CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan status reservation number yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE ]: getting reservation by reservation number...` + // ); + + // get reservation berdasarkan reservation number yang di request + let getReservationCanBeCanceled = await model.getReservationCanBeCanceled( + reservation_number + ); + + // jika data reservasi ditemukan + if (getReservationCanBeCanceled) { + // jika status dari reservation number yang di request adalah I = In Progress atau A = Loaded, maka proses cancel reservasi akan di tolak + if ( + getReservationCanBeCanceled.c_status == 'I' || + getReservationCanBeCanceled.c_status == 'A' + ) { + result = { + code: '429', + message: 'can not be cancelled. The transaction has been loaded.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } else if (getReservationCanBeCanceled.c_status == 'X') { + // jika status dari reservation number yang di request adalah X = Deleted, maka proses cancel reservasi akan di tolak + let cancelDate = getReservationCanBeCanceled.d_cancel + ? moment(getReservationCanBeCanceled.d_cancel).format( + 'DD-MM-YYYY HH:mm:ss' + ) + : ''; + result = { + code: '430', + message: `can not be cancelled. The transaction has been canceled at ${cancelDate}.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE cancel reservation validate: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } else if (getReservationCanBeCanceled.c_payment_recon_no) { + // jika reservation number yang di request sudah dilakukan payment recon, maka proses cancel reservasi akan di tolak + result = { + code: '430', + message: `can not be cancelled. The transaction has been recon.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } else { + // jika reservation number yang di request tidak ditemukan di sistem CMS + result = { + code: '414', + message: "Reservation doesn't exist.", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + result = { + code: '00', + message: 'reservation can be canceled.', + data: {}, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE CANCEL-RESERVATION-VALIDATE ]: 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 cancelReservation = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { mid, tid, reservation_number } = req.body; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST CANCEL-RESERVATION ]: ${JSON.stringify( + req.body + )}` + ); + + // check validator + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: 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 CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan status reservation number yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: getting reservation by reservation number...` + // ); + + // get reservation pending & in progress status + let getReservationCanBeCanceled = await model.getReservationCanBeCanceled( + reservation_number + ); + if (getReservationCanBeCanceled) { + if ( + getReservationCanBeCanceled.c_status == 'I' || + getReservationCanBeCanceled.c_status == 'A' + ) { + result = { + code: '429', + message: 'can not be cancelled. The transaction has been loaded.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } else if (getReservationCanBeCanceled.c_status == 'X') { + let cancelDate = getReservationCanBeCanceled.d_cancel + ? moment(getReservationCanBeCanceled.d_cancel).format( + 'DD-MM-YYYY HH:mm:ss' + ) + : ''; + result = { + code: '430', + message: `can not be cancelled. The transaction has been canceled at ${cancelDate}.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } else if (getReservationCanBeCanceled.c_payment_recon_no) { + result = { + code: '430', + message: `can not be cancelled. The transaction has been recon.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } else { + result = { + code: '414', + message: "Reservation doesn't exist.", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: getting last balance on the card by card history...` + // ); + + // get last balance on the card + let balance = 0; + let getLastBalanceFromCardHistory = + await model.getLastBalanceFromCardHistory( + getReservationCanBeCanceled.c_card_number + ); + if (getLastBalanceFromCardHistory) { + balance = getLastBalanceFromCardHistory.m_balance_after; + } + + // time + let now = moment().format('YYYY-MM-DD HH:mm:ss'); + + // binding data + let data = { + c_status: 'X', + c_status_name: 'CANCELED', + d_cancel: now, + }; + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: updating reservation to status cancel...` + // ); + + // cancel transaction + await model.cancelReservation(data, reservation_number); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: inserting log for card history...` + // ); + + // log card history + await model.createReserveBalanceLog({ + i_log_name: 110, + d_log: now, + c_card_number: getReservationCanBeCanceled.c_card_number, + c_source: 'CMS', + c_location: getPartner ? getPartner.partner_name : null, + m_balance_before: balance > 0 ? balance : 0, + m_amount: 0, + m_balance_after: balance > 0 ? balance : 0, + j_new_data: data, + j_old_data: getReservationCanBeCanceled, + c_note: `CANCEL RESERVE BALANCE ${getReservationCanBeCanceled.i_reservation_amount + } FROM ${getPartner ? getPartner.partner_name : null}`, + c_status: 'S', + d_created: now, + i_create: null, + c_create_username: 'HSM', + c_create_fullname: 'HARDWARE SECURE MODULE', + c_category: 'T', + }); + + result = { + code: '00', + message: 'reservation successfully canceled.', + data: {}, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE CANCEL-RESERVATION ]: 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 cancelReservationValidateV2 = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { mid, tid, reservation_number, ref_no } = req.body; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + req.body + )}` + ); + + // check validator + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ]: 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 CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + let getReservationCanBeCanceled; + + // jika cancelation reservation dilakukan dengan menggunakan ref no + if (ref_no) { + if (!ref_no) { + result = { + code: '400', + message: 'Ref no is required', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan status reservation number yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ]: getting reservation by ref no...` + // ); + + // get reservation berdasarkan ref_no yang di request + getReservationCanBeCanceled = + await model.getReservationCanBeCanceledByRefno(ref_no); + + if (!getReservationCanBeCanceled) { + result = { + code: '440', + message: "Ref no doesn't exist.", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + } else { + if (!reservation_number) { + result = { + code: '400', + message: 'Reservation number is required', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan status reservation number yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ]: getting reservation by reservation number...` + // ); + + // get reservation berdasarkan reservation number yang di request + getReservationCanBeCanceled = await model.getReservationCanBeCanceled( + reservation_number + ); + + if (!getReservationCanBeCanceled) { + result = { + code: '414', + message: "Reservation doesn't exist.", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + } + + let reservationNumber = getReservationCanBeCanceled?.c_reservation_no; + let cardNumber = getReservationCanBeCanceled?.c_card_number; + let amount = getReservationCanBeCanceled?.i_reservation_amount; + + // get value global parameter + let getGlobalParameter = await model.getGlobalParameter(); + // check value global parameter + if (!getGlobalParameter) { + result = { + code: '439', + message: 'HSM_CANCEL_RESERVATION_LEVEL in global parameter not found', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + return res.status(200).json(result); + } + // validasi sesuai value global parameter + if (getGlobalParameter.c_value == 'PARTNER') { + if (getPartner.i_partner != getReservationCanBeCanceled.i_partner) { + result = { + code: '438', + message: 'Can not be canceled on different source', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } else if (getGlobalParameter.c_value == 'MERCHANT') { + if (getPartner.i_merchant != getReservationCanBeCanceled.i_merchant) { + result = { + code: '438', + message: 'Can not be canceled on different source', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } else if (getGlobalParameter.c_value == 'TERMINAL') { + if (getPartner.i_terminal != getReservationCanBeCanceled.i_terminal) { + result = { + code: '438', + message: 'Can not be canceled on different source', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } + + // jika data reservasi ditemukan + if (getReservationCanBeCanceled) { + // jika status dari reservation number yang di request adalah I = In Progress atau A = Loaded, maka proses cancel reservasi akan di tolak + if ( + getReservationCanBeCanceled.c_status == 'I' || + getReservationCanBeCanceled.c_status == 'A' + ) { + result = { + code: '429', + message: 'can not be cancelled. The transaction has been loaded.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } else if (getReservationCanBeCanceled.c_status == 'X') { + // jika status dari reservation number yang di request adalah X = Deleted, maka proses cancel reservasi akan di tolak + let cancelDate = getReservationCanBeCanceled.d_cancel + ? moment(getReservationCanBeCanceled.d_cancel).format( + 'DD-MM-YYYY HH:mm:ss' + ) + : ''; + result = { + code: '430', + message: `can not be cancelled. The transaction has been canceled at ${cancelDate}.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } else if (getReservationCanBeCanceled.c_payment_recon_no) { + // jika reservation number yang di request sudah dilakukan payment recon, maka proses cancel reservasi akan di tolak + result = { + code: '430', + message: `can not be cancelled. The transaction has been recon.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } else { + // jika reservation number yang di request tidak ditemukan di sistem CMS + result = { + code: '414', + message: "Reservation doesn't exist.", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // time + let now = moment().format('YYYY-MM-DD HH:mm:ss'); + + // create security code yang isinya data reservasi yang akan di compare nantinya saat melakukan insert reservation + let securityCode = await helper.createHMAC( + mid + '|' + tid + '|' + reservationNumber + ); + + let reservationData = { + mid: mid, + tid: tid, + reservation_number: reservationNumber, + transaction_date: now, + security_code: securityCode, + }; + + // log debug + // process enkripsi data reservasi dengan AES yang nanti nya akan di kirim ke end point reservation api untuk menyimpan data reservasi + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ] encrypting data reservation: ${JSON.stringify( + // reservationData + // )}` + // ); + + // enkripsi data reservasi sebelum melakukan transaksi reservasi + let hash = helper.encryptText(JSON.stringify(reservationData)); + + result = { + code: '00', + message: 'reservation can be canceled.', + data: { + cancel_reservation_data: hash, + cancel_reservation_detail: { + reservation_number: reservationNumber, + card_number: cardNumber, + amount: amount, + }, + }, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: 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 cancelReservationV2 = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { cancel_reservation_data } = req.body; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST CANCEL-RESERVATION ]: ${JSON.stringify( + req.body + )}` + ); + + // check validator + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + let cancelReservationData; + + try { + cancelReservationData = helper.decryptText(cancel_reservation_data); + } catch (error) { } + + if (!cancelReservationData) { + result = { + code: '435', + message: 'bad request. reservation data is invalid.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // parsing data to json format + cancelReservationData = JSON.parse(cancelReservationData); + + if ( + !cancelReservationData.mid || + !cancelReservationData.tid || + !cancelReservationData.reservation_number || + !cancelReservationData.transaction_date + ) { + result = { + code: '436', + message: 'bad request. reservation data is empty.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: checking partner...` + // ); + + // get partner, merchant, terminal from tid + let getPartner = await model.getPartner( + cancelReservationData.mid, + cancelReservationData.tid + ); + if (!getPartner) { + result = { + code: '412', + message: 'terminal id is not valid', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan status reservation number yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: getting reservation by reservation number...` + // ); + + // get reservation pending & in progress status + let getReservationCanBeCanceled = await model.getReservationCanBeCanceled( + cancelReservationData.reservation_number + ); + if (getReservationCanBeCanceled) { + if ( + getReservationCanBeCanceled.c_status == 'I' || + getReservationCanBeCanceled.c_status == 'A' + ) { + result = { + code: '429', + message: 'can not be cancelled. The transaction has been loaded.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } else if (getReservationCanBeCanceled.c_status == 'X') { + let cancelDate = getReservationCanBeCanceled.d_cancel + ? moment(getReservationCanBeCanceled.d_cancel).format( + 'DD-MM-YYYY HH:mm:ss' + ) + : ''; + result = { + code: '430', + message: `can not be cancelled. The transaction has been canceled at ${cancelDate}.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } else if (getReservationCanBeCanceled.c_payment_recon_no) { + result = { + code: '430', + message: `can not be cancelled. The transaction has been recon.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } else { + result = { + code: '414', + message: "Reservation doesn't exist.", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: getting last balance on the card by card history...` + // ); + + // get last balance on the card + let balance = 0; + let getLastBalanceFromCardHistory = + await model.getLastBalanceFromCardHistory( + getReservationCanBeCanceled.c_card_number + ); + if (getLastBalanceFromCardHistory) { + balance = getLastBalanceFromCardHistory.m_balance_after; + } + + // time + let now = moment().format('YYYY-MM-DD HH:mm:ss'); + + // binding data + let data = { + c_status: 'X', + c_status_name: 'CANCELED', + d_cancel: now, + }; + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: updating reservation to status cancel...` + // ); + + // cancel transaction + await model.cancelReservation( + data, + cancelReservationData.reservation_number + ); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: inserting log for card history...` + // ); + + // log card history + await model.createReserveBalanceLog({ + i_log_name: 110, + d_log: now, + c_card_number: getReservationCanBeCanceled.c_card_number, + c_source: 'CMS', + c_location: getPartner ? getPartner.partner_name : null, + m_balance_before: balance > 0 ? balance : 0, + m_amount: 0, + m_balance_after: balance > 0 ? balance : 0, + j_new_data: data, + j_old_data: getReservationCanBeCanceled, + c_note: `CANCEL RESERVE BALANCE ${getReservationCanBeCanceled.i_reservation_amount + } FROM ${getPartner ? getPartner.partner_name : null}`, + c_status: 'S', + d_created: now, + i_create: null, + c_create_username: 'HSM', + c_create_fullname: 'HARDWARE SECURE MODULE', + c_category: 'T', + }); + + result = { + code: '00', + message: 'reservation successfully canceled.', + data: { + reservation_number: getReservationCanBeCanceled.c_reservation_no, + reservation_amount: getReservationCanBeCanceled.i_reservation_amount, + }, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE CANCEL-RESERVATION ]: 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 cancelReservationV2_1 = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { mid, tid, reservation_number } = req.body; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( + req.body + )}` + ); + + // check validator + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: 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 CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + // log debug + // proses pengecekkan status reservation number yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: getting reservation by reservation number...` + // ); + + // get reservation berdasarkan reservation number yang di request + let getReservationCanBeCanceled = await model.getReservationCanBeCanceled( + reservation_number + ); + + // jika data reservasi ditemukan + if (getReservationCanBeCanceled) { + // jika status dari reservation number yang di request adalah I = In Progress atau A = Loaded, maka proses cancel reservasi akan di tolak + if ( + getReservationCanBeCanceled.c_status == 'I' || + getReservationCanBeCanceled.c_status == 'A' + ) { + result = { + code: '429', + message: 'can not be cancelled. The transaction has been loaded.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } else if (getReservationCanBeCanceled.c_status == 'X') { + // jika status dari reservation number yang di request adalah X = Deleted, maka proses cancel reservasi akan di tolak + let cancelDate = getReservationCanBeCanceled.d_cancel + ? moment(getReservationCanBeCanceled.d_cancel).format( + 'DD-MM-YYYY HH:mm:ss' + ) + : ''; + result = { + code: '430', + message: `can not be cancelled. The transaction has been canceled at ${cancelDate}.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE cancel reservation validate: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } else if (getReservationCanBeCanceled.c_payment_recon_no) { + // jika reservation number yang di request sudah dilakukan payment recon, maka proses cancel reservasi akan di tolak + result = { + code: '430', + message: `can not be cancelled. The transaction has been recon.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } else { + // jika reservation number yang di request tidak ditemukan di sistem CMS + result = { + code: '414', + message: "Reservation doesn't exist.", + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses checking partner yang request cancel dengan data reservasi yang mau di cancel apakah dari partner yang sama + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: checking partner request with partner reservation...` + // ); + + if (getPartner.i_partner != getReservationCanBeCanceled.i_partner) { + // partner yang request cancel tidak sama dengan partner dari data reservasi + result = { + code: '438', + message: `can not be cancelled on different source.`, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: getting last balance on the card by card history...` + // ); + + // get last balance on the card + let balance = 0; + let getLastBalanceFromCardHistory = + await model.getLastBalanceFromCardHistory( + getReservationCanBeCanceled.c_card_number + ); + if (getLastBalanceFromCardHistory) { + balance = getLastBalanceFromCardHistory.m_balance_after; + } + + // time + let now = moment().format('YYYY-MM-DD HH:mm:ss'); + + // binding data + let data = { + c_status: 'X', + c_status_name: 'CANCELED', + d_cancel: now, + }; + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: updating reservation to status cancel...` + // ); + + // cancel transaction + await model.cancelReservation(data, reservation_number); + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: inserting log for card history...` + // ); + + // log card history + await model.createReserveBalanceLog({ + i_log_name: 110, + d_log: now, + c_card_number: getReservationCanBeCanceled.c_card_number, + c_source: 'CMS', + c_location: getPartner ? getPartner.partner_name : null, + m_balance_before: balance > 0 ? balance : 0, + m_amount: 0, + m_balance_after: balance > 0 ? balance : 0, + j_new_data: data, + j_old_data: getReservationCanBeCanceled, + c_note: `CANCEL RESERVE BALANCE ${getReservationCanBeCanceled.i_reservation_amount + } FROM ${getPartner ? getPartner.partner_name : null}`, + c_status: 'S', + d_created: now, + i_create: null, + c_create_username: 'HSM', + c_create_fullname: 'HARDWARE SECURE MODULE', + c_category: 'T', + }); + + result = { + code: '00', + message: 'reservation successfully canceled.', + data: {}, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE CANCEL-RESERVATION-V2.1 ]: 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: {}, + }); + } +}; + +module.exports = { cancelReservationValidate, cancelReservation, cancelReservationValidateV2, cancelReservationV2, cancelReservationV2_1 }; diff --git a/application/modules/reservebalance/reservation-create.handlers.js b/application/modules/reservebalance/reservation-create.handlers.js new file mode 100644 index 0000000..530085d --- /dev/null +++ b/application/modules/reservebalance/reservation-create.handlers.js @@ -0,0 +1,2250 @@ +const helper = require('../../helpers/helper'); +const winston = require('../../helpers/winston.logger'); +const { validationResult } = require('express-validator'); +const model = require('./reservebalance.model'); +const moment = require('moment'); + +// Pertahankan alur validasi dan pembuatan reservasi untuk klien V1 dan V2. +const reservationValidate = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { mid, tid, card_number, amount } = req.body; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST RESERVATION-VALIDATE ]: ${JSON.stringify( + req.body + )}` + ); + + // trim card number + card_number = card_number.trim(); + + // check validator + let 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); + } + + // log debug + // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. + // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya + // Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking production card number or not...` + // ); + + let cardBlacklist = await model.getCardBlacklist(card_number); + if (cardBlacklist) { + if (cardBlacklist.c_status == 'B') { + result = { + code: '445', + message: 'Card is Blacklisted', + data: {}, + }; + return res.status(200).json(result); + } + } + + // jika settingan diperuntukan untuk production + // if (process.env.SERVER_FOR == 'production') { + // // kartu yang di request bukan kartu production maka akan di tolak + // if (card_number.substring(0, 1) != '1') { + // result = { + // code: '400', + // message: "It's not production card number.", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE ]: ${JSON.stringify( + // result + // )}` + // ); + + // return res.status(200).json(result); + // } + // } else { + // // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak + // if (card_number.substring(0, 1) == '1') { + // result = { + // code: '400', + // message: + // "It's production card number. Please use the development card number.", + // 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 + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking partner...` + // ); + + // get partner, merchant, terminal from tid + let getPartner = await model.getPartner(mid, tid); + + // jika partner (mid atau tid) tidak ditemukan atau tidak terdaftar di sistem CMS + if (!getPartner) { + result = { + code: '412', + message: 'terminal id is not valid', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + // log debug + // get settingan dari parameter apakah nomor kartu yang di request harus di cek dengan data card product CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] getting checking card number by card product CMS status on parameter...` + // ); + + // get parameter to check with card product cms or not + let getCheckByCardProductStatusValue = + await model.getCheckByCardProductStatusValue(); + let checkByCardProductStatusValue = + getCheckByCardProductStatusValue?.c_value; + + // jika settingan pengecekkan nomor kartu yang di request dengan data card product yang ada di sistem CMS aktif + if (checkByCardProductStatusValue == 'A') { + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking card number...` + // ); + + // check card number yang di request terdaftar di card product CMS atau tidak + let checkCardNumber = await model.checkCardNumber(card_number); + + // jika nomor kartu yang di request tidak terdaftar di card prouct CMS + 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} [ PROCESSING RESERVATION-VALIDATE ] checking reservation amount...` + // ); + + // check reservation amount + // amount reservasi harus lebih dari 0 + 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 + // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] 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} [ PROCESSING RESERVATION-VALIDATE ] checking BI regulation status...` + // ); + + // get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak + let getBIRegulationStatus = await model.getBIRegulationStatus(); + + // jika pengecekkan regulasi BI diaktifkan + if (getBIRegulationStatus.c_value == 'A') { + // log debug + // get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking max balance on the card...` + // ); + + // get max saldo on the card + let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); + + // jika settingan paremeter maksimum saldo di dalam kartu ditemukan + if (getMaxAmountOnTheCard.c_value) { + // jika saldo dalam kartu diakumulasikan dengan amount reservasi dan jumlah nya ternyata melebihi jumlah maksimum saldo berdasarkan settingan parameter, maka akan transaksi akan di tolak + 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 + // proses pengecekkan akumulasi maksimum topup di bulan berjalan berdasarkan parameter setting di sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking max topup per month...` + // ); + + // get accumulated balance in this month dari nomor kartu yang di request + let accumulatedBalance = 0; + let getAccumulationBalanceInThisMonthFromCardHistory = + await model.getAccumulationBalanceInThisMonthFromCardHistory( + card_number, + year, + month + ); + + // jika ditemukan history akumulasi topup dari nomor kartu yang di request, maka set akumulasi saldo di bulan berjalan sama dengan history yang ditemukan + if (getAccumulationBalanceInThisMonthFromCardHistory) { + accumulatedBalance = + getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; + } + + // validate max topup per month berdasarkan parameter setting + let getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); + + // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan + if (getMaxTopupPerMonth.c_value) { + // jika akumulasi saldo kartu yang di request dijumlahkan dengan amount reservasi dan ternyata melebihi jumlah akumulasi maksumum topup dalam sebelum, maka transaksi akan di tolak + 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 + // proses pengecekkan maksimum reservasi dengna status pending di parameter setting sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking max reservation...` + // ); + + // get maksimum reservation dengan status pending dari parameter setting + let getMaxReservation = await model.getMaxReservation(); + + // jika parameter setting maksimum reservasi dengan status pending tidak ditemukan maka set menjadi 0 + let maxReservation = getMaxReservation.c_value + ? parseInt(getMaxReservation.c_value) + : 0; + + // log debug + // proses pencarian transaki dari table reservasi balance berdasarkan nomor kartu yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking total reservation pending...` + // ); + + // get total reservation pending bersarkan nomor kartu yang di request yaitu total transaksi yang status nya pending beserta jumlah amount nya + let getReservationPending = await model.getReservationPending( + card_number, + now + ); + + // jika nomor kartu yang di request ditemukan transaksi reservasi dengan status pending pada transaksi sebelumnya, maka jumlahkan total amount reservasi sebelumnya dengan amount reservasi yang dilakukan sekarang + let totalReservationPending = + getReservationPending.total_nominal_reservation > 0 + ? parseInt(getReservationPending.total_nominal_reservation) + + parseInt(amount) + : parseInt(amount); + + // jika total amount reservasi melebihi maksimum reservasi sesuai dengan parameter setting di sistem CMS maka transaksi akan di tolak + 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 + // process mendapatkan persentase issuer fee dan channel free berdasarkan settingan dari sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] getting issuer fee and channel fee...` + // ); + + // set default issuer fee + let issuerFee = 0; + let channelFee = 0; + + // get issuer fee dan channel fee dari table public.t_c_partner_fee + let getIssuer = await model.getIssuer(getPartner.i_partner, now); + + if (getIssuer) { + // per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi + if (today >= '2023-11-01') { + issuerFee = getIssuer.i_issuer_fee_nominal; + channelFee = getIssuer.i_channel_fee_nominal; + } else { + // ======================= KHUSUS LRT JABODEBEK ============================= + if (getPartner.partner_code == 'P05') { + issuerFee = getIssuer.i_issuer_fee_nominal; + channelFee = getIssuer.i_channel_fee_nominal; + } else { + // SELAIN LRT JABODEBEK + issuerFee = + (getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); + channelFee = + (getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); + } + } + } + // if (!getIssuer) { + // return res.status(200).json({ + // code: "403", + // message: "issuer doesn't exist", + // data: {}, + // }); + // } + + result = { + code: '00', + message: 'validation successfully.', + data: { + issuer_fee: issuerFee, + channel_fee: channelFee, + }, + }; + + // 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( + `[ RESPONSE RESERVATION-VALIDATE ]: 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 reservationValidateV2 = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { mid, tid, card_number, amount } = req.body; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + req.body + )}` + ); + + // trim card number + // card_number = card_number.trim(); + + // check validator + let 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-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + let cardBlacklist = await model.getCardBlacklist(card_number); + if (cardBlacklist) { + if (cardBlacklist.c_status == 'B') { + result = { + code: '445', + message: 'Card is Blacklisted', + data: {}, + }; + return res.status(200).json(result); + } + } + + // log debug + // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. + // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya + // Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking production card number or not...` + // ); + + // jika settingan diperuntukan untuk production + // if (process.env.SERVER_FOR == 'production') { + // // kartu yang di request bukan kartu production maka akan di tolak + // if (card_number.substring(0, 1) != '1') { + // result = { + // code: '400', + // message: "It's not production card number.", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + // result + // )}` + // ); + + // return res.status(200).json(result); + // } + // } else { + // // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak + // if (card_number.substring(0, 1) == '1') { + // result = { + // code: '400', + // message: + // "It's production card number. Please use the development card number.", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${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 + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking partner...` + // ); + + // get partner, merchant, terminal from tid + let getPartner = await model.getPartner(mid, tid); + + // jika partner (mid atau tid) tidak ditemukan atau tidak terdaftar di sistem CMS + if (!getPartner) { + result = { + code: '412', + message: 'terminal id is not valid', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + // log debug + // get settingan dari parameter apakah nomor kartu yang di request harus di cek dengan data card product CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] getting checking card number by card product CMS status on parameter...` + // ); + + // get parameter to check with card product cms or not + let getCheckByCardProductStatusValue = + await model.getCheckByCardProductStatusValue(); + let checkByCardProductStatusValue = + getCheckByCardProductStatusValue?.c_value; + + // jika settingan pengecekkan nomor kartu yang di request dengan data card product yang ada di sistem CMS aktif + if (checkByCardProductStatusValue == 'A') { + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking card number...` + // ); + + // check card number yang di request terdaftar di card product CMS atau tidak + let checkCardNumber = await model.checkCardNumber(card_number); + + // jika nomor kartu yang di request tidak terdaftar di card prouct CMS + if (!checkCardNumber) { + result = { + code: '413', + message: 'card number is not registered', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking reservation amount...` + // ); + + // check reservation amount + // amount reservasi harus lebih dari 0 + if (parseInt(amount) <= 0) { + result = { + code: '415', + message: 'amount must be greater than 0', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] 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} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking BI regulation status...` + // ); + + // get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak + let getBIRegulationStatus = await model.getBIRegulationStatus(); + + // jika pengecekkan regulasi BI diaktifkan + if (getBIRegulationStatus.c_value == 'A') { + // log debug + // get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking max balance on the card...` + // ); + + // get max saldo on the card + let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); + + // jika settingan paremeter maksimum saldo di dalam kartu ditemukan + if (getMaxAmountOnTheCard.c_value) { + // jika saldo dalam kartu diakumulasikan dengan amount reservasi dan jumlah nya ternyata melebihi jumlah maksimum saldo berdasarkan settingan parameter, maka akan transaksi akan di tolak + 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-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } + + // log debug + // proses pengecekkan akumulasi maksimum topup di bulan berjalan berdasarkan parameter setting di sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking max topup per month...` + // ); + + // get accumulated balance in this month dari nomor kartu yang di request + let accumulatedBalance = 0; + let getAccumulationBalanceInThisMonthFromCardHistory = + await model.getAccumulationBalanceInThisMonthFromCardHistory( + card_number, + year, + month + ); + + // jika ditemukan history akumulasi topup dari nomor kartu yang di request, maka set akumulasi saldo di bulan berjalan sama dengan history yang ditemukan + if (getAccumulationBalanceInThisMonthFromCardHistory) { + accumulatedBalance = + getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; + } + + // validate max topup per month berdasarkan parameter setting + let getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); + + // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan + if (getMaxTopupPerMonth.c_value) { + // jika akumulasi saldo kartu yang di request dijumlahkan dengan amount reservasi dan ternyata melebihi jumlah akumulasi maksumum topup dalam sebelum, maka transaksi akan di tolak + 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-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } + } + + // log debug + // proses pengecekkan maksimum reservasi dengna status pending di parameter setting sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking max reservation...` + // ); + + // get maksimum reservation dengan status pending dari parameter setting + let getMaxReservation = await model.getMaxReservation(); + + // jika parameter setting maksimum reservasi dengan status pending tidak ditemukan maka set menjadi 0 + let maxReservation = getMaxReservation.c_value + ? parseInt(getMaxReservation.c_value) + : 0; + + // log debug + // proses pencarian transaki dari table reservasi balance berdasarkan nomor kartu yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking total reservation pending...` + // ); + + // get total reservation pending bersarkan nomor kartu yang di request yaitu total transaksi yang status nya pending beserta jumlah amount nya + let getReservationPending = await model.getReservationPendingV2( + card_number, + now + ); + + let dataReservationPending = []; + let totalNominalReservationPending = 0; + if (getReservationPending.length > 0) { + for (let item of getReservationPending) { + // hitung total reservasi yang masih pending / belum di topup + totalNominalReservationPending = + totalNominalReservationPending + parseInt(item.i_reservation_amount); + + dataReservationPending.push({ + reservation_date: item.d_reservation, + amount: parseInt(item.i_reservation_amount), + partner_name: item.c_partner_name, + }); + } + } + + // jika nomor kartu yang di request ditemukan transaksi reservasi dengan status pending pada transaksi sebelumnya, maka jumlahkan total amount reservasi sebelumnya dengan amount reservasi yang dilakukan sekarang + let totalReservationPending = + totalNominalReservationPending > 0 + ? parseInt(totalNominalReservationPending) + parseInt(amount) + : parseInt(amount); + + // jika total amount reservasi melebihi maksimum reservasi sesuai dengan parameter setting di sistem CMS maka transaksi akan di tolak + 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-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // process mendapatkan persentase issuer fee dan channel free berdasarkan settingan dari sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] getting issuer fee and channel fee...` + // ); + + // set default issuer fee + let issuerFee = 0; + let channelFee = 0; + + // get issuer fee dan channel fee dari table public.t_c_partner_fee + let getIssuer = await model.getIssuer(getPartner.i_partner, now); + + if (getIssuer) { + // per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi + if (today >= '2023-11-01') { + issuerFee = getIssuer.i_issuer_fee_nominal; + channelFee = getIssuer.i_channel_fee_nominal; + } else { + // ======================= KHUSUS LRT JABODEBEK ============================= + if (getPartner.partner_code == 'P05') { + issuerFee = getIssuer.i_issuer_fee_nominal; + channelFee = getIssuer.i_channel_fee_nominal; + } else { + // SELAIN LRT JABODEBEK + issuerFee = + (getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); + channelFee = + (getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); + } + } + } + + // if (!getIssuer) { + // return res.status(200).json({ + // code: "403", + // message: "issuer doesn't exist", + // data: {}, + // }); + // } + + // log debug + // process enkripsi data reservasi dengan HMAC yang nanti nya akan di kirim ke end point reservation api sebagai pembanding bahwa data yang sudah di enkripsi tidak dimanipulasi + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] generating security code from data reservation` + // ); + + // create security code yang isinya data reservasi yang akan di compare nantinya saat melakukan insert reservation + let securityCode = await helper.createHMAC( + mid + '|' + tid + '|' + card_number + '|' + amount + ); + + let reservationData = { + mid: mid, + tid: tid, + card_number: card_number, + amount: amount, + transaction_date: now, + security_code: securityCode, + }; + + // log debug + // process enkripsi data reservasi dengan AES yang nanti nya akan di kirim ke end point reservation api untuk menyimpan data reservasi + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] encrypting data reservation: ${JSON.stringify( + // reservationData + // )}` + // ); + + // enkripsi data reservasi sebelum melakukan transaksi reservasi + let hash = helper.encryptText(JSON.stringify(reservationData)); + + result = { + code: '00', + message: 'validation successfully.', + data: { + reservation_data: hash, + reservation_detail: { + card_number: card_number, + amount: amount, + issuer_fee: issuerFee, + channel_fee: channelFee, + }, + reservation_pending: dataReservationPending, + }, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE RESERVATION-VALIDATE-V2 ]: 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 reservation = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { mid, tid, card_number, amount, ref_no, customer_name, phone_number } = + req.body; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST RESERVATION ]: ${JSON.stringify(req.body)}` + ); + + // trim card number + card_number = card_number.trim(); + + // check validator + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // log debug + // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. + // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya + // Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] checking production card number or not...` + // ); + + let cardBlacklist = await model.getCardBlacklist(card_number); + if (cardBlacklist) { + if (cardBlacklist.c_status == 'B') { + result = { + code: '445', + message: 'Card is Blacklisted', + data: {}, + }; + return res.status(200).json(result); + } + } + + // jika settingan diperuntukan untuk production + // if (process.env.SERVER_FOR == 'production') { + // // kartu yang di request bukan kartu production maka akan di tolak + // if (card_number.substring(0, 1) != '1') { + // result = { + // code: '400', + // message: "It's not production card number.", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` + // ); + + // return res.status(200).json(result); + // } + // } else { + // // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak + // if (card_number.substring(0, 1) == '1') { + // result = { + // code: '400', + // message: + // "It's production card number. Please use the development card number.", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE RESERVATION ]: ${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 + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] 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 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + // log debug + // get settingan dari parameter apakah nomor kartu yang di request harus di cek dengan data card product CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] getting checking card number by card product CMS status on parameter...` + // ); + + // get parameter to check with card product cms or not + let getCheckByCardProductStatusValue = + await model.getCheckByCardProductStatusValue(); + let checkByCardProductStatusValue = + getCheckByCardProductStatusValue?.c_value; + + // jika settingan pengecekkan nomor kartu yang di request dengan data card product yang ada di sistem CMS aktif + if (checkByCardProductStatusValue == 'A') { + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] checking card number...` + // ); + + // check card number yang di request terdaftar di card product CMS atau tidak + 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 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] checking reservation amount...` + // ); + + // check reservation amount + // amount reservasi harus lebih dari 0 + if (parseInt(amount) <= 0) { + result = { + code: '415', + message: 'amount must be greater than 0', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] 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} [ PROCESSING RESERVATION ] checking BI regulation status...` + // ); + + // get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak + let getBIRegulationStatus = await model.getBIRegulationStatus(); + if (getBIRegulationStatus.c_value == 'A') { + // log debug + // get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] checking max balance on the card...` + // ); + + // get max saldo on the card + let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); + // jika settingan paremeter maksimum saldo di dalam kartu ditemukan + if (getMaxAmountOnTheCard.c_value) { + // jika saldo dalam kartu diakumulasikan dengan amount reservasi dan jumlah nya ternyata melebihi jumlah maksimum saldo berdasarkan settingan parameter, maka akan transaksi akan di tolak + 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 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } + + // log debug + // proses pengecekkan akumulasi maksimum topup di bulan berjalan berdasarkan parameter setting di sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] checking max topup per month...` + // ); + + // get accumulated balance in this month dari nomor kartu yang di request + let accumulatedBalance = 0; + let getAccumulationBalanceInThisMonthFromCardHistory = + await model.getAccumulationBalanceInThisMonthFromCardHistory( + card_number, + year, + month + ); + + // jika ditemukan history akumulasi topup dari nomor kartu yang di request, maka set akumulasi saldo di bulan berjalan sama dengan history yang ditemukan + if (getAccumulationBalanceInThisMonthFromCardHistory) { + accumulatedBalance = + getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; + } + + // validate max topup per month berdasarkan parameter setting + let getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); + + // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan + if (getMaxTopupPerMonth.c_value) { + // jika akumulasi saldo kartu yang di request dijumlahkan dengan amount reservasi dan ternyata melebihi jumlah akumulasi maksumum topup dalam sebelum, maka transaksi akan di tolak + 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 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } + } + + // log debug + // proses pengecekkan maksimum reservasi dengna status pending di parameter setting sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] checking max reservation...` + // ); + + // get maksimum reservation dengan status pending dari parameter setting + let getMaxReservation = await model.getMaxReservation(); + let maxReservation = getMaxReservation.c_value + ? parseInt(getMaxReservation.c_value) + : 0; + + // // log debug + // winston.logger.debug(`${uniqueCode} [ PROCESSING RESERVATION ] checking reservation with flag...`); + + // // get reservation with flag + // let reservationWithFlag = await model.getReservationWithFlag( + // card_number, + // now + // ); + // let totalReservationWithFlag = + // reservationWithFlag.total_reservation > 0 + // ? reservationWithFlag.total_reservation + // : 0; + // if (totalReservationWithFlag > 0) { + // result = { + // code: "420", + // message: + // "your card number has incomplete transaction. Please unload your balance!", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` + // ); + + // return res.status(200).json(result); + // } + + // log debug + // proses pencarian transaki dari table reservasi balance berdasarkan nomor kartu yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] checking total reservation pending...` + // ); + + // get total reservation pending bersarkan nomor kartu yang di request yaitu total transaksi yang status nya pending beserta jumlah amount nya + let getReservationPending = await model.getReservationPending( + card_number, + now + ); + + // jika nomor kartu yang di request ditemukan transaksi reservasi dengan status pending pada transaksi sebelumnya, maka jumlahkan total amount reservasi sebelumnya dengan amount reservasi yang dilakukan sekarang + let totalReservationPending = + getReservationPending.total_nominal_reservation > 0 + ? parseInt(getReservationPending.total_nominal_reservation) + + parseInt(amount) + : parseInt(amount); + + // jika total amount reservasi melebihi maksimum reservasi sesuai dengan parameter setting di sistem CMS maka transaksi akan di tolak + 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 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // log debug + // process mendapatkan persentase issuer fee dan channel free berdasarkan settingan dari sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] getting issuer fee and channel fee...` + // ); + + // set default issuer fee + let issuerFee = 0; + let channelFee = 0; + + // get issuer fee dan channel fee dari table public.t_c_partner_fee + let getIssuer = await model.getIssuer(getPartner.i_partner, now); + + if (getIssuer) { + // per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi + if (today >= '2023-11-01') { + issuerFee = getIssuer.i_issuer_fee_nominal; + channelFee = getIssuer.i_channel_fee_nominal; + } else { + // ======================= KHUSUS LRT JABODEBEK ============================= + if (getPartner.partner_code == 'P05') { + issuerFee = getIssuer.i_issuer_fee_nominal; + channelFee = getIssuer.i_channel_fee_nominal; + } else { + // SELAIN LRT JABODEBEK + issuerFee = + (getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); + channelFee = + (getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); + } + } + } + + // if (!getIssuer) { + // return res.status(200).json({ + // code: "403", + // message: "issuer doesn't exist", + // data: {}, + // }); + // } + + // log debug + // proses pengecekkan value dari setting parameter untuk data reservasi yang tidak di load/topup apakah statusnya diaktifkan atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] getting reservation expiration date on parameter...` + // ); + + const { time, measure } = await model.getReservationExpiration(); + let expired = moment(now).add(time, measure).format('YYYY-MM-DD HH:mm:ss'); + + // -------------------------------- NOTES -------------------------------- + // for LRT JABO => customer_name diisi Device Name (versi penamaan LRT Jabo) dan phone_number diisi Device Code (versi kode LRT Jabo) sesuai MOM BI-WEEKLY MEETING (08/05/2023) + let customerName = customer_name; + let phoneNumber = phone_number; + + if (!customerName || customerName == '' || customerName == '-') { + customerName = getPartner ? getPartner.terminal_name : ''; + } + + if (!phoneNumber || phoneNumber == '' || phoneNumber == '-') { + phoneNumber = mid + '_' + tid; + } + + const { number: reservationNumber, sequence: reservationNoSequence } = + await model.allocateReservationNumber(getPartner.partner_code, moment(now).format('YYMMDD')); + + // binding data + let data = { + c_reservation_no: reservationNumber, + d_reservation: now, + c_ref_no: ref_no, + i_partner: getPartner ? getPartner.i_partner : null, + c_partner_code: getPartner ? getPartner.partner_code : null, + c_partner_name: getPartner ? getPartner.partner_name : null, + i_merchant: getPartner ? getPartner.i_merchant : null, + c_merchant_code: getPartner ? getPartner.merchant_code : null, + c_merchant_name: getPartner ? getPartner.merchant_name : null, + c_mid: getPartner ? getPartner.mid : null, + i_terminal: getPartner ? getPartner.i_terminal : null, + c_terminal_code: getPartner ? getPartner.terminal_code : null, + c_terminal_name: getPartner ? getPartner.terminal_name : null, + c_tid: getPartner ? getPartner.tid : null, + c_card_number: card_number, + i_reservation_amount: amount, + // i_issuer: getIssuer ? getIssuer.i_issuer : null, + // c_issuer_code: getIssuer ? getIssuer.issuer_code : null, + // c_issuer_name: getIssuer ? getIssuer.issuer_name : null, + i_issuer_fee: issuerFee, + // i_channel: null, + // c_channel_code: null, + // c_channel_name: null, + i_channel_fee: channelFee, + c_payment_ref_no: null, + i_reservation_no_seq: reservationNoSequence, + d_expired: expired, + d_load_balance: null, + c_load_balance_no: null, + c_status: 'P', + c_status_name: 'PENDING', + d_create: now, + i_create: null, + c_create_username: null, + c_create_fullname: null, + d_modify: null, + i_modify: null, + c_modify_username: null, + c_modify_fullname: null, + d_delete: null, + i_delete: null, + c_delete_username: null, + c_delete_fullname: null, + c_flag: '-1', + c_customer_name: customerName, + c_phone_number: phoneNumber, + }; + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] inserting reservation transaction...` + // ); + + // insert transaction + let insert = await model.insertReservation(data); + + // jika proses insert data semua yang berkaitan dengan reservasi saldo mengalami kegagalan, maka lakukan rollback + // kegagalan insert data transaksi bisa disebabkan karena data ref no yang di berikan client sudah digunakan + if (insert.rowCount > 0) { + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION ] inserting log for card history...` + // ); + + // log card history + await model.createReserveBalanceLog({ + i_log_name: 90, + d_log: now, + c_card_number: card_number, + c_source: 'CMS', + c_location: getPartner ? getPartner.partner_name : null, + m_balance_before: balance > 0 ? balance : 0, + m_amount: 0, + m_balance_after: balance > 0 ? balance : 0, + j_new_data: data, + j_old_data: null, + c_note: `RESERVED BALANCE ${amount} FROM ${getPartner ? getPartner.partner_name : null + } SUCCESSFULLY`, + c_status: 'S', + d_created: now, + i_create: null, + c_create_username: 'HSM', + c_create_fullname: 'HARDWARE SECURE MODULE', + c_category: 'T', + }); + + result = { + code: '00', + message: 'reservation saved successfully.', + data: { + reservation_number: reservationNumber, + reservation_time: now, + partner: getPartner ? getPartner.partner_name : null, + merchant: getPartner ? getPartner.merchant_name : null, + terminal: getPartner ? getPartner.terminal_name : null, + card_number: card_number, + reserved_amount: amount, + issuer_fee: issuerFee, + channel_fee: channelFee, + }, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } else { + result = { + code: '424', + message: 'refno is duplicate', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE RESERVATION ]: 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 reservationV2 = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { + reservation_data, + ref_no, + customer_name, + phone_number, + amount, + card_number, + } = req.body; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST RESERVATION-V2 ]: ${JSON.stringify(req.body)}` + ); + + // trim card number + // card_number = card_number.trim(); + + // check validator + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // log debug + // pengecekkan reservation data yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking reservation data...` + // ); + + let reservationData; + + try { + reservationData = helper.decryptText(reservation_data); + } catch (error) { } + + if (!reservationData) { + result = { + code: '435', + message: 'bad request. reservation data is invalid.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // parsing data to json format + reservationData = JSON.parse(reservationData); + + if ( + !reservationData.mid || + !reservationData.tid || + !reservationData.card_number || + !reservationData.amount || + !reservationData.transaction_date + ) { + result = { + code: '436', + message: 'bad request. reservation data is empty.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + if (card_number) { + if (reservationData.card_number != card_number) { + result = { + code: '441', + message: + 'bad request. card number requested is different with reservation data.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } + + let cardBlacklist = await model.getCardBlacklist( + reservationData.card_number + ); + if (cardBlacklist) { + if (cardBlacklist.c_status == 'B') { + result = { + code: '445', + message: 'Card is Blacklisted', + data: {}, + }; + return res.status(200).json(result); + } + } + + if (amount) { + if (reservationData.amount != amount) { + result = { + code: '442', + message: + 'bad request. amount requested is different with reservation data.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } + + // extract reseravtion data + let mid = reservationData.mid; + let tid = reservationData.tid; + card_number = reservationData.card_number; + amount = reservationData.amount; + let transactionDate = reservationData.transaction_date; + let securityCode = reservationData.security_code; + + if (securityCode) { + // log debug + // process enkripsi data reservasi dengan HMAC sebagai pembanding bahwa data yang di decrypt valid + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] comparing security code with decrypt data...}` + // ); + + // create security code yang isinya data reservasi yang akan di compare nantinya saat melakukan insert reservation + let securityCodeCompare = await helper.createHMAC( + mid + '|' + tid + '|' + card_number + '|' + amount + ); + + if (securityCode !== securityCodeCompare) { + result = { + code: '437', + message: 'bad request. reservation data has been changed.', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } + + // log debug + // pengecekkan reservation data yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] extracting reservation data : ${JSON.stringify( + // { + // mid: mid, + // tid: tid, + // card_number: card_number, + // amount: amount, + // transaction_date: transactionDate, + // security_code: securityCode, + // } + // )}` + // ); + + // log debug + // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. + // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya + // Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking production card number or not...` + // ); + + // jika settingan diperuntukan untuk production + // if (process.env.SERVER_FOR == 'production') { + // // kartu yang di request bukan kartu production maka akan di tolak + // if (card_number.substring(0, 1) != '1') { + // result = { + // code: '400', + // message: "It's not production card number.", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + // ); + + // return res.status(200).json(result); + // } + // } else { + // // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak + // if (card_number.substring(0, 1) == '1') { + // result = { + // code: '400', + // message: + // "It's production card number. Please use the development card number.", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${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 + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] 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-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + // log debug + // get settingan dari parameter apakah nomor kartu yang di request harus di cek dengan data card product CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] getting checking card number by card product CMS status on parameter...` + // ); + + // get parameter to check with card product cms or not + let getCheckByCardProductStatusValue = + await model.getCheckByCardProductStatusValue(); + let checkByCardProductStatusValue = + getCheckByCardProductStatusValue?.c_value; + + // jika settingan pengecekkan nomor kartu yang di request dengan data card product yang ada di sistem CMS aktif + if (checkByCardProductStatusValue == 'A') { + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking card number...` + // ); + + // check card number yang di request terdaftar di card product CMS atau tidak + 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-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking reservation amount...` + // ); + + // check reservation amount + // amount reservasi harus lebih dari 0 + if (parseInt(amount) <= 0) { + result = { + code: '415', + message: 'amount must be greater than 0', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // log debug + // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] 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} [ PROCESSING RESERVATION-V2 ] checking BI regulation status...` + // ); + + // get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak + let getBIRegulationStatus = await model.getBIRegulationStatus(); + if (getBIRegulationStatus.c_value == 'A') { + // log debug + // get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking max balance on the card...` + // ); + + // get max saldo on the card + let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); + // jika settingan paremeter maksimum saldo di dalam kartu ditemukan + if (getMaxAmountOnTheCard.c_value) { + // jika saldo dalam kartu diakumulasikan dengan amount reservasi dan jumlah nya ternyata melebihi jumlah maksimum saldo berdasarkan settingan parameter, maka akan transaksi akan di tolak + 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-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } + + // log debug + // proses pengecekkan akumulasi maksimum topup di bulan berjalan berdasarkan parameter setting di sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking max topup per month...` + // ); + + // get accumulated balance in this month dari nomor kartu yang di request + let accumulatedBalance = 0; + let getAccumulationBalanceInThisMonthFromCardHistory = + await model.getAccumulationBalanceInThisMonthFromCardHistory( + card_number, + year, + month + ); + + // jika ditemukan history akumulasi topup dari nomor kartu yang di request, maka set akumulasi saldo di bulan berjalan sama dengan history yang ditemukan + if (getAccumulationBalanceInThisMonthFromCardHistory) { + accumulatedBalance = + getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; + } + + // validate max topup per month berdasarkan parameter setting + let getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); + + // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan + if (getMaxTopupPerMonth.c_value) { + // jika akumulasi saldo kartu yang di request dijumlahkan dengan amount reservasi dan ternyata melebihi jumlah akumulasi maksumum topup dalam sebelum, maka transaksi akan di tolak + 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-V2 ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + } + } + + // log debug + // proses pengecekkan maksimum reservasi dengna status pending di parameter setting sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking max reservation...` + // ); + + // get maksimum reservation dengan status pending dari parameter setting + let getMaxReservation = await model.getMaxReservation(); + let maxReservation = getMaxReservation.c_value + ? parseInt(getMaxReservation.c_value) + : 0; + + // // log debug + // winston.logger.debug(`${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking reservation with flag...`); + + // // get reservation with flag + // let reservationWithFlag = await model.getReservationWithFlag( + // card_number, + // now + // ); + // let totalReservationWithFlag = + // reservationWithFlag.total_reservation > 0 + // ? reservationWithFlag.total_reservation + // : 0; + // if (totalReservationWithFlag > 0) { + // result = { + // code: "420", + // message: + // "your card number has incomplete transaction. Please unload your balance!", + // data: {}, + // }; + + // // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + // ); + + // return res.status(200).json(result); + // } + + // log debug + // proses pencarian transaki dari table reservasi balance berdasarkan nomor kartu yang di request + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking total reservation pending...` + // ); + + // get total reservation pending bersarkan nomor kartu yang di request yaitu total transaksi yang status nya pending beserta jumlah amount nya + let getReservationPending = await model.getReservationPendingV2( + card_number, + now + ); + + let dataReservationPending = []; + let totalNominalReservationPending = 0; + if (getReservationPending.length > 0) { + for (let item of getReservationPending) { + // hitung total reservasi yang masih pending / belum di topup + totalNominalReservationPending = + totalNominalReservationPending + parseInt(item.i_reservation_amount); + + dataReservationPending.push({ + reservation_date: item.d_reservation, + amount: parseInt(item.i_reservation_amount), + partner_name: item.c_partner_name, + }); + } + } + + // jika nomor kartu yang di request ditemukan transaksi reservasi dengan status pending pada transaksi sebelumnya, maka jumlahkan total amount reservasi sebelumnya dengan amount reservasi yang dilakukan sekarang + let totalReservationPending = + totalNominalReservationPending > 0 + ? parseInt(totalNominalReservationPending) + parseInt(amount) + : parseInt(amount); + + // jika total amount reservasi melebihi maksimum reservasi sesuai dengan parameter setting di sistem CMS maka transaksi akan di tolak + 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-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + // log debug + // process mendapatkan persentase issuer fee dan channel free berdasarkan settingan dari sistem CMS + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] getting issuer fee and channel fee...` + // ); + + // set default issuer fee + let issuerFee = 0; + let channelFee = 0; + + // get issuer fee dan channel fee dari table public.t_c_partner_fee + let getIssuer = await model.getIssuer(getPartner.i_partner, now); + + if (getIssuer) { + // per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi + if (today >= '2023-11-01') { + issuerFee = getIssuer.i_issuer_fee_nominal; + channelFee = getIssuer.i_channel_fee_nominal; + } else { + // ======================= KHUSUS LRT JABODEBEK ============================= + if (getPartner.partner_code == 'P05') { + issuerFee = getIssuer.i_issuer_fee_nominal; + channelFee = getIssuer.i_channel_fee_nominal; + } else { + // SELAIN LRT JABODEBEK + issuerFee = + (getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); + channelFee = + (getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); + } + } + } + + // if (!getIssuer) { + // return res.status(200).json({ + // code: "403", + // message: "issuer doesn't exist", + // data: {}, + // }); + // } + + // log debug + // proses pengecekkan value dari setting parameter untuk data reservasi yang tidak di load/topup apakah statusnya diaktifkan atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] getting reservation expiration date on parameter...` + // ); + + const { time, measure } = await model.getReservationExpiration(); + let expired = moment(now).add(time, measure).format('YYYY-MM-DD HH:mm:ss'); + + // -------------------------------- NOTES -------------------------------- + // for LRT JABO => customer_name diisi Device Name (versi penamaan LRT Jabo) dan phone_number diisi Device Code (versi kode LRT Jabo) sesuai MOM BI-WEEKLY MEETING (08/05/2023) + let customerName = customer_name; + let phoneNumber = phone_number; + + if (!customerName || customerName == '' || customerName == '-') { + customerName = getPartner ? getPartner.terminal_name : ''; + } + + if (!phoneNumber || phoneNumber == '' || phoneNumber == '-') { + phoneNumber = mid + '_' + tid; + } + + const { number: reservationNumber, sequence: reservationNoSequence } = + await model.allocateReservationNumber(getPartner.partner_code, moment(now).format('YYMMDD')); + + // binding data + let data = { + c_reservation_no: reservationNumber, + d_reservation: now, + c_ref_no: ref_no, + i_partner: getPartner ? getPartner.i_partner : null, + c_partner_code: getPartner ? getPartner.partner_code : null, + c_partner_name: getPartner ? getPartner.partner_name : null, + i_merchant: getPartner ? getPartner.i_merchant : null, + c_merchant_code: getPartner ? getPartner.merchant_code : null, + c_merchant_name: getPartner ? getPartner.merchant_name : null, + c_mid: getPartner ? getPartner.mid : null, + i_terminal: getPartner ? getPartner.i_terminal : null, + c_terminal_code: getPartner ? getPartner.terminal_code : null, + c_terminal_name: getPartner ? getPartner.terminal_name : null, + c_tid: getPartner ? getPartner.tid : null, + c_card_number: card_number, + i_reservation_amount: amount, + // i_issuer: getIssuer ? getIssuer.i_issuer : null, + // c_issuer_code: getIssuer ? getIssuer.issuer_code : null, + // c_issuer_name: getIssuer ? getIssuer.issuer_name : null, + i_issuer_fee: issuerFee, + // i_channel: null, + // c_channel_code: null, + // c_channel_name: null, + i_channel_fee: channelFee, + c_payment_ref_no: null, + i_reservation_no_seq: reservationNoSequence, + d_expired: expired, + d_load_balance: null, + c_load_balance_no: null, + c_status: 'P', + c_status_name: 'PENDING', + d_create: now, + i_create: null, + c_create_username: null, + c_create_fullname: null, + d_modify: null, + i_modify: null, + c_modify_username: null, + c_modify_fullname: null, + d_delete: null, + i_delete: null, + c_delete_username: null, + c_delete_fullname: null, + c_flag: '-1', + c_customer_name: customerName, + c_phone_number: phoneNumber, + }; + + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] inserting reservation transaction...` + // ); + + // (belum) ada issue disini, jadi ada case reservation number nya sama, terus error query harusnya ada handle response message nya, yg sekarang malah masuk ke blok reservation saved successfully. + + // insert transaction + let insert = await model.insertReservation(data); + + // jika proses insert data semua yang berkaitan dengan reservasi saldo mengalami kegagalan, maka lakukan rollback + // kegagalan insert data transaksi bisa disebabkan karena data ref no yang di berikan client sudah digunakan + if (insert.rowCount > 0) { + // log debug + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] inserting log for card history...` + // ); + + // log card history + await model.createReserveBalanceLog({ + i_log_name: 90, + d_log: now, + c_card_number: card_number, + c_source: 'CMS', + c_location: getPartner ? getPartner.partner_name : null, + m_balance_before: balance > 0 ? balance : 0, + m_amount: 0, + m_balance_after: balance > 0 ? balance : 0, + j_new_data: data, + j_old_data: null, + c_note: `RESERVED BALANCE ${amount} FROM ${getPartner ? getPartner.partner_name : null + } SUCCESSFULLY`, + c_status: 'S', + d_created: now, + i_create: null, + c_create_username: 'HSM', + c_create_fullname: 'HARDWARE SECURE MODULE', + c_category: 'T', + }); + + result = { + code: '00', + message: 'reservation saved successfully.', + data: { + reservation_number: reservationNumber, + reservation_time: now, + partner: getPartner ? getPartner.partner_name : null, + merchant: getPartner ? getPartner.merchant_name : null, + terminal: getPartner ? getPartner.terminal_name : null, + card_number: card_number, + reserved_amount: amount, + issuer_fee: issuerFee, + channel_fee: channelFee, + }, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } else { + result = { + code: '424', + message: 'refno is duplicate', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE RESERVATION-V2 ]: 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: {}, + }); + } +}; + +module.exports = { reservationValidate, reservationValidateV2, reservation, reservationV2 }; diff --git a/application/modules/reservebalance/reservation-decrypt.handler.js b/application/modules/reservebalance/reservation-decrypt.handler.js new file mode 100644 index 0000000..214a999 --- /dev/null +++ b/application/modules/reservebalance/reservation-decrypt.handler.js @@ -0,0 +1,33 @@ +const helper = require('../../helpers/helper'); +const winston = require('../../helpers/winston.logger'); + +// Dekripsi data reservasi pada endpoint yang sudah tersedia. +const decrpytRequest = async (req, res) => { + let uniqueCode = req.id ?? 'unknown'; + try { + uniqueCode = await helper.getUniqueCode(); + winston.logger.info(`${uniqueCode} [ REQUEST DECRYPT ]: received`); + + const data = JSON.parse(helper.decryptText(req.body.reservation_data)); + const result = { + code: '00', + message: 'decrypted successfully.', + data, + }; + + winston.logger.info(`${uniqueCode} [ RESPONSE DECRYPT ] code=${result.code}`); + return res.status(200).json(result); + } catch (error) { + const result = { + code: '500', + message: 'decrypted failed.', + data: {}, + }; + + // Catat jenis kegagalan tanpa menyimpan isi reservasi. + winston.logger.error(`${uniqueCode} [ RESPONSE DECRYPT ] code=500 error_type=${error.name}`); + return res.status(200).json(result); + } +}; + +module.exports = { decrpytRequest }; diff --git a/application/modules/reservebalance/reservation-inquiry.handlers.js b/application/modules/reservebalance/reservation-inquiry.handlers.js new file mode 100644 index 0000000..eac1746 --- /dev/null +++ b/application/modules/reservebalance/reservation-inquiry.handlers.js @@ -0,0 +1,563 @@ +const helper = require('../../helpers/helper'); +const winston = require('../../helpers/winston.logger'); +const { validationResult } = require('express-validator'); +const model = require('./reservebalance.model'); +const moment = require('moment'); + +// Pencarian reservasi, rincian transaksi, dan informasi biaya. +const checkReservation = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { mid, tid, card_number } = req.body; + + // log info + // winston.logger.info( + // `${uniqueCode} [ REQUEST RESERVATION-CHECK ]: ${JSON.stringify(req.body)}` + // ); + + winston.logger.info(`${uniqueCode} [ REQUEST RESERVATION-CHECK ]`); + + // trim card number + card_number = card_number.trim(); + + // check validator + let err = validationResult(req, res); + if (!err.isEmpty()) { + result = { + code: '400', + message: err.errors[0].msg, + data: {}, + }; + + // log warn + // winston.logger.warn( + // `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify( + // result + // )}` + // ); + + return res.status(200).json(result); + } + + // log debug + // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. + // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya + // Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-CHECK ] checking production card number or not...` + // ); + + let cardBlacklist = await model.getCardBlacklist(card_number); + if (cardBlacklist) { + if (cardBlacklist.c_status == 'B') { + result = { + code: '445', + message: 'Card is Blacklisted', + data: {}, + }; + return res.status(200).json(result); + } + } + + // jika settingan diperuntukan untuk production + // if (process.env.SERVER_FOR == 'production') { + // // kartu yang di request bukan kartu production maka akan di tolak + // if (card_number.substring(0, 1) != '1') { + // result = { + // code: '400', + // message: "It's not production card number.", + // data: {}, + // }; + + // // log warn + // // winston.logger.warn( + // // `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify( + // // result + // // )}` + // // ); + + // return res.status(200).json(result); + // } + // } else { + // // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak + // if (card_number.substring(0, 1) == '1') { + // result = { + // code: '400', + // message: + // "It's production card number. Please use the development card number.", + // data: {}, + // }; + // // log warn + // // winston.logger.warn( + // // `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify( + // // result + // // )}` + // // ); + // return res.status(200).json(result); + // } + // } + + // log debug + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-CHECK ] 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-CHECK ]: ${JSON.stringify( + // result + // )}` + // ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: { + body: req.body, + partner_id_token: req.partner_id_token, + partner_user_id_token: req.partner_user_id_token, + headers: req.headers, + }, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); + } + + // log debug + // lakukan pencarian ke table reservasion, apakah nomor kartu yang di request masih mempunyai transaksi reservasi saldo yang status nya masih pending atau in progress + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING RESERVATION-CHECK ] getting reservation with pending status and in progress status...` + // ); + + // get reservation pending & in progress status + let checkSecure = false; + let getReservationWithPendingAndInProgressStatus = + await model.getReservationWithPendingAndInProgressStatus(card_number); + if ( + getReservationWithPendingAndInProgressStatus.total_reservation_pending > 0 + ) { + checkSecure = true; + + // info jika nomor kartu yang di request mempunyai transaksi reservasi saldo yang status nya masih pending dan in progress + result = { + code: '03', + message: 'success with reservation pending or in progress.', + data: {}, + }; + } else { + // info jika nomor kartu yang di request tidak mempunyai transaksi reservasi saldo yang status nya masih pending dan in progress + result = { + code: '02', + message: 'success without reservation pending or in progress.', + data: {}, + }; + } + + // log info + // winston.logger.info( + // `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify(result)}` + // ); + + winston.logger.info(`${uniqueCode} [ RESPONSE RESERVATION-CHECK ] code=${result.code}`); + + return res.status(200).json(result); + } catch (error) { + // create log + winston.logger.error( + `[ RESPONSE RESERVATION-CHECK ]: 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 inquiryReservation = async (req, res) => { + try { + // param + let { reservation_number, card_number, start_date, end_date } = req.body; + + // time + let now = moment().format('YYYY-MM-DD HH:mm:ss'); + + // validation parameter inquiry + if (!reservation_number && !card_number) { + return res.status(200).json({ + code: '400', + message: + 'bad request. please add the reservation number or card number!', + data: {}, + }); + } + + // validation inquiry date + if ((!start_date && end_date) || (start_date && !end_date)) { + return res.status(200).json({ + code: '400', + message: 'bad request. please check the date!', + data: {}, + }); + } + + // check reservation + if (reservation_number) { + let byReservationNumber = await model.inquiryByReservationNumber( + reservation_number + ); + + if (!byReservationNumber) { + return res.status(200).json({ + code: '414', + message: "reservation doesn't exist", + data: {}, + }); + } + + return res.json({ + code: '00', + message: 'reservation has been found.', + data: byReservationNumber, + }); + } else if (card_number) { + let byCardNumber = await model.inquiryByCardNumber( + card_number, + start_date, + end_date + ); + + if (!byCardNumber) { + return res.status(200).json({ + code: '414', + message: "reservation doesn't exist", + data: [], + }); + } + + return res.json({ + code: '00', + message: 'reservation has been found.', + data: byCardNumber, + }); + } + } catch (error) { + return res.status(200).json({ + code: '500', + message: + process.env.NODE_ENV != 'production' + ? error.message + : '500 internal server error - backend server.', + data: {}, + }); + } +}; + +const inquiryReservationByReservation = async (req, res) => { + try { + // param + let { + reservation_number, + ref_no, + load_balance_number, + show_complete_data, + } = req.body; + + let result; + + if (req.query.search === 'ref-no') { + // validation parameter inquiry + if (!ref_no) { + return res.status(200).json({ + code: '400', + message: 'bad request. please add the ref number!', + data: {}, + }); + } + + // check reservation + result = await model.inquiryListByRefNumber(ref_no, show_complete_data); + + if (!result) { + return res.status(200).json({ + code: '414', + message: "reservation doesn't exist", + data: {}, + }); + } + } else if (req.query.search === 'load-balance-number') { + // validation parameter inquiry + if (!load_balance_number) { + return res.status(200).json({ + code: '400', + message: 'bad request. please add the load balance number!', + data: {}, + }); + } + + // check reservation + result = await model.inquiryListByLoadNumber( + load_balance_number, + show_complete_data + ); + + if (result.length < 1) { + return res.status(200).json({ + code: '414', + message: "reservation doesn't exist", + data: {}, + }); + } + } else { + // validation parameter inquiry + if (!reservation_number) { + return res.status(200).json({ + code: '400', + message: 'bad request. please add the reservation number!', + data: {}, + }); + } + + // check reservation + result = await model.inquiryByReservationNumber( + reservation_number, + show_complete_data + ); + + if (!result) { + return res.status(200).json({ + code: '414', + message: "reservation doesn't exist", + data: {}, + }); + } + } + + return res.json({ + code: '00', + message: 'reservation has been found.', + data: result, + }); + } catch (error) { + return res.status(200).json({ + code: '500', + message: + process.env.NODE_ENV != 'production' + ? error.message + : '500 internal server error - backend server.', + data: {}, + }); + } +}; + +const inquiryListReservationByReservation = async (req, res) => { + try { + // param + let { start_date, end_date } = req.body; + + // validation parameter inquiry + if (!start_date || !end_date) { + return res.status(200).json({ + code: '400', + message: 'bad request. please add the start date and end date!', + data: {}, + }); + } + + let startDateCheckFormat = moment(start_date, 'YYYY-MM-DD', true).isValid(); + let endDateCheckFormat = moment(end_date, 'YYYY-MM-DD', true).isValid(); + + if (startDateCheckFormat == false || endDateCheckFormat == false) { + return res.status(200).json({ + code: '400', + message: 'bad request. format start date or end date is invalid!', + data: {}, + }); + } + + // check date range max 1 month + let diff = moment(end_date).diff(moment(start_date), 'months', true); + + if (diff >= 1) { + return res.status(200).json({ + code: '400', + message: + 'bad request. We only allow data requests for 1 month. please change your date range parameter request!', + data: {}, + }); + } + + // check reservation + let listReservation = await model.inquiryListReservation( + req.partner_id_token, + start_date, + end_date + ); + + if (!listReservation) { + return res.status(200).json({ + code: '414', + message: "reservation doesn't exist", + data: {}, + }); + } + + return res.json({ + code: '00', + message: 'reservation has been found.', + data: listReservation, + }); + } catch (error) { + return res.status(200).json({ + code: '500', + message: + process.env.NODE_ENV != 'production' + ? error.message + : '500 internal server error - backend server.', + data: {}, + }); + } +}; + +const getFeeSharing = async (req, res) => { + try { + // generate unique code + // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca + let uniqueCode = await helper.getUniqueCode(); + let result = {}; + + // param + let { datetime, mid, tid } = req.body; + + // log info + winston.logger.info( + `${uniqueCode} [ REQUEST GET-FEE-SHARING ]: ${JSON.stringify(req.body)}` + ); + + // datetime + if (!datetime) { + datetime = moment().format('YYYY-MM-DD'); + } else { + datetime = moment(datetime).format('YYYY-MM-DD'); + } + + // log debug + // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak + // winston.logger.debug( + // `${uniqueCode} [ PROCESSING GET-FEE-SHARING ] checking partner...` + // ); + + // get partner, merchant, terminal from tid + let getPartner = await model.getPartner(mid, tid); + + // jika partner (mid atau tid) tidak ditemukan atau tidak terdaftar di sistem CMS + if (!getPartner) { + result = { + code: '412', + message: 'terminal id is not valid', + data: {}, + }; + + // log warn + winston.logger.warn( + `${uniqueCode} [ RESPONSE GET-FEE-SHARING ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } + + if (getPartner.i_partner != req.partner_id_token) { + result = { + code: '412', + message: 'partner is not match', + data: {}, + }; + + return res.status(200).json(result); + } + + // set default issuer fee + let issuerFee = 0; + let channelFee = 0; + + // get issuer fee dan channel fee dari table public.t_c_partner_fee + let getIssuer = await model.getIssuer(getPartner.i_partner, datetime); + + if (getIssuer) { + // per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi + if (datetime >= '2023-11-01') { + issuerFee = getIssuer.i_issuer_fee_nominal; + channelFee = getIssuer.i_channel_fee_nominal; + } else { + // ======================= KHUSUS LRT JABODEBEK ============================= + if (getPartner.partner_code == 'P05') { + issuerFee = getIssuer.i_issuer_fee_nominal; + channelFee = getIssuer.i_channel_fee_nominal; + } else { + // SELAIN LRT JABODEBEK + issuerFee = + (getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); + channelFee = + (getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); + } + } + } + + result = { + code: '00', + message: 'fee sharing has been found.', + data: { + issuer_fee: issuerFee, + channel_fee: channelFee, + }, + }; + + // log info + winston.logger.info( + `${uniqueCode} [ RESPONSE GET-FEE-SHARING ]: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); + } catch (error) { + return res.status(200).json({ + code: '500', + message: + process.env.NODE_ENV != 'production' + ? error.message + : '500 internal server error - backend server.', + data: {}, + }); + } +}; + +module.exports = { checkReservation, inquiryReservation, inquiryReservationByReservation, inquiryListReservationByReservation, getFeeSharing }; diff --git a/application/modules/reservebalance/reservebalance.controller.js b/application/modules/reservebalance/reservebalance.controller.js index 989629e..7be1897 100644 --- a/application/modules/reservebalance/reservebalance.controller.js +++ b/application/modules/reservebalance/reservebalance.controller.js @@ -1,4300 +1,29 @@ -const { validationResult } = require('express-validator'); const validate = require('./reservebalance.validation'); -const helper = require('../../helpers/helper'); -const winston = require('../../helpers/winston.logger'); -const model = require('./reservebalance.model'); const moment = require('moment'); +const { + checkReservation, + inquiryReservation, + inquiryReservationByReservation, + inquiryListReservationByReservation, + getFeeSharing, +} = require('./reservation-inquiry.handlers'); +const { + reservationValidate, + reservationValidateV2, + reservation, + reservationV2, +} = require('./reservation-create.handlers'); +const { + cancelReservationValidate, + cancelReservation, + cancelReservationValidateV2, + cancelReservationV2, + cancelReservationV2_1, +} = require('./reservation-cancel.handlers'); +const { decrpytRequest } = require('./reservation-decrypt.handler'); + moment.locale('id'); - -// ================================================================= CHECK RESERVATION ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// proses yang digunakan untuk memeriksa apakah ada reservasi yang status nya masih pending atau in progress untuk nomor kartu yang di request - -const checkReservation = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { mid, tid, card_number } = req.body; - - // log info - // winston.logger.info( - // `${uniqueCode} [ REQUEST RESERVATION-CHECK ]: ${JSON.stringify(req.body)}` - // ); - - winston.logger.info(`${uniqueCode} [ REQUEST RESERVATION-CHECK ]`); - - // trim card number - card_number = card_number.trim(); - - // check validator - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: {}, - }; - - // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify( - // result - // )}` - // ); - - return res.status(200).json(result); - } - - // log debug - // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. - // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya - // Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-CHECK ] checking production card number or not...` - // ); - - let cardBlacklist = await model.getCardBlacklist(card_number); - if (cardBlacklist) { - if (cardBlacklist.c_status == 'B') { - result = { - code: '445', - message: 'Card is Blacklisted', - data: {}, - }; - return res.status(200).json(result); - } - } - - // jika settingan diperuntukan untuk production - // if (process.env.SERVER_FOR == 'production') { - // // kartu yang di request bukan kartu production maka akan di tolak - // if (card_number.substring(0, 1) != '1') { - // result = { - // code: '400', - // message: "It's not production card number.", - // data: {}, - // }; - - // // log warn - // // winston.logger.warn( - // // `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify( - // // result - // // )}` - // // ); - - // return res.status(200).json(result); - // } - // } else { - // // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak - // if (card_number.substring(0, 1) == '1') { - // result = { - // code: '400', - // message: - // "It's production card number. Please use the development card number.", - // data: {}, - // }; - // // log warn - // // winston.logger.warn( - // // `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify( - // // result - // // )}` - // // ); - // return res.status(200).json(result); - // } - // } - - // log debug - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-CHECK ] 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-CHECK ]: ${JSON.stringify( - // result - // )}` - // ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: { - body: req.body, - partner_id_token: req.partner_id_token, - partner_user_id_token: req.partner_user_id_token, - headers: req.headers, - }, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // lakukan pencarian ke table reservasion, apakah nomor kartu yang di request masih mempunyai transaksi reservasi saldo yang status nya masih pending atau in progress - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-CHECK ] getting reservation with pending status and in progress status...` - // ); - - // get reservation pending & in progress status - let checkSecure = false; - let getReservationWithPendingAndInProgressStatus = - await model.getReservationWithPendingAndInProgressStatus(card_number); - if ( - getReservationWithPendingAndInProgressStatus.total_reservation_pending > 0 - ) { - checkSecure = true; - - // info jika nomor kartu yang di request mempunyai transaksi reservasi saldo yang status nya masih pending dan in progress - result = { - code: '03', - message: 'success with reservation pending or in progress.', - data: {}, - }; - } else { - // info jika nomor kartu yang di request tidak mempunyai transaksi reservasi saldo yang status nya masih pending dan in progress - result = { - code: '02', - message: 'success without reservation pending or in progress.', - data: {}, - }; - } - - // log info - // winston.logger.info( - // `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify(result)}` - // ); - - winston.logger.info(`${uniqueCode} [ RESPONSE RESERVATION-CHECK ] code=${result.code}`); - - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE RESERVATION-CHECK ]: 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 VALIDATE ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// proses yang digunakan untuk melakukan validasi reservasi saldo. Proses ini seharusnya dilakukan terlebih dahulu sebelum melakukan insert data reservasi ke sistem CMS - -const reservationValidate = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { mid, tid, card_number, amount } = req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST RESERVATION-VALIDATE ]: ${JSON.stringify( - req.body - )}` - ); - - // trim card number - card_number = card_number.trim(); - - // check validator - let 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); - } - - // log debug - // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. - // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya - // Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking production card number or not...` - // ); - - let cardBlacklist = await model.getCardBlacklist(card_number); - if (cardBlacklist) { - if (cardBlacklist.c_status == 'B') { - result = { - code: '445', - message: 'Card is Blacklisted', - data: {}, - }; - return res.status(200).json(result); - } - } - - // jika settingan diperuntukan untuk production - // if (process.env.SERVER_FOR == 'production') { - // // kartu yang di request bukan kartu production maka akan di tolak - // if (card_number.substring(0, 1) != '1') { - // result = { - // code: '400', - // message: "It's not production card number.", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE ]: ${JSON.stringify( - // result - // )}` - // ); - - // return res.status(200).json(result); - // } - // } else { - // // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak - // if (card_number.substring(0, 1) == '1') { - // result = { - // code: '400', - // message: - // "It's production card number. Please use the development card number.", - // 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 - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking partner...` - // ); - - // get partner, merchant, terminal from tid - let getPartner = await model.getPartner(mid, tid); - - // jika partner (mid atau tid) tidak ditemukan atau tidak terdaftar di sistem CMS - if (!getPartner) { - result = { - code: '412', - message: 'terminal id is not valid', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // log debug - // get settingan dari parameter apakah nomor kartu yang di request harus di cek dengan data card product CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] getting checking card number by card product CMS status on parameter...` - // ); - - // get parameter to check with card product cms or not - let getCheckByCardProductStatusValue = - await model.getCheckByCardProductStatusValue(); - let checkByCardProductStatusValue = - getCheckByCardProductStatusValue?.c_value; - - // jika settingan pengecekkan nomor kartu yang di request dengan data card product yang ada di sistem CMS aktif - if (checkByCardProductStatusValue == 'A') { - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking card number...` - // ); - - // check card number yang di request terdaftar di card product CMS atau tidak - let checkCardNumber = await model.checkCardNumber(card_number); - - // jika nomor kartu yang di request tidak terdaftar di card prouct CMS - 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} [ PROCESSING RESERVATION-VALIDATE ] checking reservation amount...` - // ); - - // check reservation amount - // amount reservasi harus lebih dari 0 - 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 - // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] 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} [ PROCESSING RESERVATION-VALIDATE ] checking BI regulation status...` - // ); - - // get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak - let getBIRegulationStatus = await model.getBIRegulationStatus(); - - // jika pengecekkan regulasi BI diaktifkan - if (getBIRegulationStatus.c_value == 'A') { - // log debug - // get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking max balance on the card...` - // ); - - // get max saldo on the card - let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); - - // jika settingan paremeter maksimum saldo di dalam kartu ditemukan - if (getMaxAmountOnTheCard.c_value) { - // jika saldo dalam kartu diakumulasikan dengan amount reservasi dan jumlah nya ternyata melebihi jumlah maksimum saldo berdasarkan settingan parameter, maka akan transaksi akan di tolak - 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 - // proses pengecekkan akumulasi maksimum topup di bulan berjalan berdasarkan parameter setting di sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking max topup per month...` - // ); - - // get accumulated balance in this month dari nomor kartu yang di request - let accumulatedBalance = 0; - let getAccumulationBalanceInThisMonthFromCardHistory = - await model.getAccumulationBalanceInThisMonthFromCardHistory( - card_number, - year, - month - ); - - // jika ditemukan history akumulasi topup dari nomor kartu yang di request, maka set akumulasi saldo di bulan berjalan sama dengan history yang ditemukan - if (getAccumulationBalanceInThisMonthFromCardHistory) { - accumulatedBalance = - getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; - } - - // validate max topup per month berdasarkan parameter setting - let getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); - - // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan - if (getMaxTopupPerMonth.c_value) { - // jika akumulasi saldo kartu yang di request dijumlahkan dengan amount reservasi dan ternyata melebihi jumlah akumulasi maksumum topup dalam sebelum, maka transaksi akan di tolak - 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 - // proses pengecekkan maksimum reservasi dengna status pending di parameter setting sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking max reservation...` - // ); - - // get maksimum reservation dengan status pending dari parameter setting - let getMaxReservation = await model.getMaxReservation(); - - // jika parameter setting maksimum reservasi dengan status pending tidak ditemukan maka set menjadi 0 - let maxReservation = getMaxReservation.c_value - ? parseInt(getMaxReservation.c_value) - : 0; - - // log debug - // proses pencarian transaki dari table reservasi balance berdasarkan nomor kartu yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] checking total reservation pending...` - // ); - - // get total reservation pending bersarkan nomor kartu yang di request yaitu total transaksi yang status nya pending beserta jumlah amount nya - let getReservationPending = await model.getReservationPending( - card_number, - now - ); - - // jika nomor kartu yang di request ditemukan transaksi reservasi dengan status pending pada transaksi sebelumnya, maka jumlahkan total amount reservasi sebelumnya dengan amount reservasi yang dilakukan sekarang - let totalReservationPending = - getReservationPending.total_nominal_reservation > 0 - ? parseInt(getReservationPending.total_nominal_reservation) + - parseInt(amount) - : parseInt(amount); - - // jika total amount reservasi melebihi maksimum reservasi sesuai dengan parameter setting di sistem CMS maka transaksi akan di tolak - 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 - // process mendapatkan persentase issuer fee dan channel free berdasarkan settingan dari sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] getting issuer fee and channel fee...` - // ); - - // set default issuer fee - let issuerFee = 0; - let channelFee = 0; - - // get issuer fee dan channel fee dari table public.t_c_partner_fee - let getIssuer = await model.getIssuer(getPartner.i_partner, now); - - if (getIssuer) { - // per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi - if (today >= '2023-11-01') { - issuerFee = getIssuer.i_issuer_fee_nominal; - channelFee = getIssuer.i_channel_fee_nominal; - } else { - // ======================= KHUSUS LRT JABODEBEK ============================= - if (getPartner.partner_code == 'P05') { - issuerFee = getIssuer.i_issuer_fee_nominal; - channelFee = getIssuer.i_channel_fee_nominal; - } else { - // SELAIN LRT JABODEBEK - issuerFee = - (getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); - channelFee = - (getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); - } - } - } - // if (!getIssuer) { - // return res.status(200).json({ - // code: "403", - // message: "issuer doesn't exist", - // data: {}, - // }); - // } - - result = { - code: '00', - message: 'validation successfully.', - data: { - issuer_fee: issuerFee, - channel_fee: channelFee, - }, - }; - - // 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( - `[ RESPONSE RESERVATION-VALIDATE ]: 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 VALIDATE V2 ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// proses yang digunakan untuk melakukan validasi reservasi saldo. Proses ini seharusnya dilakukan terlebih dahulu sebelum melakukan insert data reservasi ke sistem CMS -// pada proses reservation validate version 2 ini, data reservasi akan di encrypt dan data enkripan tersebut digunakan untuk end point reservation - -const reservationValidateV2 = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { mid, tid, card_number, amount } = req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - req.body - )}` - ); - - // trim card number - // card_number = card_number.trim(); - - // check validator - let 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-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - let cardBlacklist = await model.getCardBlacklist(card_number); - if (cardBlacklist) { - if (cardBlacklist.c_status == 'B') { - result = { - code: '445', - message: 'Card is Blacklisted', - data: {}, - }; - return res.status(200).json(result); - } - } - - // log debug - // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. - // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya - // Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking production card number or not...` - // ); - - // jika settingan diperuntukan untuk production - // if (process.env.SERVER_FOR == 'production') { - // // kartu yang di request bukan kartu production maka akan di tolak - // if (card_number.substring(0, 1) != '1') { - // result = { - // code: '400', - // message: "It's not production card number.", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - // result - // )}` - // ); - - // return res.status(200).json(result); - // } - // } else { - // // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak - // if (card_number.substring(0, 1) == '1') { - // result = { - // code: '400', - // message: - // "It's production card number. Please use the development card number.", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${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 - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking partner...` - // ); - - // get partner, merchant, terminal from tid - let getPartner = await model.getPartner(mid, tid); - - // jika partner (mid atau tid) tidak ditemukan atau tidak terdaftar di sistem CMS - if (!getPartner) { - result = { - code: '412', - message: 'terminal id is not valid', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // log debug - // get settingan dari parameter apakah nomor kartu yang di request harus di cek dengan data card product CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] getting checking card number by card product CMS status on parameter...` - // ); - - // get parameter to check with card product cms or not - let getCheckByCardProductStatusValue = - await model.getCheckByCardProductStatusValue(); - let checkByCardProductStatusValue = - getCheckByCardProductStatusValue?.c_value; - - // jika settingan pengecekkan nomor kartu yang di request dengan data card product yang ada di sistem CMS aktif - if (checkByCardProductStatusValue == 'A') { - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking card number...` - // ); - - // check card number yang di request terdaftar di card product CMS atau tidak - let checkCardNumber = await model.checkCardNumber(card_number); - - // jika nomor kartu yang di request tidak terdaftar di card prouct CMS - if (!checkCardNumber) { - result = { - code: '413', - message: 'card number is not registered', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking reservation amount...` - // ); - - // check reservation amount - // amount reservasi harus lebih dari 0 - if (parseInt(amount) <= 0) { - result = { - code: '415', - message: 'amount must be greater than 0', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] 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} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking BI regulation status...` - // ); - - // get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak - let getBIRegulationStatus = await model.getBIRegulationStatus(); - - // jika pengecekkan regulasi BI diaktifkan - if (getBIRegulationStatus.c_value == 'A') { - // log debug - // get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking max balance on the card...` - // ); - - // get max saldo on the card - let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); - - // jika settingan paremeter maksimum saldo di dalam kartu ditemukan - if (getMaxAmountOnTheCard.c_value) { - // jika saldo dalam kartu diakumulasikan dengan amount reservasi dan jumlah nya ternyata melebihi jumlah maksimum saldo berdasarkan settingan parameter, maka akan transaksi akan di tolak - 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-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } - - // log debug - // proses pengecekkan akumulasi maksimum topup di bulan berjalan berdasarkan parameter setting di sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking max topup per month...` - // ); - - // get accumulated balance in this month dari nomor kartu yang di request - let accumulatedBalance = 0; - let getAccumulationBalanceInThisMonthFromCardHistory = - await model.getAccumulationBalanceInThisMonthFromCardHistory( - card_number, - year, - month - ); - - // jika ditemukan history akumulasi topup dari nomor kartu yang di request, maka set akumulasi saldo di bulan berjalan sama dengan history yang ditemukan - if (getAccumulationBalanceInThisMonthFromCardHistory) { - accumulatedBalance = - getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; - } - - // validate max topup per month berdasarkan parameter setting - let getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); - - // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan - if (getMaxTopupPerMonth.c_value) { - // jika akumulasi saldo kartu yang di request dijumlahkan dengan amount reservasi dan ternyata melebihi jumlah akumulasi maksumum topup dalam sebelum, maka transaksi akan di tolak - 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-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } - } - - // log debug - // proses pengecekkan maksimum reservasi dengna status pending di parameter setting sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking max reservation...` - // ); - - // get maksimum reservation dengan status pending dari parameter setting - let getMaxReservation = await model.getMaxReservation(); - - // jika parameter setting maksimum reservasi dengan status pending tidak ditemukan maka set menjadi 0 - let maxReservation = getMaxReservation.c_value - ? parseInt(getMaxReservation.c_value) - : 0; - - // log debug - // proses pencarian transaki dari table reservasi balance berdasarkan nomor kartu yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] checking total reservation pending...` - // ); - - // get total reservation pending bersarkan nomor kartu yang di request yaitu total transaksi yang status nya pending beserta jumlah amount nya - let getReservationPending = await model.getReservationPendingV2( - card_number, - now - ); - - let dataReservationPending = []; - let totalNominalReservationPending = 0; - if (getReservationPending.length > 0) { - for (let item of getReservationPending) { - // hitung total reservasi yang masih pending / belum di topup - totalNominalReservationPending = - totalNominalReservationPending + parseInt(item.i_reservation_amount); - - dataReservationPending.push({ - reservation_date: item.d_reservation, - amount: parseInt(item.i_reservation_amount), - partner_name: item.c_partner_name, - }); - } - } - - // jika nomor kartu yang di request ditemukan transaksi reservasi dengan status pending pada transaksi sebelumnya, maka jumlahkan total amount reservasi sebelumnya dengan amount reservasi yang dilakukan sekarang - let totalReservationPending = - totalNominalReservationPending > 0 - ? parseInt(totalNominalReservationPending) + parseInt(amount) - : parseInt(amount); - - // jika total amount reservasi melebihi maksimum reservasi sesuai dengan parameter setting di sistem CMS maka transaksi akan di tolak - 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-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // process mendapatkan persentase issuer fee dan channel free berdasarkan settingan dari sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] getting issuer fee and channel fee...` - // ); - - // set default issuer fee - let issuerFee = 0; - let channelFee = 0; - - // get issuer fee dan channel fee dari table public.t_c_partner_fee - let getIssuer = await model.getIssuer(getPartner.i_partner, now); - - if (getIssuer) { - // per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi - if (today >= '2023-11-01') { - issuerFee = getIssuer.i_issuer_fee_nominal; - channelFee = getIssuer.i_channel_fee_nominal; - } else { - // ======================= KHUSUS LRT JABODEBEK ============================= - if (getPartner.partner_code == 'P05') { - issuerFee = getIssuer.i_issuer_fee_nominal; - channelFee = getIssuer.i_channel_fee_nominal; - } else { - // SELAIN LRT JABODEBEK - issuerFee = - (getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); - channelFee = - (getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); - } - } - } - - // if (!getIssuer) { - // return res.status(200).json({ - // code: "403", - // message: "issuer doesn't exist", - // data: {}, - // }); - // } - - // log debug - // process enkripsi data reservasi dengan HMAC yang nanti nya akan di kirim ke end point reservation api sebagai pembanding bahwa data yang sudah di enkripsi tidak dimanipulasi - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] generating security code from data reservation` - // ); - - // create security code yang isinya data reservasi yang akan di compare nantinya saat melakukan insert reservation - let securityCode = await helper.createHMAC( - mid + '|' + tid + '|' + card_number + '|' + amount - ); - - let reservationData = { - mid: mid, - tid: tid, - card_number: card_number, - amount: amount, - transaction_date: now, - security_code: securityCode, - }; - - // log debug - // process enkripsi data reservasi dengan AES yang nanti nya akan di kirim ke end point reservation api untuk menyimpan data reservasi - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE-V2 ] encrypting data reservation: ${JSON.stringify( - // reservationData - // )}` - // ); - - // enkripsi data reservasi sebelum melakukan transaksi reservasi - let hash = helper.encryptText(JSON.stringify(reservationData)); - - result = { - code: '00', - message: 'validation successfully.', - data: { - reservation_data: hash, - reservation_detail: { - card_number: card_number, - amount: amount, - issuer_fee: issuerFee, - channel_fee: channelFee, - }, - reservation_pending: dataReservationPending, - }, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE RESERVATION-VALIDATE-V2 ]: 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 V1 ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// proses insert data transaksi reservasi saldo. Proses ini dilakukan setelah melakukan reservation validate dengan response code 00. Output dari proses ini adalah kode reservation number dan informasi reservasi saldo yang dilakukan - -const reservation = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { mid, tid, card_number, amount, ref_no, customer_name, phone_number } = - req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST RESERVATION ]: ${JSON.stringify(req.body)}` - ); - - // trim card number - card_number = card_number.trim(); - - // check validator - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - // log debug - // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. - // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya - // Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] checking production card number or not...` - // ); - - let cardBlacklist = await model.getCardBlacklist(card_number); - if (cardBlacklist) { - if (cardBlacklist.c_status == 'B') { - result = { - code: '445', - message: 'Card is Blacklisted', - data: {}, - }; - return res.status(200).json(result); - } - } - - // jika settingan diperuntukan untuk production - // if (process.env.SERVER_FOR == 'production') { - // // kartu yang di request bukan kartu production maka akan di tolak - // if (card_number.substring(0, 1) != '1') { - // result = { - // code: '400', - // message: "It's not production card number.", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` - // ); - - // return res.status(200).json(result); - // } - // } else { - // // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak - // if (card_number.substring(0, 1) == '1') { - // result = { - // code: '400', - // message: - // "It's production card number. Please use the development card number.", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE RESERVATION ]: ${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 - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] 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 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // log debug - // get settingan dari parameter apakah nomor kartu yang di request harus di cek dengan data card product CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] getting checking card number by card product CMS status on parameter...` - // ); - - // get parameter to check with card product cms or not - let getCheckByCardProductStatusValue = - await model.getCheckByCardProductStatusValue(); - let checkByCardProductStatusValue = - getCheckByCardProductStatusValue?.c_value; - - // jika settingan pengecekkan nomor kartu yang di request dengan data card product yang ada di sistem CMS aktif - if (checkByCardProductStatusValue == 'A') { - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] checking card number...` - // ); - - // check card number yang di request terdaftar di card product CMS atau tidak - 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 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] checking reservation amount...` - // ); - - // check reservation amount - // amount reservasi harus lebih dari 0 - if (parseInt(amount) <= 0) { - result = { - code: '415', - message: 'amount must be greater than 0', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] 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} [ PROCESSING RESERVATION ] checking BI regulation status...` - // ); - - // get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak - let getBIRegulationStatus = await model.getBIRegulationStatus(); - if (getBIRegulationStatus.c_value == 'A') { - // log debug - // get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] checking max balance on the card...` - // ); - - // get max saldo on the card - let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); - // jika settingan paremeter maksimum saldo di dalam kartu ditemukan - if (getMaxAmountOnTheCard.c_value) { - // jika saldo dalam kartu diakumulasikan dengan amount reservasi dan jumlah nya ternyata melebihi jumlah maksimum saldo berdasarkan settingan parameter, maka akan transaksi akan di tolak - 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 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - } - - // log debug - // proses pengecekkan akumulasi maksimum topup di bulan berjalan berdasarkan parameter setting di sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] checking max topup per month...` - // ); - - // get accumulated balance in this month dari nomor kartu yang di request - let accumulatedBalance = 0; - let getAccumulationBalanceInThisMonthFromCardHistory = - await model.getAccumulationBalanceInThisMonthFromCardHistory( - card_number, - year, - month - ); - - // jika ditemukan history akumulasi topup dari nomor kartu yang di request, maka set akumulasi saldo di bulan berjalan sama dengan history yang ditemukan - if (getAccumulationBalanceInThisMonthFromCardHistory) { - accumulatedBalance = - getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; - } - - // validate max topup per month berdasarkan parameter setting - let getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); - - // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan - if (getMaxTopupPerMonth.c_value) { - // jika akumulasi saldo kartu yang di request dijumlahkan dengan amount reservasi dan ternyata melebihi jumlah akumulasi maksumum topup dalam sebelum, maka transaksi akan di tolak - 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 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - } - } - - // log debug - // proses pengecekkan maksimum reservasi dengna status pending di parameter setting sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] checking max reservation...` - // ); - - // get maksimum reservation dengan status pending dari parameter setting - let getMaxReservation = await model.getMaxReservation(); - let maxReservation = getMaxReservation.c_value - ? parseInt(getMaxReservation.c_value) - : 0; - - // // log debug - // winston.logger.debug(`${uniqueCode} [ PROCESSING RESERVATION ] checking reservation with flag...`); - - // // get reservation with flag - // let reservationWithFlag = await model.getReservationWithFlag( - // card_number, - // now - // ); - // let totalReservationWithFlag = - // reservationWithFlag.total_reservation > 0 - // ? reservationWithFlag.total_reservation - // : 0; - // if (totalReservationWithFlag > 0) { - // result = { - // code: "420", - // message: - // "your card number has incomplete transaction. Please unload your balance!", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` - // ); - - // return res.status(200).json(result); - // } - - // log debug - // proses pencarian transaki dari table reservasi balance berdasarkan nomor kartu yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] checking total reservation pending...` - // ); - - // get total reservation pending bersarkan nomor kartu yang di request yaitu total transaksi yang status nya pending beserta jumlah amount nya - let getReservationPending = await model.getReservationPending( - card_number, - now - ); - - // jika nomor kartu yang di request ditemukan transaksi reservasi dengan status pending pada transaksi sebelumnya, maka jumlahkan total amount reservasi sebelumnya dengan amount reservasi yang dilakukan sekarang - let totalReservationPending = - getReservationPending.total_nominal_reservation > 0 - ? parseInt(getReservationPending.total_nominal_reservation) + - parseInt(amount) - : parseInt(amount); - - // jika total amount reservasi melebihi maksimum reservasi sesuai dengan parameter setting di sistem CMS maka transaksi akan di tolak - 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 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - // log debug - // process mendapatkan persentase issuer fee dan channel free berdasarkan settingan dari sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] getting issuer fee and channel fee...` - // ); - - // set default issuer fee - let issuerFee = 0; - let channelFee = 0; - - // get issuer fee dan channel fee dari table public.t_c_partner_fee - let getIssuer = await model.getIssuer(getPartner.i_partner, now); - - if (getIssuer) { - // per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi - if (today >= '2023-11-01') { - issuerFee = getIssuer.i_issuer_fee_nominal; - channelFee = getIssuer.i_channel_fee_nominal; - } else { - // ======================= KHUSUS LRT JABODEBEK ============================= - if (getPartner.partner_code == 'P05') { - issuerFee = getIssuer.i_issuer_fee_nominal; - channelFee = getIssuer.i_channel_fee_nominal; - } else { - // SELAIN LRT JABODEBEK - issuerFee = - (getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); - channelFee = - (getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); - } - } - } - - // if (!getIssuer) { - // return res.status(200).json({ - // code: "403", - // message: "issuer doesn't exist", - // data: {}, - // }); - // } - - // log debug - // proses pengecekkan value dari setting parameter untuk data reservasi yang tidak di load/topup apakah statusnya diaktifkan atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] getting reservation expiration date on parameter...` - // ); - - const { time, measure } = await model.getReservationExpiration(); - let expired = moment(now).add(time, measure).format('YYYY-MM-DD HH:mm:ss'); - - // -------------------------------- NOTES -------------------------------- - // for LRT JABO => customer_name diisi Device Name (versi penamaan LRT Jabo) dan phone_number diisi Device Code (versi kode LRT Jabo) sesuai MOM BI-WEEKLY MEETING (08/05/2023) - let customerName = customer_name; - let phoneNumber = phone_number; - - if (!customerName || customerName == '' || customerName == '-') { - customerName = getPartner ? getPartner.terminal_name : ''; - } - - if (!phoneNumber || phoneNumber == '' || phoneNumber == '-') { - phoneNumber = mid + '_' + tid; - } - - const { number: reservationNumber, sequence: reservationNoSequence } = - await model.allocateReservationNumber(getPartner.partner_code, moment(now).format('YYMMDD')); - - // binding data - let data = { - c_reservation_no: reservationNumber, - d_reservation: now, - c_ref_no: ref_no, - i_partner: getPartner ? getPartner.i_partner : null, - c_partner_code: getPartner ? getPartner.partner_code : null, - c_partner_name: getPartner ? getPartner.partner_name : null, - i_merchant: getPartner ? getPartner.i_merchant : null, - c_merchant_code: getPartner ? getPartner.merchant_code : null, - c_merchant_name: getPartner ? getPartner.merchant_name : null, - c_mid: getPartner ? getPartner.mid : null, - i_terminal: getPartner ? getPartner.i_terminal : null, - c_terminal_code: getPartner ? getPartner.terminal_code : null, - c_terminal_name: getPartner ? getPartner.terminal_name : null, - c_tid: getPartner ? getPartner.tid : null, - c_card_number: card_number, - i_reservation_amount: amount, - // i_issuer: getIssuer ? getIssuer.i_issuer : null, - // c_issuer_code: getIssuer ? getIssuer.issuer_code : null, - // c_issuer_name: getIssuer ? getIssuer.issuer_name : null, - i_issuer_fee: issuerFee, - // i_channel: null, - // c_channel_code: null, - // c_channel_name: null, - i_channel_fee: channelFee, - c_payment_ref_no: null, - i_reservation_no_seq: reservationNoSequence, - d_expired: expired, - d_load_balance: null, - c_load_balance_no: null, - c_status: 'P', - c_status_name: 'PENDING', - d_create: now, - i_create: null, - c_create_username: null, - c_create_fullname: null, - d_modify: null, - i_modify: null, - c_modify_username: null, - c_modify_fullname: null, - d_delete: null, - i_delete: null, - c_delete_username: null, - c_delete_fullname: null, - c_flag: '-1', - c_customer_name: customerName, - c_phone_number: phoneNumber, - }; - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] inserting reservation transaction...` - // ); - - // insert transaction - let insert = await model.insertReservation(data); - - // jika proses insert data semua yang berkaitan dengan reservasi saldo mengalami kegagalan, maka lakukan rollback - // kegagalan insert data transaksi bisa disebabkan karena data ref no yang di berikan client sudah digunakan - if (insert.rowCount > 0) { - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION ] inserting log for card history...` - // ); - - // log card history - await model.createReserveBalanceLog({ - i_log_name: 90, - d_log: now, - c_card_number: card_number, - c_source: 'CMS', - c_location: getPartner ? getPartner.partner_name : null, - m_balance_before: balance > 0 ? balance : 0, - m_amount: 0, - m_balance_after: balance > 0 ? balance : 0, - j_new_data: data, - j_old_data: null, - c_note: `RESERVED BALANCE ${amount} FROM ${getPartner ? getPartner.partner_name : null - } SUCCESSFULLY`, - c_status: 'S', - d_created: now, - i_create: null, - c_create_username: 'HSM', - c_create_fullname: 'HARDWARE SECURE MODULE', - c_category: 'T', - }); - - result = { - code: '00', - message: 'reservation saved successfully.', - data: { - reservation_number: reservationNumber, - reservation_time: now, - partner: getPartner ? getPartner.partner_name : null, - merchant: getPartner ? getPartner.merchant_name : null, - terminal: getPartner ? getPartner.terminal_name : null, - card_number: card_number, - reserved_amount: amount, - issuer_fee: issuerFee, - channel_fee: channelFee, - }, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } else { - result = { - code: '424', - message: 'refno is duplicate', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE RESERVATION ]: 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 V2 ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// proses insert data transaksi reservasi saldo. Proses ini dilakukan setelah melakukan reservation validate dengan response code 00. Output dari proses ini adalah kode reservation number dan informasi reservasi saldo yang dilakukan -// pada reservation version 2 ini data yang dikirim akan di cek terlebih dahulu sebelum dilakukan insert data, hal ini bertujuan agar data yang dikirim tidak doubah dalam proses perjalanan setelah melakukan reservation validate - -const reservationV2 = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { - reservation_data, - ref_no, - customer_name, - phone_number, - amount, - card_number, - } = req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST RESERVATION-V2 ]: ${JSON.stringify(req.body)}` - ); - - // trim card number - // card_number = card_number.trim(); - - // check validator - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - // log debug - // pengecekkan reservation data yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking reservation data...` - // ); - - let reservationData; - - try { - reservationData = helper.decryptText(reservation_data); - } catch (error) { } - - if (!reservationData) { - result = { - code: '435', - message: 'bad request. reservation data is invalid.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - // parsing data to json format - reservationData = JSON.parse(reservationData); - - if ( - !reservationData.mid || - !reservationData.tid || - !reservationData.card_number || - !reservationData.amount || - !reservationData.transaction_date - ) { - result = { - code: '436', - message: 'bad request. reservation data is empty.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - if (card_number) { - if (reservationData.card_number != card_number) { - result = { - code: '441', - message: - 'bad request. card number requested is different with reservation data.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - } - - let cardBlacklist = await model.getCardBlacklist( - reservationData.card_number - ); - if (cardBlacklist) { - if (cardBlacklist.c_status == 'B') { - result = { - code: '445', - message: 'Card is Blacklisted', - data: {}, - }; - return res.status(200).json(result); - } - } - - if (amount) { - if (reservationData.amount != amount) { - result = { - code: '442', - message: - 'bad request. amount requested is different with reservation data.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - } - - // extract reseravtion data - let mid = reservationData.mid; - let tid = reservationData.tid; - card_number = reservationData.card_number; - amount = reservationData.amount; - let transactionDate = reservationData.transaction_date; - let securityCode = reservationData.security_code; - - if (securityCode) { - // log debug - // process enkripsi data reservasi dengan HMAC sebagai pembanding bahwa data yang di decrypt valid - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] comparing security code with decrypt data...}` - // ); - - // create security code yang isinya data reservasi yang akan di compare nantinya saat melakukan insert reservation - let securityCodeCompare = await helper.createHMAC( - mid + '|' + tid + '|' + card_number + '|' + amount - ); - - if (securityCode !== securityCodeCompare) { - result = { - code: '437', - message: 'bad request. reservation data has been changed.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - } - - // log debug - // pengecekkan reservation data yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] extracting reservation data : ${JSON.stringify( - // { - // mid: mid, - // tid: tid, - // card_number: card_number, - // amount: amount, - // transaction_date: transactionDate, - // security_code: securityCode, - // } - // )}` - // ); - - // log debug - // pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR. - // Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya - // Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking production card number or not...` - // ); - - // jika settingan diperuntukan untuk production - // if (process.env.SERVER_FOR == 'production') { - // // kartu yang di request bukan kartu production maka akan di tolak - // if (card_number.substring(0, 1) != '1') { - // result = { - // code: '400', - // message: "It's not production card number.", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - // ); - - // return res.status(200).json(result); - // } - // } else { - // // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak - // if (card_number.substring(0, 1) == '1') { - // result = { - // code: '400', - // message: - // "It's production card number. Please use the development card number.", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${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 - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] 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-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // log debug - // get settingan dari parameter apakah nomor kartu yang di request harus di cek dengan data card product CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-VALIDATE ] getting checking card number by card product CMS status on parameter...` - // ); - - // get parameter to check with card product cms or not - let getCheckByCardProductStatusValue = - await model.getCheckByCardProductStatusValue(); - let checkByCardProductStatusValue = - getCheckByCardProductStatusValue?.c_value; - - // jika settingan pengecekkan nomor kartu yang di request dengan data card product yang ada di sistem CMS aktif - if (checkByCardProductStatusValue == 'A') { - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking card number...` - // ); - - // check card number yang di request terdaftar di card product CMS atau tidak - 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-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - } - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking reservation amount...` - // ); - - // check reservation amount - // amount reservasi harus lebih dari 0 - if (parseInt(amount) <= 0) { - result = { - code: '415', - message: 'amount must be greater than 0', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] 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} [ PROCESSING RESERVATION-V2 ] checking BI regulation status...` - // ); - - // get settingan terkait pengecekkan regulasi BI dari parameter, apakah diaktifkan atau tidak - let getBIRegulationStatus = await model.getBIRegulationStatus(); - if (getBIRegulationStatus.c_value == 'A') { - // log debug - // get maksimum saldo yang harus ada di dalam kartu berdasarkan settingan parameter di sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking max balance on the card...` - // ); - - // get max saldo on the card - let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); - // jika settingan paremeter maksimum saldo di dalam kartu ditemukan - if (getMaxAmountOnTheCard.c_value) { - // jika saldo dalam kartu diakumulasikan dengan amount reservasi dan jumlah nya ternyata melebihi jumlah maksimum saldo berdasarkan settingan parameter, maka akan transaksi akan di tolak - 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-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } - - // log debug - // proses pengecekkan akumulasi maksimum topup di bulan berjalan berdasarkan parameter setting di sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking max topup per month...` - // ); - - // get accumulated balance in this month dari nomor kartu yang di request - let accumulatedBalance = 0; - let getAccumulationBalanceInThisMonthFromCardHistory = - await model.getAccumulationBalanceInThisMonthFromCardHistory( - card_number, - year, - month - ); - - // jika ditemukan history akumulasi topup dari nomor kartu yang di request, maka set akumulasi saldo di bulan berjalan sama dengan history yang ditemukan - if (getAccumulationBalanceInThisMonthFromCardHistory) { - accumulatedBalance = - getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance; - } - - // validate max topup per month berdasarkan parameter setting - let getMaxTopupPerMonth = await model.getMaxTopupPerMonth(); - - // jika settingan parameter maksimum akumulasi topup dalam sebulan ditemukan - if (getMaxTopupPerMonth.c_value) { - // jika akumulasi saldo kartu yang di request dijumlahkan dengan amount reservasi dan ternyata melebihi jumlah akumulasi maksumum topup dalam sebelum, maka transaksi akan di tolak - 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-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } - } - - // log debug - // proses pengecekkan maksimum reservasi dengna status pending di parameter setting sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking max reservation...` - // ); - - // get maksimum reservation dengan status pending dari parameter setting - let getMaxReservation = await model.getMaxReservation(); - let maxReservation = getMaxReservation.c_value - ? parseInt(getMaxReservation.c_value) - : 0; - - // // log debug - // winston.logger.debug(`${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking reservation with flag...`); - - // // get reservation with flag - // let reservationWithFlag = await model.getReservationWithFlag( - // card_number, - // now - // ); - // let totalReservationWithFlag = - // reservationWithFlag.total_reservation > 0 - // ? reservationWithFlag.total_reservation - // : 0; - // if (totalReservationWithFlag > 0) { - // result = { - // code: "420", - // message: - // "your card number has incomplete transaction. Please unload your balance!", - // data: {}, - // }; - - // // log warn - // winston.logger.warn( - // `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - // ); - - // return res.status(200).json(result); - // } - - // log debug - // proses pencarian transaki dari table reservasi balance berdasarkan nomor kartu yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] checking total reservation pending...` - // ); - - // get total reservation pending bersarkan nomor kartu yang di request yaitu total transaksi yang status nya pending beserta jumlah amount nya - let getReservationPending = await model.getReservationPendingV2( - card_number, - now - ); - - let dataReservationPending = []; - let totalNominalReservationPending = 0; - if (getReservationPending.length > 0) { - for (let item of getReservationPending) { - // hitung total reservasi yang masih pending / belum di topup - totalNominalReservationPending = - totalNominalReservationPending + parseInt(item.i_reservation_amount); - - dataReservationPending.push({ - reservation_date: item.d_reservation, - amount: parseInt(item.i_reservation_amount), - partner_name: item.c_partner_name, - }); - } - } - - // jika nomor kartu yang di request ditemukan transaksi reservasi dengan status pending pada transaksi sebelumnya, maka jumlahkan total amount reservasi sebelumnya dengan amount reservasi yang dilakukan sekarang - let totalReservationPending = - totalNominalReservationPending > 0 - ? parseInt(totalNominalReservationPending) + parseInt(amount) - : parseInt(amount); - - // jika total amount reservasi melebihi maksimum reservasi sesuai dengan parameter setting di sistem CMS maka transaksi akan di tolak - 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-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - // log debug - // process mendapatkan persentase issuer fee dan channel free berdasarkan settingan dari sistem CMS - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] getting issuer fee and channel fee...` - // ); - - // set default issuer fee - let issuerFee = 0; - let channelFee = 0; - - // get issuer fee dan channel fee dari table public.t_c_partner_fee - let getIssuer = await model.getIssuer(getPartner.i_partner, now); - - if (getIssuer) { - // per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi - if (today >= '2023-11-01') { - issuerFee = getIssuer.i_issuer_fee_nominal; - channelFee = getIssuer.i_channel_fee_nominal; - } else { - // ======================= KHUSUS LRT JABODEBEK ============================= - if (getPartner.partner_code == 'P05') { - issuerFee = getIssuer.i_issuer_fee_nominal; - channelFee = getIssuer.i_channel_fee_nominal; - } else { - // SELAIN LRT JABODEBEK - issuerFee = - (getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); - channelFee = - (getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); - } - } - } - - // if (!getIssuer) { - // return res.status(200).json({ - // code: "403", - // message: "issuer doesn't exist", - // data: {}, - // }); - // } - - // log debug - // proses pengecekkan value dari setting parameter untuk data reservasi yang tidak di load/topup apakah statusnya diaktifkan atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] getting reservation expiration date on parameter...` - // ); - - const { time, measure } = await model.getReservationExpiration(); - let expired = moment(now).add(time, measure).format('YYYY-MM-DD HH:mm:ss'); - - // -------------------------------- NOTES -------------------------------- - // for LRT JABO => customer_name diisi Device Name (versi penamaan LRT Jabo) dan phone_number diisi Device Code (versi kode LRT Jabo) sesuai MOM BI-WEEKLY MEETING (08/05/2023) - let customerName = customer_name; - let phoneNumber = phone_number; - - if (!customerName || customerName == '' || customerName == '-') { - customerName = getPartner ? getPartner.terminal_name : ''; - } - - if (!phoneNumber || phoneNumber == '' || phoneNumber == '-') { - phoneNumber = mid + '_' + tid; - } - - const { number: reservationNumber, sequence: reservationNoSequence } = - await model.allocateReservationNumber(getPartner.partner_code, moment(now).format('YYMMDD')); - - // binding data - let data = { - c_reservation_no: reservationNumber, - d_reservation: now, - c_ref_no: ref_no, - i_partner: getPartner ? getPartner.i_partner : null, - c_partner_code: getPartner ? getPartner.partner_code : null, - c_partner_name: getPartner ? getPartner.partner_name : null, - i_merchant: getPartner ? getPartner.i_merchant : null, - c_merchant_code: getPartner ? getPartner.merchant_code : null, - c_merchant_name: getPartner ? getPartner.merchant_name : null, - c_mid: getPartner ? getPartner.mid : null, - i_terminal: getPartner ? getPartner.i_terminal : null, - c_terminal_code: getPartner ? getPartner.terminal_code : null, - c_terminal_name: getPartner ? getPartner.terminal_name : null, - c_tid: getPartner ? getPartner.tid : null, - c_card_number: card_number, - i_reservation_amount: amount, - // i_issuer: getIssuer ? getIssuer.i_issuer : null, - // c_issuer_code: getIssuer ? getIssuer.issuer_code : null, - // c_issuer_name: getIssuer ? getIssuer.issuer_name : null, - i_issuer_fee: issuerFee, - // i_channel: null, - // c_channel_code: null, - // c_channel_name: null, - i_channel_fee: channelFee, - c_payment_ref_no: null, - i_reservation_no_seq: reservationNoSequence, - d_expired: expired, - d_load_balance: null, - c_load_balance_no: null, - c_status: 'P', - c_status_name: 'PENDING', - d_create: now, - i_create: null, - c_create_username: null, - c_create_fullname: null, - d_modify: null, - i_modify: null, - c_modify_username: null, - c_modify_fullname: null, - d_delete: null, - i_delete: null, - c_delete_username: null, - c_delete_fullname: null, - c_flag: '-1', - c_customer_name: customerName, - c_phone_number: phoneNumber, - }; - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] inserting reservation transaction...` - // ); - - // (belum) ada issue disini, jadi ada case reservation number nya sama, terus error query harusnya ada handle response message nya, yg sekarang malah masuk ke blok reservation saved successfully. - - // insert transaction - let insert = await model.insertReservation(data); - - // jika proses insert data semua yang berkaitan dengan reservasi saldo mengalami kegagalan, maka lakukan rollback - // kegagalan insert data transaksi bisa disebabkan karena data ref no yang di berikan client sudah digunakan - if (insert.rowCount > 0) { - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] inserting log for card history...` - // ); - - // log card history - await model.createReserveBalanceLog({ - i_log_name: 90, - d_log: now, - c_card_number: card_number, - c_source: 'CMS', - c_location: getPartner ? getPartner.partner_name : null, - m_balance_before: balance > 0 ? balance : 0, - m_amount: 0, - m_balance_after: balance > 0 ? balance : 0, - j_new_data: data, - j_old_data: null, - c_note: `RESERVED BALANCE ${amount} FROM ${getPartner ? getPartner.partner_name : null - } SUCCESSFULLY`, - c_status: 'S', - d_created: now, - i_create: null, - c_create_username: 'HSM', - c_create_fullname: 'HARDWARE SECURE MODULE', - c_category: 'T', - }); - - result = { - code: '00', - message: 'reservation saved successfully.', - data: { - reservation_number: reservationNumber, - reservation_time: now, - partner: getPartner ? getPartner.partner_name : null, - merchant: getPartner ? getPartner.merchant_name : null, - terminal: getPartner ? getPartner.terminal_name : null, - card_number: card_number, - reserved_amount: amount, - issuer_fee: issuerFee, - channel_fee: channelFee, - }, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } else { - result = { - code: '424', - message: 'refno is duplicate', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE RESERVATION-V2 ]: 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: {}, - }); - } -}; - -// ================================================================= CANCEL RESERVATION VALIDATE ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// proses yang digunakan untuk melakukan validasi apakah transaksi reservasi saldo dapat dibatalkan atau tidak. Proses ini seharusnya dilakukan sebelum melakukan insert data pembatalan reservasi saldo ke sistem CMS - -const cancelReservationValidate = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { mid, tid, reservation_number } = req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( - req.body - )}` - ); - - // check validator - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE ]: checking partner...` - // ); - - // 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 CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan status reservation number yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE ]: getting reservation by reservation number...` - // ); - - // get reservation berdasarkan reservation number yang di request - let getReservationCanBeCanceled = await model.getReservationCanBeCanceled( - reservation_number - ); - - // jika data reservasi ditemukan - if (getReservationCanBeCanceled) { - // jika status dari reservation number yang di request adalah I = In Progress atau A = Loaded, maka proses cancel reservasi akan di tolak - if ( - getReservationCanBeCanceled.c_status == 'I' || - getReservationCanBeCanceled.c_status == 'A' - ) { - result = { - code: '429', - message: 'can not be cancelled. The transaction has been loaded.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } else if (getReservationCanBeCanceled.c_status == 'X') { - // jika status dari reservation number yang di request adalah X = Deleted, maka proses cancel reservasi akan di tolak - let cancelDate = getReservationCanBeCanceled.d_cancel - ? moment(getReservationCanBeCanceled.d_cancel).format( - 'DD-MM-YYYY HH:mm:ss' - ) - : ''; - result = { - code: '430', - message: `can not be cancelled. The transaction has been canceled at ${cancelDate}.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} RESPONSE cancel reservation validate: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } else if (getReservationCanBeCanceled.c_payment_recon_no) { - // jika reservation number yang di request sudah dilakukan payment recon, maka proses cancel reservasi akan di tolak - result = { - code: '430', - message: `can not be cancelled. The transaction has been recon.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } else { - // jika reservation number yang di request tidak ditemukan di sistem CMS - result = { - code: '414', - message: "Reservation doesn't exist.", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - result = { - code: '00', - message: 'reservation can be canceled.', - data: {}, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE CANCEL-RESERVATION-VALIDATE ]: 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: {}, - }); - } -}; - -// ================================================================= CANCEL RESERVATION ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// proses insert data pembatalan reservasi saldo dengan memberikan flag pada reservation number yang di request sehingga reservation number tersebut tidak ter-load saat melakukan topup ke dalam kartu - -const cancelReservation = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { mid, tid, reservation_number } = req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST CANCEL-RESERVATION ]: ${JSON.stringify( - req.body - )}` - ); - - // check validator - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: 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 CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan status reservation number yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: getting reservation by reservation number...` - // ); - - // get reservation pending & in progress status - let getReservationCanBeCanceled = await model.getReservationCanBeCanceled( - reservation_number - ); - if (getReservationCanBeCanceled) { - if ( - getReservationCanBeCanceled.c_status == 'I' || - getReservationCanBeCanceled.c_status == 'A' - ) { - result = { - code: '429', - message: 'can not be cancelled. The transaction has been loaded.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } else if (getReservationCanBeCanceled.c_status == 'X') { - let cancelDate = getReservationCanBeCanceled.d_cancel - ? moment(getReservationCanBeCanceled.d_cancel).format( - 'DD-MM-YYYY HH:mm:ss' - ) - : ''; - result = { - code: '430', - message: `can not be cancelled. The transaction has been canceled at ${cancelDate}.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } else if (getReservationCanBeCanceled.c_payment_recon_no) { - result = { - code: '430', - message: `can not be cancelled. The transaction has been recon.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } else { - result = { - code: '414', - message: "Reservation doesn't exist.", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: getting last balance on the card by card history...` - // ); - - // get last balance on the card - let balance = 0; - let getLastBalanceFromCardHistory = - await model.getLastBalanceFromCardHistory( - getReservationCanBeCanceled.c_card_number - ); - if (getLastBalanceFromCardHistory) { - balance = getLastBalanceFromCardHistory.m_balance_after; - } - - // time - let now = moment().format('YYYY-MM-DD HH:mm:ss'); - - // binding data - let data = { - c_status: 'X', - c_status_name: 'CANCELED', - d_cancel: now, - }; - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: updating reservation to status cancel...` - // ); - - // cancel transaction - await model.cancelReservation(data, reservation_number); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: inserting log for card history...` - // ); - - // log card history - await model.createReserveBalanceLog({ - i_log_name: 110, - d_log: now, - c_card_number: getReservationCanBeCanceled.c_card_number, - c_source: 'CMS', - c_location: getPartner ? getPartner.partner_name : null, - m_balance_before: balance > 0 ? balance : 0, - m_amount: 0, - m_balance_after: balance > 0 ? balance : 0, - j_new_data: data, - j_old_data: getReservationCanBeCanceled, - c_note: `CANCEL RESERVE BALANCE ${getReservationCanBeCanceled.i_reservation_amount - } FROM ${getPartner ? getPartner.partner_name : null}`, - c_status: 'S', - d_created: now, - i_create: null, - c_create_username: 'HSM', - c_create_fullname: 'HARDWARE SECURE MODULE', - c_category: 'T', - }); - - result = { - code: '00', - message: 'reservation successfully canceled.', - data: {}, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE CANCEL-RESERVATION ]: 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: {}, - }); - } -}; - -// ================================================================= INQUIRY RESERVATION ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// - -const inquiryReservation = async (req, res) => { - try { - // param - let { reservation_number, card_number, start_date, end_date } = req.body; - - // time - let now = moment().format('YYYY-MM-DD HH:mm:ss'); - - // validation parameter inquiry - if (!reservation_number && !card_number) { - return res.status(200).json({ - code: '400', - message: - 'bad request. please add the reservation number or card number!', - data: {}, - }); - } - - // validation inquiry date - if ((!start_date && end_date) || (start_date && !end_date)) { - return res.status(200).json({ - code: '400', - message: 'bad request. please check the date!', - data: {}, - }); - } - - // check reservation - if (reservation_number) { - let byReservationNumber = await model.inquiryByReservationNumber( - reservation_number - ); - - if (!byReservationNumber) { - return res.status(200).json({ - code: '414', - message: "reservation doesn't exist", - data: {}, - }); - } - - return res.json({ - code: '00', - message: 'reservation has been found.', - data: byReservationNumber, - }); - } else if (card_number) { - let byCardNumber = await model.inquiryByCardNumber( - card_number, - start_date, - end_date - ); - - if (!byCardNumber) { - return res.status(200).json({ - code: '414', - message: "reservation doesn't exist", - data: [], - }); - } - - return res.json({ - code: '00', - message: 'reservation has been found.', - data: byCardNumber, - }); - } - } catch (error) { - return res.status(200).json({ - code: '500', - message: - process.env.NODE_ENV != 'production' - ? error.message - : '500 internal server error - backend server.', - data: {}, - }); - } -}; - -// ================================================================= INQUIRY RESERVATION BY REF NUMBER ================================================================= -// *Created By: Teddy Setiawan* -// *Description:* -// - -const inquiryReservationByReservation = async (req, res) => { - try { - // param - let { - reservation_number, - ref_no, - load_balance_number, - show_complete_data, - } = req.body; - - let result; - - if (req.query.search === 'ref-no') { - // validation parameter inquiry - if (!ref_no) { - return res.status(200).json({ - code: '400', - message: 'bad request. please add the ref number!', - data: {}, - }); - } - - // check reservation - result = await model.inquiryListByRefNumber(ref_no, show_complete_data); - - if (!result) { - return res.status(200).json({ - code: '414', - message: "reservation doesn't exist", - data: {}, - }); - } - } else if (req.query.search === 'load-balance-number') { - // validation parameter inquiry - if (!load_balance_number) { - return res.status(200).json({ - code: '400', - message: 'bad request. please add the load balance number!', - data: {}, - }); - } - - // check reservation - result = await model.inquiryListByLoadNumber( - load_balance_number, - show_complete_data - ); - - if (result.length < 1) { - return res.status(200).json({ - code: '414', - message: "reservation doesn't exist", - data: {}, - }); - } - } else { - // validation parameter inquiry - if (!reservation_number) { - return res.status(200).json({ - code: '400', - message: 'bad request. please add the reservation number!', - data: {}, - }); - } - - // check reservation - result = await model.inquiryByReservationNumber( - reservation_number, - show_complete_data - ); - - if (!result) { - return res.status(200).json({ - code: '414', - message: "reservation doesn't exist", - data: {}, - }); - } - } - - return res.json({ - code: '00', - message: 'reservation has been found.', - data: result, - }); - } catch (error) { - return res.status(200).json({ - code: '500', - message: - process.env.NODE_ENV != 'production' - ? error.message - : '500 internal server error - backend server.', - data: {}, - }); - } -}; - -const inquiryListReservationByReservation = async (req, res) => { - try { - // param - let { start_date, end_date } = req.body; - - // validation parameter inquiry - if (!start_date || !end_date) { - return res.status(200).json({ - code: '400', - message: 'bad request. please add the start date and end date!', - data: {}, - }); - } - - let startDateCheckFormat = moment(start_date, 'YYYY-MM-DD', true).isValid(); - let endDateCheckFormat = moment(end_date, 'YYYY-MM-DD', true).isValid(); - - if (startDateCheckFormat == false || endDateCheckFormat == false) { - return res.status(200).json({ - code: '400', - message: 'bad request. format start date or end date is invalid!', - data: {}, - }); - } - - // check date range max 1 month - let diff = moment(end_date).diff(moment(start_date), 'months', true); - - if (diff >= 1) { - return res.status(200).json({ - code: '400', - message: - 'bad request. We only allow data requests for 1 month. please change your date range parameter request!', - data: {}, - }); - } - - // check reservation - let listReservation = await model.inquiryListReservation( - req.partner_id_token, - start_date, - end_date - ); - - if (!listReservation) { - return res.status(200).json({ - code: '414', - message: "reservation doesn't exist", - data: {}, - }); - } - - return res.json({ - code: '00', - message: 'reservation has been found.', - data: listReservation, - }); - } catch (error) { - return res.status(200).json({ - code: '500', - message: - process.env.NODE_ENV != 'production' - ? error.message - : '500 internal server error - backend server.', - data: {}, - }); - } -}; - -// ================================================================= CANCEL RESERVATION V2 ================================================================= -// *Created By: Teddy Setiawan* -// *Description:* -// -const cancelReservationValidateV2 = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { mid, tid, reservation_number, ref_no } = req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - req.body - )}` - ); - - // check validator - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ]: 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 CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - let getReservationCanBeCanceled; - - // jika cancelation reservation dilakukan dengan menggunakan ref no - if (ref_no) { - if (!ref_no) { - result = { - code: '400', - message: 'Ref no is required', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan status reservation number yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ]: getting reservation by ref no...` - // ); - - // get reservation berdasarkan ref_no yang di request - getReservationCanBeCanceled = - await model.getReservationCanBeCanceledByRefno(ref_no); - - if (!getReservationCanBeCanceled) { - result = { - code: '440', - message: "Ref no doesn't exist.", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - } else { - if (!reservation_number) { - result = { - code: '400', - message: 'Reservation number is required', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan status reservation number yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ]: getting reservation by reservation number...` - // ); - - // get reservation berdasarkan reservation number yang di request - getReservationCanBeCanceled = await model.getReservationCanBeCanceled( - reservation_number - ); - - if (!getReservationCanBeCanceled) { - result = { - code: '414', - message: "Reservation doesn't exist.", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - } - - let reservationNumber = getReservationCanBeCanceled?.c_reservation_no; - let cardNumber = getReservationCanBeCanceled?.c_card_number; - let amount = getReservationCanBeCanceled?.i_reservation_amount; - - // get value global parameter - let getGlobalParameter = await model.getGlobalParameter(); - // check value global parameter - if (!getGlobalParameter) { - result = { - code: '439', - message: 'HSM_CANCEL_RESERVATION_LEVEL in global parameter not found', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - return res.status(200).json(result); - } - // validasi sesuai value global parameter - if (getGlobalParameter.c_value == 'PARTNER') { - if (getPartner.i_partner != getReservationCanBeCanceled.i_partner) { - result = { - code: '438', - message: 'Can not be canceled on different source', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } else if (getGlobalParameter.c_value == 'MERCHANT') { - if (getPartner.i_merchant != getReservationCanBeCanceled.i_merchant) { - result = { - code: '438', - message: 'Can not be canceled on different source', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } else if (getGlobalParameter.c_value == 'TERMINAL') { - if (getPartner.i_terminal != getReservationCanBeCanceled.i_terminal) { - result = { - code: '438', - message: 'Can not be canceled on different source', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } - - // jika data reservasi ditemukan - if (getReservationCanBeCanceled) { - // jika status dari reservation number yang di request adalah I = In Progress atau A = Loaded, maka proses cancel reservasi akan di tolak - if ( - getReservationCanBeCanceled.c_status == 'I' || - getReservationCanBeCanceled.c_status == 'A' - ) { - result = { - code: '429', - message: 'can not be cancelled. The transaction has been loaded.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } else if (getReservationCanBeCanceled.c_status == 'X') { - // jika status dari reservation number yang di request adalah X = Deleted, maka proses cancel reservasi akan di tolak - let cancelDate = getReservationCanBeCanceled.d_cancel - ? moment(getReservationCanBeCanceled.d_cancel).format( - 'DD-MM-YYYY HH:mm:ss' - ) - : ''; - result = { - code: '430', - message: `can not be cancelled. The transaction has been canceled at ${cancelDate}.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } else if (getReservationCanBeCanceled.c_payment_recon_no) { - // jika reservation number yang di request sudah dilakukan payment recon, maka proses cancel reservasi akan di tolak - result = { - code: '430', - message: `can not be cancelled. The transaction has been recon.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } else { - // jika reservation number yang di request tidak ditemukan di sistem CMS - result = { - code: '414', - message: "Reservation doesn't exist.", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // time - let now = moment().format('YYYY-MM-DD HH:mm:ss'); - - // create security code yang isinya data reservasi yang akan di compare nantinya saat melakukan insert reservation - let securityCode = await helper.createHMAC( - mid + '|' + tid + '|' + reservationNumber - ); - - let reservationData = { - mid: mid, - tid: tid, - reservation_number: reservationNumber, - transaction_date: now, - security_code: securityCode, - }; - - // log debug - // process enkripsi data reservasi dengan AES yang nanti nya akan di kirim ke end point reservation api untuk menyimpan data reservasi - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-VALIDATE-V2 ] encrypting data reservation: ${JSON.stringify( - // reservationData - // )}` - // ); - - // enkripsi data reservasi sebelum melakukan transaksi reservasi - let hash = helper.encryptText(JSON.stringify(reservationData)); - - result = { - code: '00', - message: 'reservation can be canceled.', - data: { - cancel_reservation_data: hash, - cancel_reservation_detail: { - reservation_number: reservationNumber, - card_number: cardNumber, - amount: amount, - }, - }, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE CANCEL-RESERVATION-VALIDATE-V2 ]: 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 cancelReservationV2 = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { cancel_reservation_data } = req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST CANCEL-RESERVATION ]: ${JSON.stringify( - req.body - )}` - ); - - // check validator - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - let cancelReservationData; - - try { - cancelReservationData = helper.decryptText(cancel_reservation_data); - } catch (error) { } - - if (!cancelReservationData) { - result = { - code: '435', - message: 'bad request. reservation data is invalid.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - // parsing data to json format - cancelReservationData = JSON.parse(cancelReservationData); - - if ( - !cancelReservationData.mid || - !cancelReservationData.tid || - !cancelReservationData.reservation_number || - !cancelReservationData.transaction_date - ) { - result = { - code: '436', - message: 'bad request. reservation data is empty.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: checking partner...` - // ); - - // get partner, merchant, terminal from tid - let getPartner = await model.getPartner( - cancelReservationData.mid, - cancelReservationData.tid - ); - if (!getPartner) { - result = { - code: '412', - message: 'terminal id is not valid', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan status reservation number yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: getting reservation by reservation number...` - // ); - - // get reservation pending & in progress status - let getReservationCanBeCanceled = await model.getReservationCanBeCanceled( - cancelReservationData.reservation_number - ); - if (getReservationCanBeCanceled) { - if ( - getReservationCanBeCanceled.c_status == 'I' || - getReservationCanBeCanceled.c_status == 'A' - ) { - result = { - code: '429', - message: 'can not be cancelled. The transaction has been loaded.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } else if (getReservationCanBeCanceled.c_status == 'X') { - let cancelDate = getReservationCanBeCanceled.d_cancel - ? moment(getReservationCanBeCanceled.d_cancel).format( - 'DD-MM-YYYY HH:mm:ss' - ) - : ''; - result = { - code: '430', - message: `can not be cancelled. The transaction has been canceled at ${cancelDate}.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } else if (getReservationCanBeCanceled.c_payment_recon_no) { - result = { - code: '430', - message: `can not be cancelled. The transaction has been recon.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } else { - result = { - code: '414', - message: "Reservation doesn't exist.", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: getting last balance on the card by card history...` - // ); - - // get last balance on the card - let balance = 0; - let getLastBalanceFromCardHistory = - await model.getLastBalanceFromCardHistory( - getReservationCanBeCanceled.c_card_number - ); - if (getLastBalanceFromCardHistory) { - balance = getLastBalanceFromCardHistory.m_balance_after; - } - - // time - let now = moment().format('YYYY-MM-DD HH:mm:ss'); - - // binding data - let data = { - c_status: 'X', - c_status_name: 'CANCELED', - d_cancel: now, - }; - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: updating reservation to status cancel...` - // ); - - // cancel transaction - await model.cancelReservation( - data, - cancelReservationData.reservation_number - ); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION ]: inserting log for card history...` - // ); - - // log card history - await model.createReserveBalanceLog({ - i_log_name: 110, - d_log: now, - c_card_number: getReservationCanBeCanceled.c_card_number, - c_source: 'CMS', - c_location: getPartner ? getPartner.partner_name : null, - m_balance_before: balance > 0 ? balance : 0, - m_amount: 0, - m_balance_after: balance > 0 ? balance : 0, - j_new_data: data, - j_old_data: getReservationCanBeCanceled, - c_note: `CANCEL RESERVE BALANCE ${getReservationCanBeCanceled.i_reservation_amount - } FROM ${getPartner ? getPartner.partner_name : null}`, - c_status: 'S', - d_created: now, - i_create: null, - c_create_username: 'HSM', - c_create_fullname: 'HARDWARE SECURE MODULE', - c_category: 'T', - }); - - result = { - code: '00', - message: 'reservation successfully canceled.', - data: { - reservation_number: getReservationCanBeCanceled.c_reservation_no, - reservation_amount: getReservationCanBeCanceled.i_reservation_amount, - }, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE CANCEL-RESERVATION ]: 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: {}, - }); - } -}; - -// ================================================================= CANCEL RESERVATION V2.1 ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// proses validate sekaligus insert data pembatalan reservasi saldo dengan memberikan flag pada reservation number yang di request sehingga reservation number tersebut tidak ter-load saat melakukan topup ke dalam kartu -// proses di version v2.1 ini, bisa digunakan tanpa harus melakukan cancel reservation validate terlebih dahulu - -const cancelReservationV2_1 = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { mid, tid, reservation_number } = req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( - req.body - )}` - ); - - // check validator - let err = validationResult(req, res); - if (!err.isEmpty()) { - result = { - code: '400', - message: err.errors[0].msg, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: 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 CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // log debug - // proses pengecekkan status reservation number yang di request - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: getting reservation by reservation number...` - // ); - - // get reservation berdasarkan reservation number yang di request - let getReservationCanBeCanceled = await model.getReservationCanBeCanceled( - reservation_number - ); - - // jika data reservasi ditemukan - if (getReservationCanBeCanceled) { - // jika status dari reservation number yang di request adalah I = In Progress atau A = Loaded, maka proses cancel reservasi akan di tolak - if ( - getReservationCanBeCanceled.c_status == 'I' || - getReservationCanBeCanceled.c_status == 'A' - ) { - result = { - code: '429', - message: 'can not be cancelled. The transaction has been loaded.', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } else if (getReservationCanBeCanceled.c_status == 'X') { - // jika status dari reservation number yang di request adalah X = Deleted, maka proses cancel reservasi akan di tolak - let cancelDate = getReservationCanBeCanceled.d_cancel - ? moment(getReservationCanBeCanceled.d_cancel).format( - 'DD-MM-YYYY HH:mm:ss' - ) - : ''; - result = { - code: '430', - message: `can not be cancelled. The transaction has been canceled at ${cancelDate}.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} RESPONSE cancel reservation validate: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } else if (getReservationCanBeCanceled.c_payment_recon_no) { - // jika reservation number yang di request sudah dilakukan payment recon, maka proses cancel reservasi akan di tolak - result = { - code: '430', - message: `can not be cancelled. The transaction has been recon.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - } else { - // jika reservation number yang di request tidak ditemukan di sistem CMS - result = { - code: '414', - message: "Reservation doesn't exist.", - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses checking partner yang request cancel dengan data reservasi yang mau di cancel apakah dari partner yang sama - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: checking partner request with partner reservation...` - // ); - - if (getPartner.i_partner != getReservationCanBeCanceled.i_partner) { - // partner yang request cancel tidak sama dengan partner dari data reservasi - result = { - code: '438', - message: `can not be cancelled on different source.`, - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } - - // log debug - // proses pencarian saldo terakhir dari nomor kartu yang di request berdasarkan data log hitory - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: getting last balance on the card by card history...` - // ); - - // get last balance on the card - let balance = 0; - let getLastBalanceFromCardHistory = - await model.getLastBalanceFromCardHistory( - getReservationCanBeCanceled.c_card_number - ); - if (getLastBalanceFromCardHistory) { - balance = getLastBalanceFromCardHistory.m_balance_after; - } - - // time - let now = moment().format('YYYY-MM-DD HH:mm:ss'); - - // binding data - let data = { - c_status: 'X', - c_status_name: 'CANCELED', - d_cancel: now, - }; - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: updating reservation to status cancel...` - // ); - - // cancel transaction - await model.cancelReservation(data, reservation_number); - - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING CANCEL-RESERVATION-V2.1 ]: inserting log for card history...` - // ); - - // log card history - await model.createReserveBalanceLog({ - i_log_name: 110, - d_log: now, - c_card_number: getReservationCanBeCanceled.c_card_number, - c_source: 'CMS', - c_location: getPartner ? getPartner.partner_name : null, - m_balance_before: balance > 0 ? balance : 0, - m_amount: 0, - m_balance_after: balance > 0 ? balance : 0, - j_new_data: data, - j_old_data: getReservationCanBeCanceled, - c_note: `CANCEL RESERVE BALANCE ${getReservationCanBeCanceled.i_reservation_amount - } FROM ${getPartner ? getPartner.partner_name : null}`, - c_status: 'S', - d_created: now, - i_create: null, - c_create_username: 'HSM', - c_create_fullname: 'HARDWARE SECURE MODULE', - c_category: 'T', - }); - - result = { - code: '00', - message: 'reservation successfully canceled.', - data: {}, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE CANCEL-RESERVATION-V2.1 ]: ${JSON.stringify( - result - )}` - ); - - return res.status(200).json(result); - } catch (error) { - // create log - winston.logger.error( - `[ RESPONSE CANCEL-RESERVATION-V2.1 ]: 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: {}, - }); - } -}; - -// ================================================================= GET FEE SHARING ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// proses fee sharing - -const getFeeSharing = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - // param - let { datetime, mid, tid } = req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST GET-FEE-SHARING ]: ${JSON.stringify(req.body)}` - ); - - // datetime - if (!datetime) { - datetime = moment().format('YYYY-MM-DD'); - } else { - datetime = moment(datetime).format('YYYY-MM-DD'); - } - - // log debug - // proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING GET-FEE-SHARING ] checking partner...` - // ); - - // get partner, merchant, terminal from tid - let getPartner = await model.getPartner(mid, tid); - - // jika partner (mid atau tid) tidak ditemukan atau tidak terdaftar di sistem CMS - if (!getPartner) { - result = { - code: '412', - message: 'terminal id is not valid', - data: {}, - }; - - // log warn - winston.logger.warn( - `${uniqueCode} [ RESPONSE GET-FEE-SHARING ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } - - if (getPartner.i_partner != req.partner_id_token) { - result = { - code: '412', - message: 'partner is not match', - data: {}, - }; - - return res.status(200).json(result); - } - - // set default issuer fee - let issuerFee = 0; - let channelFee = 0; - - // get issuer fee dan channel fee dari table public.t_c_partner_fee - let getIssuer = await model.getIssuer(getPartner.i_partner, datetime); - - if (getIssuer) { - // per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi - if (datetime >= '2023-11-01') { - issuerFee = getIssuer.i_issuer_fee_nominal; - channelFee = getIssuer.i_channel_fee_nominal; - } else { - // ======================= KHUSUS LRT JABODEBEK ============================= - if (getPartner.partner_code == 'P05') { - issuerFee = getIssuer.i_issuer_fee_nominal; - channelFee = getIssuer.i_channel_fee_nominal; - } else { - // SELAIN LRT JABODEBEK - issuerFee = - (getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount); - channelFee = - (getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount); - } - } - } - - result = { - code: '00', - message: 'fee sharing has been found.', - data: { - issuer_fee: issuerFee, - channel_fee: channelFee, - }, - }; - - // log info - winston.logger.info( - `${uniqueCode} [ RESPONSE GET-FEE-SHARING ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } catch (error) { - return res.status(200).json({ - code: '500', - message: - process.env.NODE_ENV != 'production' - ? error.message - : '500 internal server error - backend server.', - data: {}, - }); - } -}; - -const decrpytRequest = async (req, res) => { - try { - // generate unique code - // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca - let uniqueCode = await helper.getUniqueCode(); - let result = {}; - - let { reservation_data } = req.body; - - // log info - winston.logger.info( - `${uniqueCode} [ REQUEST DECRYPT ]: received` - ); - - const reservationData = helper.decryptText(reservation_data); - // parsing data to json format - const parseData = JSON.parse(reservationData); - result = { - code: '00', - message: 'decrypted successfully.', - data: parseData, - }; - - // log warn - winston.logger.info( - `${uniqueCode} [ RESPONSE DECRYPT ]: ${result.code}` - ); - - return res.status(200).json(result); - } catch (error) { - const result = { - code: '500', - message: 'decrypted failed.', - data: {}, - }; - - // log warn - winston.logger.error( - `${uniqueCode} [ RESPONSE DECRYPT ]: ${JSON.stringify(result)}` - ); - - return res.status(200).json(result); - } -}; - module.exports = { validate, checkReservation, diff --git a/application/tests/loadbalance-reservations.test.js b/application/tests/loadbalance-reservations.test.js index 0775144..7d32a5f 100644 --- a/application/tests/loadbalance-reservations.test.js +++ b/application/tests/loadbalance-reservations.test.js @@ -23,6 +23,18 @@ beforeEach(() => { model.getPartner.mockResolvedValue({ i_partner: '1', partner_code: 'TEST' }); }); +test('menolak terminal milik partner lain sebelum membaca atau menulis reservasi', async () => { + model.getPartner.mockResolvedValue({ i_partner: '2' }); + + await expect(loadingBalanceInsert(req, input)).resolves.toEqual({ + code: '412', + message: 'partner is not match', + data: {}, + }); + expect(model.findReservationsWithLoadedBalance).not.toHaveBeenCalled(); + expect(model.insertLoadingBalance).not.toHaveBeenCalled(); +}); + test.each([ [['missing', 'RBL1'], '414'], [['RBL1', 'missing'], '00'], diff --git a/application/tests/pos-reservation-handlers.test.js b/application/tests/pos-reservation-handlers.test.js new file mode 100644 index 0000000..d394432 --- /dev/null +++ b/application/tests/pos-reservation-handlers.test.js @@ -0,0 +1,71 @@ +jest.mock('../helpers/helper', () => ({ + getUniqueCode: () => 'request-fixture', + decryptText: jest.fn(), +})); +jest.mock('../helpers/winston.logger', () => ({ + logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() }, +})); +jest.mock('../modules/reservebalance/reservebalance.model', () => ({})); +jest.mock('../modules/pos/pos.model', () => ({ + getGlobalParameterData: jest.fn(), + getCardReplacement: jest.fn(), + getCardProduct: jest.fn(), +})); + +const helper = require('../helpers/helper'); +const posModel = require('../modules/pos/pos.model'); +const pos = require('../modules/pos/pos.controller'); +const reservation = require('../modules/reservebalance/reservebalance.controller'); +const { validateCardProduct, validateBIRegulation } = require('../modules/pos/card-validation.service'); + +function response() { + return { status: jest.fn().mockReturnThis(), json: jest.fn() }; +} + +beforeEach(() => jest.resetAllMocks()); + +test('data reservasi yang gagal didekripsi mengembalikan respons lama berkode 500', async () => { + helper.decryptText.mockImplementation(() => { throw new Error('Invalid data'); }); + const res = response(); + + await reservation.decrpytRequest({ body: { reservation_data: 'fixture' } }, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledWith({ code: '500', message: 'decrypted failed.', data: {} }); +}); + +test('kartu yang sudah aktif ditolak sebagai kartu pengganti dengan kode 453', async () => { + posModel.getGlobalParameterData.mockImplementation(async (name) => ({ + c_value: name === 'POS_VALIDATE_CARD_PRODUCT' ? 'A' : 'N', + })); + posModel.getCardProduct.mockResolvedValue({ c_status: 'A' }); + const res = response(); + + await pos.validateNewCardReplacement({ body: { card_number: 'fixture' } }, res); + + expect(res.status).toHaveBeenCalledWith(200); + expect(res.json).toHaveBeenCalledTimes(1); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ + code: '453', + data: { status: false, perso_status: true, detail: {} }, + })); +}); + +test('kegagalan validasi lingkungan mengakhiri alur sebelum memeriksa kartu', async () => { + posModel.getGlobalParameterData.mockResolvedValue({}); + const res = response(); + + await pos.validateNewCardReplacement({ body: { card_number: 'fixture' } }, res); + + expect(res.json).toHaveBeenCalledTimes(1); + expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ code: '400' })); + expect(posModel.getCardReplacement).not.toHaveBeenCalled(); +}); + +test('parameter POS yang kosong dikembalikan sebagai penolakan terkontrol', async () => { + posModel.getGlobalParameterData.mockResolvedValue({}); + + await expect(validateCardProduct('fixture', 'request-fixture')).resolves.toMatchObject({ code: '400' }); + await expect(validateBIRegulation('fixture', 100, 0, 'request-fixture')) + .resolves.toMatchObject({ code: '400' }); +});