diff --git a/application/modules/auth/auth.controller.js b/application/modules/auth/auth.controller.js index 8bc7515..b536008 100644 --- a/application/modules/auth/auth.controller.js +++ b/application/modules/auth/auth.controller.js @@ -4,61 +4,11 @@ const bcrypt = require('bcrypt'); const helper = require('../../helpers/helper'); const winston = require('../../helpers/winston.logger'); const model = require('./auth.model'); -const { body, validationResult } = require('express-validator'); +const { validationResult } = require('express-validator'); +const validate = require('./auth.validation'); const moment = require('moment'); moment.locale('id'); -// VALIDATION -const validate = (method) => { - switch (method) { - case 'loginPartnerUser': { - return [ - body('email') - .not() - .isEmpty() - .withMessage('Email is required') - .isEmail() - .withMessage('Email format wrong'), - body('password').not().isEmpty().withMessage('Password is required'), - ]; - } - case 'loginTerminal': { - return [ - body('mid').not().isEmpty().withMessage('MID is required'), - body('tid').not().isEmpty().withMessage('TID is required'), - body('password').not().isEmpty().withMessage('Password is required'), - ]; - } - case 'register': { - return [ - body('mid').not().isEmpty().withMessage('MID is required'), - body('tid').not().isEmpty().withMessage('TID is required'), - body('password') - .not() - .isEmpty() - .withMessage('Password is required') - .isLength({ min: 5 }) - .withMessage('Password must be least 5 characters'), - ]; - } - case 'refreshTokenPartnerUser': { - return [ - body('email') - .not() - .isEmpty() - .withMessage('Email is required') - .isEmail() - .withMessage('Email format wrong'), - ]; - } - case 'refreshTokenTerminal': { - return [ - body('mid').not().isEmpty().withMessage('MID is required'), - body('tid').not().isEmpty().withMessage('TID is required'), - ]; - } - } -}; // ================================================================= LOGIN BY PARTNER USER ================================================================= // *Created By: Mohamad Ihsan* diff --git a/application/modules/auth/auth.validation.js b/application/modules/auth/auth.validation.js new file mode 100644 index 0000000..0bb7651 --- /dev/null +++ b/application/modules/auth/auth.validation.js @@ -0,0 +1,56 @@ +const { body } = require('express-validator'); + +// Aturan input untuk setiap operasi. Urutan validasi mengikuti kontrak API. +const validate = (method) => { + switch (method) { + case 'loginPartnerUser': { + return [ + body('email') + .not() + .isEmpty() + .withMessage('Email is required') + .isEmail() + .withMessage('Email format wrong'), + body('password').not().isEmpty().withMessage('Password is required'), + ]; + } + case 'loginTerminal': { + return [ + body('mid').not().isEmpty().withMessage('MID is required'), + body('tid').not().isEmpty().withMessage('TID is required'), + body('password').not().isEmpty().withMessage('Password is required'), + ]; + } + case 'register': { + return [ + body('mid').not().isEmpty().withMessage('MID is required'), + body('tid').not().isEmpty().withMessage('TID is required'), + body('password') + .not() + .isEmpty() + .withMessage('Password is required') + .isLength({ min: 5 }) + .withMessage('Password must be least 5 characters'), + ]; + } + case 'refreshTokenPartnerUser': { + return [ + body('email') + .not() + .isEmpty() + .withMessage('Email is required') + .isEmail() + .withMessage('Email format wrong'), + ]; + } + case 'refreshTokenTerminal': { + return [ + body('mid').not().isEmpty().withMessage('MID is required'), + body('tid').not().isEmpty().withMessage('TID is required'), + ]; + } + } +}; + + +module.exports = validate; diff --git a/application/modules/cashin/cahsin.controller.js b/application/modules/cashin/cahsin.controller.js index c20258c..a5ee4e4 100644 --- a/application/modules/cashin/cahsin.controller.js +++ b/application/modules/cashin/cahsin.controller.js @@ -1,16 +1,9 @@ -const { param, body, validationResult } = require('express-validator'); +const { body, validationResult } = require('express-validator'); const helper = require('../../helpers/helper'); const winston = require('../../helpers/winston.logger'); -const model = require('./cahsin.model'); -const moment = require('moment'); -const knex = require('../../../infrastructure/database/knex'); +const { _generateCashIn, _generateCashInSales, _generateCashInSalesInternal, _generateCashInTopUpCashlessInternal } = require('./cash-in-generation.service'); const _postingCashIn = require('./cash-in-posting.service'); -moment.locale('id'); - -var result = {}; -var uniqueCode; - // VALIDATION const validate = (method) => { switch (method) { @@ -50,12 +43,11 @@ const validate = (method) => { const apiGenerateCahsIn = async (req, res) => { try { // generate unique code - uniqueCode = helper.getUniqueCode(); - // return uniqueCode + const uniqueCode = helper.getUniqueCode(); // log info winston.logger.info( - `${uniqueCode} REQUEST generate cashin: ${JSON.stringify(req.body)}` + `${uniqueCode} REQUEST generate cashin` ); const schedulerCode = 'GENERATECASHINONLINETOPUP'; @@ -65,7 +57,7 @@ const apiGenerateCahsIn = async (req, res) => { // check validator const err = validationResult(req, res); if (!err.isEmpty()) { - result = { + const result = { code: '400', message: err.errors[0].msg, data: {}, @@ -73,7 +65,7 @@ const apiGenerateCahsIn = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE generate cashin: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE generate cashin code=${result.code}` ); return res.status(200).json(result); @@ -81,13 +73,13 @@ const apiGenerateCahsIn = async (req, res) => { const cashIn = await _generateCashIn(uniqueCode); - result = { + const result = { code: '200', message: 'Succes posting', data: cashIn, }; - const finishData = await helper.finishScheduler(token, schedulerCode); + await helper.finishScheduler(token, schedulerCode); return res.status(200).json(result); } catch (error) { @@ -110,18 +102,17 @@ const apiGenerateCahsIn = async (req, res) => { const apiGenerateCashInSales = async (req, res) => { try { // generate unique code - uniqueCode = helper.getUniqueCode(); - // return uniqueCode + const uniqueCode = helper.getUniqueCode(); // log info winston.logger.info( - `${uniqueCode} REQUEST generate cashin: ${JSON.stringify(req.body)}` + `${uniqueCode} REQUEST generate cashin` ); // check validator const err = validationResult(req, res); if (!err.isEmpty()) { - result = { + const result = { code: '400', message: err.errors[0].msg, data: {}, @@ -129,7 +120,7 @@ const apiGenerateCashInSales = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE generate cashin: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE generate cashin code=${result.code}` ); return res.status(200).json(result); @@ -137,7 +128,7 @@ const apiGenerateCashInSales = async (req, res) => { const cashIn = await _generateCashInSales(uniqueCode); - result = { + const result = { code: '200', message: 'Success generate cash-in', data: cashIn, @@ -164,12 +155,11 @@ const apiGenerateCashInSales = async (req, res) => { const apiGenerateCashInSalesInternal = async (req, res) => { try { // generate unique code - uniqueCode = helper.getUniqueCode(); - // return uniqueCode + const uniqueCode = helper.getUniqueCode(); // log info winston.logger.info( - `${uniqueCode} REQUEST generate cashin sales internal: ${JSON.stringify(req.body)}` + `${uniqueCode} REQUEST generate cashin sales internal` ); const schedulerCode = 'GENERATECASHINSALESSTATIONCASHLESS'; @@ -179,7 +169,7 @@ const apiGenerateCashInSalesInternal = async (req, res) => { // check validator const err = validationResult(req, res); if (!err.isEmpty()) { - result = { + const result = { code: '400', message: err.errors[0].msg, data: {}, @@ -187,7 +177,7 @@ const apiGenerateCashInSalesInternal = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE generate cashin sales internal: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE generate cashin sales internal code=${result.code}` ); return res.status(200).json(result); @@ -195,13 +185,13 @@ const apiGenerateCashInSalesInternal = async (req, res) => { const cashIn = await _generateCashInSalesInternal(uniqueCode); - result = { + const result = { code: '200', message: 'Success generate cash-in', data: cashIn, }; - const finishData = await helper.finishScheduler(token, schedulerCode); + await helper.finishScheduler(token, schedulerCode); return res.status(200).json(result); } catch (error) { @@ -224,12 +214,11 @@ const apiGenerateCashInSalesInternal = async (req, res) => { const apiGenerateCashInTopUpCashlessInternal = async (req, res) => { try { // generate unique code - uniqueCode = helper.getUniqueCode(); - // return uniqueCode + const uniqueCode = helper.getUniqueCode(); // log info winston.logger.info( - `${uniqueCode} REQUEST generate cashin topup cashless internal: ${JSON.stringify(req.body)}` + `${uniqueCode} REQUEST generate cashin topup cashless internal` ); const schedulerCode = 'GENERATECASHINTOPUPSTATIONCASHLESS'; @@ -239,7 +228,7 @@ const apiGenerateCashInTopUpCashlessInternal = async (req, res) => { // check validator const err = validationResult(req, res); if (!err.isEmpty()) { - result = { + const result = { code: '400', message: err.errors[0].msg, data: {}, @@ -247,7 +236,7 @@ const apiGenerateCashInTopUpCashlessInternal = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE generate cashin topup cashless internal: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE generate cashin topup cashless internal code=${result.code}` ); return res.status(200).json(result); @@ -255,13 +244,13 @@ const apiGenerateCashInTopUpCashlessInternal = async (req, res) => { const cashIn = await _generateCashInTopUpCashlessInternal(uniqueCode); - result = { + const result = { code: '200', message: 'Success generate cash-in', data: cashIn, }; - const finishData = await helper.finishScheduler(token, schedulerCode); + await helper.finishScheduler(token, schedulerCode); return res.status(200).json(result); } catch (error) { @@ -287,7 +276,7 @@ const apiPostingCahsIn = async (req, res) => { const uniqueCode = helper.getUniqueCode(); // log info winston.logger.info( - `${uniqueCode} REQUEST posting cash in : ${JSON.stringify(req.body)}` + `${uniqueCode} REQUEST posting cash in ` ); // check validator @@ -301,16 +290,13 @@ const apiPostingCahsIn = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE generate posting cash in : ${JSON.stringify( - result - )}` + `${uniqueCode} RESPONSE generate posting cash in code=${result.code}` ); return res.status(200).json(result); } - // return uniqueCode - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING CAHS IN`); + winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING CASH IN`); const invoice = await _postingCashIn(uniqueCode); @@ -338,367 +324,6 @@ const apiPostingCahsIn = async (req, res) => { } }; -const _generateCashIn = async (uniqueCode) => { - let partnerRecon = await model.getPartnerRecon(knex); - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify( - partnerRecon - )}` - ); - - for (const item of partnerRecon) { - try { - await knex.transaction(async (trx) => { - const reserv = await model.getReserve( - trx, - item.c_partner_code, - item.d_payment, - item.c_invoice_no - ); - - if (!reserv || reserv.length === 0) { - return; - } - - const cashInAmount = reserv.reduce( - (sum, row) => sum + parseInt(row.i_reservation_amount, 10), - 0 - ); - - if (cashInAmount <= 0) { - return; - } - - let runningAmount = 0; - for (const detail of reserv) { - runningAmount += parseInt(detail.i_reservation_amount, 10); - if (runningAmount > parseInt(detail.invoice_amount, 10)) { - winston.logger.warn( - `SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount} on invoice ${detail.c_invoice_no})` - ); - return; - } - } - - const code = await model.generateCode( - trx, - item.c_partner_code, - moment().format('YYMMDD') - ); - - const dataCahsIn = { - c_partner_code: item.c_partner_code, - c_partner_name: item.c_partner_name, - c_cash_in_no: code, - c_in_period: item.c_in_period, - d_credit: item.d_payment, - c_invoice_no: item.c_invoice_no, - i_amount: cashInAmount, - }; - - const cashIn = await model.insertCashIn(trx, dataCahsIn); - await model.writePaynentHistory(dataCahsIn, 'SUCCESSFULLY', 0, trx); - - const dataReserve = { - c_cash_in_no: cashIn.c_cash_in_no, - d_credit: cashIn.d_credit, - c_in_period: cashIn.c_in_period, - }; - - const reserveNos = reserv.map((detail) => detail.c_reservation_no); - const cashInDetails = reserv.map((detail) => ({ - i_cash_in: cashIn.i_cash_in, - c_reservation_no: detail.c_reservation_no, - m_amount: detail.i_reservation_amount, - c_payment_recon_no: detail.c_payment_recon_no, - d_payment: detail.d_payment, - d_payment_recon: detail.d_payment_recon, - c_load_balance_no: detail.c_load_balance_no, - })); - - await model.updateIntoReserveBulk(trx, dataReserve, reserveNos); - await model.insertCashInDetailBulk(trx, cashInDetails); - - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}` - ); - }); - } catch (error) { - winston.logger.error( - `SCHEDULER-FB70-${uniqueCode} generate cash in failed for partner=${item.c_partner_code}, invoice=${item.c_invoice_no} | ${error.message}` - ); - } - } - - return partnerRecon; -}; - -const _generateCashInSales = async (uniqueCode) => { - let partnerRecon = await model.getPartnerReconSales(knex); - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify( - partnerRecon - )}` - ); - - for (const item of partnerRecon) { - try { - await knex.transaction(async (trx) => { - const sales = await model.getSalesKMT( - trx, - item.c_partner_code, - item.d_payment, - item.c_invoice_no - ); - - if (!sales || sales.length === 0) { - return; - } - - const cashInAmount = sales.reduce( - (sum, row) => sum + parseInt(row.i_total_billing, 10), - 0 - ); - - if (cashInAmount <= 0) { - return; - } - - let runningAmount = 0; - for (const detail of sales) { - runningAmount += parseInt(detail.i_total_billing, 10); - if (runningAmount > parseInt(detail.invoice_amount, 10)) { - winston.logger.warn( - `SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN SALES: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount} on invoice ${detail.c_invoice_no})` - ); - return; - } - } - - const code = await model.generateCode( - trx, - item.c_partner_code, - moment().format('YYMMDD') - ); - - const dataCahsIn = { - c_partner_code: item.c_partner_code, - c_partner_name: item.c_partner_name, - c_cash_in_no: code, - c_in_period: item.c_in_period, - d_credit: item.d_payment, - c_invoice_no: item.c_invoice_no, - i_amount: cashInAmount, - c_source: 'S', - }; - - const cashIn = await model.insertCashIn(trx, dataCahsIn); - await model.writePaynentHistory(dataCahsIn, 'SUCCESSFULLY', 0, trx); - - const dataSales = { - c_cash_in_no: cashIn.c_cash_in_no, - d_credit: cashIn.d_credit, - c_in_period: cashIn.c_in_period, - }; - - const salesNos = sales.map((detail) => detail.c_sales_no); - const cashInDetails = sales.map((detail) => ({ - i_cash_in: cashIn.i_cash_in, - c_reservation_no: detail.c_sales_no, - m_amount: detail.i_total_billing, - c_payment_recon_no: detail.c_payment_recon_no, - d_payment: detail.d_payment, - d_payment_recon: detail.d_payment_recon, - })); - - await model.updateIntoSalesKMTBulk(trx, dataSales, salesNos); - await model.insertCashInDetailBulk(trx, cashInDetails); - - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN SALES ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}` - ); - }); - } catch (error) { - winston.logger.error( - `SCHEDULER-FB70-${uniqueCode} generate cash in sales failed for partner=${item.c_partner_code}, invoice=${item.c_invoice_no} | ${error.message}` - ); - } - } - return partnerRecon; -}; - -const _generateCashInSalesInternal = async (uniqueCode) => { - let partnerRecon = await model.getPartnerReconSalesInternal(knex); - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify( - partnerRecon - )}` - ); - - for (const item of partnerRecon) { - await knex.transaction(async (trx) => { - const sales = await model.getSalesInternal( - trx, - item.c_partner_code, - item.d_payment, - item.c_invoice_no - ); - - if (!sales || sales.length === 0) { - return; - } - - const cashInAmount = sales.reduce( - (sum, row) => sum + parseInt(row.i_total_price, 10), - 0 - ); - - if (cashInAmount <= 0) { - return; - } - - let runningAmount = 0; - for (const detail of sales) { - runningAmount += parseInt(detail.i_total_price, 10); - if (runningAmount > parseInt(detail.invoice_amount, 10)) { - winston.logger.warn( - `SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN SALES INTERNAL: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount} on invoice ${detail.c_invoice_no})` - ); - return; - } - } - - const code = await model.generateCode( - trx, - item.c_partner_code, - moment().format('YYMMDD') - ); - - const dataCahsIn = { - c_partner_code: item.c_partner_code, - c_partner_name: item.c_partner_name, - c_cash_in_no: code, - c_in_period: item.c_in_period, - d_credit: item.d_payment, - c_invoice_no: item.c_invoice_no, - i_amount: cashInAmount, - c_source: 'S', - }; - - const cashIn = await model.insertCashIn(trx, dataCahsIn); - await model.writePaynentHistory(dataCahsIn, 'SUCCESSFULLY', 0, trx); - - const dataSales = { - i_cash_in: cashIn.i_cash_in, - }; - - const salesNos = sales.map((detail) => detail.c_sales_no); - const cashInDetails = sales.map((detail) => ({ - i_cash_in: cashIn.i_cash_in, - c_reservation_no: detail.c_sales_no, - m_amount: detail.i_total_price, - c_payment_recon_no: detail.c_payment_recon_no, - d_payment: detail.d_payment, - d_payment_recon: detail.d_payment_recon, - })); - - await model.updateIntoSalesInternalBulk(trx, dataSales, salesNos); - await model.insertCashInDetailBulk(trx, cashInDetails); - - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN SALES INTERNAL ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}` - ); - }); - } - return partnerRecon; -}; - -const _generateCashInTopUpCashlessInternal = async (uniqueCode) => { - let partnerRecon = await model.getPartnerReconTopUpCashlessInternal(knex); - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify( - partnerRecon - )}` - ); - - for (const item of partnerRecon) { - await knex.transaction(async (trx) => { - const topup = await model.getTopUpCashlessInternal( - trx, - item.c_partner_code, - item.d_payment, - item.c_invoice_no - ); - - if (!topup || topup.length === 0) { - return; - } - - const cashInAmount = topup.reduce( - (sum, row) => sum + parseInt(row.i_amount, 10), - 0 - ); - - if (cashInAmount <= 0) { - return; - } - - let runningAmount = 0; - for (const detail of topup) { - runningAmount += parseInt(detail.i_amount, 10); - if (runningAmount > parseInt(detail.invoice_amount, 10)) { - winston.logger.warn( - `SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN TOPUP CASHLESS INTERNAL: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount})` - ); - return; - } - } - - const code = await model.generateCode( - trx, - item.c_partner_code, - moment().format('YYMMDD') - ); - - const dataCahsIn = { - c_partner_code: item.c_partner_code, - c_partner_name: item.c_partner_name, - c_cash_in_no: code, - c_in_period: item.c_in_period, - d_credit: item.d_payment, - c_invoice_no: item.c_invoice_no, - i_amount: cashInAmount, - c_source: 'T', - }; - - const cashIn = await model.insertCashIn(trx, dataCahsIn); - await model.writePaynentHistory(dataCahsIn, 'SUCCESSFULLY', 0, trx); - - const dataTopup = { - i_cash_in: cashIn.i_cash_in, - }; - - const topupNos = topup.map((detail) => detail.c_topup_no); - const cashInDetails = topup.map((detail) => ({ - i_cash_in: cashIn.i_cash_in, - c_reservation_no: detail.c_topup_no, - m_amount: detail.i_amount, - c_payment_recon_no: detail.c_payment_recon_no, - d_payment: detail.d_payment, - d_payment_recon: detail.d_payment_recon, - })); - - await model.updateIntoTopUpCashlessInternalBulk(trx, dataTopup, topupNos); - await model.insertCashInDetailBulk(trx, cashInDetails); - - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN TOPUP CASHLESS INTERNAL ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}` - ); - }); - } - return partnerRecon; -}; - module.exports = { validate, apiGenerateCahsIn, diff --git a/application/modules/cashin/cahsin.model.js b/application/modules/cashin/cahsin.model.js index 50a96f0..99393a0 100644 --- a/application/modules/cashin/cahsin.model.js +++ b/application/modules/cashin/cahsin.model.js @@ -1,7 +1,8 @@ // GET PARTNER, MERCHANT, TERMINAL FROM TID const generateInvoice = async (invoiceDate, repost, trx) => { - let result = await trx.raw( - `SELECT * FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})` + const result = await trx.raw( + 'SELECT * FROM payment.sp_payment_req_topup_online(?, ?::boolean)', + [invoiceDate, repost] ); return result.rows || result; diff --git a/application/modules/cashin/cash-in-generation.service.js b/application/modules/cashin/cash-in-generation.service.js new file mode 100644 index 0000000..005c3f9 --- /dev/null +++ b/application/modules/cashin/cash-in-generation.service.js @@ -0,0 +1,362 @@ +const moment = require('moment'); +const knex = require('../../../infrastructure/database/knex'); +const winston = require('../../helpers/winston.logger'); +const model = require('./cahsin.model'); + +moment.locale('id'); + +// Simpan header, audit, dan detail Cash-in dalam transaksi yang sama per invoice. +const _generateCashIn = async (uniqueCode) => { + const partnerRecon = await model.getPartnerRecon(knex); + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} Cash-in candidates count=${partnerRecon.length}` + ); + + for (const item of partnerRecon) { + try { + await knex.transaction(async (trx) => { + const reserv = await model.getReserve( + trx, + item.c_partner_code, + item.d_payment, + item.c_invoice_no + ); + + if (!reserv || reserv.length === 0) { + return; + } + + const cashInAmount = reserv.reduce( + (sum, row) => sum + parseInt(row.i_reservation_amount, 10), + 0 + ); + + if (cashInAmount <= 0) { + return; + } + + let runningAmount = 0; + for (const detail of reserv) { + runningAmount += parseInt(detail.i_reservation_amount, 10); + if (runningAmount > parseInt(detail.invoice_amount, 10)) { + winston.logger.warn( + `SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount} on invoice ${detail.c_invoice_no})` + ); + return; + } + } + + const code = await model.generateCode( + trx, + item.c_partner_code, + moment().format('YYMMDD') + ); + + const cashInData = { + c_partner_code: item.c_partner_code, + c_partner_name: item.c_partner_name, + c_cash_in_no: code, + c_in_period: item.c_in_period, + d_credit: item.d_payment, + c_invoice_no: item.c_invoice_no, + i_amount: cashInAmount, + }; + + const cashIn = await model.insertCashIn(trx, cashInData); + await model.writePaynentHistory(cashInData, 'SUCCESSFULLY', 0, trx); + + const dataReserve = { + c_cash_in_no: cashIn.c_cash_in_no, + d_credit: cashIn.d_credit, + c_in_period: cashIn.c_in_period, + }; + + const reserveNos = reserv.map((detail) => detail.c_reservation_no); + const cashInDetails = reserv.map((detail) => ({ + i_cash_in: cashIn.i_cash_in, + c_reservation_no: detail.c_reservation_no, + m_amount: detail.i_reservation_amount, + c_payment_recon_no: detail.c_payment_recon_no, + d_payment: detail.d_payment, + d_payment_recon: detail.d_payment_recon, + c_load_balance_no: detail.c_load_balance_no, + })); + + await model.updateIntoReserveBulk(trx, dataReserve, reserveNos); + await model.insertCashInDetailBulk(trx, cashInDetails); + + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}` + ); + }); + } catch (error) { + winston.logger.error( + `SCHEDULER-FB70-${uniqueCode} generate cash in failed for partner=${item.c_partner_code}, invoice=${item.c_invoice_no} | ${error.message}` + ); + } + } + + return partnerRecon; +}; + +const _generateCashInSales = async (uniqueCode) => { + const partnerRecon = await model.getPartnerReconSales(knex); + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} Cash-in candidates count=${partnerRecon.length}` + ); + + for (const item of partnerRecon) { + try { + await knex.transaction(async (trx) => { + const sales = await model.getSalesKMT( + trx, + item.c_partner_code, + item.d_payment, + item.c_invoice_no + ); + + if (!sales || sales.length === 0) { + return; + } + + const cashInAmount = sales.reduce( + (sum, row) => sum + parseInt(row.i_total_billing, 10), + 0 + ); + + if (cashInAmount <= 0) { + return; + } + + let runningAmount = 0; + for (const detail of sales) { + runningAmount += parseInt(detail.i_total_billing, 10); + if (runningAmount > parseInt(detail.invoice_amount, 10)) { + winston.logger.warn( + `SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN SALES: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount} on invoice ${detail.c_invoice_no})` + ); + return; + } + } + + const code = await model.generateCode( + trx, + item.c_partner_code, + moment().format('YYMMDD') + ); + + const cashInData = { + c_partner_code: item.c_partner_code, + c_partner_name: item.c_partner_name, + c_cash_in_no: code, + c_in_period: item.c_in_period, + d_credit: item.d_payment, + c_invoice_no: item.c_invoice_no, + i_amount: cashInAmount, + c_source: 'S', + }; + + const cashIn = await model.insertCashIn(trx, cashInData); + await model.writePaynentHistory(cashInData, 'SUCCESSFULLY', 0, trx); + + const dataSales = { + c_cash_in_no: cashIn.c_cash_in_no, + d_credit: cashIn.d_credit, + c_in_period: cashIn.c_in_period, + }; + + const salesNos = sales.map((detail) => detail.c_sales_no); + const cashInDetails = sales.map((detail) => ({ + i_cash_in: cashIn.i_cash_in, + c_reservation_no: detail.c_sales_no, + m_amount: detail.i_total_billing, + c_payment_recon_no: detail.c_payment_recon_no, + d_payment: detail.d_payment, + d_payment_recon: detail.d_payment_recon, + })); + + await model.updateIntoSalesKMTBulk(trx, dataSales, salesNos); + await model.insertCashInDetailBulk(trx, cashInDetails); + + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN SALES ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}` + ); + }); + } catch (error) { + winston.logger.error( + `SCHEDULER-FB70-${uniqueCode} generate cash in sales failed for partner=${item.c_partner_code}, invoice=${item.c_invoice_no} | ${error.message}` + ); + } + } + return partnerRecon; +}; + +const _generateCashInSalesInternal = async (uniqueCode) => { + const partnerRecon = await model.getPartnerReconSalesInternal(knex); + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} Cash-in candidates count=${partnerRecon.length}` + ); + + for (const item of partnerRecon) { + await knex.transaction(async (trx) => { + const sales = await model.getSalesInternal( + trx, + item.c_partner_code, + item.d_payment, + item.c_invoice_no + ); + + if (!sales || sales.length === 0) { + return; + } + + const cashInAmount = sales.reduce( + (sum, row) => sum + parseInt(row.i_total_price, 10), + 0 + ); + + if (cashInAmount <= 0) { + return; + } + + let runningAmount = 0; + for (const detail of sales) { + runningAmount += parseInt(detail.i_total_price, 10); + if (runningAmount > parseInt(detail.invoice_amount, 10)) { + winston.logger.warn( + `SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN SALES INTERNAL: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount} on invoice ${detail.c_invoice_no})` + ); + return; + } + } + + const code = await model.generateCode( + trx, + item.c_partner_code, + moment().format('YYMMDD') + ); + + const cashInData = { + c_partner_code: item.c_partner_code, + c_partner_name: item.c_partner_name, + c_cash_in_no: code, + c_in_period: item.c_in_period, + d_credit: item.d_payment, + c_invoice_no: item.c_invoice_no, + i_amount: cashInAmount, + c_source: 'S', + }; + + const cashIn = await model.insertCashIn(trx, cashInData); + await model.writePaynentHistory(cashInData, 'SUCCESSFULLY', 0, trx); + + const dataSales = { + i_cash_in: cashIn.i_cash_in, + }; + + const salesNos = sales.map((detail) => detail.c_sales_no); + const cashInDetails = sales.map((detail) => ({ + i_cash_in: cashIn.i_cash_in, + c_reservation_no: detail.c_sales_no, + m_amount: detail.i_total_price, + c_payment_recon_no: detail.c_payment_recon_no, + d_payment: detail.d_payment, + d_payment_recon: detail.d_payment_recon, + })); + + await model.updateIntoSalesInternalBulk(trx, dataSales, salesNos); + await model.insertCashInDetailBulk(trx, cashInDetails); + + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN SALES INTERNAL ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}` + ); + }); + } + return partnerRecon; +}; + +const _generateCashInTopUpCashlessInternal = async (uniqueCode) => { + const partnerRecon = await model.getPartnerReconTopUpCashlessInternal(knex); + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} Cash-in candidates count=${partnerRecon.length}` + ); + + for (const item of partnerRecon) { + await knex.transaction(async (trx) => { + const topup = await model.getTopUpCashlessInternal( + trx, + item.c_partner_code, + item.d_payment, + item.c_invoice_no + ); + + if (!topup || topup.length === 0) { + return; + } + + const cashInAmount = topup.reduce( + (sum, row) => sum + parseInt(row.i_amount, 10), + 0 + ); + + if (cashInAmount <= 0) { + return; + } + + let runningAmount = 0; + for (const detail of topup) { + runningAmount += parseInt(detail.i_amount, 10); + if (runningAmount > parseInt(detail.invoice_amount, 10)) { + winston.logger.warn( + `SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN TOPUP CASHLESS INTERNAL: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount})` + ); + return; + } + } + + const code = await model.generateCode( + trx, + item.c_partner_code, + moment().format('YYMMDD') + ); + + const cashInData = { + c_partner_code: item.c_partner_code, + c_partner_name: item.c_partner_name, + c_cash_in_no: code, + c_in_period: item.c_in_period, + d_credit: item.d_payment, + c_invoice_no: item.c_invoice_no, + i_amount: cashInAmount, + c_source: 'T', + }; + + const cashIn = await model.insertCashIn(trx, cashInData); + await model.writePaynentHistory(cashInData, 'SUCCESSFULLY', 0, trx); + + const dataTopup = { + i_cash_in: cashIn.i_cash_in, + }; + + const topupNos = topup.map((detail) => detail.c_topup_no); + const cashInDetails = topup.map((detail) => ({ + i_cash_in: cashIn.i_cash_in, + c_reservation_no: detail.c_topup_no, + m_amount: detail.i_amount, + c_payment_recon_no: detail.c_payment_recon_no, + d_payment: detail.d_payment, + d_payment_recon: detail.d_payment_recon, + })); + + await model.updateIntoTopUpCashlessInternalBulk(trx, dataTopup, topupNos); + await model.insertCashInDetailBulk(trx, cashInDetails); + + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN TOPUP CASHLESS INTERNAL ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}` + ); + }); + } + return partnerRecon; +}; + +module.exports = { _generateCashIn, _generateCashInSales, _generateCashInSalesInternal, _generateCashInTopUpCashlessInternal }; diff --git a/application/modules/dongleorder/dongleorder.controller.js b/application/modules/dongleorder/dongleorder.controller.js index 6cd5fcb..a0a0815 100644 --- a/application/modules/dongleorder/dongleorder.controller.js +++ b/application/modules/dongleorder/dongleorder.controller.js @@ -44,9 +44,7 @@ const getDongleOrder = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE get RO and dongle order: ${JSON.stringify( - result - )}` + `${uniqueCode} RESPONSE get RO and dongle order code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); @@ -60,9 +58,7 @@ const getDongleOrder = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} RESPONSE get RO and dongle order: ${JSON.stringify( - result - )}` + `${uniqueCode} RESPONSE get RO and dongle order code=${result.code ?? "UNKNOWN"}` ); return res.json(result); @@ -94,7 +90,7 @@ const updateDongleOrder = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} REQUEST update dongle order: ${JSON.stringify(req.body)}` + `${uniqueCode} REQUEST update dongle order` ); // check validator @@ -108,7 +104,7 @@ const updateDongleOrder = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE update dongle order: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE update dongle order code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); @@ -140,7 +136,7 @@ const updateDongleOrder = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE update dongle order: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE update dongle order code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); @@ -154,7 +150,7 @@ const updateDongleOrder = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} RESPONSE update dongle order: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE update dongle order code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); diff --git a/application/modules/history/history.controller.js b/application/modules/history/history.controller.js index deb2874..84b1e76 100644 --- a/application/modules/history/history.controller.js +++ b/application/modules/history/history.controller.js @@ -49,7 +49,7 @@ const cardHistory = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} [ REQUEST CARD-HISTORY ]: ${JSON.stringify(req.body)}` + `${uniqueCode} [ REQUEST CARD-HISTORY ]` ); // check validator @@ -63,7 +63,7 @@ const cardHistory = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} [ RESPONSE CARD-HISTORY ]: ${JSON.stringify(result)}` + `${uniqueCode} [ RESPONSE CARD-HISTORY ] code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); @@ -162,7 +162,7 @@ const cardHistory = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} [ RESPONSE CARD-HISTORY ]: ${JSON.stringify(result)}` + `${uniqueCode} [ RESPONSE CARD-HISTORY ] code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); @@ -208,9 +208,7 @@ const history = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} [ REQUEST CARD-HISTORY-FROM-CMS ]: ${JSON.stringify( - req.body - )}` + `${uniqueCode} [ REQUEST CARD-HISTORY-FROM-CMS ]` ); // check validator @@ -224,9 +222,7 @@ const history = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ]: ${JSON.stringify( - result - )}` + `${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ] code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); @@ -255,9 +251,7 @@ const history = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ]: ${JSON.stringify( - result - )}` + `${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ] code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); @@ -279,9 +273,7 @@ const history = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ]: ${JSON.stringify( - result - )}` + `${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ] code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); @@ -311,9 +303,7 @@ const history = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ]: ${JSON.stringify( - result - )}` + `${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ] code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); @@ -327,9 +317,7 @@ const history = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ]: ${JSON.stringify( - result - )}` + `${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ] code=${result.code ?? "UNKNOWN"}` ); return res.json(result); diff --git a/application/modules/hsm/clear_card/clear_1.js b/application/modules/hsm/clear_card/clear_1.js index e1798f3..6035950 100644 --- a/application/modules/hsm/clear_card/clear_1.js +++ b/application/modules/hsm/clear_card/clear_1.js @@ -3,80 +3,27 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage } = require('../services/requestHsm'); const refreshHsm = require('../services/refreshHsm'); -require('dotenv').config(); +const selectHsmClient = require('../services/selectHsmClient'); -let defaultClient; -var counterDirect = 0; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +let counterDirect = 0; const controller = async (req, res) => { try { - let useClient = defaultClient; if (counterDirect > 1 || counterDirect < 0) { counterDirect = 0; } counterDirect++; let { body } = req; - // uniqueCode = body.unique_code; const uniqueCode = `${helper.getUniqueCode()}${counterDirect}`; let result = {}; - let usingHSMNumber = process.env.NUMBER_SERVER_ACTIVE === '2' ? 2 : 1; - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - usingHSMNumber = 1; - // log warn - winston.logger.warn( - `${uniqueCode} ================================== REDIRECT USING HSM SERVER 1 ==================================}` - ); - useClient = client; - } else { - usingHSMNumber = 2; - // log warn - winston.logger.warn( - `${uniqueCode} ================================== USING HSM SERVER 2 ==================================}` - ); - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - usingHSMNumber = 2; - // log warn - winston.logger.warn( - `${uniqueCode} ================================== REDIRECT USING HSM SERVER 2 ==================================}` - ); - useClient = client2; - } else { - usingHSMNumber = 1; - // log warn - winston.logger.warn( - `${uniqueCode} ================================== USING HSM SERVER 1 ==================================}` - ); - useClient = client; - } - } - } + const { client: useClient, serverNumber, redirected } = selectHsmClient(uniqueCode); + if (redirected !== undefined) { + const action = redirected ? 'redirected' : 'selected'; + const message = `${uniqueCode} HSM server=${serverNumber} action=${action}`; + if (redirected) winston.logger.warn(message); + else winston.logger.debug(message); } // log info @@ -110,9 +57,9 @@ const controller = async (req, res) => { if (error?.code !== 'HSM_TIMEOUT') throw error; try { - await refreshHsm(usingHSMNumber); + await refreshHsm(serverNumber); } catch { - winston.logger.warn(`HSM server ${usingHSMNumber} refresh failed`); + winston.logger.warn(`HSM server ${serverNumber} refresh failed`); } return res.status(200).send({ code: '5001', message: 'Timeout', data: {} }); diff --git a/application/modules/hsm/clear_card/clear_2.js b/application/modules/hsm/clear_card/clear_2.js index fdaa71d..56ed44c 100644 --- a/application/modules/hsm/clear_card/clear_2.js +++ b/application/modules/hsm/clear_card/clear_2.js @@ -1,27 +1,10 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); const controller = async (req, res) => { try { - let useClient = defaultClient; let { body } = req; let uniqueCode = body.unique_code; let result = {}; @@ -31,28 +14,7 @@ const controller = async (req, res) => { `${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-2 ]` ); - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); let transactionId = parseHsmTransactionId(body.trxID); let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData)); diff --git a/application/modules/hsm/clear_card/clear_3.js b/application/modules/hsm/clear_card/clear_3.js index 088e0a0..438b5d7 100644 --- a/application/modules/hsm/clear_card/clear_3.js +++ b/application/modules/hsm/clear_card/clear_3.js @@ -1,27 +1,10 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); const controller = async (req, res) => { try { - let useClient = defaultClient; let { body } = req; let uniqueCode = body.unique_code; let result = {}; @@ -31,28 +14,7 @@ const controller = async (req, res) => { `${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-3 ]: request to HSM ` ); - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); let transactionId = parseHsmTransactionId(body.trxID); let auth2v2responseSetData = Buffer.from( diff --git a/application/modules/hsm/clear_card/clear_4.js b/application/modules/hsm/clear_card/clear_4.js index 49a618e..d96f4d2 100644 --- a/application/modules/hsm/clear_card/clear_4.js +++ b/application/modules/hsm/clear_card/clear_4.js @@ -1,27 +1,10 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); const controller = async (req, res) => { try { - let useClient = defaultClient; let { body } = req; let uniqueCode = body.unique_code; let result = {}; @@ -31,28 +14,7 @@ const controller = async (req, res) => { `${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-4 ]` ); - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); let transactionId = parseHsmTransactionId(body.trxID); let trxrequestData = Buffer.from(generate.hexToBytes(body.requestData)); diff --git a/application/modules/hsm/clear_card/clear_5.js b/application/modules/hsm/clear_card/clear_5.js index d4da9e4..da3d340 100644 --- a/application/modules/hsm/clear_card/clear_5.js +++ b/application/modules/hsm/clear_card/clear_5.js @@ -1,27 +1,10 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); const controller = async (req, res) => { try { - let useClient = defaultClient; let { body } = req; let uniqueCode = body.unique_code; let result = {}; @@ -31,28 +14,7 @@ const controller = async (req, res) => { `${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-5 ]` ); - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); let transactionId = parseHsmTransactionId(body.trxID); let packet = Buffer.from(generate.hexToBytes(body.requestData)); diff --git a/application/modules/hsm/clear_card/clear_6.js b/application/modules/hsm/clear_card/clear_6.js index 9fbfb18..1d39217 100644 --- a/application/modules/hsm/clear_card/clear_6.js +++ b/application/modules/hsm/clear_card/clear_6.js @@ -2,23 +2,7 @@ const { param, body, validationResult } = require('express-validator'); const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); // VALIDATION const validate = (method) => { @@ -35,35 +19,13 @@ const validate = (method) => { const controller = async (req, res) => { try { - let useClient = defaultClient; // param let { mid, tid, unique_code, trxID, requestData } = req.body; let uniqueCode = unique_code; let result = {}; - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); // log debug winston.logger.debug( diff --git a/application/modules/hsm/clear_card/clear_7.js b/application/modules/hsm/clear_card/clear_7.js index f6642c6..d53ba2c 100644 --- a/application/modules/hsm/clear_card/clear_7.js +++ b/application/modules/hsm/clear_card/clear_7.js @@ -2,23 +2,7 @@ const { param, body, validationResult } = require('express-validator'); const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); // VALIDATION const validate = (method) => { @@ -35,35 +19,13 @@ const validate = (method) => { const controller = async (req, res) => { try { - let useClient = defaultClient; // param let { mid, tid, unique_code, trxID, requestData } = req.body; let uniqueCode = unique_code; let result = {}; - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); // case success write to the card but loss contact with device // result = { diff --git a/application/modules/hsm/clear_card/clear_8.js b/application/modules/hsm/clear_card/clear_8.js index 5dcebad..2dc747d 100644 --- a/application/modules/hsm/clear_card/clear_8.js +++ b/application/modules/hsm/clear_card/clear_8.js @@ -1,27 +1,10 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); const controller = async (req, res) => { try { - let useClient = defaultClient; let { body } = req; let uniqueCode = body.unique_code; let result = {}; @@ -31,28 +14,7 @@ const controller = async (req, res) => { `${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-8 ]` ); - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); let transactionId = parseHsmTransactionId(body.trxID); diff --git a/application/modules/hsm/services/selectHsmClient.js b/application/modules/hsm/services/selectHsmClient.js new file mode 100644 index 0000000..2541bd0 --- /dev/null +++ b/application/modules/hsm/services/selectHsmClient.js @@ -0,0 +1,26 @@ +require('dotenv').config(); + +const activeServer = process.env.NUMBER_SERVER_ACTIVE; +const server1 = activeServer === '1' || activeServer === '12' ? require('./webSocket').client : undefined; +const server2 = activeServer === '2' || activeServer === '12' ? require('./webSocket2').client2 : undefined; + +// Kode genap memilih server 2. Jika server pilihan belum terautentikasi, gunakan server lainnya. +function selectHsmClient(uniqueCode) { + if (activeServer === '1') return { client: server1, serverNumber: 1 }; + if (activeServer === '2') return { client: server2, serverNumber: 2 }; + if (activeServer !== '12' || !uniqueCode) return {}; + + const preferredNumber = parseInt(uniqueCode) % 2 === 0 ? 2 : 1; + const preferred = preferredNumber === 1 ? server1 : server2; + if (preferred.clientAuthenticated === false) { + return { + client: preferredNumber === 1 ? server2 : server1, + serverNumber: preferredNumber === 1 ? 2 : 1, + redirected: true, + }; + } + + return { client: preferred, serverNumber: preferredNumber, redirected: false }; +} + +module.exports = selectHsmClient; diff --git a/application/modules/hsm/topup/topup_1.js b/application/modules/hsm/topup/topup_1.js index f943e3e..6648e94 100644 --- a/application/modules/hsm/topup/topup_1.js +++ b/application/modules/hsm/topup/topup_1.js @@ -3,80 +3,27 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage } = require('../services/requestHsm'); const refreshHsm = require('../services/refreshHsm'); -require('dotenv').config(); +const selectHsmClient = require('../services/selectHsmClient'); -let defaultClient; -var counterDirect = 0; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +let counterDirect = 0; const controller = async (req, res) => { try { - let useClient = defaultClient; if (counterDirect > 1 || counterDirect < 0) { counterDirect = 0; } counterDirect++; let { body } = req; - // uniqueCode = body.unique_code; const uniqueCode = `${helper.getUniqueCode()}${counterDirect}`; let result = {}; - let usingHSMNumber = process.env.NUMBER_SERVER_ACTIVE === '2' ? 2 : 1; - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - usingHSMNumber = 1; - // log warn - winston.logger.warn( - `${uniqueCode} ================================== REDIRECT USING HSM SERVER 1 ==================================}` - ); - useClient = client; - } else { - usingHSMNumber = 2; - // log warn - winston.logger.warn( - `${uniqueCode} ================================== USING HSM SERVER 2 ==================================}` - ); - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - usingHSMNumber = 2; - // log warn - winston.logger.warn( - `${uniqueCode} ================================== REDIRECT USING HSM SERVER 2 ==================================}` - ); - useClient = client2; - } else { - usingHSMNumber = 1; - // log warn - winston.logger.warn( - `${uniqueCode} ================================== USING HSM SERVER 1 ==================================}` - ); - useClient = client; - } - } - } + const { client: useClient, serverNumber, redirected } = selectHsmClient(uniqueCode); + if (redirected !== undefined) { + const action = redirected ? 'redirected' : 'selected'; + const message = `${uniqueCode} HSM server=${serverNumber} action=${action}`; + if (redirected) winston.logger.warn(message); + else winston.logger.debug(message); } // log info @@ -110,9 +57,9 @@ const controller = async (req, res) => { if (error?.code !== 'HSM_TIMEOUT') throw error; try { - await refreshHsm(usingHSMNumber); + await refreshHsm(serverNumber); } catch { - winston.logger.warn(`HSM server ${usingHSMNumber} refresh failed`); + winston.logger.warn(`HSM server ${serverNumber} refresh failed`); } return res.status(200).send({ code: '5001', message: 'Timeout', data: {} }); diff --git a/application/modules/hsm/topup/topup_2.js b/application/modules/hsm/topup/topup_2.js index b246103..5dae5d4 100644 --- a/application/modules/hsm/topup/topup_2.js +++ b/application/modules/hsm/topup/topup_2.js @@ -1,27 +1,10 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); const controller = async (req, res) => { try { - let useClient = defaultClient; let { body } = req; let uniqueCode = body.unique_code; let result = {}; @@ -31,28 +14,7 @@ const controller = async (req, res) => { `${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-2 ]` ); - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); let transactionId = parseHsmTransactionId(body.trxID); let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData)); diff --git a/application/modules/hsm/topup/topup_3.js b/application/modules/hsm/topup/topup_3.js index 196519d..667ce2b 100644 --- a/application/modules/hsm/topup/topup_3.js +++ b/application/modules/hsm/topup/topup_3.js @@ -1,27 +1,10 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); const controller = async (req, res) => { try { - let useClient = defaultClient; let { body } = req; let uniqueCode = body.unique_code; let result = {}; @@ -31,28 +14,7 @@ const controller = async (req, res) => { `${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-3 ]: request to HSM ` ); - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); let transactionId = parseHsmTransactionId(body.trxID); let auth2v2responseSetData = Buffer.from( diff --git a/application/modules/hsm/topup/topup_4.js b/application/modules/hsm/topup/topup_4.js index 3b110ed..7aa17f7 100644 --- a/application/modules/hsm/topup/topup_4.js +++ b/application/modules/hsm/topup/topup_4.js @@ -1,27 +1,10 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); const controller = async (req, res) => { try { - let useClient = defaultClient; let { body } = req; let uniqueCode = body.unique_code; let result = {}; @@ -31,28 +14,7 @@ const controller = async (req, res) => { `${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-4 ]` ); - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); let transactionId = parseHsmTransactionId(body.trxID); let trxrequestData = Buffer.from(generate.hexToBytes(body.requestData)); diff --git a/application/modules/hsm/topup/topup_5.js b/application/modules/hsm/topup/topup_5.js index affce1e..4ee9888 100644 --- a/application/modules/hsm/topup/topup_5.js +++ b/application/modules/hsm/topup/topup_5.js @@ -1,27 +1,10 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); const controller = async (req, res) => { try { - let useClient = defaultClient; let { body } = req; let uniqueCode = body.unique_code; let result = {}; @@ -31,28 +14,7 @@ const controller = async (req, res) => { `${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-5 ]` ); - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); let transactionId = parseHsmTransactionId(body.trxID); let packet = Buffer.from(generate.hexToBytes(body.requestData)); diff --git a/application/modules/hsm/topup/topup_6.js b/application/modules/hsm/topup/topup_6.js index 126df06..ef30e78 100644 --- a/application/modules/hsm/topup/topup_6.js +++ b/application/modules/hsm/topup/topup_6.js @@ -3,23 +3,7 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const loadBalance = require('../../loadbalance/loadbalance.controller'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); // VALIDATION const validate = (method) => { @@ -54,7 +38,6 @@ const validate = (method) => { const controller = async (req, res) => { try { - let useClient = defaultClient; // param let { mid, @@ -76,28 +59,7 @@ const controller = async (req, res) => { let uniqueCode = unique_code; let result = {}; - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); // log debug winston.logger.debug( diff --git a/application/modules/hsm/topup/topup_7.js b/application/modules/hsm/topup/topup_7.js index 652e1a6..76716a2 100644 --- a/application/modules/hsm/topup/topup_7.js +++ b/application/modules/hsm/topup/topup_7.js @@ -3,23 +3,7 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const loadBalance = require('../../loadbalance/loadbalance.controller'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); // VALIDATION const validate = (method) => { @@ -58,7 +42,6 @@ const validate = (method) => { const controller = async (req, res) => { try { - let useClient = defaultClient; // param let { mid, @@ -79,28 +62,7 @@ const controller = async (req, res) => { let uniqueCode = unique_code; let result = {}; - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); // case success write to the card but loss contact with device // result = { diff --git a/application/modules/hsm/topup/topup_8.js b/application/modules/hsm/topup/topup_8.js index fb9e967..0143053 100644 --- a/application/modules/hsm/topup/topup_8.js +++ b/application/modules/hsm/topup/topup_8.js @@ -1,27 +1,10 @@ const winston = require('../../../helpers/winston.logger'); const generate = require('../utils/utils'); const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm'); -require('dotenv').config(); - -let defaultClient; - -// set connection HSM server -if (process.env.NUMBER_SERVER_ACTIVE == '1') { - var { client } = require('../services/webSocket'); - - defaultClient = client; -} else if (process.env.NUMBER_SERVER_ACTIVE == '2') { - var { client2 } = require('../services/webSocket2'); - - defaultClient = client2; -} else if (process.env.NUMBER_SERVER_ACTIVE == '12') { - var { client } = require('../services/webSocket'); - var { client2 } = require('../services/webSocket2'); -} +const selectHsmClient = require('../services/selectHsmClient'); const controller = async (req, res) => { try { - let useClient = defaultClient; let { body } = req; let uniqueCode = body.unique_code; let result = {}; @@ -31,28 +14,7 @@ const controller = async (req, res) => { `${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-8 ]` ); - // set connection HSM server - if (process.env.NUMBER_SERVER_ACTIVE == '12') { - // set request to HSM server 2 - if (uniqueCode) { - if (parseInt(uniqueCode) % 2 == 0) { - // create log - // winston.logger.error(`request to HSM server 2`); - - if (client2.clientAuthenticated == false) { - useClient = client; - } else { - useClient = client2; - } - } else { - if (client.clientAuthenticated == false) { - useClient = client2; - } else { - useClient = client; - } - } - } - } + const { client: useClient } = selectHsmClient(uniqueCode); let transactionId = parseHsmTransactionId(body.trxID); diff --git a/application/modules/invoiceonline/invoice.controller.js b/application/modules/invoiceonline/invoice.controller.js index bdb0b51..05c4dbc 100644 --- a/application/modules/invoiceonline/invoice.controller.js +++ b/application/modules/invoiceonline/invoice.controller.js @@ -1,4 +1,4 @@ -const { param, body, validationResult } = require('express-validator'); +const { body, validationResult } = require('express-validator'); const helper = require('../../helpers/helper'); const winston = require('../../helpers/winston.logger'); const { generateInvoice: _generateInvoice, retryInvoices: _postingInvoice } = require('./invoice-posting.service'); @@ -44,12 +44,12 @@ const validate = (method) => { const apiGenerateInvoice = async (req, res) => { try { // generate unique code - let uniqueCode = helper.getUniqueCode(); + const uniqueCode = helper.getUniqueCode(); let result = {}; // log info winston.logger.info( - `${uniqueCode} REQUEST generate invoice: ${JSON.stringify(req.body)}` + `${uniqueCode} REQUEST generate invoice` ); const schedulerCode = 'GENERATEINVOICEONLINETOPUP'; @@ -57,7 +57,7 @@ const apiGenerateInvoice = async (req, res) => { const token = startData.c_execution_token ?? null; // check validator - let err = validationResult(req, res); + const err = validationResult(req, res); if (!err.isEmpty()) { result = { code: '400', @@ -67,16 +67,16 @@ const apiGenerateInvoice = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE generate invoice: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE generate invoice code=${result.code}` ); return res.status(200).json(result); } // time - let invoiceDate = moment(req.body.trx_date).format('YYYY-MM-DD'); + const invoiceDate = moment(req.body.trx_date).format('YYYY-MM-DD'); - let invoice = await _generateInvoice( + const invoice = await _generateInvoice( invoiceDate, uniqueCode, req.body.repost @@ -88,7 +88,7 @@ const apiGenerateInvoice = async (req, res) => { data: invoice, }; - const finishData = await helper.finishScheduler(token, schedulerCode); + await helper.finishScheduler(token, schedulerCode); return res.status(200).json(result); } catch (error) { @@ -112,12 +112,12 @@ const apiGenerateInvoice = async (req, res) => { const apiPostingInvoice = async (req, res) => { try { // generate unique code - let uniqueCode = helper.getUniqueCode(); + const uniqueCode = helper.getUniqueCode(); let result = {}; // log info winston.logger.info( - `${uniqueCode} REQUEST posting invoice: ${JSON.stringify(req.body)}` + `${uniqueCode} REQUEST posting invoice` ); const schedulerCode = 'POSTINGINVOICEONLINETOPUP'; @@ -125,7 +125,7 @@ const apiPostingInvoice = async (req, res) => { const token = startData.c_execution_token ?? null; // check validator - let err = validationResult(req, res); + const err = validationResult(req, res); if (!err.isEmpty()) { result = { code: '400', @@ -135,7 +135,7 @@ const apiPostingInvoice = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE generate invoice: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE generate invoice code=${result.code}` ); return res.status(200).json(result); @@ -144,7 +144,7 @@ const apiPostingInvoice = async (req, res) => { // return uniqueCode winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING INVOICE`); - let invoice = await _postingInvoice(uniqueCode); + const invoice = await _postingInvoice(uniqueCode); result = { code: '200', @@ -152,7 +152,7 @@ const apiPostingInvoice = async (req, res) => { data: invoice, }; - const finishData = await helper.finishScheduler(token, schedulerCode); + await helper.finishScheduler(token, schedulerCode); return res.status(200).json(result); } catch (error) { diff --git a/application/modules/invoicesemionline/invoice-posting.service.js b/application/modules/invoicesemionline/invoice-posting.service.js new file mode 100644 index 0000000..fbe3f39 --- /dev/null +++ b/application/modules/invoicesemionline/invoice-posting.service.js @@ -0,0 +1,191 @@ +const knex = require('../../../infrastructure/database/knex'); +const winston = require('../../helpers/winston.logger'); +const helper = require('../../helpers/helper'); +const model = require('./invoice.model'); + +// Simpan data invoice sebelum mengirim dokumen ke SAP. +const _generateInvoice = async (invoiceDate, uniqueCode, repost) => { + let invoice = []; + + await knex.transaction(async (trx) => { + winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`); + + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} execute payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})` + ); + + invoice = await model.generateInvoice(invoiceDate, repost, trx); + + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} result payment.sp_payment_req_topup_online count=${invoice.length}` + ); + + if (invoice.length > 0) + for (const key in invoice) { + await model.writePaynentHistory(invoice[key], trx); + await model.insertPostingEt(invoice[key], trx); + } + }); + + if (invoice.length > 0) { + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP` + ); + + const url = + 'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2'; + + for (const key in invoice) { + const xmlHeader = { + doc_header_text: invoice[key].doc_header_text + ? invoice[key].doc_header_text + : '', + ba: invoice[key].ba ? invoice[key].ba : '', + doc_date: invoice[key].doc_date ? invoice[key].doc_date : '', + posting_date: invoice[key].posting_date + ? invoice[key].posting_date + : '', + fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : '', + fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : '', + doc_type: invoice[key].doc_type ? invoice[key].doc_type : '', + c_invoice_no: invoice[key].c_invoice_no + ? invoice[key].c_invoice_no + : '', + }; + + const xmlItem = ['S', 'H'].map((item) => { + return { + c_account_code_topup: + item === 'S' ? invoice[key].c_account_code_topup : '', + c_account_topup: item === 'H' ? invoice[key].c_account_topup : '', + ba: invoice[key].ba, + amount: invoice[key].amount, + posting_date: invoice[key].posting_date, + c_invoice_no: invoice[key].c_invoice_no, + item_text: `${item === 'S' ? 'DEBIT' : 'KREDIT'} INVOICE CMS ${ + invoice[key].doc_header_text + }`, + de_cre: item, + }; + }); + + const xmlRequest = helper.generateXMLRequest( + 'ZFMCMS_FI_001', + xmlHeader, + xmlItem + ); + + winston.logger.debug( + `SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP` + ); + + const response = await helper.postingSAP(url, xmlRequest); + + winston.logger.debug( + `SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${ + invoice[key].c_invoice_no + } from SAP` + ); + + // new transaction + await knex.transaction(async (trx) => { + const resSAP = helper.getXMLData(response); + + winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 2`); + // UPDATE CMS + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} SAP outcome type=${resSAP.type}` + ); + + await model.setReturnSAP(invoice[key], resSAP, trx); + + winston.logger.info( + `SCHEDULER-FB70-${uniqueCode} CMS update completed` + ); + }); + } + } + + return invoice; +}; + +const _postingInvoice = async (uniqueCode) => { + let postingEt = []; + await knex.transaction(async (trx) => { + postingEt = await model.getPostingEt(trx); + + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} GET POSTING ET count=${postingEt.length}` + ); + + // Retry lama menyimpan hasil seluruh batch dalam satu transaksi. + for (const item of postingEt) { + const xmlHeader = { + doc_header_text: item.doc_header_text ? item.doc_header_text : '', + ba: item.ba ? item.ba : '', + doc_date: item.doc_date ? item.doc_date : '', + posting_date: item.posting_date ? item.posting_date : '', + fisc_year: item.fiscal_year ? item.fiscal_year : '', + fisc_period: item.fis_period ? item.fis_period : '', + doc_type: item.doc_type ? item.doc_type : '', + c_invoice_no: item.reference ? item.reference : '', + }; + + const xmlItem = ['S', 'H'].map((key) => { + return { + c_account_code_topup: key === 'S' ? item.customer : '', + c_account_topup: key === 'H' ? item.account : '', + ba: item.ba, + amount: item.amount, + posting_date: item.posting_date, + c_invoice_no: item.reference, + item_text: key === 'S' ? item.text1 : item.text2, + de_cre: key, + }; + }); + + const xmlRequest = helper.generateXMLRequest( + 'ZFMCMS_FI_001', + xmlHeader, + xmlItem + ); + + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP` + ); + + const url = + 'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2'; + + const response = await helper.postingSAP(url, xmlRequest); + + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${ + item.reference + } from SAP` + ); + + const resSAP = helper.getXMLData(response); + + winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`); + // UPDATE CMS + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} SAP outcome type=${resSAP.type}` + ); + + await model.setReturnSAP( + { c_invoice_no: item.reference }, + resSAP, + trx + ); + + winston.logger.info( + `SCHEDULER-RETRY-${uniqueCode} CMS update completed` + ); + } + }); + + return postingEt; +}; + +module.exports = { _generateInvoice, _postingInvoice }; diff --git a/application/modules/invoicesemionline/invoice.controller.js b/application/modules/invoicesemionline/invoice.controller.js index c3947f1..6e56709 100644 --- a/application/modules/invoicesemionline/invoice.controller.js +++ b/application/modules/invoicesemionline/invoice.controller.js @@ -1,9 +1,8 @@ -const { param, body, validationResult } = require('express-validator'); +const { body, validationResult } = require('express-validator'); const helper = require('../../helpers/helper'); const winston = require('../../helpers/winston.logger'); -const model = require('./invoice.model'); const moment = require('moment'); -const knex = require('../../../infrastructure/database/knex'); +const { _generateInvoice, _postingInvoice } = require('./invoice-posting.service'); moment.locale('id'); // VALIDATION @@ -50,7 +49,7 @@ const apiGenerateInvoice = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} REQUEST generate invoice: ${JSON.stringify(req.body)}` + `${uniqueCode} REQUEST generate invoice` ); // check validator @@ -64,7 +63,7 @@ const apiGenerateInvoice = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE generate invoice: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE generate invoice code=${result.code}` ); return res.status(200).json(result); @@ -112,7 +111,7 @@ const apiPostingInvoice = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} REQUEST posting invoice: ${JSON.stringify(req.body)}` + `${uniqueCode} REQUEST posting invoice` ); // check validator @@ -126,7 +125,7 @@ const apiPostingInvoice = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} RESPONSE generate invoice: ${JSON.stringify(result)}` + `${uniqueCode} RESPONSE generate invoice code=${result.code}` ); return res.status(200).json(result); @@ -161,226 +160,6 @@ const apiPostingInvoice = async (req, res) => { } }; -const _generateInvoice = async (invoiceDate, uniqueCode, repost) => { - let invoice = []; - - await knex.transaction(async (trx) => { - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`); - - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} execute payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})` - ); - - invoice = await model.generateInvoice(invoiceDate, repost, trx); - - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} result payment.sp_payment_req_topup_online ${JSON.stringify( - invoice - )}` - ); - - if (invoice.length > 0) - for (let key in invoice) { - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} insert payment history et : ${JSON.stringify( - invoice - )}` - ); - - let history = await model.writePaynentHistory(invoice[key], trx); - - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} result insert payment history et : ${JSON.stringify( - history - )}` - ); - - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify( - invoice[key] - )}` - ); - - let postingEt = await model.insertPostingEt(invoice[key], trx); - - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} success insert posting et : ${JSON.stringify( - postingEt - )}` - ); - } - }); - - if (invoice.length > 0) { - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP` - ); - - let url = - 'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2'; - - for (let key in invoice) { - let xmlHeader = { - doc_header_text: invoice[key].doc_header_text - ? invoice[key].doc_header_text - : '', - ba: invoice[key].ba ? invoice[key].ba : '', - doc_date: invoice[key].doc_date ? invoice[key].doc_date : '', - posting_date: invoice[key].posting_date - ? invoice[key].posting_date - : '', - fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : '', - fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : '', - doc_type: invoice[key].doc_type ? invoice[key].doc_type : '', - c_invoice_no: invoice[key].c_invoice_no - ? invoice[key].c_invoice_no - : '', - }; - - let xmlItem = ['S', 'H'].map((item) => { - return { - c_account_code_topup: - item == 'S' ? invoice[key].c_account_code_topup : '', - c_account_topup: item == 'H' ? invoice[key].c_account_topup : '', - ba: invoice[key].ba, - amount: invoice[key].amount, - posting_date: invoice[key].posting_date, - c_invoice_no: invoice[key].c_invoice_no, - item_text: `${item == 'S' ? 'DEBIT' : 'KREDIT'} INVOICE CMS ${ - invoice[key].doc_header_text - }`, - de_cre: item, - }; - }); - - let xmlRequest = helper.generateXMLRequest( - 'ZFMCMS_FI_001', - xmlHeader, - xmlItem - ); - - winston.logger.debug( - `SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}` - ); - - let response = await helper.postingSAP(url, xmlRequest); - - winston.logger.debug( - `SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${ - invoice[key].c_invoice_no - } to SAP : ${JSON.stringify(response)}` - ); - - // new transaction - await knex.transaction(async (trx) => { - let resSAP = helper.getXMLData(response); - - winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 2`); - // UPDATE CMS - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify( - resSAP - )}` - ); - - let cms = await model.setReturnSAP(invoice[key], resSAP, trx); - - winston.logger.info( - `SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}` - ); - }); - } - } - - return invoice; -}; - -const _postingInvoice = async (uniqueCode) => { - let postingEt = []; - await knex.transaction(async (trx) => { - postingEt = await model.getPostingEt(trx); - - winston.logger.info( - `SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify( - postingEt - )}` - ); - - for (let item of postingEt) { - let xmlHeader = { - doc_header_text: item.doc_header_text ? item.doc_header_text : '', - ba: item.ba ? item.ba : '', - doc_date: item.doc_date ? item.doc_date : '', - posting_date: item.posting_date ? item.posting_date : '', - fisc_year: item.fiscal_year ? item.fiscal_year : '', - fisc_period: item.fis_period ? item.fis_period : '', - doc_type: item.doc_type ? item.doc_type : '', - c_invoice_no: item.reference ? item.reference : '', - }; - - let xmlItem = ['S', 'H'].map((key) => { - return { - c_account_code_topup: key == 'S' ? item.customer : '', - c_account_topup: key == 'H' ? item.account : '', - ba: item.ba, - amount: item.amount, - posting_date: item.posting_date, - c_invoice_no: item.reference, - item_text: key == 'S' ? item.text1 : item.text2, - de_cre: key, - }; - }); - - let xmlRequest = helper.generateXMLRequest( - 'ZFMCMS_FI_001', - xmlHeader, - xmlItem - ); - - winston.logger.info( - `SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}` - ); - - let url = - 'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2'; - - let response = await helper.postingSAP(url, xmlRequest); - - winston.logger.info( - `SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${ - item.reference - } to SAP : ${JSON.stringify(response)}` - ); - - // new transaction - // await knex.transaction(async trx => { - - let resSAP = helper.getXMLData(response); - - winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`); - // UPDATE CMS - winston.logger.info( - `SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify( - resSAP - )}` - ); - - let cms = await model.setReturnSAP( - { c_invoice_no: item.reference }, - resSAP, - trx - ); - - winston.logger.info( - `SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}` - ); - // }) - } - }); - - return postingEt; -}; - module.exports = { validate, apiPostingInvoice, diff --git a/application/modules/invoicesemionline/invoice.model.js b/application/modules/invoicesemionline/invoice.model.js index e0b8cfe..0b36b10 100644 --- a/application/modules/invoicesemionline/invoice.model.js +++ b/application/modules/invoicesemionline/invoice.model.js @@ -2,8 +2,9 @@ // GET PARTNER, MERCHANT, TERMINAL FROM TID const generateInvoice = async (invoiceDate, repost, trx) => { - let result = await trx.raw( - `SELECT * FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})` + const result = await trx.raw( + 'SELECT * FROM payment.sp_payment_req_topup_online(?, ?::boolean)', + [invoiceDate, repost] ) return result.rows || result; @@ -104,7 +105,9 @@ const setReturnSAP = async (invoice, resSAP, trx) => { t_load_balance = await trx('trx.t_d_load_balance').update({ c_return_sap: resSAP.data.E_DOCUMENTNUMBER }, ['c_load_balance_no', 'c_return_sap']) - .whereRaw(`c_load_balance_no IN (SELECT c_load_balance_no FROM payment.t_d_payment_request_topup_online WHERE c_payment = '${invoice.c_invoice_no}')`) + .whereIn('c_load_balance_no', trx('payment.t_d_payment_request_topup_online') + .select('c_load_balance_no') + .where('c_payment', invoice.c_invoice_no)); } diff --git a/application/modules/loadbalance/loadbalance.controller.js b/application/modules/loadbalance/loadbalance.controller.js index 069f257..b58b058 100644 --- a/application/modules/loadbalance/loadbalance.controller.js +++ b/application/modules/loadbalance/loadbalance.controller.js @@ -1,51 +1,11 @@ -const { param, body, validationResult } = require('express-validator'); +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'); moment.locale('id'); -// 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 UPDATE ALL TRANSACTION ====================================================== // *Created By: Mohamad Ihsan* diff --git a/application/modules/loadbalance/loadbalance.validation.js b/application/modules/loadbalance/loadbalance.validation.js new file mode 100644 index 0000000..27f40b5 --- /dev/null +++ b/application/modules/loadbalance/loadbalance.validation.js @@ -0,0 +1,46 @@ +const { body } = require('express-validator'); + +// Aturan input untuk setiap operasi. Urutan validasi mengikuti kontrak API. +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; + } +}; + + +module.exports = validate; diff --git a/application/modules/paymentrecon/payment-recon-number.service.js b/application/modules/paymentrecon/payment-recon-number.service.js new file mode 100644 index 0000000..a32b87b --- /dev/null +++ b/application/modules/paymentrecon/payment-recon-number.service.js @@ -0,0 +1,29 @@ +const { setTimeout: delay } = require('node:timers/promises'); +const moment = require('moment'); +const helper = require('../../helpers/helper'); +const winston = require('../../helpers/winston.logger'); +const model = require('./paymentrecon.model'); + +// Pertahankan jeda sebelum tiap percobaan. Ulangi hanya jika nomor sudah diklaim. +async function allocatePaymentReconNumber(partnerCode, reconDate) { + for (let attempt = 0; attempt < 5; attempt += 1) { + await delay(helper.randomNumberInt()); + const number = await generatePaymentReconNumber(partnerCode, reconDate); + if (number !== 'XX') return number; + } + return 'XX'; +} + +async function generatePaymentReconNumber(partnerCode, reconDate) { + const lastCounter = await model.getLastCounterPaymentReconNo(partnerCode, reconDate); + const nextCounter = lastCounter ? parseInt(lastCounter.c_payment_recon_no.slice(-6)) + 1 : 1; + const counter = String(nextCounter).padStart(6, '0'); + const date = moment(reconDate).format('YYMMDD'); + const paymentReconNumber = `RC${partnerCode}${date}${counter}`; + winston.logger.debug(`Payment Recon Number: ${paymentReconNumber}`); + + const insert = await model.insertPaymentReconNumber(paymentReconNumber); + return insert.rowCount < 1 ? 'XX' : paymentReconNumber; +} + +module.exports = { allocatePaymentReconNumber }; diff --git a/application/modules/paymentrecon/paymentrecon.controller.js b/application/modules/paymentrecon/paymentrecon.controller.js index 348e975..b996dbd 100644 --- a/application/modules/paymentrecon/paymentrecon.controller.js +++ b/application/modules/paymentrecon/paymentrecon.controller.js @@ -5,7 +5,7 @@ const model = require('./paymentrecon.model'); const queue = require('../../helpers/queue'); const moment = require('moment'); const { default: axios } = require('axios'); -const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +const { allocatePaymentReconNumber } = require('./payment-recon-number.service'); moment.locale('id'); var dataReconQueue = []; @@ -215,49 +215,10 @@ const paymentRecon = async (req, res) => { return res.status(200).json(result); } - let partnerCode = getPartner.partner_code; - let PaymentReconNumber; + const partnerCode = getPartner.partner_code; + const PaymentReconNumber = await allocatePaymentReconNumber(partnerCode, now); - // log debug - // winston.logger.debug( - // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: generating payment recon number...` - // ); - - // loop 1 - await _sleep(helper.randomNumberInt()); - PaymentReconNumber = await generatePaymentReconNumber(partnerCode, now); - - if (PaymentReconNumber == 'XX') { - // loop 2 - await _sleep(helper.randomNumberInt()); - PaymentReconNumber = await generatePaymentReconNumber(partnerCode, now); - - if (PaymentReconNumber == 'XX') { - // loop 3 - await _sleep(helper.randomNumberInt()); - PaymentReconNumber = await generatePaymentReconNumber(partnerCode, now); - - if (PaymentReconNumber == 'XX') { - // loop 4 - await _sleep(helper.randomNumberInt()); - PaymentReconNumber = await generatePaymentReconNumber( - partnerCode, - now - ); - - if (PaymentReconNumber == 'XX') { - // loop 5 - await _sleep(helper.randomNumberInt()); - PaymentReconNumber = await generatePaymentReconNumber( - partnerCode, - now - ); - } - } - } - } - - if (PaymentReconNumber == 'XX') { + if (PaymentReconNumber === 'XX') { result = { code: '500', message: 'server is busy. please try again.', @@ -496,48 +457,6 @@ const paymentRecon = async (req, res) => { } }; -// ================================================================= GENERATE PAYMENT RECON NUMEBR ================================================================= -// *Created By: Mohamad Ihsan* -// *Description:* -// function yang digunakan untuk mengenerate payment recon number - -const generatePaymentReconNumber = async (partnerCode, reconDate) => { - let counter = '1'; - let getLastCounterPaymentReconNo = await model.getLastCounterPaymentReconNo( - partnerCode, - reconDate - ); - - if (getLastCounterPaymentReconNo) { - counter = ( - parseInt( - getLastCounterPaymentReconNo.c_payment_recon_no.substr( - getLastCounterPaymentReconNo.c_payment_recon_no.length - 6 - ) - ) + 1 - ).toString(); - counter = counter.padStart(6, '0'); - } else { - counter = counter.padStart(6, '0'); - } - - let paymentReconNumber; - paymentReconNumber = `RC${partnerCode}${moment(reconDate).format( - 'YYMMDD' - )}${counter}`; - - // log debug - winston.logger.debug(`Payment Recon Number: ${paymentReconNumber}`); - - // insert to tempPaymentReconNumber - let insert = await model.insertPaymentReconNumber(paymentReconNumber); - if (insert.rowCount < 1) { - paymentReconNumber = 'XX'; - } - - return paymentReconNumber; -}; - module.exports = { validate, paymentRecon, diff --git a/application/modules/pos/cts-client.js b/application/modules/pos/cts-client.js new file mode 100644 index 0000000..629750e --- /dev/null +++ b/application/modules/pos/cts-client.js @@ -0,0 +1,9 @@ +const { default: axios } = require('axios'); + +// Kegagalan CTS harus selesai pada jalur error yang sudah dimiliki endpoint. +function postWithDeadline(url, data, config) { + const timeout = 5000; + return axios.post(url, data, { ...config, timeout, signal: AbortSignal.timeout(timeout) }); +} + +module.exports = { postWithDeadline }; diff --git a/application/modules/pos/pos.controller.js b/application/modules/pos/pos.controller.js index 4da2717..045fd5a 100644 --- a/application/modules/pos/pos.controller.js +++ b/application/modules/pos/pos.controller.js @@ -1,159 +1,14 @@ -const { default: axios } = require('axios'); - -// Kegagalan CTS harus selesai pada jalur error yang sudah dimiliki endpoint. -function postWithDeadline(url, data, config) { - const timeout = 5000; - return axios.post(url, data, { ...config, timeout, signal: AbortSignal.timeout(timeout) }); -} +const { postWithDeadline } = require('./cts-client'); const knex = require('../../../infrastructure/database/knex'); -const { param, body, validationResult } = require('express-validator'); +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 _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const moment = require('moment'); -const { Console } = require('winston/lib/winston/transports'); moment.locale('id'); -// VALIDATION -const validate = (method) => { - switch (method) { - case 'validateCardSales': - return [ - body('card_number') - .not() - .isEmpty() - .withMessage('Card number is required'), - ]; - case 'validateLastBalance': - return [ - body('card_number') - .not() - .isEmpty() - .withMessage('Card number is required'), - ]; - case 'validateCardTopup': - return [ - 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('last_balance') - .not() - .isEmpty() - .withMessage('Last Balance is required') - .isNumeric() - .withMessage('Last Balance is invalid format'), - ]; - case 'validateCardRedeem': - return [ - body('card_number') - .not() - .isEmpty() - .withMessage('Card number is required'), - body('station_code') - .not() - .isEmpty() - .withMessage('Station Code is required'), - ]; - case 'checkBlacklist': - return [ - body('card_number') - .not() - .isEmpty() - .withMessage('Card number is required'), - ]; - case 'validateCardReplacement': - return [ - body('card_number') - .not() - .isEmpty() - .withMessage('Card number is required'), - body('station_code') - .not() - .isEmpty() - .withMessage('Station Code is required'), - ]; - case 'validateNewCardReplacement': - return [ - body('card_number') - .not() - .isEmpty() - .withMessage('Card number is required'), - ]; - - //card_number, new_card_number, last_balance, security_code, unique_code - case 'cardReplacementConfirm': - return [ - body('card_number').not().isEmpty(), - body('new_card_number') - .not() - .isEmpty() - .withMessage('New Card number is required'), - body('last_balance') - .not() - .isEmpty() - .withMessage('Last Balance is required') - .isNumeric() - .withMessage('Last Balance is invalid format'), - body('unique_code') - .not() - .isEmpty() - .withMessage('Unique Code is required'), - body('security_code') - .not() - .isEmpty() - .withMessage('Security Code is required'), - ]; - case 'confirmCardRedeem': - return [ - body('card_number') - .not() - .isEmpty() - .withMessage('Card number is required'), - body('security_code') - .not() - .isEmpty() - .withMessage('Security Code is required'), - ]; - case 'confirmCardSales': - return [ - body('card_number') - .not() - .isEmpty() - .withMessage('Card number is required'), - body('sales_status') - .not() - .isEmpty() - .withMessage('Sales status Code is required'), - body('device_code') - .not() - .isEmpty() - .withMessage('Device Code is required'), - body('station_code') - .not() - .isEmpty() - .withMessage('Station Code is required'), - body('station_name') - .not() - .isEmpty() - .withMessage('Station name is required'), - body('created_by') - .not() - .isEmpty() - .withMessage('Created by is required'), - ]; - default: - break; - } -}; /****************** */ /* GLOBAL PARAMETER */ diff --git a/application/modules/pos/pos.validation.js b/application/modules/pos/pos.validation.js new file mode 100644 index 0000000..ed608a7 --- /dev/null +++ b/application/modules/pos/pos.validation.js @@ -0,0 +1,143 @@ +const { body } = require('express-validator'); + +// Aturan input untuk setiap operasi. Urutan validasi mengikuti kontrak API. +const validate = (method) => { + switch (method) { + case 'validateCardSales': + return [ + body('card_number') + .not() + .isEmpty() + .withMessage('Card number is required'), + ]; + case 'validateLastBalance': + return [ + body('card_number') + .not() + .isEmpty() + .withMessage('Card number is required'), + ]; + case 'validateCardTopup': + return [ + 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('last_balance') + .not() + .isEmpty() + .withMessage('Last Balance is required') + .isNumeric() + .withMessage('Last Balance is invalid format'), + ]; + case 'validateCardRedeem': + return [ + body('card_number') + .not() + .isEmpty() + .withMessage('Card number is required'), + body('station_code') + .not() + .isEmpty() + .withMessage('Station Code is required'), + ]; + case 'checkBlacklist': + return [ + body('card_number') + .not() + .isEmpty() + .withMessage('Card number is required'), + ]; + case 'validateCardReplacement': + return [ + body('card_number') + .not() + .isEmpty() + .withMessage('Card number is required'), + body('station_code') + .not() + .isEmpty() + .withMessage('Station Code is required'), + ]; + case 'validateNewCardReplacement': + return [ + body('card_number') + .not() + .isEmpty() + .withMessage('Card number is required'), + ]; + + //card_number, new_card_number, last_balance, security_code, unique_code + case 'cardReplacementConfirm': + return [ + body('card_number').not().isEmpty(), + body('new_card_number') + .not() + .isEmpty() + .withMessage('New Card number is required'), + body('last_balance') + .not() + .isEmpty() + .withMessage('Last Balance is required') + .isNumeric() + .withMessage('Last Balance is invalid format'), + body('unique_code') + .not() + .isEmpty() + .withMessage('Unique Code is required'), + body('security_code') + .not() + .isEmpty() + .withMessage('Security Code is required'), + ]; + case 'confirmCardRedeem': + return [ + body('card_number') + .not() + .isEmpty() + .withMessage('Card number is required'), + body('security_code') + .not() + .isEmpty() + .withMessage('Security Code is required'), + ]; + case 'confirmCardSales': + return [ + body('card_number') + .not() + .isEmpty() + .withMessage('Card number is required'), + body('sales_status') + .not() + .isEmpty() + .withMessage('Sales status Code is required'), + body('device_code') + .not() + .isEmpty() + .withMessage('Device Code is required'), + body('station_code') + .not() + .isEmpty() + .withMessage('Station Code is required'), + body('station_name') + .not() + .isEmpty() + .withMessage('Station name is required'), + body('created_by') + .not() + .isEmpty() + .withMessage('Created by is required'), + ]; + default: + break; + } +}; + + +module.exports = validate; diff --git a/application/modules/refundkmt/refundkmt.controller.js b/application/modules/refundkmt/refundkmt.controller.js index 96b0320..3d2cf25 100644 --- a/application/modules/refundkmt/refundkmt.controller.js +++ b/application/modules/refundkmt/refundkmt.controller.js @@ -53,7 +53,7 @@ const callbackOy = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} [ REQUEST REFUND-KMT ]: ${JSON.stringify(req.body)}` + `${uniqueCode} [ REQUEST REFUND-KMT ]` ); // check validator @@ -67,7 +67,7 @@ const callbackOy = async (req, res) => { // log warn winston.logger.warn( - `${uniqueCode} [ RESPONSE REFUND-KMT ]: ${JSON.stringify(result)}` + `${uniqueCode} [ RESPONSE REFUND-KMT ] code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); @@ -75,9 +75,6 @@ const callbackOy = async (req, res) => { // time let now = moment().format('YYYY-MM-DD HH:mm:ss'); - winston.logger.warn( - `${uniqueCode} [ RESPONSE REFUND-KMT ]: ${JSON.stringify(result)}` - ); let recipient_bank_code = recipient_bank.toUpperCase(); // check trx_id yang di request match @@ -96,7 +93,7 @@ const callbackOy = async (req, res) => { data: {}, }; winston.logger.warn( - `${uniqueCode} [ RESPONSE REFUND-KMT ]: ${JSON.stringify(result)}` + `${uniqueCode} [ RESPONSE REFUND-KMT ] code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); } else if (checkRequest.c_status?.trim() == 'A') { @@ -106,13 +103,13 @@ const callbackOy = async (req, res) => { data: {}, }; winston.logger.warn( - `${uniqueCode} [ RESPONSE REFUND-KMT ]: ${JSON.stringify(result)}` + `${uniqueCode} [ RESPONSE REFUND-KMT ] code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); } winston.logger.warn( - `${uniqueCode} [ checkRequest ]: ${JSON.stringify(checkRequest)}` + `${uniqueCode} [ checkRequest ] found=${Boolean(checkRequest)}` ); if (status.code != '000') { @@ -134,7 +131,7 @@ const callbackOy = async (req, res) => { ); winston.logger.warn( - `${uniqueCode} [ log date_reimbusement ]: ${JSON.stringify(date_reimbursement)}` + `${uniqueCode} [ log date_reimbusement ]: ${date_reimbursement}` ); //Update Card Replacement @@ -191,7 +188,7 @@ const callbackOy = async (req, res) => { // log info winston.logger.info( - `${uniqueCode} [ RESPONSE REFUND-KMT ]: ${JSON.stringify(result)}` + `${uniqueCode} [ RESPONSE REFUND-KMT ] code=${result.code ?? "UNKNOWN"}` ); return res.status(200).json(result); diff --git a/application/modules/reservebalance/reservebalance.controller.js b/application/modules/reservebalance/reservebalance.controller.js index f421892..989629e 100644 --- a/application/modules/reservebalance/reservebalance.controller.js +++ b/application/modules/reservebalance/reservebalance.controller.js @@ -1,92 +1,11 @@ -const { param, body, validationResult } = require('express-validator'); +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'); moment.locale('id'); -// VALIDATION -// define parameter-parameter request untuk setiap end point -const validate = (method) => { - switch (method) { - case 'checkReservation': - return [ - body('mid').not().isEmpty().withMessage('MID is required'), - body('tid').not().isEmpty().withMessage('TID is required'), - body('card_number') - .not() - .isEmpty() - .withMessage('Card Number is required'), - ]; - case 'reservationValidate': - return [ - body('mid').not().isEmpty().withMessage('MID is required'), - body('tid').not().isEmpty().withMessage('TID is required'), - body('card_number') - .not() - .isEmpty() - .withMessage('Card Number is required'), - body('amount') - .not() - .isEmpty() - .withMessage('Amount is required') - .isNumeric() - .withMessage('Amount is invalid format'), - ]; - case 'reservation': - return [ - body('mid').not().isEmpty().withMessage('MID is required'), - body('tid').not().isEmpty().withMessage('TID is required'), - body('card_number') - .not() - .isEmpty() - .withMessage('Card Number is required'), - body('ref_no').not().isEmpty().withMessage('Ref No is required'), - body('amount') - .not() - .isEmpty() - .withMessage('Amount is required') - .isNumeric() - .withMessage('Amount is invalid format'), - ]; - case 'reservationV2': - return [ - body('reservation_data') - .not() - .isEmpty() - .withMessage('Reservation data is required'), - body('ref_no').not().isEmpty().withMessage('Ref No is required'), - ]; - case 'cancelReservation': - return [ - body('mid').not().isEmpty().withMessage('MID is required'), - body('tid').not().isEmpty().withMessage('TID is required'), - body('reservation_number') - .not() - .isEmpty() - .withMessage('Reservation Number is required'), - ]; - case 'cancelReservationValidateV2': - return [ - body('mid').not().isEmpty().withMessage('MID is required'), - body('tid').not().isEmpty().withMessage('TID is required'), - ]; - case 'cancelReservationV2': - return [ - body('cancel_reservation_data') - .not() - .isEmpty() - .withMessage('Cancel Reservation data is required'), - ]; - case 'getFeeSharing': - return [ - body('mid').not().isEmpty().withMessage('MID is required'), - body('tid').not().isEmpty().withMessage('TID is required'), - ]; - default: - break; - } -}; // ================================================================= CHECK RESERVATION ================================================================= // *Created By: Mohamad Ihsan* diff --git a/application/modules/reservebalance/reservebalance.validation.js b/application/modules/reservebalance/reservebalance.validation.js new file mode 100644 index 0000000..c0e0d99 --- /dev/null +++ b/application/modules/reservebalance/reservebalance.validation.js @@ -0,0 +1,86 @@ +const { body } = require('express-validator'); + +// Aturan input untuk setiap operasi. Urutan validasi mengikuti kontrak API. +const validate = (method) => { + switch (method) { + case 'checkReservation': + return [ + body('mid').not().isEmpty().withMessage('MID is required'), + body('tid').not().isEmpty().withMessage('TID is required'), + body('card_number') + .not() + .isEmpty() + .withMessage('Card Number is required'), + ]; + case 'reservationValidate': + return [ + body('mid').not().isEmpty().withMessage('MID is required'), + body('tid').not().isEmpty().withMessage('TID is required'), + body('card_number') + .not() + .isEmpty() + .withMessage('Card Number is required'), + body('amount') + .not() + .isEmpty() + .withMessage('Amount is required') + .isNumeric() + .withMessage('Amount is invalid format'), + ]; + case 'reservation': + return [ + body('mid').not().isEmpty().withMessage('MID is required'), + body('tid').not().isEmpty().withMessage('TID is required'), + body('card_number') + .not() + .isEmpty() + .withMessage('Card Number is required'), + body('ref_no').not().isEmpty().withMessage('Ref No is required'), + body('amount') + .not() + .isEmpty() + .withMessage('Amount is required') + .isNumeric() + .withMessage('Amount is invalid format'), + ]; + case 'reservationV2': + return [ + body('reservation_data') + .not() + .isEmpty() + .withMessage('Reservation data is required'), + body('ref_no').not().isEmpty().withMessage('Ref No is required'), + ]; + case 'cancelReservation': + return [ + body('mid').not().isEmpty().withMessage('MID is required'), + body('tid').not().isEmpty().withMessage('TID is required'), + body('reservation_number') + .not() + .isEmpty() + .withMessage('Reservation Number is required'), + ]; + case 'cancelReservationValidateV2': + return [ + body('mid').not().isEmpty().withMessage('MID is required'), + body('tid').not().isEmpty().withMessage('TID is required'), + ]; + case 'cancelReservationV2': + return [ + body('cancel_reservation_data') + .not() + .isEmpty() + .withMessage('Cancel Reservation data is required'), + ]; + case 'getFeeSharing': + return [ + body('mid').not().isEmpty().withMessage('MID is required'), + body('tid').not().isEmpty().withMessage('TID is required'), + ]; + default: + break; + } +}; + + +module.exports = validate; diff --git a/application/tests/cash-in-controller.test.js b/application/tests/cash-in-controller.test.js new file mode 100644 index 0000000..5a0afe2 --- /dev/null +++ b/application/tests/cash-in-controller.test.js @@ -0,0 +1,42 @@ +jest.mock('../helpers/helper', () => ({ + getUniqueCode: jest.fn(), + startScheduler: jest.fn(), + finishScheduler: jest.fn(), +})); +jest.mock('../helpers/winston.logger', () => ({ + logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() }, +})); +jest.mock('../modules/cashin/cash-in-generation.service', () => ({ + _generateCashIn: jest.fn(), +})); +jest.mock('../modules/cashin/cash-in-posting.service', () => jest.fn()); + +const helper = require('../helpers/helper'); +const { _generateCashIn } = require('../modules/cashin/cash-in-generation.service'); +const { apiGenerateCahsIn } = require('../modules/cashin/cahsin.controller'); + +test('permintaan Cash-in paralel mempertahankan kode dan hasil masing-masing', async () => { + let finishFirst; + helper.getUniqueCode.mockReturnValueOnce('job-a').mockReturnValueOnce('job-b'); + helper.startScheduler.mockResolvedValueOnce({ c_execution_token: 'a' }) + .mockResolvedValueOnce({ c_execution_token: 'b' }); + helper.finishScheduler.mockImplementation((token) => { + if (token === 'a') return new Promise((resolve) => { finishFirst = resolve; }); + }); + _generateCashIn.mockImplementation(async (id) => [id]); + + const firstResponse = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + const secondResponse = { status: jest.fn().mockReturnThis(), json: jest.fn() }; + const first = apiGenerateCahsIn({}, firstResponse); + await apiGenerateCahsIn({}, secondResponse); + expect(finishFirst).toBeDefined(); + finishFirst(); + await first; + + expect(firstResponse.json).toHaveBeenCalledWith({ + code: '200', message: 'Succes posting', data: ['job-a'], + }); + expect(secondResponse.json).toHaveBeenCalledWith({ + code: '200', message: 'Succes posting', data: ['job-b'], + }); +}); diff --git a/application/tests/paymentrecon-concurrency.test.js b/application/tests/paymentrecon-concurrency.test.js index e18e3b2..5616a32 100644 --- a/application/tests/paymentrecon-concurrency.test.js +++ b/application/tests/paymentrecon-concurrency.test.js @@ -61,3 +61,17 @@ test('a failed atomic commit returns an error instead of reporting reconciliatio expect(response.body.code).toBe('500'); expect(model.insertPaymentReconTransaction).not.toHaveBeenCalled(); }); + +test('konflik nomor rekonsiliasi berhenti setelah lima percobaan', async () => { + model.insertPaymentReconNumber.mockResolvedValue({ rowCount: 0 }); + + const response = await request(app).post('/api/payment-recon').send(body); + + expect(response.status).toBe(200); + expect(response.body).toMatchObject({ + code: '500', + message: 'server is busy. please try again.', + }); + expect(model.insertPaymentReconNumber).toHaveBeenCalledTimes(5); + expect(model.completePaymentRecon).not.toHaveBeenCalled(); +});