Compare commits

..

169 Commits

Author SHA1 Message Date
WildanFahri a723626209 remove card category code from validateReplacement response 2026-11-26 10:35:40 +07:00
Mohamad Ihsan 3792b455e8 Limit PostgreSQL pools and cluster workers 2026-11-23 16:34:39 +07:00
WildanFahri e496e34fae add card category details to validateReplacement response 2026-11-16 17:30:32 +07:00
teddys48 3f9511157f update loki without label 2026-09-14 14:10:53 +07:00
teddys48 be59fbb9e2 update loki without label 2026-09-14 09:20:33 +07:00
Mohamad Ihsan 375d69c955 rollback store procedure generate invoice 2026-05-08 16:08:05 +07:00
Mohamad Ihsan 7890aed029 enhance generate invoice 2026-05-08 15:10:51 +07:00
Mohamad Ihsan 8152326743 rollback 2026-05-08 14:43:27 +07:00
Mohamad Ihsan 30d8e70da2 adjust query knex to native query 2026-05-08 14:40:19 +07:00
Mohamad Ihsan 9a4d741c05 bug fix generate invoice online topup 2026-05-08 14:09:03 +07:00
Mohamad Ihsan 18787a3605 enhancement generate and posting invoice online topup 2026-05-08 13:55:30 +07:00
Mohamad Ihsan 69fe9b97d8 bug fix result of generate invoice online topup 2026-05-08 12:35:07 +07:00
Mohamad Ihsan 3027dd30b3 skip the process if invoice amount not equal total transaction 2026-05-01 20:09:04 +07:00
Mohamad Ihsan 9feed0d542 add info error 2026-05-01 19:15:32 +07:00
Mohamad Ihsan b556a40dba rollback get partner recon 2026-05-01 19:06:55 +07:00
Mohamad Ihsan e1af54e851 bug fixed get partner recon 2026-05-01 18:02:59 +07:00
Mohamad Ihsan 23fadc4cb0 backup old function 2026-04-27 19:21:43 +07:00
Mohamad Ihsan fefa11c544 enhance query get data from posting et 2026-04-27 18:55:24 +07:00
Mohamad Ihsan ce8239ca38 downgrade bcrypt 2026-04-26 21:14:09 +07:00
Mohamad Ihsan c6f397d352 bug fix helper 2026-04-26 20:59:11 +07:00
WildanFahri 81addd40e8 update funtion add helper scheduler 2026-04-26 18:09:30 +07:00
WildanFahri fef18ff448 new funtion helper for scheduler 2026-04-26 16:09:29 +07:00
Mohamad Ihsan d84bc6941e enhancement slow query 2026-04-25 22:19:36 +07:00
Mohamad Ihsan 676553409b adding description 2026-02-04 12:22:22 +07:00
Mohamad Ihsan 72a94891ed coding enhancement 2026-02-04 12:17:24 +07:00
Mohamad Ihsan 84be7587a8 optimize query and add indexing 2026-02-04 11:48:56 +07:00
Mohamad Ihsan 8080b89c46 modify query getTopUpCashlessInternal and add indexing 2026-02-04 11:27:29 +07:00
Mohamad Ihsan 6dbd9b6246 modify query generate cash in sales and add indexing 2026-02-01 11:43:23 +07:00
Mohamad Ihsan 5bafb81d8d bugs fixed topup station cashless 2026-01-12 12:54:50 +07:00
Mohamad Ihsan 1dd7860c0b enhancement for cash in sales station 2026-01-08 19:58:57 +07:00
Mohamad Ihsan 1cf06d1fdd bugs fixed query 2025-12-16 17:29:47 +07:00
Mohamad Ihsan be2cedc869 bug fixed completing data sales 2025-12-16 16:47:36 +07:00
Mohamad Ihsan f5f75381ca adding version and description 2025-10-30 21:08:19 +07:00
Mohamad Ihsan 5cbdccca11 update packages 2025-10-30 21:07:49 +07:00
ihsan fd386788f8 remove pengkondisian 2025-08-28 12:54:08 +07:00
ihsan 6ddf225485 pengkondisian kebutuhan uji coba posting posting sales 2025-08-28 10:42:48 +07:00
ihsan 1645aa54aa bug fixed last balance 2025-08-26 19:00:01 +07:00
ihsan 797bf97bf8 add version 2025-08-26 18:25:06 +07:00
ihsan a7f5c8c8e0 bug fixed 2025-08-26 18:20:52 +07:00
ihsan d2d44f3ba9 add check balance to CTS 2025-08-26 18:15:45 +07:00
ihsan 4dccbf20f5 change url cts 2025-08-26 17:24:02 +07:00
ihsan b888951ee3 remove bearer 2025-08-26 17:14:34 +07:00
ihsan 87dedd241a change url cts from env 2025-08-26 17:11:49 +07:00
ihsan d4f56aacd8 update query pengecekkan card theme 2025-08-25 17:54:22 +07:00
ihsan fec5209c83 update bugs 2025-07-04 10:57:33 +07:00
ihsan 93b6bd94ca add log 2025-07-04 10:47:35 +07:00
ihsan 39ac9e0e2d add log 2025-07-04 10:46:13 +07:00
ihsan 5037e022fd bug fixed generate cash-in untuk transaksi topup cashless internal 2025-07-03 11:52:56 +07:00
ihsan cbb1d353a3 bug fixed field 2025-06-30 21:38:43 +07:00
ihsan f73accc275 Merge branch 'develop_v1.6.1' of https://github.com/mohamadihsan/topuponline into develop 2025-06-30 17:52:54 +07:00
ihsan d7c62eda3f add new service generate cash in topup cashless internal 2025-06-30 17:52:22 +07:00
WildanFahri a4b089ac85 Merge branch 'develop' of https://github.com/mohamadihsan/topuponline into develop 2025-06-30 14:41:16 +07:00
WildanFahri 3bf01d9059 add new endpoint for replacement validate new card 2025-06-30 14:41:10 +07:00
ihsan 8e54ebb704 bug fixed variable in query 2025-06-30 13:26:13 +07:00
ihsan 48fb780252 add new service completing data v2 2025-06-25 19:52:47 +07:00
ihsan 382ccaab58 add debugging 2025-06-25 18:39:12 +07:00
ihsan 41444e037c bug fixed 2025-06-25 18:34:36 +07:00
ihsan c49e4b3526 update bug code 2025-06-25 18:25:55 +07:00
ihsan d99882b8b9 update 2025-06-25 17:54:24 +07:00
ihsan 45091038fe update knex poo config untuk development 2025-06-25 17:53:04 +07:00
ihsan 7c6e08a5b5 update log 2025-06-25 17:49:52 +07:00
ihsan 6e7d727b40 update pool sesuai rekomendasi 2025-06-25 17:33:07 +07:00
ihsan 3bb2748387 bug fixed 2025-06-25 17:24:13 +07:00
ihsan 6fea76b721 bug fixed reservation success jika terjadi how many client 2025-06-25 17:10:17 +07:00
ihsan 934e962dba Merge branch 'develop_v1.6.1' of https://github.com/mohamadihsan/topuponline into develop 2025-06-25 16:59:16 +07:00
ihsan 3ccac7d220 bug fixed 2025-06-25 16:58:38 +07:00
WildanFahri cede2396b7 update get cts is_warranty 2025-06-17 17:58:29 +07:00
WildanFahri 9c06ec992e update getLastBalanceCTS 2025-06-17 17:42:58 +07:00
ihsan 419700d6c5 bugs fixed ppn value 2025-06-13 20:13:33 +07:00
ihsan 6af2637bca update bugs 2025-06-13 20:00:58 +07:00
ihsan 8bb705f973 update query lengkapi data sales internal 2025-06-13 18:47:42 +07:00
ihsan 6755824ad0 update service completing data dengan menambahkan ppn value dari globala parameter 2025-06-13 16:23:25 +07:00
ihsan d93e3549ea add new service completing data sales internal 2025-06-13 14:26:45 +07:00
ihsan af697bd24d add generate cash in sales internal 2025-06-05 19:04:50 +07:00
WildanFahri c792a5ef15 update validate replacement 2025-05-27 15:14:40 +07:00
WildanFahri 282cc6372a update 2025-05-27 14:54:44 +07:00
WildanFahri aea6577e38 update valid_date 2025-05-27 14:37:10 +07:00
WildanFahri 6ae2de5010 update 2025-05-26 12:12:05 +07:00
WildanFahri d7c3ad199a update response code pos cms 2025-05-23 14:21:01 +07:00
WildanFahri 3808dafda7 update response code pos cms 2025-05-23 14:12:07 +07:00
WildanFahri 14ea651b28 update response code pos cms 2025-05-16 14:30:20 +07:00
WildanFahri 4079caa059 update response code pos cms 2025-05-16 13:38:30 +07:00
WildanFahri 351a81a069 update pos cms 2025-05-15 15:01:20 +07:00
ihsan 35aad851ba bug fix 2025-05-06 17:27:20 +07:00
ihsan e25797e091 add logger 2025-05-06 17:01:54 +07:00
ihsan ac1c3c969b Merge branch 'develop' of https://github.com/mohamadihsan/topuponline into develop 2025-05-06 12:15:57 +07:00
ihsan 0e256ae481 remove pengecekkan last balance dari card history server 2025-05-06 12:15:49 +07:00
WildanFahri 2179a67b41 update pos cms - handle status replacement 2025-05-06 10:47:58 +07:00
WildanFahri fd3741e2ee update pos improvement temp 2025-05-06 09:49:40 +07:00
WildanFahri 2eb91dc105 debuging hardcode redeem validate 2025-05-05 21:29:18 +07:00
WildanFahri a257d50872 debuging 2025-05-05 21:26:50 +07:00
WildanFahri fdebd4dbe9 debuging 2025-05-05 21:24:07 +07:00
WildanFahri 745d186b3f debuging redeem validate 2025-05-05 21:22:52 +07:00
WildanFahri 0145ce5703 debuging redeem validate 2025-05-05 21:11:43 +07:00
WildanFahri a45acf1488 update redeem validate 2025-05-05 21:06:38 +07:00
WildanFahri bbc26c5964 update redeem validate 2025-05-05 20:48:59 +07:00
WildanFahri 7058143c4e update version 2025-04-25 14:23:15 +07:00
WildanFahri 5af2cc37d0 update merge conflict 2025-04-25 11:27:34 +07:00
WildanFahri 75acdc4195 Merge branch 'develop_v1.6.1' of https://github.com/mohamadihsan/topuponline into develop 2025-04-24 15:14:01 +07:00
ihsan a08cedf7e8 update 2025-04-24 14:55:51 +07:00
WildanFahri a16a0172a4 update pos improvement (CMS) 2025-04-23 11:33:10 +07:00
ihsan 9af6f4f823 bug fixed 2025-03-26 15:17:56 +07:00
ihsan 5259fd89ef chnage version 2025-03-26 05:24:29 +07:00
ihsan 0e35368e22 handling max flag 255 2025-03-24 21:26:59 +07:00
ihsan 0fdc901193 change logic 2025-03-24 16:44:02 +07:00
ihsan c3a458313e bug fixed flag 0 auto clear 2025-03-24 09:24:51 +07:00
ihsan 8ed7e738ab bug fixed log 2025-03-21 13:59:40 +07:00
ihsan 11b2ff8721 remove debug log 2025-03-21 13:56:21 +07:00
ihsan 851f1b14f6 update 2025-03-21 13:51:11 +07:00
ihsan 67c33c8e1f add debug log 2025-03-21 13:48:07 +07:00
ihsan ad8951c567 update 2025-03-21 11:19:52 +07:00
ihsan 5da07d9330 bug fixed 2025-03-21 11:14:12 +07:00
ihsan a680bc235d bug fixed 2025-03-21 11:09:46 +07:00
ihsan 269ae0088d add log debug 2025-03-21 11:03:36 +07:00
ihsan fe6fe9e72e bug fixed 2025-03-21 10:46:00 +07:00
ihsan 060c9d0b0b bug fixed variable 2025-03-21 10:38:34 +07:00
ihsan 7eff55e7f3 bug fixed max flag 255 2025-03-21 10:27:04 +07:00
ihsan 810d432374 bugs fixed 2025-03-21 10:13:49 +07:00
ihsan 687521146e Merge branch 'develop' of https://github.com/mohamadihsan/topuponline into develop 2025-03-21 10:09:42 +07:00
ihsan e82a09187c update query load balance if found flag has been 255 2025-03-21 10:09:36 +07:00
WildanFahri 3a8e2976f0 bug fixing 2025-03-10 15:07:40 +07:00
WildanFahri 530b5eed7e bug fixed 2025-03-05 13:48:55 +07:00
WildanFahri e9e9bbf4c8 bug fixing 2025-03-05 13:34:47 +07:00
WildanFahri 29c8f60135 bug fixing 2025-03-05 12:44:54 +07:00
WildanFahri cc497f606b bug fixing 2025-03-05 12:35:42 +07:00
WildanFahri c17e56731f bug fixing 2025-03-05 12:10:24 +07:00
lutfi f5574250d7 pos, add is_warranty card replacement validate 2025-03-04 16:43:17 +07:00
ihsan 3a85e63c01 update 2025-03-04 12:14:20 +07:00
ihsan 301696661d Merge branch 'develop' of https://github.com/mohamadihsan/topuponline into develop_v1.5.7 2025-03-03 13:59:31 +07:00
ihsan 9fa469fc67 change file rotate log time 2025-03-03 13:57:55 +07:00
lutfi 02fa5cb909 update 2025-01-24 18:12:26 +07:00
lutfi 3dfd2a50d4 update 2025-01-24 17:56:56 +07:00
ihsan d51325cd81 update version info 2025-01-16 15:13:31 +07:00
ihsan 99ebab8591 bug fixed autocomplete transaction 2025-01-16 15:12:30 +07:00
ihsan 92b72dbe7a update log debug 2025-01-16 13:05:13 +07:00
WildanFahri d2e1ff2274 Merge branch 'wildan' of https://github.com/mohamadihsan/topuponline into develop_v1.5.5 2025-01-15 11:43:31 +07:00
WildanFahri 5c67284a51 update logging updateReservationAndLoadingBalance 2025-01-15 11:40:32 +07:00
ihsan b4d700e27d check log 2025-01-15 11:39:28 +07:00
ihsan d18b91edda update 2025-01-15 11:27:47 +07:00
WildanFahri 3b97844c64 Merge branch 'wildan' of https://github.com/mohamadihsan/topuponline into develop_v1.5.5 2025-01-14 19:58:19 +07:00
WildanFahri 1ce4424494 check log insert t_d_load_balance_history 2025-01-14 19:57:37 +07:00
ihsan 6c5e472c4b bug fixed 2025-01-14 19:46:02 +07:00
ihsan 57d7f260d0 add log 2025-01-14 19:25:21 +07:00
ihsan 2834265206 update 2025-01-13 19:34:34 +07:00
ihsan 40ddf02c51 update 2025-01-13 19:29:10 +07:00
WildanFahri ba20dce4d1 add log updateReservationAndLoadingBalance 2025-01-13 19:23:33 +07:00
WildanFahri aec06cb481 add log updateReservationAndLoadingBalance 2025-01-13 18:05:27 +07:00
WildanFahri 7434464106 update 2025-01-07 16:39:51 +07:00
ihsan 01d95ae783 bug fixed 2025-01-07 07:16:06 +07:00
ihsan d690cb2c0b update 2025-01-07 06:43:29 +07:00
ihsan 88f82281dc bug fixed 2025-01-06 17:33:25 +07:00
ihsan 2e5d76d97d bug fixed 2025-01-06 17:27:25 +07:00
ihsan fc9c1a4b73 add description new version 2025-01-06 17:04:24 +07:00
ihsan 7d4ff6c8b3 update version 2025-01-06 17:03:17 +07:00
WildanFahri 8bda43d2b2 update topup6 2025-01-06 16:54:11 +07:00
lutfi 36139073d4 Merge branch 'develop_v1.5.4' of https://github.com/mohamadihsan/topuponline 2025-01-01 14:57:00 +07:00
lutfi 3c8fc4d81d update cash in 2025-01-01 14:52:36 +07:00
ihsan 22ce0b611a add version 2024-12-25 23:19:23 +07:00
ihsan 785e1f2542 add version 2024-12-25 23:18:14 +07:00
ihsan a6c6146933 update 2024-11-05 21:05:25 +07:00
lutfi 0113e6dbb1 update d_disburse 2024-10-25 05:39:27 +07:00
lutfi 8d2f4bcda2 update 2024-10-17 16:12:12 +07:00
lutfi 9aa3428620 update 2024-10-17 15:37:25 +07:00
lutfi e8c73abf2e update 2024-10-17 14:39:05 +07:00
lutfi 6275d8cf86 update 2024-10-17 14:32:46 +07:00
lutfi 8af96b9a5f update 2024-10-17 14:30:20 +07:00
lutfi d9f3516d56 update 2024-10-17 14:29:11 +07:00
lutfi b7dec2613f Merge branch 'develop' of https://github.com/mohamadihsan/topuponline into develop 2024-10-17 14:06:07 +07:00
lutfi d540308d2d update 2024-10-17 12:14:47 +07:00
31 changed files with 7176 additions and 9715 deletions
+35
View File
@@ -6,3 +6,38 @@
# debugging log contains log all validation checks step by step, request data from client, error log, and response data to client # 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 # online topup log contains request data from client, error log, and response data to client
# error log contains only error system or error service # error log contains only error system or error service
## Kapasitas koneksi PostgreSQL
Pengaturan pool utama dan pool tambahan ada di `knexfile.js`.
Titik awal untuk satu replika dengan dua worker dan kedua pool pada server
PostgreSQL yang sama adalah maksimal 20 koneksi aplikasi.
```dotenv
DB_POOL_MAX=8
DB_POOLING_POOL_MAX=2
DB_POOL_ACQUIRE_TIMEOUT_MS=5000
CLUSTER_WORKERS=2
```
Kedua pool memakai minimum 0 dan melepas koneksi yang idle setelah sekitar 30
detik. Timeout akuisisi membatasi waktu tunggu mendapatkan koneksi, dalam
milidetik. `CLUSTER_WORKERS` berlaku untuk cluster Node dan sticky session.
Jika tidak diisi, batas bawaan adalah dua worker atau jumlah CPU yang tersedia
jika lebih kecil. Mode biasa, termasuk mode multi-port, memakai satu proses
per instans. Hitung juga proses yang dibuat PM2 atau orchestrator.
Untuk tiap server PostgreSQL, kurangi `max_connections` dengan slot cadangan,
koneksi puncak layanan lain, dan ruang untuk operasi. Jika kedua pool menuju
server yang sama, bagi jatah TopUp dengan jumlah maksimum proses aplikasi yang
bisa hidup bersamaan, termasuk saat rolling deploy. Hasilnya adalah batas
gabungan kedua pool per proses. Jika kedua pool menuju server berbeda, hitung
jatah masing-masing server.
Contoh dengan jatah 40 koneksi dan maksimum empat proses bersamaan.
Batas 8 + 2 per proses menggunakan paling banyak 40 koneksi. Jumlah pengguna
aktif tidak langsung menentukan ukuran pool. Uji dengan trafik representatif,
lalu pantau latensi query, timeout akuisisi Knex, dan sesi `active`,
`idle`, serta `idle in transaction` pada `pg_stat_activity` sebelum menaikkan
batas.
-12
View File
@@ -134,24 +134,20 @@ const logger = {
console.log(statusCode); console.log(statusCode);
winstonLoki.log.error({ winstonLoki.log.error({
message: message, message: message,
labels: {
route: url, route: url,
status_code: statusCode, status_code: statusCode,
issuer_name: issuerName, issuer_name: issuerName,
},
}); });
} else { } else {
let reservation_number = info.meta.res.body.data.reservation_number; let reservation_number = info.meta.res.body.data.reservation_number;
let card_number = info.meta.res.body.data.card_number; let card_number = info.meta.res.body.data.card_number;
winstonLoki.log.info({ winstonLoki.log.info({
message: message, message: message,
labels: {
route: url, route: url,
status_code: statusCode, status_code: statusCode,
issuer_name: issuerName, issuer_name: issuerName,
reservation_number: reservation_number, reservation_number: reservation_number,
card_number: card_number, card_number: card_number,
},
}); });
} }
} else if (url == "/api/topup6" || url == "/api/topup7") { } else if (url == "/api/topup6" || url == "/api/topup7") {
@@ -167,26 +163,22 @@ const logger = {
) { ) {
winstonLoki.log.error({ winstonLoki.log.error({
message: message, message: message,
labels: {
route: url, route: url,
status_code: statusCode, status_code: statusCode,
issuer_name: issuerName, issuer_name: issuerName,
card_number: card_number, card_number: card_number,
uid: uid, uid: uid,
trxID: trxID, trxID: trxID,
},
}); });
} else { } else {
winstonLoki.log.info({ winstonLoki.log.info({
message: message, message: message,
labels: {
route: url, route: url,
status_code: statusCode, status_code: statusCode,
issuer_name: issuerName, issuer_name: issuerName,
card_number: card_number, card_number: card_number,
uid: uid, uid: uid,
trxID: trxID, trxID: trxID,
},
}); });
} }
} else { } else {
@@ -200,22 +192,18 @@ const logger = {
) { ) {
winstonLoki.log.error({ winstonLoki.log.error({
message: message, message: message,
labels: {
route: url, route: url,
status_code: statusCode, status_code: statusCode,
issuer_name: issuerName, issuer_name: issuerName,
trxID: trxID, trxID: trxID,
},
}); });
} else { } else {
winstonLoki.log.info({ winstonLoki.log.info({
message: message, message: message,
labels: {
route: url, route: url,
status_code: statusCode, status_code: statusCode,
issuer_name: issuerName, issuer_name: issuerName,
trxID: trxID, trxID: trxID,
},
}); });
} }
} }
+140 -12
View File
@@ -1,4 +1,6 @@
const CryptoJS = require('crypto-js'); const CryptoJS = require('crypto-js');
const { randomUUID } = require('crypto');
const knex = require('../../infrastructure/database/knex');
// ENCRYPT TEXT // ENCRYPT TEXT
const encryptText = (text) => { const encryptText = (text) => {
@@ -68,36 +70,30 @@ function generateXMLRequest(urn, headers, items) {
'0' '0'
)}</ITEMNO_ACC> )}</ITEMNO_ACC>
<!--Optional:--> <!--Optional:-->
<CUSTOMER>${ <CUSTOMER>${item.c_account_code_topup
item.c_account_code_topup
? item.c_account_code_topup ? item.c_account_code_topup
: '' : ''
}</CUSTOMER> }</CUSTOMER>
<!--Optional:--> <!--Optional:-->
<GL_ACCOUNT>${ <GL_ACCOUNT>${item.c_account_topup ? item.c_account_topup : ''
item.c_account_topup ? item.c_account_topup : ''
}</GL_ACCOUNT> }</GL_ACCOUNT>
<!--Optional:--> <!--Optional:-->
<BUS_AREA>${item.ba ? item.ba : ''}</BUS_AREA> <BUS_AREA>${item.ba ? item.ba : ''}</BUS_AREA>
<!--Optional:--> <!--Optional:-->
<AMT_DOCCUR>${ <AMT_DOCCUR>${item.amount ? item.amount : ''
item.amount ? item.amount : ''
}</AMT_DOCCUR> }</AMT_DOCCUR>
<!--Optional:--> <!--Optional:-->
<BLINE_DATE>${ <BLINE_DATE>${item.posting_date ? item.posting_date : ''
item.posting_date ? item.posting_date : ''
}</BLINE_DATE> }</BLINE_DATE>
<!--Optional:--> <!--Optional:-->
<COSTCENTER></COSTCENTER> <COSTCENTER></COSTCENTER>
<!--Optional:--> <!--Optional:-->
<PROFITCENTER></PROFITCENTER> <PROFITCENTER></PROFITCENTER>
<!--Optional:--> <!--Optional:-->
<ALLOC_NMBR>${ <ALLOC_NMBR>${item.c_invoice_no ? item.c_invoice_no : ''
item.c_invoice_no ? item.c_invoice_no : ''
}</ALLOC_NMBR> }</ALLOC_NMBR>
<!--Optional:--> <!--Optional:-->
<ITEM_TEXT>${ <ITEM_TEXT>${item.item_text ? item.item_text : ''
item.item_text ? item.item_text : ''
}</ITEM_TEXT> }</ITEM_TEXT>
<!--Optional:--> <!--Optional:-->
<DE_CRE_IND>${item.de_cre}</DE_CRE_IND> <DE_CRE_IND>${item.de_cre}</DE_CRE_IND>
@@ -313,6 +309,136 @@ function getXMLData(response) {
return resSAP; return resSAP;
} }
async function startScheduler(schedulerCode) {
return await knex.transaction(async (trx) => {
const job = await knex('log.t_monitoring_scheduler_history')
.transacting(trx)
.where('c_scheduler_code', schedulerCode)
.where('c_status', 'idle')
.whereRaw(`
d_run_datetime BETWEEN NOW() - INTERVAL '3 minutes'
AND NOW() + INTERVAL '1 minute'
`)
.orderBy('d_run_datetime', 'desc')
.forUpdate()
.first();
let result;
if (!job) {
const master = await knex('log.t_monitoring_master_scheduler_name as mn')
.join('log.t_monitoring_master_scheduler_time as mt', 'mn.i_scheduler_name', 'mt.i_scheduler_name')
.transacting(trx)
.select(
'mn.i_scheduler_name',
'mn.c_scheduler_name',
'mn.c_scheduler_code',
'mn.c_category',
'mt.i_scheduler_time'
)
.where('mn.c_scheduler_code', schedulerCode)
.first();
if (!master) {
throw new Error('Master scheduler not found');
}
const token = randomUUID();
const inserted = await knex('log.t_monitoring_scheduler_history')
.transacting(trx)
.insert({
i_scheduler_name: master.i_scheduler_name,
i_scheduler_time: master.i_scheduler_time,
c_scheduler_name: master.c_scheduler_name,
d_run_datetime: knex.fn.now(),
c_status: 'processing',
d_started_at: knex.fn.now(),
c_execution_token: token,
c_category: master.c_category,
c_type: 'AUTO',
d_created: knex.fn.now(),
i_create: 0,
c_create_username: 'system',
c_create_fullname: 'system',
c_scheduler_code: master.c_scheduler_code
})
.returning('*');
result = inserted[0];
} else {
const token = randomUUID();
const updated = await knex('log.t_monitoring_scheduler_history')
.transacting(trx)
.where('i_scheduler_history', job.i_scheduler_history)
.update({
c_status: 'processing',
d_started_at: knex.fn.now(),
c_execution_token: token
})
.returning('*');
result = updated[0];
}
return result;
});
}
async function finishScheduler(token = null, schedulerCode = null) {
return await knex.transaction(async (trx) => {
let result = null;
if (token) {
const updated = await knex('log.t_monitoring_scheduler_history')
.transacting(trx)
.where('c_execution_token', token)
.where('c_status', 'processing')
.update({
c_status: 'finished',
d_finished_at: knex.fn.now()
})
.returning('*');
if (updated.length > 0) {
result = updated[0];
}
}
if (!result && schedulerCode) {
const job = await knex('log.t_monitoring_scheduler_history')
.transacting(trx)
.where('c_scheduler_code', schedulerCode)
.where('c_status', 'processing')
.whereNotNull('d_started_at')
.whereRaw(`d_started_at >= NOW() - INTERVAL '5 minutes'`)
.orderBy('d_started_at', 'desc')
.forUpdate()
.first();
if (job) {
const updated = await knex('log.t_monitoring_scheduler_history')
.transacting(trx)
.where('i_scheduler_history', job.i_scheduler_history)
.update({
c_status: 'finished',
d_finished_at: knex.fn.now()
})
.returning('*');
result = updated[0];
}
}
return result;
});
}
module.exports = { module.exports = {
encryptText, encryptText,
decryptText, decryptText,
@@ -322,4 +448,6 @@ module.exports = {
generateXMLRequest, generateXMLRequest,
postingSAP, postingSAP,
getXMLData, getXMLData,
startScheduler,
finishScheduler,
}; };
+21 -21
View File
@@ -1,8 +1,8 @@
const moment = require('moment'); const moment = require("moment");
const winston = require('winston'); const winston = require("winston");
const loki = require('winston-loki'); const loki = require("winston-loki");
require('winston-daily-rotate-file'); require("winston-daily-rotate-file");
require('dotenv').config(); require("dotenv").config();
const { combine, timestamp, printf, colorize, align, json } = winston.format; const { combine, timestamp, printf, colorize, align, json } = winston.format;
let lokiUrl = process.env.LOKI_URL; let lokiUrl = process.env.LOKI_URL;
@@ -18,39 +18,39 @@ var log;
const fileRotateTransport = new winston.transports.DailyRotateFile({ const fileRotateTransport = new winston.transports.DailyRotateFile({
filename: `./lokiLog/%DATE%-onlinetopup.log`, filename: `./lokiLog/%DATE%-onlinetopup.log`,
datePattern: 'YYYY-MM-DD', datePattern: "YYYY-MM-DD",
maxFiles: '1d', maxFiles: "1d",
}); });
if ( if (
process.env.NODE_ENV == 'production' || process.env.NODE_ENV == "production" ||
process.env.NODE_ENV == 'PRODUCTION' process.env.NODE_ENV == "PRODUCTION"
) { ) {
log = winston.createLogger({ log = winston.createLogger({
levels: logLevels, levels: logLevels,
level: process.env.LOG_LEVEL || 'info', level: process.env.LOG_LEVEL || "info",
exitOnError: false, exitOnError: false,
// format: combine(timestamp(), json()), // format: combine(timestamp(), json()),
format: combine( format: combine(
// colorize({ all: true }), // colorize({ all: true }),
timestamp({ timestamp({
format: 'YYYY-MM-DD HH:mm:ss.SSS', format: "YYYY-MM-DD HH:mm:ss.SSS",
}), }),
align(), align(),
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`) printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`),
), ),
defaultMeta: { service: 'topuponline' }, defaultMeta: { service: "topuponline" },
transports: [ transports: [
new loki({ new loki({
host: lokiUrl, host: lokiUrl,
labels: { app: 'topuponline' }, labels: { app: "topuponline" },
json: true, json: true,
format: json(), format: json(),
replaceTimestamp: true, replaceTimestamp: true,
onConnectionError: (err) => console.error(err), onConnectionError: (err) => console.error(err),
}), }),
new transports.Console({ new winston.transports.Console({
format: format.combine(format.simple(), format.colorize()), format: combine(colorize()),
}), }),
], ],
}); });
@@ -59,7 +59,7 @@ if (
transports: [ transports: [
new loki({ new loki({
host: lokiUrl, host: lokiUrl,
labels: { app: 'topuponline' }, labels: { app: "topuponline" },
handleExceptions: true, handleExceptions: true,
handleRejections: true, handleRejections: true,
clearOnError: true, clearOnError: true,
@@ -75,19 +75,19 @@ if (
}); });
} }
if (process.env.NODE_ENV != 'testing' && process.env.NODE_ENV != 'TESTING') { if (process.env.NODE_ENV != "testing" && process.env.NODE_ENV != "TESTING") {
log.add( log.add(
new winston.transports.Console({ new winston.transports.Console({
// format: winston.format.cli(), // format: winston.format.cli(),
format: combine( format: combine(
colorize({ all: true }), colorize({ all: true }),
timestamp({ timestamp({
format: 'YYYY-MM-DD HH:mm:ss.SSS', format: "YYYY-MM-DD HH:mm:ss.SSS",
}), }),
align(), align(),
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`) printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`),
), ),
}) }),
); );
} }
+9 -1
View File
@@ -27,7 +27,13 @@ var logger;
const fileRotateTransport = new winston.transports.DailyRotateFile({ const fileRotateTransport = new winston.transports.DailyRotateFile({
filename: `application/logs/%DATE%-onlinetopup.log`, filename: `application/logs/%DATE%-onlinetopup.log`,
datePattern: "YYYY-MM-DD", datePattern: "YYYY-MM-DD",
maxFiles: "90d", maxFiles: "60d",
});
const fileRotateTransportDebug = new winston.transports.DailyRotateFile({
filename: `application/logs/debug/%DATE%-onlinetopup.log`,
datePattern: "YYYY-MM-DD",
maxFiles: "30d",
}); });
// //
// If we're not in production then log to the `console` with the format: // If we're not in production then log to the `console` with the format:
@@ -54,6 +60,7 @@ if (
defaultMeta: { service: "topuponline-service" }, defaultMeta: { service: "topuponline-service" },
transports: [ transports: [
fileRotateTransport, fileRotateTransport,
fileRotateTransportDebug,
// //
// - Write all logs with importance level of `error` or less to `error.log` // - Write all logs with importance level of `error` or less to `error.log`
// - Write all logs with importance level of `info` or less to `onlinetopup.log` // - Write all logs with importance level of `info` or less to `onlinetopup.log`
@@ -84,6 +91,7 @@ if (
defaultMeta: { service: "topuponline-service" }, defaultMeta: { service: "topuponline-service" },
transports: [ transports: [
fileRotateTransport, fileRotateTransport,
fileRotateTransportDebug,
// //
// - Write all logs with importance level of `error` or less to `error.log` // - Write all logs with importance level of `error` or less to `error.log`
// - Write all logs with importance level of `info` or less to `onlinetopup.log` // - Write all logs with importance level of `info` or less to `onlinetopup.log`
@@ -161,6 +161,47 @@ const getLoadBalanceNumberSequence = async (req, res, next) => {
} }
next(); next();
}; };
const getLoadBalanceNumberSequence2 = async (req) => {
// set default load_balance_number_sequence dari partner apapun is null
let load_balance_number_sequence = null;
// cek jika redis is connect
let isRedisReady = await redisClient.isReady;
// jika tidak connect
if (isRedisReady) {
// jika connect maka cari sequence dari reservation number sesuai partner yg merequest
// format value nya harusnya seperti ini = { date: '2023-01-01', sequence: 1 }
// data req.partner_id_token di dapat dari authenticateToken di jwt middleware
let getValue = await redisClient.GET(
'load_balance_number_sequence_' + req.partner_id_token
);
if (getValue) {
// parsing data menjadi json format
let parsedValue = JSON.parse(getValue);
// cek apakah tanggal sequence yang di redis sama dengan hari ini atau bukan
if (parsedValue.date == moment().format('YYYY-MM-DD')) {
// jika tanggal nya sama dengan hari ini maka ambil sequence untuk reservation number yang di generate dari redis
load_balance_number_sequence = parseInt(parsedValue.sequence);
// langsung update sequence walaupun transaksi insert nya belum selesai
// impact menggunakan redis, untuk nomor sequence bisa saja ada yg loncat karena bisa saja ada transaksi insert reservation yang gagal
let setValue = {
date: moment().format('YYYY-MM-DD'),
sequence: parseInt(parsedValue.sequence) + 1,
};
await redisClient.SET(
`load_balance_number_sequence_${req.partner_id_token}`,
JSON.stringify(setValue)
);
}
}
}
return load_balance_number_sequence;
// next();
};
const setLoadBalanceNumberSequence = async (partner_id, sequence) => { const setLoadBalanceNumberSequence = async (partner_id, sequence) => {
// cek jika redis is connect // cek jika redis is connect
@@ -188,4 +229,5 @@ module.exports = {
setReservationNumberSequence, setReservationNumberSequence,
getLoadBalanceNumberSequence, getLoadBalanceNumberSequence,
setLoadBalanceNumberSequence, setLoadBalanceNumberSequence,
getLoadBalanceNumberSequence2,
}; };
+415 -198
View File
@@ -57,6 +57,10 @@ const apiGenerateCahsIn = async (req, res) => {
`${uniqueCode} REQUEST generate cashin: ${JSON.stringify(req.body)}` `${uniqueCode} REQUEST generate cashin: ${JSON.stringify(req.body)}`
); );
const schedulerCode = 'GENERATECASHINONLINETOPUP';
const startData = await helper.startScheduler(schedulerCode);
const token = startData.c_execution_token ?? null;
// check validator // check validator
const err = validationResult(req, res); const err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
@@ -82,6 +86,8 @@ const apiGenerateCahsIn = async (req, res) => {
data: cashIn, data: cashIn,
}; };
const finishData = await helper.finishScheduler(token, schedulerCode);
return res.status(200).json(result); return res.status(200).json(result);
} catch (error) { } catch (error) {
// create log // create log
@@ -154,7 +160,127 @@ const apiGenerateCashInSales = async (req, res) => {
} }
}; };
// RETRY POSTING INVOICE const apiGenerateCashInSalesInternal = async (req, res) => {
try {
// generate unique code
uniqueCode = helper.getUniqueCode();
// return uniqueCode
// log info
winston.logger.info(
`${uniqueCode} REQUEST generate cashin sales internal: ${JSON.stringify(req.body)}`
);
const schedulerCode = 'GENERATECASHINSALESSTATIONCASHLESS';
const startData = await helper.startScheduler(schedulerCode);
const token = startData.c_execution_token ?? null;
// check validator
const err = validationResult(req, res);
if (!err.isEmpty()) {
result = {
code: '400',
message: err.errors[0].msg,
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE generate cashin sales internal: ${JSON.stringify(result)}`
);
return res.status(200).json(result);
}
const cashIn = await _generateCashInSalesInternal(uniqueCode);
result = {
code: '200',
message: 'Success generate cash-in',
data: cashIn,
};
const finishData = await helper.finishScheduler(token, schedulerCode);
return res.status(200).json(result);
} catch (error) {
// create log
winston.logger.error(
`500 internal server error - backend server | ${error.message}`
);
return res.status(200).json({
code: '500',
message:
process.env.NODE_ENV != 'production'
? error.message
: '500 internal server error - backend server.',
data: {},
});
}
};
const apiGenerateCashInTopUpCashlessInternal = async (req, res) => {
try {
// generate unique code
uniqueCode = helper.getUniqueCode();
// return uniqueCode
// log info
winston.logger.info(
`${uniqueCode} REQUEST generate cashin topup cashless internal: ${JSON.stringify(req.body)}`
);
const schedulerCode = 'GENERATECASHINTOPUPSTATIONCASHLESS';
const startData = await helper.startScheduler(schedulerCode);
const token = startData.c_execution_token ?? null;
// check validator
const err = validationResult(req, res);
if (!err.isEmpty()) {
result = {
code: '400',
message: err.errors[0].msg,
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} RESPONSE generate cashin topup cashless internal: ${JSON.stringify(result)}`
);
return res.status(200).json(result);
}
const cashIn = await _generateCashInTopUpCashlessInternal(uniqueCode);
result = {
code: '200',
message: 'Success generate cash-in',
data: cashIn,
};
const finishData = await helper.finishScheduler(token, schedulerCode);
return res.status(200).json(result);
} catch (error) {
// create log
winston.logger.error(
`500 internal server error - backend server | ${error.message}`
);
return res.status(200).json({
code: '500',
message:
process.env.NODE_ENV != 'production'
? error.message
: '500 internal server error - backend server.',
data: {},
});
}
};
// RETRY POSTING CASH IN
const apiPostingCahsIn = async (req, res) => { const apiPostingCahsIn = async (req, res) => {
try { try {
// generate unique code // generate unique code
@@ -215,7 +341,6 @@ const apiPostingCahsIn = async (req, res) => {
const _generateCashIn = async (uniqueCode) => { const _generateCashIn = async (uniqueCode) => {
let partnerRecon = await model.getPartnerRecon(knex); let partnerRecon = await model.getPartnerRecon(knex);
// return partnerRecon
winston.logger.info( winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify( `SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify(
partnerRecon partnerRecon
@@ -223,38 +348,8 @@ const _generateCashIn = async (uniqueCode) => {
); );
for (const item of partnerRecon) { for (const item of partnerRecon) {
let reserve = [];
let code = '';
await knex.transaction(async (trx) => {
try { try {
code = await model.generateCode( await knex.transaction(async (trx) => {
trx,
item.c_partner_code,
moment().format('YYMMDD')
);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} generate cash in : ${code}`
);
// Cash-in
let dataCahsIn = {
c_partner_code: item.c_partner_code,
c_partner_name: item.c_partner_name,
c_cash_in_no: code,
c_in_period: item.c_in_period,
d_credit: item.d_payment,
c_invoice_no: item.c_invoice_no,
i_amount: item.amount,
};
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN ${code} DATA : ${JSON.stringify(
dataCahsIn
)}`
);
// CASH-IN DETAIL
let data = [];
const reserv = await model.getReserve( const reserv = await model.getReserve(
trx, trx,
item.c_partner_code, item.c_partner_code,
@@ -262,40 +357,57 @@ const _generateCashIn = async (uniqueCode) => {
item.c_invoice_no item.c_invoice_no
); );
//TOTAL AMOUNT CASH-IN if (!reserv || reserv.length === 0) {
let cashInAmount = 0; return;
for (const itemCI of reserv) {
cashInAmount += parseInt(itemCI.i_reservation_amount);
} }
dataCahsIn.i_amount = cashInAmount;
if(cashInAmount > 0) { const cashInAmount = reserv.reduce(
//INSERT CASH-IN (sum, row) => sum + parseInt(row.i_reservation_amount, 10),
const cashIn = await model.insertCashIn(trx, dataCahsIn); 0
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN HISTORY ${code} DATA : ${JSON.stringify(
dataCahsIn
)}`
);
const paymentyHistory = await model.writePaynentHistory(
dataCahsIn,
'SUCCESSFULLY',
0,
trx
); );
let m_amount = 0; if (cashInAmount <= 0) {
return;
}
let runningAmount = 0;
for (const detail of reserv) { for (const detail of reserv) {
// data.push({ runningAmount += parseInt(detail.i_reservation_amount, 10);
// i_cash_in: cashIn.i_cash_in, if (runningAmount > parseInt(detail.invoice_amount, 10)) {
// c_reservation_no: detail.c_reservation_no, winston.logger.warn(
// m_amount: detail.i_reservation_amount, `SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount} on invoice ${detail.c_invoice_no})`
// c_payment_recon_no: detail.c_payment_recon_no, );
// d_payment: detail.d_payment, return;
// d_payment_recon: detail.d_payment_recon, }
// c_load_balance_no: detail.c_load_balance_no, }
// });
let temp = { const code = await model.generateCode(
trx,
item.c_partner_code,
moment().format('YYMMDD')
);
const dataCahsIn = {
c_partner_code: item.c_partner_code,
c_partner_name: item.c_partner_name,
c_cash_in_no: code,
c_in_period: item.c_in_period,
d_credit: item.d_payment,
c_invoice_no: item.c_invoice_no,
i_amount: cashInAmount,
};
const cashIn = await model.insertCashIn(trx, dataCahsIn);
await model.writePaynentHistory(dataCahsIn, 'SUCCESSFULLY', 0, trx);
const dataReserve = {
c_cash_in_no: cashIn.c_cash_in_no,
d_credit: cashIn.d_credit,
c_in_period: cashIn.c_in_period,
};
const reserveNos = reserv.map((detail) => detail.c_reservation_no);
const cashInDetails = reserv.map((detail) => ({
i_cash_in: cashIn.i_cash_in, i_cash_in: cashIn.i_cash_in,
c_reservation_no: detail.c_reservation_no, c_reservation_no: detail.c_reservation_no,
m_amount: detail.i_reservation_amount, m_amount: detail.i_reservation_amount,
@@ -303,61 +415,27 @@ const _generateCashIn = async (uniqueCode) => {
d_payment: detail.d_payment, d_payment: detail.d_payment,
d_payment_recon: detail.d_payment_recon, d_payment_recon: detail.d_payment_recon,
c_load_balance_no: detail.c_load_balance_no, c_load_balance_no: detail.c_load_balance_no,
}; }));
let reserveNo = detail.c_reservation_no; await model.updateIntoReserveBulk(trx, dataReserve, reserveNos);
let dataReserve = { await model.insertCashInDetailBulk(trx, cashInDetails);
c_cash_in_no: cashIn.c_cash_in_no,
d_credit: cashIn.d_credit,
c_in_period: cashIn.c_in_period,
};
m_amount += parseInt(detail.i_reservation_amount);
if(m_amount <= detail.invoice_amount) {
await model.updateIntoReserve(trx, dataReserve, reserveNo);
winston.logger.info( winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} CASH-IN UPDATE RESERVE BALANCE ${reserveNo} DATA : ${JSON.stringify( `SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}`
dataReserve
)}`
); );
await model.insertCashInDetail(trx, temp);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN DETAIL, ID CASH-IN ${cashIn.i_cash_in} : ${JSON.stringify(
temp
)}`
);
} else {
await trx.rollback();
winston.logger.info(
`${uniqueCode} ROLLBACK CASH-IN: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${m_amount} > INVOICE AMOUNT (${detail.invoice_amount}) : ${JSON.stringify(
dataCahsIn
)}`
);
}
}
await wait(10000);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN TO RESERVE ${code} DATA : ${JSON.stringify(
dataCahsIn
)}`
);
}
await trx.commit();
} catch (error) {
sts = "error";
await trx.rollback();
}
}); });
} catch (error) {
winston.logger.error(
`SCHEDULER-FB70-${uniqueCode} generate cash in failed for partner=${item.c_partner_code}, invoice=${item.c_invoice_no} | ${error.message}`
);
} }
}
return partnerRecon; return partnerRecon;
}; };
const _generateCashInSales = async (uniqueCode) => { const _generateCashInSales = async (uniqueCode) => {
let partnerRecon = await model.getPartnerReconSales(knex); let partnerRecon = await model.getPartnerReconSales(knex);
// return partnerRecon
winston.logger.info( winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify( `SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify(
partnerRecon partnerRecon
@@ -365,38 +443,8 @@ const _generateCashInSales = async (uniqueCode) => {
); );
for (const item of partnerRecon) { for (const item of partnerRecon) {
let reserve = [];
let code = '';
await knex.transaction(async (trx) => {
try { try {
code = await model.generateCode( await knex.transaction(async (trx) => {
trx,
item.c_partner_code,
moment().format('YYMMDD')
);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} generate cash in : ${code}`
);
// Cash-in
let dataCahsIn = {
c_partner_code: item.c_partner_code,
c_partner_name: item.c_partner_name,
c_cash_in_no: code,
c_in_period: item.c_in_period,
d_credit: item.d_payment,
c_invoice_no: item.c_invoice_no,
i_amount: item.amount,
c_source: 'S'
};
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN SALES ${code} DATA : ${JSON.stringify(
dataCahsIn
)}`
);
// CASH-IN DETAIL
const sales = await model.getSalesKMT( const sales = await model.getSalesKMT(
trx, trx,
item.c_partner_code, item.c_partner_code,
@@ -404,80 +452,249 @@ const _generateCashInSales = async (uniqueCode) => {
item.c_invoice_no item.c_invoice_no
); );
winston.logger.info( if (!sales || sales.length === 0) {
`SCHEDULER-FB70-${uniqueCode} DATA SALES ${code} : ${JSON.stringify( sales )}` return;
);
//TOTAL AMOUNT CASH-IN
let cashInAmount = 0;
for (const itemCI of sales) {
cashInAmount += parseInt(itemCI.i_total_billing);
} }
dataCahsIn.i_amount = cashInAmount;
if(cashInAmount > 0) { const cashInAmount = sales.reduce(
//INSERT CASH-IN (sum, row) => sum + parseInt(row.i_total_billing, 10),
const cashIn = await model.insertCashIn(trx, dataCahsIn); 0
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN HISTORY ${code} DATA : ${JSON.stringify(
dataCahsIn
)}`
);
const paymentyHistory = await model.writePaynentHistory(
dataCahsIn, 'SUCCESSFULLY', 0, trx
); );
let m_amount = 0; if (cashInAmount <= 0) {
return;
}
let runningAmount = 0;
for (const detail of sales) { for (const detail of sales) {
let temp = { runningAmount += parseInt(detail.i_total_billing, 10);
if (runningAmount > parseInt(detail.invoice_amount, 10)) {
winston.logger.warn(
`SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN SALES: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount} on invoice ${detail.c_invoice_no})`
);
return;
}
}
const code = await model.generateCode(
trx,
item.c_partner_code,
moment().format('YYMMDD')
);
const dataCahsIn = {
c_partner_code: item.c_partner_code,
c_partner_name: item.c_partner_name,
c_cash_in_no: code,
c_in_period: item.c_in_period,
d_credit: item.d_payment,
c_invoice_no: item.c_invoice_no,
i_amount: cashInAmount,
c_source: 'S',
};
const cashIn = await model.insertCashIn(trx, dataCahsIn);
await model.writePaynentHistory(dataCahsIn, 'SUCCESSFULLY', 0, trx);
const dataSales = {
c_cash_in_no: cashIn.c_cash_in_no,
d_credit: cashIn.d_credit,
c_in_period: cashIn.c_in_period,
};
const salesNos = sales.map((detail) => detail.c_sales_no);
const cashInDetails = sales.map((detail) => ({
i_cash_in: cashIn.i_cash_in, i_cash_in: cashIn.i_cash_in,
c_reservation_no: detail.c_sales_no, c_reservation_no: detail.c_sales_no,
m_amount: detail.i_total_billing, m_amount: detail.i_total_billing,
c_payment_recon_no: detail.c_payment_recon_no, c_payment_recon_no: detail.c_payment_recon_no,
d_payment: detail.d_payment, d_payment: detail.d_payment,
d_payment_recon: detail.d_payment_recon, d_payment_recon: detail.d_payment_recon,
}; }));
let salesNo = detail.c_sales_no; await model.updateIntoSalesKMTBulk(trx, dataSales, salesNos);
let dataSales = { await model.insertCashInDetailBulk(trx, cashInDetails);
c_cash_in_no: cashIn.c_cash_in_no,
d_credit: cashIn.d_credit,
c_in_period: cashIn.c_in_period,
};
m_amount += parseInt(detail.i_total_billing);
if(m_amount <= detail.invoice_amount) {
await model.updateIntoSalesKMT(trx, dataSales, salesNo);
winston.logger.info( winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} CASH-IN UPDATE SALES KMT MOBILE ${salesNo} DATA : ${JSON.stringify( `SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN SALES ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}`
dataSales
)}`
); );
await model.insertCashInDetail(trx, temp); });
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN DETAIL, ID CASH-IN ${cashIn.i_cash_in} : ${JSON.stringify(
temp
)}`
);
} else {
await trx.rollback();
winston.logger.info(
`${uniqueCode} ROLLBACK CASH-IN: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${m_amount} > INVOICE AMOUNT (${detail.invoice_amount}) : ${JSON.stringify(
dataCahsIn
)}`
);
}
}
await wait(10000);
winston.logger.info();
}
await trx.commit();
} catch (error) { } catch (error) {
sts = "error"; winston.logger.error(
await trx.rollback(); `SCHEDULER-FB70-${uniqueCode} generate cash in sales failed for partner=${item.c_partner_code}, invoice=${item.c_invoice_no} | ${error.message}`
);
}
}
return partnerRecon;
};
const _generateCashInSalesInternal = async (uniqueCode) => {
let partnerRecon = await model.getPartnerReconSalesInternal(knex);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify(
partnerRecon
)}`
);
for (const item of partnerRecon) {
await knex.transaction(async (trx) => {
const sales = await model.getSalesInternal(
trx,
item.c_partner_code,
item.d_payment,
item.c_invoice_no
);
if (!sales || sales.length === 0) {
return;
} }
const cashInAmount = sales.reduce(
(sum, row) => sum + parseInt(row.i_total_price, 10),
0
);
if (cashInAmount <= 0) {
return;
}
let runningAmount = 0;
for (const detail of sales) {
runningAmount += parseInt(detail.i_total_price, 10);
if (runningAmount > parseInt(detail.invoice_amount, 10)) {
winston.logger.warn(
`SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN SALES INTERNAL: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount} on invoice ${detail.c_invoice_no})`
);
return;
}
}
const code = await model.generateCode(
trx,
item.c_partner_code,
moment().format('YYMMDD')
);
const dataCahsIn = {
c_partner_code: item.c_partner_code,
c_partner_name: item.c_partner_name,
c_cash_in_no: code,
c_in_period: item.c_in_period,
d_credit: item.d_payment,
c_invoice_no: item.c_invoice_no,
i_amount: cashInAmount,
c_source: 'S',
};
const cashIn = await model.insertCashIn(trx, dataCahsIn);
await model.writePaynentHistory(dataCahsIn, 'SUCCESSFULLY', 0, trx);
const dataSales = {
i_cash_in: cashIn.i_cash_in,
};
const salesNos = sales.map((detail) => detail.c_sales_no);
const cashInDetails = sales.map((detail) => ({
i_cash_in: cashIn.i_cash_in,
c_reservation_no: detail.c_sales_no,
m_amount: detail.i_total_price,
c_payment_recon_no: detail.c_payment_recon_no,
d_payment: detail.d_payment,
d_payment_recon: detail.d_payment_recon,
}));
await model.updateIntoSalesInternalBulk(trx, dataSales, salesNos);
await model.insertCashInDetailBulk(trx, cashInDetails);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN SALES INTERNAL ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}`
);
});
}
return partnerRecon;
};
const _generateCashInTopUpCashlessInternal = async (uniqueCode) => {
let partnerRecon = await model.getPartnerReconTopUpCashlessInternal(knex);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify(
partnerRecon
)}`
);
for (const item of partnerRecon) {
await knex.transaction(async (trx) => {
const topup = await model.getTopUpCashlessInternal(
trx,
item.c_partner_code,
item.d_payment,
item.c_invoice_no
);
if (!topup || topup.length === 0) {
return;
}
const cashInAmount = topup.reduce(
(sum, row) => sum + parseInt(row.i_amount, 10),
0
);
if (cashInAmount <= 0) {
return;
}
let runningAmount = 0;
for (const detail of topup) {
runningAmount += parseInt(detail.i_amount, 10);
if (runningAmount > parseInt(detail.invoice_amount, 10)) {
winston.logger.warn(
`SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN TOPUP CASHLESS INTERNAL: AMOUNT CASH-IN > TOTAL INVOICE. AMOUNT ${runningAmount} > INVOICE AMOUNT (${detail.invoice_amount})`
);
return;
}
}
const code = await model.generateCode(
trx,
item.c_partner_code,
moment().format('YYMMDD')
);
const dataCahsIn = {
c_partner_code: item.c_partner_code,
c_partner_name: item.c_partner_name,
c_cash_in_no: code,
c_in_period: item.c_in_period,
d_credit: item.d_payment,
c_invoice_no: item.c_invoice_no,
i_amount: cashInAmount,
c_source: 'T',
};
const cashIn = await model.insertCashIn(trx, dataCahsIn);
await model.writePaynentHistory(dataCahsIn, 'SUCCESSFULLY', 0, trx);
const dataTopup = {
i_cash_in: cashIn.i_cash_in,
};
const topupNos = topup.map((detail) => detail.c_topup_no);
const cashInDetails = topup.map((detail) => ({
i_cash_in: cashIn.i_cash_in,
c_reservation_no: detail.c_topup_no,
m_amount: detail.i_amount,
c_payment_recon_no: detail.c_payment_recon_no,
d_payment: detail.d_payment,
d_payment_recon: detail.d_payment_recon,
}));
await model.updateIntoTopUpCashlessInternalBulk(trx, dataTopup, topupNos);
await model.insertCashInDetailBulk(trx, cashInDetails);
winston.logger.info(
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN TOPUP CASHLESS INTERNAL ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}`
);
}); });
} }
return partnerRecon; return partnerRecon;
@@ -559,16 +776,16 @@ const _postingCashIn = async (uniqueCode) => {
return postingEt; return postingEt;
}; };
function wait(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
module.exports = { module.exports = {
validate, validate,
apiGenerateCahsIn, apiGenerateCahsIn,
apiGenerateCashInSales, apiGenerateCashInSales,
apiGenerateCashInSalesInternal,
apiGenerateCashInTopUpCashlessInternal,
apiPostingCahsIn, apiPostingCahsIn,
_postingCashIn, _postingCashIn,
_generateCashIn, _generateCashIn,
_generateCashInSales _generateCashInSales,
_generateCashInSalesInternal,
_generateCashInTopUpCashlessInternal,
}; };
+264 -25
View File
@@ -1,12 +1,10 @@
// GET PARTNER, MERCHANT, TERMINAL FROM TID // GET PARTNER, MERCHANT, TERMINAL FROM TID
const generateInvoice = async (invoiceDate, repost, trx) => { const generateInvoice = async (invoiceDate, repost, trx) => {
let result = await trx.select( let result = await trx.raw(
trx.raw( `SELECT * FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`
`* FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`
)
); );
return result; return result.rows || result;
}; };
const insertPostingEt = async (code, dataCashIn, trx) => { const insertPostingEt = async (code, dataCashIn, trx) => {
@@ -281,14 +279,14 @@ const getReserve = async (trx, code, date, invoice) => {
.leftJoin('trx.t_d_load_balance as tdlb', function () { .leftJoin('trx.t_d_load_balance as tdlb', function () {
this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no'); this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no');
}) })
.leftJoin('payment.t_d_invoice as tdi', function () { .innerJoin('payment.t_d_invoice as tdi', function () {
this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no').orOn( this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no').orOn(
'tdi.c_invoice_no', 'tdi.c_invoice_no',
'=', '=',
'tdrb.c_invoice_no' 'tdrb.c_invoice_no'
); );
}) })
.leftJoin('payment.t_d_payment_recon as tdpr', function () { .innerJoin('payment.t_d_payment_recon as tdpr', function () {
this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no'); this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no');
}) })
.where('tdrb.c_status', '=', 'A') .where('tdrb.c_status', '=', 'A')
@@ -299,9 +297,11 @@ const getReserve = async (trx, code, date, invoice) => {
.where('tdpr.c_status', '=', 'S') .where('tdpr.c_status', '=', 'S')
.whereNotNull('tdi.c_return_sap') .whereNotNull('tdi.c_return_sap')
.whereNotNull('tdrb.c_load_balance_no') .whereNotNull('tdrb.c_load_balance_no')
.whereRaw( .whereNull('tdrb.c_cash_in_no')
`tdrb.c_reservation_no in (SELECT c_reservation_no FROM payment.t_d_payment_recon where c_status = 'S' ) AND tdrb.c_reservation_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)` // .whereRaw(
); // `tdrb.c_reservation_no in (SELECT c_reservation_no FROM payment.t_d_payment_recon where c_status = 'S' ) AND tdrb.c_reservation_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)`
// );
return res; return res;
}; };
@@ -321,8 +321,8 @@ const getSalesKMT = async (trx, code, date, invoice) => {
'tdsi.m_total_billing as invoice_amount' 'tdsi.m_total_billing as invoice_amount'
]) ])
.from('kmt_mobile.t_d_sales_kmt_mobile AS tdskm') .from('kmt_mobile.t_d_sales_kmt_mobile AS tdskm')
.leftJoin('payment.t_d_payment_recon_sales_kmt_mobile as tdpr', 'tdpr.c_sales_no', 'tdskm.c_sales_no') .innerJoin('payment.t_d_payment_recon_sales_kmt_mobile as tdpr', 'tdpr.c_sales_no', 'tdskm.c_sales_no')
.leftJoin('payment.t_d_sales_invoice as tdsi', 'tdsi.i_sales_invoice', 'tdskm.i_sales_invoice') .innerJoin('payment.t_d_sales_invoice as tdsi', 'tdsi.i_sales_invoice', 'tdskm.i_sales_invoice')
.where('tdskm.c_sales_status', '=', 'A') .where('tdskm.c_sales_status', '=', 'A')
.where('tdsi.c_status', '!=', 'X') .where('tdsi.c_status', '!=', 'X')
@@ -332,7 +332,81 @@ const getSalesKMT = async (trx, code, date, invoice) => {
.where('tdpr.c_status', '=', 'S') .where('tdpr.c_status', '=', 'S')
.whereNotNull('tdsi.c_return_sap') .whereNotNull('tdsi.c_return_sap')
.whereRaw( .whereRaw(
`tdskm.c_sales_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)` `NOT EXISTS (
SELECT 1
FROM payment.t_d_cash_in_detail cid
WHERE cid.c_reservation_no = tdskm.c_sales_no
AND cid.b_reversal IS NOT TRUE
)`
);
return res;
};
const getSalesInternal = async (trx, code, date, invoice) => {
const res = await trx
.select([
'tdskm.c_sales_no',
'tdskm.i_total_price',
'tdpr.c_payment_recon_no',
'tdpr.d_payment',
'tdpr.d_payment_recon',
'tmp.c_code as c_partner_code',
'tmp.c_name as c_partner_name',
'tdsi.c_invoice_no',
'tdsi.i_total_price as invoice_amount'
])
.from('trx.t_d_sales_internal AS tdskm')
.innerJoin('payment.t_d_payment_recon_sales_internal as tdpr', 'tdpr.c_sales_no', 'tdskm.c_sales_no')
.innerJoin('payment.t_d_sales_invoice_internal as tdsi', 'tdsi.i_sales_invoice_internal', 'tdskm.i_sales_invoice_internal')
.innerJoin('public.t_m_partner as tmp', 'tmp.i_partner', 'tdskm.i_partner')
.where('tdsi.c_status', '!=', 'X')
.where('tmp.c_code', '=', code)
.where('tdpr.d_payment', '=', date)
.where('tdsi.c_invoice_no', '=', invoice)
.where('tdpr.c_status', '=', 'S')
.whereNotNull('tdsi.c_return_sap_fi')
.whereRaw(
`NOT EXISTS (
SELECT 1
FROM payment.t_d_cash_in_detail cid
WHERE cid.c_reservation_no = tdskm.c_sales_no
AND cid.b_reversal IS NOT TRUE)`
);
return res;
};
const getTopUpCashlessInternal = async (trx, code, date, invoice) => {
const res = await trx
.select([
'tdskm.c_topup_no',
'tdskm.i_amount',
'tdpr.c_payment_recon_no',
'tdpr.d_payment',
'tdpr.d_payment_recon',
'tmp.c_code as c_partner_code',
'tmp.c_name as c_partner_name',
'tdsi.c_invoice_no',
'tdsi.i_total_amount as invoice_amount'
])
.from('trx.t_d_topup_cashless_internal AS tdskm')
.innerJoin('payment.t_d_payment_recon_topup_cashless_internal as tdpr', 'tdpr.c_topup_no', 'tdskm.c_topup_no')
.innerJoin('payment.t_d_topup_cashless_invoice_internal as tdsi', 'tdsi.i_topup_cashless_invoice_internal', 'tdskm.i_topup_cashless_invoice_internal')
.innerJoin('public.t_m_partner as tmp', 'tmp.i_partner', 'tdskm.i_partner')
.where('tdsi.c_status', '!=', 'X')
.where('tmp.c_code', '=', code)
.where('tdpr.d_payment', '=', date)
.where('tdsi.c_invoice_no', '=', invoice)
.where('tdpr.c_status', '=', 'S')
.whereNotNull('tdsi.c_return_sap')
.whereRaw(
`NOT EXISTS (
SELECT 1
FROM payment.t_d_cash_in_detail cid
WHERE cid.c_reservation_no = tdskm.c_topup_no
AND cid.b_reversal IS NOT TRUE
)`
); );
return res; return res;
@@ -412,7 +486,7 @@ const getPartnerRecon = async (trx) => {
'i_company', 'i_company',
'i_holding', 'i_holding',
trx.raw(`CASE trx.raw(`CASE
WHEN to_char(tdpr.d_payment, 'YYYYMM') >= to_char(tdi.d_invoice_date, 'YYYYMM') WHEN date_trunc('month', tdpr.d_payment) >= date_trunc('month', tdi.d_invoice_date)
THEN 'IP' THEN 'IP'
ELSE ELSE
'OP' 'OP'
@@ -422,17 +496,17 @@ const getPartnerRecon = async (trx) => {
.leftJoin('trx.t_d_load_balance as tdlb', function () { .leftJoin('trx.t_d_load_balance as tdlb', function () {
this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no'); this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no');
}) })
.leftJoin('payment.t_d_invoice as tdi', function () { .innerJoin('payment.t_d_invoice as tdi', function () {
this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no').orOn( this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no').orOn(
'tdi.c_invoice_no', 'tdi.c_invoice_no',
'=', '=',
'tdrb.c_invoice_no' 'tdrb.c_invoice_no'
); );
}) })
.leftJoin('payment.t_d_payment_recon as tdpr', function () { .innerJoin('payment.t_d_payment_recon as tdpr', function () {
this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no'); this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no');
}) })
.leftJoin('public.t_m_partner as tmp', function () { .innerJoin('public.t_m_partner as tmp', function () {
this.on('tmp.i_partner', '=', 'tdrb.i_partner'); this.on('tmp.i_partner', '=', 'tdrb.i_partner');
}) })
// .leftJoin('payment.t_d_cash_in_detail as tdcid', function () { // .leftJoin('payment.t_d_cash_in_detail as tdcid', function () {
@@ -475,19 +549,19 @@ const getPartnerReconSales = async (trx) => {
trx.raw('coalesce(SUM(tdskm.i_total_billing),0) AS amount'), trx.raw('coalesce(SUM(tdskm.i_total_billing),0) AS amount'),
'tmp.c_account_topup', 'tmp.c_account_topup',
'tmp.c_account_code_topup', 'tmp.c_account_code_topup',
trx.raw(`CASE WHEN to_char(tdpr.d_payment, 'YYYYMM') >= to_char(tdsi.d_invoice_date, 'YYYYMM') trx.raw(`CASE WHEN date_trunc('month', tdpr.d_payment) >= date_trunc('month', tdsi.d_invoice_date)
THEN 'IP' ELSE 'OP' THEN 'IP' ELSE 'OP'
END c_in_period`), END c_in_period`),
]) ])
.from('kmt_mobile.t_d_sales_kmt_mobile AS tdskm') .from('kmt_mobile.t_d_sales_kmt_mobile AS tdskm')
.leftJoin('payment.t_d_sales_invoice as tdsi', function () { .innerJoin('payment.t_d_sales_invoice as tdsi', function () {
this.on('tdsi.i_sales_invoice', '=', 'tdskm.i_sales_invoice'); this.on('tdsi.i_sales_invoice', '=', 'tdskm.i_sales_invoice');
}) })
.leftJoin('payment.t_d_payment_recon_sales_kmt_mobile as tdpr', function () { .innerJoin('payment.t_d_payment_recon_sales_kmt_mobile as tdpr', function () {
this.on('tdpr.c_sales_no', '=', 'tdskm.c_sales_no'); this.on('tdpr.c_sales_no', '=', 'tdskm.c_sales_no');
}) })
.leftJoin('public.t_m_partner as tmp', function () { .innerJoin('public.t_m_partner as tmp', function () {
this.on('tmp.i_partner', '=', 'tdskm.i_partner'); this.on('tmp.i_partner', '=', 'tdskm.i_partner');
}) })
.where('tdskm.c_sales_status', '=', 'A') .where('tdskm.c_sales_status', '=', 'A')
@@ -508,20 +582,108 @@ const getPartnerReconSales = async (trx) => {
return res; return res;
}; };
const getPartnerReconSalesInternal = async (trx) => {
const res = await trx
.select([
'tmp.c_code as c_partner_code',
'tmp.c_name as c_partner_name',
'tdsi.c_invoice_no',
'tdsi.d_invoice_date',
trx.raw("to_char(tdpr.d_payment, 'YYYY-MM-DD') AS d_payment"),
trx.raw('coalesce(SUM(tdskm.i_total_price),0) AS amount'),
'tmp.c_account_sales_revenue',
'tmp.c_account_code_sales_ar',
trx.raw(`CASE WHEN date_trunc('month', tdpr.d_payment) >= date_trunc('month', tdsi.d_invoice_date)
THEN 'IP' ELSE 'IP'
END c_in_period`),
])
.from('trx.t_d_sales_internal AS tdskm')
.innerJoin('payment.t_d_sales_invoice_internal as tdsi', function () {
this.on('tdsi.i_sales_invoice_internal', '=', 'tdskm.i_sales_invoice_internal');
})
.innerJoin('payment.t_d_payment_recon_sales_internal as tdpr', function () {
this.on('tdpr.c_sales_no', '=', 'tdskm.c_sales_no');
})
.innerJoin('public.t_m_partner as tmp', function () {
this.on('tmp.i_partner', '=', 'tdskm.i_partner');
})
.where('tdsi.c_status', '!=', 'X')
.where('tdpr.c_status', '=', 'S')
.whereNotNull('tdsi.c_return_sap_fi')
.whereNull('tdskm.i_cash_in')
.groupBy([
'tmp.c_code',
'tmp.c_name',
'tdsi.c_invoice_no',
'tdsi.d_invoice_date',
'tdpr.d_payment',
'tmp.c_account_sales_revenue',
'tmp.c_account_code_sales_ar'
]);
return res;
};
const getPartnerReconTopUpCashlessInternal = async (trx) => {
const res = await trx
.select([
'tmp.c_code as c_partner_code',
'tmp.c_name as c_partner_name',
'tdsi.c_invoice_no',
'tdsi.d_invoice_date',
trx.raw("to_char(tdpr.d_payment, 'YYYY-MM-DD') AS d_payment"),
trx.raw('coalesce(SUM(tdskm.i_amount),0) AS amount'),
'tmp.c_account_topup',
'tmp.c_account_code_topup',
trx.raw(`CASE WHEN date_trunc('month', tdpr.d_payment) >= date_trunc('month', tdsi.d_invoice_date)
THEN 'IP' ELSE 'IP'
END c_in_period`),
])
.from('trx.t_d_topup_cashless_internal AS tdskm')
.innerJoin('payment.t_d_topup_cashless_invoice_internal as tdsi', function () {
this.on('tdsi.i_topup_cashless_invoice_internal', '=', 'tdskm.i_topup_cashless_invoice_internal');
})
.innerJoin('payment.t_d_payment_recon_topup_cashless_internal as tdpr', function () {
this.on('tdpr.c_topup_no', '=', 'tdskm.c_topup_no');
})
.innerJoin('public.t_m_partner as tmp', function () {
this.on('tmp.i_partner', '=', 'tdskm.i_partner');
})
.where('tdsi.c_status', '!=', 'X')
.where('tdpr.c_status', '=', 'S')
.whereNotNull('tdsi.c_return_sap')
.whereNull('tdskm.i_cash_in')
.groupBy([
'tmp.c_code',
'tmp.c_name',
'tdsi.c_invoice_no',
'tdsi.d_invoice_date',
'tdpr.d_payment',
'tmp.c_account_topup',
'tmp.c_account_code_topup'
]);
return res;
};
const generateCode = async (trx, c_partner_code, d_payment_recon) => { const generateCode = async (trx, c_partner_code, d_payment_recon) => {
let code = ''; let code = '';
let prefix = `CIN${c_partner_code}${d_payment_recon}`; let prefix = `CIN${c_partner_code}${d_payment_recon}`;
let result = await trx let result = await trx
.select([trx.raw(`substring(c_cash_in_no, 13, 3) AS code`)]) .select([trx.raw(`right(c_cash_in_no, 3) AS code`)])
.from('payment.t_d_cash_in') .from('payment.t_d_cash_in')
.whereRaw(`substring(c_cash_in_no, 1, 12) = '${prefix}'`) .where('c_cash_in_no', 'like', `${prefix}%`)
// .where("d_project_date", projectDate) // .where("d_project_date", projectDate)
.orderBy('c_cash_in_no', 'DESC') .orderBy('c_cash_in_no', 'DESC')
.first(); .first();
if (result) { if (result) {
let counter = parseInt(result.code) + 1; let counter = parseInt(result.code, 10) + 1;
counter = String(counter).padStart(3, '0'); counter = String(counter).padStart(3, '0');
code = `${prefix}${counter}`; code = `${prefix}${counter}`;
} else { } else {
@@ -551,6 +713,16 @@ const updateIntoReserve = async (trx, dataReserve, reserveNo) => {
return result; return result;
}; };
const updateIntoReserveBulk = async (trx, dataReserve, reserveNos) => {
if (!Array.isArray(reserveNos) || reserveNos.length === 0) {
return 0;
}
return trx('trx.t_d_reservation_balance')
.whereIn('c_reservation_no', reserveNos)
.update(dataReserve);
};
const updateIntoSalesKMT = async (trx, dataSales, salesNo) => { const updateIntoSalesKMT = async (trx, dataSales, salesNo) => {
let result = await trx('kmt_mobile.t_d_sales_kmt_mobile') let result = await trx('kmt_mobile.t_d_sales_kmt_mobile')
.update(dataSales, ['*']) .update(dataSales, ['*'])
@@ -558,11 +730,67 @@ const updateIntoSalesKMT = async (trx, dataSales, salesNo) => {
return result; return result;
}; };
const updateIntoSalesKMTBulk = async (trx, dataSales, salesNos) => {
if (!Array.isArray(salesNos) || salesNos.length === 0) {
return 0;
}
return trx('kmt_mobile.t_d_sales_kmt_mobile')
.whereIn('c_sales_no', salesNos)
.update(dataSales);
};
const updateIntoSalesInternal = async (trx, dataSales, salesNo) => {
let result = await trx('trx.t_d_sales_internal')
.update(dataSales, ['*'])
.where({ c_sales_no: salesNo });
return result;
};
const updateIntoSalesInternalBulk = async (trx, dataSales, salesNos) => {
if (!Array.isArray(salesNos) || salesNos.length === 0) {
return 0;
}
return trx('trx.t_d_sales_internal')
.whereIn('c_sales_no', salesNos)
.update(dataSales);
};
const updateIntoTopUpCashlessInternal = async (trx, dataTopup, topupNo) => {
let result = await trx('trx.t_d_topup_cashless_internal')
.update(dataTopup, ['*'])
.where({ c_topup_no: topupNo });
return result;
};
const updateIntoTopUpCashlessInternalBulk = async (
trx,
dataTopup,
topupNos
) => {
if (!Array.isArray(topupNos) || topupNos.length === 0) {
return 0;
}
return trx('trx.t_d_topup_cashless_internal')
.whereIn('c_topup_no', topupNos)
.update(dataTopup);
};
const insertCashIn = async (trx, data) => { const insertCashIn = async (trx, data) => {
let result = await trx('payment.t_d_cash_in').insert(data, ['*']); let result = await trx('payment.t_d_cash_in').insert(data, ['*']);
return result[0]; return result[0];
}; };
const insertCashInDetailBulk = async (trx, data) => {
if (!Array.isArray(data) || data.length === 0) {
return 0;
}
return trx('payment.t_d_cash_in_detail').insert(data);
};
const writePaynentHistory = async (data, message, i_log_name, trx) => { const writePaynentHistory = async (data, message, i_log_name, trx) => {
console.log(data); console.log(data);
const result = await trx('log.t_log_invoice').insert( const result = await trx('log.t_log_invoice').insert(
@@ -598,9 +826,20 @@ module.exports = {
insertCashInDetail, insertCashInDetail,
getPartnerRecon, getPartnerRecon,
getPartnerReconSales, getPartnerReconSales,
getPartnerReconSalesInternal,
getPartnerReconTopUpCashlessInternal,
getReserve, getReserve,
getSalesKMT, getSalesKMT,
getSalesInternal,
getTopUpCashlessInternal,
insertCashIn, insertCashIn,
insertCashInDetailBulk,
updateIntoReserve, updateIntoReserve,
updateIntoSalesKMT updateIntoReserveBulk,
updateIntoSalesKMT,
updateIntoSalesKMTBulk,
updateIntoSalesInternal,
updateIntoSalesInternalBulk,
updateIntoTopUpCashlessInternal,
updateIntoTopUpCashlessInternalBulk,
}; };
@@ -53,6 +53,10 @@ const apiGenerateInvoice = async (req, res) => {
`${uniqueCode} REQUEST generate invoice: ${JSON.stringify(req.body)}` `${uniqueCode} REQUEST generate invoice: ${JSON.stringify(req.body)}`
); );
const schedulerCode = 'GENERATEINVOICEONLINETOPUP';
const startData = await helper.startScheduler(schedulerCode);
const token = startData.c_execution_token ?? null;
// check validator // check validator
let err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
@@ -81,10 +85,12 @@ const apiGenerateInvoice = async (req, res) => {
result = { result = {
code: '200', code: '200',
message: 'Succes posting', message: 'Succes generate invoice online topup',
data: invoice, data: invoice,
}; };
const finishData = await helper.finishScheduler(token, schedulerCode);
return res.status(200).json(result); return res.status(200).json(result);
} catch (error) { } catch (error) {
// create log // create log
@@ -115,6 +121,10 @@ const apiPostingInvoice = async (req, res) => {
`${uniqueCode} REQUEST posting invoice: ${JSON.stringify(req.body)}` `${uniqueCode} REQUEST posting invoice: ${JSON.stringify(req.body)}`
); );
const schedulerCode = 'POSTINGINVOICEONLINETOPUP';
const startData = await helper.startScheduler(schedulerCode);
const token = startData.c_execution_token ?? null;
// check validator // check validator
let err = validationResult(req, res); let err = validationResult(req, res);
if (!err.isEmpty()) { if (!err.isEmpty()) {
@@ -143,6 +153,8 @@ const apiPostingInvoice = async (req, res) => {
data: invoice, data: invoice,
}; };
const finishData = await helper.finishScheduler(token, schedulerCode);
return res.status(200).json(result); return res.status(200).json(result);
} catch (error) { } catch (error) {
// create log // create log
+253 -112
View File
@@ -2,9 +2,9 @@
// GET PARTNER, MERCHANT, TERMINAL FROM TID // GET PARTNER, MERCHANT, TERMINAL FROM TID
const generateInvoice = async (invoiceDate, repost, trx) => { const generateInvoice = async (invoiceDate, repost, trx) => {
let result = await trx.select(trx.raw(`* FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`)) let result = await trx.raw(`SELECT * FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`)
return result; return result.rows || result;
} }
@@ -26,26 +26,30 @@ const insertPostingEt = async (invoice, trx) => {
reference: invoice.c_invoice_no, reference: invoice.c_invoice_no,
amount: invoice.amount, amount: invoice.amount,
ba: invoice.ba, ba: invoice.ba,
indeks: (index+1), indeks: (index + 1),
totalidx: type.length, totalidx: type.length,
doc_header_text: invoice.c_invoice_no, doc_header_text: invoice.c_invoice_no,
pos_status : 3 pos_status: 3
} }
if(item == 'H'){ if (item == 'H') {
data = {...data, ...{ data = {
...data, ...{
text: `Posting Invoice CMS ${invoice.c_invoice_no}`, text: `Posting Invoice CMS ${invoice.c_invoice_no}`,
debit_kredit: item, debit_kredit: item,
account: invoice.c_account_topup, account: invoice.c_account_topup,
customer: null customer: null
}} }
}else{ }
data = {...data, ...{ } else {
data = {
...data, ...{
text: `Posting Invoice CMS ${invoice.c_invoice_no}`, text: `Posting Invoice CMS ${invoice.c_invoice_no}`,
debit_kredit: item, debit_kredit: item,
account: null, account: null,
customer: invoice.c_account_code_topup customer: invoice.c_account_code_topup
}} }
}
} }
et.push(data) et.push(data)
@@ -58,30 +62,117 @@ const insertPostingEt = async (invoice, trx) => {
} }
const getPostingEt = async(trx) => { const getPostingEt = async (trx) => {
const result = await trx('public.posting_et AS pe').select([ const result = await trx.raw(`
'doc_header_text', WITH params AS (
'ba',
'doc_date',
'posting_date',
'fiscal_year',
trx.raw(`TO_CHAR(doc_date::DATE, 'MM') AS fis_period`),
'doc_type',
'reference',
'tcode',
'amount',
trx.raw(`'IDR' AS currency`),
trx.raw(`(select pe2.customer from posting_et pe2 where pe2.reference = pe.reference and debit_kredit = 'S' LIMIT 1) as customer`),
trx.raw(`(select pe2.account from posting_et pe2 where pe2.reference = pe.reference and debit_kredit = 'H' LIMIT 1) as account`),
trx.raw(`(select pe2.text from posting_et pe2 where pe2.reference = pe.reference and debit_kredit = 'S' LIMIT 1) as text1`),
trx.raw(`(select pe2.text from posting_et pe2 where pe2.reference = pe.reference and debit_kredit = 'H' LIMIT 1) as text2`),
])
.where('tcode', '=', "FB70")
.whereIn('pos_status', ["3"])
.groupBy([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 12])
return result SELECT
EXTRACT(YEAR FROM CURRENT_DATE)::TEXT AS curr_year,
EXTRACT(YEAR FROM CURRENT_DATE - INTERVAL '1 year')::TEXT AS prev_year,
TO_CHAR(CURRENT_DATE, 'MM') AS curr_month
),
base AS (
SELECT
pe.doc_header_text,
pe.ba,
pe.doc_date,
pe.posting_date,
pe.fiscal_year,
TO_CHAR(pe.doc_date::DATE, 'MM') AS fis_period,
pe.doc_type,
pe.reference,
pe.tcode,
pe.amount,
pe.customer,
pe.account,
pe.text,
pe.debit_kredit
FROM public.posting_et pe
CROSS JOIN params p
WHERE
pe.tcode = 'FB70'
AND pe.pos_status = '3'
-- Prefix search still index friendly
AND pe.doc_header_text LIKE 'INV%'
AND (
-- Current year all months
pe.fiscal_year = p.curr_year
OR (
-- Previous year December only
-- only when current month is January
p.curr_month = '01'
AND pe.fiscal_year = p.prev_year
AND TO_CHAR(pe.doc_date::DATE, 'MM') = '12'
)
)
)
SELECT
b.doc_header_text,
b.ba,
b.doc_date,
b.posting_date,
b.fiscal_year,
b.fis_period,
b.doc_type,
b.reference,
b.tcode,
b.amount,
'IDR'::VARCHAR AS currency,
MAX(b.customer) FILTER (
WHERE b.debit_kredit = 'S'
) AS customer,
MAX(b.account) FILTER (
WHERE b.debit_kredit = 'H'
) AS account,
MAX(b.text) FILTER (
WHERE b.debit_kredit = 'S'
) AS text1,
MAX(b.text) FILTER (
WHERE b.debit_kredit = 'H'
) AS text2
FROM base b
GROUP BY
b.doc_header_text,
b.ba,
b.doc_date,
b.posting_date,
b.fiscal_year,
b.fis_period,
b.doc_type,
b.reference,
b.tcode,
b.amount
ORDER BY
b.fiscal_year,
b.doc_date,
b.reference
`);
return result.rows || result
} }
@@ -89,98 +180,148 @@ const setReturnSAP = async (invoice, resSAP, trx, posting = false, c_invoice_no
let t_invoice = {} let t_invoice = {}
let t_load_balance = {} let t_load_balance = {}
let posting_et = {} let posting_et = {}
if(resSAP.type == 'S'){ const paymentRequestSql = `
SELECT c_load_balance_no
FROM payment.t_d_payment_request_topup_online
WHERE c_payment = ?
`;
if (resSAP.type == 'S') {
// update invoice // update invoice
t_invoice = await trx('payment.t_d_invoice').update({ t_invoice = await trx.raw(
c_return_sap: resSAP.data.E_DOCUMENTNUMBER `
}, ["*"]) UPDATE payment.t_d_invoice
.where({ SET c_return_sap = ?
c_invoice_no: c_invoice_no WHERE c_invoice_no = ?
}); RETURNING *
`,
[resSAP.data.E_DOCUMENTNUMBER, c_invoice_no]
);
// update load balance // update load balance
t_load_balance = await trx('trx.t_d_load_balance').update({ t_load_balance = await trx.raw(
c_return_sap: resSAP.data.E_DOCUMENTNUMBER `
}, ['c_load_balance_no', 'c_return_sap']) UPDATE trx.t_d_load_balance
.whereRaw(`c_load_balance_no IN (SELECT c_load_balance_no FROM payment.t_d_payment_request_topup_online WHERE c_payment = '${c_invoice_no}')`) SET c_return_sap = ?
WHERE c_load_balance_no IN (
${paymentRequestSql}
)
RETURNING c_load_balance_no, c_return_sap
`,
[resSAP.data.E_DOCUMENTNUMBER, c_invoice_no]
);
posting_et = await trx('public.posting_et').update({ posting_et = await trx.raw(
pos_status : 0, `
status0 : resSAP.type, UPDATE public.posting_et
no_doksap : resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null, SET pos_status = 0,
status1 : resSAP.message ? resSAP.message : null status0 = ?,
}, ['file_name','status0']).where({ no_doksap = ?,
reference: c_invoice_no status1 = ?
}) WHERE no_dok = ?
RETURNING file_name, status0
`,
[
resSAP.type,
resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null,
resSAP.message ? resSAP.message : null,
c_invoice_no
]
);
if(posting) { if (posting) {
await writePaynentHistory(t_invoice[0], "SUCCESSFULLY", 102, trx) await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], "SUCCESSFULLY", 102, trx)
} else { } else {
await writePaynentHistory(t_invoice[0], "SUCCESS TO RETRY SAP", 118, trx) await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], "SUCCESS TO RETRY SAP", 118, trx)
} }
}else { } else {
let text = resSAP.message; let text = resSAP.message;
let result = text.toUpperCase(); let result = text.toUpperCase();
if(result.includes("ALREADY")){ if (result.includes("ALREADY")) {
let result = text.toUpperCase().split('-'); let result = text.toUpperCase().split('-');
let doc_number = result[1].trim().split(" ")[0] let doc_number = result[1].trim().split(" ")[0]
// update invoice
const d = new Date();
let year = d.getFullYear();
posting_et = await trx('public.posting_et').update({ posting_et = await trx.raw(
pos_status : 0, `
status0 : 'S', UPDATE public.posting_et
no_doksap : doc_number, SET pos_status = 0,
status1 : resSAP.message ? resSAP.message : null status0 = 'S',
}, ['file_name','status0']).where({ no_doksap = ?,
reference: c_invoice_no status1 = ?
}) WHERE no_dok = ?
RETURNING file_name, status0
`,
[doc_number, resSAP.message ? resSAP.message : null, c_invoice_no]
);
// update invoice // update invoice
t_invoice = await trx('payment.t_d_invoice').update({ t_invoice = await trx.raw(
c_return_sap: doc_number `
}, ['*']) UPDATE payment.t_d_invoice
.where({ SET c_return_sap = ?
c_invoice_no: c_invoice_no WHERE c_invoice_no = ?
}); RETURNING *
`,
[doc_number, c_invoice_no]
);
// update load balance // update load balance
t_load_balance = await trx('trx.t_d_load_balance').update({ t_load_balance = await trx.raw(
c_return_sap: doc_number `
}, ['c_load_balance_no', 'c_return_sap']) UPDATE trx.t_d_load_balance
.whereRaw(`c_load_balance_no IN (SELECT c_load_balance_no FROM payment.t_d_payment_request_topup_online WHERE c_payment = '${c_invoice_no}')`) SET c_return_sap = ?
WHERE c_load_balance_no IN (
${paymentRequestSql}
)
RETURNING c_load_balance_no, c_return_sap
`,
[doc_number, c_invoice_no]
);
if(posting) { if (posting) {
await writePaynentHistory(t_invoice[0], "SUCCESSFULLY", 102, trx) await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], "SUCCESSFULLY", 102, trx)
} else { } else {
await writePaynentHistory(t_invoice[0], "SUCCESS TO RETRY SAP", 118, trx) await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], "SUCCESS TO RETRY SAP", 118, trx)
} }
}else{ } else {
// update posting et // update posting et
posting_et = await trx('public.posting_et').update({ posting_et = await trx.raw(
pos_status : resSAP.type == 'S' ? 0 : 3, `
status0 : resSAP.type, UPDATE public.posting_et
no_doksap : resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null, SET pos_status = ?,
status1 : resSAP.message ? resSAP.message : null status0 = ?,
}, ['file_name','status0']).where({ no_doksap = ?,
reference: c_invoice_no status1 = ?
}) WHERE no_dok = ?
RETURNING file_name, status0
`,
[
resSAP.type == 'S' ? 0 : 3,
resSAP.type,
resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null,
resSAP.message ? resSAP.message : null,
c_invoice_no
]
);
// update invoice // update invoice
t_invoice = await trx('payment.t_d_invoice').select(['*']) t_invoice = await trx.raw(
.where({ `
c_invoice_no: c_invoice_no SELECT *
}); FROM payment.t_d_invoice
WHERE c_invoice_no = ?
`,
[c_invoice_no]
);
if(posting) { if (posting) {
await writePaynentHistory(t_invoice[0], `SUCCESS WITH SAP ERR: ${resSAP.message}`,102, trx) await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], `SUCCESS WITH SAP ERR: ${resSAP.message}`, 102, trx)
} else { } else {
await writePaynentHistory(t_invoice[0], `FAIL TO RETRY WITH SAP ERR: ${resSAP.message}`,118, trx) await writePaynentHistory(t_invoice.rows?.[0] || t_invoice[0], `FAIL TO RETRY WITH SAP ERR: ${resSAP.message}`, 118, trx)
} }
} }
@@ -190,9 +331,9 @@ const setReturnSAP = async (invoice, resSAP, trx, posting = false, c_invoice_no
// update posting et // update posting et
return { return {
invoice : t_invoice, invoice: t_invoice.rows || t_invoice,
load_balance : t_load_balance, load_balance: t_load_balance.rows || t_load_balance,
posting_et : posting_et posting_et: posting_et.rows || posting_et
} }
} }
@@ -201,18 +342,18 @@ const writePaynentHistory = async (data, message, i_log_name, trx) => {
console.log(data) console.log(data)
const result = await trx('log.t_log_invoice').insert({ const result = await trx('log.t_log_invoice').insert({
// i_log_name : 102, // i_log_name : 102,
i_log_name : i_log_name, i_log_name: i_log_name,
d_log : trx.raw('NOW()'), d_log: trx.raw('NOW()'),
c_invoice_no : data?.c_invoice_no || '', c_invoice_no: data?.c_invoice_no || '',
c_partner_name : data?.c_partner_name || '', c_partner_name: data?.c_partner_name || '',
j_new_data : JSON.stringify(data), j_new_data: JSON.stringify(data),
d_payment_date: trx.raw('NOW()'), d_payment_date: trx.raw('NOW()'),
c_note : message, c_note: message,
c_status : 'S', c_status: 'S',
d_created : trx.raw('NOW()'), d_created: trx.raw('NOW()'),
m_amount : data?.amount || 0, m_amount: data?.amount || 0,
m_mdr_amount : 0, m_mdr_amount: 0,
m_mdr_net : data?.amount || 0 m_mdr_net: data?.amount || 0
}, ['i_log_name', 'c_note']) }, ['i_log_name', 'c_note'])
@@ -220,7 +361,7 @@ const writePaynentHistory = async (data, message, i_log_name, trx) => {
} }
const getParameterSetting = async(trx, code) => { const getParameterSetting = async (trx, code) => {
const result = await trx('public.t_m_global_parameter_sap AS tmgps').select([ const result = await trx('public.t_m_global_parameter_sap AS tmgps').select([
"c_value" "c_value"
@@ -233,7 +374,7 @@ const getParameterSetting = async(trx, code) => {
} }
const getInvoice = async(code, trx) => { const getInvoice = async (code, trx) => {
const result = await trx('payment.t_d_invoice') const result = await trx('payment.t_d_invoice')
.where('c_invoice_no', '=', code) .where('c_invoice_no', '=', code)
@@ -2,9 +2,11 @@
// GET PARTNER, MERCHANT, TERMINAL FROM TID // GET PARTNER, MERCHANT, TERMINAL FROM TID
const generateInvoice = async (invoiceDate, repost, trx) => { const generateInvoice = async (invoiceDate, repost, trx) => {
let result = await trx.select(trx.raw(`* FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`)) let result = await trx.raw(
`SELECT * FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`
)
return result; return result.rows || result;
} }
@@ -6,6 +6,7 @@ const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const moment = require('moment'); const moment = require('moment');
const { const {
setLoadBalanceNumberSequence, setLoadBalanceNumberSequence,
getLoadBalanceNumberSequence2,
} = require('../../middlewares/redis.middleware'); } = require('../../middlewares/redis.middleware');
moment.locale('id'); moment.locale('id');
@@ -68,8 +69,9 @@ const generateLoadBalanceNumber = async (data, date, counter) => {
// insert to temp load balance number // insert to temp load balance number
let insert = await model.insertLoadBalanceNumber(loadBalanceNumber); let insert = await model.insertLoadBalanceNumber(loadBalanceNumber);
// console.log("DEBUGING insert", insert)
if (insert.rowCount < 1) { if (insert.rowCount < 1) {
loadBalanceNumber = 'XX'; loadBalanceNumber = 'DUPLICATE';
} }
return loadBalanceNumber; return loadBalanceNumber;
}; };
@@ -179,7 +181,7 @@ const updateAllTransaction = async (
); );
// update reservation and load balance transaction // update reservation and load balance transaction
await model.updateReservationAndLoadingBalance( const update = await model.updateReservationAndLoadingBalance(
reservationNumber, reservationNumber,
data, data,
dataLoadingBalanceDetail, dataLoadingBalanceDetail,
@@ -187,6 +189,7 @@ const updateAllTransaction = async (
flag flag
); );
if (update) {
// log debug // log debug
winston.logger.debug(`${uniqueCode} inserting log for card history...`); winston.logger.debug(`${uniqueCode} inserting log for card history...`);
@@ -214,6 +217,9 @@ const updateAllTransaction = async (
}); });
return true; return true;
} else {
return false;
}
} else { } else {
// insert new load balance transaction by data on card and update data reservation // insert new load balance transaction by data on card and update data reservation
@@ -264,7 +270,7 @@ const updateAllTransaction = async (
loadBalanceNoSequence loadBalanceNoSequence
); );
if (newLoadBalanceNumber != 'XX') { if (newLoadBalanceNumber != 'DUPLICATE') {
// set sequence to redis // set sequence to redis
// await setLoadBalanceNumberSequence( // await setLoadBalanceNumberSequence(
// req.partner_id_token, // req.partner_id_token,
@@ -287,7 +293,7 @@ const updateAllTransaction = async (
} }
maxLoop++; maxLoop++;
} while (newLoadBalanceNumber == 'XX'); } while (newLoadBalanceNumber == 'DUPLICATE');
let dataLoadBalance = { let dataLoadBalance = {
c_load_balance_no: newLoadBalanceNumber, c_load_balance_no: newLoadBalanceNumber,
@@ -424,7 +430,15 @@ const updateAllTransaction = async (
const loadingBalanceRequest = async (req, res) => { const loadingBalanceRequest = async (req, res) => {
try { try {
// param // param
let { mid, tid, card_number, uid, balance, flag, unique_code } = req.body; // let { mid, tid, card_number, uid, balance, flag, unique_code } = req.body;
let mid = req.body.mid;
let tid = req.body.tid;
let card_number = req.body.card_number;
let uid = req.body.uid;
let balance = req.body.balance;
let flag = req.body.flag;
let unique_code = req.body.unique_code;
// uniqueCode = await helper.getUniqueCode(); // uniqueCode = await helper.getUniqueCode();
let uniqueCode = unique_code; let uniqueCode = unique_code;
@@ -704,9 +718,45 @@ const loadingBalanceRequest = async (req, res) => {
// let getReservationPendingWithFlag = // let getReservationPendingWithFlag =
// await model.getReservationPendingWithFlag(card_number, now); // await model.getReservationPendingWithFlag(card_number, now);
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG X ]: ${JSON.stringify(
getReservationPendingWithFlagCounter
)}`
);
// winston.logger.warn(
// `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 1.1 ]: ${JSON.stringify(
// getReservationPending
// )}`
// );
// winston.logger.warn(
// `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 2 ]: ${JSON.stringify(req.body)}`
// );
// winston.logger.warn(
// `${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG 2.1 ]: ${flag}`
// );
if (getReservationPendingWithFlagCounter.length > 0) { if (getReservationPendingWithFlagCounter.length > 0) {
if (lastFlag) { if (lastFlag) {
if (parseInt(lastFlag) <= parseInt(flag)) {
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG Y ]: ${card_number}`
);
// manipulasi last flag jika flag kartu sudah kembali ke 0
if (parseInt(lastFlag) == 255 && parseInt(flag) == 0) {
lastFlag = -1
}
if (parseInt(lastFlag) < parseInt(flag)) {
winston.logger.warn(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-REQUEST DEBUG Z ]: ${card_number}`
);
let reservationNumberPendingSuccessLoaded = []; let reservationNumberPendingSuccessLoaded = [];
let loadBalanceNumberPendingSuccessLoaded = []; let loadBalanceNumberPendingSuccessLoaded = [];
let totalReservationAmount = 0; let totalReservationAmount = 0;
@@ -1470,8 +1520,81 @@ const loadingBalanceInsert = async (req, param) => {
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting loading balance sequence...` // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: getting loading balance sequence...`
// ); // );
// Pindah ke bawah (nested if condition)
// if (!loadBalanceNoSequence) {
// // get loading balance
// getLoadBalanceSequence = await model.getLoadBalanceSequence(
// getPartner,
// today
// );
// loadBalanceNoSequence = getLoadBalanceSequence
// ? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1
// : 1;
// }
let maxLoop = 0;
// do {
// // await _sleep(helper.randomNumberInt());
// console.log("DEBUGING loadBalanceNoSequence", loadBalanceNoSequence)
// if (maxLoop > 0) {
// loadBalanceNoSequence++;
// }
// // set sequence to redis
// await setLoadBalanceNumberSequence(
// req.partner_id_token,
// loadBalanceNoSequence
// );
// // log warn
// // winston.logger.warn(
// // `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: generating load balance number...`
// // );
// loadBalanceNumber = await generateLoadBalanceNumber(
// getPartner,
// moment(today).format('YYMMDD'),
// loadBalanceNoSequence
// );
// // if (loadBalanceNumber != 'XX') {
// // set sequence to redis
// // await setLoadBalanceNumberSequence(
// // req.partner_id_token,
// // loadBalanceNoSequence
// // );
// // }
// // log warn
// winston.logger.debug(
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: load balance number sequence is ${loadBalanceNoSequence}.`
// );
// if (maxLoop > maxLoopParameter) {
// // create log
// winston.logger.error(
// `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: 500 internal server error. Server is busy. please try again`
// );
// return {
// code: '500',
// message:
// process.env.NODE_ENV != 'production'
// ? '500 internal server error (max loop) - backend server.'
// : '500 internal server error (max loop) - backend server.',
// data: {},
// };
// }
// maxLoop++;
// } while (loadBalanceNumber == 'XX');
//================== Start nested if condition ====================
loadBalanceNoSequence = await getLoadBalanceNumberSequence2(req);
console.log('DEBUGING loadBalanceNoSequence START', loadBalanceNoSequence);
if (!loadBalanceNoSequence) { if (!loadBalanceNoSequence) {
// get loading balance
getLoadBalanceSequence = await model.getLoadBalanceSequence( getLoadBalanceSequence = await model.getLoadBalanceSequence(
getPartner, getPartner,
today today
@@ -1479,65 +1602,130 @@ const loadingBalanceInsert = async (req, param) => {
loadBalanceNoSequence = getLoadBalanceSequence loadBalanceNoSequence = getLoadBalanceSequence
? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1 ? parseInt(getLoadBalanceSequence.i_load_balance_no_seq) + 1
: 1; : 1;
}
let maxLoop = 0;
do {
// await _sleep(helper.randomNumberInt());
if (maxLoop > 0) {
loadBalanceNoSequence++;
}
// set sequence to redis
await setLoadBalanceNumberSequence( await setLoadBalanceNumberSequence(
req.partner_id_token, req.partner_id_token,
loadBalanceNoSequence + 1
);
console.log(
'Masuk kondisi !loadBalanceNoSequence',
loadBalanceNoSequence loadBalanceNoSequence
); );
}
// log warn // Percobaan 1
// winston.logger.warn(
// `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: generating load balance number...`
// );
loadBalanceNumber = await generateLoadBalanceNumber( loadBalanceNumber = await generateLoadBalanceNumber(
getPartner, getPartner,
moment(today).format('YYMMDD'), moment(today).format('YYMMDD'),
loadBalanceNoSequence loadBalanceNoSequence
); );
// log warn
winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT Percobaan 1 ]: load balance number sequence is ${loadBalanceNoSequence}.`
);
console.log('DEBUGING loadBalanceNumber PERCOBAAN 1', loadBalanceNumber);
// if (loadBalanceNumber != 'XX') { if (loadBalanceNumber == 'DUPLICATE') {
// set sequence to redis loadBalanceNoSequence = await getLoadBalanceNumberSequence2(req);
// await setLoadBalanceNumberSequence( console.log(
// req.partner_id_token, 'DEBUGING loadBalanceNoSequence PERCOBAAN 2',
// loadBalanceNoSequence loadBalanceNoSequence
// ); );
// } // Percobaan 2
loadBalanceNumber = await generateLoadBalanceNumber(
getPartner,
moment(today).format('YYMMDD'),
loadBalanceNoSequence
);
// log warn
winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT Percobaan 2 ]: load balance number sequence is ${loadBalanceNoSequence}.`
);
console.log('DEBUGING loadBalanceNumber PERCOBAAN 2', loadBalanceNumber);
if (loadBalanceNumber == 'DUPLICATE') {
loadBalanceNoSequence = await getLoadBalanceNumberSequence2(req);
console.log(
'DEBUGING loadBalanceNoSequence PERCOBAAN 3',
loadBalanceNoSequence
);
// Percobaan 3
loadBalanceNumber = await generateLoadBalanceNumber(
getPartner,
moment(today).format('YYMMDD'),
loadBalanceNoSequence
);
// log warn
winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT Percobaan 3 ]: load balance number sequence is ${loadBalanceNoSequence}.`
);
console.log(
'DEBUGING loadBalanceNumber PERCOBAAN 3',
loadBalanceNumber
);
if (loadBalanceNumber == 'DUPLICATE') {
loadBalanceNoSequence = await getLoadBalanceNumberSequence2(req);
console.log(
'DEBUGING loadBalanceNoSequence PERCOBAAN 4',
loadBalanceNoSequence
);
// Percobaan 4
loadBalanceNumber = await generateLoadBalanceNumber(
getPartner,
moment(today).format('YYMMDD'),
loadBalanceNoSequence
);
// log warn
winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT Percobaan 4 ]: load balance number sequence is ${loadBalanceNoSequence}.`
);
console.log(
'DEBUGING loadBalanceNumber PERCOBAAN 4',
loadBalanceNumber
);
if (loadBalanceNumber == 'DUPLICATE') {
loadBalanceNoSequence = await getLoadBalanceNumberSequence2(req);
console.log(
'DEBUGING loadBalanceNoSequence PERCOBAAN 5',
loadBalanceNoSequence
);
// Percobaan 5
loadBalanceNumber = await generateLoadBalanceNumber(
getPartner,
moment(today).format('YYMMDD'),
loadBalanceNoSequence
);
// log warn
winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT Percobaan 5 ]: load balance number sequence is ${loadBalanceNoSequence}.`
);
console.log(
'DEBUGING loadBalanceNumber PERCOBAAN 5',
loadBalanceNumber
);
if (loadBalanceNumber == 'DUPLICATE') {
// log warn // log warn
winston.logger.debug( winston.logger.debug(
`${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: load balance number sequence is ${loadBalanceNoSequence}.` `${uniqueCode} [ PROCESSING LOADING-BALANCE-INSERT ]: load balance number sequence is ${loadBalanceNoSequence}.`
); );
if (maxLoop > maxLoopParameter) {
// create log // create log
winston.logger.error( winston.logger.error(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: 500 internal server error. Server is busy. please try again` `${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: 505 internal server error. Server is busy. please try again`
); );
return { return {
code: '500', code: '505',
message: message:
process.env.NODE_ENV != 'production' process.env.NODE_ENV != 'production'
? '500 internal server error (max loop) - backend server.' ? '505 internal server error (max loop) - backend server.'
: '500 internal server error (max loop) - backend server.', : '505 Server is busy. please try again.',
data: {}, data: {},
}; };
} }
}
}
}
}
maxLoop++; //================== End nested if condition ====================
} while (loadBalanceNumber == 'XX');
let data = { let data = {
c_load_balance_no: loadBalanceNumber, c_load_balance_no: loadBalanceNumber,
d_load_balance: now, d_load_balance: now,
@@ -1681,6 +1869,8 @@ const loadingBalanceInsert = async (req, param) => {
// balance // balance
// )} [FLAG] : ${JSON.stringify(flag)}` // )} [FLAG] : ${JSON.stringify(flag)}`
// ); // );
console.log("MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMM");
console.log(insertLoadingBalance);
if (insertLoadingBalance > 0) { if (insertLoadingBalance > 0) {
result = { result = {
@@ -1960,7 +2150,7 @@ const loadingBalanceUpdate = async (param) => {
// log info // log info
winston.logger.info( winston.logger.info(
`${uniqueCode} [ RESPONSE LOADING-BALANCE-INSERT ]: ${JSON.stringify( `${uniqueCode} [ RESPONSE LOADING-BALANCE-UPDATE ]: ${JSON.stringify(
result result
)}` )}`
); );
@@ -1,4 +1,5 @@
const knex = require('../../../infrastructure/database/knex'); const knex = require('../../../infrastructure/database/knex');
const winston = require('../../helpers/winston.logger');
// CHECK CARD NUMBER // CHECK CARD NUMBER
const checkCardNumber = (cardNumber) => { const checkCardNumber = (cardNumber) => {
@@ -107,7 +108,14 @@ const getReservationPendingV2 = (cardNumber, time, flag) => {
.whereIn('c_status', ['P', 'I']) .whereIn('c_status', ['P', 'I'])
// .where("d_expired", ">=", time) // .where("d_expired", ">=", time)
.whereRaw( .whereRaw(
`c_reservation_no NOT IN (SELECT c_reservation_no FROM trx.t_d_fraud tdf WHERE tdf.c_status = 'A' AND tdf.c_card_number = '${cardNumber}')` `NOT EXISTS (
SELECT 1
FROM trx.t_d_fraud tdf
WHERE tdf.c_reservation_no = trx.t_d_reservation_balance.c_reservation_no
AND tdf.c_status = 'A'
AND tdf.c_card_number = ?
)`,
[cardNumber]
) )
.where(function () { .where(function () {
this.orWhere('c_flag', flag).orWhere('c_flag', '-1'); this.orWhere('c_flag', flag).orWhere('c_flag', '-1');
@@ -118,7 +126,24 @@ const getReservationPendingV2 = (cardNumber, time, flag) => {
// GET RESERVATION PENDING WITH COMPARE FLAG COUNTER // GET RESERVATION PENDING WITH COMPARE FLAG COUNTER
const getReservationPendingWithFlagCounter = (cardNumber, time, flag) => { const getReservationPendingWithFlagCounter = (cardNumber, time, flag) => {
let result = knex('trx.t_d_reservation_balance') let result
if (flag == '0' || flag == 0) {
result = knex('trx.t_d_reservation_balance')
// .sum("i_reservation_amount as total_reservation_amount")
// .count("* as total_reservation")
.select(
'i_reservation_amount',
'c_reservation_no',
'c_flag',
'c_load_balance_no'
)
.where('c_card_number', cardNumber)
.whereIn('c_status', ['P', 'I'])
.whereRaw('??::INT <= ??', ['c_flag', parseInt(255)])
// .where("d_expired", ">=", time)
.where('c_flag', '!=', '-1');
} else {
result = knex('trx.t_d_reservation_balance')
// .sum("i_reservation_amount as total_reservation_amount") // .sum("i_reservation_amount as total_reservation_amount")
// .count("* as total_reservation") // .count("* as total_reservation")
.select( .select(
@@ -132,6 +157,8 @@ const getReservationPendingWithFlagCounter = (cardNumber, time, flag) => {
.whereRaw('??::INT < ??', ['c_flag', parseInt(flag)]) .whereRaw('??::INT < ??', ['c_flag', parseInt(flag)])
// .where("d_expired", ">=", time) // .where("d_expired", ">=", time)
.where('c_flag', '!=', '-1'); .where('c_flag', '!=', '-1');
}
return result; return result;
}; };
@@ -150,7 +177,14 @@ const getReservationPendingWithFlagCounterV2 = (cardNumber, time, flag) => {
.whereIn('c_status', ['P', 'I']) .whereIn('c_status', ['P', 'I'])
.whereRaw('??::INT < ??', ['c_flag', parseInt(flag)]) .whereRaw('??::INT < ??', ['c_flag', parseInt(flag)])
.whereRaw( .whereRaw(
`c_reservation_no NOT IN (SELECT c_reservation_no FROM trx.t_d_fraud tdf WHERE tdf.c_status = 'A' AND tdf.c_card_number = '${cardNumber}')` `NOT EXISTS (
SELECT 1
FROM trx.t_d_fraud tdf
WHERE tdf.c_reservation_no = trx.t_d_reservation_balance.c_reservation_no
AND tdf.c_status = 'A'
AND tdf.c_card_number = ?
)`,
[cardNumber]
) )
// .where("d_expired", ">=", time) // .where("d_expired", ">=", time)
.where('c_flag', '!=', '-1'); .where('c_flag', '!=', '-1');
@@ -178,7 +212,14 @@ const getReservationPendingWithFlagV2 = (cardNumber, time) => {
.where('c_card_number', cardNumber) .where('c_card_number', cardNumber)
.whereIn('c_status', ['P', 'I']) .whereIn('c_status', ['P', 'I'])
.whereRaw( .whereRaw(
`c_reservation_no NOT IN (SELECT c_reservation_no FROM trx.t_d_fraud tdf WHERE tdf.c_status = 'A' AND tdf.c_card_number = '${cardNumber}')` `NOT EXISTS (
SELECT 1
FROM trx.t_d_fraud tdf
WHERE tdf.c_reservation_no = trx.t_d_reservation_balance.c_reservation_no
AND tdf.c_status = 'A'
AND tdf.c_card_number = ?
)`,
[cardNumber]
) )
.whereNotNull('c_flag_code'); .whereNotNull('c_flag_code');
return result; return result;
@@ -300,11 +341,11 @@ const insertLoadingBalance = async (
.insert(data) .insert(data)
.returning('i_load_balance') .returning('i_load_balance')
.then((resp) => { .then((resp) => {
let id = resp[0]; let id = typeof resp[0] === 'object' ? resp[0].i_load_balance : resp[0];
let loadDetail = []; let loadDetail = [];
detail.forEach((element) => { detail.forEach((element) => {
loadDetail.push({ loadDetail.push({
i_load_balance: id, i_load_balance: id ? id : id.i_load_balance,
i_reservation_balance: element.i_reservation_balance, i_reservation_balance: element.i_reservation_balance,
c_reservation_no: element.c_reservation_no, c_reservation_no: element.c_reservation_no,
i_amount: element.i_amount, i_amount: element.i_amount,
@@ -332,11 +373,11 @@ const insertLoadingBalance = async (
.insert(data); .insert(data);
}) })
.then((history) => { .then((history) => {
let id = history[0]; let id = typeof history[0] === 'object' ? history[0].i_load_balance : history[0];
let loadDetail = []; let loadDetail = [];
detail.forEach((element) => { detail.forEach((element) => {
loadDetail.push({ loadDetail.push({
i_load_balance: id, i_load_balance: id ? id : id.i_load_balance,
i_reservation_balance: element.i_reservation_balance, i_reservation_balance: element.i_reservation_balance,
c_reservation_no: element.c_reservation_no, c_reservation_no: element.c_reservation_no,
i_amount: element.i_amount, i_amount: element.i_amount,
@@ -393,14 +434,23 @@ const insertLoadingBalance = async (
}); });
}) })
.then(trx.commit) .then(trx.commit)
.catch(trx.rollback); .catch((error) => {
console.log("SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS");
console.log(error);
trx.rollback
});
}) })
.then((result) => { .then((result) => {
// console.log(result); // console.log("result insertLoadingBalance", result);
winston.logger.debug(`XXXXXXXXXXX1 : ${result}`);
winston.logger.debug(`XXXXXXXXXXX2 : ${JSON.stringify(result)}`);
return result.rowCount; return result.rowCount;
}) })
.catch((error) => { .catch((error) => {
// console.log(error.message); // console.log("error.message insertLoadingBalance", error.message);
winston.logger.debug(`YYYYYYYYYYY1 : ${error}`);
winston.logger.debug(`YYYYYYYYYYY2 : ${JSON.stringify(error)}`);
return error.message; return error.message;
}); });
}; };
@@ -499,7 +549,7 @@ const insertLoadingBalanceHistoryOnly = async (
let loadDetail = []; let loadDetail = [];
detail.forEach((element) => { detail.forEach((element) => {
loadDetail.push({ loadDetail.push({
i_load_balance: id, i_load_balance: id.i_load_balance,
i_reservation_balance: element.i_reservation_balance, i_reservation_balance: element.i_reservation_balance,
c_reservation_no: element.c_reservation_no, c_reservation_no: element.c_reservation_no,
i_amount: element.i_amount, i_amount: element.i_amount,
@@ -623,17 +673,34 @@ const updateReservationAndLoadingBalance = async (
.where('c_load_balance_no', data.c_load_balance_no) .where('c_load_balance_no', data.c_load_balance_no)
.then(() => { .then(() => {
// insert load balance history // insert load balance history
// winston.logger.debug(
// `${reservationNumber} proses insert t_d_load_balance_history updateReservationAndLoadingBalance`
// );
return knex('trx.t_d_load_balance_history') return knex('trx.t_d_load_balance_history')
.transacting(trx) .transacting(trx)
.returning('i_load_balance') .returning('i_load_balance')
.insert(data); .insert(data);
}) })
.then((history) => { .then((history) => {
// winston.logger.debug(
// `${JSON.stringify(history)} history t_d_load_balance_history_detail`
// );
// winston.logger.debug(
// `${JSON.stringify(
// history[0]
// )} id t_d_load_balance_history_detail before parseint`
// );
let id = history[0]; let id = history[0];
// winston.logger.debug(
// `${id} id t_d_load_balance_history_detail id only`
// );
// winston.logger.debug(
// `${id.i_load_balance} id t_d_load_balance_history_detail id.i_load_balance`
// );
let loadDetail = []; let loadDetail = [];
detail.forEach((element) => { detail.forEach((element) => {
loadDetail.push({ loadDetail.push({
i_load_balance: id, i_load_balance: id.i_load_balance,
i_reservation_balance: element.i_reservation_balance, i_reservation_balance: element.i_reservation_balance,
c_reservation_no: element.c_reservation_no, c_reservation_no: element.c_reservation_no,
i_amount: element.i_amount, i_amount: element.i_amount,
@@ -648,6 +715,11 @@ const updateReservationAndLoadingBalance = async (
}); });
}); });
// winston.logger.debug(
// `${reservationNumber} proses insert t_d_load_balance_history_detail updateReservationAndLoadingBalance: ${JSON.stringify(
// loadDetail
// )}`
// );
// insert detail load balance // insert detail load balance
return knex('trx.t_d_load_balance_history_detail') return knex('trx.t_d_load_balance_history_detail')
.transacting(trx) .transacting(trx)
@@ -655,6 +727,9 @@ const updateReservationAndLoadingBalance = async (
}) })
.then(() => { .then(() => {
// update reservation // update reservation
// winston.logger.debug(
// `${reservationNumber} proses update t_d_reservation_balance updateReservationAndLoadingBalance`
// );
return knex('trx.t_d_reservation_balance') return knex('trx.t_d_reservation_balance')
.transacting(trx) .transacting(trx)
.update({ .update({
@@ -671,16 +746,31 @@ const updateReservationAndLoadingBalance = async (
}) })
.whereIn('c_reservation_no', reservationNumber); .whereIn('c_reservation_no', reservationNumber);
}) })
.then(trx.commit) .then(() => {
.catch(trx.rollback); // winston.logger.debug(`${reservationNumber} commit transaction`);
}) return trx.commit();
.then((result) => {
// console.log(result);
return result.rowCount;
}) })
.catch((error) => { .catch((error) => {
winston.logger.debug(
`${reservationNumber} rollback transaction: ${error.message}`
);
trx.rollback(); // Rollback transaction
// throw error; // Rethrow error to outer catch
});
})
.then((result) => {
// winston.logger.debug(
// `${reservationNumber} result success ${JSON.stringify(result)}}`
// );
// console.log(result);
return true;
})
.catch((error) => {
winston.logger.debug(
`${reservationNumber} result error: ${error.message}`
);
// console.log(error.message); // console.log(error.message);
return error.message; return false;
}); });
}; };
@@ -807,17 +897,6 @@ const getReservationPendingWithoutFraud = (
reservationNumber = [] reservationNumber = []
) => { ) => {
if (reservationNumber.length > 0) { if (reservationNumber.length > 0) {
let rsv = '';
if (reservationNumber.length > 0) {
for (let index = 0; index < reservationNumber.length; index++) {
if (index > 0) {
rsv = rsv + ',';
}
rsv = rsv + "'" + reservationNumber[index] + "'";
}
}
let result = knex('trx.t_d_reservation_balance') let result = knex('trx.t_d_reservation_balance')
.select( .select(
'trx.t_d_reservation_balance.i_reservation_amount', 'trx.t_d_reservation_balance.i_reservation_amount',
@@ -827,7 +906,14 @@ const getReservationPendingWithoutFraud = (
.where('trx.t_d_reservation_balance.c_card_number', cardNumber) .where('trx.t_d_reservation_balance.c_card_number', cardNumber)
.whereIn('trx.t_d_reservation_balance.c_status', ['P', 'I']) .whereIn('trx.t_d_reservation_balance.c_status', ['P', 'I'])
.whereRaw( .whereRaw(
`trx.t_d_reservation_balance.c_reservation_no NOT IN (SELECT c_reservation_no FROM trx.t_d_fraud WHERE trx.t_d_fraud.c_status = 'A' AND trx.t_d_fraud.c_reservation_no IN (${rsv}))` `NOT EXISTS (
SELECT 1
FROM trx.t_d_fraud f
WHERE f.c_reservation_no = trx.t_d_reservation_balance.c_reservation_no
AND f.c_status = 'A'
AND f.c_reservation_no = ANY(ARRAY[?])
)`,
[reservationNumber]
) )
// .where("d_expired", ">=", time) // .where("d_expired", ">=", time)
.where(function () { .where(function () {
@@ -877,17 +963,6 @@ const getLastHistory = (cardNumber) => {
// INSERT FRAUD TRANSACTION // INSERT FRAUD TRANSACTION
const insertFraudTransaction = (reservationNumber) => { const insertFraudTransaction = (reservationNumber) => {
let rsv = '';
if (reservationNumber.length > 0) {
for (let index = 0; index < reservationNumber.length; index++) {
if (index > 0) {
rsv = rsv + ',';
}
rsv = rsv + "'" + reservationNumber[index] + "'";
}
}
let result = knex let result = knex
.into( .into(
knex.raw( knex.raw(
@@ -944,7 +1019,14 @@ const insertFraudTransaction = (reservationNumber) => {
reservationNumber reservationNumber
) )
.whereRaw( .whereRaw(
`trx.t_d_reservation_balance.c_reservation_no NOT IN (SELECT c_reservation_no FROM trx.t_d_fraud WHERE trx.t_d_fraud.c_status = 'A' AND trx.t_d_fraud.c_reservation_no IN (${rsv}))` `NOT EXISTS (
SELECT 1
FROM trx.t_d_fraud f
WHERE f.c_reservation_no = trx.t_d_reservation_balance.c_reservation_no
AND f.c_status = 'A'
AND f.c_reservation_no = ANY(ARRAY[?])
)`,
[reservationNumber]
); );
}); });
return result; return result;
@@ -1021,7 +1103,7 @@ const updateReservationAndInsertLoadingBalance = async (
let loadDetail = []; let loadDetail = [];
detailLoadBalance.forEach((element) => { detailLoadBalance.forEach((element) => {
loadDetail.push({ loadDetail.push({
i_load_balance: id, i_load_balance: id.i_load_balance,
i_reservation_balance: element.i_reservation_balance, i_reservation_balance: element.i_reservation_balance,
c_reservation_no: element.c_reservation_no, c_reservation_no: element.c_reservation_no,
i_amount: element.i_reservation_amount, i_amount: element.i_reservation_amount,
@@ -1059,7 +1141,7 @@ const updateReservationAndInsertLoadingBalance = async (
}) })
.whereIn('c_reservation_no', reservationNumber); .whereIn('c_reservation_no', reservationNumber);
}) })
.then(trx.commit) .then(() => trx.commit())
.catch(trx.rollback); .catch(trx.rollback);
}) })
.then((result) => { .then((result) => {
+2 -14
View File
@@ -1,17 +1,5 @@
require("dotenv").config(); const { pooling: poolingConfig } = require("../../../knexfile");
let host = process.env.DB_HOST_POOLING; const dbPooling = require("knex")(poolingConfig);
let user = process.env.DB_USER_POOLING;
let name = process.env.DB_NAME_POOLING;
let password = process.env.DB_PASSWORD_POOLING;
const dbPooling = require("knex")({
client: "pg",
connection: {
host: host,
user: user,
password: password,
database: name,
},
});
const knex = require("../../../infrastructure/database/knex"); const knex = require("../../../infrastructure/database/knex");
const moment = require("moment"); const moment = require("moment");
moment.locale("id"); moment.locale("id");
File diff suppressed because it is too large Load Diff
+277 -1
View File
@@ -20,6 +20,28 @@ const getCardReplacement = (card_number) => {
return result; return result;
}; };
const getCardReplacementScheduler = async () => {
const today = new Date().toISOString().split('T')[0]; // Format: 'YYYY-MM-DD'
const result = await knex('trx.t_d_card_replacement')
.select('c_card_no')
.where('i_last_balance', null)
.where('d_valid_date', '>=', today);
return result;
};
// GET IS CARD SALES
const getCardSales = (card_number) => {
let result = knex('trx.t_d_sales_kmt_temp')
.select()
.where('card_number', card_number)
.orderBy('i_sales_kmt_temp', 'DESC')
.first();
return result;
};
// GET IS CARD ADDED TO BLACKLIST // GET IS CARD ADDED TO BLACKLIST
const getCardProduct = (card_number) => { const getCardProduct = (card_number) => {
let result = knex('public.t_m_card_product') let result = knex('public.t_m_card_product')
@@ -80,11 +102,255 @@ const updateReplacement = async (i_card_replacement, dataReplacement) => {
return result; return result;
}; };
// UPDATE CARD REPLACEMENT BY CARD NUMBER
const updateReplacementByCardNumber = async (card_number, dataReplacement) => {
let result = await knex('trx.t_d_card_replacement')
.update(dataReplacement, ['*'])
.where({ c_card_no: card_number });
return result;
};
// UPDATE CARD SALES
const updateSales = async (i_sales_kmt_temp, dataSales) => {
let result = await knex('trx.t_d_sales_kmt_temp')
.update(dataSales, ['*'])
.where({ i_sales_kmt_temp: i_sales_kmt_temp });
return result;
};
const insertReplacementDetail = async (dataReplacement) => { const insertReplacementDetail = async (dataReplacement) => {
let result = await knex("trx.t_d_card_replacement_detail").insert(dataReplacement); let result = await knex("trx.t_d_card_replacement_detail").insert(dataReplacement);
return result; return result;
}; };
const insertSales = async (dataSales) => {
let result = await knex("trx.t_d_sales_kmt_temp").insert(dataSales);
return result;
};
const getPPNCardSales = async () => {
let result = await knex('public.t_m_global_parameter')
.select('c_value')
.where('c_code', 'CARD_SALES_TAX')
.where('c_status', 'A')
.first();
return result;
};
const completingDataSalesInternal = async (ppn) => {
let result
await knex.transaction(async (trx) => {
try {
await trx.raw(`
UPDATE trx.t_d_sales_internal AS trx
SET
c_material_number_sap = subquery.c_material_number_sap,
i_card_theme = subquery.i_card_theme,
i_tax_amount = subquery.tax,
is_complete = subquery.is_complete
FROM (
SELECT DISTINCT ON (trx.t_d_sales_internal.c_card_number, t_m_card_theme.c_card_type_code, t_m_card_theme.c_card_digit_key, t_m_card_theme.c_variant_code)
trx.t_d_sales_internal.c_card_number,
t_m_card_theme.i_card_theme,
t_m_card_theme.c_material_number_sap,
trx.t_d_sales_internal.i_card_price AS card_selling_price,
ROUND(trx.t_d_sales_internal.i_card_price * 100 / (100 + ${ppn}::float)) AS card_price_before_tax,
ROUND((${ppn}::float / 100::float) * (ROUND(trx.t_d_sales_internal.i_card_price * 100 / (100 + ${ppn}::float)))) AS tax,
CASE
WHEN trx.t_d_sales_internal.c_category = 'S' THEN true
ELSE false
END is_complete
FROM trx.t_d_sales_internal
JOIN public.t_m_card_theme ON
SUBSTRING(trx.t_d_sales_internal.c_card_number, 1, 1) = t_m_card_theme.c_card_type_code
AND SUBSTRING(trx.t_d_sales_internal.c_card_number, 2, 2) = t_m_card_theme.c_card_digit_key
AND SUBSTRING(trx.t_d_sales_internal.c_card_number, 4, 1) = t_m_card_theme.c_variant_code
AND SUBSTRING(trx.t_d_sales_internal.c_card_number, 7, 2) = RIGHT(t_m_card_theme.i_year::text, 2)
WHERE
trx.t_d_sales_internal.is_complete is not true
AND trx.t_d_sales_internal.i_card_price > 0
AND trx.t_d_sales_internal.i_sales_invoice_internal is null
AND t_m_card_theme.c_status = 'A'
ORDER BY
trx.t_d_sales_internal.c_card_number,
t_m_card_theme.c_card_type_code,
t_m_card_theme.c_card_digit_key,
t_m_card_theme.c_variant_code,
t_m_card_theme.i_year DESC,
trx.t_d_sales_internal.d_create ASC
) AS subquery
WHERE
trx.c_card_number = subquery.c_card_number
AND trx.i_sales_invoice_internal IS NULL
`);
await trx.raw(`
UPDATE trx.t_d_sales_internal AS trx
SET
c_old_material_number_sap = subquery.c_material_number_sap,
i_old_card_theme = subquery.i_card_theme,
i_old_tax_amount = subquery.tax,
is_complete = subquery.is_complete
FROM (
SELECT DISTINCT ON (trx.t_d_sales_internal.c_old_card_number, t_m_card_theme.c_card_type_code, t_m_card_theme.c_card_digit_key, t_m_card_theme.c_variant_code)
trx.t_d_sales_internal.c_old_card_number,
t_m_card_theme.i_card_theme,
t_m_card_theme.c_material_number_sap,
trx.t_d_sales_internal.i_old_card_price AS card_selling_price,
ROUND(trx.t_d_sales_internal.i_old_card_price * 100 / (100 + ${ppn}::float)) AS card_price_before_tax,
ROUND((${ppn}::float / 100::float) * (ROUND(trx.t_d_sales_internal.i_old_card_price * 100 / (100 + ${ppn}::float)))) AS tax,
CASE
WHEN trx.t_d_sales_internal.c_category = 'S' THEN true
WHEN trx.t_d_sales_internal.c_category IN ('N', 'W') THEN true
ELSE false
END is_complete
FROM trx.t_d_sales_internal
JOIN public.t_m_card_theme ON
SUBSTRING(trx.t_d_sales_internal.c_old_card_number, 1, 1) = t_m_card_theme.c_card_type_code
AND SUBSTRING(trx.t_d_sales_internal.c_old_card_number, 2, 2) = t_m_card_theme.c_card_digit_key
AND SUBSTRING(trx.t_d_sales_internal.c_old_card_number, 4, 1) = t_m_card_theme.c_variant_code
AND SUBSTRING(trx.t_d_sales_internal.c_old_card_number, 7, 2) = RIGHT(t_m_card_theme.i_year::text, 2)
WHERE
trx.t_d_sales_internal.is_complete is not true
AND trx.t_d_sales_internal.i_old_card_price > 0
AND trx.t_d_sales_internal.c_category IN ('N', 'W')
AND trx.t_d_sales_internal.i_sales_invoice_internal is null
AND t_m_card_theme.c_status = 'A'
ORDER BY
trx.t_d_sales_internal.c_old_card_number,
t_m_card_theme.c_card_type_code,
t_m_card_theme.c_card_digit_key,
t_m_card_theme.c_variant_code,
t_m_card_theme.i_year DESC,
trx.t_d_sales_internal.d_create ASC
) AS subquery
WHERE
trx.c_old_card_number = subquery.c_old_card_number
AND trx.i_sales_invoice_internal IS NULL
`);
await trx.commit();
result = {
success: true,
message: 'Berhasil update data sales internal.'
};
} catch (error) {
await trx.rollback();
result = {
success: false,
message: `Gagal update data sales internal: ${error.message}`
};
}
});
return result;
};
const completingDataSalesNewCard = async (ppn) => {
return await knex.raw(`
UPDATE trx.t_d_sales_internal AS trx
SET
c_material_number_sap = subquery.c_material_number_sap,
i_card_theme = subquery.i_card_theme,
i_tax_amount = subquery.tax,
is_complete = subquery.is_complete
FROM (
SELECT DISTINCT ON (trx.t_d_sales_internal.c_card_number, t_m_card_theme.c_card_type_code, t_m_card_theme.c_card_digit_key, t_m_card_theme.c_variant_code)
trx.t_d_sales_internal.c_card_number,
t_m_card_theme.i_card_theme,
t_m_card_theme.c_material_number_sap,
trx.t_d_sales_internal.i_card_price AS card_selling_price,
ROUND(trx.t_d_sales_internal.i_card_price * 100 / (100 + ${ppn}::float)) AS card_price_before_tax,
ROUND((${ppn}::float / 100::float) * (ROUND(trx.t_d_sales_internal.i_card_price * 100 / (100 + ${ppn}::float)))) AS tax,
CASE
WHEN trx.t_d_sales_internal.c_category = 'S' THEN true
ELSE false
END is_complete
FROM trx.t_d_sales_internal
JOIN public.t_m_card_theme ON
SUBSTRING(trx.t_d_sales_internal.c_card_number, 1, 1) = t_m_card_theme.c_card_type_code
AND SUBSTRING(trx.t_d_sales_internal.c_card_number, 2, 2) = t_m_card_theme.c_card_digit_key
AND SUBSTRING(trx.t_d_sales_internal.c_card_number, 4, 1) = t_m_card_theme.c_variant_code
AND SUBSTRING(trx.t_d_sales_internal.c_card_number, 7, 2) = RIGHT(t_m_card_theme.i_year::text, 2)
WHERE
trx.t_d_sales_internal.is_complete is not true
AND trx.t_d_sales_internal.i_card_price > 0
AND trx.t_d_sales_internal.i_sales_invoice_internal is null
AND t_m_card_theme.c_status = 'A'
ORDER BY
trx.t_d_sales_internal.c_card_number,
t_m_card_theme.c_card_type_code,
t_m_card_theme.c_card_digit_key,
t_m_card_theme.c_variant_code,
t_m_card_theme.i_year DESC,
trx.t_d_sales_internal.d_create ASC
) AS subquery
WHERE
trx.c_card_number = subquery.c_card_number
AND trx.i_sales_invoice_internal IS NULL
`);
};
const completingDataSalesOldCard = async (ppn) => {
return await knex.raw(`
UPDATE trx.t_d_sales_internal AS trx
SET
c_old_material_number_sap = subquery.c_material_number_sap,
i_old_card_theme = subquery.i_card_theme,
i_old_tax_amount = subquery.tax
FROM (
SELECT DISTINCT ON (trx.t_d_sales_internal.c_old_card_number, t_m_card_theme.c_card_type_code, t_m_card_theme.c_card_digit_key, t_m_card_theme.c_variant_code)
trx.t_d_sales_internal.c_old_card_number,
t_m_card_theme.i_card_theme,
t_m_card_theme.c_material_number_sap,
trx.t_d_sales_internal.i_old_card_price AS card_selling_price,
ROUND(trx.t_d_sales_internal.i_old_card_price * 100 / (100 + ${ppn}::float)) AS card_price_before_tax,
ROUND((${ppn}::float / 100::float) * (ROUND(trx.t_d_sales_internal.i_old_card_price * 100 / (100 + ${ppn}::float)))) AS tax,
CASE
WHEN trx.t_d_sales_internal.c_category = 'S' THEN true
WHEN trx.t_d_sales_internal.c_category IN ('N', 'W') THEN true
ELSE false
END is_complete
FROM trx.t_d_sales_internal
JOIN public.t_m_card_theme ON
SUBSTRING(trx.t_d_sales_internal.c_old_card_number, 1, 1) = t_m_card_theme.c_card_type_code
AND SUBSTRING(trx.t_d_sales_internal.c_old_card_number, 2, 2) = t_m_card_theme.c_card_digit_key
AND SUBSTRING(trx.t_d_sales_internal.c_old_card_number, 4, 1) = t_m_card_theme.c_variant_code
AND SUBSTRING(trx.t_d_sales_internal.c_old_card_number, 7, 2) = RIGHT(t_m_card_theme.i_year::text, 2)
WHERE
trx.t_d_sales_internal.is_complete is not true
AND trx.t_d_sales_internal.i_old_card_price > 0
AND trx.t_d_sales_internal.c_category IN ('N', 'W')
AND trx.t_d_sales_internal.i_sales_invoice_internal is null
AND t_m_card_theme.c_status = 'A'
ORDER BY
trx.t_d_sales_internal.c_old_card_number,
t_m_card_theme.c_card_type_code,
t_m_card_theme.c_card_digit_key,
t_m_card_theme.c_variant_code,
t_m_card_theme.i_year DESC,
trx.t_d_sales_internal.d_create ASC
) AS subquery
WHERE
trx.c_old_card_number = subquery.c_old_card_number
AND trx.i_sales_invoice_internal IS NULL
`);
};
const updateDataSalesIsComplete = async () => {
return await knex.raw(`
UPDATE trx.t_d_sales_internal SET is_complete = true
WHERE
is_complete is not true
AND c_material_number_sap is not null
AND i_tax_amount is not null
AND c_old_material_number_sap is not null
AND i_old_tax_amount is not null
AND c_category IN ('N', 'W')
`);
};
module.exports = { module.exports = {
getCardBlacklist, getCardBlacklist,
getCardReplacement, getCardReplacement,
@@ -93,5 +359,15 @@ module.exports = {
getLastBalanceFromCardHistory, getLastBalanceFromCardHistory,
getAccumulationBalanceInThisMonthFromCardHistory, getAccumulationBalanceInThisMonthFromCardHistory,
updateReplacement, updateReplacement,
insertReplacementDetail insertReplacementDetail,
insertSales,
getCardSales,
updateSales,
getCardReplacementScheduler,
updateReplacementByCardNumber,
getPPNCardSales,
completingDataSalesInternal,
completingDataSalesNewCard,
completingDataSalesOldCard,
updateDataSalesIsComplete,
}; };
@@ -79,7 +79,7 @@ const callbackOy = async (req, res) => {
`${uniqueCode} [ RESPONSE REFUND-KMT ]: ${JSON.stringify(result)}` `${uniqueCode} [ RESPONSE REFUND-KMT ]: ${JSON.stringify(result)}`
); );
let recipient_bank_code = recipient_bank.toLowerCase(); let recipient_bank_code = recipient_bank.toUpperCase();
// check trx_id yang di request match // check trx_id yang di request match
let checkRequest = await model.checkRedeem( let checkRequest = await model.checkRedeem(
partner_trx_id, partner_trx_id,
@@ -129,11 +129,14 @@ const callbackOy = async (req, res) => {
}; };
} }
const unixTimeZero = Date.parse(last_updated_date); const date_reimbursement = moment(last_updated_date, 'DD-MM-YYYY HH:mm:ss').format(
const date_reimbursement = moment(unixTimeZero).format(
'YYYY-MM-DD HH:mm:ss' 'YYYY-MM-DD HH:mm:ss'
); );
winston.logger.warn(
`${uniqueCode} [ log date_reimbusement ]: ${JSON.stringify(date_reimbursement)}`
);
//Update Card Replacement //Update Card Replacement
await model.updateReplacementComplete( await model.updateReplacementComplete(
checkRequest.i_card_replacement, checkRequest.i_card_replacement,
@@ -141,6 +144,7 @@ const callbackOy = async (req, res) => {
date_reimbursement date_reimbursement
); );
/*
//Notif Email //Notif Email
let urlCMS = ''; let urlCMS = '';
if (process.env.SERVER_FOR == 'production') { if (process.env.SERVER_FOR == 'production') {
@@ -170,7 +174,8 @@ const callbackOy = async (req, res) => {
status: 'complete', status: 'complete',
}, },
}); });
console.log('urlCMS', url); */
// console.log('urlCMS', url)
result = { result = {
code: '00', code: '00',
@@ -32,6 +32,13 @@ const updateReplacementComplete = (i_replacement, request_no, date_disburse) =>
let result = knex("trx.t_d_card_replacement") let result = knex("trx.t_d_card_replacement")
.where("i_card_replacement", i_replacement) .where("i_card_replacement", i_replacement)
.where("c_request_no", request_no) .where("c_request_no", request_no)
// .update({
// c_status: "A",
// c_status_name: "COMPLETED",
// d_disburse: date_disburse,
// c_response_code: "000",
// c_response_message: "Success"
// });
.update({ .update({
c_status: "A", c_status: "A",
c_status_name: "COMPLETED", c_status_name: "COMPLETED",
@@ -1254,7 +1254,7 @@ const reservation = async (req, res) => {
try { try {
// generate unique code // generate unique code
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
let uniqueCode = helper.getUniqueCode(); let uniqueCode = await helper.getUniqueCode();
let result = {}; let result = {};
// param // param
@@ -1712,11 +1712,11 @@ const reservation = async (req, res) => {
// create log // create log
winston.logger.error(`server is busy. please try again.`); winston.logger.error(`server is busy. please try again.`);
return { return res.status(200).json({
code: '500', code: '500',
message: 'server is busy. please try again.', message: 'server is busy. please try again.',
data: {}, data: {},
}; });
} }
maxLoop++; maxLoop++;
@@ -1823,29 +1823,7 @@ const reservation = async (req, res) => {
// jika proses insert data semua yang berkaitan dengan reservasi saldo mengalami kegagalan, maka lakukan rollback // jika proses insert data semua yang berkaitan dengan reservasi saldo mengalami kegagalan, maka lakukan rollback
// kegagalan insert data transaksi bisa disebabkan karena data ref no yang di berikan client sudah digunakan // kegagalan insert data transaksi bisa disebabkan karena data ref no yang di berikan client sudah digunakan
if (insert.rowCount < 1) { if (insert.rowCount > 0) {
// log debug
// winston.logger.debug(
// `${uniqueCode} [ PROCESSING RESERVATION ] deleting reservation number validate...`
// );
// delete data reservasi yang mengalami kegagalan insert data
await model.deleteReservationNumberValidate(reservationNumber);
result = {
code: '424',
message: 'refno is duplicate',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}`
);
return res.status(200).json(result);
}
// log debug // log debug
// winston.logger.debug( // winston.logger.debug(
// `${uniqueCode} [ PROCESSING RESERVATION ] inserting log for card history...` // `${uniqueCode} [ PROCESSING RESERVATION ] inserting log for card history...`
@@ -1863,8 +1841,7 @@ const reservation = async (req, res) => {
m_balance_after: balance > 0 ? balance : 0, m_balance_after: balance > 0 ? balance : 0,
j_new_data: data, j_new_data: data,
j_old_data: null, j_old_data: null,
c_note: `RESERVED BALANCE ${amount} FROM ${ c_note: `RESERVED BALANCE ${amount} FROM ${getPartner ? getPartner.partner_name : null
getPartner ? getPartner.partner_name : null
} SUCCESSFULLY`, } SUCCESSFULLY`,
c_status: 'S', c_status: 'S',
d_created: now, d_created: now,
@@ -1896,6 +1873,28 @@ const reservation = async (req, res) => {
); );
return res.status(200).json(result); return res.status(200).json(result);
} else {
// log debug
// winston.logger.debug(
// `${uniqueCode} [ PROCESSING RESERVATION ] deleting reservation number validate...`
// );
// delete data reservasi yang mengalami kegagalan insert data
await model.deleteReservationNumberValidate(reservationNumber);
result = {
code: '424',
message: 'refno is duplicate',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE RESERVATION ]: ${JSON.stringify(result)}`
);
return res.status(200).json(result);
}
} catch (error) { } catch (error) {
// create log // create log
winston.logger.error( winston.logger.error(
@@ -1923,7 +1922,7 @@ const reservationV2 = async (req, res) => {
try { try {
// generate unique code // generate unique code
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca // unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
let uniqueCode = helper.getUniqueCode(); let uniqueCode = await helper.getUniqueCode();
let result = {}; let result = {};
// param // param
@@ -1971,7 +1970,7 @@ const reservationV2 = async (req, res) => {
try { try {
reservationData = helper.decryptText(reservation_data); reservationData = helper.decryptText(reservation_data);
} catch (error) {} } catch (error) { }
if (!reservationData) { if (!reservationData) {
result = { result = {
@@ -2547,11 +2546,11 @@ const reservationV2 = async (req, res) => {
// create log // create log
winston.logger.error(`server is busy. please try again.`); winston.logger.error(`server is busy. please try again.`);
return { return res.status(200).json({
code: '500', code: '500',
message: 'server is busy. please try again.', message: 'server is busy. please try again.',
data: {}, data: {},
}; });
} }
maxLoop++; maxLoop++;
@@ -2653,34 +2652,14 @@ const reservationV2 = async (req, res) => {
// `${uniqueCode} [ PROCESSING RESERVATION-V2 ] inserting reservation transaction...` // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] inserting reservation transaction...`
// ); // );
// (belum) ada issue disini, jadi ada case reservation number nya sama, terus error query harusnya ada handle response message nya, yg sekarang malah masuk ke blok reservation saved successfully.
// insert transaction // insert transaction
let insert = await model.insertReservation(data); let insert = await model.insertReservation(data);
// jika proses insert data semua yang berkaitan dengan reservasi saldo mengalami kegagalan, maka lakukan rollback // jika proses insert data semua yang berkaitan dengan reservasi saldo mengalami kegagalan, maka lakukan rollback
// kegagalan insert data transaksi bisa disebabkan karena data ref no yang di berikan client sudah digunakan // kegagalan insert data transaksi bisa disebabkan karena data ref no yang di berikan client sudah digunakan
if (insert.rowCount < 1) { if (insert.rowCount > 0) {
// log debug
// winston.logger.debug(
// `${uniqueCode} [ PROCESSING RESERVATION-V2 ] deleting reservation number validate...`
// );
// delete data reservasi yang mengalami kegagalan insert data
await model.deleteReservationNumberValidate(reservationNumber);
result = {
code: '424',
message: 'refno is duplicate',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}`
);
return res.status(200).json(result);
}
// log debug // log debug
// winston.logger.debug( // winston.logger.debug(
// `${uniqueCode} [ PROCESSING RESERVATION-V2 ] inserting log for card history...` // `${uniqueCode} [ PROCESSING RESERVATION-V2 ] inserting log for card history...`
@@ -2698,8 +2677,7 @@ const reservationV2 = async (req, res) => {
m_balance_after: balance > 0 ? balance : 0, m_balance_after: balance > 0 ? balance : 0,
j_new_data: data, j_new_data: data,
j_old_data: null, j_old_data: null,
c_note: `RESERVED BALANCE ${amount} FROM ${ c_note: `RESERVED BALANCE ${amount} FROM ${getPartner ? getPartner.partner_name : null
getPartner ? getPartner.partner_name : null
} SUCCESSFULLY`, } SUCCESSFULLY`,
c_status: 'S', c_status: 'S',
d_created: now, d_created: now,
@@ -2731,6 +2709,28 @@ const reservationV2 = async (req, res) => {
); );
return res.status(200).json(result); return res.status(200).json(result);
} else {
// log debug
// winston.logger.debug(
// `${uniqueCode} [ PROCESSING RESERVATION-V2 ] deleting reservation number validate...`
// );
// delete data reservasi yang mengalami kegagalan insert data
await model.deleteReservationNumberValidate(reservationNumber);
result = {
code: '424',
message: 'refno is duplicate',
data: {},
};
// log warn
winston.logger.warn(
`${uniqueCode} [ RESPONSE RESERVATION-V2 ]: ${JSON.stringify(result)}`
);
return res.status(200).json(result);
}
} catch (error) { } catch (error) {
// create log // create log
winston.logger.error( winston.logger.error(
@@ -3174,8 +3174,7 @@ const cancelReservation = async (req, res) => {
m_balance_after: balance > 0 ? balance : 0, m_balance_after: balance > 0 ? balance : 0,
j_new_data: data, j_new_data: data,
j_old_data: getReservationCanBeCanceled, j_old_data: getReservationCanBeCanceled,
c_note: `CANCEL RESERVE BALANCE ${ c_note: `CANCEL RESERVE BALANCE ${getReservationCanBeCanceled.i_reservation_amount
getReservationCanBeCanceled.i_reservation_amount
} FROM ${getPartner ? getPartner.partner_name : null}`, } FROM ${getPartner ? getPartner.partner_name : null}`,
c_status: 'S', c_status: 'S',
d_created: now, d_created: now,
@@ -3327,6 +3326,14 @@ const inquiryReservationByReservation = async (req, res) => {
// check reservation // check reservation
result = await model.inquiryListByRefNumber(ref_no, show_complete_data); result = await model.inquiryListByRefNumber(ref_no, show_complete_data);
if (!result) {
return res.status(200).json({
code: '414',
message: "reservation doesn't exist",
data: {},
});
}
} else if (req.query.search === 'load-balance-number') { } else if (req.query.search === 'load-balance-number') {
// validation parameter inquiry // validation parameter inquiry
if (!load_balance_number) { if (!load_balance_number) {
@@ -3342,6 +3349,14 @@ const inquiryReservationByReservation = async (req, res) => {
load_balance_number, load_balance_number,
show_complete_data show_complete_data
); );
if (result.length < 1) {
return res.status(200).json({
code: '414',
message: "reservation doesn't exist",
data: {},
});
}
} else { } else {
// validation parameter inquiry // validation parameter inquiry
if (!reservation_number) { if (!reservation_number) {
@@ -3357,7 +3372,6 @@ const inquiryReservationByReservation = async (req, res) => {
reservation_number, reservation_number,
show_complete_data show_complete_data
); );
}
if (!result) { if (!result) {
return res.status(200).json({ return res.status(200).json({
@@ -3366,6 +3380,7 @@ const inquiryReservationByReservation = async (req, res) => {
data: {}, data: {},
}); });
} }
}
return res.json({ return res.json({
code: '00', code: '00',
@@ -3877,7 +3892,7 @@ const cancelReservationV2 = async (req, res) => {
try { try {
cancelReservationData = helper.decryptText(cancel_reservation_data); cancelReservationData = helper.decryptText(cancel_reservation_data);
} catch (error) {} } catch (error) { }
if (!cancelReservationData) { if (!cancelReservationData) {
result = { result = {
@@ -4091,8 +4106,7 @@ const cancelReservationV2 = async (req, res) => {
m_balance_after: balance > 0 ? balance : 0, m_balance_after: balance > 0 ? balance : 0,
j_new_data: data, j_new_data: data,
j_old_data: getReservationCanBeCanceled, j_old_data: getReservationCanBeCanceled,
c_note: `CANCEL RESERVE BALANCE ${ c_note: `CANCEL RESERVE BALANCE ${getReservationCanBeCanceled.i_reservation_amount
getReservationCanBeCanceled.i_reservation_amount
} FROM ${getPartner ? getPartner.partner_name : null}`, } FROM ${getPartner ? getPartner.partner_name : null}`,
c_status: 'S', c_status: 'S',
d_created: now, d_created: now,
@@ -4374,8 +4388,7 @@ const cancelReservationV2_1 = async (req, res) => {
m_balance_after: balance > 0 ? balance : 0, m_balance_after: balance > 0 ? balance : 0,
j_new_data: data, j_new_data: data,
j_old_data: getReservationCanBeCanceled, j_old_data: getReservationCanBeCanceled,
c_note: `CANCEL RESERVE BALANCE ${ c_note: `CANCEL RESERVE BALANCE ${getReservationCanBeCanceled.i_reservation_amount
getReservationCanBeCanceled.i_reservation_amount
} FROM ${getPartner ? getPartner.partner_name : null}`, } FROM ${getPartner ? getPartner.partner_name : null}`,
c_status: 'S', c_status: 'S',
d_created: now, d_created: now,
@@ -152,7 +152,7 @@ const getMaxReservation = () => {
}; };
// INQUIRY BY RESERVATION NUMBER // INQUIRY BY RESERVATION NUMBER
let inquiryByReservationNumber = (reservationNumber, show_complete_data) => { const inquiryByReservationNumber = (reservationNumber, show_complete_data) => {
let result = knex('trx.t_d_reservation_balance'); let result = knex('trx.t_d_reservation_balance');
if (show_complete_data === true) { if (show_complete_data === true) {
result.select( result.select(
@@ -198,14 +198,14 @@ let inquiryByReservationNumber = (reservationNumber, show_complete_data) => {
); );
}); });
result result = result
.where('trx.t_d_reservation_balance.c_reservation_no', reservationNumber) .where('trx.t_d_reservation_balance.c_reservation_no', reservationNumber)
.first(); .first();
return result; return result;
}; };
// INQUIRY LIST RESERVATION // INQUIRY LIST RESERVATION
let inquiryListReservation = (partnerID, startDate, endDate) => { const inquiryListReservation = (partnerID, startDate, endDate) => {
let result = knex('trx.t_d_reservation_balance'); let result = knex('trx.t_d_reservation_balance');
result.select( result.select(
'trx.t_d_reservation_balance.c_reservation_no as reservation_number', 'trx.t_d_reservation_balance.c_reservation_no as reservation_number',
@@ -253,7 +253,7 @@ let inquiryListReservation = (partnerID, startDate, endDate) => {
}; };
// INQUIRY BY CARD NUMBER // INQUIRY BY CARD NUMBER
let inquiryByCardNumber = (cardNumber, startDate, endDate) => { const inquiryByCardNumber = (cardNumber, startDate, endDate) => {
let result = knex('trx.t_d_reservation_balance') let result = knex('trx.t_d_reservation_balance')
.select( .select(
'c_reservation_no as reservation_number', 'c_reservation_no as reservation_number',
@@ -286,7 +286,14 @@ const getReservationPending = (cardNumber, time) => {
.where('c_card_number', cardNumber) .where('c_card_number', cardNumber)
.where('c_status', 'P') .where('c_status', 'P')
.whereRaw( .whereRaw(
`c_reservation_no NOT IN (SELECT c_reservation_no FROM trx.t_d_fraud tdf WHERE tdf.c_status = 'A' AND tdf.c_card_number = '${cardNumber}')` `NOT EXISTS (
SELECT 1
FROM trx.t_d_fraud f
WHERE f.c_reservation_no = trx.t_d_reservation_balance.c_reservation_no
AND f.c_status = 'A'
AND f.c_card_number = ?
)`,
[cardNumber]
) )
// .where("d_expired", ">=", time) // .where("d_expired", ">=", time)
.first(); .first();
@@ -310,7 +317,14 @@ const getReservationPendingV2 = (cardNumber, time) => {
.where('c_card_number', cardNumber) .where('c_card_number', cardNumber)
.where('c_status', 'P') .where('c_status', 'P')
.whereRaw( .whereRaw(
`c_reservation_no NOT IN (SELECT c_reservation_no FROM trx.t_d_fraud tdf WHERE tdf.c_status = 'A' AND tdf.c_card_number = '${cardNumber}')` `NOT EXISTS (
SELECT 1
FROM trx.t_d_fraud f
WHERE f.c_reservation_no = trx.t_d_reservation_balance.c_reservation_no
AND f.c_status = 'A'
AND f.c_card_number = ?
)`,
[cardNumber]
); );
return result; return result;
@@ -425,7 +439,7 @@ const deleteReservationNumberValidate = (reservationNumber) => {
}; };
// INQUIRY BY REF NUMBER // INQUIRY BY REF NUMBER
let inquiryListByRefNumber = (refNumber, show_complete_data) => { const inquiryListByRefNumber = (refNumber, show_complete_data) => {
let result = knex('trx.t_d_reservation_balance'); let result = knex('trx.t_d_reservation_balance');
if (show_complete_data === true) { if (show_complete_data === true) {
result.select( result.select(
@@ -469,7 +483,7 @@ let inquiryListByRefNumber = (refNumber, show_complete_data) => {
); );
}); });
result.where('trx.t_d_reservation_balance.c_ref_no', refNumber).first(); result = result.where('trx.t_d_reservation_balance.c_ref_no', refNumber).first();
return result; return result;
}; };
+14
View File
@@ -17,6 +17,20 @@ router.get(
controller.apiGenerateCashInSales controller.apiGenerateCashInSales
); );
router.get(
"/online/cash-in-sales-internal",
// auth.authenticateToken,
// controller.validate("generateInvoice"),
controller.apiGenerateCashInSalesInternal
);
router.get(
"/online/cash-in-topup-cashless-internal",
// auth.authenticateToken,
// controller.validate("generateInvoice"),
controller.apiGenerateCashInTopUpCashlessInternal
);
router.post( router.post(
"/online/cash-in/posting", "/online/cash-in/posting",
// auth.authenticateToken, // auth.authenticateToken,
+49
View File
@@ -51,6 +51,14 @@ router.post(
controller.validateReplacement controller.validateReplacement
); );
// API Validate Replacement New Card
router.post(
"/pos/cardreplacement/validatenewcard",
auth.authenticateToken,
controller.validate("validateNewCardReplacement"),
controller.validateNewCardReplacement
);
// API Replacement Confirm // API Replacement Confirm
router.post( router.post(
"/pos/cardreplacement/confirm", "/pos/cardreplacement/confirm",
@@ -59,4 +67,45 @@ router.post(
controller.replacementConfirm controller.replacementConfirm
); );
// API Redeem Confirm
router.post(
"/pos/cardredeem/confirm",
auth.authenticateToken,
controller.validate("confirmCardRedeem"),
controller.confirmRedeem
);
// API Sales Confirm
router.post(
"/pos/cardsales/confirm",
auth.authenticateToken,
controller.validate("confirmCardSales"),
controller.confirmSales
);
// API Sales Confirm
router.post(
"/pos/schedulerCTS/lastbalance",
auth.authenticateToken,
controller.getLastBalanceCTS
);
// API Scheduler Lengkapi Data Sales Internal
router.post(
"/pos/sales/complete-data",
controller.completeDataSalesInternal
);
// API Scheduler Lengkapi Data Sales Internal V2
router.post(
"/pos/sales/complete-data-v2",
controller.completeDataSalesInternalV2
);
// API Test
router.post(
"/pos/test",
controller.testAPI
);
module.exports = router; module.exports = router;
+139
View File
@@ -0,0 +1,139 @@
# Cash-in Index Checklist
These indexes are suggested for the heavy cash-in read paths in `application/modules/cashin/cahsin.model.js`.
Apply them first in a staging environment and validate with `EXPLAIN (ANALYZE, BUFFERS)` before promoting to production.
## 1. Reservation balance lookup
Used by `getReserve()` and `getPartnerRecon()`.
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdrb_cash_in_lookup
ON trx.t_d_reservation_balance (c_partner_code, c_invoice_no, c_reservation_no)
WHERE c_status = 'A'
AND c_load_balance_no IS NOT NULL
AND c_cash_in_no IS NULL;
```
## 2. Reservation balance join key
Supports joins to payment recon and load balance.
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdrb_load_balance_no
ON trx.t_d_reservation_balance (c_load_balance_no);
```
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdrb_reservation_no
ON trx.t_d_reservation_balance (c_reservation_no);
```
## 3. Payment recon lookup
Used by `getReserve()`, `getPartnerRecon()`, and related sales/topup queries.
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdpr_reservation_status_payment
ON payment.t_d_payment_recon (c_reservation_no, d_payment)
WHERE c_status = 'S';
```
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdpr_sales_status_payment
ON payment.t_d_payment_recon_sales_kmt_mobile (c_sales_no, d_payment)
WHERE c_status = 'S';
```
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdpr_sales_internal_status_payment
ON payment.t_d_payment_recon_sales_internal (c_sales_no, d_payment)
WHERE c_status = 'S';
```
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdpr_topup_internal_status_payment
ON payment.t_d_payment_recon_topup_cashless_internal (c_topup_no, d_payment)
WHERE c_status = 'S';
```
## 4. Invoice lookup
Used by the cash-in and recon queries.
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdi_invoice_status_return
ON payment.t_d_invoice (c_invoice_no)
WHERE c_status <> 'X'
AND c_return_sap IS NOT NULL;
```
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdsi_invoice_status_return
ON payment.t_d_sales_invoice (c_invoice_no)
WHERE c_status <> 'X'
AND c_return_sap IS NOT NULL;
```
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdsi_internal_invoice_status_return
ON payment.t_d_sales_invoice_internal (c_invoice_no)
WHERE c_status <> 'X'
AND c_return_sap_fi IS NOT NULL;
```
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdsi_topup_internal_invoice_status_return
ON payment.t_d_topup_cashless_invoice_internal (c_invoice_no)
WHERE c_status <> 'X'
AND c_return_sap IS NOT NULL;
```
-- Indexes to optimize performance when posting invoice online topup
```sql
CREATE INDEX idx_posting_et_reference ON public.posting_et(reference);
CREATE INDEX idx_posting_et_tcode_status ON public.posting_et(tcode, pos_status);
```
## 5. Cash-in detail anti-join
Used by `getSalesKMT()`, `getSalesInternal()`, and `getTopUpCashlessInternal()` to exclude already-posted rows.
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdcid_reservation_not_reversed
ON payment.t_d_cash_in_detail (c_reservation_no)
WHERE b_reversal IS NOT TRUE;
```
## 6. Cash-in code generation
Used by `generateCode()`.
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tdcashin_code_prefix
ON payment.t_d_cash_in (c_cash_in_no);
```
If prefix lookups still scan too much data, consider a functional index on the prefix pattern that matches your code format.
## 7. Partner lookup
Used by recon queries that join through `public.t_m_partner`.
```sql
CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_tmp_i_partner
ON public.t_m_partner (i_partner);
```
## Notes
- `CONCURRENTLY` avoids blocking writes, but it cannot run inside a transaction.
- Partial indexes are the best fit here because the queries always filter on status and posting flags.
- After creating indexes, run `EXPLAIN (ANALYZE, BUFFERS)` on:
- `getReserve()`
- `getPartnerRecon()`
- `getPartnerReconSales()`
- `getPartnerReconSalesInternal()`
- `getPartnerReconTopUpCashlessInternal()`
- If you want, I can also draft a migration file for these indexes in Knex format.
@@ -0,0 +1,143 @@
-- =========================================================
-- RECOMMENDED INDEXES FOR PRODUCTION
-- =========================================================
-- Main filtering index
CREATE INDEX IF NOT EXISTS idx_posting_et_main_filter
ON public.posting_et (
tcode,
pos_status,
fiscal_year
);
-- Prefix LIKE 'INV%'
CREATE INDEX IF NOT EXISTS idx_posting_et_doc_header
ON public.posting_et (doc_header_text);
-- Join & aggregation optimization
CREATE INDEX IF NOT EXISTS idx_posting_et_reference_debit
ON public.posting_et (
reference,
debit_kredit
);
-- Optional covering index for large tables
CREATE INDEX IF NOT EXISTS idx_posting_et_covering
ON public.posting_et (
tcode,
pos_status,
fiscal_year,
reference
);
-- =========================================================
-- PRODUCTION QUERY
-- =========================================================
WITH params AS (
SELECT
EXTRACT(YEAR FROM CURRENT_DATE)::TEXT AS curr_year,
EXTRACT(YEAR FROM CURRENT_DATE - INTERVAL '1 year')::TEXT AS prev_year,
TO_CHAR(CURRENT_DATE, 'MM') AS curr_month
),
base AS (
SELECT
pe.doc_header_text,
pe.ba,
pe.doc_date,
pe.posting_date,
pe.fiscal_year,
TO_CHAR(pe.doc_date::DATE, 'MM') AS fis_period,
pe.doc_type,
pe.reference,
pe.tcode,
pe.amount,
pe.customer,
pe.account,
pe.text,
pe.debit_kredit
FROM public.posting_et pe
CROSS JOIN params p
WHERE
pe.tcode = 'FB70'
AND pe.pos_status = '3'
-- Prefix search still index friendly
AND pe.doc_header_text LIKE 'INV%'
AND (
-- Current year all months
pe.fiscal_year = p.curr_year
OR (
-- Previous year December only
-- only when current month is January
p.curr_month = '01'
AND pe.fiscal_year = p.prev_year
AND TO_CHAR(pe.doc_date::DATE, 'MM') = '12'
)
)
)
SELECT
b.doc_header_text,
b.ba,
b.doc_date,
b.posting_date,
b.fiscal_year,
b.fis_period,
b.doc_type,
b.reference,
b.tcode,
b.amount,
'IDR'::VARCHAR AS currency,
MAX(b.customer) FILTER (
WHERE b.debit_kredit = 'S'
) AS customer,
MAX(b.account) FILTER (
WHERE b.debit_kredit = 'H'
) AS account,
MAX(b.text) FILTER (
WHERE b.debit_kredit = 'S'
) AS text1,
MAX(b.text) FILTER (
WHERE b.debit_kredit = 'H'
) AS text2
FROM base b
GROUP BY
b.doc_header_text,
b.ba,
b.doc_date,
b.posting_date,
b.fiscal_year,
b.fis_period,
b.doc_type,
b.reference,
b.tcode,
b.amount
ORDER BY
b.fiscal_year,
b.doc_date,
b.reference;
@@ -0,0 +1,20 @@
-- Indexes to optimize performance
CREATE INDEX CONCURRENTLY idx_tdl_d_load_balance_void
ON trx.t_d_load_balance(d_load_balance, b_void, c_invoice_no);
CREATE INDEX CONCURRENTLY idx_tdrb_invoice_status
ON trx.t_d_reservation_balance(c_invoice_no, c_status);
CREATE INDEX CONCURRENTLY idx_tmp_b_invoice
ON public.t_m_partner(i_partner, b_invoice);
CREATE INDEX CONCURRENTLY idx_tdprt_date_status
ON payment.t_d_payment_request_topup_online(d_date_payment_request, b_sent, b_void);
-- Note:
-- Expected Performance Gain: 10-100x faster depending on partner volume and data size.
-- Indexes to optimize performance when posting invoice online topup
CREATE INDEX idx_posting_et_reference ON public.posting_et(reference);
CREATE INDEX idx_posting_et_tcode_status ON public.posting_et(tcode, pos_status);
+52 -111
View File
@@ -1,11 +1,14 @@
require('dotenv').config(); require('dotenv').config();
// var http = require('http');
const cluster = require('node:cluster'); const cluster = require('node:cluster');
const totalCPUs = require('node:os').cpus().length; const { createServer } = require('node:http');
const process = require('node:process'); const { clusterWorkerCount } = require('./infrastructure/runtime-config');
require('./knexfile'); // Validate pool limits before starting any workers.
const winston = require('./application/helpers/winston.logger'); const winston = require('./application/helpers/winston.logger');
const app = require('./server');
const sticky = require('sticky-session'); const port = parseInt(process.env.PORT) || 3000;
const clustered = process.env.CLUSTER_NODE?.toUpperCase() === 'YES';
const stickySession = process.env.CLUSTER_NODE_STICKY_SESSION?.toUpperCase() === 'YES';
const multiplePorts = process.env.RUNNING_ON_MULTIPLE_PORT?.toUpperCase() === 'YES';
var serverHSMStatus = 'HSM SERVER NOT CONNECTED'; var serverHSMStatus = 'HSM SERVER NOT CONNECTED';
if (process.env.NUMBER_SERVER_ACTIVE == '1') { if (process.env.NUMBER_SERVER_ACTIVE == '1') {
@@ -29,122 +32,60 @@ if (process.env.CHANGE_TO_DRC == 'YES' || process.env.CHANGE_TO_DRC == 'yes') {
} }
} }
// jika mau di cluster gunakan script berikut: if (clustered) {
if (process.env.CLUSTER_NODE.toUpperCase() == 'YES') { if (cluster.isPrimary) {
if (cluster.isMaster) { const workerCount = clusterWorkerCount();
console.log(`Number of CPUs is ${totalCPUs}`); if (stickySession || multiplePorts) {
console.log(`Master ${process.pid} is running`); winston.logger.warn('CLUSTER_NODE=YES takes precedence over sticky session and multiple ports');
}
// Fork workers. winston.logger.info(`Starting Node.js cluster with ${workerCount} workers`);
for (let i = 0; i < totalCPUs; i++) { for (let i = 0; i < workerCount; i++) {
cluster.fork(); cluster.fork();
} }
cluster.on('exit', (worker, code, signal) => { cluster.on('exit', (worker, code) => {
console.log(`worker ${worker.process.pid} died`); winston.logger.warn(`Worker ${worker.process.pid} exited with code ${code}. Starting replacement`);
console.log("Let's fork another worker!");
console.log('with code: ' + code);
cluster.fork(); cluster.fork();
}); });
// console.log(`worker pid=${process.pid}`);
} else { } else {
startExpress(); require('./server').listen(port, () => logListening(port, ' with cluster node'));
}
} else if (stickySession) {
const workerCount = clusterWorkerCount();
const sticky = require('sticky-session');
if (cluster.isPrimary) {
if (multiplePorts) {
winston.logger.warn('CLUSTER_NODE_STICKY_SESSION=YES takes precedence over multiple ports');
}
winston.logger.info(`Starting sticky session cluster with ${workerCount} workers`);
}
const server = sticky(workerCount, () => {
const workerServer = createServer(require('./server'));
workerServer.on('connection', (socket) => socket.resume());
return workerServer;
});
if (cluster.isPrimary) {
// Keep the first HTTP bytes on the socket until the worker takes ownership.
server.pauseOnConnect = true;
server.listen(port, () => logListening(port, ' with sticky session'));
} }
} else { } else {
// jika tidak mau di cluster langsung call function startExpress const app = require('./server');
startExpress(); const ports = new Set([port]);
if (multiplePorts && process.env.PORTS) {
for (const additionalPort of process.env.PORTS.split(',')) {
ports.add(parseInt(additionalPort));
}
} else if (multiplePorts) {
winston.logger.warn('Running on multiple ports is active but PORTS is unset');
}
for (const listenPort of ports) {
app.listen(listenPort, () => logListening(listenPort));
}
} }
function startExpress() { function logListening(listenPort, mode = '') {
// set port, listen for requests
const PORT = process.env.PORT || 3000;
// jika settingan running on multiple
if (
process.env.RUNNING_ON_MULTIPLE_PORT.toUpperCase() == 'YES' &&
process.env.CLUSTER_NODE.toUpperCase() == 'NO'
) {
const PORTS = process.env.PORTS;
if (!PORTS) {
winston.logger.warn(
`Running on multiple port is active but the ports not yet set in .env`
);
} else {
let ports = PORTS.split(',');
for (let index = 0; index < ports.length; index++) {
const port = ports[index];
app.listen(port, () => {
winston.logger.info( winston.logger.info(
`Server is running on version ${ `Server is running${mode} on version ${process.env.VERSION} environment: ${(process.env.NODE_ENV || 'production').toUpperCase()} port: ${listenPort} on ${serverActive}. HSM STATUS : ${serverHSMStatus}`
process.env.VERSION
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${port} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `
); );
});
}
}
} else if (
process.env.RUNNING_ON_MULTIPLE_PORT.toUpperCase() == 'YES' &&
process.env.CLUSTER_NODE.toUpperCase() == 'YES'
) {
winston.logger.warn(
`If you want running the service on multiple port, please set CLUSTER_NODE = NO in .env file `
);
} else if (
process.env.CLUSTER_NODE_STICKY_SESSION.toUpperCase() == 'YES' &&
process.env.CLUSTER_NODE.toUpperCase() == 'YES'
) {
winston.logger.warn(
`If you want running the service with sticky session, please set CLUSTER_NODE = NO in .env file `
);
}
let message = `Server is running on version ${
process.env.VERSION
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `;
if (process.env.CLUSTER_NODE.toUpperCase() == 'YES') {
message = `Server is running with cluster node on version ${
process.env.VERSION
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `;
} else if (process.env.CLUSTER_NODE_STICKY_SESSION.toUpperCase() == 'YES') {
message = `Server is running with sticky session on version ${
process.env.VERSION
} environment: ${process.env.NODE_ENV.toUpperCase()} port: ${PORT} on ${serverActive}. HSM STATUS : ${serverHSMStatus} `;
}
if (process.env.CLUSTER_NODE_STICKY_SESSION.toUpperCase() == 'YES') {
const server = app.listen(PORT, () => {
console.log(
`Worker ${process.pid} started. Listening on port ${
server.address().port
}`
);
winston.logger.info(message);
});
// Use sticky-session with the server instance
sticky.listen(server);
} else {
app.listen(PORT, () => {
winston.logger.info(message);
});
}
} }
// Use sticky-session to handle sticky sessions
// if (!sticky.listen(cluster, port)) {
// // This is the master process, and it should not be listening to the port
// cluster.on('listening', (worker, address) => {
// console.log(
// `Worker ${worker.id} is now connected to ${address.address}:${address.port}`
// );
// });
// cluster.on('exit', (worker) => {
// console.log(`Worker ${worker.id} has exited`);
// });
// }
+20
View File
@@ -0,0 +1,20 @@
const os = require('node:os');
function positiveIntegerFromEnv(name, fallback) {
const value = process.env[name]?.trim();
if (!value) return fallback;
const number = Number(value);
if (!/^\d+$/.test(value) || !Number.isSafeInteger(number) || number < 1) {
throw new Error(`${name} must be a positive integer`);
}
return number;
}
function clusterWorkerCount() {
const availableCPUs = os.availableParallelism?.() ?? os.cpus().length;
return positiveIntegerFromEnv('CLUSTER_WORKERS', Math.min(2, availableCPUs));
}
module.exports = { positiveIntegerFromEnv, clusterWorkerCount };
+29 -8
View File
@@ -1,4 +1,16 @@
require('dotenv').config(); require('dotenv').config();
const { positiveIntegerFromEnv } = require('./infrastructure/runtime-config');
const poolOptions = {
min: 0,
idleTimeoutMillis: 30000,
acquireTimeoutMillis: positiveIntegerFromEnv('DB_POOL_ACQUIRE_TIMEOUT_MS', 5000),
};
const primaryPostgresPool = {
...poolOptions,
max: positiveIntegerFromEnv('DB_POOL_MAX', 8),
};
let host; let host;
let database; let database;
@@ -68,10 +80,7 @@ module.exports = {
password: password, password: password,
}, },
// connection: process.env.DB_URL, // connection: process.env.DB_URL,
pool: { pool: primaryPostgresPool,
min: 2,
max: 30,
},
migrations: { migrations: {
directory: './infrastructure/database/migrations', directory: './infrastructure/database/migrations',
}, },
@@ -80,12 +89,27 @@ module.exports = {
testing: { testing: {
client: 'pg', client: 'pg',
connection: process.env.DB_URL, connection: process.env.DB_URL,
pool: primaryPostgresPool,
migrations: { migrations: {
directory: './infrastructure/database/migrations', directory: './infrastructure/database/migrations',
}, },
seeds: { directory: './infrastructure/database/seeds' }, seeds: { directory: './infrastructure/database/seeds' },
}, },
pooling: {
client: 'pg',
connection: {
host: process.env.DB_HOST_POOLING,
user: process.env.DB_USER_POOLING,
password: process.env.DB_PASSWORD_POOLING,
database: process.env.DB_NAME_POOLING,
},
pool: {
...poolOptions,
max: positiveIntegerFromEnv('DB_POOLING_POOL_MAX', 2),
},
},
production: { production: {
client: 'pg', client: 'pg',
connection: { connection: {
@@ -95,10 +119,7 @@ module.exports = {
password: password, password: password,
}, },
// connection: process.env.DB_URL, // connection: process.env.DB_URL,
pool: { pool: primaryPostgresPool,
min: 2,
max: 20,
},
migrations: { migrations: {
directory: './infrastructure/database/migrations', directory: './infrastructure/database/migrations',
}, },
+2605 -8411
View File
File diff suppressed because it is too large Load Diff
+9 -7
View File
@@ -1,7 +1,7 @@
{ {
"name": "topuponline", "name": "onlinetopup-v1",
"version": "1.0.0", "version": "1.6.6",
"description": "", "description": "optimize query and coding enhancement",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start": "nodemon index", "start": "nodemon index",
@@ -23,7 +23,7 @@
"homepage": "https://github.com/mohamadihsan/topuponline#readme", "homepage": "https://github.com/mohamadihsan/topuponline#readme",
"dependencies": { "dependencies": {
"axios": "^1.7.7", "axios": "^1.7.7",
"bcrypt": "^5.0.1", "bcrypt": "^4.0.1",
"body-parser": "^1.19.0", "body-parser": "^1.19.0",
"check-internet-connected": "^2.0.6", "check-internet-connected": "^2.0.6",
"cors": "^2.8.5", "cors": "^2.8.5",
@@ -37,11 +37,13 @@
"moment": "^2.29.3", "moment": "^2.29.3",
"node-cron": "^3.0.1", "node-cron": "^3.0.1",
"pg": "^8.6.0", "pg": "^8.6.0",
"pm2": "^5.2.0", "pm2": "^6.0.13",
"prom-client": "^14.2.0", "prom-client": "^14.2.0",
"redis": "^4.6.5", "redis": "^4.6.5",
"response-time": "^2.3.2", "response-time": "^2.3.2",
"simple-update-notifier": "^2.0.0",
"sticky-session": "^0.1.0", "sticky-session": "^0.1.0",
"superagent": "^10.2.3",
"winston": "^3.7.2", "winston": "^3.7.2",
"winston-daily-rotate-file": "^4.7.1", "winston-daily-rotate-file": "^4.7.1",
"winston-loki": "^6.0.6", "winston-loki": "^6.0.6",
@@ -50,8 +52,8 @@
}, },
"devDependencies": { "devDependencies": {
"jest": "^29.0.2", "jest": "^29.0.2",
"nodemon": "^2.0.7", "nodemon": "^3.1.10",
"supertest": "^6.2.4" "supertest": "^7.1.3"
}, },
"jest": { "jest": {
"testEnvironment": "node", "testEnvironment": "node",
@@ -0,0 +1,10 @@
-- query untuk mengecek invoice date yang terlambat tergenerate lebih dari 1 bulan setelah load balance date
SELECT t.d_reservation::date, t.d_load_balance::date, TO_DATE(SUBSTRING(t.c_invoice_no FROM 7 FOR 6), 'YYMMDD') as d_invoice, t.c_invoice_no, t.c_in_period, t.c_cash_in_no
FROM trx.t_d_reservation_balance t
WHERE
t.d_reservation > '2026-01-01' AND
ABS(
t.d_load_balance::date
- TO_DATE(SUBSTRING(t.c_invoice_no FROM 7 FOR 6), 'YYMMDD')
) > 30;