From d94ff1fc0309f79ec7f8015e0aa38d4c954dca7c Mon Sep 17 00:00:00 2001 From: Mohamad Ihsan Date: Wed, 8 Jun 2022 18:34:55 +0700 Subject: [PATCH] update --- application/helpers/helper.js | 40 +- application/helpers/winston.logger.js | 37 +- application/modules/auth/auth.controller.js | 10 + .../modules/history/history.controller.js | 4 + .../loadbalance/loadbalance.controller.js | 421 ++++++++++++++++-- .../reservebalance.controller.js | 7 + index.js | 14 +- 7 files changed, 471 insertions(+), 62 deletions(-) diff --git a/application/helpers/helper.js b/application/helpers/helper.js index 6d29b39..f3aa03a 100644 --- a/application/helpers/helper.js +++ b/application/helpers/helper.js @@ -1,24 +1,34 @@ -const CryptoJS = require('crypto-js'); +const CryptoJS = require("crypto-js"); // ENCRYPT TEXT const encryptText = (text) => { - try { - return CryptoJS.AES.encrypt(text, process.env.SECRET_KEY).toString() - } catch (error) { - return error.message; - } -} + try { + return CryptoJS.AES.encrypt(text, process.env.SECRET_KEY).toString(); + } catch (error) { + return error.message; + } +}; // DECRYPT TEXT const decryptText = (cipherText) => { - try { - return CryptoJS.AES.decrypt(cipherText, process.env.SECRET_KEY).toString(CryptoJS.enc.Utf8) - } catch (error) { - return error.message; - } + try { + return CryptoJS.AES.decrypt(cipherText, process.env.SECRET_KEY).toString( + CryptoJS.enc.Utf8 + ); + } catch (error) { + return error.message; + } +}; + +// RANDOM UNIQUE CODE +function getUniqueCode() { + const maxDate = Date.now(); + const timestamp = Math.floor(Math.random() * maxDate).toString(); + return timestamp; } module.exports = { - encryptText, - decryptText, -} \ No newline at end of file + encryptText, + decryptText, + getUniqueCode, +}; diff --git a/application/helpers/winston.logger.js b/application/helpers/winston.logger.js index 8c19ca1..9fd80d0 100644 --- a/application/helpers/winston.logger.js +++ b/application/helpers/winston.logger.js @@ -1,17 +1,46 @@ const winston = require("winston"); const { combine, timestamp, printf, colorize, align, json } = winston.format; +const logLevels = { + fatal: 0, + error: 1, + warn: 2, + info: 3, + debug: 4, + trace: 5, +}; + const logger = winston.createLogger({ - level: process.env.LOG_LEVEL || 'info', - format: combine(timestamp(), json()), + levels: logLevels, + level: process.env.LOG_LEVEL || "info", + // format: combine(timestamp(), json()), + format: combine( + // colorize({ all: true }), + timestamp({ + format: "YYYY-MM-DD HH:mm:ss.SSS", + }), + align(), + printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`) + ), defaultMeta: { service: "topuponline-service" }, transports: [ // // - Write all logs with importance level of `error` or less to `error.log` // - Write all logs with importance level of `info` or less to `combined.log` // - // new winston.transports.File({ filename: "error.log", level: "error" }), - // new winston.transports.File({ filename: "combined.log" }), + new winston.transports.File({ + filename: "application/logs/error.log", + level: "error", + }), + new winston.transports.File({ + filename: "application/logs/debug.log", + level: "debug", + }), + new winston.transports.File({ + filename: "application/logs/trace.log", + level: "info", + }), + new winston.transports.File({ filename: "application/logs/combined.log" }), ], }); diff --git a/application/modules/auth/auth.controller.js b/application/modules/auth/auth.controller.js index 6303ce0..604f137 100644 --- a/application/modules/auth/auth.controller.js +++ b/application/modules/auth/auth.controller.js @@ -2,6 +2,7 @@ const knex = require("../../../infrastructure/database/knex"); const jwt = require("../../middlewares/jwt.middleware"); 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 moment = require("moment"); @@ -110,6 +111,9 @@ const login = async (req, res, next) => { }, }); } catch (error) { + // create log + winston.logger.error(`${error.message}`); + return res.status(200).json({ code: "500", message: @@ -184,6 +188,9 @@ const register = async (req, res) => { data: result.command, }); } catch (error) { + // create log + winston.logger.error(`${error.message}`); + return res.status(200).json({ code: "500", message: @@ -251,6 +258,9 @@ const refreshToken = async (req, res) => { }, }); } catch (error) { + // create log + winston.logger.error(`${error.message}`); + return res.status(200).json({ code: "500", message: diff --git a/application/modules/history/history.controller.js b/application/modules/history/history.controller.js index ef0348a..9ae81ac 100644 --- a/application/modules/history/history.controller.js +++ b/application/modules/history/history.controller.js @@ -1,4 +1,5 @@ const { param, body, validationResult } = require("express-validator"); +const winston = require("../../helpers/winston.logger"); const model = require("./history.model"); const moment = require("moment"); moment.locale("id"); @@ -82,6 +83,9 @@ const history = async (req, res) => { data: result, }); } catch (error) { + // create log + winston.logger.error(`${error.message}`); + return res.status(200).json({ code: "500", message: diff --git a/application/modules/loadbalance/loadbalance.controller.js b/application/modules/loadbalance/loadbalance.controller.js index 4de3b7c..7ff70da 100644 --- a/application/modules/loadbalance/loadbalance.controller.js +++ b/application/modules/loadbalance/loadbalance.controller.js @@ -1,4 +1,6 @@ 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"); @@ -58,32 +60,87 @@ const loadingBalanceRequest = async (req, res) => { }); } + let result = {}; + + // generate unique code + let uniqueCode = await helper.getUniqueCode(); + // param let { mid, tid, card_number, uid, balance, flag } = req.body; + // log debug + winston.logger.debug( + `${uniqueCode} request load balance validate: ${JSON.stringify(req.body)}` + ); + // log info + winston.logger.info( + `${uniqueCode} request load balance validate: ${JSON.stringify(req.body)}` + ); + // time let now = moment().format("YYYY-MM-DD HH:mm:ss"); + // log debug + winston.logger.debug(`${uniqueCode} checking partner...`); + // get partner, merchant, terminal from tid let getPartner = await model.getPartner(mid, tid); if (!getPartner) { - return res.status(200).json({ + result = { code: "403", message: "terminal id is not valid", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // 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 card number...`); + // check card number let checkCardNumber = await model.checkCardNumber(card_number); if (!checkCardNumber) { - return res.status(200).json({ + result = { code: "403", message: "card number is not registered", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // 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 flag on the card and the server...` + ); + // check last flag let checkFlag = await model.checkFlag(card_number, uid.toUpperCase()); let lastFlag = null; @@ -91,28 +148,59 @@ const loadingBalanceRequest = async (req, res) => { 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) { + // log debug + winston.logger.debug( + `updating reservation and load balance transaction...` + ); + // update await updateReservationAndLoadingBalance( getReservationPendingWithFlag, mid, tid ); - return res.status(200).json({ + + result = { code: "01", message: "your card number has been cleared successfully", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // 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} 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, @@ -120,11 +208,26 @@ const loadingBalanceRequest = async (req, res) => { ); if (getReservationPending.length < 1) { - return res.status(200).json({ + result = { code: "403", message: "reservation doesn't exist", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // log info + winston.logger.info( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } let totalReservation = 0; @@ -147,30 +250,74 @@ const loadingBalanceRequest = async (req, res) => { 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) { - return res.status(200).json({ + result = { code: "403", message: "reservation doesn't exist", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // 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 total topup amount...`); + // check total amount topup if (parseInt(amountTopup) <= 0) { - return res.status(200).json({ + result = { code: "403", message: "can't topup with amount = 0", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // 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 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) { @@ -178,14 +325,32 @@ const loadingBalanceRequest = async (req, res) => { parseInt(balance) + parseInt(amountTopup) > parseInt(getMaxAmountOnTheCard.c_value) ) { - return res.status(200).json({ + result = { code: "403", message: "your card number has reached the maximum balance", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // 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 max topup per month...`); + // get accumulated balance in this month let accumulatedBalance = 19900000; @@ -196,27 +361,57 @@ const loadingBalanceRequest = async (req, res) => { parseInt(accumulatedBalance) + parseInt(amountTopup) > parseInt(getMaxTopupPerMonth.c_value) ) { - return res.status(200).json({ + result = { code: "403", message: "your card number has been limit top up for this month", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // log info + winston.logger.info( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } } } - let result = { - amount: amountTopup, - total_reservation: totalReservation, - reservation_number: reservationNumber, - }; - - return res.json({ + result = { code: "00", message: "reservation exists", - data: result, - }); + data: { + amount: amountTopup, + total_reservation: totalReservation, + reservation_number: reservationNumber, + unique_code: uniqueCode, + }, + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify(result)}` + ); + // 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: @@ -253,22 +448,56 @@ const loadingBalance = async (req, res) => { uid, balance, flag, + unique_code, } = req.body; + let result = {}; + + let uniqueCode = unique_code ? unique_code : 9999999999999; + // log debug + winston.logger.debug( + `${uniqueCode} request load balance insert: ${JSON.stringify(req.body)}` + ); + // log info + winston.logger.info( + `${uniqueCode} request load balance insert: ${JSON.stringify(req.body)}` + ); + // 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) { - return res.status(200).json({ + result = { code: "403", message: "terminal id is not valid", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // 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 status...`); + // check reservation status for (let index = 0; index < reservation_number.length; index++) { let reservationStatus = await model.findReservation( @@ -276,11 +505,26 @@ const loadingBalance = async (req, res) => { ); if (!reservationStatus) { - return res.status(200).json({ + result = { code: "403", message: "reservation number doesn't exist", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // log info + winston.logger.info( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } if (reservationStatus.c_status == "A") { @@ -289,7 +533,7 @@ const loadingBalance = async (req, res) => { ); let loadBalanceNumberExisting = reservationLoaded.c_load_balance_no; let loadDate = reservationLoaded.d_load_balance; - return res.status(200).json({ + result = { code: "00", message: "reservation has been successfully loaded on " + @@ -297,10 +541,28 @@ const loadingBalance = async (req, res) => { data: { load_balance_number: loadBalanceNumberExisting, }, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // 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, @@ -308,13 +570,31 @@ const loadingBalance = async (req, res) => { ); if (getReservationPending.length < 1) { - return res.status(200).json({ + result = { code: "403", message: "reservation doesn't exist", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // 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 total topup amount...`); + // check total topup and request topup let amountTopup = 0; getReservationPending.forEach((rsv) => { @@ -322,13 +602,31 @@ const loadingBalance = async (req, res) => { }); if (amount != amountTopup) { - return res.status(200).json({ + result = { code: "403", message: "topup amount is different", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // 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 loading balance sequence...`); + // get loading balance const getLoadBalanceSequence = await model.getLoadBalanceSequence( getPartner, @@ -338,6 +636,9 @@ const loadingBalance = async (req, res) => { ? 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, @@ -381,16 +682,34 @@ const loadingBalance = async (req, res) => { 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) { - return res.status(200).json({ + result = { code: "403", message: "reservation number doesn't exist", data: {}, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + // log info + winston.logger.info( + `${uniqueCode} response load balance validate: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } detail.push({ i_reservation_balance: reservation.i_reservation_balance @@ -429,6 +748,9 @@ const loadingBalance = async (req, res) => { }); } + // log debug + winston.logger.debug(`${uniqueCode} inserting load balance transaction...`); + await model.insertLoadingBalance( data, detail, @@ -441,7 +763,7 @@ const loadingBalance = async (req, res) => { flag ); - return res.status(200).json({ + result = { code: "00", message: write_status ? "transaction saved successfully. Err: failed write to the card" @@ -449,8 +771,24 @@ const loadingBalance = async (req, res) => { data: { load_balance_number: loadBalanceNumber, }, - }); + }; + + // log debug + winston.logger.debug( + `${uniqueCode} response load balance insert: ${JSON.stringify(result)}` + ); + // 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: @@ -531,6 +869,11 @@ const inquiryLoadingBalance = async (req, res) => { }); } } catch (error) { + // create log + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); + return res.status(200).json({ code: "500", message: diff --git a/application/modules/reservebalance/reservebalance.controller.js b/application/modules/reservebalance/reservebalance.controller.js index 4fb7ae7..b360c61 100644 --- a/application/modules/reservebalance/reservebalance.controller.js +++ b/application/modules/reservebalance/reservebalance.controller.js @@ -1,4 +1,5 @@ const { param, body, validationResult } = require("express-validator"); +const winston = require("../../helpers/winston.logger"); const model = require("./reservebalance.model"); const moment = require("moment"); moment.locale("id"); @@ -260,6 +261,9 @@ const reservation = async (req, res) => { }, }); } catch (error) { + // create log + winston.logger.error(`${error.message}`); + return res.status(200).json({ code: "500", message: @@ -340,6 +344,9 @@ const inquiryReservation = async (req, res) => { }); } } catch (error) { + // create log + winston.logger.error(`${error.message}`); + return res.status(200).json({ code: "500", message: diff --git a/index.js b/index.js index 55d68a9..efd91f6 100644 --- a/index.js +++ b/index.js @@ -6,8 +6,8 @@ const winston = require("./application/helpers/winston.logger"); const authRoute = require("./application/routes/auth.routes"); const reservationRoute = require("./application/routes/reservebalance.routes"); const loadBalanceRoute = require("./application/routes/loadbalance.routes"); -const hsmRoute = require("./application/routes/hsm.routes") -const historyRoute = require("./application/routes/history.routes") +const hsmRoute = require("./application/routes/hsm.routes"); +const historyRoute = require("./application/routes/history.routes"); require("dotenv").config(); @@ -27,7 +27,13 @@ app.use(bodyParser.urlencoded({ extended: true })); // ============================== ROUTES API ============================== app.get("/", (req, res) => { - res.json({ message: "Welcome to Topup Online Service.", data: { text: "0nlinet0pupkci", chiper_text: helper.encryptText('0nlinet0pupkci') } }); + res.json({ + message: "Welcome to Topup Online Service.", + data: { + text: "0nlinet0pupkci", + chiper_text: helper.encryptText("0nlinet0pupkci"), + }, + }); }); app.use("/api/", authRoute); @@ -39,5 +45,5 @@ app.use("/api/", reservationRoute); // set port, listen for requests const PORT = process.env.PORT || 8000; app.listen(PORT, () => { - winston.logger.info(`Server is running on port ${PORT}`) + winston.logger.info(`Server is running`); });