const { param, body, validationResult } = require('express-validator'); const helper = require('../../helpers/helper'); const winston = require('../../helpers/winston.logger'); const model = require('./loadbalance.model'); const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const moment = require('moment'); const { setLoadBalanceNumberSequence, } = require('../../middlewares/redis.middleware'); moment.locale('id'); // variable yang digunakan untuk melakukan perulangan proses generate reservation number jika reservation number yang di generate sudah digunakan orang lain var maxLoopParameter = 1000; // VALIDATION const validate = (method) => { switch (method) { case 'loadingBalanceRequest': return [ body('mid').not().isEmpty().withMessage('MID is required'), body('tid').not().isEmpty().withMessage('TID is required'), body('uid').not().isEmpty().withMessage('UID is required'), body('flag').not().isEmpty().withMessage('Flag is required'), body('card_number') .not() .isEmpty() .withMessage('Card Number is required'), ]; case 'loadingBalance': return [ body('mid').not().isEmpty().withMessage('MID is required'), body('tid').not().isEmpty().withMessage('TID is required'), body('uid').not().isEmpty().withMessage('UID is required'), body('flag').not().isEmpty().withMessage('Flag is required'), body('card_number') .not() .isEmpty() .withMessage('Card Number is required'), body('amount') .not() .isEmpty() .withMessage('Amount is required') .isNumeric() .withMessage('Amount is invalid format'), body('reservation_number') .not() .isEmpty() .withMessage('Reservation Number is required') .isArray() .withMessage('Reservation Number is invalid request format'), ]; default: break; } }; // ================================================= FUNCTION GENERATE LOAD BALANCE NUMBER =================================================== // *Created By: Mohamad Ihsan* // *Description:* // function yang digunakan untuk men-generate load balance number const generateLoadBalanceNumber = async (data, date, counter) => { let code = data.partner_code ? data.partner_code : 'XXX'; let prefix = 'LBL'; let loadBalanceNumber = prefix + '' + code + '' + '' + date + counter.toString().padStart(6, '0'); // insert to temp load balance number let insert = await model.insertLoadBalanceNumber(loadBalanceNumber); if (insert.rowCount < 1) { loadBalanceNumber = 'XX'; } return loadBalanceNumber; }; // ==================================================== 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 today = moment().format('YYYY-MM-DD'); 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 await model.updateReservationAndLoadingBalance( reservationNumber, data, dataLoadingBalanceDetail, now, flag ); // 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 { // 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...` ); // generate load balance number let newLoadBalanceNumber; let getLoadBalanceSequence; let loadBalanceNoSequence = req.load_balance_number_sequence; // log debug winston.logger.debug(`${uniqueCode} getting loading balance sequence...`); if (!loadBalanceNoSequence) { // get loading balance getLoadBalanceSequence = await model.getLoadBalanceSequence( getPartner, today ); loadBalanceNoSequence = getLoadBalanceSequence ? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1 : 1; } let maxLoop = 0; do { // await _sleep(helper.randomNumberInt()); if (maxLoop > 0) { loadBalanceNoSequence++; } // set sequence to redis await setLoadBalanceNumberSequence( req.partner_id_token, loadBalanceNoSequence ); // log warn winston.logger.warn(`${uniqueCode} generating load balance number...`); newLoadBalanceNumber = await generateLoadBalanceNumber( getPartner, moment(today).format('YYMMDD'), loadBalanceNoSequence ); if (newLoadBalanceNumber != 'XX') { // set sequence to redis // await setLoadBalanceNumberSequence( // req.partner_id_token, // loadBalanceNoSequence // ); } // log warn winston.logger.warn( `${uniqueCode} load balance number is ${newLoadBalanceNumber}.` ); if (maxLoop > maxLoopParameter) { // create log winston.logger.error( `${uniqueCode} 500 internal server error. Server is busy. please try again` ); return false; } maxLoop++; } while (newLoadBalanceNumber == 'XX'); 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; // 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); } // 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); } // 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 ]: ${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); if (getReservationPendingWithFlagCounter.length > 0) { if (lastFlag) { if (parseInt(lastFlag) <= parseInt(flag)) { 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 ]: ${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 ]: ${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'); let today = moment().format('YYYY-MM-DD'); // 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; } // log warn // winston.logger.warn( // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation status...` // ); // check reservation status for (let index = 0; index < reservation_number.length; index++) { let reservationStatus = await model.findReservation( reservation_number[index] ); // 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 there are reservation with status active if (reservationStatus.c_status == 'A') { // if there are reservation on load balance table transaction but before process on reservation failed update to LOADED let reservationLoaded = await model.findReservationLoaded( reservationStatus.i_reservation_balance ); if (reservationLoaded) { let loadBalanceNumberExisting = reservationLoaded.c_load_balance_no; let loadDate = reservationLoaded.d_load_balance; result = { code: '00', message: 'reservation has been successfully loaded on ' + moment(loadDate).format('DD MMM YYYY HH:mm:ss'), data: { load_balance_number: loadBalanceNumberExisting, }, }; // log info 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; } // generate load balance number let loadBalanceNumber; let getLoadBalanceSequence; let loadBalanceNoSequence = req.load_balance_number_sequence; // log debug // winston.logger.debug( // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting loading balance sequence...` // ); if (!loadBalanceNoSequence) { // get loading balance getLoadBalanceSequence = await model.getLoadBalanceSequence( getPartner, today ); loadBalanceNoSequence = getLoadBalanceSequence ? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1 : 1; } let maxLoop = 0; do { // await _sleep(helper.randomNumberInt()); if (maxLoop > 0) { loadBalanceNoSequence++; } // set sequence to redis await setLoadBalanceNumberSequence( req.partner_id_token, loadBalanceNoSequence ); // log warn // winston.logger.warn( // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: generating load balance number...` // ); loadBalanceNumber = await generateLoadBalanceNumber( getPartner, moment(today).format('YYMMDD'), loadBalanceNoSequence ); if (loadBalanceNumber != 'XX') { // set sequence to redis // await setLoadBalanceNumberSequence( // req.partner_id_token, // loadBalanceNoSequence // ); } // log warn // winston.logger.warn( // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: load balance number is ${loadBalanceNumber}.` // ); if (maxLoop > maxLoopParameter) { // create log winston.logger.error( `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: 500 internal server error. Server is busy. please try again` ); return { code: '500', message: process.env.NODE_ENV != 'production' ? '500 internal server error (max loop) - backend server.' : '500 internal server error (max loop) - backend server.', data: {}, }; } maxLoop++; } while (loadBalanceNumber == 'XX'); 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, }; // log debug // winston.logger.debug( // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting reservation detail...` // ); let detail = []; reservation_number = []; for (let index = 0; index < getReservationPending.length; index++) { reservation_number.push(getReservationPending[index].c_reservation_no); let reservation = await model.findReservation( getReservationPending[index].c_reservation_no ); 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, }); } // 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; } 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-INSERT ]: ${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, loadingBalanceInsert, loadingBalanceUpdate, };