mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:46:28 +00:00
Clean up project structure and color interactive logs
This commit is contained in:
+13
-7
@@ -1,11 +1,17 @@
|
||||
# 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.
|
||||
- [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 };
|
||||
@@ -1,4 +1,5 @@
|
||||
const { Counter } = require('prom-client');
|
||||
const { colorTerminalLine } = require('./terminal-log-color');
|
||||
|
||||
const WIB_OFFSET_MS = 7 * 60 * 60 * 1000;
|
||||
|
||||
@@ -8,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; });
|
||||
|
||||
@@ -23,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 {
|
||||
|
||||
@@ -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 };
|
||||
@@ -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 };
|
||||
@@ -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;
|
||||
@@ -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;
|
||||
|
||||
@@ -14,6 +14,28 @@ test('timestamp log mengikuti WIB dan mempertahankan waktu kejadian saat tanggal
|
||||
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);
|
||||
|
||||
@@ -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 } });
|
||||
|
||||
@@ -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' });
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
# Cash-in Index Checklist
|
||||
|
||||
These indexes are suggested for the heavy cash-in read paths in `application/modules/cashin/cahsin.model.js`.
|
||||
These indexes are suggested for the heavy cash-in read paths in `application/modules/cashin/cashin.model.js`.
|
||||
|
||||
Apply them first in a staging environment and validate with `EXPLAIN (ANALYZE, BUFFERS)` before promoting to production.
|
||||
|
||||
|
||||
Generated
+1
-80
@@ -11,8 +11,6 @@
|
||||
"dependencies": {
|
||||
"axios": "^1.7.7",
|
||||
"bcrypt": "^5.1.1",
|
||||
"body-parser": "^1.19.0",
|
||||
"check-internet-connected": "^2.0.6",
|
||||
"cors": "^2.8.5",
|
||||
"crypto-js": "^4.1.1",
|
||||
"dotenv": "^8.2.0",
|
||||
@@ -22,17 +20,14 @@
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"knex": "^3.1.0",
|
||||
"moment": "^2.29.3",
|
||||
"node-cron": "^3.0.1",
|
||||
"pg": "^8.6.0",
|
||||
"pm2": "^6.0.13",
|
||||
"prom-client": "^14.2.0",
|
||||
"redis": "^4.6.5",
|
||||
"response-time": "^2.3.2",
|
||||
"simple-update-notifier": "^2.0.0",
|
||||
"sticky-session": "^0.1.0",
|
||||
"superagent": "^10.2.3",
|
||||
"winston": "^3.7.2",
|
||||
"winston-daily-rotate-file": "^4.7.1",
|
||||
"ws": "^8.5.0",
|
||||
"xml2js": "^0.6.2"
|
||||
},
|
||||
@@ -2889,12 +2884,6 @@
|
||||
"integrity": "sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/bluebird": {
|
||||
"version": "3.7.2",
|
||||
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.7.2.tgz",
|
||||
"integrity": "sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/bodec": {
|
||||
"version": "0.1.0",
|
||||
"resolved": "https://registry.npmjs.org/bodec/-/bodec-0.1.0.tgz",
|
||||
@@ -3126,18 +3115,6 @@
|
||||
"integrity": "sha512-syedaZ9cPe7r3hoQA9twWYKu5AIyCswN5+szkmPBe9ccdLrj4bYaCnLVPTLd2kgVRc7+zoX4tyPgRnFKCj5YjQ==",
|
||||
"license": "MIT/X11"
|
||||
},
|
||||
"node_modules/check-internet-connected": {
|
||||
"version": "2.0.6",
|
||||
"resolved": "https://registry.npmjs.org/check-internet-connected/-/check-internet-connected-2.0.6.tgz",
|
||||
"integrity": "sha512-ZoU3ovnutroET6nWLp7zt7Er03aLQc4VqMZEBEuWhU/uI8B1x8j3v3rFcufEugNXUxZ7SPF4eMCufJ3vY7Ha2A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bluebird": "^3.7.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/chokidar": {
|
||||
"version": "3.6.0",
|
||||
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
|
||||
@@ -4497,15 +4474,6 @@
|
||||
"flat-cache": "^6.1.23"
|
||||
}
|
||||
},
|
||||
"node_modules/file-stream-rotator": {
|
||||
"version": "0.6.1",
|
||||
"resolved": "https://registry.npmjs.org/file-stream-rotator/-/file-stream-rotator-0.6.1.tgz",
|
||||
"integrity": "sha512-u+dBid4PvZw17PmDeRcNOtCP9CCK/9lRN2w+r1xIS7yOL9JFrIBKTvrYsxT4P0pGtThYTn++QS5ChHaUov3+zQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"moment": "^2.29.1"
|
||||
}
|
||||
},
|
||||
"node_modules/fill-range": {
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
|
||||
@@ -7761,18 +7729,6 @@
|
||||
"integrity": "sha512-eh0GgfEkpnoWDq+VY8OyvYhFEzBk6jIYbRKdIlyTiAXIVJ8PyBaKb0rp7oDtoddbdoHWhq8wwr+XZ81F1rpNdA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/node-cron": {
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/node-cron/-/node-cron-3.0.3.tgz",
|
||||
"integrity": "sha512-dOal67//nohNgYWb+nWmg5dkFdIwDm8EpeGYMekPMrngV3637lqnX0lbUcCtgibHTz6SEz7DAIjKvKDFYCnO1A==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"uuid": "8.3.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/node-fetch": {
|
||||
"version": "2.7.0",
|
||||
"resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
|
||||
@@ -7920,15 +7876,6 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/object-hash": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/object-hash/-/object-hash-2.2.0.tgz",
|
||||
"integrity": "sha512-gScRMn0bS5fH+IuwyIFgnh9zBdo4DV+6GhygmWM9HyNJSgS0hScp1f5vjtm7oIIOiT9trXrShAkLFSc2IqKNgw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 6"
|
||||
}
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
@@ -9402,6 +9349,7 @@
|
||||
"version": "2.0.0",
|
||||
"resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz",
|
||||
"integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"semver": "^7.5.3"
|
||||
@@ -10070,15 +10018,6 @@
|
||||
"node": ">= 0.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/uuid": {
|
||||
"version": "8.3.2",
|
||||
"resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz",
|
||||
"integrity": "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg==",
|
||||
"license": "MIT",
|
||||
"bin": {
|
||||
"uuid": "dist/bin/uuid"
|
||||
}
|
||||
},
|
||||
"node_modules/v8-to-istanbul": {
|
||||
"version": "9.3.0",
|
||||
"resolved": "https://registry.npmjs.org/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz",
|
||||
@@ -10209,24 +10148,6 @@
|
||||
"node": ">= 12.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/winston-daily-rotate-file": {
|
||||
"version": "4.7.1",
|
||||
"resolved": "https://registry.npmjs.org/winston-daily-rotate-file/-/winston-daily-rotate-file-4.7.1.tgz",
|
||||
"integrity": "sha512-7LGPiYGBPNyGHLn9z33i96zx/bd71pjBn9tqQzO3I4Tayv94WPmBNwKC7CO1wPHdP9uvu+Md/1nr6VSH9h0iaA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"file-stream-rotator": "^0.6.1",
|
||||
"object-hash": "^2.0.1",
|
||||
"triple-beam": "^1.3.0",
|
||||
"winston-transport": "^4.4.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"winston": "^3"
|
||||
}
|
||||
},
|
||||
"node_modules/winston-transport": {
|
||||
"version": "4.9.0",
|
||||
"resolved": "https://registry.npmjs.org/winston-transport/-/winston-transport-4.9.0.tgz",
|
||||
|
||||
@@ -25,8 +25,6 @@
|
||||
"dependencies": {
|
||||
"axios": "^1.7.7",
|
||||
"bcrypt": "^5.1.1",
|
||||
"body-parser": "^1.19.0",
|
||||
"check-internet-connected": "^2.0.6",
|
||||
"cors": "^2.8.5",
|
||||
"crypto-js": "^4.1.1",
|
||||
"dotenv": "^8.2.0",
|
||||
@@ -36,17 +34,14 @@
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"knex": "^3.1.0",
|
||||
"moment": "^2.29.3",
|
||||
"node-cron": "^3.0.1",
|
||||
"pg": "^8.6.0",
|
||||
"pm2": "^6.0.13",
|
||||
"prom-client": "^14.2.0",
|
||||
"redis": "^4.6.5",
|
||||
"response-time": "^2.3.2",
|
||||
"simple-update-notifier": "^2.0.0",
|
||||
"sticky-session": "^0.1.0",
|
||||
"superagent": "^10.2.3",
|
||||
"winston": "^3.7.2",
|
||||
"winston-daily-rotate-file": "^4.7.1",
|
||||
"ws": "^8.5.0",
|
||||
"xml2js": "^0.6.2"
|
||||
},
|
||||
|
||||
+23
-240
@@ -1,252 +1,35 @@
|
||||
require('../infrastructure/transaction-time').configureTransactionClock();
|
||||
const express = require('express');
|
||||
const bodyParser = require('body-parser');
|
||||
const cors = require('cors');
|
||||
const helper = require('../application/helpers/helper');
|
||||
const winston = require('../application/helpers/winston.logger');
|
||||
const authRoute = require('../application/routes/auth.routes');
|
||||
const dongleOrderRoute = require('../application/routes/dongleorder.routes');
|
||||
const reservationRoute = require('../application/routes/reservebalance.routes');
|
||||
const loadBalanceRoute = require('../application/routes/loadbalance.routes');
|
||||
const hsmRoute = require('../application/routes/hsm.routes');
|
||||
const historyRoute = require('../application/routes/history.routes');
|
||||
const paymentReconRoute = require('../application/routes/paymentrecon.routes');
|
||||
const invoiceRoute = require('../application/routes/invoiceonline.routes');
|
||||
const cashinRoute = require('../application/routes/cahsin.routes');
|
||||
const posRoute = require('../application/routes/pos.routes');
|
||||
const pooling = require('../application/routes/pooling.routes');
|
||||
const refundkmtRoute = require('../application/routes/refundkmt.routes');
|
||||
const cron = require('node-cron');
|
||||
const moment = require('moment');
|
||||
require('dotenv').config();
|
||||
moment.locale('id');
|
||||
require('../infrastructure/transaction-time').configureTransactionClock();
|
||||
|
||||
const path = require('node:path');
|
||||
const express = require('express');
|
||||
const cors = require('cors');
|
||||
const responseTime = require('response-time');
|
||||
const { logger } = require('../application/helpers/getbodyrequest');
|
||||
const { auditMetrics } = require('../application/helpers/response-audit');
|
||||
const { stdoutMetrics } = require('../application/helpers/stdout-log');
|
||||
const { poolMetrics } = require('../infrastructure/database/pool-metrics');
|
||||
const client = require('prom-client');
|
||||
const register = new client.Registry();
|
||||
const {
|
||||
topuponline_metrics,
|
||||
topuponline_metrics_response_time,
|
||||
topuponline_metrics_load_balance,
|
||||
} = require('../application/helpers/prometheusmetrics');
|
||||
const moment = require('moment');
|
||||
const { correlation, response } = require('../application/middlewares/response-telemetry.middleware');
|
||||
const { mountMetrics } = require('./metrics');
|
||||
const { mountApiRoutes } = require('./routes');
|
||||
|
||||
moment.locale('id');
|
||||
|
||||
const app = express();
|
||||
const port = process.env.PORT || '3000';
|
||||
|
||||
let promApp = process.env.PROM_APP || 'topuponline';
|
||||
register.setDefaultLabels({ app: promApp });
|
||||
client.collectDefaultMetrics({ register });
|
||||
register.registerMetric(topuponline_metrics);
|
||||
register.registerMetric(topuponline_metrics_response_time);
|
||||
register.registerMetric(topuponline_metrics_load_balance);
|
||||
for (const metric of [...auditMetrics, ...stdoutMetrics, ...poolMetrics]) register.registerMetric(metric);
|
||||
|
||||
app.get('/metrics', (req, res) => {
|
||||
res.setHeader('Content-Type', register.contentType);
|
||||
register.metrics().then((data) => res.send(data));
|
||||
});
|
||||
|
||||
var corsOptions = {
|
||||
origin: [
|
||||
'http://localhost:' + process.env.PORT || 3000,
|
||||
'http://localhost:3000',
|
||||
],
|
||||
mountMetrics(app);
|
||||
app.use(cors({
|
||||
origin: ['http://localhost:' + port, 'http://localhost:3000'],
|
||||
exposedHeaders: ['X-Request-Id', 'X-Response-Time'],
|
||||
};
|
||||
|
||||
// app.use(cors(corsOptions));
|
||||
app.use(cors(corsOptions));
|
||||
|
||||
// add static file
|
||||
app.use(express.static('public'));
|
||||
|
||||
// parse requests of content-type - application/json
|
||||
app.use(bodyParser.json());
|
||||
|
||||
// parse requests of content-type - application/x-www-form-urlencoded
|
||||
app.use(bodyParser.urlencoded({ extended: true }));
|
||||
|
||||
}));
|
||||
app.use(express.static(path.join(__dirname, '..', 'public')));
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(responseTime());
|
||||
|
||||
// ============================== ROUTES API ==============================
|
||||
app.get('/', async (req, res) => {
|
||||
res.json({
|
||||
message: 'Welcome to Topup Online Service.',
|
||||
data: {},
|
||||
});
|
||||
app.get('/', (req, res) => {
|
||||
res.json({ message: 'Welcome to Topup Online Service.', data: {} });
|
||||
});
|
||||
|
||||
app.use(logger.correlation);
|
||||
app.use(logger.response);
|
||||
|
||||
app.use('/api/', authRoute);
|
||||
app.use('/api/', dongleOrderRoute);
|
||||
app.use('/api/', historyRoute);
|
||||
app.use('/api/', hsmRoute);
|
||||
app.use('/api/', loadBalanceRoute);
|
||||
app.use('/api/', paymentReconRoute);
|
||||
app.use('/api/', reservationRoute);
|
||||
app.use('/api/', invoiceRoute);
|
||||
app.use('/api/', cashinRoute);
|
||||
app.use('/api/', posRoute);
|
||||
app.use('/api/', pooling);
|
||||
app.use('/api/', refundkmtRoute);
|
||||
|
||||
// ============================== SAP SCHEDULLER =============================
|
||||
|
||||
// if (process.env.NODE_ENV.toUpperCase() == "PRODUCTION") {
|
||||
|
||||
// ===================================================
|
||||
// SCHEDULER FOR GENERATE INVOICE
|
||||
// ===================================================
|
||||
|
||||
// const {
|
||||
// _generateInvoice,
|
||||
// _postingInvoice,
|
||||
// } = require('../application/modules/invoiceonline/invoice.controller');
|
||||
|
||||
// GENERATE + POSTING INVOICE
|
||||
// cron.schedule('0 1 * * *', async () => {
|
||||
// try {
|
||||
// // let ivoiceDate = moment().add(1, 'days').format("YYYY-MM-DD");
|
||||
// let ivoiceDate = moment().format('YYYY-MM-DD');
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.debug(
|
||||
// `STARTING SCHEDULER-FB70 GENERATE INVOICE ${ivoiceDate} `
|
||||
// );
|
||||
// const generate = await _generateInvoice(ivoiceDate, uniqueCode, false);
|
||||
// winston.logger.debug(
|
||||
// `END SCHEDULER-FB70 GENERATE INVOICE ${ivoiceDate} : ${JSON.stringify(
|
||||
// generate
|
||||
// )}`
|
||||
// );
|
||||
// const reGenerate = await _generateInvoice(ivoiceDate, uniqueCode, true);
|
||||
// winston.logger.debug(
|
||||
// `END SCHEDULER-FB70 RE-GENERATE INVOICE THAT HAVE BEEN DELETED ${ivoiceDate} : ${JSON.stringify(
|
||||
// generate
|
||||
// )}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
// RE-TRY POSTING
|
||||
// cron.schedule('0 7 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.debug(`STARTING SCHEDULER-FB70 RE-TRY POSTING INVOICE`);
|
||||
// const posting = await _postingInvoice(uniqueCode);
|
||||
// winston.logger.debug(
|
||||
// `END SCHEDULER-FB70 RE-TRY POSTING INVOICE : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
// cron.schedule('0 12 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.debug(`STARTING SCHEDULER-FB70 RE-TRY POSTING INVOICE`);
|
||||
// const posting = await _postingInvoice(uniqueCode);
|
||||
// winston.logger.debug(
|
||||
// `END SCHEDULER-FB70 RE-TRY POSTING INVOICE : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
// cron.schedule('0 17 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.debug(`STARTING SCHEDULER-FB70 RE-TRY POSTING INVOICE`);
|
||||
// const posting = await _postingInvoice(uniqueCode);
|
||||
// winston.logger.debug(
|
||||
// `END SCHEDULER-FB70 RE-TRY POSTING INVOICE : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
// ===================================================
|
||||
// SCHEDULER FOR GENERATE INVOICE
|
||||
// ===================================================
|
||||
// cash in
|
||||
// const {
|
||||
// _generateCashIn,
|
||||
// } = require('../application/modules/cashin/cahsin.controller');
|
||||
|
||||
// cron.schedule('30 7 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.info(
|
||||
// `STARTING SCHEDULER-FB70 GENERATE CASH IN ${uniqueCode}`
|
||||
// );
|
||||
// const posting = await _generateCashIn(uniqueCode);
|
||||
// winston.logger.info(
|
||||
// `END SCHEDULER-FB70 GENERATE CASH IN : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 SCHEDULER-FB70 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
// cron.schedule('30 12 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.info(
|
||||
// `STARTING SCHEDULER-FB70 GENERATE CASH IN ${uniqueCode}`
|
||||
// );
|
||||
// const posting = await _generateCashIn(uniqueCode);
|
||||
// winston.logger.info(
|
||||
// `END SCHEDULER-FB70 GENERATE CASH IN : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 SCHEDULER-FB70 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
// cron.schedule('30 17 * * *', async () => {
|
||||
// try {
|
||||
// let uniqueCode = helper.getUniqueCode();
|
||||
// winston.logger.info(
|
||||
// `STARTING SCHEDULER-FB70 GENERATE CASH IN ${uniqueCode}`
|
||||
// );
|
||||
// const posting = await _generateCashIn(uniqueCode);
|
||||
// winston.logger.info(
|
||||
// `END SCHEDULER-FB70 GENERATE CASH IN : ${JSON.stringify(posting)}`
|
||||
// );
|
||||
// } catch (error) {
|
||||
// // create log
|
||||
// winston.logger.error(
|
||||
// `500 SCHEDULER-FB70 internal server error - backend server | ${error.message}`
|
||||
// );
|
||||
// }
|
||||
// });
|
||||
|
||||
// }
|
||||
app.use(correlation, response);
|
||||
mountApiRoutes(app);
|
||||
|
||||
module.exports = app;
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
const client = require('prom-client');
|
||||
const { auditMetrics } = require('../application/helpers/response-audit');
|
||||
const { stdoutMetrics } = require('../application/helpers/stdout-log');
|
||||
const { poolMetrics } = require('../infrastructure/database/pool-metrics');
|
||||
const { logger } = require('../application/helpers/winston.logger');
|
||||
const { logErrorCode } = require('../application/helpers/log-fields');
|
||||
const transactionMetrics = require('../application/helpers/prometheusmetrics');
|
||||
|
||||
function mountMetrics(app) {
|
||||
const registry = new client.Registry();
|
||||
registry.setDefaultLabels({ app: process.env.PROM_APP || 'topuponline' });
|
||||
client.collectDefaultMetrics({ register: registry });
|
||||
|
||||
for (const metric of [...Object.values(transactionMetrics), ...auditMetrics, ...stdoutMetrics, ...poolMetrics]) {
|
||||
registry.registerMetric(metric);
|
||||
}
|
||||
|
||||
app.get('/metrics', async (req, res) => {
|
||||
try {
|
||||
const metrics = await registry.metrics();
|
||||
res.setHeader('Content-Type', registry.contentType);
|
||||
res.send(metrics);
|
||||
} catch (error) {
|
||||
logger.error('Metrics collection failed | error_code=' + logErrorCode(error));
|
||||
res.status(500).type('text').send('Metrics collection failed');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { mountMetrics };
|
||||
@@ -0,0 +1,29 @@
|
||||
const authRoute = require('../application/routes/auth.routes');
|
||||
const dongleOrderRoute = require('../application/routes/dongleorder.routes');
|
||||
const reservationRoute = require('../application/routes/reservebalance.routes');
|
||||
const loadBalanceRoute = require('../application/routes/loadbalance.routes');
|
||||
const hsmRoute = require('../application/routes/hsm.routes');
|
||||
const historyRoute = require('../application/routes/history.routes');
|
||||
const paymentReconRoute = require('../application/routes/paymentrecon.routes');
|
||||
const invoiceRoute = require('../application/routes/invoiceonline.routes');
|
||||
const cashinRoute = require('../application/routes/cashin.routes');
|
||||
const posRoute = require('../application/routes/pos.routes');
|
||||
const pooling = require('../application/routes/pooling.routes');
|
||||
const refundkmtRoute = require('../application/routes/refundkmt.routes');
|
||||
|
||||
function mountApiRoutes(app) {
|
||||
app.use('/api/', authRoute);
|
||||
app.use('/api/', dongleOrderRoute);
|
||||
app.use('/api/', historyRoute);
|
||||
app.use('/api/', hsmRoute);
|
||||
app.use('/api/', loadBalanceRoute);
|
||||
app.use('/api/', paymentReconRoute);
|
||||
app.use('/api/', reservationRoute);
|
||||
app.use('/api/', invoiceRoute);
|
||||
app.use('/api/', cashinRoute);
|
||||
app.use('/api/', posRoute);
|
||||
app.use('/api/', pooling);
|
||||
app.use('/api/', refundkmtRoute);
|
||||
}
|
||||
|
||||
module.exports = { mountApiRoutes };
|
||||
Reference in New Issue
Block a user