Compare commits

...

63 Commits

Author SHA1 Message Date
ihsan e30c78beb7 update cash in penentuan in period atau out period 2023-11-03 15:50:11 +07:00
ihsan 1d2e92b85f add sticky session config 2023-11-01 16:45:23 +07:00
ihsan 51cb6c1212 update logs 2023-10-20 11:07:38 +07:00
ihsan 6c93cff3bb update 2023-10-18 11:17:06 +07:00
ihsan b24335043a update setting with node cluster 2023-10-18 11:07:31 +07:00
ihsan ac2ea55b5d remove log check reservation 2023-10-17 11:14:37 +07:00
ihsan f3e9097bfa update fee sharing from persentage to nominal 2023-10-17 11:04:22 +07:00
ihsan 0dcec2a6ad add log debug for server busy 2023-10-15 18:32:39 +07:00
ihsan f8f974eb11 update log 2023-10-11 13:30:40 +07:00
ihsan 29981e9757 update 2023-10-11 13:27:03 +07:00
ihsan a59a9090a7 update 2023-10-11 13:23:56 +07:00
ihsan ca17c397c5 update bugs 2023-10-11 13:21:15 +07:00
ihsan ff1a80f3b5 update bugs axios 2023-10-11 13:19:19 +07:00
ihsan 4bda7458b4 update bugs 2023-10-11 13:17:15 +07:00
ihsan d4d61d1d79 update 2023-10-11 13:12:07 +07:00
ihsan 80557a53e8 implement run on multiple port by config env 2023-10-11 12:57:52 +07:00
ihsan 920a6d4ccd implement api hsm refresh 2023-10-11 12:26:02 +07:00
ihsan ecd0cb12c4 update 2023-10-06 16:23:37 +07:00
ihsan fe484b08af debug 2023-10-06 16:02:49 +07:00
ihsan f5a55392c9 upate 2023-10-06 15:40:00 +07:00
ihsan 2dc27ea57c debug ip 2023-10-06 13:43:42 +07:00
ihsan ecb78bfa29 update 2023-10-05 13:59:47 +07:00
ihsan 74936dbe0d add sticky 2023-10-05 11:46:23 +07:00
ihsan b1814031b9 update 2023-10-05 11:32:14 +07:00
ihsan b5061cf78e Merge branch 'develop_v1.4.5' into develop 2023-10-05 10:57:24 +07:00
ihsan a8e0376496 add sticky session with cluster 2023-10-05 10:57:04 +07:00
ihsan 16a20faee6 Merge branch 'develop_v1.4.5' into develop 2023-10-05 10:41:07 +07:00
ihsan 0f34326da4 update 2023-10-05 10:40:00 +07:00
ihsan 5d7852eff9 Merge branch 'develop_v1.4.5' into develop 2023-10-04 23:23:54 +07:00
ihsan 009e6caead disabled cluster 2023-10-04 23:23:37 +07:00
ihsan e61392d81a Merge branch 'develop_v1.4.4' into develop 2023-10-04 17:37:09 +07:00
ihsan 083e0af4a0 disabled cluster 2023-10-04 17:36:49 +07:00
ihsan 8c0b6f7e7c Merge branch 'develop_v1.4.4' into develop 2023-10-04 16:47:13 +07:00
ihsan b87e6cc450 update 2023-10-04 16:46:55 +07:00
ihsan cee0352271 Merge branch 'develop_v1.4.4' into develop 2023-10-04 16:10:42 +07:00
ihsan afc72b73ec update 2023-10-04 16:09:50 +07:00
ihsan dfce874ce9 Merge branch 'develop_v1.4.4' into develop 2023-10-04 16:06:38 +07:00
ihsan a2079a7263 update log 2023-10-02 13:36:24 +07:00
ihsan 19de123628 update bugs redis set sequence 2023-10-02 10:44:19 +07:00
ihsan 69ab898bf3 update bugs 2023-09-28 13:08:51 +07:00
ihsan 84de02de26 Merge branch 'develop_v1.4.4' into develop 2023-09-25 18:22:21 +07:00
Mohamad Lutfi d5df8d4f32 update generate cash-in 2023-09-25 11:49:22 +07:00
ihsan ae74b4c1bd update comment log debug 2023-09-25 11:30:59 +07:00
ihsan dab14b66c4 update fraud bugs 2023-09-21 18:34:05 +07:00
ihsan 46e3cd689b Merge branch 'develop_v1.4.3' into develop 2023-09-21 11:42:46 +07:00
ihsan 481858117d update 2023-09-17 14:55:55 +07:00
ihsan 31b581c85e Merge branch 'develop_v1.4.1' into develop 2023-08-30 12:38:37 +07:00
ihsan 50008e2006 Merge branch 'develop_v1.4.1' into develop 2023-08-29 19:04:15 +07:00
ihsan c30cdcf4ed Merge branch 'develop_v1.4.1' into develop 2023-08-25 11:18:58 +07:00
ihsan e77a975ccc Merge branch 'develop_v1.4.1' into develop 2023-08-25 10:55:27 +07:00
ihsan 728a9a92c9 Merge branch 'develop_v1.4.1' into develop 2023-08-25 10:42:12 +07:00
ihsan 24006105b9 Merge branch 'develop_v1.4.0' into develop 2023-07-21 19:22:52 +07:00
ihsan c2e95ee6a5 Merge branch 'develop_v1.4.0' into develop 2023-07-12 13:30:00 +07:00
ihsan da1912d05d Merge branch 'develop_v1.4.0' into develop 2023-07-12 13:19:26 +07:00
ihsan 7171d1e3f5 Merge remote-tracking branch 'origin/develop_v1.4.0' into develop 2023-07-11 13:11:42 +07:00
ihsan 05098fa3ac Merge branch 'develop_v1.4.0' into develop 2023-07-03 12:58:10 +07:00
ihsan 131cac392b Merge branch 'develop_v1.3.8' into develop 2023-05-25 11:59:53 +07:00
ihsan cd3c29bee0 Merge branch 'develop_v1.3.8' into develop 2023-05-24 17:03:46 +07:00
ihsan 8436ea2071 Merge branch 'develop_v1.3.8' into develop 2023-05-24 15:51:19 +07:00
ihsan 032e12d9d0 update 2023-05-22 14:19:30 +07:00
ihsan 5e91b9a147 Revert "Revert "backup env""
This reverts commit 3645bb2420.
2023-05-22 14:17:38 +07:00
ihsan 9b8865233b Revert "add version on index"
This reverts commit 18cab4b93b.
2023-05-22 14:16:48 +07:00
ihsan 3645bb2420 Revert "backup env"
This reverts commit c5b75058d3.
2023-05-22 14:06:44 +07:00
16 changed files with 1372 additions and 1027 deletions
+53 -28
View File
@@ -1,49 +1,58 @@
const jwt = require("jsonwebtoken"); const jwt = require('jsonwebtoken');
const helper = require("../helpers/helper"); const helper = require('../helpers/helper');
const winston = require('../helpers/winston.logger');
const generateRefreshToken = (req) => { const generateRefreshToken = (req) => {
let expiresIn = process.env.JWT_REFRESH_EXPIRATION ? process.env.JWT_REFRESH_EXPIRATION : "7d"; let expiresIn = process.env.JWT_REFRESH_EXPIRATION
? process.env.JWT_REFRESH_EXPIRATION
: '7d';
let signOptions = { let signOptions = {
issuer: 'CMS Kereta Commuter Indonesia', issuer: 'CMS Kereta Commuter Indonesia',
expiresIn: expiresIn, expiresIn: expiresIn,
} };
return jwt.sign(req, process.env.REFRESH_TOKEN_SECRET, signOptions); return jwt.sign(req, process.env.REFRESH_TOKEN_SECRET, signOptions);
}; };
const authenticateRefreshToken = (req, res, next) => { const authenticateRefreshToken = (req, res, next) => {
let verifyOptions = { let verifyOptions = {
issuer: 'CMS Kereta Commuter Indonesia', issuer: 'CMS Kereta Commuter Indonesia',
} };
jwt.verify(req.header("refresh_token"), process.env.REFRESH_TOKEN_SECRET, verifyOptions, (err, data) => { jwt.verify(
req.header('refresh_token'),
process.env.REFRESH_TOKEN_SECRET,
verifyOptions,
(err, data) => {
if (err) { if (err) {
return res.json({ return res.json({
code: "400", code: '400',
message: "Refresh Token is invalid. Please login!", message: 'Refresh Token is invalid. Please login!',
data: {}, data: {},
}); });
} }
next(); next();
}); }
);
}; };
const generateAccessToken = (req) => { const generateAccessToken = (req) => {
let expiresIn = process.env.JWT_EXPIRATION ? process.env.JWT_EXPIRATION : "1d"; let expiresIn = process.env.JWT_EXPIRATION
? process.env.JWT_EXPIRATION
: '1d';
let signOptions = { let signOptions = {
issuer: 'CMS Kereta Commuter Indonesia', issuer: 'CMS Kereta Commuter Indonesia',
expiresIn: expiresIn, expiresIn: expiresIn,
} };
if (req.user_group_id == "1") { if (req.user_group_id == '1') {
expiresIn = parseInt(process.env.JWT_EXPIRATION_ADMIN_WEB); expiresIn = parseInt(process.env.JWT_EXPIRATION_ADMIN_WEB);
} else if (req.user_group_id == "2") { } else if (req.user_group_id == '2') {
expiresIn = parseInt(process.env.JWT_EXPIRATION_MOBILE_PHONE); expiresIn = parseInt(process.env.JWT_EXPIRATION_MOBILE_PHONE);
} else if ( } else if (
req.user_group_id == "3" || req.user_group_id == '3' ||
req.user_group_id == "4" || req.user_group_id == '4' ||
req.user_group_id == "5" req.user_group_id == '5'
) { ) {
expiresIn = parseInt(process.env.JWT_EXPIRATION_TERMINAL); expiresIn = parseInt(process.env.JWT_EXPIRATION_TERMINAL);
} }
@@ -52,28 +61,43 @@ const generateAccessToken = (req) => {
}; };
const authenticateToken = async (req, res, next) => { const authenticateToken = async (req, res, next) => {
let authHeader = req.headers["authorization"]; let authHeader = req.headers['authorization'];
var ip = req.headers['x-real-ip'] || req.connection.remoteAddress;
console.log('INI LHO IP NYA....................: ' + ip);
if (authHeader) { if (authHeader) {
let token = authHeader && authHeader.split(" ")[1]; let token = authHeader && authHeader.split(' ')[1];
// winston.logger.info(
// `000000000000 [ AUTHENTICATE TOKEN ]: ${JSON.stringify({
// token: token,
// ip: ip,
// })}`
// );
if (!token) { if (!token) {
return res.json({ return res.json({
code: "401", code: '401',
message: "Token is required", message: 'Token is required',
data: {}, data: {},
}); });
} }
let verifyOptions = { let verifyOptions = {
issuer: 'CMS Kereta Commuter Indonesia', issuer: 'CMS Kereta Commuter Indonesia',
} };
await jwt.verify(token, process.env.TOKEN_SECRET, verifyOptions, (err, data) => { await jwt.verify(
token,
process.env.TOKEN_SECRET,
verifyOptions,
(err, data) => {
if (err) { if (err) {
return res.json({ return res.json({
code: "402", code: '402',
message: "Invalid Token.", message: 'Invalid Token.',
data: {}, data: {},
}); });
} }
@@ -84,11 +108,12 @@ const authenticateToken = async (req, res, next) => {
req.partner_user_id_token = helper.decryptText(data.partner_user_id); req.partner_user_id_token = helper.decryptText(data.partner_user_id);
next(); next();
}); }
);
} else { } else {
return res.json({ return res.json({
code: "400", code: '400',
message: "Header not found", message: 'Header not found',
data: {}, data: {},
}); });
} }
+75 -75
View File
@@ -101,9 +101,9 @@ const loginPartnerUser = async (req, res, next) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: checking data login...` // `${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: checking data login...`
); // );
// check status data partner user apakah masih aktif atau tidak // check status data partner user apakah masih aktif atau tidak
let checkDataLoginPartnerUser = await model.checkDataLoginPartnerUser( let checkDataLoginPartnerUser = await model.checkDataLoginPartnerUser(
@@ -129,9 +129,9 @@ const loginPartnerUser = async (req, res, next) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: checking password...` // `${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: checking password...`
); // );
// check password // check password
let checkPassword = await bcrypt.compare( let checkPassword = await bcrypt.compare(
@@ -158,9 +158,9 @@ const loginPartnerUser = async (req, res, next) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: generating access token...` // `${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: generating access token...`
); // );
// generate access token, yaitu token transaksi yang digunakan untuk setiap request ke setiap end point api // generate access token, yaitu token transaksi yang digunakan untuk setiap request ke setiap end point api
let accessToken = await jwt.generateAccessToken({ let accessToken = await jwt.generateAccessToken({
@@ -171,9 +171,9 @@ const loginPartnerUser = async (req, res, next) => {
}); });
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: generating refresh token...` // `${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: generating refresh token...`
); // );
// generate refresh token, yaitu token yang digunakan untuk mendapatkan token transaksi baru jika token sebelumnya sudah expired // generate refresh token, yaitu token yang digunakan untuk mendapatkan token transaksi baru jika token sebelumnya sudah expired
let refreshToken = await jwt.generateRefreshToken({ let refreshToken = await jwt.generateRefreshToken({
@@ -184,9 +184,9 @@ const loginPartnerUser = async (req, res, next) => {
}); });
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: inserting refresh token...` // `${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: inserting refresh token...`
); // );
// insert refresh token // insert refresh token
await model.insertRefreshTokenPartner(email, refreshToken); await model.insertRefreshTokenPartner(email, refreshToken);
@@ -263,9 +263,9 @@ const loginTerminal = async (req, res, next) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: checking MID and TID...` // `${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: checking MID and TID...`
); // );
// check mid dan tid, apakah mid dan tid yang di request terdaftar dan status nya aktif di sistem CMS // check mid dan tid, apakah mid dan tid yang di request terdaftar dan status nya aktif di sistem CMS
let checkMidTid = await model.checkMidTid(mid, tid); let checkMidTid = await model.checkMidTid(mid, tid);
@@ -285,9 +285,9 @@ const loginTerminal = async (req, res, next) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: checking data login...` // `${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: checking data login...`
); // );
// check data mid dan tid yang di request sudah di daftarkan di terminal login dan statusnya aktif atau tidak // check data mid dan tid yang di request sudah di daftarkan di terminal login dan statusnya aktif atau tidak
let checkDataLogin = await model.checkDataLogin(mid, tid); let checkDataLogin = await model.checkDataLogin(mid, tid);
@@ -309,9 +309,9 @@ const loginTerminal = async (req, res, next) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: checking password...` // `${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: checking password...`
); // );
// check password // check password
let checkPassword = await bcrypt.compare( let checkPassword = await bcrypt.compare(
@@ -336,9 +336,9 @@ const loginTerminal = async (req, res, next) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: generating access token...` // `${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: generating access token...`
); // );
// generate access token, yaitu token transaksi yang digunakan untuk request ke setiap end point api // generate access token, yaitu token transaksi yang digunakan untuk request ke setiap end point api
let accessToken = await jwt.generateAccessToken({ let accessToken = await jwt.generateAccessToken({
@@ -347,9 +347,9 @@ const loginTerminal = async (req, res, next) => {
}); });
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: generating refresh token...` // `${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: generating refresh token...`
); // );
// generate refresh token, yaitu token yang digunakan untuk mengenerate token transaksi baru jika token sebelumnya sudah expired // generate refresh token, yaitu token yang digunakan untuk mengenerate token transaksi baru jika token sebelumnya sudah expired
let refreshToken = await jwt.generateRefreshToken({ let refreshToken = await jwt.generateRefreshToken({
@@ -358,9 +358,9 @@ const loginTerminal = async (req, res, next) => {
}); });
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: inserting refresh token...` // `${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: inserting refresh token...`
); // );
// insert refresh token // insert refresh token
await model.insertRefreshToken(mid, tid, refreshToken); await model.insertRefreshToken(mid, tid, refreshToken);
@@ -437,9 +437,9 @@ const register = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REGISTER ]: checking MID and TID...` // `${uniqueCode} [ PROCESSING REGISTER ]: checking MID and TID...`
); // );
// check mid dan tid yang di request sudah terdaftar di master terminal sistem CMS atau belum dan status nya aktif // check mid dan tid yang di request sudah terdaftar di master terminal sistem CMS atau belum dan status nya aktif
let checkMidTid = await model.checkMidTid(mid, tid); let checkMidTid = await model.checkMidTid(mid, tid);
@@ -459,9 +459,9 @@ const register = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REGISTER ]: checking data login...` // `${uniqueCode} [ PROCESSING REGISTER ]: checking data login...`
); // );
// check data login, apaka mid dan tid yang di request sudah terdaftar di terminal login atau belum // check data login, apaka mid dan tid yang di request sudah terdaftar di terminal login atau belum
let checkDataLogin = await model.checkDataLogin(mid, tid); let checkDataLogin = await model.checkDataLogin(mid, tid);
@@ -483,9 +483,9 @@ const register = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REGISTER ]: encrypting password...` // `${uniqueCode} [ PROCESSING REGISTER ]: encrypting password...`
); // );
// encrypt password // encrypt password
let saltRounds = 10; let saltRounds = 10;
@@ -507,9 +507,9 @@ const register = async (req, res) => {
}; };
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REGISTER ]: inserting data login...` // `${uniqueCode} [ PROCESSING REGISTER ]: inserting data login...`
); // );
// insert data login // insert data login
result = await model.insertDataLogin(data); result = await model.insertDataLogin(data);
@@ -585,17 +585,17 @@ const refreshTokenTerminal = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: authenticating refresh token...` // `${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: authenticating refresh token...`
); // );
// verify, apaka refresh token yang di request valid atau tidak // verify, apaka refresh token yang di request valid atau tidak
await jwt.authenticateRefreshToken; await jwt.authenticateRefreshToken;
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: checking refresh token...` // `${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: checking refresh token...`
); // );
// cek apakah refresh token yang di request terdaftar di sistem CMS // cek apakah refresh token yang di request terdaftar di sistem CMS
let checkRefreshToken = await model.checkRefreshToken( let checkRefreshToken = await model.checkRefreshToken(
@@ -623,9 +623,9 @@ const refreshTokenTerminal = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: generating access token...` // `${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: generating access token...`
); // );
let accessToken; let accessToken;
let refreshToken; let refreshToken;
@@ -637,9 +637,9 @@ const refreshTokenTerminal = async (req, res) => {
}); });
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: generating refresh token...` // `${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: generating refresh token...`
); // );
// generate new refresh token // generate new refresh token
refreshToken = await jwt.generateRefreshToken({ refreshToken = await jwt.generateRefreshToken({
@@ -648,9 +648,9 @@ const refreshTokenTerminal = async (req, res) => {
}); });
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: updating refresh token...` // `${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: updating refresh token...`
); // );
// update insert refresh token // update insert refresh token
await model.updateRefreshToken(mid, tid, refresh_token, refreshToken); await model.updateRefreshToken(mid, tid, refresh_token, refreshToken);
@@ -731,17 +731,17 @@ const refreshTokenPartnerUser = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: authenticating refresh token...` // `${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: authenticating refresh token...`
); // );
// verify apaka refresh token yang di request valid atau tidak // verify apaka refresh token yang di request valid atau tidak
await jwt.authenticateRefreshToken; await jwt.authenticateRefreshToken;
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: checking refresh token...` // `${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: checking refresh token...`
); // );
// cek apaka refresh token yang di request terdaftar di sistem CMS atau tidak // cek apaka refresh token yang di request terdaftar di sistem CMS atau tidak
let checkRefreshToken = await model.checkRefreshTokenPartner( let checkRefreshToken = await model.checkRefreshTokenPartner(
@@ -768,9 +768,9 @@ const refreshTokenPartnerUser = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: generating access token...` // `${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: generating access token...`
); // );
let accessToken; let accessToken;
let refreshToken; let refreshToken;
@@ -807,9 +807,9 @@ const refreshTokenPartnerUser = async (req, res) => {
}); });
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: generating refresh token...` // `${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: generating refresh token...`
); // );
// generate new refresh token // generate new refresh token
refreshToken = await jwt.generateRefreshToken({ refreshToken = await jwt.generateRefreshToken({
@@ -820,9 +820,9 @@ const refreshTokenPartnerUser = async (req, res) => {
}); });
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: updating refresh token...` // `${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: updating refresh token...`
); // );
// update insert refresh token // update insert refresh token
await model.updateRefreshTokenPartner(email, refresh_token, refreshToken); await model.updateRefreshTokenPartner(email, refresh_token, refreshToken);
+237 -156
View File
@@ -1,17 +1,18 @@
// GET PARTNER, MERCHANT, TERMINAL FROM TID // GET PARTNER, MERCHANT, TERMINAL FROM TID
const generateInvoice = async (invoiceDate, repost, trx) => { const generateInvoice = async (invoiceDate, repost, trx) => {
let result = await trx.select(
let result = await trx.select(trx.raw(`* FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`)) trx.raw(
`* FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`
)
);
return result; return result;
};
}
const insertPostingEt = async (code, dataCashIn, trx) => { const insertPostingEt = async (code, dataCashIn, trx) => {
let type = ['S', 'H'] let type = ['S', 'H'];
let et = [] let et = [];
let posting_et = [] let posting_et = [];
type.forEach((item, index) => { type.forEach((item, index) => {
let data = { let data = {
file_name: code, file_name: code,
@@ -25,41 +26,55 @@ const insertPostingEt = async (code, dataCashIn, trx) => {
reference: code, reference: code,
amount: dataCashIn.amount, amount: dataCashIn.amount,
ba: dataCashIn.ba, ba: dataCashIn.ba,
indeks: (index+1), indeks: index + 1,
totalidx: type.length, totalidx: type.length,
doc_header_text: code, doc_header_text: code,
pos_status : 4 pos_status: 4,
} };
if (item == 'H') { if (item == 'H') {
data = {...data, ...{ data = {
...data,
...{
text: `Cash-in CMS ${code}`, text: `Cash-in CMS ${code}`,
debit_kredit: item, debit_kredit: item,
account: dataCashIn.c_account_topup, account: dataCashIn.c_account_topup,
customer: null customer: null,
}} },
};
} else { } else {
data = {...data, ...{ data = {
...data,
...{
text: `Cash-in CMS ${code}`, text: `Cash-in CMS ${code}`,
debit_kredit: item, debit_kredit: item,
account: null, account: null,
customer: dataCashIn.c_account_code_topup customer: dataCashIn.c_account_code_topup,
}} },
};
} }
et.push(data) et.push(data);
}); });
posting_et = await trx('public.posting_et').insert(et, ['indeks', 'customer', 'account', 'ba', 'fiscal_year', 'amount', 'no_dok', 'text', 'debit_kredit']) posting_et = await trx('public.posting_et').insert(et, [
'indeks',
'customer',
'account',
'ba',
'fiscal_year',
'amount',
'no_dok',
'text',
'debit_kredit',
]);
return posting_et[0] return posting_et[0];
};
}
const getPostingEt = async (trx) => { const getPostingEt = async (trx) => {
const result = await trx('public.posting_et AS pe')
const result = await trx('public.posting_et AS pe').select([ .select([
'doc_header_text', 'doc_header_text',
'ba', 'ba',
'doc_date', 'doc_date',
@@ -72,90 +87,132 @@ const getPostingEt = async(trx) => {
'tcode', 'tcode',
'amount', 'amount',
trx.raw(`'IDR' AS currency`), trx.raw(`'IDR' AS currency`),
trx.raw(`(SELECT customer FROM public.posting_et where reference = pe.reference and debit_kredit = 'S') as customer`), trx.raw(
trx.raw(`(SELECT account FROM public.posting_et where reference = pe.reference and debit_kredit = 'H') as account `), `(SELECT customer FROM public.posting_et where reference = pe.reference and debit_kredit = 'S') as customer`
trx.raw(`(SELECT text FROM public.posting_et where reference = pe.reference and debit_kredit = 'S') as text1`), ),
trx.raw(`(SELECT text FROM public.posting_et where reference = pe.reference and debit_kredit = 'H') as text2`) trx.raw(
`(SELECT account FROM public.posting_et where reference = pe.reference and debit_kredit = 'H') as account `
),
trx.raw(
`(SELECT text FROM public.posting_et where reference = pe.reference and debit_kredit = 'S') as text1`
),
trx.raw(
`(SELECT text FROM public.posting_et where reference = pe.reference and debit_kredit = 'H') as text2`
),
]) ])
.where('tcode', '=', "FB70") .where('tcode', '=', 'FB70')
// .where('reference', '=', reference) // .where('reference', '=', reference)
.whereIn('pos_status', ["4"]) .whereIn('pos_status', ['4'])
.groupBy(['doc_header_text', 'ba', 'doc_header_text', 'tcode', 'ba', 'amount', 'posting_date', 'doc_date', 'doc_type', 'fiscal_year', 'reference', 'no_dok']) .groupBy([
'doc_header_text',
'ba',
'doc_header_text',
'tcode',
'ba',
'amount',
'posting_date',
'doc_date',
'doc_type',
'fiscal_year',
'reference',
'no_dok',
]);
return result return result;
};
}
const setReturnSAP = async (code, resSAP, trx) => { const setReturnSAP = async (code, resSAP, trx) => {
let t_cash_in = [] let t_cash_in = [];
let reserveBalance = [] let reserveBalance = [];
if (resSAP.type == 'S') { if (resSAP.type == 'S') {
// update invoice // update invoice
t_cash_in = await trx('payment.t_d_cash_in').update({ t_cash_in = await trx('payment.t_d_cash_in')
.update(
{
c_return_sap: resSAP.data.E_DOCUMENTNUMBER, c_return_sap: resSAP.data.E_DOCUMENTNUMBER,
c_return_year_sap: resSAP.data.E_DOCUMENTYEAR c_return_year_sap: resSAP.data.E_DOCUMENTYEAR,
}, ['c_cash_in_no','c_return_sap']) },
['c_cash_in_no', 'c_return_sap']
)
.where({ .where({
c_cash_in_no: code c_cash_in_no: code,
}); });
// update load balance // update load balance
reserveBalance = await trx('trx.t_d_reservation_balance').update({ reserveBalance = await trx('trx.t_d_reservation_balance')
.update(
{
c_return_cash_in_sap: resSAP.data.E_DOCUMENTNUMBER, c_return_cash_in_sap: resSAP.data.E_DOCUMENTNUMBER,
c_cash_in_no: code c_cash_in_no: code,
}, ['c_cash_in_no', 'c_return_sap']) },
.whereRaw(`c_reservation_no IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail tdcid LEFT JOIN payment.t_d_cash_in tdci ON tdcid.i_cash_in = tdci.i_cash_in WHERE tdci.c_cash_in_no = '${code}')`) ['c_cash_in_no', 'c_return_sap']
)
.whereRaw(
`c_reservation_no IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail tdcid LEFT JOIN payment.t_d_cash_in tdci ON tdcid.i_cash_in = tdci.i_cash_in WHERE tdci.c_cash_in_no = '${code}')`
);
} else { } else {
let text = resSAP.message; let text = resSAP.message;
let result = text.toUpperCase(); let result = text.toUpperCase();
if(result.includes("ALREADY")){ if (result.includes('ALREADY')) {
let result = text.toUpperCase().split('-'); let result = text.toUpperCase().split('-');
let doc_number = result[1].trim().split(" ")[0] let doc_number = result[1].trim().split(' ')[0];
// update invoice // update invoice
const d = new Date(); const d = new Date();
let year = d.getFullYear(); let year = d.getFullYear();
t_cash_in = await trx('payment.t_d_cash_in').update({ t_cash_in = await trx('payment.t_d_cash_in')
.update(
{
c_return_sap: doc_number, c_return_sap: doc_number,
c_return_year_sap: year c_return_year_sap: year,
}, ['c_cash_in_no','c_return_sap']) },
['c_cash_in_no', 'c_return_sap']
)
.where({ .where({
c_cash_in_no: code c_cash_in_no: code,
}); });
// update load balance // update load balance
reserveBalance = await trx('trx.t_d_reservation_balance').update({ reserveBalance = await trx('trx.t_d_reservation_balance')
.update(
{
c_return_cash_in_sap: resSAP.data.E_DOCUMENTNUMBER, c_return_cash_in_sap: resSAP.data.E_DOCUMENTNUMBER,
c_cash_in_no: code c_cash_in_no: code,
}, ['c_cash_in_no', 'c_return_sap']) },
.whereRaw(`c_reservation_no IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail tdcid LEFT JOIN payment.t_d_cash_in tdci ON tdcid.i_cash_in = tdci.i_cash_in WHERE tdci.c_cash_in_no = '${code}')`) ['c_cash_in_no', 'c_return_sap']
)
.whereRaw(
`c_reservation_no IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail tdcid LEFT JOIN payment.t_d_cash_in tdci ON tdcid.i_cash_in = tdci.i_cash_in WHERE tdci.c_cash_in_no = '${code}')`
);
} }
} }
// update posting et // update posting et
const posting_et = await trx('public.posting_et').update({ const posting_et = await trx('public.posting_et')
.update(
{
pos_status: resSAP.type == 'S' ? 0 : 4, pos_status: resSAP.type == 'S' ? 0 : 4,
status0: resSAP.type, status0: resSAP.type,
no_doksap : resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null, no_doksap: resSAP.data.E_DOCUMENTNUMBER
status1 : resSAP.message ? resSAP.message : null ? resSAP.data.E_DOCUMENTNUMBER
}, ['file_name','status0']).where({ : null,
no_dok: code status1: resSAP.message ? resSAP.message : null,
}) },
['file_name', 'status0']
)
.where({
no_dok: code,
});
return { return {
cash_in: t_cash_in[0], cash_in: t_cash_in[0],
reserveBalance: reserveBalance[0], reserveBalance: reserveBalance[0],
posting_et : posting_et[0] posting_et: posting_et[0],
} };
};
}
const getRecon = async (trx) => { const getRecon = async (trx) => {
let sql = `SELECT let sql = `SELECT
tdi.c_invoice_no, tdi.c_invoice_no,
'FB70' AS tcode, 'FB70' AS tcode,
@@ -200,138 +257,162 @@ const getRecon = async (trx) => {
SELECT c_reservation_no FROM payment.t_d_payment_recon tdpr WHERE tdpr.c_status = 'S' SELECT c_reservation_no FROM payment.t_d_payment_recon tdpr WHERE tdpr.c_status = 'S'
) )
GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, tdpr.d_payment, b_past_month GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, tdpr.d_payment, b_past_month
ORDER BY tdpr.d_payment` ORDER BY tdpr.d_payment`;
let result = await trx.raw(sql) let result = await trx.raw(sql);
return result.rows return result.rows;
} };
const getReserve = async (trx, code, date, invoice) => { const getReserve = async (trx, code, date, invoice) => {
const res = await trx
const res = await trx.select([ .select([
"tdrb.c_reservation_no", 'tdrb.c_reservation_no',
"tdrb.i_reservation_amount", 'tdrb.i_reservation_amount',
"tdpr.c_payment_recon_no", 'tdpr.c_payment_recon_no',
"tdpr.d_payment", 'tdpr.d_payment',
"tdpr.d_payment_recon", 'tdpr.d_payment_recon',
"tdrb.c_partner_code", 'tdrb.c_partner_code',
"tdrb.c_partner_name", 'tdrb.c_partner_name',
"tdrb.c_load_balance_no", 'tdrb.c_load_balance_no',
"tdi.c_invoice_no" 'tdi.c_invoice_no',
]) ])
.from("trx.t_d_reservation_balance AS tdrb") .from('trx.t_d_reservation_balance AS tdrb')
.leftJoin('trx.t_d_load_balance as tdlb', function () { .leftJoin('trx.t_d_load_balance as tdlb', function () {
this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no') this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no');
}) })
.leftJoin('payment.t_d_invoice as tdi', function () { .leftJoin('payment.t_d_invoice as tdi', function () {
this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no') this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no').orOn(
'tdi.c_invoice_no',
'=',
'tdrb.c_invoice_no'
);
}) })
.leftJoin('payment.t_d_payment_recon as tdpr', function () { .leftJoin('payment.t_d_payment_recon as tdpr', function () {
this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no') this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no');
}) })
.where("tdrb.c_status", "=", "A") .where('tdrb.c_status', '=', 'A')
.where("tdi.c_status", "!=", "X") .where('tdi.c_status', '!=', 'X')
.where("tdrb.c_partner_code", "=", code) .where('tdrb.c_partner_code', '=', code)
.where("tdpr.d_payment", "=", date) .where('tdpr.d_payment', '=', date)
.where("tdi.c_invoice_no", "=", invoice) .where('tdi.c_invoice_no', '=', invoice)
.where("tdpr.c_status", "=", "S") .where('tdpr.c_status', '=', 'S')
.whereNotNull("tdi.c_return_sap") .whereNotNull('tdi.c_return_sap')
.whereNotNull("tdrb.c_load_balance_no") .whereNotNull('tdrb.c_load_balance_no')
.whereRaw(`tdrb.c_reservation_no in (SELECT c_reservation_no FROM payment.t_d_payment_recon where c_status = 'S' ) AND tdrb.c_reservation_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)`) .whereRaw(
return res `tdrb.c_reservation_no in (SELECT c_reservation_no FROM payment.t_d_payment_recon where c_status = 'S' ) AND tdrb.c_reservation_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)`
} );
return res;
};
const getPartnerRecon = async (trx) => { const getPartnerRecon = async (trx) => {
const res = await trx
const res = await trx.select([ .select([
"tdpr.c_partner_code", 'tdpr.c_partner_code',
"tdrb.c_partner_name", 'tdrb.c_partner_name',
"tdi.c_invoice_no", 'tdi.c_invoice_no',
"tdi.d_invoice_date", 'tdi.d_invoice_date',
trx.raw("to_char(tdpr.d_payment, 'YYYY-MM-DD') AS d_payment"), trx.raw("to_char(tdpr.d_payment, 'YYYY-MM-DD') AS d_payment"),
trx.raw("SUM(tdrb.i_reservation_amount) AS amount"), trx.raw('SUM(tdrb.i_reservation_amount) AS amount'),
"tmp.c_account_topup", 'tmp.c_account_topup',
"tmp.c_account_code_topup", 'tmp.c_account_code_topup',
"i_company", 'i_company',
"i_holding", 'i_holding',
trx.raw(`CASE trx.raw(`CASE
WHEN to_char(tdpr.d_payment, 'MM') = to_char(tdi.d_invoice_date, 'MM') WHEN to_char(tdpr.d_payment, 'MM') >= to_char(tdi.d_invoice_date, 'MM')
THEN 'IP' THEN 'IP'
ELSE ELSE
'OP' 'OP'
END c_in_period`), END c_in_period`),
]) ])
.from("trx.t_d_reservation_balance AS tdrb") .from('trx.t_d_reservation_balance AS tdrb')
.leftJoin('trx.t_d_load_balance as tdlb', function () { .leftJoin('trx.t_d_load_balance as tdlb', function () {
this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no') this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no');
}) })
.leftJoin('payment.t_d_invoice as tdi', function () { .leftJoin('payment.t_d_invoice as tdi', function () {
this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no') this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no').orOn(
'tdi.c_invoice_no',
'=',
'tdrb.c_invoice_no'
);
}) })
.leftJoin('payment.t_d_payment_recon as tdpr', function () { .leftJoin('payment.t_d_payment_recon as tdpr', function () {
this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no') this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no');
}) })
.leftJoin('public.t_m_partner as tmp', function () { .leftJoin('public.t_m_partner as tmp', function () {
this.on('tmp.c_code', '=', 'tdrb.c_partner_code') this.on('tmp.i_partner', '=', 'tdrb.i_partner');
}) })
.where("tdrb.c_status", "=", "A") .where('tdrb.c_status', '=', 'A')
.where("tdi.c_status", "!=", "X") .where('tdi.c_status', '!=', 'X')
.where("tdpr.c_status", "=", "S") .where('tdpr.c_status', '=', 'S')
.whereNotNull("tdi.c_return_sap") .whereNotNull('tdi.c_return_sap')
.whereNotNull("tdrb.c_load_balance_no") .whereNotNull('tdrb.c_load_balance_no')
.whereRaw(`tdrb.c_reservation_no in (SELECT c_reservation_no FROM payment.t_d_payment_recon where c_status = 'S' ) AND tdrb.c_reservation_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)`) .whereRaw(
.groupBy(["tdpr.c_partner_code","tdrb.c_partner_name","tdi.c_invoice_no","tdi.d_invoice_date", "tdpr.d_payment", "tmp.c_account_topup", "tmp.c_account_code_topup", "tdi.i_company", "i_holding"]) `tdrb.c_reservation_no in (SELECT c_reservation_no FROM payment.t_d_payment_recon where c_status = 'S' ) AND tdrb.c_reservation_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)`
)
.groupBy([
'tdpr.c_partner_code',
'tdrb.c_partner_name',
'tdi.c_invoice_no',
'tdi.d_invoice_date',
'tdpr.d_payment',
'tmp.c_account_topup',
'tmp.c_account_code_topup',
'tdi.i_company',
'i_holding',
]);
// .toSql() // .toSql()
return res return res;
};
}
const generateCode = async (trx, c_partner_code, d_payment_recon) => { const generateCode = async (trx, c_partner_code, d_payment_recon) => {
let code = "" let code = '';
let prefix = `CIN${c_partner_code}${d_payment_recon}` let prefix = `CIN${c_partner_code}${d_payment_recon}`;
let result =await trx.select([trx.raw(`substring(c_cash_in_no, 13, 3) AS code`)]) let result = await trx
.from("payment.t_d_cash_in") .select([trx.raw(`substring(c_cash_in_no, 13, 3) AS code`)])
.from('payment.t_d_cash_in')
.whereRaw(`substring(c_cash_in_no, 1, 12) = '${prefix}'`) .whereRaw(`substring(c_cash_in_no, 1, 12) = '${prefix}'`)
// .where("d_project_date", projectDate) // .where("d_project_date", projectDate)
.orderBy('c_cash_in_no', 'DESC') .orderBy('c_cash_in_no', 'DESC')
.first() .first();
if (result) { if (result) {
let counter = parseInt(result.code)+1 let counter = parseInt(result.code) + 1;
counter = String(counter).padStart(3, '0'); counter = String(counter).padStart(3, '0');
code = `${prefix}${counter}` code = `${prefix}${counter}`;
} else { } else {
code = `${prefix}001` code = `${prefix}001`;
} }
return code return code;
} };
const insertCashInDetail = async (trx, data) => { const insertCashInDetail = async (trx, data) => {
let result = [] let result = [];
if (data.length > 0) { if (data.length > 0) {
result = await trx('payment.t_d_cash_in_detail').insert(data,["*"]) result = await trx('payment.t_d_cash_in_detail').insert(data, ['*']);
}
return result
} }
return result;
};
const updateIntoReserve = async (trx, dataReserve, reserveNo) => { const updateIntoReserve = async (trx, dataReserve, reserveNo) => {
let result = await trx('trx.t_d_reservation_balance').update(dataReserve, ["*"]).where({c_reservation_no: reserveNo}) let result = await trx('trx.t_d_reservation_balance')
return result .update(dataReserve, ['*'])
} .where({ c_reservation_no: reserveNo });
return result;
};
const insertCashIn = async (trx, data) => { const insertCashIn = async (trx, data) => {
let result = await trx('payment.t_d_cash_in').insert(data,["*"]) let result = await trx('payment.t_d_cash_in').insert(data, ['*']);
return result[0] return result[0];
} };
const writePaynentHistory = async (data, message, i_log_name, trx) => { const writePaynentHistory = async (data, message, i_log_name, trx) => {
console.log(data) console.log(data);
const result = await trx('log.t_log_invoice').insert({ const result = await trx('log.t_log_invoice').insert(
{
// i_log_name : 102, // i_log_name : 102,
i_log_name: 119, i_log_name: 119,
d_log: trx.raw('NOW()'), d_log: trx.raw('NOW()'),
@@ -344,13 +425,13 @@ const writePaynentHistory = async (data, message, i_log_name, trx) => {
d_created: trx.raw('NOW()'), d_created: trx.raw('NOW()'),
m_amount: data.amount, m_amount: data.amount,
m_mdr_amount: 0, m_mdr_amount: 0,
m_mdr_net : data.amount m_mdr_net: data.amount,
},
['i_log_name', 'c_note']
);
}, ['i_log_name', 'c_note']) return result;
};
return result
}
module.exports = { module.exports = {
generateInvoice, generateInvoice,
@@ -365,5 +446,5 @@ module.exports = {
getReserve, getReserve,
getPartnerRecon, getPartnerRecon,
insertCashIn, insertCashIn,
updateIntoReserve updateIntoReserve,
}; };
@@ -228,9 +228,9 @@ const history = async (req, res) => {
let now = moment().format('YYYY-MM-DD HH:mm:ss'); let now = moment().format('YYYY-MM-DD HH:mm:ss');
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING CARD-HISTORY-FROM-CMS ]: checking parameter start date and end date...` // `${uniqueCode} [ PROCESSING CARD-HISTORY-FROM-CMS ]: checking parameter start date and end date...`
); // );
// validation inquiry date // validation inquiry date
if ((!start_date && end_date) || (start_date && !end_date)) { if ((!start_date && end_date) || (start_date && !end_date)) {
@@ -251,9 +251,9 @@ const history = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING CARD-HISTORY-FROM-CMS ]: checking mid and tid is valid or not...` // `${uniqueCode} [ PROCESSING CARD-HISTORY-FROM-CMS ]: checking mid and tid is valid or not...`
); // );
// get partner, merchant, terminal from tid // get partner, merchant, terminal from tid
let getPartner = await model.getPartner(mid, tid); let getPartner = await model.getPartner(mid, tid);
@@ -275,9 +275,9 @@ const history = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING CARD-HISTORY-FROM-CMS ]: getting history card from log CMS...` // `${uniqueCode} [ PROCESSING CARD-HISTORY-FROM-CMS ]: getting history card from log CMS...`
); // );
// get data history kartu di log sistem CMS // get data history kartu di log sistem CMS
let history = await model.historyByCardNumber( let history = await model.historyByCardNumber(
+32 -12
View File
@@ -1,3 +1,4 @@
const { default: axios } = require('axios');
const helper = require('../../helpers/helper'); const helper = require('../../helpers/helper');
const winston = require('../../helpers/winston.logger'); const winston = require('../../helpers/winston.logger');
const generate = require('./utils/utils'); const generate = require('./utils/utils');
@@ -33,6 +34,7 @@ const controller = async (req, res) => {
let uniqueCode = await helper.getUniqueCode(); let uniqueCode = await helper.getUniqueCode();
uniqueCode = uniqueCode + '' + counterDirect; uniqueCode = uniqueCode + '' + counterDirect;
let result = {}; let result = {};
let usingHSMNumber = 1;
// set connection HSM server // set connection HSM server
if (process.env.NUMBER_SERVER_ACTIVE == '12') { if (process.env.NUMBER_SERVER_ACTIVE == '12') {
@@ -43,12 +45,14 @@ const controller = async (req, res) => {
// winston.logger.error(`request to HSM server 2`); // winston.logger.error(`request to HSM server 2`);
if (client2.clientAuthenticated == false) { if (client2.clientAuthenticated == false) {
usingHSMNumber = 1;
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} ================================== REDIRECT USING HSM SERVER 1 ==================================}` `${uniqueCode} ================================== REDIRECT USING HSM SERVER 1 ==================================}`
); );
useClient = client; useClient = client;
} else { } else {
usingHSMNumber = 2;
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} ================================== USING HSM SERVER 2 ==================================}` `${uniqueCode} ================================== USING HSM SERVER 2 ==================================}`
@@ -57,12 +61,14 @@ const controller = async (req, res) => {
} }
} else { } else {
if (client.clientAuthenticated == false) { if (client.clientAuthenticated == false) {
usingHSMNumber = 2;
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} ================================== REDIRECT USING HSM SERVER 2 ==================================}` `${uniqueCode} ================================== REDIRECT USING HSM SERVER 2 ==================================}`
); );
useClient = client2; useClient = client2;
} else { } else {
usingHSMNumber = 1;
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} ================================== USING HSM SERVER 1 ==================================}` `${uniqueCode} ================================== USING HSM SERVER 1 ==================================}`
@@ -137,20 +143,34 @@ const controller = async (req, res) => {
await _sleep(10); await _sleep(10);
} }
// if (_timeOut) { if (_timeOut) {
// result = { let url = `http://${process.env.IP_HSM_SERVER_1}/feliqserver/v1/api/hsm/refresh`;
// code: "5001", if (usingHSMNumber == 2) {
// message: "Timeout", url = `http://${process.env.IP_HSM_SERVER_2}/feliqserver/v1/api/hsm/refresh`;
// data: {}, }
// };
// // log warn let response = await axios({
// winston.logger.warn( url: url,
// `${uniqueCode} response HSM - auth1v2: ${JSON.stringify(result)}` method: 'get',
// ); });
// return res.status(200).send(result); result = {
// } code: '5001',
message: 'Timeout',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-1 ]: ${JSON.stringify(
result
)} and refresh HSM ${usingHSMNumber} response status: ${
response.status
} | response text: ${response.statusText}`
);
return res.status(200).send(result);
}
_stopMessage = 0; _stopMessage = 0;
+14 -14
View File
@@ -62,7 +62,7 @@ function startInterval() {
interval = setInterval(function () { interval = setInterval(function () {
checkInternetConnected(config) checkInternetConnected(config)
.then((result) => { .then((result) => {
console.log(`retry open websocket server 1`); //successfully connected to a server // console.log(`retry open websocket server 1`); //successfully connected to a server
// log debug // log debug
// winston.logger.debug(`retry open websocket server 1`); // winston.logger.debug(`retry open websocket server 1`);
client.open(); client.open();
@@ -106,7 +106,7 @@ class WebSocketClient {
// Disconnection of WebSocket // Disconnection of WebSocket
close = () => { close = () => {
this.ws.close(); this.ws.close();
console.log(`websocket server 1 close`); // console.log(`websocket server 1 close`);
// log debug // log debug
// winston.logger.debug(`websocket server 1 close`); // winston.logger.debug(`websocket server 1 close`);
@@ -114,13 +114,13 @@ class WebSocketClient {
// Open event // Open event
onOpen = () => { onOpen = () => {
console.log(`opening websocket server 1`); // console.log(`opening websocket server 1`);
// log debug // log debug
// winston.logger.debug(`opening websocket server 1`); // winston.logger.debug(`opening websocket server 1`);
if (this.isOpened()) { if (this.isOpened()) {
console.log(`websocket server 1 open successfully`); // console.log(`websocket server 1 open successfully`);
// log debug // log debug
// winston.logger.debug(`websocket server 1 open successfully`); // winston.logger.debug(`websocket server 1 open successfully`);
@@ -137,7 +137,7 @@ class WebSocketClient {
}; };
onClose = () => { onClose = () => {
console.log(`websocket server 1 close`); // console.log(`websocket server 1 close`);
// log debug // log debug
// winston.logger.debug(`websocket server 1 close`); // winston.logger.debug(`websocket server 1 close`);
@@ -209,9 +209,9 @@ class WebSocketClient {
message[1] == 0 message[1] == 0
) { ) {
respData = null; respData = null;
console.log( // console.log(
`websocket server 1 message tenant: ${generate.buf2hex(message)}` // `websocket server 1 message tenant: ${generate.buf2hex(message)}`
); // );
// log debug // log debug
// winston.logger.debug( // winston.logger.debug(
@@ -227,16 +227,16 @@ class WebSocketClient {
await _sleep(10); await _sleep(10);
} }
let respCode = generate.getResponseCode(respData); let respCode = generate.getResponseCode(respData);
console.log(`websocket server 1 resp data tenant: ${respCode}`); // console.log(`websocket server 1 resp data tenant: ${respCode}`);
// log debug // log debug
// winston.logger.debug(`websocket server 1 resp data tenant: ${respCode}`); // winston.logger.debug(`websocket server 1 resp data tenant: ${respCode}`);
if (respCode == '0000' || respCode == '0502') { if (respCode == '0000' || respCode == '0502') {
this.clientAuthenticated = true; this.clientAuthenticated = true;
} }
console.log( // console.log(
`websocket server 1 client authenticate: ${this.clientAuthenticated}` // `websocket server 1 client authenticate: ${this.clientAuthenticated}`
); // );
// log debug // log debug
// winston.logger.debug( // winston.logger.debug(
@@ -253,7 +253,7 @@ class WebSocketClient {
var client = new WebSocketClient(); var client = new WebSocketClient();
if (!client.openWebSocketStatus) { if (!client.openWebSocketStatus) {
console.log(`first open websocket server 1`); // console.log(`first open websocket server 1`);
// log info // log info
// winston.logger.info(`first open websocket server 1`); // winston.logger.info(`first open websocket server 1`);
@@ -264,7 +264,7 @@ setInterval(function () {
// let statusConnection = client.clientAuthenticated; // let statusConnection = client.clientAuthenticated;
// if (!statusConnection) { // if (!statusConnection) {
if (!this.ws) { if (!this.ws) {
console.log(`websocket server 1 retry call client Auth`); // console.log(`websocket server 1 retry call client Auth`);
// log debug // log debug
// winston.logger.debug(`retry call client Auth`); // winston.logger.debug(`retry call client Auth`);
+14 -14
View File
@@ -62,7 +62,7 @@ function startInterval() {
interval = setInterval(function () { interval = setInterval(function () {
checkInternetConnected(config) checkInternetConnected(config)
.then((result) => { .then((result) => {
console.log(`retry open websocket server 2`); //successfully connected to a server // console.log(`retry open websocket server 2`); //successfully connected to a server
// log debug // log debug
// winston.logger.debug(`retry open websocket server 2`); // winston.logger.debug(`retry open websocket server 2`);
@@ -107,7 +107,7 @@ class WebSocketClient {
// Disconnection of WebSocket // Disconnection of WebSocket
close = () => { close = () => {
this.ws.close(); this.ws.close();
console.log(`websocket server 2 close`); // console.log(`websocket server 2 close`);
// log debug // log debug
// winston.logger.debug(`websocket server 2 close`); // winston.logger.debug(`websocket server 2 close`);
@@ -115,13 +115,13 @@ class WebSocketClient {
// Open event // Open event
onOpen = () => { onOpen = () => {
console.log(`opening server 2 websocket`); // console.log(`opening server 2 websocket`);
// log debug // log debug
// winston.logger.debug(`opening server 2 websocket`); // winston.logger.debug(`opening server 2 websocket`);
if (this.isOpened()) { if (this.isOpened()) {
console.log(`websocket server 2 open successfully`); // console.log(`websocket server 2 open successfully`);
// log debug // log debug
// winston.logger.debug(`websocket server 2 open successfully`); // winston.logger.debug(`websocket server 2 open successfully`);
@@ -138,7 +138,7 @@ class WebSocketClient {
}; };
onClose = () => { onClose = () => {
console.log(`websocket server 2 close`); // console.log(`websocket server 2 close`);
// log debug // log debug
// winston.logger.debug(`websocket server 2 close`); // winston.logger.debug(`websocket server 2 close`);
@@ -210,9 +210,9 @@ class WebSocketClient {
message[1] == 0 message[1] == 0
) { ) {
respData = null; respData = null;
console.log( // console.log(
`websocket server 2 message tenant: ${generate.buf2hex(message)}` // `websocket server 2 message tenant: ${generate.buf2hex(message)}`
); // );
// log debug // log debug
// winston.logger.debug( // winston.logger.debug(
@@ -228,7 +228,7 @@ class WebSocketClient {
await _sleep(10); await _sleep(10);
} }
let respCode = generate.getResponseCode(respData); let respCode = generate.getResponseCode(respData);
console.log(`websocket server 2 resp data tenant: ${respCode}`); // console.log(`websocket server 2 resp data tenant: ${respCode}`);
// log debug // log debug
// winston.logger.debug(`websocket server 2 resp data tenant: ${respCode}`); // winston.logger.debug(`websocket server 2 resp data tenant: ${respCode}`);
@@ -236,9 +236,9 @@ class WebSocketClient {
if (respCode == '0000' || respCode == '0502') { if (respCode == '0000' || respCode == '0502') {
this.clientAuthenticated = true; this.clientAuthenticated = true;
} }
console.log( // console.log(
`websocket server 2 client authenticate: ${this.clientAuthenticated}` // `websocket server 2 client authenticate: ${this.clientAuthenticated}`
); // );
// log debug // log debug
// winston.logger.debug( // winston.logger.debug(
@@ -255,7 +255,7 @@ class WebSocketClient {
var client2 = new WebSocketClient(); var client2 = new WebSocketClient();
if (!client2.openWebSocketStatus) { if (!client2.openWebSocketStatus) {
console.log(`first open websocket server 2`); // console.log(`first open websocket server 2`);
// log info // log info
// winston.logger.info(`first open websocket server 2`); // winston.logger.info(`first open websocket server 2`);
@@ -266,7 +266,7 @@ setInterval(function () {
// let statusConnection = client2.clientAuthenticated; // let statusConnection = client2.clientAuthenticated;
// if (!statusConnection) { // if (!statusConnection) {
if (!this.ws) { if (!this.ws) {
console.log(`websocket server 2 retry call client Auth`); // console.log(`websocket server 2 retry call client Auth`);
// log debug // log debug
// winston.logger.debug(`retry call client Auth`); // winston.logger.debug(`retry call client Auth`);
@@ -226,18 +226,9 @@ const updateAllTransaction = async (
let newLoadBalanceNumber; let newLoadBalanceNumber;
let getLoadBalanceSequence; let getLoadBalanceSequence;
let loadBalanceNoSequence = req.load_balance_number_sequence; let loadBalanceNoSequence = req.load_balance_number_sequence;
let maxLoop = 0;
do {
// await _sleep(helper.randomNumberInt());
if (maxLoop > 0) {
loadBalanceNoSequence++;
}
// log debug // log debug
winston.logger.debug( winston.logger.debug(`${uniqueCode} getting loading balance sequence...`);
`${uniqueCode} getting loading balance sequence...`
);
if (!loadBalanceNoSequence) { if (!loadBalanceNoSequence) {
// get loading balance // get loading balance
@@ -250,6 +241,20 @@ const updateAllTransaction = async (
: 1; : 1;
} }
let maxLoop = 0;
do {
// await _sleep(helper.randomNumberInt());
if (maxLoop > 0) {
loadBalanceNoSequence++;
}
// set sequence to redis
await setLoadBalanceNumberSequence(
req.partner_id_token,
loadBalanceNoSequence
);
// log warn // log warn
winston.logger.warn(`${uniqueCode} generating load balance number...`); winston.logger.warn(`${uniqueCode} generating load balance number...`);
@@ -261,10 +266,10 @@ const updateAllTransaction = async (
if (newLoadBalanceNumber != 'XX') { if (newLoadBalanceNumber != 'XX') {
// set sequence to redis // set sequence to redis
await setLoadBalanceNumberSequence( // await setLoadBalanceNumberSequence(
req.partner_id_token, // req.partner_id_token,
loadBalanceNoSequence // loadBalanceNoSequence
); // );
} }
// log warn // log warn
@@ -275,7 +280,7 @@ const updateAllTransaction = async (
if (maxLoop > maxLoopParameter) { if (maxLoop > maxLoopParameter) {
// create log // create log
winston.logger.error( winston.logger.error(
`500 internal server error (max loop) - backend server | ${error.message}` `${uniqueCode} 500 internal server error. Server is busy. please try again`
); );
return false; return false;
@@ -326,26 +331,26 @@ const updateAllTransaction = async (
await model.createDetailLoadBalanceFromReservation(reservationNumber); await model.createDetailLoadBalanceFromReservation(reservationNumber);
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} detail load balance with reservation no : ${JSON.stringify( // `${uniqueCode} detail load balance with reservation no : ${JSON.stringify(
reservationNumber // reservationNumber
)}` // )}`
); // );
if (detailLoadBalance.length > 0) { if (detailLoadBalance.length > 0) {
// log warn // log warn
winston.logger.warn( // winston.logger.warn(
`${uniqueCode} AAAAAAAAAAAAAAAAAA1111 [DATA] : ${JSON.stringify( // `${uniqueCode} AAAAAAAAAAAAAAAAAA1111 [DATA] : ${JSON.stringify(
reservationNumber // reservationNumber
)} [LB] : ${JSON.stringify(dataLoadBalance)} [LBD] : ${JSON.stringify( // )} [LB] : ${JSON.stringify(dataLoadBalance)} [LBD] : ${JSON.stringify(
detailLoadBalance // detailLoadBalance
)} [NOW] : ${JSON.stringify(now)} [FLAG] : ${JSON.stringify(flag)}` // )} [NOW] : ${JSON.stringify(now)} [FLAG] : ${JSON.stringify(flag)}`
); // );
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} updating reservation and insert new load balance transaction...` // `${uniqueCode} updating reservation and insert new load balance transaction...`
); // );
// update reservation and load balance transaction // update reservation and load balance transaction
let updateReservationAndInsertLoadingBalance = let updateReservationAndInsertLoadingBalance =
@@ -358,11 +363,11 @@ const updateAllTransaction = async (
); );
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} status insert new load balance and update reservation : ${JSON.stringify( // `${uniqueCode} status insert new load balance and update reservation : ${JSON.stringify(
updateReservationAndInsertLoadingBalance // updateReservationAndInsertLoadingBalance
)}` // )}`
); // );
// if (updateReservationAndInsertLoadingBalance > 0) { // if (updateReservationAndInsertLoadingBalance > 0) {
// // log debug // // log debug
@@ -452,9 +457,9 @@ const loadingBalanceRequest = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking production card number or not...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking production card number or not...`
); // );
// jika settingan untuk server adalah production // jika settingan untuk server adalah production
if (process.env.SERVER_FOR == 'production') { if (process.env.SERVER_FOR == 'production') {
@@ -502,9 +507,9 @@ const loadingBalanceRequest = async (req, res) => {
let month = moment().format('M'); let month = moment().format('M');
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking partner...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking partner...`
); // );
// get partner, merchant, terminal from tid // get partner, merchant, terminal from tid
let getPartner = await model.getPartner(mid, tid); let getPartner = await model.getPartner(mid, tid);
@@ -552,9 +557,9 @@ const loadingBalanceRequest = async (req, res) => {
// jika settingan pengecekkan nomor kartu dengan card product CMS aktif // jika settingan pengecekkan nomor kartu dengan card product CMS aktif
if (checkByCardProductStatusValue == 'A') { if (checkByCardProductStatusValue == 'A') {
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking card number...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking card number...`
); // );
// check card number request dengan list card number yang terdaftar di CMS // check card number request dengan list card number yang terdaftar di CMS
let checkCardNumber = await model.checkCardNumber(card_number); let checkCardNumber = await model.checkCardNumber(card_number);
@@ -579,9 +584,9 @@ const loadingBalanceRequest = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking flag on the card and the server...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking flag on the card and the server...`
); // );
// check last flag untuk nomor kartu dan uid yang di request di sistem CMS // check last flag untuk nomor kartu dan uid yang di request di sistem CMS
let checkFlag = await model.checkFlag(card_number, uid.toUpperCase()); let checkFlag = await model.checkFlag(card_number, uid.toUpperCase());
@@ -593,9 +598,9 @@ const loadingBalanceRequest = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending...`
); // );
// get total reservation pending // get total reservation pending
let getReservationPending = await model.getReservationPendingV2( let getReservationPending = await model.getReservationPendingV2(
@@ -605,9 +610,9 @@ const loadingBalanceRequest = async (req, res) => {
); );
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking fraud transaction...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking fraud transaction...`
); // );
// cek disini apakah sebelumnya topup // cek disini apakah sebelumnya topup
let cardHistory = await model.checkCardHistory(card_number); let cardHistory = await model.checkCardHistory(card_number);
@@ -654,7 +659,7 @@ const loadingBalanceRequest = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST updateFraudToReserve ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -670,9 +675,9 @@ const loadingBalanceRequest = async (req, res) => {
await model.getReservationPendingWithFlagCounter(card_number, now, flag); await model.getReservationPendingWithFlagCounter(card_number, now, flag);
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending with flag...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending with flag...`
); // );
// get total reservation pending // get total reservation pending
// let getReservationPendingWithFlag = // let getReservationPendingWithFlag =
// await model.getReservationPendingWithFlag(card_number, now); // await model.getReservationPendingWithFlag(card_number, now);
@@ -697,9 +702,9 @@ const loadingBalanceRequest = async (req, res) => {
}); });
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: updating reservation and load balance transaction...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: updating reservation and load balance transaction...`
); // );
// update // update
let insertUpdate = await updateAllTransaction( let insertUpdate = await updateAllTransaction(
@@ -717,9 +722,9 @@ const loadingBalanceRequest = async (req, res) => {
if (insertUpdate) { if (insertUpdate) {
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSINGE LOADING-BALANCE-REQUEST ]: updating flag to server...` // `${uniqueCode} [ PROCESSINGE LOADING-BALANCE-REQUEST ]: updating flag to server...`
); // );
// update flag from Server // update flag from Server
await model.updateFlag( await model.updateFlag(
@@ -770,9 +775,9 @@ const loadingBalanceRequest = async (req, res) => {
// await model.updateFlag(now, card_number, uid.toUpperCase(), balance, flag); // await model.updateFlag(now, card_number, uid.toUpperCase(), balance, flag);
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending...`
); // );
// reget total reservation pending // reget total reservation pending
getReservationPending = await model.getReservationPendingV2( getReservationPending = await model.getReservationPendingV2(
@@ -790,7 +795,7 @@ const loadingBalanceRequest = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST getReservationPending ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -821,7 +826,7 @@ const loadingBalanceRequest = async (req, res) => {
// log warn // log warn
winston.logger.warn( winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST totalReservation ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -830,14 +835,14 @@ const loadingBalanceRequest = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking the card number in list fraud transaction or not...XXXXXXXXXXXXXXXXXXXX` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking the card number in list fraud transaction or not...XXXXXXXXXXXXXXXXXXXX`
); // );
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking total topup amount...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking total topup amount...`
); // );
// check total amount topup // check total amount topup
if (parseInt(amountTopup) <= 0) { if (parseInt(amountTopup) <= 0) {
@@ -858,9 +863,9 @@ const loadingBalanceRequest = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking BI regulation status...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking BI regulation status...`
); // );
// get BI regulation status // get BI regulation status
let getBIRegulationStatus = await model.getBIRegulationStatus(); let getBIRegulationStatus = await model.getBIRegulationStatus();
@@ -884,7 +889,7 @@ const loadingBalanceRequest = async (req, res) => {
if (getBIRegulationStatus.c_value == 'A') { if (getBIRegulationStatus.c_value == 'A') {
// log debug // log debug
winston.logger.debug(`${uniqueCode} checking topup partial status...`); // winston.logger.debug(`${uniqueCode} checking topup partial status...`);
// check topup partial status // check topup partial status
let getTopupPartialStatus = await model.getTopupPartialStatus(); let getTopupPartialStatus = await model.getTopupPartialStatus();
@@ -907,9 +912,9 @@ const loadingBalanceRequest = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max balance on the card...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max balance on the card...`
); // );
// get max saldo on the card // get max saldo on the card
let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard(); let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
@@ -1008,9 +1013,9 @@ const loadingBalanceRequest = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max topup per month...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max topup per month...`
); // );
// get accumulated balance in this month // get accumulated balance in this month
let accumulatedBalance = 0; let accumulatedBalance = 0;
@@ -1122,9 +1127,9 @@ const loadingBalanceRequest = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: updating status reservation to in progress...${reservationNumberTemp}, ${now}, ${flag}` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: updating status reservation to in progress...${reservationNumberTemp}, ${now}, ${flag}`
); // );
// update status to in progress // update status to in progress
let updateStatusReservation = await model.updateStatusReservation( let updateStatusReservation = await model.updateStatusReservation(
@@ -1247,9 +1252,9 @@ const loadingBalanceInsert = async (req, param) => {
} }
// log warn // log warn
winston.logger.warn( // winston.logger.warn(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation status...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation status...`
); // );
// check reservation status // check reservation status
for (let index = 0; index < reservation_number.length; index++) { for (let index = 0; index < reservation_number.length; index++) {
@@ -1308,9 +1313,9 @@ const loadingBalanceInsert = async (req, param) => {
} }
// log warn // log warn
winston.logger.warn( // winston.logger.warn(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking last log history...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking last log history...`
); // );
// get last history by card number // get last history by card number
let lastHistory = await model.getLastHistory(card_number); let lastHistory = await model.getLastHistory(card_number);
@@ -1319,17 +1324,17 @@ const loadingBalanceInsert = async (req, param) => {
// if last history card is topup (21 = log name id for topup) // if last history card is topup (21 = log name id for topup)
if (lastHistory.i_log_name == 21 && lastHistory.c_source == 'CMS') { if (lastHistory.i_log_name == 21 && lastHistory.c_source == 'CMS') {
// log warn // log warn
winston.logger.warn( // winston.logger.warn(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting fraud transaction...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting fraud transaction...`
); // );
// insert reservation transaction to fraud table // insert reservation transaction to fraud table
await model.insertFraudTransaction(reservation_number); await model.insertFraudTransaction(reservation_number);
// log warn // log warn
winston.logger.warn( // winston.logger.warn(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: suspending reservation...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: suspending reservation...`
); // );
// update reservation with suspend status // update reservation with suspend status
await model.suspendReservation(reservation_number, now); await model.suspendReservation(reservation_number, now);
@@ -1352,9 +1357,9 @@ const loadingBalanceInsert = async (req, param) => {
} }
// log warn // log warn
winston.logger.warn( // winston.logger.warn(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking fraud transaction...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking fraud transaction...`
); // );
// get data fraud by card number and status fraud is not closed // get data fraud by card number and status fraud is not closed
let fraudTransaction = await model.getFraudTransaction(card_number); let fraudTransaction = await model.getFraudTransaction(card_number);
@@ -1367,9 +1372,9 @@ const loadingBalanceInsert = async (req, param) => {
} }
// log warn // log warn
winston.logger.warn( // winston.logger.warn(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation pending...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation pending...`
); // );
// get total reservation pending without fraud // get total reservation pending without fraud
let getReservationPending = await model.getReservationPendingWithoutFraud( let getReservationPending = await model.getReservationPendingWithoutFraud(
@@ -1396,9 +1401,9 @@ const loadingBalanceInsert = async (req, param) => {
} }
// log warn // log warn
winston.logger.warn( // winston.logger.warn(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking total topup amount...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking total topup amount...`
); // );
// check total topup and request topup // check total topup and request topup
let amountTopup = 0; let amountTopup = 0;
@@ -1427,23 +1432,11 @@ const loadingBalanceInsert = async (req, param) => {
let loadBalanceNumber; let loadBalanceNumber;
let getLoadBalanceSequence; let getLoadBalanceSequence;
let loadBalanceNoSequence = req.load_balance_number_sequence; let loadBalanceNoSequence = req.load_balance_number_sequence;
let maxLoop = 0;
do {
// await _sleep(helper.randomNumberInt());
if (maxLoop > 0) {
loadBalanceNoSequence++;
console.log(
'WOOOOOOOOOOOOOOOOOOOOOOOOOYYYYYYYYYYYYYYYYYYYYYYYYYYY: ' +
loadBalanceNoSequence
);
}
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting loading balance sequence...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting loading balance sequence...`
); // );
if (!loadBalanceNoSequence) { if (!loadBalanceNoSequence) {
// get loading balance // get loading balance
@@ -1454,48 +1447,57 @@ const loadingBalanceInsert = async (req, param) => {
loadBalanceNoSequence = getLoadBalanceSequence loadBalanceNoSequence = getLoadBalanceSequence
? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1 ? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1
: 1; : 1;
console.log(
'SIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAPPPPPPPPPPPP: ' +
loadBalanceNoSequence
);
} }
// log warn let maxLoop = 0;
winston.logger.warn( do {
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: generating load balance number...` // await _sleep(helper.randomNumberInt());
if (maxLoop > 0) {
loadBalanceNoSequence++;
}
// set sequence to redis
await setLoadBalanceNumberSequence(
req.partner_id_token,
loadBalanceNoSequence
); );
// log warn
// winston.logger.warn(
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: generating load balance number...`
// );
loadBalanceNumber = await generateLoadBalanceNumber( loadBalanceNumber = await generateLoadBalanceNumber(
getPartner, getPartner,
moment(today).format('YYMMDD'), moment(today).format('YYMMDD'),
loadBalanceNoSequence loadBalanceNoSequence
); );
if (loadBalanceNumber != 'XX') { // if (loadBalanceNumber != 'XX') {
// set sequence to redis // set sequence to redis
await setLoadBalanceNumberSequence( // await setLoadBalanceNumberSequence(
req.partner_id_token, // req.partner_id_token,
loadBalanceNoSequence // loadBalanceNoSequence
); // );
} // }
// log warn // log warn
winston.logger.warn( winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: load balance number is ${loadBalanceNumber}.` `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: load balance number sequence is ${loadBalanceNoSequence}.`
); );
if (maxLoop > maxLoopParameter) { if (maxLoop > maxLoopParameter) {
// create log // create log
winston.logger.error( winston.logger.error(
`[ RESPONSE LOADING-BALANCE-INSERT ]: 500 internal server error (max loop) - backend server | ${error.message}` `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: 500 internal server error. Server is busy. please try again`
); );
return { return {
code: '500', code: '500',
message: message:
process.env.NODE_ENV != 'production' process.env.NODE_ENV != 'production'
? error.message ? '500 internal server error (max loop) - backend server.'
: '500 internal server error (max loop) - backend server.', : '500 internal server error (max loop) - backend server.',
data: {}, data: {},
}; };
@@ -1543,9 +1545,9 @@ const loadingBalanceInsert = async (req, param) => {
}; };
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting reservation detail...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting reservation detail...`
); // );
let detail = []; let detail = [];
reservation_number = []; reservation_number = [];
@@ -1611,14 +1613,14 @@ const loadingBalanceInsert = async (req, param) => {
// check data load balance by reservation_number exist or not // check data load balance by reservation_number exist or not
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking load balance transaction has been exists or not...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking load balance transaction has been exists or not...`
); // );
// log warn // log warn
winston.logger.warn( // winston.logger.warn(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting load balance transaction...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting load balance transaction...`
); // );
// insert transaction // insert transaction
let insertLoadingBalance = await model.insertLoadingBalance( let insertLoadingBalance = await model.insertLoadingBalance(
@@ -1634,19 +1636,19 @@ const loadingBalanceInsert = async (req, param) => {
); );
// log warn // log warn
winston.logger.warn( // winston.logger.warn(
`${uniqueCode} [DATA] : ${JSON.stringify( // `${uniqueCode} [DATA] : ${JSON.stringify(
data // data
)} [DETAIL] : ${JSON.stringify(detail)} [RSV] : ${JSON.stringify( // )} [DETAIL] : ${JSON.stringify(detail)} [RSV] : ${JSON.stringify(
reservation_number // reservation_number
)} [NOW] : ${JSON.stringify(now)} [WRITE STATUS] : ${JSON.stringify( // )} [NOW] : ${JSON.stringify(now)} [WRITE STATUS] : ${JSON.stringify(
write_status // write_status
)} [CARD NUMBER] : ${JSON.stringify( // )} [CARD NUMBER] : ${JSON.stringify(
card_number // card_number
)} [UID] : ${JSON.stringify(uid)} [BALANCE] : ${JSON.stringify( // )} [UID] : ${JSON.stringify(uid)} [BALANCE] : ${JSON.stringify(
balance // balance
)} [FLAG] : ${JSON.stringify(flag)}` // )} [FLAG] : ${JSON.stringify(flag)}`
); // );
if (insertLoadingBalance > 0) { if (insertLoadingBalance > 0) {
result = { result = {
@@ -1736,9 +1738,9 @@ const loadingBalanceUpdate = async (param) => {
let today = moment().format('YYYY-MM-DD'); let today = moment().format('YYYY-MM-DD');
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: checking partner...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: checking partner...`
); // );
// get partner, merchant, terminal from tid // get partner, merchant, terminal from tid
let getPartner = await model.getPartner(mid, tid); let getPartner = await model.getPartner(mid, tid);
@@ -1773,9 +1775,9 @@ const loadingBalanceUpdate = async (param) => {
}; };
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: updating load balance transaction...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: updating load balance transaction...`
); // );
// update transaction // update transaction
await model.updateLoadingBalance( await model.updateLoadingBalance(
@@ -1790,9 +1792,9 @@ const loadingBalanceUpdate = async (param) => {
); );
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: inserting load balance transaction history ${loadBalanceNumber}...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: inserting load balance transaction history ${loadBalanceNumber}...`
); // );
let findDataLoadBalance = await model.findLoadBalance(loadBalanceNumber); let findDataLoadBalance = await model.findLoadBalance(loadBalanceNumber);
let dataLoadBalance = {}; let dataLoadBalance = {};
@@ -1876,9 +1878,9 @@ const loadingBalanceUpdate = async (param) => {
if (!write_status) { if (!write_status) {
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: inserting log for card history...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-UPDATE ]: inserting log for card history...`
); // );
// log card history // log card history
await model.createLoadBalanceLog({ await model.createLoadBalanceLog({
@@ -861,6 +861,7 @@ const getLastHistory = (cardNumber) => {
.where('c_source', 'CMS') .where('c_source', 'CMS')
.where('c_status', 'S') .where('c_status', 'S')
.orderBy('d_log', 'desc') .orderBy('d_log', 'desc')
.orderBy('i_log_card', 'desc')
.first(); .first();
return result; return result;
}; };
@@ -880,7 +881,9 @@ const insertFraudTransaction = (reservationNumber) => {
let result = knex let result = knex
.into( .into(
knex.raw('?? (??, ??, ??, ??, ??, ??)', [ knex.raw(
'?? (??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??)',
[
'trx.t_d_fraud', 'trx.t_d_fraud',
'c_card_number', 'c_card_number',
'c_reservation_no', 'c_reservation_no',
@@ -888,7 +891,21 @@ const insertFraudTransaction = (reservationNumber) => {
'c_reservation_status', 'c_reservation_status',
'c_reservation_flag', 'c_reservation_flag',
'c_reservation_ref_no', 'c_reservation_ref_no',
]) 'd_reservation',
'c_reservation_status_name',
'i_partner',
'c_partner_code',
'c_partner_name',
'i_merchant',
'c_merchant_code',
'c_merchant_name',
'c_mid',
'i_terminal',
'c_terminal_code',
'c_terminal_name',
'c_tid',
]
)
) )
.insert(function () { .insert(function () {
this.select( this.select(
@@ -897,7 +914,20 @@ const insertFraudTransaction = (reservationNumber) => {
'i_reservation_amount', 'i_reservation_amount',
'c_status', 'c_status',
'c_flag', 'c_flag',
'c_ref_no' 'c_ref_no',
'd_reservation',
'c_status_name',
'i_partner',
'c_partner_code',
'c_partner_name',
'i_merchant',
'c_merchant_code',
'c_merchant_name',
'c_mid',
'i_terminal',
'c_terminal_code',
'c_terminal_name',
'c_tid'
) )
.from('trx.t_d_reservation_balance') .from('trx.t_d_reservation_balance')
.whereIn( .whereIn(
@@ -115,9 +115,9 @@ const paymentRecon = async (req, res) => {
let now = moment().format('YYYY-MM-DD HH:mm:ss'); let now = moment().format('YYYY-MM-DD HH:mm:ss');
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING PAYMENT-RECON ]: checking partner...` // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: checking partner...`
); // );
// get partner, merchant, terminal from tid // get partner, merchant, terminal from tid
let getPartner = await model.getPartnerByID(partner_id); let getPartner = await model.getPartnerByID(partner_id);
@@ -167,9 +167,9 @@ const paymentRecon = async (req, res) => {
let PaymentReconNumber; let PaymentReconNumber;
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING PAYMENT-RECON ]: generating payment recon number...` // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: generating payment recon number...`
); // );
// loop 1 // loop 1
await _sleep(helper.randomNumberInt()); await _sleep(helper.randomNumberInt());
@@ -221,9 +221,9 @@ const paymentRecon = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING PAYMENT-RECON ]: checking reservation status has been cancelled or not...` // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: checking reservation status has been cancelled or not...`
); // );
// check reservation number yang di request apakah masih aktif atau sudah di cancel // check reservation number yang di request apakah masih aktif atau sudah di cancel
let checkReservationCanceledStatus = let checkReservationCanceledStatus =
@@ -241,9 +241,9 @@ const paymentRecon = async (req, res) => {
}; };
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...` // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...`
); // );
// insert payment recon transaction // insert payment recon transaction
await model.insertPaymentReconTransaction( await model.insertPaymentReconTransaction(
@@ -270,9 +270,9 @@ const paymentRecon = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING PAYMENT-RECON ]: checking reservation number in CMS...` // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: checking reservation number in CMS...`
); // );
// cek reservation number tercatat di sistem CMS atau tidak // cek reservation number tercatat di sistem CMS atau tidak
let check = await model.checkReservationNumberAndAmount(reservation_number); let check = await model.checkReservationNumberAndAmount(reservation_number);
@@ -289,9 +289,9 @@ const paymentRecon = async (req, res) => {
}; };
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...` // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...`
); // );
// insert payment recon transaction // insert payment recon transaction
await model.insertPaymentReconTransaction( await model.insertPaymentReconTransaction(
@@ -331,9 +331,9 @@ const paymentRecon = async (req, res) => {
}; };
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...` // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...`
); // );
// insert payment recon transaction // insert payment recon transaction
await model.insertPaymentReconTransaction( await model.insertPaymentReconTransaction(
@@ -373,9 +373,9 @@ const paymentRecon = async (req, res) => {
}; };
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...` // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...`
); // );
// insert payment recon transaction // insert payment recon transaction
await model.insertPaymentReconTransaction( await model.insertPaymentReconTransaction(
@@ -409,9 +409,9 @@ const paymentRecon = async (req, res) => {
}; };
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING PAYMENT-RECON ]: updating payment recon number...` // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: updating payment recon number...`
); // );
let update = await model.updatePaymentReconNo(data); let update = await model.updatePaymentReconNo(data);
if (!update) { if (!update) {
@@ -434,9 +434,9 @@ const paymentRecon = async (req, res) => {
} }
// log debug // log debug
winston.logger.debug( // winston.logger.debug(
`${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...` // `${uniqueCode} [ PROCESSING PAYMENT-RECON ]: inserting payment recon transaction...`
); // );
result = { result = {
code: '00', code: '00',
File diff suppressed because it is too large Load Diff
+16 -2
View File
@@ -1,8 +1,22 @@
# ================================= ENVIRONMENT ================================= # ================================= ENVIRONMENT =================================
#NODE_ENV=production #NODE_ENV=production
NODE_ENV=development NODE_ENV=development
CUSTOM_MODE_NODE_ENV=devprod
#NODE_ENV=testing #NODE_ENV=testing
PORT=3000 PORT=3000
VERSION=v1.4.6
# ===================== CLUSTER NODE (YES or NO) ===========================
CLUSTER_NODE=NO
# ===================== CLUSTER WITH RUNNING ON MULTIPLE PORT (YES or NO) ===========================
RUNNING_ON_MULTIPLE_PORT=NO
# PISAHKAN DENGAN MENGGUNAKAN SEPARATOR KOMA TANPA SPASI
PORTS=3001,3002,3003,3004
# ===================== CLUSTER NODE STICKY SESSION(YES or NO) ===========================
CLUSTER_NODE_STICKY_SESSION=YES
# =========================== KONFIGURASI UNTUK SERVER =========================== # =========================== KONFIGURASI UNTUK SERVER ===========================
# SERVER_FOR=development # SERVER_FOR=development
@@ -29,9 +43,9 @@ DB_USER_POOLING=postgres
DB_PASSWORD_POOLING=inhc0mmute_cms DB_PASSWORD_POOLING=inhc0mmute_cms
# ==================================== LOKI ===================================== # ==================================== LOKI =====================================
LOKI_URL=http://10.20.14.30:3100 LOKI_URL=http://localhost:3100
# ==================================== APP PROMETHEUS ===================================== # =============================== APP PROMETHEUS =================================
PROM_APP = topuponline PROM_APP = topuponline
# ================================== SECRET KEY ================================== # ================================== SECRET KEY ==================================
+97 -7
View File
@@ -1,12 +1,12 @@
require('dotenv').config(); require('dotenv').config();
// var http = require('http');
const cluster = require('node:cluster'); const cluster = require('node:cluster');
const totalCPUs = require('node:os').cpus().length; const totalCPUs = require('node:os').cpus().length;
const process = require('node:process'); const process = require('node:process');
const winston = require('./application/helpers/winston.logger'); const winston = require('./application/helpers/winston.logger');
const server = require('./server'); const app = require('./server');
const sticky = require('sticky-session');
// set port, listen for requests
const PORT = process.env.PORT || 3000;
var serverHSMStatus = 'HSM SERVER NOT CONNECTED'; var serverHSMStatus = 'HSM SERVER NOT CONNECTED';
if (process.env.NUMBER_SERVER_ACTIVE == '1') { if (process.env.NUMBER_SERVER_ACTIVE == '1') {
serverHSMStatus = `SERVER 1 CONNECTED on ip ${process.env.IP_HSM_SERVER_1}`; serverHSMStatus = `SERVER 1 CONNECTED on ip ${process.env.IP_HSM_SERVER_1}`;
@@ -29,6 +29,8 @@ if (process.env.CHANGE_TO_DRC == 'YES' || process.env.CHANGE_TO_DRC == 'yes') {
} }
} }
// jika mau di cluster gunakan script berikut:
if (process.env.CLUSTER_NODE.toUpperCase() == 'YES') {
if (cluster.isMaster) { if (cluster.isMaster) {
console.log(`Number of CPUs is ${totalCPUs}`); console.log(`Number of CPUs is ${totalCPUs}`);
console.log(`Master ${process.pid} is running`); console.log(`Master ${process.pid} is running`);
@@ -41,20 +43,108 @@ if (cluster.isMaster) {
cluster.on('exit', (worker, code, signal) => { cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`); console.log(`worker ${worker.process.pid} died`);
console.log("Let's fork another worker!"); console.log("Let's fork another worker!");
console.log('with code: ' + code);
cluster.fork(); cluster.fork();
}); });
// console.log(`worker pid=${process.pid}`);
} else { } else {
startExpress(); startExpress();
} }
} else {
console.log(`worker pid=${process.pid}`); // jika tidak mau di cluster langsung call function startExpress
startExpress();
}
function startExpress() { function startExpress() {
server.listen(PORT, () => { // set port, listen for requests
const PORT = process.env.PORT || 3000;
// jika settingan running on multiple
if (
process.env.RUNNING_ON_MULTIPLE_PORT.toUpperCase() == 'YES' &&
process.env.CLUSTER_NODE.toUpperCase() == 'NO'
) {
const PORTS = process.env.PORTS;
if (!PORTS) {
winston.logger.warn(
`Running on multiple port is active but the ports not yet set in .env`
);
} else {
let ports = PORTS.split(',');
for (let index = 0; index < ports.length; index++) {
const port = ports[index];
app.listen(port, () => {
winston.logger.info( winston.logger.info(
`Server is running on version ${ `Server is running on version ${
process.env.VERSION process.env.VERSION
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} ` } environment: ${process.env.NODE_ENV.toUpperCase()} port: ${port} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `
); );
}); });
} }
}
} else if (
process.env.RUNNING_ON_MULTIPLE_PORT.toUpperCase() == 'YES' &&
process.env.CLUSTER_NODE.toUpperCase() == 'YES'
) {
winston.logger.warn(
`If you want running the service on multiple port, please set CLUSTER_NODE = NO in .env file `
);
} else if (
process.env.CLUSTER_NODE_STICKY_SESSION.toUpperCase() == 'YES' &&
process.env.CLUSTER_NODE.toUpperCase() == 'YES'
) {
winston.logger.warn(
`If you want running the service with sticky session, please set CLUSTER_NODE = NO in .env file `
);
}
let message = `Server is running on version ${
process.env.VERSION
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `;
if (process.env.CLUSTER_NODE.toUpperCase() == 'YES') {
message = `Server is running with cluster node on version ${
process.env.VERSION
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `;
} else if (process.env.CLUSTER_NODE_STICKY_SESSION.toUpperCase() == 'YES') {
message = `Server is running with sticky session on version ${
process.env.VERSION
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `;
}
if (process.env.CLUSTER_NODE_STICKY_SESSION.toUpperCase() == 'YES') {
const server = app.listen(PORT, () => {
console.log(
`Worker ${process.pid} started. Listening on port ${
server.address().port
}`
);
winston.logger.info(message);
});
// Use sticky-session with the server instance
sticky.listen(server);
} else {
app.listen(PORT, () => {
winston.logger.info(message);
});
}
}
// Use sticky-session to handle sticky sessions
// if (!sticky.listen(cluster, port)) {
// // This is the master process, and it should not be listening to the port
// cluster.on('listening', (worker, address) => {
// console.log(
// `Worker ${worker.id} is now connected to ${address.address}:${address.port}`
// );
// });
// cluster.on('exit', (worker) => {
// console.log(`Worker ${worker.id} has exited`);
// });
// }
+24
View File
@@ -6,6 +6,29 @@ let port;
let user; let user;
let password; let password;
if (process.env.CUSTOM_MODE_NODE_ENV == 'devprod') {
// blok ini hanya digunakan untuk kebutuhan testing
if (process.env.SERVER_FOR == 'local') {
host = process.env.DB_HOST_LOCAL;
database = process.env.DB_NAME_LOCAL;
port = process.env.DB_PORT_LOCAL;
user = process.env.DB_USER_LOCAL;
password = process.env.DB_PASSWORD_LOCAL;
} else if (process.env.SERVER_FOR == 'development') {
host = '10.20.14.14';
database = 'postgres';
port = 5432;
user = 'postgres';
password = 'inhc0mmute_cms';
} else if (process.env.SERVER_FOR == 'production') {
host = '10.20.14.14';
database = 'postgres';
port = 5432;
user = 'postgres';
password = 'inhc0mmute_cms';
}
} else {
// setting an normal harusnya masuk blok ini
if (process.env.SERVER_FOR == 'local') { if (process.env.SERVER_FOR == 'local') {
host = process.env.DB_HOST_LOCAL; host = process.env.DB_HOST_LOCAL;
database = process.env.DB_NAME_LOCAL; database = process.env.DB_NAME_LOCAL;
@@ -25,6 +48,7 @@ if (process.env.SERVER_FOR == 'local') {
user = 'postgres'; user = 'postgres';
password = 'inhc0mmute_cms'; password = 'inhc0mmute_cms';
} }
}
module.exports = { module.exports = {
// development: { // development: {
+22
View File
@@ -28,6 +28,7 @@
"prom-client": "^14.2.0", "prom-client": "^14.2.0",
"redis": "^4.6.5", "redis": "^4.6.5",
"response-time": "^2.3.2", "response-time": "^2.3.2",
"sticky-session": "^1.1.2",
"winston": "^3.7.2", "winston": "^3.7.2",
"winston-daily-rotate-file": "^4.7.1", "winston-daily-rotate-file": "^4.7.1",
"winston-loki": "^6.0.6", "winston-loki": "^6.0.6",
@@ -8301,6 +8302,18 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/sticky-session": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/sticky-session/-/sticky-session-1.1.2.tgz",
"integrity": "sha512-1PPeJYu5SqjYcBNp93On4cQJuN7q+M+RbVjmYW1KSCKSv/rN1cVVyBBB0kCexsg0qJpQXgfHOt6bCneJTYRafQ==",
"dependencies": {
"debug": "^2.2.0",
"ip": "^1.0.0"
},
"engines": {
"node": ">= 0.12.0"
}
},
"node_modules/string_decoder": { "node_modules/string_decoder": {
"version": "1.3.0", "version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
@@ -15338,6 +15351,15 @@
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",
"integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==" "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ=="
}, },
"sticky-session": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/sticky-session/-/sticky-session-1.1.2.tgz",
"integrity": "sha512-1PPeJYu5SqjYcBNp93On4cQJuN7q+M+RbVjmYW1KSCKSv/rN1cVVyBBB0kCexsg0qJpQXgfHOt6bCneJTYRafQ==",
"requires": {
"debug": "^2.2.0",
"ip": "^1.0.0"
}
},
"string_decoder": { "string_decoder": {
"version": "1.3.0", "version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
+1
View File
@@ -41,6 +41,7 @@
"prom-client": "^14.2.0", "prom-client": "^14.2.0",
"redis": "^4.6.5", "redis": "^4.6.5",
"response-time": "^2.3.2", "response-time": "^2.3.2",
"sticky-session": "^1.1.2",
"winston": "^3.7.2", "winston": "^3.7.2",
"winston-daily-rotate-file": "^4.7.1", "winston-daily-rotate-file": "^4.7.1",
"winston-loki": "^6.0.6", "winston-loki": "^6.0.6",