From 585e53917e0b700619d796872caf700f80814b3a Mon Sep 17 00:00:00 2001 From: Mohamad Ihsan Date: Thu, 9 Jun 2022 11:58:28 +0700 Subject: [PATCH] update --- ...e727b13210eef32232709400762e5fb-audit.json | 15 + application/helpers/winston.logger.js | 109 ++++--- application/modules/auth/auth.controller.js | 227 ++++++++++++-- .../loadbalance/loadbalance.controller.js | 288 +++++++----------- .../reservebalance.controller.js | 214 ++++++++++--- docs/error_code | 0 6 files changed, 563 insertions(+), 290 deletions(-) create mode 100644 .71c131f2ce727b13210eef32232709400762e5fb-audit.json create mode 100644 docs/error_code diff --git a/.71c131f2ce727b13210eef32232709400762e5fb-audit.json b/.71c131f2ce727b13210eef32232709400762e5fb-audit.json new file mode 100644 index 0000000..37ab6f0 --- /dev/null +++ b/.71c131f2ce727b13210eef32232709400762e5fb-audit.json @@ -0,0 +1,15 @@ +{ + "keep": { + "days": true, + "amount": 1 + }, + "auditLog": ".71c131f2ce727b13210eef32232709400762e5fb-audit.json", + "files": [ + { + "date": 1654709500492, + "name": "2022-06-09-onlinetopup.log", + "hash": "993e2e8dc6db8ef8e4dab349e223ddd177dbaa784b0545cd1171cae495d250ae" + } + ], + "hashType": "sha256" +} \ No newline at end of file diff --git a/application/helpers/winston.logger.js b/application/helpers/winston.logger.js index 9fd80d0..38f5f3e 100644 --- a/application/helpers/winston.logger.js +++ b/application/helpers/winston.logger.js @@ -1,4 +1,6 @@ +const moment = require("moment"); const winston = require("winston"); +require('winston-daily-rotate-file'); const { combine, timestamp, printf, colorize, align, json } = winston.format; const logLevels = { @@ -9,40 +11,7 @@ const logLevels = { debug: 4, trace: 5, }; - -const logger = winston.createLogger({ - 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: "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" }), - ], -}); +let logger; // // Replaces the previous transports with those in the @@ -54,11 +23,81 @@ const logger = winston.createLogger({ // transports: [new DailyRotateFile()], // }); +const fileRotateTransport = new winston.transports.DailyRotateFile({ + filename: "%DATE%-onlinetopup.log", + datePattern: "YYYY-MM-DD", + maxFiles: "1d", +}); + // // If we're not in production then log to the `console` with the format: // `${info.level}: ${info.message} JSON.stringify({ ...rest }) ` // -if (process.env.NODE_ENV != "production") { +if (process.env.NODE_ENV == "production") { + let logger = winston.createLogger({ + levels: logLevels, + level: process.env.LOG_LEVEL || "info", + exitOnError: false, + // 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: [ + fileRotateTransport, + // + // - Write all logs with importance level of `error` or less to `error.log` + // - Write all logs with importance level of `info` or less to `onlinetopup.log` + // + new winston.transports.File({ + filename: `application/logs/error.log`, + level: "error", + }), + new winston.transports.File({ + filename: `application/logs/${moment().format("YYYY-MM-DD")}-onlinetopup.log`, + }), + ], + }); +} else { + logger = winston.createLogger({ + levels: logLevels, + level: process.env.LOG_LEVEL || "info", + exitOnError: false, + // 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: [ + fileRotateTransport, + // + // - Write all logs with importance level of `error` or less to `error.log` + // - Write all logs with importance level of `info` or less to `onlinetopup.log` + // + new winston.transports.File({ + filename: `application/logs/error.log`, + level: "error", + }), + new winston.transports.File({ + filename: `application/logs/debug/${moment().format("YYYY-MM-DD")}.log`, + level: "debug", + }), + new winston.transports.File({ + filename: `application/logs/${moment().format("YYYY-MM-DD")}-onlinetopup.log`, + }), + ], + }); + logger.add( new winston.transports.Console({ // format: winston.format.cli(), diff --git a/application/modules/auth/auth.controller.js b/application/modules/auth/auth.controller.js index 604f137..08efc31 100644 --- a/application/modules/auth/auth.controller.js +++ b/application/modules/auth/auth.controller.js @@ -8,6 +8,9 @@ const { body, validationResult } = require("express-validator"); const moment = require("moment"); moment.locale("id"); +var result = {}; +var uniqueCode; + // VALIDATION const validate = (method) => { switch (method) { @@ -42,77 +45,141 @@ const validate = (method) => { // LOGIN const login = async (req, res, next) => { try { + + // generate unique code + uniqueCode = await helper.getUniqueCode(); + let { mid, tid, password } = req.body; + // log info + winston.logger.info( + `${uniqueCode} REQUEST login: ${JSON.stringify(req.body)}` + ); + // validate const err = validationResult(req); if (!err.isEmpty()) { - return res.status(200).json({ + result = { code: "400", message: err.errors[0].msg, data: {}, - }); + } + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE login: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } + // log debug + winston.logger.debug(`${uniqueCode} checking MID and TID...`); + // check mid dan tid let checkMidTid = await model.checkMidTid(mid, tid); if (!checkMidTid) { - return res.status(200).json({ + result = { code: "403", message: "MID or TID is not registered.", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE login: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } + // log debug + winston.logger.debug(`${uniqueCode} checking data login...`); + // check data login let checkDataLogin = await model.checkDataLogin(mid, tid); if (!checkDataLogin) { - return res.status(200).json({ + result = { code: "403", message: "Terminal Login already exists.", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE login: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } + // log debug + winston.logger.debug(`${uniqueCode} checking password...`); + // check password let checkPassword = await bcrypt.compare( password, checkDataLogin.c_password_hash ); if (!checkPassword) { - return res.status(200).json({ + result = { code: "403", message: "Password is wrong.", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE login: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } + // log debug + winston.logger.debug(`${uniqueCode} generating access token...`); + // generate access token let accessToken = await jwt.generateAccessToken({ mid: helper.encryptText(mid), tid: helper.encryptText(tid), }); + // log debug + winston.logger.debug(`${uniqueCode} generating refresh token...`); + // generate refresh token let refreshToken = await jwt.generateRefreshToken({ mid: helper.encryptText(mid), tid: helper.encryptText(tid), }); + // log debug + winston.logger.debug(`${uniqueCode} inserting refresh token...`); + // insert refresh token await model.insertRefreshToken(mid, tid, refreshToken); - return res.json({ + result = { code: "00", message: "Login Success.", data: { access_token: accessToken, refresh_token: refreshToken, }, - }); + }; + + // log info + winston.logger.info( + `${uniqueCode} RESPONSE login: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } catch (error) { // create log - winston.logger.error(`${error.message}`); + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); return res.status(200).json({ code: "500", @@ -128,38 +195,77 @@ const login = async (req, res, next) => { // REGISTER const register = async (req, res) => { try { + // generate unique code + uniqueCode = await helper.getUniqueCode(); + let { mid, tid, password } = req.body; + // log info + winston.logger.info( + `${uniqueCode} REQUEST register: ${JSON.stringify(req.body)}` + ); + // validate const err = validationResult(req); if (!err.isEmpty()) { - return res.status(200).json({ + result = { code: "400", message: err.errors[0].msg, data: {}, - }); + } + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE register: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } + + // log debug + winston.logger.debug(`${uniqueCode} checking MID and TID...`); + // check mid dan tid let checkMidTid = await model.checkMidTid(mid, tid); if (!checkMidTid) { - return res.status(200).json({ - code: "403", + result = { + code: "410", message: "MID or TID is not registered.", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE register: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } + // log debug + winston.logger.debug(`${uniqueCode} checking data login...`); + // check data login let checkDataLogin = await model.checkDataLogin(mid, tid); if (checkDataLogin) { - return res.status(200).json({ - code: "403", + result = { + code: "411", message: "Terminal Login already exists.", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE register: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } + // log debug + winston.logger.debug(`${uniqueCode} encrypting password...`); + // encrypt password const saltRounds = 10; let salt = bcrypt.genSaltSync(saltRounds); @@ -179,17 +285,29 @@ const register = async (req, res) => { c_create_fullname: null, }; - // insert data login - let result = await model.insertDataLogin(data); + // log debug + winston.logger.debug(`${uniqueCode} inserting data login...`); - return res.status(200).json({ + // insert data login + result = await model.insertDataLogin(data); + + result = { code: "00", message: "Data login saved successfully.", data: result.command, - }); + }; + + // log info + winston.logger.info( + `${uniqueCode} RESPONSE register: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } catch (error) { // create log - winston.logger.error(`${error.message}`); + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); return res.status(200).json({ code: "500", @@ -205,61 +323,108 @@ const register = async (req, res) => { // REFRESH TOKEN const refreshToken = async (req, res) => { try { + // generate unique code + uniqueCode = await helper.getUniqueCode(); + const { mid, tid } = req.body; const refresh_token = req.header("refresh_token"); + // log info + winston.logger.info( + `${uniqueCode} REQUEST refresh token: ${JSON.stringify(req.body)}` + ); + // validate const err = validationResult(req); if (!err.isEmpty()) { - return res.status(200).json({ + result = { code: "400", message: err.errors[0].msg, data: {}, - }); + } + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE refresh token: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } + + // log debug + winston.logger.debug(`${uniqueCode} authenticating refresh token...`); + // verify await jwt.authenticateRefreshToken; + // log debug + winston.logger.debug(`${uniqueCode} checking refresh token...`); + let checkRefreshToken = await model.checkRefreshToken( mid, tid, refresh_token ); if (!checkRefreshToken) { - return res.status(200).json({ + result = { code: "400", message: "Refresh Token is invalid. Please try login", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE refresh token: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } + // log debug + winston.logger.debug(`${uniqueCode} generating access token...`); + // generate new access token let accessToken = await jwt.generateAccessToken({ mid: helper.encryptText(mid), tid: helper.encryptText(tid), }); + // log debug + winston.logger.debug(`${uniqueCode} generating refresh token...`); + // generate new refresh token let refreshToken = await jwt.generateRefreshToken({ mid: helper.encryptText(mid), tid: helper.encryptText(tid), }); + // log debug + winston.logger.debug(`${uniqueCode} updating refresh token...`); + // update insert refresh token await model.updateRefreshToken(mid, tid, refresh_token, refreshToken); - return res.json({ + result = { code: "00", message: "New Token has been generated.", data: { access_token: accessToken, refresh_token: refreshToken, }, - }); + }; + + // log info + winston.logger.info( + `${uniqueCode} RESPONSE refresh token: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } catch (error) { // create log - winston.logger.error(`${error.message}`); + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); return res.status(200).json({ code: "500", diff --git a/application/modules/loadbalance/loadbalance.controller.js b/application/modules/loadbalance/loadbalance.controller.js index 7ff70da..9d2d751 100644 --- a/application/modules/loadbalance/loadbalance.controller.js +++ b/application/modules/loadbalance/loadbalance.controller.js @@ -5,6 +5,9 @@ const model = require("./loadbalance.model"); const moment = require("moment"); moment.locale("id"); +var result = {}; +var uniqueCode; + // VALIDATION const validate = (method) => { switch (method) { @@ -50,33 +53,36 @@ const validate = (method) => { // LOADING BALANCE REQUEST const loadingBalanceRequest = async (req, res) => { try { - // check validator - const err = validationResult(req, res); - if (!err.isEmpty()) { - return res.status(200).json({ - code: "400", - message: err.errors[0].msg, - data: {}, - }); - } - - let result = {}; - // generate unique code - let uniqueCode = await helper.getUniqueCode(); + 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)}` + `${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"); @@ -87,20 +93,14 @@ const loadingBalanceRequest = async (req, res) => { let getPartner = await model.getPartner(mid, tid); if (!getPartner) { result = { - code: "403", + code: "412", 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -115,20 +115,14 @@ const loadingBalanceRequest = async (req, res) => { let checkCardNumber = await model.checkCardNumber(card_number); if (!checkCardNumber) { result = { - code: "403", + code: "413", 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -175,15 +169,9 @@ const loadingBalanceRequest = async (req, res) => { 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -209,20 +197,14 @@ const loadingBalanceRequest = async (req, res) => { if (getReservationPending.length < 1) { result = { - code: "403", + code: "414", 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -261,20 +243,14 @@ const loadingBalanceRequest = async (req, res) => { totalReservation = i; if (totalReservation == 0) { result = { - code: "403", + code: "414", 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -288,20 +264,14 @@ const loadingBalanceRequest = async (req, res) => { // check total amount topup if (parseInt(amountTopup) <= 0) { result = { - code: "403", - message: "can't topup with amount = 0", + code: "415", + message: "amount must be greater than 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -326,20 +296,14 @@ const loadingBalanceRequest = async (req, res) => { parseInt(getMaxAmountOnTheCard.c_value) ) { result = { - code: "403", + code: "416", 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -362,20 +326,14 @@ const loadingBalanceRequest = async (req, res) => { parseInt(getMaxTopupPerMonth.c_value) ) { result = { - code: "403", + code: "417", 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -396,13 +354,9 @@ const loadingBalanceRequest = async (req, res) => { }, }; - // 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)}` + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify(result)}` ); return res.json(result); @@ -426,16 +380,6 @@ const loadingBalanceRequest = async (req, res) => { // LOAD BALANCE const loadingBalance = async (req, res) => { try { - // check validator - const err = validationResult(req, res); - if (!err.isEmpty()) { - return res.status(200).json({ - code: "400", - message: err.errors[0].msg, - data: {}, - }); - } - // param let { mid, @@ -451,18 +395,30 @@ const loadingBalance = async (req, res) => { unique_code, } = req.body; - let result = {}; + uniqueCode = unique_code ? unique_code : 9999999999999; - 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)}` + `${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"); @@ -474,20 +430,14 @@ const loadingBalance = async (req, res) => { let getPartner = await model.getPartner(mid, tid); if (!getPartner) { result = { - code: "403", + code: "412", 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -506,20 +456,14 @@ const loadingBalance = async (req, res) => { if (!reservationStatus) { result = { - code: "403", - message: "reservation number doesn't exist", + code: "414", + 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -543,15 +487,9 @@ const loadingBalance = async (req, res) => { }, }; - // 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( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -571,20 +509,14 @@ const loadingBalance = async (req, res) => { if (getReservationPending.length < 1) { result = { - code: "403", + code: "414", 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -603,20 +535,14 @@ const loadingBalance = async (req, res) => { if (amount != amountTopup) { result = { - code: "403", + code: "418", 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -691,20 +617,14 @@ const loadingBalance = async (req, res) => { if (!reservation) { result = { - code: "403", - message: "reservation number doesn't exist", + code: "414", + 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( + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE load balance validate: ${JSON.stringify( result )}` ); @@ -773,13 +693,9 @@ const loadingBalance = async (req, res) => { }, }; - // 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)}` + `${uniqueCode} RESPONSE load balance insert: ${JSON.stringify(result)}` ); return res.status(200).json(result); @@ -836,7 +752,7 @@ const inquiryLoadingBalance = async (req, res) => { if (!byLoadBalanceNumber) { return res.status(200).json({ - code: "403", + code: "419", message: "load balance doesn't exist", data: [], }); @@ -856,7 +772,7 @@ const inquiryLoadingBalance = async (req, res) => { if (!byCardNumber) { return res.status(200).json({ - code: "403", + code: "419", message: "load balance doesn't exist", data: {}, }); diff --git a/application/modules/reservebalance/reservebalance.controller.js b/application/modules/reservebalance/reservebalance.controller.js index b360c61..1db2add 100644 --- a/application/modules/reservebalance/reservebalance.controller.js +++ b/application/modules/reservebalance/reservebalance.controller.js @@ -1,9 +1,13 @@ const { param, body, validationResult } = require("express-validator"); +const helper = require("../../helpers/helper"); const winston = require("../../helpers/winston.logger"); const model = require("./reservebalance.model"); const moment = require("moment"); moment.locale("id"); +var result = {}; +var uniqueCode; + // VALIDATION const validate = (method) => { switch (method) { @@ -31,55 +35,108 @@ const validate = (method) => { // RESERVATION const reservation = async (req, res) => { try { - // check validator - const err = validationResult(req, res); - if (!err.isEmpty()) { - return res.status(200).json({ - code: "400", - message: err.errors[0].msg, - data: {}, - }); - } + // generate unique code + uniqueCode = await helper.getUniqueCode(); // param let { mid, tid, card_number, amount, ref_no } = req.body; + // log info + winston.logger.info( + `${uniqueCode} REQUEST reservation: ${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) { - return res.status(200).json({ - code: "403", + result = { + code: "412", message: "terminal id is not valid", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } // check card number let checkCardNumber = await model.checkCardNumber(card_number); if (!checkCardNumber) { - return res.status(200).json({ - code: "403", + result = { + code: "413", message: "card number is not registered", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } + // log debug + winston.logger.debug(`${uniqueCode} checking reservation amount...`); // check reservation amount if (parseInt(amount) <= 0) { - return res.status(200).json({ - code: "403", + result = { + code: "415", message: "amount must be greater than 0", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } + // log debug + 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 last balance on the card let balance = 1950000; @@ -90,14 +147,26 @@ const reservation = async (req, res) => { parseInt(balance) + parseInt(amount) > parseInt(getMaxAmountOnTheCard.c_value) ) { - return res.status(200).json({ - code: "403", + result = { + code: "416", message: "your card number has reached the maximum balance", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } } + // log debug + winston.logger.debug(`${uniqueCode} checking max topup per month...`); + // get accumulated balance in this month let accumulatedBalance = 19950000; @@ -108,21 +177,36 @@ const reservation = async (req, res) => { parseInt(accumulatedBalance) + parseInt(amount) > parseInt(getMaxTopupPerMonth.c_value) ) { - return res.status(200).json({ - code: "403", + result = { + code: "417", message: "your card number has been limit top up for this month", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } } } + // log debug + winston.logger.debug(`${uniqueCode} checking max reservation...`); + // get max reservation let getMaxReservation = await model.getMaxReservation(); let maxReservation = getMaxReservation.c_value ? getMaxReservation.c_value : 1; + // log debug + winston.logger.debug(`${uniqueCode} checking reservation with flag...`); + // get reservation with flag let reservationWithFlag = await model.getReservationWithFlag( card_number, @@ -133,14 +217,26 @@ const reservation = async (req, res) => { ? reservationWithFlag.total_reservation : 0; if (totalReservationWithFlag > 0) { - return res.status(200).json({ - code: "403", + result = { + code: "420", message: "your card number has incomplete transaction. Please unload your balance!", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } + // log debug + winston.logger.debug(`${uniqueCode} checking total reservation pending...`); + // get total reservation pending let getReservationPending = await model.getReservationPending( card_number, @@ -152,21 +248,33 @@ const reservation = async (req, res) => { : 0; if (totalReservationPending >= maxReservation) { - return res.status(200).json({ - code: "403", + result = { + code: "421", message: "your card number has some pending transaction. Please finished it!", data: {}, - }); + }; + + // log warn + winston.logger.warn( + `${uniqueCode} RESPONSE reservation: ${JSON.stringify( + result + )}` + ); + + return res.status(200).json(result); } + // log debug + winston.logger.debug(`${uniqueCode} getting issuer fee and channel fee...`); + // get issuer fee let issuerFee = 0; let channelFee = 0; let getIssuer = await model.getIssuer(getPartner.i_partner); if (getIssuer) { - issuerFee = getIssuer.i_issuer_fee_perc; - channelFee = getIssuer.i_channel_fee_perc; + issuerFee = (getIssuer.i_issuer_fee_perc/100) * 1500; + channelFee = (getIssuer.i_channel_fee_perc/100) * 1500; } // if (!getIssuer) { // return res.status(200).json({ @@ -176,6 +284,9 @@ const reservation = async (req, res) => { // }); // } + // log debug + winston.logger.debug(`${uniqueCode} checking reservation sequence...`); + // get reservation const getReservationNumberSequence = await model.getReservationNumberSequence(getPartner, today); @@ -183,6 +294,9 @@ const reservation = async (req, res) => { ? parseInt(getReservationNumberSequence.i_reservation_no_seq) + 1 : 1; + // log debug + winston.logger.debug(`${uniqueCode} generating reservation number...`); + // generate reservation number let reservationNumber = await model.generateReservationNumber( getPartner, @@ -190,6 +304,11 @@ const reservation = async (req, res) => { reservationNoSequence ); + // log debug + winston.logger.debug( + `${uniqueCode} getting reservation expiration date on parameter...` + ); + // get reservation expiration date by parameter let getReservationExpirationDateValue = await model.getReservationExpirationDateValue(); @@ -197,6 +316,11 @@ const reservation = async (req, res) => { ? parseInt(getReservationExpirationDateValue.c_value) : 1; + // log debug + winston.logger.debug( + `${uniqueCode} getting reservation expiration date measure on parameter...` + ); + // get reservation expiration date measure by parameter let getReservationExpirationDateMeasure = await model.getReservationExpirationDateMeasure(); @@ -251,18 +375,30 @@ const reservation = async (req, res) => { c_delete_fullname: null, }; + // log debug + winston.logger.debug(`${uniqueCode} inserting reservation transaction...`); + await model.insertReservation(data); - return res.status(200).json({ + result = { code: "00", message: "reservation saved successfully.", data: { reservation_number: reservationNumber, }, - }); + }; + + // log info + winston.logger.info( + `${uniqueCode} RESPONSE reservation: ${JSON.stringify(result)}` + ); + + return res.status(200).json(result); } catch (error) { // create log - winston.logger.error(`${error.message}`); + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); return res.status(200).json({ code: "500", @@ -311,7 +447,7 @@ const inquiryReservation = async (req, res) => { if (!byReservationNumber) { return res.status(200).json({ - code: "403", + code: "414", message: "reservation doesn't exist", data: {}, }); @@ -331,7 +467,7 @@ const inquiryReservation = async (req, res) => { if (!byCardNumber) { return res.status(200).json({ - code: "403", + code: "414", message: "reservation doesn't exist", data: [], }); @@ -345,7 +481,9 @@ const inquiryReservation = async (req, res) => { } } catch (error) { // create log - winston.logger.error(`${error.message}`); + winston.logger.error( + `500 internal server error - backend server | ${error.message}` + ); return res.status(200).json({ code: "500", diff --git a/docs/error_code b/docs/error_code new file mode 100644 index 0000000..e69de29