Files
Online-Topup-V1/application/modules/loadbalance/loadbalance.controller.js
T
2022-06-13 16:00:24 +07:00

1043 lines
28 KiB
JavaScript

const { param, body, validationResult } = require("express-validator");
const helper = require("../../helpers/helper");
const winston = require("../../helpers/winston.logger");
const model = require("./loadbalance.model");
const moment = require("moment");
moment.locale("id");
var result = {};
var uniqueCode;
// 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;
}
};
// LOADING BALANCE REQUEST
const loadingBalanceRequest = async (req, res) => {
try {
// generate unique code
uniqueCode = await helper.getUniqueCode();
// param
let { mid, tid, card_number, uid, balance, flag } = req.body;
// log info
winston.logger.info(
`${uniqueCode} REQUEST load balance validate: ${JSON.stringify(req.body)}`
);
// check validator
const err = validationResult(req, res);
if (!err.isEmpty()) {
result = {
code: "400",
message: err.errors[0].msg,
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
// time
let now = moment().format("YYYY-MM-DD HH:mm:ss");
let year = moment().format("Y");
let month = moment().format("M");
// log debug
winston.logger.debug(`${uniqueCode} checking partner...`);
// get partner, merchant, terminal from tid
let getPartner = await model.getPartner(mid, tid);
if (!getPartner) {
result = {
code: "412",
message: "terminal id is not valid",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
// log debug
winston.logger.debug(`${uniqueCode} checking card number...`);
// check card number
let checkCardNumber = await model.checkCardNumber(card_number);
if (!checkCardNumber) {
result = {
code: "413",
message: "card number is not registered",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
// log debug
winston.logger.debug(
`${uniqueCode} checking flag on the card and the server...`
);
// check last flag
let checkFlag = await model.checkFlag(card_number, uid.toUpperCase());
let lastFlag = null;
if (checkFlag) {
lastFlag = checkFlag.c_flag;
}
// log debug
winston.logger.debug(
`${uniqueCode} checking reservation pending with flag...`
);
// get total reservation pending
let getReservationPendingWithFlag =
await model.getReservationPendingWithFlag(card_number, now);
if (getReservationPendingWithFlag.length > 0) {
if (lastFlag && lastFlag != flag) {
let reservationNumberPendingWithflag = [];
getReservationPendingWithFlag.forEach((element) => {
reservationNumberPendingWithflag.push(element.c_reservation_no);
});
// log debug
winston.logger.debug(
`${uniqueCode} updating reservation and load balance transaction...`
);
// update
let insertUpdate = await updateReservationAndLoadingBalance(
reservationNumberPendingWithflag,
mid,
tid,
balance,
uniqueCode
);
if (insertUpdate) {
// log debug
winston.logger.debug(`${uniqueCode} updating flag to server...`);
// update flag from Server
await model.updateFlag(
now,
card_number,
uid.toUpperCase(),
balance,
flag
);
result = {
code: "01",
message: "your card number has been cleared successfully",
data: {},
};
} else {
result = {
code: "423",
message: "updated failed",
data: {},
};
}
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
}
// log debug
winston.logger.debug(`${uniqueCode} updating flag to server...`);
// update flag from Server
await model.updateFlag(now, card_number, uid.toUpperCase(), balance, flag);
// log debug
winston.logger.debug(`${uniqueCode} checking reservation pending...`);
// get total reservation pending
let getReservationPending = await model.getReservationPending(
card_number,
now
);
if (getReservationPending.length < 1) {
result = {
code: "414",
message: "reservation doesn't exist",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
let totalReservation = 0;
let amountTopup = 0;
let reservationNumber = [];
let reservationNumberTemp = [];
let i = 0;
getReservationPending.forEach((rsv) => {
if (rsv.c_flag) {
if (lastFlag == flag) {
amountTopup += parseInt(rsv.i_reservation_amount);
reservationNumber.push(rsv.c_reservation_no);
i++;
}
} else {
amountTopup += parseInt(rsv.i_reservation_amount);
reservationNumber.push(rsv.c_reservation_no);
i++;
}
reservationNumberTemp.push(rsv.c_reservation_no);
});
// log debug
winston.logger.debug(
`${uniqueCode} updating status reservation to in progress...`
);
// update status to in progress
await model.updateStatusReservation(reservationNumberTemp, now);
totalReservation = i;
if (totalReservation == 0) {
result = {
code: "414",
message: "reservation doesn't exist",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
// log debug
winston.logger.debug(`${uniqueCode} checking total topup amount...`);
// check total amount topup
if (parseInt(amountTopup) <= 0) {
result = {
code: "415",
message: "amount must be greater than 0",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
// log debug
winston.logger.debug(`${uniqueCode} checking BI regulation status...`);
// get BI regulation status
const getBIRegulationStatus = await model.getBIRegulationStatus();
if (getBIRegulationStatus.c_value == "A") {
// log debug
winston.logger.debug(`${uniqueCode} checking max balance on the card...`);
// get max saldo on the card
const getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
if (getMaxAmountOnTheCard.c_value) {
if (
parseInt(balance) + parseInt(amountTopup) >
parseInt(getMaxAmountOnTheCard.c_value)
) {
result = {
code: "416",
message: "your card number has reached the maximum balance",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
}
// log debug
winston.logger.debug(`${uniqueCode} checking max topup per month...`);
// get accumulated balance in this month
let accumulatedBalance = 0;
let getAccumulationBalanceInThisMonthFromCardHistory =
await model.getAccumulationBalanceInThisMonthFromCardHistory(
card_number,
year,
month
);
if (getAccumulationBalanceInThisMonthFromCardHistory) {
accumulatedBalance =
getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance;
}
// validate max topup per month
const getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
if (getMaxTopupPerMonth.c_value) {
if (
parseInt(accumulatedBalance) + parseInt(amountTopup) >
parseInt(getMaxTopupPerMonth.c_value)
) {
result = {
code: "417",
message: "your card number has been limit top up for this month",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
}
}
result = {
code: "00",
message: "reservation exists",
data: {
amount: amountTopup,
total_reservation: totalReservation,
reservation_number: reservationNumber,
unique_code: uniqueCode,
},
};
// log info
winston.logger.info(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(result)}`
);
return res.json(result);
} catch (error) {
// create log
winston.logger.error(
`500 internal server error - backend server | ${error.message}`
);
return res.status(200).json({
code: "500",
message:
process.env.NODE_ENV != "production"
? error.message
: "500 internal server error - backend server.",
data: {},
});
}
};
// LOAD BALANCE
const loadingBalance = async (req, res) => {
try {
// param
let {
mid,
tid,
card_number,
amount,
reservation_number,
ref_no,
write_status,
uid,
balance,
flag,
unique_code,
} = req.body;
uniqueCode = unique_code ? unique_code : 9999999999999;
// log info
winston.logger.info(
`${uniqueCode} REQUEST load balance insert: ${JSON.stringify(req.body)}`
);
// check validator
const err = validationResult(req, res);
if (!err.isEmpty()) {
result = {
code: "400",
message: err.errors[0].msg,
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}`
);
return res.status(200).json(result);
}
// time
let now = moment().format("YYYY-MM-DD HH:mm:ss");
let today = moment().format("YYYY-MM-DD");
// log debug
winston.logger.debug(`${uniqueCode} checking partner...`);
// get partner, merchant, terminal from tid
let getPartner = await model.getPartner(mid, tid);
if (!getPartner) {
result = {
code: "412",
message: "terminal id is not valid",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
// log debug
winston.logger.debug(`${uniqueCode} checking reservation status...`);
// check reservation status
for (let index = 0; index < reservation_number.length; index++) {
let reservationStatus = await model.findReservation(
reservation_number[index]
);
if (!reservationStatus) {
result = {
code: "414",
message: "reservation doesn't exist",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
if (reservationStatus.c_status == "A") {
var reservationLoaded = await model.findReservationLoaded(
reservationStatus.i_reservation_balance
);
let loadBalanceNumberExisting = reservationLoaded.c_load_balance_no;
let loadDate = reservationLoaded.d_load_balance;
result = {
code: "00",
message:
"reservation has been successfully loaded on " +
moment(loadDate).format("DD MMM YYYY HH:mm:ss"),
data: {
load_balance_number: loadBalanceNumberExisting,
},
};
// log info
winston.logger.info(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
}
// log debug
winston.logger.debug(`${uniqueCode} checking reservation pending...`);
// get total reservation pending
let getReservationPending = await model.getReservationPending(
card_number,
now
);
if (getReservationPending.length < 1) {
result = {
code: "414",
message: "reservation doesn't exist",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
// log debug
winston.logger.debug(`${uniqueCode} checking total topup amount...`);
// check total topup and request topup
let amountTopup = 0;
getReservationPending.forEach((rsv) => {
amountTopup += parseInt(rsv.i_reservation_amount);
});
if (amount != amountTopup) {
result = {
code: "418",
message: "topup amount is different",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
// log debug
winston.logger.debug(`${uniqueCode} getting loading balance sequence...`);
// get loading balance
const getLoadBalanceSequence = await model.getLoadBalanceSequence(
getPartner,
today
);
const loadBalanceNoSequence = getLoadBalanceSequence
? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1
: 1;
// log debug
winston.logger.debug(`${uniqueCode} generating load balance number...`);
// generate load balance number
let loadBalanceNumber = await model.generateLoadBalanceNumber(
getPartner,
moment(today).format("YYYYMMDD"),
loadBalanceNoSequence
);
let data = {
c_load_balance_no: loadBalanceNumber,
d_load_balance: now,
c_ref_no: ref_no,
i_partner: getPartner ? getPartner.i_partner : null,
c_partner_code: getPartner ? getPartner.partner_code : null,
c_partner_name: getPartner ? getPartner.partner_name : null,
i_merchant: getPartner ? getPartner.i_merchant : null,
c_merchant_code: getPartner ? getPartner.merchant_code : null,
c_merchant_name: getPartner ? getPartner.merchant_name : null,
c_mid: getPartner ? getPartner.mid : null,
i_terminal: getPartner ? getPartner.i_terminal : null,
c_terminal_code: getPartner ? getPartner.terminal_code : null,
c_terminal_name: getPartner ? getPartner.terminal_name : null,
c_tid: getPartner ? getPartner.tid : null,
c_card_number: card_number,
i_topup_amount: amount,
m_balance: balance,
c_return_sap: null,
i_load_balance_no_seq: loadBalanceNoSequence,
c_idm: uid,
c_status: write_status ? "F" : "A",
c_status_name: write_status ? "FAILED" : "SUCCESS",
d_create: now,
i_create: null,
c_create_username: null,
c_create_fullname: null,
d_modify: null,
i_modify: null,
c_modify_username: null,
c_modify_fullname: null,
d_delete: null,
i_delete: null,
c_delete_username: null,
c_delete_fullname: null,
};
// log debug
winston.logger.debug(`${uniqueCode} getting reservation detail...`);
let detail = [];
for (let index = 0; index < reservation_number.length; index++) {
let reservation = await model.findReservation(reservation_number[index]);
if (!reservation) {
result = {
code: "414",
message: "reservation doesn't exist",
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(
result
)}`
);
return res.status(200).json(result);
}
detail.push({
i_reservation_balance: reservation.i_reservation_balance
? reservation.i_reservation_balance
: null,
c_reservation_no: reservation.i_reservation_balance
? reservation.c_reservation_no
: null,
i_amount: reservation.i_reservation_balance
? reservation.i_reservation_amount
: null,
i_issuer: reservation.i_reservation_balance
? reservation.i_issuer
: null,
i_issuer_code: reservation.i_reservation_balance
? reservation.c_issuer_code
: null,
i_issuer_name: reservation.i_reservation_balance
? reservation.c_issuer_name
: null,
i_issuer_fee: reservation.i_reservation_balance
? reservation.i_issuer_fee
: null,
i_channel: reservation.i_reservation_balance
? reservation.i_channel
: null,
i_channel_code: reservation.i_reservation_balance
? reservation.c_channel_code
: null,
i_channel_name: reservation.i_reservation_balance
? reservation.c_channel_name
: null,
i_channel_fee: reservation.i_reservation_balance
? reservation.i_channel_fee
: null,
});
}
// log debug
winston.logger.debug(`${uniqueCode} inserting load balance transaction...`);
// insert transaction
await model.insertLoadingBalance(
data,
detail,
reservation_number,
now,
write_status,
card_number,
uid.toUpperCase(),
balance,
flag
);
if (!write_status) {
// log debug
winston.logger.debug(`${uniqueCode} inserting log for card history...`);
// log card history
await model.createLoadBalanceLog({
i_log_name: 89,
d_log: now,
c_card_number: card_number,
c_source: "CMS - HSM",
c_location: null,
m_balance_before: balance - amount > 0 ? balance - amount : 0,
m_amount: amount,
m_balance_after: balance,
j_new_data: { data: data, detail: detail },
j_old_data: null,
c_note: "SUCCESSFULLY LOADED",
c_status: "S",
d_created: now,
i_create: null,
c_create_username: "HSM",
c_create_fullname: "HARDWARE SECURE MODULE",
c_category: null,
});
}
result = {
code: "00",
message: write_status
? "transaction saved successfully. Err: failed write to the card"
: "balance loaded successfully",
data: {
load_balance_number: loadBalanceNumber,
},
};
// log info
winston.logger.info(
`${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}`
);
return res.status(200).json(result);
} catch (error) {
// create log
winston.logger.error(
`500 internal server error - backend server | ${error.message}`
);
return res.status(200).json({
code: "500",
message:
process.env.NODE_ENV != "production"
? error.message
: "500 internal server error - backend server.",
data: {},
});
}
};
// INQUIRY LOADING BALANCE
const inquiryLoadingBalance = async (req, res) => {
try {
// param
let { load_balance_number, card_number, start_date, end_date } = req.body;
// time
let now = moment().format("YYYY-MM-DD HH:mm:ss");
// validation parameter inquiry
if (!load_balance_number && !card_number) {
return res.status(200).json({
code: "400",
message:
"bad request. please add the load balance number or card number!",
data: {},
});
}
// validation inquiry date
if ((!start_date && end_date) || (start_date && !end_date)) {
return res.status(200).json({
code: "400",
message: "bad request. please check the date!",
data: {},
});
}
// check load balance
if (load_balance_number) {
let byLoadBalanceNumber = await model.inquiryByLoadBalanceNumber(
load_balance_number
);
if (!byLoadBalanceNumber) {
return res.status(200).json({
code: "419",
message: "load balance doesn't exist",
data: [],
});
}
return res.json({
code: "00",
message: "load balance has been found.",
data: byLoadBalanceNumber,
});
} else if (card_number) {
let byCardNumber = await model.inquiryByCardNumber(
card_number,
start_date,
end_date
);
if (!byCardNumber) {
return res.status(200).json({
code: "419",
message: "load balance doesn't exist",
data: {},
});
}
return res.json({
code: "00",
message: "load balance has been found.",
data: byCardNumber,
});
}
} catch (error) {
return res.status(200).json({
code: "500",
message:
process.env.NODE_ENV != "production"
? error.message
: "500 internal server error - backend server.",
data: {},
});
}
};
const updateReservationAndLoadingBalance = async (
reservationNumber,
mid,
tid,
balance,
uniqueCode
) => {
try {
// log debug
winston.logger.debug(`${uniqueCode} getting last reservation with flag...`);
// get reservation
let dataReservation = [];
let getLastReservationFlag = await model.getLastReservationFlag(
reservationNumber
);
if (getLastReservationFlag) {
dataReservation = getLastReservationFlag;
}
// log debug
winston.logger.debug(
`${uniqueCode} getting last load balance transaction...`
);
// get load balance
let dataLoadingBalance = [];
let getLastLoadingBalanceFlag = await model.getLastLoadingBalanceFlag(
reservationNumber
);
if (getLastLoadingBalanceFlag) {
dataLoadingBalance = getLastLoadingBalanceFlag;
}
// get detail load balance
let dataLoadingBalanceDetail = [];
if (dataLoadingBalance) {
// log debug
winston.logger.debug(
`${uniqueCode} getting last load balance detail transaction...`
);
let getLastLoadingBalanceDetailFlag =
await model.getLastLoadingBalanceDetailFlag(
dataLoadingBalance.i_load_balance
);
if (getLastLoadingBalanceDetailFlag) {
dataLoadingBalanceDetail = getLastLoadingBalanceDetailFlag;
}
}
if (
dataReservation &&
dataLoadingBalance &&
dataLoadingBalanceDetail.length > 0
) {
// time
let now = moment().format("YYYY-MM-DD HH:mm:ss");
let today = moment().format("YYYY-MM-DD");
let getPartner = await model.getPartner(mid, tid);
// log debug
winston.logger.debug(`${uniqueCode} getting loading balance sequence...`);
// get loading balance
const getLoadBalanceSequence = await model.getLoadBalanceSequence(
getPartner,
today
);
const loadBalanceNoSequence = getLoadBalanceSequence
? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1
: 1;
// log debug
winston.logger.debug(`${uniqueCode} generating load balance number...`);
// generate load balance number
let loadBalanceNumber = await model.generateLoadBalanceNumber(
getPartner,
moment(today).format("YYYYMMDD"),
loadBalanceNoSequence
);
let data = {
c_load_balance_no: loadBalanceNumber,
d_load_balance: now,
c_ref_no: dataReservation.c_ref_no,
i_partner: getPartner ? getPartner.i_partner : null,
c_partner_code: getPartner ? getPartner.partner_code : null,
c_partner_name: getPartner ? getPartner.partner_name : null,
i_merchant: getPartner ? getPartner.i_merchant : null,
c_merchant_code: getPartner ? getPartner.merchant_code : null,
c_merchant_name: getPartner ? getPartner.merchant_name : null,
c_mid: getPartner ? getPartner.mid : null,
i_terminal: getPartner ? getPartner.i_terminal : null,
c_terminal_code: getPartner ? getPartner.terminal_code : null,
c_terminal_name: getPartner ? getPartner.terminal_name : null,
c_tid: getPartner ? getPartner.tid : null,
c_card_number: dataReservation.c_card_number,
i_topup_amount: dataLoadingBalance.i_topup_amount,
m_balance: dataLoadingBalance.m_balance,
c_return_sap: null,
i_load_balance_no_seq: loadBalanceNoSequence,
c_status: "A",
c_status_name: "SUCCESS",
d_create: now,
i_create: null,
c_create_username: null,
c_create_fullname: null,
d_modify: null,
i_modify: null,
c_modify_username: null,
c_modify_fullname: null,
d_delete: null,
i_delete: null,
c_delete_username: null,
c_delete_fullname: null,
};
// log debug
winston.logger.debug(
`${uniqueCode} updating reservation and inserting load balance transaction...`
);
// insert reservation and load balance transaction
await model.insertReservationAndLoadingBalance(
reservationNumber,
data,
dataLoadingBalanceDetail,
now
);
// log debug
winston.logger.debug(`${uniqueCode} inserting log for card history...`);
// log card history
await model.createLoadBalanceLog({
i_log_name: 89,
d_log: now,
c_card_number: dataReservation.c_card_number,
c_source: "CMS - HSM",
c_location: null,
m_balance_before: dataLoadingBalance.m_balance,
m_amount: dataLoadingBalance.i_topup_amount,
m_balance_after: balance,
j_new_data: { data: data, detail: dataLoadingBalanceDetail },
j_old_data: null,
c_note: "SUCCESSFULLY LOADED",
c_status: "S",
d_created: now,
i_create: null,
c_create_username: "HSM",
c_create_fullname: "HARDWARE SECURE MODULE",
c_category: null,
});
return true;
} else {
return false;
}
} catch (error) {
// create log
winston.logger.error(
`500 internal server error - backend server | ${error.message}`
);
return false;
}
};
module.exports = {
validate,
loadingBalanceRequest,
loadingBalance,
inquiryLoadingBalance,
};