mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:46:28 +00:00
Compare commits
9 Commits
f7c9c186f3
...
95c9170e18
| Author | SHA1 | Date | |
|---|---|---|---|
| 95c9170e18 | |||
| 3063468ae8 | |||
| 7927eeeac4 | |||
| 3902a74d6f | |||
| 1a59996dea | |||
| 418c38687a | |||
| 7e0cbc9ecd | |||
| 87235bcf35 | |||
| b399ae4938 |
@@ -0,0 +1,10 @@
|
||||
root = true
|
||||
|
||||
[*]
|
||||
charset = utf-8
|
||||
insert_final_newline = true
|
||||
|
||||
[*.{js,json,yml,yaml}]
|
||||
indent_style = space
|
||||
indent_size = 2
|
||||
trim_trailing_whitespace = true
|
||||
@@ -0,0 +1,38 @@
|
||||
name: Backend checks
|
||||
|
||||
on:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
backend:
|
||||
runs-on: ubuntu-latest
|
||||
services:
|
||||
postgres:
|
||||
image: postgres:18
|
||||
env:
|
||||
POSTGRES_USER: topup_test
|
||||
POSTGRES_PASSWORD: fixture
|
||||
POSTGRES_DB: topup_loadbalance_test
|
||||
ports:
|
||||
- 5432:5432
|
||||
options: >-
|
||||
--health-cmd "pg_isready -U topup_test -d topup_loadbalance_test"
|
||||
--health-interval 5s
|
||||
--health-timeout 5s
|
||||
--health-retries 10
|
||||
env:
|
||||
NODE_ENV: testing
|
||||
TOPUP_TEST_LOAD_BALANCE_DB_URL: postgresql://topup_test:fixture@127.0.0.1:5432/topup_loadbalance_test
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '24'
|
||||
cache: npm
|
||||
- run: npm ci
|
||||
- run: npm run lint
|
||||
- run: npm test -- --runInBand
|
||||
+14
-7
@@ -1,11 +1,18 @@
|
||||
# document error code saved on error_code file in docs folder
|
||||
# Online Top Up
|
||||
|
||||
# online topup log transaction saved on application/logs folder.
|
||||
## In DEVELOPMENT environment, debugging log, online topup log, and error log will be active.
|
||||
## In PRODUCTION environment, online topup log and error log will be active.
|
||||
# debugging log contains log all validation checks step by step, request data from client, error log, and response data to client
|
||||
# online topup log contains request data from client, error log, and response data to client
|
||||
# error log contains only error system or error service
|
||||
- `index.js` menjalankan server HTTP dan mengatur proses worker.
|
||||
- `server/` menyusun middleware Express, route API, dan metrik.
|
||||
- `application/` berisi modul bisnis, route, middleware, dan tes.
|
||||
- `infrastructure/` memuat koneksi database, migrasi, dan konfigurasi runtime.
|
||||
- `docs/database/` berisi referensi SQL untuk pemeriksaan dan pemeliharaan.
|
||||
- [Koleksi Bruno API](docs/api/bruno/README.md) untuk dokumentasi endpoint dan request lokal.
|
||||
- [Kode respons API](docs/error-codes.md) dan [setup HSM FeliQ](docs/hsm-feliq-setup.md) ada di direktori dokumentasi.
|
||||
|
||||
Log operasional ditulis sebagai JSON ke stdout. Terminal interaktif menampilkan
|
||||
merah untuk error backend, kuning untuk penolakan validasi atau warning, dan
|
||||
hijau untuk hasil sukses yang memiliki kode. Setel `NO_COLOR=1` untuk
|
||||
mematikan warna. Output yang ditangkap PM2, Docker, atau collector tetap berupa
|
||||
JSON polos saat stdout berupa pipe. Timestamp log mengikuti WIB.
|
||||
|
||||
## Kapasitas koneksi PostgreSQL
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIE7jCCA9agAwIBAgIJIrmxYwzstDwuMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV
|
||||
BAYTAkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMScw
|
||||
JQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTIwHhcNMTkwOTI3
|
||||
MDE1NDIzWhcNMjkwNTI5MDUwMDM5WjBeMQswCQYDVQQGEwJKUDEjMCEGA1UEChMa
|
||||
Q3liZXJ0cnVzdCBKYXBhbiBDby4sIEx0ZC4xKjAoBgNVBAMTIUN5YmVydHJ1c3Qg
|
||||
SmFwYW4gU3VyZVNlcnZlciBDQSBHNDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
|
||||
AQoCggEBAMtunFmosT8IxBkVFP+OnkGkcVmbui+hdVBlGZhniniVluAhigm2WUxx
|
||||
p4X5V3B/QKJLZmeAswmzxGKXaDCzcomYxXTygNXcTLI+IMyRisEO7V1NXFHUjSEl
|
||||
KaY1LzCA9/emldnmRjX6B9Zt5xXK5q12WOIWkJECEwwKku77tvtKZPRKaCNCGsZ5
|
||||
Hja7PBs07jLoE0rMuZLQZNQEB0W63attKGCGzEk50lDj+wQ0UlUbQk3zAEsvdE6X
|
||||
o1qZy9l783Va40vSx3VqhGYb4jWQrg2CrAtJcKQNSJ0m9yxJVVQDwpQQwGxHO5Em
|
||||
Qv1LGJExASegOXzhzqCr5yiwECfSrOsCAwEAAaOCAa4wggGqMB0GA1UdDgQWBBRi
|
||||
p9La3oW2kvGFvPbolZ11oPpOHzAfBgNVHSMEGDAWgBQKhal3ZQWYfECB+A+XLDjx
|
||||
Cuw8zzASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjBJBgNVHR8E
|
||||
QjBAMD6gPKA6hjhodHRwOi8vcmVwb3NpdG9yeS5zZWNvbXRydXN0Lm5ldC9TQy1S
|
||||
b290Mi9TQ1Jvb3QyQ1JMLmNybDBSBgNVHSAESzBJMEcGCiqDCIybG2SHBQQwOTA3
|
||||
BggrBgEFBQcCARYraHR0cHM6Ly9yZXBvc2l0b3J5LnNlY29tdHJ1c3QubmV0L1ND
|
||||
LVJvb3QyLzCBhQYIKwYBBQUHAQEEeTB3MDAGCCsGAQUFBzABhiRodHRwOi8vc2Ny
|
||||
b290Y2EyLm9jc3Auc2Vjb210cnVzdC5uZXQwQwYIKwYBBQUHMAKGN2h0dHA6Ly9y
|
||||
ZXBvc2l0b3J5LnNlY29tdHJ1c3QubmV0L1NDLVJvb3QyL1NDUm9vdDJjYS5jZXIw
|
||||
HQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IB
|
||||
AQDFUXkuQAZKY5Pb/JvgufizJ8uZKpN++fiI8kOTgkrSriNYNjO9iEdTwVV3sW3P
|
||||
abr3lAdCGrJ+wgArLLUnBZ7VGM//UlDhTRe4A19c0TmV1udTSbxabwQJbN1zIGbG
|
||||
3KQsumg9/70PaIkawnihx9/TxGCrJkAH5W+9pkX7OWefsahylwiPkKRkJRv2em/v
|
||||
rMRyb3LxRU5t84k1xQqCnMxTEWOAiWoOtatExZ38a8kn8kqiE1NEvtPOzSrVjSvD
|
||||
7pH56AlvO7hzGzng60kyWnAz6O5rQ0tsFIgW9xloWTQQVcfEtzvjc8ptuP9onkbA
|
||||
jMRDJaqLXrIVtB7GMek7S6AO
|
||||
-----END CERTIFICATE-----
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl
|
||||
MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe
|
||||
U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX
|
||||
DTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy
|
||||
dXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj
|
||||
YXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV
|
||||
OVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr
|
||||
zbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM
|
||||
VAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ
|
||||
hNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO
|
||||
ojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw
|
||||
awNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs
|
||||
OPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3
|
||||
DQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF
|
||||
coJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc
|
||||
okgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8
|
||||
t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy
|
||||
1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/
|
||||
SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03
|
||||
-----END CERTIFICATE-----
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,80 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let felicaPollingResponse = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
let _timeOut = false;
|
||||
|
||||
let _validasi = body.requestData.slice(4, 20)
|
||||
|
||||
let transactionId = Buffer.from([0x00, 0x00]);
|
||||
let apiId = Buffer.from([0x01]);
|
||||
reqData = generate.makeRequestData(transactionId, apiId, felicaPollingResponse);
|
||||
|
||||
client.sendData(reqData)
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
setInterval(function () {
|
||||
respData = Buffer.from([
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00
|
||||
])
|
||||
_timeOut = true
|
||||
}, 10000);
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14, 30)
|
||||
while (message[2] == 1 && _stopMessage == 1 && _validasi.toLowerCase() == __validasi.toLowerCase()) {
|
||||
respData = null
|
||||
console.log('*WS MESSAGE Auth1v2: ' + generate.buf2hex(message));
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
if (_timeOut) {
|
||||
return res.status(200).send({
|
||||
status: "99",
|
||||
message: "Timeout",
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: "Request Authenticate 1 Success",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "02",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,68 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let _validationTrxID = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
|
||||
if (auth2v2requestData[0] != 0x41) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: "Wrong Respone from Card",
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x02]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, auth2v2requestData);
|
||||
|
||||
client.sendData(reqData);
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 2 && message[0] == _validationTrxID[0] && message[1] == _validationTrxID[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Auth2v2: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: "Request Authenticate 2 Success",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,69 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let auth2v2responseSetData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
console.log('Req Auth Resp: ' + body.requestData);
|
||||
|
||||
if (auth2v2responseSetData[0] != 0x43) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: "Wrong Respone from Card",
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x03]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, auth2v2responseSetData);
|
||||
|
||||
client.sendData(reqData);
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 3 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Auth2v2 Resp: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while(respData == null){
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: "Request Authenticate Resp Success",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,59 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
|
||||
let transactionEnd = Buffer.from([]);
|
||||
let apiId = Buffer.from([0x06]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, transactionEnd);
|
||||
let _stopMessage = 1;
|
||||
|
||||
client.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 6 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE EndTrx: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while(respData == null){
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: "End Transaction Success",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,61 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
|
||||
let apiId = Buffer.from([0x04]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, trxrequestData);
|
||||
|
||||
client.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 4 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Transmit Packet: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while(respData == null){
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,67 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let packet = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
if (packet[0] != 0x45) {
|
||||
return {
|
||||
status: "03",
|
||||
message: "Respone Card Wrong",
|
||||
data: {}
|
||||
}
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x05]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, packet);
|
||||
client.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 5 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Received Packet: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,132 +0,0 @@
|
||||
const WebSocket = require('ws')
|
||||
const fs = require('fs')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
const generate = require('../utils/utils')
|
||||
|
||||
let ssl_ca_crt = './app/assets/cert/CACerts.pem'
|
||||
let ssl_client_pfx = './app/assets/cert/FeliqClient0002-02.pfx';
|
||||
let options = {
|
||||
ca : fs.readFileSync(ssl_ca_crt),
|
||||
agent: false,
|
||||
passphrase : "GPqs+Uia78",
|
||||
pfx : fs.readFileSync(ssl_client_pfx),
|
||||
};
|
||||
let url = 'wss://gateway04.cyberware.co.jp/feliqserver/v1/wsapi';
|
||||
|
||||
class WebSocketClient{
|
||||
|
||||
ws = null;
|
||||
clientAuthenticated = false;
|
||||
|
||||
// Connection of WebSocket
|
||||
open = () => {
|
||||
this.ws = new WebSocket(url, [], options);
|
||||
this.ws.on('open', this.onOpen);
|
||||
this.ws.on('close', this.onClose);
|
||||
}
|
||||
// Disconnection of WebSocket
|
||||
close = () => {
|
||||
this.ws.close();
|
||||
console.log('WebSocket Close');
|
||||
}
|
||||
|
||||
// Open event
|
||||
onOpen = () => {
|
||||
console.log('WebSocket Open');
|
||||
this.isOpened();
|
||||
if(!this.clientAuthenticated){
|
||||
this.clientAuth();
|
||||
}
|
||||
}
|
||||
|
||||
onClose = () => {
|
||||
console.log('WebSocket Close');
|
||||
this.clientAuthenticated = false;
|
||||
this.isOpened();
|
||||
this.open();
|
||||
}
|
||||
|
||||
// Connection check
|
||||
isOpened = () => {
|
||||
return this.ws.readyState == WebSocket.OPEN;
|
||||
}
|
||||
|
||||
// Received data check
|
||||
isReceive(){
|
||||
return this.receiveData != null;
|
||||
}
|
||||
|
||||
// Acquiring received data
|
||||
getReceiveData(){
|
||||
return this.receiveData;
|
||||
}
|
||||
|
||||
clearReceiveData(){
|
||||
this.receiveData = null;
|
||||
}
|
||||
|
||||
// Send data
|
||||
sendData(data){
|
||||
this.receiveData = null;
|
||||
this.ws.send(data);
|
||||
}
|
||||
|
||||
async clientAuth(){
|
||||
try{
|
||||
const authHead = Buffer.alloc(2);
|
||||
// Set system code (when 0x0000)
|
||||
authHead[0] = 0x93;
|
||||
authHead[1] = 0x9E;
|
||||
// Set API key
|
||||
//const apiKeyBytes = Buffer.from('82002732-9148-34e5-843b-c639a0c88cc5-0TC') // T4
|
||||
const apiKeyBytes = Buffer.from('4c6dd075-dbcb-375f-81f7-62990a5d7000-0TC') // Nutech
|
||||
// Secret setting
|
||||
//const secretBytes = Buffer.from('TdtSo/i5ZmbwPr82gt4fElK96lV9ClVo7votHKMIUuo='); // T4
|
||||
const secretBytes = Buffer.from('U5xs7nVonhtbQ+XiYATRSg8Nk5sPu1IpVx7X40KyWiw='); // Nutech
|
||||
|
||||
const authData = Buffer.concat([authHead, apiKeyBytes, secretBytes]);
|
||||
|
||||
let transactionId = Buffer.from([0x00, 0x00]);
|
||||
let apiId = Buffer.from([0x00]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, authData);
|
||||
|
||||
let respData = null;
|
||||
let _stopMessage = 1;
|
||||
|
||||
this.sendData(reqData);
|
||||
|
||||
this.ws.on('message', (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14,30)
|
||||
while(message[2] == 0 && _stopMessage == 1 && message[0] == 0 && message[1] == 0){
|
||||
respData = null
|
||||
console.log('*WS MESSAGE Tenan: ' + generate.buf2hex(message));
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while(respData == null){
|
||||
await _sleep(10);
|
||||
}
|
||||
let respCode = generate.getResponseCode(respData);
|
||||
console.log(`Resp Data Tenant = ${respCode}`)
|
||||
|
||||
if (respCode == "0000" || respCode == "0502") this.clientAuthenticated = true;
|
||||
console.log(`clientAuthenticated = ${this.clientAuthenticated}`);
|
||||
}catch (error) {
|
||||
console.log(`error ${error}`)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
const client = new WebSocketClient();
|
||||
client.open();
|
||||
|
||||
setInterval(function(){
|
||||
client.clientAuth()
|
||||
}, 59000);
|
||||
|
||||
module.exports = {
|
||||
client
|
||||
};
|
||||
@@ -1,61 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
|
||||
let apiId = Buffer.from([0x04]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, trxrequestData);
|
||||
|
||||
client.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 4 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Transmit Packet: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while(respData == null){
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: 'Generate Write Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,79 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let packet = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
if (packet[0] != 0x47) {
|
||||
return {
|
||||
status: "03",
|
||||
message: "Respone Card Wrong",
|
||||
data: {}
|
||||
}
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x05]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, packet);
|
||||
client.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 5 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Received Packet: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
if (respData[6] != 0x47 || (respData1[9] != 0x00 && respData1[10] != 0x00)){
|
||||
return res.status(200).send({
|
||||
status: "02",
|
||||
message: "Gagal",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respData1.slice(6,10),
|
||||
transcode: null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: 'Topup Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,157 +0,0 @@
|
||||
const { Buffer } = require("buffer")
|
||||
const fs = require('fs')
|
||||
|
||||
// Generate request data for FeliQ Server
|
||||
function makeRequestData(transactionId, apiId, data){
|
||||
let request = Buffer.alloc(2 + 1 + 1 + data.length)
|
||||
let dataSize = Buffer.alloc(1)
|
||||
dataSize[0] = data.length
|
||||
request = Buffer.concat([transactionId, apiId, dataSize, data])
|
||||
return request;
|
||||
}
|
||||
|
||||
// Extract response code from API response data
|
||||
function getResponseCode(data){
|
||||
let respCode = Buffer.alloc(2)
|
||||
respCode[0] = data[3]
|
||||
respCode[1] = data[4]
|
||||
return buf2hex(respCode)
|
||||
}
|
||||
|
||||
// Extract response data from API response data
|
||||
function getResponseData(apiData){
|
||||
let data = Buffer.alloc(apiData[5])
|
||||
apiData.copy(data, 0, 6, apiData[5]+6)
|
||||
return buf2hex(data);
|
||||
}
|
||||
|
||||
|
||||
function buf2hex(buffer){ // buffer is an ArrayBuffer
|
||||
return [...new Uint8Array(buffer)]
|
||||
.map(x => x.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
}
|
||||
|
||||
function hexToBytes(hex) {
|
||||
for (var bytes = [], c = 0; c < hex.length; c += 2)
|
||||
bytes.push(parseInt(hex.substr(c, 2), 16))
|
||||
return bytes
|
||||
}
|
||||
|
||||
|
||||
function hex2ascii(hexx) {
|
||||
let hex = hexx.toString();//force conversion
|
||||
let str = ''
|
||||
for (var i = 0; i < hex.length; i += 2)
|
||||
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16))
|
||||
return str
|
||||
}
|
||||
|
||||
const formatDate = (date, type) => {
|
||||
var inputDate = new Date(date);
|
||||
|
||||
let tanggal = inputDate.getDate()
|
||||
let bulan = inputDate.getMonth() + 1
|
||||
let tahun = inputDate.getFullYear()
|
||||
|
||||
let jam = inputDate.getHours()
|
||||
let menit = inputDate.getMinutes()
|
||||
let detik = inputDate.getSeconds()
|
||||
|
||||
if (bulan.toString().length < 2) bulan = '0' + bulan
|
||||
if (tanggal.toString().length < 2) tanggal = '0' + tanggal
|
||||
if (jam.toString().length < 2) jam = '0' + jam
|
||||
if (menit.toString().length < 2) menit = '0' + menit
|
||||
if (detik.toString().length < 2) detik = '0' + detik
|
||||
|
||||
let formatTanggal = [tahun, bulan, tanggal].join('')
|
||||
let formatWaktu = [jam, menit, detik].join('')
|
||||
|
||||
return [formatTanggal, formatWaktu].join('')
|
||||
}
|
||||
|
||||
function getTranscode(cardData, nominal){
|
||||
let trxType = Buffer.from([0x02])
|
||||
let uid = Buffer.alloc(8)
|
||||
let cardType = Buffer.alloc(2)
|
||||
|
||||
var cardNumber = Buffer.alloc(16)
|
||||
cardData.copy(cardNumber, 0, 12+16, 12+16+16)
|
||||
|
||||
cardNumber = cardNumber.toString()
|
||||
|
||||
cardData.copy(uid, 0, 1,9)
|
||||
let _cardNumber = Buffer.from(hexToBytes(cardNumber))
|
||||
|
||||
var balanceArray = Buffer.alloc(4)
|
||||
var balanceArrayExis = Buffer.alloc(4)
|
||||
var exec_idArray = Buffer.alloc(2)
|
||||
|
||||
cardData.copy(balanceArray, 0, 12+16+16, 12+16+16+4)
|
||||
cardData.copy(balanceArrayExis, 0, 12+16+16, 12+16+16+4)
|
||||
exec_idArray[1] = cardData[cardData.length -1]
|
||||
exec_idArray[0] = cardData[cardData.length -2]
|
||||
|
||||
let balanceExisting = balanceArrayExis.reverse()
|
||||
let nominalStr = Buffer.from(hexToBytes(String(nominal).padStart(8, '0')))
|
||||
|
||||
let balance = Buffer.from(balanceArray).readInt32LE()
|
||||
balance += parseInt(nominal)
|
||||
balanceArray.writeInt32LE(balance)
|
||||
let balanceAfter = balanceArray.reverse()
|
||||
|
||||
let dateTime = Buffer.from(hexToBytes(formatDate(new Date())))
|
||||
|
||||
cardData.copy(cardType,0, 1 + 8 + 3 + 1, 1 + 8 + 3 + 1 + 2)
|
||||
|
||||
let samID = Buffer.alloc(8)
|
||||
let samBalBefore = Buffer.alloc(4)
|
||||
let samBalAfter = Buffer.alloc(4)
|
||||
|
||||
let exec_id = exec_idArray.readUInt16BE()
|
||||
exec_id++
|
||||
|
||||
exec_idArray.writeUInt16BE(exec_id)
|
||||
|
||||
let _transcode = Buffer.concat([trxType, _cardNumber, balanceExisting, nominalStr, balanceAfter,dateTime,
|
||||
cardType, uid, samID, samBalBefore, samBalAfter, exec_idArray])
|
||||
return _transcode
|
||||
}
|
||||
|
||||
const logging = (date, title, message, id = 0) => {
|
||||
let month = date.getMonth() + 1;
|
||||
|
||||
try {
|
||||
//create folder/file if not exists
|
||||
if (!fs.existsSync(`./logs`)) {
|
||||
fs.mkdirSync(`./logs`)
|
||||
}
|
||||
if (!fs.existsSync(`./logs/log-${month}`)) {
|
||||
fs.mkdirSync(`./logs/log-${month}`)
|
||||
}
|
||||
|
||||
if (message.command) {
|
||||
message.command = buf2hex(message.command)
|
||||
}
|
||||
|
||||
let content = `[${formatDate(date)}] | { "id": ${id}, "title": ${title}, "message": ${message} }`;
|
||||
|
||||
fs.writeFileSync(`./logs/log-${month}/log.txt`, '\n' + content, {flag: 'a+'});
|
||||
|
||||
return
|
||||
} catch (err) {
|
||||
console.error("Error from logging: ", err.message);
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
makeRequestData,
|
||||
getResponseCode,
|
||||
getResponseData,
|
||||
buf2hex,
|
||||
hexToBytes,
|
||||
hex2ascii,
|
||||
getTranscode,
|
||||
logging
|
||||
}
|
||||
@@ -1,29 +0,0 @@
|
||||
const { Router } = require("express")
|
||||
const router = Router()
|
||||
|
||||
const _readData = require('../controller/readData')
|
||||
const _readDataResp = require('../controller/readDataResp')
|
||||
|
||||
const _auth1 = require('../controller/authenticate1')
|
||||
const _auth2 = require('../controller/authenticate2')
|
||||
const _authResp = require('../controller/authenticateResp')
|
||||
|
||||
const _topup = require('../controller/topup')
|
||||
const _topupResp = require('../controller/topupResp')
|
||||
|
||||
const _end = require('../controller/endTranscation')
|
||||
|
||||
router.post('/read', _readData)
|
||||
router.post('/readResp', _readDataResp)
|
||||
|
||||
router.post('/auth1', _auth1)
|
||||
router.post('/auth2', _auth2)
|
||||
router.post('/authResp', _authResp)
|
||||
|
||||
router.post('/topup', _topup)
|
||||
router.post('/topupResp', _topupResp)
|
||||
|
||||
router.post('/end',_end)
|
||||
|
||||
|
||||
module.exports = router
|
||||
@@ -1,50 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIE7jCCA9agAwIBAgIJIrmxYwzstDwuMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV
|
||||
BAYTAkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMScw
|
||||
JQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTIwHhcNMTkwOTI3
|
||||
MDE1NDIzWhcNMjkwNTI5MDUwMDM5WjBeMQswCQYDVQQGEwJKUDEjMCEGA1UEChMa
|
||||
Q3liZXJ0cnVzdCBKYXBhbiBDby4sIEx0ZC4xKjAoBgNVBAMTIUN5YmVydHJ1c3Qg
|
||||
SmFwYW4gU3VyZVNlcnZlciBDQSBHNDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
|
||||
AQoCggEBAMtunFmosT8IxBkVFP+OnkGkcVmbui+hdVBlGZhniniVluAhigm2WUxx
|
||||
p4X5V3B/QKJLZmeAswmzxGKXaDCzcomYxXTygNXcTLI+IMyRisEO7V1NXFHUjSEl
|
||||
KaY1LzCA9/emldnmRjX6B9Zt5xXK5q12WOIWkJECEwwKku77tvtKZPRKaCNCGsZ5
|
||||
Hja7PBs07jLoE0rMuZLQZNQEB0W63attKGCGzEk50lDj+wQ0UlUbQk3zAEsvdE6X
|
||||
o1qZy9l783Va40vSx3VqhGYb4jWQrg2CrAtJcKQNSJ0m9yxJVVQDwpQQwGxHO5Em
|
||||
Qv1LGJExASegOXzhzqCr5yiwECfSrOsCAwEAAaOCAa4wggGqMB0GA1UdDgQWBBRi
|
||||
p9La3oW2kvGFvPbolZ11oPpOHzAfBgNVHSMEGDAWgBQKhal3ZQWYfECB+A+XLDjx
|
||||
Cuw8zzASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjBJBgNVHR8E
|
||||
QjBAMD6gPKA6hjhodHRwOi8vcmVwb3NpdG9yeS5zZWNvbXRydXN0Lm5ldC9TQy1S
|
||||
b290Mi9TQ1Jvb3QyQ1JMLmNybDBSBgNVHSAESzBJMEcGCiqDCIybG2SHBQQwOTA3
|
||||
BggrBgEFBQcCARYraHR0cHM6Ly9yZXBvc2l0b3J5LnNlY29tdHJ1c3QubmV0L1ND
|
||||
LVJvb3QyLzCBhQYIKwYBBQUHAQEEeTB3MDAGCCsGAQUFBzABhiRodHRwOi8vc2Ny
|
||||
b290Y2EyLm9jc3Auc2Vjb210cnVzdC5uZXQwQwYIKwYBBQUHMAKGN2h0dHA6Ly9y
|
||||
ZXBvc2l0b3J5LnNlY29tdHJ1c3QubmV0L1NDLVJvb3QyL1NDUm9vdDJjYS5jZXIw
|
||||
HQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IB
|
||||
AQDFUXkuQAZKY5Pb/JvgufizJ8uZKpN++fiI8kOTgkrSriNYNjO9iEdTwVV3sW3P
|
||||
abr3lAdCGrJ+wgArLLUnBZ7VGM//UlDhTRe4A19c0TmV1udTSbxabwQJbN1zIGbG
|
||||
3KQsumg9/70PaIkawnihx9/TxGCrJkAH5W+9pkX7OWefsahylwiPkKRkJRv2em/v
|
||||
rMRyb3LxRU5t84k1xQqCnMxTEWOAiWoOtatExZ38a8kn8kqiE1NEvtPOzSrVjSvD
|
||||
7pH56AlvO7hzGzng60kyWnAz6O5rQ0tsFIgW9xloWTQQVcfEtzvjc8ptuP9onkbA
|
||||
jMRDJaqLXrIVtB7GMek7S6AO
|
||||
-----END CERTIFICATE-----
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl
|
||||
MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe
|
||||
U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX
|
||||
DTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy
|
||||
dXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj
|
||||
YXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV
|
||||
OVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr
|
||||
zbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM
|
||||
VAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ
|
||||
hNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO
|
||||
ojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw
|
||||
awNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs
|
||||
OPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3
|
||||
DQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF
|
||||
coJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc
|
||||
okgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8
|
||||
t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy
|
||||
1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/
|
||||
SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03
|
||||
-----END CERTIFICATE-----
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,235 +0,0 @@
|
||||
const knex = require("../../infrastructure/database/knex");
|
||||
const jwt = require("../middlewares/jwt.middleware");
|
||||
const { body, validationResult } = require("express-validator");
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "login": {
|
||||
return [
|
||||
body("username").not().isEmpty().withMessage("Username ID is required"),
|
||||
body("password").not().isEmpty().withMessage("Password is required"),
|
||||
body("user_group_id")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("User Group ID is required"),
|
||||
];
|
||||
}
|
||||
case "register": {
|
||||
return [
|
||||
body("username").not().isEmpty().withMessage("Username ID is required"),
|
||||
body("password")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Username Name is required")
|
||||
.isLength({ min: 5 })
|
||||
.withMessage("Password must be least 5 characters"),
|
||||
body("user_group_id")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("User Group ID is required"),
|
||||
];
|
||||
}
|
||||
case "token": {
|
||||
return [
|
||||
body("refresh_token")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Refresh Token is required"),
|
||||
];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// REFRESH TOKEN
|
||||
const token = (req, res) => {
|
||||
try {
|
||||
const { refresh_token } = req.body;
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
code: "01",
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
// verify
|
||||
jwt.authenticateRefreshToken;
|
||||
|
||||
let result = knex
|
||||
.select()
|
||||
.from("core.t_mtr_user")
|
||||
.where("last_token_text", refresh_token)
|
||||
.where("active_boo", true)
|
||||
.first();
|
||||
if (result.count() > 0) {
|
||||
let accessToken = jwt.generateAccessToken({
|
||||
user_id: result.user_id,
|
||||
username: result.username,
|
||||
user_group_id: result.user_group_id,
|
||||
});
|
||||
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "New Token has been generated.",
|
||||
data: {
|
||||
access_token: accessToken,
|
||||
user: {
|
||||
username: result.username_var,
|
||||
user_group_id: result.user_group_id_int,
|
||||
fullname: result.fullname_var,
|
||||
email: result.email_var,
|
||||
phone: result.phone_var,
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Refresh Token is not available.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// LOGIN
|
||||
const login = async (req, res, next) => {
|
||||
try {
|
||||
let { username, password, user_group_id } = req.body;
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
code: "01",
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
let result = await knex
|
||||
.select()
|
||||
.from("core.t_mtr_user")
|
||||
.where("username_var", username)
|
||||
.where("user_group_id_int", user_group_id)
|
||||
.where("active_boo", true)
|
||||
.first();
|
||||
if (result) {
|
||||
let accessToken = jwt.generateAccessToken({
|
||||
user_id: result.user_id_seq,
|
||||
username: result.username_var,
|
||||
user_group_id: result.user_group_id_int,
|
||||
});
|
||||
|
||||
let refreshToken = jwt.generateRefreshToken({
|
||||
user_id: result.user_id_seq,
|
||||
username: result.username_var,
|
||||
user_group_id: result.user_group_id_int,
|
||||
});
|
||||
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Login Success.",
|
||||
data: {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
user: {
|
||||
username: result.username_var,
|
||||
user_group_id: result.user_group_id_int,
|
||||
fullname: result.fullname_var,
|
||||
email: result.email_var,
|
||||
phone: result.phone_var,
|
||||
},
|
||||
},
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "User not registered.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// REGISTER
|
||||
const register = async (req, res) => {
|
||||
try {
|
||||
let {
|
||||
username,
|
||||
password,
|
||||
user_group_id,
|
||||
fullname,
|
||||
email,
|
||||
phone,
|
||||
} = req.body;
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
code: "01",
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
let find = await knex("core.t_mtr_user")
|
||||
.where("username", username)
|
||||
.first();
|
||||
|
||||
if (!find) {
|
||||
let result = await knex("core.t_mtr_user").insert({
|
||||
user_id_seq: username,
|
||||
password_var: password,
|
||||
user_group_id_id: user_group_id,
|
||||
fullname_var: fullname,
|
||||
email_var: email,
|
||||
phone_var: phone,
|
||||
active_boo: true,
|
||||
created_by_var: "REGISTER FORM",
|
||||
});
|
||||
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data has been saved.",
|
||||
data: result.command,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Data already exist",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
login,
|
||||
register,
|
||||
token,
|
||||
};
|
||||
@@ -1,80 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let felicaPollingResponse = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
let _timeOut = false;
|
||||
|
||||
let _validasi = body.requestData.slice(4, 20)
|
||||
|
||||
let transactionId = Buffer.from([0x00, 0x00]);
|
||||
let apiId = Buffer.from([0x01]);
|
||||
reqData = generate.makeRequestData(transactionId, apiId, felicaPollingResponse);
|
||||
|
||||
client.sendData(reqData)
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
setInterval(function () {
|
||||
respData = Buffer.from([
|
||||
0x00, 0x00, 0x00, 0x00,
|
||||
0x00, 0x00, 0x00, 0x00
|
||||
])
|
||||
_timeOut = true
|
||||
}, 10000);
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14, 30)
|
||||
while (message[2] == 1 && _stopMessage == 1 && _validasi.toLowerCase() == __validasi.toLowerCase()) {
|
||||
respData = null
|
||||
console.log('*WS MESSAGE Auth1v2: ' + generate.buf2hex(message));
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
if (_timeOut) {
|
||||
return res.status(200).send({
|
||||
status: "99",
|
||||
message: "Timeout",
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: "Request Authenticate 1 Success",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "02",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,68 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let _validationTrxID = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
|
||||
if (auth2v2requestData[0] != 0x41) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: "Wrong Respone from Card",
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x02]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, auth2v2requestData);
|
||||
|
||||
client.sendData(reqData);
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 2 && message[0] == _validationTrxID[0] && message[1] == _validationTrxID[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Auth2v2: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: "Request Authenticate 2 Success",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,69 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let auth2v2responseSetData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
console.log('Req Auth Resp: ' + body.requestData);
|
||||
|
||||
if (auth2v2responseSetData[0] != 0x43) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: "Wrong Respone from Card",
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x03]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, auth2v2responseSetData);
|
||||
|
||||
client.sendData(reqData);
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 3 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Auth2v2 Resp: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while(respData == null){
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: "Request Authenticate Resp Success",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,59 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
|
||||
let transactionEnd = Buffer.from([]);
|
||||
let apiId = Buffer.from([0x06]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, transactionEnd);
|
||||
let _stopMessage = 1;
|
||||
|
||||
client.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 6 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE EndTrx: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while(respData == null){
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: "End Transaction Success",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,61 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
|
||||
let apiId = Buffer.from([0x04]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, trxrequestData);
|
||||
|
||||
client.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 4 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Transmit Packet: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while(respData == null){
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,67 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let packet = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
if (packet[0] != 0x45) {
|
||||
return {
|
||||
status: "03",
|
||||
message: "Respone Card Wrong",
|
||||
data: {}
|
||||
}
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x05]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, packet);
|
||||
client.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 5 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Received Packet: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,61 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
|
||||
let apiId = Buffer.from([0x04]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, trxrequestData);
|
||||
|
||||
client.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 4 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Transmit Packet: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while(respData == null){
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: 'Generate Write Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,79 +0,0 @@
|
||||
const { client } = require('./services/webSocket')
|
||||
const generate = require('./utils/utils')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let packet = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
if (packet[0] != 0x47) {
|
||||
return {
|
||||
status: "03",
|
||||
message: "Respone Card Wrong",
|
||||
data: {}
|
||||
}
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x05]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, packet);
|
||||
client.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
client.ws.on('message', (message) => {
|
||||
while(message[2] == 5 && message[0] == transactionId[0] && message[1] == transactionId[1] && _stopMessage == 1){
|
||||
respData = null;
|
||||
console.log('*WS MESSAGE Received Packet: ' + generate.buf2hex(message));
|
||||
respData = message
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
if (respData[6] != 0x47 || (respData1[9] != 0x00 && respData1[10] != 0x00)){
|
||||
return res.status(200).send({
|
||||
status: "02",
|
||||
message: "Gagal",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respData1.slice(6,10),
|
||||
transcode: null
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return res.status(200).send({
|
||||
status: "00",
|
||||
message: 'Topup Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length/2,
|
||||
}
|
||||
})
|
||||
|
||||
} catch (error) {
|
||||
return res.status(200).send({
|
||||
status: "01",
|
||||
message: error.message,
|
||||
data: {}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,233 +0,0 @@
|
||||
const knex = require("../../infrastructure/database/knex");
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "createPaymentChannel": {
|
||||
return [
|
||||
body("payment_channel_id")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Payment Channel ID is required")
|
||||
.matches("[0-9]")
|
||||
.withMessage("Payment Channel ID is invalid format"),
|
||||
body("payment_channel_name")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Payment Channel Name is required"),
|
||||
];
|
||||
}
|
||||
case "updatePaymentChannel": {
|
||||
return [
|
||||
param("id", "ID data is invalid format").matches("[0-9]"),
|
||||
body("payment_channel_id")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Payment Channel ID is required")
|
||||
.matches("[0-9]")
|
||||
.withMessage("Payment Channel ID is invalid format"),
|
||||
body("payment_channel_name")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Payment Channel Name is required"),
|
||||
];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// SHOW ALL DATA
|
||||
const getPaymentChannels = async (req, res) => {
|
||||
try {
|
||||
let result = await knex.select().from("mtr.t_mtr_payment_channel");
|
||||
if (result) {
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data found.",
|
||||
data: result,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Data not found.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// SHOW DATA BY ID
|
||||
const getPaymentChannelById = async (req, res) => {
|
||||
try {
|
||||
let id = req.params.id;
|
||||
|
||||
let result = await knex
|
||||
.select()
|
||||
.from("mtr.t_mtr_payment_channel")
|
||||
.where("payment_channel_id_seq", id)
|
||||
.first();
|
||||
if (result) {
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data found.",
|
||||
data: result,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Data not found.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// CREATED NEW DATA
|
||||
const createPaymentChannel = async (req, res) => {
|
||||
try {
|
||||
let { payment_channel_id, payment_channel_name, logo } = req.body;
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
code: "01",
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
let find = await knex("mtr.t_mtr_payment_channel")
|
||||
.where("payment_channel_id_seq", payment_channel_id)
|
||||
.orWhere("payment_channel_name_var", payment_channel_name)
|
||||
.first();
|
||||
|
||||
if (!find) {
|
||||
let result = await knex("mtr.t_mtr_payment_channel").insert({
|
||||
payment_channel_id_seq: payment_channel_id,
|
||||
payment_channel_name_var: payment_channel_name,
|
||||
logo_txt: logo,
|
||||
active_boo: true,
|
||||
created_by_var: "",
|
||||
});
|
||||
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data has been saved.",
|
||||
data: result.command,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Data already exist",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// UDPATE DATA BY ID
|
||||
const updatePaymentChannel = async (req, res) => {
|
||||
try {
|
||||
let id = req.params.id;
|
||||
let { payment_channel_id, payment_channel_name, logo } = req.body;
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
code: "01",
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
let result = await knex("mtr.t_mtr_payment_channel")
|
||||
.where("payment_channel_id_seq", id)
|
||||
.update({
|
||||
payment_channel_id_seq: payment_channel_id,
|
||||
payment_channel_name_var: payment_channel_name,
|
||||
logo_txt: logo,
|
||||
active_boo: true,
|
||||
updated_by_var: "",
|
||||
});
|
||||
|
||||
if (result) {
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data has been updated.",
|
||||
data: result,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "No Data updated",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// DELETE DATA BY ID
|
||||
const deletePaymentChannel = async (req, res) => {
|
||||
try {
|
||||
let id = req.params.id;
|
||||
|
||||
let result = await knex("mtr.t_mtr_payment_channel")
|
||||
.where("payment_channel_id_seq", id)
|
||||
.del();
|
||||
|
||||
if (result) {
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data has been deleted.",
|
||||
data: result,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "No Data deleted",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
getPaymentChannels,
|
||||
getPaymentChannelById,
|
||||
createPaymentChannel,
|
||||
updatePaymentChannel,
|
||||
deletePaymentChannel,
|
||||
};
|
||||
@@ -1,132 +0,0 @@
|
||||
const WebSocket = require('ws')
|
||||
const fs = require('fs')
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
||||
const generate = require('../utils/utils')
|
||||
|
||||
let ssl_ca_crt = './app/assets/cert/CACerts.pem'
|
||||
let ssl_client_pfx = './app/assets/cert/FeliqClient0002-02.pfx';
|
||||
let options = {
|
||||
ca : fs.readFileSync(ssl_ca_crt),
|
||||
agent: false,
|
||||
passphrase : "GPqs+Uia78",
|
||||
pfx : fs.readFileSync(ssl_client_pfx),
|
||||
};
|
||||
let url = 'wss://gateway04.cyberware.co.jp/feliqserver/v1/wsapi';
|
||||
|
||||
class WebSocketClient{
|
||||
|
||||
ws = null;
|
||||
clientAuthenticated = false;
|
||||
|
||||
// Connection of WebSocket
|
||||
open = () => {
|
||||
this.ws = new WebSocket(url, [], options);
|
||||
this.ws.on('open', this.onOpen);
|
||||
this.ws.on('close', this.onClose);
|
||||
}
|
||||
// Disconnection of WebSocket
|
||||
close = () => {
|
||||
this.ws.close();
|
||||
console.log('WebSocket Close');
|
||||
}
|
||||
|
||||
// Open event
|
||||
onOpen = () => {
|
||||
console.log('WebSocket Open');
|
||||
this.isOpened();
|
||||
if(!this.clientAuthenticated){
|
||||
this.clientAuth();
|
||||
}
|
||||
}
|
||||
|
||||
onClose = () => {
|
||||
console.log('WebSocket Close');
|
||||
this.clientAuthenticated = false;
|
||||
this.isOpened();
|
||||
this.open();
|
||||
}
|
||||
|
||||
// Connection check
|
||||
isOpened = () => {
|
||||
return this.ws.readyState == WebSocket.OPEN;
|
||||
}
|
||||
|
||||
// Received data check
|
||||
isReceive(){
|
||||
return this.receiveData != null;
|
||||
}
|
||||
|
||||
// Acquiring received data
|
||||
getReceiveData(){
|
||||
return this.receiveData;
|
||||
}
|
||||
|
||||
clearReceiveData(){
|
||||
this.receiveData = null;
|
||||
}
|
||||
|
||||
// Send data
|
||||
sendData(data){
|
||||
this.receiveData = null;
|
||||
this.ws.send(data);
|
||||
}
|
||||
|
||||
async clientAuth(){
|
||||
try{
|
||||
const authHead = Buffer.alloc(2);
|
||||
// Set system code (when 0x0000)
|
||||
authHead[0] = 0x93;
|
||||
authHead[1] = 0x9E;
|
||||
// Set API key
|
||||
//const apiKeyBytes = Buffer.from('82002732-9148-34e5-843b-c639a0c88cc5-0TC') // T4
|
||||
const apiKeyBytes = Buffer.from('4c6dd075-dbcb-375f-81f7-62990a5d7000-0TC') // Nutech
|
||||
// Secret setting
|
||||
//const secretBytes = Buffer.from('TdtSo/i5ZmbwPr82gt4fElK96lV9ClVo7votHKMIUuo='); // T4
|
||||
const secretBytes = Buffer.from('U5xs7nVonhtbQ+XiYATRSg8Nk5sPu1IpVx7X40KyWiw='); // Nutech
|
||||
|
||||
const authData = Buffer.concat([authHead, apiKeyBytes, secretBytes]);
|
||||
|
||||
let transactionId = Buffer.from([0x00, 0x00]);
|
||||
let apiId = Buffer.from([0x00]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, authData);
|
||||
|
||||
let respData = null;
|
||||
let _stopMessage = 1;
|
||||
|
||||
this.sendData(reqData);
|
||||
|
||||
this.ws.on('message', (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14,30)
|
||||
while(message[2] == 0 && _stopMessage == 1 && message[0] == 0 && message[1] == 0){
|
||||
respData = null
|
||||
console.log('*WS MESSAGE Tenan: ' + generate.buf2hex(message));
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
})
|
||||
|
||||
while(respData == null){
|
||||
await _sleep(10);
|
||||
}
|
||||
let respCode = generate.getResponseCode(respData);
|
||||
console.log(`Resp Data Tenant = ${respCode}`)
|
||||
|
||||
if (respCode == "0000" || respCode == "0502") this.clientAuthenticated = true;
|
||||
console.log(`clientAuthenticated = ${this.clientAuthenticated}`);
|
||||
}catch (error) {
|
||||
console.log(`error ${error}`)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
const client = new WebSocketClient();
|
||||
client.open();
|
||||
|
||||
setInterval(function(){
|
||||
client.clientAuth()
|
||||
}, 59000);
|
||||
|
||||
module.exports = {
|
||||
client
|
||||
};
|
||||
@@ -1,241 +0,0 @@
|
||||
const knex = require("../../infrastructure/database/knex");
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "createUser": {
|
||||
return [
|
||||
body("user_id")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Payment Channel ID is required")
|
||||
.matches("[0-9]")
|
||||
.withMessage("Payment Channel ID is invalid format"),
|
||||
body("username")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Payment Channel Name is required"),
|
||||
];
|
||||
}
|
||||
case "updateUser": {
|
||||
return [
|
||||
param("id", "ID data is invalid format").matches("[0-9]"),
|
||||
body("user_id")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Payment Channel ID is required")
|
||||
.matches("[0-9]")
|
||||
.withMessage("Payment Channel ID is invalid format"),
|
||||
body("username")
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Payment Channel Name is required"),
|
||||
];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// SHOW ALL DATA
|
||||
const getUsers = async (req, res) => {
|
||||
try {
|
||||
let result = await knex.select().from("core.t_mtr_user");
|
||||
if (result) {
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data found.",
|
||||
data: result,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Data not found.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// SHOW DATA BY ID
|
||||
const getUserById = async (req, res) => {
|
||||
try {
|
||||
let id = req.params.id;
|
||||
|
||||
let result = await knex
|
||||
.select()
|
||||
.from("core.t_mtr_user")
|
||||
.where("user_id_seq", id)
|
||||
.first();
|
||||
if (result) {
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data found.",
|
||||
data: result,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Data not found.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// CREATED NEW DATA
|
||||
const createUser = async (req, res) => {
|
||||
try {
|
||||
let {
|
||||
username,
|
||||
password,
|
||||
user_group_id,
|
||||
fullname,
|
||||
email,
|
||||
phone,
|
||||
} = req.body;
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
code: "01",
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
let find = await knex("core.t_mtr_user")
|
||||
.where("username", username)
|
||||
.first();
|
||||
|
||||
if (!find) {
|
||||
let result = await knex("core.t_mtr_user").insert({
|
||||
username_var: username,
|
||||
password_var: password,
|
||||
user_group_id_int: user_group_id,
|
||||
fullname_var: fullname,
|
||||
email_var: email,
|
||||
phone_var: phone,
|
||||
active_boo: true,
|
||||
created_by_var: "",
|
||||
});
|
||||
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data has been saved.",
|
||||
data: result.command,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "User already exist",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// UDPATE DATA BY ID
|
||||
const updateUser = async (req, res) => {
|
||||
try {
|
||||
let id = req.params.id;
|
||||
let { username, logo } = req.body;
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
return res.status(400).json({
|
||||
code: "01",
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
let result = await knex("core.t_mtr_user").where("user_id_seq", id).update({
|
||||
username_var: username,
|
||||
password_var: password,
|
||||
user_group_id_int: user_group_id,
|
||||
fullname_var: fullname,
|
||||
email_var: email,
|
||||
phone_var: phone,
|
||||
active_boo: true,
|
||||
updated_by_var: "",
|
||||
});
|
||||
|
||||
if (result) {
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data has been updated.",
|
||||
data: result,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "No Data updated",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// DELETE DATA BY ID
|
||||
const deleteUser = async (req, res) => {
|
||||
try {
|
||||
let id = req.params.id;
|
||||
|
||||
let result = await knex("core.t_mtr_user").where("user_id_seq", id).del();
|
||||
|
||||
if (result) {
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "Data has been deleted.",
|
||||
data: result,
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "No Data deleted",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: error.message,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
getUsers,
|
||||
getUserById,
|
||||
createUser,
|
||||
updateUser,
|
||||
deleteUser,
|
||||
};
|
||||
@@ -1,157 +0,0 @@
|
||||
const { Buffer } = require("buffer")
|
||||
const fs = require('fs')
|
||||
|
||||
// Generate request data for FeliQ Server
|
||||
function makeRequestData(transactionId, apiId, data){
|
||||
let request = Buffer.alloc(2 + 1 + 1 + data.length)
|
||||
let dataSize = Buffer.alloc(1)
|
||||
dataSize[0] = data.length
|
||||
request = Buffer.concat([transactionId, apiId, dataSize, data])
|
||||
return request;
|
||||
}
|
||||
|
||||
// Extract response code from API response data
|
||||
function getResponseCode(data){
|
||||
let respCode = Buffer.alloc(2)
|
||||
respCode[0] = data[3]
|
||||
respCode[1] = data[4]
|
||||
return buf2hex(respCode)
|
||||
}
|
||||
|
||||
// Extract response data from API response data
|
||||
function getResponseData(apiData){
|
||||
let data = Buffer.alloc(apiData[5])
|
||||
apiData.copy(data, 0, 6, apiData[5]+6)
|
||||
return buf2hex(data);
|
||||
}
|
||||
|
||||
|
||||
function buf2hex(buffer){ // buffer is an ArrayBuffer
|
||||
return [...new Uint8Array(buffer)]
|
||||
.map(x => x.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
}
|
||||
|
||||
function hexToBytes(hex) {
|
||||
for (var bytes = [], c = 0; c < hex.length; c += 2)
|
||||
bytes.push(parseInt(hex.substr(c, 2), 16))
|
||||
return bytes
|
||||
}
|
||||
|
||||
|
||||
function hex2ascii(hexx) {
|
||||
let hex = hexx.toString();//force conversion
|
||||
let str = ''
|
||||
for (var i = 0; i < hex.length; i += 2)
|
||||
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16))
|
||||
return str
|
||||
}
|
||||
|
||||
const formatDate = (date, type) => {
|
||||
var inputDate = new Date(date);
|
||||
|
||||
let tanggal = inputDate.getDate()
|
||||
let bulan = inputDate.getMonth() + 1
|
||||
let tahun = inputDate.getFullYear()
|
||||
|
||||
let jam = inputDate.getHours()
|
||||
let menit = inputDate.getMinutes()
|
||||
let detik = inputDate.getSeconds()
|
||||
|
||||
if (bulan.toString().length < 2) bulan = '0' + bulan
|
||||
if (tanggal.toString().length < 2) tanggal = '0' + tanggal
|
||||
if (jam.toString().length < 2) jam = '0' + jam
|
||||
if (menit.toString().length < 2) menit = '0' + menit
|
||||
if (detik.toString().length < 2) detik = '0' + detik
|
||||
|
||||
let formatTanggal = [tahun, bulan, tanggal].join('')
|
||||
let formatWaktu = [jam, menit, detik].join('')
|
||||
|
||||
return [formatTanggal, formatWaktu].join('')
|
||||
}
|
||||
|
||||
function getTranscode(cardData, nominal){
|
||||
let trxType = Buffer.from([0x02])
|
||||
let uid = Buffer.alloc(8)
|
||||
let cardType = Buffer.alloc(2)
|
||||
|
||||
var cardNumber = Buffer.alloc(16)
|
||||
cardData.copy(cardNumber, 0, 12+16, 12+16+16)
|
||||
|
||||
cardNumber = cardNumber.toString()
|
||||
|
||||
cardData.copy(uid, 0, 1,9)
|
||||
let _cardNumber = Buffer.from(hexToBytes(cardNumber))
|
||||
|
||||
var balanceArray = Buffer.alloc(4)
|
||||
var balanceArrayExis = Buffer.alloc(4)
|
||||
var exec_idArray = Buffer.alloc(2)
|
||||
|
||||
cardData.copy(balanceArray, 0, 12+16+16, 12+16+16+4)
|
||||
cardData.copy(balanceArrayExis, 0, 12+16+16, 12+16+16+4)
|
||||
exec_idArray[1] = cardData[cardData.length -1]
|
||||
exec_idArray[0] = cardData[cardData.length -2]
|
||||
|
||||
let balanceExisting = balanceArrayExis.reverse()
|
||||
let nominalStr = Buffer.from(hexToBytes(String(nominal).padStart(8, '0')))
|
||||
|
||||
let balance = Buffer.from(balanceArray).readInt32LE()
|
||||
balance += parseInt(nominal)
|
||||
balanceArray.writeInt32LE(balance)
|
||||
let balanceAfter = balanceArray.reverse()
|
||||
|
||||
let dateTime = Buffer.from(hexToBytes(formatDate(new Date())))
|
||||
|
||||
cardData.copy(cardType,0, 1 + 8 + 3 + 1, 1 + 8 + 3 + 1 + 2)
|
||||
|
||||
let samID = Buffer.alloc(8)
|
||||
let samBalBefore = Buffer.alloc(4)
|
||||
let samBalAfter = Buffer.alloc(4)
|
||||
|
||||
let exec_id = exec_idArray.readUInt16BE()
|
||||
exec_id++
|
||||
|
||||
exec_idArray.writeUInt16BE(exec_id)
|
||||
|
||||
let _transcode = Buffer.concat([trxType, _cardNumber, balanceExisting, nominalStr, balanceAfter,dateTime,
|
||||
cardType, uid, samID, samBalBefore, samBalAfter, exec_idArray])
|
||||
return _transcode
|
||||
}
|
||||
|
||||
const logging = (date, title, message, id = 0) => {
|
||||
let month = date.getMonth() + 1;
|
||||
|
||||
try {
|
||||
//create folder/file if not exists
|
||||
if (!fs.existsSync(`./logs`)) {
|
||||
fs.mkdirSync(`./logs`)
|
||||
}
|
||||
if (!fs.existsSync(`./logs/log-${month}`)) {
|
||||
fs.mkdirSync(`./logs/log-${month}`)
|
||||
}
|
||||
|
||||
if (message.command) {
|
||||
message.command = buf2hex(message.command)
|
||||
}
|
||||
|
||||
let content = `[${formatDate(date)}] | { "id": ${id}, "title": ${title}, "message": ${message} }`;
|
||||
|
||||
fs.writeFileSync(`./logs/log-${month}/log.txt`, '\n' + content, {flag: 'a+'});
|
||||
|
||||
return
|
||||
} catch (err) {
|
||||
console.error("Error from logging: ", err.message);
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
makeRequestData,
|
||||
getResponseCode,
|
||||
getResponseData,
|
||||
buf2hex,
|
||||
hexToBytes,
|
||||
hex2ascii,
|
||||
getTranscode,
|
||||
logging
|
||||
}
|
||||
@@ -1,83 +0,0 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
|
||||
const generateRefreshToken = (req) => {
|
||||
return jwt.sign(req, process.env.REFRESH_TOKEN_SECRET);
|
||||
};
|
||||
|
||||
const authenticateRefreshToken = (req, res, next) => {
|
||||
jwt.verify(req.token, process.env.REFRESH_TOKEN_SECRET, (err, data) => {
|
||||
if (err) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Invalid Token",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
};
|
||||
|
||||
const generateAccessToken = (req) => {
|
||||
let expiresIn = process.env.EXPIRE_JWT ? process.env.EXPIRE_JWT : "1d";
|
||||
if (req.user_group_id == "1") {
|
||||
expiresIn = process.env.EXPIRE_JWT_ADMIN_WEB;
|
||||
} else if (req.user_group_id == "2") {
|
||||
expiresIn = process.env.EXPIRE_JWT_MOBILE_PHONE;
|
||||
} else if (
|
||||
req.user_group_id == "3" ||
|
||||
req.user_group_id == "4" ||
|
||||
req.user_group_id == "5"
|
||||
) {
|
||||
expiresIn = process.env.EXPIRE_JWT_TERMINAL;
|
||||
}
|
||||
|
||||
return jwt.sign(req, process.env.TOKEN_SECRET, {
|
||||
expiresIn: expiresIn,
|
||||
});
|
||||
};
|
||||
|
||||
const authenticateToken = async (req, res, next) => {
|
||||
let authHeader = req.headers["authorization"];
|
||||
|
||||
if (authHeader) {
|
||||
let token = authHeader && authHeader.split(" ")[1];
|
||||
|
||||
if (!token) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Token is required",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
await jwt.verify(token, process.env.TOKEN_SECRET, (err, data) => {
|
||||
if (err) {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Invalid Token",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
req.user_id = data.user_id;
|
||||
req.username = data.username;
|
||||
req.user_group_id = data.user_group_id;
|
||||
|
||||
next();
|
||||
});
|
||||
} else {
|
||||
return res.json({
|
||||
code: "01",
|
||||
message: "Header not found",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
generateRefreshToken,
|
||||
authenticateRefreshToken,
|
||||
generateAccessToken,
|
||||
authenticateToken,
|
||||
};
|
||||
@@ -1,10 +0,0 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const controller = require("../controllers/auth");
|
||||
|
||||
// ============================== AUTH ==============================
|
||||
router.post("/login", controller.validate("login"), controller.login);
|
||||
router.post("/register", controller.validate("register"), controller.register);
|
||||
router.post("/token", controller.validate("token"), controller.token);
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,25 +0,0 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const auth = require("../middlewares/jwt.middleware");
|
||||
const controller = require("../controllers/user");
|
||||
|
||||
// ============================== USER ==============================
|
||||
router.get("/user", auth.authenticateToken, controller.getUsers);
|
||||
router.get("/user/:id", auth.authenticateToken, controller.getUserById);
|
||||
router.post(
|
||||
"/user",
|
||||
auth.authenticateToken,
|
||||
controller.validate("createUser"),
|
||||
controller.createUser
|
||||
);
|
||||
router.put(
|
||||
"/user/:id",
|
||||
auth.authenticateToken,
|
||||
controller.validate("updateUser"),
|
||||
controller.updateUser
|
||||
);
|
||||
router.delete("/user/:id", auth.authenticateToken, controller.deleteUser);
|
||||
|
||||
// ============================== OTHER ==============================
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,29 +0,0 @@
|
||||
const { Router } = require("express")
|
||||
const router = Router()
|
||||
|
||||
const _readData = require('../controllers/hsmReadData')
|
||||
const _readDataResp = require('../controllers/hsmReadDataResp')
|
||||
|
||||
const _auth1 = require('../controllers/hsmAuthenticate1')
|
||||
const _auth2 = require('../controllers/hsmAuthenticate2')
|
||||
const _authResp = require('../controllers/hsmAuthenticateResp')
|
||||
|
||||
const _topup = require('../controllers/hsmTopup')
|
||||
const _topupResp = require('../controllers/hsmTopupResp')
|
||||
|
||||
const _end = require('../controllers/hsmEndTranscation')
|
||||
|
||||
router.post('/read', _readData)
|
||||
router.post('/readResp', _readDataResp)
|
||||
|
||||
router.post('/auth1', _auth1)
|
||||
router.post('/auth2', _auth2)
|
||||
router.post('/authResp', _authResp)
|
||||
|
||||
router.post('/topup', _topup)
|
||||
router.post('/topupResp', _topupResp)
|
||||
|
||||
router.post('/end',_end)
|
||||
|
||||
|
||||
module.exports = router
|
||||
@@ -1,37 +0,0 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const auth = require("../middlewares/jwt.middleware");
|
||||
const controller = require("../controllers/payment-channel");
|
||||
|
||||
// ============================== PAYMENT CHANNEL ==============================
|
||||
router.get(
|
||||
"/payment-channel",
|
||||
auth.authenticateToken,
|
||||
controller.getPaymentChannels
|
||||
);
|
||||
router.get(
|
||||
"/payment-channel/:id",
|
||||
auth.authenticateToken,
|
||||
controller.getPaymentChannelById
|
||||
);
|
||||
router.post(
|
||||
"/payment-channel",
|
||||
auth.authenticateToken,
|
||||
controller.validate("createPaymentChannel"),
|
||||
controller.createPaymentChannel
|
||||
);
|
||||
router.put(
|
||||
"/payment-channel/:id",
|
||||
auth.authenticateToken,
|
||||
controller.validate("updatePaymentChannel"),
|
||||
controller.updatePaymentChannel
|
||||
);
|
||||
router.delete(
|
||||
"/payment-channel/:id",
|
||||
auth.authenticateToken,
|
||||
controller.deletePaymentChannel
|
||||
);
|
||||
|
||||
// ============================== OTHER ==============================
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,50 +0,0 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIE7jCCA9agAwIBAgIJIrmxYwzstDwuMA0GCSqGSIb3DQEBCwUAMF0xCzAJBgNV
|
||||
BAYTAkpQMSUwIwYDVQQKExxTRUNPTSBUcnVzdCBTeXN0ZW1zIENPLixMVEQuMScw
|
||||
JQYDVQQLEx5TZWN1cml0eSBDb21tdW5pY2F0aW9uIFJvb3RDQTIwHhcNMTkwOTI3
|
||||
MDE1NDIzWhcNMjkwNTI5MDUwMDM5WjBeMQswCQYDVQQGEwJKUDEjMCEGA1UEChMa
|
||||
Q3liZXJ0cnVzdCBKYXBhbiBDby4sIEx0ZC4xKjAoBgNVBAMTIUN5YmVydHJ1c3Qg
|
||||
SmFwYW4gU3VyZVNlcnZlciBDQSBHNDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC
|
||||
AQoCggEBAMtunFmosT8IxBkVFP+OnkGkcVmbui+hdVBlGZhniniVluAhigm2WUxx
|
||||
p4X5V3B/QKJLZmeAswmzxGKXaDCzcomYxXTygNXcTLI+IMyRisEO7V1NXFHUjSEl
|
||||
KaY1LzCA9/emldnmRjX6B9Zt5xXK5q12WOIWkJECEwwKku77tvtKZPRKaCNCGsZ5
|
||||
Hja7PBs07jLoE0rMuZLQZNQEB0W63attKGCGzEk50lDj+wQ0UlUbQk3zAEsvdE6X
|
||||
o1qZy9l783Va40vSx3VqhGYb4jWQrg2CrAtJcKQNSJ0m9yxJVVQDwpQQwGxHO5Em
|
||||
Qv1LGJExASegOXzhzqCr5yiwECfSrOsCAwEAAaOCAa4wggGqMB0GA1UdDgQWBBRi
|
||||
p9La3oW2kvGFvPbolZ11oPpOHzAfBgNVHSMEGDAWgBQKhal3ZQWYfECB+A+XLDjx
|
||||
Cuw8zzASBgNVHRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjBJBgNVHR8E
|
||||
QjBAMD6gPKA6hjhodHRwOi8vcmVwb3NpdG9yeS5zZWNvbXRydXN0Lm5ldC9TQy1S
|
||||
b290Mi9TQ1Jvb3QyQ1JMLmNybDBSBgNVHSAESzBJMEcGCiqDCIybG2SHBQQwOTA3
|
||||
BggrBgEFBQcCARYraHR0cHM6Ly9yZXBvc2l0b3J5LnNlY29tdHJ1c3QubmV0L1ND
|
||||
LVJvb3QyLzCBhQYIKwYBBQUHAQEEeTB3MDAGCCsGAQUFBzABhiRodHRwOi8vc2Ny
|
||||
b290Y2EyLm9jc3Auc2Vjb210cnVzdC5uZXQwQwYIKwYBBQUHMAKGN2h0dHA6Ly9y
|
||||
ZXBvc2l0b3J5LnNlY29tdHJ1c3QubmV0L1NDLVJvb3QyL1NDUm9vdDJjYS5jZXIw
|
||||
HQYDVR0lBBYwFAYIKwYBBQUHAwEGCCsGAQUFBwMCMA0GCSqGSIb3DQEBCwUAA4IB
|
||||
AQDFUXkuQAZKY5Pb/JvgufizJ8uZKpN++fiI8kOTgkrSriNYNjO9iEdTwVV3sW3P
|
||||
abr3lAdCGrJ+wgArLLUnBZ7VGM//UlDhTRe4A19c0TmV1udTSbxabwQJbN1zIGbG
|
||||
3KQsumg9/70PaIkawnihx9/TxGCrJkAH5W+9pkX7OWefsahylwiPkKRkJRv2em/v
|
||||
rMRyb3LxRU5t84k1xQqCnMxTEWOAiWoOtatExZ38a8kn8kqiE1NEvtPOzSrVjSvD
|
||||
7pH56AlvO7hzGzng60kyWnAz6O5rQ0tsFIgW9xloWTQQVcfEtzvjc8ptuP9onkbA
|
||||
jMRDJaqLXrIVtB7GMek7S6AO
|
||||
-----END CERTIFICATE-----
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIDdzCCAl+gAwIBAgIBADANBgkqhkiG9w0BAQsFADBdMQswCQYDVQQGEwJKUDEl
|
||||
MCMGA1UEChMcU0VDT00gVHJ1c3QgU3lzdGVtcyBDTy4sTFRELjEnMCUGA1UECxMe
|
||||
U2VjdXJpdHkgQ29tbXVuaWNhdGlvbiBSb290Q0EyMB4XDTA5MDUyOTA1MDAzOVoX
|
||||
DTI5MDUyOTA1MDAzOVowXTELMAkGA1UEBhMCSlAxJTAjBgNVBAoTHFNFQ09NIFRy
|
||||
dXN0IFN5c3RlbXMgQ08uLExURC4xJzAlBgNVBAsTHlNlY3VyaXR5IENvbW11bmlj
|
||||
YXRpb24gUm9vdENBMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAV
|
||||
OVKxUrO6xVmCxF1SrjpDZYBLx/KWvNs2l9amZIyoXvDjChz335c9S672XewhtUGr
|
||||
zbl+dp+++T42NKA7wfYxEUV0kz1XgMX5iZnK5atq1LXaQZAQwdbWQonCv/Q4EpVM
|
||||
VAX3NuRFg3sUZdbcDE3R3n4MqzvEFb46VqZab3ZpUql6ucjrappdUtAtCms1FgkQ
|
||||
hNBqyjoGADdH5H5XTz+L62e4iKrFvlNVspHEfbmwhRkGeC7bYRr6hfVKkaHnFtWO
|
||||
ojnflLhwHyg/i/xAXmODPIMqGplrz95Zajv8bxbXH/1KEOtOghY6rCcMU/Gt1SSw
|
||||
awNQwS08Ft1ENCcadfsCAwEAAaNCMEAwHQYDVR0OBBYEFAqFqXdlBZh8QIH4D5cs
|
||||
OPEK7DzPMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3
|
||||
DQEBCwUAA4IBAQBMOqNErLlFsceTfsgLCkLfZOoc7llsCLqJX2rKSpWeeo8HxdpF
|
||||
coJxDjrSzG+ntKEju/Ykn8sX/oymzsLS28yN/HH8AynBbF0zX2S2ZTuJbxh2ePXc
|
||||
okgfGT+Ok+vx+hfuzU7jBBJV1uXk3fs+BXziHV7Gp7yXT2g69ekuCkO2r1dcYmh8
|
||||
t/2jioSgrGK+KwmHNPBqAbubKVY8/gA3zyNs8U6qtnRGEmyR7jTV7JqR50S+kDFy
|
||||
1UkC9gLl9B/rfNmWVan/7Ir5mUf/NVoCqgTLiluHcSmRvaS0eg29mvVXIwAHIRc/
|
||||
SjnRBUkLp7Y3gaVdjKozXoEofKd9J+sAro03
|
||||
-----END CERTIFICATE-----
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,171 +0,0 @@
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const winston = require("winston");
|
||||
const expressWinston = require("express-winston");
|
||||
const moment = require("moment");
|
||||
const responseAudit = require("./response-audit");
|
||||
const { writeStdoutLine, formatLog } = require("./stdout-log");
|
||||
const knex = require("../../infrastructure/database/knex");
|
||||
const {
|
||||
topuponline_metrics,
|
||||
topuponline_metrics_response_time,
|
||||
topuponline_metrics_load_balance,
|
||||
} = require("../helpers/prometheusmetrics");
|
||||
|
||||
const routes = new Set([
|
||||
"/api/reservation",
|
||||
"/api/reservation/v2",
|
||||
"/api/loadbalance/request",
|
||||
"/api/topup1",
|
||||
"/api/topup2",
|
||||
"/api/topup3",
|
||||
"/api/topup4",
|
||||
"/api/topup5",
|
||||
"/api/topup6",
|
||||
"/api/topup7",
|
||||
"/api/topup8",
|
||||
]);
|
||||
|
||||
function getRoute(url) {
|
||||
return url.split('?', 1)[0];
|
||||
}
|
||||
|
||||
// Tandai respons yang dipantau dengan ID unik per request, termasuk ketika HSM gagal.
|
||||
function correlation(req, res, next) {
|
||||
if (routes.has(getRoute(req.originalUrl))) {
|
||||
req.id = randomUUID();
|
||||
res.setHeader('X-Request-Id', req.id);
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
function getTransactionId(responseId, requestId) {
|
||||
// ID transaksi HSM terdiri dari empat digit hex. Abaikan nilai mentah lain dari body.
|
||||
for (const value of [responseId, requestId]) {
|
||||
if (typeof value === 'string' && /^[0-9a-f]{4}$/i.test(value)) return value.toLowerCase();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const successfulCodes = new Set(['00', '01', '02', '03', '04']);
|
||||
const isTopupRoute = (route) => /^\/api\/topup[1-8]$/.test(route);
|
||||
|
||||
function getLoadBalanceNumber(responseNumber, requestNumber) {
|
||||
return [responseNumber, requestNumber].find((value) =>
|
||||
typeof value === 'string' && /^LBL[0-9A-Za-z-]{1,35}$/.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
const issuerCache = new Map();
|
||||
const issuerLookups = new Set();
|
||||
|
||||
// Enrichment tidak boleh menahan respons atau mengantrekan lookup per transaksi.
|
||||
function getIssuerName(partnerId) {
|
||||
if (!partnerId) return 'UNDEFINED';
|
||||
const cached = issuerCache.get(partnerId);
|
||||
if (cached?.expiresAt > Date.now()) return cached.name;
|
||||
if (issuerLookups.size < 4 && !issuerLookups.has(partnerId)) {
|
||||
issuerLookups.add(partnerId);
|
||||
void refreshIssuer(partnerId);
|
||||
}
|
||||
return cached?.name || 'UNDEFINED';
|
||||
}
|
||||
|
||||
async function refreshIssuer(partnerId) {
|
||||
let name = 'UNDEFINED';
|
||||
try {
|
||||
const partner = await knex('t_m_partner').where('i_partner', partnerId)
|
||||
.first('c_name').timeout(500, { cancel: true });
|
||||
name = partner?.c_name || name;
|
||||
} catch {
|
||||
// PostgreSQL sedang sibuk. Tetap catat audit dan coba lagi setelah jeda.
|
||||
} finally {
|
||||
issuerLookups.delete(partnerId);
|
||||
issuerCache.delete(partnerId);
|
||||
if (issuerCache.size >= 256) issuerCache.delete(issuerCache.keys().next().value);
|
||||
issuerCache.set(partnerId, { name, expiresAt: Date.now() + (name === 'UNDEFINED' ? 5000 : 300000) });
|
||||
}
|
||||
}
|
||||
|
||||
function recordResponse(event, partnerId, reservationNumber, message) {
|
||||
const issuerName = getIssuerName(partnerId);
|
||||
const level = successfulCodes.has(event.status_code) ? 'info' : 'error';
|
||||
responseAudit.record({
|
||||
level,
|
||||
message: typeof message === 'string' ? message : 'HTTP response',
|
||||
...event,
|
||||
issuer_name: issuerName,
|
||||
...(reservationNumber && { reservation_number: reservationNumber }),
|
||||
});
|
||||
|
||||
const labels = { route: event.route, status_code: event.status_code, issuer_name: issuerName };
|
||||
|
||||
topuponline_metrics.observe(labels, event.response_time_ms);
|
||||
topuponline_metrics_response_time.observe(labels, event.response_time_ms);
|
||||
if (isTopupRoute(event.route)) {
|
||||
topuponline_metrics_load_balance.observe(labels, event.response_time_ms);
|
||||
}
|
||||
}
|
||||
|
||||
const logger = {
|
||||
correlation,
|
||||
response: expressWinston.logger({
|
||||
// Formatter mencatat audit/metrics sebagai efek samping; jangan gandakan ke file.
|
||||
transports: [new winston.transports.Console({ silent: true })],
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.printf((info) => {
|
||||
const { req, res, responseTime } = info.meta;
|
||||
const route = getRoute(req.originalUrl);
|
||||
const data = res.body?.data;
|
||||
const applicationCode = String(res.body?.code ?? '');
|
||||
const event = {
|
||||
event: 'http_response',
|
||||
request_id: req.id,
|
||||
partner_id: /^\d{1,16}$/.test(req.partner_id_token) ? String(req.partner_id_token) : undefined,
|
||||
trx_id: isTopupRoute(route) ? getTransactionId(data?.trxID, req.body?.trxID) : null,
|
||||
load_balance_number: getLoadBalanceNumber(data?.load_balance_number, req.body?.load_balance_number),
|
||||
route,
|
||||
method: req.method,
|
||||
http_status: res.statusCode,
|
||||
status_code: /^\d{2,4}$/.test(applicationCode) ? applicationCode : 'UNKNOWN',
|
||||
response_time_ms: responseTime,
|
||||
};
|
||||
|
||||
// Format Winston dijalankan sinkron agar audit dan metrik tercatat sebelum respons selesai.
|
||||
const reservationNumber = route.startsWith('/api/reservation') && successfulCodes.has(event.status_code)
|
||||
? data?.reservation_number
|
||||
: undefined;
|
||||
try {
|
||||
recordResponse(event, req.partner_id_token, reservationNumber, res.body?.message);
|
||||
} catch {
|
||||
writeStdoutLine(formatLog({
|
||||
event: 'response_telemetry_error',
|
||||
level: 'error',
|
||||
message: 'Failed to record Online TopUp response telemetry',
|
||||
request_id: req.id,
|
||||
route,
|
||||
}));
|
||||
}
|
||||
|
||||
const body = {
|
||||
id: req.id,
|
||||
tag: "RES",
|
||||
from: req.ip,
|
||||
endpoint: route,
|
||||
time: moment().format(),
|
||||
responseTime: `${responseTime} ms`,
|
||||
...event,
|
||||
};
|
||||
return `[${body.time}] | ${JSON.stringify(body)}`;
|
||||
})
|
||||
),
|
||||
ignoreRoute: (req) => !routes.has(getRoute(req.originalUrl)),
|
||||
responseWhitelist: [...expressWinston.responseWhitelist, "body"],
|
||||
requestWhitelist: [...expressWinston.requestWhitelist, "body", "id", "ip", "partner_id_token"],
|
||||
bodyWhitelist: ["trxID", "load_balance_number"],
|
||||
}),
|
||||
// Request terpisah dihilangkan karena respons terstruktur sudah menjadi audit.
|
||||
request: (req, res, next) => next(),
|
||||
};
|
||||
|
||||
module.exports = { logger };
|
||||
@@ -0,0 +1,23 @@
|
||||
const correlationPattern = /^(?:\d{1,16}|[a-f\d]{8}(?:-[a-f\d]{4}){3}-[a-f\d]{12})$/i;
|
||||
|
||||
// Kode dari klien bisa dipakai untuk korelasi selama bentuknya sesuai protokol.
|
||||
function logCorrelation(value) {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return 'unknown';
|
||||
const reference = String(value);
|
||||
return correlationPattern.test(reference) ? reference : 'unknown';
|
||||
}
|
||||
|
||||
function logStatusCode(value) {
|
||||
if (typeof value !== 'string' && typeof value !== 'number') return 'UNKNOWN';
|
||||
const code = String(value);
|
||||
return /^\d{2,4}$/.test(code) ? code : 'UNKNOWN';
|
||||
}
|
||||
|
||||
function logErrorCode(error) {
|
||||
const code = error?.code;
|
||||
if (typeof code === 'string' && /^(?:[A-Z\d]{5}|[A-Z][A-Z\d_]{2,29})$/.test(code)) return code;
|
||||
const name = error?.name;
|
||||
return typeof name === 'string' && /^[A-Za-z]{1,30}Error$/.test(name) ? name : 'Error';
|
||||
}
|
||||
|
||||
module.exports = { logCorrelation, logStatusCode, logErrorCode };
|
||||
@@ -1,4 +1,7 @@
|
||||
const { Counter } = require('prom-client');
|
||||
const { colorTerminalLine } = require('./terminal-log-color');
|
||||
|
||||
const WIB_OFFSET_MS = 7 * 60 * 60 * 1000;
|
||||
|
||||
const skipped = new Counter({
|
||||
name: 'topuponline_stdout_copies_skipped_total',
|
||||
@@ -6,7 +9,7 @@ const skipped = new Counter({
|
||||
labelNames: ['reason'],
|
||||
});
|
||||
|
||||
function createStdoutWriter(stream, onSkip) {
|
||||
function createStdoutWriter(stream, onSkip, { colors = stream.isTTY === true && !process.env.NO_COLOR } = {}) {
|
||||
let failed = false;
|
||||
stream.on('error', () => { failed = true; });
|
||||
|
||||
@@ -21,7 +24,9 @@ function createStdoutWriter(stream, onSkip) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stream.write(`${line}\n`, (error) => {
|
||||
// Sisipkan ANSI hanya saat menulis ke terminal. Arsip dan collector memakai JSON polos.
|
||||
const output = colors ? colorTerminalLine(line) : line;
|
||||
stream.write(`${output}\n`, (error) => {
|
||||
if (error) onSkip('unavailable');
|
||||
});
|
||||
} catch {
|
||||
@@ -42,7 +47,8 @@ function formatLog(event, time = Date.now()) {
|
||||
.slice(0, 512);
|
||||
}
|
||||
return JSON.stringify({
|
||||
timestamp: new Date(time).toISOString(),
|
||||
// Bentuk timestamp WIB dari epoch supaya hasilnya sama di semua host.
|
||||
timestamp: new Date(time + WIB_OFFSET_MS).toISOString().replace(/Z$/, '+07:00'),
|
||||
app: 'topuponline',
|
||||
pid: process.pid,
|
||||
...safeEvent,
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
const RED = '\x1b[31m';
|
||||
const YELLOW = '\x1b[33m';
|
||||
const GREEN = '\x1b[32m';
|
||||
const RESET = '\x1b[0m';
|
||||
|
||||
function colorForResponseCode(code) {
|
||||
if (/^(0[0-4]|2\d{2})$/.test(code)) return GREEN;
|
||||
if (code === '423') return RED;
|
||||
if (/^4\d{2}$/.test(code) || code === '5003') return YELLOW;
|
||||
if (/^5\d{2,3}$/.test(code)) return RED;
|
||||
}
|
||||
|
||||
function colorTerminalLine(line) {
|
||||
let record;
|
||||
try {
|
||||
record = JSON.parse(line);
|
||||
} catch {
|
||||
return line;
|
||||
}
|
||||
|
||||
if (!record || typeof record !== 'object') return line;
|
||||
|
||||
let color;
|
||||
if (record.event === 'http_response') {
|
||||
// Kode aplikasi tetap bermakna saat API mengembalikan HTTP 200.
|
||||
if (record.http_status >= 500) color = RED;
|
||||
else if (record.http_status >= 400) color = YELLOW;
|
||||
else color = colorForResponseCode(record.status_code);
|
||||
} else if (record.level !== 'fatal' && record.level !== 'error' && typeof record.message === 'string') {
|
||||
const [, code] = record.message.match(/(?:^|\s)code=(\d{2,4})(?=\s|$)/) || [];
|
||||
color = colorForResponseCode(code);
|
||||
}
|
||||
|
||||
if (!color && (record.level === 'error' || record.level === 'fatal')) color = RED;
|
||||
if (!color && record.level === 'warn') color = YELLOW;
|
||||
return color ? color + line + RESET : line;
|
||||
}
|
||||
|
||||
module.exports = { colorTerminalLine };
|
||||
@@ -0,0 +1,156 @@
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const winston = require("winston");
|
||||
const expressWinston = require("express-winston");
|
||||
const responseAudit = require("../helpers/response-audit");
|
||||
const { writeStdoutLine, formatLog } = require("../helpers/stdout-log");
|
||||
const knex = require("../../infrastructure/database/knex");
|
||||
const {
|
||||
topuponline_metrics,
|
||||
topuponline_metrics_response_time,
|
||||
topuponline_metrics_load_balance,
|
||||
} = require("../helpers/prometheusmetrics");
|
||||
|
||||
const routes = new Set([
|
||||
"/api/reservation",
|
||||
"/api/reservation/v2",
|
||||
"/api/loadbalance/request",
|
||||
"/api/topup1",
|
||||
"/api/topup2",
|
||||
"/api/topup3",
|
||||
"/api/topup4",
|
||||
"/api/topup5",
|
||||
"/api/topup6",
|
||||
"/api/topup7",
|
||||
"/api/topup8",
|
||||
]);
|
||||
|
||||
function getRoute(url) {
|
||||
return url.split('?', 1)[0];
|
||||
}
|
||||
|
||||
// Tandai respons yang dipantau dengan ID unik per request, termasuk ketika HSM gagal.
|
||||
function correlation(req, res, next) {
|
||||
if (routes.has(getRoute(req.originalUrl))) {
|
||||
req.id = randomUUID();
|
||||
res.setHeader('X-Request-Id', req.id);
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
function getTransactionId(responseId, requestId) {
|
||||
// ID transaksi HSM terdiri dari empat digit hex. Abaikan nilai mentah lain dari body.
|
||||
for (const value of [responseId, requestId]) {
|
||||
if (typeof value === 'string' && /^[0-9a-f]{4}$/i.test(value)) return value.toLowerCase();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const successfulCodes = new Set(['00', '01', '02', '03', '04']);
|
||||
const isTopupRoute = (route) => /^\/api\/topup[1-8]$/.test(route);
|
||||
|
||||
function getLoadBalanceNumber(responseNumber, requestNumber) {
|
||||
return [responseNumber, requestNumber].find((value) =>
|
||||
typeof value === 'string' && /^LBL[0-9A-Za-z-]{1,35}$/.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
const issuerCache = new Map();
|
||||
const issuerLookups = new Set();
|
||||
|
||||
// Enrichment tidak boleh menahan respons atau mengantrekan lookup per transaksi.
|
||||
function getIssuerName(partnerId) {
|
||||
if (!partnerId) return 'UNDEFINED';
|
||||
const cached = issuerCache.get(partnerId);
|
||||
if (cached?.expiresAt > Date.now()) return cached.name;
|
||||
if (issuerLookups.size < 4 && !issuerLookups.has(partnerId)) {
|
||||
issuerLookups.add(partnerId);
|
||||
void refreshIssuer(partnerId);
|
||||
}
|
||||
return cached?.name || 'UNDEFINED';
|
||||
}
|
||||
|
||||
async function refreshIssuer(partnerId) {
|
||||
let name = 'UNDEFINED';
|
||||
try {
|
||||
const partner = await knex('t_m_partner').where('i_partner', partnerId)
|
||||
.first('c_name').timeout(500, { cancel: true });
|
||||
name = partner?.c_name || name;
|
||||
} catch {
|
||||
// PostgreSQL sedang sibuk. Tetap catat audit dan coba lagi setelah jeda.
|
||||
} finally {
|
||||
issuerLookups.delete(partnerId);
|
||||
issuerCache.delete(partnerId);
|
||||
if (issuerCache.size >= 256) issuerCache.delete(issuerCache.keys().next().value);
|
||||
issuerCache.set(partnerId, { name, expiresAt: Date.now() + (name === 'UNDEFINED' ? 5000 : 300000) });
|
||||
}
|
||||
}
|
||||
|
||||
function recordResponse(event, partnerId, reservationNumber, message) {
|
||||
const issuerName = getIssuerName(partnerId);
|
||||
const level = successfulCodes.has(event.status_code) ? 'info' : 'error';
|
||||
responseAudit.record({
|
||||
level,
|
||||
message: typeof message === 'string' ? message : 'HTTP response',
|
||||
...event,
|
||||
issuer_name: issuerName,
|
||||
...(reservationNumber && { reservation_number: reservationNumber }),
|
||||
});
|
||||
|
||||
const labels = { route: event.route, status_code: event.status_code, issuer_name: issuerName };
|
||||
|
||||
topuponline_metrics.observe(labels, event.response_time_ms);
|
||||
topuponline_metrics_response_time.observe(labels, event.response_time_ms);
|
||||
if (isTopupRoute(event.route)) {
|
||||
topuponline_metrics_load_balance.observe(labels, event.response_time_ms);
|
||||
}
|
||||
}
|
||||
|
||||
const response = expressWinston.logger({
|
||||
// Formatter mencatat audit/metrics sebagai efek samping; jangan gandakan ke file.
|
||||
transports: [new winston.transports.Console({ silent: true })],
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.printf((info) => {
|
||||
const { req, res, responseTime } = info.meta;
|
||||
const route = getRoute(req.originalUrl);
|
||||
const data = res.body?.data;
|
||||
const applicationCode = String(res.body?.code ?? '');
|
||||
const event = {
|
||||
event: 'http_response',
|
||||
request_id: req.id,
|
||||
partner_id: /^\d{1,16}$/.test(req.partner_id_token) ? String(req.partner_id_token) : undefined,
|
||||
trx_id: isTopupRoute(route) ? getTransactionId(data?.trxID, req.body?.trxID) : null,
|
||||
load_balance_number: getLoadBalanceNumber(data?.load_balance_number, req.body?.load_balance_number),
|
||||
route,
|
||||
method: req.method,
|
||||
http_status: res.statusCode,
|
||||
status_code: /^\d{2,4}$/.test(applicationCode) ? applicationCode : 'UNKNOWN',
|
||||
response_time_ms: responseTime,
|
||||
};
|
||||
|
||||
// Catat audit dan metrik saat middleware memproses respons transaksi.
|
||||
const reservationNumber = route.startsWith('/api/reservation') && successfulCodes.has(event.status_code)
|
||||
? data?.reservation_number
|
||||
: undefined;
|
||||
try {
|
||||
recordResponse(event, req.partner_id_token, reservationNumber, res.body?.message);
|
||||
} catch {
|
||||
writeStdoutLine(formatLog({
|
||||
event: 'response_telemetry_error',
|
||||
level: 'error',
|
||||
message: 'Failed to record Online TopUp response telemetry',
|
||||
request_id: req.id,
|
||||
route,
|
||||
}));
|
||||
}
|
||||
|
||||
return info.message;
|
||||
})
|
||||
),
|
||||
ignoreRoute: (req) => !routes.has(getRoute(req.originalUrl)),
|
||||
responseWhitelist: ['statusCode', 'body'],
|
||||
requestWhitelist: ['originalUrl', 'method', 'body', 'id', 'partner_id_token'],
|
||||
bodyWhitelist: ["trxID", "load_balance_number"],
|
||||
});
|
||||
|
||||
module.exports = { correlation, response };
|
||||
@@ -0,0 +1,249 @@
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { validationResult } = require('express-validator');
|
||||
const model = require('./auth.model');
|
||||
const bcrypt = require('bcrypt');
|
||||
const jwt = require('../../middlewares/jwt.middleware');
|
||||
|
||||
// Login partner dan terminal memiliki sumber akun yang berbeda.
|
||||
const loginPartnerUser = async (req, res) => {
|
||||
let uniqueCode = req.id ?? 'unknown';
|
||||
try {
|
||||
uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
const { email, password } = req.body;
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST LOGIN-PARTNER-USER ]`);
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-PARTNER-USER ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// check status data partner user apakah masih aktif atau tidak
|
||||
const checkDataLoginPartnerUser = await model.checkDataLoginPartnerUser(
|
||||
email.toUpperCase()
|
||||
);
|
||||
|
||||
// jika partner user yang di request tidak aktif maka login akan ditolak
|
||||
if (!checkDataLoginPartnerUser) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: "Partner User doesn't exists.",
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-PARTNER-USER ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// check password
|
||||
const checkPassword = await bcrypt.compare(
|
||||
password,
|
||||
checkDataLoginPartnerUser.c_password.replace('$2y$', '$2a$')
|
||||
);
|
||||
|
||||
// jika password tidak sama dengan password yang tersimpan di sistem CMS
|
||||
if (!checkPassword) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: 'Password is wrong.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-PARTNER-USER ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// generate access token, yaitu token transaksi yang digunakan untuk setiap request ke setiap end point api
|
||||
const accessToken = await jwt.generateAccessToken({
|
||||
partner_id: helper.encryptText(checkDataLoginPartnerUser.i_partner),
|
||||
partner_user_id: helper.encryptText(
|
||||
checkDataLoginPartnerUser.i_partner_user
|
||||
),
|
||||
});
|
||||
|
||||
// generate refresh token, yaitu token yang digunakan untuk mendapatkan token transaksi baru jika token sebelumnya sudah expired
|
||||
const refreshToken = await jwt.generateRefreshToken({
|
||||
partner_id: helper.encryptText(checkDataLoginPartnerUser.i_partner),
|
||||
partner_user_id: helper.encryptText(
|
||||
checkDataLoginPartnerUser.i_partner_user
|
||||
),
|
||||
});
|
||||
|
||||
// insert refresh token
|
||||
await model.insertRefreshTokenPartner(email, refreshToken);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Login Success.',
|
||||
data: {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
},
|
||||
};
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
winston.logger.error(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-PARTNER-USER ] code=500 error_type=${error?.name || 'Error'}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const loginTerminal = async (req, res) => {
|
||||
let uniqueCode = req.id ?? 'unknown';
|
||||
try {
|
||||
uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
const { mid, tid, password } = req.body;
|
||||
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST LOGIN-TERMINAL ]`
|
||||
);
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// check mid dan tid, apakah mid dan tid yang di request terdaftar dan status nya aktif di sistem CMS
|
||||
const checkMidTid = await model.checkMidTid(mid, tid);
|
||||
if (!checkMidTid) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: 'MID or TID is not registered.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// check data mid dan tid yang di request sudah di daftarkan di terminal login dan statusnya aktif atau tidak
|
||||
const checkDataLogin = await model.checkDataLogin(mid, tid);
|
||||
|
||||
// jika mid dan tid yang di request tidak di daftarkan di terminal login
|
||||
if (!checkDataLogin) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: "Terminal Login doesn't exists.",
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// check password
|
||||
const checkPassword = await bcrypt.compare(
|
||||
password,
|
||||
checkDataLogin.c_password_hash
|
||||
);
|
||||
|
||||
// jika password tidak sama dengan password yang disimpan di sistem CMS
|
||||
if (!checkPassword) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: 'Password is wrong.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// generate access token, yaitu token transaksi yang digunakan untuk request ke setiap end point api
|
||||
const accessToken = await jwt.generateAccessToken({
|
||||
mid: helper.encryptText(mid),
|
||||
tid: helper.encryptText(tid),
|
||||
});
|
||||
|
||||
// generate refresh token, yaitu token yang digunakan untuk mengenerate token transaksi baru jika token sebelumnya sudah expired
|
||||
const refreshToken = await jwt.generateRefreshToken({
|
||||
mid: helper.encryptText(mid),
|
||||
tid: helper.encryptText(tid),
|
||||
});
|
||||
|
||||
// insert refresh token
|
||||
await model.insertRefreshToken(mid, tid, refreshToken);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Login Success.',
|
||||
data: {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
},
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
winston.logger.error(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ] code=500 error_type=${error?.name || 'Error'}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { loginPartnerUser, loginTerminal };
|
||||
@@ -0,0 +1,96 @@
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./auth.model');
|
||||
|
||||
// Ambil data profil berdasarkan identitas yang diberikan middleware autentikasi.
|
||||
const getTIDMID = async (req, res) => {
|
||||
let uniqueCode = req.id ?? 'unknown';
|
||||
try {
|
||||
uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
const partner_id = req.partner_id_token;
|
||||
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST GET-TID-MID ]`
|
||||
);
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
const getTIDMID = await model.getTIDMID(partner_id);
|
||||
if (!getTIDMID) {
|
||||
return res.status(200).json({
|
||||
code: '403',
|
||||
message: "TID MID doesn't exists.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Success',
|
||||
data: getTIDMID,
|
||||
};
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
winston.logger.error(
|
||||
`${uniqueCode} [ RESPONSE GET-TID-MID ] code=500 error_type=${error?.name || 'Error'}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getPartnerUser = async (req, res) => {
|
||||
let uniqueCode = req.id ?? 'unknown';
|
||||
try {
|
||||
uniqueCode = await helper.getUniqueCode();
|
||||
|
||||
let result = {};
|
||||
const partner_user_id = req.partner_user_id_token;
|
||||
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST GET-PARTNER-USER ]`
|
||||
);
|
||||
|
||||
// get partner user detail
|
||||
const partnerUser = await model.getPartnerUser(partner_user_id);
|
||||
if (!partnerUser) {
|
||||
return res.status(200).json({
|
||||
code: '403',
|
||||
message: "Partner User doesn't exists.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Success',
|
||||
data: partnerUser,
|
||||
};
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
winston.logger.error(
|
||||
`${uniqueCode} [ RESPONSE GET-PARTNER-USER ] code=500 error_type=${error?.name || 'Error'}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { getTIDMID, getPartnerUser };
|
||||
@@ -0,0 +1,225 @@
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { validationResult } = require('express-validator');
|
||||
const jwt = require('../../middlewares/jwt.middleware');
|
||||
const model = require('./auth.model');
|
||||
|
||||
// Ganti refresh token yang tersimpan hanya setelah token lama lolos pemeriksaan CMS.
|
||||
const refreshTokenTerminal = async (req, res) => {
|
||||
let uniqueCode = req.id ?? 'unknown';
|
||||
try {
|
||||
uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
const { mid, tid } = req.body;
|
||||
const refresh_token = req.headers['refresh-token'];
|
||||
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST REFRESH-TOKEN-TERMINAL ]`
|
||||
);
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-TERMINAL ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// Middleware route sudah memverifikasi tanda tangan refresh token.
|
||||
|
||||
// cek apakah refresh token yang di request terdaftar di sistem CMS
|
||||
const checkRefreshToken = await model.checkRefreshToken(
|
||||
mid,
|
||||
tid,
|
||||
refresh_token
|
||||
);
|
||||
|
||||
// jika refresh token tidak terdaftar di sistem CMS
|
||||
if (!checkRefreshToken) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'Refresh Token is invalid. Please try login',
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-TERMINAL ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let accessToken;
|
||||
let refreshToken;
|
||||
|
||||
// generate new access token
|
||||
accessToken = await jwt.generateAccessToken({
|
||||
mid: helper.encryptText(mid),
|
||||
tid: helper.encryptText(tid),
|
||||
});
|
||||
|
||||
// generate new refresh token
|
||||
refreshToken = await jwt.generateRefreshToken({
|
||||
mid: helper.encryptText(mid),
|
||||
tid: helper.encryptText(tid),
|
||||
});
|
||||
|
||||
// update insert refresh token
|
||||
await model.updateRefreshToken(mid, tid, refresh_token, refreshToken);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'New Token has been generated.',
|
||||
data: {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
},
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-TERMINAL ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
winston.logger.error(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN ] code=500 error_type=${error?.name || 'Error'}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const refreshTokenPartnerUser = async (req, res) => {
|
||||
let uniqueCode = req.id ?? 'unknown';
|
||||
try {
|
||||
uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
const { email } = req.body;
|
||||
const refresh_token = req.headers['refresh-token'];
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-PARTNER-USER ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// Middleware route sudah memverifikasi tanda tangan refresh token.
|
||||
|
||||
// cek apaka refresh token yang di request terdaftar di sistem CMS atau tidak
|
||||
const checkRefreshToken = await model.checkRefreshTokenPartner(
|
||||
email,
|
||||
refresh_token
|
||||
);
|
||||
|
||||
// jika refresh token tidak terdaftar di sistem CMS
|
||||
if (!checkRefreshToken) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'Refresh Token is invalid. Please try login',
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-PARTNER-USER ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let accessToken;
|
||||
let refreshToken;
|
||||
|
||||
// check data partner user terdaftar dan status nya masih aktif atau tidak
|
||||
const checkDataLoginPartnerUser = await model.checkDataLoginPartnerUser(
|
||||
email.toUpperCase()
|
||||
);
|
||||
|
||||
// jika partner user tidak terdaftar atau status nya tidak aktif
|
||||
if (!checkDataLoginPartnerUser) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: "Partner User doesn't exists.",
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-PARTNER-USER ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// generate new access token
|
||||
accessToken = await jwt.generateAccessToken({
|
||||
partner_id: helper.encryptText(checkDataLoginPartnerUser.i_partner),
|
||||
partner_user_id: helper.encryptText(
|
||||
checkDataLoginPartnerUser.i_partner_user
|
||||
),
|
||||
});
|
||||
|
||||
// generate new refresh token
|
||||
refreshToken = await jwt.generateRefreshToken({
|
||||
partner_id: helper.encryptText(checkDataLoginPartnerUser.i_partner),
|
||||
partner_user_id: helper.encryptText(
|
||||
checkDataLoginPartnerUser.i_partner_user
|
||||
),
|
||||
});
|
||||
|
||||
// update insert refresh token
|
||||
await model.updateRefreshTokenPartner(email, refresh_token, refreshToken);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'New Token has been generated.',
|
||||
data: {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
},
|
||||
};
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
winston.logger.error(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-PARTNER-USER ] code=500 error_type=${error?.name || 'Error'}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { refreshTokenTerminal, refreshTokenPartnerUser };
|
||||
@@ -0,0 +1,120 @@
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { validationResult } = require('express-validator');
|
||||
const model = require('./auth.model');
|
||||
const bcrypt = require('bcrypt');
|
||||
const moment = require('moment');
|
||||
|
||||
// Registrasi terminal menyimpan hash password setelah validasi terminal.
|
||||
const register = async (req, res) => {
|
||||
let uniqueCode = req.id ?? 'unknown';
|
||||
try {
|
||||
uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
const { mid, tid, password } = req.body;
|
||||
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST REGISTER ]`
|
||||
);
|
||||
|
||||
// validate
|
||||
const err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REGISTER ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// check mid dan tid yang di request sudah terdaftar di master terminal sistem CMS atau belum dan status nya aktif
|
||||
const checkMidTid = await model.checkMidTid(mid, tid);
|
||||
if (!checkMidTid) {
|
||||
result = {
|
||||
code: '410',
|
||||
message: 'MID or TID is not registered.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REGISTER ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// check data login, apaka mid dan tid yang di request sudah terdaftar di terminal login atau belum
|
||||
const checkDataLogin = await model.checkDataLogin(mid, tid);
|
||||
|
||||
// jika mid dan tid sudah terdaftar di terminal login
|
||||
if (checkDataLogin) {
|
||||
result = {
|
||||
code: '411',
|
||||
message: 'Terminal Login already exists.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REGISTER ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// encrypt password
|
||||
const saltRounds = 10;
|
||||
const salt = bcrypt.genSaltSync(saltRounds);
|
||||
const passwordHash = bcrypt.hashSync(password, salt);
|
||||
|
||||
// binding data
|
||||
const data = {
|
||||
c_mid: mid,
|
||||
c_tid: tid,
|
||||
c_password: password,
|
||||
c_password_hash: passwordHash,
|
||||
c_status: 'A',
|
||||
c_status_name: 'ACTIVE',
|
||||
d_create: moment().format('YYYY-MM-DD HH:mm:ss'),
|
||||
i_create: null,
|
||||
c_create_username: null,
|
||||
c_create_fullname: null,
|
||||
};
|
||||
|
||||
// insert data login
|
||||
result = await model.insertDataLogin(data);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Data login saved successfully.',
|
||||
data: result.command,
|
||||
};
|
||||
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REGISTER ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
winston.logger.error(
|
||||
`${uniqueCode} [ RESPONSE REGISTER ] code=500 error_type=${error?.name || 'Error'}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { register };
|
||||
@@ -1,926 +1,12 @@
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
const jwt = require('../../middlewares/jwt.middleware');
|
||||
const bcrypt = require('bcrypt');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./auth.model');
|
||||
const { validationResult } = require('express-validator');
|
||||
const validate = require('./auth.validation');
|
||||
const moment = require('moment');
|
||||
const validate = require('./auth.validation');
|
||||
const { loginPartnerUser, loginTerminal } = require('./auth-login.handlers');
|
||||
const { register } = require('./auth-registration.handler');
|
||||
const { refreshTokenTerminal, refreshTokenPartnerUser } = require('./auth-refresh.handlers');
|
||||
const { getTIDMID, getPartnerUser } = require('./auth-profile.handlers');
|
||||
|
||||
moment.locale('id');
|
||||
|
||||
|
||||
// ================================================================= LOGIN BY PARTNER USER =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *Description:*
|
||||
// fungsi yang digunakan login online topup dengan menggunakan data user partner
|
||||
|
||||
const loginPartnerUser = async (req, res, next) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
let { email, password } = req.body;
|
||||
|
||||
// log info
|
||||
// winston.logger.info(
|
||||
// `${uniqueCode} [ REQUEST LOGIN-PARTNER-USER ]: ${JSON.stringify({
|
||||
// email: email,
|
||||
// })}`
|
||||
// );
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST LOGIN-PARTNER-USER ]`);
|
||||
|
||||
// validate
|
||||
let err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-PARTNER-USER ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: checking data login...`
|
||||
// );
|
||||
|
||||
// check status data partner user apakah masih aktif atau tidak
|
||||
let checkDataLoginPartnerUser = await model.checkDataLoginPartnerUser(
|
||||
email.toUpperCase()
|
||||
);
|
||||
|
||||
// jika partner user yang di request tidak aktif maka login akan ditolak
|
||||
if (!checkDataLoginPartnerUser) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: "Partner User doesn't exists.",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-PARTNER-USER ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: checking password...`
|
||||
// );
|
||||
|
||||
// check password
|
||||
let checkPassword = await bcrypt.compare(
|
||||
password,
|
||||
checkDataLoginPartnerUser.c_password.replace('$2y$', '$2a$')
|
||||
);
|
||||
|
||||
// jika password tidak sama dengan password yang tersimpan di sistem CMS
|
||||
if (!checkPassword) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: 'Password is wrong.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-PARTNER-USER ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: generating access token...`
|
||||
// );
|
||||
|
||||
// generate access token, yaitu token transaksi yang digunakan untuk setiap request ke setiap end point api
|
||||
let accessToken = await jwt.generateAccessToken({
|
||||
partner_id: helper.encryptText(checkDataLoginPartnerUser.i_partner),
|
||||
partner_user_id: helper.encryptText(
|
||||
checkDataLoginPartnerUser.i_partner_user
|
||||
),
|
||||
});
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${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
|
||||
let refreshToken = await jwt.generateRefreshToken({
|
||||
partner_id: helper.encryptText(checkDataLoginPartnerUser.i_partner),
|
||||
partner_user_id: helper.encryptText(
|
||||
checkDataLoginPartnerUser.i_partner_user
|
||||
),
|
||||
});
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOGIN-PARTNER-USER ]: inserting refresh token...`
|
||||
// );
|
||||
|
||||
// insert refresh token
|
||||
await model.insertRefreshTokenPartner(email, refreshToken);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Login Success.',
|
||||
data: {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
// winston.logger.info(
|
||||
// `${uniqueCode} [ RESPONSE LOGIN-PARTNER-USER ]: ${JSON.stringify(result)}`
|
||||
// );
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOGIN-PARTNER-USER ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ================================================================= LOGIN BY TID MID =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *Description:*
|
||||
// fungsi yang digunakan login online topup dengan menggunakan data tid dan mid
|
||||
|
||||
const loginTerminal = async (req, res, next) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
let { mid, tid, password } = req.body;
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST LOGIN-TERMINAL ]: ${JSON.stringify({
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
})}`
|
||||
);
|
||||
|
||||
// validate
|
||||
let err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${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
|
||||
let checkMidTid = await model.checkMidTid(mid, tid);
|
||||
if (!checkMidTid) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: 'MID or TID is not registered.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${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
|
||||
let checkDataLogin = await model.checkDataLogin(mid, tid);
|
||||
|
||||
// jika mid dan tid yang di request tidak di daftarkan di terminal login
|
||||
if (!checkDataLogin) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: "Terminal Login doesn't exists.",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: checking password...`
|
||||
// );
|
||||
|
||||
// check password
|
||||
let checkPassword = await bcrypt.compare(
|
||||
password,
|
||||
checkDataLogin.c_password_hash
|
||||
);
|
||||
|
||||
// jika password tidak sama dengan password yang disimpan di sistem CMS
|
||||
if (!checkPassword) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: 'Password is wrong.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: generating access token...`
|
||||
// );
|
||||
|
||||
// generate access token, yaitu token transaksi yang digunakan untuk request ke setiap end point api
|
||||
let accessToken = await jwt.generateAccessToken({
|
||||
mid: helper.encryptText(mid),
|
||||
tid: helper.encryptText(tid),
|
||||
});
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: generating refresh token...`
|
||||
// );
|
||||
|
||||
// generate refresh token, yaitu token yang digunakan untuk mengenerate token transaksi baru jika token sebelumnya sudah expired
|
||||
let refreshToken = await jwt.generateRefreshToken({
|
||||
mid: helper.encryptText(mid),
|
||||
tid: helper.encryptText(tid),
|
||||
});
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOGIN-TERMINAL ]: inserting refresh token...`
|
||||
// );
|
||||
|
||||
// insert refresh token
|
||||
await model.insertRefreshToken(mid, tid, refreshToken);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Login Success.',
|
||||
data: {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE LOGIN-TERMINAL ] code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOGIN-TERMINAL ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ================================================================= REGISTER =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *Description:*
|
||||
// fungsi yang digunakan mendaftarkan tid dan mid agar bisa login ke sistem online topup
|
||||
|
||||
const register = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
let { mid, tid, password } = req.body;
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST REGISTER ]: ${JSON.stringify({
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
})}`
|
||||
);
|
||||
|
||||
// validate
|
||||
let err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REGISTER ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ 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
|
||||
let checkMidTid = await model.checkMidTid(mid, tid);
|
||||
if (!checkMidTid) {
|
||||
result = {
|
||||
code: '410',
|
||||
message: 'MID or TID is not registered.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REGISTER ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REGISTER ]: checking data login...`
|
||||
// );
|
||||
|
||||
// check data login, apaka mid dan tid yang di request sudah terdaftar di terminal login atau belum
|
||||
let checkDataLogin = await model.checkDataLogin(mid, tid);
|
||||
|
||||
// jika mid dan tid sudah terdaftar di terminal login
|
||||
if (checkDataLogin) {
|
||||
result = {
|
||||
code: '411',
|
||||
message: 'Terminal Login already exists.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REGISTER ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REGISTER ]: encrypting password...`
|
||||
// );
|
||||
|
||||
// encrypt password
|
||||
let saltRounds = 10;
|
||||
let salt = bcrypt.genSaltSync(saltRounds);
|
||||
let passwordHash = bcrypt.hashSync(password, salt);
|
||||
|
||||
// binding data
|
||||
let data = {
|
||||
c_mid: mid,
|
||||
c_tid: tid,
|
||||
c_password: password,
|
||||
c_password_hash: passwordHash,
|
||||
c_status: 'A',
|
||||
c_status_name: 'ACTIVE',
|
||||
d_create: moment().format('YYYY-MM-DD HH:mm:ss'),
|
||||
i_create: null,
|
||||
c_create_username: null,
|
||||
c_create_fullname: null,
|
||||
};
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REGISTER ]: inserting data login...`
|
||||
// );
|
||||
|
||||
// insert data login
|
||||
result = await model.insertDataLogin(data);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Data login saved successfully.',
|
||||
data: result.command,
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REGISTER ]: ${JSON.stringify(result)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE REGISTER ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ================================================================= REFRESH TOKEN TERMINAL =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *Description:*
|
||||
// fungsi yang digunakan mengenerate token baru untuk terminal login
|
||||
|
||||
const refreshTokenTerminal = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
let { mid, tid } = req.body;
|
||||
let refresh_token = req.headers['refresh-token'];
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST REFRESH-TOKEN-TERMINAL ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// validate
|
||||
let err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-TERMINAL ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: authenticating refresh token...`
|
||||
// );
|
||||
|
||||
// verify, apaka refresh token yang di request valid atau tidak
|
||||
await jwt.authenticateRefreshToken;
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: checking refresh token...`
|
||||
// );
|
||||
|
||||
// cek apakah refresh token yang di request terdaftar di sistem CMS
|
||||
let checkRefreshToken = await model.checkRefreshToken(
|
||||
mid,
|
||||
tid,
|
||||
refresh_token
|
||||
);
|
||||
|
||||
// jika refresh token tidak terdaftar di sistem CMS
|
||||
if (!checkRefreshToken) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'Refresh Token is invalid. Please try login',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-TERMINAL ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: generating access token...`
|
||||
// );
|
||||
|
||||
let accessToken;
|
||||
let refreshToken;
|
||||
|
||||
// generate new access token
|
||||
accessToken = await jwt.generateAccessToken({
|
||||
mid: helper.encryptText(mid),
|
||||
tid: helper.encryptText(tid),
|
||||
});
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: generating refresh token...`
|
||||
// );
|
||||
|
||||
// generate new refresh token
|
||||
refreshToken = await jwt.generateRefreshToken({
|
||||
mid: helper.encryptText(mid),
|
||||
tid: helper.encryptText(tid),
|
||||
});
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REFRESH-TOKEN-TERMINAL ]: updating refresh token...`
|
||||
// );
|
||||
|
||||
// update insert refresh token
|
||||
await model.updateRefreshToken(mid, tid, refresh_token, refreshToken);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'New Token has been generated.',
|
||||
data: {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-TERMINAL ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE REFRESH-TOKEN ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ================================================================= REFRESH TOKEN PARTNER USER =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *Description:*
|
||||
// fungsi yang digunakan mengenerate token baru untuk login user partner
|
||||
|
||||
const refreshTokenPartnerUser = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
let { email } = req.body;
|
||||
let refresh_token = req.headers['refresh-token'];
|
||||
|
||||
// log info
|
||||
// winston.logger.info(
|
||||
// `${uniqueCode} [ REQUEST REFRESH-TOKEN-PARTNER-USER ]: ${JSON.stringify(
|
||||
// req.body
|
||||
// )}`
|
||||
// );
|
||||
|
||||
// validate
|
||||
let err = validationResult(req);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-PARTNER-USER ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: authenticating refresh token...`
|
||||
// );
|
||||
|
||||
// verify apaka refresh token yang di request valid atau tidak
|
||||
await jwt.authenticateRefreshToken;
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: checking refresh token...`
|
||||
// );
|
||||
|
||||
// cek apaka refresh token yang di request terdaftar di sistem CMS atau tidak
|
||||
let checkRefreshToken = await model.checkRefreshTokenPartner(
|
||||
email,
|
||||
refresh_token
|
||||
);
|
||||
|
||||
// jika refresh token tidak terdaftar di sistem CMS
|
||||
if (!checkRefreshToken) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'Refresh Token is invalid. Please try login',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-PARTNER-USER ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: generating access token...`
|
||||
// );
|
||||
|
||||
let accessToken;
|
||||
let refreshToken;
|
||||
|
||||
// check data partner user terdaftar dan status nya masih aktif atau tidak
|
||||
let checkDataLoginPartnerUser = await model.checkDataLoginPartnerUser(
|
||||
email.toUpperCase()
|
||||
);
|
||||
|
||||
// jika partner user tidak terdaftar atau status nya tidak aktif
|
||||
if (!checkDataLoginPartnerUser) {
|
||||
result = {
|
||||
code: '403',
|
||||
message: "Partner User doesn't exists.",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFRESH-TOKEN-PARTNER-USER ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// generate new access token
|
||||
accessToken = await jwt.generateAccessToken({
|
||||
partner_id: helper.encryptText(checkDataLoginPartnerUser.i_partner),
|
||||
partner_user_id: helper.encryptText(
|
||||
checkDataLoginPartnerUser.i_partner_user
|
||||
),
|
||||
});
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: generating refresh token...`
|
||||
// );
|
||||
|
||||
// generate new refresh token
|
||||
refreshToken = await jwt.generateRefreshToken({
|
||||
partner_id: helper.encryptText(checkDataLoginPartnerUser.i_partner),
|
||||
partner_user_id: helper.encryptText(
|
||||
checkDataLoginPartnerUser.i_partner_user
|
||||
),
|
||||
});
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING REFRESH-TOKEN-PARTNER-USER ]: updating refresh token...`
|
||||
// );
|
||||
|
||||
// update insert refresh token
|
||||
await model.updateRefreshTokenPartner(email, refresh_token, refreshToken);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'New Token has been generated.',
|
||||
data: {
|
||||
access_token: accessToken,
|
||||
refresh_token: refreshToken,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
// winston.logger.info(
|
||||
// `${uniqueCode} [ RESPONSE REFRESH-TOKEN-PARTNER-USER ]: ${JSON.stringify(
|
||||
// result
|
||||
// )}`
|
||||
// );
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE REFRESH-TOKEN-PARTNER-USER ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ================================================================= GET TID MID =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *Description:*
|
||||
// fungsi yang digunakan menampilkan data tid dan mid berdasarkan token partner
|
||||
|
||||
const getTIDMID = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
let partner_id = req.partner_id_token;
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST GET-TID-MID ]: ${JSON.stringify(partner_id)}`
|
||||
);
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let getTIDMID = await model.getTIDMID(partner_id);
|
||||
if (!getTIDMID) {
|
||||
return res.status(200).json({
|
||||
code: '403',
|
||||
message: "TID MID doesn't exists.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Success',
|
||||
data: getTIDMID,
|
||||
};
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE GET-TID-MID ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// ================================================================= GET PARTNER USER =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *Description:*
|
||||
// fungsi yang digunakan menampilkan data profile partner user berdarkan token transaksinya
|
||||
|
||||
const getPartnerUser = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
|
||||
let result = {};
|
||||
let partner_user_id = req.partner_user_id_token;
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST GET-PARTNER-USER ]: ${JSON.stringify(
|
||||
partner_user_id
|
||||
)}`
|
||||
);
|
||||
|
||||
// get partner user detail
|
||||
let partnerUser = await model.getPartnerUser(partner_user_id);
|
||||
if (!partnerUser) {
|
||||
return res.status(200).json({
|
||||
code: '403',
|
||||
message: "Partner User doesn't exists.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Success',
|
||||
data: partnerUser,
|
||||
};
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE GET-PARTNER-USER ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
loginPartnerUser,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
const moment = require('moment');
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./cahsin.model');
|
||||
const model = require('./cashin.model');
|
||||
|
||||
moment.locale('id');
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ const db = require('../../../infrastructure/database/knex');
|
||||
const helper = require('../../helpers/helper');
|
||||
const { logger } = require('../../helpers/winston.logger');
|
||||
const { getSapSettings } = require('../invoiceonline/invoice.model');
|
||||
const model = require('./cahsin.model');
|
||||
const model = require('./cashin.model');
|
||||
|
||||
const preConnectErrors = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ERR_INVALID_URL']);
|
||||
const timeoutMs = 15000;
|
||||
|
||||
+4
-4
@@ -40,7 +40,7 @@ const validate = (method) => {
|
||||
};
|
||||
|
||||
// POSTING INVOICE
|
||||
const apiGenerateCahsIn = async (req, res) => {
|
||||
const apiGenerateCashIn = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
const uniqueCode = helper.getUniqueCode();
|
||||
@@ -271,7 +271,7 @@ const apiGenerateCashInTopUpCashlessInternal = async (req, res) => {
|
||||
};
|
||||
|
||||
// RETRY POSTING CASH IN
|
||||
const apiPostingCahsIn = async (req, res) => {
|
||||
const apiPostingCashIn = async (req, res) => {
|
||||
try {
|
||||
const uniqueCode = helper.getUniqueCode();
|
||||
// log info
|
||||
@@ -326,11 +326,11 @@ const apiPostingCahsIn = async (req, res) => {
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
apiGenerateCahsIn,
|
||||
apiGenerateCashIn,
|
||||
apiGenerateCashInSales,
|
||||
apiGenerateCashInSalesInternal,
|
||||
apiGenerateCashInTopUpCashlessInternal,
|
||||
apiPostingCahsIn,
|
||||
apiPostingCashIn,
|
||||
_postingCashIn,
|
||||
_generateCashIn,
|
||||
_generateCashInSales,
|
||||
@@ -1,233 +0,0 @@
|
||||
const { default: axios } = require('axios');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
var counterDirect = 0;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
if (counterDirect > 1 || counterDirect < 0) {
|
||||
counterDirect = 0;
|
||||
}
|
||||
counterDirect++;
|
||||
|
||||
let { body } = req;
|
||||
// uniqueCode = body.unique_code;
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
uniqueCode = uniqueCode + '' + counterDirect;
|
||||
let result = {};
|
||||
let usingHSMNumber = 1;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
// create log
|
||||
// winston.logger.error(`request to HSM server 2`);
|
||||
|
||||
if (client2.clientAuthenticated == false) {
|
||||
usingHSMNumber = 1;
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} ================================== REDIRECT USING HSM SERVER 1 ==================================}`
|
||||
);
|
||||
useClient = client;
|
||||
} else {
|
||||
usingHSMNumber = 2;
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} ================================== USING HSM SERVER 2 ==================================}`
|
||||
);
|
||||
useClient = client2;
|
||||
}
|
||||
} else {
|
||||
if (client.clientAuthenticated == false) {
|
||||
usingHSMNumber = 2;
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} ================================== REDIRECT USING HSM SERVER 2 ==================================}`
|
||||
);
|
||||
useClient = client2;
|
||||
} else {
|
||||
usingHSMNumber = 1;
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} ================================== USING HSM SERVER 1 ==================================}`
|
||||
);
|
||||
useClient = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-1 ]: STARTING TOP UP...`
|
||||
);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-1 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
let felicaPollingResponse = Buffer.from(
|
||||
generate.hexToBytes(body.requestData)
|
||||
);
|
||||
let _stopMessage = 1;
|
||||
let _timeOut = false;
|
||||
|
||||
let _validasi = body.requestData.slice(4, 20);
|
||||
|
||||
let transactionId = Buffer.from([0x00, 0x00]);
|
||||
let apiId = Buffer.from([0x01]);
|
||||
reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
felicaPollingResponse
|
||||
);
|
||||
|
||||
useClient.sendData(reqData);
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
setInterval(function () {
|
||||
respData = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
|
||||
_timeOut = true;
|
||||
}, 10000);
|
||||
|
||||
useClient.ws.on('message', (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14, 30);
|
||||
while (
|
||||
message[2] == 1 &&
|
||||
_stopMessage == 1 &&
|
||||
_validasi.toLowerCase() == __validasi.toLowerCase()
|
||||
) {
|
||||
respData = null;
|
||||
// console.log('*WS MESSAGE Auth1v2: ' + generate.buf2hex(message));
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-1 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
});
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
if (_timeOut) {
|
||||
let url = `http://${process.env.IP_HSM_SERVER_1}/feliqserver/v1/api/hsm/refresh`;
|
||||
if (usingHSMNumber == 2) {
|
||||
url = `http://${process.env.IP_HSM_SERVER_2}/feliqserver/v1/api/hsm/refresh`;
|
||||
}
|
||||
|
||||
let response = await axios({
|
||||
url: url,
|
||||
method: 'get',
|
||||
});
|
||||
|
||||
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;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
if (respData1) {
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Request Authenticate 1 Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
unique_code: uniqueCode,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: '5004',
|
||||
message: 'Empty Data from HSM',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
unique_code: uniqueCode,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-1 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-1 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,184 +0,0 @@
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-2 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
// create log
|
||||
// winston.logger.error(`request to HSM server 2`);
|
||||
|
||||
if (client2.clientAuthenticated == false) {
|
||||
useClient = client;
|
||||
} else {
|
||||
useClient = client2;
|
||||
}
|
||||
} else {
|
||||
if (client.clientAuthenticated == false) {
|
||||
useClient = client2;
|
||||
} else {
|
||||
useClient = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let _validationTrxID = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
let _timeOut = false;
|
||||
|
||||
if (auth2v2requestData[0] != 0x41) {
|
||||
result = {
|
||||
code: '5003',
|
||||
message: 'Wrong Respone from Card',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x02]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
auth2v2requestData
|
||||
);
|
||||
|
||||
useClient.sendData(reqData);
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
setInterval(function () {
|
||||
respData = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
|
||||
_timeOut = true;
|
||||
}, 10000);
|
||||
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 2 &&
|
||||
message[0] == _validationTrxID[0] &&
|
||||
message[1] == _validationTrxID[1] &&
|
||||
_stopMessage == 1
|
||||
) {
|
||||
respData = null;
|
||||
// console.log("*WS MESSAGE Auth2v2: " + generate.buf2hex(message));
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-2 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
});
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
if (_timeOut) {
|
||||
result = {
|
||||
code: '5001',
|
||||
message: 'Timeout',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-2 ]: message from HSM ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Request Authenticate 2 Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-2 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,163 +0,0 @@
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-3 ]: request to HSM ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
// create log
|
||||
// winston.logger.error(`request to HSM server 2`);
|
||||
|
||||
if (client2.clientAuthenticated == false) {
|
||||
useClient = client;
|
||||
} else {
|
||||
useClient = client2;
|
||||
}
|
||||
} else {
|
||||
if (client.clientAuthenticated == false) {
|
||||
useClient = client2;
|
||||
} else {
|
||||
useClient = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let auth2v2responseSetData = Buffer.from(
|
||||
generate.hexToBytes(body.requestData)
|
||||
);
|
||||
let _stopMessage = 1;
|
||||
// console.log("Req Auth Resp: " + body.requestData);
|
||||
|
||||
if (auth2v2responseSetData[0] != 0x43) {
|
||||
result = {
|
||||
code: '5003',
|
||||
message: 'Wrong Respone from Card',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-3 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x03]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
auth2v2responseSetData
|
||||
);
|
||||
|
||||
useClient.sendData(reqData);
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 3 &&
|
||||
message[0] == transactionId[0] &&
|
||||
message[1] == transactionId[1] &&
|
||||
_stopMessage == 1
|
||||
) {
|
||||
respData = null;
|
||||
// console.log("*WS MESSAGE auth2v2 Resp: " + generate.buf2hex(message));
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-3 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
});
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Request Authenticate Resp Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-3 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-3 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,142 +0,0 @@
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-8 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
// create log
|
||||
// winston.logger.error(`request to HSM server 2`);
|
||||
|
||||
if (client2.clientAuthenticated == false) {
|
||||
useClient = client;
|
||||
} else {
|
||||
useClient = client2;
|
||||
}
|
||||
} else {
|
||||
if (client.clientAuthenticated == false) {
|
||||
useClient = client2;
|
||||
} else {
|
||||
useClient = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
|
||||
let transactionEnd = Buffer.from([]);
|
||||
let apiId = Buffer.from([0x06]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
transactionEnd
|
||||
);
|
||||
let _stopMessage = 1;
|
||||
|
||||
useClient.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 6 &&
|
||||
message[0] == transactionId[0] &&
|
||||
message[1] == transactionId[1] &&
|
||||
_stopMessage == 1
|
||||
) {
|
||||
respData = null;
|
||||
// console.log("*WS MESSAGE EndTrx: " + generate.buf2hex(message));
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-8 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
});
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'End Transaction Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-8 ]: ENDING TOP UP... ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-8 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,146 +0,0 @@
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-4 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
// create log
|
||||
// winston.logger.error(`request to HSM server 2`);
|
||||
|
||||
if (client2.clientAuthenticated == false) {
|
||||
useClient = client;
|
||||
} else {
|
||||
useClient = client2;
|
||||
}
|
||||
} else {
|
||||
if (client.clientAuthenticated == false) {
|
||||
useClient = client2;
|
||||
} else {
|
||||
useClient = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
|
||||
let apiId = Buffer.from([0x04]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
trxrequestData
|
||||
);
|
||||
|
||||
useClient.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 4 &&
|
||||
message[0] == transactionId[0] &&
|
||||
message[1] == transactionId[1] &&
|
||||
_stopMessage == 1
|
||||
) {
|
||||
respData = null;
|
||||
// console.log(
|
||||
// "*WS MESSAGE Transmit Packet: " + generate.buf2hex(message)
|
||||
// );
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-4 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
});
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-4 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-4 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,157 +0,0 @@
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-5 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
// create log
|
||||
// winston.logger.error(`request to HSM server 2`);
|
||||
|
||||
if (client2.clientAuthenticated == false) {
|
||||
useClient = client;
|
||||
} else {
|
||||
useClient = client2;
|
||||
}
|
||||
} else {
|
||||
if (client.clientAuthenticated == false) {
|
||||
useClient = client2;
|
||||
} else {
|
||||
useClient = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let packet = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
if (packet[0] != 0x45) {
|
||||
result = {
|
||||
code: '03',
|
||||
message: 'Respone Card Wrong',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-5 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x05]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, packet);
|
||||
useClient.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 5 &&
|
||||
message[0] == transactionId[0] &&
|
||||
message[1] == transactionId[1] &&
|
||||
_stopMessage == 1
|
||||
) {
|
||||
respData = null;
|
||||
// console.log(
|
||||
// "*WS MESSAGE Received Packet: " + generate.buf2hex(message)
|
||||
// );
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-5 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
});
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-5 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-5 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,51 +0,0 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
require("dotenv").config();
|
||||
|
||||
// Get Service Code, Block, dan System Code
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
// check service block
|
||||
if (
|
||||
process.env.SERVICEBLOCK_SERVICE_MUTUAL == "" ||
|
||||
process.env.SERVICEBLOCK_BLOCK_READ == "" ||
|
||||
process.env.SERVICEBLOCK_BLOCK_WRITE == ""
|
||||
) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`PLEASE CONFIGURE SERVICE BLOCK ON THE ENVIRONMENT!`
|
||||
);
|
||||
}
|
||||
|
||||
let sytemCode = "939E";
|
||||
let serviceReadNS = "4B1017208B20";
|
||||
let blockReadNS = "800081008200";
|
||||
let serviceMutual = process.env.SERVICEBLOCK_SERVICE_MUTUAL;
|
||||
let blockReadS = process.env.SERVICEBLOCK_BLOCK_READ;
|
||||
let blockWrite = process.env.SERVICEBLOCK_BLOCK_WRITE;
|
||||
let locFlag = 15;
|
||||
return res.status(200).send({
|
||||
code: "00",
|
||||
message: "Get Service Succeess",
|
||||
data: {
|
||||
sysCode: sytemCode,
|
||||
sReadNS: serviceReadNS,
|
||||
sMutual: serviceMutual,
|
||||
bReadNS: blockReadNS,
|
||||
bReadS: blockReadS,
|
||||
bWrite: blockWrite,
|
||||
lFlag: locFlag,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: "5001",
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,265 +0,0 @@
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const loadBalance = require('../loadbalance/loadbalance.controller');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'topup':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('uid').not().isEmpty().withMessage('UID is required'),
|
||||
body('flag').not().isEmpty().withMessage('Flag is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card Number is required'),
|
||||
body('amount')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Amount is required')
|
||||
.isNumeric()
|
||||
.withMessage('Amount is invalid format'),
|
||||
body('reservation_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Reservation Number is required')
|
||||
.isArray()
|
||||
.withMessage('Reservation Number is invalid request format'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let {
|
||||
mid,
|
||||
tid,
|
||||
card_number,
|
||||
amount,
|
||||
reservation_number,
|
||||
ref_no,
|
||||
write_status,
|
||||
uid,
|
||||
balance,
|
||||
flag,
|
||||
execution_id,
|
||||
unique_code,
|
||||
trxID,
|
||||
requestData,
|
||||
} = req.body;
|
||||
|
||||
let uniqueCode = unique_code;
|
||||
let result = {};
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
// create log
|
||||
// winston.logger.error(`request to HSM server 2`);
|
||||
|
||||
if (client2.clientAuthenticated == false) {
|
||||
useClient = client;
|
||||
} else {
|
||||
useClient = client2;
|
||||
}
|
||||
} else {
|
||||
if (client.clientAuthenticated == false) {
|
||||
useClient = client2;
|
||||
} else {
|
||||
useClient = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-6 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// check validator
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-6 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(trxID));
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(requestData));
|
||||
let _stopMessage = 1;
|
||||
let execID;
|
||||
if (execution_id) {
|
||||
execID = execution_id;
|
||||
} else {
|
||||
let execByte = Buffer.alloc(2);
|
||||
trxrequestData.copy(execByte, 0, 24, 26);
|
||||
execID = generate.buf2hex(execByte);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x04]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
trxrequestData
|
||||
);
|
||||
|
||||
useClient.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 4 &&
|
||||
message[0] == transactionId[0] &&
|
||||
message[1] == transactionId[1] &&
|
||||
_stopMessage == 1
|
||||
) {
|
||||
respData = null;
|
||||
// console.log(
|
||||
// "*WS MESSAGE Transmit Packet: " + generate.buf2hex(message)
|
||||
// );
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-6 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
});
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-6 ]: inserting load balance transaction...`
|
||||
);
|
||||
|
||||
let data = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
card_number: card_number,
|
||||
amount: amount,
|
||||
reservation_number: reservation_number,
|
||||
ref_no: ref_no,
|
||||
write_status: write_status,
|
||||
uid: uid,
|
||||
balance: balance,
|
||||
flag: flag,
|
||||
unique_code: unique_code,
|
||||
execution_id: execID,
|
||||
};
|
||||
|
||||
// insert data load balance
|
||||
let insert = await loadBalance.loadingBalanceInsert(req, data);
|
||||
if (insert) {
|
||||
if (insert.code == '00') {
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Generate Write Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
load_balance_number: insert.data.load_balance_number,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: insert.code,
|
||||
message: insert.message,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '423',
|
||||
message: 'update/insert failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-6 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-6 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
controller,
|
||||
};
|
||||
@@ -1,318 +0,0 @@
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const loadBalance = require('../loadbalance/loadbalance.controller');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'topupResponse':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('uid').not().isEmpty().withMessage('UID is required'),
|
||||
body('flag').not().isEmpty().withMessage('Flag is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card Number is required'),
|
||||
body('amount')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Amount is required')
|
||||
.isNumeric()
|
||||
.withMessage('Amount is invalid format'),
|
||||
body('reservation_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Reservation Number is required')
|
||||
.isArray()
|
||||
.withMessage('Reservation Number is invalid request format'),
|
||||
body('load_balance_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Load Balance Number is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let {
|
||||
mid,
|
||||
tid,
|
||||
card_number,
|
||||
amount,
|
||||
reservation_number,
|
||||
ref_no,
|
||||
uid,
|
||||
balance,
|
||||
flag,
|
||||
unique_code,
|
||||
load_balance_number,
|
||||
trxID,
|
||||
requestData,
|
||||
} = req.body;
|
||||
|
||||
let uniqueCode = unique_code;
|
||||
let result = {};
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
// create log
|
||||
// winston.logger.error(`request to HSM server 2`);
|
||||
|
||||
if (client2.clientAuthenticated == false) {
|
||||
useClient = client;
|
||||
} else {
|
||||
useClient = client2;
|
||||
}
|
||||
} else {
|
||||
if (client.clientAuthenticated == false) {
|
||||
useClient = client2;
|
||||
} else {
|
||||
useClient = client;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// case success write to the card but loss contact with device
|
||||
// result = {
|
||||
// code: "100",
|
||||
// message: "failed topup",
|
||||
// data: {},
|
||||
// };
|
||||
// return res.status(200).send(result);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-7 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(trxID));
|
||||
let packet = Buffer.from(generate.hexToBytes(requestData));
|
||||
let _stopMessage = 1;
|
||||
if (packet[0] != 0x47) {
|
||||
result = {
|
||||
code: '03',
|
||||
message: 'Respone Card Wrong',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-7 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x05]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, packet);
|
||||
useClient.sendData(reqData);
|
||||
|
||||
let respCode = null;
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 5 &&
|
||||
message[0] == transactionId[0] &&
|
||||
message[1] == transactionId[1] &&
|
||||
_stopMessage == 1
|
||||
) {
|
||||
respData = null;
|
||||
// console.log(
|
||||
// "*WS MESSAGE Received Packet: " + generate.buf2hex(message)
|
||||
// );
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
});
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
respCode = generate.getResponseCode(respData);
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
let data = {};
|
||||
|
||||
if (
|
||||
respData[6] != 0x47 ||
|
||||
(respData1[9] != 0x00 && respData1[10] != 0x00)
|
||||
) {
|
||||
data = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
card_number: card_number,
|
||||
amount: amount,
|
||||
reservation_number: reservation_number,
|
||||
ref_no: ref_no,
|
||||
write_status: 'FW',
|
||||
uid: uid,
|
||||
balance: parseInt(balance) + parseInt(amount),
|
||||
flag: parseInt(flag),
|
||||
unique_code: unique_code,
|
||||
load_balance_number: load_balance_number,
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: updating load balance transaction is FW...`
|
||||
);
|
||||
|
||||
// update data load balance
|
||||
let update = await loadBalance.loadingBalanceUpdate(data);
|
||||
if (update) {
|
||||
if (update.code == '00') {
|
||||
result = {
|
||||
code: '5002',
|
||||
message: 'failed from HSM',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respData1.slice(6, 10),
|
||||
transcode: null,
|
||||
load_balance_number: update.data.load_balance_number,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: update.code,
|
||||
message: update.message,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '423',
|
||||
message: 'update/insert failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// jika sudah mencapai maksimum counting flag, maka reset flag ke awal
|
||||
if (flag >= 255) {
|
||||
flag = -1;
|
||||
}
|
||||
|
||||
data = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
card_number: card_number,
|
||||
amount: amount,
|
||||
reservation_number: reservation_number,
|
||||
ref_no: ref_no,
|
||||
write_status: null,
|
||||
uid: uid,
|
||||
balance: balance,
|
||||
flag: flag ? parseInt(flag) + 1 : flag,
|
||||
unique_code: unique_code,
|
||||
load_balance_number: load_balance_number,
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: updating load balance transaction...`
|
||||
);
|
||||
|
||||
// update data load balance
|
||||
let update = await loadBalance.loadingBalanceUpdate(data);
|
||||
if (update) {
|
||||
if (update.code == '00') {
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Topup Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
load_balance_number: update.data.load_balance_number,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: update.code,
|
||||
message: update.message,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '423',
|
||||
message: 'update/insert failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-7 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-7 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { validate, controller };
|
||||
@@ -0,0 +1,789 @@
|
||||
const { logCorrelation, logErrorCode, logStatusCode } = require('../../helpers/log-fields');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { validationResult } = require('express-validator');
|
||||
const model = require('./loadbalance.model');
|
||||
const moment = require('moment');
|
||||
const { updateAllTransaction } = require('./load-balance-write.service');
|
||||
|
||||
// Tangani permintaan saldo dan jalankan pembaruan reservasi sesuai hasil pengecekan.
|
||||
const loadingBalanceRequest = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
// let { mid, tid, card_number, uid, balance, flag, unique_code } = req.body;
|
||||
|
||||
let mid = req.body.mid;
|
||||
let tid = req.body.tid;
|
||||
let card_number = req.body.card_number;
|
||||
let uid = req.body.uid;
|
||||
let balance = req.body.balance;
|
||||
let flag = req.body.flag;
|
||||
let unique_code = req.body.unique_code;
|
||||
|
||||
// uniqueCode = await helper.getUniqueCode();
|
||||
let uniqueCode = unique_code;
|
||||
let result = {};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ REQUEST LOADING-BALANCE-REQUEST ]`
|
||||
);
|
||||
|
||||
// check validator
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let cardBlacklist = await model.getCardBlacklist(card_number);
|
||||
if (cardBlacklist) {
|
||||
if (cardBlacklist.c_status == 'B') {
|
||||
result = {
|
||||
code: '445',
|
||||
message: 'Card is Blacklisted',
|
||||
data: {},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking production card number or not...`
|
||||
// );
|
||||
|
||||
// jika settingan untuk server adalah production
|
||||
// if (process.env.SERVER_FOR == 'production') {
|
||||
// // jika settingan production maka nomor kartu yang di request harus berawalan angka 1, jika bukan angka 1 maka ditolak
|
||||
// if (card_number.substring(0, 1) != '1') {
|
||||
// result = {
|
||||
// code: '400',
|
||||
// message: "It's not production card number.",
|
||||
// data: {},
|
||||
// };
|
||||
|
||||
// // log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
|
||||
// result
|
||||
// )}`
|
||||
// );
|
||||
|
||||
// return res.status(200).json(result);
|
||||
// }
|
||||
// } else {
|
||||
// // jika settingan bukan production, bisa development atau local maka jika ada nomor kartu berawalan angka 1 maka ditolak
|
||||
// if (card_number.substring(0, 1) == '1') {
|
||||
// result = {
|
||||
// code: '400',
|
||||
// message:
|
||||
// "It's production card number. Please use the development card number.",
|
||||
// data: {},
|
||||
// };
|
||||
|
||||
// // log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST ]: ${JSON.stringify(
|
||||
// result
|
||||
// )}`
|
||||
// );
|
||||
|
||||
// return res.status(200).json(result);
|
||||
// }
|
||||
// }
|
||||
|
||||
// time
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
let year = moment().format('Y');
|
||||
let month = moment().format('M');
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking partner...`
|
||||
// );
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
if (!getPartner) {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'terminal id is not valid',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
if (getPartner.i_partner != req.partner_id_token) {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'partner is not match',
|
||||
data: {},
|
||||
};
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// get parameter setting pengecekkan nomor kartu dengan card product di CMS
|
||||
let getCheckByCardProductStatusValue =
|
||||
await model.getCheckByCardProductStatusValue();
|
||||
|
||||
// check value global parameter
|
||||
if (!getCheckByCardProductStatusValue) {
|
||||
result = {
|
||||
code: '439',
|
||||
message: 'HSM_CHECK_BY_CARD_PRODUCT_STAT in global parameter not found',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let checkByCardProductStatusValue =
|
||||
getCheckByCardProductStatusValue.c_value;
|
||||
|
||||
// jika settingan pengecekkan nomor kartu dengan card product CMS aktif
|
||||
if (checkByCardProductStatusValue == 'A') {
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking card number...`
|
||||
// );
|
||||
|
||||
// check card number request dengan list card number yang terdaftar di CMS
|
||||
let checkCardNumber = await model.checkCardNumber(card_number);
|
||||
|
||||
// jika nomor kartu yang di request di terdaftar di CMS maka di tolak
|
||||
if (!checkCardNumber) {
|
||||
result = {
|
||||
code: '413',
|
||||
message: 'card number is not registered',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${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
|
||||
let checkFlag = await model.checkFlag(card_number, uid.toUpperCase());
|
||||
let lastFlag = null;
|
||||
|
||||
// jika flag atas nomor kartu dan uid yang di request ditemukan di CMS maka set flag terkahir kartu seperti data dari CMS
|
||||
if (checkFlag) {
|
||||
lastFlag = checkFlag.c_flag;
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending...`
|
||||
// );
|
||||
|
||||
// get total reservation pending
|
||||
let getReservationPending = await model.getReservationPendingV2(
|
||||
card_number,
|
||||
now,
|
||||
flag
|
||||
);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking fraud transaction...`
|
||||
// );
|
||||
|
||||
// cek disini apakah sebelumnya topup
|
||||
let cardHistory = await model.checkCardHistory(card_number);
|
||||
|
||||
if (cardHistory.length > 0) {
|
||||
if (cardHistory.i_log_name == 21 && cardHistory.c_source == 'CMS') {
|
||||
if (getReservationPending.length > 0) {
|
||||
// insert semua reserve balance ke fraud
|
||||
let dataFraud = [];
|
||||
let rsv = [];
|
||||
for (let item of getReservationPending) {
|
||||
rsv.push(item.c_reservation_no);
|
||||
dataFraud.push({
|
||||
c_card_number: item.c_card_number,
|
||||
c_reservation_no: item.c_reservation_no,
|
||||
i_reservation_amount: parseInt(item.i_reservation_amount),
|
||||
c_reservation_status: item.c_status,
|
||||
c_reservation_flag: item.c_flag,
|
||||
c_reservation_ref_no: item.c_ref_no,
|
||||
});
|
||||
}
|
||||
winston.logger.debug(
|
||||
`${logCorrelation(uniqueCode)} [ LOAD BALANCE FRAUD CANDIDATES ] count=${dataFraud.length}`
|
||||
);
|
||||
await model.insertFraud(dataFraud);
|
||||
// log debug
|
||||
|
||||
// update reserve balance
|
||||
await model.updateFraudToReserve(rsv);
|
||||
} else {
|
||||
result = {
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST updateFraudToReserve ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// get total reservation pending with compare flag counter on card and the reservation transaction
|
||||
// where status != -1
|
||||
let getReservationPendingWithFlagCounter =
|
||||
await model.getReservationPendingWithFlagCounter(card_number, now, flag);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending with flag...`
|
||||
// );
|
||||
// get total reservation pending
|
||||
// let getReservationPendingWithFlag =
|
||||
// await model.getReservationPendingWithFlag(card_number, now);
|
||||
|
||||
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 1.1 ]: ${JSON.stringify(
|
||||
// getReservationPending
|
||||
// )}`
|
||||
// );
|
||||
|
||||
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 2 ]: ${JSON.stringify(req.body)}`
|
||||
// );
|
||||
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 2.1 ]: ${flag}`
|
||||
// );
|
||||
|
||||
if (getReservationPendingWithFlagCounter.length > 0) {
|
||||
if (lastFlag) {
|
||||
|
||||
|
||||
// manipulasi last flag jika flag kartu sudah kembali ke 0
|
||||
if (parseInt(lastFlag) == 255 && parseInt(flag) == 0) {
|
||||
lastFlag = -1
|
||||
}
|
||||
|
||||
if (parseInt(lastFlag) < parseInt(flag)) {
|
||||
|
||||
|
||||
let reservationNumberPendingSuccessLoaded = [];
|
||||
let loadBalanceNumberPendingSuccessLoaded = [];
|
||||
let totalReservationAmount = 0;
|
||||
|
||||
getReservationPendingWithFlagCounter.forEach((element) => {
|
||||
reservationNumberPendingSuccessLoaded.push(
|
||||
element.c_reservation_no
|
||||
);
|
||||
if (element.c_load_balance_no) {
|
||||
loadBalanceNumberPendingSuccessLoaded.push(
|
||||
element.c_load_balance_no
|
||||
);
|
||||
}
|
||||
totalReservationAmount += parseInt(element.i_reservation_amount);
|
||||
});
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: updating reservation and load balance transaction...`
|
||||
// );
|
||||
|
||||
// update
|
||||
let insertUpdate = await updateAllTransaction(
|
||||
reservationNumberPendingSuccessLoaded,
|
||||
loadBalanceNumberPendingSuccessLoaded,
|
||||
mid,
|
||||
tid,
|
||||
card_number,
|
||||
balance,
|
||||
flag,
|
||||
uniqueCode,
|
||||
totalReservationAmount,
|
||||
uid
|
||||
);
|
||||
|
||||
if (insertUpdate) {
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSINGE LOADING-BALANCE-REQUEST ]: updating flag to server...`
|
||||
// );
|
||||
|
||||
// update flag from Server
|
||||
await model.updateFlag(
|
||||
now,
|
||||
card_number,
|
||||
uid.toUpperCase(),
|
||||
balance,
|
||||
flag
|
||||
);
|
||||
|
||||
result = {
|
||||
code: '01',
|
||||
message: 'your card number has been cleared successfully',
|
||||
data: {
|
||||
load_balance_number: loadBalanceNumberPendingSuccessLoaded[0],
|
||||
amount: parseInt(totalReservationAmount),
|
||||
total_reservation: getReservationPendingWithFlagCounter.length,
|
||||
reservation_number: reservationNumberPendingSuccessLoaded,
|
||||
partial_topup: false,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: '423',
|
||||
message: 'updated failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
if (getReservationPending.length < 1) {
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(`${uniqueCode} updating flag to server...`);
|
||||
|
||||
// // update flag from Server
|
||||
// await model.updateFlag(now, card_number, uid.toUpperCase(), balance, flag);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking reservation pending...`
|
||||
// );
|
||||
|
||||
// reget total reservation pending
|
||||
getReservationPending = await model.getReservationPendingV2(
|
||||
card_number,
|
||||
now,
|
||||
flag
|
||||
);
|
||||
|
||||
if (getReservationPending.length < 1) {
|
||||
result = {
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST getReservationPending ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let partialTopup = false;
|
||||
let totalReservation = 0;
|
||||
let amountTopup = 0;
|
||||
let reservationNumber = [];
|
||||
let reservationNumberTemp = [];
|
||||
let i = 0;
|
||||
getReservationPending.forEach((rsv) => {
|
||||
amountTopup += parseInt(rsv.i_reservation_amount);
|
||||
reservationNumber.push(rsv.c_reservation_no);
|
||||
reservationNumberTemp.push(rsv.c_reservation_no);
|
||||
i++;
|
||||
});
|
||||
|
||||
totalReservation = i;
|
||||
if (totalReservation == 0) {
|
||||
result = {
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST totalReservation ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking the card number in list fraud transaction or not...XXXXXXXXXXXXXXXXXXXX`
|
||||
// );
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking total topup amount...`
|
||||
// );
|
||||
|
||||
// check total amount topup
|
||||
if (parseInt(amountTopup) <= 0) {
|
||||
result = {
|
||||
code: '415',
|
||||
message: 'amount must be greater than 0',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking BI regulation status...`
|
||||
// );
|
||||
|
||||
// get BI regulation status
|
||||
let getBIRegulationStatus = await model.getBIRegulationStatus();
|
||||
|
||||
// check value global parameter
|
||||
if (!getBIRegulationStatus) {
|
||||
result = {
|
||||
code: '439',
|
||||
message: 'HSM_BI_REGULATION_STAT in global parameter not found',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
if (getBIRegulationStatus.c_value == 'A') {
|
||||
// log debug
|
||||
// winston.logger.debug(`${uniqueCode} checking topup partial status...`);
|
||||
|
||||
// check topup partial status
|
||||
let getTopupPartialStatus = await model.getTopupPartialStatus();
|
||||
|
||||
// check value global parameter
|
||||
if (!getTopupPartialStatus) {
|
||||
result = {
|
||||
code: '439',
|
||||
message: 'HSM_TOPUP_PARTIAL_STAT in global parameter not found',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max balance on the card...`
|
||||
// );
|
||||
|
||||
// get max saldo on the card
|
||||
let getMaxAmountOnTheCard = await model.getMaxAmountOnTheCard();
|
||||
|
||||
// check value global parameter
|
||||
if (!getMaxAmountOnTheCard) {
|
||||
result = {
|
||||
code: '439',
|
||||
message:
|
||||
'HSM_BI_MAX_AMOUNT_ON_THE_CARD in global parameter not found',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
if (getMaxAmountOnTheCard.c_value) {
|
||||
if (
|
||||
parseInt(balance) + parseInt(amountTopup) >
|
||||
parseInt(getMaxAmountOnTheCard.c_value)
|
||||
) {
|
||||
// if topup partial is active
|
||||
if (getTopupPartialStatus.c_value == 'A') {
|
||||
// reset reservation data
|
||||
partialTopup = true;
|
||||
totalReservation = 0;
|
||||
amountTopup = 0;
|
||||
reservationNumber = [];
|
||||
reservationNumberTemp = [];
|
||||
i = 0;
|
||||
|
||||
// sum amount can be topup
|
||||
getReservationPending.forEach((rsv) => {
|
||||
if (
|
||||
parseInt(balance) + parseInt(amountTopup) <=
|
||||
parseInt(getMaxAmountOnTheCard.c_value)
|
||||
) {
|
||||
amountTopup += parseInt(rsv.i_reservation_amount);
|
||||
if (
|
||||
amountTopup > parseInt(getMaxAmountOnTheCard.c_value) ||
|
||||
parseInt(balance) + amountTopup >
|
||||
parseInt(getMaxAmountOnTheCard.c_value)
|
||||
) {
|
||||
amountTopup =
|
||||
amountTopup - parseInt(rsv.i_reservation_amount);
|
||||
i--;
|
||||
} else {
|
||||
reservationNumber.push(rsv.c_reservation_no);
|
||||
reservationNumberTemp.push(rsv.c_reservation_no);
|
||||
}
|
||||
}
|
||||
i++;
|
||||
});
|
||||
|
||||
totalReservation = i;
|
||||
if (totalReservation == 0) {
|
||||
result = {
|
||||
code: '414',
|
||||
message:
|
||||
"reservation doesn't exist. Lowest amount exceeds the maximum balance",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} RESPONSE load balance validate code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '416',
|
||||
message: 'your card number has reached the maximum balance',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: checking max topup per month...`
|
||||
// );
|
||||
|
||||
// get accumulated balance in this month
|
||||
let accumulatedBalance = 0;
|
||||
let getAccumulationBalanceInThisMonthFromCardHistory =
|
||||
await model.getAccumulationBalanceInThisMonthFromCardHistory(
|
||||
card_number,
|
||||
year,
|
||||
month
|
||||
);
|
||||
if (getAccumulationBalanceInThisMonthFromCardHistory) {
|
||||
accumulatedBalance =
|
||||
getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance;
|
||||
}
|
||||
|
||||
// validate max topup per month
|
||||
let getMaxTopupPerMonth = await model.getMaxTopupPerMonth();
|
||||
|
||||
// check value global parameter
|
||||
if (!getMaxTopupPerMonth) {
|
||||
result = {
|
||||
code: '439',
|
||||
message: 'HSM_BI_MAX_TOPUP_PER_MONTH in global parameter not found',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
if (getMaxTopupPerMonth.c_value) {
|
||||
if (
|
||||
parseInt(accumulatedBalance) + parseInt(amountTopup) >
|
||||
parseInt(getMaxTopupPerMonth.c_value)
|
||||
) {
|
||||
// if topup partial is active
|
||||
if (getTopupPartialStatus.c_value == 'A') {
|
||||
// reset reservation data
|
||||
partialTopup = true;
|
||||
totalReservation = 0;
|
||||
amountTopup = 0;
|
||||
reservationNumber = [];
|
||||
reservationNumberTemp = [];
|
||||
i = 0;
|
||||
|
||||
// sum amount can be topup
|
||||
getReservationPending.forEach((rsv) => {
|
||||
if (
|
||||
parseInt(balance) + parseInt(amountTopup) <=
|
||||
parseInt(getMaxAmountOnTheCard.c_value)
|
||||
) {
|
||||
amountTopup += parseInt(rsv.i_reservation_amount);
|
||||
if (
|
||||
amountTopup > parseInt(getMaxAmountOnTheCard.c_value) ||
|
||||
parseInt(balance) + amountTopup >
|
||||
parseInt(getMaxAmountOnTheCard.c_value)
|
||||
) {
|
||||
amountTopup =
|
||||
amountTopup - parseInt(rsv.i_reservation_amount);
|
||||
i--;
|
||||
} else {
|
||||
reservationNumber.push(rsv.c_reservation_no);
|
||||
reservationNumberTemp.push(rsv.c_reservation_no);
|
||||
}
|
||||
}
|
||||
i++;
|
||||
});
|
||||
|
||||
totalReservation = i;
|
||||
if (totalReservation == 0) {
|
||||
result = {
|
||||
code: '417',
|
||||
message:
|
||||
"reservation doesn't exist. Lowest amount exceeds the limit top up for this month",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} RESPONSE load balance validate code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '417',
|
||||
message: 'your card number has been limit top up for this month',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-REQUEST ]: updating status reservation to in progress...${reservationNumberTemp}, ${now}, ${flag}`
|
||||
// );
|
||||
|
||||
// update status to in progress
|
||||
let updateStatusReservation = await model.updateStatusReservation(
|
||||
reservationNumberTemp,
|
||||
now,
|
||||
flag
|
||||
);
|
||||
|
||||
if (updateStatusReservation) {
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'reservation exists',
|
||||
data: {
|
||||
amount: parseInt(amountTopup),
|
||||
total_reservation: totalReservation,
|
||||
reservation_number: reservationNumber,
|
||||
partial_topup: partialTopup,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
} else {
|
||||
result = {
|
||||
code: '434',
|
||||
message: '[434] Failed, please try again later',
|
||||
data: {
|
||||
amount: parseInt(amountTopup),
|
||||
total_reservation: totalReservation,
|
||||
reservation_number: reservationNumber,
|
||||
partial_topup: partialTopup,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-REQUEST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
}
|
||||
|
||||
return res.json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE-REQUEST ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { loadingBalanceRequest };
|
||||
@@ -0,0 +1,816 @@
|
||||
const { logCorrelation, logErrorCode, logStatusCode } = require('../../helpers/log-fields');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./loadbalance.model');
|
||||
const moment = require('moment');
|
||||
|
||||
// Alur tulis saldo dipakai oleh HSM dan proses permintaan saldo.
|
||||
const updateAllTransaction = async (
|
||||
reservationNumber,
|
||||
loadBalanceNumber,
|
||||
mid,
|
||||
tid,
|
||||
cardNumber,
|
||||
balance,
|
||||
flag,
|
||||
uniqueCode,
|
||||
totalReservationAmount,
|
||||
uid
|
||||
) => {
|
||||
try {
|
||||
// log debug
|
||||
winston.logger.debug(`${logCorrelation(uniqueCode)} getting last reservation with flag...`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${logCorrelation(uniqueCode)} getting last load balance transaction...`
|
||||
);
|
||||
|
||||
// get load balance
|
||||
let dataLoadingBalance = null;
|
||||
let dataLoadingBalanceDetail = [];
|
||||
|
||||
if (loadBalanceNumber.length > 0) {
|
||||
let getLastLoadingBalanceFlag = await model.getLastLoadingBalanceFlag(
|
||||
loadBalanceNumber
|
||||
);
|
||||
if (getLastLoadingBalanceFlag) {
|
||||
dataLoadingBalance = getLastLoadingBalanceFlag;
|
||||
}
|
||||
}
|
||||
|
||||
// get detail load balance
|
||||
if (dataLoadingBalance) {
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${logCorrelation(uniqueCode)} getting last load balance detail transaction...`
|
||||
);
|
||||
|
||||
let getLastLoadingBalanceDetailFlag =
|
||||
await model.getLastLoadingBalanceDetailFlag(
|
||||
dataLoadingBalance.i_load_balance
|
||||
);
|
||||
if (getLastLoadingBalanceDetailFlag) {
|
||||
dataLoadingBalanceDetail = getLastLoadingBalanceDetailFlag;
|
||||
}
|
||||
}
|
||||
|
||||
// time
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
|
||||
if (dataLoadingBalance && dataLoadingBalanceDetail.length > 0) {
|
||||
let data = {
|
||||
c_load_balance_no: dataLoadingBalance.c_load_balance_no,
|
||||
d_load_balance: dataLoadingBalance.d_load_balance,
|
||||
c_ref_no: dataLoadingBalance.c_ref_no,
|
||||
i_partner: dataLoadingBalance.i_partner,
|
||||
c_partner_code: dataLoadingBalance.c_partner_code,
|
||||
c_partner_name: dataLoadingBalance.c_partner_name,
|
||||
i_merchant: dataLoadingBalance.i_merchant,
|
||||
c_merchant_code: dataLoadingBalance.c_merchant_code,
|
||||
c_merchant_name: dataLoadingBalance.c_merchant_name,
|
||||
c_mid: dataLoadingBalance.c_mid,
|
||||
i_terminal: dataLoadingBalance.i_terminal,
|
||||
c_terminal_code: dataLoadingBalance.c_terminal_code,
|
||||
c_terminal_name: dataLoadingBalance.c_terminal_name,
|
||||
c_tid: dataLoadingBalance.c_tid,
|
||||
c_card_number: dataLoadingBalance.c_card_number,
|
||||
i_topup_amount: dataLoadingBalance.i_topup_amount,
|
||||
m_balance: dataLoadingBalance.m_balance,
|
||||
c_return_sap: null,
|
||||
i_load_balance_no_seq: dataLoadingBalance.i_load_balance_no_seq,
|
||||
c_idm: dataLoadingBalance.c_idm,
|
||||
c_status: 'A',
|
||||
c_status_name: 'SUCCESS',
|
||||
d_create: now,
|
||||
i_create: null,
|
||||
c_create_username: null,
|
||||
c_create_fullname: null,
|
||||
d_modify: null,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
d_delete: null,
|
||||
i_delete: null,
|
||||
c_delete_username: null,
|
||||
c_delete_fullname: null,
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${logCorrelation(uniqueCode)} updating reservation and load balance transaction...`
|
||||
);
|
||||
|
||||
const cardHistory = {
|
||||
i_log_name: 21,
|
||||
d_log: dataLoadingBalance.d_load_balance,
|
||||
c_card_number: cardNumber,
|
||||
c_source: 'CMS',
|
||||
c_location: getPartner ? getPartner.partner_name : null,
|
||||
m_balance_before: parseInt(dataLoadingBalance.m_balance),
|
||||
m_amount: parseInt(dataLoadingBalance.i_topup_amount),
|
||||
m_balance_after: parseInt(balance),
|
||||
j_new_data: { data: data, detail: dataLoadingBalanceDetail },
|
||||
j_old_data: null,
|
||||
c_note: `LOAD BALANCE ${dataLoadingBalance.i_topup_amount} FROM ${
|
||||
getPartner ? getPartner.partner_name : null
|
||||
} SUCCESSFULLY`,
|
||||
c_status: 'S',
|
||||
d_created: now,
|
||||
i_create: null,
|
||||
c_create_username: 'HSM',
|
||||
c_create_fullname: 'HARDWARE SECURE MODULE',
|
||||
c_category: 'T',
|
||||
};
|
||||
|
||||
return await model.updateReservationAndLoadingBalance(
|
||||
reservationNumber, data, dataLoadingBalanceDetail, now, flag, cardHistory
|
||||
);
|
||||
} else {
|
||||
// insert new load balance transaction by data on card and update data reservation
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${logCorrelation(uniqueCode)} generating and insert new data load balance...`
|
||||
);
|
||||
|
||||
const { number: newLoadBalanceNumber, sequence: loadBalanceNoSequence } =
|
||||
await model.allocateLoadBalanceNumber(getPartner.partner_code, moment(now).format('YYMMDD'));
|
||||
|
||||
let dataLoadBalance = {
|
||||
c_load_balance_no: newLoadBalanceNumber,
|
||||
d_load_balance: now,
|
||||
c_ref_no: null,
|
||||
i_partner: getPartner.i_partner,
|
||||
c_partner_code: getPartner.partner_code,
|
||||
c_partner_name: getPartner.partner_name,
|
||||
i_merchant: getPartner.i_merchant,
|
||||
c_merchant_code: getPartner.merchant_code,
|
||||
c_merchant_name: getPartner.merchant_name,
|
||||
c_mid: getPartner.mid,
|
||||
i_terminal: getPartner.i_terminal,
|
||||
c_terminal_code: getPartner.terminal_code,
|
||||
c_terminal_name: getPartner.terminal_name,
|
||||
c_tid: getPartner.tid,
|
||||
c_card_number: cardNumber,
|
||||
i_topup_amount: totalReservationAmount,
|
||||
m_balance: balance,
|
||||
c_return_sap: null,
|
||||
i_load_balance_no_seq: loadBalanceNoSequence,
|
||||
c_idm: uid,
|
||||
c_status: 'A',
|
||||
c_status_name: 'SUCCESS',
|
||||
d_create: now,
|
||||
i_create: null,
|
||||
c_create_username: null,
|
||||
c_create_fullname: null,
|
||||
d_modify: null,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
d_delete: null,
|
||||
i_delete: null,
|
||||
c_delete_username: null,
|
||||
c_delete_fullname: null,
|
||||
};
|
||||
|
||||
// create detaial load balance
|
||||
let detailLoadBalance =
|
||||
await model.createDetailLoadBalanceFromReservation(reservationNumber);
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} detail load balance with reservation no : ${JSON.stringify(
|
||||
// reservationNumber
|
||||
// )}`
|
||||
// );
|
||||
|
||||
if (detailLoadBalance.length === 0) return false;
|
||||
|
||||
const updated = await model.updateReservationAndInsertLoadingBalance(
|
||||
reservationNumber, dataLoadBalance, detailLoadBalance, now, flag
|
||||
);
|
||||
return typeof updated === 'number' && updated > 0;
|
||||
|
||||
}
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ LOAD BALANCE RECONCILIATION ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const loadingBalanceInsert = async (req, param) => {
|
||||
try {
|
||||
// param
|
||||
let mid = param.mid;
|
||||
let tid = param.tid;
|
||||
let card_number = param.card_number;
|
||||
let amount = param.amount;
|
||||
let reservation_number = param.reservation_number;
|
||||
let ref_no = param.ref_no;
|
||||
let write_status = param.write_status;
|
||||
let uid = param.uid;
|
||||
let balance = param.balance;
|
||||
let flag = param.flag;
|
||||
let unique_code = param.unique_code;
|
||||
let execution_id = param.execution_id;
|
||||
|
||||
let uniqueCode = unique_code ? unique_code : 9999999999999;
|
||||
let result = {};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ REQUEST LOADING-BALANCE-INSERT ]`
|
||||
);
|
||||
|
||||
// time
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
// log warn
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
if (!getPartner) {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'terminal id is not valid',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-INSERT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
if (getPartner.i_partner != req.partner_id_token) {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'partner is not match',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// Pemanggil HSM yang mengirim respons HTTP.
|
||||
return result;
|
||||
}
|
||||
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation status...`
|
||||
// );
|
||||
|
||||
const statuses = await model.findReservationsWithLoadedBalance(reservation_number);
|
||||
const statusByNumber = new Map(statuses.map((status) => [status.c_reservation_no, status]));
|
||||
// Urutan input menentukan respons pertama, walaupun PostgreSQL mengurutkan hasilnya.
|
||||
for (const number of reservation_number) {
|
||||
const reservationStatus = statusByNumber.get(String(number));
|
||||
|
||||
// if reservation doesn't exist or has been canceled
|
||||
if (!reservationStatus) {
|
||||
result = {
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-INSERT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
if (reservationStatus.loaded_id != null) {
|
||||
result = {
|
||||
code: '00',
|
||||
message:
|
||||
'reservation has been successfully loaded on ' +
|
||||
moment(reservationStatus.loaded_at).format('DD MMM YYYY HH:mm:ss'),
|
||||
data: { load_balance_number: reservationStatus.loaded_number },
|
||||
};
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-INSERT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking last log history...`
|
||||
// );
|
||||
|
||||
// get last history by card number
|
||||
let lastHistory = await model.getLastHistory(card_number);
|
||||
|
||||
if (lastHistory) {
|
||||
// if last history card is topup (21 = log name id for topup)
|
||||
if (lastHistory.i_log_name == 21 && lastHistory.c_source == 'CMS') {
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting fraud transaction...`
|
||||
// );
|
||||
|
||||
// insert reservation transaction to fraud table
|
||||
await model.insertFraudTransaction(reservation_number);
|
||||
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: suspending reservation...`
|
||||
// );
|
||||
|
||||
// update reservation with suspend status
|
||||
await model.suspendReservation(reservation_number, now);
|
||||
|
||||
result = {
|
||||
code: '432',
|
||||
message: 'your card number has fraud transaction',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-INSERT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking fraud transaction...`
|
||||
// );
|
||||
|
||||
// get data fraud by card number and status fraud is not closed
|
||||
let fraudTransaction = await model.getFraudTransaction(card_number);
|
||||
let fraudReservationNumber = [];
|
||||
|
||||
if (fraudTransaction.length > 0) {
|
||||
fraudTransaction.forEach((rsv) => {
|
||||
fraudReservationNumber.push(rsv.c_reservation_no);
|
||||
});
|
||||
}
|
||||
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking reservation pending...`
|
||||
// );
|
||||
|
||||
// get total reservation pending without fraud
|
||||
let getReservationPending = await model.getReservationPendingWithoutFraud(
|
||||
card_number,
|
||||
flag,
|
||||
fraudReservationNumber
|
||||
);
|
||||
|
||||
if (getReservationPending.length < 1) {
|
||||
result = {
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-INSERT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking total topup amount...`
|
||||
// );
|
||||
|
||||
// check total topup and request topup
|
||||
let amountTopup = 0;
|
||||
getReservationPending.forEach((rsv) => {
|
||||
amountTopup += parseInt(rsv.i_reservation_amount);
|
||||
});
|
||||
|
||||
if (parseInt(amount) != parseInt(amountTopup)) {
|
||||
result = {
|
||||
code: '418',
|
||||
message: 'topup amount is different',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-INSERT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting reservation detail...`
|
||||
// );
|
||||
|
||||
const detail = [];
|
||||
reservation_number = getReservationPending.map((pending) => pending.c_reservation_no);
|
||||
const reservations = await model.findReservationDetails(reservation_number);
|
||||
const detailByNumber = new Map(reservations.map((reservation) => [reservation.c_reservation_no, reservation]));
|
||||
for (const number of reservation_number) {
|
||||
const reservation = detailByNumber.get(String(number));
|
||||
|
||||
if (!reservation) {
|
||||
result = {
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-INSERT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
detail.push({
|
||||
i_reservation_balance: reservation.i_reservation_balance
|
||||
? reservation.i_reservation_balance
|
||||
: null,
|
||||
c_reservation_no: reservation.i_reservation_balance
|
||||
? reservation.c_reservation_no
|
||||
: null,
|
||||
i_amount: reservation.i_reservation_balance
|
||||
? reservation.i_reservation_amount
|
||||
: null,
|
||||
i_issuer: reservation.i_reservation_balance
|
||||
? reservation.i_issuer
|
||||
: null,
|
||||
i_issuer_code: reservation.i_reservation_balance
|
||||
? reservation.c_issuer_code
|
||||
: null,
|
||||
i_issuer_name: reservation.i_reservation_balance
|
||||
? reservation.c_issuer_name
|
||||
: null,
|
||||
i_issuer_fee: reservation.i_reservation_balance
|
||||
? reservation.i_issuer_fee
|
||||
: null,
|
||||
i_channel: reservation.i_reservation_balance
|
||||
? reservation.i_channel
|
||||
: null,
|
||||
i_channel_code: reservation.i_reservation_balance
|
||||
? reservation.c_channel_code
|
||||
: null,
|
||||
i_channel_name: reservation.i_reservation_balance
|
||||
? reservation.c_channel_name
|
||||
: null,
|
||||
i_channel_fee: reservation.i_reservation_balance
|
||||
? reservation.i_channel_fee
|
||||
: null,
|
||||
});
|
||||
}
|
||||
|
||||
const { number: loadBalanceNumber, sequence: loadBalanceNoSequence } =
|
||||
await model.allocateLoadBalanceNumber(getPartner.partner_code, moment(now).format('YYMMDD'));
|
||||
|
||||
let data = {
|
||||
c_load_balance_no: loadBalanceNumber,
|
||||
d_load_balance: now,
|
||||
c_ref_no: ref_no,
|
||||
i_partner: getPartner ? getPartner.i_partner : null,
|
||||
c_partner_code: getPartner ? getPartner.partner_code : null,
|
||||
c_partner_name: getPartner ? getPartner.partner_name : null,
|
||||
i_merchant: getPartner ? getPartner.i_merchant : null,
|
||||
c_merchant_code: getPartner ? getPartner.merchant_code : null,
|
||||
c_merchant_name: getPartner ? getPartner.merchant_name : null,
|
||||
c_mid: getPartner ? getPartner.mid : null,
|
||||
i_terminal: getPartner ? getPartner.i_terminal : null,
|
||||
c_terminal_code: getPartner ? getPartner.terminal_code : null,
|
||||
c_terminal_name: getPartner ? getPartner.terminal_name : null,
|
||||
c_tid: getPartner ? getPartner.tid : null,
|
||||
c_card_number: card_number,
|
||||
i_execution_id: execution_id,
|
||||
i_topup_amount: amount ? parseInt(amount) : amount,
|
||||
m_balance: balance ? parseInt(balance) : balance,
|
||||
c_return_sap: null,
|
||||
i_load_balance_no_seq: loadBalanceNoSequence,
|
||||
c_idm: uid,
|
||||
c_status: write_status ? 'F' : 'P',
|
||||
c_status_name: write_status ? 'FAILED' : 'PENDING',
|
||||
d_create: now,
|
||||
i_create: null,
|
||||
c_create_username: null,
|
||||
c_create_fullname: null,
|
||||
d_modify: null,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
d_delete: null,
|
||||
i_delete: null,
|
||||
c_delete_username: null,
|
||||
c_delete_fullname: null,
|
||||
};
|
||||
|
||||
// check data load balance by reservation_number exist or not
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: checking load balance transaction has been exists or not...`
|
||||
// );
|
||||
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: inserting load balance transaction...`
|
||||
// );
|
||||
|
||||
// insert transaction
|
||||
let insertLoadingBalance = await model.insertLoadingBalance(
|
||||
data,
|
||||
detail,
|
||||
reservation_number,
|
||||
now,
|
||||
write_status,
|
||||
card_number,
|
||||
uid.toUpperCase(),
|
||||
balance,
|
||||
flag
|
||||
);
|
||||
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [DATA] : ${JSON.stringify(
|
||||
// data
|
||||
// )} [DETAIL] : ${JSON.stringify(detail)} [RSV] : ${JSON.stringify(
|
||||
// reservation_number
|
||||
// )} [NOW] : ${JSON.stringify(now)} [WRITE STATUS] : ${JSON.stringify(
|
||||
// write_status
|
||||
// )} [CARD NUMBER] : ${JSON.stringify(
|
||||
// card_number
|
||||
// )} [UID] : ${JSON.stringify(uid)} [BALANCE] : ${JSON.stringify(
|
||||
// balance
|
||||
// )} [FLAG] : ${JSON.stringify(flag)}`
|
||||
// );
|
||||
if (insertLoadingBalance > 0) {
|
||||
result = {
|
||||
code: '00',
|
||||
message: write_status
|
||||
? 'transaction saved successfully. Err: failed write to the card'
|
||||
: 'balance loaded successfully',
|
||||
data: {
|
||||
load_balance_number: loadBalanceNumber,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-INSERT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
} else {
|
||||
result = {
|
||||
code: '433',
|
||||
message: '[433] Failed, please try again later',
|
||||
data: {
|
||||
load_balance_number: loadBalanceNumber,
|
||||
},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-INSERT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE-INSERT ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
|
||||
return {
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
const loadingBalanceUpdate = async (param) => {
|
||||
let uniqueCode;
|
||||
try {
|
||||
// param
|
||||
let mid = param.mid;
|
||||
let tid = param.tid;
|
||||
let card_number = param.card_number;
|
||||
let amount = param.amount;
|
||||
let reservation_number = param.reservation_number;
|
||||
let ref_no = param.ref_no;
|
||||
let write_status = param.write_status;
|
||||
let uid = param.uid;
|
||||
let balance = param.balance;
|
||||
let flag = param.flag;
|
||||
let unique_code = param.unique_code;
|
||||
let loadBalanceNumber = param.load_balance_number;
|
||||
|
||||
uniqueCode = unique_code || 9999999999999;
|
||||
let result = {};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ REQUEST LOADING-BALANCE-UPDATE ]`
|
||||
);
|
||||
|
||||
// time
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
if (!getPartner) {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'terminal id is not valid',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-UPDATE ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
let data = {
|
||||
d_load_balance: now,
|
||||
c_ref_no: ref_no,
|
||||
m_balance: balance,
|
||||
c_return_sap: null,
|
||||
c_status: write_status ? 'F' : 'A',
|
||||
c_status_name: write_status ? 'FAILED' : 'SUCCESS',
|
||||
d_modify: now,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
};
|
||||
|
||||
// Semua penulisan saling terkait. Kirim sukses hanya setelah transaksi selesai.
|
||||
await model.withLoadBalanceTransaction(async (trx) => {
|
||||
await model.updateLoadingBalance(
|
||||
trx,
|
||||
data,
|
||||
now,
|
||||
write_status,
|
||||
card_number,
|
||||
uid.toUpperCase(),
|
||||
balance,
|
||||
flag,
|
||||
loadBalanceNumber
|
||||
);
|
||||
|
||||
const findDataLoadBalance = await model.findLoadBalance(loadBalanceNumber, trx);
|
||||
let dataLoadBalance = {};
|
||||
let detailLoadBalance = [];
|
||||
|
||||
if (findDataLoadBalance) {
|
||||
const findDataLoadBalanceDetail = await model.findLoadBalanceDetail(
|
||||
findDataLoadBalance.i_load_balance,
|
||||
trx
|
||||
);
|
||||
|
||||
dataLoadBalance = {
|
||||
c_load_balance_no: findDataLoadBalance.c_load_balance_no,
|
||||
d_load_balance: now,
|
||||
c_ref_no: findDataLoadBalance.c_ref_no,
|
||||
i_partner: findDataLoadBalance.i_partner,
|
||||
c_partner_code: findDataLoadBalance.c_partner_code,
|
||||
c_partner_name: findDataLoadBalance.c_partner_name,
|
||||
i_merchant: findDataLoadBalance.i_merchant,
|
||||
c_merchant_code: findDataLoadBalance.c_merchant_code,
|
||||
c_merchant_name: findDataLoadBalance.c_merchant_name,
|
||||
c_mid: findDataLoadBalance.c_mid,
|
||||
i_terminal: findDataLoadBalance.i_terminal,
|
||||
c_terminal_code: findDataLoadBalance.c_terminal_code,
|
||||
c_terminal_name: findDataLoadBalance.c_terminal_name,
|
||||
c_tid: findDataLoadBalance.c_tid,
|
||||
c_card_number: findDataLoadBalance.c_card_number,
|
||||
i_topup_amount: findDataLoadBalance.i_topup_amount,
|
||||
m_balance: findDataLoadBalance.m_balance,
|
||||
c_return_sap: findDataLoadBalance.c_return_sap,
|
||||
i_load_balance_no_seq: findDataLoadBalance.i_load_balance_no_seq,
|
||||
c_idm: findDataLoadBalance.c_idm,
|
||||
c_status: write_status ? 'F' : 'A',
|
||||
c_status_name: write_status ? 'FAILED' : 'SUCCESS',
|
||||
d_create: findDataLoadBalance.d_create,
|
||||
i_create: findDataLoadBalance.i_create,
|
||||
c_create_username: findDataLoadBalance.c_create_username,
|
||||
c_create_fullname: findDataLoadBalance.c_create_fullname,
|
||||
d_modify: now,
|
||||
i_modify: findDataLoadBalance.i_modify,
|
||||
c_modify_username: findDataLoadBalance.c_modify_username,
|
||||
c_modify_fullname: findDataLoadBalance.c_modify_fullname,
|
||||
d_delete: findDataLoadBalance.d_delete,
|
||||
i_delete: findDataLoadBalance.i_delete,
|
||||
c_delete_username: findDataLoadBalance.c_delete_username,
|
||||
c_delete_fullname: findDataLoadBalance.c_delete_fullname,
|
||||
};
|
||||
|
||||
let i = 0;
|
||||
findDataLoadBalanceDetail.forEach((element) => {
|
||||
detailLoadBalance[i] = {
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_amount,
|
||||
i_issuer: element.i_issuer,
|
||||
i_issuer_code: element.c_issuer_code,
|
||||
i_issuer_name: element.c_issuer_name,
|
||||
i_issuer_fee: element.i_issuer_fee,
|
||||
i_channel: element.i_channel,
|
||||
i_channel_code: element.c_channel_code,
|
||||
i_channel_name: element.c_channel_name,
|
||||
i_channel_fee: element.i_channel_fee,
|
||||
};
|
||||
i++;
|
||||
});
|
||||
|
||||
// insert transaction
|
||||
await model.insertLoadingBalanceHistoryOnly(
|
||||
trx,
|
||||
dataLoadBalance,
|
||||
detailLoadBalance,
|
||||
reservation_number,
|
||||
now,
|
||||
write_status,
|
||||
card_number,
|
||||
uid.toUpperCase(),
|
||||
balance,
|
||||
flag
|
||||
);
|
||||
}
|
||||
|
||||
if (!write_status) {
|
||||
// log card history
|
||||
await model.createLoadBalanceLog({
|
||||
i_log_name: 21,
|
||||
d_log: now,
|
||||
c_card_number: card_number,
|
||||
c_source: 'CMS',
|
||||
c_location: getPartner ? getPartner.partner_name : null,
|
||||
m_balance_before: parseInt(balance) > 0 ? parseInt(balance) : 0,
|
||||
m_amount: parseInt(amount),
|
||||
m_balance_after: parseInt(balance) + parseInt(amount),
|
||||
j_new_data: { data: dataLoadBalance, detail: detailLoadBalance },
|
||||
j_old_data: null,
|
||||
c_note: `LOAD BALANCE ${amount} FROM ${
|
||||
getPartner ? getPartner.partner_name : null
|
||||
} SUCCESSFULLY`,
|
||||
c_status: 'S',
|
||||
d_created: now,
|
||||
i_create: null,
|
||||
c_create_username: 'HSM',
|
||||
c_create_fullname: 'HARDWARE SECURE MODULE',
|
||||
c_category: 'T',
|
||||
}, trx);
|
||||
}
|
||||
});
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: write_status
|
||||
? 'transaction saved successfully. Err: failed write to the card'
|
||||
: 'balance loaded successfully',
|
||||
data: {
|
||||
load_balance_number: loadBalanceNumber,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-UPDATE ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE LOADING-BALANCE-UPDATE ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
|
||||
return {
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { updateAllTransaction, loadingBalanceInsert, loadingBalanceUpdate };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -196,7 +196,7 @@ const getReservationPendingWithFlagCounterV2 = (cardNumber, time, flag) => {
|
||||
};
|
||||
|
||||
// GET RESERVATION PENDING WITH FLAG
|
||||
const getReservationPendingWithFlag = (cardNumber, time) => {
|
||||
const getReservationPendingWithFlag = (cardNumber) => {
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
// .sum("i_reservation_amount as total_reservation_amount")
|
||||
// .count("* as total_reservation")
|
||||
@@ -208,7 +208,7 @@ const getReservationPendingWithFlag = (cardNumber, time) => {
|
||||
};
|
||||
|
||||
// GET RESERVATION PENDING WITH FLAG
|
||||
const getReservationPendingWithFlagV2 = (cardNumber, time) => {
|
||||
const getReservationPendingWithFlagV2 = (cardNumber) => {
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
// .sum("i_reservation_amount as total_reservation_amount")
|
||||
// .count("* as total_reservation")
|
||||
@@ -344,129 +344,101 @@ function findReservationDetails(reservationNumbers) {
|
||||
}
|
||||
|
||||
// INSERT LOADING BALANCE
|
||||
function mapLoadBalanceDetails(rows, loadBalanceId, amountField = 'i_amount') {
|
||||
return rows.map((row) => ({
|
||||
i_load_balance: loadBalanceId,
|
||||
i_reservation_balance: row.i_reservation_balance,
|
||||
c_reservation_no: row.c_reservation_no,
|
||||
i_amount: row[amountField],
|
||||
i_issuer: row.i_issuer,
|
||||
i_issuer_code: row.i_issuer_code,
|
||||
i_issuer_name: row.i_issuer_name,
|
||||
i_issuer_fee: row.i_issuer_fee,
|
||||
i_channel: row.i_channel,
|
||||
i_channel_code: row.i_channel_code,
|
||||
i_channel_name: row.i_channel_name,
|
||||
i_channel_fee: row.i_channel_fee,
|
||||
}));
|
||||
}
|
||||
|
||||
function getInsertedLoadBalanceId(row) {
|
||||
const id = typeof row === 'object' && row !== null ? row.i_load_balance : row;
|
||||
if (!id) throw new Error('Database did not return a load balance ID');
|
||||
return id;
|
||||
}
|
||||
|
||||
async function replaceFlagCount(trx, now, cardNumber, uid, balance, flag) {
|
||||
await trx('trx.t_d_flag_counting')
|
||||
.where('c_card_number', cardNumber)
|
||||
.whereRaw('UPPER(c_uid) = ?', [uid])
|
||||
.del();
|
||||
|
||||
return trx('trx.t_d_flag_counting').insert({
|
||||
d_request: now,
|
||||
c_card_number: cardNumber,
|
||||
c_uid: uid,
|
||||
i_balance: balance,
|
||||
c_flag: flag,
|
||||
});
|
||||
}
|
||||
|
||||
function logTransactionFailure(operation, error) {
|
||||
const sqlState = typeof error?.code === 'string' && /^[A-Z0-9]{5}$/.test(error.code)
|
||||
? error.code
|
||||
: 'UNKNOWN';
|
||||
winston.logger.error('Load balance transaction failed | operation=' + operation + ' sqlstate=' + sqlState);
|
||||
}
|
||||
|
||||
const insertLoadingBalance = async (
|
||||
data,
|
||||
detail,
|
||||
reservationNumber,
|
||||
now,
|
||||
writeStatus,
|
||||
_writeStatus,
|
||||
cardNumber,
|
||||
uid,
|
||||
balance,
|
||||
flag
|
||||
) => {
|
||||
return await knex
|
||||
.transaction((trx) => {
|
||||
// Mengembalikan chain memastikan kegagalan SQL memicu rollback otomatis.
|
||||
return knex('trx.t_d_load_balance')
|
||||
.transacting(trx)
|
||||
.insert(data)
|
||||
.returning('i_load_balance')
|
||||
.then((resp) => {
|
||||
let id = typeof resp[0] === 'object' ? resp[0].i_load_balance : resp[0];
|
||||
let loadDetail = [];
|
||||
detail.forEach((element) => {
|
||||
loadDetail.push({
|
||||
i_load_balance: id ? id : id.i_load_balance,
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_amount,
|
||||
i_issuer: element.i_issuer,
|
||||
i_issuer_code: element.i_issuer_code,
|
||||
i_issuer_name: element.i_issuer_name,
|
||||
i_issuer_fee: element.i_issuer_fee,
|
||||
i_channel: element.i_channel,
|
||||
i_channel_code: element.i_channel_code,
|
||||
i_channel_name: element.i_channel_name,
|
||||
i_channel_fee: element.i_channel_fee,
|
||||
});
|
||||
});
|
||||
try {
|
||||
// Header, detail, riwayat, reservasi, dan flag harus tersimpan dalam satu transaksi.
|
||||
const result = await knex.transaction(async (trx) => {
|
||||
const [header] = await trx('trx.t_d_load_balance').insert(data).returning('i_load_balance');
|
||||
await trx('trx.t_d_load_balance_detail').insert(
|
||||
mapLoadBalanceDetails(detail, getInsertedLoadBalanceId(header))
|
||||
);
|
||||
|
||||
// insert detail load balance
|
||||
return knex('trx.t_d_load_balance_detail')
|
||||
.transacting(trx)
|
||||
.insert(loadDetail);
|
||||
})
|
||||
.then(() => {
|
||||
// insert load balance history
|
||||
return knex('trx.t_d_load_balance_history')
|
||||
.transacting(trx)
|
||||
.returning('i_load_balance')
|
||||
.insert(data);
|
||||
})
|
||||
.then((history) => {
|
||||
let id = typeof history[0] === 'object' ? history[0].i_load_balance : history[0];
|
||||
let loadDetail = [];
|
||||
detail.forEach((element) => {
|
||||
loadDetail.push({
|
||||
i_load_balance: id ? id : id.i_load_balance,
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_amount,
|
||||
i_issuer: element.i_issuer,
|
||||
i_issuer_code: element.i_issuer_code,
|
||||
i_issuer_name: element.i_issuer_name,
|
||||
i_issuer_fee: element.i_issuer_fee,
|
||||
i_channel: element.i_channel,
|
||||
i_channel_code: element.i_channel_code,
|
||||
i_channel_name: element.i_channel_name,
|
||||
i_channel_fee: element.i_channel_fee,
|
||||
});
|
||||
});
|
||||
const [history] = await trx('trx.t_d_load_balance_history').insert(data).returning('i_load_balance');
|
||||
await trx('trx.t_d_load_balance_history_detail').insert(
|
||||
mapLoadBalanceDetails(detail, getInsertedLoadBalanceId(history))
|
||||
);
|
||||
|
||||
// insert detail load balance
|
||||
return knex('trx.t_d_load_balance_history_detail')
|
||||
.transacting(trx)
|
||||
.insert(loadDetail);
|
||||
await trx('trx.t_d_reservation_balance')
|
||||
.update({
|
||||
c_status: 'I',
|
||||
c_status_name: 'IN PROGRESS',
|
||||
d_load_balance: now,
|
||||
c_load_balance_no: data.c_load_balance_no,
|
||||
c_flag_code: 'FW',
|
||||
c_flag: flag,
|
||||
d_modify: now,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
})
|
||||
.then(() => {
|
||||
// update reservation
|
||||
return knex('trx.t_d_reservation_balance')
|
||||
.transacting(trx)
|
||||
.update({
|
||||
c_status: 'I',
|
||||
c_status_name: 'IN PROGRESS',
|
||||
d_load_balance: now,
|
||||
c_load_balance_no: data.c_load_balance_no,
|
||||
c_flag_code: 'FW',
|
||||
c_flag: flag,
|
||||
d_modify: now,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
})
|
||||
.whereIn('c_reservation_no', reservationNumber);
|
||||
})
|
||||
.then(() => {
|
||||
// delete flag counting
|
||||
return knex('trx.t_d_flag_counting')
|
||||
.transacting(trx)
|
||||
.where('c_card_number', cardNumber)
|
||||
.whereRaw('UPPER(c_uid) = ?', [uid])
|
||||
.del();
|
||||
})
|
||||
.then(() => {
|
||||
// insert flag counting
|
||||
return knex('trx.t_d_flag_counting').transacting(trx).insert({
|
||||
d_request: now,
|
||||
c_card_number: cardNumber,
|
||||
c_uid: uid,
|
||||
i_balance: balance,
|
||||
c_flag: flag,
|
||||
});
|
||||
});
|
||||
})
|
||||
.then((result) => {
|
||||
return result.rowCount;
|
||||
})
|
||||
.catch((error) => {
|
||||
winston.logger.error(`Load balance insert rolled back | sqlstate=${error.code || 'UNKNOWN'}`);
|
||||
return error.message;
|
||||
.whereIn('c_reservation_no', reservationNumber);
|
||||
|
||||
return replaceFlagCount(trx, now, cardNumber, uid, balance, flag);
|
||||
});
|
||||
return result.rowCount;
|
||||
} catch (error) {
|
||||
logTransactionFailure('insert', error);
|
||||
return error.message;
|
||||
}
|
||||
};
|
||||
|
||||
// UPDATE LOADING BALANCE
|
||||
const updateLoadingBalance = async (
|
||||
trx,
|
||||
data,
|
||||
now,
|
||||
writeStatus,
|
||||
@@ -476,68 +448,35 @@ const updateLoadingBalance = async (
|
||||
flag,
|
||||
loadBalanceNumber
|
||||
) => {
|
||||
await knex
|
||||
.transaction((trx) => {
|
||||
knex('trx.t_d_load_balance')
|
||||
.transacting(trx)
|
||||
.update(data)
|
||||
.where('c_load_balance_no', loadBalanceNumber)
|
||||
.then(() => {
|
||||
// insert load balance history
|
||||
return knex('trx.t_d_load_balance_history')
|
||||
.transacting(trx)
|
||||
.insert(data);
|
||||
})
|
||||
.then(() => {
|
||||
// update reservation
|
||||
return knex('trx.t_d_reservation_balance')
|
||||
.transacting(trx)
|
||||
.update({
|
||||
c_flag_code: writeStatus ? 'FW' : null,
|
||||
c_status: writeStatus ? 'I' : 'A',
|
||||
c_status_name: writeStatus ? 'IN PROGRESS' : 'LOADED',
|
||||
d_load_balance: now,
|
||||
c_load_balance_no: loadBalanceNumber,
|
||||
d_modify: now,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
})
|
||||
.where('c_load_balance_no', loadBalanceNumber);
|
||||
})
|
||||
.then(() => {
|
||||
// delete flag counting
|
||||
return knex('trx.t_d_flag_counting')
|
||||
.transacting(trx)
|
||||
.where('c_card_number', cardNumber)
|
||||
.whereRaw('UPPER(c_uid) = ?', [uid])
|
||||
.del();
|
||||
})
|
||||
.then(() => {
|
||||
// insert flag counting
|
||||
return knex('trx.t_d_flag_counting').transacting(trx).insert({
|
||||
d_request: now,
|
||||
c_card_number: cardNumber,
|
||||
c_uid: uid,
|
||||
i_balance: balance,
|
||||
c_flag: flag,
|
||||
});
|
||||
})
|
||||
.then(trx.commit)
|
||||
.catch(trx.rollback);
|
||||
const updated = await trx('trx.t_d_load_balance')
|
||||
.update(data)
|
||||
.where('c_load_balance_no', loadBalanceNumber);
|
||||
if (updated === 0) {
|
||||
const error = new Error('Load balance was not found');
|
||||
error.code = 'LOAD_BALANCE_NOT_FOUND';
|
||||
throw error;
|
||||
}
|
||||
await trx('trx.t_d_load_balance_history').insert(data);
|
||||
|
||||
await trx('trx.t_d_reservation_balance')
|
||||
.update({
|
||||
c_flag_code: writeStatus ? 'FW' : null,
|
||||
c_status: writeStatus ? 'I' : 'A',
|
||||
c_status_name: writeStatus ? 'IN PROGRESS' : 'LOADED',
|
||||
d_load_balance: now,
|
||||
c_load_balance_no: loadBalanceNumber,
|
||||
d_modify: now,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
})
|
||||
.then((result) => {
|
||||
// console.log(result);
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
.where('c_load_balance_no', loadBalanceNumber);
|
||||
|
||||
await replaceFlagCount(trx, now, cardNumber, uid, balance, flag);
|
||||
};
|
||||
|
||||
// INSERT LOADING BALANCE HISTORY
|
||||
const insertLoadingBalanceHistoryOnly = async (
|
||||
trx,
|
||||
data,
|
||||
detail,
|
||||
reservationNumber,
|
||||
@@ -548,96 +487,37 @@ const insertLoadingBalanceHistoryOnly = async (
|
||||
balance,
|
||||
flag
|
||||
) => {
|
||||
await knex
|
||||
.transaction((trx) => {
|
||||
knex('trx.t_d_load_balance_history')
|
||||
.transacting(trx)
|
||||
.insert(data)
|
||||
.returning('i_load_balance')
|
||||
.then((resp) => {
|
||||
let id = resp[0];
|
||||
let loadDetail = [];
|
||||
detail.forEach((element) => {
|
||||
loadDetail.push({
|
||||
i_load_balance: id.i_load_balance,
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_amount,
|
||||
i_issuer: element.i_issuer,
|
||||
i_issuer_code: element.i_issuer_code,
|
||||
i_issuer_name: element.i_issuer_name,
|
||||
i_issuer_fee: element.i_issuer_fee,
|
||||
i_channel: element.i_channel,
|
||||
i_channel_code: element.i_channel_code,
|
||||
i_channel_name: element.i_channel_name,
|
||||
i_channel_fee: element.i_channel_fee,
|
||||
});
|
||||
});
|
||||
const [history] = await trx('trx.t_d_load_balance_history').insert(data).returning('i_load_balance');
|
||||
await trx('trx.t_d_load_balance_history_detail').insert(
|
||||
mapLoadBalanceDetails(detail, getInsertedLoadBalanceId(history))
|
||||
);
|
||||
|
||||
// insert detail load balance
|
||||
return knex('trx.t_d_load_balance_history_detail')
|
||||
.transacting(trx)
|
||||
.insert(loadDetail);
|
||||
})
|
||||
.then(() => {
|
||||
// update reservation
|
||||
return knex('trx.t_d_reservation_balance')
|
||||
.transacting(trx)
|
||||
.update({
|
||||
c_flag_code: writeStatus ? 'FW' : null,
|
||||
c_status: writeStatus ? 'I' : 'A',
|
||||
c_status_name: writeStatus ? 'IN PROGRESS' : 'LOADED',
|
||||
// d_load_balance: now,
|
||||
// c_load_balance_no: data.c_load_balance_no,
|
||||
d_modify: now,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
})
|
||||
.whereIn('c_reservation_no', reservationNumber);
|
||||
})
|
||||
.then(() => {
|
||||
// delete flag counting
|
||||
return knex('trx.t_d_flag_counting')
|
||||
.transacting(trx)
|
||||
.where('c_card_number', cardNumber)
|
||||
.whereRaw('UPPER(c_uid) = ?', [uid])
|
||||
.del();
|
||||
})
|
||||
.then(() => {
|
||||
// insert flag counting
|
||||
return knex('trx.t_d_flag_counting').transacting(trx).insert({
|
||||
d_request: now,
|
||||
c_card_number: cardNumber,
|
||||
c_uid: uid,
|
||||
i_balance: balance,
|
||||
c_flag: flag,
|
||||
});
|
||||
})
|
||||
.then(trx.commit)
|
||||
.catch(trx.rollback);
|
||||
await trx('trx.t_d_reservation_balance')
|
||||
.update({
|
||||
c_flag_code: writeStatus ? 'FW' : null,
|
||||
c_status: writeStatus ? 'I' : 'A',
|
||||
c_status_name: writeStatus ? 'IN PROGRESS' : 'LOADED',
|
||||
d_modify: now,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
})
|
||||
.then((result) => {
|
||||
// console.log(result);
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
.whereIn('c_reservation_no', reservationNumber);
|
||||
|
||||
await replaceFlagCount(trx, now, cardNumber, uid, balance, flag);
|
||||
};
|
||||
|
||||
// FIND LOAD BALANCE
|
||||
let findLoadBalance = (loadBalanceNumber) => {
|
||||
let result = knex('trx.t_d_load_balance')
|
||||
const findLoadBalance = (loadBalanceNumber, connection = knex) => {
|
||||
const result = connection('trx.t_d_load_balance')
|
||||
.where('c_load_balance_no', loadBalanceNumber)
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// FIND LOAD BALANCE DETAIL
|
||||
let findLoadBalanceDetail = (loadBalanceId) => {
|
||||
let result = knex('trx.t_d_load_balance_detail').where(
|
||||
const findLoadBalanceDetail = (loadBalanceId, connection = knex) => {
|
||||
const result = connection('trx.t_d_load_balance_detail').where(
|
||||
'i_load_balance',
|
||||
loadBalanceId
|
||||
);
|
||||
@@ -655,123 +535,43 @@ const checkFlag = (cardNumber, uid) => {
|
||||
};
|
||||
|
||||
// UPDATE RESERVATION AND LOADING BALANCE CASE FAILED WRITE BEFORE
|
||||
const updateReservationAndLoadingBalance = async (
|
||||
reservationNumber,
|
||||
data,
|
||||
detail,
|
||||
now,
|
||||
flag
|
||||
) => {
|
||||
return await knex
|
||||
.transaction((trx) => {
|
||||
knex('trx.t_d_load_balance')
|
||||
.transacting(trx)
|
||||
.update(data)
|
||||
.where('c_load_balance_no', data.c_load_balance_no)
|
||||
.then(() => {
|
||||
// insert load balance history
|
||||
// winston.logger.debug(
|
||||
// `${reservationNumber} proses insert t_d_load_balance_history updateReservationAndLoadingBalance`
|
||||
// );
|
||||
return knex('trx.t_d_load_balance_history')
|
||||
.transacting(trx)
|
||||
.returning('i_load_balance')
|
||||
.insert(data);
|
||||
})
|
||||
.then((history) => {
|
||||
// winston.logger.debug(
|
||||
// `${JSON.stringify(history)} history t_d_load_balance_history_detail`
|
||||
// );
|
||||
// winston.logger.debug(
|
||||
// `${JSON.stringify(
|
||||
// history[0]
|
||||
// )} id t_d_load_balance_history_detail before parseint`
|
||||
// );
|
||||
let id = history[0];
|
||||
// winston.logger.debug(
|
||||
// `${id} id t_d_load_balance_history_detail id only`
|
||||
// );
|
||||
// winston.logger.debug(
|
||||
// `${id.i_load_balance} id t_d_load_balance_history_detail id.i_load_balance`
|
||||
// );
|
||||
let loadDetail = [];
|
||||
detail.forEach((element) => {
|
||||
loadDetail.push({
|
||||
i_load_balance: id.i_load_balance,
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_amount,
|
||||
i_issuer: element.i_issuer,
|
||||
i_issuer_code: element.i_issuer_code,
|
||||
i_issuer_name: element.i_issuer_name,
|
||||
i_issuer_fee: element.i_issuer_fee,
|
||||
i_channel: element.i_channel,
|
||||
i_channel_code: element.i_channel_code,
|
||||
i_channel_name: element.i_channel_name,
|
||||
i_channel_fee: element.i_channel_fee,
|
||||
});
|
||||
});
|
||||
|
||||
// winston.logger.debug(
|
||||
// `${reservationNumber} proses insert t_d_load_balance_history_detail updateReservationAndLoadingBalance: ${JSON.stringify(
|
||||
// loadDetail
|
||||
// )}`
|
||||
// );
|
||||
// insert detail load balance
|
||||
return knex('trx.t_d_load_balance_history_detail')
|
||||
.transacting(trx)
|
||||
.insert(loadDetail);
|
||||
})
|
||||
.then(() => {
|
||||
// update reservation
|
||||
// winston.logger.debug(
|
||||
// `${reservationNumber} proses update t_d_reservation_balance updateReservationAndLoadingBalance`
|
||||
// );
|
||||
return knex('trx.t_d_reservation_balance')
|
||||
.transacting(trx)
|
||||
.update({
|
||||
d_load_balance: data.d_load_balance,
|
||||
c_load_balance_no: data.c_load_balance_no,
|
||||
c_flag: flag,
|
||||
c_flag_code: null,
|
||||
c_status: 'A',
|
||||
c_status_name: 'LOADED',
|
||||
d_modify: now,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
})
|
||||
.whereIn('c_reservation_no', reservationNumber);
|
||||
})
|
||||
.then(() => {
|
||||
// winston.logger.debug(`${reservationNumber} commit transaction`);
|
||||
return trx.commit();
|
||||
})
|
||||
.catch((error) => {
|
||||
winston.logger.debug(
|
||||
`${reservationNumber} rollback transaction: ${error.message}`
|
||||
);
|
||||
trx.rollback(); // Rollback transaction
|
||||
// throw error; // Rethrow error to outer catch
|
||||
});
|
||||
})
|
||||
.then((result) => {
|
||||
// winston.logger.debug(
|
||||
// `${reservationNumber} result success ${JSON.stringify(result)}}`
|
||||
// );
|
||||
// console.log(result);
|
||||
return true;
|
||||
})
|
||||
.catch((error) => {
|
||||
winston.logger.debug(
|
||||
`${reservationNumber} result error: ${error.message}`
|
||||
const updateReservationAndLoadingBalance = async (reservationNumber, data, detail, now, flag, cardHistory) => {
|
||||
try {
|
||||
await knex.transaction(async (trx) => {
|
||||
const updated = await trx('trx.t_d_load_balance').update(data).where('c_load_balance_no', data.c_load_balance_no);
|
||||
if (updated === 0) throw new Error('Load balance was not found for recovery');
|
||||
const [history] = await trx('trx.t_d_load_balance_history').insert(data).returning('i_load_balance');
|
||||
await trx('trx.t_d_load_balance_history_detail').insert(
|
||||
mapLoadBalanceDetails(detail, getInsertedLoadBalanceId(history))
|
||||
);
|
||||
// console.log(error.message);
|
||||
return false;
|
||||
await markReservationsLoaded(trx, reservationNumber, data, now, flag);
|
||||
// Audit pemulihan harus berhasil sebelum status saldo dan reservasi di-commit.
|
||||
await createLoadBalanceLog(cardHistory, trx);
|
||||
});
|
||||
return true;
|
||||
} catch (error) {
|
||||
logTransactionFailure('update_reservations_and_balance', error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
//
|
||||
function markReservationsLoaded(trx, reservationNumbers, data, now, flag) {
|
||||
return trx('trx.t_d_reservation_balance')
|
||||
.update({
|
||||
d_load_balance: data.d_load_balance,
|
||||
c_load_balance_no: data.c_load_balance_no,
|
||||
c_flag: flag,
|
||||
c_flag_code: null,
|
||||
c_status: 'A',
|
||||
c_status_name: 'LOADED',
|
||||
d_modify: now,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
})
|
||||
.whereIn('c_reservation_no', reservationNumbers);
|
||||
}
|
||||
|
||||
const getLastReservationFlag = (reservationNumber) => {
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.whereIn('c_reservation_no', reservationNumber)
|
||||
@@ -821,34 +621,11 @@ const updateStatusReservation = (reservationNumber, now, flag) => {
|
||||
|
||||
// update flag
|
||||
const updateFlag = async (now, cardNumber, uid, balance, flag) => {
|
||||
await knex
|
||||
.transaction((trx) => {
|
||||
knex('trx.t_d_flag_counting')
|
||||
.transacting(trx)
|
||||
.where('c_card_number', cardNumber)
|
||||
.whereRaw('UPPER(c_uid) = ?', [uid])
|
||||
.del()
|
||||
.then(() => {
|
||||
// insert flag counting
|
||||
return knex('trx.t_d_flag_counting').transacting(trx).insert({
|
||||
d_request: now,
|
||||
c_card_number: cardNumber,
|
||||
c_uid: uid,
|
||||
i_balance: balance,
|
||||
c_flag: flag,
|
||||
});
|
||||
})
|
||||
.then(trx.commit)
|
||||
.catch(trx.rollback);
|
||||
})
|
||||
.then((result) => {
|
||||
// console.log(result);
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
try {
|
||||
await knex.transaction((trx) => replaceFlagCount(trx, now, cardNumber, uid, balance, flag));
|
||||
} catch (error) {
|
||||
logTransactionFailure('replace_flag', error);
|
||||
}
|
||||
};
|
||||
|
||||
// GET ACCUMULATION BALANCE IN THIS MONTH FROM CARD HISTORY
|
||||
@@ -871,8 +648,8 @@ const getAccumulationBalanceInThisMonthFromCardHistory = (
|
||||
};
|
||||
|
||||
// CREATE LOG FOR CARD HISTORY
|
||||
const createLoadBalanceLog = (data) => {
|
||||
let result = knex('log.t_log_card').insert(data);
|
||||
const createLoadBalanceLog = (data, connection = knex) => {
|
||||
const result = connection('log.t_log_card').insert(data);
|
||||
return result;
|
||||
};
|
||||
|
||||
@@ -1078,66 +855,23 @@ const updateReservationAndInsertLoadingBalance = async (
|
||||
now,
|
||||
flag
|
||||
) => {
|
||||
return await knex
|
||||
.transaction((trx) => {
|
||||
knex('trx.t_d_load_balance')
|
||||
.transacting(trx)
|
||||
try {
|
||||
// Mode pemulihan memakai nominal reservasi sebagai nominal detail saldo.
|
||||
return await knex.transaction(async (trx) => {
|
||||
const [header] = await trx('trx.t_d_load_balance')
|
||||
.insert(dataLoadBalance)
|
||||
.returning('i_load_balance')
|
||||
.then((detail) => {
|
||||
let id = detail[0];
|
||||
let loadDetail = [];
|
||||
detailLoadBalance.forEach((element) => {
|
||||
loadDetail.push({
|
||||
i_load_balance: id.i_load_balance,
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_reservation_amount,
|
||||
i_issuer: element.i_issuer,
|
||||
i_issuer_code: element.i_issuer_code,
|
||||
i_issuer_name: element.i_issuer_name,
|
||||
i_issuer_fee: element.i_issuer_fee,
|
||||
i_channel: element.i_channel,
|
||||
i_channel_code: element.i_channel_code,
|
||||
i_channel_name: element.i_channel_name,
|
||||
i_channel_fee: element.i_channel_fee,
|
||||
});
|
||||
});
|
||||
|
||||
// insert detail load balance
|
||||
return knex('trx.t_d_load_balance_detail')
|
||||
.transacting(trx)
|
||||
.insert(loadDetail);
|
||||
})
|
||||
.then(() => {
|
||||
// update reservation
|
||||
return knex('trx.t_d_reservation_balance')
|
||||
.transacting(trx)
|
||||
.update({
|
||||
d_load_balance: dataLoadBalance.d_load_balance,
|
||||
c_load_balance_no: dataLoadBalance.c_load_balance_no,
|
||||
c_flag: flag,
|
||||
c_flag_code: null,
|
||||
c_status: 'A',
|
||||
c_status_name: 'LOADED',
|
||||
d_modify: now,
|
||||
i_modify: null,
|
||||
c_modify_username: null,
|
||||
c_modify_fullname: null,
|
||||
})
|
||||
.whereIn('c_reservation_no', reservationNumber);
|
||||
})
|
||||
.then(() => trx.commit())
|
||||
.catch(trx.rollback);
|
||||
})
|
||||
.then((result) => {
|
||||
// console.log(result);
|
||||
return result.rowCount;
|
||||
})
|
||||
.catch((error) => {
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
.returning('i_load_balance');
|
||||
await trx('trx.t_d_load_balance_detail').insert(
|
||||
mapLoadBalanceDetails(detailLoadBalance, getInsertedLoadBalanceId(header), 'i_reservation_amount')
|
||||
);
|
||||
const updated = await markReservationsLoaded(trx, reservationNumber, dataLoadBalance, now, flag);
|
||||
if (updated === 0) throw new Error('No reservations found for load balance recovery');
|
||||
return updated;
|
||||
});
|
||||
} catch (error) {
|
||||
logTransactionFailure('insert_balance_from_reservations', error);
|
||||
return error.message;
|
||||
}
|
||||
};
|
||||
|
||||
// GET TOPUP PARTIAL STATUS FROM GLOBAL PARAMETER
|
||||
@@ -1150,7 +884,10 @@ const getTopupPartialStatus = () => {
|
||||
return result;
|
||||
};
|
||||
|
||||
const withLoadBalanceTransaction = (operation) => knex.transaction(operation);
|
||||
|
||||
module.exports = {
|
||||
withLoadBalanceTransaction,
|
||||
checkCardNumber,
|
||||
getPartner,
|
||||
getIssuer,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const { pooling: poolingConfig } = require("../../../knexfile");
|
||||
const dbPooling = require("knex")(poolingConfig);
|
||||
const { withTransactionTimeZone } = require("../../../infrastructure/transaction-time");
|
||||
const dbPooling = require("knex")(withTransactionTimeZone(poolingConfig));
|
||||
const { observePool } = require("../../../infrastructure/database/pool-metrics");
|
||||
observePool("pooling", dbPooling.client.pool);
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
const { logErrorCode, logStatusCode } = require('../../helpers/log-fields');
|
||||
const helper = require('../../helpers/helper');
|
||||
const model = require('./pos.model');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { postWithDeadline } = require('./cts-client');
|
||||
const { validateBlacklist } = require('./card-validation.service');
|
||||
|
||||
// Pengecekan saldo lokal dan pengambilan saldo melalui CTS.
|
||||
const checkLastBalance = async (req, res) => {
|
||||
let result = {};
|
||||
let { card_number } = req.body;
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
|
||||
//CHECK IS CARD BLACKLISTED
|
||||
let cardBlacklist = await validateBlacklist(card_number, uniqueCode);
|
||||
if (cardBlacklist) {
|
||||
return res.status(200).json(cardBlacklist);
|
||||
}
|
||||
|
||||
let last_balance = 0;
|
||||
let getLastBalanceFromCardHistory = await model.getLastBalanceFromCardHistory(
|
||||
card_number
|
||||
);
|
||||
if (getLastBalanceFromCardHistory) {
|
||||
last_balance = getLastBalanceFromCardHistory.m_balance_after;
|
||||
}
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {
|
||||
card_number: card_number,
|
||||
last_balance: last_balance,
|
||||
},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
};
|
||||
|
||||
const checkLastBalanceCTS = async (card_number, uniqueCode, req) => {
|
||||
let token_api;
|
||||
let result = {};
|
||||
|
||||
//LOG-INFO
|
||||
|
||||
let last_balance = 0;
|
||||
let getLastBalanceFromCardHistory = await model.getLastBalanceFromCardHistory(
|
||||
card_number
|
||||
);
|
||||
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ CTS CARD HISTORY ] found=${Boolean(getLastBalanceFromCardHistory)}`
|
||||
);
|
||||
|
||||
if (getLastBalanceFromCardHistory) {
|
||||
last_balance = getLastBalanceFromCardHistory.m_balance_after;
|
||||
}
|
||||
|
||||
let auth = req.header('Authorization');
|
||||
token_api = auth.replace('Bearer ', '');
|
||||
|
||||
const protocol = req.protocol;
|
||||
const host = req.headers.host;
|
||||
const current_url = protocol + '://' + host;
|
||||
|
||||
let config = {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: 'Bearer ' + token_api,
|
||||
},
|
||||
};
|
||||
const dataPost = { card_number: card_number };
|
||||
const url = current_url + `/api/pos/card-lastbalance`;
|
||||
const resp = await postWithDeadline(url, dataPost, config);
|
||||
|
||||
if (
|
||||
resp.data.data == undefined ||
|
||||
resp.data.data.detail.last_balance == undefined
|
||||
) {
|
||||
result = {
|
||||
code: '446',
|
||||
message: 'Card number not exist in CTS to get last balance',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {
|
||||
last_balance: last_balance,
|
||||
},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE GET LAST-BALANCE FROM CTS ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {
|
||||
last_balance: last_balance,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE GET LAST-BALANCE FROM CTS ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return result;
|
||||
};
|
||||
|
||||
const getLastBalanceCTS = async (req, res) => {
|
||||
let last_balance;
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
// const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance'
|
||||
const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`;
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST GET LAST BALANCE CTS ]`);
|
||||
|
||||
//CARD REPLACEMENT VALIDATION
|
||||
const dataCard = await model.getCardReplacementScheduler();
|
||||
|
||||
for (const card of dataCard) {
|
||||
const payload = {
|
||||
card_number: card.c_card_no,
|
||||
};
|
||||
|
||||
let config = {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
};
|
||||
const url = baseUrl;
|
||||
const response = await postWithDeadline(url, payload, config);
|
||||
if (response.data.code == undefined || response.data.code != 200) {
|
||||
if (response.data.code == 404) {
|
||||
result = {
|
||||
code: '494',
|
||||
message: 'No data found in CTS for the given card number',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ CTS REQUEST FAILED ] code=${logStatusCode(response.data.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
result = {
|
||||
code: '500',
|
||||
message: 'CTS service not avaliable',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ CTS REQUEST FAILED ] code=${logStatusCode(response.data.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
last_balance = response.data.data.balance_after;
|
||||
let dataReplacementUpdate = {
|
||||
i_last_balance: last_balance,
|
||||
};
|
||||
// update card_replacement
|
||||
await model.updateReplacementByCardNumber(
|
||||
card.c_card_no,
|
||||
dataReplacementUpdate
|
||||
);
|
||||
// log debug
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ GET LAST BALANCE CTS ] code=200`
|
||||
);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE GET LAST BALANCE CTS ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE GET LAST BALANCE CTS ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { checkLastBalance, getLastBalanceCTS };
|
||||
@@ -0,0 +1,534 @@
|
||||
const { logErrorCode, logStatusCode } = require('../../helpers/log-fields');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { validationResult } = require('express-validator');
|
||||
const moment = require('moment');
|
||||
const { postWithDeadline } = require('./cts-client');
|
||||
const model = require('./pos.model');
|
||||
const {
|
||||
validateEnvironment,
|
||||
validateBlacklist,
|
||||
validateCardProduct,
|
||||
checkCardReplacement,
|
||||
} = require('./card-validation.service');
|
||||
|
||||
// Validasi dan konfirmasi redeem untuk kartu yang memenuhi syarat.
|
||||
const validateRedeem = async (req, res) => {
|
||||
let dataCard;
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
let last_balance = null;
|
||||
let dataCardReplacement = {};
|
||||
let { card_number, station_code } = req.body;
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-REDEEM ]`);
|
||||
|
||||
//CHECK VALIDATOR
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//TRIM CARD NUMBER
|
||||
card_number = card_number.trim();
|
||||
|
||||
//CHECK IS CARD ALLOW
|
||||
const validEnv = await validateEnvironment(card_number, uniqueCode);
|
||||
if (validEnv) {
|
||||
res.status(200).json(validEnv);
|
||||
}
|
||||
|
||||
//CHECK IS CARD BLACKLISTED
|
||||
let cardBlacklist = await validateBlacklist(card_number, uniqueCode);
|
||||
if (cardBlacklist) {
|
||||
return res.status(200).json(cardBlacklist);
|
||||
}
|
||||
|
||||
//CARD PRODUCT VALIDATION
|
||||
const validCardProduct = await validateCardProduct(card_number, uniqueCode);
|
||||
if (validCardProduct) {
|
||||
dataCard = validCardProduct.data;
|
||||
//CARD NOT REGISTERED IN CARD_PRODUCT
|
||||
if (dataCard.status == false) {
|
||||
return res.status(200).json(validCardProduct);
|
||||
}
|
||||
|
||||
dataCard = dataCard.detail;
|
||||
const card_status = dataCard.c_status;
|
||||
|
||||
// Status valid => Active (A)
|
||||
if (card_status != 'A') {
|
||||
if (card_status == 'R') {
|
||||
result = {
|
||||
code: '451',
|
||||
message: 'Card is redeemed or replaced.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else if (card_status == 'B') {
|
||||
result = {
|
||||
code: '445',
|
||||
message: 'Card is blacklisted.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else if (card_status == 'N') {
|
||||
result = {
|
||||
code: '463',
|
||||
message: 'Card is not activated.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else if (card_status == 'P') {
|
||||
result = {
|
||||
code: '458',
|
||||
message: 'Card is persoed and not yet active.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-REDEEM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
//CARD REPLACEMENT VALIDATION
|
||||
const validCardReplacement = await checkCardReplacement(
|
||||
card_number,
|
||||
uniqueCode
|
||||
);
|
||||
if (validCardReplacement) {
|
||||
dataCardReplacement = validCardReplacement.data;
|
||||
//CARD NOT REGISTERED IN CARD_REPLACEMENT
|
||||
if (dataCardReplacement.status == false) {
|
||||
return res.status(200).json(validCardReplacement);
|
||||
}
|
||||
dataCardReplacement = dataCardReplacement.detail;
|
||||
|
||||
let replacement_redeem_category =
|
||||
dataCardReplacement.c_replace_redeem_category_code.trim();
|
||||
//replacement_redeem_category: R - REDEEM | w - REPLACEMENT WARRANTY | N - REPLACEMENT NON-WARRANTY
|
||||
if (replacement_redeem_category != 'R') {
|
||||
result = {
|
||||
code: '491',
|
||||
message: 'Card not registered as redeem.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REDEEM-VALIDATE ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let replacement_station_code =
|
||||
dataCardReplacement.c_org_dept_station_code.trim();
|
||||
if (replacement_station_code != station_code) {
|
||||
result = {
|
||||
code: '411',
|
||||
message: 'Station code not match.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REDEEM-VALIDATE ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let replacement_status = dataCardReplacement.c_status.trim();
|
||||
//replacement_status: N - NEW | X - CANCELLED | A - COMPLETED
|
||||
if (replacement_status != 'N') {
|
||||
if (replacement_status == 'X') {
|
||||
result = {
|
||||
code: '406',
|
||||
message: 'Replacement or redeem Card Status is cancelled.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else if (replacement_status == 'A') {
|
||||
result = {
|
||||
code: '407',
|
||||
message: 'Card has been replaced or redeemed.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: '408',
|
||||
message: 'Redeem or replacement card status not defined.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-REDEEM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
//Cek tanggal d_valid_date
|
||||
|
||||
//Update Data Replacement
|
||||
let date_request = dataCardReplacement.d_request;
|
||||
let date_valid = dataCardReplacement.d_valid_date;
|
||||
|
||||
let now = moment().format('YYYY-MM-DD');
|
||||
date_valid = moment(date_valid).format('YYYY-MM-DD');
|
||||
date_request = moment(date_request).format('YYYY-MM-DD');
|
||||
|
||||
if (now < date_valid) {
|
||||
//other status
|
||||
result = {
|
||||
code: '456',
|
||||
message: 'The valid replacement date is insufficient.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {
|
||||
date_now: now,
|
||||
date_request: date_request,
|
||||
date_valid: date_valid,
|
||||
},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
last_balance = dataCardReplacement.i_last_balance;
|
||||
if (last_balance == null) {
|
||||
let result = {};
|
||||
// const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance'
|
||||
const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`;
|
||||
const payload = {
|
||||
card_number: card_number,
|
||||
};
|
||||
let config = {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
};
|
||||
const url = baseUrl;
|
||||
const response = await postWithDeadline(url, payload, config);
|
||||
if (response.data.code == undefined || response.data.code != 200) {
|
||||
if (response.data.code == 404) {
|
||||
result = {
|
||||
code: '494',
|
||||
message: 'No data found in CTS for the given card number',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ CTS REQUEST FAILED ] code=${logStatusCode(response.data.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
result = {
|
||||
code: '415',
|
||||
message: 'Last Balance not updated.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ CTS REQUEST FAILED ] code=${logStatusCode(response.data.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
last_balance = response.data.data.balance_after;
|
||||
}
|
||||
|
||||
let security_code = await helper.createHMAC(card_number);
|
||||
|
||||
//CARD VALID TO REDEEM
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {
|
||||
security_code: security_code,
|
||||
last_balance: last_balance,
|
||||
card_number: card_number,
|
||||
unique_code: uniqueCode,
|
||||
},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-REDEEM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE VALIDATE-REDEEM ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const confirmRedeem = async (req, res) => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
let { card_number, security_code } = req.body;
|
||||
let dataCardRedeem = {};
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST REDEEM-CONFIRM ]`);
|
||||
|
||||
//CHECK VALIDATOR
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//CHECK SECURITY-CODE
|
||||
if (security_code) {
|
||||
let securityCodeCompare = await helper.createHMAC(card_number);
|
||||
|
||||
if (security_code !== securityCodeCompare) {
|
||||
result = {
|
||||
code: '437',
|
||||
message: 'bad request. security code does not match.',
|
||||
data: {},
|
||||
};
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REDEEM-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
//TRIM CARD NUMBER
|
||||
card_number = card_number.trim();
|
||||
|
||||
//CHECK IS CARD ALLOW
|
||||
const validEnv = await validateEnvironment(card_number, uniqueCode);
|
||||
if (validEnv) {
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ VALIDATE ENV CARD NUMBER ] code=${logStatusCode(validEnv?.code)}`
|
||||
);
|
||||
res.status(200).json(validEnv);
|
||||
}
|
||||
|
||||
//CHECK IS CARD BLACKLISTED
|
||||
let cardBlacklist = await validateBlacklist(card_number, uniqueCode);
|
||||
if (cardBlacklist) {
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ VALIDATE BLACKLIST CARD NUMBER ] code=${logStatusCode(cardBlacklist?.code)}`
|
||||
);
|
||||
return res.status(200).json(cardBlacklist);
|
||||
}
|
||||
|
||||
//CARD REPLACEMENT VALIDATION
|
||||
const validCardReplacement = await checkCardReplacement(
|
||||
card_number,
|
||||
uniqueCode
|
||||
);
|
||||
if (validCardReplacement) {
|
||||
dataCardRedeem = validCardReplacement.data;
|
||||
//CARD NOT REGISTERED IN CARD_REPLACEMENT
|
||||
if (dataCardRedeem.status == false) {
|
||||
return res.status(200).json(validCardReplacement);
|
||||
}
|
||||
dataCardRedeem = dataCardRedeem.detail;
|
||||
|
||||
let replacement_redeem_category =
|
||||
dataCardRedeem.c_replace_redeem_category_code.trim();
|
||||
//replacement_redeem_category: R - REDEEM | w - REPLACEMENT WARRANTY | N - REPLACEMENT NON-WARRANTY
|
||||
if (replacement_redeem_category != 'R') {
|
||||
result = {
|
||||
code: '491',
|
||||
message: 'Card not registered as redeem.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REDEEM-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let redeem_status = dataCardRedeem.c_status.trim();
|
||||
//redeem_status: N - NEW | X - CANCELLED | A - COMPLETED
|
||||
if (redeem_status != 'N') {
|
||||
if (redeem_status == 'X') {
|
||||
result = {
|
||||
code: '406',
|
||||
message: 'Card replacement status is cancelled.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else if (redeem_status == 'A') {
|
||||
result = {
|
||||
code: '407',
|
||||
message: 'Card has been replaced or redeemed.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: '408',
|
||||
message: 'Redeem or replacement card status not defined.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REDEEM-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
//Cek tanggal d_valid_date
|
||||
//Update Data Replacement
|
||||
let date_request = dataCardRedeem.d_request;
|
||||
let date_valid = dataCardRedeem.d_valid_date;
|
||||
|
||||
let now = moment().format('YYYY-MM-DD');
|
||||
date_valid = moment(date_valid).format('YYYY-MM-DD');
|
||||
date_request = moment(date_request).format('YYYY-MM-DD');
|
||||
|
||||
if (now < date_valid) {
|
||||
//other status
|
||||
result = {
|
||||
code: '456',
|
||||
message: 'The valid replacement date is insufficient.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {
|
||||
date_now: now,
|
||||
date_request: date_request,
|
||||
date_valid: date_valid,
|
||||
},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REDEEM-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let i_card_replacement = dataCardRedeem.i_card_replacement;
|
||||
let dataReplacementUpdate = {
|
||||
c_status: 'A',
|
||||
c_status_name: 'COMPLETED',
|
||||
};
|
||||
//Update Data Card Card Replacement
|
||||
await model.updateReplacement(i_card_replacement, dataReplacementUpdate);
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ UPDATE DATA REDEEM ]`
|
||||
);
|
||||
|
||||
//CARD VALID TO REPLACEMENT
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {
|
||||
card_number: card_number,
|
||||
},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REPLACEMENT-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE REPLACEMENT-CONFIRM ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { validateRedeem, confirmRedeem };
|
||||
@@ -0,0 +1,933 @@
|
||||
const { logCorrelation, logErrorCode, logStatusCode } = require('../../helpers/log-fields');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { validationResult } = require('express-validator');
|
||||
const moment = require('moment');
|
||||
const { postWithDeadline } = require('./cts-client');
|
||||
const model = require('./pos.model');
|
||||
const {
|
||||
validateEnvironment,
|
||||
validateBlacklist,
|
||||
validateCardProduct,
|
||||
checkCardReplacement,
|
||||
} = require('./card-validation.service');
|
||||
|
||||
// Validasi kartu lama dan baru sebelum konfirmasi penggantian.
|
||||
const validateReplacement = async (req, res) => {
|
||||
let dataCard;
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
let { card_number, station_code } = req.body;
|
||||
let dataCardReplacement = {};
|
||||
let last_balance = null;
|
||||
let is_warranty = false;
|
||||
|
||||
winston.logger.info(`${logCorrelation(uniqueCode)} [ REQUEST VALIDATE-REPLACEMENT ]`);
|
||||
|
||||
//CHECK VALIDATOR
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//TRIM CARD NUMBER
|
||||
card_number = card_number.trim();
|
||||
|
||||
//CHECK IS CARD ALLOW
|
||||
const validEnv = await validateEnvironment(card_number, uniqueCode);
|
||||
if (validEnv) {
|
||||
return res.status(200).json(validEnv);
|
||||
}
|
||||
|
||||
//CHECK IS CARD BLACKLISTED
|
||||
let cardBlacklist = await validateBlacklist(card_number, uniqueCode);
|
||||
if (cardBlacklist) {
|
||||
return res.status(200).json(cardBlacklist);
|
||||
}
|
||||
|
||||
//CARD PRODUCT VALIDATION
|
||||
const validCardProduct = await validateCardProduct(card_number, uniqueCode);
|
||||
if (validCardProduct) {
|
||||
dataCard = validCardProduct.data;
|
||||
//CARD NOT REGISTERED IN CARD_PRODUCT
|
||||
if (dataCard.status == false) {
|
||||
return res.status(200).json(validCardProduct);
|
||||
}
|
||||
|
||||
dataCard = dataCard.detail;
|
||||
const card_status = dataCard.c_status;
|
||||
|
||||
// Status valid => Active (A)
|
||||
if (card_status != 'A') {
|
||||
if (card_status == 'R') {
|
||||
result = {
|
||||
code: '451',
|
||||
message: 'Card is redeemed or replaced.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else if (card_status == 'B') {
|
||||
result = {
|
||||
code: '445',
|
||||
message: 'Card is blacklisted.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else if (card_status == 'N') {
|
||||
result = {
|
||||
code: '463',
|
||||
message: 'Card is not activated.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else if (card_status == 'P') {
|
||||
result = {
|
||||
code: '458',
|
||||
message: 'Card is persoed and not yet active.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE VALIDATE-REPLACEMENT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
//CARD REPLACEMENT VALIDATION
|
||||
const validCardReplacement = await checkCardReplacement(
|
||||
card_number,
|
||||
uniqueCode
|
||||
);
|
||||
if (validCardReplacement) {
|
||||
dataCardReplacement = validCardReplacement.data;
|
||||
//CARD NOT REGISTERED IN CARD_REPLACEMENT
|
||||
if (dataCardReplacement.status == false) {
|
||||
return res.status(200).json(validCardReplacement);
|
||||
}
|
||||
dataCardReplacement = dataCardReplacement.detail;
|
||||
|
||||
let category_replacement =
|
||||
dataCardReplacement.c_replace_redeem_category_code;
|
||||
//replacement_redeem_category: R - REDEEM | w - REPLACEMENT WARRANTY | N - REPLACEMENT NON-WARRANTY
|
||||
if (category_replacement == 'R') {
|
||||
result = {
|
||||
code: '492',
|
||||
message: 'Card not registered as replacement.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE REPLACEMENT-VALIDATE ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
//is warranty
|
||||
if (category_replacement == 'W') {
|
||||
is_warranty = true;
|
||||
}
|
||||
|
||||
let replacement_station_code =
|
||||
dataCardReplacement.c_org_dept_station_code.trim();
|
||||
if (replacement_station_code != station_code) {
|
||||
result = {
|
||||
code: '411',
|
||||
message: 'Station code not match.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE REPLACEMENT-VALIDATE ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let replacement_status = dataCardReplacement.c_status.trim();
|
||||
//replacement_status: N - NEW | X - CANCELLED | A - COMPLETED
|
||||
if (replacement_status != 'N') {
|
||||
if (replacement_status == 'X') {
|
||||
result = {
|
||||
code: '406',
|
||||
message: 'Replacement or redeem Card Status is cancelled.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else if (replacement_status == 'A') {
|
||||
result = {
|
||||
code: '407',
|
||||
message: 'Card has been replaced or redeemed.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: '408',
|
||||
message: 'Redeem or replacement card status not defined.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE VALIDATE-REPLACEMENT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//Cek tanggal d_valid_date
|
||||
|
||||
let date_request = dataCardReplacement.d_request;
|
||||
let date_valid = dataCardReplacement.d_valid_date;
|
||||
|
||||
let now = moment().format('YYYY-MM-DD');
|
||||
date_valid = moment(date_valid).format('YYYY-MM-DD');
|
||||
date_request = moment(date_request).format('YYYY-MM-DD');
|
||||
|
||||
if (now < date_valid) {
|
||||
//other status
|
||||
result = {
|
||||
code: '456',
|
||||
message: 'The valid replacement date is insufficient.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {
|
||||
date_now: now,
|
||||
date_request: date_request,
|
||||
date_valid: date_valid,
|
||||
},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE REPLACEMENT-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
last_balance = dataCardReplacement.i_last_balance;
|
||||
if (last_balance == null) {
|
||||
// if (is_warranty == true) {
|
||||
// let result = {};
|
||||
// const baseUrl = 'http://127.0.0.1:3000';
|
||||
// const payload = {
|
||||
// card_number: card_number,
|
||||
// };
|
||||
// const response = await axios.post(baseUrl + '/api/pos/test', payload);
|
||||
// if (
|
||||
// !response.data.code == undefined ||
|
||||
// response.data.data.status == false
|
||||
// ) {
|
||||
// result = {
|
||||
// code: '415',
|
||||
// message: 'Last Balance not updated.',
|
||||
// data: {
|
||||
// status: false,
|
||||
// detail: {},
|
||||
// },
|
||||
// };
|
||||
// winston.logger.info(
|
||||
// `${uniqueCode} [ FAILED HIT - card_number : ${card_number} ]: ${response.data.message}`
|
||||
// );
|
||||
// return res.status(200).json(result);
|
||||
// }
|
||||
// last_balance = response.data.data.detail.last_balance;
|
||||
// let dataReplacementUpdate = {
|
||||
// i_last_balance: last_balance,
|
||||
// };
|
||||
// // update card_replacement
|
||||
// await model.updateReplacementByCardNumber(
|
||||
// card_number,
|
||||
// dataReplacementUpdate
|
||||
// );
|
||||
// // log debug
|
||||
// winston.logger.info(
|
||||
// `${uniqueCode} [ GET LAST BALANCE CTS ${card_number} ]: ${last_balance}`
|
||||
// );
|
||||
// } else {
|
||||
// result = {
|
||||
// code: '415',
|
||||
// message: 'Last Balance not updated.',
|
||||
// data: {
|
||||
// status: false,
|
||||
// detail: {},
|
||||
// },
|
||||
// };
|
||||
// //LOG-INFO
|
||||
// winston.logger.info(
|
||||
// `${uniqueCode} [ RESPONSE VALIDATE-REPLACEMENT ]: ${JSON.stringify(
|
||||
// result
|
||||
// )}`
|
||||
// );
|
||||
// return res.status(200).json(result);
|
||||
|
||||
// if (is_warranty == true) {
|
||||
let result = {};
|
||||
// const baseUrl = 'https://appdev.kci.id/cts/v2/api/info/last-balance'
|
||||
const baseUrl = `${process.env.CTS_URL}/v2/api/info/last-balance`;
|
||||
const payload = {
|
||||
card_number: card_number,
|
||||
};
|
||||
let config = {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
};
|
||||
const url = baseUrl;
|
||||
const response = await postWithDeadline(url, payload, config);
|
||||
if (response.data.code == undefined || response.data.code != 200) {
|
||||
if (response.data.code == 404) {
|
||||
result = {
|
||||
code: '494',
|
||||
message: 'No data found in CTS for the given card number',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ CTS REQUEST FAILED ] code=${logStatusCode(response.data.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
result = {
|
||||
code: '415',
|
||||
message: 'Last Balance not updated.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ CTS REQUEST FAILED ] code=${logStatusCode(response.data.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
last_balance = response.data.data.balance_after;
|
||||
let dataReplacementUpdate = {
|
||||
i_last_balance: last_balance,
|
||||
};
|
||||
// update card_replacement
|
||||
await model.updateReplacementByCardNumber(
|
||||
card_number,
|
||||
dataReplacementUpdate
|
||||
);
|
||||
// log debug
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ GET LAST BALANCE CTS ] code=200`
|
||||
);
|
||||
// }
|
||||
}
|
||||
|
||||
// ==================== Contoh service Scheduller get last balance from CTS ====================
|
||||
// if (last_balance == null) {
|
||||
// //CHECK CARD LAST_BALANCE
|
||||
// const dataLastBalance = await checkLastBalanceCTS(card_number, uniqueCode, req);
|
||||
// if (!dataLastBalance.data.status || dataLastBalance.data.status == false) {
|
||||
// return res.status(200).json(dataLastBalance);
|
||||
// }
|
||||
// last_balance = dataLastBalance.data.detail.last_balance;
|
||||
|
||||
// let dataReplacementUpdate = {
|
||||
// i_last_balance: last_balance
|
||||
// };
|
||||
// // update card_replacement
|
||||
// await model.updateReplacement(dataCardReplacement.i_card_replacement, dataReplacementUpdate);
|
||||
|
||||
// // log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ UPDATE LAST BALANCE CARD ${card_number} ]: ${last_balance}`
|
||||
// );
|
||||
|
||||
// }
|
||||
|
||||
// create security code
|
||||
let security_code = await helper.createHMAC(
|
||||
card_number + '|' + last_balance
|
||||
);
|
||||
|
||||
//CARD VALID TO REPLACEMENT
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {
|
||||
security_code: security_code,
|
||||
last_balance: last_balance,
|
||||
is_warranty: is_warranty,
|
||||
unique_code: uniqueCode,
|
||||
card_category: {
|
||||
id: dataCardReplacement.card_category_id,
|
||||
code: dataCardReplacement.card_category_code,
|
||||
name: dataCardReplacement.card_category_name
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE VALIDATE-REPLACEMENT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE VALIDATE-REPLACEMENT ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const validateNewCardReplacement = async (req, res) => {
|
||||
let dataCardNew;
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
let { card_number } = req.body;
|
||||
|
||||
winston.logger.info(`${logCorrelation(uniqueCode)} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ]`);
|
||||
|
||||
//CHECK VALIDATOR
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//TRIM CARD NUMBER
|
||||
card_number = card_number.trim();
|
||||
|
||||
//CHECK IS CARD ALLOW
|
||||
const validEnv = await validateEnvironment(card_number, uniqueCode);
|
||||
if (validEnv) {
|
||||
return res.status(200).json(validEnv);
|
||||
}
|
||||
|
||||
//CHECK IS CARD BLACKLISTED
|
||||
let cardBlacklist = await validateBlacklist(card_number, uniqueCode);
|
||||
if (cardBlacklist) {
|
||||
result = {
|
||||
code: '457',
|
||||
message: 'New card is blacklisted.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//CARD REPLACEMENT VALIDATION
|
||||
const validCardReplacement = await checkCardReplacement(
|
||||
card_number,
|
||||
uniqueCode
|
||||
);
|
||||
//CARD REGISTERED IN CARD_REPLACEMENT
|
||||
if (validCardReplacement.data.status == true) {
|
||||
result = {
|
||||
code: '461',
|
||||
message:
|
||||
'New card number exists in the card replacement data and cannot be used for card replacement.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
const validCardProductNew = await validateCardProduct(
|
||||
card_number,
|
||||
uniqueCode
|
||||
);
|
||||
if (validCardProductNew) {
|
||||
dataCardNew = validCardProductNew.data;
|
||||
//CARD NOT REGISTERED IN CARD_PRODUCT
|
||||
if (dataCardNew.status == false) {
|
||||
return res.status(200).json(validCardProductNew);
|
||||
}
|
||||
|
||||
dataCardNew = dataCardNew.detail;
|
||||
const card_new_status = dataCardNew.c_status;
|
||||
// Status valid => Active (A)
|
||||
|
||||
if (card_new_status != 'P') {
|
||||
if (card_new_status == 'A') {
|
||||
result = {
|
||||
code: '453',
|
||||
message: 'New card is already activated.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} else if (card_new_status == 'R') {
|
||||
result = {
|
||||
code: '454',
|
||||
message: 'New card is redeemed or replaced.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} else if (card_new_status == 'B') {
|
||||
result = {
|
||||
code: '457',
|
||||
message: 'New card is blacklisted.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//other status
|
||||
result = {
|
||||
code: '455',
|
||||
message: 'New Card not valid for replacement.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
//CARD VALID TO REPLACEMENT
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ REQUEST VALIDATE-NEW-CARD-REPLACEMENT ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const replacementConfirm = async (req, res) => {
|
||||
let dataCardNew;
|
||||
try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
let {
|
||||
card_number,
|
||||
new_card_number,
|
||||
last_balance,
|
||||
security_code,
|
||||
unique_code,
|
||||
} = req.body;
|
||||
let uniqueCode = unique_code;
|
||||
let dataCardReplacement = {};
|
||||
|
||||
winston.logger.info(`${logCorrelation(uniqueCode)} [ REQUEST REPLACEMENT-CONFIRM ]`);
|
||||
|
||||
//CHECK VALIDATOR
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
if (card_number == new_card_number) {
|
||||
result = {
|
||||
code: '493',
|
||||
message: 'bad request. new card number cannot be same.',
|
||||
data: {},
|
||||
};
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE REPLACEMENT-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//CHECK SECURITY-CODE
|
||||
if (security_code) {
|
||||
let securityCodeCompare = await helper.createHMAC(
|
||||
card_number + '|' + last_balance
|
||||
);
|
||||
|
||||
if (security_code !== securityCodeCompare) {
|
||||
result = {
|
||||
code: '437',
|
||||
message: 'bad request. security code does not match.',
|
||||
data: {},
|
||||
};
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE REPLACEMENT-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
//TRIM CARD NUMBER
|
||||
card_number = card_number.trim();
|
||||
new_card_number = new_card_number.trim();
|
||||
|
||||
//CHECK IS CARD ALLOW
|
||||
const validEnv = await validateEnvironment(card_number, uniqueCode);
|
||||
if (validEnv) {
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ VALIDATE ENV OLD CARD NUMBER ] code=${logStatusCode(validEnv?.code)}`
|
||||
);
|
||||
return res.status(200).json(validEnv);
|
||||
}
|
||||
|
||||
//CHECK IS CARD ALLOW
|
||||
const validEnvNew = await validateEnvironment(new_card_number, uniqueCode);
|
||||
if (validEnvNew) {
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ VALIDATE ENV NEW CARD NUMBER ] code=${logStatusCode(validEnvNew?.code)}`
|
||||
);
|
||||
return res.status(200).json(validEnv);
|
||||
}
|
||||
|
||||
//CHECK IS CARD BLACKLISTED
|
||||
let cardBlacklist = await validateBlacklist(card_number, uniqueCode);
|
||||
if (cardBlacklist) {
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ VALIDATE BLACKLIST OLD CARD NUMBER ] code=${logStatusCode(cardBlacklist?.code)}`
|
||||
);
|
||||
return res.status(200).json(cardBlacklist);
|
||||
}
|
||||
let cardBlacklistNew = await validateBlacklist(new_card_number, uniqueCode);
|
||||
if (cardBlacklistNew) {
|
||||
cardBlacklistNew.message = 'New Card is blacklisted.';
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${logCorrelation(uniqueCode)} [ VALIDATE BLACKLIST NEW CARD NUMBER ] code=${logStatusCode(cardBlacklistNew?.code)}`
|
||||
);
|
||||
return res.status(200).json(cardBlacklistNew);
|
||||
}
|
||||
|
||||
//CARD REPLACEMENT VALIDATION
|
||||
const validCardReplacement = await checkCardReplacement(
|
||||
card_number,
|
||||
uniqueCode
|
||||
);
|
||||
if (validCardReplacement) {
|
||||
dataCardReplacement = validCardReplacement.data;
|
||||
//CARD NOT REGISTERED IN CARD_REPLACEMENT
|
||||
if (dataCardReplacement.status == false) {
|
||||
return res.status(200).json(validCardReplacement);
|
||||
}
|
||||
dataCardReplacement = dataCardReplacement.detail;
|
||||
|
||||
let replacement_status = dataCardReplacement.c_status.trim();
|
||||
//replacement_status: N - NEW | X - CANCELLED | A - COMPLETED
|
||||
if (replacement_status != 'N') {
|
||||
if (replacement_status == 'X') {
|
||||
result = {
|
||||
code: '406',
|
||||
message: 'Replacement or redeem Card Status is cancelled.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else if (replacement_status == 'A') {
|
||||
result = {
|
||||
code: '458',
|
||||
message: 'Card has been replaced.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: '408',
|
||||
message: 'Redeem or replacement card status not defined.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
}
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE REPLACEMENT-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
//CHECK NEW CARD
|
||||
const newCardReplacement = await checkCardReplacement(
|
||||
new_card_number,
|
||||
uniqueCode
|
||||
);
|
||||
if (newCardReplacement.data.status == true) {
|
||||
result = {
|
||||
code: '461',
|
||||
message:
|
||||
'New card number exists in the card replacement data and cannot be used for card replacement.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//CHECK NEW CARD
|
||||
const validCardProductNew = await validateCardProduct(
|
||||
new_card_number,
|
||||
uniqueCode
|
||||
);
|
||||
if (validCardProductNew) {
|
||||
dataCardNew = validCardProductNew.data;
|
||||
//CARD NOT REGISTERED IN CARD_PRODUCT
|
||||
if (dataCardNew.status == false) {
|
||||
return res.status(200).json(validCardProductNew);
|
||||
}
|
||||
|
||||
dataCardNew = dataCardNew.detail;
|
||||
const card_new_status = dataCardNew.c_status;
|
||||
// Status valid => Active (A)
|
||||
|
||||
if (card_new_status != 'P') {
|
||||
if (card_new_status == 'A') {
|
||||
result = {
|
||||
code: '453',
|
||||
message: 'New card is already activated.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} else if (card_new_status == 'R') {
|
||||
result = {
|
||||
code: '454',
|
||||
message: 'New card is redeemed or replaced.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} else if (card_new_status == 'B') {
|
||||
result = {
|
||||
code: '457',
|
||||
message: 'New card is blacklisted.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//other status
|
||||
result = {
|
||||
code: '455',
|
||||
message: 'New Card not valid for replacement.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
//Cek tanggal d_valid_date
|
||||
|
||||
//Update Data Replacement
|
||||
let date_request = dataCardReplacement.d_request;
|
||||
let date_valid = dataCardReplacement.d_valid_date;
|
||||
|
||||
let now = moment().format('YYYY-MM-DD');
|
||||
date_valid = moment(date_valid).format('YYYY-MM-DD');
|
||||
date_request = moment(date_request).format('YYYY-MM-DD');
|
||||
|
||||
if (now < date_valid) {
|
||||
//other status
|
||||
result = {
|
||||
code: '456',
|
||||
message: 'The valid replacement date is insufficient.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {
|
||||
date_now: now,
|
||||
date_request: date_request,
|
||||
date_valid: date_valid,
|
||||
},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE REPLACEMENT-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let i_card_replacement = dataCardReplacement.i_card_replacement;
|
||||
let dataReplacementUpdate = {
|
||||
c_status: 'A',
|
||||
c_status_name: 'COMPLETED',
|
||||
c_replace_card_no: new_card_number,
|
||||
};
|
||||
//Update Data Card Card Replacement
|
||||
await model.updateReplacement(i_card_replacement, dataReplacementUpdate);
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ UPDATE DATA REPLACEMENT ]`
|
||||
);
|
||||
|
||||
//Insert Data Detail Replacement
|
||||
let dataDetailReplacement = {
|
||||
i_card_replacement: i_card_replacement,
|
||||
c_old_card_no: card_number,
|
||||
c_new_card_no: new_card_number,
|
||||
i_amount: last_balance,
|
||||
unique_code: uniqueCode,
|
||||
};
|
||||
await model.insertReplacementDetail(dataDetailReplacement);
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ INSERT DATA REPLACEMENT DETAIL ]`
|
||||
);
|
||||
|
||||
//CARD VALID TO REPLACEMENT
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {
|
||||
old_card_number: card_number,
|
||||
new_card_number: new_card_number,
|
||||
balance: last_balance,
|
||||
},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${logCorrelation(uniqueCode)} [ RESPONSE REPLACEMENT-CONFIRM ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE REPLACEMENT-CONFIRM ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { validateReplacement, validateNewCardReplacement, replacementConfirm };
|
||||
@@ -0,0 +1,436 @@
|
||||
const { logErrorCode, logStatusCode } = require('../../helpers/log-fields');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { validationResult } = require('express-validator');
|
||||
const model = require('./pos.model');
|
||||
const {
|
||||
validateEnvironment,
|
||||
validateBlacklist,
|
||||
validateCardProduct,
|
||||
checkCardSales,
|
||||
} = require('./card-validation.service');
|
||||
|
||||
// Validasi dan konfirmasi penjualan, termasuk pelengkapan data sales internal.
|
||||
const validateSales = async (req, res) => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let dataCard = {};
|
||||
let result = {};
|
||||
let detail_card = {};
|
||||
let card_product = false;
|
||||
|
||||
let { card_number } = req.body;
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-SALES ]`);
|
||||
|
||||
// CHECK VALIDATOR
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// TRIM CARD NUMBER
|
||||
card_number = card_number.trim();
|
||||
|
||||
//CHECK IS CARD ALLOW
|
||||
const validEnv = await validateEnvironment(card_number, uniqueCode);
|
||||
if (validEnv) {
|
||||
return res.status(200).json(validEnv);
|
||||
}
|
||||
|
||||
//CHECK IS CARD BLACKLISTED
|
||||
let cardBlacklist = await validateBlacklist(card_number, uniqueCode);
|
||||
if (cardBlacklist) {
|
||||
return res.status(200).json(cardBlacklist);
|
||||
}
|
||||
|
||||
//CARD PRODUCT VALIDATION
|
||||
const validCardProduct = await validateCardProduct(card_number, uniqueCode);
|
||||
|
||||
if (validCardProduct) {
|
||||
//CARD NOT REGISTERED IN CARD_PRODUCT
|
||||
if (validCardProduct.data.status == false) {
|
||||
return res.status(200).json(validCardProduct);
|
||||
}
|
||||
|
||||
card_product = true;
|
||||
dataCard = validCardProduct.data.detail;
|
||||
//A: ACTIVED | N: GENERATED | P: PERSOED | B: BLACKLISTED | R: REDEEMED -> harus N/Generated
|
||||
const card_status = dataCard.c_status;
|
||||
detail_card = {
|
||||
card_number: dataCard.c_card_number,
|
||||
card_theme: dataCard.i_card_theme,
|
||||
card_theme_code: dataCard.c_card_theme_code,
|
||||
card_theme_name: dataCard.c_card_theme_name,
|
||||
card_theme_card_digit_key: dataCard.c_card_theme_card_digit_key,
|
||||
card_type: dataCard.i_card_type,
|
||||
card_type_code: dataCard.c_card_type_code,
|
||||
card_type_name: dataCard.c_card_type_name,
|
||||
variant: dataCard.i_variant,
|
||||
variant_code: dataCard.c_variant_code,
|
||||
variant_name: dataCard.c_variant_name,
|
||||
status: dataCard.c_status,
|
||||
status_name: dataCard.c_status_name,
|
||||
};
|
||||
|
||||
if (card_status != 'N' && card_status != 'P') {
|
||||
if (card_status == 'A') {
|
||||
result = {
|
||||
code: '450',
|
||||
message: 'Card is already activated.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: detail_card,
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} else if (card_status == 'R') {
|
||||
result = {
|
||||
code: '451',
|
||||
message: 'Card is redeemed.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: detail_card,
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} else if (card_status == 'B') {
|
||||
result = {
|
||||
code: '445',
|
||||
message: 'Card is blacklisted.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: detail_card,
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//other status
|
||||
result = {
|
||||
code: '462',
|
||||
message: 'Card not valid to sales.',
|
||||
data: {
|
||||
status: false,
|
||||
perso_status: true,
|
||||
detail: detail_card,
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
//CARD SALES VALIDATION
|
||||
const validCardSales = await checkCardSales(card_number, uniqueCode);
|
||||
if (validCardSales) {
|
||||
let dataCardSales = validCardSales.data;
|
||||
if (dataCardSales.status == false) {
|
||||
return res.status(200).json(validCardSales);
|
||||
}
|
||||
// let detailCardSales = dataCardSales.detail;
|
||||
|
||||
// if (detailCardSales.sales_status != 'SUCCESS') {
|
||||
// //Update Data Sales Temp
|
||||
// let updateDataSales = {
|
||||
// sales_status: sales_status,
|
||||
// device_code: device_code,
|
||||
// station_code: station_code,
|
||||
// station_name: station_name,
|
||||
// created_by: created_by,
|
||||
// device_time: device_time
|
||||
// }
|
||||
// // update card_sales
|
||||
// await model.updateSales(detailCardSales.i_sales_kmt_temp, updateDataSales);
|
||||
// // log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ UPDATE SALES ${card_number} ]: ${updateDataSales}`
|
||||
// );
|
||||
|
||||
// result = {
|
||||
// code: '00',
|
||||
// message: 'Successfully.',
|
||||
// data: {
|
||||
// status: true,
|
||||
// },
|
||||
// };
|
||||
// return res.status(200).json(result);
|
||||
// }
|
||||
}
|
||||
|
||||
//Card Sales Validation OK
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
perso_status: false,
|
||||
card_product: card_product,
|
||||
detail: detail_card,
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE VALIDATE-SALES ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const confirmSales = async (req, res) => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
let {
|
||||
card_number,
|
||||
sales_status,
|
||||
device_code,
|
||||
station_code,
|
||||
station_name,
|
||||
created_by,
|
||||
device_time,
|
||||
} = req.body;
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-SALES ]`);
|
||||
|
||||
// CHECK VALIDATOR
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//CARD SALES VALIDATION
|
||||
const validCardSales = await checkCardSales(card_number, uniqueCode);
|
||||
if (validCardSales) {
|
||||
let dataCardSales = validCardSales.data;
|
||||
if (dataCardSales.status == false) {
|
||||
return res.status(200).json(validCardSales);
|
||||
}
|
||||
let detailCardSales = dataCardSales.detail;
|
||||
|
||||
if (detailCardSales.sales_status != 'SUCCESS') {
|
||||
//Update Data Sales Temp
|
||||
let updateDataSales = {
|
||||
sales_status: sales_status,
|
||||
device_code: device_code,
|
||||
station_code: station_code,
|
||||
station_name: station_name,
|
||||
created_by: created_by,
|
||||
device_time: device_time,
|
||||
};
|
||||
// update card_sales
|
||||
await model.updateSales(
|
||||
detailCardSales.i_sales_kmt_temp,
|
||||
updateDataSales
|
||||
);
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ UPDATE SALES ]`
|
||||
);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
//Insert Data Sales Temp
|
||||
let dataSales = {
|
||||
card_number: card_number,
|
||||
sales_status: sales_status,
|
||||
device_code: device_code,
|
||||
station_code: station_code,
|
||||
station_name: station_name,
|
||||
created_by: created_by,
|
||||
device_time: device_time,
|
||||
};
|
||||
await model.insertSales(dataSales);
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ INSERT DATA REPLACEMENT DETAIL ]`
|
||||
);
|
||||
|
||||
//Card Sales Confirm OK
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CONFIRM-SALES ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const completeDataSalesInternal = async (req, res) => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL ]`);
|
||||
|
||||
// GET PPN FROM GLOBAL PARAMETER
|
||||
let ppn = await model.getPPNCardSales();
|
||||
if (!ppn) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'value pajak belum di set',
|
||||
data: {},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ VALIDATE COMPLETING DATA SALES INTERNAL ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL - PPN ${ppn.c_value} % ]`);
|
||||
|
||||
ppn = parseFloat(ppn.c_value);
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL - UPDATE DATA ]`);
|
||||
|
||||
//COMPLETING DATA SALES INTERNAL
|
||||
const response = await model.completingDataSalesInternal(ppn);
|
||||
|
||||
if (!response.success) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'failed update data sales',
|
||||
data: {},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ VALIDATE COMPLETING DATA SALES INTERNAL ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL SUCCESS ] code=${result.code}`);
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE COMPLETING DATA SALES INTERNAL ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const completeDataSalesInternalV2 = async (req, res) => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ COMPLETING DATA SALES INTERNAL V2 ]`);
|
||||
|
||||
// GET PPN FROM GLOBAL PARAMETER
|
||||
let ppn = await model.getPPNCardSales();
|
||||
if (!ppn) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'value pajak belum di set',
|
||||
data: {},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ VALIDATE COMPLETING DATA SALES INTERNAL V2 ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
ppn = parseFloat(ppn.c_value);
|
||||
|
||||
//COMPLETING DATA SALES INTERNAL
|
||||
await model.completingDataSalesNewCard(ppn);
|
||||
await model.completingDataSalesOldCard(ppn);
|
||||
await model.updateDataSalesIsComplete();
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE COMPLETING DATA SALES INTERNAL V2 ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { validateSales, confirmSales, completeDataSalesInternal, completeDataSalesInternalV2 };
|
||||
@@ -0,0 +1,232 @@
|
||||
const { logErrorCode, logStatusCode } = require('../../helpers/log-fields');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { validationResult } = require('express-validator');
|
||||
const {
|
||||
validateEnvironment,
|
||||
validateBlacklist,
|
||||
validateCardProduct,
|
||||
validateBIRegulation,
|
||||
} = require('./card-validation.service');
|
||||
|
||||
// Validasi top up dan pengecekan blacklist untuk endpoint POS.
|
||||
const validateTopup = async (req, res) => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let dataCard = {};
|
||||
let result = {};
|
||||
let { card_number, amount, last_balance } = req.body;
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST VALIDATE-TOPUP ]`);
|
||||
|
||||
// CHECK VALIDATOR
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// TRIM CARD NUMBER
|
||||
card_number = card_number.trim();
|
||||
|
||||
//CHECK IS CARD ALLOW
|
||||
const validEnv = await validateEnvironment(card_number, uniqueCode);
|
||||
if (validEnv) {
|
||||
return res.status(200).json(validEnv);
|
||||
}
|
||||
|
||||
//CHECK IS CARD BLACKLISTED
|
||||
let cardBlacklist = await validateBlacklist(card_number, uniqueCode);
|
||||
if (cardBlacklist) {
|
||||
return res.status(200).json(cardBlacklist);
|
||||
}
|
||||
|
||||
//CARD PRODUCT VALIDATION
|
||||
const validCardProduct = await validateCardProduct(card_number, uniqueCode);
|
||||
if (validCardProduct) {
|
||||
dataCard = validCardProduct.data;
|
||||
//CARD NOT REGISTERED IN CARD_PRODUCT
|
||||
if (dataCard.status == false) {
|
||||
return res.status(200).json(validCardProduct);
|
||||
}
|
||||
|
||||
dataCard = dataCard.detail;
|
||||
const card_status = dataCard.c_status;
|
||||
winston.logger.debug(`${uniqueCode} [ VALIDATE-TOPUP CARD STATUS ] status=${card_status}`);
|
||||
|
||||
// Status valid => Persoed (P) atau Active (A)
|
||||
if (card_status != 'P' && card_status != 'A') {
|
||||
if (card_status == 'B') {
|
||||
result = {
|
||||
code: '445',
|
||||
message: 'Card is blacklisted.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} else if (card_status == 'R') {
|
||||
result = {
|
||||
code: '451',
|
||||
message: 'Card is redeemed or replaced.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} else if (card_status == 'N') {
|
||||
result = {
|
||||
code: '463',
|
||||
message: 'Card is not activated.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} else {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'Card status: ' + card_status,
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if (last_balance) {
|
||||
// let getLastBalanceFromCardHistory = await model.getLastBalanceFromCardHistory(card_number);
|
||||
// if (getLastBalanceFromCardHistory) {
|
||||
// last_balance = getLastBalanceFromCardHistory.m_balance_after;
|
||||
// }
|
||||
// }
|
||||
// last_balance = 2000000;
|
||||
|
||||
// CHECK POS_BI_REGULATION_STAT
|
||||
const validBIRegulation = await validateBIRegulation(
|
||||
card_number,
|
||||
amount,
|
||||
last_balance,
|
||||
uniqueCode
|
||||
);
|
||||
if (validBIRegulation) {
|
||||
return res.status(200).json(validBIRegulation);
|
||||
}
|
||||
|
||||
//Card Topup Validation OK
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {
|
||||
card_number: card_number,
|
||||
last_balance: last_balance,
|
||||
amount: amount,
|
||||
},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE VALIDATE-TOPUP ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const checkBlacklist = async (req, res) => {
|
||||
try {
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
let { card_number } = req.body;
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST CHECK-BLACKLIST ]`);
|
||||
|
||||
//CHECK VALIDATOR
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
//TRIM CARD NUMBER
|
||||
card_number = card_number.trim();
|
||||
|
||||
//CHECK IS CARD ALLOW
|
||||
const validEnv = await validateEnvironment(card_number, uniqueCode);
|
||||
if (validEnv) {
|
||||
res.status(200).json(validEnv);
|
||||
}
|
||||
|
||||
//CHECK IS CARD BLACKLISTED
|
||||
let cardBlacklist = await validateBlacklist(card_number, uniqueCode);
|
||||
if (cardBlacklist) {
|
||||
return res.status(200).json(cardBlacklist);
|
||||
}
|
||||
|
||||
//CARD IS NOT BLACKLISTED
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Card is not blacklisted.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CHECK-BLACKLIST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CHECK-BLACKLIST ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { validateTopup, checkBlacklist };
|
||||
@@ -0,0 +1,370 @@
|
||||
const { logStatusCode } = require('../../helpers/log-fields');
|
||||
const model = require('./pos.model');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const moment = require('moment');
|
||||
|
||||
// Pengecekan kartu dipakai bersama oleh alur penjualan, top up, redeem, dan penggantian.
|
||||
const validateEnvironment = async (card_number, uniqueCode) => {
|
||||
let result = {};
|
||||
const validateEnvStatus = await model.getGlobalParameterData(
|
||||
'POS_CARD_VALIDATE_ENV'
|
||||
);
|
||||
|
||||
if (validateEnvStatus.c_value) {
|
||||
if (validateEnvStatus.c_value == 'A') {
|
||||
// jika settingan diperuntukan untuk production
|
||||
if (process.env.SERVER_FOR == 'production') {
|
||||
// kartu yang di request bukan kartu production maka akan di tolak
|
||||
if (card_number.substring(0, 1) != '1') {
|
||||
result = {
|
||||
code: '400',
|
||||
message: "It's not production card number.",
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
} else {
|
||||
// jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak
|
||||
if (card_number.substring(0, 1) == '1') {
|
||||
result = {
|
||||
code: '400',
|
||||
message:
|
||||
"It's production card number. Please use the development card number.",
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ]: skip.`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'POS_CARD_VALIDATE_ENV in global parameter not found',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
const validateBlacklist = async (card_number, uniqueCode) => {
|
||||
let result = {};
|
||||
const validateBlacklistStatus = await model.getGlobalParameterData(
|
||||
'POS_VALIDATE_CARD_BLACKLIST'
|
||||
);
|
||||
if (validateBlacklistStatus.c_value) {
|
||||
if (validateBlacklistStatus.c_value == 'A') {
|
||||
let cardBlacklist = await model.getCardBlacklist(card_number);
|
||||
if (cardBlacklist) {
|
||||
if (cardBlacklist.c_status == 'B') {
|
||||
result = {
|
||||
code: '445',
|
||||
message: 'Card is blacklisted.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CHECK-BLACKLIST ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//LOG-INFO
|
||||
winston.logger.info(`${uniqueCode} [ RESPONSE CHECK-BLACKLIST ]: skip.`);
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'POS_VALIDATE_CARD_BLACKLIST in global parameter not found',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CHECK-VALIDATE-ENV ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
const validateCardProduct = async (card_number, uniqueCode) => {
|
||||
let resultCP = {};
|
||||
const validateCardProductStatus = await model.getGlobalParameterData(
|
||||
'POS_VALIDATE_CARD_PRODUCT'
|
||||
);
|
||||
if (validateCardProductStatus.c_value) {
|
||||
if (validateCardProductStatus.c_value == 'A') {
|
||||
//SALES VALIDATION
|
||||
const dataCard = await model.getCardProduct(card_number);
|
||||
//No Card Product
|
||||
if (!dataCard) {
|
||||
resultCP = {
|
||||
code: '447',
|
||||
message: 'Card number is not registered in card product.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
resultCP = {
|
||||
code: '00',
|
||||
message: 'Card number is registered in card product.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: dataCard,
|
||||
},
|
||||
};
|
||||
}
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-CARD PRODUCT ] code=${logStatusCode(resultCP?.code)}`
|
||||
);
|
||||
return resultCP;
|
||||
} else {
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-CARD PRODUCT ]: skip.`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
resultCP = {
|
||||
code: '400',
|
||||
message: 'POS_VALIDATE_CARD_PRODUCT in global parameter not found',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-CARD PRODUCT ]: ${resultCP.code}`
|
||||
);
|
||||
return resultCP;
|
||||
}
|
||||
};
|
||||
|
||||
const checkCardReplacement = async (card_number, uniqueCode) => {
|
||||
let resultCR = {};
|
||||
|
||||
//SALES VALIDATION
|
||||
const dataCard = await model.getCardReplacement(card_number);
|
||||
//No Card Product
|
||||
if (!dataCard) {
|
||||
resultCR = {
|
||||
code: '448',
|
||||
message: 'Card number is not exist in card replacement.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
resultCR = {
|
||||
code: '00',
|
||||
message: 'Card number is registered in card replacement.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: dataCard,
|
||||
},
|
||||
};
|
||||
}
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-CARD REPLACEMENT ] code=${logStatusCode(resultCR?.code)}`
|
||||
);
|
||||
return resultCR;
|
||||
};
|
||||
|
||||
const checkCardSales = async (card_number, uniqueCode) => {
|
||||
const dataCard = await model.getCardSales(card_number);
|
||||
let resultCR = null;
|
||||
|
||||
if (dataCard) {
|
||||
const isSold = dataCard.sales_status === 'SUCCESS';
|
||||
resultCR = {
|
||||
code: isSold ? '444' : '00',
|
||||
message: isSold ? 'Card has been sold.' : 'Success',
|
||||
data: {
|
||||
status: !isSold,
|
||||
detail: isSold ? {} : dataCard,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CHECK-CARD SALES ] code=${logStatusCode(resultCR?.code)}`
|
||||
);
|
||||
|
||||
return resultCR;
|
||||
};
|
||||
|
||||
const validateBIRegulation = async (
|
||||
card_number,
|
||||
amount,
|
||||
last_balance,
|
||||
uniqueCode
|
||||
) => {
|
||||
let results = {};
|
||||
const validateBIRegulation = await model.getGlobalParameterData(
|
||||
'POS_BI_REGULATION_STAT'
|
||||
);
|
||||
if (validateBIRegulation.c_value) {
|
||||
if (validateBIRegulation.c_value == 'A') {
|
||||
// time
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
let today = moment().format('YYYY-MM-DD');
|
||||
let year = moment().format('Y');
|
||||
let month = moment().format('M');
|
||||
|
||||
// CHECK MAX AMOUNT ON CARD
|
||||
let checkMaxAmountOnTheCard = await model.getGlobalParameterData(
|
||||
'HSM_BI_MAX_AMOUNT_ON_THE_CARD'
|
||||
);
|
||||
if (checkMaxAmountOnTheCard.c_value) {
|
||||
if (
|
||||
parseInt(last_balance) + parseInt(amount) >
|
||||
parseInt(checkMaxAmountOnTheCard.c_value)
|
||||
) {
|
||||
results = {
|
||||
code: '416',
|
||||
message: 'Card number has reached the maximum balance',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION: MAX AMOUNT ] code=${logStatusCode(results?.code)}`
|
||||
);
|
||||
return results;
|
||||
}
|
||||
} else {
|
||||
results = {
|
||||
code: '400',
|
||||
message:
|
||||
'HSM_BI_MAX_AMOUNT_ON_THE_CARD in global parameter not found',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: ${results.code}`
|
||||
);
|
||||
return results;
|
||||
}
|
||||
|
||||
// VALIDATE MAX TOPUP PER MONTH
|
||||
let checkMaxTopupPerMonth = await model.getGlobalParameterData(
|
||||
'HSM_BI_MAX_TOPUP_PER_MONTH'
|
||||
);
|
||||
if (checkMaxTopupPerMonth.c_value) {
|
||||
// get accumulated balance in this month dari nomor kartu yang di request
|
||||
let accumulatedBalance = 0;
|
||||
let getAccumulationBalanceInThisMonthFromCardHistory =
|
||||
await model.getAccumulationBalanceInThisMonthFromCardHistory(
|
||||
card_number,
|
||||
year,
|
||||
month
|
||||
);
|
||||
|
||||
if (getAccumulationBalanceInThisMonthFromCardHistory) {
|
||||
accumulatedBalance =
|
||||
getAccumulationBalanceInThisMonthFromCardHistory.accumulation_balance;
|
||||
}
|
||||
|
||||
if (
|
||||
parseInt(accumulatedBalance) + parseInt(amount) >
|
||||
parseInt(checkMaxTopupPerMonth.c_value)
|
||||
) {
|
||||
results = {
|
||||
code: '417',
|
||||
message: 'card number has been limit top up for this month',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION: MAX TOPUP PER MONTH ] code=${logStatusCode(results?.code)}`
|
||||
);
|
||||
return results;
|
||||
}
|
||||
} else {
|
||||
results = {
|
||||
code: '400',
|
||||
message: 'HSM_BI_MAX_TOPUP_PER_MONTH in global parameter not found',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: ${results.code}`
|
||||
);
|
||||
return results;
|
||||
}
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: pass`
|
||||
);
|
||||
} else {
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: skip`
|
||||
);
|
||||
}
|
||||
} else {
|
||||
results = {
|
||||
code: '400',
|
||||
message: 'POS_BI_REGULATION_STAT in global parameter not found',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
};
|
||||
//LOG-INFO
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE VALIDATE-BI-REGULATION ]: ${results.code}`
|
||||
);
|
||||
return results;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { validateEnvironment, validateBlacklist, validateCardProduct, checkCardReplacement, checkCardSales, validateBIRegulation };
|
||||
@@ -0,0 +1,43 @@
|
||||
const { logErrorCode } = require('../../helpers/log-fields');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
|
||||
// Endpoint diagnostik POS.
|
||||
const testAPI = async (req, res) => {
|
||||
try {
|
||||
let result = {};
|
||||
let { card_number } = req.body;
|
||||
let last_balance = '10000';
|
||||
|
||||
//CARD VALID TO REPLACEMENT
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Successfully.',
|
||||
data: {
|
||||
status: true,
|
||||
detail: {
|
||||
card_number: card_number,
|
||||
last_balance: last_balance,
|
||||
},
|
||||
},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE VALIDATE-REPLACEMENT ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {
|
||||
status: false,
|
||||
detail: {},
|
||||
},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { testAPI };
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,33 @@
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
|
||||
// Dekripsi data reservasi pada endpoint yang sudah tersedia.
|
||||
const decrpytRequest = async (req, res) => {
|
||||
let uniqueCode = req.id ?? 'unknown';
|
||||
try {
|
||||
uniqueCode = await helper.getUniqueCode();
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST DECRYPT ]: received`);
|
||||
|
||||
const data = JSON.parse(helper.decryptText(req.body.reservation_data));
|
||||
const result = {
|
||||
code: '00',
|
||||
message: 'decrypted successfully.',
|
||||
data,
|
||||
};
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ RESPONSE DECRYPT ] code=${result.code}`);
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
const result = {
|
||||
code: '500',
|
||||
message: 'decrypted failed.',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// Catat jenis kegagalan tanpa menyimpan isi reservasi.
|
||||
winston.logger.error(`${uniqueCode} [ RESPONSE DECRYPT ] code=500 error_type=${error.name}`);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { decrpytRequest };
|
||||
@@ -0,0 +1,562 @@
|
||||
const { logErrorCode, logStatusCode } = require('../../helpers/log-fields');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { validationResult } = require('express-validator');
|
||||
const model = require('./reservebalance.model');
|
||||
const moment = require('moment');
|
||||
|
||||
// Pencarian reservasi, rincian transaksi, dan informasi biaya.
|
||||
const checkReservation = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
// param
|
||||
let { mid, tid, card_number } = req.body;
|
||||
|
||||
// log info
|
||||
// winston.logger.info(
|
||||
// `${uniqueCode} [ REQUEST RESERVATION-CHECK ]: ${JSON.stringify(req.body)}`
|
||||
// );
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ REQUEST RESERVATION-CHECK ]`);
|
||||
|
||||
// trim card number
|
||||
card_number = card_number.trim();
|
||||
|
||||
// check validator
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify(
|
||||
// result
|
||||
// )}`
|
||||
// );
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// pengecekkan nomor kartu yang di request adalah kartu production atau bukan berdasarkan settingan di .ENV dengan constanta SERVER_FOR.
|
||||
// Jika settingan .ENV SERVER_FOR adalah production dan nomor kartu KMT yang di request adalah kartu development maka sistem online topup akan menolaknya. Begitupun sebaliknya
|
||||
// Begitupun sebaliknya, jika settingan .ENV SERVER_FOR adalah development dan nomor kartu KMT yang di request adalah kartu production maka sistem online topup akan menolaknya
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING RESERVATION-CHECK ] checking production card number or not...`
|
||||
// );
|
||||
|
||||
let cardBlacklist = await model.getCardBlacklist(card_number);
|
||||
if (cardBlacklist) {
|
||||
if (cardBlacklist.c_status == 'B') {
|
||||
result = {
|
||||
code: '445',
|
||||
message: 'Card is Blacklisted',
|
||||
data: {},
|
||||
};
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
}
|
||||
|
||||
// jika settingan diperuntukan untuk production
|
||||
// if (process.env.SERVER_FOR == 'production') {
|
||||
// // kartu yang di request bukan kartu production maka akan di tolak
|
||||
// if (card_number.substring(0, 1) != '1') {
|
||||
// result = {
|
||||
// code: '400',
|
||||
// message: "It's not production card number.",
|
||||
// data: {},
|
||||
// };
|
||||
|
||||
// // log warn
|
||||
// // winston.logger.warn(
|
||||
// // `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify(
|
||||
// // result
|
||||
// // )}`
|
||||
// // );
|
||||
|
||||
// return res.status(200).json(result);
|
||||
// }
|
||||
// } else {
|
||||
// // jika settingan bukan diperuntukan untuk production, bisa development atau local atau yang lainnya dan kemudian kartu yang di request merupakan kartu production maka akan di tolak
|
||||
// if (card_number.substring(0, 1) == '1') {
|
||||
// result = {
|
||||
// code: '400',
|
||||
// message:
|
||||
// "It's production card number. Please use the development card number.",
|
||||
// data: {},
|
||||
// };
|
||||
// // log warn
|
||||
// // winston.logger.warn(
|
||||
// // `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify(
|
||||
// // result
|
||||
// // )}`
|
||||
// // );
|
||||
// return res.status(200).json(result);
|
||||
// }
|
||||
// }
|
||||
|
||||
// log debug
|
||||
// proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING RESERVATION-CHECK ] checking partner...`
|
||||
// );
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
if (!getPartner) {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'terminal id is not valid',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify(
|
||||
// result
|
||||
// )}`
|
||||
// );
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
if (getPartner.i_partner != req.partner_id_token) {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'partner is not match',
|
||||
data: {
|
||||
body: req.body,
|
||||
partner_id_token: req.partner_id_token,
|
||||
partner_user_id_token: req.partner_user_id_token,
|
||||
headers: req.headers,
|
||||
},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE RESERVATION-CHECK ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// lakukan pencarian ke table reservasion, apakah nomor kartu yang di request masih mempunyai transaksi reservasi saldo yang status nya masih pending atau in progress
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING RESERVATION-CHECK ] getting reservation with pending status and in progress status...`
|
||||
// );
|
||||
|
||||
// get reservation pending & in progress status
|
||||
let checkSecure = false;
|
||||
let getReservationWithPendingAndInProgressStatus =
|
||||
await model.getReservationWithPendingAndInProgressStatus(card_number);
|
||||
if (
|
||||
getReservationWithPendingAndInProgressStatus.total_reservation_pending > 0
|
||||
) {
|
||||
checkSecure = true;
|
||||
|
||||
// info jika nomor kartu yang di request mempunyai transaksi reservasi saldo yang status nya masih pending dan in progress
|
||||
result = {
|
||||
code: '03',
|
||||
message: 'success with reservation pending or in progress.',
|
||||
data: {},
|
||||
};
|
||||
} else {
|
||||
// info jika nomor kartu yang di request tidak mempunyai transaksi reservasi saldo yang status nya masih pending dan in progress
|
||||
result = {
|
||||
code: '02',
|
||||
message: 'success without reservation pending or in progress.',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
|
||||
// log info
|
||||
// winston.logger.info(
|
||||
// `${uniqueCode} [ RESPONSE RESERVATION-CHECK ]: ${JSON.stringify(result)}`
|
||||
// );
|
||||
|
||||
winston.logger.info(`${uniqueCode} [ RESPONSE RESERVATION-CHECK ] code=${result.code}`);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE RESERVATION-CHECK ] code=500 error_code=${logErrorCode(error)}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const inquiryReservation = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let { reservation_number, card_number, start_date, end_date } = req.body;
|
||||
|
||||
// time
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
// validation parameter inquiry
|
||||
if (!reservation_number && !card_number) {
|
||||
return res.status(200).json({
|
||||
code: '400',
|
||||
message:
|
||||
'bad request. please add the reservation number or card number!',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
// validation inquiry date
|
||||
if ((!start_date && end_date) || (start_date && !end_date)) {
|
||||
return res.status(200).json({
|
||||
code: '400',
|
||||
message: 'bad request. please check the date!',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
// check reservation
|
||||
if (reservation_number) {
|
||||
let byReservationNumber = await model.inquiryByReservationNumber(
|
||||
reservation_number
|
||||
);
|
||||
|
||||
if (!byReservationNumber) {
|
||||
return res.status(200).json({
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({
|
||||
code: '00',
|
||||
message: 'reservation has been found.',
|
||||
data: byReservationNumber,
|
||||
});
|
||||
} else if (card_number) {
|
||||
let byCardNumber = await model.inquiryByCardNumber(
|
||||
card_number,
|
||||
start_date,
|
||||
end_date
|
||||
);
|
||||
|
||||
if (!byCardNumber) {
|
||||
return res.status(200).json({
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({
|
||||
code: '00',
|
||||
message: 'reservation has been found.',
|
||||
data: byCardNumber,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const inquiryReservationByReservation = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let {
|
||||
reservation_number,
|
||||
ref_no,
|
||||
load_balance_number,
|
||||
show_complete_data,
|
||||
} = req.body;
|
||||
|
||||
let result;
|
||||
|
||||
if (req.query.search === 'ref-no') {
|
||||
// validation parameter inquiry
|
||||
if (!ref_no) {
|
||||
return res.status(200).json({
|
||||
code: '400',
|
||||
message: 'bad request. please add the ref number!',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
// check reservation
|
||||
result = await model.inquiryListByRefNumber(ref_no, show_complete_data);
|
||||
|
||||
if (!result) {
|
||||
return res.status(200).json({
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} else if (req.query.search === 'load-balance-number') {
|
||||
// validation parameter inquiry
|
||||
if (!load_balance_number) {
|
||||
return res.status(200).json({
|
||||
code: '400',
|
||||
message: 'bad request. please add the load balance number!',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
// check reservation
|
||||
result = await model.inquiryListByLoadNumber(
|
||||
load_balance_number,
|
||||
show_complete_data
|
||||
);
|
||||
|
||||
if (result.length < 1) {
|
||||
return res.status(200).json({
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// validation parameter inquiry
|
||||
if (!reservation_number) {
|
||||
return res.status(200).json({
|
||||
code: '400',
|
||||
message: 'bad request. please add the reservation number!',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
// check reservation
|
||||
result = await model.inquiryByReservationNumber(
|
||||
reservation_number,
|
||||
show_complete_data
|
||||
);
|
||||
|
||||
if (!result) {
|
||||
return res.status(200).json({
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return res.json({
|
||||
code: '00',
|
||||
message: 'reservation has been found.',
|
||||
data: result,
|
||||
});
|
||||
} catch (error) {
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const inquiryListReservationByReservation = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let { start_date, end_date } = req.body;
|
||||
|
||||
// validation parameter inquiry
|
||||
if (!start_date || !end_date) {
|
||||
return res.status(200).json({
|
||||
code: '400',
|
||||
message: 'bad request. please add the start date and end date!',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
let startDateCheckFormat = moment(start_date, 'YYYY-MM-DD', true).isValid();
|
||||
let endDateCheckFormat = moment(end_date, 'YYYY-MM-DD', true).isValid();
|
||||
|
||||
if (startDateCheckFormat == false || endDateCheckFormat == false) {
|
||||
return res.status(200).json({
|
||||
code: '400',
|
||||
message: 'bad request. format start date or end date is invalid!',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
// check date range max 1 month
|
||||
let diff = moment(end_date).diff(moment(start_date), 'months', true);
|
||||
|
||||
if (diff >= 1) {
|
||||
return res.status(200).json({
|
||||
code: '400',
|
||||
message:
|
||||
'bad request. We only allow data requests for 1 month. please change your date range parameter request!',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
// check reservation
|
||||
let listReservation = await model.inquiryListReservation(
|
||||
req.partner_id_token,
|
||||
start_date,
|
||||
end_date
|
||||
);
|
||||
|
||||
if (!listReservation) {
|
||||
return res.status(200).json({
|
||||
code: '414',
|
||||
message: "reservation doesn't exist",
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
return res.json({
|
||||
code: '00',
|
||||
message: 'reservation has been found.',
|
||||
data: listReservation,
|
||||
});
|
||||
} catch (error) {
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const getFeeSharing = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
// param
|
||||
let { datetime, mid, tid } = req.body;
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST GET-FEE-SHARING ]`
|
||||
);
|
||||
|
||||
// datetime
|
||||
if (!datetime) {
|
||||
datetime = moment().format('YYYY-MM-DD');
|
||||
} else {
|
||||
datetime = moment(datetime).format('YYYY-MM-DD');
|
||||
}
|
||||
|
||||
// log debug
|
||||
// proses pengecekkan data partner berdasarkan mid dan tid yang di request, apakah terdaftar di sistem CMS atau tidak
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING GET-FEE-SHARING ] checking partner...`
|
||||
// );
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
|
||||
// jika partner (mid atau tid) tidak ditemukan atau tidak terdaftar di sistem CMS
|
||||
if (!getPartner) {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'terminal id is not valid',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE GET-FEE-SHARING ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
if (getPartner.i_partner != req.partner_id_token) {
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'partner is not match',
|
||||
data: {},
|
||||
};
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// set default issuer fee
|
||||
let issuerFee = 0;
|
||||
let channelFee = 0;
|
||||
|
||||
// get issuer fee dan channel fee dari table public.t_c_partner_fee
|
||||
let getIssuer = await model.getIssuer(getPartner.i_partner, datetime);
|
||||
|
||||
if (getIssuer) {
|
||||
// per tanggal 1 November 2023 fee sharing mulai menggunakan amount nominal dan bukan persentase lagi
|
||||
if (datetime >= '2023-11-01') {
|
||||
issuerFee = getIssuer.i_issuer_fee_nominal;
|
||||
channelFee = getIssuer.i_channel_fee_nominal;
|
||||
} else {
|
||||
// ======================= KHUSUS LRT JABODEBEK =============================
|
||||
if (getPartner.partner_code == 'P05') {
|
||||
issuerFee = getIssuer.i_issuer_fee_nominal;
|
||||
channelFee = getIssuer.i_channel_fee_nominal;
|
||||
} else {
|
||||
// SELAIN LRT JABODEBEK
|
||||
issuerFee =
|
||||
(getIssuer.i_issuer_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
channelFee =
|
||||
(getIssuer.i_channel_fee_perc / 100) * parseInt(getIssuer.i_amount);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'fee sharing has been found.',
|
||||
data: {
|
||||
issuer_fee: issuerFee,
|
||||
channel_fee: channelFee,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE GET-FEE-SHARING ] code=${logStatusCode(result?.code)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { checkReservation, inquiryReservation, inquiryReservationByReservation, inquiryListReservationByReservation, getFeeSharing };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,13 +1,13 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const auth = require("../middlewares/jwt.middleware");
|
||||
const controller = require("../modules/cashin/cahsin.controller");
|
||||
const controller = require("../modules/cashin/cashin.controller");
|
||||
|
||||
router.get(
|
||||
"/online/cash-in",
|
||||
// auth.authenticateToken,
|
||||
// controller.validate("generateInvoice"),
|
||||
controller.apiGenerateCahsIn
|
||||
controller.apiGenerateCashIn
|
||||
);
|
||||
|
||||
router.get(
|
||||
@@ -35,7 +35,7 @@ router.post(
|
||||
"/online/cash-in/posting",
|
||||
// auth.authenticateToken,
|
||||
// controller.validate("generateInvoice"),
|
||||
controller.apiPostingCahsIn
|
||||
controller.apiPostingCashIn
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,112 @@
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const bcrypt = require('bcrypt');
|
||||
const jwt = require('../middlewares/jwt.middleware');
|
||||
const model = require('../modules/auth/auth.model');
|
||||
const { logger } = require('../helpers/winston.logger');
|
||||
|
||||
jest.mock('bcrypt', () => ({ compare: jest.fn() }));
|
||||
jest.mock('../helpers/helper', () => ({
|
||||
getUniqueCode: () => 'auth-fixture',
|
||||
encryptText: (value) => `encoded-${value}`,
|
||||
}));
|
||||
jest.mock('../helpers/winston.logger', () => ({
|
||||
logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() },
|
||||
}));
|
||||
jest.mock('../middlewares/jwt.middleware', () => ({
|
||||
authenticateToken: (req, res, next) => next(),
|
||||
authenticateRefreshToken: (req, res, next) => next(),
|
||||
generateAccessToken: jest.fn(),
|
||||
generateRefreshToken: jest.fn(),
|
||||
}));
|
||||
jest.mock('../modules/auth/auth.model', () => ({
|
||||
checkDataLoginPartnerUser: jest.fn(),
|
||||
insertRefreshTokenPartner: jest.fn(),
|
||||
checkRefreshToken: jest.fn(),
|
||||
updateRefreshToken: jest.fn(),
|
||||
}));
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api', require('../routes/auth.routes'));
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
jwt.generateAccessToken.mockResolvedValue('fixture-access');
|
||||
jwt.generateRefreshToken.mockResolvedValue('fixture-refresh');
|
||||
});
|
||||
|
||||
test('login partner memvalidasi password dan menyimpan refresh token sebelum merespons', async () => {
|
||||
model.checkDataLoginPartnerUser.mockResolvedValue({
|
||||
i_partner: 1,
|
||||
i_partner_user: 2,
|
||||
c_password: '$2y$fixture-hash',
|
||||
});
|
||||
bcrypt.compare.mockResolvedValue(true);
|
||||
|
||||
const res = await request(app).post('/api/login').send({
|
||||
email: 'partner@example.test',
|
||||
password: 'fixture-password',
|
||||
});
|
||||
|
||||
expect(model.checkDataLoginPartnerUser).toHaveBeenCalledWith('PARTNER@EXAMPLE.TEST');
|
||||
expect(bcrypt.compare).toHaveBeenCalledWith('fixture-password', '$2a$fixture-hash');
|
||||
expect(model.insertRefreshTokenPartner).toHaveBeenCalledWith('partner@example.test', 'fixture-refresh');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({
|
||||
code: '00',
|
||||
message: 'Login Success.',
|
||||
data: { access_token: 'fixture-access', refresh_token: 'fixture-refresh' },
|
||||
});
|
||||
});
|
||||
|
||||
test('login dengan password fixture yang salah tidak membuat atau menyimpan token', async () => {
|
||||
model.checkDataLoginPartnerUser.mockResolvedValue({ c_password: '$2y$fixture-hash' });
|
||||
bcrypt.compare.mockResolvedValue(false);
|
||||
|
||||
const res = await request(app).post('/api/login').send({
|
||||
email: 'partner@example.test',
|
||||
password: 'fixture-wrong-password',
|
||||
});
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ code: '403', message: 'Password is wrong.', data: {} });
|
||||
expect(jwt.generateAccessToken).not.toHaveBeenCalled();
|
||||
expect(model.insertRefreshTokenPartner).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('refresh terminal memperbarui token dan mencatat hasil tanpa isi token atau request', async () => {
|
||||
model.checkRefreshToken.mockResolvedValue(true);
|
||||
|
||||
const res = await request(app).post('/api/refresh-token/terminal')
|
||||
.set('refresh-token', 'fixture-old-token')
|
||||
.send({ mid: 'fixture-mid', tid: 'fixture-tid' });
|
||||
|
||||
expect(model.checkRefreshToken).toHaveBeenCalledWith('fixture-mid', 'fixture-tid', 'fixture-old-token');
|
||||
expect(model.updateRefreshToken).toHaveBeenCalledWith(
|
||||
'fixture-mid', 'fixture-tid', 'fixture-old-token', 'fixture-refresh',
|
||||
);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({
|
||||
code: '00',
|
||||
message: 'New Token has been generated.',
|
||||
data: { access_token: 'fixture-access', refresh_token: 'fixture-refresh' },
|
||||
});
|
||||
expect(logger.info.mock.calls.flat()).toEqual([
|
||||
'auth-fixture [ REQUEST REFRESH-TOKEN-TERMINAL ]',
|
||||
'auth-fixture [ RESPONSE REFRESH-TOKEN-TERMINAL ] code=00',
|
||||
]);
|
||||
});
|
||||
|
||||
test('refresh terminal yang tidak terdaftar berhenti tanpa membuat token', async () => {
|
||||
model.checkRefreshToken.mockResolvedValue(null);
|
||||
|
||||
const res = await request(app).post('/api/refresh-token/terminal')
|
||||
.set('refresh-token', 'fixture-old-token')
|
||||
.send({ mid: 'fixture-mid', tid: 'fixture-tid' });
|
||||
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ code: '400', message: 'Refresh Token is invalid. Please try login', data: {} });
|
||||
expect(jwt.generateAccessToken).not.toHaveBeenCalled();
|
||||
expect(model.updateRefreshToken).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -13,7 +13,7 @@ jest.mock('../modules/cashin/cash-in-posting.service', () => jest.fn());
|
||||
|
||||
const helper = require('../helpers/helper');
|
||||
const { _generateCashIn } = require('../modules/cashin/cash-in-generation.service');
|
||||
const { apiGenerateCahsIn } = require('../modules/cashin/cahsin.controller');
|
||||
const { apiGenerateCashIn } = require('../modules/cashin/cashin.controller');
|
||||
|
||||
test('permintaan Cash-in paralel mempertahankan kode dan hasil masing-masing', async () => {
|
||||
let finishFirst;
|
||||
@@ -27,8 +27,8 @@ test('permintaan Cash-in paralel mempertahankan kode dan hasil masing-masing', a
|
||||
|
||||
const firstResponse = { status: jest.fn().mockReturnThis(), json: jest.fn() };
|
||||
const secondResponse = { status: jest.fn().mockReturnThis(), json: jest.fn() };
|
||||
const first = apiGenerateCahsIn({}, firstResponse);
|
||||
await apiGenerateCahsIn({}, secondResponse);
|
||||
const first = apiGenerateCashIn({}, firstResponse);
|
||||
await apiGenerateCashIn({}, secondResponse);
|
||||
expect(finishFirst).toBeDefined();
|
||||
finishFirst();
|
||||
await first;
|
||||
|
||||
@@ -34,7 +34,7 @@ integration('cash-in SAP posting with PostgreSQL and a local HTTP stand-in', ()
|
||||
postCashIn = require('../modules/cashin/cash-in-posting.service');
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api', require('../routes/cahsin.routes'));
|
||||
app.use('/api', require('../routes/cashin.routes'));
|
||||
await db.raw(`
|
||||
CREATE SCHEMA payment;
|
||||
CREATE SCHEMA trx;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
const model = require('../modules/loadbalance/loadbalance.model');
|
||||
const { loadingBalanceInsert } = require('../modules/loadbalance/loadbalance.controller');
|
||||
const { logger } = require('../helpers/winston.logger');
|
||||
const { loadingBalanceInsert, loadingBalanceUpdate } = require('../modules/loadbalance/loadbalance.controller');
|
||||
|
||||
jest.mock('../helpers/helper', () => ({}));
|
||||
jest.mock('../helpers/winston.logger', () => ({ logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() } }));
|
||||
@@ -12,6 +13,12 @@ jest.mock('../modules/loadbalance/loadbalance.model', () => ({
|
||||
allocateLoadBalanceNumber: jest.fn(),
|
||||
findReservationDetails: jest.fn(),
|
||||
insertLoadingBalance: jest.fn(),
|
||||
withLoadBalanceTransaction: jest.fn(),
|
||||
updateLoadingBalance: jest.fn(),
|
||||
findLoadBalance: jest.fn(),
|
||||
findLoadBalanceDetail: jest.fn(),
|
||||
insertLoadingBalanceHistoryOnly: jest.fn(),
|
||||
createLoadBalanceLog: jest.fn(),
|
||||
}));
|
||||
|
||||
const req = { partner_id_token: '1' };
|
||||
@@ -23,6 +30,32 @@ beforeEach(() => {
|
||||
model.getPartner.mockResolvedValue({ i_partner: '1', partner_code: 'TEST' });
|
||||
});
|
||||
|
||||
test('menolak terminal milik partner lain sebelum membaca atau menulis reservasi', async () => {
|
||||
model.getPartner.mockResolvedValue({ i_partner: '2' });
|
||||
|
||||
await expect(loadingBalanceInsert(req, input)).resolves.toEqual({
|
||||
code: '412',
|
||||
message: 'partner is not match',
|
||||
data: {},
|
||||
});
|
||||
expect(model.findReservationsWithLoadedBalance).not.toHaveBeenCalled();
|
||||
expect(model.insertLoadingBalance).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('log layanan tidak menyimpan kode klien mentah atau data kartu', async () => {
|
||||
model.getPartner.mockResolvedValue(null);
|
||||
|
||||
await expect(loadingBalanceInsert(req, {
|
||||
...input,
|
||||
unique_code: 'fixture-arbitrary-reference',
|
||||
uid: 'fixture-private-uid',
|
||||
card_number: 'fixture-private-card',
|
||||
})).resolves.toMatchObject({ code: '412' });
|
||||
|
||||
expect(logger.info).toHaveBeenCalledWith('unknown [ REQUEST LOADING-BALANCE-INSERT ]');
|
||||
expect(logger.warn).toHaveBeenCalledWith('unknown [ RESPONSE LOADING-BALANCE-INSERT ] code=412');
|
||||
});
|
||||
|
||||
test.each([
|
||||
[['missing', 'RBL1'], '414'],
|
||||
[['RBL1', 'missing'], '00'],
|
||||
@@ -83,3 +116,48 @@ test('preserves code 414 if a pending reservation is absent at the new read', as
|
||||
expect(model.allocateLoadBalanceNumber).not.toHaveBeenCalled();
|
||||
expect(model.insertLoadingBalance).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const updateInput = {
|
||||
...input,
|
||||
card_number: 'fixture-card',
|
||||
load_balance_number: 'LBL1',
|
||||
balance: 100,
|
||||
};
|
||||
|
||||
function setupUpdateTransaction() {
|
||||
const trx = jest.fn();
|
||||
model.withLoadBalanceTransaction.mockImplementation((operation) => operation(trx));
|
||||
model.findLoadBalance.mockResolvedValue({ i_load_balance: 7, c_load_balance_no: 'LBL1' });
|
||||
model.findLoadBalanceDetail.mockResolvedValue([{ c_reservation_no: 'RBL1' }]);
|
||||
return trx;
|
||||
}
|
||||
|
||||
test.each([
|
||||
['updateLoadingBalance', ['findLoadBalance', 'insertLoadingBalanceHistoryOnly', 'createLoadBalanceLog']],
|
||||
['insertLoadingBalanceHistoryOnly', ['createLoadBalanceLog']],
|
||||
['createLoadBalanceLog', []],
|
||||
])('Load Balance mengembalikan kode 500 jika %s gagal', async (stage, laterStages) => {
|
||||
setupUpdateTransaction();
|
||||
const failure = Object.assign(new Error('fixture write failed'), { code: '23514' });
|
||||
model[stage].mockRejectedValue(failure);
|
||||
|
||||
await expect(loadingBalanceUpdate(updateInput)).resolves.toMatchObject({ code: '500', data: {} });
|
||||
await expect(model.withLoadBalanceTransaction.mock.results[0].value).rejects.toBe(failure);
|
||||
for (const laterStage of laterStages) expect(model[laterStage]).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('pembaruan saldo, riwayat, dan audit memakai transaksi yang sama', async () => {
|
||||
const trx = setupUpdateTransaction();
|
||||
|
||||
await expect(loadingBalanceUpdate(updateInput)).resolves.toMatchObject({
|
||||
code: '00',
|
||||
data: { load_balance_number: 'LBL1' },
|
||||
});
|
||||
|
||||
expect(model.withLoadBalanceTransaction).toHaveBeenCalledTimes(1);
|
||||
expect(model.updateLoadingBalance.mock.calls[0][0]).toBe(trx);
|
||||
expect(model.findLoadBalance).toHaveBeenCalledWith('LBL1', trx);
|
||||
expect(model.findLoadBalanceDetail).toHaveBeenCalledWith(7, trx);
|
||||
expect(model.insertLoadingBalanceHistoryOnly.mock.calls[0][0]).toBe(trx);
|
||||
expect(model.createLoadBalanceLog).toHaveBeenCalledWith(expect.objectContaining({ i_log_name: 21 }), trx);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
jest.mock('../../infrastructure/database/knex', () => ({ transaction: jest.fn() }));
|
||||
jest.mock('../helpers/winston.logger', () => ({ logger: { error: jest.fn() } }));
|
||||
|
||||
const db = require('../../infrastructure/database/knex');
|
||||
const { logger } = require('../helpers/winston.logger');
|
||||
const model = require('../modules/loadbalance/loadbalance.model');
|
||||
|
||||
const header = { c_load_balance_no: 'LBL1', d_load_balance: '2026-11-24' };
|
||||
const detail = {
|
||||
i_reservation_balance: 7,
|
||||
c_reservation_no: 'RBL1',
|
||||
i_amount: 20000,
|
||||
i_reservation_amount: 10000,
|
||||
};
|
||||
|
||||
function captureTransaction(failTable, updatedReservations = 1) {
|
||||
const writes = [];
|
||||
const failure = Object.assign(new Error('fixture write failure'), { code: '23514' });
|
||||
const trx = jest.fn((table) => {
|
||||
const query = {};
|
||||
|
||||
for (const method of ['insert', 'update', 'del', 'returning', 'where', 'whereIn', 'whereRaw']) {
|
||||
query[method] = (...args) => {
|
||||
writes.push([table, method, ...args]);
|
||||
return query;
|
||||
};
|
||||
}
|
||||
|
||||
query.then = (resolve, reject) => {
|
||||
if (table === failTable) return Promise.reject(failure).then(resolve, reject);
|
||||
const result = table === 'trx.t_d_load_balance' ? [{ i_load_balance: 10 }]
|
||||
: table === 'trx.t_d_load_balance_history' ? [{ i_load_balance: 20 }]
|
||||
: table === 'trx.t_d_reservation_balance' ? updatedReservations
|
||||
: { rowCount: 1 };
|
||||
return Promise.resolve(result).then(resolve, reject);
|
||||
};
|
||||
|
||||
return query;
|
||||
});
|
||||
|
||||
db.transaction.mockImplementation((callback) => callback(trx));
|
||||
return { trx, writes };
|
||||
}
|
||||
|
||||
beforeEach(() => jest.clearAllMocks());
|
||||
|
||||
test('simpan saldo memakai ID header dan riwayat masing-masing dalam satu transaksi', async () => {
|
||||
const { trx, writes } = captureTransaction();
|
||||
|
||||
await expect(model.insertLoadingBalance(
|
||||
header, [detail], ['RBL1'], '2026-11-24', false, 'card', 'UID', 20000, 1
|
||||
)).resolves.toBe(1);
|
||||
|
||||
expect(db.transaction).toHaveBeenCalledTimes(1);
|
||||
expect(trx.mock.calls.flat()).toEqual([
|
||||
'trx.t_d_load_balance', 'trx.t_d_load_balance_detail',
|
||||
'trx.t_d_load_balance_history', 'trx.t_d_load_balance_history_detail',
|
||||
'trx.t_d_reservation_balance', 'trx.t_d_flag_counting', 'trx.t_d_flag_counting',
|
||||
]);
|
||||
expect(writes).toContainEqual([
|
||||
'trx.t_d_load_balance_detail', 'insert', [expect.objectContaining({ i_load_balance: 10, i_amount: 20000 })],
|
||||
]);
|
||||
expect(writes).toContainEqual([
|
||||
'trx.t_d_load_balance_history_detail', 'insert', [expect.objectContaining({ i_load_balance: 20, i_amount: 20000 })],
|
||||
]);
|
||||
});
|
||||
|
||||
test('kegagalan detail menggagalkan callback transaksi sebelum status reservasi berubah', async () => {
|
||||
const { trx } = captureTransaction('trx.t_d_load_balance_history_detail');
|
||||
|
||||
await expect(model.updateReservationAndLoadingBalance(
|
||||
['RBL1'], header, [detail], '2026-11-24', 1
|
||||
)).resolves.toBe(false);
|
||||
|
||||
expect(trx).not.toHaveBeenCalledWith('trx.t_d_reservation_balance');
|
||||
await expect(db.transaction.mock.results[0].value).rejects.toMatchObject({ code: '23514' });
|
||||
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining('sqlstate=23514'));
|
||||
});
|
||||
|
||||
test('pemulihan saldo memakai nominal reservasi dan mengembalikan jumlah reservasi diperbarui', async () => {
|
||||
const { writes } = captureTransaction();
|
||||
|
||||
await expect(model.updateReservationAndInsertLoadingBalance(
|
||||
['RBL1'], header, [detail], '2026-11-24', 1
|
||||
)).resolves.toBe(1);
|
||||
|
||||
expect(writes).toContainEqual([
|
||||
'trx.t_d_load_balance_detail', 'insert', [expect.objectContaining({ i_amount: 10000 })],
|
||||
]);
|
||||
expect(writes).toContainEqual([
|
||||
'trx.t_d_reservation_balance', 'update', expect.objectContaining({ c_status: 'A', c_status_name: 'LOADED' }),
|
||||
]);
|
||||
});
|
||||
|
||||
test('pembuatan saldo pemulihan dibatalkan jika tidak ada reservasi yang diperbarui', async () => {
|
||||
captureTransaction(undefined, 0);
|
||||
|
||||
await expect(model.updateReservationAndInsertLoadingBalance(
|
||||
['RBL1'], header, [detail], '2026-11-24', 1
|
||||
)).resolves.toBe('No reservations found for load balance recovery');
|
||||
await expect(db.transaction.mock.results[0].value).rejects.toThrow('No reservations found');
|
||||
});
|
||||
@@ -0,0 +1,178 @@
|
||||
const testDatabaseUrl = process.env.TOPUP_TEST_LOAD_BALANCE_DB_URL;
|
||||
const integration = testDatabaseUrl ? describe : describe.skip;
|
||||
|
||||
jest.mock('../../infrastructure/database/knex', () => {
|
||||
const connection = (...args) => mockTransaction(...args);
|
||||
connection.transaction = (callback) => mockTransaction.transaction(callback);
|
||||
return connection;
|
||||
});
|
||||
|
||||
let mockTransaction;
|
||||
|
||||
jest.mock('../helpers/winston.logger', () => ({
|
||||
logger: { info: jest.fn(), debug: jest.fn(), warn: jest.fn(), error: jest.fn() },
|
||||
}));
|
||||
|
||||
integration('pembaruan Load Balance di PostgreSQL', () => {
|
||||
let db;
|
||||
let update;
|
||||
let recover;
|
||||
|
||||
beforeAll(() => {
|
||||
const url = new URL(testDatabaseUrl);
|
||||
if (url.hostname !== '127.0.0.1' || url.pathname !== '/topup_loadbalance_test') {
|
||||
throw new Error('Gunakan database lokal topup_loadbalance_test khusus pengujian.');
|
||||
}
|
||||
|
||||
const { withTransactionTimeZone } = require('../../infrastructure/transaction-time');
|
||||
db = require('knex')(withTransactionTimeZone({
|
||||
client: 'pg',
|
||||
connection: testDatabaseUrl,
|
||||
pool: {
|
||||
min: 0,
|
||||
max: 1,
|
||||
afterCreate(connection, done) {
|
||||
connection.query("SET TIME ZONE 'UTC'", (error) => done(error, connection));
|
||||
},
|
||||
},
|
||||
}));
|
||||
const model = require('../modules/loadbalance/loadbalance.model');
|
||||
jest.spyOn(model, 'getPartner').mockResolvedValue({ partner_name: 'Fixture Partner' });
|
||||
({ loadingBalanceUpdate: update } = require('../modules/loadbalance/loadbalance.controller'));
|
||||
({ updateAllTransaction: recover } = require('../modules/loadbalance/load-balance-write.service'));
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
// Skema fixture ikut dibatalkan bersama transaksi induk setelah pengujian.
|
||||
mockTransaction = await db.transaction();
|
||||
await mockTransaction.raw(`
|
||||
CREATE SCHEMA trx;
|
||||
CREATE SCHEMA log;
|
||||
CREATE TABLE trx.t_d_load_balance (
|
||||
i_load_balance serial PRIMARY KEY, c_load_balance_no text UNIQUE,
|
||||
d_load_balance timestamp, c_ref_no text, m_balance integer,
|
||||
c_return_sap text, c_status text, c_status_name text,
|
||||
d_modify timestamp, i_modify integer, c_modify_username text, c_modify_fullname text
|
||||
);
|
||||
ALTER TABLE trx.t_d_load_balance
|
||||
ADD COLUMN i_partner integer, ADD COLUMN c_partner_code text, ADD COLUMN c_partner_name text,
|
||||
ADD COLUMN i_merchant integer, ADD COLUMN c_merchant_code text, ADD COLUMN c_merchant_name text,
|
||||
ADD COLUMN c_mid text, ADD COLUMN i_terminal integer, ADD COLUMN c_terminal_code text,
|
||||
ADD COLUMN c_terminal_name text, ADD COLUMN c_tid text, ADD COLUMN c_card_number text,
|
||||
ADD COLUMN i_topup_amount integer, ADD COLUMN i_load_balance_no_seq integer, ADD COLUMN c_idm text,
|
||||
ADD COLUMN d_create timestamp, ADD COLUMN i_create integer, ADD COLUMN c_create_username text,
|
||||
ADD COLUMN c_create_fullname text, ADD COLUMN d_delete timestamp, ADD COLUMN i_delete integer,
|
||||
ADD COLUMN c_delete_username text, ADD COLUMN c_delete_fullname text;
|
||||
CREATE TABLE trx.t_d_load_balance_history (LIKE trx.t_d_load_balance INCLUDING DEFAULTS);
|
||||
CREATE TABLE trx.t_d_load_balance_detail (
|
||||
i_load_balance integer, i_reservation_balance integer, c_reservation_no text, i_amount integer,
|
||||
i_issuer integer, c_issuer_code text, c_issuer_name text, i_issuer_fee integer,
|
||||
i_channel integer, c_channel_code text, c_channel_name text, i_channel_fee integer
|
||||
);
|
||||
CREATE TABLE trx.t_d_load_balance_history_detail (
|
||||
i_load_balance integer, i_reservation_balance integer, c_reservation_no text, i_amount integer,
|
||||
i_issuer integer, i_issuer_code text, i_issuer_name text, i_issuer_fee integer,
|
||||
i_channel integer, i_channel_code text, i_channel_name text, i_channel_fee integer
|
||||
);
|
||||
CREATE TABLE trx.t_d_reservation_balance (
|
||||
c_reservation_no text, c_load_balance_no text, c_status text, c_status_name text,
|
||||
c_flag text, c_flag_code text, d_load_balance timestamp, d_modify timestamp, i_modify integer,
|
||||
c_modify_username text, c_modify_fullname text
|
||||
);
|
||||
CREATE TABLE trx.t_d_flag_counting (
|
||||
d_request timestamp, c_card_number text, c_uid text, i_balance integer, c_flag text
|
||||
);
|
||||
CREATE TABLE log.t_log_card (
|
||||
i_log_name integer, d_log timestamp, c_card_number text, c_source text, c_location text,
|
||||
m_balance_before integer, m_amount integer, m_balance_after integer, j_new_data jsonb, j_old_data jsonb,
|
||||
c_note text, c_status text, d_created timestamp, i_create integer, c_create_username text,
|
||||
c_create_fullname text, c_category text
|
||||
);
|
||||
INSERT INTO trx.t_d_load_balance (c_load_balance_no, c_status, m_balance) VALUES ('LBL1', 'I', 50);
|
||||
INSERT INTO trx.t_d_load_balance_detail VALUES (1, 7, 'RBL1', 20);
|
||||
INSERT INTO trx.t_d_reservation_balance (c_reservation_no, c_load_balance_no, c_status)
|
||||
VALUES ('RBL1', 'LBL1', 'I');
|
||||
INSERT INTO trx.t_d_flag_counting (c_card_number, c_uid, i_balance, c_flag)
|
||||
VALUES ('card-fixture', 'UID', 50, '1');
|
||||
`);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (mockTransaction) await mockTransaction.rollback();
|
||||
mockTransaction = undefined;
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (db) await db.destroy();
|
||||
});
|
||||
|
||||
const input = {
|
||||
load_balance_number: 'LBL1', reservation_number: ['RBL1'],
|
||||
mid: 'fixture-mid', tid: 'fixture-tid', card_number: 'card-fixture',
|
||||
uid: 'uid', write_status: false, balance: 70, amount: 20, flag: '2',
|
||||
};
|
||||
|
||||
test.each([
|
||||
['saldo', "ALTER TABLE trx.t_d_load_balance ADD CHECK (c_status <> 'A')"],
|
||||
['detail riwayat', 'ALTER TABLE trx.t_d_load_balance_history_detail ADD CHECK (i_amount < 0)'],
|
||||
['audit kartu', 'ALTER TABLE log.t_log_card ADD CHECK (i_log_name <> 21)'],
|
||||
])('kegagalan menulis %s membatalkan seluruh perubahan', async (_stage, constraint) => {
|
||||
await mockTransaction.raw(constraint);
|
||||
|
||||
await expect(update(input)).resolves.toMatchObject({ code: '500' });
|
||||
|
||||
await expect(mockTransaction('trx.t_d_load_balance').first('c_status', 'm_balance'))
|
||||
.resolves.toEqual({ c_status: 'I', m_balance: 50 });
|
||||
await expect(mockTransaction('trx.t_d_reservation_balance').first('c_status'))
|
||||
.resolves.toEqual({ c_status: 'I' });
|
||||
await expect(mockTransaction('trx.t_d_flag_counting').first('i_balance'))
|
||||
.resolves.toEqual({ i_balance: 50 });
|
||||
await expect(mockTransaction('trx.t_d_load_balance_history').select('i_load_balance')).resolves.toEqual([]);
|
||||
await expect(mockTransaction('trx.t_d_load_balance_history_detail').select('i_load_balance')).resolves.toEqual([]);
|
||||
await expect(mockTransaction('log.t_log_card').select('i_log_name')).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
test('hasil sukses menyimpan saldo, riwayat, dan audit', async () => {
|
||||
await expect(update(input)).resolves.toMatchObject({ code: '00' });
|
||||
|
||||
await expect(mockTransaction('trx.t_d_load_balance').first('c_status', 'm_balance'))
|
||||
.resolves.toEqual({ c_status: 'A', m_balance: 70 });
|
||||
await expect(mockTransaction('trx.t_d_load_balance_history_detail').first('i_amount'))
|
||||
.resolves.toEqual({ i_amount: 20 });
|
||||
await expect(mockTransaction('log.t_log_card').first('i_log_name'))
|
||||
.resolves.toEqual({ i_log_name: 21 });
|
||||
});
|
||||
|
||||
test('gagal menulis audit pemulihan membatalkan pembaruan saldo dan reservasi', async () => {
|
||||
await mockTransaction.raw(`
|
||||
INSERT INTO trx.t_d_load_balance_history
|
||||
(i_load_balance, c_load_balance_no, d_load_balance, c_status, m_balance, i_topup_amount)
|
||||
VALUES (20, 'LBL1', '2026-11-25 00:30:00', 'I', 50, 20);
|
||||
INSERT INTO trx.t_d_load_balance_history_detail VALUES (20, 7, 'RBL1', 20);
|
||||
ALTER TABLE log.t_log_card ADD CHECK (i_log_name <> 21)
|
||||
`);
|
||||
|
||||
await expect(recover(
|
||||
['RBL1'], ['LBL1'], 'fixture-mid', 'fixture-tid', 'card-fixture', 70, '2', '123', 20, 'UID'
|
||||
)).resolves.toBe(false);
|
||||
|
||||
const { logger } = require('../helpers/winston.logger');
|
||||
expect(logger.error).toHaveBeenCalledWith(expect.stringContaining(
|
||||
'operation=update_reservations_and_balance sqlstate=23514'
|
||||
));
|
||||
await expect(mockTransaction('trx.t_d_load_balance').first('c_status')).resolves.toEqual({ c_status: 'I' });
|
||||
await expect(mockTransaction('trx.t_d_reservation_balance').first('c_status')).resolves.toEqual({ c_status: 'I' });
|
||||
await expect(mockTransaction('trx.t_d_load_balance_history').select('i_load_balance'))
|
||||
.resolves.toEqual([{ i_load_balance: 20 }]);
|
||||
await expect(mockTransaction('log.t_log_card').select('i_log_name')).resolves.toEqual([]);
|
||||
});
|
||||
|
||||
test('sesi PostgreSQL memakai tanggal Jakarta ketika UTC masih sehari sebelumnya', async () => {
|
||||
const { rows: [row] } = await mockTransaction.raw(`
|
||||
SELECT current_setting('TimeZone') AS zone,
|
||||
(TIMESTAMPTZ '2026-11-24 17:30:00+00')::date::text AS business_date
|
||||
`);
|
||||
|
||||
expect(row).toEqual({ zone: 'Asia/Jakarta', business_date: '2026-11-25' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
const { logCorrelation, logStatusCode, logErrorCode } = require('../helpers/log-fields');
|
||||
|
||||
test('membatasi korelasi ke format yang dipakai aplikasi', () => {
|
||||
expect(logCorrelation(123456789)).toBe('123456789');
|
||||
expect(logCorrelation('9af6e483-10b9-414d-9eb9-f113de42532b'))
|
||||
.toBe('9af6e483-10b9-414d-9eb9-f113de42532b');
|
||||
expect(logCorrelation('fixture\nextra')).toBe('unknown');
|
||||
expect(logCorrelation({ number: '123' })).toBe('unknown');
|
||||
});
|
||||
|
||||
test('mempertahankan kode berguna tanpa isi pesan error', () => {
|
||||
expect(logStatusCode('00')).toBe('00');
|
||||
expect(logStatusCode(404)).toBe('404');
|
||||
expect(logStatusCode('404 fixture-detail')).toBe('UNKNOWN');
|
||||
expect(logErrorCode({ code: '23514', message: 'fixture SQL parameters' })).toBe('23514');
|
||||
expect(logErrorCode({ code: 'ETIMEDOUT' })).toBe('ETIMEDOUT');
|
||||
expect(logErrorCode({ code: 'fixture-private', name: 'TypeError' })).toBe('TypeError');
|
||||
expect(logErrorCode('fixture message')).toBe('Error');
|
||||
});
|
||||
@@ -1,20 +0,0 @@
|
||||
const request = require("supertest");
|
||||
const app = require("../../server");
|
||||
require("dotenv").config();
|
||||
|
||||
let token = "";
|
||||
|
||||
beforeAll(async () => {
|
||||
const res = await request(app).post("/api/login").send({
|
||||
email: "C-ACCESS.ONLINETOPUP@KRL.CO.ID",
|
||||
password: "106C231o",
|
||||
});
|
||||
code = res.body.code;
|
||||
token = res.body.data.access_token;
|
||||
});
|
||||
|
||||
describe("TOKEN transaction is generate", () => {
|
||||
it("should test that get code 00 == 00", () => {
|
||||
expect(code).toEqual("00");
|
||||
});
|
||||
});
|
||||
@@ -6,6 +6,36 @@ const createAuditArchive = require('../helpers/audit-archive');
|
||||
const { createStdoutWriter, formatLog } = require('../helpers/stdout-log');
|
||||
const createRedisOperations = require('../helpers/redis-operations');
|
||||
|
||||
test('timestamp log mengikuti WIB dan mempertahankan waktu kejadian saat tanggal berganti', () => {
|
||||
const time = Date.parse('2026-11-24T17:30:00.123Z');
|
||||
const { timestamp } = JSON.parse(formatLog({ event: 'http_response' }, time));
|
||||
|
||||
expect(timestamp).toBe('2026-11-25T00:30:00.123+07:00');
|
||||
expect(Date.parse(timestamp)).toBe(time);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['5001', '31'],
|
||||
['400', '33'],
|
||||
['5003', '33'],
|
||||
['00', '32'],
|
||||
])('warna terminal untuk kode %s hanya muncul pada TTY', (statusCode, color) => {
|
||||
const line = formatLog({ event: 'http_response', http_status: 200, status_code: statusCode });
|
||||
const makeStream = (isTTY) => Object.assign(new EventEmitter(), {
|
||||
isTTY,
|
||||
writable: true,
|
||||
write: jest.fn(),
|
||||
});
|
||||
const terminal = makeStream(true);
|
||||
const pipe = makeStream(false);
|
||||
|
||||
createStdoutWriter(terminal, jest.fn(), { colors: true })(line);
|
||||
createStdoutWriter(pipe, jest.fn())(line);
|
||||
|
||||
expect(terminal.write).toHaveBeenCalledWith(`\x1b[${color}m${line}\x1b[0m\n`, expect.any(Function));
|
||||
expect(pipe.write).toHaveBeenCalledWith(`${line}\n`, expect.any(Function));
|
||||
});
|
||||
|
||||
test('stdout backpressure preserves every audit and a stale Loki URL does not trigger HTTP', () => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'topup-audit-'));
|
||||
const audit = createAuditArchive(directory);
|
||||
@@ -38,6 +68,8 @@ test('stdout backpressure preserves every audit and a stale Loki URL does not tr
|
||||
const [file] = fs.readdirSync(directory);
|
||||
const archived = fs.readFileSync(path.join(directory, file), 'utf8').trim().split('\n').map(JSON.parse);
|
||||
expect(archived.map(({ request_id }) => request_id)).toEqual(['first', 'slow-console', 'recovered']);
|
||||
expect(archived[0].timestamp).toBe(emitted[0].timestamp);
|
||||
expect(archived[0].timestamp).toMatch(/\+07:00$/);
|
||||
} finally {
|
||||
jest.dontMock('../helpers/audit-archive');
|
||||
jest.dontMock('../helpers/stdout-log');
|
||||
|
||||
@@ -3,25 +3,14 @@ const request = require('supertest');
|
||||
const responseTime = require('response-time');
|
||||
const knex = require('../../infrastructure/database/knex');
|
||||
const responseAudit = require('../helpers/response-audit');
|
||||
const { logger } = require('../helpers/getbodyrequest');
|
||||
const { correlation, response: responseTelemetry } = require('../middlewares/response-telemetry.middleware');
|
||||
const histograms = Object.values(require('../helpers/prometheusmetrics'));
|
||||
|
||||
jest.mock('../../infrastructure/database/knex', () => jest.fn());
|
||||
jest.mock('../helpers/response-audit', () => ({ record: jest.fn() }));
|
||||
jest.mock('winston-daily-rotate-file', () => {
|
||||
const winston = require('winston');
|
||||
const Transport = require('winston-transport');
|
||||
class MemoryTransport extends Transport {
|
||||
log(info, callback) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
winston.transports.DailyRotateFile = MemoryTransport;
|
||||
return MemoryTransport;
|
||||
});
|
||||
|
||||
const app = express();
|
||||
app.use(express.json(), responseTime(), logger.correlation, logger.request, logger.response);
|
||||
app.use(express.json(), responseTime(), correlation, responseTelemetry);
|
||||
app.post('/api/topup1', (req, res) => {
|
||||
req._startTime = Date.now() - req.body.duration;
|
||||
res.json({ code: '00', data: { trxID: req.body.trxID } });
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const model = require('../modules/paymentrecon/paymentrecon.model');
|
||||
const { paymentRecon, validate } = require('../modules/paymentrecon/paymentrecon.controller');
|
||||
|
||||
jest.mock('../middlewares/jwt.middleware', () => ({
|
||||
authenticateToken(req, res, next) {
|
||||
req.partner_id_token = '1';
|
||||
next();
|
||||
},
|
||||
}));
|
||||
jest.mock('../helpers/helper', () => ({ getUniqueCode: () => 'fixture', randomNumberInt: () => 0 }));
|
||||
jest.mock('../helpers/winston.logger', () => ({ logger: {
|
||||
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
|
||||
@@ -21,10 +26,7 @@ jest.mock('../modules/paymentrecon/paymentrecon.model', () => ({
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.post('/api/payment-recon', (req, res, next) => {
|
||||
req.partner_id_token = '1';
|
||||
next();
|
||||
}, validate('paymentRecon'), paymentRecon);
|
||||
app.use('/api', require('../routes/paymentrecon.routes'));
|
||||
const body = { date: '2026-11-23', reservation_number: 'RBL1', bank_ref: 'BANK1', amount: 1000 };
|
||||
|
||||
beforeEach(() => {
|
||||
@@ -35,6 +37,22 @@ beforeEach(() => {
|
||||
model.checkReservationNumberAndAmount.mockResolvedValue({ total_transaction: 1, total_amount: '1000' });
|
||||
});
|
||||
|
||||
test('Payment Recon berhasil menyimpan transaksi dan mengembalikan nomor rekonsiliasi', async () => {
|
||||
model.completePaymentRecon.mockResolvedValue(true);
|
||||
|
||||
const response = await request(app).post('/api/payment-recon').send(body);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({
|
||||
code: '00',
|
||||
data: { payment_recon_no: expect.stringMatching(/^RCTST\d{12}$/) },
|
||||
});
|
||||
expect(model.completePaymentRecon).toHaveBeenCalledWith(expect.objectContaining({
|
||||
paymentReconNumber: response.body.data.payment_recon_no,
|
||||
time: response.body.data.recon_date,
|
||||
}));
|
||||
});
|
||||
|
||||
test('the loser of a concurrent reconciliation returns the winner’s number and code 04', async () => {
|
||||
const winner = { c_payment_recon_no: 'RC-WINNER', d_payment_recon: '2026-11-23 10:00:00' };
|
||||
model.checkReservationNumberAndAmountAlreadyRecon
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
const request = require("supertest");
|
||||
const app = require("../../server");
|
||||
require("dotenv").config();
|
||||
|
||||
let token = process.env.TOKEN_TESTING;
|
||||
|
||||
describe("POST Payment Recon", () => {
|
||||
it("should create new post payment recon", async () => {
|
||||
const res = await request(app)
|
||||
.post("/api/payment-recon")
|
||||
.send({
|
||||
date: "2022-08-30",
|
||||
bank_ref: "BR220830",
|
||||
reservation_number: "RSVMP1401620220707002",
|
||||
amount: "10000",
|
||||
})
|
||||
.set("Authorization", `Bearer ${token}`);
|
||||
expect(res.statusCode).toBe(200);
|
||||
if (
|
||||
res.body.code != "00" &&
|
||||
res.body.code != "01" &&
|
||||
res.body.code != "02" &&
|
||||
res.body.code != "03" &&
|
||||
res.body.code != "04"
|
||||
) {
|
||||
expect(res.body.code).toContain(
|
||||
"response code must be : 00 | 01 | 02 | 03 | 04"
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,71 @@
|
||||
jest.mock('../helpers/helper', () => ({
|
||||
getUniqueCode: () => 'request-fixture',
|
||||
decryptText: jest.fn(),
|
||||
}));
|
||||
jest.mock('../helpers/winston.logger', () => ({
|
||||
logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() },
|
||||
}));
|
||||
jest.mock('../modules/reservebalance/reservebalance.model', () => ({}));
|
||||
jest.mock('../modules/pos/pos.model', () => ({
|
||||
getGlobalParameterData: jest.fn(),
|
||||
getCardReplacement: jest.fn(),
|
||||
getCardProduct: jest.fn(),
|
||||
}));
|
||||
|
||||
const helper = require('../helpers/helper');
|
||||
const posModel = require('../modules/pos/pos.model');
|
||||
const pos = require('../modules/pos/pos.controller');
|
||||
const reservation = require('../modules/reservebalance/reservebalance.controller');
|
||||
const { validateCardProduct, validateBIRegulation } = require('../modules/pos/card-validation.service');
|
||||
|
||||
function response() {
|
||||
return { status: jest.fn().mockReturnThis(), json: jest.fn() };
|
||||
}
|
||||
|
||||
beforeEach(() => jest.resetAllMocks());
|
||||
|
||||
test('data reservasi yang gagal didekripsi mengembalikan respons lama berkode 500', async () => {
|
||||
helper.decryptText.mockImplementation(() => { throw new Error('Invalid data'); });
|
||||
const res = response();
|
||||
|
||||
await reservation.decrpytRequest({ body: { reservation_data: 'fixture' } }, res);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledWith({ code: '500', message: 'decrypted failed.', data: {} });
|
||||
});
|
||||
|
||||
test('kartu yang sudah aktif ditolak sebagai kartu pengganti dengan kode 453', async () => {
|
||||
posModel.getGlobalParameterData.mockImplementation(async (name) => ({
|
||||
c_value: name === 'POS_VALIDATE_CARD_PRODUCT' ? 'A' : 'N',
|
||||
}));
|
||||
posModel.getCardProduct.mockResolvedValue({ c_status: 'A' });
|
||||
const res = response();
|
||||
|
||||
await pos.validateNewCardReplacement({ body: { card_number: 'fixture' } }, res);
|
||||
|
||||
expect(res.status).toHaveBeenCalledWith(200);
|
||||
expect(res.json).toHaveBeenCalledTimes(1);
|
||||
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
|
||||
code: '453',
|
||||
data: { status: false, perso_status: true, detail: {} },
|
||||
}));
|
||||
});
|
||||
|
||||
test('kegagalan validasi lingkungan mengakhiri alur sebelum memeriksa kartu', async () => {
|
||||
posModel.getGlobalParameterData.mockResolvedValue({});
|
||||
const res = response();
|
||||
|
||||
await pos.validateNewCardReplacement({ body: { card_number: 'fixture' } }, res);
|
||||
|
||||
expect(res.json).toHaveBeenCalledTimes(1);
|
||||
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({ code: '400' }));
|
||||
expect(posModel.getCardReplacement).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('parameter POS yang kosong dikembalikan sebagai penolakan terkontrol', async () => {
|
||||
posModel.getGlobalParameterData.mockResolvedValue({});
|
||||
|
||||
await expect(validateCardProduct('fixture', 'request-fixture')).resolves.toMatchObject({ code: '400' });
|
||||
await expect(validateBIRegulation('fixture', 100, 0, 'request-fixture'))
|
||||
.resolves.toMatchObject({ code: '400' });
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
const request = require('supertest');
|
||||
|
||||
jest.mock('../../server/routes', () => ({
|
||||
mountApiRoutes(app) {
|
||||
app.post('/api/fixture', (req, res) => res.json(req.body));
|
||||
},
|
||||
}));
|
||||
jest.mock('../middlewares/response-telemetry.middleware', () => ({
|
||||
correlation(req, res, next) { next(); },
|
||||
response(req, res, next) { next(); },
|
||||
}));
|
||||
|
||||
const app = require('../../server');
|
||||
|
||||
test('entry point menyajikan halaman utama, file publik, dan metrik', async () => {
|
||||
await request(app).get('/').expect(200, { message: 'Welcome to Topup Online Service.', data: {} });
|
||||
await request(app).get('/images/logo_portal_kmt.png').expect(200).expect('Content-Type', /image\/png/);
|
||||
await request(app).get('/metrics').expect(200).expect('Content-Type', /text\/plain/);
|
||||
});
|
||||
|
||||
test('entry point mempertahankan parse JSON, form, dan header CORS', async () => {
|
||||
await request(app).post('/api/fixture')
|
||||
.set('Origin', 'http://localhost:3000')
|
||||
.send({ code: '00' })
|
||||
.expect('Access-Control-Allow-Origin', 'http://localhost:3000')
|
||||
.expect('Access-Control-Expose-Headers', 'X-Request-Id,X-Response-Time')
|
||||
.expect(200, { code: '00' });
|
||||
await request(app).post('/api/fixture')
|
||||
.type('form').send({ code: '00' })
|
||||
.expect(200, { code: '00' });
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
const { execFileSync } = require('node:child_process');
|
||||
|
||||
test('jam bisnis Jakarta konsisten saat host diawali dengan zona UTC', () => {
|
||||
const script = `
|
||||
require('./infrastructure/transaction-time').configureTransactionClock();
|
||||
const moment = require('moment');
|
||||
const instant = new Date('2026-11-24T17:30:00.000Z');
|
||||
const transactionTime = moment(instant);
|
||||
process.stdout.write(JSON.stringify({
|
||||
dateTime: transactionTime.format('YYYY-MM-DD HH:mm:ss'),
|
||||
numberDate: transactionTime.format('YYMMDD'),
|
||||
utc: instant.toISOString(),
|
||||
}));
|
||||
`;
|
||||
const output = execFileSync(process.execPath, ['-e', script], {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, TZ: 'UTC' },
|
||||
});
|
||||
|
||||
expect(JSON.parse(output)).toEqual({
|
||||
dateTime: '2026-11-25 00:30:00',
|
||||
numberDate: '261125',
|
||||
utc: '2026-11-24T17:30:00.000Z',
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user