mirror of
https://github.com/mohamadihsan/topuponline.git
synced 2026-12-05 10:56:27 +00:00
Compare commits
492 Commits
dev_prod
...
f7c9c186f3
| Author | SHA1 | Date | |
|---|---|---|---|
| f7c9c186f3 | |||
| cb05cb15d6 | |||
| eb22deb3a9 | |||
| 19be3bb4a9 | |||
| 572444a114 | |||
| 7957bf5a64 | |||
| ff06c45dc5 | |||
| 5762f218fd | |||
| 8d1f7a40e9 | |||
| ce0139d29a | |||
| 3792b455e8 | |||
| e496e34fae | |||
| 3f9511157f | |||
| be59fbb9e2 | |||
| 375d69c955 | |||
| 7890aed029 | |||
| 8152326743 | |||
| 30d8e70da2 | |||
| 9a4d741c05 | |||
| 18787a3605 | |||
| 69fe9b97d8 | |||
| 3027dd30b3 | |||
| 9feed0d542 | |||
| b556a40dba | |||
| e1af54e851 | |||
| 23fadc4cb0 | |||
| fefa11c544 | |||
| ce8239ca38 | |||
| c6f397d352 | |||
| 81addd40e8 | |||
| fef18ff448 | |||
| d84bc6941e | |||
| 676553409b | |||
| 72a94891ed | |||
| 84be7587a8 | |||
| 8080b89c46 | |||
| 6dbd9b6246 | |||
| 5bafb81d8d | |||
| 1dd7860c0b | |||
| 1cf06d1fdd | |||
| be2cedc869 | |||
| f5f75381ca | |||
| 5cbdccca11 | |||
| fd386788f8 | |||
| 6ddf225485 | |||
| 1645aa54aa | |||
| 797bf97bf8 | |||
| a7f5c8c8e0 | |||
| d2d44f3ba9 | |||
| 4dccbf20f5 | |||
| b888951ee3 | |||
| 87dedd241a | |||
| d4f56aacd8 | |||
| fec5209c83 | |||
| 93b6bd94ca | |||
| 39ac9e0e2d | |||
| 5037e022fd | |||
| cbb1d353a3 | |||
| f73accc275 | |||
| d7c62eda3f | |||
| a4b089ac85 | |||
| 3bf01d9059 | |||
| 8e54ebb704 | |||
| 48fb780252 | |||
| 382ccaab58 | |||
| 41444e037c | |||
| c49e4b3526 | |||
| d99882b8b9 | |||
| 45091038fe | |||
| 7c6e08a5b5 | |||
| 6e7d727b40 | |||
| 3bb2748387 | |||
| 6fea76b721 | |||
| 934e962dba | |||
| 3ccac7d220 | |||
| cede2396b7 | |||
| 9c06ec992e | |||
| 419700d6c5 | |||
| 6af2637bca | |||
| 8bb705f973 | |||
| 6755824ad0 | |||
| d93e3549ea | |||
| af697bd24d | |||
| c792a5ef15 | |||
| 282cc6372a | |||
| aea6577e38 | |||
| 6ae2de5010 | |||
| d7c3ad199a | |||
| 3808dafda7 | |||
| 14ea651b28 | |||
| 4079caa059 | |||
| 351a81a069 | |||
| 35aad851ba | |||
| e25797e091 | |||
| ac1c3c969b | |||
| 0e256ae481 | |||
| 2179a67b41 | |||
| fd3741e2ee | |||
| 2eb91dc105 | |||
| a257d50872 | |||
| fdebd4dbe9 | |||
| 745d186b3f | |||
| 0145ce5703 | |||
| a45acf1488 | |||
| bbc26c5964 | |||
| 7058143c4e | |||
| 5af2cc37d0 | |||
| 75acdc4195 | |||
| a08cedf7e8 | |||
| a16a0172a4 | |||
| 9af6f4f823 | |||
| 5259fd89ef | |||
| 0e35368e22 | |||
| 0fdc901193 | |||
| c3a458313e | |||
| 8ed7e738ab | |||
| 11b2ff8721 | |||
| 851f1b14f6 | |||
| 67c33c8e1f | |||
| ad8951c567 | |||
| 5da07d9330 | |||
| a680bc235d | |||
| 269ae0088d | |||
| fe6fe9e72e | |||
| 060c9d0b0b | |||
| 7eff55e7f3 | |||
| 810d432374 | |||
| 687521146e | |||
| e82a09187c | |||
| 3a8e2976f0 | |||
| 530b5eed7e | |||
| e9e9bbf4c8 | |||
| 29c8f60135 | |||
| cc497f606b | |||
| c17e56731f | |||
| f5574250d7 | |||
| 3a85e63c01 | |||
| 301696661d | |||
| 9fa469fc67 | |||
| 02fa5cb909 | |||
| 3dfd2a50d4 | |||
| d51325cd81 | |||
| 99ebab8591 | |||
| 92b72dbe7a | |||
| d2e1ff2274 | |||
| 5c67284a51 | |||
| b4d700e27d | |||
| d18b91edda | |||
| 3b97844c64 | |||
| 1ce4424494 | |||
| 6c5e472c4b | |||
| 57d7f260d0 | |||
| 2834265206 | |||
| 40ddf02c51 | |||
| ba20dce4d1 | |||
| aec06cb481 | |||
| 7434464106 | |||
| 01d95ae783 | |||
| d690cb2c0b | |||
| 88f82281dc | |||
| 2e5d76d97d | |||
| fc9c1a4b73 | |||
| 7d4ff6c8b3 | |||
| 8bda43d2b2 | |||
| 36139073d4 | |||
| 3c8fc4d81d | |||
| 22ce0b611a | |||
| 785e1f2542 | |||
| a6c6146933 | |||
| 0113e6dbb1 | |||
| 8d2f4bcda2 | |||
| 9aa3428620 | |||
| e8c73abf2e | |||
| 6275d8cf86 | |||
| 8af96b9a5f | |||
| d9f3516d56 | |||
| b7dec2613f | |||
| d540308d2d | |||
| 9708f81242 | |||
| 35c9fe205c | |||
| b206b50968 | |||
| 007690bcc8 | |||
| 3248d76cd6 | |||
| 1c72e98b81 | |||
| 490bc5f68a | |||
| 2480dc6ba9 | |||
| 733a39b22b | |||
| c6dffc09d9 | |||
| f4dbacd8b4 | |||
| 9dacea3399 | |||
| fdd303cb9e | |||
| 1891b551fa | |||
| 543d733820 | |||
| 9478cd4a31 | |||
| 0d2bd65350 | |||
| 8eaf79bfd1 | |||
| 9d5a0153f9 | |||
| 817832d925 | |||
| 63f4407804 | |||
| 9e876fee67 | |||
| a953df2f0f | |||
| 3e5d29e8d5 | |||
| 9cf4a717a6 | |||
| c8682214e4 | |||
| 9c8a553c30 | |||
| 388e2fc22c | |||
| f7828bccaa | |||
| adee7c1522 | |||
| 807f7f0f2e | |||
| 79e82f4581 | |||
| 503b683c16 | |||
| 944cd372a9 | |||
| 950a93ed0f | |||
| d53439f948 | |||
| a32d834a62 | |||
| 43d839ddbf | |||
| fccb28c608 | |||
| f72153d463 | |||
| 899569221c | |||
| 893a243c80 | |||
| 9e5c6ba41d | |||
| 4bd4230627 | |||
| 2e8e2586e2 | |||
| 503ecdfd6e | |||
| 79d4269b70 | |||
| 603a74a5b7 | |||
| c9a08d6832 | |||
| 308fef3ecd | |||
| 31d007dd67 | |||
| 6fe3ecc89f | |||
| b6b043b0a2 | |||
| bbdb4c2963 | |||
| 33f3b64d17 | |||
| 5ff0cae4d6 | |||
| c80b12ba53 | |||
| e3673f738c | |||
| f7d7d0efce | |||
| 30c32ca293 | |||
| 4d47090994 | |||
| 3fefaed395 | |||
| b1be54d5ba | |||
| 536d1a5c94 | |||
| 5d8369edd8 | |||
| 3c26dd6e23 | |||
| 0baf1332b6 | |||
| 5aca4559c2 | |||
| 21a45058f0 | |||
| edc70c3e6b | |||
| 4bb2facddb | |||
| 466c18fe21 | |||
| ed11c6ccc4 | |||
| 3515b5459f | |||
| e4cf444b83 | |||
| ddf01d2246 | |||
| 1fb0913eb5 | |||
| 293602bed2 | |||
| 87461a4a14 | |||
| fbcae2e596 | |||
| c7f816a449 | |||
| eeab7627ae | |||
| 9052668cbc | |||
| f615e9207f | |||
| 1ba983e745 | |||
| 8f254758dd | |||
| e7c4388956 | |||
| 3d31e6f6a5 | |||
| 1b3991c82f | |||
| 38edd07d65 | |||
| fff4915078 | |||
| 820f833844 | |||
| 1bd85ba888 | |||
| cab77e8872 | |||
| 7b52cebeb7 | |||
| 4c3496e9f2 | |||
| 529d6d7ffc | |||
| 5ca30fbfc4 | |||
| d3729ab906 | |||
| 95bfc120c5 | |||
| 9e98533ffb | |||
| 0ab80c0ac4 | |||
| ef274a483c | |||
| d129ad7a2f | |||
| 1f127807d3 | |||
| e30c78beb7 | |||
| 1014e4374a | |||
| 1d2e92b85f | |||
| 88c3b9bc4a | |||
| 51cb6c1212 | |||
| ffa6830734 | |||
| 6c93cff3bb | |||
| b24335043a | |||
| ac2ea55b5d | |||
| f3e9097bfa | |||
| 0dcec2a6ad | |||
| f8f974eb11 | |||
| 29981e9757 | |||
| a59a9090a7 | |||
| ca17c397c5 | |||
| ff1a80f3b5 | |||
| 4bda7458b4 | |||
| d4d61d1d79 | |||
| 80557a53e8 | |||
| 920a6d4ccd | |||
| ecd0cb12c4 | |||
| fe484b08af | |||
| f5a55392c9 | |||
| 2dc27ea57c | |||
| ecb78bfa29 | |||
| 74936dbe0d | |||
| b1814031b9 | |||
| b5061cf78e | |||
| a8e0376496 | |||
| 16a20faee6 | |||
| 0f34326da4 | |||
| 5a63ca6ea1 | |||
| 5d7852eff9 | |||
| 009e6caead | |||
| e61392d81a | |||
| 083e0af4a0 | |||
| 8c0b6f7e7c | |||
| b87e6cc450 | |||
| cee0352271 | |||
| afc72b73ec | |||
| dfce874ce9 | |||
| a2079a7263 | |||
| 19de123628 | |||
| b942d114ad | |||
| 69ab898bf3 | |||
| 7c66ebe702 | |||
| 84de02de26 | |||
| d5df8d4f32 | |||
| ae74b4c1bd | |||
| dab14b66c4 | |||
| 46e3cd689b | |||
| 6b0d67ee60 | |||
| 481858117d | |||
| 7805bc902b | |||
| 1fd9940706 | |||
| 95f4a03e81 | |||
| 5d8f4d086e | |||
| 4c7230ba6b | |||
| 409fe6f0ce | |||
| 1b2eff69b4 | |||
| d0e3fb289e | |||
| e3ab361b24 | |||
| fc28f4e767 | |||
| 14026e8bf0 | |||
| 4f69c84b5f | |||
| 3c1fc92d59 | |||
| 44f81586e3 | |||
| a333ddb58f | |||
| e51a7bc98c | |||
| f2c5d65ec0 | |||
| af52b6916b | |||
| bcb9225466 | |||
| ad0942a93d | |||
| 90dfdc8857 | |||
| 4828a230fb | |||
| 476235440c | |||
| 933e83cd1a | |||
| 04885f22d6 | |||
| 97860df622 | |||
| 3b68ab9ab3 | |||
| 31b581c85e | |||
| 40bd4b97e2 | |||
| a3a4772f77 | |||
| 50008e2006 | |||
| 59d77f838f | |||
| 6ef43923e1 | |||
| c30cdcf4ed | |||
| 91f759e994 | |||
| e77a975ccc | |||
| 2130890909 | |||
| edc1f35e8b | |||
| 728a9a92c9 | |||
| ceb17a5999 | |||
| 47af9992be | |||
| ede3aacef3 | |||
| de01a058eb | |||
| a6b17139bf | |||
| 23ed7baf76 | |||
| 7a7f18701d | |||
| 98c9fbe577 | |||
| dcea11420b | |||
| ff84e687ed | |||
| 24006105b9 | |||
| 2c132afdb1 | |||
| e34434f96c | |||
| c2e95ee6a5 | |||
| 6df951da14 | |||
| da1912d05d | |||
| 9cbc467904 | |||
| d3d28e496f | |||
| 0a5e82dbbb | |||
| 11b5d2317c | |||
| 7171d1e3f5 | |||
| fb5565f399 | |||
| 0df4fc0091 | |||
| 05c69b0e1d | |||
| 7ca95e17c0 | |||
| b07e9eda89 | |||
| 6c7131c944 | |||
| 05098fa3ac | |||
| 920284f07d | |||
| f97c9e6c66 | |||
| c885c49925 | |||
| 04128c8b86 | |||
| 663b92c759 | |||
| ff1582e50d | |||
| 0b921f3dc6 | |||
| ee9fa58b94 | |||
| 131cac392b | |||
| 625ad19907 | |||
| cd3c29bee0 | |||
| f1e659c64a | |||
| 8436ea2071 | |||
| df7d6909a3 | |||
| 032e12d9d0 | |||
| 5e91b9a147 | |||
| 9b8865233b | |||
| 3645bb2420 | |||
| c5b75058d3 | |||
| 18cab4b93b | |||
| 40990b3498 | |||
| fa43d34c90 | |||
| 5a0d579405 | |||
| 8e9f9dca82 | |||
| c8755f9e2d | |||
| f2e6b31b82 | |||
| 751191e10e | |||
| 33039fab21 | |||
| 2c31a4e425 | |||
| b5b72ecf6c | |||
| b7e5d0c426 | |||
| 82bd1c5276 | |||
| c39675b1ac | |||
| 146e64fc63 | |||
| 058cd6edfc | |||
| 3fb2124534 | |||
| c4f276289a | |||
| f8aacae0ea | |||
| 0e237bd66d | |||
| 8e8704a1a2 | |||
| 25c3d03761 | |||
| 3be8c88db4 | |||
| 983902d08e | |||
| 7a09320404 | |||
| ff245148f6 | |||
| 5a4870408c | |||
| e3ef16753e | |||
| 90aaf3f6f6 | |||
| 0437eaab25 | |||
| 4a98a1c5cd | |||
| 3c927b6385 | |||
| 41bdf42bac | |||
| 986f2de372 | |||
| be1c3c179b | |||
| 1df38dbdf0 | |||
| aae040e908 | |||
| 37a81c826a | |||
| 34ee6cc703 | |||
| 7476de9ebe | |||
| 094d9809ff | |||
| 74993b5e26 | |||
| 5ceb25c892 | |||
| 2c744a350c | |||
| 270f859e0d | |||
| ba46437d11 | |||
| 255fb13ab7 | |||
| 7685916b19 | |||
| 0d1e4869be | |||
| 052c71220f | |||
| 6234fb5e36 | |||
| 4f72e83710 | |||
| 10f9f3a0bb | |||
| 8a5127a9e8 | |||
| bb666ee512 | |||
| 9ba2e03187 | |||
| f39c92f28d | |||
| 0f36b9f264 | |||
| c7334aa084 | |||
| e714540970 | |||
| dd52e4ce01 | |||
| c22d1b3596 | |||
| e41fa25c05 | |||
| 659531d908 | |||
| 8f8da98f6e | |||
| 56cbc627a2 | |||
| a2a9a8c72f | |||
| 1af459fc4e | |||
| 47dc7eecc9 | |||
| a8d32ada48 |
@@ -0,0 +1,109 @@
|
||||
---
|
||||
name: principal-code-craftsmanship
|
||||
description: |
|
||||
Standar rekayasa backend, arsitektur (Clean/DDD), query DB efisien (zero N+1), memori, dan error handling level Principal/Staff Engineer. Gunakan saat merancang, menulis, atau me-refactor kode backend, database, dan logika bisnis.
|
||||
---
|
||||
|
||||
# Principal / Staff Software Architect Engineering Standard (15+ Years Experience)
|
||||
|
||||
Standar ini menetapkan level rekayasa perangkat lunak tertinggi setara **Principal / Staff Engineer / Lead Architect** dari ekosistem teknologi kelas dunia. Setiap baris kode harus mencerminkan kematangan teknis, keanggunan struktur, efisiensi sumber daya ekstrem, dan kemudahan pemeliharaan jangka panjang.
|
||||
|
||||
---
|
||||
|
||||
## 🏛️ 1. Pemahaman & Arsitektur Mendalam (Architectural Rigor)
|
||||
- **Separation of Concerns yang Tegas**:
|
||||
- `Delivery / Handler`: Hanya bertugas parsing HTTP request, validasi format DTO awal, pemanggilan usecase, dan formatting response HTTP. Dilarang keras menaruh query SQL atau aturan bisnis inti di layer ini.
|
||||
- `Usecase / Service`: Mengorkestrasi aturan bisnis (business workflows), validasi domain, kalkulasi, transaksi multi-tabel, dan audit logging.
|
||||
- `Repository`: Mengisolasi penuh interaksi database/storage. Menerima dan mengembalikan domain entity / value objects.
|
||||
- `Domain`: Mendefinisikan struct entitas bisnis murni dan interface kontrak tanpa ketergantungan pada framework eksternal.
|
||||
- **Transaksionalitas & Integritas Data (ACID)**:
|
||||
- Operasi yang melibatkan lebih dari satu tabel (contoh: pembuatan transaksi + insert detail + pemotongan stok + invoice log) **WAJIB** berada dalam satu Database Transaction (`tx`).
|
||||
- Lakukan *rollback* otomatis dengan `defer tx.Rollback()` jika terjadi error pada langkah manapun sebelum `tx.Commit()`.
|
||||
- Mencegah deadlock dengan selalu mengunci baris data dalam urutan ID yang deterministik jika melakukan update konkuren.
|
||||
|
||||
---
|
||||
|
||||
## 📖 2. Keterbacaan Kode & Kerapihan Ekstrem (Zero Cognitive Load)
|
||||
- **Guard Clauses & Early Returns**:
|
||||
- Hindari piramida nesting `if-else` bertingkat yang dalam.
|
||||
- Validasi error atau kondisi tepi (*edge cases*) di awal fungsi dan langsung lakukan return (`if err != nil { return err }`).
|
||||
- **Penamaan Simbol yang Self-Documenting**:
|
||||
- Gunakan penamaan variabel dan fungsi yang memiliki makna bisnis eksplisit (contoh: `isStockSufficient`, `calculateEligibleDiscount`, `deductWarehouseStock`).
|
||||
- Hindari singkatan ambigu atau nama variabel 1 huruf kecuali index loop standar (`i`, `j`).
|
||||
- **Fungsi Berukuran Ringkas & Single Responsibility**:
|
||||
- Satu fungsi/method hanya melakukan satu tugas secara sempurna. Jika fungsi melebihi 40-50 baris, pecah bagian logikanya menjadi private helper methods yang bersih.
|
||||
|
||||
---
|
||||
|
||||
## ⚡ 3. Logika & Algoritma Efisien (Algorithmic Precision)
|
||||
- **Eliminasi Kompleksitas $O(N^2)$**:
|
||||
- Hindari perulangan bersarang (*nested loops*) untuk mencocokkan data relasional.
|
||||
- Transformasikan data pembanding ke dalam Hash Map / Dictionary ($O(1)$ lookup) sebelum iterasi utama:
|
||||
```go
|
||||
// CONTOH SENIOR: O(N) lookup bukan nested loop O(N*M)
|
||||
productMap := make(map[int64]domain.Produk, len(products))
|
||||
for _, p := range products {
|
||||
productMap[p.ID] = p
|
||||
}
|
||||
for _, item := range orderItems {
|
||||
if prod, exists := productMap[item.ProductID]; exists {
|
||||
// Proses dengan O(1) akses
|
||||
}
|
||||
}
|
||||
```
|
||||
- **Idempotensi**:
|
||||
- Pastikan operasi krusial (pembayaran, pembatalan pesanan, webhook) aman dieksekusi lebih dari satu kali tanpa menduplikasi data atau merusak saldo/stok.
|
||||
|
||||
---
|
||||
|
||||
## 🚀 4. Kinerja Query & Database Tingkat Lanjut (Database Mastery)
|
||||
- **Anti-N+1 Queries**:
|
||||
- Jangan pernah menjalankan query di dalam perulangan (`for loop`). Selalu kumpulkan ID yang dibutuhkan dan jalankan satu query `WHERE id IN (...)` secara batch.
|
||||
- **Selective Column Scanning (No Blind `SELECT *`)**:
|
||||
- Hanya ambil kolom yang benar-benar dibutuhkan oleh operasi terkait. Contoh: untuk verifikasi stok, hanya scan `(produk_id, qty)` atau `(id, stok)`.
|
||||
- Hal ini memangkas transfer data jaringan, menghemat buffer pool DB, dan mencegah bug tipe data scan seperti pointer mismatch.
|
||||
- **Pemanfaatan Index & Sizing**:
|
||||
- Pastikan klausa `WHERE`, `JOIN`, dan `ORDER BY` memanfaatkan index komposit yang tersedia.
|
||||
- Untuk paginasi dataset besar, prioritaskan *cursor-based pagination* atau limit/offset yang ter-index.
|
||||
|
||||
---
|
||||
|
||||
## 💾 5. Efisiensi Memori & Sumber Daya (Zero-Waste Resources)
|
||||
- **Pre-Alokasi Kapasitas Slice & Map (Go)**:
|
||||
- Selalu definisikan kapasitas awal slice jika ukuran maksimumnya sudah diketahui:
|
||||
```go
|
||||
// Sangat efisien, mencegah alokasi memori berulang di heap
|
||||
results := make([]domain.DetailTransaksi, 0, len(items))
|
||||
```
|
||||
- **Context Lifecycle & Cancellation**:
|
||||
- Teruskan `context.Context` ke semua panggilan I/O, database query, dan HTTP client.
|
||||
- Hormati pembatalan context (`ctx.Done()`) agar koneksi atau goroutine tidak menggantung jika client memutuskan koneksi.
|
||||
- **Pembersihan Sumber Daya Terjamin**:
|
||||
- Selalu tutup file handler, HTTP response body, atau DB cursor menggunakan `defer`.
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ 6. Penanganan Bug & Error yang Human-Friendly (Defensive Resilience)
|
||||
- **Error Bertingkat dengan Konteks**:
|
||||
- Bungkus error teknis dengan konteks asal fungsi menggunakan `fmt.Errorf("failed to deduct stock for product %d: %w", productID, err)`.
|
||||
- **Pesan untuk Pengguna yang Jelas & Tidak Menakutkan**:
|
||||
- Konversikan pesan error teknis database/sistem menjadi pesan bisnis yang ramah dalam Bahasa Indonesia pada API response:
|
||||
- Bukan: *"sql: duplicate key value violates unique constraint"*
|
||||
- Melainkan: *"Kode transaksi tersebut sudah pernah dibuat sebelumnya. Silakan periksa kembali."*
|
||||
- **Structured Logging (Zap Logger)**:
|
||||
- Catat log error dengan field berstruktur (`zap.Int64("user_id", ...), zap.String("action", ...), zap.Error(err)`), bukan sekadar string gabungan.
|
||||
|
||||
---
|
||||
|
||||
## 📝 7. Catatan & Dokumentasi Berbahasa Indonesia Berkualitas Tinggi
|
||||
- Setiap method atau logika penting wajib memiliki docstring/komentar dalam **Bahasa Indonesia** yang rapi, profesional, dan menjelaskan:
|
||||
1. **Tujuan bisnis**: Apa fungsi logika ini.
|
||||
2. **Alasan (*The Why*)**: Mengapa pendekatan ini dipilih atau aturan bisnis apa yang mendasarinya.
|
||||
3. **Edge Case**: Kasus batas apa yang diantisipasi (misal: penanganan timeout, stok minus, pembulatan desimal).
|
||||
- Contoh gaya komentar standar Principal:
|
||||
```go
|
||||
// ValidateAndDeductStock memvalidasi ketersediaan stok fisik di gudang terkait
|
||||
// sebelum pesanan dibuat. Menggunakan row locking (FOR UPDATE) untuk mencegah
|
||||
// kondisi race condition (overselling) pada transaksi konkuren volume tinggi.
|
||||
```
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
---
|
||||
name: principal-qa-engineering
|
||||
description: |
|
||||
Standar Quality Assurance & Staff SDET level Principal. Gunakan saat merancang strategi pengujian, menulis unit/integration/API/concurrency test, review PR, atau melakukan verifikasi kualitas sebelum rilis. (Untuk E2E browser, rujuk skill playwright-e2e-testing).
|
||||
---
|
||||
|
||||
# Principal QA Engineering & Quality Gate Standard (Staff SDET)
|
||||
|
||||
Standar ini memastikan kualitas perangkat lunak dibangun sejak desain (*shift-left*), teruji secara deterministik di setiap layer, dan siap rilis tanpa regresi.
|
||||
|
||||
---
|
||||
|
||||
## 1. Risk-Based Test Strategy & Testing Trophy
|
||||
- **Proporsi Pengujian yang Sehat**:
|
||||
- **Unit Test (Mayoritas)**: Cepat, terisolasi, menguji logika bisnis murni, kalkulasi, dan *edge cases*.
|
||||
- **Integration Test (Kritis)**: Menguji interaksi nyata ke database, cache, dan message queue (gunakan DB test terisolasi/rollback transaksi, jangan mock DB untuk query bisnis).
|
||||
- **API / Contract Test**: Menguji HTTP status code, skema JSON, validasi input, dan format error.
|
||||
- **E2E Browser Test (Selektif)**: Hanya untuk *critical user journeys*; delegasikan implementasinya ke skill `playwright-e2e-testing`.
|
||||
- **Risk Matrix**: Prioritaskan cakupan tertinggi pada alur berisiko tinggi (autentikasi, otorisasi/tenant isolation, pembayaran, pemotongan stok, dan mutasi saldo).
|
||||
|
||||
---
|
||||
|
||||
## 2. Sistematika Desain Test Case (Zero Blind Spots)
|
||||
Setiap fitur atau endpoint baru wajib diuji dengan kategori berikut:
|
||||
- **Boundary Value Analysis (BVA)**: Nilai batas (`0`, `-1`, `1`, `MAX_INT`, string kosong `""`, whitespace, panjang karakter maksimum, angka desimal/pembulatan mata uang).
|
||||
- **Equivalence & Negative Cases**: Tipe data salah, field wajib hilang, format invalid, token kedaluwarsa, akses lintas user/tenant (IDOR), dan payload melebihi batas.
|
||||
- **State Transition**: Pastikan alur status (mis. `draft` -> `paid` -> `void`) menolak transisi ilegal dan hanya mengizinkan transisi yang sah.
|
||||
|
||||
---
|
||||
|
||||
## 3. Database, Idempotency & Concurrency Testing
|
||||
- **Transaction & Rollback**: Uji skenario kegagalan di tengah proses multi-tabel untuk memastikan seluruh perubahan di-rollback sempurna tanpa data yatim (*orphan records*).
|
||||
- **Idempotency**: Uji pengiriman ulang (*retry* / double click / duplicate webhook) pada operasi mutasi agar tidak menggandakan transaksi atau saldo.
|
||||
- **Concurrency / Race Condition**: Untuk operasi stok/saldo/kuota, buat test paralel (goroutine / `Promise.all` / multi-thread) guna memverifikasi locking atau optimistic concurrency berjalan tanpa *overselling*.
|
||||
|
||||
---
|
||||
|
||||
## 4. Test Determinism & Data Management (Anti-Flaky)
|
||||
- **Test Isolation**: Setiap test wajib independen (buat data sendiri via Factory/Builder, bersihkan via transaksi rollback atau cleanup hook). Dilarang bergantung pada urutan eksekusi test lain.
|
||||
- **Zero Arbitrary Sleep**: Dilarang menggunakan `sleep()` tetap untuk menunggu proses asinkron; gunakan *polling/condition wait* dengan timeout eksplisit.
|
||||
- **Fake Clock & Boundary Mocking**: Inject waktu (*clock interface*) untuk menguji kedaluwarsa/timezone. Hanya mock *external third-party boundary* (payment gateway, WA/email API), jangan mock logika domain inti.
|
||||
|
||||
---
|
||||
|
||||
## 5. Non-Functional Quality & Resilience
|
||||
- **Fault Injection**: Verifikasi sistem tetap mengembalikan error yang aman dan terkontrol saat dependency eksternal timeout atau mengembalikan HTTP 5xx.
|
||||
- **Performance Baseline**: Untuk endpoint kritikal atau query dataset besar, verifikasi tidak ada regresi N+1 query dan pantau latensi p95/p99 di bawah beban wajar.
|
||||
|
||||
---
|
||||
|
||||
## 6. Quality Gates & Bug-to-Test Policy
|
||||
- **Critical-Path Coverage**: Fokus pada cakupan cabang logika (*branch coverage*) dan alur bisnis kritis, bukan sekadar mengejar angka 100% *line coverage* semu.
|
||||
- **Bug-to-Test Rule (Wajib)**: Setiap bug yang ditemukan di QA atau produksi **wajib** memiliki minimal 1 automated regression test yang gagal sebelum perbaikan dan lulus setelah perbaikan.
|
||||
- **Go / No-Go Release Gate**:
|
||||
1. Seluruh unit, integration, dan contract test hijau tanpa *skipped/flaky test*.
|
||||
2. Migrasi database sudah diverifikasi aman (sinkron dengan `secure-software-hardening`).
|
||||
3. Tidak ada error 500 tak tertangani atau kebocoran data sensitif pada log/response.
|
||||
@@ -0,0 +1,97 @@
|
||||
---
|
||||
name: root-cause-debugging
|
||||
description: |
|
||||
Metodologi diagnosis bug mendalam (RCA), forensik crash, analisis query DB lambat & deadlock lintas bahasa. Gunakan saat investigasi error 500, memory leak, high CPU, race condition, atau bug fixing existing project.
|
||||
---
|
||||
|
||||
# Universal Root Cause Debugging & Schema Forensics Standard (Staff Site Reliability & Systems Engineer)
|
||||
|
||||
Standar ini memandu investigasi kegagalan sistem secara metodis, ilmiah, dan presisi. Dilarang melakukan perbaikan spekulatif (*guess-and-check* atau sekadar menambal simptom luar). Setiap perbaikan wajib mengidentifikasi akar penyebab struktural (*root cause*) dan menyertakan mitigasi anti-regresi.
|
||||
|
||||
---
|
||||
|
||||
## 🔬 1. Metodologi RCA 5 Tahap (The 5-Stage RCA Protocol)
|
||||
|
||||
```mermaid
|
||||
flowchart LR
|
||||
S1["1. Observasi &<br/>Kumpulkan Bukti"] --> S2["2. Isolasi &<br/>Minimal Reproduksi"]
|
||||
S2 --> S3["3. Bedah Akar Masalah<br/>(Bukan Simptom)"]
|
||||
S3 --> S4["4. Perbaikan Bedah<br/>(Surgical Fix)"]
|
||||
S4 --> S5["5. Verifikasi &<br/>Tes Anti-Regresi"]
|
||||
```
|
||||
|
||||
### Tahap 1: Observasi & Forensik Log
|
||||
- Jangan langsung mengubah kode sebelum memahami jejak error.
|
||||
- Kumpulkan fakta objektif:
|
||||
- **Stack trace lengkap**: Baris file, method, dan package asal muasal error.
|
||||
- **Input payload**: Parameter URL, query params, request body, dan tipe datanya.
|
||||
- **Kondisi lingkungan**: Versi app, role user, status database (apakah data terkait berstatus pending, null, dsb.).
|
||||
|
||||
### Tahap 2: Isolasi & Minimal Reproducible Example (MRE)
|
||||
- Buat skenario minimal yang mampu memicu bug tersebut secara konsisten:
|
||||
- Tulis satu unit test / integration test kecil yang **sengaja gagal (FAIL)** akibat bug tersebut.
|
||||
- Jika test berhasil mereproduksi bug, Anda telah mengisolasi 80% dari masalah.
|
||||
|
||||
### Tahap 3: Identifikasi Akar Penyebab (*The Root Cause*)
|
||||
Tanyakan *"Mengapa"* hingga mencapai akar struktural:
|
||||
- *Simptom*: `Scan error: can't scan int64 into float64`.
|
||||
- *Penyebab Level 1*: Tipe data kolom DB berbeda dengan tipe struct di Go.
|
||||
- *Penyebab Level 2 (Akar Masalah)*: Query menggunakan `SELECT *` sehingga memindai kolom yang tidak diperlukan untuk kalkulasi stok, dan kolom tersebut memiliki tipe data historis yang tidak kompatibel.
|
||||
|
||||
### Tahap 4: Perbaikan Bedah (*Surgical Fix*)
|
||||
- Perbaiki akar masalahnya secara bersih, bukan sekadar membungkus dengan `try-catch` kosong atau menyamarkan error (*swallowing error*).
|
||||
- Hindari perubahan besar (*massive refactor*) yang tidak berhubungan dengan bug saat proses patching.
|
||||
|
||||
### Tahap 5: Verifikasi Anti-Regresi
|
||||
- Jalankan test yang dibuat di Tahap 2 → pastikan kini berubah status menjadi **LULUS (PASS)**.
|
||||
- Jalankan keseluruhan test suite project untuk memastikan fungsionalitas lain di sekitarnya tidak terdampak (*zero side-effects*).
|
||||
|
||||
---
|
||||
|
||||
## 🗄️ 2. Forensik Database & Desain Skema (Schema Forensics)
|
||||
|
||||
### A. Mendiagnosis Deadlock & Lock Contention
|
||||
- **Ciri**: Request API menggantung lama (*hanging*) lalu berakhir dengan timeout 500 atau pesan `deadlock detected (SQLSTATE 40P01)`.
|
||||
- **Akar Penyebab**: Dua transaksi konkuren mencoba mengunci dua baris data yang sama dalam urutan yang berlawanan:
|
||||
- Transaksi A mengunci Baris 1 → menunggu Baris 2.
|
||||
- Transaksi B mengunci Baris 2 → menunggu Baris 1.
|
||||
- **Solusi Standar Staff Architect**:
|
||||
1. Selalu urutkan daftar ID yang akan dikunci secara deterministik sebelum operasi `FOR UPDATE`:
|
||||
```go
|
||||
// BENAR: Kunci selalu berurutan dari ID terkecil ke terbesar
|
||||
sort.Slice(productIDs, func(i, j int) bool { return productIDs[i] < productIDs[j] })
|
||||
```
|
||||
2. Persingkat durasi transaksi database (jangan letakkan remote HTTP call pihak ketiga di dalam blok transaksi DB!).
|
||||
|
||||
### B. Mendiagnosis Konflik Soft Delete & Unique Constraint
|
||||
- **Ciri**: Error `duplicate key value violates unique constraint` saat user mendaftar ulang dengan email yang sama padahal akun lama sudah dihapus (*soft deleted*).
|
||||
- **Akar Masalah**: Index unique standar (`UNIQUE(email)`) tetap memperhitungkan baris data yang memiliki `deleted_at IS NOT NULL`.
|
||||
- **Solusi Skema**:
|
||||
Gunakan **Partial Unique Index** (PostgreSQL):
|
||||
```sql
|
||||
-- Index hanya berlaku untuk baris data yang belum dihapus
|
||||
CREATE UNIQUE INDEX uq_users_active_email ON users(email) WHERE deleted_at IS NULL;
|
||||
```
|
||||
|
||||
### C. Mendiagnosis Query Lambat dengan `EXPLAIN ANALYZE`
|
||||
- Jalankan `EXPLAIN (ANALYZE, BUFFERS) <query>` untuk melihat execution plan:
|
||||
- **`Seq Scan` pada tabel besar**: Mengindikasikan index hilang atau klausa `WHERE` menggunakan fungsi yang membatalkan index (contoh: `WHERE LOWER(email) = ...` membutuhkan expression index `CREATE INDEX ON users(LOWER(email))`).
|
||||
- **`Nested Loop` dengan row count besar**: Mengindikasikan join tidak menggunakan index pada foreign key.
|
||||
|
||||
---
|
||||
|
||||
## ⚡ 3. Forensik Memory Leak & CPU Spike
|
||||
|
||||
| Ekosistem | Gejala Umum | Alat & Langkah Investigasi |
|
||||
|---|---|---|
|
||||
| **Go** | RAM terus naik tanpa pernah turun, OOM kill di container. | Gunakan `net/http/pprof`. Periksa goroutine leak (`/debug/pprof/goroutine`): biasanya akibat goroutine menunggu unbuffered channel tanpa context timeout. |
|
||||
| **Node.js** | Event loop lag tinggi, heap memory exhaustion. | Gunakan `--inspect` dan rekam Chrome DevTools Heap Snapshot. Cari detached DOM nodes atau event listener yang tidak di-unsubscribe. |
|
||||
| **Python** | Memori bertambah seiring bertambahnya request. | Gunakan modul `tracemalloc` atau `objgraph` untuk mendeteksi siklus referensi objek yang tidak terjangkau garbage collection. |
|
||||
| **Database** | CPU DB 100%, koneksi pool habis (*exhausted*). | Cek query yang sedang berjalan via `pg_stat_activity WHERE state = 'active' ORDER BY query_start`. Cari query tanpa limit atau N+1 query yang membanjiri pool. |
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ 4. Aturan Penutupan Bug (Mandatory Anti-Regression)
|
||||
- Setiap perbaikan bug pada *existing project* **WAJIB** disertai minimal 1 automated regression test (unit atau integration test) yang mereproduksi kondisi bug sebelum diperbaiki dan lulus setelah perbaikan.
|
||||
- Jika penyebabnya adalah asumsi data/edge-case yang terlewat, periksa apakah pola bug serupa ada di modul lain sebelum menutup tiket.
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
---
|
||||
name: secure-software-hardening
|
||||
description: |
|
||||
Standar keamanan aplikasi (OWASP Top 10, auth/JWT/CORS, anti-SQLi/XSS/IDOR) dan keamanan migrasi database produksi (Zero-Downtime DDL) lintas bahasa. Gunakan saat merancang auth, mengamankan endpoint, atau membuat migrasi DB produksi.
|
||||
---
|
||||
|
||||
# Universal Security Hardening & Database Safety Standard (Principal Security Architect)
|
||||
|
||||
Standar ini memandu pengerasan keamanan menyeluruh pada aplikasi backend, frontend, API, dan basis data produksi. Wajib diterapkan untuk melindungi integritas sistem, data pengguna, dan mencegah downtime fatal saat perubahan skema data.
|
||||
|
||||
---
|
||||
|
||||
## 🛡️ 1. Pencegahan Injeksi & Sanitasi Data (Zero-Trust Input)
|
||||
|
||||
- **SQL Injection (SQLi)**:
|
||||
- Dilarang keras menggabungkan string (*string concatenation/formatting*) ke dalam klausa SQL (`fmt.Sprintf`, `f"..."`, `"...".$var`).
|
||||
- Selalu gunakan *Parameterized Queries* / *Prepared Statements* atau ORM yang aman:
|
||||
- **Go (Bun/database/sql)**: `Where("user_id = ?", userID)` atau `db.Query("SELECT ... WHERE id = $1", id)`
|
||||
- **Node.js (Prisma/Knex/pg)**: `prisma.user.findUnique(...)` atau `$1, $2`
|
||||
- **Python (SQLAlchemy/Django)**: `session.execute(text("SELECT ... WHERE id = :id"), {"id": uid})`
|
||||
- **PHP (PDO/Laravel)**: `DB::select('SELECT ... WHERE id = ?', [$id])`
|
||||
- **Cross-Site Scripting (XSS)**:
|
||||
- Jangan pernah merender input mentah dari user langsung ke HTML (hindari `dangerouslySetInnerHTML`, `v-html`, `{!! $var !!}`).
|
||||
- Jika memerlukan HTML rich-text, gunakan library sanitizer tersertifikasi (contoh: DOMPurify, sanitize-html).
|
||||
- **Command Injection**:
|
||||
- Hindari eksekusi shell command (`exec`, `system`, `shell_exec`, `child_process.exec`). Jika mutlak diperlukan, gunakan argumen array terpisah (`execFile(['git', 'status'])`), jangan pernah lewatkan input user ke dalam string command.
|
||||
|
||||
---
|
||||
|
||||
## 🔐 2. Otorisasi Objek & Kontrol Akses (IDOR / BOLA Prevention)
|
||||
Broken Object Level Authorization (IDOR) adalah celah nomor 1 pada REST API.
|
||||
|
||||
- **Aturan Kepemilikan Wajib (*Ownership Assertion*)**:
|
||||
- Jangan pernah mengandalkan ID dari parameter URL tanpa memverifikasi hak akses user:
|
||||
```sql
|
||||
-- SALAH: Rentan IDOR (user A bisa mengakses transaksi user B)
|
||||
SELECT * FROM transaksi WHERE id = :targetId;
|
||||
|
||||
-- BENAR: Pastikan data memang milik user yang sedang login (atau admin dengan role resmi)
|
||||
SELECT * FROM transaksi WHERE id = :targetId AND (user_id = :authenticatedUserId OR :isAdmin = true);
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🔑 3. Pengamanan Token, Cookie & Sesi
|
||||
- **Cookie Flags Wajib**:
|
||||
- `HttpOnly`: Mencegah script JavaScript (XSS) membaca cookie autentikasi.
|
||||
- `Secure`: Cookie hanya dikirimkan melalui protokol HTTPS terenkripsi.
|
||||
- `SameSite=Lax` (atau `Strict`): Mencegah serangan Cross-Site Request Forgery (CSRF).
|
||||
- **JWT Best Practices**:
|
||||
- Gunakan masa berlaku Access Token yang singkat (contoh: 15–30 menit).
|
||||
- Gunakan Refresh Token Rotation: setiap kali refresh token dipakai, token lama dihanguskan dan token baru diterbitkan untuk mendeteksi pencurian token (*token reuse detection*).
|
||||
|
||||
---
|
||||
|
||||
## 🌐 4. CORS & Keamanan Header HTTP
|
||||
- **CORS Ketat**:
|
||||
- Dilarang mengizinkan wildcard `Access-Control-Allow-Origin: *` jika endpoint menerima kredensial/cookie.
|
||||
- Tentukan domain whitelist yang eksplisit (contoh: `https://member.esensi.id`, `https://esensi.id`).
|
||||
- **Security Headers Wajib**:
|
||||
- `X-Content-Type-Options: nosniff`
|
||||
- `X-Frame-Options: DENY` atau `SAMEORIGIN` (mencegah Clickjacking)
|
||||
- `Strict-Transport-Security (HSTS)`
|
||||
- `Referrer-Policy: strict-origin-when-cross-origin`
|
||||
|
||||
---
|
||||
|
||||
## 🗄️ 5. Database Safety & Zero-Downtime DDL (Tabel Produksi)
|
||||
|
||||
Operasi DDL yang ceroboh pada tabel besar dapat mengunci (*exclusive table lock*) seluruh sistem dan memicu downtime.
|
||||
|
||||
### A. Aturan Pembuatan Index Tanpa Lock
|
||||
- Pada PostgreSQL, **WAJIB** membuat index menggunakan klausa `CONCURRENTLY`:
|
||||
```sql
|
||||
-- BENAR: Tidak mengunci operasi INSERT/UPDATE yang sedang berlangsung
|
||||
CREATE INDEX CONCURRENTLY idx_transaksi_created_at ON transaksi(created_at);
|
||||
```
|
||||
|
||||
### B. Aturan Penambahan Kolom Baru
|
||||
- Hindari menambahkan kolom baru dengan `DEFAULT` bernilai dinamis atau expression berat pada tabel jutaan baris tanpa evaluasi lock.
|
||||
- Pola aman: Tambahkan kolom sebagai `NULLABLE` terlebih dahulu → migrasikan data secara bertahap → baru tambahkan constraint `NOT NULL` jika diperlukan.
|
||||
|
||||
### C. Strategi Perubahan Kolom Breaking (Expand and Contract Pattern)
|
||||
Jangan langsung me-rename atau menghapus kolom yang sedang aktif dipakai backend:
|
||||
1. **Fase 1 (Expand)**: Tambahkan kolom baru. Update aplikasi agar menulis ke kolom baru dan kolom lama secara paralel.
|
||||
2. **Fase 2 (Backfill)**: Salin data historis dari kolom lama ke kolom baru secara bertahap (*batching*).
|
||||
3. **Fase 3 (Contract)**: Alihkan seluruh proses baca ke kolom baru.
|
||||
4. **Fase 4 (Cleanup)**: Hapus kolom lama setelah seluruh instance aplikasi menggunakan kolom baru.
|
||||
|
||||
### D. Safe Data Backfilling (Anti-Lock Batching)
|
||||
Jangan jalankan satu query update raksasa:
|
||||
```sql
|
||||
-- SALAH: Mengunci jutaan baris sekaligus, memicu kehabisan lock memory & timeout
|
||||
UPDATE orders SET status = 'completed' WHERE status IS NULL;
|
||||
|
||||
-- BENAR: Jalankan dalam batch kecil berulang (misal 1.000 row per batch)
|
||||
DO $$
|
||||
DECLARE
|
||||
rows_updated INT;
|
||||
BEGIN
|
||||
LOOP
|
||||
UPDATE orders SET status = 'completed'
|
||||
WHERE id IN (
|
||||
SELECT id FROM orders WHERE status IS NULL LIMIT 1000 FOR UPDATE SKIP LOCKED
|
||||
);
|
||||
GET DIAGNOSTICS rows_updated = ROW_COUNT;
|
||||
EXIT WHEN rows_updated = 0;
|
||||
COMMIT;
|
||||
END LOOP;
|
||||
END $$;
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧹 6. Sanitasi Log & Proteksi Rahasia (No Secrets in Logs)
|
||||
- Sensor/masking data sensitif sebelum dicatat ke log (misal `password`, `token`, `pin`, `nomor_kartu`, `cvv`, `nik`).
|
||||
- Dilarang men-commit file konfigurasi yang berisi kredensial plaintext (`.env`, private keys, password VPS) ke dalam version control. Selalu gunakan file template `.env.example`.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
/lokiLog/audit/
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
@@ -5,4 +5,39 @@
|
||||
## In PRODUCTION environment, online topup log and error log will be active.
|
||||
# debugging log contains log all validation checks step by step, request data from client, error log, and response data to client
|
||||
# online topup log contains request data from client, error log, and response data to client
|
||||
# error log contains only error system or error service
|
||||
# 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.
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { randomUUID } = require('node:crypto');
|
||||
|
||||
// Satu deskriptor append per proses membatasi memori tanpa menunggu layanan log eksternal.
|
||||
function createAuditArchive(directory, { retentionDays = 0 } = {}) {
|
||||
let day;
|
||||
let descriptor;
|
||||
let lastPrunedDay;
|
||||
const runId = randomUUID();
|
||||
|
||||
function pruneExpiredFiles(time) {
|
||||
if (!retentionDays || lastPrunedDay === new Date(time).toISOString().slice(0, 10)) return 0;
|
||||
lastPrunedDay = new Date(time).toISOString().slice(0, 10);
|
||||
const cutoffDay = new Date(time - retentionDays * 24 * 60 * 60 * 1000)
|
||||
.toISOString()
|
||||
.slice(0, 10);
|
||||
let errors = 0;
|
||||
|
||||
try {
|
||||
for (const name of fs.readdirSync(directory)) {
|
||||
const match = /^(\d{4}-\d{2}-\d{2})-\d+-[a-f0-9-]+\.jsonl$/i.exec(name);
|
||||
if (!match || match[1] >= cutoffDay) continue;
|
||||
try {
|
||||
fs.unlinkSync(path.join(directory, name));
|
||||
} catch {
|
||||
errors += 1;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
errors += 1;
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
function append(line, time) {
|
||||
const date = new Date(time).toISOString().slice(0, 10);
|
||||
if (day !== date) {
|
||||
close();
|
||||
fs.mkdirSync(directory, { recursive: true, mode: 0o750 });
|
||||
descriptor = fs.openSync(path.join(directory, `${date}-${process.pid}-${runId}.jsonl`), 'a', 0o640);
|
||||
day = date;
|
||||
}
|
||||
fs.appendFileSync(descriptor, `${line}\n`);
|
||||
return { retentionErrors: pruneExpiredFiles(time) };
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (descriptor !== undefined) fs.closeSync(descriptor);
|
||||
descriptor = undefined;
|
||||
day = undefined;
|
||||
}
|
||||
|
||||
return { append, close };
|
||||
}
|
||||
|
||||
module.exports = createAuditArchive;
|
||||
@@ -0,0 +1,171 @@
|
||||
const { randomUUID } = require('node:crypto');
|
||||
const winston = require("winston");
|
||||
const expressWinston = require("express-winston");
|
||||
const moment = require("moment");
|
||||
const responseAudit = require("./response-audit");
|
||||
const { writeStdoutLine, formatLog } = require("./stdout-log");
|
||||
const knex = require("../../infrastructure/database/knex");
|
||||
const {
|
||||
topuponline_metrics,
|
||||
topuponline_metrics_response_time,
|
||||
topuponline_metrics_load_balance,
|
||||
} = require("../helpers/prometheusmetrics");
|
||||
|
||||
const routes = new Set([
|
||||
"/api/reservation",
|
||||
"/api/reservation/v2",
|
||||
"/api/loadbalance/request",
|
||||
"/api/topup1",
|
||||
"/api/topup2",
|
||||
"/api/topup3",
|
||||
"/api/topup4",
|
||||
"/api/topup5",
|
||||
"/api/topup6",
|
||||
"/api/topup7",
|
||||
"/api/topup8",
|
||||
]);
|
||||
|
||||
function getRoute(url) {
|
||||
return url.split('?', 1)[0];
|
||||
}
|
||||
|
||||
// Tandai respons yang dipantau dengan ID unik per request, termasuk ketika HSM gagal.
|
||||
function correlation(req, res, next) {
|
||||
if (routes.has(getRoute(req.originalUrl))) {
|
||||
req.id = randomUUID();
|
||||
res.setHeader('X-Request-Id', req.id);
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
function getTransactionId(responseId, requestId) {
|
||||
// ID transaksi HSM terdiri dari empat digit hex. Abaikan nilai mentah lain dari body.
|
||||
for (const value of [responseId, requestId]) {
|
||||
if (typeof value === 'string' && /^[0-9a-f]{4}$/i.test(value)) return value.toLowerCase();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const successfulCodes = new Set(['00', '01', '02', '03', '04']);
|
||||
const isTopupRoute = (route) => /^\/api\/topup[1-8]$/.test(route);
|
||||
|
||||
function getLoadBalanceNumber(responseNumber, requestNumber) {
|
||||
return [responseNumber, requestNumber].find((value) =>
|
||||
typeof value === 'string' && /^LBL[0-9A-Za-z-]{1,35}$/.test(value)
|
||||
);
|
||||
}
|
||||
|
||||
const issuerCache = new Map();
|
||||
const issuerLookups = new Set();
|
||||
|
||||
// Enrichment tidak boleh menahan respons atau mengantrekan lookup per transaksi.
|
||||
function getIssuerName(partnerId) {
|
||||
if (!partnerId) return 'UNDEFINED';
|
||||
const cached = issuerCache.get(partnerId);
|
||||
if (cached?.expiresAt > Date.now()) return cached.name;
|
||||
if (issuerLookups.size < 4 && !issuerLookups.has(partnerId)) {
|
||||
issuerLookups.add(partnerId);
|
||||
void refreshIssuer(partnerId);
|
||||
}
|
||||
return cached?.name || 'UNDEFINED';
|
||||
}
|
||||
|
||||
async function refreshIssuer(partnerId) {
|
||||
let name = 'UNDEFINED';
|
||||
try {
|
||||
const partner = await knex('t_m_partner').where('i_partner', partnerId)
|
||||
.first('c_name').timeout(500, { cancel: true });
|
||||
name = partner?.c_name || name;
|
||||
} catch {
|
||||
// PostgreSQL sedang sibuk. Tetap catat audit dan coba lagi setelah jeda.
|
||||
} finally {
|
||||
issuerLookups.delete(partnerId);
|
||||
issuerCache.delete(partnerId);
|
||||
if (issuerCache.size >= 256) issuerCache.delete(issuerCache.keys().next().value);
|
||||
issuerCache.set(partnerId, { name, expiresAt: Date.now() + (name === 'UNDEFINED' ? 5000 : 300000) });
|
||||
}
|
||||
}
|
||||
|
||||
function recordResponse(event, partnerId, reservationNumber, message) {
|
||||
const issuerName = getIssuerName(partnerId);
|
||||
const level = successfulCodes.has(event.status_code) ? 'info' : 'error';
|
||||
responseAudit.record({
|
||||
level,
|
||||
message: typeof message === 'string' ? message : 'HTTP response',
|
||||
...event,
|
||||
issuer_name: issuerName,
|
||||
...(reservationNumber && { reservation_number: reservationNumber }),
|
||||
});
|
||||
|
||||
const labels = { route: event.route, status_code: event.status_code, issuer_name: issuerName };
|
||||
|
||||
topuponline_metrics.observe(labels, event.response_time_ms);
|
||||
topuponline_metrics_response_time.observe(labels, event.response_time_ms);
|
||||
if (isTopupRoute(event.route)) {
|
||||
topuponline_metrics_load_balance.observe(labels, event.response_time_ms);
|
||||
}
|
||||
}
|
||||
|
||||
const logger = {
|
||||
correlation,
|
||||
response: expressWinston.logger({
|
||||
// Formatter mencatat audit/metrics sebagai efek samping; jangan gandakan ke file.
|
||||
transports: [new winston.transports.Console({ silent: true })],
|
||||
format: winston.format.combine(
|
||||
winston.format.timestamp(),
|
||||
winston.format.printf((info) => {
|
||||
const { req, res, responseTime } = info.meta;
|
||||
const route = getRoute(req.originalUrl);
|
||||
const data = res.body?.data;
|
||||
const applicationCode = String(res.body?.code ?? '');
|
||||
const event = {
|
||||
event: 'http_response',
|
||||
request_id: req.id,
|
||||
partner_id: /^\d{1,16}$/.test(req.partner_id_token) ? String(req.partner_id_token) : undefined,
|
||||
trx_id: isTopupRoute(route) ? getTransactionId(data?.trxID, req.body?.trxID) : null,
|
||||
load_balance_number: getLoadBalanceNumber(data?.load_balance_number, req.body?.load_balance_number),
|
||||
route,
|
||||
method: req.method,
|
||||
http_status: res.statusCode,
|
||||
status_code: /^\d{2,4}$/.test(applicationCode) ? applicationCode : 'UNKNOWN',
|
||||
response_time_ms: responseTime,
|
||||
};
|
||||
|
||||
// Format Winston dijalankan sinkron agar audit dan metrik tercatat sebelum respons selesai.
|
||||
const reservationNumber = route.startsWith('/api/reservation') && successfulCodes.has(event.status_code)
|
||||
? data?.reservation_number
|
||||
: undefined;
|
||||
try {
|
||||
recordResponse(event, req.partner_id_token, reservationNumber, res.body?.message);
|
||||
} catch {
|
||||
writeStdoutLine(formatLog({
|
||||
event: 'response_telemetry_error',
|
||||
level: 'error',
|
||||
message: 'Failed to record Online TopUp response telemetry',
|
||||
request_id: req.id,
|
||||
route,
|
||||
}));
|
||||
}
|
||||
|
||||
const body = {
|
||||
id: req.id,
|
||||
tag: "RES",
|
||||
from: req.ip,
|
||||
endpoint: route,
|
||||
time: moment().format(),
|
||||
responseTime: `${responseTime} ms`,
|
||||
...event,
|
||||
};
|
||||
return `[${body.time}] | ${JSON.stringify(body)}`;
|
||||
})
|
||||
),
|
||||
ignoreRoute: (req) => !routes.has(getRoute(req.originalUrl)),
|
||||
responseWhitelist: [...expressWinston.responseWhitelist, "body"],
|
||||
requestWhitelist: [...expressWinston.requestWhitelist, "body", "id", "ip", "partner_id_token"],
|
||||
bodyWhitelist: ["trxID", "load_balance_number"],
|
||||
}),
|
||||
// Request terpisah dihilangkan karena respons terstruktur sudah menjadi audit.
|
||||
request: (req, res, next) => next(),
|
||||
};
|
||||
|
||||
module.exports = { logger };
|
||||
+276
-103
@@ -1,4 +1,7 @@
|
||||
const CryptoJS = require("crypto-js");
|
||||
const CryptoJS = require('crypto-js');
|
||||
const { randomUUID } = require('crypto');
|
||||
const knex = require('../../infrastructure/database/knex');
|
||||
const { logger } = require('./winston.logger');
|
||||
|
||||
// ENCRYPT TEXT
|
||||
const encryptText = (text) => {
|
||||
@@ -20,10 +23,19 @@ const decryptText = (cipherText) => {
|
||||
}
|
||||
};
|
||||
|
||||
// CREATE HMAC
|
||||
const createHMAC = async (payload) => {
|
||||
let hash = await CryptoJS.HmacSHA256(
|
||||
payload,
|
||||
process.env.SECRET_KEY
|
||||
).toString();
|
||||
return hash;
|
||||
};
|
||||
|
||||
// RANDOM UNIQUE CODE
|
||||
function getUniqueCode() {
|
||||
const maxDate = Date.now();
|
||||
const timestamp = Math.floor(Math.random() * maxDate).toString();
|
||||
let maxDate = Date.now();
|
||||
let timestamp = Math.floor(Math.random() * maxDate).toString();
|
||||
return timestamp;
|
||||
}
|
||||
|
||||
@@ -32,52 +44,62 @@ function getRandomArbitrary(min, max) {
|
||||
}
|
||||
|
||||
function randomNumberInt() {
|
||||
const result = [];
|
||||
let result = [];
|
||||
while (result.length !== 3) {
|
||||
let random = getRandomArbitrary(0, 9);
|
||||
if (!result.includes(random)) result.push(random);
|
||||
|
||||
|
||||
// To check if the first no is not zero
|
||||
if (result.length === 1 && random === 0) result.pop();
|
||||
}
|
||||
return parseInt( result.join("") );
|
||||
return parseInt(result.join(''));
|
||||
}
|
||||
|
||||
// GENERATE XML REQUEST
|
||||
function generateXMLRequest(urn, headers, items) {
|
||||
let xmlRequest = ''
|
||||
|
||||
let xmlRequest = '';
|
||||
|
||||
switch (urn.toUpperCase()) {
|
||||
case 'ZFMCMS_FI_001':
|
||||
|
||||
let xmlItem = ''
|
||||
let xmlItem = '';
|
||||
|
||||
items.map((item, index) => {
|
||||
xmlItem += `<item>
|
||||
<!--Optional:-->
|
||||
<ITEMNO_ACC>${String(index+1).padStart(10, '0')}</ITEMNO_ACC>
|
||||
<ITEMNO_ACC>${String(index + 1).padStart(
|
||||
10,
|
||||
'0'
|
||||
)}</ITEMNO_ACC>
|
||||
<!--Optional:-->
|
||||
<CUSTOMER>${item.c_account_code_topup ? item.c_account_code_topup : ""}</CUSTOMER>
|
||||
<CUSTOMER>${item.c_account_code_topup
|
||||
? item.c_account_code_topup
|
||||
: ''
|
||||
}</CUSTOMER>
|
||||
<!--Optional:-->
|
||||
<GL_ACCOUNT>${item.c_account_topup ? item.c_account_topup : ""}</GL_ACCOUNT>
|
||||
<GL_ACCOUNT>${item.c_account_topup ? item.c_account_topup : ''
|
||||
}</GL_ACCOUNT>
|
||||
<!--Optional:-->
|
||||
<BUS_AREA>${item.ba ? item.ba : ""}</BUS_AREA>
|
||||
<BUS_AREA>${item.ba ? item.ba : ''}</BUS_AREA>
|
||||
<!--Optional:-->
|
||||
<AMT_DOCCUR>${item.amount ? item.amount : ""}</AMT_DOCCUR>
|
||||
<AMT_DOCCUR>${item.amount ? item.amount : ''
|
||||
}</AMT_DOCCUR>
|
||||
<!--Optional:-->
|
||||
<BLINE_DATE>${item.posting_date ? item.posting_date : ""}</BLINE_DATE>
|
||||
<BLINE_DATE>${item.posting_date ? item.posting_date : ''
|
||||
}</BLINE_DATE>
|
||||
<!--Optional:-->
|
||||
<COSTCENTER></COSTCENTER>
|
||||
<!--Optional:-->
|
||||
<PROFITCENTER></PROFITCENTER>
|
||||
<!--Optional:-->
|
||||
<ALLOC_NMBR>${item.c_invoice_no ? item.c_invoice_no : ""}</ALLOC_NMBR>
|
||||
<ALLOC_NMBR>${item.c_invoice_no ? item.c_invoice_no : ''
|
||||
}</ALLOC_NMBR>
|
||||
<!--Optional:-->
|
||||
<ITEM_TEXT>${item.item_text ? item.item_text : ""}</ITEM_TEXT>
|
||||
<ITEM_TEXT>${item.item_text ? item.item_text : ''
|
||||
}</ITEM_TEXT>
|
||||
<!--Optional:-->
|
||||
<DE_CRE_IND>${item.de_cre}</DE_CRE_IND>
|
||||
</item>`
|
||||
})
|
||||
</item>`;
|
||||
});
|
||||
|
||||
xmlRequest = `<SOAP:Envelope xmlns:SOAP='http://schemas.xmlsoap.org/soap/envelope/'
|
||||
xmlns:urn='urn:sap-com:document:sap:rfc:functions'>
|
||||
@@ -144,144 +166,295 @@ function generateXMLRequest(urn, headers, items) {
|
||||
</C_T_RETURN>
|
||||
</urn:${urn}>
|
||||
</SOAP:Body>
|
||||
</SOAP:Envelope>`
|
||||
</SOAP:Envelope>`;
|
||||
break;
|
||||
default:
|
||||
console.log('Sorry, we are out of ' + urn + '.');
|
||||
logger.warn('Unsupported SAP XML template');
|
||||
}
|
||||
|
||||
return xmlRequest
|
||||
|
||||
return xmlRequest;
|
||||
}
|
||||
|
||||
// POSTING SAP
|
||||
async function postingSAP(url, body, credential){
|
||||
async function postingSAP(url, body, credential, { timeoutMs = 15000, maxRedirects } = {}) {
|
||||
try {
|
||||
let axios = require('axios');
|
||||
|
||||
const axios = require("axios");
|
||||
|
||||
const config = {
|
||||
headers : {
|
||||
let config = {
|
||||
headers: {
|
||||
'Content-Type': 'text/xml',
|
||||
'responseType': 'text',
|
||||
},
|
||||
responseType: 'text',
|
||||
timeout: timeoutMs,
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
maxRedirects,
|
||||
auth: {
|
||||
username: credential.username,
|
||||
password: credential.password
|
||||
}
|
||||
}
|
||||
password: credential.password,
|
||||
},
|
||||
};
|
||||
|
||||
const resp = await axios.post(url, body, config)
|
||||
let resp = await axios.post(url, body, config);
|
||||
|
||||
return {
|
||||
status : resp.status,
|
||||
message: "Success",
|
||||
data : resp.data
|
||||
}
|
||||
|
||||
status: resp.status,
|
||||
message: 'Success',
|
||||
data: resp.data,
|
||||
};
|
||||
} catch (error) {
|
||||
// Error 😨
|
||||
// Error 😨
|
||||
|
||||
if (error.response) {
|
||||
/*
|
||||
* The request was made and the server responded with a
|
||||
* status code that falls out of the range of 2xx
|
||||
*/
|
||||
return {
|
||||
status : error.response.status,
|
||||
message: error.message,
|
||||
data : []
|
||||
}
|
||||
} else if (error.request) {
|
||||
/*
|
||||
* The request was made but no response was received, `error.request`
|
||||
* is an instance of XMLHttpRequest in the browser and an instance
|
||||
* of http.ClientRequest in Node.js
|
||||
*/
|
||||
return {
|
||||
status : 500,
|
||||
message: "can't connect to sap network".toUpperCase(),
|
||||
data : []
|
||||
}
|
||||
} else {
|
||||
// Something happened in setting up the request and triggered an Error
|
||||
return {
|
||||
status : 500,
|
||||
message: error.message,
|
||||
data : []
|
||||
}
|
||||
}
|
||||
if (error.response) {
|
||||
/*
|
||||
* The request was made and the server responded with a
|
||||
* status code that falls out of the range of 2xx
|
||||
*/
|
||||
return {
|
||||
status: error.response.status,
|
||||
errorCode: error.code,
|
||||
message: error.message,
|
||||
data: [],
|
||||
};
|
||||
} else if (error.request) {
|
||||
/*
|
||||
* The request was made but no response was received, `error.request`
|
||||
* is an instance of XMLHttpRequest in the browser and an instance
|
||||
* of http.ClientRequest in Node.js
|
||||
*/
|
||||
return {
|
||||
status: 500,
|
||||
errorCode: error.code,
|
||||
message: "can't connect to sap network".toUpperCase(),
|
||||
data: [],
|
||||
};
|
||||
} else {
|
||||
// Something happened in setting up the request and triggered an Error
|
||||
return {
|
||||
status: 500,
|
||||
errorCode: error.code,
|
||||
message: error.message,
|
||||
data: [],
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GET SOAP RESPONSE DATA
|
||||
function getXMLData(response) {
|
||||
const xml2js = require('xml2js');
|
||||
// console.log(xmlString)
|
||||
let xml2js = require('xml2js');
|
||||
// console.log(xmlString)
|
||||
let resSAP = {
|
||||
type: '',
|
||||
message : '',
|
||||
data : {
|
||||
message: '',
|
||||
data: {
|
||||
E_DOCUMENTYEAR: '',
|
||||
E_DOCUMENTNUMBER: '',
|
||||
// ITEM: [],
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
if(response.status == 200){
|
||||
|
||||
const options = {
|
||||
if (response.status == 200) {
|
||||
let options = {
|
||||
explicitArray: false,
|
||||
tagNameProcessors: [xml2js.processors.stripPrefix]
|
||||
}
|
||||
tagNameProcessors: [xml2js.processors.stripPrefix],
|
||||
};
|
||||
|
||||
xml2js.parseString(response.data, options, (err, result) => {
|
||||
|
||||
if (err) throw err
|
||||
if (err) throw err;
|
||||
|
||||
let soapBody = result.Envelope.Body;
|
||||
|
||||
if (soapBody.$) delete soapBody.$
|
||||
if (soapBody.$) delete soapBody.$;
|
||||
|
||||
resSAP.data.E_DOCUMENTYEAR = soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTYEAR'] ? soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTYEAR'] : "0000"
|
||||
resSAP.data.E_DOCUMENTNUMBER = soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTNUMBER'] ? soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTNUMBER'] : ""
|
||||
resSAP.data.E_DOCUMENTYEAR = soapBody['ZFMCMS_FI_001.Response'][
|
||||
'E_DOCUMENTYEAR'
|
||||
]
|
||||
? soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTYEAR']
|
||||
: '0000';
|
||||
resSAP.data.E_DOCUMENTNUMBER = soapBody['ZFMCMS_FI_001.Response'][
|
||||
'E_DOCUMENTNUMBER'
|
||||
]
|
||||
? soapBody['ZFMCMS_FI_001.Response']['E_DOCUMENTNUMBER']
|
||||
: '';
|
||||
|
||||
if(soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']){
|
||||
if (!Array.isArray(soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'])) {
|
||||
if (soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']) {
|
||||
if (
|
||||
!Array.isArray(
|
||||
soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']
|
||||
)
|
||||
) {
|
||||
// resSAP.data.ITEM.push(soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'])
|
||||
resSAP.type = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']['TYPE']
|
||||
resSAP.message = "[SAP] " + soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']['MESSAGE_1']
|
||||
resSAP.type =
|
||||
soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']['TYPE'];
|
||||
resSAP.message =
|
||||
'[SAP] ' +
|
||||
soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][
|
||||
'MESSAGE_1'
|
||||
];
|
||||
} else {
|
||||
// resSAP.data.ITEM = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item']
|
||||
resSAP.type = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][0]['TYPE']
|
||||
|
||||
const indexMessage = soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'].length - 1
|
||||
let message = "[SAP] "+ soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][indexMessage]['MESSAGE_1']
|
||||
resSAP.type =
|
||||
soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][0]['TYPE'];
|
||||
|
||||
resSAP.message = message
|
||||
let indexMessage =
|
||||
soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'].length - 1;
|
||||
let message =
|
||||
'[SAP] ' +
|
||||
soapBody['ZFMCMS_FI_001.Response']['C_T_RETURN']['item'][
|
||||
indexMessage
|
||||
]['MESSAGE_1'];
|
||||
|
||||
resSAP.message = message;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
}else {
|
||||
|
||||
resSAP.type = 'E'
|
||||
resSAP.message = response.message ? response.message : "aa"
|
||||
|
||||
} else {
|
||||
resSAP.type = 'E';
|
||||
resSAP.message = response.message ? response.message : 'aa';
|
||||
}
|
||||
|
||||
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 = {
|
||||
encryptText,
|
||||
decryptText,
|
||||
createHMAC,
|
||||
getUniqueCode,
|
||||
randomNumberInt,
|
||||
generateXMLRequest,
|
||||
postingSAP,
|
||||
getXMLData
|
||||
getXMLData,
|
||||
startScheduler,
|
||||
finishScheduler,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
const client = require("prom-client");
|
||||
|
||||
const responseBucketsMs = [5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000, 15000, 30000, 60000];
|
||||
const responseLabels = ["route", "status_code", "issuer_name"];
|
||||
|
||||
const topuponline_metrics = new client.Histogram({
|
||||
name: "topuponline",
|
||||
help: "Durasi request Online TopUp dalam milidetik berdasarkan kode aplikasi",
|
||||
labelNames: responseLabels,
|
||||
buckets: responseBucketsMs,
|
||||
});
|
||||
|
||||
const topuponline_metrics_response_time = new client.Histogram({
|
||||
name: "topuponline_response_time",
|
||||
help: "Durasi respons Online TopUp dalam milidetik",
|
||||
labelNames: responseLabels,
|
||||
buckets: responseBucketsMs,
|
||||
});
|
||||
|
||||
const topuponline_metrics_load_balance = new client.Histogram({
|
||||
name: "topuponline_load_balance",
|
||||
help: "Durasi respons tahap TopUp dalam milidetik",
|
||||
labelNames: responseLabels,
|
||||
buckets: responseBucketsMs,
|
||||
});
|
||||
|
||||
module.exports = {
|
||||
topuponline_metrics,
|
||||
topuponline_metrics_response_time,
|
||||
topuponline_metrics_load_balance,
|
||||
};
|
||||
@@ -0,0 +1,45 @@
|
||||
// Perintah yang sudah terkirim baru dilepas oleh node-redis saat socket ditutup.
|
||||
function createRedisOperations(client, { timeoutMs = 500, onTimeout = () => {} } = {}) {
|
||||
let reconnecting = false;
|
||||
|
||||
function resetConnection() {
|
||||
if (reconnecting) return;
|
||||
reconnecting = true;
|
||||
if (client.isOpen) {
|
||||
client.disconnect().catch(() => {}).then(reconnect);
|
||||
} else {
|
||||
reconnect();
|
||||
}
|
||||
}
|
||||
|
||||
function reconnect() {
|
||||
// Setelah socket lama dilepas, isReady milik klien menentukan kapan socket baru dapat dipakai.
|
||||
reconnecting = false;
|
||||
if (!client.isOpen) void client.connect().catch(() => {});
|
||||
}
|
||||
|
||||
async function execute(command) {
|
||||
if (!client.isReady || reconnecting) return null;
|
||||
let timer;
|
||||
try {
|
||||
return await Promise.race([
|
||||
command(client),
|
||||
new Promise((resolve) => {
|
||||
timer = setTimeout(() => {
|
||||
onTimeout();
|
||||
resetConnection();
|
||||
resolve(null);
|
||||
}, timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
return execute;
|
||||
}
|
||||
|
||||
module.exports = createRedisOperations;
|
||||
@@ -0,0 +1,51 @@
|
||||
const { Counter } = require('prom-client');
|
||||
const createAuditArchive = require('./audit-archive');
|
||||
const { formatLog, writeStdoutLine } = require('./stdout-log');
|
||||
require('dotenv').config();
|
||||
|
||||
const auditErrors = new Counter({
|
||||
name: 'topuponline_audit_write_errors_total',
|
||||
help: 'Failed local audit archive writes',
|
||||
});
|
||||
const retentionErrors = new Counter({
|
||||
name: 'topuponline_audit_retention_errors_total',
|
||||
help: 'Failed local audit archive retention deletions',
|
||||
});
|
||||
const retentionDaysValue = process.env.TOPUP_AUDIT_RETENTION_DAYS;
|
||||
const retentionDays = retentionDaysValue === undefined || retentionDaysValue === ''
|
||||
? 0
|
||||
: Number(retentionDaysValue);
|
||||
if (retentionDaysValue !== undefined && retentionDaysValue !== '') {
|
||||
if (!Number.isSafeInteger(retentionDays) || retentionDays < 1 || retentionDays > 36500) {
|
||||
throw new Error('TOPUP_AUDIT_RETENTION_DAYS must be an integer between 1 and 36500');
|
||||
}
|
||||
}
|
||||
const archive = createAuditArchive(
|
||||
process.env.TOPUP_AUDIT_DIR || './lokiLog/audit',
|
||||
{ retentionDays }
|
||||
);
|
||||
let archiveUnavailable = false;
|
||||
|
||||
function record(event) {
|
||||
const time = Date.now();
|
||||
const line = formatLog(event, time);
|
||||
try {
|
||||
const result = archive.append(line, time);
|
||||
if (result.retentionErrors > 0) retentionErrors.inc(result.retentionErrors);
|
||||
archiveUnavailable = false;
|
||||
} catch (error) {
|
||||
auditErrors.inc();
|
||||
if (!archiveUnavailable) {
|
||||
writeStdoutLine(formatLog({
|
||||
level: 'error',
|
||||
event: 'audit_archive_error',
|
||||
message: 'Unable to write the local audit archive',
|
||||
error_code: error.code || 'UNKNOWN',
|
||||
}, time));
|
||||
}
|
||||
archiveUnavailable = true;
|
||||
}
|
||||
writeStdoutLine(line);
|
||||
}
|
||||
|
||||
module.exports = { record, auditMetrics: [auditErrors, retentionErrors] };
|
||||
@@ -0,0 +1,52 @@
|
||||
const { Counter } = require('prom-client');
|
||||
|
||||
const skipped = new Counter({
|
||||
name: 'topuponline_stdout_copies_skipped_total',
|
||||
help: 'Log copies skipped while stdout was unavailable or under backpressure',
|
||||
labelNames: ['reason'],
|
||||
});
|
||||
|
||||
function createStdoutWriter(stream, onSkip) {
|
||||
let failed = false;
|
||||
stream.on('error', () => { failed = true; });
|
||||
|
||||
return (line) => {
|
||||
// Arsip atau log file sudah menjadi salinan lokal. Jangan menambah antrean stdout.
|
||||
if (failed || !stream.writable) {
|
||||
onSkip('unavailable');
|
||||
return;
|
||||
}
|
||||
if (stream.writableNeedDrain) {
|
||||
onSkip('backpressure');
|
||||
return;
|
||||
}
|
||||
try {
|
||||
stream.write(`${line}\n`, (error) => {
|
||||
if (error) onSkip('unavailable');
|
||||
});
|
||||
} catch {
|
||||
failed = true;
|
||||
onSkip('unavailable');
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
const writeStdoutLine = createStdoutWriter(process.stdout, (reason) => skipped.inc({ reason }));
|
||||
|
||||
function formatLog(event, time = Date.now()) {
|
||||
const safeEvent = { ...event };
|
||||
if (typeof safeEvent.message === 'string') {
|
||||
safeEvent.message = safeEvent.message
|
||||
.replace(/\bBearer\s+[\w.+/=-]+/gi, 'Bearer [redacted]')
|
||||
.replace(/(["']?(?:password|passwd|pin|token|authorization|card[_ ]?number|uid|cvv|nik|requestData|responseData)["']?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,}\]]+)/gi, '$1[redacted]')
|
||||
.slice(0, 512);
|
||||
}
|
||||
return JSON.stringify({
|
||||
timestamp: new Date(time).toISOString(),
|
||||
app: 'topuponline',
|
||||
pid: process.pid,
|
||||
...safeEvent,
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = { createStdoutWriter, writeStdoutLine, formatLog, stdoutMetrics: [skipped] };
|
||||
@@ -1,8 +1,30 @@
|
||||
const moment = require("moment");
|
||||
const winston = require("winston");
|
||||
require("winston-daily-rotate-file");
|
||||
const { formatLog, writeStdoutLine } = require("./stdout-log");
|
||||
require("dotenv").config();
|
||||
const { combine, timestamp, printf, colorize, align, json } = winston.format;
|
||||
const { combine, timestamp, printf, align } = winston.format;
|
||||
|
||||
function stdoutMessage(message) {
|
||||
if (typeof message !== "string") return "Application log";
|
||||
// Ringkasan mempertahankan konteks lama tanpa mengirim isi kartu, XML, atau data HSM.
|
||||
const payloadStart = message.search(/[:|]\s+(?:\{|"|\[\s*[{\]"\d]|<\?xml\b|(?:request|response)\s*data\b|message from HSM\b)/i);
|
||||
const summary = payloadStart === -1 ? message : message.slice(0, payloadStart);
|
||||
return summary.trim()
|
||||
.replace(/\bBearer\s+[\w.+/=-]+/gi, "Bearer [redacted]")
|
||||
.replace(/(["']?(?:password|passwd|pin|token|authorization|card[_ ]?number|uid|cvv|nik|requestData|responseData)["']?\s*[:=]\s*)(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,}\]]+)/gi, "$1[redacted]")
|
||||
.slice(0, 512);
|
||||
}
|
||||
|
||||
class StdoutTransport extends winston.Transport {
|
||||
log(info, done) {
|
||||
writeStdoutLine(formatLog({
|
||||
level: info[Symbol.for("level")],
|
||||
event: "application_log",
|
||||
service: info.service,
|
||||
message: stdoutMessage(info.message),
|
||||
}));
|
||||
done();
|
||||
}
|
||||
}
|
||||
|
||||
const logLevels = {
|
||||
fatal: 0,
|
||||
@@ -14,26 +36,6 @@ const logLevels = {
|
||||
};
|
||||
var logger;
|
||||
|
||||
//
|
||||
// Replaces the previous transports with those in the
|
||||
// new configuration wholesale.
|
||||
//
|
||||
// const DailyRotateFile = require("winston-daily-rotate-file");
|
||||
// logger.configure({
|
||||
// level: "verbose",
|
||||
// transports: [new DailyRotateFile()],
|
||||
// });
|
||||
|
||||
const fileRotateTransport = new winston.transports.DailyRotateFile({
|
||||
filename: `application/logs/%DATE%-onlinetopup.log`,
|
||||
datePattern: "YYYY-MM-DD",
|
||||
maxFiles: "90d",
|
||||
});
|
||||
//
|
||||
// If we're not in production then log to the `console` with the format:
|
||||
// `${info.level}: ${info.message} JSON.stringify({ ...rest }) `
|
||||
//
|
||||
|
||||
if (
|
||||
process.env.NODE_ENV == "production" ||
|
||||
process.env.NODE_ENV == "PRODUCTION"
|
||||
@@ -42,9 +44,7 @@ if (
|
||||
levels: logLevels,
|
||||
level: process.env.LOG_LEVEL || "info",
|
||||
exitOnError: false,
|
||||
// format: combine(timestamp(), json()),
|
||||
format: combine(
|
||||
// colorize({ all: true }),
|
||||
timestamp({
|
||||
format: "YYYY-MM-DD HH:mm:ss.SSS",
|
||||
}),
|
||||
@@ -52,29 +52,14 @@ if (
|
||||
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
|
||||
),
|
||||
defaultMeta: { service: "topuponline-service" },
|
||||
transports: [
|
||||
fileRotateTransport,
|
||||
//
|
||||
// - Write all logs with importance level of `error` or less to `error.log`
|
||||
// - Write all logs with importance level of `info` or less to `onlinetopup.log`
|
||||
//
|
||||
new winston.transports.File({
|
||||
filename: `application/logs/error.log`,
|
||||
level: "error",
|
||||
}),
|
||||
// new winston.transports.File({
|
||||
// filename: `application/logs/${moment().format("YYYY-MM-DD")}-onlinetopup.log`,
|
||||
// }),
|
||||
],
|
||||
transports: [new winston.transports.Console({ silent: true })],
|
||||
});
|
||||
} else {
|
||||
logger = winston.createLogger({
|
||||
levels: logLevels,
|
||||
level: process.env.LOG_LEVEL || "debug",
|
||||
exitOnError: false,
|
||||
// format: combine(timestamp(), json()),
|
||||
format: combine(
|
||||
// colorize({ all: true }),
|
||||
timestamp({
|
||||
format: "YYYY-MM-DD HH:mm:ss.SSS",
|
||||
}),
|
||||
@@ -82,41 +67,12 @@ if (
|
||||
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
|
||||
),
|
||||
defaultMeta: { service: "topuponline-service" },
|
||||
transports: [
|
||||
fileRotateTransport,
|
||||
//
|
||||
// - Write all logs with importance level of `error` or less to `error.log`
|
||||
// - Write all logs with importance level of `info` or less to `onlinetopup.log`
|
||||
//
|
||||
new winston.transports.File({
|
||||
filename: `application/logs/error.log`,
|
||||
level: "error",
|
||||
}),
|
||||
new winston.transports.File({
|
||||
filename: `application/logs/debug/${moment().format("YYYY-MM-DD")}.log`,
|
||||
level: "debug",
|
||||
}),
|
||||
// new winston.transports.File({
|
||||
// filename: `application/logs/${moment().format("YYYY-MM-DD")}-onlinetopup.log`,
|
||||
// }),
|
||||
],
|
||||
transports: [new winston.transports.Console({ silent: true })],
|
||||
});
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV != "testing" && process.env.NODE_ENV != "TESTING") {
|
||||
logger.add(
|
||||
new winston.transports.Console({
|
||||
// format: winston.format.cli(),
|
||||
format: combine(
|
||||
colorize({ all: true }),
|
||||
timestamp({
|
||||
format: "YYYY-MM-DD HH:mm:ss.SSS",
|
||||
}),
|
||||
align(),
|
||||
printf((info) => `[${info.timestamp}] ${info.level}: ${info.message}`)
|
||||
),
|
||||
})
|
||||
);
|
||||
logger.add(new StdoutTransport());
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -1,49 +1,59 @@
|
||||
const jwt = require("jsonwebtoken");
|
||||
const helper = require("../helpers/helper");
|
||||
const jwt = require('jsonwebtoken');
|
||||
const helper = require('../helpers/helper');
|
||||
const winston = require('../helpers/winston.logger');
|
||||
|
||||
const generateRefreshToken = (req) => {
|
||||
let expiresIn = process.env.JWT_REFRESH_EXPIRATION ? process.env.JWT_REFRESH_EXPIRATION : "7d";
|
||||
let expiresIn = process.env.JWT_REFRESH_EXPIRATION
|
||||
? process.env.JWT_REFRESH_EXPIRATION
|
||||
: '7d';
|
||||
let signOptions = {
|
||||
issuer: 'CMS Kereta Commuter Indonesia',
|
||||
expiresIn: expiresIn,
|
||||
}
|
||||
};
|
||||
|
||||
return jwt.sign(req, process.env.REFRESH_TOKEN_SECRET, signOptions);
|
||||
};
|
||||
|
||||
const authenticateRefreshToken = (req, res, next) => {
|
||||
|
||||
let verifyOptions = {
|
||||
issuer: 'CMS Kereta Commuter Indonesia',
|
||||
}
|
||||
};
|
||||
|
||||
jwt.verify(req.header("refresh_token"), process.env.REFRESH_TOKEN_SECRET, verifyOptions, (err, data) => {
|
||||
if (err) {
|
||||
return res.json({
|
||||
code: "400",
|
||||
message: "Refresh Token is invalid. Please login!",
|
||||
data: {},
|
||||
});
|
||||
jwt.verify(
|
||||
req.headers['refresh-token'],
|
||||
process.env.REFRESH_TOKEN_SECRET,
|
||||
verifyOptions,
|
||||
(err, data) => {
|
||||
if (err) {
|
||||
return res.json({
|
||||
code: '400',
|
||||
message: 'Refresh Token is invalid. Please login!!',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
next();
|
||||
});
|
||||
);
|
||||
};
|
||||
|
||||
const generateAccessToken = (req) => {
|
||||
let expiresIn = process.env.JWT_EXPIRATION ? process.env.JWT_EXPIRATION : "1d";
|
||||
let expiresIn = process.env.JWT_EXPIRATION
|
||||
? process.env.JWT_EXPIRATION
|
||||
: '1d';
|
||||
let signOptions = {
|
||||
issuer: 'CMS Kereta Commuter Indonesia',
|
||||
expiresIn: expiresIn,
|
||||
}
|
||||
};
|
||||
|
||||
if (req.user_group_id == "1") {
|
||||
if (req.user_group_id == '1') {
|
||||
expiresIn = parseInt(process.env.JWT_EXPIRATION_ADMIN_WEB);
|
||||
} else if (req.user_group_id == "2") {
|
||||
} else if (req.user_group_id == '2') {
|
||||
expiresIn = parseInt(process.env.JWT_EXPIRATION_MOBILE_PHONE);
|
||||
} else if (
|
||||
req.user_group_id == "3" ||
|
||||
req.user_group_id == "4" ||
|
||||
req.user_group_id == "5"
|
||||
req.user_group_id == '3' ||
|
||||
req.user_group_id == '4' ||
|
||||
req.user_group_id == '5'
|
||||
) {
|
||||
expiresIn = parseInt(process.env.JWT_EXPIRATION_TERMINAL);
|
||||
}
|
||||
@@ -52,43 +62,55 @@ const generateAccessToken = (req) => {
|
||||
};
|
||||
|
||||
const authenticateToken = async (req, res, next) => {
|
||||
let authHeader = req.headers["authorization"];
|
||||
let authHeader = req.headers['authorization'];
|
||||
|
||||
if (authHeader) {
|
||||
let token = authHeader && authHeader.split(" ")[1];
|
||||
let token = authHeader && authHeader.split(' ')[1];
|
||||
|
||||
// winston.logger.info(
|
||||
// `000000000000 [ AUTHENTICATE TOKEN ]: ${JSON.stringify({
|
||||
// token: token,
|
||||
// ip: ip,
|
||||
// })}`
|
||||
// );
|
||||
|
||||
if (!token) {
|
||||
return res.json({
|
||||
code: "401",
|
||||
message: "Token is required",
|
||||
code: '401',
|
||||
message: 'Token is required',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
let verifyOptions = {
|
||||
issuer: 'CMS Kereta Commuter Indonesia',
|
||||
}
|
||||
};
|
||||
|
||||
await jwt.verify(token, process.env.TOKEN_SECRET, verifyOptions, (err, data) => {
|
||||
if (err) {
|
||||
return res.json({
|
||||
code: "402",
|
||||
message: "Invalid Token.",
|
||||
data: {},
|
||||
});
|
||||
await jwt.verify(
|
||||
token,
|
||||
process.env.TOKEN_SECRET,
|
||||
verifyOptions,
|
||||
(err, data) => {
|
||||
if (err) {
|
||||
return res.json({
|
||||
code: '402',
|
||||
message: 'Invalid Token.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
req.mid_token = helper.decryptText(data.mid);
|
||||
req.tid_token = helper.decryptText(data.tid);
|
||||
req.partner_id_token = helper.decryptText(data.partner_id);
|
||||
req.partner_user_id_token = helper.decryptText(data.partner_user_id);
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
req.mid_token = helper.decryptText(data.mid);
|
||||
req.tid_token = helper.decryptText(data.tid);
|
||||
req.partner_id_token = helper.decryptText(data.partner_id);
|
||||
req.partner_user_id_token = helper.decryptText(data.partner_user_id);
|
||||
|
||||
next();
|
||||
});
|
||||
);
|
||||
} else {
|
||||
return res.json({
|
||||
code: "400",
|
||||
message: "Header not found",
|
||||
code: '400',
|
||||
message: 'Header not found',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
require('dotenv').config();
|
||||
const redis = require('redis');
|
||||
const createRedisOperations = require('../helpers/redis-operations');
|
||||
const { logger } = require('../helpers/winston.logger');
|
||||
|
||||
const redisClient = redis.createClient({
|
||||
url: process.env.REDIS_URL || 'redis://127.0.0.1:6379',
|
||||
disableOfflineQueue: true,
|
||||
commandsQueueMaxLength: 256,
|
||||
});
|
||||
|
||||
redisClient.on('error', () => {});
|
||||
redisClient.on('ready', () => logger.info('Redis connection ready'));
|
||||
void redisClient.connect().catch(() => logger.error('Redis connection failed'));
|
||||
|
||||
const execute = createRedisOperations(redisClient, {
|
||||
onTimeout: () => logger.warn('Redis command deadline exceeded'),
|
||||
});
|
||||
|
||||
async function redisMiddleware(req, res, next) {
|
||||
const value = await execute((client) => client.get('cardproduct'));
|
||||
if (value) {
|
||||
try {
|
||||
res.status(200).json({ code: 200, message: 'Success get from redis', data: JSON.parse(value) });
|
||||
return;
|
||||
} catch {
|
||||
// Payload cache yang rusak dapat dibaca ulang dari sumbernya.
|
||||
}
|
||||
}
|
||||
res.once('finish', () => {
|
||||
if (res.body !== undefined) void execute((client) => client.set('cardproduct', JSON.stringify(res.body), { EX: 10 }));
|
||||
});
|
||||
next();
|
||||
}
|
||||
|
||||
module.exports = { redisMiddleware };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,56 @@
|
||||
const { body } = require('express-validator');
|
||||
|
||||
// Aturan input untuk setiap operasi. Urutan validasi mengikuti kontrak API.
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'loginPartnerUser': {
|
||||
return [
|
||||
body('email')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Email is required')
|
||||
.isEmail()
|
||||
.withMessage('Email format wrong'),
|
||||
body('password').not().isEmpty().withMessage('Password is required'),
|
||||
];
|
||||
}
|
||||
case 'loginTerminal': {
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('password').not().isEmpty().withMessage('Password is required'),
|
||||
];
|
||||
}
|
||||
case 'register': {
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('password')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Password is required')
|
||||
.isLength({ min: 5 })
|
||||
.withMessage('Password must be least 5 characters'),
|
||||
];
|
||||
}
|
||||
case 'refreshTokenPartnerUser': {
|
||||
return [
|
||||
body('email')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Email is required')
|
||||
.isEmail()
|
||||
.withMessage('Email format wrong'),
|
||||
];
|
||||
}
|
||||
case 'refreshTokenTerminal': {
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
];
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
module.exports = validate;
|
||||
@@ -1,26 +1,38 @@
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
const helper = require("../../helpers/helper");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const model = require("./cahsin.model");
|
||||
const moment = require("moment");
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
|
||||
moment.locale("id");
|
||||
|
||||
var result = {};
|
||||
var uniqueCode;
|
||||
const { body, validationResult } = require('express-validator');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { _generateCashIn, _generateCashInSales, _generateCashInSalesInternal, _generateCashInTopUpCashlessInternal } = require('./cash-in-generation.service');
|
||||
const _postingCashIn = require('./cash-in-posting.service');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "generateInvoice":
|
||||
case 'generateInvoice':
|
||||
return [
|
||||
body('trx_date').notEmpty().withMessage('trx_date is required!').isISO8601().withMessage('invalid trx_date format YYYY-MM-DD !').escape().trim(),
|
||||
body('repost').notEmpty().withMessage('repost is required!').isBoolean().withMessage('repost must boolean!').escape().trim(),
|
||||
body('trx_date')
|
||||
.notEmpty()
|
||||
.withMessage('trx_date is required!')
|
||||
.isISO8601()
|
||||
.withMessage('invalid trx_date format YYYY-MM-DD !')
|
||||
.escape()
|
||||
.trim(),
|
||||
body('repost')
|
||||
.notEmpty()
|
||||
.withMessage('repost is required!')
|
||||
.isBoolean()
|
||||
.withMessage('repost must boolean!')
|
||||
.escape()
|
||||
.trim(),
|
||||
];
|
||||
case "postingInvoice":
|
||||
case 'postingInvoice':
|
||||
return [
|
||||
body('trx_date').notEmpty().withMessage('trx_date is required!').isISO8601().withMessage('invalid trx_date format YYYY-MM-DD !').escape().trim(),
|
||||
body('trx_date')
|
||||
.notEmpty()
|
||||
.withMessage('trx_date is required!')
|
||||
.isISO8601()
|
||||
.withMessage('invalid trx_date format YYYY-MM-DD !')
|
||||
.escape()
|
||||
.trim(),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
@@ -29,255 +41,299 @@ const validate = (method) => {
|
||||
|
||||
// POSTING INVOICE
|
||||
const apiGenerateCahsIn = async (req, res) => {
|
||||
|
||||
try {
|
||||
// generate unique code
|
||||
uniqueCode = helper.getUniqueCode();
|
||||
// return uniqueCode
|
||||
const uniqueCode = helper.getUniqueCode();
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST generate cashin: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} REQUEST generate cashin`
|
||||
);
|
||||
|
||||
const schedulerCode = 'GENERATECASHINONLINETOPUP';
|
||||
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",
|
||||
const result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE generate cashin: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} RESPONSE generate cashin code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
const cashIn = await _generateCashIn(uniqueCode)
|
||||
const cashIn = await _generateCashIn(uniqueCode);
|
||||
|
||||
result = {
|
||||
code: "200",
|
||||
message: "Succes posting",
|
||||
data: cashIn
|
||||
const result = {
|
||||
code: '200',
|
||||
message: 'Succes posting',
|
||||
data: cashIn,
|
||||
};
|
||||
|
||||
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 apiGenerateCashInSales = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
const uniqueCode = helper.getUniqueCode();
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST generate cashin`
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
const result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE generate cashin code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
const cashIn = await _generateCashInSales(uniqueCode);
|
||||
|
||||
const result = {
|
||||
code: '200',
|
||||
message: 'Success generate cash-in',
|
||||
data: cashIn,
|
||||
};
|
||||
|
||||
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: {},
|
||||
});
|
||||
}
|
||||
// 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 INVOICE
|
||||
const apiPostingCahsIn = async (req, res) => {
|
||||
const apiGenerateCashInSalesInternal = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
uniqueCode = helper.getUniqueCode()
|
||||
let { body } = req
|
||||
const uniqueCode = helper.getUniqueCode();
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST posting cash in : ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} REQUEST generate cashin sales internal`
|
||||
);
|
||||
|
||||
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",
|
||||
const result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE generate posting cash in : ${JSON.stringify(result)}`
|
||||
`${uniqueCode} RESPONSE generate cashin sales internal code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// return uniqueCode
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING CAHS IN`)
|
||||
const cashIn = await _generateCashInSalesInternal(uniqueCode);
|
||||
|
||||
const invoice = await _postingCashIn(uniqueCode)
|
||||
const result = {
|
||||
code: '200',
|
||||
message: 'Success generate cash-in',
|
||||
data: cashIn,
|
||||
};
|
||||
|
||||
result = {
|
||||
code: "200",
|
||||
message: "Succes",
|
||||
data: invoice,
|
||||
}
|
||||
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: {},
|
||||
});
|
||||
// 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 _generateCashIn = async (uniqueCode) => {
|
||||
const apiGenerateCashInTopUpCashlessInternal = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
const uniqueCode = helper.getUniqueCode();
|
||||
|
||||
let partnerRecon = await model.getPartnerRecon(knex)
|
||||
// return partnerRecon
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} getPartner Recon cash in : ${JSON.stringify(partnerRecon)}`)
|
||||
for (const item of partnerRecon) {
|
||||
let reserve = []
|
||||
let code = ""
|
||||
await knex.transaction(async trx => {
|
||||
code = await model.generateCode(trx, item.c_partner_code, moment().format("YYMMDD"))
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} generate cash in : ${code}`)
|
||||
|
||||
// Insert cahs in
|
||||
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 : item.amount
|
||||
}
|
||||
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN ${code} DATA : ${JSON.stringify(dataCahsIn)}`)
|
||||
const cashIn = await model.insertCashIn(trx, dataCahsIn)
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST generate cashin topup cashless internal`
|
||||
);
|
||||
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN HISTORY ${code} DATA : ${JSON.stringify(dataCahsIn)}`)
|
||||
const paymentyHistory = await model.writePaynentHistory(dataCahsIn, "SUCCESSFULLY", 0, trx)
|
||||
const schedulerCode = 'GENERATECASHINTOPUPSTATIONCASHLESS';
|
||||
const startData = await helper.startScheduler(schedulerCode);
|
||||
const token = startData.c_execution_token ?? null;
|
||||
|
||||
// Insert cahs in detail
|
||||
let data = []
|
||||
const reserv = await model.getReserve(trx, item.c_partner_code, item.d_payment, item.c_invoice_no)
|
||||
for (const detail of reserv) {
|
||||
data.push({
|
||||
i_cash_in : cashIn.i_cash_in,
|
||||
c_reservation_no : detail.c_reservation_no,
|
||||
m_amount : detail.i_reservation_amount,
|
||||
c_payment_recon_no : detail.c_payment_recon_no,
|
||||
d_payment : detail.d_payment,
|
||||
d_payment_recon : detail.d_payment_recon,
|
||||
c_load_balance_no : detail.c_load_balance_no
|
||||
})
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
const result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
let reserveNo = detail.c_reservation_no
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE generate cashin topup cashless internal code=${result.code}`
|
||||
);
|
||||
|
||||
let dataReserve = {
|
||||
c_cash_in_no : cashIn.c_cash_in_no,
|
||||
d_credit : cashIn.d_credit,
|
||||
c_in_period : cashIn.c_in_period,
|
||||
}
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
await model.updateIntoReserve(trx, dataReserve, reserveNo)
|
||||
|
||||
}
|
||||
await wait(5000)
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN TO RESERVE ${code} DATA : ${JSON.stringify(dataCahsIn)}`)
|
||||
await model.insertCashInDetail(trx, data)
|
||||
// await model.insertPostingEt(code, item, trx)
|
||||
const cashIn = await _generateCashInTopUpCashlessInternal(uniqueCode);
|
||||
|
||||
})
|
||||
const result = {
|
||||
code: '200',
|
||||
message: 'Success generate cash-in',
|
||||
data: cashIn,
|
||||
};
|
||||
|
||||
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: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return partnerRecon
|
||||
// RETRY POSTING CASH IN
|
||||
const apiPostingCahsIn = async (req, res) => {
|
||||
try {
|
||||
const uniqueCode = helper.getUniqueCode();
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST posting cash in `
|
||||
);
|
||||
|
||||
}
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
const result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
const _postingCashIn = async (uniqueCode) => {
|
||||
let data = []
|
||||
let postingEt = await model.getPostingEt(knex)
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE generate posting cash in code=${result.code}`
|
||||
);
|
||||
|
||||
for (const item of postingEt) {
|
||||
await knex.transaction(async trx => {
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify(item)}`)
|
||||
|
||||
let xmlHeader = {
|
||||
doc_header_text : item.doc_header_text ? item.doc_header_text : "",
|
||||
ba: item.ba ? item.ba : "",
|
||||
doc_date : item.doc_date ? item.doc_date : "",
|
||||
posting_date : item.posting_date ? item.posting_date : "",
|
||||
fisc_year : item.fiscal_year ? item.fiscal_year : "",
|
||||
fisc_period : item.fis_period ? item.fis_period: "",
|
||||
doc_type: item.doc_type ? item.doc_type : "",
|
||||
c_invoice_no : item.reference ? item.reference : ""
|
||||
}
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let xmlItem = ['S', 'H'].map(key => {
|
||||
return {
|
||||
c_account_code_topup : key == 'S' ? item.customer : "",
|
||||
c_account_topup : key == 'H' ? item.account : "",
|
||||
ba : item.ba,
|
||||
amount : item.amount,
|
||||
posting_date : item.posting_date,
|
||||
c_invoice_no : item.reference,
|
||||
item_text :key == 'S' ? item.text1 : item.text2,
|
||||
de_cre : key
|
||||
}
|
||||
});
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING CASH IN`);
|
||||
|
||||
let xmlRequest = helper.generateXMLRequest('ZFMCMS_FI_001', xmlHeader, xmlItem)
|
||||
console.log(xmlRequest)
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`);
|
||||
|
||||
const url = 'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2'
|
||||
const invoice = await _postingCashIn(uniqueCode);
|
||||
|
||||
const response = await helper.postingSAP(url, xmlRequest)
|
||||
const result = {
|
||||
code: '200',
|
||||
message: 'Succes',
|
||||
data: invoice,
|
||||
};
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${item.reference} to SAP : ${JSON.stringify(response)}`);
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
const resSAP = helper.getXMLData(response)
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`);
|
||||
// UPDATE CMS
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(resSAP)}`)
|
||||
|
||||
const cms = await model.setReturnSAP(item.no_dok, resSAP, trx)
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`)
|
||||
|
||||
})
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
return postingEt
|
||||
|
||||
}
|
||||
|
||||
function wait(milliseconds) {
|
||||
return new Promise(resolve => setTimeout(resolve, milliseconds));
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
apiGenerateCahsIn,
|
||||
apiGenerateCashInSales,
|
||||
apiGenerateCashInSalesInternal,
|
||||
apiGenerateCashInTopUpCashlessInternal,
|
||||
apiPostingCahsIn,
|
||||
_postingCashIn,
|
||||
_generateCashIn
|
||||
};
|
||||
_generateCashIn,
|
||||
_generateCashInSales,
|
||||
_generateCashInSalesInternal,
|
||||
_generateCashInTopUpCashlessInternal,
|
||||
};
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
|
||||
// GET PARTNER, MERCHANT, TERMINAL FROM TID
|
||||
const generateInvoice = async (invoiceDate, repost, trx) => {
|
||||
const result = await trx.raw(
|
||||
'SELECT * FROM payment.sp_payment_req_topup_online(?, ?::boolean)',
|
||||
[invoiceDate, repost]
|
||||
);
|
||||
|
||||
let result = await trx.select(trx.raw(`* FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`))
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
return result.rows || result;
|
||||
};
|
||||
|
||||
const insertPostingEt = async (code, dataCashIn, trx) => {
|
||||
let type = ['S', 'H']
|
||||
let et = []
|
||||
let posting_et = []
|
||||
let type = ['S', 'H'];
|
||||
let et = [];
|
||||
let posting_et = [];
|
||||
type.forEach((item, index) => {
|
||||
let data = {
|
||||
file_name: code,
|
||||
@@ -25,137 +25,138 @@ const insertPostingEt = async (code, dataCashIn, trx) => {
|
||||
reference: code,
|
||||
amount: dataCashIn.amount,
|
||||
ba: dataCashIn.ba,
|
||||
indeks: (index+1),
|
||||
indeks: index + 1,
|
||||
totalidx: type.length,
|
||||
doc_header_text: code,
|
||||
pos_status : 4
|
||||
}
|
||||
|
||||
if(item == 'H'){
|
||||
data = {...data, ...{
|
||||
text: `Cash-in CMS ${code}`,
|
||||
debit_kredit: item,
|
||||
account: dataCashIn.c_account_topup,
|
||||
customer: null
|
||||
}}
|
||||
}else{
|
||||
data = {...data, ...{
|
||||
text: `Cash-in CMS ${code}`,
|
||||
debit_kredit: item,
|
||||
account: null,
|
||||
customer: dataCashIn.c_account_code_topup
|
||||
}}
|
||||
pos_status: 4,
|
||||
};
|
||||
|
||||
if (item == 'H') {
|
||||
data = {
|
||||
...data,
|
||||
...{
|
||||
text: `Cash-in CMS ${code}`,
|
||||
debit_kredit: item,
|
||||
account: dataCashIn.c_account_topup,
|
||||
customer: null,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
data = {
|
||||
...data,
|
||||
...{
|
||||
text: `Cash-in CMS ${code}`,
|
||||
debit_kredit: item,
|
||||
account: null,
|
||||
customer: dataCashIn.c_account_code_topup,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
et.push(data)
|
||||
et.push(data);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
posting_et = await trx('public.posting_et').insert(et, ['indeks', 'customer', 'account', 'ba', 'fiscal_year', 'amount', 'no_dok', 'text', 'debit_kredit'])
|
||||
|
||||
return posting_et[0]
|
||||
|
||||
}
|
||||
|
||||
const getPostingEt = async(trx) => {
|
||||
|
||||
const result = await trx('public.posting_et AS pe').select([
|
||||
'doc_header_text',
|
||||
posting_et = await trx('public.posting_et').insert(et, [
|
||||
'indeks',
|
||||
'customer',
|
||||
'account',
|
||||
'ba',
|
||||
'doc_date',
|
||||
'posting_date',
|
||||
'fiscal_year',
|
||||
trx.raw(`TO_CHAR(doc_date::DATE, 'MM') AS fis_period`),
|
||||
'doc_type',
|
||||
'reference',
|
||||
'no_dok',
|
||||
'tcode',
|
||||
'amount',
|
||||
trx.raw(`'IDR' AS currency`),
|
||||
trx.raw(`(SELECT customer FROM public.posting_et where reference = pe.reference and debit_kredit = 'S') as customer`),
|
||||
trx.raw(`(SELECT account FROM public.posting_et where reference = pe.reference and debit_kredit = 'H') as account `),
|
||||
trx.raw(`(SELECT text FROM public.posting_et where reference = pe.reference and debit_kredit = 'S') as text1`),
|
||||
trx.raw(`(SELECT text FROM public.posting_et where reference = pe.reference and debit_kredit = 'H') as text2`)
|
||||
])
|
||||
.where('tcode', '=', "FB70")
|
||||
// .where('reference', '=', reference)
|
||||
.whereIn('pos_status', ["4"])
|
||||
'no_dok',
|
||||
'text',
|
||||
'debit_kredit',
|
||||
]);
|
||||
|
||||
.groupBy(['doc_header_text', 'ba', 'doc_header_text', 'tcode', 'ba', 'amount', 'posting_date', 'doc_date', 'doc_type', 'fiscal_year', 'reference', 'no_dok'])
|
||||
|
||||
return result
|
||||
|
||||
}
|
||||
return posting_et[0];
|
||||
};
|
||||
|
||||
const setReturnSAP = async (code, resSAP, trx) => {
|
||||
let t_cash_in = []
|
||||
let reserveBalance = []
|
||||
const cashInPostingTable = 'payment.t_cash_in_sap_posting';
|
||||
|
||||
if(resSAP.type == 'S'){
|
||||
// update invoice
|
||||
t_cash_in = await trx('payment.t_d_cash_in').update({
|
||||
c_return_sap: resSAP.data.E_DOCUMENTNUMBER,
|
||||
c_return_year_sap: resSAP.data.E_DOCUMENTYEAR
|
||||
}, ['c_cash_in_no','c_return_sap'])
|
||||
.where({
|
||||
c_cash_in_no: code
|
||||
});
|
||||
|
||||
// update load balance
|
||||
reserveBalance = await trx('trx.t_d_reservation_balance').update({
|
||||
c_return_cash_in_sap: resSAP.data.E_DOCUMENTNUMBER,
|
||||
c_cash_in_no: code
|
||||
}, ['c_cash_in_no', 'c_return_sap'])
|
||||
.whereRaw(`c_reservation_no IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail tdcid LEFT JOIN payment.t_d_cash_in tdci ON tdcid.i_cash_in = tdci.i_cash_in WHERE tdci.c_cash_in_no = '${code}')`)
|
||||
const getPostingEt = (db, limit) => db('public.posting_et AS pe')
|
||||
.select(
|
||||
'pe.doc_header_text', 'pe.ba', 'pe.doc_date', 'pe.posting_date', 'pe.fiscal_year',
|
||||
'pe.doc_type', 'pe.reference', 'pe.no_dok', 'pe.tcode', 'pe.amount',
|
||||
db.raw("TO_CHAR(pe.doc_date::date, 'MM') AS fis_period"),
|
||||
db.raw("'IDR' AS currency"),
|
||||
db.raw("MAX(pe.customer) FILTER (WHERE pe.debit_kredit = 'S') AS customer"),
|
||||
db.raw("MAX(pe.account) FILTER (WHERE pe.debit_kredit = 'H') AS account"),
|
||||
db.raw("MAX(pe.text) FILTER (WHERE pe.debit_kredit = 'S') AS text1"),
|
||||
db.raw("MAX(pe.text) FILTER (WHERE pe.debit_kredit = 'H') AS text2"),
|
||||
)
|
||||
.join('payment.t_d_cash_in AS cash', 'cash.c_cash_in_no', 'pe.no_dok')
|
||||
.where({ 'pe.tcode': 'FB70', 'pe.pos_status': '4' })
|
||||
.whereRaw("NULLIF(BTRIM(cash.c_return_sap::text), '') IS NULL")
|
||||
.whereNotExists(db(cashInPostingTable).whereColumn('cash_in_no', 'pe.no_dok'))
|
||||
.groupBy(
|
||||
'pe.doc_header_text', 'pe.ba', 'pe.doc_date', 'pe.posting_date', 'pe.fiscal_year',
|
||||
'pe.doc_type', 'pe.reference', 'pe.no_dok', 'pe.tcode', 'pe.amount',
|
||||
)
|
||||
.havingRaw("MAX(NULLIF(BTRIM(pe.customer::text), '')) FILTER (WHERE pe.debit_kredit = 'S') IS NOT NULL")
|
||||
.havingRaw("MAX(NULLIF(BTRIM(pe.account::text), '')) FILTER (WHERE pe.debit_kredit = 'H') IS NOT NULL")
|
||||
.orderBy('pe.no_dok')
|
||||
.limit(limit);
|
||||
|
||||
}else {
|
||||
let text = resSAP.message;
|
||||
let result = text.toUpperCase();
|
||||
if(result.includes("ALREADY")){
|
||||
let result = text.toUpperCase().split('-');
|
||||
let doc_number = result[1].trim().split(" ")[0]
|
||||
// update invoice
|
||||
const d = new Date();
|
||||
let year = d.getFullYear();
|
||||
t_cash_in = await trx('payment.t_d_cash_in').update({
|
||||
c_return_sap: doc_number,
|
||||
c_return_year_sap: year
|
||||
}, ['c_cash_in_no','c_return_sap'])
|
||||
.where({
|
||||
c_cash_in_no: code
|
||||
});
|
||||
// Batasi pengiriman lintas replika tanpa memegang koneksi selama panggilan SAP.
|
||||
const claimCashInPosting = (db, code) => db.transaction(async (trx) => {
|
||||
const { rows: [{ acquired }] } = await trx.raw('SELECT pg_try_advisory_xact_lock(17290, 1) AS acquired');
|
||||
if (!acquired) return 'busy';
|
||||
const sending = await trx(cashInPostingTable)
|
||||
.where('state', 'sending')
|
||||
.whereRaw("updated_at > now() - interval '30 seconds'")
|
||||
.first('cash_in_no');
|
||||
if (sending) return 'busy';
|
||||
|
||||
// update load balance
|
||||
reserveBalance = await trx('trx.t_d_reservation_balance').update({
|
||||
c_return_cash_in_sap: resSAP.data.E_DOCUMENTNUMBER,
|
||||
c_cash_in_no: code
|
||||
}, ['c_cash_in_no', 'c_return_sap'])
|
||||
.whereRaw(`c_reservation_no IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail tdcid LEFT JOIN payment.t_d_cash_in tdci ON tdcid.i_cash_in = tdci.i_cash_in WHERE tdci.c_cash_in_no = '${code}')`)
|
||||
const pending = await trx('payment.t_d_cash_in AS cash')
|
||||
.where('cash.c_cash_in_no', code)
|
||||
.whereRaw("NULLIF(BTRIM(cash.c_return_sap::text), '') IS NULL")
|
||||
.whereExists(trx('public.posting_et').where({ no_dok: code, tcode: 'FB70', pos_status: '4' }))
|
||||
.first('cash.c_cash_in_no');
|
||||
if (!pending) return 'skipped';
|
||||
|
||||
}
|
||||
const inserted = await trx(cashInPostingTable)
|
||||
.insert({ cash_in_no: code, state: 'sending' })
|
||||
.onConflict('cash_in_no').ignore().returning('cash_in_no');
|
||||
return inserted.length === 1 ? 'claimed' : 'skipped';
|
||||
});
|
||||
|
||||
}
|
||||
const releaseUnsentCashInPosting = (db, code) => db(cashInPostingTable)
|
||||
.where({ cash_in_no: code, state: 'sending' }).del();
|
||||
|
||||
// update posting et
|
||||
const posting_et = await trx('public.posting_et').update({
|
||||
pos_status : resSAP.type == 'S' ? 0 : 4,
|
||||
status0 : resSAP.type,
|
||||
no_doksap : resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null,
|
||||
status1 : resSAP.message ? resSAP.message : null
|
||||
}, ['file_name','status0']).where({
|
||||
no_dok: code
|
||||
})
|
||||
const recordCashInOutcome = (db, code, { documentNo, documentYear, status }) => db(cashInPostingTable)
|
||||
.where({ cash_in_no: code, state: 'sending' })
|
||||
.update({
|
||||
state: documentNo ? 'accepted' : 'unknown',
|
||||
document_no: documentNo || null,
|
||||
document_year: documentYear || null,
|
||||
outcome: status,
|
||||
updated_at: db.fn.now(),
|
||||
});
|
||||
|
||||
return {
|
||||
cash_in : t_cash_in[0],
|
||||
reserveBalance : reserveBalance[0],
|
||||
posting_et : posting_et[0]
|
||||
}
|
||||
|
||||
}
|
||||
const getAcceptedCashInPostings = (db, limit) => db(cashInPostingTable)
|
||||
.where('state', 'accepted').orderBy('updated_at').limit(limit).select('cash_in_no');
|
||||
|
||||
// Pulihkan hasil SAP yang sudah dikonfirmasi jika penyimpanan CMS sebelumnya gagal.
|
||||
const finishCashInPosting = (db, code) => db.transaction(async (trx) => {
|
||||
const posting = await trx(cashInPostingTable)
|
||||
.where({ cash_in_no: code, state: 'accepted' }).forUpdate().first();
|
||||
if (!posting) return;
|
||||
|
||||
const { document_no: documentNo, document_year: documentYear } = posting;
|
||||
const cashIn = await trx('payment.t_d_cash_in').where('c_cash_in_no', code)
|
||||
.update({ c_return_sap: documentNo, c_return_year_sap: documentYear }).returning('i_cash_in');
|
||||
if (cashIn.length !== 1) throw new Error('Cash-in document missing or duplicated during SAP finalization');
|
||||
await trx('trx.t_d_reservation_balance')
|
||||
.whereIn('c_reservation_no', trx('payment.t_d_cash_in_detail')
|
||||
.where('i_cash_in', cashIn[0].i_cash_in).select('c_reservation_no'))
|
||||
.update({ c_return_cash_in_sap: documentNo, c_cash_in_no: code });
|
||||
await trx('public.posting_et').where({ no_dok: code, tcode: 'FB70' })
|
||||
.update({ pos_status: 0, status0: 'S', no_doksap: documentNo, status1: 'SAP confirmed' });
|
||||
await trx(cashInPostingTable).where({ cash_in_no: code })
|
||||
.update({ state: 'completed', updated_at: trx.fn.now() });
|
||||
});
|
||||
|
||||
const getRecon = async (trx) => {
|
||||
|
||||
let sql = `SELECT
|
||||
tdi.c_invoice_no,
|
||||
'FB70' AS tcode,
|
||||
@@ -200,170 +201,594 @@ const getRecon = async (trx) => {
|
||||
SELECT c_reservation_no FROM payment.t_d_payment_recon tdpr WHERE tdpr.c_status = 'S'
|
||||
)
|
||||
GROUP BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17, tdpr.d_payment, b_past_month
|
||||
ORDER BY tdpr.d_payment`
|
||||
let result = await trx.raw(sql)
|
||||
ORDER BY tdpr.d_payment`;
|
||||
let result = await trx.raw(sql);
|
||||
|
||||
return result.rows
|
||||
}
|
||||
return result.rows;
|
||||
};
|
||||
|
||||
const getReserve = async(trx, code, date, invoice) => {
|
||||
const getReserve = async (trx, code, date, invoice) => {
|
||||
const res = await trx
|
||||
.select([
|
||||
'tdrb.c_reservation_no',
|
||||
'tdrb.i_reservation_amount',
|
||||
'tdpr.c_payment_recon_no',
|
||||
'tdpr.d_payment',
|
||||
'tdpr.d_payment_recon',
|
||||
'tdrb.c_partner_code',
|
||||
'tdrb.c_partner_name',
|
||||
'tdrb.c_load_balance_no',
|
||||
'tdi.c_invoice_no',
|
||||
'tdi.m_amount as invoice_amount'
|
||||
])
|
||||
.from('trx.t_d_reservation_balance AS tdrb')
|
||||
.leftJoin('trx.t_d_load_balance as tdlb', function () {
|
||||
this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no');
|
||||
})
|
||||
.innerJoin('payment.t_d_invoice as tdi', function () {
|
||||
this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no').orOn(
|
||||
'tdi.c_invoice_no',
|
||||
'=',
|
||||
'tdrb.c_invoice_no'
|
||||
);
|
||||
})
|
||||
.innerJoin('payment.t_d_payment_recon as tdpr', function () {
|
||||
this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no');
|
||||
})
|
||||
.where('tdrb.c_status', '=', 'A')
|
||||
.where('tdi.c_status', '!=', 'X')
|
||||
.where('tdrb.c_partner_code', '=', code)
|
||||
.where('tdpr.d_payment', '=', date)
|
||||
.where('tdi.c_invoice_no', '=', invoice)
|
||||
.where('tdpr.c_status', '=', 'S')
|
||||
.whereNotNull('tdi.c_return_sap')
|
||||
.whereNotNull('tdrb.c_load_balance_no')
|
||||
.whereNull('tdrb.c_cash_in_no')
|
||||
// .whereRaw(
|
||||
// `tdrb.c_reservation_no in (SELECT c_reservation_no FROM payment.t_d_payment_recon where c_status = 'S' ) AND tdrb.c_reservation_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)`
|
||||
// );
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
const res = await trx.select([
|
||||
"tdrb.c_reservation_no",
|
||||
"tdrb.i_reservation_amount",
|
||||
"tdpr.c_payment_recon_no",
|
||||
"tdpr.d_payment",
|
||||
"tdpr.d_payment_recon",
|
||||
"tdrb.c_partner_code",
|
||||
"tdrb.c_partner_name",
|
||||
"tdrb.c_load_balance_no",
|
||||
"tdi.c_invoice_no"
|
||||
])
|
||||
.from("trx.t_d_reservation_balance AS tdrb")
|
||||
.leftJoin('trx.t_d_load_balance as tdlb', function () {
|
||||
this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no')
|
||||
})
|
||||
.leftJoin('payment.t_d_invoice as tdi', function () {
|
||||
this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no')
|
||||
})
|
||||
.leftJoin('payment.t_d_payment_recon as tdpr', function () {
|
||||
this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no')
|
||||
})
|
||||
.where("tdrb.c_status", "=", "A")
|
||||
.where("tdi.c_status", "!=", "X")
|
||||
.where("tdrb.c_partner_code", "=", code)
|
||||
.where("tdpr.d_payment", "=", date)
|
||||
.where("tdi.c_invoice_no", "=", invoice)
|
||||
.where("tdpr.c_status", "=", "S")
|
||||
.whereNotNull("tdi.c_return_sap")
|
||||
.whereNotNull("tdrb.c_load_balance_no")
|
||||
.whereRaw(`tdrb.c_reservation_no in (SELECT c_reservation_no FROM payment.t_d_payment_recon where c_status = 'S' ) AND tdrb.c_reservation_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)`)
|
||||
return res
|
||||
}
|
||||
|
||||
const getPartnerRecon = async(trx) => {
|
||||
|
||||
const res = await trx.select([
|
||||
"tdpr.c_partner_code",
|
||||
"tdrb.c_partner_name",
|
||||
"tdi.c_invoice_no",
|
||||
"tdi.d_invoice_date",
|
||||
trx.raw("to_char(tdpr.d_payment, 'YYYY-MM-DD') AS d_payment"),
|
||||
trx.raw("SUM(tdrb.i_reservation_amount) AS amount"),
|
||||
"tmp.c_account_topup",
|
||||
"tmp.c_account_code_topup",
|
||||
"i_company",
|
||||
"i_holding",
|
||||
trx.raw(`CASE
|
||||
WHEN to_char(tdpr.d_payment, 'MM') = to_char(tdi.d_invoice_date, 'MM')
|
||||
const getSalesKMT = async (trx, code, date, invoice) => {
|
||||
const res = await trx
|
||||
.select([
|
||||
'tdskm.c_sales_no',
|
||||
'tdskm.i_total_billing',
|
||||
'tdpr.c_payment_recon_no',
|
||||
'tdpr.d_payment',
|
||||
'tdpr.d_payment_recon',
|
||||
'tdskm.c_partner_code',
|
||||
'tdskm.c_partner_name',
|
||||
'tdsi.c_invoice_no',
|
||||
'tdsi.m_total_billing as invoice_amount'
|
||||
])
|
||||
.from('kmt_mobile.t_d_sales_kmt_mobile AS tdskm')
|
||||
.innerJoin('payment.t_d_payment_recon_sales_kmt_mobile as tdpr', 'tdpr.c_sales_no', 'tdskm.c_sales_no')
|
||||
.innerJoin('payment.t_d_sales_invoice as tdsi', 'tdsi.i_sales_invoice', 'tdskm.i_sales_invoice')
|
||||
|
||||
.where('tdskm.c_sales_status', '=', 'A')
|
||||
.where('tdsi.c_status', '!=', 'X')
|
||||
.where('tdskm.c_partner_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_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;
|
||||
};
|
||||
|
||||
const getPartnerRecon = async (trx) => {
|
||||
// const res = await trx
|
||||
// .select([
|
||||
// 'tdpr.c_partner_code',
|
||||
// 'tdrb.c_partner_name',
|
||||
// 'tdi.c_invoice_no',
|
||||
// 'tdi.d_invoice_date',
|
||||
// trx.raw("to_char(tdpr.d_payment, 'YYYY-MM-DD') AS d_payment"),
|
||||
// trx.raw('SUM(tdrb.i_reservation_amount) AS amount'),
|
||||
// 'tmp.c_account_topup',
|
||||
// 'tmp.c_account_code_topup',
|
||||
// 'i_company',
|
||||
// 'i_holding',
|
||||
// trx.raw(`CASE
|
||||
// WHEN to_char(tdpr.d_payment, 'MM') >= to_char(tdi.d_invoice_date, 'MM')
|
||||
// THEN 'IP'
|
||||
// ELSE
|
||||
// 'OP'
|
||||
// END c_in_period`),
|
||||
// ])
|
||||
// .from('trx.t_d_reservation_balance AS tdrb')
|
||||
// .leftJoin('trx.t_d_load_balance as tdlb', function () {
|
||||
// this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no');
|
||||
// })
|
||||
// .leftJoin('payment.t_d_invoice as tdi', function () {
|
||||
// this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no').orOn(
|
||||
// 'tdi.c_invoice_no',
|
||||
// '=',
|
||||
// 'tdrb.c_invoice_no'
|
||||
// );
|
||||
// })
|
||||
// .leftJoin('payment.t_d_payment_recon as tdpr', function () {
|
||||
// this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no');
|
||||
// })
|
||||
// .leftJoin('public.t_m_partner as tmp', function () {
|
||||
// this.on('tmp.i_partner', '=', 'tdrb.i_partner');
|
||||
// })
|
||||
|
||||
// .where('tdrb.c_status', '=', 'A')
|
||||
// .where('tdi.c_status', '!=', 'X')
|
||||
// .where('tdpr.c_status', '=', 'S')
|
||||
// .whereNotNull('tdi.c_return_sap')
|
||||
// .whereNotNull('tdrb.c_load_balance_no')
|
||||
// .whereRaw(
|
||||
// `tdrb.c_reservation_no in (SELECT c_reservation_no FROM payment.t_d_payment_recon where c_status = 'S' ) AND tdrb.c_reservation_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)`
|
||||
// )
|
||||
// .groupBy([
|
||||
// 'tdpr.c_partner_code',
|
||||
// 'tdrb.c_partner_name',
|
||||
// 'tdi.c_invoice_no',
|
||||
// 'tdi.d_invoice_date',
|
||||
// 'tdpr.d_payment',
|
||||
// 'tmp.c_account_topup',
|
||||
// 'tmp.c_account_code_topup',
|
||||
// 'tdi.i_company',
|
||||
// 'i_holding',
|
||||
// ])
|
||||
// .limit(1);
|
||||
// .toSql()
|
||||
|
||||
const res = await trx
|
||||
.select([
|
||||
'tdpr.c_partner_code',
|
||||
'tdrb.c_partner_name',
|
||||
'tdi.c_invoice_no',
|
||||
'tdi.d_invoice_date',
|
||||
trx.raw("to_char(tdpr.d_payment, 'YYYY-MM-DD') AS d_payment"),
|
||||
trx.raw('coalesce(SUM(tdrb.i_reservation_amount),0) AS amount'),
|
||||
// trx.raw('coalesce(SUM(tdcid.m_amount),0) AS amount_cash_in'),
|
||||
'tmp.c_account_topup',
|
||||
'tmp.c_account_code_topup',
|
||||
'i_company',
|
||||
'i_holding',
|
||||
trx.raw(`CASE
|
||||
WHEN date_trunc('month', tdpr.d_payment) >= date_trunc('month', tdi.d_invoice_date)
|
||||
THEN 'IP'
|
||||
ELSE
|
||||
'OP'
|
||||
END c_in_period`),
|
||||
])
|
||||
.from("trx.t_d_reservation_balance AS tdrb")
|
||||
.leftJoin('trx.t_d_load_balance as tdlb', function () {
|
||||
this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no')
|
||||
})
|
||||
.leftJoin('payment.t_d_invoice as tdi', function () {
|
||||
this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no')
|
||||
})
|
||||
.leftJoin('payment.t_d_payment_recon as tdpr', function () {
|
||||
this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no')
|
||||
})
|
||||
.leftJoin('public.t_m_partner as tmp', function () {
|
||||
this.on('tmp.c_code', '=', 'tdrb.c_partner_code')
|
||||
})
|
||||
|
||||
.where("tdrb.c_status", "=", "A")
|
||||
.where("tdi.c_status", "!=", "X")
|
||||
.where("tdpr.c_status", "=", "S")
|
||||
.whereNotNull("tdi.c_return_sap")
|
||||
.whereNotNull("tdrb.c_load_balance_no")
|
||||
.whereRaw(`tdrb.c_reservation_no in (SELECT c_reservation_no FROM payment.t_d_payment_recon where c_status = 'S' ) AND tdrb.c_reservation_no NOT IN (SELECT c_reservation_no FROM payment.t_d_cash_in_detail WHERE b_reversal IS NOT TRUE)`)
|
||||
.groupBy(["tdpr.c_partner_code","tdrb.c_partner_name","tdi.c_invoice_no","tdi.d_invoice_date", "tdpr.d_payment", "tmp.c_account_topup", "tmp.c_account_code_topup", "tdi.i_company", "i_holding"])
|
||||
// .toSql()
|
||||
])
|
||||
.from('trx.t_d_reservation_balance AS tdrb')
|
||||
.leftJoin('trx.t_d_load_balance as tdlb', function () {
|
||||
this.on('tdrb.c_load_balance_no', '=', 'tdlb.c_load_balance_no');
|
||||
})
|
||||
.innerJoin('payment.t_d_invoice as tdi', function () {
|
||||
this.on('tdi.c_invoice_no', '=', 'tdlb.c_invoice_no').orOn(
|
||||
'tdi.c_invoice_no',
|
||||
'=',
|
||||
'tdrb.c_invoice_no'
|
||||
);
|
||||
})
|
||||
.innerJoin('payment.t_d_payment_recon as tdpr', function () {
|
||||
this.on('tdpr.c_reservation_no', '=', 'tdrb.c_reservation_no');
|
||||
})
|
||||
.innerJoin('public.t_m_partner as tmp', function () {
|
||||
this.on('tmp.i_partner', '=', 'tdrb.i_partner');
|
||||
})
|
||||
// .leftJoin('payment.t_d_cash_in_detail as tdcid', function () {
|
||||
// this.on('tdcid.c_reservation_no', '=', 'tdrb.c_reservation_no');
|
||||
// })
|
||||
|
||||
return res
|
||||
.where('tdrb.c_status', '=', 'A')
|
||||
.where('tdi.c_status', '!=', 'X')
|
||||
.where('tdpr.c_status', '=', 'S')
|
||||
.whereNotNull('tdi.c_return_sap')
|
||||
.whereNotNull('tdrb.c_load_balance_no')
|
||||
.whereNull('tdrb.c_cash_in_no')
|
||||
.groupBy([
|
||||
'tdpr.c_partner_code',
|
||||
'tdrb.c_partner_name',
|
||||
'tdi.c_invoice_no',
|
||||
'tdi.d_invoice_date',
|
||||
'tdpr.d_payment',
|
||||
'tmp.c_account_topup',
|
||||
'tmp.c_account_code_topup',
|
||||
'tdi.i_company',
|
||||
'i_holding',
|
||||
]);
|
||||
// .havingRaw(
|
||||
// 'coalesce(SUM(tdrb.i_reservation_amount),0) > coalesce(SUM(tdcid.m_amount),0)'
|
||||
// );
|
||||
|
||||
}
|
||||
return res;
|
||||
};
|
||||
|
||||
const getPartnerReconSales = async (trx) => {
|
||||
|
||||
const res = await trx
|
||||
.select([
|
||||
'tdsi.c_partner_code',
|
||||
'tdsi.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_billing),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 'OP'
|
||||
END c_in_period`),
|
||||
])
|
||||
.from('kmt_mobile.t_d_sales_kmt_mobile AS tdskm')
|
||||
|
||||
.innerJoin('payment.t_d_sales_invoice as tdsi', function () {
|
||||
this.on('tdsi.i_sales_invoice', '=', 'tdskm.i_sales_invoice');
|
||||
})
|
||||
.innerJoin('payment.t_d_payment_recon_sales_kmt_mobile 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('tdskm.c_sales_status', '=', 'A')
|
||||
.where('tdsi.c_status', '!=', 'X')
|
||||
.where('tdpr.c_status', '=', 'S')
|
||||
.whereNotNull('tdsi.c_return_sap')
|
||||
.whereNull('tdskm.c_cash_in_no')
|
||||
.groupBy([
|
||||
'tdsi.c_partner_code',
|
||||
'tdsi.c_partner_name',
|
||||
'tdsi.c_invoice_no',
|
||||
'tdsi.d_invoice_date',
|
||||
'tdpr.d_payment',
|
||||
'tmp.c_account_topup',
|
||||
'tmp.c_account_code_topup'
|
||||
]);
|
||||
|
||||
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) => {
|
||||
let code = ""
|
||||
let prefix = `CIN${c_partner_code}${d_payment_recon}`
|
||||
let code = '';
|
||||
let prefix = `CIN${c_partner_code}${d_payment_recon}`;
|
||||
|
||||
let result =await trx.select([trx.raw(`substring(c_cash_in_no, 13, 3) AS code`)])
|
||||
.from("payment.t_d_cash_in")
|
||||
.whereRaw(`substring(c_cash_in_no, 1, 12) = '${prefix}'`)
|
||||
// .where("d_project_date", projectDate)
|
||||
.orderBy('c_cash_in_no', 'DESC')
|
||||
.first()
|
||||
let result = await trx
|
||||
.select([trx.raw(`right(c_cash_in_no, 3) AS code`)])
|
||||
.from('payment.t_d_cash_in')
|
||||
.where('c_cash_in_no', 'like', `${prefix}%`)
|
||||
// .where("d_project_date", projectDate)
|
||||
.orderBy('c_cash_in_no', 'DESC')
|
||||
.first();
|
||||
|
||||
if(result){
|
||||
let counter = parseInt(result.code)+1
|
||||
if (result) {
|
||||
let counter = parseInt(result.code, 10) + 1;
|
||||
counter = String(counter).padStart(3, '0');
|
||||
code = `${prefix}${counter}`
|
||||
|
||||
}else{
|
||||
code = `${prefix}001`
|
||||
code = `${prefix}${counter}`;
|
||||
} else {
|
||||
code = `${prefix}001`;
|
||||
}
|
||||
|
||||
return code
|
||||
}
|
||||
return code;
|
||||
};
|
||||
|
||||
const insertCashInDetail = async (trx, data) => {
|
||||
let result = []
|
||||
if(data.length > 0){
|
||||
result = await trx('payment.t_d_cash_in_detail').insert(data,["*"])
|
||||
let result = [];
|
||||
// if (data.length > 0) {
|
||||
// result = await trx('payment.t_d_cash_in_detail').insert(data, ['*']);
|
||||
// }
|
||||
|
||||
if (data) {
|
||||
result = await trx('payment.t_d_cash_in_detail').insert(data, ['*']);
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const updateIntoReserve = async (trx, dataReserve, reserveNo) => {
|
||||
let result = await trx('trx.t_d_reservation_balance').update(dataReserve, ["*"]).where({c_reservation_no: reserveNo})
|
||||
return result
|
||||
}
|
||||
let result = await trx('trx.t_d_reservation_balance')
|
||||
.update(dataReserve, ['*'])
|
||||
.where({ c_reservation_no: reserveNo });
|
||||
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) => {
|
||||
let result = await trx('kmt_mobile.t_d_sales_kmt_mobile')
|
||||
.update(dataSales, ['*'])
|
||||
.where({ c_sales_no: salesNo });
|
||||
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) => {
|
||||
let result = await trx('payment.t_d_cash_in').insert(data,["*"])
|
||||
return result[0]
|
||||
}
|
||||
let result = await trx('payment.t_d_cash_in').insert(data, ['*']);
|
||||
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) => {
|
||||
console.log(data)
|
||||
const result = await trx('log.t_log_invoice').insert({
|
||||
// i_log_name : 102,
|
||||
i_log_name : 119,
|
||||
d_log : trx.raw('NOW()'),
|
||||
c_invoice_no : data.c_cash_in_no,
|
||||
c_partner_name : data.c_partner_name,
|
||||
j_new_data : JSON.stringify(data),
|
||||
d_payment_date: trx.raw('NOW()'),
|
||||
c_note : message,
|
||||
c_status : 'S',
|
||||
d_created : trx.raw('NOW()'),
|
||||
m_amount : data.amount,
|
||||
m_mdr_amount : 0,
|
||||
m_mdr_net : data.amount
|
||||
|
||||
}, ['i_log_name', 'c_note'])
|
||||
|
||||
return result
|
||||
|
||||
}
|
||||
const result = await trx('log.t_log_invoice').insert(
|
||||
{
|
||||
// i_log_name : 102,
|
||||
i_log_name: 119,
|
||||
d_log: trx.raw('NOW()'),
|
||||
c_invoice_no: data.c_cash_in_no,
|
||||
c_partner_name: data.c_partner_name,
|
||||
j_new_data: JSON.stringify(data),
|
||||
d_payment_date: trx.raw('NOW()'),
|
||||
c_note: message,
|
||||
c_status: 'S',
|
||||
d_created: trx.raw('NOW()'),
|
||||
m_amount: data.amount,
|
||||
m_mdr_amount: 0,
|
||||
m_mdr_net: data.amount,
|
||||
},
|
||||
['i_log_name', 'c_note']
|
||||
);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
generateInvoice,
|
||||
insertPostingEt,
|
||||
setReturnSAP,
|
||||
getPostingEt,
|
||||
claimCashInPosting,
|
||||
getAcceptedCashInPostings,
|
||||
finishCashInPosting,
|
||||
releaseUnsentCashInPosting,
|
||||
recordCashInOutcome,
|
||||
writePaynentHistory,
|
||||
|
||||
getRecon,
|
||||
generateCode,
|
||||
insertCashInDetail,
|
||||
getReserve,
|
||||
getPartnerRecon,
|
||||
getPartnerReconSales,
|
||||
getPartnerReconSalesInternal,
|
||||
getPartnerReconTopUpCashlessInternal,
|
||||
getReserve,
|
||||
getSalesKMT,
|
||||
getSalesInternal,
|
||||
getTopUpCashlessInternal,
|
||||
insertCashIn,
|
||||
updateIntoReserve
|
||||
};
|
||||
insertCashInDetailBulk,
|
||||
updateIntoReserve,
|
||||
updateIntoReserveBulk,
|
||||
updateIntoSalesKMT,
|
||||
updateIntoSalesKMTBulk,
|
||||
updateIntoSalesInternal,
|
||||
updateIntoSalesInternalBulk,
|
||||
updateIntoTopUpCashlessInternal,
|
||||
updateIntoTopUpCashlessInternalBulk,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,362 @@
|
||||
const moment = require('moment');
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./cahsin.model');
|
||||
|
||||
moment.locale('id');
|
||||
|
||||
// Simpan header, audit, dan detail Cash-in dalam transaksi yang sama per invoice.
|
||||
const _generateCashIn = async (uniqueCode) => {
|
||||
const partnerRecon = await model.getPartnerRecon(knex);
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} Cash-in candidates count=${partnerRecon.length}`
|
||||
);
|
||||
|
||||
for (const item of partnerRecon) {
|
||||
try {
|
||||
await knex.transaction(async (trx) => {
|
||||
const reserv = await model.getReserve(
|
||||
trx,
|
||||
item.c_partner_code,
|
||||
item.d_payment,
|
||||
item.c_invoice_no
|
||||
);
|
||||
|
||||
if (!reserv || reserv.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const cashInAmount = reserv.reduce(
|
||||
(sum, row) => sum + parseInt(row.i_reservation_amount, 10),
|
||||
0
|
||||
);
|
||||
|
||||
if (cashInAmount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let runningAmount = 0;
|
||||
for (const detail of reserv) {
|
||||
runningAmount += parseInt(detail.i_reservation_amount, 10);
|
||||
if (runningAmount > parseInt(detail.invoice_amount, 10)) {
|
||||
winston.logger.warn(
|
||||
`SCHEDULER-FB70-${uniqueCode} SKIP CASH-IN: 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 cashInData = {
|
||||
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, cashInData);
|
||||
await model.writePaynentHistory(cashInData, '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,
|
||||
c_reservation_no: detail.c_reservation_no,
|
||||
m_amount: detail.i_reservation_amount,
|
||||
c_payment_recon_no: detail.c_payment_recon_no,
|
||||
d_payment: detail.d_payment,
|
||||
d_payment_recon: detail.d_payment_recon,
|
||||
c_load_balance_no: detail.c_load_balance_no,
|
||||
}));
|
||||
|
||||
await model.updateIntoReserveBulk(trx, dataReserve, reserveNos);
|
||||
await model.insertCashInDetailBulk(trx, cashInDetails);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}`
|
||||
);
|
||||
});
|
||||
} 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;
|
||||
};
|
||||
|
||||
const _generateCashInSales = async (uniqueCode) => {
|
||||
const partnerRecon = await model.getPartnerReconSales(knex);
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} Cash-in candidates count=${partnerRecon.length}`
|
||||
);
|
||||
|
||||
for (const item of partnerRecon) {
|
||||
try {
|
||||
await knex.transaction(async (trx) => {
|
||||
const sales = await model.getSalesKMT(
|
||||
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_billing, 10),
|
||||
0
|
||||
);
|
||||
|
||||
if (cashInAmount <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
let runningAmount = 0;
|
||||
for (const detail of sales) {
|
||||
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 cashInData = {
|
||||
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, cashInData);
|
||||
await model.writePaynentHistory(cashInData, '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,
|
||||
c_reservation_no: detail.c_sales_no,
|
||||
m_amount: detail.i_total_billing,
|
||||
c_payment_recon_no: detail.c_payment_recon_no,
|
||||
d_payment: detail.d_payment,
|
||||
d_payment_recon: detail.d_payment_recon,
|
||||
}));
|
||||
|
||||
await model.updateIntoSalesKMTBulk(trx, dataSales, salesNos);
|
||||
await model.insertCashInDetailBulk(trx, cashInDetails);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} INSERT CASH-IN SALES ${code} SUCCESS. partner=${item.c_partner_code}, invoice=${item.c_invoice_no}, rows=${cashInDetails.length}, amount=${cashInAmount}`
|
||||
);
|
||||
});
|
||||
} catch (error) {
|
||||
winston.logger.error(
|
||||
`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) => {
|
||||
const partnerRecon = await model.getPartnerReconSalesInternal(knex);
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} Cash-in candidates count=${partnerRecon.length}`
|
||||
);
|
||||
|
||||
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 cashInData = {
|
||||
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, cashInData);
|
||||
await model.writePaynentHistory(cashInData, '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) => {
|
||||
const partnerRecon = await model.getPartnerReconTopUpCashlessInternal(knex);
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} Cash-in candidates count=${partnerRecon.length}`
|
||||
);
|
||||
|
||||
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 cashInData = {
|
||||
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, cashInData);
|
||||
await model.writePaynentHistory(cashInData, '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;
|
||||
};
|
||||
|
||||
module.exports = { _generateCashIn, _generateCashInSales, _generateCashInSalesInternal, _generateCashInTopUpCashlessInternal };
|
||||
@@ -0,0 +1,103 @@
|
||||
const db = require('../../../infrastructure/database/knex');
|
||||
const helper = require('../../helpers/helper');
|
||||
const { logger } = require('../../helpers/winston.logger');
|
||||
const { getSapSettings } = require('../invoiceonline/invoice.model');
|
||||
const model = require('./cahsin.model');
|
||||
|
||||
const preConnectErrors = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ERR_INVALID_URL']);
|
||||
const timeoutMs = 15000;
|
||||
const batchSize = 50;
|
||||
|
||||
async function postCashIn(uniqueCode) {
|
||||
const accepted = await model.getAcceptedCashInPostings(db, batchSize);
|
||||
for (const { cash_in_no: code } of accepted) await model.finishCashInPosting(db, code);
|
||||
|
||||
const items = await model.getPostingEt(db, batchSize);
|
||||
if (items.length === 0) return [];
|
||||
|
||||
const { url, username, password } = await getSapSettings(db);
|
||||
if (!url || !username || !password) throw new Error('SAP cash-in settings are incomplete');
|
||||
|
||||
const processed = [];
|
||||
for (const item of items) {
|
||||
if (!item.customer || !item.account) {
|
||||
logger.warn(`Cash-in ${uniqueCode} ${item.no_dok} SAP accounts missing`);
|
||||
continue;
|
||||
}
|
||||
const xml = buildXml(item);
|
||||
const claim = await model.claimCashInPosting(db, item.no_dok);
|
||||
if (claim === 'busy') break;
|
||||
if (claim === 'claimed') {
|
||||
await submitCashIn(item.no_dok, uniqueCode, url, xml, { username, password });
|
||||
processed.push(item);
|
||||
}
|
||||
}
|
||||
return processed;
|
||||
}
|
||||
|
||||
// Klaim sudah commit saat HTTP dikirim. Hasil yang tidak pasti menunggu rekonsiliasi.
|
||||
async function submitCashIn(code, uniqueCode, url, xml, credentials) {
|
||||
const response = await helper.postingSAP(url, xml, credentials, { timeoutMs, maxRedirects: 0 });
|
||||
if (preConnectErrors.has(response.errorCode)) {
|
||||
await model.releaseUnsentCashInPosting(db, code);
|
||||
logger.warn(`Cash-in ${uniqueCode} ${code} SAP connection not established`);
|
||||
return;
|
||||
}
|
||||
|
||||
const outcome = readOutcome(response);
|
||||
await model.recordCashInOutcome(db, code, outcome);
|
||||
if (outcome.documentNo) {
|
||||
await model.finishCashInPosting(db, code);
|
||||
} else {
|
||||
logger.warn(`Cash-in ${uniqueCode} ${code} requires SAP reconciliation (${outcome.status})`);
|
||||
}
|
||||
}
|
||||
|
||||
function readOutcome(response) {
|
||||
if (response.status !== 200) {
|
||||
const timedOut = ['ERR_CANCELED', 'ECONNABORTED', 'ETIMEDOUT'].includes(response.errorCode);
|
||||
return { status: timedOut ? 'SAP_TIMEOUT' : 'SAP_HTTP_ERROR' };
|
||||
}
|
||||
try {
|
||||
const result = helper.getXMLData(response);
|
||||
const { E_DOCUMENTNUMBER: documentNo, E_DOCUMENTYEAR: documentYear } = result.data;
|
||||
if (result.type === 'S' && /^\d+$/.test(documentNo) && /[1-9]/.test(documentNo)) {
|
||||
return { documentNo, documentYear, status: 'SAP_CONFIRMED' };
|
||||
}
|
||||
// SAP juga dapat mengembalikan nomor dokumen yang telah diposting untuk referensi ini.
|
||||
const alreadyPosted = /\bALREADY\b[^-]*-\s*(\d+)(?:\s|$)/i.exec(result.message)?.[1];
|
||||
if (alreadyPosted && /[1-9]/.test(alreadyPosted)) {
|
||||
const year = documentYear === '0000' ? String(new Date().getFullYear()) : documentYear;
|
||||
return { documentNo: alreadyPosted, documentYear: year, status: 'SAP_ALREADY_POSTED' };
|
||||
}
|
||||
} catch {
|
||||
return { status: 'SAP_INVALID_RESPONSE' };
|
||||
}
|
||||
return { status: 'SAP_UNCONFIRMED' };
|
||||
}
|
||||
|
||||
function buildXml(item) {
|
||||
const header = {
|
||||
doc_header_text: item.doc_header_text || '',
|
||||
ba: item.ba || '',
|
||||
doc_date: item.doc_date || '',
|
||||
posting_date: item.posting_date || '',
|
||||
fisc_year: item.fiscal_year || '',
|
||||
fisc_period: item.fis_period || '',
|
||||
doc_type: item.doc_type || '',
|
||||
c_invoice_no: item.reference || '',
|
||||
};
|
||||
const lines = ['S', 'H'].map((side) => ({
|
||||
c_account_code_topup: side === 'S' ? item.customer : '',
|
||||
c_account_topup: side === 'H' ? item.account : '',
|
||||
ba: item.ba,
|
||||
amount: item.amount,
|
||||
posting_date: item.posting_date,
|
||||
c_invoice_no: item.reference || '',
|
||||
item_text: (side === 'S' ? item.text1 : item.text2) || '',
|
||||
de_cre: side,
|
||||
}));
|
||||
return helper.generateXMLRequest('ZFMCMS_FI_001', header, lines);
|
||||
}
|
||||
|
||||
module.exports = postCashIn;
|
||||
@@ -1,16 +1,16 @@
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
const helper = require("../../helpers/helper");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const model = require("./dongleorder.model");
|
||||
const moment = require("moment");
|
||||
moment.locale("id");
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./dongleorder.model');
|
||||
const moment = require('moment');
|
||||
moment.locale('id');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "dongleOrderUpdate":
|
||||
case 'dongleOrderUpdate':
|
||||
return [
|
||||
body("dongle_id").not().isEmpty().withMessage("Dongle ID is required"),
|
||||
body('dongle_id').not().isEmpty().withMessage('Dongle ID is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
@@ -20,12 +20,11 @@ const validate = (method) => {
|
||||
// GET DONGLE ORDER
|
||||
const getDongleOrder = async (req, res) => {
|
||||
try {
|
||||
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
// param
|
||||
let year = req.query.year;
|
||||
let year = req.query.year;
|
||||
|
||||
if (!year) {
|
||||
year = moment().format('YYYY');
|
||||
@@ -34,34 +33,32 @@ const getDongleOrder = async (req, res) => {
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} get RO...`);
|
||||
|
||||
// get RO
|
||||
// get RO
|
||||
let getRO = await model.getRO(year);
|
||||
if (getRO.length == 0) {
|
||||
result = {
|
||||
code: "422",
|
||||
code: '422',
|
||||
message: "data doesn't exists'",
|
||||
data: [],
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE get RO and dongle order: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
`${uniqueCode} RESPONSE get RO and dongle order code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "success",
|
||||
code: '00',
|
||||
message: 'success',
|
||||
data: getRO,
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} RESPONSE get RO and dongle order: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} RESPONSE get RO and dongle order code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.json(result);
|
||||
@@ -72,11 +69,11 @@ const getDongleOrder = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
@@ -86,75 +83,74 @@ const getDongleOrder = async (req, res) => {
|
||||
const updateDongleOrder = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let {
|
||||
dongle_id, status
|
||||
} = req.body;
|
||||
let { dongle_id, status } = req.body;
|
||||
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST update dongle order: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} REQUEST update dongle order`
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: "400",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE update dongle order: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} RESPONSE update dongle order code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// time
|
||||
let now = moment().format("YYYY-MM-DD HH:mm:ss");
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`${uniqueCode} updating dongle order...`);
|
||||
|
||||
let data = {
|
||||
c_status: status == "C" ? "C" : "I",
|
||||
c_status_name: status == "C" ? "CREATED" : "INJECTED",
|
||||
c_status: status == 'C' ? 'C' : 'I',
|
||||
c_status_name: status == 'C' ? 'CREATED' : 'INJECTED',
|
||||
d_modify: now,
|
||||
}
|
||||
};
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let updateDongleOrderStatus = await model.updateDongleOrderStatus(data, dongle_id);
|
||||
let updateDongleOrderStatus = await model.updateDongleOrderStatus(
|
||||
data,
|
||||
dongle_id
|
||||
);
|
||||
if (!updateDongleOrderStatus) {
|
||||
result = {
|
||||
code: "423",
|
||||
message: "update failed",
|
||||
code: '423',
|
||||
message: 'update failed',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE update dongle order: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
`${uniqueCode} RESPONSE update dongle order code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "updated successfully",
|
||||
code: '00',
|
||||
message: 'updated successfully',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} RESPONSE update dongle order: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} RESPONSE update dongle order code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
@@ -165,11 +161,11 @@ const updateDongleOrder = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,30 +1,30 @@
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
const helper = require("../../helpers/helper");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const model = require("./history.model");
|
||||
const moment = require("moment");
|
||||
moment.locale("id");
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./history.model');
|
||||
const moment = require('moment');
|
||||
moment.locale('id');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "cardHistory":
|
||||
case 'cardHistory':
|
||||
return [
|
||||
body("data")
|
||||
body('data')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Data is required")
|
||||
.withMessage('Data is required')
|
||||
.isArray()
|
||||
.withMessage("Data is invalid request format"),
|
||||
.withMessage('Data is invalid request format'),
|
||||
];
|
||||
case "history":
|
||||
case 'history':
|
||||
return [
|
||||
body("mid").not().isEmpty().withMessage("MID is required"),
|
||||
body("tid").not().isEmpty().withMessage("TID is required"),
|
||||
body("card_number")
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Card Number is required"),
|
||||
.withMessage('Card Number is required'),
|
||||
];
|
||||
|
||||
default:
|
||||
@@ -32,33 +32,38 @@ const validate = (method) => {
|
||||
}
|
||||
};
|
||||
|
||||
// HISTORY FROM CARD
|
||||
// ================================================================= HISTORY FROM CARD =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *Description:*
|
||||
// proses yang digunakan untuk menampilkan history kartu berdasrkan data / content yang tersimpan di dalam kartu
|
||||
|
||||
const cardHistory = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
let result = [];
|
||||
|
||||
// param
|
||||
let { data } = req.body;
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST card history: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST CARD-HISTORY ]`
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: "400",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
data: [],
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE card history: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE CARD-HISTORY ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
@@ -76,44 +81,66 @@ const cardHistory = async (req, res) => {
|
||||
let indexHistory = 0;
|
||||
let checkReskaFormat;
|
||||
let checkKCIFormat;
|
||||
|
||||
// lakukan perulangan data array yang dikirim dari client
|
||||
for (let index = 0; index < data.length; index++) {
|
||||
element = data[index];
|
||||
|
||||
if (element != "00000000000000000000000000000000") {
|
||||
if (element != '00000000000000000000000000000000') {
|
||||
date = moment(
|
||||
new Date((parseInt(element.slice(0, 8), 16) + 946684800) * 1000)
|
||||
).format("YYYY-MM-DD HH:mm:ss");
|
||||
).format('YYYY-MM-DD HH:mm:ss');
|
||||
nominal = parseInt(element.slice(8, 16), 16);
|
||||
mid = element.slice(16, 20);
|
||||
tid = element.slice(20, 24);
|
||||
mid = element.slice(16, 20).toUpperCase();
|
||||
tid = element.slice(20, 24).toUpperCase();
|
||||
|
||||
// blok yang menandakan konten untuk reska
|
||||
checkReskaFormat = element.slice(14, 20);
|
||||
|
||||
// blok yang menandakan konten untuk KCI
|
||||
checkKCIFormat = element.slice(26, 28);
|
||||
|
||||
if (checkReskaFormat == "000000") {
|
||||
istopup = "Deduct";
|
||||
// jika blok untuk reska itu 000000 maka state bahwa itu transaki deduct dari sistem reska
|
||||
if (checkReskaFormat == '000000') {
|
||||
istopup = 'Deduct';
|
||||
|
||||
// get nominal dari blok konten yang dikirim
|
||||
nominal = parseInt(element.slice(20, 24), 16);
|
||||
|
||||
date = element.slice(4, 8) + '-' + element.slice(2, 4) + '-' + element.slice(0, 2) + ' ' + element.slice(8, 10) + ':' + element.slice(10, 12) + ':' + element.slice(12, 14);
|
||||
// get date dari blok konten yang dikirim
|
||||
date =
|
||||
element.slice(4, 8) +
|
||||
'-' +
|
||||
element.slice(2, 4) +
|
||||
'-' +
|
||||
element.slice(0, 2) +
|
||||
' ' +
|
||||
element.slice(8, 10) +
|
||||
':' +
|
||||
element.slice(10, 12) +
|
||||
':' +
|
||||
element.slice(12, 14);
|
||||
|
||||
// get terminal name
|
||||
terminalName = "PARKIR RESKA";
|
||||
console.log('HAHAHHAHAHAHHAHAHAHAHAHHA');
|
||||
} else if (checkKCIFormat == "00") {
|
||||
terminalName = 'PARKIR RESKA';
|
||||
} else if (checkKCIFormat == '00') {
|
||||
// jika blok untuk KCI itu 00 maka state bahwa itu transaksi dari sistem KCI
|
||||
// ambil konten di blok ke 25 dan 26, jika konten nya == 0 maka itu transaksi topup, dan jika bukan 0 maka itu transaksi deduct
|
||||
istopup =
|
||||
parseInt(element.slice(24, 26), 16) == 0 ? "Topup" : "Deduct";
|
||||
parseInt(element.slice(24, 26), 16) == 0 ? 'Topup' : 'Deduct';
|
||||
|
||||
// get terminal name
|
||||
terminalName = await model.getTerminalKCIExisting(mid);
|
||||
terminalName = terminalName ? terminalName.merchant_name : "";
|
||||
terminalName = terminalName ? terminalName.merchant_name : '';
|
||||
} else {
|
||||
// jika bukan blok reska dan KCI maka cek dari tid mid dari sistem CMS
|
||||
// ambil konten di blok ke 25 dan 26, jika konten nya == 0 maka itu transaksi topup, dan jika bukan 0 maka itu transaksi deduct
|
||||
istopup =
|
||||
parseInt(element.slice(24, 26), 16) == 0 ? "Topup" : "Deduct";
|
||||
parseInt(element.slice(24, 26), 16) == 0 ? 'Topup' : 'Deduct';
|
||||
|
||||
// get terminal name
|
||||
terminalName = await model.getPartnerPartialMIDTID(mid, tid);
|
||||
terminalName = terminalName ? terminalName.merchant_name : "";
|
||||
terminalName = terminalName ? terminalName.merchant_name : '';
|
||||
}
|
||||
|
||||
history[indexHistory] = {
|
||||
@@ -128,74 +155,137 @@ const cardHistory = async (req, res) => {
|
||||
}
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "success",
|
||||
code: '00',
|
||||
message: 'success',
|
||||
data: history,
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} RESPONSE card history: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE CARD-HISTORY ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE CARD-HISTORY ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
data: {},
|
||||
: '500 internal server error - backend server.',
|
||||
data: [],
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// HISTORY FROM CMS
|
||||
// ================================================================= HISTORY FROM CMS =================================================================
|
||||
// *Created By: Mohamad Ihsan*
|
||||
// *Description:*
|
||||
// proses yang digunakan untuk menampilkan history kartu berdasrkan log di sistem CMS
|
||||
|
||||
const history = async (req, res) => {
|
||||
try {
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
return res.status(200).json({
|
||||
code: "400",
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
// param
|
||||
let { mid, tid, card_number, start_date, end_date } = req.body;
|
||||
|
||||
// time
|
||||
let now = moment().format("YYYY-MM-DD HH:mm:ss");
|
||||
|
||||
// validation inquiry date
|
||||
if ((!start_date && end_date) || (start_date && !end_date)) {
|
||||
return res.status(200).json({
|
||||
code: "400",
|
||||
message: "bad request. please check the date!",
|
||||
data: {},
|
||||
});
|
||||
if (mid) {
|
||||
mid = mid.toUpperCase();
|
||||
}
|
||||
|
||||
if (tid) {
|
||||
tid = tid.toUpperCase();
|
||||
}
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST CARD-HISTORY-FROM-CMS ]`
|
||||
);
|
||||
|
||||
// check validator
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// time
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING CARD-HISTORY-FROM-CMS ]: checking parameter start date and end date...`
|
||||
// );
|
||||
|
||||
// PostgreSQL menggunakan batas hari inklusif sesuai tanggal yang diminta.
|
||||
const hasDateRange = start_date || end_date;
|
||||
if (hasDateRange && (
|
||||
!moment(start_date, 'YYYY-MM-DD', true).isValid() ||
|
||||
!moment(end_date, 'YYYY-MM-DD', true).isValid() ||
|
||||
start_date > end_date
|
||||
)) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'bad request. please check the date!',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING CARD-HISTORY-FROM-CMS ]: checking mid and tid is valid or not...`
|
||||
// );
|
||||
|
||||
// get partner, merchant, terminal from tid
|
||||
let getPartner = await model.getPartner(mid, tid);
|
||||
if (!getPartner) {
|
||||
return res.status(200).json({
|
||||
code: "412",
|
||||
message: "terminal id is not valid",
|
||||
result = {
|
||||
code: '412',
|
||||
message: 'terminal id is not valid',
|
||||
data: {},
|
||||
});
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// card history and load balance transaction
|
||||
let result = await model.historyByCardNumber(
|
||||
// log debug
|
||||
// winston.logger.debug(
|
||||
// `${uniqueCode} [ PROCESSING CARD-HISTORY-FROM-CMS ]: getting history card from log CMS...`
|
||||
// );
|
||||
|
||||
// get data history kartu di log sistem CMS
|
||||
let history = await model.historyByCardNumber(
|
||||
mid,
|
||||
tid,
|
||||
card_number,
|
||||
@@ -203,26 +293,46 @@ const history = async (req, res) => {
|
||||
end_date
|
||||
);
|
||||
|
||||
if (!result) {
|
||||
return res.status(200).json({
|
||||
code: "422",
|
||||
// jika history tidak ditemukan di log sistem CMS
|
||||
if (!history) {
|
||||
result = {
|
||||
code: '422',
|
||||
message: "history doesn't exist",
|
||||
data: [],
|
||||
});
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
return res.json({
|
||||
code: "00",
|
||||
message: "history has been found.",
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'history has been found.',
|
||||
data: result,
|
||||
});
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CARD-HISTORY-FROM-CMS ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CARD-HISTORY-FROM-CMS ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -78,47 +78,39 @@ const getTerminalKCIExisting = (mid) => {
|
||||
return result;
|
||||
};
|
||||
|
||||
// HISTORY BY CARD NUMBER
|
||||
let historyByCardNumber = (mid, tid, cardNumber, startDate, endDate) => {
|
||||
// let result = knex("trx.t_d_reservation_balance")
|
||||
// .select(
|
||||
// "'reservation' as transaction_type",
|
||||
// "trx.t_d_reservation_balance.c_reservation_no as unique_number",
|
||||
// "trx.t_d_reservation_balance.d_reservation as date",
|
||||
// "trx.t_d_reservation_balance.c_ref_no as ref_no",
|
||||
// "trx.t_d_reservation_balance.c_partner_name as partner_name",
|
||||
// "trx.t_d_reservation_balance.c_merchant_name as merchant_name",
|
||||
// "trx.t_d_reservation_balance.c_terminal_name as terminal_name",
|
||||
// "trx.t_d_reservation_balance.c_card_number as card_number",
|
||||
// "trx.t_d_reservation_balance.i_reservation_amount as amount",
|
||||
// "trx.t_d_reservation_balance.i_issuer_fee as issuer_fee",
|
||||
// "trx.t_d_reservation_balance.i_channel_fee as channel_fee",
|
||||
// "trx.t_d_reservation_balance.c_status as status_code",
|
||||
// "trx.t_d_reservation_balance.c_status_name as description"
|
||||
// )
|
||||
// .where("trx.t_d_reservation_balance.c_mid", mid)
|
||||
// .where("trx.t_d_reservation_balance.c_tid", tid)
|
||||
// .where("trx.t_d_reservation_balance.c_card_number", cardNumber)
|
||||
// .orderBy("trx.t_d_reservation_balance.d_reservation", "desc");
|
||||
|
||||
// if (startDate && endDate) {
|
||||
// result.whereRaw("??::date >= ?", ["trx.t_d_reservation_balance.d_reservation", startDate]);
|
||||
// result.whereRaw("??::date <= ?", ["trx.t_d_reservation_balance.d_reservation", endDate]);
|
||||
// }
|
||||
|
||||
let result = knex
|
||||
.select("*")
|
||||
.from(
|
||||
"(select trx.t_d_reservation_balance.c_reservation_no as unique_number, trx.t_d_reservation_balance.d_reservation as date, trx.t_d_reservation_balance.c_ref_no as ref_no, trx.t_d_reservation_balance.c_partner_name as partner_name, trx.t_d_reservation_balance.c_merchant_name as merchant_name, trx.t_d_reservation_balance.c_terminal_name as terminal_name, trx.t_d_reservation_balance.c_card_number as card_number, trx.t_d_reservation_balance.i_reservation_amount as amount, trx.t_d_reservation_balance.i_issuer_fee as issuer_fee, trx.t_d_reservation_balance.i_channel_fee as channel_fee, trx.t_d_reservation_balance.c_status as status_code, trx.t_d_reservation_balance.c_status_name as description from trx.t_d_reservation_balance where trx.t_d_reservation_balance.c_mid = '?' and trx.t_d_reservation_balance.c_tid = '?' and trx.t_d_reservation_balance.c_card_number = '?' union all select trx.t_d_load_balance.c_load_balance_no as unique_number, trx.t_d_load_balance.d_load_balance as load_date, trx.t_d_load_balance.c_ref_no as ref_no, trx.t_d_load_balance.c_partner_name as partner_name, trx.t_d_load_balance.c_merchant_name as merchant_name, trx.t_d_load_balance.c_terminal_name as terminal_name, trx.t_d_load_balance.c_card_number as card_number, trx.t_d_load_balance.i_topup_amount as amount, trx.t_d_load_balance_detail.i_issuer_fee as issuer_fee, trx.t_d_load_balance_detail.i_channel_fee as channel_fee, trx.t_d_load_balance.c_status as status_code, trx.t_d_load_balance.c_status_name as description from trx.t_d_load_balance left join trx.t_d_load_balance_detail on trx.t_d_load_balance_detail.i_load_balance = trx.t_d_load_balance.i_load_balance where trx.t_d_load_balance.c_mid = '?' and trx.t_d_load_balance.c_tid = '?' and trx.t_d_load_balance.c_card_number = '?')",
|
||||
mid,
|
||||
tid,
|
||||
cardNumber,
|
||||
mid,
|
||||
tid,
|
||||
cardNumber
|
||||
// Terapkan batas tanggal pada kedua sumber sebelum menggabungkan riwayat.
|
||||
const historyByCardNumber = (mid, tid, cardNumber, startDate, endDate) => {
|
||||
const scopedHistory = (table, dateColumn) => {
|
||||
const query = knex(table).where({
|
||||
'history.c_mid': mid, 'history.c_tid': tid, 'history.c_card_number': cardNumber,
|
||||
});
|
||||
if (startDate && endDate) {
|
||||
query.whereRaw('?? >= ?::date', [dateColumn, startDate])
|
||||
.whereRaw('?? < (?::date + 1)', [dateColumn, endDate]);
|
||||
}
|
||||
return query.select(
|
||||
'history.c_ref_no as ref_no', 'history.c_partner_name as partner_name',
|
||||
'history.c_merchant_name as merchant_name', 'history.c_terminal_name as terminal_name',
|
||||
'history.c_card_number as card_number',
|
||||
);
|
||||
};
|
||||
|
||||
return result;
|
||||
const reservations = scopedHistory('trx.t_d_reservation_balance as history', 'history.d_reservation')
|
||||
.select(
|
||||
'history.c_reservation_no as unique_number', 'history.d_reservation as date',
|
||||
'history.i_reservation_amount as amount', 'history.i_issuer_fee as issuer_fee',
|
||||
'history.i_channel_fee as channel_fee', 'history.c_status as status_code',
|
||||
'history.c_status_name as description',
|
||||
);
|
||||
const loads = scopedHistory('trx.t_d_load_balance as history', 'history.d_load_balance')
|
||||
.leftJoin('trx.t_d_load_balance_detail as detail', 'detail.i_load_balance', 'history.i_load_balance')
|
||||
.select(
|
||||
'history.c_load_balance_no as unique_number', 'history.d_load_balance as date',
|
||||
'history.i_topup_amount as amount', 'detail.i_issuer_fee as issuer_fee',
|
||||
'detail.i_channel_fee as channel_fee', 'history.c_status as status_code',
|
||||
'history.c_status_name as description',
|
||||
);
|
||||
return reservations.unionAll([loads]);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
|
||||
@@ -1,24 +1,25 @@
|
||||
const helper = require("../../helpers/helper");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const { default: axios } = require('axios');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
var counterDirect = 0;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -31,11 +32,12 @@ const controller = async (req, res) => {
|
||||
let { body } = req;
|
||||
// uniqueCode = body.unique_code;
|
||||
let uniqueCode = await helper.getUniqueCode();
|
||||
uniqueCode = uniqueCode+''+counterDirect;
|
||||
uniqueCode = uniqueCode + '' + counterDirect;
|
||||
let result = {};
|
||||
let usingHSMNumber = 1;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -43,12 +45,14 @@ const controller = async (req, res) => {
|
||||
// winston.logger.error(`request to HSM server 2`);
|
||||
|
||||
if (client2.clientAuthenticated == false) {
|
||||
usingHSMNumber = 1;
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} ================================== REDIRECT USING HSM SERVER 1 ==================================}`
|
||||
);
|
||||
useClient = client;
|
||||
} else {
|
||||
usingHSMNumber = 2;
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} ================================== USING HSM SERVER 2 ==================================}`
|
||||
@@ -57,12 +61,14 @@ const controller = async (req, res) => {
|
||||
}
|
||||
} else {
|
||||
if (client.clientAuthenticated == false) {
|
||||
usingHSMNumber = 2;
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} ================================== REDIRECT USING HSM SERVER 2 ==================================}`
|
||||
);
|
||||
useClient = client2;
|
||||
} else {
|
||||
usingHSMNumber = 1;
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} ================================== USING HSM SERVER 1 ==================================}`
|
||||
@@ -74,11 +80,15 @@ const controller = async (req, res) => {
|
||||
}
|
||||
|
||||
// log info
|
||||
winston.logger.info(`${uniqueCode} REQUEST load balance - STARTING...`);
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-1 ]: STARTING TOP UP...`
|
||||
);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - auth1v2: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-1 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
let felicaPollingResponse = Buffer.from(
|
||||
@@ -107,7 +117,7 @@ const controller = async (req, res) => {
|
||||
_timeOut = true;
|
||||
}, 10000);
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14, 30);
|
||||
while (
|
||||
message[2] == 1 &&
|
||||
@@ -119,7 +129,9 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message Auth1v2: ${generate.buf2hex(message)}`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-1 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
@@ -131,20 +143,34 @@ const controller = async (req, res) => {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
// if (_timeOut) {
|
||||
// result = {
|
||||
// code: "5001",
|
||||
// message: "Timeout",
|
||||
// data: {},
|
||||
// };
|
||||
if (_timeOut) {
|
||||
let url = `http://${process.env.IP_HSM_SERVER_1}/feliqserver/v1/api/hsm/refresh`;
|
||||
if (usingHSMNumber == 2) {
|
||||
url = `http://${process.env.IP_HSM_SERVER_2}/feliqserver/v1/api/hsm/refresh`;
|
||||
}
|
||||
|
||||
// // log warn
|
||||
// winston.logger.warn(
|
||||
// `${uniqueCode} response HSM - auth1v2: ${JSON.stringify(result)}`
|
||||
// );
|
||||
let response = await axios({
|
||||
url: url,
|
||||
method: 'get',
|
||||
});
|
||||
|
||||
// return res.status(200).send(result);
|
||||
// }
|
||||
result = {
|
||||
code: '5001',
|
||||
message: 'Timeout',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-1 ]: ${JSON.stringify(
|
||||
result
|
||||
)} and refresh HSM ${usingHSMNumber} response status: ${
|
||||
response.status
|
||||
} | response text: ${response.statusText}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
@@ -155,8 +181,8 @@ const controller = async (req, res) => {
|
||||
|
||||
if (respData1) {
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Request Authenticate 1 Success",
|
||||
code: '00',
|
||||
message: 'Request Authenticate 1 Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -167,8 +193,8 @@ const controller = async (req, res) => {
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: "5004",
|
||||
message: "Empty Data from HSM",
|
||||
code: '5004',
|
||||
message: 'Empty Data from HSM',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -181,22 +207,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - auth1v2: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-1 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-1 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -27,11 +27,13 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - auth2v2: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-2 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -57,17 +59,20 @@ const controller = async (req, res) => {
|
||||
let _validationTrxID = Buffer.from(generate.hexToBytes(body.trxID));
|
||||
let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
let _stopMessage = 1;
|
||||
let _timeOut = false;
|
||||
|
||||
if (auth2v2requestData[0] != 0x41) {
|
||||
result = {
|
||||
code: "5003",
|
||||
message: "Wrong Respone from Card",
|
||||
code: '5003',
|
||||
message: 'Wrong Respone from Card',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} response HSM - auth2v2: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
@@ -84,7 +89,13 @@ const controller = async (req, res) => {
|
||||
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
useClient.ws.on("message", (message) => {
|
||||
|
||||
setInterval(function () {
|
||||
respData = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]);
|
||||
_timeOut = true;
|
||||
}, 10000);
|
||||
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 2 &&
|
||||
message[0] == _validationTrxID[0] &&
|
||||
@@ -96,7 +107,9 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message Auth2v2: ${generate.buf2hex(message)}`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-2 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
@@ -108,6 +121,23 @@ const controller = async (req, res) => {
|
||||
await _sleep(10);
|
||||
}
|
||||
|
||||
if (_timeOut) {
|
||||
result = {
|
||||
code: '5001',
|
||||
message: 'Timeout',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-2 ]: message from HSM ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
_stopMessage = 0;
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
@@ -116,8 +146,8 @@ const controller = async (req, res) => {
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Request Authenticate 2 Success",
|
||||
code: '00',
|
||||
message: 'Request Authenticate 2 Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -128,22 +158,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - auth2v2: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-2 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-2 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -27,11 +27,13 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request auth2v2 Resp: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-3 ]: request to HSM ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -62,14 +64,16 @@ const controller = async (req, res) => {
|
||||
|
||||
if (auth2v2responseSetData[0] != 0x43) {
|
||||
result = {
|
||||
code: "5003",
|
||||
message: "Wrong Respone from Card",
|
||||
code: '5003',
|
||||
message: 'Wrong Respone from Card',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} response HSM - auth2v2 resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-3 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
@@ -87,7 +91,7 @@ const controller = async (req, res) => {
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 3 &&
|
||||
message[0] == transactionId[0] &&
|
||||
@@ -99,7 +103,7 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message auth2v2 Resp: ${generate.buf2hex(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-3 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
@@ -121,8 +125,8 @@ const controller = async (req, res) => {
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Request Authenticate Resp Success",
|
||||
code: '00',
|
||||
message: 'Request Authenticate Resp Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -133,22 +137,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - auth2v2 resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-3 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-3 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
const helper = require('../../../helpers/helper');
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage } = require('../services/requestHsm');
|
||||
const refreshHsm = require('../services/refreshHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
let counterDirect = 0;
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
if (counterDirect > 1 || counterDirect < 0) {
|
||||
counterDirect = 0;
|
||||
}
|
||||
counterDirect++;
|
||||
|
||||
let { body } = req;
|
||||
const uniqueCode = `${helper.getUniqueCode()}${counterDirect}`;
|
||||
let result = {};
|
||||
|
||||
const { client: useClient, serverNumber, redirected } = selectHsmClient(uniqueCode);
|
||||
if (redirected !== undefined) {
|
||||
const action = redirected ? 'redirected' : 'selected';
|
||||
const message = `${uniqueCode} HSM server=${serverNumber} action=${action}`;
|
||||
if (redirected) winston.logger.warn(message);
|
||||
else winston.logger.debug(message);
|
||||
}
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-1 ]: STARTING CLEAR...`
|
||||
);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING CLEAR CARD KATEGORI PEGAWAI-1 ]`
|
||||
);
|
||||
|
||||
let felicaPollingResponse = Buffer.from(
|
||||
generate.hexToBytes(body.requestData)
|
||||
);
|
||||
|
||||
const cardId = body.requestData.slice(4, 20);
|
||||
|
||||
let transactionId = Buffer.from([0x00, 0x00]);
|
||||
let apiId = Buffer.from([0x01]);
|
||||
const reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
felicaPollingResponse
|
||||
);
|
||||
|
||||
let respData;
|
||||
try {
|
||||
respData = await requestHsm(useClient?.ws, reqData, { cardId });
|
||||
} catch (error) {
|
||||
if (error?.code !== 'HSM_TIMEOUT') throw error;
|
||||
|
||||
try {
|
||||
await refreshHsm(serverNumber);
|
||||
} catch {
|
||||
winston.logger.warn(`HSM server ${serverNumber} refresh failed`);
|
||||
}
|
||||
|
||||
return res.status(200).send({ code: '5001', message: 'Timeout', data: {} });
|
||||
}
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
if (respData1) {
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Request Authenticate 1 Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
unique_code: uniqueCode,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: '5004',
|
||||
message: 'Empty Data from HSM',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
unique_code: uniqueCode,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-1 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CLEAR CARD KATEGORI PEGAWAI-1 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,82 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-2 ]`
|
||||
);
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
let transactionId = parseHsmTransactionId(body.trxID);
|
||||
let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
|
||||
if (auth2v2requestData[0] != 0x41) {
|
||||
result = {
|
||||
code: '5003',
|
||||
message: 'Wrong Respone from Card',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-2 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x02]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
auth2v2requestData
|
||||
);
|
||||
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Request Authenticate 2 Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-2 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CLEAR CARD KATEGORI PEGAWAI-2 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,85 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-3 ]: request to HSM `
|
||||
);
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
let transactionId = parseHsmTransactionId(body.trxID);
|
||||
let auth2v2responseSetData = Buffer.from(
|
||||
generate.hexToBytes(body.requestData)
|
||||
);
|
||||
// console.log("Req Auth Resp: " + body.requestData);
|
||||
|
||||
if (auth2v2responseSetData[0] != 0x43) {
|
||||
result = {
|
||||
code: '5003',
|
||||
message: 'Wrong Respone from Card',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-3 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x03]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
auth2v2responseSetData
|
||||
);
|
||||
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Request Authenticate Resp Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-3 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CLEAR CARD KATEGORI PEGAWAI-3 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,67 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-4 ]`
|
||||
);
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
let transactionId = parseHsmTransactionId(body.trxID);
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
|
||||
let apiId = Buffer.from([0x04]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
trxrequestData
|
||||
);
|
||||
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-4 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CLEAR CARD KATEGORI PEGAWAI-4 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,76 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-5 ]`
|
||||
);
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
let transactionId = parseHsmTransactionId(body.trxID);
|
||||
let packet = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
if (packet[0] != 0x45) {
|
||||
result = {
|
||||
code: '03',
|
||||
message: 'Respone Card Wrong',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-5 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x05]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, packet);
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-5 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CLEAR CARD KATEGORI PEGAWAI-5 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,103 @@
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'clear':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let { mid, tid, unique_code, trxID, requestData } = req.body;
|
||||
|
||||
let uniqueCode = unique_code;
|
||||
let result = {};
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-6 ]`
|
||||
);
|
||||
|
||||
// check validator
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-6 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let transactionId = parseHsmTransactionId(trxID);
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(requestData));
|
||||
|
||||
let apiId = Buffer.from([0x04]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
trxrequestData
|
||||
);
|
||||
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Cleared Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-6 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CLEAR CARD KATEGORI PEGAWAI-6 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
controller,
|
||||
};
|
||||
@@ -0,0 +1,129 @@
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'clearResponse':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let { mid, tid, unique_code, trxID, requestData } = req.body;
|
||||
|
||||
let uniqueCode = unique_code;
|
||||
let result = {};
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
// case success write to the card but loss contact with device
|
||||
// result = {
|
||||
// code: "100",
|
||||
// message: "failed clear",
|
||||
// data: {},
|
||||
// };
|
||||
// return res.status(200).send(result);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-7 ]`
|
||||
);
|
||||
|
||||
let transactionId = parseHsmTransactionId(trxID);
|
||||
let packet = Buffer.from(generate.hexToBytes(requestData));
|
||||
if (packet[0] != 0x47) {
|
||||
result = {
|
||||
code: '03',
|
||||
message: 'Respone Card Wrong',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-7 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x05]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, packet);
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
let data = {};
|
||||
|
||||
if (
|
||||
respData[6] != 0x47 ||
|
||||
(respData1[9] != 0x00 && respData1[10] != 0x00)
|
||||
) {
|
||||
data = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
unique_code: unique_code,
|
||||
};
|
||||
|
||||
result = {
|
||||
code: '5002',
|
||||
message: 'failed from HSM',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respData1.slice(6, 10),
|
||||
transcode: null,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
data = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
unique_code: unique_code,
|
||||
};
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Cleared Response Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-7 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CLEAR CARD KATEGORI PEGAWAI-7 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { validate, controller };
|
||||
@@ -0,0 +1,65 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST CLEAR CARD KATEGORI PEGAWAI-8 ]`
|
||||
);
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
let transactionId = parseHsmTransactionId(body.trxID);
|
||||
|
||||
let transactionEnd = Buffer.from([]);
|
||||
let apiId = Buffer.from([0x06]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
transactionEnd
|
||||
);
|
||||
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'End Transaction Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE CLEAR CARD KATEGORI PEGAWAI-8 ]: ENDING TOP UP... ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE CLEAR CARD KATEGORI PEGAWAI-8 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,51 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
require('dotenv').config();
|
||||
|
||||
// Get Service Code, Block, dan System Code
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
// check service block
|
||||
if (
|
||||
process.env.SERVICEBLOCK_SERVICE_MUTUAL == '' ||
|
||||
process.env.SERVICEBLOCK_BLOCK_READ == '' ||
|
||||
process.env.SERVICEBLOCK_BLOCK_WRITE == ''
|
||||
) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`PLEASE CONFIGURE SERVICE BLOCK ON THE ENVIRONMENT!`
|
||||
);
|
||||
}
|
||||
|
||||
let sytemCode = '939E';
|
||||
let serviceReadNS = '4B1017208B20';
|
||||
let blockReadNS = '800081008200';
|
||||
let serviceMutual = process.env.SERVICEBLOCK_SERVICE_MUTUAL;
|
||||
let blockReadS = process.env.SERVICEBLOCK_BLOCK_READ;
|
||||
let blockWrite = process.env.SERVICEBLOCK_BLOCK_WRITE;
|
||||
let locFlag = 15;
|
||||
return res.status(200).send({
|
||||
code: '00',
|
||||
message: 'Get Service Succeess',
|
||||
data: {
|
||||
sysCode: sytemCode,
|
||||
sReadNS: serviceReadNS,
|
||||
sMutual: serviceMutual,
|
||||
bReadNS: blockReadNS,
|
||||
bReadS: blockReadS,
|
||||
bWrite: blockWrite,
|
||||
lFlag: locFlag,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,22 +1,22 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -27,11 +27,13 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - end transaction: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-8 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -70,7 +72,7 @@ const controller = async (req, res) => {
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 6 &&
|
||||
message[0] == transactionId[0] &&
|
||||
@@ -82,7 +84,7 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message end transaction: ${generate.buf2hex(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-8 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
@@ -104,35 +106,34 @@ const controller = async (req, res) => {
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "End Transaction Success",
|
||||
code: '00',
|
||||
message: 'End Transaction Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(`${uniqueCode} RESPONSE load balance - END...`);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - end transaction: ${JSON.stringify(result)}`
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-8 ]: ENDING TOP UP... ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-8 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -27,11 +27,13 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - read data: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-4 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -70,7 +72,7 @@ const controller = async (req, res) => {
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 4 &&
|
||||
message[0] == transactionId[0] &&
|
||||
@@ -84,7 +86,9 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message read data: ${generate.buf2hex(message)}`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-4 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
@@ -104,8 +108,8 @@ const controller = async (req, res) => {
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Read Succeess",
|
||||
code: '00',
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -116,22 +120,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - read data: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-4 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-4 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
const controller = async (req, res) => {
|
||||
@@ -27,11 +27,13 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - read data resp: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-5 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -58,14 +60,16 @@ const controller = async (req, res) => {
|
||||
let _stopMessage = 1;
|
||||
if (packet[0] != 0x45) {
|
||||
result = {
|
||||
code: "03",
|
||||
message: "Respone Card Wrong",
|
||||
code: '03',
|
||||
message: 'Respone Card Wrong',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} response HSM - read data resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-5 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
@@ -79,7 +83,7 @@ const controller = async (req, res) => {
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 5 &&
|
||||
message[0] == transactionId[0] &&
|
||||
@@ -93,7 +97,7 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message read data resp: ${generate.buf2hex(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-5 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
@@ -115,8 +119,8 @@ const controller = async (req, res) => {
|
||||
respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Read Succeess",
|
||||
code: '00',
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -127,22 +131,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - read data resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-5 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-5 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
const WebSocket = require('ws');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, HSM_TIMEOUT_MS } = require('./requestHsm');
|
||||
require('dotenv').config();
|
||||
|
||||
const certDirectory = path.join(__dirname, '../../../assets/cert');
|
||||
const ssl_ca_crt = path.join(certDirectory, 'CACerts.pem');
|
||||
const ssl_client_pfx = path.join(certDirectory, 'FeliqClient0002-03.pfx');
|
||||
const options = {
|
||||
ca: fs.readFileSync(ssl_ca_crt),
|
||||
agent: false,
|
||||
passphrase: 'GPqs+Uia78',
|
||||
pfx: fs.readFileSync(ssl_client_pfx),
|
||||
};
|
||||
|
||||
const RECONNECT_DELAY_MS = 5900;
|
||||
|
||||
// Kelola satu koneksi, satu upaya autentikasi, dan satu jadwal pengganti per HSM.
|
||||
function createHsmClient(serverNumber, authRetryDelayMs) {
|
||||
const backup = process.env.CHANGE_TO_DRC?.toUpperCase() === 'YES' ? '_BACKUP' : '';
|
||||
const suffix = `${backup}_${serverNumber}`;
|
||||
const url = process.env[`URL_HSM_SERVER${suffix}`];
|
||||
const apiKey = process.env[`APIKEY_HSM_SERVER${suffix}`];
|
||||
const secret = process.env[`SECRETKEY_HSM_SERVER${suffix}`];
|
||||
const systemCode = process.env.SYSTEM_CODE;
|
||||
const client = {
|
||||
ws: null,
|
||||
clientAuthenticated: false,
|
||||
sendData(data) {
|
||||
this.ws.send(data);
|
||||
},
|
||||
};
|
||||
|
||||
if (!url || !apiKey || !secret || !systemCode) {
|
||||
winston.logger.error(`HSM server ${serverNumber} configuration is incomplete`);
|
||||
return client;
|
||||
}
|
||||
|
||||
const authData = Buffer.concat([
|
||||
Buffer.from(generate.hexToBytes(systemCode)),
|
||||
Buffer.from(apiKey),
|
||||
Buffer.from(secret),
|
||||
]);
|
||||
const authPacket = generate.makeRequestData(Buffer.alloc(2), Buffer.alloc(1), authData);
|
||||
|
||||
function scheduleReconnect() {
|
||||
setTimeout(connect, RECONNECT_DELAY_MS).unref();
|
||||
}
|
||||
|
||||
function connect() {
|
||||
let socket;
|
||||
try {
|
||||
socket = new WebSocket(url, [], { ...options, handshakeTimeout: HSM_TIMEOUT_MS });
|
||||
} catch {
|
||||
winston.logger.warn(`HSM server ${serverNumber} could not open a WebSocket`);
|
||||
scheduleReconnect();
|
||||
return;
|
||||
}
|
||||
|
||||
client.ws = socket;
|
||||
let authRetry;
|
||||
|
||||
async function authenticate() {
|
||||
try {
|
||||
const response = await requestHsm(socket, authPacket);
|
||||
if (client.ws !== socket || socket.readyState !== WebSocket.OPEN) return;
|
||||
|
||||
const code = generate.getResponseCode(response);
|
||||
if (code === '0000' || code === '0502') {
|
||||
client.clientAuthenticated = true;
|
||||
return;
|
||||
}
|
||||
winston.logger.warn(`HSM server ${serverNumber} rejected authentication`);
|
||||
} catch (error) {
|
||||
if (client.ws !== socket || socket.readyState !== WebSocket.OPEN) return;
|
||||
winston.logger.warn(`HSM server ${serverNumber} authentication failed`);
|
||||
if (error.code === 'HSM_TIMEOUT') {
|
||||
socket.terminate();
|
||||
return;
|
||||
}
|
||||
}
|
||||
authRetry = setTimeout(authenticate, authRetryDelayMs);
|
||||
authRetry.unref();
|
||||
}
|
||||
|
||||
socket.once('open', authenticate);
|
||||
socket.on('error', () => {
|
||||
client.clientAuthenticated = false;
|
||||
winston.logger.warn(`HSM server ${serverNumber} WebSocket error`);
|
||||
});
|
||||
socket.once('close', () => {
|
||||
clearTimeout(authRetry);
|
||||
socket.off('open', authenticate);
|
||||
client.clientAuthenticated = false;
|
||||
client.ws = null;
|
||||
scheduleReconnect();
|
||||
});
|
||||
}
|
||||
|
||||
connect();
|
||||
return client;
|
||||
}
|
||||
|
||||
module.exports = createHsmClient;
|
||||
@@ -0,0 +1,23 @@
|
||||
const axios = require('axios');
|
||||
|
||||
const refreshes = new Map();
|
||||
const REFRESH_TIMEOUT_MS = 5000;
|
||||
|
||||
// Satu refresh per server cukup ketika beberapa otentikasi timeout bersamaan.
|
||||
async function refreshHsm(serverNumber) {
|
||||
const backup = process.env.CHANGE_TO_DRC?.toUpperCase() === 'YES' ? '_BACKUP' : '';
|
||||
const host = process.env[`IP_HSM_SERVER${backup}_${serverNumber}`];
|
||||
if (!host) throw new Error('HSM refresh address is missing');
|
||||
|
||||
const ongoing = refreshes.get(host);
|
||||
if (ongoing) return ongoing;
|
||||
|
||||
const refresh = axios.get(`http://${host}/feliqserver/v1/api/hsm/refresh`, {
|
||||
timeout: REFRESH_TIMEOUT_MS,
|
||||
signal: AbortSignal.timeout(REFRESH_TIMEOUT_MS),
|
||||
}).finally(() => refreshes.delete(host));
|
||||
refreshes.set(host, refresh);
|
||||
return refresh;
|
||||
}
|
||||
|
||||
module.exports = refreshHsm;
|
||||
@@ -0,0 +1,125 @@
|
||||
const { OPEN } = require('ws');
|
||||
|
||||
const HSM_TIMEOUT_MS = 10000;
|
||||
const MAX_UNCERTAIN_RESPONSES = 256;
|
||||
const socketStates = new WeakMap();
|
||||
|
||||
function responseKey(message) {
|
||||
if (!Buffer.isBuffer(message) || message.length < 5) return;
|
||||
|
||||
const api = message[2];
|
||||
if (api === 1) {
|
||||
if (message.length >= 15) return `card:${message.toString('hex', 7, 15)}`;
|
||||
} else if (api === 0 || message.length >= 6) {
|
||||
return message.readUIntBE(0, 3);
|
||||
}
|
||||
}
|
||||
|
||||
function getSocketState(socket) {
|
||||
const existing = socketStates.get(socket);
|
||||
if (existing) return existing;
|
||||
|
||||
const pending = new Map();
|
||||
const uncertain = new Set();
|
||||
const state = { pending, uncertain, recycle: false, cleanup };
|
||||
|
||||
function onMessage(message) {
|
||||
const key = responseKey(message);
|
||||
if (uncertain.delete(key)) {
|
||||
cleanup();
|
||||
return;
|
||||
}
|
||||
pending.get(key)?.(null, message);
|
||||
}
|
||||
|
||||
function failAll(error) {
|
||||
uncertain.clear();
|
||||
state.recycle = false;
|
||||
for (const complete of pending.values()) complete(error);
|
||||
cleanup();
|
||||
}
|
||||
|
||||
function onClose() {
|
||||
failAll(new Error('HSM WebSocket closed'));
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
if (pending.size > 0) return;
|
||||
if (!state.recycle && uncertain.size > 0) return;
|
||||
|
||||
socket.off('message', onMessage);
|
||||
socket.off('close', onClose);
|
||||
socket.off('error', failAll);
|
||||
socketStates.delete(socket);
|
||||
if (state.recycle && socket.readyState === OPEN) socket.terminate();
|
||||
}
|
||||
|
||||
socket.on('message', onMessage);
|
||||
socket.on('close', onClose);
|
||||
socket.on('error', failAll);
|
||||
socketStates.set(socket, state);
|
||||
return state;
|
||||
}
|
||||
|
||||
// Daftarkan respons sebelum mengirim paket agar balasan cepat tetap tertangkap.
|
||||
async function requestHsm(socket, packet, { cardId, timeoutMs = HSM_TIMEOUT_MS } = {}) {
|
||||
if (cardId !== undefined && !/^[\da-f]{16}$/i.test(cardId)) {
|
||||
throw new Error('Invalid HSM card ID');
|
||||
}
|
||||
if (socket?.readyState !== OPEN) throw new Error('HSM WebSocket is not open');
|
||||
|
||||
const key = cardId === undefined ? packet.readUIntBE(0, 3) : `card:${cardId.toLowerCase()}`;
|
||||
const state = getSocketState(socket);
|
||||
if (state.uncertain.has(key)) {
|
||||
// Protokol tidak membedakan balasan lama dari retry dengan ID yang sama.
|
||||
// Ganti koneksi setelah request lain selesai, tanpa mengirim ulang paket.
|
||||
state.recycle = true;
|
||||
state.cleanup();
|
||||
throw new Error('HSM response still uncertain; reconnect required');
|
||||
}
|
||||
if (state.recycle) throw new Error('HSM WebSocket is waiting to reconnect');
|
||||
if (state.pending.has(key)) throw new Error('A matching HSM request is already pending');
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
const error = new Error('HSM response timed out');
|
||||
error.code = 'HSM_TIMEOUT';
|
||||
if (state.uncertain.size < MAX_UNCERTAIN_RESPONSES) state.uncertain.add(key);
|
||||
else state.recycle = true;
|
||||
complete(error);
|
||||
}, timeoutMs);
|
||||
|
||||
function complete(error, response) {
|
||||
if (state.pending.get(key) !== complete) return;
|
||||
clearTimeout(timer);
|
||||
state.pending.delete(key);
|
||||
state.cleanup();
|
||||
if (error) reject(error);
|
||||
else resolve(response);
|
||||
}
|
||||
|
||||
state.pending.set(key, complete);
|
||||
try {
|
||||
socket.send(packet, (error) => {
|
||||
if (error) complete(error);
|
||||
});
|
||||
} catch (error) {
|
||||
complete(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function hsmErrorMessage(error) {
|
||||
if (error?.code === 'HSM_TIMEOUT') return 'Timeout';
|
||||
return '500 internal server error - backend server.';
|
||||
}
|
||||
|
||||
// ID transaksi FeliQ menempati tepat dua byte sebelum kode operasi.
|
||||
function parseHsmTransactionId(value) {
|
||||
if (typeof value !== 'string' || !/^[\da-f]{4}$/i.test(value)) {
|
||||
throw new Error('Invalid HSM transaction ID');
|
||||
}
|
||||
return Buffer.from(value, 'hex');
|
||||
}
|
||||
|
||||
module.exports = { requestHsm, hsmErrorMessage, parseHsmTransactionId, HSM_TIMEOUT_MS };
|
||||
@@ -0,0 +1,26 @@
|
||||
require('dotenv').config();
|
||||
|
||||
const activeServer = process.env.NUMBER_SERVER_ACTIVE;
|
||||
const server1 = activeServer === '1' || activeServer === '12' ? require('./webSocket').client : undefined;
|
||||
const server2 = activeServer === '2' || activeServer === '12' ? require('./webSocket2').client2 : undefined;
|
||||
|
||||
// Kode genap memilih server 2. Jika server pilihan belum terautentikasi, gunakan server lainnya.
|
||||
function selectHsmClient(uniqueCode) {
|
||||
if (activeServer === '1') return { client: server1, serverNumber: 1 };
|
||||
if (activeServer === '2') return { client: server2, serverNumber: 2 };
|
||||
if (activeServer !== '12' || !uniqueCode) return {};
|
||||
|
||||
const preferredNumber = parseInt(uniqueCode) % 2 === 0 ? 2 : 1;
|
||||
const preferred = preferredNumber === 1 ? server1 : server2;
|
||||
if (preferred.clientAuthenticated === false) {
|
||||
return {
|
||||
client: preferredNumber === 1 ? server2 : server1,
|
||||
serverNumber: preferredNumber === 1 ? 2 : 1,
|
||||
redirected: true,
|
||||
};
|
||||
}
|
||||
|
||||
return { client: preferred, serverNumber: preferredNumber, redirected: false };
|
||||
}
|
||||
|
||||
module.exports = selectHsmClient;
|
||||
@@ -1,264 +1,5 @@
|
||||
const WebSocket = require("ws");
|
||||
const checkInternetConnected = require("check-internet-connected");
|
||||
const winston = require("../../../helpers/winston.logger");
|
||||
const fs = require("fs");
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const generate = require("../utils/utils");
|
||||
require("dotenv").config();
|
||||
const createHsmClient = require('./createHsmClient');
|
||||
|
||||
let ssl_ca_crt = "./application/assets/cert/CACerts.pem";
|
||||
let ssl_client_pfx = "./application/assets/cert/FeliqClient0002-03.pfx";
|
||||
const client = createHsmClient(1, 39000);
|
||||
|
||||
let options = {
|
||||
ca: fs.readFileSync(ssl_ca_crt),
|
||||
agent: false,
|
||||
passphrase: "GPqs+Uia78",
|
||||
pfx: fs.readFileSync(ssl_client_pfx),
|
||||
};
|
||||
|
||||
// check config HSM
|
||||
if (
|
||||
process.env.URL_HSM_SERVER_1 == "" ||
|
||||
process.env.APIKEY_HSM_SERVER_1 == "" ||
|
||||
process.env.SECRETKEY_HSM_SERVER_1 == ""
|
||||
) {
|
||||
// create log
|
||||
winston.logger.error(`PLEASE CONFIGURE HSM SERVER ON THE ENVIRONMENT!`);
|
||||
}
|
||||
|
||||
// check system code
|
||||
if (process.env.SYSTEM_CODE == "") {
|
||||
// create log
|
||||
winston.logger.error(`PLEASE CONFIGURE SYSTEM CODE ON THE ENVIRONMENT!`);
|
||||
}
|
||||
|
||||
// init server hsm
|
||||
var url;
|
||||
var apiKeyBytes;
|
||||
var secretBytes;
|
||||
var systemCode = Buffer.from(generate.hexToBytes(process.env.SYSTEM_CODE));
|
||||
|
||||
if (process.env.CHANGE_TO_DRC == "YES" || process.env.CHANGE_TO_DRC == "yes") {
|
||||
// config for DRC
|
||||
url = process.env.URL_HSM_SERVER_BACKUP_1;
|
||||
apiKeyBytes = Buffer.from(process.env.APIKEY_HSM_SERVER_BACKUP_1);
|
||||
secretBytes = Buffer.from(process.env.SECRETKEY_HSM_SERVER_BACKUP_1);
|
||||
} else {
|
||||
// config for DC
|
||||
url = process.env.URL_HSM_SERVER_1;
|
||||
apiKeyBytes = Buffer.from(process.env.APIKEY_HSM_SERVER_1);
|
||||
secretBytes = Buffer.from(process.env.SECRETKEY_HSM_SERVER_1);
|
||||
}
|
||||
|
||||
const config = {
|
||||
timeout: 1000, //timeout connecting to each server, each try
|
||||
retries: 5, //number of retries to do before failing
|
||||
domain: "https://google.com", //the domain to check DNS record of
|
||||
};
|
||||
|
||||
var interval;
|
||||
|
||||
function startInterval() {
|
||||
interval = setInterval(function () {
|
||||
checkInternetConnected(config)
|
||||
.then((result) => {
|
||||
// console.log(result); //successfully connected to a server
|
||||
// log debug
|
||||
winston.logger.debug(`retry open websocket server 1`);
|
||||
client.open();
|
||||
stopInterval();
|
||||
})
|
||||
.catch((ex) => {
|
||||
// console.log(ex); // cannot connect to a server or error occurred.
|
||||
// log error
|
||||
winston.logger.error(`error start interval server 1 : ${ex}`);
|
||||
});
|
||||
}, 5900);
|
||||
}
|
||||
|
||||
function stopInterval() {
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
class WebSocketClient {
|
||||
ws = null;
|
||||
clientAuthenticated = false;
|
||||
openWebSocketStatus = false;
|
||||
|
||||
// Connection of WebSocket
|
||||
open = () => {
|
||||
try {
|
||||
if (this.ws == null) {
|
||||
this.ws = new WebSocket(url, [], options);
|
||||
|
||||
this.ws.on("open", this.onOpen);
|
||||
this.ws.on("close", this.onClose);
|
||||
this.ws.on("error", this.onError);
|
||||
|
||||
this.ws.setMaxListeners(0);
|
||||
}
|
||||
|
||||
this.openWebSocketStatus = true;
|
||||
} catch (error) {
|
||||
this.openWebSocketStatus = false;
|
||||
}
|
||||
};
|
||||
// Disconnection of WebSocket
|
||||
close = () => {
|
||||
this.ws.close();
|
||||
// console.log('WebSocket Close');
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 1 close`);
|
||||
};
|
||||
|
||||
// Open event
|
||||
onOpen = () => {
|
||||
// console.log("WebSocket Open");
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`opening websocket server 1`);
|
||||
|
||||
if (this.isOpened()) {
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 1 open successfully`);
|
||||
|
||||
if (!this.clientAuthenticated) {
|
||||
this.clientAuth();
|
||||
}
|
||||
} else {
|
||||
// log error
|
||||
winston.logger.error(`websocket server 1 open failed`);
|
||||
}
|
||||
};
|
||||
|
||||
onClose = () => {
|
||||
// console.log("WebSocket Close");
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 1 close`);
|
||||
|
||||
this.clientAuthenticated = false;
|
||||
this.ws = null;
|
||||
startInterval();
|
||||
};
|
||||
|
||||
onError = () => {
|
||||
// console.log("WebSocket Error");
|
||||
|
||||
// log error
|
||||
winston.logger.error(`websocket server 1 error`);
|
||||
|
||||
this.clientAuthenticated = false;
|
||||
};
|
||||
|
||||
// Connection check
|
||||
isOpened = () => {
|
||||
return this.ws.readyState == WebSocket.OPEN;
|
||||
};
|
||||
|
||||
// Received data check
|
||||
isReceive() {
|
||||
return this.receiveData != null;
|
||||
}
|
||||
|
||||
// Acquiring received data
|
||||
getReceiveData() {
|
||||
return this.receiveData;
|
||||
}
|
||||
|
||||
clearReceiveData() {
|
||||
this.receiveData = null;
|
||||
}
|
||||
|
||||
// Send data
|
||||
sendData(data) {
|
||||
this.receiveData = null;
|
||||
this.ws.send(data);
|
||||
}
|
||||
|
||||
async clientAuth() {
|
||||
try {
|
||||
var authHead = Buffer.alloc(2);
|
||||
// Set system code (when 0x0000)
|
||||
// authHead[0] = 0x93;
|
||||
// authHead[1] = 0x9e;
|
||||
authHead = systemCode;
|
||||
|
||||
const authData = Buffer.concat([authHead, apiKeyBytes, secretBytes]);
|
||||
|
||||
let transactionId = Buffer.from([0x00, 0x00]);
|
||||
let apiId = Buffer.from([0x00]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, authData);
|
||||
|
||||
let respData = null;
|
||||
let _stopMessage = 1;
|
||||
|
||||
this.sendData(reqData);
|
||||
|
||||
this.ws.on("message", (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14, 30);
|
||||
while (
|
||||
message[2] == 0 &&
|
||||
_stopMessage == 1 &&
|
||||
message[0] == 0 &&
|
||||
message[1] == 0
|
||||
) {
|
||||
respData = null;
|
||||
// console.log("*WS MESSAGE Tenan: " + generate.buf2hex(message));
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`websocket server 1 message tenant: ${generate.buf2hex(message)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
});
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
let respCode = generate.getResponseCode(respData);
|
||||
// console.log(`Resp Data Tenant = ${respCode}`);
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 1 resp data tenant: ${respCode}`);
|
||||
|
||||
if (respCode == "0000" || respCode == "0502") {
|
||||
this.clientAuthenticated = true;
|
||||
}
|
||||
// console.log(`clientAuthenticated = ${this.clientAuthenticated}`);
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`websocket server 1 client authenticate: ${this.clientAuthenticated}`
|
||||
);
|
||||
} catch (error) {
|
||||
// console.log(`error ${error}`);
|
||||
// log error
|
||||
winston.logger.error(`websocket error: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var client = new WebSocketClient();
|
||||
if (!client.openWebSocketStatus) {
|
||||
// log info
|
||||
winston.logger.info(`first open websocket server 1`);
|
||||
client.open();
|
||||
}
|
||||
|
||||
setInterval(function () {
|
||||
// let statusConnection = client.clientAuthenticated;
|
||||
// if (!statusConnection) {
|
||||
if (!this.ws) {
|
||||
// log debug
|
||||
// winston.logger.debug(`retry call client Auth`);
|
||||
client.clientAuth();
|
||||
}
|
||||
// }
|
||||
}, 39000);
|
||||
|
||||
module.exports = {
|
||||
client,
|
||||
};
|
||||
module.exports = { client };
|
||||
|
||||
@@ -1,264 +1,5 @@
|
||||
const WebSocket = require("ws");
|
||||
const checkInternetConnected = require("check-internet-connected");
|
||||
const winston = require("../../../helpers/winston.logger");
|
||||
const fs = require("fs");
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
const generate = require("../utils/utils");
|
||||
require("dotenv").config();
|
||||
const createHsmClient = require('./createHsmClient');
|
||||
|
||||
let ssl_ca_crt = "./application/assets/cert/CACerts.pem";
|
||||
let ssl_client_pfx = "./application/assets/cert/FeliqClient0002-03.pfx";
|
||||
const client2 = createHsmClient(2, 50000);
|
||||
|
||||
let options = {
|
||||
ca: fs.readFileSync(ssl_ca_crt),
|
||||
agent: false,
|
||||
passphrase: "GPqs+Uia78",
|
||||
pfx: fs.readFileSync(ssl_client_pfx),
|
||||
};
|
||||
|
||||
// check config HSM
|
||||
if (
|
||||
process.env.URL_HSM_SERVER_2 == "" ||
|
||||
process.env.APIKEY_HSM_SERVER_2 == "" ||
|
||||
process.env.SECRETKEY_HSM_SERVER_2 == ""
|
||||
) {
|
||||
// create log
|
||||
winston.logger.error(`PLEASE CONFIGURE HSM SERVER ON THE ENVIRONMENT!`);
|
||||
}
|
||||
|
||||
// check system code
|
||||
if (process.env.SYSTEM_CODE == "") {
|
||||
// create log
|
||||
winston.logger.error(`PLEASE CONFIGURE SYSTEM CODE ON THE ENVIRONMENT!`);
|
||||
}
|
||||
|
||||
// init server hsm
|
||||
var url;
|
||||
var apiKeyBytes;
|
||||
var secretBytes;
|
||||
var systemCode = Buffer.from(generate.hexToBytes(process.env.SYSTEM_CODE));
|
||||
|
||||
if (process.env.CHANGE_TO_DRC == "YES" || process.env.CHANGE_TO_DRC == "yes") {
|
||||
// config for DRC
|
||||
url = process.env.URL_HSM_SERVER_BACKUP_2;
|
||||
apiKeyBytes = Buffer.from(process.env.APIKEY_HSM_SERVER_BACKUP_2);
|
||||
secretBytes = Buffer.from(process.env.SECRETKEY_HSM_SERVER_BACKUP_2);
|
||||
} else {
|
||||
// config for DC
|
||||
url = process.env.URL_HSM_SERVER_2;
|
||||
apiKeyBytes = Buffer.from(process.env.APIKEY_HSM_SERVER_2);
|
||||
secretBytes = Buffer.from(process.env.SECRETKEY_HSM_SERVER_2);
|
||||
}
|
||||
|
||||
const config = {
|
||||
timeout: 1000, //timeout connecting to each server, each try
|
||||
retries: 5, //number of retries to do before failing
|
||||
domain: "https://google.com", //the domain to check DNS record of
|
||||
};
|
||||
|
||||
var interval;
|
||||
|
||||
function startInterval() {
|
||||
interval = setInterval(function () {
|
||||
checkInternetConnected(config)
|
||||
.then((result) => {
|
||||
// console.log(result); //successfully connected to a server
|
||||
// log debug
|
||||
winston.logger.debug(`retry open websocket server 2`);
|
||||
client2.open();
|
||||
stopInterval();
|
||||
})
|
||||
.catch((ex) => {
|
||||
// console.log(ex); // cannot connect to a server or error occurred.
|
||||
// log error
|
||||
winston.logger.error(`error start interval server 2 : ${ex}`);
|
||||
});
|
||||
}, 5900);
|
||||
}
|
||||
|
||||
function stopInterval() {
|
||||
clearInterval(interval);
|
||||
}
|
||||
|
||||
class WebSocketClient {
|
||||
ws = null;
|
||||
clientAuthenticated = false;
|
||||
openWebSocketStatus = false;
|
||||
|
||||
// Connection of WebSocket
|
||||
open = () => {
|
||||
try {
|
||||
if (this.ws == null) {
|
||||
this.ws = new WebSocket(url, [], options);
|
||||
|
||||
this.ws.on("open", this.onOpen);
|
||||
this.ws.on("close", this.onClose);
|
||||
this.ws.on("error", this.onError);
|
||||
|
||||
this.ws.setMaxListeners(0);
|
||||
}
|
||||
|
||||
this.openWebSocketStatus = true;
|
||||
} catch (error) {
|
||||
this.openWebSocketStatus = false;
|
||||
}
|
||||
};
|
||||
// Disconnection of WebSocket
|
||||
close = () => {
|
||||
this.ws.close();
|
||||
// console.log('WebSocket Close');
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 2 close`);
|
||||
};
|
||||
|
||||
// Open event
|
||||
onOpen = () => {
|
||||
// console.log("WebSocket Open");
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`opening server 2 websocket`);
|
||||
|
||||
if (this.isOpened()) {
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 2 open successfully`);
|
||||
|
||||
if (!this.clientAuthenticated) {
|
||||
this.clientAuth();
|
||||
}
|
||||
} else {
|
||||
// log error
|
||||
winston.logger.error(`websocket server 2 open failed`);
|
||||
}
|
||||
};
|
||||
|
||||
onClose = () => {
|
||||
// console.log("WebSocket Close");
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 2 close`);
|
||||
|
||||
this.clientAuthenticated = false;
|
||||
this.ws = null;
|
||||
startInterval();
|
||||
};
|
||||
|
||||
onError = () => {
|
||||
// console.log("WebSocket Error");
|
||||
|
||||
// log error
|
||||
winston.logger.error(`websocket server 2 error`);
|
||||
|
||||
this.clientAuthenticated = false;
|
||||
};
|
||||
|
||||
// Connection check
|
||||
isOpened = () => {
|
||||
return this.ws.readyState == WebSocket.OPEN;
|
||||
};
|
||||
|
||||
// Received data check
|
||||
isReceive() {
|
||||
return this.receiveData != null;
|
||||
}
|
||||
|
||||
// Acquiring received data
|
||||
getReceiveData() {
|
||||
return this.receiveData;
|
||||
}
|
||||
|
||||
clearReceiveData() {
|
||||
this.receiveData = null;
|
||||
}
|
||||
|
||||
// Send data
|
||||
sendData(data) {
|
||||
this.receiveData = null;
|
||||
this.ws.send(data);
|
||||
}
|
||||
|
||||
async clientAuth() {
|
||||
try {
|
||||
var authHead = Buffer.alloc(2);
|
||||
// Set system code (when 0x0000)
|
||||
// authHead[0] = 0x93;
|
||||
// authHead[1] = 0x9e;
|
||||
authHead = systemCode;
|
||||
|
||||
const authData = Buffer.concat([authHead, apiKeyBytes, secretBytes]);
|
||||
|
||||
let transactionId = Buffer.from([0x00, 0x00]);
|
||||
let apiId = Buffer.from([0x00]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, authData);
|
||||
|
||||
let respData = null;
|
||||
let _stopMessage = 1;
|
||||
|
||||
this.sendData(reqData);
|
||||
|
||||
this.ws.on("message", (message) => {
|
||||
let __validasi = generate.buf2hex(message).slice(14, 30);
|
||||
while (
|
||||
message[2] == 0 &&
|
||||
_stopMessage == 1 &&
|
||||
message[0] == 0 &&
|
||||
message[1] == 0
|
||||
) {
|
||||
respData = null;
|
||||
// console.log("*WS MESSAGE Tenan: " + generate.buf2hex(message));
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`websocket server 2 message tenant: ${generate.buf2hex(message)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
_stopMessage = 2;
|
||||
}
|
||||
});
|
||||
|
||||
while (respData == null) {
|
||||
await _sleep(10);
|
||||
}
|
||||
let respCode = generate.getResponseCode(respData);
|
||||
// console.log(`Resp Data Tenant = ${respCode}`);
|
||||
// log debug
|
||||
winston.logger.debug(`websocket server 2 resp data tenant: ${respCode}`);
|
||||
|
||||
if (respCode == "0000" || respCode == "0502") {
|
||||
this.clientAuthenticated = true;
|
||||
}
|
||||
// console.log(`clientAuthenticated = ${this.clientAuthenticated}`);
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`websocket server 2 client authenticate: ${this.clientAuthenticated}`
|
||||
);
|
||||
} catch (error) {
|
||||
// console.log(`error ${error}`);
|
||||
// log error
|
||||
winston.logger.error(`websocket server 2 error: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var client2 = new WebSocketClient();
|
||||
if (!client2.openWebSocketStatus) {
|
||||
// log info
|
||||
winston.logger.info(`first open websocket server 2`);
|
||||
client2.open();
|
||||
}
|
||||
|
||||
setInterval(function () {
|
||||
// let statusConnection = client2.clientAuthenticated;
|
||||
// if (!statusConnection) {
|
||||
if (!this.ws) {
|
||||
// log debug
|
||||
// winston.logger.debug(`retry call client Auth`);
|
||||
client2.clientAuth();
|
||||
}
|
||||
// }
|
||||
}, 50000);
|
||||
|
||||
module.exports = {
|
||||
client2,
|
||||
};
|
||||
module.exports = { client2 };
|
||||
|
||||
@@ -98,8 +98,15 @@ const controller = async (req, res) => {
|
||||
}
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-6 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
@@ -109,17 +116,14 @@ const controller = async (req, res) => {
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} response HSM - write topup: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-6 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - write topup: ${JSON.stringify(req.body)}`
|
||||
);
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(trxID));
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(requestData));
|
||||
let _stopMessage = 1;
|
||||
@@ -159,7 +163,7 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message write topup: ${generate.buf2hex(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-6 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
@@ -182,7 +186,7 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - inserting load balance transaction...`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-6 ]: inserting load balance transaction...`
|
||||
);
|
||||
|
||||
let data = {
|
||||
@@ -201,7 +205,7 @@ const controller = async (req, res) => {
|
||||
};
|
||||
|
||||
// insert data load balance
|
||||
let insert = await loadBalance.loadingBalanceInsert(data);
|
||||
let insert = await loadBalance.loadingBalanceInsert(req, data);
|
||||
if (insert) {
|
||||
if (insert.code == '00') {
|
||||
result = {
|
||||
@@ -232,14 +236,16 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} response HSM - write topup: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-6 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-6 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
require('dotenv').config();
|
||||
|
||||
// Get Service Code, Block, dan System Code
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
// check service block
|
||||
if (
|
||||
process.env.SERVICEBLOCK_SERVICE_MUTUAL == '' ||
|
||||
process.env.SERVICEBLOCK_BLOCK_READ == '' ||
|
||||
process.env.SERVICEBLOCK_BLOCK_WRITE == ''
|
||||
) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`PLEASE CONFIGURE SERVICE BLOCK ON THE ENVIRONMENT!`
|
||||
);
|
||||
}
|
||||
|
||||
let sytemCode = '939E';
|
||||
let serviceReadNS = '4B1017208B20';
|
||||
let blockReadNS = '800081008200';
|
||||
let serviceMutual = process.env.SERVICEBLOCK_SERVICE_MUTUAL;
|
||||
let blockReadS = process.env.SERVICEBLOCK_BLOCK_READ;
|
||||
let blockWrite = process.env.SERVICEBLOCK_BLOCK_WRITE;
|
||||
let locFlag = 15;
|
||||
return res.status(200).send({
|
||||
code: '00',
|
||||
message: 'Get Service Succeess',
|
||||
data: {
|
||||
sysCode: sytemCode,
|
||||
sReadNS: serviceReadNS,
|
||||
sMutual: serviceMutual,
|
||||
bReadNS: blockReadNS,
|
||||
bReadS: blockReadS,
|
||||
bWrite: blockWrite,
|
||||
lFlag: locFlag,
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return res.json({
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,119 @@
|
||||
const helper = require('../../../helpers/helper');
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage } = require('../services/requestHsm');
|
||||
const refreshHsm = require('../services/refreshHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
let counterDirect = 0;
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
if (counterDirect > 1 || counterDirect < 0) {
|
||||
counterDirect = 0;
|
||||
}
|
||||
counterDirect++;
|
||||
|
||||
let { body } = req;
|
||||
const uniqueCode = `${helper.getUniqueCode()}${counterDirect}`;
|
||||
let result = {};
|
||||
|
||||
const { client: useClient, serverNumber, redirected } = selectHsmClient(uniqueCode);
|
||||
if (redirected !== undefined) {
|
||||
const action = redirected ? 'redirected' : 'selected';
|
||||
const message = `${uniqueCode} HSM server=${serverNumber} action=${action}`;
|
||||
if (redirected) winston.logger.warn(message);
|
||||
else winston.logger.debug(message);
|
||||
}
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-1 ]: STARTING TOP UP...`
|
||||
);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-1 ]`
|
||||
);
|
||||
|
||||
let felicaPollingResponse = Buffer.from(
|
||||
generate.hexToBytes(body.requestData)
|
||||
);
|
||||
|
||||
const cardId = body.requestData.slice(4, 20);
|
||||
|
||||
let transactionId = Buffer.from([0x00, 0x00]);
|
||||
let apiId = Buffer.from([0x01]);
|
||||
const reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
felicaPollingResponse
|
||||
);
|
||||
|
||||
let respData;
|
||||
try {
|
||||
respData = await requestHsm(useClient?.ws, reqData, { cardId });
|
||||
} catch (error) {
|
||||
if (error?.code !== 'HSM_TIMEOUT') throw error;
|
||||
|
||||
try {
|
||||
await refreshHsm(serverNumber);
|
||||
} catch {
|
||||
winston.logger.warn(`HSM server ${serverNumber} refresh failed`);
|
||||
}
|
||||
|
||||
return res.status(200).send({ code: '5001', message: 'Timeout', data: {} });
|
||||
}
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
if (respData1) {
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Request Authenticate 1 Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
unique_code: uniqueCode,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: '5004',
|
||||
message: 'Empty Data from HSM',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
unique_code: uniqueCode,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-1 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-1 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,82 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-2 ]`
|
||||
);
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
let transactionId = parseHsmTransactionId(body.trxID);
|
||||
let auth2v2requestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
|
||||
if (auth2v2requestData[0] != 0x41) {
|
||||
result = {
|
||||
code: '5003',
|
||||
message: 'Wrong Respone from Card',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-2 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x02]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
auth2v2requestData
|
||||
);
|
||||
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Request Authenticate 2 Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-2 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-2 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,85 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-3 ]: request to HSM `
|
||||
);
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
let transactionId = parseHsmTransactionId(body.trxID);
|
||||
let auth2v2responseSetData = Buffer.from(
|
||||
generate.hexToBytes(body.requestData)
|
||||
);
|
||||
// console.log("Req Auth Resp: " + body.requestData);
|
||||
|
||||
if (auth2v2responseSetData[0] != 0x43) {
|
||||
result = {
|
||||
code: '5003',
|
||||
message: 'Wrong Respone from Card',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-3 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x03]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
auth2v2responseSetData
|
||||
);
|
||||
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Request Authenticate Resp Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-3 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-3 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,67 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-4 ]`
|
||||
);
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
let transactionId = parseHsmTransactionId(body.trxID);
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
|
||||
let apiId = Buffer.from([0x04]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
trxrequestData
|
||||
);
|
||||
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-4 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-4 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,76 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-5 ]`
|
||||
);
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
let transactionId = parseHsmTransactionId(body.trxID);
|
||||
let packet = Buffer.from(generate.hexToBytes(body.requestData));
|
||||
if (packet[0] != 0x45) {
|
||||
result = {
|
||||
code: '03',
|
||||
message: 'Respone Card Wrong',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-5 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x05]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, packet);
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Read Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-5 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-5 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -0,0 +1,184 @@
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const loadBalance = require('../../loadbalance/loadbalance.controller');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'topup':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('uid').not().isEmpty().withMessage('UID is required'),
|
||||
body('flag').not().isEmpty().withMessage('Flag is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card Number is required'),
|
||||
body('amount')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Amount is required')
|
||||
.isNumeric()
|
||||
.withMessage('Amount is invalid format'),
|
||||
body('reservation_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Reservation Number is required')
|
||||
.isArray()
|
||||
.withMessage('Reservation Number is invalid request format'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let {
|
||||
mid,
|
||||
tid,
|
||||
card_number,
|
||||
amount,
|
||||
reservation_number,
|
||||
ref_no,
|
||||
write_status,
|
||||
uid,
|
||||
balance,
|
||||
flag,
|
||||
execution_id,
|
||||
unique_code,
|
||||
trxID,
|
||||
requestData,
|
||||
} = req.body;
|
||||
|
||||
let uniqueCode = unique_code;
|
||||
let result = {};
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-6 ]`
|
||||
);
|
||||
|
||||
// check validator
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-6 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
let transactionId = parseHsmTransactionId(trxID);
|
||||
let trxrequestData = Buffer.from(generate.hexToBytes(requestData));
|
||||
let execID;
|
||||
if (execution_id) {
|
||||
execID = execution_id;
|
||||
} else {
|
||||
let execByte = Buffer.alloc(2);
|
||||
trxrequestData.copy(execByte, 0, 24, 26);
|
||||
execID = generate.buf2hex(execByte);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x04]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
trxrequestData
|
||||
);
|
||||
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-6 ]: inserting load balance transaction...`
|
||||
);
|
||||
|
||||
let data = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
card_number: card_number,
|
||||
amount: amount,
|
||||
reservation_number: reservation_number,
|
||||
ref_no: ref_no,
|
||||
write_status: write_status,
|
||||
uid: uid,
|
||||
balance: balance,
|
||||
flag: flag,
|
||||
unique_code: unique_code,
|
||||
execution_id: execID,
|
||||
};
|
||||
|
||||
// insert data load balance
|
||||
let insert = await loadBalance.loadingBalanceInsert(req, data);
|
||||
if (insert) {
|
||||
if (insert.code == '00') {
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Generate Write Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
load_balance_number: insert.data.load_balance_number,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: insert.code,
|
||||
message: insert.message,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '423',
|
||||
message: 'update/insert failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-6 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-6 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
controller,
|
||||
};
|
||||
@@ -0,0 +1,237 @@
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const loadBalance = require('../../loadbalance/loadbalance.controller');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'topupResponse':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('uid').not().isEmpty().withMessage('UID is required'),
|
||||
body('flag').not().isEmpty().withMessage('Flag is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card Number is required'),
|
||||
body('amount')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Amount is required')
|
||||
.isNumeric()
|
||||
.withMessage('Amount is invalid format'),
|
||||
body('reservation_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Reservation Number is required')
|
||||
.isArray()
|
||||
.withMessage('Reservation Number is invalid request format'),
|
||||
body('load_balance_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Load Balance Number is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
// param
|
||||
let {
|
||||
mid,
|
||||
tid,
|
||||
card_number,
|
||||
amount,
|
||||
reservation_number,
|
||||
ref_no,
|
||||
uid,
|
||||
balance,
|
||||
flag,
|
||||
unique_code,
|
||||
load_balance_number,
|
||||
trxID,
|
||||
requestData,
|
||||
} = req.body;
|
||||
|
||||
let uniqueCode = unique_code;
|
||||
let result = {};
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
// case success write to the card but loss contact with device
|
||||
// result = {
|
||||
// code: "100",
|
||||
// message: "failed topup",
|
||||
// data: {},
|
||||
// };
|
||||
// return res.status(200).send(result);
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-7 ]`
|
||||
);
|
||||
|
||||
let transactionId = parseHsmTransactionId(trxID);
|
||||
let packet = Buffer.from(generate.hexToBytes(requestData));
|
||||
if (packet[0] != 0x47) {
|
||||
result = {
|
||||
code: '03',
|
||||
message: 'Respone Card Wrong',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-7 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
}
|
||||
|
||||
let apiId = Buffer.from([0x05]);
|
||||
let reqData = generate.makeRequestData(transactionId, apiId, packet);
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
let data = {};
|
||||
|
||||
if (
|
||||
respData[6] != 0x47 ||
|
||||
(respData1[9] != 0x00 && respData1[10] != 0x00)
|
||||
) {
|
||||
data = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
card_number: card_number,
|
||||
amount: amount,
|
||||
reservation_number: reservation_number,
|
||||
ref_no: ref_no,
|
||||
write_status: 'FW',
|
||||
uid: uid,
|
||||
balance: parseInt(balance) + parseInt(amount),
|
||||
flag: parseInt(flag),
|
||||
unique_code: unique_code,
|
||||
load_balance_number: load_balance_number,
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: updating load balance transaction is FW...`
|
||||
);
|
||||
|
||||
// update data load balance
|
||||
let update = await loadBalance.loadingBalanceUpdate(data);
|
||||
if (update) {
|
||||
if (update.code == '00') {
|
||||
result = {
|
||||
code: '5002',
|
||||
message: 'failed from HSM',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respData1.slice(6, 10),
|
||||
transcode: null,
|
||||
load_balance_number: update.data.load_balance_number,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: update.code,
|
||||
message: update.message,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '423',
|
||||
message: 'update/insert failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// jika sudah mencapai maksimum counting flag, maka reset flag ke awal
|
||||
if (flag >= 255) {
|
||||
flag = -1;
|
||||
}
|
||||
|
||||
data = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
card_number: card_number,
|
||||
amount: amount,
|
||||
reservation_number: reservation_number,
|
||||
ref_no: ref_no,
|
||||
write_status: null,
|
||||
uid: uid,
|
||||
balance: balance,
|
||||
flag: flag ? parseInt(flag) + 1 : flag,
|
||||
unique_code: unique_code,
|
||||
load_balance_number: load_balance_number,
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: updating load balance transaction...`
|
||||
);
|
||||
|
||||
// update data load balance
|
||||
let update = await loadBalance.loadingBalanceUpdate(data);
|
||||
if (update) {
|
||||
if (update.code == '00') {
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'Topup Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
responseData: respData1,
|
||||
responseLength: respData1.length / 2,
|
||||
load_balance_number: update.data.load_balance_number,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: update.code,
|
||||
message: update.message,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '423',
|
||||
message: 'update/insert failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-7 ]: ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-7 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = { validate, controller };
|
||||
@@ -0,0 +1,65 @@
|
||||
const winston = require('../../../helpers/winston.logger');
|
||||
const generate = require('../utils/utils');
|
||||
const { requestHsm, hsmErrorMessage, parseHsmTransactionId } = require('../services/requestHsm');
|
||||
const selectHsmClient = require('../services/selectHsmClient');
|
||||
|
||||
const controller = async (req, res) => {
|
||||
try {
|
||||
let { body } = req;
|
||||
let uniqueCode = body.unique_code;
|
||||
let result = {};
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-8 ]`
|
||||
);
|
||||
|
||||
const { client: useClient } = selectHsmClient(uniqueCode);
|
||||
|
||||
let transactionId = parseHsmTransactionId(body.trxID);
|
||||
|
||||
let transactionEnd = Buffer.from([]);
|
||||
let apiId = Buffer.from([0x06]);
|
||||
let reqData = generate.makeRequestData(
|
||||
transactionId,
|
||||
apiId,
|
||||
transactionEnd
|
||||
);
|
||||
|
||||
const respData = await requestHsm(useClient?.ws, reqData);
|
||||
|
||||
transactionId[0] = respData[0];
|
||||
transactionId[1] = respData[1];
|
||||
const respCode = generate.getResponseCode(respData);
|
||||
const respData1 = generate.getResponseData(respData);
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'End Transaction Success',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
},
|
||||
};
|
||||
|
||||
// log debug
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-8 ]: ENDING TOP UP... ${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-8 ]: 500 internal server error - backend server | ${error?.code === 'HSM_TIMEOUT' ? 'HSM_TIMEOUT' : 'HSM_REQUEST_FAILED'}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: '5001',
|
||||
message: hsmErrorMessage(error),
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = controller;
|
||||
@@ -1,55 +1,55 @@
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const generate = require("./utils/utils");
|
||||
const loadBalance = require("../loadbalance/loadbalance.controller");
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const generate = require('./utils/utils');
|
||||
const loadBalance = require('../loadbalance/loadbalance.controller');
|
||||
const _sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
require("dotenv").config();
|
||||
require('dotenv').config();
|
||||
|
||||
let useClient;
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "1") {
|
||||
var { client } = require("./services/webSocket");
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '1') {
|
||||
var { client } = require('./services/webSocket');
|
||||
|
||||
useClient = client;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "2") {
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '2') {
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
|
||||
useClient = client2;
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
var { client } = require("./services/webSocket");
|
||||
var { client2 } = require("./services/webSocket2");
|
||||
} else if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
var { client } = require('./services/webSocket');
|
||||
var { client2 } = require('./services/webSocket2');
|
||||
}
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "topupResponse":
|
||||
case 'topupResponse':
|
||||
return [
|
||||
body("mid").not().isEmpty().withMessage("MID is required"),
|
||||
body("tid").not().isEmpty().withMessage("TID is required"),
|
||||
body("uid").not().isEmpty().withMessage("UID is required"),
|
||||
body("flag").not().isEmpty().withMessage("Flag is required"),
|
||||
body("card_number")
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('uid').not().isEmpty().withMessage('UID is required'),
|
||||
body('flag').not().isEmpty().withMessage('Flag is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Card Number is required"),
|
||||
body("amount")
|
||||
.withMessage('Card Number is required'),
|
||||
body('amount')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Amount is required")
|
||||
.withMessage('Amount is required')
|
||||
.isNumeric()
|
||||
.withMessage("Amount is invalid format"),
|
||||
body("reservation_number")
|
||||
.withMessage('Amount is invalid format'),
|
||||
body('reservation_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Reservation Number is required")
|
||||
.withMessage('Reservation Number is required')
|
||||
.isArray()
|
||||
.withMessage("Reservation Number is invalid request format"),
|
||||
body("load_balance_number")
|
||||
.withMessage('Reservation Number is invalid request format'),
|
||||
body('load_balance_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage("Load Balance Number is required"),
|
||||
.withMessage('Load Balance Number is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
@@ -79,7 +79,7 @@ const controller = async (req, res) => {
|
||||
let result = {};
|
||||
|
||||
// set connection HSM server
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == "12") {
|
||||
if (process.env.NUMBER_SERVER_ACTIVE == '12') {
|
||||
// set request to HSM server 2
|
||||
if (uniqueCode) {
|
||||
if (parseInt(uniqueCode) % 2 == 0) {
|
||||
@@ -111,7 +111,9 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} request HSM - topup resp: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} [ REQUEST LOADING-BALANCE TOPUP-7 ]: ${JSON.stringify(
|
||||
req.body
|
||||
)}`
|
||||
);
|
||||
|
||||
let transactionId = Buffer.from(generate.hexToBytes(trxID));
|
||||
@@ -119,14 +121,16 @@ const controller = async (req, res) => {
|
||||
let _stopMessage = 1;
|
||||
if (packet[0] != 0x47) {
|
||||
result = {
|
||||
code: "03",
|
||||
message: "Respone Card Wrong",
|
||||
code: '03',
|
||||
message: 'Respone Card Wrong',
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} response HSM - topup resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-7 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
@@ -140,7 +144,7 @@ const controller = async (req, res) => {
|
||||
let respData = null;
|
||||
let respData1 = null;
|
||||
|
||||
useClient.ws.on("message", (message) => {
|
||||
useClient.ws.on('message', (message) => {
|
||||
while (
|
||||
message[2] == 5 &&
|
||||
message[0] == transactionId[0] &&
|
||||
@@ -154,7 +158,9 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message topup resp: ${generate.buf2hex(message)}`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: message from HSM ${generate.buf2hex(
|
||||
message
|
||||
)}`
|
||||
);
|
||||
|
||||
respData = message;
|
||||
@@ -186,7 +192,7 @@ const controller = async (req, res) => {
|
||||
amount: amount,
|
||||
reservation_number: reservation_number,
|
||||
ref_no: ref_no,
|
||||
write_status: "FW",
|
||||
write_status: 'FW',
|
||||
uid: uid,
|
||||
balance: parseInt(balance) + parseInt(amount),
|
||||
flag: parseInt(flag),
|
||||
@@ -196,23 +202,43 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - updating load balance transaction...`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: updating load balance transaction is FW...`
|
||||
);
|
||||
|
||||
// update data load balance
|
||||
await loadBalance.loadingBalanceUpdate(data);
|
||||
|
||||
result = {
|
||||
code: "5002",
|
||||
message: "failed from HSM",
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respData1.slice(6, 10),
|
||||
transcode: null,
|
||||
load_balance_number: update.data.load_balance_number,
|
||||
},
|
||||
};
|
||||
let update = await loadBalance.loadingBalanceUpdate(data);
|
||||
if (update) {
|
||||
if (update.code == '00') {
|
||||
result = {
|
||||
code: '5002',
|
||||
message: 'failed from HSM',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respData1.slice(6, 10),
|
||||
transcode: null,
|
||||
load_balance_number: update.data.load_balance_number,
|
||||
},
|
||||
};
|
||||
} else {
|
||||
result = {
|
||||
code: update.code,
|
||||
message: update.message,
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: '423',
|
||||
message: 'update/insert failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// jika sudah mencapai maksimum counting flag, maka reset flag ke awal
|
||||
if (flag >= 255) {
|
||||
flag = -1;
|
||||
}
|
||||
|
||||
data = {
|
||||
mid: mid,
|
||||
tid: tid,
|
||||
@@ -230,16 +256,16 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - updating load balance transaction...`
|
||||
`${uniqueCode} [ PROCESSING LOADING-BALANCE TOPUP-7 ]: updating load balance transaction...`
|
||||
);
|
||||
|
||||
// update data load balance
|
||||
let update = await loadBalance.loadingBalanceUpdate(data);
|
||||
if (update) {
|
||||
if (update.code == "00") {
|
||||
if (update.code == '00') {
|
||||
result = {
|
||||
code: "00",
|
||||
message: "Topup Succeess",
|
||||
code: '00',
|
||||
message: 'Topup Succeess',
|
||||
data: {
|
||||
trxID: generate.buf2hex(transactionId),
|
||||
responseCode: respCode,
|
||||
@@ -257,8 +283,8 @@ const controller = async (req, res) => {
|
||||
}
|
||||
} else {
|
||||
result = {
|
||||
code: "423",
|
||||
message: "update/insert failed",
|
||||
code: '423',
|
||||
message: 'update/insert failed',
|
||||
data: {},
|
||||
};
|
||||
}
|
||||
@@ -266,22 +292,24 @@ const controller = async (req, res) => {
|
||||
|
||||
// log debug
|
||||
winston.logger.debug(
|
||||
`${uniqueCode} HSM - message topup resp: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} [ RESPONSE LOADING-BALANCE TOPUP-7 ]: ${JSON.stringify(
|
||||
result
|
||||
)}`
|
||||
);
|
||||
|
||||
return res.status(200).send(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`500 internal server error - backend server | ${error.message}`
|
||||
`[ RESPONSE LOADING-BALANCE TOPUP-7 ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).send({
|
||||
code: "5001",
|
||||
code: '5001',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -1,157 +1,178 @@
|
||||
const { Buffer } = require("buffer")
|
||||
const fs = require('fs')
|
||||
const { Buffer } = require('buffer');
|
||||
const fs = require('fs');
|
||||
const { formatLog, writeStdoutLine } = require('../../../helpers/stdout-log');
|
||||
|
||||
// Generate request data for FeliQ Server
|
||||
function makeRequestData(transactionId, apiId, data){
|
||||
let request = Buffer.alloc(2 + 1 + 1 + data.length)
|
||||
let dataSize = Buffer.alloc(1)
|
||||
dataSize[0] = data.length
|
||||
request = Buffer.concat([transactionId, apiId, dataSize, data])
|
||||
return request;
|
||||
function makeRequestData(transactionId, apiId, data) {
|
||||
let request = Buffer.alloc(2 + 1 + 1 + data.length);
|
||||
let dataSize = Buffer.alloc(1);
|
||||
dataSize[0] = data.length;
|
||||
request = Buffer.concat([transactionId, apiId, dataSize, data]);
|
||||
return request;
|
||||
}
|
||||
|
||||
|
||||
// Extract response code from API response data
|
||||
function getResponseCode(data){
|
||||
let respCode = Buffer.alloc(2)
|
||||
respCode[0] = data[3]
|
||||
respCode[1] = data[4]
|
||||
return buf2hex(respCode)
|
||||
function getResponseCode(data) {
|
||||
let respCode = Buffer.alloc(2);
|
||||
respCode[0] = data[3];
|
||||
respCode[1] = data[4];
|
||||
return buf2hex(respCode);
|
||||
}
|
||||
|
||||
// Extract response data from API response data
|
||||
function getResponseData(apiData){
|
||||
let data = Buffer.alloc(apiData[5])
|
||||
apiData.copy(data, 0, 6, apiData[5]+6)
|
||||
return buf2hex(data);
|
||||
}
|
||||
function getResponseData(apiData) {
|
||||
let data = Buffer.alloc(apiData[5]);
|
||||
apiData.copy(data, 0, 6, apiData[5] + 6);
|
||||
return buf2hex(data);
|
||||
}
|
||||
|
||||
|
||||
function buf2hex(buffer){ // buffer is an ArrayBuffer
|
||||
return [...new Uint8Array(buffer)]
|
||||
.map(x => x.toString(16).padStart(2, '0'))
|
||||
.join('')
|
||||
}
|
||||
function buf2hex(buffer) {
|
||||
// buffer is an ArrayBuffer
|
||||
return [...new Uint8Array(buffer)]
|
||||
.map((x) => x.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
function hexToBytes(hex) {
|
||||
for (var bytes = [], c = 0; c < hex.length; c += 2)
|
||||
bytes.push(parseInt(hex.substr(c, 2), 16))
|
||||
return bytes
|
||||
}
|
||||
|
||||
for (var bytes = [], c = 0; c < hex.length; c += 2)
|
||||
bytes.push(parseInt(hex.substr(c, 2), 16));
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function hex2ascii(hexx) {
|
||||
let hex = hexx.toString();//force conversion
|
||||
let str = ''
|
||||
for (var i = 0; i < hex.length; i += 2)
|
||||
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16))
|
||||
return str
|
||||
let hex = hexx.toString(); //force conversion
|
||||
let str = '';
|
||||
for (var i = 0; i < hex.length; i += 2)
|
||||
str += String.fromCharCode(parseInt(hex.substr(i, 2), 16));
|
||||
return str;
|
||||
}
|
||||
|
||||
const formatDate = (date, type) => {
|
||||
var inputDate = new Date(date);
|
||||
var inputDate = new Date(date);
|
||||
|
||||
let tanggal = inputDate.getDate()
|
||||
let bulan = inputDate.getMonth() + 1
|
||||
let tahun = inputDate.getFullYear()
|
||||
let tanggal = inputDate.getDate();
|
||||
let bulan = inputDate.getMonth() + 1;
|
||||
let tahun = inputDate.getFullYear();
|
||||
|
||||
let jam = inputDate.getHours()
|
||||
let menit = inputDate.getMinutes()
|
||||
let detik = inputDate.getSeconds()
|
||||
|
||||
if (bulan.toString().length < 2) bulan = '0' + bulan
|
||||
if (tanggal.toString().length < 2) tanggal = '0' + tanggal
|
||||
if (jam.toString().length < 2) jam = '0' + jam
|
||||
if (menit.toString().length < 2) menit = '0' + menit
|
||||
if (detik.toString().length < 2) detik = '0' + detik
|
||||
let jam = inputDate.getHours();
|
||||
let menit = inputDate.getMinutes();
|
||||
let detik = inputDate.getSeconds();
|
||||
|
||||
let formatTanggal = [tahun, bulan, tanggal].join('')
|
||||
let formatWaktu = [jam, menit, detik].join('')
|
||||
if (bulan.toString().length < 2) bulan = '0' + bulan;
|
||||
if (tanggal.toString().length < 2) tanggal = '0' + tanggal;
|
||||
if (jam.toString().length < 2) jam = '0' + jam;
|
||||
if (menit.toString().length < 2) menit = '0' + menit;
|
||||
if (detik.toString().length < 2) detik = '0' + detik;
|
||||
|
||||
return [formatTanggal, formatWaktu].join('')
|
||||
}
|
||||
let formatTanggal = [tahun, bulan, tanggal].join('');
|
||||
let formatWaktu = [jam, menit, detik].join('');
|
||||
|
||||
function getTranscode(cardData, nominal){
|
||||
let trxType = Buffer.from([0x02])
|
||||
let uid = Buffer.alloc(8)
|
||||
let cardType = Buffer.alloc(2)
|
||||
return [formatTanggal, formatWaktu].join('');
|
||||
};
|
||||
|
||||
var cardNumber = Buffer.alloc(16)
|
||||
cardData.copy(cardNumber, 0, 12+16, 12+16+16)
|
||||
function getTranscode(cardData, nominal) {
|
||||
let trxType = Buffer.from([0x02]);
|
||||
let uid = Buffer.alloc(8);
|
||||
let cardType = Buffer.alloc(2);
|
||||
|
||||
cardNumber = cardNumber.toString()
|
||||
var cardNumber = Buffer.alloc(16);
|
||||
cardData.copy(cardNumber, 0, 12 + 16, 12 + 16 + 16);
|
||||
|
||||
cardData.copy(uid, 0, 1,9)
|
||||
let _cardNumber = Buffer.from(hexToBytes(cardNumber))
|
||||
cardNumber = cardNumber.toString();
|
||||
|
||||
var balanceArray = Buffer.alloc(4)
|
||||
var balanceArrayExis = Buffer.alloc(4)
|
||||
var exec_idArray = Buffer.alloc(2)
|
||||
|
||||
cardData.copy(balanceArray, 0, 12+16+16, 12+16+16+4)
|
||||
cardData.copy(balanceArrayExis, 0, 12+16+16, 12+16+16+4)
|
||||
exec_idArray[1] = cardData[cardData.length -1]
|
||||
exec_idArray[0] = cardData[cardData.length -2]
|
||||
cardData.copy(uid, 0, 1, 9);
|
||||
let _cardNumber = Buffer.from(hexToBytes(cardNumber));
|
||||
|
||||
let balanceExisting = balanceArrayExis.reverse()
|
||||
let nominalStr = Buffer.from(hexToBytes(String(nominal).padStart(8, '0')))
|
||||
var balanceArray = Buffer.alloc(4);
|
||||
var balanceArrayExis = Buffer.alloc(4);
|
||||
var exec_idArray = Buffer.alloc(2);
|
||||
|
||||
let balance = Buffer.from(balanceArray).readInt32LE()
|
||||
balance += parseInt(nominal)
|
||||
balanceArray.writeInt32LE(balance)
|
||||
let balanceAfter = balanceArray.reverse()
|
||||
cardData.copy(balanceArray, 0, 12 + 16 + 16, 12 + 16 + 16 + 4);
|
||||
cardData.copy(balanceArrayExis, 0, 12 + 16 + 16, 12 + 16 + 16 + 4);
|
||||
exec_idArray[1] = cardData[cardData.length - 1];
|
||||
exec_idArray[0] = cardData[cardData.length - 2];
|
||||
|
||||
let dateTime = Buffer.from(hexToBytes(formatDate(new Date())))
|
||||
let balanceExisting = balanceArrayExis.reverse();
|
||||
let nominalStr = Buffer.from(hexToBytes(String(nominal).padStart(8, '0')));
|
||||
|
||||
cardData.copy(cardType,0, 1 + 8 + 3 + 1, 1 + 8 + 3 + 1 + 2)
|
||||
let balance = Buffer.from(balanceArray).readInt32LE();
|
||||
balance += parseInt(nominal);
|
||||
balanceArray.writeInt32LE(balance);
|
||||
let balanceAfter = balanceArray.reverse();
|
||||
|
||||
let samID = Buffer.alloc(8)
|
||||
let samBalBefore = Buffer.alloc(4)
|
||||
let samBalAfter = Buffer.alloc(4)
|
||||
let dateTime = Buffer.from(hexToBytes(formatDate(new Date())));
|
||||
|
||||
let exec_id = exec_idArray.readUInt16BE()
|
||||
exec_id++
|
||||
cardData.copy(cardType, 0, 1 + 8 + 3 + 1, 1 + 8 + 3 + 1 + 2);
|
||||
|
||||
exec_idArray.writeUInt16BE(exec_id)
|
||||
let samID = Buffer.alloc(8);
|
||||
let samBalBefore = Buffer.alloc(4);
|
||||
let samBalAfter = Buffer.alloc(4);
|
||||
|
||||
let _transcode = Buffer.concat([trxType, _cardNumber, balanceExisting, nominalStr, balanceAfter,dateTime,
|
||||
cardType, uid, samID, samBalBefore, samBalAfter, exec_idArray])
|
||||
return _transcode
|
||||
let exec_id = exec_idArray.readUInt16BE();
|
||||
exec_id++;
|
||||
|
||||
exec_idArray.writeUInt16BE(exec_id);
|
||||
|
||||
let _transcode = Buffer.concat([
|
||||
trxType,
|
||||
_cardNumber,
|
||||
balanceExisting,
|
||||
nominalStr,
|
||||
balanceAfter,
|
||||
dateTime,
|
||||
cardType,
|
||||
uid,
|
||||
samID,
|
||||
samBalBefore,
|
||||
samBalAfter,
|
||||
exec_idArray,
|
||||
]);
|
||||
return _transcode;
|
||||
}
|
||||
|
||||
const logging = (date, title, message, id = 0) => {
|
||||
let month = date.getMonth() + 1;
|
||||
let month = date.getMonth() + 1;
|
||||
|
||||
try {
|
||||
//create folder/file if not exists
|
||||
if (!fs.existsSync(`./logs`)) {
|
||||
fs.mkdirSync(`./logs`)
|
||||
}
|
||||
if (!fs.existsSync(`./logs/log-${month}`)) {
|
||||
fs.mkdirSync(`./logs/log-${month}`)
|
||||
}
|
||||
|
||||
if (message.command) {
|
||||
message.command = buf2hex(message.command)
|
||||
}
|
||||
|
||||
let content = `[${formatDate(date)}] | { "id": ${id}, "title": ${title}, "message": ${message} }`;
|
||||
|
||||
fs.writeFileSync(`./logs/log-${month}/log.txt`, '\n' + content, {flag: 'a+'});
|
||||
|
||||
return
|
||||
} catch (err) {
|
||||
console.error("Error from logging: ", err.message);
|
||||
return
|
||||
try {
|
||||
//create folder/file if not exists
|
||||
if (!fs.existsSync(`./logs`)) {
|
||||
fs.mkdirSync(`./logs`);
|
||||
}
|
||||
}
|
||||
if (!fs.existsSync(`./logs/log-${month}`)) {
|
||||
fs.mkdirSync(`./logs/log-${month}`);
|
||||
}
|
||||
|
||||
if (message.command) {
|
||||
message.command = buf2hex(message.command);
|
||||
}
|
||||
|
||||
let content = `[${formatDate(
|
||||
date
|
||||
)}] | { "id": ${id}, "title": ${title}, "message": ${message} }`;
|
||||
|
||||
fs.writeFileSync(`./logs/log-${month}/log.txt`, '\n' + content, {
|
||||
flag: 'a+',
|
||||
});
|
||||
|
||||
return;
|
||||
} catch (err) {
|
||||
writeStdoutLine(formatLog({
|
||||
level: 'error',
|
||||
event: 'hsm_log_write_error',
|
||||
message: 'Unable to write the HSM log file',
|
||||
error_code: err.code || 'UNKNOWN',
|
||||
}));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
makeRequestData,
|
||||
getResponseCode,
|
||||
getResponseData,
|
||||
buf2hex,
|
||||
hexToBytes,
|
||||
hex2ascii,
|
||||
getTranscode,
|
||||
logging
|
||||
}
|
||||
makeRequestData,
|
||||
getResponseCode,
|
||||
getResponseData,
|
||||
buf2hex,
|
||||
hexToBytes,
|
||||
hex2ascii,
|
||||
getTranscode,
|
||||
logging,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
const { setTimeout: delay } = require('node:timers/promises');
|
||||
const helper = require('../../helpers/helper');
|
||||
const { logger } = require('../../helpers/winston.logger');
|
||||
const db = require('../../../infrastructure/database/knex');
|
||||
const model = require('./invoice.model');
|
||||
|
||||
const preConnectErrors = new Set(['ECONNREFUSED', 'ENOTFOUND', 'EAI_AGAIN', 'ERR_INVALID_URL']);
|
||||
const sapTimeoutMs = 15000;
|
||||
|
||||
async function generateInvoice(invoiceDate, uniqueCode, repost) {
|
||||
const invoices = await db.transaction(async (trx) => {
|
||||
const generated = await model.generateInvoice(invoiceDate, repost, trx);
|
||||
for (const invoice of generated) await model.insertPostingEt(invoice, trx);
|
||||
return generated;
|
||||
});
|
||||
return postInvoices(invoices, uniqueCode, true);
|
||||
}
|
||||
|
||||
async function retryInvoices(uniqueCode) {
|
||||
const invoices = [];
|
||||
for (const invoiceNo of await model.getAcceptedSapPostings(db)) {
|
||||
const invoice = await model.finishSapPosting(db, invoiceNo);
|
||||
if (invoice) invoices.push(invoice);
|
||||
}
|
||||
const queued = await model.getPostingEt(db);
|
||||
return [...invoices, ...await postInvoices(queued, uniqueCode, false)];
|
||||
}
|
||||
|
||||
async function postInvoices(items, uniqueCode, initialPosting) {
|
||||
if (items.length === 0) return [];
|
||||
const settings = await model.getSapSettings(db);
|
||||
const invoices = [];
|
||||
for (const [index, item] of items.entries()) {
|
||||
const invoiceNo = initialPosting ? item.c_invoice_no : item.reference;
|
||||
const spacingMs = index < items.length - 1 ? (initialPosting ? 1000 : 2000) : 0;
|
||||
const invoice = await postInvoice(item, invoiceNo, settings, uniqueCode, initialPosting, spacingMs);
|
||||
if (invoice) invoices.push(invoice);
|
||||
}
|
||||
return invoices;
|
||||
}
|
||||
|
||||
async function postInvoice(item, invoiceNo, settings, uniqueCode, initialPosting, spacingMs) {
|
||||
const { url, username, password } = settings;
|
||||
const debitAccount = initialPosting ? item.c_account_code_topup : item.customer;
|
||||
const creditAccount = initialPosting ? item.c_account_topup : item.account;
|
||||
if (!invoiceNo || !url || !username || !password || !debitAccount || !creditAccount) {
|
||||
logger.warn(`FB70 ${uniqueCode} ${invoiceNo} SAP settings or accounts missing`);
|
||||
return invoiceNo ? model.getInvoice(invoiceNo, db) : null;
|
||||
}
|
||||
|
||||
const xml = generatePostingXml(item, invoiceNo, debitAccount, creditAccount, initialPosting);
|
||||
if (!await model.claimSapPosting(db, invoiceNo, initialPosting)) {
|
||||
return await model.finishSapPosting(db, invoiceNo) || (initialPosting ? model.getInvoice(invoiceNo, db) : null);
|
||||
}
|
||||
|
||||
const invoice = await submitClaimedInvoice(
|
||||
invoiceNo, uniqueCode, url, xml, { username, password }
|
||||
);
|
||||
if (spacingMs) await delay(spacingMs);
|
||||
return invoice;
|
||||
}
|
||||
|
||||
async function submitClaimedInvoice(invoiceNo, uniqueCode, url, xml, credentials) {
|
||||
// Klaim sudah commit. Timeout atau kematian proses setelah pengiriman menahan retry.
|
||||
const response = await helper.postingSAP(url, xml, credentials, {
|
||||
timeoutMs: sapTimeoutMs,
|
||||
maxRedirects: 0,
|
||||
});
|
||||
if (preConnectErrors.has(response.errorCode)) {
|
||||
await model.releaseUnsentPosting(db, invoiceNo);
|
||||
logger.warn(`FB70 ${uniqueCode} ${invoiceNo} SAP connection not established`);
|
||||
return model.getInvoice(invoiceNo, db);
|
||||
}
|
||||
|
||||
const { documentNo, outcome } = readSapOutcome(response);
|
||||
await model.recordSapOutcome(db, invoiceNo, documentNo, outcome);
|
||||
if (documentNo) return model.finishSapPosting(db, invoiceNo);
|
||||
|
||||
logger.warn(`FB70 ${uniqueCode} ${invoiceNo} requires SAP reconciliation (${outcome})`);
|
||||
return model.getInvoice(invoiceNo, db);
|
||||
}
|
||||
|
||||
function readSapOutcome(response) {
|
||||
if (response.status !== 200) {
|
||||
const timedOut = ['ERR_CANCELED', 'ECONNABORTED', 'ETIMEDOUT'].includes(response.errorCode);
|
||||
return { documentNo: null, outcome: timedOut ? 'SAP_TIMEOUT' : 'SAP_HTTP_ERROR' };
|
||||
}
|
||||
try {
|
||||
const result = helper.getXMLData(response);
|
||||
const documentNo = result.data.E_DOCUMENTNUMBER;
|
||||
if (result.type === 'S' && /^\d+$/.test(documentNo) && /[1-9]/.test(documentNo)) {
|
||||
return { documentNo, outcome: 'SAP_CONFIRMED' };
|
||||
}
|
||||
} catch {
|
||||
return { documentNo: null, outcome: 'SAP_INVALID_RESPONSE' };
|
||||
}
|
||||
return { documentNo: null, outcome: 'SAP_UNCONFIRMED' };
|
||||
}
|
||||
|
||||
function generatePostingXml(item, invoiceNo, debitAccount, creditAccount, initialPosting) {
|
||||
const header = {
|
||||
doc_header_text: item.doc_header_text || '',
|
||||
ba: item.ba || '',
|
||||
doc_date: item.doc_date || '',
|
||||
posting_date: item.posting_date || '',
|
||||
fisc_year: (initialPosting ? item.fisc_year : item.fiscal_year) || '',
|
||||
fisc_period: (initialPosting ? item.fisc_period : item.fis_period) || '',
|
||||
doc_type: item.doc_type || '',
|
||||
c_invoice_no: invoiceNo,
|
||||
};
|
||||
const lines = ['S', 'H'].map((side) => {
|
||||
const debit = side === 'S';
|
||||
const itemText = initialPosting
|
||||
? `${debit ? 'DEBIT' : 'KREDIT'} INVOICE CMS ${item.doc_header_text}`
|
||||
: (debit ? item.text1 : item.text2);
|
||||
return {
|
||||
c_account_code_topup: debit ? debitAccount : '',
|
||||
c_account_topup: debit ? '' : creditAccount,
|
||||
ba: item.ba,
|
||||
amount: item.amount,
|
||||
posting_date: item.posting_date,
|
||||
c_invoice_no: invoiceNo,
|
||||
item_text: itemText,
|
||||
de_cre: side,
|
||||
};
|
||||
});
|
||||
return helper.generateXMLRequest('ZFMCMS_FI_001', header, lines);
|
||||
}
|
||||
|
||||
module.exports = { generateInvoice, retryInvoices };
|
||||
@@ -1,38 +1,37 @@
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
const helper = require("../../helpers/helper");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const model = require("./invoice.model");
|
||||
const moment = require("moment");
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
moment.locale("id");
|
||||
const { body, validationResult } = require('express-validator');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const { generateInvoice: _generateInvoice, retryInvoices: _postingInvoice } = require('./invoice-posting.service');
|
||||
const moment = require('moment');
|
||||
moment.locale('id');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "generateInvoice":
|
||||
case 'generateInvoice':
|
||||
return [
|
||||
body("trx_date")
|
||||
body('trx_date')
|
||||
.notEmpty()
|
||||
.withMessage("trx_date is required!")
|
||||
.withMessage('trx_date is required!')
|
||||
.isISO8601()
|
||||
.withMessage("invalid trx_date format YYYY-MM-DD !")
|
||||
.withMessage('invalid trx_date format YYYY-MM-DD !')
|
||||
.escape()
|
||||
.trim(),
|
||||
body("repost")
|
||||
body('repost')
|
||||
.notEmpty()
|
||||
.withMessage("repost is required!")
|
||||
.withMessage('repost is required!')
|
||||
.isBoolean()
|
||||
.withMessage("repost must boolean!")
|
||||
.withMessage('repost must boolean!')
|
||||
.escape()
|
||||
.trim(),
|
||||
];
|
||||
case "postingInvoice":
|
||||
case 'postingInvoice':
|
||||
return [
|
||||
body("trx_date")
|
||||
body('trx_date')
|
||||
.notEmpty()
|
||||
.withMessage("trx_date is required!")
|
||||
.withMessage('trx_date is required!')
|
||||
.isISO8601()
|
||||
.withMessage("invalid trx_date format YYYY-MM-DD !")
|
||||
.withMessage('invalid trx_date format YYYY-MM-DD !')
|
||||
.escape()
|
||||
.trim(),
|
||||
];
|
||||
@@ -45,46 +44,52 @@ const validate = (method) => {
|
||||
const apiGenerateInvoice = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
const uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST generate invoice: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} REQUEST generate invoice`
|
||||
);
|
||||
|
||||
const schedulerCode = 'GENERATEINVOICEONLINETOPUP';
|
||||
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",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE generate invoice: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} RESPONSE generate invoice code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// time
|
||||
let invoiceDate = moment(req.body.trx_date).format("YYYY-MM-DD");
|
||||
const invoiceDate = moment(req.body.trx_date).format('YYYY-MM-DD');
|
||||
|
||||
let invoice = await _generateInvoice(
|
||||
const invoice = await _generateInvoice(
|
||||
invoiceDate,
|
||||
uniqueCode,
|
||||
req.body.repost
|
||||
);
|
||||
|
||||
result = {
|
||||
code: "200",
|
||||
message: "Succes posting",
|
||||
code: '200',
|
||||
message: 'Succes generate invoice online topup',
|
||||
data: invoice,
|
||||
};
|
||||
|
||||
await helper.finishScheduler(token, schedulerCode);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
@@ -93,11 +98,11 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
@@ -107,26 +112,30 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
const apiPostingInvoice = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
const uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST posting invoice: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} REQUEST posting invoice`
|
||||
);
|
||||
|
||||
const schedulerCode = 'POSTINGINVOICEONLINETOPUP';
|
||||
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",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE generate invoice: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} RESPONSE generate invoice code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
@@ -138,11 +147,13 @@ const apiPostingInvoice = async (req, res) => {
|
||||
const invoice = await _postingInvoice(uniqueCode);
|
||||
|
||||
result = {
|
||||
code: "200",
|
||||
message: "Succes",
|
||||
code: '200',
|
||||
message: 'Succes',
|
||||
data: invoice,
|
||||
};
|
||||
|
||||
await helper.finishScheduler(token, schedulerCode);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
@@ -151,350 +162,16 @@ const apiPostingInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
let invoice = [];
|
||||
const collection = []
|
||||
await knex.transaction(async (trx) => {
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} execute payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`
|
||||
);
|
||||
|
||||
invoice = await model.generateInvoice(invoiceDate, repost, trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} result payment.sp_payment_req_topup_online ${JSON.stringify(
|
||||
invoice
|
||||
)}`
|
||||
);
|
||||
if (invoice.length > 0) {
|
||||
|
||||
for (const key in invoice) {
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify(
|
||||
invoice[key]
|
||||
)}`
|
||||
);
|
||||
|
||||
let postingEt = await model.insertPostingEt(invoice[key], trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} success insert posting et : ${JSON.stringify(
|
||||
postingEt
|
||||
)}`
|
||||
);
|
||||
}
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`
|
||||
);
|
||||
|
||||
const credUsername = await model.getParameterSetting(knex, "SAP_AUTH_USERNAME")
|
||||
const credPassword = await model.getParameterSetting(knex, "SAP_AUTH_PASSWORD")
|
||||
const parameter = await model.getParameterSetting(knex, "SAP_FI_URL_FOR_FB70")
|
||||
|
||||
for (const key in invoice) {
|
||||
let prepare = {
|
||||
status : true,
|
||||
cms : true,
|
||||
message: "Success",
|
||||
}
|
||||
|
||||
if(!credUsername) {
|
||||
prepare = {
|
||||
status : false,
|
||||
cms : false,
|
||||
message: "[CMS] FAILED GET SETTING FOR SAP_AUTH_USERNAME",
|
||||
}
|
||||
}
|
||||
|
||||
if(!credPassword) {
|
||||
prepare = {
|
||||
status : false,
|
||||
cms : false,
|
||||
message: "[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD",
|
||||
}
|
||||
}
|
||||
|
||||
if(!parameter) {
|
||||
prepare = {
|
||||
status : false,
|
||||
cms : false,
|
||||
message: "[CMS] FAILED GET SETTING FOR SAP_AUTH_PASSWORD",
|
||||
}
|
||||
}
|
||||
|
||||
const credential = {
|
||||
username: credUsername.c_value,
|
||||
password: credPassword.c_value
|
||||
}
|
||||
|
||||
if(invoice[key].c_account_code_topup == null || invoice[key].c_account_topup == null) {
|
||||
prepare = {
|
||||
status : false,
|
||||
cms : false,
|
||||
message: "[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP",
|
||||
}
|
||||
}
|
||||
|
||||
if(invoice[key].c_account_code_topup == "" || invoice[key].c_account_topup == "") {
|
||||
prepare = {
|
||||
status : false,
|
||||
cms : false,
|
||||
message: "[CMS] FAILED GET PARTNER ACCOUNT CODE TOPUP / ACCOUNT TOPUP",
|
||||
}
|
||||
}
|
||||
|
||||
let xmlHeader = {
|
||||
doc_header_text: invoice[key].doc_header_text
|
||||
? invoice[key].doc_header_text
|
||||
: "",
|
||||
ba: invoice[key].ba ? invoice[key].ba : "",
|
||||
doc_date: invoice[key].doc_date ? invoice[key].doc_date : "",
|
||||
posting_date: invoice[key].posting_date
|
||||
? invoice[key].posting_date
|
||||
: "",
|
||||
fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : "",
|
||||
fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : "",
|
||||
doc_type: invoice[key].doc_type ? invoice[key].doc_type : "",
|
||||
c_invoice_no: invoice[key].c_invoice_no
|
||||
? invoice[key].c_invoice_no
|
||||
: "",
|
||||
};
|
||||
|
||||
let xmlItem = ["S", "H"].map((item) => {
|
||||
return {
|
||||
c_account_code_topup:
|
||||
item == "S" ? invoice[key].c_account_code_topup : "",
|
||||
c_account_topup: item == "H" ? invoice[key].c_account_topup : "",
|
||||
ba: invoice[key].ba,
|
||||
amount: invoice[key].amount,
|
||||
posting_date: invoice[key].posting_date,
|
||||
c_invoice_no: invoice[key].c_invoice_no,
|
||||
item_text: `${item == "S" ? "DEBIT" : "KREDIT"} INVOICE CMS ${
|
||||
invoice[key].doc_header_text
|
||||
}`,
|
||||
de_cre: item,
|
||||
};
|
||||
});
|
||||
|
||||
let xmlRequest = helper.generateXMLRequest(
|
||||
"ZFMCMS_FI_001",
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}`
|
||||
);
|
||||
|
||||
let response = {}
|
||||
|
||||
if(prepare.status){
|
||||
|
||||
response = await helper.postingSAP(parameter.c_value, xmlRequest, credential);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
|
||||
invoice[key].c_invoice_no
|
||||
} to SAP : ${JSON.stringify(response)}`
|
||||
);
|
||||
}
|
||||
|
||||
// new transaction
|
||||
// await knex.transaction(async (trx) => {
|
||||
|
||||
let resSAP
|
||||
if(prepare.status){
|
||||
resSAP = helper.getXMLData(response);
|
||||
}else {
|
||||
resSAP = {
|
||||
type: 'E',
|
||||
message : prepare?.message || "FAILED GET PARAMETER SETTING",
|
||||
data : {}
|
||||
}
|
||||
}
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
|
||||
resSAP
|
||||
)}`
|
||||
);
|
||||
await wait(1000)
|
||||
const cms = await model.setReturnSAP(invoice[key], resSAP, trx, true, invoice[key].c_invoice_no);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
|
||||
);
|
||||
|
||||
collection.push(cms.invoice[0])
|
||||
|
||||
// });
|
||||
}
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
return collection;
|
||||
};
|
||||
|
||||
const _postingInvoice = async (uniqueCode) => {
|
||||
let postingEt = [];
|
||||
const collection = []
|
||||
postingEt = await model.getPostingEt(knex);
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify(
|
||||
postingEt
|
||||
)}`
|
||||
);
|
||||
|
||||
const credUsername = await model.getParameterSetting(knex, "SAP_AUTH_USERNAME")
|
||||
const credPassword = await model.getParameterSetting(knex, "SAP_AUTH_PASSWORD")
|
||||
const parameter = await model.getParameterSetting(knex, "SAP_FI_URL_FOR_FB70")
|
||||
|
||||
let prepare = {
|
||||
status : true,
|
||||
message: "Success",
|
||||
}
|
||||
|
||||
if(!credUsername) {
|
||||
prepare = {
|
||||
status : false,
|
||||
message: "FAILED GET SETTING FOR SAP_AUTH_USERNAME",
|
||||
}
|
||||
}
|
||||
|
||||
if(!credPassword) {
|
||||
prepare = {
|
||||
status : false,
|
||||
message: "FAILED GET SETTING FOR SAP_AUTH_PASSWORD",
|
||||
}
|
||||
}
|
||||
|
||||
if(!parameter) {
|
||||
prepare = {
|
||||
status : false,
|
||||
message: "FAILED GET SETTING FOR SAP_AUTH_PASSWORD",
|
||||
}
|
||||
}
|
||||
|
||||
const credential = {
|
||||
username: credUsername.c_value,
|
||||
password: credPassword.c_value
|
||||
}
|
||||
|
||||
for (const item of postingEt) {
|
||||
|
||||
await knex.transaction(async (trx) => {
|
||||
|
||||
let response = {}
|
||||
|
||||
let resSAP = {}
|
||||
|
||||
if(prepare.status){
|
||||
|
||||
let xmlHeader = {
|
||||
doc_header_text: item.doc_header_text ? item.doc_header_text : "",
|
||||
ba: item.ba ? item.ba : "",
|
||||
doc_date: item.doc_date ? item.doc_date : "",
|
||||
posting_date: item.posting_date ? item.posting_date : "",
|
||||
fisc_year: item.fiscal_year ? item.fiscal_year : "",
|
||||
fisc_period: item.fis_period ? item.fis_period : "",
|
||||
doc_type: item.doc_type ? item.doc_type : "",
|
||||
c_invoice_no: item.reference ? item.reference : "",
|
||||
};
|
||||
|
||||
let xmlItem = ["S", "H"].map((key) => {
|
||||
return {
|
||||
c_account_code_topup: key == "S" ? item.customer : "",
|
||||
c_account_topup: key == "H" ? item.account : "",
|
||||
ba: item.ba,
|
||||
amount: item.amount,
|
||||
posting_date: item.posting_date,
|
||||
c_invoice_no: item.reference,
|
||||
item_text: key == "S" ? item.text1 : item.text2,
|
||||
de_cre: key,
|
||||
};
|
||||
});
|
||||
|
||||
let xmlRequest = helper.generateXMLRequest(
|
||||
"ZFMCMS_FI_001",
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`
|
||||
);
|
||||
|
||||
response = await helper.postingSAP(parameter.c_value, xmlRequest, credential);
|
||||
|
||||
winston.logger.debug(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
|
||||
item.reference
|
||||
} to SAP : ${JSON.stringify(response)}`
|
||||
);
|
||||
|
||||
resSAP = helper.getXMLData(response);
|
||||
|
||||
}else{
|
||||
resSAP = {
|
||||
type: 'E',
|
||||
message : prepare?.message || "FAILED GET PARAMETER SETTING",
|
||||
data : {}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`);
|
||||
// UPDATE CMS
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
|
||||
resSAP
|
||||
)}`
|
||||
);
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} ITEM REFERENCE ${item.reference}`);
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} URL SAP ${parameter.c_value}`);
|
||||
let invoice = await model.getInvoice(item.reference, trx)
|
||||
await wait(1000)
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RETRY INVOICE ${JSON.stringify(invoice)}`);
|
||||
const cms = await model.setReturnSAP(
|
||||
invoice,
|
||||
resSAP,
|
||||
trx,
|
||||
false,
|
||||
item.reference
|
||||
);
|
||||
await wait(1000)
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
|
||||
);
|
||||
|
||||
collection.push(cms.invoice[0])
|
||||
|
||||
})
|
||||
}
|
||||
|
||||
return collection;
|
||||
};
|
||||
|
||||
function wait(milliseconds) {
|
||||
return new Promise(resolve => setTimeout(resolve, milliseconds));
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
apiPostingInvoice,
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
|
||||
const sapPostingTable = 'payment.t_invoice_sap_posting';
|
||||
|
||||
// GET PARTNER, MERCHANT, TERMINAL FROM TID
|
||||
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(?, ?::boolean)',
|
||||
[invoiceDate, repost]
|
||||
);
|
||||
|
||||
return result;
|
||||
return result.rows || result;
|
||||
|
||||
}
|
||||
|
||||
const insertPostingEt = async (invoice, trx) => {
|
||||
console.log("invoice : ", invoice)
|
||||
let type = ['S', 'H']
|
||||
let et = []
|
||||
let posting_et = []
|
||||
@@ -26,31 +30,35 @@ const insertPostingEt = async (invoice, trx) => {
|
||||
reference: invoice.c_invoice_no,
|
||||
amount: invoice.amount,
|
||||
ba: invoice.ba,
|
||||
indeks: (index+1),
|
||||
indeks: (index + 1),
|
||||
totalidx: type.length,
|
||||
doc_header_text: invoice.c_invoice_no,
|
||||
pos_status : 3
|
||||
pos_status: 3
|
||||
}
|
||||
|
||||
if(item == 'H'){
|
||||
data = {...data, ...{
|
||||
text: `Posting Invoice CMS ${invoice.c_invoice_no}`,
|
||||
debit_kredit: item,
|
||||
account: invoice.c_account_topup,
|
||||
customer: null
|
||||
}}
|
||||
}else{
|
||||
data = {...data, ...{
|
||||
text: `Posting Invoice CMS ${invoice.c_invoice_no}`,
|
||||
debit_kredit: item,
|
||||
account: null,
|
||||
customer: invoice.c_account_code_topup
|
||||
}}
|
||||
|
||||
if (item == 'H') {
|
||||
data = {
|
||||
...data, ...{
|
||||
text: `Posting Invoice CMS ${invoice.c_invoice_no}`,
|
||||
debit_kredit: item,
|
||||
account: invoice.c_account_topup,
|
||||
customer: null
|
||||
}
|
||||
}
|
||||
} else {
|
||||
data = {
|
||||
...data, ...{
|
||||
text: `Posting Invoice CMS ${invoice.c_invoice_no}`,
|
||||
debit_kredit: item,
|
||||
account: null,
|
||||
customer: invoice.c_account_code_topup
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
et.push(data)
|
||||
|
||||
});
|
||||
});
|
||||
|
||||
posting_et = await trx('public.posting_et').insert(et, ['indeks', 'customer', 'account', 'ba', 'fiscal_year', 'amount', 'no_dok', 'text', 'debit_kredit'])
|
||||
|
||||
@@ -58,161 +66,235 @@ const insertPostingEt = async (invoice, trx) => {
|
||||
|
||||
}
|
||||
|
||||
const getPostingEt = async(trx) => {
|
||||
const getPostingEt = async (trx) => {
|
||||
|
||||
const result = await trx('public.posting_et AS pe').select([
|
||||
'doc_header_text',
|
||||
'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])
|
||||
const result = await trx.raw(`
|
||||
WITH params AS (
|
||||
|
||||
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'
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM payment.t_invoice_sap_posting sap
|
||||
WHERE sap.invoice_no = pe.reference
|
||||
)
|
||||
|
||||
-- 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
|
||||
|
||||
}
|
||||
|
||||
const setReturnSAP = async (invoice, resSAP, trx, posting = false, c_invoice_no) => {
|
||||
let t_invoice = {}
|
||||
let t_load_balance = {}
|
||||
let posting_et = {}
|
||||
if(resSAP.type == 'S'){
|
||||
// update invoice
|
||||
t_invoice = await trx('payment.t_d_invoice').update({
|
||||
c_return_sap: resSAP.data.E_DOCUMENTNUMBER
|
||||
}, ["*"])
|
||||
.where({
|
||||
c_invoice_no: c_invoice_no
|
||||
});
|
||||
|
||||
// update load balance
|
||||
t_load_balance = await trx('trx.t_d_load_balance').update({
|
||||
c_return_sap: resSAP.data.E_DOCUMENTNUMBER
|
||||
}, ['c_load_balance_no', 'c_return_sap'])
|
||||
.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}')`)
|
||||
|
||||
posting_et = await trx('public.posting_et').update({
|
||||
pos_status : 0,
|
||||
status0 : resSAP.type,
|
||||
no_doksap : resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null,
|
||||
status1 : resSAP.message ? resSAP.message : null
|
||||
}, ['file_name','status0']).where({
|
||||
reference: c_invoice_no
|
||||
})
|
||||
async function claimSapPosting(db, invoiceNo, initialPosting) {
|
||||
// Dokumen lama yang sudah tercatat di CMS juga tidak boleh dikirim ulang.
|
||||
const invoice = await getInvoice(invoiceNo, db);
|
||||
if (!invoice || invoice.c_return_sap) return false;
|
||||
const postedEntry = await db('public.posting_et')
|
||||
.where({ no_dok: invoiceNo, tcode: 'FB70', pos_status: 0 })
|
||||
.first('no_dok');
|
||||
if (postedEntry) return false;
|
||||
|
||||
if(posting) {
|
||||
await writePaynentHistory(t_invoice[0], "SUCCESSFULLY", 102, trx)
|
||||
} else {
|
||||
await writePaynentHistory(t_invoice[0], "SUCCESS TO RETRY SAP", 118, trx)
|
||||
}
|
||||
const inserted = await db(sapPostingTable)
|
||||
.insert({ invoice_no: invoiceNo, state: 'sending', initial_posting: initialPosting })
|
||||
.onConflict('invoice_no').ignore()
|
||||
.returning('invoice_no');
|
||||
return inserted.length === 1;
|
||||
}
|
||||
|
||||
}else {
|
||||
function releaseUnsentPosting(db, invoiceNo) {
|
||||
return db(sapPostingTable).where({ invoice_no: invoiceNo, state: 'sending' }).del();
|
||||
}
|
||||
|
||||
let text = resSAP.message;
|
||||
let result = text.toUpperCase();
|
||||
|
||||
if(result.includes("ALREADY")){
|
||||
let result = text.toUpperCase().split('-');
|
||||
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({
|
||||
pos_status : 0,
|
||||
status0 : 'S',
|
||||
no_doksap : doc_number,
|
||||
status1 : resSAP.message ? resSAP.message : null
|
||||
}, ['file_name','status0']).where({
|
||||
reference: c_invoice_no
|
||||
function recordSapOutcome(db, invoiceNo, documentNo, outcome) {
|
||||
return db.transaction(async (trx) => {
|
||||
const [posting] = await trx(sapPostingTable)
|
||||
.where({ invoice_no: invoiceNo, state: 'sending' })
|
||||
.update({
|
||||
state: documentNo ? 'accepted' : 'unknown',
|
||||
document_no: documentNo,
|
||||
outcome,
|
||||
updated_at: trx.fn.now(),
|
||||
})
|
||||
.returning('initial_posting');
|
||||
if (!posting || documentNo) return;
|
||||
|
||||
// update invoice
|
||||
t_invoice = await trx('payment.t_d_invoice').update({
|
||||
c_return_sap: doc_number
|
||||
}, ['*'])
|
||||
.where({
|
||||
c_invoice_no: c_invoice_no
|
||||
});
|
||||
|
||||
// update load balance
|
||||
t_load_balance = await trx('trx.t_d_load_balance').update({
|
||||
c_return_sap: doc_number
|
||||
}, ['c_load_balance_no', 'c_return_sap'])
|
||||
.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}')`)
|
||||
|
||||
if(posting) {
|
||||
await writePaynentHistory(t_invoice[0], "SUCCESSFULLY", 102, trx)
|
||||
} else {
|
||||
await writePaynentHistory(t_invoice[0], "SUCCESS TO RETRY SAP", 118, trx)
|
||||
}
|
||||
|
||||
}else{
|
||||
// update posting et
|
||||
posting_et = await trx('public.posting_et').update({
|
||||
pos_status : resSAP.type == 'S' ? 0 : 3,
|
||||
status0 : resSAP.type,
|
||||
no_doksap : resSAP.data.E_DOCUMENTNUMBER ? resSAP.data.E_DOCUMENTNUMBER : null,
|
||||
status1 : resSAP.message ? resSAP.message : null
|
||||
}, ['file_name','status0']).where({
|
||||
reference: c_invoice_no
|
||||
})
|
||||
|
||||
// update invoice
|
||||
t_invoice = await trx('payment.t_d_invoice').select(['*'])
|
||||
.where({
|
||||
c_invoice_no: c_invoice_no
|
||||
});
|
||||
|
||||
if(posting) {
|
||||
await writePaynentHistory(t_invoice[0], `SUCCESS WITH SAP ERR: ${resSAP.message}`,102, trx)
|
||||
} else {
|
||||
await writePaynentHistory(t_invoice[0], `FAIL TO RETRY WITH SAP ERR: ${resSAP.message}`,118, trx)
|
||||
}
|
||||
|
||||
await trx('public.posting_et')
|
||||
.where({ no_dok: invoiceNo, tcode: 'FB70', pos_status: 3 })
|
||||
.update({ status0: 'E', status1: outcome });
|
||||
const invoice = await getInvoice(invoiceNo, trx);
|
||||
if (invoice) {
|
||||
await writePaynentHistory(
|
||||
invoice,
|
||||
`SAP reconciliation required: ${outcome}`,
|
||||
posting.initial_posting ? 102 : 118,
|
||||
trx
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
function getAcceptedSapPostings(db) {
|
||||
return db(sapPostingTable).where({ state: 'accepted' }).orderBy('invoice_no').pluck('invoice_no');
|
||||
}
|
||||
|
||||
// update posting et
|
||||
// Klaim finalisasi dan seluruh perubahan lokal di-commit bersama.
|
||||
async function finishSapPosting(db, invoiceNo) {
|
||||
return db.transaction(async (trx) => {
|
||||
const [posting] = await trx(sapPostingTable)
|
||||
.where({ invoice_no: invoiceNo, state: 'accepted' })
|
||||
.update({ state: 'completed', updated_at: trx.fn.now() })
|
||||
.returning(['document_no', 'initial_posting']);
|
||||
if (!posting) return null;
|
||||
|
||||
return {
|
||||
invoice : t_invoice,
|
||||
load_balance : t_load_balance,
|
||||
posting_et : posting_et
|
||||
}
|
||||
|
||||
const { document_no: documentNo, initial_posting: initialPosting } = posting;
|
||||
const [invoice] = await trx('payment.t_d_invoice')
|
||||
.where('c_invoice_no', invoiceNo)
|
||||
.where(function () {
|
||||
this.whereNull('c_return_sap').orWhereIn('c_return_sap', ['', documentNo]);
|
||||
})
|
||||
.update({ c_return_sap: documentNo })
|
||||
.returning('*');
|
||||
if (!invoice) throw new Error('Invoice missing or already associated with a different SAP document');
|
||||
|
||||
const paymentRequests = trx('payment.t_d_payment_request_topup_online')
|
||||
.where('c_payment', invoiceNo)
|
||||
.select('c_load_balance_no');
|
||||
await trx('trx.t_d_load_balance')
|
||||
.whereIn('c_load_balance_no', paymentRequests)
|
||||
.update({ c_return_sap: documentNo });
|
||||
await trx('public.posting_et')
|
||||
.where({ no_dok: invoiceNo, tcode: 'FB70', pos_status: 3 })
|
||||
.update({
|
||||
pos_status: 0,
|
||||
status0: 'S',
|
||||
no_doksap: documentNo,
|
||||
status1: 'SAP document confirmed',
|
||||
});
|
||||
await writePaynentHistory(
|
||||
invoice,
|
||||
initialPosting ? 'SUCCESSFULLY' : 'SUCCESS TO RETRY SAP',
|
||||
initialPosting ? 102 : 118,
|
||||
trx
|
||||
);
|
||||
return invoice;
|
||||
});
|
||||
}
|
||||
|
||||
const writePaynentHistory = async (data, message, i_log_name, trx) => {
|
||||
console.log(data)
|
||||
const result = await trx('log.t_log_invoice').insert({
|
||||
// i_log_name : 102,
|
||||
i_log_name : i_log_name,
|
||||
d_log : trx.raw('NOW()'),
|
||||
c_invoice_no : data?.c_invoice_no || '',
|
||||
c_partner_name : data?.c_partner_name || '',
|
||||
j_new_data : JSON.stringify(data),
|
||||
i_log_name: i_log_name,
|
||||
d_log: trx.raw('NOW()'),
|
||||
c_invoice_no: data?.c_invoice_no || '',
|
||||
c_partner_name: data?.c_partner_name || '',
|
||||
j_new_data: JSON.stringify(data),
|
||||
d_payment_date: trx.raw('NOW()'),
|
||||
c_note : message,
|
||||
c_status : 'S',
|
||||
d_created : trx.raw('NOW()'),
|
||||
m_amount : data?.amount || 0,
|
||||
m_mdr_amount : 0,
|
||||
m_mdr_net : data?.amount || 0
|
||||
c_note: message,
|
||||
c_status: 'S',
|
||||
d_created: trx.raw('NOW()'),
|
||||
m_amount: data?.amount || 0,
|
||||
m_mdr_amount: 0,
|
||||
m_mdr_net: data?.amount || 0
|
||||
|
||||
}, ['i_log_name', 'c_note'])
|
||||
|
||||
@@ -220,24 +302,24 @@ const writePaynentHistory = async (data, message, i_log_name, trx) => {
|
||||
|
||||
}
|
||||
|
||||
const getParameterSetting = async(trx, code) => {
|
||||
|
||||
const result = await trx('public.t_m_global_parameter_sap AS tmgps').select([
|
||||
"c_value"
|
||||
])
|
||||
.where('c_code', '=', code)
|
||||
.where('c_status', '=', "A")
|
||||
.first()
|
||||
|
||||
return result
|
||||
|
||||
async function getSapSettings(db) {
|
||||
const codes = {
|
||||
SAP_FI_URL_FOR_FB70: 'url',
|
||||
SAP_AUTH_USERNAME: 'username',
|
||||
SAP_AUTH_PASSWORD: 'password',
|
||||
};
|
||||
const rows = await db('public.t_m_global_parameter_sap')
|
||||
.where('c_status', 'A')
|
||||
.whereIn('c_code', Object.keys(codes))
|
||||
.select('c_code', 'c_value');
|
||||
return Object.fromEntries(rows.map(({ c_code, c_value }) => [codes[c_code], c_value]));
|
||||
}
|
||||
|
||||
const getInvoice = async(code, trx) => {
|
||||
const getInvoice = async (code, trx) => {
|
||||
|
||||
const result = await trx('payment.t_d_invoice')
|
||||
.where('c_invoice_no', '=', code)
|
||||
.first()
|
||||
const result = await trx('payment.t_d_invoice')
|
||||
.where('c_invoice_no', '=', code)
|
||||
.first()
|
||||
|
||||
return result
|
||||
|
||||
@@ -246,9 +328,13 @@ const getInvoice = async(code, trx) => {
|
||||
module.exports = {
|
||||
generateInvoice,
|
||||
insertPostingEt,
|
||||
setReturnSAP,
|
||||
claimSapPosting,
|
||||
releaseUnsentPosting,
|
||||
recordSapOutcome,
|
||||
getAcceptedSapPostings,
|
||||
finishSapPosting,
|
||||
getPostingEt,
|
||||
writePaynentHistory,
|
||||
getParameterSetting,
|
||||
getSapSettings,
|
||||
getInvoice
|
||||
};
|
||||
};
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const helper = require('../../helpers/helper');
|
||||
const model = require('./invoice.model');
|
||||
|
||||
// Simpan data invoice sebelum mengirim dokumen ke SAP.
|
||||
const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
let invoice = [];
|
||||
|
||||
await knex.transaction(async (trx) => {
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} execute payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`
|
||||
);
|
||||
|
||||
invoice = await model.generateInvoice(invoiceDate, repost, trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} result payment.sp_payment_req_topup_online count=${invoice.length}`
|
||||
);
|
||||
|
||||
if (invoice.length > 0)
|
||||
for (const key in invoice) {
|
||||
await model.writePaynentHistory(invoice[key], trx);
|
||||
await model.insertPostingEt(invoice[key], trx);
|
||||
}
|
||||
});
|
||||
|
||||
if (invoice.length > 0) {
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`
|
||||
);
|
||||
|
||||
const url =
|
||||
'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2';
|
||||
|
||||
for (const key in invoice) {
|
||||
const xmlHeader = {
|
||||
doc_header_text: invoice[key].doc_header_text
|
||||
? invoice[key].doc_header_text
|
||||
: '',
|
||||
ba: invoice[key].ba ? invoice[key].ba : '',
|
||||
doc_date: invoice[key].doc_date ? invoice[key].doc_date : '',
|
||||
posting_date: invoice[key].posting_date
|
||||
? invoice[key].posting_date
|
||||
: '',
|
||||
fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : '',
|
||||
fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : '',
|
||||
doc_type: invoice[key].doc_type ? invoice[key].doc_type : '',
|
||||
c_invoice_no: invoice[key].c_invoice_no
|
||||
? invoice[key].c_invoice_no
|
||||
: '',
|
||||
};
|
||||
|
||||
const xmlItem = ['S', 'H'].map((item) => {
|
||||
return {
|
||||
c_account_code_topup:
|
||||
item === 'S' ? invoice[key].c_account_code_topup : '',
|
||||
c_account_topup: item === 'H' ? invoice[key].c_account_topup : '',
|
||||
ba: invoice[key].ba,
|
||||
amount: invoice[key].amount,
|
||||
posting_date: invoice[key].posting_date,
|
||||
c_invoice_no: invoice[key].c_invoice_no,
|
||||
item_text: `${item === 'S' ? 'DEBIT' : 'KREDIT'} INVOICE CMS ${
|
||||
invoice[key].doc_header_text
|
||||
}`,
|
||||
de_cre: item,
|
||||
};
|
||||
});
|
||||
|
||||
const xmlRequest = helper.generateXMLRequest(
|
||||
'ZFMCMS_FI_001',
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
|
||||
winston.logger.debug(
|
||||
`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP`
|
||||
);
|
||||
|
||||
const response = await helper.postingSAP(url, xmlRequest);
|
||||
|
||||
winston.logger.debug(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
|
||||
invoice[key].c_invoice_no
|
||||
} from SAP`
|
||||
);
|
||||
|
||||
// new transaction
|
||||
await knex.transaction(async (trx) => {
|
||||
const resSAP = helper.getXMLData(response);
|
||||
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 2`);
|
||||
// UPDATE CMS
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} SAP outcome type=${resSAP.type}`
|
||||
);
|
||||
|
||||
await model.setReturnSAP(invoice[key], resSAP, trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} CMS update completed`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return invoice;
|
||||
};
|
||||
|
||||
const _postingInvoice = async (uniqueCode) => {
|
||||
let postingEt = [];
|
||||
await knex.transaction(async (trx) => {
|
||||
postingEt = await model.getPostingEt(trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} GET POSTING ET count=${postingEt.length}`
|
||||
);
|
||||
|
||||
// Retry lama menyimpan hasil seluruh batch dalam satu transaksi.
|
||||
for (const item of postingEt) {
|
||||
const xmlHeader = {
|
||||
doc_header_text: item.doc_header_text ? item.doc_header_text : '',
|
||||
ba: item.ba ? item.ba : '',
|
||||
doc_date: item.doc_date ? item.doc_date : '',
|
||||
posting_date: item.posting_date ? item.posting_date : '',
|
||||
fisc_year: item.fiscal_year ? item.fiscal_year : '',
|
||||
fisc_period: item.fis_period ? item.fis_period : '',
|
||||
doc_type: item.doc_type ? item.doc_type : '',
|
||||
c_invoice_no: item.reference ? item.reference : '',
|
||||
};
|
||||
|
||||
const xmlItem = ['S', 'H'].map((key) => {
|
||||
return {
|
||||
c_account_code_topup: key === 'S' ? item.customer : '',
|
||||
c_account_topup: key === 'H' ? item.account : '',
|
||||
ba: item.ba,
|
||||
amount: item.amount,
|
||||
posting_date: item.posting_date,
|
||||
c_invoice_no: item.reference,
|
||||
item_text: key === 'S' ? item.text1 : item.text2,
|
||||
de_cre: key,
|
||||
};
|
||||
});
|
||||
|
||||
const xmlRequest = helper.generateXMLRequest(
|
||||
'ZFMCMS_FI_001',
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP`
|
||||
);
|
||||
|
||||
const url =
|
||||
'http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2';
|
||||
|
||||
const response = await helper.postingSAP(url, xmlRequest);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${
|
||||
item.reference
|
||||
} from SAP`
|
||||
);
|
||||
|
||||
const resSAP = helper.getXMLData(response);
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`);
|
||||
// UPDATE CMS
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} SAP outcome type=${resSAP.type}`
|
||||
);
|
||||
|
||||
await model.setReturnSAP(
|
||||
{ c_invoice_no: item.reference },
|
||||
resSAP,
|
||||
trx
|
||||
);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} CMS update completed`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
return postingEt;
|
||||
};
|
||||
|
||||
module.exports = { _generateInvoice, _postingInvoice };
|
||||
@@ -1,38 +1,37 @@
|
||||
const { param, body, validationResult } = require("express-validator");
|
||||
const helper = require("../../helpers/helper");
|
||||
const winston = require("../../helpers/winston.logger");
|
||||
const model = require("./invoice.model");
|
||||
const moment = require("moment");
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
moment.locale("id");
|
||||
const { body, validationResult } = require('express-validator');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const moment = require('moment');
|
||||
const { _generateInvoice, _postingInvoice } = require('./invoice-posting.service');
|
||||
moment.locale('id');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case "generateInvoice":
|
||||
case 'generateInvoice':
|
||||
return [
|
||||
body("trx_date")
|
||||
body('trx_date')
|
||||
.notEmpty()
|
||||
.withMessage("trx_date is required!")
|
||||
.withMessage('trx_date is required!')
|
||||
.isISO8601()
|
||||
.withMessage("invalid trx_date format YYYY-MM-DD !")
|
||||
.withMessage('invalid trx_date format YYYY-MM-DD !')
|
||||
.escape()
|
||||
.trim(),
|
||||
body("repost")
|
||||
body('repost')
|
||||
.notEmpty()
|
||||
.withMessage("repost is required!")
|
||||
.withMessage('repost is required!')
|
||||
.isBoolean()
|
||||
.withMessage("repost must boolean!")
|
||||
.withMessage('repost must boolean!')
|
||||
.escape()
|
||||
.trim(),
|
||||
];
|
||||
case "postingInvoice":
|
||||
case 'postingInvoice':
|
||||
return [
|
||||
body("trx_date")
|
||||
body('trx_date')
|
||||
.notEmpty()
|
||||
.withMessage("trx_date is required!")
|
||||
.withMessage('trx_date is required!')
|
||||
.isISO8601()
|
||||
.withMessage("invalid trx_date format YYYY-MM-DD !")
|
||||
.withMessage('invalid trx_date format YYYY-MM-DD !')
|
||||
.escape()
|
||||
.trim(),
|
||||
];
|
||||
@@ -50,28 +49,28 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST generate invoice: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} REQUEST generate invoice`
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: "400",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE generate invoice: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} RESPONSE generate invoice code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// time
|
||||
let invoiceDate = moment(req.body.trx_date).format("YYYY-MM-DD");
|
||||
let invoiceDate = moment(req.body.trx_date).format('YYYY-MM-DD');
|
||||
|
||||
let invoice = await _generateInvoice(
|
||||
invoiceDate,
|
||||
@@ -80,8 +79,8 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
result = {
|
||||
code: "200",
|
||||
message: "Succes posting",
|
||||
code: '200',
|
||||
message: 'Succes posting',
|
||||
data: invoice,
|
||||
};
|
||||
|
||||
@@ -93,11 +92,11 @@ const apiGenerateInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
@@ -112,21 +111,21 @@ const apiPostingInvoice = async (req, res) => {
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} REQUEST posting invoice: ${JSON.stringify(req.body)}`
|
||||
`${uniqueCode} REQUEST posting invoice`
|
||||
);
|
||||
|
||||
// check validator
|
||||
const err = validationResult(req, res);
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: "400",
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} RESPONSE generate invoice: ${JSON.stringify(result)}`
|
||||
`${uniqueCode} RESPONSE generate invoice code=${result.code}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
@@ -135,11 +134,11 @@ const apiPostingInvoice = async (req, res) => {
|
||||
// return uniqueCode
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} RE-TRY POSTING INVOICE`);
|
||||
|
||||
const invoice = await _postingInvoice(uniqueCode);
|
||||
let invoice = await _postingInvoice(uniqueCode);
|
||||
|
||||
result = {
|
||||
code: "200",
|
||||
message: "Succes",
|
||||
code: '200',
|
||||
message: 'Succes',
|
||||
data: invoice,
|
||||
};
|
||||
|
||||
@@ -151,236 +150,16 @@ const apiPostingInvoice = async (req, res) => {
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: "500",
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != "production"
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: "500 internal server error - backend server.",
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const _generateInvoice = async (invoiceDate, uniqueCode, repost) => {
|
||||
let invoice = [];
|
||||
|
||||
await knex.transaction(async (trx) => {
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 1`);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} execute payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`
|
||||
);
|
||||
|
||||
invoice = await model.generateInvoice(invoiceDate, repost, trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} result payment.sp_payment_req_topup_online ${JSON.stringify(
|
||||
invoice
|
||||
)}`
|
||||
);
|
||||
|
||||
if (invoice.length > 0)
|
||||
for (const key in invoice) {
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} insert payment history et : ${JSON.stringify(
|
||||
invoice
|
||||
)}`
|
||||
);
|
||||
|
||||
let history = await model.writePaynentHistory(invoice[key], trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} result insert payment history et : ${JSON.stringify(
|
||||
history
|
||||
)}`
|
||||
);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} insert posting et ${JSON.stringify(
|
||||
invoice[key]
|
||||
)}`
|
||||
);
|
||||
|
||||
let postingEt = await model.insertPostingEt(invoice[key], trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} success insert posting et : ${JSON.stringify(
|
||||
postingEt
|
||||
)}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
if (invoice.length > 0) {
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} preparing posting FB70 to SAP`
|
||||
);
|
||||
|
||||
const url =
|
||||
"http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2";
|
||||
|
||||
for (const key in invoice) {
|
||||
let xmlHeader = {
|
||||
doc_header_text: invoice[key].doc_header_text
|
||||
? invoice[key].doc_header_text
|
||||
: "",
|
||||
ba: invoice[key].ba ? invoice[key].ba : "",
|
||||
doc_date: invoice[key].doc_date ? invoice[key].doc_date : "",
|
||||
posting_date: invoice[key].posting_date
|
||||
? invoice[key].posting_date
|
||||
: "",
|
||||
fisc_year: invoice[key].fisc_year ? invoice[key].fisc_year : "",
|
||||
fisc_period: invoice[key].fisc_period ? invoice[key].fisc_period : "",
|
||||
doc_type: invoice[key].doc_type ? invoice[key].doc_type : "",
|
||||
c_invoice_no: invoice[key].c_invoice_no
|
||||
? invoice[key].c_invoice_no
|
||||
: "",
|
||||
};
|
||||
|
||||
let xmlItem = ["S", "H"].map((item) => {
|
||||
return {
|
||||
c_account_code_topup:
|
||||
item == "S" ? invoice[key].c_account_code_topup : "",
|
||||
c_account_topup: item == "H" ? invoice[key].c_account_topup : "",
|
||||
ba: invoice[key].ba,
|
||||
amount: invoice[key].amount,
|
||||
posting_date: invoice[key].posting_date,
|
||||
c_invoice_no: invoice[key].c_invoice_no,
|
||||
item_text: `${item == "S" ? "DEBIT" : "KREDIT"} INVOICE CMS ${
|
||||
invoice[key].doc_header_text
|
||||
}`,
|
||||
de_cre: item,
|
||||
};
|
||||
});
|
||||
|
||||
let xmlRequest = helper.generateXMLRequest(
|
||||
"ZFMCMS_FI_001",
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
|
||||
winston.logger.debug(
|
||||
`SCHEDULER-FB70-${uniqueCode} REQUEST posting ${invoice[key].c_invoice_no} to SAP : ${xmlRequest}`
|
||||
);
|
||||
|
||||
const response = await helper.postingSAP(url, xmlRequest);
|
||||
|
||||
winston.logger.debug(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESPONSE posting ${
|
||||
invoice[key].c_invoice_no
|
||||
} to SAP : ${JSON.stringify(response)}`
|
||||
);
|
||||
|
||||
// new transaction
|
||||
await knex.transaction(async (trx) => {
|
||||
const resSAP = helper.getXMLData(response);
|
||||
|
||||
winston.logger.info(`SCHEDULER-FB70-${uniqueCode} TRANSACTION 2`);
|
||||
// UPDATE CMS
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
|
||||
resSAP
|
||||
)}`
|
||||
);
|
||||
|
||||
const cms = await model.setReturnSAP(invoice[key], resSAP, trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-FB70-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
|
||||
);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return invoice;
|
||||
};
|
||||
|
||||
const _postingInvoice = async (uniqueCode) => {
|
||||
let postingEt = [];
|
||||
await knex.transaction(async (trx) => {
|
||||
postingEt = await model.getPostingEt(trx);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} GET POSTING ET : ${JSON.stringify(
|
||||
postingEt
|
||||
)}`
|
||||
);
|
||||
|
||||
for (const item of postingEt) {
|
||||
let xmlHeader = {
|
||||
doc_header_text: item.doc_header_text ? item.doc_header_text : "",
|
||||
ba: item.ba ? item.ba : "",
|
||||
doc_date: item.doc_date ? item.doc_date : "",
|
||||
posting_date: item.posting_date ? item.posting_date : "",
|
||||
fisc_year: item.fiscal_year ? item.fiscal_year : "",
|
||||
fisc_period: item.fis_period ? item.fis_period : "",
|
||||
doc_type: item.doc_type ? item.doc_type : "",
|
||||
c_invoice_no: item.reference ? item.reference : "",
|
||||
};
|
||||
|
||||
let xmlItem = ["S", "H"].map((key) => {
|
||||
return {
|
||||
c_account_code_topup: key == "S" ? item.customer : "",
|
||||
c_account_topup: key == "H" ? item.account : "",
|
||||
ba: item.ba,
|
||||
amount: item.amount,
|
||||
posting_date: item.posting_date,
|
||||
c_invoice_no: item.reference,
|
||||
item_text: key == "S" ? item.text1 : item.text2,
|
||||
de_cre: key,
|
||||
};
|
||||
});
|
||||
|
||||
let xmlRequest = helper.generateXMLRequest(
|
||||
"ZFMCMS_FI_001",
|
||||
xmlHeader,
|
||||
xmlItem
|
||||
);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} REQUEST posting ${item.reference} to SAP : ${xmlRequest}`
|
||||
);
|
||||
|
||||
const url =
|
||||
"http://piqas.kereta-api.co.id:51500/XISOAPAdapter/MessageServlet?senderParty=&senderService=KCI_ETICKETING_2&receiverParty=&receiverService=&interface=SI_KCI_CMS_FI01&interfaceNamespace=urn:Posting_ETicketing_2";
|
||||
|
||||
const response = await helper.postingSAP(url, xmlRequest);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} RESPONSE posting ${
|
||||
item.reference
|
||||
} to SAP : ${JSON.stringify(response)}`
|
||||
);
|
||||
|
||||
// new transaction
|
||||
// await knex.transaction(async trx => {
|
||||
|
||||
const resSAP = helper.getXMLData(response);
|
||||
|
||||
winston.logger.info(`SCHEDULER-RETRY-${uniqueCode} TRANSACTION 2`);
|
||||
// UPDATE CMS
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} SET resposn FB70 to CMS : ${JSON.stringify(
|
||||
resSAP
|
||||
)}`
|
||||
);
|
||||
|
||||
const cms = await model.setReturnSAP(
|
||||
{ c_invoice_no: item.reference },
|
||||
resSAP,
|
||||
trx
|
||||
);
|
||||
|
||||
winston.logger.info(
|
||||
`SCHEDULER-RETRY-${uniqueCode} RESULT CMS : ${JSON.stringify(cms)}`
|
||||
);
|
||||
// })
|
||||
}
|
||||
});
|
||||
|
||||
return postingEt;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
apiPostingInvoice,
|
||||
|
||||
@@ -2,14 +2,16 @@
|
||||
// GET PARTNER, MERCHANT, TERMINAL FROM TID
|
||||
const generateInvoice = async (invoiceDate, repost, trx) => {
|
||||
|
||||
let result = await trx.select(trx.raw(`* FROM payment.sp_payment_req_topup_online('${invoiceDate}', ${repost})`))
|
||||
const result = await trx.raw(
|
||||
'SELECT * FROM payment.sp_payment_req_topup_online(?, ?::boolean)',
|
||||
[invoiceDate, repost]
|
||||
)
|
||||
|
||||
return result;
|
||||
return result.rows || result;
|
||||
|
||||
}
|
||||
|
||||
const insertPostingEt = async (invoice, trx) => {
|
||||
console.log("invoice : ", invoice)
|
||||
let type = ['S', 'H']
|
||||
let et = []
|
||||
let posting_et = []
|
||||
@@ -103,7 +105,9 @@ const setReturnSAP = async (invoice, resSAP, trx) => {
|
||||
t_load_balance = await trx('trx.t_d_load_balance').update({
|
||||
c_return_sap: resSAP.data.E_DOCUMENTNUMBER
|
||||
}, ['c_load_balance_no', 'c_return_sap'])
|
||||
.whereRaw(`c_load_balance_no IN (SELECT c_load_balance_no FROM payment.t_d_payment_request_topup_online WHERE c_payment = '${invoice.c_invoice_no}')`)
|
||||
.whereIn('c_load_balance_no', trx('payment.t_d_payment_request_topup_online')
|
||||
.select('c_load_balance_no')
|
||||
.where('c_payment', invoice.c_invoice_no));
|
||||
|
||||
}
|
||||
|
||||
@@ -126,7 +130,6 @@ const setReturnSAP = async (invoice, resSAP, trx) => {
|
||||
}
|
||||
|
||||
const writePaynentHistory = async (data, trx) => {
|
||||
console.log(data)
|
||||
const result = await trx('log.t_log_invoice').insert({
|
||||
i_log_name : 102,
|
||||
d_log : trx.raw('NOW()'),
|
||||
@@ -153,4 +156,4 @@ module.exports = {
|
||||
setReturnSAP,
|
||||
getPostingEt,
|
||||
writePaynentHistory
|
||||
};
|
||||
};
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,4 +1,9 @@
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
const createTransactionNumberAllocator = require('../../../infrastructure/database/transaction-number');
|
||||
const allocateTransactionNumber = createTransactionNumberAllocator(knex);
|
||||
|
||||
const allocateLoadBalanceNumber = (partnerCode, date) => allocateTransactionNumber('LBL', partnerCode, date);
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
|
||||
// CHECK CARD NUMBER
|
||||
const checkCardNumber = (cardNumber) => {
|
||||
@@ -44,13 +49,27 @@ const getPartner = (mid, tid) => {
|
||||
// GET ISSUER
|
||||
const getIssuer = (id) => {
|
||||
let result = knex('t_c_partner_fee')
|
||||
.select('i_issuer_fee_perc', 'i_channel_fee_perc')
|
||||
.select(
|
||||
'i_issuer_fee_perc',
|
||||
'i_channel_fee_perc',
|
||||
'i_issuer_fee_nominal',
|
||||
'i_channel_fee_nominal'
|
||||
)
|
||||
.where('i_partner', id)
|
||||
.where('c_status', 'A')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET IS CARD ADDED TO BLACKLIST
|
||||
const getCardBlacklist = (card_number) => {
|
||||
let result = knex('public.t_m_card_blacklist')
|
||||
.select('c_status')
|
||||
.where('c_card_number', card_number)
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET CHECKING CARD PRODUCT FROM GLOBAL PARAMETER
|
||||
const getCheckByCardProductStatusValue = () => {
|
||||
let result = knex('t_m_global_parameter')
|
||||
@@ -93,7 +112,14 @@ const getReservationPendingV2 = (cardNumber, time, flag) => {
|
||||
.whereIn('c_status', ['P', 'I'])
|
||||
// .where("d_expired", ">=", time)
|
||||
.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 () {
|
||||
this.orWhere('c_flag', flag).orWhere('c_flag', '-1');
|
||||
@@ -104,7 +130,24 @@ const getReservationPendingV2 = (cardNumber, time, flag) => {
|
||||
|
||||
// GET RESERVATION PENDING WITH COMPARE FLAG COUNTER
|
||||
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")
|
||||
// .count("* as total_reservation")
|
||||
.select(
|
||||
@@ -118,6 +161,8 @@ const getReservationPendingWithFlagCounter = (cardNumber, time, flag) => {
|
||||
.whereRaw('??::INT < ??', ['c_flag', parseInt(flag)])
|
||||
// .where("d_expired", ">=", time)
|
||||
.where('c_flag', '!=', '-1');
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
@@ -136,7 +181,14 @@ const getReservationPendingWithFlagCounterV2 = (cardNumber, time, flag) => {
|
||||
.whereIn('c_status', ['P', 'I'])
|
||||
.whereRaw('??::INT < ??', ['c_flag', parseInt(flag)])
|
||||
.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('c_flag', '!=', '-1');
|
||||
@@ -164,7 +216,14 @@ const getReservationPendingWithFlagV2 = (cardNumber, time) => {
|
||||
.where('c_card_number', cardNumber)
|
||||
.whereIn('c_status', ['P', 'I'])
|
||||
.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');
|
||||
return result;
|
||||
@@ -244,28 +303,45 @@ let inquiryByCardNumber = (cardNumber, startDate, endDate) => {
|
||||
return result;
|
||||
};
|
||||
|
||||
// FIND RESERVATION LOADED
|
||||
const findReservationLoaded = (reservationID) => {
|
||||
let result = knex('trx.t_d_load_balance')
|
||||
.leftJoin(
|
||||
'trx.t_d_load_balance_detail',
|
||||
'trx.t_d_load_balance.i_load_balance',
|
||||
'trx.t_d_load_balance_detail.i_load_balance'
|
||||
// Satu query untuk reservasi dan hasil load aktif yang relevan dengan tahap validasi.
|
||||
function findReservationsWithLoadedBalance(reservationNumbers) {
|
||||
return knex('trx.t_d_reservation_balance as reservation')
|
||||
.distinctOn('reservation.c_reservation_no')
|
||||
.select(
|
||||
'reservation.c_reservation_no',
|
||||
'loaded.i_load_balance as loaded_id',
|
||||
'loaded.c_load_balance_no as loaded_number',
|
||||
'loaded.d_load_balance as loaded_at'
|
||||
)
|
||||
.where('trx.t_d_load_balance_detail.i_reservation_balance', reservationID)
|
||||
.where('trx.t_d_load_balance.c_status', 'A')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
.joinRaw(`
|
||||
LEFT JOIN LATERAL (
|
||||
SELECT balance.i_load_balance, balance.c_load_balance_no, balance.d_load_balance
|
||||
FROM trx.t_d_load_balance_detail detail
|
||||
JOIN trx.t_d_load_balance balance ON balance.i_load_balance = detail.i_load_balance
|
||||
WHERE detail.i_reservation_balance = reservation.i_reservation_balance
|
||||
AND reservation.c_status = 'A'
|
||||
AND balance.c_status = 'A'
|
||||
ORDER BY balance.i_load_balance
|
||||
LIMIT 1
|
||||
) loaded ON TRUE
|
||||
`)
|
||||
.whereIn('reservation.c_reservation_no', reservationNumbers)
|
||||
.where('reservation.c_status', '!=', 'X')
|
||||
.orderBy(['reservation.c_reservation_no', 'reservation.i_reservation_balance']);
|
||||
}
|
||||
|
||||
// FIND RESERVATION
|
||||
const findReservation = (reservationNumber) => {
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.where('c_reservation_no', reservationNumber)
|
||||
function findReservationDetails(reservationNumbers) {
|
||||
return knex('trx.t_d_reservation_balance')
|
||||
.distinctOn('c_reservation_no')
|
||||
.select(
|
||||
'c_reservation_no', 'i_reservation_balance', 'i_reservation_amount',
|
||||
'i_issuer', 'c_issuer_code', 'c_issuer_name', 'i_issuer_fee',
|
||||
'i_channel', 'c_channel_code', 'c_channel_name', 'i_channel_fee'
|
||||
)
|
||||
.whereIn('c_reservation_no', reservationNumbers)
|
||||
.where('c_status', '!=', 'X')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
.orderBy(['c_reservation_no', 'i_reservation_balance']);
|
||||
}
|
||||
|
||||
// INSERT LOADING BALANCE
|
||||
const insertLoadingBalance = async (
|
||||
@@ -281,16 +357,17 @@ const insertLoadingBalance = async (
|
||||
) => {
|
||||
return await knex
|
||||
.transaction((trx) => {
|
||||
knex('trx.t_d_load_balance')
|
||||
// Mengembalikan chain memastikan kegagalan SQL memicu rollback otomatis.
|
||||
return knex('trx.t_d_load_balance')
|
||||
.transacting(trx)
|
||||
.insert(data)
|
||||
.returning('i_load_balance')
|
||||
.then((resp) => {
|
||||
let id = resp[0];
|
||||
let id = typeof resp[0] === 'object' ? resp[0].i_load_balance : resp[0];
|
||||
let loadDetail = [];
|
||||
detail.forEach((element) => {
|
||||
loadDetail.push({
|
||||
i_load_balance: id,
|
||||
i_load_balance: id ? id : id.i_load_balance,
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_amount,
|
||||
@@ -318,11 +395,11 @@ const insertLoadingBalance = async (
|
||||
.insert(data);
|
||||
})
|
||||
.then((history) => {
|
||||
let id = history[0];
|
||||
let id = typeof history[0] === 'object' ? history[0].i_load_balance : history[0];
|
||||
let loadDetail = [];
|
||||
detail.forEach((element) => {
|
||||
loadDetail.push({
|
||||
i_load_balance: id,
|
||||
i_load_balance: id ? id : id.i_load_balance,
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_amount,
|
||||
@@ -377,16 +454,13 @@ const insertLoadingBalance = async (
|
||||
i_balance: balance,
|
||||
c_flag: flag,
|
||||
});
|
||||
})
|
||||
.then(trx.commit)
|
||||
.catch(trx.rollback);
|
||||
});
|
||||
})
|
||||
.then((result) => {
|
||||
// console.log(result);
|
||||
return result.rowCount;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
winston.logger.error(`Load balance insert rolled back | sqlstate=${error.code || 'UNKNOWN'}`);
|
||||
return error.message;
|
||||
});
|
||||
};
|
||||
@@ -457,7 +531,7 @@ const updateLoadingBalance = async (
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
};
|
||||
@@ -485,7 +559,7 @@ const insertLoadingBalanceHistoryOnly = async (
|
||||
let loadDetail = [];
|
||||
detail.forEach((element) => {
|
||||
loadDetail.push({
|
||||
i_load_balance: id,
|
||||
i_load_balance: id.i_load_balance,
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_amount,
|
||||
@@ -548,24 +622,11 @@ const insertLoadingBalanceHistoryOnly = async (
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
};
|
||||
|
||||
// GET LOADING BALANCE SEQUENCE
|
||||
const getLoadBalanceSequence = (data, date) => {
|
||||
let result = knex('trx.t_d_load_balance')
|
||||
.select('i_load_balance_no_seq')
|
||||
.orderBy('i_load_balance_no_seq', 'desc')
|
||||
.whereNotNull('i_load_balance_no_seq')
|
||||
.where('i_partner', data.i_partner)
|
||||
.where('i_merchant', data.i_merchant)
|
||||
.whereRaw('??::date = ?', ['d_load_balance', date])
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// FIND LOAD BALANCE
|
||||
let findLoadBalance = (loadBalanceNumber) => {
|
||||
let result = knex('trx.t_d_load_balance')
|
||||
@@ -609,17 +670,34 @@ const updateReservationAndLoadingBalance = async (
|
||||
.where('c_load_balance_no', data.c_load_balance_no)
|
||||
.then(() => {
|
||||
// insert load balance history
|
||||
// winston.logger.debug(
|
||||
// `${reservationNumber} proses insert t_d_load_balance_history updateReservationAndLoadingBalance`
|
||||
// );
|
||||
return knex('trx.t_d_load_balance_history')
|
||||
.transacting(trx)
|
||||
.returning('i_load_balance')
|
||||
.insert(data);
|
||||
})
|
||||
.then((history) => {
|
||||
// winston.logger.debug(
|
||||
// `${JSON.stringify(history)} history t_d_load_balance_history_detail`
|
||||
// );
|
||||
// winston.logger.debug(
|
||||
// `${JSON.stringify(
|
||||
// history[0]
|
||||
// )} id t_d_load_balance_history_detail before parseint`
|
||||
// );
|
||||
let id = history[0];
|
||||
// winston.logger.debug(
|
||||
// `${id} id t_d_load_balance_history_detail id only`
|
||||
// );
|
||||
// winston.logger.debug(
|
||||
// `${id.i_load_balance} id t_d_load_balance_history_detail id.i_load_balance`
|
||||
// );
|
||||
let loadDetail = [];
|
||||
detail.forEach((element) => {
|
||||
loadDetail.push({
|
||||
i_load_balance: id,
|
||||
i_load_balance: id.i_load_balance,
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_amount,
|
||||
@@ -634,6 +712,11 @@ const updateReservationAndLoadingBalance = async (
|
||||
});
|
||||
});
|
||||
|
||||
// winston.logger.debug(
|
||||
// `${reservationNumber} proses insert t_d_load_balance_history_detail updateReservationAndLoadingBalance: ${JSON.stringify(
|
||||
// loadDetail
|
||||
// )}`
|
||||
// );
|
||||
// insert detail load balance
|
||||
return knex('trx.t_d_load_balance_history_detail')
|
||||
.transacting(trx)
|
||||
@@ -641,6 +724,9 @@ const updateReservationAndLoadingBalance = async (
|
||||
})
|
||||
.then(() => {
|
||||
// update reservation
|
||||
// winston.logger.debug(
|
||||
// `${reservationNumber} proses update t_d_reservation_balance updateReservationAndLoadingBalance`
|
||||
// );
|
||||
return knex('trx.t_d_reservation_balance')
|
||||
.transacting(trx)
|
||||
.update({
|
||||
@@ -657,16 +743,31 @@ const updateReservationAndLoadingBalance = async (
|
||||
})
|
||||
.whereIn('c_reservation_no', reservationNumber);
|
||||
})
|
||||
.then(trx.commit)
|
||||
.catch(trx.rollback);
|
||||
.then(() => {
|
||||
// winston.logger.debug(`${reservationNumber} commit transaction`);
|
||||
return trx.commit();
|
||||
})
|
||||
.catch((error) => {
|
||||
winston.logger.debug(
|
||||
`${reservationNumber} rollback transaction: ${error.message}`
|
||||
);
|
||||
trx.rollback(); // Rollback transaction
|
||||
// throw error; // Rethrow error to outer catch
|
||||
});
|
||||
})
|
||||
.then((result) => {
|
||||
// winston.logger.debug(
|
||||
// `${reservationNumber} result success ${JSON.stringify(result)}}`
|
||||
// );
|
||||
// console.log(result);
|
||||
return result.rowCount;
|
||||
return true;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
return error.message;
|
||||
winston.logger.debug(
|
||||
`${reservationNumber} result error: ${error.message}`
|
||||
);
|
||||
// console.log(error.message);
|
||||
return false;
|
||||
});
|
||||
};
|
||||
|
||||
@@ -745,7 +846,7 @@ const updateFlag = async (now, cardNumber, uid, balance, flag) => {
|
||||
return result;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
};
|
||||
@@ -761,8 +862,8 @@ const getAccumulationBalanceInThisMonthFromCardHistory = (
|
||||
.where('c_card_number', cardNumber)
|
||||
.where('c_status', 'S')
|
||||
.where('m_balance_after', '>', 0)
|
||||
.whereRaw("DATE_PART('YEAR', ??) = ?", ['d_log', year])
|
||||
.whereRaw("DATE_PART('MONTH', ??) = ?", ['d_log', month])
|
||||
.whereRaw('?? >= make_date(?, ?, 1)', ['d_log', year, month])
|
||||
.whereRaw("?? < make_date(?, ?, 1) + interval '1 month'", ['d_log', year, month])
|
||||
.whereIn('i_log_name', [21])
|
||||
.groupBy('c_card_number')
|
||||
.first();
|
||||
@@ -775,17 +876,6 @@ const createLoadBalanceLog = (data) => {
|
||||
return result;
|
||||
};
|
||||
|
||||
// INSERT TEMP LOAD BALANCE NUMBER1
|
||||
const insertLoadBalanceNumber = (loadBalanceNumber) => {
|
||||
let result = knex('trx.t_d_load_balance_no_validate')
|
||||
.insert({
|
||||
c_load_balance_no: loadBalanceNumber,
|
||||
})
|
||||
.onConflict('c_load_balance_no')
|
||||
.ignore();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET RESERVATION PENDING WITHOUT FRAUD
|
||||
const getReservationPendingWithoutFraud = (
|
||||
cardNumber,
|
||||
@@ -793,17 +883,6 @@ const getReservationPendingWithoutFraud = (
|
||||
reservationNumber = []
|
||||
) => {
|
||||
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')
|
||||
.select(
|
||||
'trx.t_d_reservation_balance.i_reservation_amount',
|
||||
@@ -813,7 +892,14 @@ const getReservationPendingWithoutFraud = (
|
||||
.where('trx.t_d_reservation_balance.c_card_number', cardNumber)
|
||||
.whereIn('trx.t_d_reservation_balance.c_status', ['P', 'I'])
|
||||
.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(function () {
|
||||
@@ -856,34 +942,40 @@ const getLastHistory = (cardNumber) => {
|
||||
.where('c_source', 'CMS')
|
||||
.where('c_status', 'S')
|
||||
.orderBy('d_log', 'desc')
|
||||
.orderBy('i_log_card', 'desc')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// INSERT FRAUD TRANSACTION
|
||||
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
|
||||
.into(
|
||||
knex.raw('?? (??, ??, ??, ??, ??, ??)', [
|
||||
'trx.t_d_fraud',
|
||||
'c_card_number',
|
||||
'c_reservation_no',
|
||||
'i_reservation_amount',
|
||||
'c_reservation_status',
|
||||
'c_reservation_flag',
|
||||
'c_reservation_ref_no',
|
||||
])
|
||||
knex.raw(
|
||||
'?? (??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??, ??)',
|
||||
[
|
||||
'trx.t_d_fraud',
|
||||
'c_card_number',
|
||||
'c_reservation_no',
|
||||
'i_reservation_amount',
|
||||
'c_reservation_status',
|
||||
'c_reservation_flag',
|
||||
'c_reservation_ref_no',
|
||||
'd_reservation',
|
||||
'c_reservation_status_name',
|
||||
'i_partner',
|
||||
'c_partner_code',
|
||||
'c_partner_name',
|
||||
'i_merchant',
|
||||
'c_merchant_code',
|
||||
'c_merchant_name',
|
||||
'c_mid',
|
||||
'i_terminal',
|
||||
'c_terminal_code',
|
||||
'c_terminal_name',
|
||||
'c_tid',
|
||||
]
|
||||
)
|
||||
)
|
||||
.insert(function () {
|
||||
this.select(
|
||||
@@ -892,7 +984,20 @@ const insertFraudTransaction = (reservationNumber) => {
|
||||
'i_reservation_amount',
|
||||
'c_status',
|
||||
'c_flag',
|
||||
'c_ref_no'
|
||||
'c_ref_no',
|
||||
'd_reservation',
|
||||
'c_status_name',
|
||||
'i_partner',
|
||||
'c_partner_code',
|
||||
'c_partner_name',
|
||||
'i_merchant',
|
||||
'c_merchant_code',
|
||||
'c_merchant_name',
|
||||
'c_mid',
|
||||
'i_terminal',
|
||||
'c_terminal_code',
|
||||
'c_terminal_name',
|
||||
'c_tid'
|
||||
)
|
||||
.from('trx.t_d_reservation_balance')
|
||||
.whereIn(
|
||||
@@ -900,7 +1005,14 @@ const insertFraudTransaction = (reservationNumber) => {
|
||||
reservationNumber
|
||||
)
|
||||
.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;
|
||||
@@ -920,10 +1032,10 @@ const suspendReservation = (reservationNumber, datetime) => {
|
||||
// CHECK HISTORY CARD
|
||||
const checkCardHistory = (c_card_number) => {
|
||||
let result = knex('log.t_log_card')
|
||||
// .select(['i_log_name', 'c_source'])
|
||||
// .select(['i_log_name'])
|
||||
.where('c_card_number', c_card_number)
|
||||
.whereIn('i_log_name', [21, 90])
|
||||
.where('c_source', 'CMS')
|
||||
.whereIn('i_log_name', ['21', '90'])
|
||||
.orderBy('d_log', 'DESC')
|
||||
.first();
|
||||
|
||||
@@ -977,7 +1089,7 @@ const updateReservationAndInsertLoadingBalance = async (
|
||||
let loadDetail = [];
|
||||
detailLoadBalance.forEach((element) => {
|
||||
loadDetail.push({
|
||||
i_load_balance: id,
|
||||
i_load_balance: id.i_load_balance,
|
||||
i_reservation_balance: element.i_reservation_balance,
|
||||
c_reservation_no: element.c_reservation_no,
|
||||
i_amount: element.i_reservation_amount,
|
||||
@@ -1015,23 +1127,34 @@ const updateReservationAndInsertLoadingBalance = async (
|
||||
})
|
||||
.whereIn('c_reservation_no', reservationNumber);
|
||||
})
|
||||
.then(trx.commit)
|
||||
.then(() => trx.commit())
|
||||
.catch(trx.rollback);
|
||||
})
|
||||
.then((result) => {
|
||||
console.log(result);
|
||||
// console.log(result);
|
||||
return result.rowCount;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.log(error.message);
|
||||
// console.log(error.message);
|
||||
return error.message;
|
||||
});
|
||||
};
|
||||
|
||||
// GET TOPUP PARTIAL STATUS FROM GLOBAL PARAMETER
|
||||
const getTopupPartialStatus = () => {
|
||||
let result = knex('t_m_global_parameter')
|
||||
.select('c_value')
|
||||
.where('c_code', '=', 'HSM_TOPUP_PARTIAL_STAT')
|
||||
.first();
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
checkCardNumber,
|
||||
getPartner,
|
||||
getIssuer,
|
||||
getCardBlacklist,
|
||||
getCheckByCardProductStatusValue,
|
||||
getReservationPending,
|
||||
getReservationPendingWithFlagCounter,
|
||||
@@ -1039,12 +1162,12 @@ module.exports = {
|
||||
getBIRegulationStatus,
|
||||
getMaxAmountOnTheCard,
|
||||
getMaxTopupPerMonth,
|
||||
findReservationLoaded,
|
||||
findReservation,
|
||||
findReservationsWithLoadedBalance,
|
||||
findReservationDetails,
|
||||
insertLoadingBalance,
|
||||
updateLoadingBalance,
|
||||
insertLoadingBalanceHistoryOnly,
|
||||
getLoadBalanceSequence,
|
||||
allocateLoadBalanceNumber,
|
||||
findLoadBalance,
|
||||
findLoadBalanceDetail,
|
||||
inquiryByLoadBalanceNumber,
|
||||
@@ -1058,7 +1181,6 @@ module.exports = {
|
||||
updateFlag,
|
||||
getAccumulationBalanceInThisMonthFromCardHistory,
|
||||
createLoadBalanceLog,
|
||||
insertLoadBalanceNumber,
|
||||
getReservationPendingWithoutFraud,
|
||||
getFraudTransaction,
|
||||
getLastHistory,
|
||||
@@ -1072,4 +1194,5 @@ module.exports = {
|
||||
getReservationPendingWithFlagV2,
|
||||
createDetailLoadBalanceFromReservation,
|
||||
updateReservationAndInsertLoadingBalance,
|
||||
getTopupPartialStatus,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
const { body } = require('express-validator');
|
||||
|
||||
// Aturan input untuk setiap operasi. Urutan validasi mengikuti kontrak API.
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'loadingBalanceRequest':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('uid').not().isEmpty().withMessage('UID is required'),
|
||||
body('flag').not().isEmpty().withMessage('Flag is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card Number is required'),
|
||||
];
|
||||
case 'loadingBalance':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('uid').not().isEmpty().withMessage('UID is required'),
|
||||
body('flag').not().isEmpty().withMessage('Flag is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card Number is required'),
|
||||
body('amount')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Amount is required')
|
||||
.isNumeric()
|
||||
.withMessage('Amount is invalid format'),
|
||||
body('reservation_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Reservation Number is required')
|
||||
.isArray()
|
||||
.withMessage('Reservation Number is invalid request format'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
module.exports = validate;
|
||||
@@ -0,0 +1,29 @@
|
||||
const { setTimeout: delay } = require('node:timers/promises');
|
||||
const moment = require('moment');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./paymentrecon.model');
|
||||
|
||||
// Pertahankan jeda sebelum tiap percobaan. Ulangi hanya jika nomor sudah diklaim.
|
||||
async function allocatePaymentReconNumber(partnerCode, reconDate) {
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
await delay(helper.randomNumberInt());
|
||||
const number = await generatePaymentReconNumber(partnerCode, reconDate);
|
||||
if (number !== 'XX') return number;
|
||||
}
|
||||
return 'XX';
|
||||
}
|
||||
|
||||
async function generatePaymentReconNumber(partnerCode, reconDate) {
|
||||
const lastCounter = await model.getLastCounterPaymentReconNo(partnerCode, reconDate);
|
||||
const nextCounter = lastCounter ? parseInt(lastCounter.c_payment_recon_no.slice(-6)) + 1 : 1;
|
||||
const counter = String(nextCounter).padStart(6, '0');
|
||||
const date = moment(reconDate).format('YYMMDD');
|
||||
const paymentReconNumber = `RC${partnerCode}${date}${counter}`;
|
||||
winston.logger.debug(`Payment Recon Number: ${paymentReconNumber}`);
|
||||
|
||||
const insert = await model.insertPaymentReconNumber(paymentReconNumber);
|
||||
return insert.rowCount < 1 ? 'XX' : paymentReconNumber;
|
||||
}
|
||||
|
||||
module.exports = { allocatePaymentReconNumber };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,33 +1,34 @@
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
|
||||
// GET PARTNER, MERCHANT, TERMINAL FROM TID
|
||||
const getPartner = (mid, tid) => {
|
||||
let result = knex
|
||||
.select(
|
||||
"t_m_partner.i_partner",
|
||||
"t_m_partner.c_code as partner_code",
|
||||
"t_m_partner.c_name as partner_name",
|
||||
"t_m_merchant.i_merchant",
|
||||
"t_m_merchant.c_code as merchant_code",
|
||||
"t_m_merchant.c_name as merchant_name",
|
||||
"t_m_merchant.e_mid as mid",
|
||||
"t_m_terminal.i_terminal",
|
||||
"t_m_terminal.c_code as terminal_code",
|
||||
"t_m_terminal.c_name as terminal_name",
|
||||
"t_m_terminal.e_tid as tid"
|
||||
't_m_partner.i_partner',
|
||||
't_m_partner.c_code as partner_code',
|
||||
't_m_partner.c_name as partner_name',
|
||||
't_m_partner.b_payment_recon',
|
||||
't_m_merchant.i_merchant',
|
||||
't_m_merchant.c_code as merchant_code',
|
||||
't_m_merchant.c_name as merchant_name',
|
||||
't_m_merchant.e_mid as mid',
|
||||
't_m_terminal.i_terminal',
|
||||
't_m_terminal.c_code as terminal_code',
|
||||
't_m_terminal.c_name as terminal_name',
|
||||
't_m_terminal.e_tid as tid'
|
||||
)
|
||||
.from("t_m_terminal")
|
||||
.from('t_m_terminal')
|
||||
.leftJoin(
|
||||
"t_m_merchant",
|
||||
"t_m_terminal.i_merchant",
|
||||
"t_m_merchant.i_merchant"
|
||||
't_m_merchant',
|
||||
't_m_terminal.i_merchant',
|
||||
't_m_merchant.i_merchant'
|
||||
)
|
||||
.leftJoin("t_m_partner", "t_m_merchant.i_partner", "t_m_partner.i_partner")
|
||||
.where("t_m_merchant.e_mid", mid)
|
||||
.where("t_m_terminal.e_tid", tid)
|
||||
.where("t_m_terminal.c_status", "A")
|
||||
.where("t_m_merchant.c_status", "A")
|
||||
.where("t_m_partner.c_status", "A")
|
||||
.leftJoin('t_m_partner', 't_m_merchant.i_partner', 't_m_partner.i_partner')
|
||||
.where('t_m_merchant.e_mid', mid)
|
||||
.where('t_m_terminal.e_tid', tid)
|
||||
.where('t_m_terminal.c_status', 'A')
|
||||
.where('t_m_merchant.c_status', 'A')
|
||||
.where('t_m_partner.c_status', 'A')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
@@ -35,59 +36,75 @@ const getPartner = (mid, tid) => {
|
||||
const getPartnerByID = (partner_id) => {
|
||||
let result = knex
|
||||
.select(
|
||||
"t_m_partner.i_partner",
|
||||
"t_m_partner.c_code as partner_code",
|
||||
"t_m_partner.c_name as partner_name"
|
||||
't_m_partner.i_partner',
|
||||
't_m_partner.c_code as partner_code',
|
||||
't_m_partner.c_name as partner_name',
|
||||
't_m_partner.b_payment_recon'
|
||||
)
|
||||
.from("t_m_partner")
|
||||
.where("t_m_partner.i_partner", partner_id)
|
||||
.where("t_m_partner.c_status", "A")
|
||||
.from('t_m_partner')
|
||||
.where('t_m_partner.i_partner', partner_id)
|
||||
.where('t_m_partner.c_status', 'A')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
const checkReservationNumberAndAmount = (reservationNumber) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.count("* as total_transaction")
|
||||
.sum("i_reservation_amount as total_amount")
|
||||
.groupBy("c_ref_no")
|
||||
.where("c_reservation_no", reservationNumber)
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.count('* as total_transaction')
|
||||
.sum('i_reservation_amount as total_amount')
|
||||
.groupBy('c_ref_no')
|
||||
.where('c_reservation_no', reservationNumber)
|
||||
// .where("c_status", "A")
|
||||
.whereNull("c_payment_recon_no")
|
||||
.whereNull('c_payment_recon_no')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
const checkReservationCanceledStatus = (reservationNumber) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.where("c_reservation_no", reservationNumber)
|
||||
.where("c_status", "X")
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.where('c_reservation_no', reservationNumber)
|
||||
.where('c_status', 'X')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
const checkReservation = (reservationNumber) => {
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.where('c_reservation_no', reservationNumber)
|
||||
.where('c_status', '!=', 'X')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
const checkReservationNumberAndAmountAlreadyRecon = (reservationNumber) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.select("c_payment_recon_no", "d_payment_recon")
|
||||
.where("c_reservation_no", reservationNumber)
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.select('c_payment_recon_no', 'd_payment_recon')
|
||||
.where('c_reservation_no', reservationNumber)
|
||||
// .where("c_status", "A")
|
||||
.whereNotNull("c_payment_recon_no")
|
||||
.whereNotNull('c_payment_recon_no')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// UPDATE PAYMENT RECON
|
||||
const updatePaymentReconNo = (data) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.update({
|
||||
c_payment_recon_no: data.payment_recon_no,
|
||||
d_payment: data.date,
|
||||
d_payment_recon: data.time,
|
||||
})
|
||||
.whereNull("c_payment_recon_no")
|
||||
.where("c_reservation_no", data.reservation_number);
|
||||
return result;
|
||||
};
|
||||
// Klaim dan audit sukses harus commit bersama agar retry tidak meninggalkan status parsial.
|
||||
function completePaymentRecon({ date, time, partnerId, partnerCode, paymentReconNumber,
|
||||
bankRef, reservationNumber, amount, expectedAmount, responseData }) {
|
||||
return knex.transaction(async (trx) => {
|
||||
const updated = await trx('trx.t_d_reservation_balance')
|
||||
.where({ c_reservation_no: reservationNumber, i_partner: partnerId, i_reservation_amount: expectedAmount })
|
||||
.whereNull('c_payment_recon_no')
|
||||
.where('c_status', '!=', 'X')
|
||||
.update({ c_payment_recon_no: paymentReconNumber, d_payment: date, d_payment_recon: time });
|
||||
|
||||
if (updated === 0) return false;
|
||||
if (updated !== 1) throw new Error('Payment reconciliation matched more than one reservation');
|
||||
await insertPaymentReconTransaction(
|
||||
date, time, partnerCode, paymentReconNumber, bankRef, reservationNumber, amount,
|
||||
'S', 'SUCCESS', '00', 'SUCCESS', responseData, trx
|
||||
);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
// INSERT PAYMENT RECON
|
||||
const insertPaymentReconTransaction = (
|
||||
@@ -102,9 +119,10 @@ const insertPaymentReconTransaction = (
|
||||
statusName,
|
||||
responseCode,
|
||||
responseMessage,
|
||||
responseData
|
||||
responseData,
|
||||
connection = knex
|
||||
) => {
|
||||
let result = knex("payment.t_d_payment_recon").insert({
|
||||
let result = connection('payment.t_d_payment_recon').insert({
|
||||
d_payment: date,
|
||||
d_payment_recon: now,
|
||||
c_partner_code: partnerCode,
|
||||
@@ -123,34 +141,34 @@ const insertPaymentReconTransaction = (
|
||||
|
||||
// INSERT TEMP PAYMENT RECON NUMBER
|
||||
const insertPaymentReconNumber = (paymentReconNumber) => {
|
||||
let result = knex("payment.t_d_payment_recon_no_validate")
|
||||
let result = knex('payment.t_d_payment_recon_no_validate')
|
||||
.insert({
|
||||
c_payment_recon_no: paymentReconNumber,
|
||||
})
|
||||
.onConflict("c_payment_recon_no")
|
||||
.onConflict('c_payment_recon_no')
|
||||
.ignore();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET LAST COUNTER PAYMENT RECON NO
|
||||
const getLastCounterPaymentReconNo = (partnerCode, reconDate) => {
|
||||
let result = knex("payment.t_d_payment_recon")
|
||||
.select("c_payment_recon_no", "d_payment_recon")
|
||||
.whereRaw("??::date = ?", ["d_payment_recon", reconDate])
|
||||
.where("c_partner_code", partnerCode)
|
||||
let result = knex('payment.t_d_payment_recon')
|
||||
.select('c_payment_recon_no', 'd_payment_recon')
|
||||
.whereRaw('??::date = ?', ['d_payment_recon', reconDate])
|
||||
.where('c_partner_code', partnerCode)
|
||||
// .orderBy("d_payment_recon", "desc")
|
||||
.orderBy("c_payment_recon_no", "desc")
|
||||
.orderBy('c_payment_recon_no', 'desc')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
const getReservationToRecon = (date) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.select("c_reservation_no", "i_reservation_amount")
|
||||
.whereNull("d_cancel")
|
||||
.whereNull("c_payment_recon_no")
|
||||
.whereRaw("??::date = ?", ["d_reservation", date])
|
||||
.orderBy("c_reservation_no", "asc");
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.select('c_reservation_no', 'i_reservation_amount')
|
||||
.whereNull('d_cancel')
|
||||
.whereNull('c_payment_recon_no')
|
||||
.whereRaw('??::date = ?', ['d_reservation', date])
|
||||
.orderBy('c_reservation_no', 'asc');
|
||||
return result;
|
||||
};
|
||||
|
||||
@@ -159,8 +177,9 @@ module.exports = {
|
||||
getPartnerByID,
|
||||
checkReservationNumberAndAmount,
|
||||
checkReservationCanceledStatus,
|
||||
checkReservation,
|
||||
checkReservationNumberAndAmountAlreadyRecon,
|
||||
updatePaymentReconNo,
|
||||
completePaymentRecon,
|
||||
insertPaymentReconTransaction,
|
||||
insertPaymentReconNumber,
|
||||
getLastCounterPaymentReconNo,
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
const model = require("./pooling.model");
|
||||
const { logger } = require("../../helpers/winston.logger");
|
||||
|
||||
function respond(res, code, message, data = []) {
|
||||
return res.status(200).json({ code, message, data });
|
||||
}
|
||||
|
||||
function failure(res, error) {
|
||||
logger.error("Pooling failed | " + (error.code || error.name));
|
||||
if (error.code === "POOLING_CARD_CONFLICT") return respond(res, "409", "Fail insert data card product");
|
||||
return respond(res, "500", process.env.NODE_ENV === "production"
|
||||
? "500 internal server error - backend server." : error.message);
|
||||
}
|
||||
|
||||
async function runBatches(res, operation, name, empty, complete) {
|
||||
let count = 0;
|
||||
try {
|
||||
for (;;) {
|
||||
const batch = await operation();
|
||||
if (batch.busy) return respond(res, "409", "Pooling is being processed. Please retry.");
|
||||
if (!batch.count) return respond(res, ...(count ? complete : empty));
|
||||
count += batch.count;
|
||||
logger.info("Pooling " + name + " batch committed | count=" + batch.count);
|
||||
}
|
||||
} catch (error) {
|
||||
return failure(res, error);
|
||||
}
|
||||
}
|
||||
|
||||
const validateData = (req, res) => runBatches(res, model.validateBatch, "validate",
|
||||
["00", "No Pooling Data"], ["00", "Validate success"]);
|
||||
|
||||
const insertCardProduct = (req, res) => runBatches(res, model.syncBatch, "sync",
|
||||
["409", "No data valid"], ["00", "Success"]);
|
||||
|
||||
async function insertPooling(req, res) {
|
||||
const { batch, data, card_number, uid } = req.body || {};
|
||||
const cards = batch ? data : [{ card_number, uid }];
|
||||
if (!Array.isArray(cards) || cards.length === 0) return respond(res, "409", "Data is required");
|
||||
if (cards.some((card) => !card?.card_number)) return respond(res, "409", "Card Number is required");
|
||||
if (cards.some((card) => !card?.uid)) return respond(res, "409", "uid is required");
|
||||
|
||||
try {
|
||||
await model.insertRawCards(cards);
|
||||
logger.info("Pooling raw batch committed | count=" + cards.length);
|
||||
return respond(res, "00", "Success insert data");
|
||||
} catch (error) {
|
||||
return failure(res, error);
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { validateData, insertCardProduct, insertPooling };
|
||||
@@ -0,0 +1,84 @@
|
||||
const { pooling: poolingConfig } = require("../../../knexfile");
|
||||
const dbPooling = require("knex")(poolingConfig);
|
||||
const { observePool } = require("../../../infrastructure/database/pool-metrics");
|
||||
observePool("pooling", dbPooling.client.pool);
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
const moment = require("moment");
|
||||
|
||||
const BATCH_SIZE = 500;
|
||||
const validateLock = 3824001;
|
||||
const syncLock = 3824002;
|
||||
|
||||
const cardColumns = ["c_card_number", "c_idm"];
|
||||
const cardKey = (row) => JSON.stringify(cardColumns.map((column) => row[column]));
|
||||
|
||||
async function insertRawCards(cards) {
|
||||
// Satu request insert tetap atomik meski SQL dikirim dalam potongan kecil.
|
||||
await dbPooling.transaction(async (trx) => {
|
||||
for (let start = 0; start < cards.length; start += BATCH_SIZE) {
|
||||
const rows = cards.slice(start, start + BATCH_SIZE).map((card) => ({
|
||||
c_card_number: card.card_number, c_idm: card.uid,
|
||||
}));
|
||||
await trx("raw").insert(rows);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async function existingKeys(trx, table, cards) {
|
||||
const tuples = [];
|
||||
const nullable = [];
|
||||
for (const card of cards) {
|
||||
const tuple = cardColumns.map((column) => card[column]);
|
||||
if (tuple.includes(null)) nullable.push(card);
|
||||
else tuples.push(tuple);
|
||||
}
|
||||
const query = trx(table).select(cardColumns).whereIn(cardColumns, tuples);
|
||||
for (const card of nullable) query.orWhere(card);
|
||||
const existing = await query;
|
||||
return new Set(existing.map(cardKey));
|
||||
}
|
||||
|
||||
async function ensureCards(trx, table, cards) {
|
||||
if (!cards.length) return;
|
||||
const unique = [...new Map(cards.map((card) => [cardKey(card), card])).values()];
|
||||
const existing = await existingKeys(trx, table, unique);
|
||||
const missing = unique.filter((card) => !existing.has(cardKey(card)));
|
||||
if (!missing.length) return;
|
||||
await trx(table).insert(missing).onConflict().ignore();
|
||||
const stored = await existingKeys(trx, table, missing);
|
||||
if (stored.size !== missing.length) {
|
||||
const error = new Error("Card conflict in pooling destination");
|
||||
error.code = "POOLING_CARD_CONFLICT";
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function processBatch(table, pendingColumn, lock, apply) {
|
||||
return dbPooling.transaction(async (trx) => {
|
||||
const { rows: [{ acquired }] } = await trx.raw("SELECT pg_try_advisory_xact_lock(?::bigint) AS acquired", [lock]);
|
||||
if (!acquired) return { busy: true, count: 0 };
|
||||
// CTID hanya dipakai selama baris terkunci pada transaksi ini.
|
||||
const rows = await trx(table).select(...cardColumns, trx.raw("ctid::text AS row_id"))
|
||||
.where(pendingColumn, false).limit(BATCH_SIZE).forUpdate().skipLocked();
|
||||
if (!rows.length) return { busy: false, count: 0 };
|
||||
const cards = rows.map(({ c_card_number, c_idm }) => ({ c_card_number, c_idm }));
|
||||
await apply(trx, cards);
|
||||
const timestampColumn = pendingColumn === "b_validate" ? "d_validate" : "d_sync";
|
||||
await trx(table).whereIn(trx.raw("ctid::text"), rows.map(({ row_id }) => row_id))
|
||||
.update({ [pendingColumn]: true, [timestampColumn]: moment().format("YYYY-MM-DD HH:mm:ss") });
|
||||
return { busy: false, count: rows.length };
|
||||
});
|
||||
}
|
||||
|
||||
const validateBatch = () => processBatch("raw", "b_validate", validateLock, async (trx, cards) => {
|
||||
const existing = await existingKeys(knex, "t_m_card_product", cards);
|
||||
await ensureCards(trx, "valid", cards.filter((card) => !existing.has(cardKey(card))));
|
||||
await ensureCards(trx, "invalid", cards.filter((card) => existing.has(cardKey(card))));
|
||||
});
|
||||
|
||||
const syncBatch = () => processBatch("valid", "b_sync", syncLock, async (trx, cards) => {
|
||||
// Jika commit utama berhasil tetapi penandaan gagal, retry mengenali pasangan yang sudah ada.
|
||||
await knex.transaction((main) => ensureCards(main, "t_m_card_product", cards));
|
||||
});
|
||||
|
||||
module.exports = { insertRawCards, validateBatch, syncBatch };
|
||||
@@ -0,0 +1,9 @@
|
||||
const { default: axios } = require('axios');
|
||||
|
||||
// Kegagalan CTS harus selesai pada jalur error yang sudah dimiliki endpoint.
|
||||
function postWithDeadline(url, data, config) {
|
||||
const timeout = 5000;
|
||||
return axios.post(url, data, { ...config, timeout, signal: AbortSignal.timeout(timeout) });
|
||||
}
|
||||
|
||||
module.exports = { postWithDeadline };
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,373 @@
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
|
||||
// GET IS CARD ADDED TO BLACKLIST
|
||||
const getCardBlacklist = (card_number) => {
|
||||
let result = knex('public.t_m_card_blacklist')
|
||||
.select('c_status')
|
||||
.where('c_card_number', card_number)
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET IS CARD ADDED TO BLACKLIST
|
||||
const getCardReplacement = (card_number) => {
|
||||
let result = knex('trx.t_d_card_replacement')
|
||||
.select()
|
||||
.where('c_card_no', card_number)
|
||||
.orderBy('i_card_replacement', 'DESC')
|
||||
.first();
|
||||
|
||||
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
|
||||
const getCardProduct = (card_number) => {
|
||||
let result = knex('public.t_m_card_product')
|
||||
.select()
|
||||
.where('c_card_number', card_number)
|
||||
.orderBy('i_request_order', 'DESC')
|
||||
.first();
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET CHECKING FROM GLOBAL PARAMETER
|
||||
const getGlobalParameterData = (code) => {
|
||||
let result = knex('t_m_global_parameter')
|
||||
.select('c_value')
|
||||
.where('c_code', code)
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET LAST BALANCE FROM CARD HISTORY
|
||||
const getLastBalanceFromCardHistory = (cardNumber) => {
|
||||
let result = knex('log.t_log_card')
|
||||
.select('m_balance_after')
|
||||
.where('c_card_number', cardNumber)
|
||||
.where('c_status', 'S')
|
||||
.where('m_balance_after', '>', 0)
|
||||
.orderBy('d_log', 'desc')
|
||||
.limit(1)
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET ACCUMULATION BALANCE IN THIS MONTH FROM CARD HISTORY
|
||||
const getAccumulationBalanceInThisMonthFromCardHistory = (
|
||||
cardNumber,
|
||||
year,
|
||||
month
|
||||
) => {
|
||||
let result = knex('log.t_log_card')
|
||||
.sum('m_amount as accumulation_balance')
|
||||
.where('c_card_number', cardNumber)
|
||||
.where('c_status', 'S')
|
||||
.where('m_balance_after', '>', 0)
|
||||
.whereRaw('?? >= make_date(?, ?, 1)', ['d_log', year, month])
|
||||
.whereRaw("?? < make_date(?, ?, 1) + interval '1 month'", ['d_log', year, month])
|
||||
.whereIn('i_log_name', [21])
|
||||
.groupBy('c_card_number')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// UPDATE CARD REPLACEMENT
|
||||
const updateReplacement = async (i_card_replacement, dataReplacement) => {
|
||||
let result = await knex('trx.t_d_card_replacement')
|
||||
.update(dataReplacement, ['*'])
|
||||
.where({ i_card_replacement: i_card_replacement });
|
||||
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) => {
|
||||
let result = await knex("trx.t_d_card_replacement_detail").insert(dataReplacement);
|
||||
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 = {
|
||||
getCardBlacklist,
|
||||
getCardReplacement,
|
||||
getCardProduct,
|
||||
getGlobalParameterData,
|
||||
getLastBalanceFromCardHistory,
|
||||
getAccumulationBalanceInThisMonthFromCardHistory,
|
||||
updateReplacement,
|
||||
insertReplacementDetail,
|
||||
insertSales,
|
||||
getCardSales,
|
||||
updateSales,
|
||||
getCardReplacementScheduler,
|
||||
updateReplacementByCardNumber,
|
||||
getPPNCardSales,
|
||||
completingDataSalesInternal,
|
||||
completingDataSalesNewCard,
|
||||
completingDataSalesOldCard,
|
||||
updateDataSalesIsComplete,
|
||||
};
|
||||
@@ -0,0 +1,143 @@
|
||||
const { body } = require('express-validator');
|
||||
|
||||
// Aturan input untuk setiap operasi. Urutan validasi mengikuti kontrak API.
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'validateCardSales':
|
||||
return [
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card number is required'),
|
||||
];
|
||||
case 'validateLastBalance':
|
||||
return [
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card number is required'),
|
||||
];
|
||||
case 'validateCardTopup':
|
||||
return [
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card number is required'),
|
||||
body('amount')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Amount is required')
|
||||
.isNumeric()
|
||||
.withMessage('Amount is invalid format'),
|
||||
body('last_balance')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Last Balance is required')
|
||||
.isNumeric()
|
||||
.withMessage('Last Balance is invalid format'),
|
||||
];
|
||||
case 'validateCardRedeem':
|
||||
return [
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card number is required'),
|
||||
body('station_code')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Station Code is required'),
|
||||
];
|
||||
case 'checkBlacklist':
|
||||
return [
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card number is required'),
|
||||
];
|
||||
case 'validateCardReplacement':
|
||||
return [
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card number is required'),
|
||||
body('station_code')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Station Code is required'),
|
||||
];
|
||||
case 'validateNewCardReplacement':
|
||||
return [
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card number is required'),
|
||||
];
|
||||
|
||||
//card_number, new_card_number, last_balance, security_code, unique_code
|
||||
case 'cardReplacementConfirm':
|
||||
return [
|
||||
body('card_number').not().isEmpty(),
|
||||
body('new_card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('New Card number is required'),
|
||||
body('last_balance')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Last Balance is required')
|
||||
.isNumeric()
|
||||
.withMessage('Last Balance is invalid format'),
|
||||
body('unique_code')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Unique Code is required'),
|
||||
body('security_code')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Security Code is required'),
|
||||
];
|
||||
case 'confirmCardRedeem':
|
||||
return [
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card number is required'),
|
||||
body('security_code')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Security Code is required'),
|
||||
];
|
||||
case 'confirmCardSales':
|
||||
return [
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card number is required'),
|
||||
body('sales_status')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Sales status Code is required'),
|
||||
body('device_code')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Device Code is required'),
|
||||
body('station_code')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Station Code is required'),
|
||||
body('station_name')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Station name is required'),
|
||||
body('created_by')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Created by is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
module.exports = validate;
|
||||
@@ -0,0 +1,215 @@
|
||||
const { param, body, validationResult } = require('express-validator');
|
||||
const helper = require('../../helpers/helper');
|
||||
const winston = require('../../helpers/winston.logger');
|
||||
const model = require('./refundkmt.model');
|
||||
const moment = require('moment');
|
||||
moment.locale('id');
|
||||
|
||||
// VALIDATION
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'callbackOy':
|
||||
return [
|
||||
body('partner_trx_id')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Partner Trx Id is required'),
|
||||
body('trx_id').not().isEmpty().withMessage('Trx Id is required'),
|
||||
body('amount').not().isEmpty().withMessage('Amount is required'),
|
||||
body('recipient_bank')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Recipient Bank is required'),
|
||||
body('recipient_account')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Recipient Account is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
const callbackOy = async (req, res) => {
|
||||
try {
|
||||
// generate unique code
|
||||
// unique code ini digunakan untuk keperluan log agar mudah untuk dibaca
|
||||
let uniqueCode = helper.getUniqueCode();
|
||||
let result = {};
|
||||
|
||||
// param
|
||||
let {
|
||||
status,
|
||||
amount,
|
||||
recipient_name,
|
||||
recipient_bank,
|
||||
recipient_account,
|
||||
trx_id,
|
||||
partner_trx_id,
|
||||
timestamp,
|
||||
created_date,
|
||||
last_updated_date,
|
||||
} = req.body;
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ REQUEST REFUND-KMT ]`
|
||||
);
|
||||
|
||||
// check validator
|
||||
let err = validationResult(req, res);
|
||||
if (!err.isEmpty()) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: err.errors[0].msg,
|
||||
data: {},
|
||||
};
|
||||
|
||||
// log warn
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFUND-KMT ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
// time
|
||||
let now = moment().format('YYYY-MM-DD HH:mm:ss');
|
||||
|
||||
let recipient_bank_code = recipient_bank.toUpperCase();
|
||||
// check trx_id yang di request match
|
||||
let checkRequest = await model.checkRedeem(
|
||||
partner_trx_id,
|
||||
trx_id,
|
||||
amount,
|
||||
recipient_bank_code,
|
||||
recipient_account
|
||||
);
|
||||
|
||||
if (!checkRequest) {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'Refund Request Transaction is not found.',
|
||||
data: {},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFUND-KMT ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
} else if (checkRequest.c_status?.trim() == 'A') {
|
||||
result = {
|
||||
code: '400',
|
||||
message: 'Refund transaction is already completed.',
|
||||
data: {},
|
||||
};
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ RESPONSE REFUND-KMT ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
return res.status(200).json(result);
|
||||
}
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ checkRequest ] found=${Boolean(checkRequest)}`
|
||||
);
|
||||
|
||||
if (status.code != '000') {
|
||||
result = {
|
||||
code: '400',
|
||||
message: status.message,
|
||||
data: {
|
||||
trx_id: trx_id,
|
||||
partner_trx_id: partner_trx_id,
|
||||
amount: amount,
|
||||
recipient_bank: recipient_bank_code,
|
||||
recipient_account: recipient_account,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const date_reimbursement = moment(last_updated_date, 'DD-MM-YYYY HH:mm:ss').format(
|
||||
'YYYY-MM-DD HH:mm:ss'
|
||||
);
|
||||
|
||||
winston.logger.warn(
|
||||
`${uniqueCode} [ log date_reimbusement ]: ${date_reimbursement}`
|
||||
);
|
||||
|
||||
//Update Card Replacement
|
||||
await model.updateReplacementComplete(
|
||||
checkRequest.i_card_replacement,
|
||||
checkRequest.c_request_no,
|
||||
date_reimbursement
|
||||
);
|
||||
|
||||
/*
|
||||
//Notif Email
|
||||
let urlCMS = '';
|
||||
if (process.env.SERVER_FOR == 'production') {
|
||||
urlCMS = 'https://cms.kci.id';
|
||||
} else if (process.env.SERVER_FOR == 'development') {
|
||||
urlCMS = 'http://10.20.14.69';
|
||||
} else {
|
||||
urlCMS = 'http://localhost:8000';
|
||||
}
|
||||
|
||||
let axios = require('axios');
|
||||
|
||||
const url = urlCMS + '/api/redeem/notifemail';
|
||||
|
||||
// let resp = await axios.post(url, body, config);
|
||||
const responseMail = await axios({
|
||||
method: 'post',
|
||||
url: url,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
data: {
|
||||
i_card_replacement: checkRequest.i_card_replacement?.trim(),
|
||||
c_request_no: checkRequest.c_request_no?.trim(),
|
||||
c_card_no: checkRequest.c_card_no?.trim(),
|
||||
status: 'complete',
|
||||
},
|
||||
});
|
||||
*/
|
||||
// console.log('urlCMS', url)
|
||||
|
||||
result = {
|
||||
code: '00',
|
||||
message: 'success',
|
||||
data: {
|
||||
trx_id: trx_id,
|
||||
partner_trx_id: partner_trx_id,
|
||||
amount: amount,
|
||||
recipient_bank: recipient_bank,
|
||||
recipient_account: recipient_account,
|
||||
last_updated_date: last_updated_date,
|
||||
},
|
||||
};
|
||||
|
||||
// log info
|
||||
winston.logger.info(
|
||||
`${uniqueCode} [ RESPONSE REFUND-KMT ] code=${result.code ?? "UNKNOWN"}`
|
||||
);
|
||||
|
||||
return res.status(200).json(result);
|
||||
} catch (error) {
|
||||
// create log
|
||||
winston.logger.error(
|
||||
`[ RESPONSE REFUND-KMT ]: 500 internal server error - backend server | ${error.message}`
|
||||
);
|
||||
|
||||
return res.status(200).json({
|
||||
code: '500',
|
||||
message:
|
||||
process.env.NODE_ENV != 'production'
|
||||
? error.message
|
||||
: '500 internal server error - backend server.',
|
||||
data: {},
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
validate,
|
||||
callbackOy,
|
||||
};
|
||||
@@ -0,0 +1,55 @@
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
|
||||
const checkRedeem = (partner_trx_id, trx_id, amount, recipient_bank, recipient_account) => {
|
||||
let result = knex
|
||||
.select(
|
||||
"t_d_card_replacement.i_card_replacement",
|
||||
"t_d_card_replacement.c_request_no",
|
||||
"t_d_card_replacement.c_card_no",
|
||||
"t_d_card_replacement.i_request_disburse",
|
||||
"t_d_card_replacement.c_refund_trx_id",
|
||||
"t_d_card_replacement.c_status"
|
||||
)
|
||||
.from("trx.t_d_card_replacement")
|
||||
// .leftJoin(
|
||||
// "t_m_merchant", "t_m_terminal.c_card_no", "t_m_merchant.i_merchant"
|
||||
// )
|
||||
// .leftJoin("t_m_partner", "t_m_merchant.i_partner", "t_m_partner.i_partner")
|
||||
.where("t_d_card_replacement.c_method", "CASHLESS")
|
||||
// .where("t_d_card_replacement.c_status", "OP")
|
||||
.where("t_d_card_replacement.i_last_balance", amount)
|
||||
.where("t_d_card_replacement.c_request_no", partner_trx_id)
|
||||
.where("t_d_card_replacement.c_refund_trx_id", trx_id)
|
||||
.where("t_d_card_replacement.c_bank_code", recipient_bank)
|
||||
.where("t_d_card_replacement.c_account_number", recipient_account)
|
||||
// .whereNull("t_d_card_replacement.c_status", "OP")
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// UPDATE REPLACEMENT
|
||||
const updateReplacementComplete = (i_replacement, request_no, date_disburse) => {
|
||||
let result = knex("trx.t_d_card_replacement")
|
||||
.where("i_card_replacement", i_replacement)
|
||||
.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({
|
||||
c_status: "A",
|
||||
c_status_name: "COMPLETED",
|
||||
d_disburse: date_disburse,
|
||||
c_response_code: "000",
|
||||
c_response_message: "Success"
|
||||
});
|
||||
return result;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
checkRedeem,
|
||||
updateReplacementComplete
|
||||
};
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,24 +1,14 @@
|
||||
const knex = require("../../../infrastructure/database/knex");
|
||||
const knex = require('../../../infrastructure/database/knex');
|
||||
const createTransactionNumberAllocator = require('../../../infrastructure/database/transaction-number');
|
||||
const allocateTransactionNumber = createTransactionNumberAllocator(knex);
|
||||
|
||||
const allocateReservationNumber = (partnerCode, date) => allocateTransactionNumber('RBL', partnerCode, date);
|
||||
|
||||
// CHECK CARD NUMBER
|
||||
const checkCardNumber = (cardNumber) => {
|
||||
let result = knex("t_m_card_product")
|
||||
.where("c_card_number", cardNumber)
|
||||
.where("c_status", "!=", "X")
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET RESERVATION
|
||||
const getReservationNumberSequence = (data, date) => {
|
||||
console.log('AKU DIPANGGIL');
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.select("i_reservation_no_seq")
|
||||
.orderBy("i_reservation_no_seq", "desc")
|
||||
.whereNotNull("i_reservation_no_seq")
|
||||
.where("i_partner", data.i_partner)
|
||||
.where("i_merchant", data.i_merchant)
|
||||
.whereRaw("??::date = ?", ["d_reservation", date])
|
||||
let result = knex('t_m_card_product')
|
||||
.where('c_card_number', cardNumber)
|
||||
.where('c_status', '!=', 'X')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
@@ -27,236 +17,330 @@ const getReservationNumberSequence = (data, date) => {
|
||||
const getPartner = (mid, tid) => {
|
||||
let result = knex
|
||||
.select(
|
||||
"t_m_partner.i_partner",
|
||||
"t_m_partner.c_code as partner_code",
|
||||
"t_m_partner.c_name as partner_name",
|
||||
"t_m_merchant.i_merchant",
|
||||
"t_m_merchant.c_code as merchant_code",
|
||||
"t_m_merchant.c_name as merchant_name",
|
||||
"t_m_merchant.e_mid as mid",
|
||||
"t_m_terminal.i_terminal",
|
||||
"t_m_terminal.c_code as terminal_code",
|
||||
"t_m_terminal.c_name as terminal_name",
|
||||
"t_m_terminal.e_tid as tid"
|
||||
't_m_partner.i_partner',
|
||||
't_m_partner.c_code as partner_code',
|
||||
't_m_partner.c_name as partner_name',
|
||||
't_m_merchant.i_merchant',
|
||||
't_m_merchant.c_code as merchant_code',
|
||||
't_m_merchant.c_name as merchant_name',
|
||||
't_m_merchant.e_mid as mid',
|
||||
't_m_terminal.i_terminal',
|
||||
't_m_terminal.c_code as terminal_code',
|
||||
't_m_terminal.c_name as terminal_name',
|
||||
't_m_terminal.e_tid as tid'
|
||||
)
|
||||
.from("t_m_terminal")
|
||||
.from('t_m_terminal')
|
||||
.leftJoin(
|
||||
"t_m_merchant",
|
||||
"t_m_terminal.i_merchant",
|
||||
"t_m_merchant.i_merchant"
|
||||
't_m_merchant',
|
||||
't_m_terminal.i_merchant',
|
||||
't_m_merchant.i_merchant'
|
||||
)
|
||||
.leftJoin("t_m_partner", "t_m_merchant.i_partner", "t_m_partner.i_partner")
|
||||
.where("t_m_merchant.e_mid", mid)
|
||||
.where("t_m_terminal.e_tid", tid)
|
||||
.where("t_m_terminal.c_status", "A")
|
||||
.where("t_m_merchant.c_status", "A")
|
||||
.where("t_m_partner.c_status", "A")
|
||||
.leftJoin('t_m_partner', 't_m_merchant.i_partner', 't_m_partner.i_partner')
|
||||
.where('t_m_merchant.e_mid', mid)
|
||||
.where('t_m_terminal.e_tid', tid)
|
||||
.where('t_m_terminal.c_status', 'A')
|
||||
.where('t_m_merchant.c_status', 'A')
|
||||
.where('t_m_partner.c_status', 'A')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET ISSUER FEE
|
||||
const getIssuer = (id, time) => {
|
||||
let result = knex("t_c_partner_fee")
|
||||
.select("i_issuer_fee_perc", "i_channel_fee_perc", "i_amount")
|
||||
.where("i_partner", id)
|
||||
.where("c_status", "A")
|
||||
.where("d_valid", "<=", time)
|
||||
.orderBy("d_valid", "desc")
|
||||
let result = knex('t_c_partner_fee')
|
||||
.select(
|
||||
'i_issuer_fee_perc',
|
||||
'i_channel_fee_perc',
|
||||
'i_amount',
|
||||
'i_issuer_fee_nominal',
|
||||
'i_channel_fee_nominal'
|
||||
)
|
||||
.where('i_partner', id)
|
||||
.where('c_status', 'A')
|
||||
.where('d_valid', '<=', time)
|
||||
.orderBy('d_valid', 'desc')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET RESERVATION EXPIRATION DATE FROM GLOBAL PARAMETER
|
||||
const getReservationExpirationDateValue = () => {
|
||||
let result = knex("t_m_global_parameter")
|
||||
.select("c_value")
|
||||
.where("c_code", "HSM_EXP_RSV_VAL")
|
||||
.where("c_status", "A")
|
||||
// GET IS CARD ADDED TO BLACKLIST
|
||||
const getCardBlacklist = (card_number) => {
|
||||
let result = knex('public.t_m_card_blacklist')
|
||||
.select('c_status')
|
||||
.where('c_card_number', card_number)
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET RESERVATION EXPIRATION DATE MEASURE FROM GLOBAL PARAMETER
|
||||
const getReservationExpirationDateMeasure = () => {
|
||||
let result = knex("t_m_global_parameter")
|
||||
.select("c_value")
|
||||
.where("c_code", "HSM_EXP_RSV_MEA")
|
||||
.where("c_status", "A")
|
||||
.first();
|
||||
return result;
|
||||
// Baca nilai dan satuan dalam satu snapshot agar konfigurasi tetap konsisten.
|
||||
const getReservationExpiration = async () => {
|
||||
const rows = await knex('t_m_global_parameter')
|
||||
.select('c_code', 'c_value')
|
||||
.whereIn('c_code', ['HSM_EXP_RSV_VAL', 'HSM_EXP_RSV_MEA'])
|
||||
.where('c_status', 'A');
|
||||
const value = rows.find(({ c_code }) => c_code === 'HSM_EXP_RSV_VAL')?.c_value;
|
||||
const unit = rows.find(({ c_code }) => c_code === 'HSM_EXP_RSV_MEA')?.c_value;
|
||||
return { time: value ? parseInt(value) : 1, measure: unit || 'hours' };
|
||||
};
|
||||
|
||||
// GET CHECKING CARD PRODUCT FROM GLOBAL PARAMETER
|
||||
const getCheckByCardProductStatusValue = () => {
|
||||
let result = knex("t_m_global_parameter")
|
||||
.select("c_value")
|
||||
.where("c_code", "HSM_CHECK_BY_CARD_PRODUCT_STAT")
|
||||
.where("c_status", "A")
|
||||
let result = knex('t_m_global_parameter')
|
||||
.select('c_value')
|
||||
.where('c_code', 'HSM_CHECK_BY_CARD_PRODUCT_STAT')
|
||||
.where('c_status', 'A')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET BI REGULATION STATUS FROM GLOBAL PARAMETER
|
||||
const getBIRegulationStatus = () => {
|
||||
let result = knex("t_m_global_parameter")
|
||||
.select("c_value")
|
||||
.where("c_code", "HSM_BI_REGULATION_STAT")
|
||||
.where("c_status", "A")
|
||||
let result = knex('t_m_global_parameter')
|
||||
.select('c_value')
|
||||
.where('c_code', 'HSM_BI_REGULATION_STAT')
|
||||
.where('c_status', 'A')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET MAX AMOUNT ON THE CARD FROM GLOBAL PARAMETER
|
||||
const getMaxAmountOnTheCard = () => {
|
||||
let result = knex("t_m_global_parameter")
|
||||
.select("c_value")
|
||||
.where("c_code", "HSM_BI_MAX_AMOUNT_ON_THE_CARD")
|
||||
.where("c_status", "A")
|
||||
let result = knex('t_m_global_parameter')
|
||||
.select('c_value')
|
||||
.where('c_code', 'HSM_BI_MAX_AMOUNT_ON_THE_CARD')
|
||||
.where('c_status', 'A')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET MAX TOPUP PER MONTH FROM GLOBAL PARAMETER
|
||||
const getMaxTopupPerMonth = () => {
|
||||
let result = knex("t_m_global_parameter")
|
||||
.select("c_value")
|
||||
.where("c_code", "HSM_BI_MAX_TOPUP_PER_MONTH")
|
||||
.where("c_status", "A")
|
||||
let result = knex('t_m_global_parameter')
|
||||
.select('c_value')
|
||||
.where('c_code', 'HSM_BI_MAX_TOPUP_PER_MONTH')
|
||||
.where('c_status', 'A')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET MAX RESERVATION FROM GLOBAL PARAMETER
|
||||
const getMaxReservation = () => {
|
||||
let result = knex("t_m_global_parameter")
|
||||
.select("c_value")
|
||||
.where("c_code", "HSM_MAX_RSV_PEN")
|
||||
.where("c_status", "A")
|
||||
let result = knex('t_m_global_parameter')
|
||||
.select('c_value')
|
||||
.where('c_code', 'HSM_MAX_RSV_PEN')
|
||||
.where('c_status', 'A')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// INQUIRY BY RESERVATION NUMBER
|
||||
let inquiryByReservationNumber = (reservationNumber) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.select(
|
||||
"c_reservation_no as reservation_number",
|
||||
"d_reservation as reservation_date",
|
||||
"c_ref_no as ref_no",
|
||||
"c_partner_name as partner_name",
|
||||
"c_merchant_name as merchant_name",
|
||||
"c_terminal_name as terminal_name",
|
||||
"c_card_number as card_number",
|
||||
"i_reservation_amount as reservation_amount",
|
||||
"i_issuer_fee as issuer_fee",
|
||||
"i_channel_fee as channel_fee",
|
||||
"c_payment_recon_no as payment_recon_no",
|
||||
"d_payment_recon as recon_date",
|
||||
"c_status as status_code",
|
||||
"c_status_name as description"
|
||||
)
|
||||
.where("c_reservation_no", reservationNumber)
|
||||
const inquiryByReservationNumber = (reservationNumber, show_complete_data) => {
|
||||
let result = knex('trx.t_d_reservation_balance');
|
||||
if (show_complete_data === true) {
|
||||
result.select(
|
||||
'trx.t_d_reservation_balance.c_reservation_no as reservation_number',
|
||||
'trx.t_d_reservation_balance.d_reservation as reservation_date',
|
||||
'trx.t_d_reservation_balance.c_ref_no as ref_no',
|
||||
'trx.t_d_reservation_balance.c_partner_name as partner_name_reservation',
|
||||
'trx.t_d_reservation_balance.c_merchant_name as merchant_name_reservation',
|
||||
'trx.t_d_reservation_balance.c_terminal_name as terminal_name_reservation',
|
||||
'trx.t_d_load_balance.d_load_balance as load_date',
|
||||
'trx.t_d_load_balance.c_partner_name as partner_name_load',
|
||||
'trx.t_d_load_balance.c_merchant_name as merchant_name_load',
|
||||
'trx.t_d_load_balance.c_terminal_name as terminal_name_load',
|
||||
'trx.t_d_reservation_balance.c_card_number as card_number',
|
||||
'trx.t_d_reservation_balance.i_reservation_amount as amount',
|
||||
'trx.t_d_reservation_balance.i_issuer_fee as issuer_fee',
|
||||
'trx.t_d_reservation_balance.i_channel_fee as channel_fee',
|
||||
'trx.t_d_reservation_balance.c_payment_recon_no as payment_recon_no',
|
||||
'trx.t_d_reservation_balance.d_payment_recon as recon_date',
|
||||
'trx.t_d_reservation_balance.c_status as status_code',
|
||||
'trx.t_d_reservation_balance.c_status_name as description'
|
||||
);
|
||||
} else {
|
||||
result.select(
|
||||
'trx.t_d_reservation_balance.c_reservation_no as reservation_number',
|
||||
'trx.t_d_reservation_balance.d_reservation as reservation_date',
|
||||
'trx.t_d_reservation_balance.c_ref_no as ref_no',
|
||||
'trx.t_d_reservation_balance.c_partner_name as partner_name_reservation',
|
||||
'trx.t_d_load_balance.d_load_balance as load_date',
|
||||
'trx.t_d_load_balance.c_partner_name as partner_name_load',
|
||||
'trx.t_d_reservation_balance.c_card_number as card_number',
|
||||
'trx.t_d_reservation_balance.i_reservation_amount as amount',
|
||||
'trx.t_d_reservation_balance.c_status as status_code',
|
||||
'trx.t_d_reservation_balance.c_status_name as description'
|
||||
);
|
||||
}
|
||||
|
||||
result.leftJoin('trx.t_d_load_balance', function () {
|
||||
this.on(
|
||||
'trx.t_d_reservation_balance.c_load_balance_no',
|
||||
'=',
|
||||
'trx.t_d_load_balance.c_load_balance_no'
|
||||
);
|
||||
});
|
||||
|
||||
result = result
|
||||
.where('trx.t_d_reservation_balance.c_reservation_no', reservationNumber)
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// INQUIRY LIST RESERVATION
|
||||
let inquiryListReservation = (partnerID, startDate, endDate) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.select(
|
||||
"c_reservation_no as reservation_number",
|
||||
"d_reservation as reservation_date",
|
||||
"c_ref_no as ref_no",
|
||||
"c_partner_name as partner_name",
|
||||
"c_merchant_name as merchant_name",
|
||||
"c_terminal_name as terminal_name",
|
||||
"c_card_number as card_number",
|
||||
"i_reservation_amount as reservation_amount",
|
||||
"i_issuer_fee as issuer_fee",
|
||||
"i_channel_fee as channel_fee",
|
||||
"c_payment_recon_no as payment_recon_no",
|
||||
"d_payment_recon as recon_date",
|
||||
"c_status as status_code",
|
||||
"c_status_name as description"
|
||||
)
|
||||
.where("i_partner", partnerID);
|
||||
|
||||
if (startDate && endDate) {
|
||||
result.whereRaw("??::date >= ?", ["d_reservation", startDate]);
|
||||
result.whereRaw("??::date <= ?", ["d_reservation", endDate]);
|
||||
}
|
||||
const inquiryListReservation = (partnerID, startDate, endDate) => {
|
||||
let result = knex('trx.t_d_reservation_balance');
|
||||
result.select(
|
||||
'trx.t_d_reservation_balance.c_reservation_no as reservation_number',
|
||||
'trx.t_d_reservation_balance.d_reservation as reservation_date',
|
||||
'trx.t_d_reservation_balance.c_ref_no as ref_no',
|
||||
'trx.t_d_reservation_balance.c_partner_name as partner_name_reservation',
|
||||
'trx.t_d_reservation_balance.c_merchant_name as merchant_name_reservation',
|
||||
'trx.t_d_reservation_balance.c_terminal_name as terminal_name_reservation',
|
||||
'trx.t_d_load_balance.d_load_balance as load_date',
|
||||
'trx.t_d_load_balance.c_partner_name as partner_name_load',
|
||||
'trx.t_d_load_balance.c_merchant_name as merchant_name_load',
|
||||
'trx.t_d_load_balance.c_terminal_name as terminal_name_load',
|
||||
'trx.t_d_reservation_balance.c_card_number as card_number',
|
||||
'trx.t_d_reservation_balance.i_reservation_amount as amount',
|
||||
'trx.t_d_reservation_balance.i_issuer_fee as issuer_fee',
|
||||
'trx.t_d_reservation_balance.i_channel_fee as channel_fee',
|
||||
'trx.t_d_reservation_balance.c_payment_recon_no as payment_recon_no',
|
||||
'trx.t_d_reservation_balance.d_payment_recon as recon_date',
|
||||
'trx.t_d_reservation_balance.c_status as status_code',
|
||||
'trx.t_d_reservation_balance.c_status_name as description'
|
||||
);
|
||||
|
||||
result.leftJoin('trx.t_d_load_balance', function () {
|
||||
this.on(
|
||||
'trx.t_d_reservation_balance.c_load_balance_no',
|
||||
'=',
|
||||
'trx.t_d_load_balance.c_load_balance_no'
|
||||
);
|
||||
});
|
||||
|
||||
result.where('trx.t_d_reservation_balance.i_partner', partnerID);
|
||||
|
||||
if (startDate && endDate) {
|
||||
result.whereRaw('??::date >= ?', [
|
||||
'trx.t_d_reservation_balance.d_reservation',
|
||||
startDate,
|
||||
]);
|
||||
result.whereRaw('??::date <= ?', [
|
||||
'trx.t_d_reservation_balance.d_reservation',
|
||||
endDate,
|
||||
]);
|
||||
}
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// INQUIRY BY CARD NUMBER
|
||||
let inquiryByCardNumber = (cardNumber, startDate, endDate) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
const inquiryByCardNumber = (cardNumber, startDate, endDate) => {
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.select(
|
||||
"c_reservation_no as reservation_number",
|
||||
"d_reservation as reservation_date",
|
||||
"c_ref_no as ref_no",
|
||||
"c_partner_name as partner_name",
|
||||
"c_merchant_name as merchant_name",
|
||||
"c_terminal_name as terminal_name",
|
||||
"c_card_number as card_number",
|
||||
"i_reservation_amount as reservation_amount",
|
||||
"i_issuer_fee as issuer_fee",
|
||||
"i_channel_fee as channel_fee",
|
||||
"c_status as status_code",
|
||||
"c_status_name as description"
|
||||
'c_reservation_no as reservation_number',
|
||||
'd_reservation as reservation_date',
|
||||
'c_ref_no as ref_no',
|
||||
'c_partner_name as partner_name',
|
||||
'c_merchant_name as merchant_name',
|
||||
'c_terminal_name as terminal_name',
|
||||
'c_card_number as card_number',
|
||||
'i_reservation_amount as amount',
|
||||
'i_issuer_fee as issuer_fee',
|
||||
'i_channel_fee as channel_fee',
|
||||
'c_status as status_code',
|
||||
'c_status_name as description'
|
||||
)
|
||||
.where("c_card_number", cardNumber);
|
||||
.where('c_card_number', cardNumber);
|
||||
|
||||
if (startDate && endDate) {
|
||||
result.whereRaw("??::date >= ?", ["d_reservation", startDate]);
|
||||
result.whereRaw("??::date <= ?", ["d_reservation", endDate]);
|
||||
result.whereRaw('??::date >= ?', ['d_reservation', startDate]);
|
||||
result.whereRaw('??::date <= ?', ['d_reservation', endDate]);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET RESERVATION PENDING
|
||||
const getReservationPending = (cardNumber, time) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.count("* as total_reservation")
|
||||
.sum("i_reservation_amount as total_nominal_reservation")
|
||||
.where("c_card_number", cardNumber)
|
||||
.where("c_status", "P")
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.count('* as total_reservation')
|
||||
.sum('i_reservation_amount as total_nominal_reservation')
|
||||
.where('c_card_number', cardNumber)
|
||||
.where('c_status', 'P')
|
||||
.whereRaw(
|
||||
`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)
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
const getReservationPendingV2 = (cardNumber, time) => {
|
||||
let 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_partner_name',
|
||||
'c_flag',
|
||||
'd_reservation',
|
||||
'c_ref_no',
|
||||
'c_card_number',
|
||||
'c_status'
|
||||
)
|
||||
.where('c_card_number', cardNumber)
|
||||
.where('c_status', 'P')
|
||||
.whereRaw(
|
||||
`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;
|
||||
};
|
||||
|
||||
// GET RESERVATION WITH FLAG
|
||||
const getReservationWithFlag = (cardNumber, time) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.count("* as total_reservation")
|
||||
.where("c_card_number", cardNumber)
|
||||
.whereIn("c_status", ["P", "I"])
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.count('* as total_reservation')
|
||||
.where('c_card_number', cardNumber)
|
||||
.whereIn('c_status', ['P', 'I'])
|
||||
// .where("d_expired", ">=", time)
|
||||
.whereNotNull("c_flag")
|
||||
.whereNotNull('c_flag')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// INSERT RESERVATION
|
||||
const insertReservation = (data) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.insert(data)
|
||||
.onConflict("c_ref_no")
|
||||
.onConflict('c_ref_no')
|
||||
.ignore();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET LAST BALANCE FROM CARD HISTORY
|
||||
const getLastBalanceFromCardHistory = (cardNumber) => {
|
||||
let result = knex("log.t_log_card")
|
||||
.select("m_balance_after")
|
||||
.where("c_card_number", cardNumber)
|
||||
.where("c_status", "S")
|
||||
.where("m_balance_after", ">", 0)
|
||||
.orderBy("d_log", "desc")
|
||||
let result = knex('log.t_log_card')
|
||||
.select('m_balance_after')
|
||||
.where('c_card_number', cardNumber)
|
||||
.where('c_status', 'S')
|
||||
.where('m_balance_after', '>', 0)
|
||||
.orderBy('d_log', 'desc')
|
||||
.limit(1)
|
||||
.first();
|
||||
return result;
|
||||
@@ -268,73 +352,184 @@ const getAccumulationBalanceInThisMonthFromCardHistory = (
|
||||
year,
|
||||
month
|
||||
) => {
|
||||
let result = knex("log.t_log_card")
|
||||
.sum("m_amount as accumulation_balance")
|
||||
.where("c_card_number", cardNumber)
|
||||
.where("c_status", "S")
|
||||
.where("m_balance_after", ">", 0)
|
||||
.whereRaw("DATE_PART('YEAR', ??) = ?", ["d_log", year])
|
||||
.whereRaw("DATE_PART('MONTH', ??) = ?", ["d_log", month])
|
||||
.whereIn("i_log_name", [21])
|
||||
.groupBy("c_card_number")
|
||||
let result = knex('log.t_log_card')
|
||||
.sum('m_amount as accumulation_balance')
|
||||
.where('c_card_number', cardNumber)
|
||||
.where('c_status', 'S')
|
||||
.where('m_balance_after', '>', 0)
|
||||
.whereRaw('?? >= make_date(?, ?, 1)', ['d_log', year, month])
|
||||
.whereRaw("?? < make_date(?, ?, 1) + interval '1 month'", ['d_log', year, month])
|
||||
.whereIn('i_log_name', [21])
|
||||
.groupBy('c_card_number')
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// CREATE LOG FOR CARD HISTORY
|
||||
const createReserveBalanceLog = (data) => {
|
||||
let result = knex("log.t_log_card").insert(data);
|
||||
let result = knex('log.t_log_card').insert(data);
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET RESERVATION PENDING AND IN PROGRESS
|
||||
const getReservationWithPendingAndInProgressStatus = (cardNumber) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.count("* as total_reservation_pending")
|
||||
.where("c_card_number", cardNumber)
|
||||
.whereIn("c_status", ["P", "I"])
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.count('* as total_reservation_pending')
|
||||
.where('c_card_number', cardNumber)
|
||||
.whereIn('c_status', ['P', 'I'])
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
// GET RESERVATION PENDING AND NOT YET PAYMENT RECON
|
||||
const getReservationCanBeCanceled = (reservation_number) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
.where("c_reservation_no", reservation_number)
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.where('c_reservation_no', reservation_number)
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
const insertReservationNumber = (reservationNumber) => {
|
||||
let result = knex("trx.t_d_reservation_no_validate")
|
||||
.insert({
|
||||
c_reservation_no: reservationNumber,
|
||||
})
|
||||
.onConflict("c_reservation_no")
|
||||
.ignore();
|
||||
// GET RESERVATION PENDING AND NOT YET PAYMENT RECON
|
||||
const getReservationCanBeCanceledByRefno = (ref_no) => {
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.where('c_ref_no', ref_no)
|
||||
.first();
|
||||
return result;
|
||||
};
|
||||
|
||||
const cancelReservation = (data, reservationNumber) => {
|
||||
let result = knex("trx.t_d_reservation_balance")
|
||||
let result = knex('trx.t_d_reservation_balance')
|
||||
.update(data)
|
||||
.where("c_reservation_no", reservationNumber);
|
||||
.where('c_reservation_no', reservationNumber);
|
||||
return result;
|
||||
};
|
||||
const deleteReservationNumberValidate = (reservationNumber) => {
|
||||
let result = knex("trx.t_d_reservation_no_validate")
|
||||
.where("c_reservation_no", reservationNumber)
|
||||
.del();
|
||||
// INQUIRY BY REF NUMBER
|
||||
const inquiryListByRefNumber = (refNumber, show_complete_data) => {
|
||||
let result = knex('trx.t_d_reservation_balance');
|
||||
if (show_complete_data === true) {
|
||||
result.select(
|
||||
'trx.t_d_reservation_balance.c_reservation_no as reservation_number',
|
||||
'trx.t_d_reservation_balance.d_reservation as reservation_date',
|
||||
'trx.t_d_reservation_balance.c_ref_no as ref_no',
|
||||
'trx.t_d_reservation_balance.c_partner_name as partner_name_reservation',
|
||||
'trx.t_d_reservation_balance.c_merchant_name as merchant_name_reservation',
|
||||
'trx.t_d_reservation_balance.c_terminal_name as terminal_name_reservation',
|
||||
'trx.t_d_load_balance.d_load_balance as load_date',
|
||||
'trx.t_d_load_balance.c_partner_name as partner_name_load',
|
||||
'trx.t_d_load_balance.c_merchant_name as merchant_name_load',
|
||||
'trx.t_d_load_balance.c_terminal_name as terminal_name_load',
|
||||
'trx.t_d_reservation_balance.c_card_number as card_number',
|
||||
'trx.t_d_reservation_balance.i_reservation_amount as amount',
|
||||
'trx.t_d_reservation_balance.i_issuer_fee as issuer_fee',
|
||||
'trx.t_d_reservation_balance.i_channel_fee as channel_fee',
|
||||
'trx.t_d_reservation_balance.c_status as status_code',
|
||||
'trx.t_d_reservation_balance.c_status_name as description'
|
||||
);
|
||||
} else {
|
||||
result.select(
|
||||
'trx.t_d_reservation_balance.c_reservation_no as reservation_number',
|
||||
'trx.t_d_reservation_balance.d_reservation as reservation_date',
|
||||
'trx.t_d_reservation_balance.c_ref_no as ref_no',
|
||||
'trx.t_d_reservation_balance.c_partner_name as partner_name_reservation',
|
||||
'trx.t_d_load_balance.d_load_balance as load_date',
|
||||
'trx.t_d_load_balance.c_partner_name as partner_name_load',
|
||||
'trx.t_d_reservation_balance.c_card_number as card_number',
|
||||
'trx.t_d_reservation_balance.i_reservation_amount as amount',
|
||||
'trx.t_d_reservation_balance.c_status as status_code',
|
||||
'trx.t_d_reservation_balance.c_status_name as description'
|
||||
);
|
||||
}
|
||||
|
||||
result.leftJoin('trx.t_d_load_balance', function () {
|
||||
this.on(
|
||||
'trx.t_d_reservation_balance.c_load_balance_no',
|
||||
'=',
|
||||
'trx.t_d_load_balance.c_load_balance_no'
|
||||
);
|
||||
});
|
||||
|
||||
result = result.where('trx.t_d_reservation_balance.c_ref_no', refNumber).first();
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
// ================================================================= INQUIRY LOAD BALANCE =================================================================
|
||||
// *Created By: Teddy Setiawan*
|
||||
// *Description:*
|
||||
//
|
||||
|
||||
// INQUIRY BY LOAD BALANCE NUMBER
|
||||
const inquiryListByLoadNumber = (load_balance_number, show_complete_data) => {
|
||||
let result = knex('trx.t_d_reservation_balance');
|
||||
|
||||
if (show_complete_data === true) {
|
||||
result.select(
|
||||
'trx.t_d_reservation_balance.c_reservation_no as reservation_number',
|
||||
'trx.t_d_reservation_balance.d_reservation as reservation_date',
|
||||
'trx.t_d_reservation_balance.c_ref_no as ref_no',
|
||||
'trx.t_d_reservation_balance.c_partner_name as partner_name_reservation',
|
||||
'trx.t_d_reservation_balance.c_merchant_name as merchant_name_reservation',
|
||||
'trx.t_d_reservation_balance.c_terminal_name as terminal_name_reservation',
|
||||
'trx.t_d_load_balance.d_load_balance as load_date',
|
||||
'trx.t_d_load_balance.c_partner_name as partner_name_load',
|
||||
'trx.t_d_load_balance.c_merchant_name as merchant_name_load',
|
||||
'trx.t_d_load_balance.c_terminal_name as terminal_name_load',
|
||||
'trx.t_d_reservation_balance.c_card_number as card_number',
|
||||
'trx.t_d_reservation_balance.i_reservation_amount as amount',
|
||||
'trx.t_d_reservation_balance.i_issuer_fee as issuer_fee',
|
||||
'trx.t_d_reservation_balance.i_channel_fee as channel_fee',
|
||||
'trx.t_d_reservation_balance.c_payment_recon_no as payment_recon_no',
|
||||
'trx.t_d_reservation_balance.d_payment_recon as recon_date',
|
||||
'trx.t_d_reservation_balance.c_status as status_code',
|
||||
'trx.t_d_reservation_balance.c_status_name as description'
|
||||
);
|
||||
} else {
|
||||
result.select(
|
||||
'trx.t_d_reservation_balance.c_reservation_no as reservation_number',
|
||||
'trx.t_d_reservation_balance.d_reservation as reservation_date',
|
||||
'trx.t_d_reservation_balance.c_ref_no as ref_no',
|
||||
'trx.t_d_reservation_balance.c_partner_name as partner_name_reservation',
|
||||
'trx.t_d_load_balance.d_load_balance as load_date',
|
||||
'trx.t_d_load_balance.c_partner_name as partner_name_load',
|
||||
'trx.t_d_reservation_balance.c_card_number as card_number',
|
||||
'trx.t_d_reservation_balance.i_reservation_amount as amount',
|
||||
'trx.t_d_reservation_balance.c_status as status_code',
|
||||
'trx.t_d_reservation_balance.c_status_name as description'
|
||||
);
|
||||
}
|
||||
|
||||
result
|
||||
.leftJoin('trx.t_d_load_balance', function () {
|
||||
this.on(
|
||||
'trx.t_d_reservation_balance.c_load_balance_no',
|
||||
'=',
|
||||
'trx.t_d_load_balance.c_load_balance_no'
|
||||
);
|
||||
})
|
||||
.where(
|
||||
'trx.t_d_reservation_balance.c_load_balance_no',
|
||||
load_balance_number
|
||||
);
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
const getGlobalParameter = () => {
|
||||
let result = knex('t_m_global_parameter')
|
||||
.select('c_value')
|
||||
.where('c_code', '=', 'HSM_CANCEL_RESERVATION_LEVEL')
|
||||
.first();
|
||||
|
||||
return result;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
checkCardNumber,
|
||||
getReservationNumberSequence,
|
||||
allocateReservationNumber,
|
||||
getPartner,
|
||||
getIssuer,
|
||||
getReservationExpirationDateValue,
|
||||
getReservationExpirationDateMeasure,
|
||||
getCardBlacklist,
|
||||
getReservationExpiration,
|
||||
getCheckByCardProductStatusValue,
|
||||
getBIRegulationStatus,
|
||||
getMaxAmountOnTheCard,
|
||||
@@ -344,6 +539,7 @@ module.exports = {
|
||||
inquiryListReservation,
|
||||
inquiryByCardNumber,
|
||||
getReservationPending,
|
||||
getReservationPendingV2,
|
||||
getReservationWithFlag,
|
||||
insertReservation,
|
||||
getLastBalanceFromCardHistory,
|
||||
@@ -351,7 +547,9 @@ module.exports = {
|
||||
createReserveBalanceLog,
|
||||
getReservationWithPendingAndInProgressStatus,
|
||||
getReservationCanBeCanceled,
|
||||
insertReservationNumber,
|
||||
getReservationCanBeCanceledByRefno,
|
||||
cancelReservation,
|
||||
deleteReservationNumberValidate,
|
||||
inquiryListByRefNumber,
|
||||
getGlobalParameter,
|
||||
inquiryListByLoadNumber,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
const { body } = require('express-validator');
|
||||
|
||||
// Aturan input untuk setiap operasi. Urutan validasi mengikuti kontrak API.
|
||||
const validate = (method) => {
|
||||
switch (method) {
|
||||
case 'checkReservation':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card Number is required'),
|
||||
];
|
||||
case 'reservationValidate':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card Number is required'),
|
||||
body('amount')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Amount is required')
|
||||
.isNumeric()
|
||||
.withMessage('Amount is invalid format'),
|
||||
];
|
||||
case 'reservation':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('card_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Card Number is required'),
|
||||
body('ref_no').not().isEmpty().withMessage('Ref No is required'),
|
||||
body('amount')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Amount is required')
|
||||
.isNumeric()
|
||||
.withMessage('Amount is invalid format'),
|
||||
];
|
||||
case 'reservationV2':
|
||||
return [
|
||||
body('reservation_data')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Reservation data is required'),
|
||||
body('ref_no').not().isEmpty().withMessage('Ref No is required'),
|
||||
];
|
||||
case 'cancelReservation':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
body('reservation_number')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Reservation Number is required'),
|
||||
];
|
||||
case 'cancelReservationValidateV2':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
];
|
||||
case 'cancelReservationV2':
|
||||
return [
|
||||
body('cancel_reservation_data')
|
||||
.not()
|
||||
.isEmpty()
|
||||
.withMessage('Cancel Reservation data is required'),
|
||||
];
|
||||
case 'getFeeSharing':
|
||||
return [
|
||||
body('mid').not().isEmpty().withMessage('MID is required'),
|
||||
body('tid').not().isEmpty().withMessage('TID is required'),
|
||||
];
|
||||
default:
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
module.exports = validate;
|
||||
@@ -10,6 +10,27 @@ router.get(
|
||||
controller.apiGenerateCahsIn
|
||||
);
|
||||
|
||||
router.get(
|
||||
"/online/cash-in-sales",
|
||||
// auth.authenticateToken,
|
||||
// controller.validate("generateInvoice"),
|
||||
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(
|
||||
"/online/cash-in/posting",
|
||||
// auth.authenticateToken,
|
||||
|
||||
@@ -1,43 +1,82 @@
|
||||
const { Router } = require("express");
|
||||
const { Router } = require('express');
|
||||
const router = Router();
|
||||
|
||||
const auth = require("../middlewares/jwt.middleware");
|
||||
const _readData = require("../modules/hsm/readData");
|
||||
const _readDataResp = require("../modules/hsm/readDataResp");
|
||||
const auth = require('../middlewares/jwt.middleware');
|
||||
|
||||
const _auth1 = require("../modules/hsm/authenticate1");
|
||||
const _auth2 = require("../modules/hsm/authenticate2");
|
||||
const _authResp = require("../modules/hsm/authenticateResp");
|
||||
// Topup
|
||||
const _auth1 = require('../modules/hsm/topup/topup_1');
|
||||
const _auth2 = require('../modules/hsm/topup/topup_2');
|
||||
const _authResp = require('../modules/hsm/topup/topup_3');
|
||||
|
||||
const _topup = require("../modules/hsm/topup");
|
||||
const _topupResp = require("../modules/hsm/topupResp");
|
||||
const _readData = require('../modules/hsm/topup/topup_4');
|
||||
const _readDataResp = require('../modules/hsm/topup/topup_5');
|
||||
|
||||
const _end = require("../modules/hsm/endTranscation");
|
||||
const _topup = require('../modules/hsm/topup/topup_6');
|
||||
const _topupResp = require('../modules/hsm/topup/topup_7');
|
||||
|
||||
const _getService = require("../modules/hsm/service_block");
|
||||
const _end = require('../modules/hsm/topup/topup_8');
|
||||
|
||||
const _getService = require('../modules/hsm/topup/service_block');
|
||||
|
||||
router.post("/topup1", auth.authenticateToken, _auth1);
|
||||
router.post("/topup2", auth.authenticateToken, _auth2);
|
||||
router.post("/topup3", auth.authenticateToken, _authResp);
|
||||
router.post("/topup4", auth.authenticateToken, _readData);
|
||||
router.post("/topup5", auth.authenticateToken, _readDataResp);
|
||||
router.post('/topup1', auth.authenticateToken, _auth1);
|
||||
router.post('/topup2', auth.authenticateToken, _auth2);
|
||||
router.post('/topup3', auth.authenticateToken, _authResp);
|
||||
router.post('/topup4', auth.authenticateToken, _readData);
|
||||
router.post('/topup5', auth.authenticateToken, _readDataResp);
|
||||
|
||||
router.post(
|
||||
"/topup6",
|
||||
'/topup6',
|
||||
auth.authenticateToken,
|
||||
_topup.validate("topup"),
|
||||
_topup.validate('topup'),
|
||||
_topup.controller
|
||||
);
|
||||
router.post(
|
||||
"/topup7",
|
||||
'/topup7',
|
||||
auth.authenticateToken,
|
||||
_topupResp.validate("topupResponse"),
|
||||
_topupResp.validate('topupResponse'),
|
||||
_topupResp.controller
|
||||
);
|
||||
|
||||
router.post("/topup8", auth.authenticateToken, _end);
|
||||
router.post('/topup8', auth.authenticateToken, _end);
|
||||
|
||||
router.get("/getservice", auth.authenticateToken, _getService);
|
||||
router.get('/getservice', auth.authenticateToken, _getService);
|
||||
|
||||
// Clear Card
|
||||
const _authClear1 = require('../modules/hsm/clear_card/clear_1');
|
||||
const _authClear2 = require('../modules/hsm/clear_card/clear_2');
|
||||
const _authRespClear = require('../modules/hsm/clear_card/clear_3');
|
||||
|
||||
const _readDataClear = require('../modules/hsm/clear_card/clear_4');
|
||||
const _readDataRespClear = require('../modules/hsm/clear_card/clear_5');
|
||||
|
||||
const _clear = require('../modules/hsm/clear_card/clear_6');
|
||||
const _clearResp = require('../modules/hsm/clear_card/clear_7');
|
||||
|
||||
const _endClear = require('../modules/hsm/clear_card/clear_8');
|
||||
|
||||
const _getServiceClear = require('../modules/hsm/clear_card/service_block');
|
||||
|
||||
router.post('/clear1', auth.authenticateToken, _authClear1);
|
||||
router.post('/clear2', auth.authenticateToken, _authClear2);
|
||||
router.post('/clear3', auth.authenticateToken, _authRespClear);
|
||||
router.post('/clear4', auth.authenticateToken, _readDataClear);
|
||||
router.post('/clear5', auth.authenticateToken, _readDataRespClear);
|
||||
|
||||
router.post(
|
||||
'/clear6',
|
||||
auth.authenticateToken,
|
||||
_clear.validate('clear'),
|
||||
_clear.controller
|
||||
);
|
||||
router.post(
|
||||
'/clear7',
|
||||
auth.authenticateToken,
|
||||
_clearResp.validate('clearResponse'),
|
||||
_clearResp.controller
|
||||
);
|
||||
|
||||
router.post('/clear8', auth.authenticateToken, _endClear);
|
||||
|
||||
router.get('/clear/getservice', auth.authenticateToken, _getServiceClear);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -1,26 +1,13 @@
|
||||
const express = require("express");
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const auth = require("../middlewares/jwt.middleware");
|
||||
const controller = require("../modules/loadbalance/loadbalance.controller");
|
||||
const auth = require('../middlewares/jwt.middleware');
|
||||
const controller = require('../modules/loadbalance/loadbalance.controller');
|
||||
|
||||
router.post(
|
||||
"/loadbalance/request",
|
||||
'/loadbalance/request',
|
||||
auth.authenticateToken,
|
||||
controller.validate("loadingBalanceRequest"),
|
||||
controller.validate('loadingBalanceRequest'),
|
||||
controller.loadingBalanceRequest
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/loadbalance",
|
||||
auth.authenticateToken,
|
||||
controller.validate("loadingBalance"),
|
||||
controller.loadingBalance
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/loadbalance/inquiry",
|
||||
auth.authenticateToken,
|
||||
controller.inquiryLoadingBalance
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -1,25 +1,13 @@
|
||||
const express = require("express");
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const auth = require("../middlewares/jwt.middleware");
|
||||
const controller = require("../modules/paymentrecon/paymentrecon.controller");
|
||||
const auth = require('../middlewares/jwt.middleware');
|
||||
const controller = require('../modules/paymentrecon/paymentrecon.controller');
|
||||
|
||||
router.post(
|
||||
"/payment-recon",
|
||||
'/payment-recon',
|
||||
auth.authenticateToken,
|
||||
controller.validate("paymentRecon"),
|
||||
controller.validate('paymentRecon'),
|
||||
controller.paymentRecon
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/payment-recon/semi-topup-online",
|
||||
auth.authenticateToken,
|
||||
controller.validate("paymentReconSemiTopupOnline"),
|
||||
controller.paymentReconSemiTopupOnline
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/payment-recon/to-cms",
|
||||
controller.paymentReconToCMS
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const auth = require("../middlewares/jwt.middleware");
|
||||
const controller = require("../modules/pooling/pooling.controller");
|
||||
|
||||
router.post(
|
||||
"/validate-pooling",
|
||||
auth.authenticateToken,
|
||||
controller.validateData
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/insert-pooling",
|
||||
auth.authenticateToken,
|
||||
controller.insertPooling
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/insert-card-product",
|
||||
auth.authenticateToken,
|
||||
controller.insertCardProduct
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,111 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
const auth = require("../middlewares/jwt.middleware");
|
||||
const controller = require("../modules/pos/pos.controller");
|
||||
|
||||
// API Sample Get Last Balance
|
||||
router.post(
|
||||
"/pos/card-lastbalance",
|
||||
auth.authenticateToken,
|
||||
controller.validate("validateLastBalance"),
|
||||
controller.checkLastBalance
|
||||
);
|
||||
|
||||
// API Validate Sales MT
|
||||
router.post(
|
||||
"/pos/cardsales/validate",
|
||||
auth.authenticateToken,
|
||||
controller.validate("validateCardSales"),
|
||||
controller.validateSales
|
||||
);
|
||||
|
||||
// API Validate Topup MT
|
||||
router.post(
|
||||
"/pos/cardtopup/validate",
|
||||
auth.authenticateToken,
|
||||
controller.validate("validateCardTopup"),
|
||||
controller.validateTopup
|
||||
);
|
||||
|
||||
// API Validate Redeem MT
|
||||
router.post(
|
||||
"/pos/cardredeem/validate",
|
||||
auth.authenticateToken,
|
||||
controller.validate("validateCardRedeem"),
|
||||
controller.validateRedeem
|
||||
);
|
||||
|
||||
// API Check Blacklist
|
||||
router.post(
|
||||
"/pos/checkcardblacklist",
|
||||
auth.authenticateToken,
|
||||
controller.validate("checkBlacklist"),
|
||||
controller.checkBlacklist
|
||||
);
|
||||
|
||||
// API Validate Replacement MT
|
||||
router.post(
|
||||
"/pos/cardreplacement/validate",
|
||||
auth.authenticateToken,
|
||||
controller.validate("validateCardReplacement"),
|
||||
controller.validateReplacement
|
||||
);
|
||||
|
||||
// API Validate Replacement New Card
|
||||
router.post(
|
||||
"/pos/cardreplacement/validatenewcard",
|
||||
auth.authenticateToken,
|
||||
controller.validate("validateNewCardReplacement"),
|
||||
controller.validateNewCardReplacement
|
||||
);
|
||||
|
||||
// API Replacement Confirm
|
||||
router.post(
|
||||
"/pos/cardreplacement/confirm",
|
||||
auth.authenticateToken,
|
||||
controller.validate("cardReplacementConfirm"),
|
||||
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;
|
||||
@@ -0,0 +1,13 @@
|
||||
const express = require("express");
|
||||
const router = express.Router();
|
||||
// const auth = require("../middlewares/jwt.middleware");
|
||||
const controller = require("../modules/refundkmt/refundkmt.controller");
|
||||
|
||||
router.post(
|
||||
"/refund-callback",
|
||||
// auth.authenticateToken,
|
||||
controller.validate("callbackOy"),
|
||||
controller.callbackOy
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -1,59 +1,109 @@
|
||||
const express = require("express");
|
||||
const express = require('express');
|
||||
const router = express.Router();
|
||||
const auth = require("../middlewares/jwt.middleware");
|
||||
const controller = require("../modules/reservebalance/reservebalance.controller");
|
||||
const auth = require('../middlewares/jwt.middleware');
|
||||
const controller = require('../modules/reservebalance/reservebalance.controller');
|
||||
|
||||
// ================================================================= ROUTE V1 =================================================================
|
||||
router.post(
|
||||
"/reservation/check",
|
||||
'/reservation/check',
|
||||
auth.authenticateToken,
|
||||
controller.validate("checkReservation"),
|
||||
controller.validate('checkReservation'),
|
||||
controller.checkReservation
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/reservation/validate",
|
||||
'/reservation/validate',
|
||||
auth.authenticateToken,
|
||||
controller.validate("reservationValidate"),
|
||||
controller.validate('reservationValidate'),
|
||||
controller.reservationValidate
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/reservation",
|
||||
'/reservation',
|
||||
auth.authenticateToken,
|
||||
controller.validate("reservation"),
|
||||
controller.validate('reservation'),
|
||||
controller.reservation
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/reservation/cancel/validate",
|
||||
'/reservation/cancel/validate',
|
||||
auth.authenticateToken,
|
||||
controller.validate("cancelReservation"),
|
||||
controller.validate('cancelReservation'),
|
||||
controller.cancelReservationValidate
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/reservation/cancel",
|
||||
'/reservation/cancel',
|
||||
auth.authenticateToken,
|
||||
controller.validate("cancelReservation"),
|
||||
controller.validate('cancelReservation'),
|
||||
controller.cancelReservation
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/reservation/inquiry-hold",
|
||||
'/reservation/inquiry-hold',
|
||||
auth.authenticateToken,
|
||||
controller.inquiryReservation
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/reservation/inquiry/v1",
|
||||
'/reservation/inquiry/v1',
|
||||
auth.authenticateToken,
|
||||
controller.inquiryReservationByReservation
|
||||
);
|
||||
|
||||
router.post(
|
||||
"/list-reservation/inquiry/v1",
|
||||
'/list-reservation/inquiry/v1',
|
||||
auth.authenticateToken,
|
||||
controller.inquiryListReservationByReservation
|
||||
);
|
||||
|
||||
// ================================================================= ROUTE V2 =================================================================
|
||||
router.post(
|
||||
'/reservation/validate/v2',
|
||||
auth.authenticateToken,
|
||||
controller.validate('reservationValidate'),
|
||||
controller.reservationValidateV2
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/reservation/v2',
|
||||
auth.authenticateToken,
|
||||
controller.validate('reservationV2'),
|
||||
controller.reservationV2
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/reservation/cancel/validate/v2',
|
||||
auth.authenticateToken,
|
||||
controller.validate('cancelReservationValidateV2'),
|
||||
controller.cancelReservationValidateV2
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/reservation/cancel/v2',
|
||||
auth.authenticateToken,
|
||||
controller.validate('cancelReservationV2'),
|
||||
controller.cancelReservationV2
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/reservation/fee-sharing',
|
||||
auth.authenticateToken,
|
||||
controller.validate('getFeeSharing'),
|
||||
controller.getFeeSharing
|
||||
);
|
||||
|
||||
router.post(
|
||||
'/reservation/decrypt',
|
||||
auth.authenticateToken,
|
||||
controller.decrpytRequest
|
||||
);
|
||||
|
||||
// router.post(
|
||||
// '/reservation/cancel/v2.1',
|
||||
// auth.authenticateToken,
|
||||
// controller.validate('cancelReservation'),
|
||||
// controller.cancelReservationV2_1
|
||||
// );
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
jest.mock('../helpers/helper', () => ({
|
||||
getUniqueCode: jest.fn(),
|
||||
startScheduler: jest.fn(),
|
||||
finishScheduler: jest.fn(),
|
||||
}));
|
||||
jest.mock('../helpers/winston.logger', () => ({
|
||||
logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() },
|
||||
}));
|
||||
jest.mock('../modules/cashin/cash-in-generation.service', () => ({
|
||||
_generateCashIn: jest.fn(),
|
||||
}));
|
||||
jest.mock('../modules/cashin/cash-in-posting.service', () => jest.fn());
|
||||
|
||||
const helper = require('../helpers/helper');
|
||||
const { _generateCashIn } = require('../modules/cashin/cash-in-generation.service');
|
||||
const { apiGenerateCahsIn } = require('../modules/cashin/cahsin.controller');
|
||||
|
||||
test('permintaan Cash-in paralel mempertahankan kode dan hasil masing-masing', async () => {
|
||||
let finishFirst;
|
||||
helper.getUniqueCode.mockReturnValueOnce('job-a').mockReturnValueOnce('job-b');
|
||||
helper.startScheduler.mockResolvedValueOnce({ c_execution_token: 'a' })
|
||||
.mockResolvedValueOnce({ c_execution_token: 'b' });
|
||||
helper.finishScheduler.mockImplementation((token) => {
|
||||
if (token === 'a') return new Promise((resolve) => { finishFirst = resolve; });
|
||||
});
|
||||
_generateCashIn.mockImplementation(async (id) => [id]);
|
||||
|
||||
const firstResponse = { status: jest.fn().mockReturnThis(), json: jest.fn() };
|
||||
const secondResponse = { status: jest.fn().mockReturnThis(), json: jest.fn() };
|
||||
const first = apiGenerateCahsIn({}, firstResponse);
|
||||
await apiGenerateCahsIn({}, secondResponse);
|
||||
expect(finishFirst).toBeDefined();
|
||||
finishFirst();
|
||||
await first;
|
||||
|
||||
expect(firstResponse.json).toHaveBeenCalledWith({
|
||||
code: '200', message: 'Succes posting', data: ['job-a'],
|
||||
});
|
||||
expect(secondResponse.json).toHaveBeenCalledWith({
|
||||
code: '200', message: 'Succes posting', data: ['job-b'],
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,146 @@
|
||||
const { createServer } = require('node:http');
|
||||
const { once } = require('node:events');
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const migration = require('../../infrastructure/database/migrations/20261124000200_create_cash_in_sap_posting');
|
||||
|
||||
jest.mock('../../infrastructure/database/knex', () => require('knex')({
|
||||
client: 'pg',
|
||||
connection: process.env.TOPUP_TEST_CASH_IN_DB_URL,
|
||||
pool: { min: 0, max: 1, acquireTimeoutMillis: 2000 },
|
||||
}));
|
||||
|
||||
const connection = process.env.TOPUP_TEST_CASH_IN_DB_URL;
|
||||
const integration = connection ? describe : describe.skip;
|
||||
const soapResponse = `<Envelope><Body><ZFMCMS_FI_001.Response>
|
||||
<E_DOCUMENTYEAR>2026</E_DOCUMENTYEAR><E_DOCUMENTNUMBER>100007</E_DOCUMENTNUMBER>
|
||||
<C_T_RETURN><item><TYPE>S</TYPE><MESSAGE_1>OK</MESSAGE_1></item></C_T_RETURN>
|
||||
</ZFMCMS_FI_001.Response></Body></Envelope>`;
|
||||
|
||||
integration('cash-in SAP posting with PostgreSQL and a local HTTP stand-in', () => {
|
||||
let db;
|
||||
let postCashIn;
|
||||
let sap;
|
||||
let app;
|
||||
let answer;
|
||||
const requests = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
const url = new URL(connection);
|
||||
if (url.hostname !== '127.0.0.1' || url.pathname !== '/topup_cashin_test') {
|
||||
throw new Error('Cash-in tests require a disposable localhost topup_cashin_test database');
|
||||
}
|
||||
db = require('../../infrastructure/database/knex');
|
||||
postCashIn = require('../modules/cashin/cash-in-posting.service');
|
||||
app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api', require('../routes/cahsin.routes'));
|
||||
await db.raw(`
|
||||
CREATE SCHEMA payment;
|
||||
CREATE SCHEMA trx;
|
||||
CREATE TABLE payment.t_d_cash_in (
|
||||
i_cash_in serial PRIMARY KEY, c_cash_in_no text UNIQUE, c_return_sap text, c_return_year_sap text
|
||||
);
|
||||
CREATE TABLE payment.t_d_cash_in_detail (i_cash_in integer, c_reservation_no text);
|
||||
CREATE TABLE trx.t_d_reservation_balance (c_reservation_no text, c_return_cash_in_sap text, c_cash_in_no text);
|
||||
CREATE TABLE public.posting_et (
|
||||
doc_header_text text, ba text, doc_date date, posting_date date, fiscal_year text,
|
||||
doc_type text, reference text, no_dok text, tcode text, amount integer,
|
||||
debit_kredit text, customer text, account text, text text,
|
||||
pos_status integer, status0 text, no_doksap text, status1 text
|
||||
);
|
||||
CREATE TABLE public.t_m_global_parameter_sap (c_status text, c_code text, c_value text);
|
||||
`);
|
||||
await migration.up(db);
|
||||
sap = createServer((req, res) => {
|
||||
requests.push(req.headers.authorization);
|
||||
req.resume();
|
||||
answer(res);
|
||||
}).listen(0, '127.0.0.1');
|
||||
await once(sap, 'listening');
|
||||
await db('t_m_global_parameter_sap').insert([
|
||||
{ c_code: 'SAP_FI_URL_FOR_FB70', c_value: `http://127.0.0.1:${sap.address().port}` },
|
||||
{ c_code: 'SAP_AUTH_USERNAME', c_value: 'fixture' },
|
||||
{ c_code: 'SAP_AUTH_PASSWORD', c_value: 'secret' },
|
||||
].map((row) => ({ ...row, c_status: 'A' })));
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (sap) {
|
||||
const closed = once(sap, 'close');
|
||||
sap.close();
|
||||
sap.closeAllConnections();
|
||||
await closed;
|
||||
}
|
||||
await db?.destroy();
|
||||
});
|
||||
|
||||
async function enqueue(code) {
|
||||
const [cash] = await db('payment.t_d_cash_in').insert({ c_cash_in_no: code }).returning('i_cash_in');
|
||||
await db('payment.t_d_cash_in_detail').insert({ i_cash_in: cash.i_cash_in, c_reservation_no: code });
|
||||
await db('trx.t_d_reservation_balance').insert({ c_reservation_no: code });
|
||||
const item = { no_dok: code, reference: code, tcode: 'FB70', pos_status: 4, amount: 100 };
|
||||
await db('posting_et').insert([
|
||||
{ ...item, debit_kredit: 'S', customer: '123' },
|
||||
{ ...item, debit_kredit: 'H', account: '456' },
|
||||
]);
|
||||
}
|
||||
|
||||
test('releases the only DB connection during SAP and prevents a duplicate post', async () => {
|
||||
await enqueue('CASH-SUCCESS');
|
||||
const call = once(sap, 'request', { signal: AbortSignal.timeout(3000) });
|
||||
let sapReply;
|
||||
answer = (res) => { sapReply = res; };
|
||||
const before = requests.length;
|
||||
const first = request(app).post('/api/online/cash-in/posting').send({}).then((response) => response);
|
||||
try {
|
||||
await call;
|
||||
expect(db.client.pool.numUsed()).toBe(0);
|
||||
expect(await postCashIn('concurrent fixture')).toEqual([]);
|
||||
expect(requests.slice(before)).toEqual([`Basic ${Buffer.from('fixture:secret').toString('base64')}`]);
|
||||
} finally {
|
||||
sapReply?.end(soapResponse);
|
||||
expect((await first).body).toMatchObject({ code: '200', data: [{ no_dok: 'CASH-SUCCESS' }] });
|
||||
}
|
||||
expect(await db('payment.t_d_cash_in').where('c_cash_in_no', 'CASH-SUCCESS').first())
|
||||
.toMatchObject({ c_return_sap: '100007', c_return_year_sap: '2026' });
|
||||
expect(await db('trx.t_d_reservation_balance').where('c_reservation_no', 'CASH-SUCCESS').first())
|
||||
.toMatchObject({ c_return_cash_in_sap: '100007' });
|
||||
expect(await db('posting_et').where('no_dok', 'CASH-SUCCESS').pluck('pos_status')).toEqual([0, 0]);
|
||||
});
|
||||
|
||||
test('holds a document for reconciliation when SAP returns an uncertain result', async () => {
|
||||
await enqueue('CASH-UNKNOWN');
|
||||
answer = (res) => { res.writeHead(500).end('uncertain'); };
|
||||
const before = requests.length;
|
||||
await postCashIn('fixture');
|
||||
expect(await postCashIn('retry fixture')).toEqual([]);
|
||||
expect(requests.length - before).toBe(1);
|
||||
expect(await db('payment.t_cash_in_sap_posting').where('cash_in_no', 'CASH-UNKNOWN').first())
|
||||
.toMatchObject({ state: 'unknown', outcome: 'SAP_HTTP_ERROR' });
|
||||
expect(await db('posting_et').where('no_dok', 'CASH-UNKNOWN').pluck('pos_status')).toEqual([4, 4]);
|
||||
});
|
||||
|
||||
test('retries local finalization without another SAP request', async () => {
|
||||
await enqueue('CASH-RECOVER');
|
||||
await db.raw(`
|
||||
ALTER TABLE public.posting_et ADD CONSTRAINT reject_fixture_finalize
|
||||
CHECK (no_dok <> 'CASH-RECOVER' OR pos_status = 4)
|
||||
`);
|
||||
answer = (res) => res.end(soapResponse);
|
||||
const before = requests.length;
|
||||
try {
|
||||
await expect(postCashIn('fixture')).rejects.toMatchObject({ code: '23514' });
|
||||
expect(await db('payment.t_cash_in_sap_posting').where('cash_in_no', 'CASH-RECOVER').first())
|
||||
.toMatchObject({ state: 'accepted', document_no: '100007' });
|
||||
expect(await db('payment.t_d_cash_in').where('c_cash_in_no', 'CASH-RECOVER').first())
|
||||
.toMatchObject({ c_return_sap: null });
|
||||
} finally {
|
||||
await db.raw('ALTER TABLE public.posting_et DROP CONSTRAINT reject_fixture_finalize');
|
||||
}
|
||||
expect(await postCashIn('recovery fixture')).toEqual([]);
|
||||
expect(requests.length - before).toBe(1);
|
||||
expect(await db('payment.t_cash_in_sap_posting').where('cash_in_no', 'CASH-RECOVER').first())
|
||||
.toMatchObject({ state: 'completed' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,115 @@
|
||||
const { Registry } = require('prom-client');
|
||||
const { observePool, poolMetrics } = require('../../infrastructure/database/pool-metrics');
|
||||
|
||||
jest.mock('../../infrastructure/database/knex', () => require('knex')({
|
||||
client: 'pg',
|
||||
connection: process.env.TOPUP_TEST_READ_DB_URL,
|
||||
pool: { min: 0, max: 1 },
|
||||
}));
|
||||
|
||||
const connection = process.env.TOPUP_TEST_READ_DB_URL;
|
||||
const integration = connection ? describe : describe.skip;
|
||||
|
||||
integration('hot read paths in PostgreSQL', () => {
|
||||
let db;
|
||||
let history;
|
||||
let reserve;
|
||||
let load;
|
||||
let pos;
|
||||
|
||||
beforeAll(async () => {
|
||||
const url = new URL(connection);
|
||||
if (url.hostname !== '127.0.0.1' || url.pathname !== '/topup_reads_test') {
|
||||
throw new Error('Read-path tests require a disposable localhost topup_reads_test database');
|
||||
}
|
||||
db = require('../../infrastructure/database/knex');
|
||||
observePool('primary', db.client.pool);
|
||||
history = require('../modules/history/history.model');
|
||||
reserve = require('../modules/reservebalance/reservebalance.model');
|
||||
load = require('../modules/loadbalance/loadbalance.model');
|
||||
pos = require('../modules/pos/pos.model');
|
||||
await db.raw(`
|
||||
CREATE SCHEMA trx;
|
||||
CREATE SCHEMA log;
|
||||
CREATE TABLE t_m_global_parameter (c_code text, c_status text, c_value text);
|
||||
CREATE TABLE log.t_log_card (
|
||||
c_card_number text, c_status text, m_balance_after integer,
|
||||
m_amount integer, d_log timestamp, i_log_name integer
|
||||
);
|
||||
CREATE TABLE trx.t_d_reservation_balance (
|
||||
c_mid text, c_tid text, c_card_number text, c_ref_no text,
|
||||
c_partner_name text, c_merchant_name text, c_terminal_name text,
|
||||
c_reservation_no text, d_reservation timestamp, i_reservation_amount integer,
|
||||
i_issuer_fee integer, i_channel_fee integer, c_status text, c_status_name text
|
||||
);
|
||||
CREATE TABLE trx.t_d_load_balance (
|
||||
c_mid text, c_tid text, c_card_number text, c_ref_no text,
|
||||
c_partner_name text, c_merchant_name text, c_terminal_name text, c_load_balance_no text,
|
||||
d_load_balance timestamp, i_topup_amount integer, c_status text, c_status_name text, i_load_balance integer
|
||||
);
|
||||
CREATE TABLE trx.t_d_load_balance_detail (i_load_balance integer, i_issuer_fee integer, i_channel_fee integer);
|
||||
`);
|
||||
});
|
||||
|
||||
afterAll(async () => { await db?.destroy(); });
|
||||
|
||||
test('reads reservation expiry in one statement and ignores inactive values', async () => {
|
||||
await db('t_m_global_parameter').insert([
|
||||
{ c_code: 'HSM_EXP_RSV_VAL', c_status: 'A', c_value: '2' },
|
||||
{ c_code: 'HSM_EXP_RSV_MEA', c_status: 'A', c_value: 'days' },
|
||||
{ c_code: 'HSM_EXP_RSV_VAL', c_status: 'I', c_value: '15' },
|
||||
]);
|
||||
const query = jest.fn();
|
||||
db.on('query', query);
|
||||
try {
|
||||
expect(await reserve.getReservationExpiration()).toEqual({ time: 2, measure: 'days' });
|
||||
expect(query).toHaveBeenCalledTimes(1);
|
||||
} finally {
|
||||
db.removeListener('query', query);
|
||||
}
|
||||
});
|
||||
|
||||
test('monthly aggregation includes the first instant and excludes the next month', async () => {
|
||||
await db('log.t_log_card').insert([
|
||||
['2026-10-31 23:59:59', 100], ['2026-11-01 00:00:00', 10],
|
||||
['2026-11-30 23:59:59', 20], ['2026-12-01 00:00:00', 100],
|
||||
].map(([d_log, m_amount]) => ({
|
||||
c_card_number: 'card', c_status: 'S', m_balance_after: 100, i_log_name: 21, d_log, m_amount,
|
||||
})));
|
||||
for (const model of [reserve, load, pos]) {
|
||||
const total = await model.getAccumulationBalanceInThisMonthFromCardHistory('card', '2026', '11');
|
||||
expect(Number(total.accumulation_balance)).toBe(30);
|
||||
}
|
||||
});
|
||||
|
||||
test('filters history in both branches and retains history without dates', async () => {
|
||||
const key = { c_mid: 'MID', c_tid: 'TID', c_card_number: 'card' };
|
||||
await db('trx.t_d_reservation_balance').insert([
|
||||
{ ...key, c_reservation_no: 'RBL-IN', d_reservation: '2026-11-24 00:00:00' },
|
||||
{ ...key, c_reservation_no: 'RBL-OUT', d_reservation: '2026-11-23 23:59:59' },
|
||||
]);
|
||||
await db('trx.t_d_load_balance').insert([
|
||||
{ ...key, c_load_balance_no: 'LBL-IN', d_load_balance: '2026-11-24 23:59:59' },
|
||||
{ ...key, c_load_balance_no: 'LBL-OUT', d_load_balance: '2026-11-25 00:00:00' },
|
||||
]);
|
||||
const rows = await history.historyByCardNumber('MID', 'TID', 'card', '2026-11-24', '2026-11-24');
|
||||
expect(rows.map(({ unique_number }) => unique_number).sort()).toEqual(['LBL-IN', 'RBL-IN']);
|
||||
expect(await history.historyByCardNumber('MID', 'TID', 'card')).toHaveLength(4);
|
||||
});
|
||||
|
||||
test('exposes pool statistics without querying PostgreSQL for the scrape', async () => {
|
||||
const registry = new Registry();
|
||||
for (const metric of poolMetrics) registry.registerMetric(metric);
|
||||
const query = jest.fn();
|
||||
db.on('query', query);
|
||||
try {
|
||||
const body = await registry.metrics();
|
||||
expect(body).toContain('topuponline_db_pool_connections{pool="primary",state="max"} 1');
|
||||
expect(body).toContain('topuponline_db_pool_pending_acquires{pool="primary"} 0');
|
||||
expect(body).toContain('topuponline_db_pool_acquire_seconds_count{pool="primary",outcome="success"}');
|
||||
expect(query).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
db.removeListener('query', query);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,266 @@
|
||||
const { EventEmitter } = require('node:events');
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const { OPEN, CLOSED } = require('ws');
|
||||
const { requestHsm } = require('../modules/hsm/services/requestHsm');
|
||||
|
||||
const mockClient = { ws: null, clientAuthenticated: true };
|
||||
const mockClient2 = { ws: null, clientAuthenticated: true };
|
||||
|
||||
jest.mock('../modules/hsm/services/webSocket', () => ({ client: mockClient }));
|
||||
jest.mock('../modules/hsm/services/webSocket2', () => ({ client2: mockClient2 }));
|
||||
jest.mock('../helpers/winston.logger', () => ({
|
||||
logger: { info: jest.fn(), debug: jest.fn(), warn: jest.fn(), error: jest.fn() },
|
||||
}));
|
||||
jest.mock('../helpers/helper', () => ({ getUniqueCode: () => '123' }));
|
||||
jest.mock('../middlewares/jwt.middleware', () => ({
|
||||
authenticateToken: (req, res, next) => next(),
|
||||
}));
|
||||
jest.mock('../modules/loadbalance/loadbalance.controller', () => ({
|
||||
loadingBalanceInsert: jest.fn(),
|
||||
loadingBalanceUpdate: jest.fn(),
|
||||
}));
|
||||
jest.mock('axios', () => ({ get: jest.fn() }));
|
||||
|
||||
const axios = require('axios');
|
||||
const loadBalance = require('../modules/loadbalance/loadbalance.controller');
|
||||
const previousMode = process.env.NUMBER_SERVER_ACTIVE;
|
||||
process.env.NUMBER_SERVER_ACTIVE = '12';
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.use('/api', require('../routes/hsm.routes'));
|
||||
const auth1 = require('../modules/hsm/topup/topup_1');
|
||||
|
||||
afterAll(() => restoreEnv('NUMBER_SERVER_ACTIVE', previousMode));
|
||||
afterEach(() => {
|
||||
jest.useRealTimers();
|
||||
jest.clearAllMocks();
|
||||
mockClient.ws = null;
|
||||
mockClient2.ws = null;
|
||||
mockClient.clientAuthenticated = true;
|
||||
mockClient2.clientAuthenticated = true;
|
||||
});
|
||||
|
||||
function restoreEnv(key, value) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
|
||||
function openSocket(send) {
|
||||
const socket = new EventEmitter();
|
||||
socket.readyState = OPEN;
|
||||
socket.send = jest.fn(send);
|
||||
socket.terminate = jest.fn(() => {
|
||||
socket.readyState = CLOSED;
|
||||
socket.emit('close');
|
||||
});
|
||||
return socket;
|
||||
}
|
||||
|
||||
function expectClean(socket) {
|
||||
for (const event of ['message', 'close', 'error']) {
|
||||
expect(socket.listenerCount(event)).toBe(0);
|
||||
}
|
||||
}
|
||||
|
||||
test('cleans up after 50 concurrent responses received out of order', async () => {
|
||||
jest.useFakeTimers();
|
||||
const socket = openSocket();
|
||||
const packets = Array.from({ length: 50 }, (_, id) => Buffer.from([0, id, 4]));
|
||||
const responses = packets.map((packet) => Buffer.concat([packet, Buffer.alloc(3)]));
|
||||
const pending = packets.map((packet) => requestHsm(socket, packet));
|
||||
|
||||
expect(socket.listenerCount('message')).toBe(1);
|
||||
await expect(requestHsm(socket, packets[0])).rejects.toThrow('already pending');
|
||||
expect(socket.send).toHaveBeenCalledTimes(50);
|
||||
socket.emit('message', Buffer.from([0, 0, 4]));
|
||||
socket.emit('message', Buffer.from([0, 50, 4, 0, 0, 0]));
|
||||
for (const response of [...responses].reverse()) socket.emit('message', response);
|
||||
|
||||
await expect(Promise.all(pending)).resolves.toEqual(responses);
|
||||
expectClean(socket);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
test.each(['close', 'error', 'send throw', 'send callback'])('cleans up after %s', async (failure) => {
|
||||
jest.useFakeTimers();
|
||||
const socket = openSocket((packet, done) => {
|
||||
if (failure === 'send throw') throw new Error(failure);
|
||||
if (failure === 'send callback') done(new Error(failure));
|
||||
});
|
||||
const pending = requestHsm(socket, Buffer.from([0, 1, 4]));
|
||||
const result = expect(pending).rejects.toThrow(failure);
|
||||
if (failure === 'close') socket.emit('close');
|
||||
if (failure === 'error') socket.emit('error', new Error(failure));
|
||||
await result;
|
||||
expectClean(socket);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
test('drops a late response and reuses the key only after it has drained', async () => {
|
||||
jest.useFakeTimers();
|
||||
const socket = openSocket();
|
||||
const packet = Buffer.from([0, 1, 4]);
|
||||
const timedOut = expect(requestHsm(socket, packet, { timeoutMs: 30 })).rejects.toThrow('timed out');
|
||||
jest.advanceTimersByTime(30);
|
||||
await timedOut;
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
|
||||
socket.emit('message', Buffer.from([0, 1, 4, 0, 1, 0]));
|
||||
expectClean(socket);
|
||||
const response = Buffer.from([0, 1, 4, 0, 0, 0]);
|
||||
socket.send.mockImplementation(() => socket.emit('message', response));
|
||||
await expect(requestHsm(socket, packet)).resolves.toBe(response);
|
||||
expectClean(socket);
|
||||
});
|
||||
|
||||
test('an ambiguous retry never sends a second packet or interrupts an unrelated active request', async () => {
|
||||
jest.useFakeTimers();
|
||||
const socket = openSocket();
|
||||
const packet = Buffer.from([0, 1, 4]);
|
||||
const other = requestHsm(socket, Buffer.from([0, 2, 4]));
|
||||
const timedOut = expect(requestHsm(socket, packet, { timeoutMs: 30 })).rejects.toThrow('timed out');
|
||||
jest.advanceTimersByTime(30);
|
||||
await timedOut;
|
||||
|
||||
await expect(requestHsm(socket, packet)).rejects.toThrow('reconnect required');
|
||||
expect(socket.send).toHaveBeenCalledTimes(2);
|
||||
expect(socket.terminate).not.toHaveBeenCalled();
|
||||
const response = Buffer.from([0, 2, 4, 0, 0, 0]);
|
||||
socket.emit('message', response);
|
||||
await expect(other).resolves.toBe(response);
|
||||
expect(socket.terminate).toHaveBeenCalledTimes(1);
|
||||
expectClean(socket);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
test('bounds the number of unanswered IDs retained on a socket', async () => {
|
||||
jest.useFakeTimers();
|
||||
const socket = openSocket();
|
||||
const results = Array.from({ length: 257 }, (_, id) => {
|
||||
const packet = Buffer.from([id >> 8, id & 255, 4]);
|
||||
return expect(requestHsm(socket, packet, { timeoutMs: 30 })).rejects.toThrow('timed out');
|
||||
});
|
||||
jest.advanceTimersByTime(30);
|
||||
await Promise.all(results);
|
||||
expect(socket.terminate).toHaveBeenCalledTimes(1);
|
||||
expectClean(socket);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
const cardId = 'aabbccddeeff0011';
|
||||
const payloads = [
|
||||
`0000${cardId.toUpperCase()}`, '41', '43', '44', '45',
|
||||
`46${'00'.repeat(25)}`, '470000000000', '48',
|
||||
];
|
||||
const steps = ['topup', 'clear'].flatMap((route) =>
|
||||
payloads.map((requestData, index) => [route + (index + 1), requestData])
|
||||
);
|
||||
|
||||
function validBody(requestData) {
|
||||
return {
|
||||
trxID: '1234', requestData, unique_code: '123', mid: 'MID', tid: 'TID',
|
||||
flag: '1', uid: 'UID', card_number: 'card', amount: 1000, balance: 2000,
|
||||
reservation_number: ['reservation'], load_balance_number: 'balance',
|
||||
};
|
||||
}
|
||||
|
||||
test.each(steps)('%s remains compatible and releases the listener', async (route, requestData) => {
|
||||
const socket = openSocket((packet) => {
|
||||
if (packet[2] === 1) {
|
||||
socket.emit('message', Buffer.from('01020100000900ffffffffffffffff', 'hex'));
|
||||
socket.emit('message', Buffer.from(`12340100000900${cardId}`, 'hex'));
|
||||
return;
|
||||
}
|
||||
const payload = Buffer.from(requestData, 'hex');
|
||||
socket.emit('message', Buffer.concat([packet.subarray(0, 3), Buffer.from([0, 0, payload.length]), payload]));
|
||||
});
|
||||
mockClient.ws = socket;
|
||||
mockClient2.ws = socket;
|
||||
const dbResult = { code: '00', data: { load_balance_number: 'balance' } };
|
||||
loadBalance.loadingBalanceInsert.mockResolvedValue(dbResult);
|
||||
loadBalance.loadingBalanceUpdate.mockResolvedValue(dbResult);
|
||||
|
||||
const response = await request(app).post(`/api/${route}`).send(validBody(requestData));
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({ code: '00', data: { trxID: '1234', responseCode: '0000' } });
|
||||
expect(socket.send).toHaveBeenCalledTimes(1);
|
||||
expectClean(socket);
|
||||
});
|
||||
|
||||
test.each(['getservice', 'clear/getservice'])('%s remains available with no HSM connection', async (route) => {
|
||||
const response = await request(app).get(`/api/${route}`);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.code).toBe('00');
|
||||
});
|
||||
|
||||
test('disconnecting during topup6 returns a controlled error before any database write', async () => {
|
||||
const socket = openSocket(() => socket.emit('close'));
|
||||
mockClient.ws = socket;
|
||||
|
||||
const response = await request(app).post('/api/topup6').send(validBody(payloads[5]));
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({ code: '5001', data: {} });
|
||||
expect(loadBalance.loadingBalanceInsert).not.toHaveBeenCalled();
|
||||
expectClean(socket);
|
||||
});
|
||||
|
||||
test('rejects malformed HSM IDs before sending a packet or refreshing the service', async () => {
|
||||
const socket = openSocket();
|
||||
mockClient.ws = socket;
|
||||
mockClient2.ws = socket;
|
||||
|
||||
for (const [route, body] of [
|
||||
['topup1', validBody('0000aa')],
|
||||
['topup6', { ...validBody(payloads[5]), trxID: '123g' }],
|
||||
]) {
|
||||
const response = await request(app).post(`/api/${route}`).send(body);
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({ code: '5001', data: {} });
|
||||
}
|
||||
expect(socket.send).not.toHaveBeenCalled();
|
||||
expect(axios.get).not.toHaveBeenCalled();
|
||||
expect(loadBalance.loadingBalanceInsert).not.toHaveBeenCalled();
|
||||
expectClean(socket);
|
||||
});
|
||||
|
||||
test('stage 1 timeouts on backup HSM 2 share one bounded refresh', async () => {
|
||||
jest.useFakeTimers();
|
||||
const previousHost = process.env.IP_HSM_SERVER_BACKUP_2;
|
||||
const previousDr = process.env.CHANGE_TO_DRC;
|
||||
try {
|
||||
process.env.IP_HSM_SERVER_BACKUP_2 = '127.0.0.1';
|
||||
process.env.CHANGE_TO_DRC = 'YES';
|
||||
let rejectRefresh;
|
||||
axios.get.mockReturnValue(new Promise((resolve, reject) => { rejectRefresh = reject; }));
|
||||
mockClient.clientAuthenticated = false;
|
||||
const socket = openSocket();
|
||||
mockClient2.ws = socket;
|
||||
const send = jest.fn();
|
||||
const status = jest.fn(() => ({ send }));
|
||||
const pending = [
|
||||
auth1({ body: validBody(payloads[0]) }, { status }),
|
||||
auth1({ body: validBody('00001122334455667788') }, { status }),
|
||||
];
|
||||
await jest.advanceTimersByTimeAsync(10000);
|
||||
|
||||
expect(axios.get).toHaveBeenCalledTimes(1);
|
||||
expect(axios.get).toHaveBeenCalledWith(
|
||||
'http://127.0.0.1/feliqserver/v1/api/hsm/refresh',
|
||||
expect.objectContaining({ timeout: 5000 })
|
||||
);
|
||||
rejectRefresh(new Error('refresh failed'));
|
||||
await Promise.all(pending);
|
||||
expect(status).toHaveBeenCalledWith(200);
|
||||
expect(send).toHaveBeenCalledTimes(2);
|
||||
expect(send).toHaveBeenCalledWith({ code: '5001', message: 'Timeout', data: {} });
|
||||
socket.emit('close');
|
||||
expectClean(socket);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
restoreEnv('IP_HSM_SERVER_BACKUP_2', previousHost);
|
||||
restoreEnv('CHANGE_TO_DRC', previousDr);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,122 @@
|
||||
const { once } = require('node:events');
|
||||
const { createServer } = require('node:http');
|
||||
const db = require('../../infrastructure/database/knex');
|
||||
const helper = require('../helpers/helper');
|
||||
const model = require('../modules/invoiceonline/invoice.model');
|
||||
const { generateInvoice, retryInvoices } = require('../modules/invoiceonline/invoice-posting.service');
|
||||
|
||||
jest.mock('../../infrastructure/database/knex', () => ({ transaction: jest.fn() }));
|
||||
jest.mock('../helpers/helper', () => ({
|
||||
generateXMLRequest: jest.fn(),
|
||||
postingSAP: jest.fn(),
|
||||
getXMLData: jest.fn(),
|
||||
}));
|
||||
jest.mock('../helpers/winston.logger', () => ({ logger: { warn: jest.fn() } }));
|
||||
jest.mock('../modules/invoiceonline/invoice.model');
|
||||
|
||||
const invoiceNo = 'INV-TEST-1';
|
||||
const generated = {
|
||||
c_invoice_no: invoiceNo,
|
||||
c_account_code_topup: 'DEBIT',
|
||||
c_account_topup: 'CREDIT',
|
||||
};
|
||||
const queued = { reference: invoiceNo, customer: 'DEBIT', account: 'CREDIT' };
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
helper.generateXMLRequest.mockReturnValue('<fixture/>');
|
||||
model.getSapSettings.mockResolvedValue({ url: 'http://sap.test', username: 'fixture', password: 'fixture' });
|
||||
model.getPostingEt.mockResolvedValue([queued]);
|
||||
model.getAcceptedSapPostings.mockResolvedValue([]);
|
||||
model.getInvoice.mockResolvedValue(generated);
|
||||
});
|
||||
|
||||
test('generation commits its queue before SAP and finalizes after a confirmed document', async () => {
|
||||
const trx = {};
|
||||
let committed = false;
|
||||
db.transaction.mockImplementation(async (callback) => {
|
||||
const result = await callback(trx);
|
||||
committed = true;
|
||||
return result;
|
||||
});
|
||||
model.generateInvoice.mockResolvedValue([generated]);
|
||||
model.claimSapPosting.mockResolvedValue(true);
|
||||
model.finishSapPosting.mockResolvedValue(generated);
|
||||
helper.postingSAP.mockImplementation(() => {
|
||||
expect(committed).toBe(true);
|
||||
return { status: 200 };
|
||||
});
|
||||
helper.getXMLData.mockReturnValue({ type: 'S', data: { E_DOCUMENTNUMBER: '0000123456' } });
|
||||
|
||||
await expect(generateInvoice('2026-11-23', 'run', false)).resolves.toEqual([generated]);
|
||||
expect(model.insertPostingEt).toHaveBeenCalledWith(generated, trx);
|
||||
expect(model.claimSapPosting).toHaveBeenCalledWith(db, invoiceNo, true);
|
||||
expect(helper.postingSAP).toHaveBeenCalledWith(
|
||||
'http://sap.test', '<fixture/>', { username: 'fixture', password: 'fixture' },
|
||||
{ timeoutMs: 15000, maxRedirects: 0 }
|
||||
);
|
||||
expect(model.recordSapOutcome).toHaveBeenCalledWith(db, invoiceNo, '0000123456', 'SAP_CONFIRMED');
|
||||
expect(model.finishSapPosting).toHaveBeenCalledWith(db, invoiceNo);
|
||||
});
|
||||
|
||||
test.each([
|
||||
[{ status: 500, errorCode: 'ERR_CANCELED' }, 'SAP_TIMEOUT'],
|
||||
[{ status: 502 }, 'SAP_HTTP_ERROR'],
|
||||
[{ status: 200 }, 'SAP_INVALID_RESPONSE'],
|
||||
])('one claim stops concurrent and later retries after an ambiguous result', async (response, outcome) => {
|
||||
let claimed = false;
|
||||
model.claimSapPosting.mockImplementation(async () => {
|
||||
if (claimed) return false;
|
||||
claimed = true;
|
||||
return true;
|
||||
});
|
||||
helper.postingSAP.mockResolvedValue(response);
|
||||
helper.getXMLData.mockImplementation(() => { throw new Error('invalid XML'); });
|
||||
|
||||
await Promise.all([retryInvoices('first'), retryInvoices('concurrent')]);
|
||||
await retryInvoices('later');
|
||||
expect(helper.postingSAP).toHaveBeenCalledTimes(1);
|
||||
expect(model.recordSapOutcome).toHaveBeenCalledWith(db, invoiceNo, null, outcome);
|
||||
expect(model.releaseUnsentPosting).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('a connection refusal makes the invoice eligible for another attempt', async () => {
|
||||
model.claimSapPosting.mockResolvedValue(true);
|
||||
helper.postingSAP.mockResolvedValue({ status: 500, errorCode: 'ECONNREFUSED' });
|
||||
|
||||
await retryInvoices('run');
|
||||
expect(model.releaseUnsentPosting).toHaveBeenCalledWith(db, invoiceNo);
|
||||
expect(model.recordSapOutcome).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('retries a previously accepted invoice locally after finalization fails', async () => {
|
||||
model.getAcceptedSapPostings.mockResolvedValue([invoiceNo]);
|
||||
model.getPostingEt.mockResolvedValue([]);
|
||||
model.finishSapPosting.mockRejectedValueOnce(new Error('database unavailable')).mockResolvedValue(generated);
|
||||
|
||||
await expect(retryInvoices('first')).rejects.toThrow('database unavailable');
|
||||
await expect(retryInvoices('second')).resolves.toEqual([generated]);
|
||||
expect(helper.postingSAP).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('real SAP HTTP client aborts a request whose response never finishes', async () => {
|
||||
const { postingSAP } = jest.requireActual('../helpers/helper');
|
||||
const server = createServer((req) => req.resume());
|
||||
const listening = once(server, 'listening');
|
||||
server.listen(0, '127.0.0.1');
|
||||
await listening;
|
||||
const incoming = once(server, 'request', { signal: AbortSignal.timeout(3000) });
|
||||
try {
|
||||
const response = postingSAP(
|
||||
`http://127.0.0.1:${server.address().port}/sap`,
|
||||
'<fixture/>',
|
||||
{ username: 'fixture', password: 'fixture' },
|
||||
{ timeoutMs: 250, maxRedirects: 0 }
|
||||
);
|
||||
await incoming;
|
||||
expect((await response).errorCode).toMatch(/ERR_CANCELED|ECONNABORTED/);
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
const model = require('../modules/loadbalance/loadbalance.model');
|
||||
const { loadingBalanceInsert } = require('../modules/loadbalance/loadbalance.controller');
|
||||
|
||||
jest.mock('../helpers/helper', () => ({}));
|
||||
jest.mock('../helpers/winston.logger', () => ({ logger: { info: jest.fn(), warn: jest.fn(), error: jest.fn() } }));
|
||||
jest.mock('../modules/loadbalance/loadbalance.model', () => ({
|
||||
getPartner: jest.fn(),
|
||||
findReservationsWithLoadedBalance: jest.fn(),
|
||||
getLastHistory: jest.fn(),
|
||||
getFraudTransaction: jest.fn(),
|
||||
getReservationPendingWithoutFraud: jest.fn(),
|
||||
allocateLoadBalanceNumber: jest.fn(),
|
||||
findReservationDetails: jest.fn(),
|
||||
insertLoadingBalance: jest.fn(),
|
||||
}));
|
||||
|
||||
const req = { partner_id_token: '1' };
|
||||
const input = { uid: 'fixture', amount: 30, reservation_number: ['RBL2', 'RBL1'] };
|
||||
const loaded = { c_reservation_no: 'RBL1', loaded_id: 10, loaded_number: 'LBL1', loaded_at: '2026-11-23' };
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
model.getPartner.mockResolvedValue({ i_partner: '1', partner_code: 'TEST' });
|
||||
});
|
||||
|
||||
test.each([
|
||||
[['missing', 'RBL1'], '414'],
|
||||
[['RBL1', 'missing'], '00'],
|
||||
])('uses input order when a batch contains a missing and an already-loaded reservation', async (numbers, code) => {
|
||||
model.findReservationsWithLoadedBalance.mockResolvedValue([loaded]);
|
||||
|
||||
const result = await loadingBalanceInsert(req, { ...input, reservation_number: numbers });
|
||||
|
||||
expect(result.code).toBe(code);
|
||||
if (code === '00') expect(result.data.load_balance_number).toBe('LBL1');
|
||||
expect(model.findReservationsWithLoadedBalance).toHaveBeenCalledTimes(1);
|
||||
expect(model.findReservationsWithLoadedBalance).toHaveBeenCalledWith(numbers);
|
||||
expect(model.allocateLoadBalanceNumber).not.toHaveBeenCalled();
|
||||
expect(model.insertLoadingBalance).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
function setupPending() {
|
||||
model.findReservationsWithLoadedBalance.mockResolvedValue([
|
||||
{ c_reservation_no: 'RBL1' }, { c_reservation_no: 'RBL2' },
|
||||
]);
|
||||
model.getFraudTransaction.mockResolvedValue([]);
|
||||
model.getReservationPendingWithoutFraud.mockResolvedValue([
|
||||
{ c_reservation_no: 'RBL2', i_reservation_amount: 20 },
|
||||
{ c_reservation_no: 'RBL1', i_reservation_amount: 10 },
|
||||
]);
|
||||
model.allocateLoadBalanceNumber.mockResolvedValue({ number: 'LBLTEST261124000023', sequence: 23 });
|
||||
}
|
||||
|
||||
test('fetches pending details once and preserves the pending order and amounts', async () => {
|
||||
setupPending();
|
||||
model.findReservationDetails.mockResolvedValue([
|
||||
{ c_reservation_no: 'RBL1', i_reservation_balance: 1, i_reservation_amount: 10 },
|
||||
{ c_reservation_no: 'RBL2', i_reservation_balance: 2, i_reservation_amount: 20 },
|
||||
]);
|
||||
model.insertLoadingBalance.mockResolvedValue(1);
|
||||
|
||||
await expect(loadingBalanceInsert(req, input)).resolves.toMatchObject({
|
||||
code: '00',
|
||||
data: { load_balance_number: 'LBLTEST261124000023' },
|
||||
});
|
||||
expect(model.allocateLoadBalanceNumber).toHaveBeenCalledWith('TEST', expect.stringMatching(/^\d{6}$/));
|
||||
expect(model.findReservationDetails).toHaveBeenCalledTimes(1);
|
||||
expect(model.findReservationDetails).toHaveBeenCalledWith(['RBL2', 'RBL1']);
|
||||
const [header, details, numbers] = model.insertLoadingBalance.mock.calls[0];
|
||||
expect(header).toMatchObject({ c_load_balance_no: 'LBLTEST261124000023', i_load_balance_no_seq: 23 });
|
||||
expect(numbers).toEqual(['RBL2', 'RBL1']);
|
||||
expect(details).toMatchObject([
|
||||
{ c_reservation_no: 'RBL2', i_amount: 20 },
|
||||
{ c_reservation_no: 'RBL1', i_amount: 10 },
|
||||
]);
|
||||
});
|
||||
|
||||
test('preserves code 414 if a pending reservation is absent at the new read', async () => {
|
||||
setupPending();
|
||||
model.findReservationDetails.mockResolvedValue([]);
|
||||
|
||||
await expect(loadingBalanceInsert(req, input)).resolves.toMatchObject({ code: '414' });
|
||||
expect(model.allocateLoadBalanceNumber).not.toHaveBeenCalled();
|
||||
expect(model.insertLoadingBalance).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
const fs = require('node:fs');
|
||||
const os = require('node:os');
|
||||
const path = require('node:path');
|
||||
const { EventEmitter } = require('node:events');
|
||||
const createAuditArchive = require('../helpers/audit-archive');
|
||||
const { createStdoutWriter, formatLog } = require('../helpers/stdout-log');
|
||||
const createRedisOperations = require('../helpers/redis-operations');
|
||||
|
||||
test('stdout backpressure preserves every audit and a stale Loki URL does not trigger HTTP', () => {
|
||||
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'topup-audit-'));
|
||||
const audit = createAuditArchive(directory);
|
||||
const previous = process.env.LOKI_URL;
|
||||
process.env.LOKI_URL = 'http://127.0.0.1:1';
|
||||
const stream = new EventEmitter();
|
||||
stream.writable = true;
|
||||
stream.writableNeedDrain = false;
|
||||
stream.write = jest.fn((line, callback) => { callback(); });
|
||||
const onSkip = jest.fn();
|
||||
const writeStdoutLine = createStdoutWriter(stream, onSkip);
|
||||
|
||||
try {
|
||||
jest.isolateModules(() => {
|
||||
jest.doMock('../helpers/audit-archive', () => () => audit);
|
||||
jest.doMock('../helpers/stdout-log', () => ({ formatLog, writeStdoutLine }));
|
||||
jest.doMock('axios', () => { throw new Error('Audit must never load an HTTP client'); });
|
||||
const { record } = require('../helpers/response-audit');
|
||||
record({ level: 'info', event: 'http_response', request_id: 'first', message: 'Line one\nLine two' });
|
||||
stream.writableNeedDrain = true;
|
||||
record({ level: 'info', event: 'http_response', request_id: 'slow-console' });
|
||||
stream.writableNeedDrain = false;
|
||||
record({ level: 'error', event: 'http_response', request_id: 'recovered' });
|
||||
});
|
||||
expect(onSkip).toHaveBeenCalledWith('backpressure');
|
||||
expect(stream.write).toHaveBeenCalledTimes(2);
|
||||
const emitted = stream.write.mock.calls.map(([line]) => JSON.parse(line));
|
||||
expect(emitted.map(({ request_id }) => request_id)).toEqual(['first', 'recovered']);
|
||||
expect(emitted[0]).toMatchObject({ app: 'topuponline', message: 'Line one\nLine two' });
|
||||
const [file] = fs.readdirSync(directory);
|
||||
const archived = fs.readFileSync(path.join(directory, file), 'utf8').trim().split('\n').map(JSON.parse);
|
||||
expect(archived.map(({ request_id }) => request_id)).toEqual(['first', 'slow-console', 'recovered']);
|
||||
} finally {
|
||||
jest.dontMock('../helpers/audit-archive');
|
||||
jest.dontMock('../helpers/stdout-log');
|
||||
jest.dontMock('axios');
|
||||
if (previous === undefined) delete process.env.LOKI_URL;
|
||||
else process.env.LOKI_URL = previous;
|
||||
audit.close();
|
||||
for (const file of fs.readdirSync(directory)) fs.unlinkSync(path.join(directory, file));
|
||||
fs.rmdirSync(directory);
|
||||
}
|
||||
});
|
||||
|
||||
test('Redis deadline releases outstanding commands and later requests use the recovered connection', async () => {
|
||||
let rejectCommand;
|
||||
const client = {
|
||||
isReady: true,
|
||||
isOpen: true,
|
||||
disconnect: jest.fn(async () => {
|
||||
client.isReady = false;
|
||||
client.isOpen = false;
|
||||
rejectCommand(new Error('socket closed'));
|
||||
}),
|
||||
connect: jest.fn(async () => { client.isOpen = true; client.isReady = true; }),
|
||||
};
|
||||
const timedOut = jest.fn();
|
||||
const execute = createRedisOperations(client, { timeoutMs: 20, onTimeout: timedOut });
|
||||
const result = await execute(() => new Promise((resolve, reject) => { rejectCommand = reject; }));
|
||||
|
||||
expect(result).toBeNull();
|
||||
expect(timedOut).toHaveBeenCalledTimes(1);
|
||||
expect(client.disconnect).toHaveBeenCalledTimes(1);
|
||||
expect(client.connect).toHaveBeenCalledTimes(1);
|
||||
await expect(execute(async () => 'OK')).resolves.toBe('OK');
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const responseTime = require('response-time');
|
||||
const knex = require('../../infrastructure/database/knex');
|
||||
const responseAudit = require('../helpers/response-audit');
|
||||
const { logger } = require('../helpers/getbodyrequest');
|
||||
const histograms = Object.values(require('../helpers/prometheusmetrics'));
|
||||
|
||||
jest.mock('../../infrastructure/database/knex', () => jest.fn());
|
||||
jest.mock('../helpers/response-audit', () => ({ record: jest.fn() }));
|
||||
jest.mock('winston-daily-rotate-file', () => {
|
||||
const winston = require('winston');
|
||||
const Transport = require('winston-transport');
|
||||
class MemoryTransport extends Transport {
|
||||
log(info, callback) {
|
||||
callback();
|
||||
}
|
||||
}
|
||||
winston.transports.DailyRotateFile = MemoryTransport;
|
||||
return MemoryTransport;
|
||||
});
|
||||
|
||||
const app = express();
|
||||
app.use(express.json(), responseTime(), logger.correlation, logger.request, logger.response);
|
||||
app.post('/api/topup1', (req, res) => {
|
||||
req._startTime = Date.now() - req.body.duration;
|
||||
res.json({ code: '00', data: { trxID: req.body.trxID } });
|
||||
});
|
||||
app.post('/api/topup2', (req, res) => {
|
||||
req.partner_id_token = 'fixture';
|
||||
res.json({ code: '5001', data: {} });
|
||||
});
|
||||
app.post('/api/topup3', (req, res) => {
|
||||
req.partner_id_token = '9917';
|
||||
res.json({ code: '00', data: {} });
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
jest.clearAllMocks();
|
||||
for (const histogram of histograms) histogram.reset();
|
||||
});
|
||||
|
||||
test('distinct transaction IDs and latencies share one histogram series per bucket', async () => {
|
||||
const transactionIds = ['0001', '0002', '0100', '01a0'];
|
||||
const responses = await Promise.all(transactionIds.map((trxID, index) =>
|
||||
request(app).post('/api/topup1?fixture=1').send({ trxID, duration: 200 + index * 100 })
|
||||
));
|
||||
|
||||
for (const histogram of histograms) {
|
||||
const metric = await histogram.get();
|
||||
const counts = metric.values.filter((value) => value.metricName.endsWith('_count'));
|
||||
expect(counts).toEqual([{
|
||||
metricName: `${metric.name}_count`,
|
||||
labels: { route: '/api/topup1', status_code: '00', issuer_name: 'UNDEFINED' },
|
||||
value: transactionIds.length,
|
||||
}]);
|
||||
expect(metric.values.some((entry) => entry.labels.le === 1000)).toBe(true);
|
||||
}
|
||||
|
||||
const logs = responseAudit.record.mock.calls.map(([info]) => info);
|
||||
const requestIds = responses.map(({ headers }) => headers['x-request-id']);
|
||||
expect(new Set(requestIds).size).toBe(transactionIds.length);
|
||||
responses.forEach(({ headers, body }, index) => {
|
||||
const record = logs.find((entry) => entry.request_id === headers['x-request-id']);
|
||||
expect(headers['x-response-time']).toMatch(/ms$/);
|
||||
expect(body.data.trxID).toBe(transactionIds[index]);
|
||||
expect(record).toMatchObject({
|
||||
event: 'http_response',
|
||||
http_status: 200,
|
||||
trx_id: transactionIds[index],
|
||||
});
|
||||
expect(record.response_time_ms).toBeGreaterThanOrEqual(200 + index * 100);
|
||||
expect(record).not.toHaveProperty('labels');
|
||||
});
|
||||
});
|
||||
|
||||
test('logs the valid request transaction ID on HSM failure even if issuer lookup fails', async () => {
|
||||
knex.mockReturnValue({
|
||||
where: jest.fn().mockReturnValue({
|
||||
first: jest.fn().mockReturnValue({ timeout: jest.fn().mockRejectedValue(new Error('DB unavailable')) }),
|
||||
}),
|
||||
});
|
||||
const response = await request(app).post('/api/topup2').send({ trxID: 'ABCD', card_number: 'fixture-card' });
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
const [info] = responseAudit.record.mock.calls[0];
|
||||
expect(info).toMatchObject({
|
||||
level: 'error',
|
||||
status_code: '5001',
|
||||
request_id: response.headers['x-request-id'],
|
||||
trx_id: 'abcd',
|
||||
issuer_name: 'UNDEFINED',
|
||||
});
|
||||
expect(info).not.toHaveProperty('card_number');
|
||||
});
|
||||
|
||||
test('a slow issuer lookup is shared and audit records are emitted while it is pending', async () => {
|
||||
let finishLookup;
|
||||
const pending = new Promise((resolve) => { finishLookup = resolve; });
|
||||
const timeout = jest.fn().mockReturnValue(pending);
|
||||
knex.mockReturnValue({
|
||||
where: jest.fn().mockReturnValue({ first: jest.fn().mockReturnValue({ timeout }) }),
|
||||
});
|
||||
|
||||
try {
|
||||
await Promise.all(Array.from({ length: 12 }, () => request(app).post('/api/topup3')));
|
||||
expect(timeout).toHaveBeenCalledTimes(1);
|
||||
expect(responseAudit.record).toHaveBeenCalledTimes(12);
|
||||
expect(responseAudit.record).toHaveBeenCalledWith(expect.objectContaining({
|
||||
issuer_name: 'UNDEFINED',
|
||||
partner_id: '9917',
|
||||
}));
|
||||
} finally {
|
||||
finishLookup({ c_name: 'Fixture' });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
const express = require('express');
|
||||
const request = require('supertest');
|
||||
const model = require('../modules/paymentrecon/paymentrecon.model');
|
||||
const { paymentRecon, validate } = require('../modules/paymentrecon/paymentrecon.controller');
|
||||
|
||||
jest.mock('../helpers/helper', () => ({ getUniqueCode: () => 'fixture', randomNumberInt: () => 0 }));
|
||||
jest.mock('../helpers/winston.logger', () => ({ logger: {
|
||||
debug: jest.fn(), info: jest.fn(), warn: jest.fn(), error: jest.fn(),
|
||||
} }));
|
||||
jest.mock('../modules/paymentrecon/paymentrecon.model', () => ({
|
||||
getPartnerByID: jest.fn(),
|
||||
checkReservation: jest.fn(),
|
||||
checkReservationNumberAndAmountAlreadyRecon: jest.fn(),
|
||||
getLastCounterPaymentReconNo: jest.fn(),
|
||||
insertPaymentReconNumber: jest.fn(),
|
||||
checkReservationCanceledStatus: jest.fn(),
|
||||
checkReservationNumberAndAmount: jest.fn(),
|
||||
completePaymentRecon: jest.fn(),
|
||||
insertPaymentReconTransaction: jest.fn(),
|
||||
}));
|
||||
|
||||
const app = express();
|
||||
app.use(express.json());
|
||||
app.post('/api/payment-recon', (req, res, next) => {
|
||||
req.partner_id_token = '1';
|
||||
next();
|
||||
}, validate('paymentRecon'), paymentRecon);
|
||||
const body = { date: '2026-11-23', reservation_number: 'RBL1', bank_ref: 'BANK1', amount: 1000 };
|
||||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
model.getPartnerByID.mockResolvedValue({ b_payment_recon: true, partner_code: 'TST' });
|
||||
model.checkReservation.mockResolvedValue({ i_partner: 1 });
|
||||
model.insertPaymentReconNumber.mockResolvedValue({ rowCount: 1 });
|
||||
model.checkReservationNumberAndAmount.mockResolvedValue({ total_transaction: 1, total_amount: '1000' });
|
||||
});
|
||||
|
||||
test('the loser of a concurrent reconciliation returns the winner’s number and code 04', async () => {
|
||||
const winner = { c_payment_recon_no: 'RC-WINNER', d_payment_recon: '2026-11-23 10:00:00' };
|
||||
model.checkReservationNumberAndAmountAlreadyRecon
|
||||
.mockResolvedValueOnce(undefined)
|
||||
.mockResolvedValueOnce(winner);
|
||||
model.completePaymentRecon.mockResolvedValue(false);
|
||||
|
||||
const response = await request(app).post('/api/payment-recon').send(body);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({ code: '04', data: { payment_recon_no: 'RC-WINNER' } });
|
||||
expect(model.completePaymentRecon).toHaveBeenCalledWith(expect.objectContaining({
|
||||
reservationNumber: 'RBL1', expectedAmount: '1000',
|
||||
}));
|
||||
expect(model.insertPaymentReconTransaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('a failed atomic commit returns an error instead of reporting reconciliation success', async () => {
|
||||
model.completePaymentRecon.mockRejectedValue(new Error('transaction failed'));
|
||||
|
||||
const response = await request(app).post('/api/payment-recon').send(body);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body.code).toBe('500');
|
||||
expect(model.insertPaymentReconTransaction).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test('konflik nomor rekonsiliasi berhenti setelah lima percobaan', async () => {
|
||||
model.insertPaymentReconNumber.mockResolvedValue({ rowCount: 0 });
|
||||
|
||||
const response = await request(app).post('/api/payment-recon').send(body);
|
||||
|
||||
expect(response.status).toBe(200);
|
||||
expect(response.body).toMatchObject({
|
||||
code: '500',
|
||||
message: 'server is busy. please try again.',
|
||||
});
|
||||
expect(model.insertPaymentReconNumber).toHaveBeenCalledTimes(5);
|
||||
expect(model.completePaymentRecon).not.toHaveBeenCalled();
|
||||
});
|
||||
@@ -0,0 +1,105 @@
|
||||
const makeKnex = require('knex');
|
||||
const migration = require('../../infrastructure/database/migrations/20261124000100_create_transaction_number_counter');
|
||||
const createAllocator = require('../../infrastructure/database/transaction-number');
|
||||
|
||||
const connection = process.env.TOPUP_TEST_NUMBER_DB_URL;
|
||||
const integration = connection ? describe : describe.skip;
|
||||
|
||||
integration('transaction number allocation in PostgreSQL', () => {
|
||||
let firstDb;
|
||||
let secondDb;
|
||||
let first;
|
||||
let second;
|
||||
|
||||
beforeAll(async () => {
|
||||
const url = new URL(connection);
|
||||
if (url.hostname !== '127.0.0.1' || url.pathname !== '/topup_test') {
|
||||
throw new Error('Number allocation tests require a disposable localhost topup_test database');
|
||||
}
|
||||
const settings = { client: 'pg', connection, pool: { min: 0, max: 4 } };
|
||||
firstDb = makeKnex(settings);
|
||||
secondDb = makeKnex(settings);
|
||||
first = createAllocator(firstDb);
|
||||
second = createAllocator(secondDb);
|
||||
// Gagal bila skema sudah ada agar pengujian hanya memakai database kosong.
|
||||
await firstDb.raw(`
|
||||
CREATE SCHEMA trx;
|
||||
CREATE TABLE trx.t_d_reservation_no_validate (c_reservation_no varchar(50) PRIMARY KEY);
|
||||
CREATE TABLE trx.t_d_reservation_balance (c_reservation_no varchar(50));
|
||||
CREATE TABLE trx.t_d_load_balance_no_validate (c_load_balance_no varchar(50) PRIMARY KEY);
|
||||
CREATE TABLE trx.t_d_load_balance (c_load_balance_no varchar(50));
|
||||
CREATE TABLE trx.t_d_load_balance_history (c_load_balance_no varchar(50));
|
||||
`);
|
||||
await migration.up(firstDb);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await Promise.all([firstDb?.destroy(), secondDb?.destroy()]);
|
||||
});
|
||||
|
||||
test.each([
|
||||
['RBL', 't_d_reservation_balance', 't_d_reservation_no_validate', 'c_reservation_no'],
|
||||
['LBL', 't_d_load_balance_history', 't_d_load_balance_no_validate', 'c_load_balance_no'],
|
||||
])('%s claims 100 distinct numbers across independent pools, starting after legacy data', async (type, table, claim, column) => {
|
||||
const prefix = `${type}KCI261124`;
|
||||
await firstDb(`trx.${table}`).insert([
|
||||
{ [column]: `${prefix}000400` },
|
||||
{ [column]: `${prefix}000XYZ` },
|
||||
{ [column]: `${type}ABC261124999999` },
|
||||
]);
|
||||
await firstDb(`trx.${claim}`).insert({ [column]: `${prefix}000401` });
|
||||
|
||||
const issued = await Promise.all(Array.from({ length: 100 }, (_, index) =>
|
||||
(index % 2 === 0 ? first : second)(type, 'KCI', '261124')
|
||||
));
|
||||
const sequences = issued.map(({ sequence }) => sequence).sort((a, b) => a - b);
|
||||
|
||||
expect(sequences).toEqual(Array.from({ length: 100 }, (_, index) => 402 + index));
|
||||
expect(new Set(issued.map(({ number }) => number)).size).toBe(100);
|
||||
expect(issued.every(({ number, sequence }) => number === `${prefix}${String(sequence).padStart(6, '0')}`)).toBe(true);
|
||||
expect(await firstDb(`trx.${claim}`).where(column, 'like', `${prefix}%`)).toHaveLength(101);
|
||||
});
|
||||
|
||||
test('continues after an old writer claims a block of LBL numbers', async () => {
|
||||
const prefix = 'LBLOLD261124';
|
||||
await firstDb('trx.t_d_load_balance').insert({ c_load_balance_no: `${prefix}000041` });
|
||||
await expect(first('LBL', 'OLD', '261124')).resolves.toEqual({ number: `${prefix}000042`, sequence: 42 });
|
||||
await firstDb('trx.t_d_load_balance_no_validate').insert(
|
||||
Array.from({ length: 10 }, (_, index) => ({ c_load_balance_no: `${prefix}0000${43 + index}` }))
|
||||
);
|
||||
await expect(second('LBL', 'OLD', '261124')).resolves.toEqual({ number: `${prefix}000053`, sequence: 53 });
|
||||
});
|
||||
|
||||
test('shares the fallback partner prefix and starts a fresh counter on the next date', async () => {
|
||||
const issued = await Promise.all([first('RBL', null, '261124'), second('RBL', 'XXX', '261124')]);
|
||||
expect(issued.map(({ number }) => number).sort()).toEqual(['RBLXXX261124000001', 'RBLXXX261124000002']);
|
||||
await expect(second('RBL', 'XXX', '261125')).resolves.toEqual({ number: 'RBLXXX261125000001', sequence: 1 });
|
||||
});
|
||||
|
||||
test('reports exhaustion without returning a seven-digit sequence', async () => {
|
||||
await firstDb('trx.t_d_reservation_balance').insert([
|
||||
{ c_reservation_no: 'RBLMAX261124999998' },
|
||||
{ c_reservation_no: 'RBLEND261124999999' },
|
||||
]);
|
||||
await expect(first('RBL', 'MAX', '261124')).resolves.toEqual({ number: 'RBLMAX261124999999', sequence: 999999 });
|
||||
await expect(second('RBL', 'MAX', '261124')).rejects.toThrow('sequence exhausted');
|
||||
await expect(second('RBL', 'END', '261124')).rejects.toThrow('sequence exhausted');
|
||||
});
|
||||
|
||||
test('rolls the counter back when PostgreSQL rejects the new claim', async () => {
|
||||
const prefix = 'RBLERR261124';
|
||||
await expect(first('RBL', 'ERR', '261124')).resolves.toEqual({ number: `${prefix}000001`, sequence: 1 });
|
||||
await firstDb.raw(`
|
||||
ALTER TABLE trx.t_d_reservation_no_validate ADD CONSTRAINT reject_fixture
|
||||
CHECK (c_reservation_no <> 'RBLERR261124000002')
|
||||
`);
|
||||
try {
|
||||
await expect(second('RBL', 'ERR', '261124')).rejects.toMatchObject({ code: '23514' });
|
||||
const counter = await firstDb('trx.t_transaction_number_counter').where({ number_prefix: prefix }).first();
|
||||
expect(counter.last_value).toBe(1);
|
||||
} finally {
|
||||
await firstDb.raw('ALTER TABLE trx.t_d_reservation_no_validate DROP CONSTRAINT reject_fixture');
|
||||
}
|
||||
await expect(second('RBL', 'ERR', '261124')).resolves.toEqual({ number: `${prefix}000002`, sequence: 2 });
|
||||
});
|
||||
});
|
||||
@@ -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.
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user