diff --git a/docs/ANALISIS_SISTEM_DAN_UIUX.md b/docs/ANALISIS_SISTEM_DAN_UIUX.md deleted file mode 100644 index bfa700d..0000000 --- a/docs/ANALISIS_SISTEM_DAN_UIUX.md +++ /dev/null @@ -1,274 +0,0 @@ -# Analisis Komprehensif Sistem, Logika Backend, dan UI/UX — Billing RT/RW Net - -> **Target Project**: `/opt/billing-rtrw` (VPS `deneva` — `116.212.74.115`) -> **Layanan**: `billing-rtrw.service` (Node.js v20+, port `3001`) -> **Repository Asal**: `https://github.com/alijayanet/billing-rtrw` -> **Repository Fork/Deploy**: `https://github.com/alijayanet/billing-rtrw` - ---- - -## 1. Ringkasan Eksekutif & Gambaran Sistem - -Billing RT/RW Net ini adalah sistem manajemen operasional ISP (Internet Service Provider) berbasis komunitas yang memadukan: -1. **Billing & Invoicing**: Siklus tagihan bulanan, isolir otomatis, dan pembayaran QRIS dinamis/manual. -2. **Network Automation**: Integrasi RouterOS MikroTik (PPPoE, Hotspot Voucher, Simple Queue, Address List). -3. **Hardware Management (FTTH)**: Embedded ACS TR-069 Server (CWMP) untuk manajemen ONT klien dan SNMP OLT (EPON/GPON). -4. **Customer Self-Service (PWA)**: Portal pelanggan mobile-first dengan auto-login 90 hari, ganti WiFi SSID/password mandiri, grafik pemakaian kuota/bandwidth, dan reboot modem. -5. **Multi-Channel Bot**: Bot WhatsApp (Baileys socket) dan Bot Telegram untuk notifikasi, penagihan, dan tiket operasional. - -```mermaid -flowchart TD - subgraph Klien_Pelanggan["Portal Klien & Interaksi"] - CustPWA["Customer PWA (Tailwind + Lucide)"] - PublicVoucher["Portal Voucher & QRIS"] - WABot["WhatsApp Bot (Baileys)"] - TeleBot["Telegram Bot Notifikasi"] - end - - subgraph Core_Backend["Express 4 Engine (Port 3001)"] - App["app-customer.js (Main Entry)"] - ACSServer["Embedded TR-069 Server (/acs)"] - AuthSvc["Auth & Token Service (90 Hari)"] - BillSvc["Billing & Invoice Engine"] - MikroSvc["MikroTik RouterOS API"] - OLTSvc["OLT Service (SNMP / Web)"] - UsageSvc["Bandwidth Usage Tracker"] - end - - subgraph Data_Network["Infrastruktur Jaringan & Database"] - DB[("SQLite WAL (better-sqlite3)")] - MikroTik[("Router MikroTik (PPPoE / Hotspot)")] - OLT[("OLT Fiber (Hioso/HSGQ/VSOL)")] - CPE[("ONT / Modem Pelanggan (TR-069)")] - end - - CustPWA -->|HTTP/REST| App - PublicVoucher -->|HTTP/REST| App - WABot <--> App - TeleBot <--> App - App --> AuthSvc - App --> BillSvc - App --> MikroSvc - App --> OLTSvc - App --> UsageSvc - CPE <-->|CWMP SOAP| ACSServer - ACSServer <--> DB - BillSvc <--> DB - MikroSvc <--> MikroTik - OLTSvc <--> OLT - UsageSvc <--> MikroTik -``` - ---- - -## 2. Analisis Backend & Logika Alur Fungsi - -### 2.1 Arsitektur Server & Runtime -* **Runtime**: Node.js `>=20.0.0` (Native ES Module + CommonJS hybrid). -* **Database Engine**: SQLite 3 melalui `better-sqlite3` dengan mode **WAL (Write-Ahead Logging)**, foreign keys aktif, sinkronisasi file cepat dan hemat resource. -* **Proses Lifecycle**: Dikelola oleh Systemd (`billing-rtrw.service`) dengan auto-restart `on-failure` (delay 5 detik), batas memori RAM `--max-old-space-size=512`. -* **Proteksi Server**: - * Penanganan `unhandledRejection` dan `uncaughtException` terpusat agar error koneksi (misal timeout MikroTik) tidak mematikan server Express. - * Fallback port otomatis (`startServer` mencoba port +1000 jika port 3001 bentrok). - * Proteksi CSRF berbasis validasi header `Origin` dan `Referer` (mengecualikan webhook dan endpoint SOAP ACS). - ---- - -### 2.2 Modul-Modul Inti & Alur Logika - -#### A. Layanan Billing, Invoice & Isolir (`services/billingService.js` & `services/cronService.js`) -* **Logika Pembuatan Tagihan**: - 1. Cron berjalan setiap hari (`cronService.js`) memeriksa seluruh pelanggan aktif. - 2. Tagihan dibuat otomatis setiap siklus tanggal tagihan (`billing_date`) untuk periode bulan berjalan. - 3. Kode unik nominal QRIS (`qris_amount_unique`) diinjeksi 3 digit acak (1–999) agar mutasi bank/QRIS dapat dicocokkan otomatis tanpa payment gateway berbayar. -* **Logika Isolir Otomatis**: - 1. Bila tanggal saat ini mencapai atau melewati `isolir_day` (default tanggal 20 tiap bulan) dan tagihan pelanggan masih `unpaid`: - 2. Status pelanggan di database diubah menjadi `isolated`. - 3. `mikrotikService` dipanggil untuk memindahkan secret PPPoE ke profile isolir atau memasukkan IP klien ke Address List `ISOLIR` di MikroTik Firewall. - 4. Sesi aktif diputus (`disconnectPPPoE`) sehingga pelanggan ter-redirect ke halaman Walled Garden (`/isolated`). - -#### B. Layanan TR-069 ACS Server (`services/acsServerService.js` & `/acs`) -* **Protokol**: CWMP (CPE WAN Management Protocol) via SOAP XML over HTTP POST. -* **Alur Inform & Handshake**: - 1. Modem (ONT) mengirim HTTP POST `Inform` ke endpoint `/acs`. - 2. Server memeriksa header `Authorization`. Jika belum diautentikasi, server membalas dengan **HTTP 401 Unauthorized** (Digest Challenge). - 3. Modem mengirim kembali request dengan Digest Hash yang dihitung berdasarkan username (`skyfiber`) dan password acak perangkat. - 4. Server membaca parameter XML (`Device.DeviceInfo.*`, `Device.WANDevice.*`, `Device.Ethernet.*`, `Device.LANDevice.*`). - 5. Data kekuatan redaman optik (`RXPower`, `TXPower`), serial number, model, dan versi software disimpan ke tabel `acsdevices`. - 6. Server memeriksa antrean tugas (task queue) per perangkat: jika ada perintah ganti password WiFi atau reboot, server merespons dengan `SetParameterValues` atau `Reboot`. - -#### C. Pengelolaan WiFi Multi-Vendor (`services/customerDeviceService.js`) -* **Masalah Klasik**: Tiap vendor modem (Huawei, ZTE, FiberHome, Nokia) memiliki skema OID/TR-098 yang berbeda-beda. Mengirim parameter yang salah menyebabkan SOAP Fault 9007. -* **Logika Adaptif Per-Vendor**: - * **Huawei / FiberHome / Nokia**: Memprioritaskan `PreSharedKey.1.KeyPassphrase` dan menghindari pengiriman hex 64-digit bersamaan dengan plain string. - * **ZTE / ZICG / CIOT**: Memprioritaskan `KeyPassphrase` top-level. - * **Dual-Band SSID**: Mengatur `WLANConfiguration.1.SSID` (2.4 GHz) dan `WLANConfiguration.5.SSID` (5 GHz) secara independen tanpa merusak konfigurasi guest SSID. - -#### D. Integrasi Jaringan MikroTik (`services/mikrotikService.js`) -* **Koneksi**: RouterOS API (port default `25722`/`8728`) menggunakan library `routeros-client`. -* **Fitur Utama**: - * Sinkronisasi PPPoE: Read active connections, update secret passwords, kick active sessions. - * Monitoring Traffic: Mengambil data byte RX/TX interface pelanggan untuk kalkulasi kuota. - * Voucher Hotspot: Direct injection user hotspot, profile rate-limit, dan validitas voucher. - -#### E. Autentikasi Pelanggan & Persistent Token (`services/customerAuthTokenService.js`) -* **Alur Sesi PWA**: - 1. Pelanggan memasukkan nomor HP / ID Pelanggan. - 2. Saat login berhasil, backend men-generate token kriptografi acak `crypto.randomBytes(32).toString('hex')`. - 3. Token di-hash dengan SHA-256 dan disimpan di tabel SQLite `customer_auth_tokens` dengan masa berlaku 90 hari. - 4. Plain token dikirimkan ke browser sebagai cookie `customer_remember` (`httpOnly`, `secure`, `sameSite: lax`). - 5. Ketika pengguna membuka PWA (bahkan setelah browser/HP di-restart), middleware auto-login memverifikasi cookie ini dan merekonstruksi session secara transparan. - -#### F. Pelacakan Kuota & Pemakaian Bandwidth (`services/usageService.js`) -* **Logika Agregasi**: - 1. Mengambil byte delta dari MikroTik queue / interface. - 2. Menyimpan sampel agregat harian dan bulanan ke database. - 3. Menyediakan API untuk konsumsi frontend (Chart.js di dashboard pelanggan). - ---- - -## 3. Analisis UI / UX, Styling, Typografi & Layout - -Pemeriksaan mendalam terhadap template EJS dan file CSS/JS di `/opt/billing-rtrw/views/` dan `/opt/billing-rtrw/public/` mengungkap sejumlah temuan penting mengenai styling, engine, dan konsistensi desain: - -### 3.1 Peta Engine & Library UI per Portal - -| Portal / Halaman | Engine CSS Utama | Library Icon | Font Family Utama | Style Pendekatan | -|---|---|---|---|---| -| **Customer Dashboard** (`views/dashboard.ejs`) | **Tailwind CSS 3.4.17** (via CDN) | **Lucide Icons** (v1.48.0) + FontAwesome 6.4.0 | **Plus Jakarta Sans** (Google Fonts) | Modern App Shell / Glassmorphism Mobile-first | -| **Customer Login** (`views/login.ejs`) | **Bootstrap 5.3.2** (CDN) | **Bootstrap Icons 1.11.3** | **System Font Stack** (`-apple-system`, Segoe UI, Roboto) | Centered Glass Card / Radial Background | -| **Admin Portal** (`views/admin/*`) | **Custom CSS** (`/css/admin.css`) | **Bootstrap Icons 1.11.3** + FontAwesome | **Inter** (Google Fonts) | Desktop Enterprise Sidebar & Table Layout | -| **Teknisi Portal** (`views/tech/*`) | **Bootstrap 5** + `/css/theme.css` | **Bootstrap Icons** | System Font / Inter | Mobile Bottom Navigation | -| **Halaman Peta Jaringan** (`views/admin/map.ejs`) | **Leaflet 1.9.4** + `/css/admin.css` | FontAwesome + SVG Animasi | Inter | Fullscreen Interactive Map & Vector Layer | - ---- - -### 3.2 Analisis Typografi & Hierarki Font - -``` -[Customer Dashboard] Plus Jakarta Sans (300, 400, 500, 600, 700, 800) - ├── Title / Header : text-base sm:text-lg font-bold (Tracking tight) - ├── Section Labels : text-xs font-semibold text-slate-400 uppercase (Tracking wider) - ├── Body / Konten : text-sm font-normal text-slate-200 (Leading relaxed) - └── Badges & Metadata : text-[10px] sm:text-xs font-medium - -[Customer Login] System Font Stack (BlinkMacSystemFont, Segoe UI, Roboto) - └── Ketidaksesuaian : Font berbeda dengan Dashboard; saat user login terjadi visual jump dari font sistem ke Plus Jakarta Sans. - -[Admin Portal] Inter (300, 400, 500, 600, 700, 800) - ├── Sidebar Items : font-size 13px, font-weight 500 - ├── Data Table Header : font-size 11px, text-transform uppercase, letter-spacing 0.5px - └── Table Data Cells : font-size 13px, color var(--text: #e6edf3) -``` - ---- - -### 3.3 Analisis Styling, Palette Warna & Tema Gelap/Terang - -#### Palette Warna Dominan -1. **Mode Gelap (Customer Dashboard)**: - * Background Utama: `#0b0f19` (Deep Blue-Black) - * Card & Panel: `#1e293b` (Slate 800) dengan border `#334155` (Slate 700) - * Aksen Primer (Brand): Gradasi Teal `#14b8a6` ke Cyan `#06b6d4` - * Aksen Sekunder: Indigo `#6366f1` - * Status Indikator: Hijau Sukses `#10b981`, Merah Warning/Error `#f43f5e`, Amber `#f59e0b` -2. **Mode Terang (Customer Dashboard & Global Theme)**: - * Background Utama: `#f1f5f9` (Slate 100) - * Card & Panel: `#ffffff` murni dengan border `rgba(15, 23, 42, 0.08)` - * Teks Utama: `#0f172a` (Slate 900), Teks Muted: `#64748b` (Slate 500) -3. **Mekanisme Tema (Theming Engine)**: - * Terdapat dua sistem tema yang berjalan berdampingan: - * `views/dashboard.ejs` menggunakan script lokal inline (`localStorage: skyfiber-customer-theme`) mengendalikan class `dark` pada `` untuk Tailwind. - * Portal lainnya menggunakan `/js/theme.js` dan `/css/theme.css` (`localStorage: app-theme`) mengendalikan atribut `data-theme="light|dark"`. - * Pada rilis `v1.9.4`, kedua key ini sudah disinkronkan, namun styling mode terang di portal admin masih membutuhkan penyesuaian kontras pada beberapa tabel dan modal. - ---- - -### 3.4 Analisis Layout, Spacing, Alignment & UX - -#### 1. Customer Dashboard (Mobile App Shell) -* **Alignment & Container**: - * Lebar maksimum dibatasi ke `max-w-md` atau `max-w-lg` di tengah layar (`mx-auto`), memberikan rasa native mobile application saat dibuka di smartphone maupun desktop browser. - * Padding konten konsisten (`px-4 py-3`), dengan padding bawah ekstra (`pb-28`) untuk memberi ruang bagi floating navigation dock. -* **Floating Glass Dock (5 Tab Navigasi)**: - * Terpasang fixed di bagian bawah layar: `fixed bottom-4 left-1/2 -translate-x-1/2`. - * Menggunakan efek glassmorphism (`backdrop-blur-md`, background semi-transparan, border tipis halus). - * Indikator aktif berupa **sliding pill** yang bergerak halus mengikuti tab yang diklik (`updatePillPosition`). - * Tab navigasi: - 1. `tab-beranda` (Home, status paket, kuota, shortcut aksi) - 2. `tab-router` (Status ONT, redaman fiber optic, ganti WiFi, reboot) - 3. `tab-ppob` (Layanan isi pulsa & token listrik - status Coming Soon) - 4. `tab-tagihan` (Riwayat invoice, tombol bayar QRIS) - 5. `tab-profile` (Data akun, riwayat tiket kendala, tombol CS WhatsApp, logout) -* **Kerapian & Touch Target**: - * Seluruh tombol interaktif memiliki ukuran touch-target minimal `40x40px` (ramah sentuhan jari di layar HP). - * Safe-area-insets untuk iPhone (`env(safe-area-inset-bottom)`) sudah ditambahkan pada `.dock-glass`. - -#### 2. Admin & Staff Portal -* **Layout**: - * Sidebar navigasi di sisi kiri (`width: 240px`, fixed). - * Konten utama di sebelah kanan dengan header fixed dan breadcrumb. - * Responsive breakpoint: Pada layar kecil (mobile), sidebar disembunyikan dan diakses lewat toggle menu hamburger. - ---- - -### 3.5 Temuan Evaluasi & Celah UI/UX (Bottlenecks) - -1. **Fragmentasi Framework CSS**: - * Halaman login menggunakan **Bootstrap 5**, sedangkan dashboard pelanggan menggunakan **Tailwind CSS**. Ini membebani browser pengguna karena harus mengunduh dua framework CSS besar saat pertama kali membuka aplikasi. -2. **Ketergantungan CDN Runtime (Client-Side Tailwind)**: - * Dashboard pelanggan menggunakan ``. CDN ini mem-parse class Tailwind saat runtime di perangkat klien (JIT compiler di browser), yang dapat memperlambat rendering awal (First Contentful Paint) pada ponsel berspesifikasi rendah. -3. **Dual Icon Libraries**: - * Halaman dashboard memuat **Lucide Icons** dan **FontAwesome 6.4.0** secara bersamaan. FontAwesome (file CSS + font ~400KB) hanya digunakan untuk segelintir ikon kecil, sementara sebagian besar UI sudah menggunakan SVG Lucide. -4. **Log Error Berulang di Backend**: - * Terdapat log `Telegram Polling Error` berkala pada journal server deneva karena token bot belum dikonfigurasi / timeout koneksi ke server Telegram API. - ---- - -## 4. Rencana Kerja Terperinci (Execution Plan) - -Rencana perubahan ini dibagi menjadi 4 fase berurutan dengan prinsip **zero-downtime** dan keamanan data: - -```mermaid -timeline - title Timeline Rencana Peningkatan Billing RTRW - Fase 1 : Konsolidasi Backend & Error Fix : Fix Polling Telegram : Optimalisasi Error Handling - Fase 2 : Unifikasi Design System : Standarisasi Font (Plus Jakarta Sans) : Harmonisasi Halaman Login & Dashboard - Fase 3 : Optimasi Asset & Performa : Eliminasi Redundansi Icon : Cache Profiling & PWA Hardening - Fase 4 : Testing & Validasi : Uji Responsivitas Semua Layar : Uji Fungsi WiFi & Pembayaran Live -``` - -### Fase 1: Perbaikan Stabilitas & Logika Backend -1. **Fix Polling Telegram (`services/telegramBot.js`)**: - * Tambahkan pengecekan kondisi: jika token Telegram kosong, nonaktifkan `polling: true` agar tidak membanjiri log server dengan polling error setiap 5 detik. -2. **Peningkatan Ketahanan Koneksi MikroTik (`services/mikrotikService.js`)**: - * Implementasikan retry backoff otomatis saat query queue/PPPoE timeout, menghindari uncaught exception yang tidak perlu. -3. **Audit Query Database (`config/database.js`)**: - * Periksa indeks pada tabel `pppoe_traffic_samples`, `invoices`, dan `customer_auth_tokens` untuk mempercepat query bulanan. - -### Fase 2: Harmonisasi UI/UX & Standarisasi Tipografi -1. **Standarisasi Tipografi**: - * Terapkan font **Plus Jakarta Sans** ke seluruh halaman pelanggan, termasuk halaman Login (`views/login.ejs`), Register, dan Isolir (`views/isolated.ejs`), menggantikan system font default agar pengalaman visual konsisten sejak awal. -2. **Harmonisasi Desain Halaman Login (`views/login.ejs`)**: - * Rombak halaman login agar memiliki nuansa tema, sudut rounded, dan aksen warna Teal/Cyan yang identik dengan Dashboard Pelanggan. - * Ganti elemen Bootstrap pada halaman login menjadi layout yang selaras dengan tema dashboard. -3. **Penyempurnaan Form Ganti WiFi di Tab Router**: - * Perjelas instruksi frekuensi 2.4 GHz vs 5 GHz. - * Tambahkan toggle visibility (mata) untuk password WiFi dan validasi panjang password (minimal 8 karakter) di sisi klien sebelum submit. - -### Fase 3: Optimasi Frontend & Efisiensi Aset -1. **Rasionalisasi Icon**: - * Migrasikan sisa ikon FontAwesome di Dashboard pelanggan ke **Lucide Icons** bawaan. - * Hapus pemanggilan CSS FontAwesome di dashboard pelanggan untuk menghemat ukuran transfer data hingga ~400 KB. -2. **Optimasi Mode Terang (Light Mode)**: - * Periksa dan rapikan kontras teks di seluruh tab dashboard agar tidak ada teks putih yang tidak terbaca saat berganti ke background terang. - * Pastikan border card dan form input terlihat tegas pada mode terang. - -### Fase 4: Pengujian, Validasi & Deployment -1. **Uji Coba Lintas Perangkat**: - * Uji tampilan di mobile (Android Chrome, iOS Safari), tablet, dan desktop. - * Uji fungsi PWA Add to Home Screen dan verifikasi auto-login setelah kill aplikasi. -2. **Uji Fungsional End-to-End**: - * Uji ganti SSID/password pada modem online. - * Uji alur pembuatan invoice dan QRIS. - * Restart service `billing-rtrw.service` dan verifikasi log bersih tanpa error. diff --git a/docs/AUDIT_FINDINGS_SUMMARY.md b/docs/AUDIT_FINDINGS_SUMMARY.md deleted file mode 100644 index 570d1a9..0000000 --- a/docs/AUDIT_FINDINGS_SUMMARY.md +++ /dev/null @@ -1,317 +0,0 @@ -# AUDIT FINDINGS SUMMARY - QUICK REFERENCE -**Status:** Complete Audit -**Date:** 14 August 2026 -**Format:** Executive Summary for Management - ---- - -## 🎯 AUDIT OVERVIEW - -| Metric | Status | Details | -|--------|--------|---------| -| **Security Score** | 5.5/10 | ⚠️ Critical issues found | -| **Code Quality** | 7/10 | Good structure, needs hardening | -| **Database Integrity** | 8/10 | Well-designed schema | -| **Production Ready** | ❌ NO | Must fix critical issues first | -| **Audit Completed** | ✅ YES | Full report available | - ---- - -## 🔴 CRITICAL FINDINGS (MUST FIX IMMEDIATELY) - -### 1. PASSWORD STORAGE (CRITICAL) -- **Issue:** Passwords stored in plaintext in database -- **Risk:** Full account compromise if database breached -- **Files:** `services/techService.js`, `settings.json` -- **Fix Time:** 4-6 hours -- **Severity:** CRITICAL -- **Status:** Not Fixed ❌ - -### 2. DEFAULT CREDENTIALS (CRITICAL) -- **Issue:** Default admin password `admin123` in settings.json -- **Risk:** Anyone can login to admin panel -- **Fix Time:** 1 hour -- **Severity:** CRITICAL -- **Status:** Not Fixed ❌ - -### 3. UNENCRYPTED CREDENTIALS (CRITICAL) -- **Issue:** API keys and passwords in plaintext in settings.json -- **Risk:** Exposure in version control, server breach -- **Files:** `settings.json` -- **Fix Time:** 2-3 hours -- **Severity:** CRITICAL -- **Status:** Not Fixed ❌ - -### 4. WEAK PASSWORD HASHING (HIGH) -- **Issue:** SHA256 and MD5 used instead of bcrypt/argon2 -- **Risk:** Password cracking in hours/minutes -- **Files:** Multiple service files -- **Fix Time:** 6-8 hours -- **Severity:** HIGH -- **Status:** Not Fixed ❌ - ---- - -## 🟠 HIGH PRIORITY FINDINGS - -### 5. CSRF PROTECTION (LIMITED) -- **Issue:** Only Referer/Origin validation, no explicit CSRF tokens -- **Risk:** Cross-site request forgery attacks possible -- **Fix Time:** 4-6 hours -- **Severity:** HIGH - -### 6. SESSION MANAGEMENT -- **Issue:** In-memory session store, no regeneration on login -- **Risk:** Session hijacking possible -- **Fix Time:** 3-4 hours -- **Severity:** HIGH - -### 7. INPUT VALIDATION -- **Issue:** Incomplete input validation and sanitization -- **Risk:** XSS and injection attacks -- **Fix Time:** 8-10 hours -- **Severity:** HIGH - ---- - -## 🟡 MEDIUM PRIORITY FINDINGS - -### 8. FILE UPLOAD SECURITY -- **Issue:** Only MIME type validation, no deep file scanning -- **Risk:** Malicious file upload -- **Fix Time:** 2-4 hours -- **Severity:** MEDIUM - -### 9. BACKUP & DISASTER RECOVERY -- **Issue:** Auto-backup disabled in settings -- **Risk:** Data loss in disaster scenario -- **Fix Time:** 2-3 hours -- **Severity:** MEDIUM - -### 10. ERROR LOGGING -- **Issue:** Some errors may expose sensitive info -- **Risk:** Information disclosure -- **Fix Time:** 2-3 hours -- **Severity:** MEDIUM - ---- - -## ✅ POSITIVE FINDINGS - -### What's Working Well: -- ✅ Database design is solid with proper constraints -- ✅ Error handling middleware implemented -- ✅ Winston logger properly configured -- ✅ SQL queries use parameterized statements (SQL injection safe) -- ✅ File upload has MIME type validation -- ✅ Session cookies have httpOnly and sameSite flags -- ✅ CORS/Origin checking implemented -- ✅ Comprehensive feature set well-structured - ---- - -## 📊 TIMELINE TO PRODUCTION READINESS - -``` -Week 1 (CRITICAL): -├─ Fix password hashing → 8 hours -├─ Setup .env & remove hardcoded secrets → 4 hours -├─ Implement CSRF tokens → 4 hours -├─ Setup session store → 3 hours -└─ Testing → 4 hours - TOTAL: ~23 hours (3 days) - -Week 2 (HIGH): -├─ Input validation framework → 8 hours -├─ Rate limiting → 4 hours -├─ Backup automation → 3 hours -├─ Security headers (helmet) → 2 hours -└─ Testing & QA → 8 hours - TOTAL: ~25 hours (3 days) - -Week 3 (MEDIUM): -├─ File upload scanning → 6 hours -├─ Log review & cleanup → 4 hours -├─ Documentation → 4 hours -└─ Staging deployment → 4 hours - TOTAL: ~18 hours (2 days) - -GRAND TOTAL: ~66 hours (~2 weeks full-time) - or ~3-4 weeks part-time (20 hrs/week) -``` - ---- - -## 💼 BUSINESS IMPACT - -### Current State (If Deployed Now): -- 🔴 **NOT RECOMMENDED** for production -- Risk of account takeover is HIGH -- Risk of data breach is CRITICAL -- Compliance risk with regulations (OJK, PCI-DSS if payment processing) - -### After Critical Fixes (1-2 weeks): -- 🟢 **PRODUCTION READY** for initial deployment -- Password security improved significantly -- Credentials properly managed -- Basic CSRF protection in place - -### After All Fixes (3-4 weeks): -- 🟢 **PRODUCTION HARDENED** -- Enterprise-grade security -- Compliance-ready -- Audit-ready for external review - ---- - -## 👥 RESOURCE REQUIREMENTS - -### Team Needed: -- **Backend Developer(s):** 1-2 (main focus) -- **Security Reviewer:** 1 (part-time, 4-6 hours/week) -- **QA/Tester:** 1 (part-time, 2-4 hours/week) -- **DevOps/Infrastructure:** 0.5 (env setup, deployment) - -### Skills Required: -- Node.js/JavaScript (Backend) -- Database migration experience -- Security best practices knowledge -- Testing & QA methodologies - ---- - -## 🎯 RECOMMENDED ACTION PLAN - -### Phase 1: IMMEDIATE (Days 1-2) -1. ✅ Review this audit with team -2. ✅ Create .env file with sensitive data -3. ✅ Install required packages (bcrypt, helmet, etc) -4. ✅ Backup current database - -### Phase 2: CRITICAL FIXES (Days 3-5) -1. ✅ Implement password hashing with bcrypt -2. ✅ Migrate existing passwords -3. ✅ Setup environment variables -4. ✅ Remove hardcoded credentials - -### Phase 3: TESTING & VALIDATION (Days 6-7) -1. ✅ Test all authentication flows -2. ✅ Verify password migration -3. ✅ Test environment variable loading -4. ✅ Deploy to staging - -### Phase 4: HIGH PRIORITY FIXES (Week 2) -1. ✅ Implement CSRF protection -2. ✅ Setup session store -3. ✅ Add rate limiting -4. ✅ Input validation - -### Phase 5: FINAL HARDENING (Week 3) -1. ✅ Security headers (Helmet) -2. ✅ File upload scanning -3. ✅ Backup automation -4. ✅ Final testing - -### Phase 6: PRODUCTION DEPLOYMENT (End of Week 3) -1. ✅ Security review checklist -2. ✅ Final audit verification -3. ✅ Deploy to production -4. ✅ Monitoring setup - ---- - -## 📋 DEPLOYMENT CHECKLIST - -Before production deployment, verify: - -- [ ] **Password Security** - - [ ] Bcrypt implemented and tested - - [ ] All passwords migrated to hashes - - [ ] No plaintext passwords in code/config - - [ ] Login flows working with hashed passwords - -- [ ] **Credential Management** - - [ ] .env file created and populated - - [ ] Settings.json reviewed for sensitive data - - [ ] .env added to .gitignore - - [ ] Environment variables working - -- [ ] **Access Control** - - [ ] CSRF protection implemented - - [ ] Rate limiting configured - - [ ] Session management hardened - - [ ] Role-based access control verified - -- [ ] **Security Headers** - - [ ] Helmet.js installed and configured - - [ ] HTTPS enforced (if applicable) - - [ ] Security headers present in responses - -- [ ] **Data Protection** - - [ ] Input validation implemented - - [ ] Output sanitization verified - - [ ] File uploads scanning configured - - [ ] Database encryption (at rest if needed) - -- [ ] **Logging & Monitoring** - - [ ] Audit trail logged for sensitive operations - - [ ] Error logging configured - - [ ] Monitoring alerts setup - - [ ] Log aggregation configured - -- [ ] **Backup & Recovery** - - [ ] Automated backup enabled - - [ ] Backup encryption enabled - - [ ] Recovery procedure tested - - [ ] Backup retention policy set - -- [ ] **Testing** - - [ ] Unit tests passing - - [ ] Integration tests passing - - [ ] Security tests completed - - [ ] Load testing completed - - [ ] Penetration testing (optional but recommended) - -- [ ] **Documentation** - - [ ] Security practices documented - - [ ] Incident response plan ready - - [ ] Setup procedures documented - - [ ] Troubleshooting guide prepared - ---- - -## 🚨 KNOWN VULNERABILITIES - -| Vulnerability | CVSS Score | Status | Action | -|---|---|---|---| -| Plaintext password storage | 9.8 | Open | CRITICAL - Fix immediately | -| Default credentials | 8.7 | Open | CRITICAL - Fix immediately | -| Unencrypted API keys | 8.9 | Open | CRITICAL - Fix immediately | -| Weak password hashing | 7.5 | Open | HIGH - Fix this week | -| Limited CSRF protection | 6.5 | Open | HIGH - Fix this week | -| In-memory session store | 6.1 | Open | HIGH - Fix this week | -| Incomplete input validation | 7.1 | Open | HIGH - Fix this week | - ---- - -## 📞 CONTACT & SUPPORT - -For questions or clarifications: -1. Review detailed findings in `AUDIT_SECURITY_2026.md` -2. Check implementation guide in `IMPLEMENTATION_GUIDE_SECURITY.md` -3. Consult code samples in this document - ---- - -## 📝 SIGN-OFF - -**Audit Completed By:** Security & Code Quality Review Team -**Date Completed:** 14 August 2026 -**Next Review:** 30 days after fixes implementation -**Status:** READY FOR ACTION ✅ - ---- - -**RECOMMENDATION: DO NOT DEPLOY TO PRODUCTION UNTIL CRITICAL FIXES ARE COMPLETED** - -For production deployment, all findings must be reviewed, and critical issues must be resolved. diff --git a/docs/AUDIT_LENGKAP.md b/docs/AUDIT_LENGKAP.md deleted file mode 100644 index 0fe6e07..0000000 --- a/docs/AUDIT_LENGKAP.md +++ /dev/null @@ -1,1374 +0,0 @@ -# AUDIT LENGKAP APLIKASI BILLING RTRWnet (B481) -**Status Aplikasi:** BERJALAN & PRODUKSI -**Tanggal Audit:** Juni 2026 -**Tipe Sistem:** ISP Billing & Management System - ---- - -## 1. INFORMASI UMUM APLIKASI - -### 1.1 Identitas Sistem -- **Nama Aplikasi:** RTRWNET Management & Billing System -- **Versi:** 1.0.0 -- **Entry Point:** `app-customer.js` -- **Port Default:** 3001 (dapat diubah di settings.json) -- **Host Default:** localhost (dapat diubah di settings.json) -- **Runtime:** Node.js ≥20.0.0 - -### 1.2 Tech Stack -- **Backend Framework:** Express.js 4.18.2 -- **Database:** SQLite (better-sqlite3 11.3.0) -- **Frontend Templating:** EJS 3.1.10 -- **CSS Framework:** Bootstrap 5 + Bootstrap Icons -- **Mapping Library:** Leaflet (Peta geografis) -- **WhatsApp Integration:** Baileys (@whiskeysockets/baileys 6.7.21) -- **Session Management:** express-session 1.18.1 -- **File Upload:** multer 2.1.1 -- **Task Scheduling:** node-cron 4.2.1 -- **Spreadsheet:** xlsx (dari CDN sheetjs) - -### 1.3 Fitur Utama -1. **Portal Pelanggan** (Self-service) -2. **Portal Admin** (Manajemen lengkap) -3. **Portal Teknisi** (Field support) -4. **Portal Agen** (Sales & pembayaran) -5. **Portal Kolektor** (Approval pembayaran) -6. **Portal Finance** (Laporan keuangan) -7. **Billing & Invoicing** (Tagihan otomatis) -8. **MikroTik Integration** (PPPoE, Hotspot, Voucher) -9. **GenieACS Integration** (Manajemen CPE/ONU) -10. **OLT PON Management** (SNMP-based) -11. **WhatsApp Automation** (Baileys) -12. **Payment Gateway** (Midtrans, Tripay, Xendit, Duitku) -13. **GIS Mapping** (Peta pelanggan & ODP) -14. **Inventory Management** (Gudang) -15. **Ticketing System** (Support) -16. **Built-in TR-069 ACS** (Lightweight, tanpa GenieACS eksternal) - ---- - -## 2. ARSITEKTUR SISTEM - -### 2.1 Struktur Direktori -``` -billing-B481/ -├── app-customer.js ← Entry point utama -├── config/ ← Konfigurasi sistem -│ ├── database.js (SQLite initialization) -│ ├── logger.js (Logging - Winston & Pino) -│ ├── settingsManager.js (Kelola settings.json) -│ ├── settingsValidator.js (Validasi konfigurasi) -│ ├── genieacs.js (GenieACS API connector) -│ ├── genieacs-commands.js (GenieACS command builder) -│ ├── i18n.js (Internationalization) -│ ├── customerTag.js (Customer tagging logic) -│ └── settingsEncryption.js (Encryption helpers) -├── services/ ← Business logic (27 files) -│ ├── billingService.js (Invoice generation, promo, prorata) -│ ├── customerService.js (CRUD pelanggan) -│ ├── adminService.js (Admin management) -│ ├── mikrotikService.js (RouterOS API) -│ ├── oltService.js (OLT/SNMP management) -│ ├── onuProvisionService.js (ONU provisioning) -│ ├── telegramBot.js (Telegram integration) -│ ├── cronService.js (Task scheduling) -│ ├── paymentService.js (Payment gateways) -│ ├── voucherPaymentService.js (E-voucher) -│ ├── monitoringService.js (Health check) -│ └── ...17 services lainnya -├── routes/ ← API endpoints & page rendering -│ ├── customerPortal.js (Customer login, profile, billing) -│ ├── adminPortal.js (Admin panel) -│ ├── techPortal.js (Teknisi portal) -│ ├── agentPortal.js (Agen sales & pembayaran) -│ ├── collectorPortal.js (Kolektor approval) -│ ├── financePortal.js (Finance reports) -│ ├── voucherPaymentAPI.js (Voucher API) -│ ├── settingsAPI.js (Settings management API) -│ └── admin/ (Admin sub-routes) -├── middleware/ ← Middleware Express -│ ├── errorHandler.js (Error handling) -│ ├── settingsMiddleware.js (Settings injection) -│ └── attendanceUpload.js (Attendance upload) -├── views/ ← EJS Templates (78 files) -│ ├── customer/ (Customer portal pages) -│ ├── admin/ (Admin portal pages) -│ ├── tech/ (Teknisi pages) -│ ├── agent/ (Agen pages) -│ ├── collector/ (Kolektor pages) -│ ├── partials/ (Reusable components) -│ └── ...public pages -├── public/ ← Static files -│ ├── css/ (Bootstrap, custom styles) -│ ├── img/ (Logo, heroes) -│ ├── js/ (Frontend logic) -│ ├── uploads/ (QRIS, payment proof, tickets) -│ ├── sw.js (Service worker PWA) -│ └── manifest.webmanifest (PWA manifest) -├── database/ ← SQLite database -│ └── billing.db (Main database file) -├── scripts/ ← Utility scripts -│ ├── fix-database.sh (Database migration) -│ ├── verify-database.js (Database check) -│ └── ...test & migration scripts -├── locales/ ← i18n translations -│ ├── en.json (English) -│ └── id.json (Indonesian) -├── settings.json ← Application configuration -├── package.json ← Dependencies -└── .env ← Environment variables (optional) -``` - -### 2.2 Flow Aplikasi - -**Startup Process:** -1. `node app-customer.js` → Load `app-customer.js` -2. Inisialisasi database SQLite (`config/database.js`) -3. Load settings dari `settings.json` -4. Setup middleware (session, CSRF, i18n) -5. Mount portals (customer, admin, tech, agent, collector) -6. Start cron jobs (billing, isolir, pengingat tagihan) -7. Listen pada port `settings.json.server_port` - -**Request Flow (Contoh: Customer Login):** -``` -GET /customer/login - ↓ (Express routing) - ↓ (Session middleware) - ↓ (i18n middleware) - ↓ (customerPortal.js router) - ↓ (No auth required - render login page) - ↓ (EJS template rendering) - ← Response: HTML page -``` - -**POST Login Flow:** -``` -POST /customer/login - ↓ (Body parsing middleware) - ↓ (CSRF check via Referer/Origin) - ↓ (customerPortal.js - findCustomerProfileByLoginId) - ↓ (Database query: SELECT * FROM customers WHERE id/email/phone = ?) - ↓ (Verify kredensial) - ↓ (Set session.userId) - ↓ (Redirect ke /customer/dashboard) - ← Response: 302 redirect -``` - ---- - -## 3. DATABASE & SCHEMA - -### 3.1 Karakteristik Database -- **Type:** SQLite (better-sqlite3) -- **File Location:** `database/billing.db` -- **Journal Mode:** WAL (Write-Ahead Logging) -- **Foreign Keys:** Enabled -- **Timezone Function:** NOW_LOCAL() berdasarkan setting `timezone` - -### 3.2 Tabel Utama -Berdasarkan `config/database.js`, tabel yang di-initialize: - -1. **Konfigurasi & Settings** - - `settings` (key-value store untuk pengaturan runtime) - - `expense_categories` (kategori pengeluaran) - -2. **Master Data** - - `packages` (Paket layanan - name, price, speed_down, speed_up) - - `customers` (Pelanggan - phone, email, paket, PPPoE, GenieACS tag) - - `routers` (MikroTik router - host, user, password, port) - - `olts` (OLT devices - host, community SNMP, port, brand) - - `odps` (ODP - Optical Distribution Point - koordinat, lokasi) - -3. **Billing & Invoicing** - - `invoices` (Tagihan - customer_id, period_year, period_month, amount, status) - - `payments` (Pembayaran - invoice_id, amount, method, gateway, proof) - - `payment_approvals` (Approval kolektor - pending approval) - -4. **PPPoE Management** - - `pppoe_users` (User PPPoE - username, secret, speed profile) - - `pppoe_traffic_samples` (Traffic monitoring - bytes in/out, timestamp) - -5. **Hotspot** - - `hotspot_users` (User hotspot - username, password) - - `hotspot_sessions` (Session aktif) - -6. **Voucher** - - `voucher_batches` (Batch voucher - name, quantity, amount, price) - - `vouchers` (Individual vouchers - code, batch_id, status) - -7. **GenieACS & TR-069** - - `acsdevices` atau `genieacs_devices` (Daftar perangkat ACS) - - `acs_sessions` (Session TR-069) - -8. **OLT & ONU** - - `onu_mapping` (Pemetaan ONU ke pelanggan - olt_id, onu_port) - - `onu_provision` (Status provisioning ONU) - -9. **Operasional** - - `audit_trail` (Log audit untuk aktivitas sensitif) - - `expenses` (Catatan pengeluaran) - - `cash_in` (Catatan pemasukan) - - `technicians` (Daftar teknisi + login) - - `cashiers` (Daftar kasir) - - `agents` (Daftar agen) - - `collectors` (Daftar kolektor) - - `tickets` (Tiket support) - - `inventory_items` (Item gudang) - - `attendance` (Kehadiran karyawan) - - `digiflazz_transactions` (Pulsa/data digital transaksi) - - `vomit_log` (Log webhook pembayaran) - -### 3.3 Skema Relasi -``` -customers (1) ──→ (N) invoices - ├─→ (N) payments - ├─→ (N) pppoe_users - ├─→ (N) tickets - └─→ (1) packages - -packages (1) ──→ (N) customers - └─→ (N) pppoe_profiles - -routers (1) ──→ (N) pppoe_users - └─→ (N) hotspot_users - -olts (1) ──→ (N) onu_mapping - ├─→ (N) onu_provision - └─→ (1) odps - -voucher_batches (1) ──→ (N) vouchers -agents (1) ──→ (N) payments (via agent commission) -``` - ---- - -## 4. ENDPOINTS & ROUTES - -### 4.1 Portal Pelanggan (/customer) -**File:** `routes/customerPortal.js` - -**Authentication Routes:** -| Method | Endpoint | Fitur | -|--------|----------|-------| -| GET | `/customer/login` | Form login pelanggan | -| POST | `/customer/login` | Proses login (ID/email/phone) | -| GET | `/customer/logout` | Logout & destroy session | -| GET | `/customer/register` | Form registrasi pelanggan baru | -| POST | `/customer/register` | Proses registrasi | -| POST | `/customer/login-with-otp` | Login dengan OTP (jika enabled) | - -**Dashboard & Info:** -| GET | `/customer/dashboard` | Dashboard utama pelanggan | -| GET | `/customer/billing` | Riwayat tagihan | -| GET | `/customer/payment` | Halaman pembayaran | -| GET | `/customer/invoice/:id` | Detail invoice (cetak) | -| GET | `/customer/terms` | Syarat & ketentuan | -| GET | `/customer/privacy` | Kebijakan privasi | - -**CPE/Device Management:** -| GET | `/customer/device/:id` | Detail perangkat (SSID, password) | -| POST | `/customer/device/:id/reboot` | Reboot CPE | -| POST | `/customer/device/:id/wifi-change` | Ubah SSID/password Wi-Fi | -| POST | `/customer/device/:id/identify` | Identify perangkat (blink LED) | - -**Support & Ticketing:** -| GET | `/customer/tickets` | Daftar tiket pelanggan | -| POST | `/customer/tickets/create` | Buat tiket baru | -| POST | `/customer/tickets/:id/reply` | Reply tiket | - -**Payments:** -| POST | `/customer/pay` | Initiate pembayaran (gateway) | -| GET | `/customer/payment/callback` | Callback payment gateway | -| POST | `/api/webhook/v1/payment-notif` | Webhook pembayaran generik | - -**Voucher:** -| GET | `/customer/voucher` | Halaman beli voucher | -| POST | `/customer/voucher/buy` | Beli voucher hotspot | - -### 4.2 Portal Admin (/admin) -**File:** `routes/adminPortal.js` - -**Authentication:** -| Method | Endpoint | Fitur | -|--------|----------|-------| -| GET | `/admin/login` | Form login admin | -| POST | `/admin/login` | Proses login admin | -| GET | `/admin/logout` | Logout admin | - -**Dashboard & Reporting:** -| GET | `/admin/dashboard` | Dashboard ringkasan | -| GET | `/admin/reports` | Report keuangan/agregasi | -| GET | `/admin/billing/report` | Laporan billing | -| GET | `/admin/agents/report` | Laporan agen | - -**Pelanggan Management:** -| GET | `/admin/customers` | Daftar pelanggan | -| GET | `/admin/customers/search` | Search pelanggan | -| GET | `/admin/customers/:id` | Detail pelanggan | -| POST | `/admin/customers` | Tambah pelanggan | -| PUT | `/admin/customers/:id` | Edit pelanggan | -| DELETE | `/admin/customers/:id` | Hapus pelanggan | -| POST | `/admin/customers/:id/isolate` | Isolir pelanggan | -| POST | `/admin/customers/:id/unisolate` | Buka isolir | -| POST | `/admin/customers/reset-promo` | Reset siklus promo | -| GET | `/admin/customers/import` | Form impor pelanggan | -| POST | `/admin/customers/import` | Upload & impor Excel | -| GET | `/admin/customers/export` | Export daftar pelanggan | - -**Billing & Invoicing:** -| GET | `/admin/billing/invoices` | Daftar invoice | -| GET | `/admin/billing/invoices/:id` | Detail invoice | -| POST | `/admin/billing/generate` | Generate tagihan bulanan | -| POST | `/admin/billing/generate-single` | Generate untuk 1 pelanggan | -| POST | `/admin/billing/unpay` | Batalkan pembayaran | -| POST | `/admin/billing/prorata-susulan` | Prorata bulan pasang | -| GET | `/admin/billing/print/:id` | Cetak invoice | - -**Pembayaran & Gateway:** -| GET | `/admin/payments` | Daftar pembayaran | -| POST | `/admin/payments/verify` | Verifikasi pembayaran | -| GET | `/admin/payments/webhook-logs` | Log webhook pembayaran | -| POST | `/admin/payments/process` | Manual bayar invoice | -| GET | `/admin/settings/gateways` | Konfigurasi payment gateway | - -**Paket Layanan:** -| GET | `/admin/packages` | Daftar paket | -| POST | `/admin/packages` | Tambah paket | -| PUT | `/admin/packages/:id` | Edit paket | -| DELETE | `/admin/packages/:id` | Hapus paket | - -**MikroTik Management:** -| GET | `/admin/mikrotik/routers` | Daftar router | -| POST | `/admin/mikrotik/routers` | Tambah router | -| PUT | `/admin/mikrotik/routers/:id` | Edit router | -| POST | `/admin/mikrotik/test-connection` | Test koneksi router | -| GET | `/admin/mikrotik/pppoe/profiles` | Profil PPPoE | -| GET | `/admin/mikrotik/pppoe/users` | Daftar user PPPoE | -| GET | `/admin/mikrotik/pppoe/active-sessions` | Sesi PPPoE aktif | -| GET | `/admin/mikrotik/hotspot/users` | User hotspot | -| GET | `/admin/mikrotik/hotspot/active` | Sesi hotspot aktif | -| GET | `/admin/mikrotik/voucher/batches` | Batch voucher | -| POST | `/admin/mikrotik/voucher/generate` | Generate voucher | -| POST | `/admin/mikrotik/voucher/print` | Cetak voucher | -| GET | `/admin/mikrotik/voucher/export` | Export voucher CSV | - -**GenieACS & CPE:** -| GET | `/admin/genieacs/devices` | Daftar perangkat | -| GET | `/admin/genieacs/devices/:id` | Detail perangkat | -| POST | `/admin/genieacs/devices/:id/set-ssid` | Ubah SSID massal | -| POST | `/admin/genieacs/devices/:id/reboot` | Reboot perangkat | -| POST | `/admin/genieacs/devices/:id/provision` | Provision parameter | - -**OLT & ONU Management:** -| GET | `/admin/olts` | Daftar OLT | -| POST | `/admin/olts` | Tambah OLT | -| PUT | `/admin/olts/:id` | Edit OLT | -| GET | `/admin/olts/:id/onuses` | ONU per OLT | -| POST | `/admin/olts/:id/onu-reboot` | Reboot ONU | -| POST | `/admin/olts/:id/onu-authorize` | Otorisasi ONU | -| POST | `/admin/olts/:id/onu-rename` | Rename ONU | - -**Peta & Geografis:** -| GET | `/admin/map` | Peta interaktif pelanggan & ODP | -| GET | `/admin/map/customer-data` | JSON data pelanggan untuk peta | -| POST | `/admin/map/save-route` | Simpan jalur kabel | - -**Agen Management:** -| GET | `/admin/agents` | Daftar agen | -| POST | `/admin/agents` | Tambah agen | -| PUT | `/admin/agents/:id` | Edit agen | -| POST | `/admin/agents/:id/topup` | Top-up saldo agen | -| GET | `/admin/agents/:id/transactions` | Transaksi agen | -| GET | `/admin/agents/digiflazz` | Dashboard Digiflazz | - -**Tiket & Support:** -| GET | `/admin/tickets` | Daftar tiket | -| GET | `/admin/tickets/:id` | Detail tiket | -| POST | `/admin/tickets/:id/assign` | Assign ke teknisi | -| POST | `/admin/tickets/:id/close` | Tutup tiket | - -**Pengguna Internal:** -| GET | `/admin/users/technicians` | Daftar teknisi | -| POST | `/admin/users/technicians` | Tambah teknisi | -| PUT | `/admin/users/technicians/:id` | Edit teknisi | -| GET | `/admin/users/cashiers` | Daftar kasir | -| POST | `/admin/users/cashiers` | Tambah kasir | -| GET | `/admin/users/collectors` | Daftar kolektor | - -**WhatsApp & Notifikasi:** -| GET | `/admin/whatsapp/status` | Status koneksi WhatsApp | -| POST | `/admin/whatsapp/auth` | Otorisasi WhatsApp (QR code) | -| POST | `/admin/whatsapp/logout` | Logout WhatsApp | -| GET | `/admin/whatsapp/broadcast` | Form broadcast massal | -| POST | `/admin/whatsapp/broadcast/send` | Kirim broadcast | -| POST | `/admin/whatsapp/broadcast/pause` | Pause broadcast | -| POST | `/admin/whatsapp/test-notification` | Test notifikasi | - -**Inventory & Maintenance:** -| GET | `/admin/inventory` | Daftar inventory | -| POST | `/admin/inventory` | Tambah item | -| PUT | `/admin/inventory/:id` | Edit item | -| POST | `/admin/inventory/:id/adjust` | Adjustment stok | - -**Backup & Settings:** -| GET | `/admin/backup` | Halaman backup | -| POST | `/admin/backup/create` | Buat backup | -| POST | `/admin/backup/restore` | Restore backup | -| POST | `/admin/backup/delete` | Hapus backup file | -| GET | `/admin/settings` | Halaman settings | -| POST | `/admin/settings/save` | Simpan settings | -| POST | `/admin/settings/test-connection` | Test koneksi berbagai service | - -**Audit & Monitoring:** -| GET | `/admin/audit-logs` | Riwayat audit | -| GET | `/admin/monitoring` | Status sistem | - -### 4.3 Portal Teknisi (/tech) -**File:** `routes/techPortal.js` - -| Method | Endpoint | Fitur | -|--------|----------|-------| -| GET | `/tech/login` | Login teknisi | -| POST | `/tech/login` | Proses login | -| GET | `/tech/dashboard` | Dashboard teknisi | -| GET | `/tech/tickets` | Pool tiket untuk teknisi | -| POST | `/tech/tickets/:id/take` | Ambil tiket | -| POST | `/tech/tickets/:id/update` | Update progress tiket | -| POST | `/tech/tickets/:id/complete` | Selesaikan tiket | -| GET | `/tech/map` | Peta pelanggan & rute | -| GET | `/tech/customers/new` | Input pelanggan baru | -| POST | `/tech/customers/new` | Submit pelanggan baru | -| GET | `/tech/devices` | Daftar perangkat GenieACS | -| GET | `/tech/monitoring` | Monitoring sistem | -| POST | `/tech/attendance/check-in` | Check-in kehadiran (GPS) | -| POST | `/tech/attendance/check-out` | Check-out kehadiran | - -### 4.4 Portal Agen (/agent) -**File:** `routes/agentPortal.js` - -| Method | Endpoint | Fitur | -|--------|----------|-------| -| GET | `/agent/login` | Login agen | -| POST | `/agent/login` | Proses login agen | -| GET | `/agent/dashboard` | Dashboard agen | -| GET | `/agent/billing/check` | Cek tagihan pelanggan | -| POST | `/agent/billing/pay` | Bayar tagihan (saldo agen) | -| GET | `/agent/voucher` | Halaman jual voucher | -| POST | `/agent/voucher/buy` | Beli voucher dari stok | -| POST | `/agent/voucher/print` | Cetak struk transaksi | -| GET | `/agent/digiflazz` | Dashboard produk digital | -| POST | `/agent/digiflazz/buy` | Beli pulsa/data | -| GET | `/agent/digiflazz/status` | Cek status transaksi | -| GET | `/agent/balance` | Saldo akun agen | -| GET | `/agent/transactions` | Riwayat transaksi | - -### 4.5 Portal Kolektor (/collector) -**File:** `routes/collectorPortal.js` - -| Method | Endpoint | Fitur | -|--------|----------|-------| -| GET | `/collector/login` | Login kolektor | -| POST | `/collector/login` | Proses login | -| GET | `/collector/dashboard` | Dashboard kolektor | -| GET | `/collector/billing/check` | Cek tagihan pelanggan | -| POST | `/collector/billing/request` | Buat request pembayaran | -| GET | `/collector/requests` | Daftar request pending | -| GET | `/collector/history` | Riwayat approval | - -### 4.6 Portal Finance (/finance) -**File:** `routes/financePortal.js` - -| Method | Endpoint | Fitur | -|--------|----------|-------| -| GET | `/finance/dashboard` | Dashboard keuangan | -| GET | `/finance/summary` | Ringkasan pemasukan/pengeluaran | -| GET | `/finance/expenses` | Laporan pengeluaran | -| POST | `/finance/expenses` | Catat pengeluaran | -| GET | `/finance/cashflow` | Laporan arus kas | - -### 4.7 Public Routes (Tanpa Login) -| Method | Endpoint | Fitur | -|--------|----------|-------| -| GET | `/` | Redirect ke `/customer/login` | -| GET | `/login` | Alias singkat customer login | -| GET | `/isolated` | Halaman isolir statis (redirect MikroTik) | -| GET | `/isolated/status` | Polling status pelanggan isolir | -| GET | `/public/check-billing` | Cek tagihan tanpa login | -| GET | `/public/voucher` | Halaman beli voucher publik | -| GET | `/qris/static.jpg` | QRIS statis untuk pembayaran | -| GET | `/uploads/qris/:filename` | Download QRIS image | -| GET | `/health` | Health check endpoint | -| POST | `/webhook/digiflazz` | Webhook Digiflazz callback | -| POST | `/acs` | Built-in TR-069 ACS endpoint | - -### 4.8 Settings & Configuration API -**File:** `routes/settingsAPI.js` - -| Method | Endpoint | Fitur | -|--------|----------|-------| -| GET | `/api/settings` | Ambil settings (cached) | -| POST | `/api/settings` | Update settings | -| POST | `/api/settings/test-genieacs` | Test koneksi GenieACS | -| POST | `/api/settings/test-mikrotik` | Test koneksi MikroTik | -| POST | `/api/settings/test-tripay` | Test koneksi Tripay | -| POST | `/api/settings/test-midtrans` | Test koneksi Midtrans | -| GET | `/api/backup/list` | Daftar backup files | - -### 4.9 Voucher Payment API -**File:** `routes/voucherPaymentAPI.js` - -| Method | Endpoint | Fitur | -|--------|----------|-------| -| GET | `/api/voucher/available` | List voucher tersedia | -| POST | `/api/voucher/purchase` | Beli voucher (JSON API) | -| GET | `/api/voucher/status/:code` | Cek status voucher | - ---- - -## 5. FITUR-FITUR UTAMA - -### 5.1 Billing & Invoicing -**Service:** `services/billingService.js` - -**Fitur:** -- ✅ Generate tagihan bulanan otomatis (trigger: 1 bulan 00:01) -- ✅ Harga Promo: Diskon N siklus pertama per pelanggan -- ✅ Prorata: Tagihan proportional untuk bulan pasang -- ✅ Susulan Prorata: Tambahan tagihan untuk menutup bulan pasang -- ✅ Status Invoice: Draft → Pending → Paid → Overdue → Cancelled -- ✅ Reset Promo Cycles: Admin dapat reset ulang harga promo -- ✅ Cetak Invoice: PDF-ready HTML format - -**Database Tables:** -- `invoices` (id, customer_id, period_year, period_month, amount, status, notes) -- `payments` (id, invoice_id, amount, method, gateway, proof, timestamp) -- `payment_approvals` (id, payment_id, approver_id, status) - -### 5.2 MikroTik Integration -**Service:** `services/mikrotikService.js` - -**Fitur:** -- ✅ Multi-router support (multiple MikroTik instances) -- ✅ RouterOS 7 compatible -- ✅ PPPoE: Profil, user/secret, sesi aktif, monitor trafik -- ✅ Hotspot: Profil, user, sesi aktif -- ✅ Jam Kalong: Ganti profil malam/siang otomatis (cron 00:00 & 06:00) -- ✅ FUP (Fair Usage Policy): Monitor GB & ganti profil turun kecepatan -- ✅ Usage Tracking: Sinkron pemakaian setiap 10 menit dari sesi aktif -- ✅ Voucher: Generate batch, sinkron, cetak, export CSV -- ✅ Backup Konfigurasi: Download backup dari router - -**Supported Operations:** -- Add/Remove PPPoE user -- Monitor active sessions -- Change profile (traffic shaping) -- Generate voucher codes -- Export/import configuration - -### 5.3 GenieACS & TR-069 -**Services:** -- `services/acsServerService.js` (Built-in lightweight ACS) -- `services/customerDeviceService.js` (CPE/ONU device management) -- `routes/acsPortal.js` (GenieACS REST API integration) - -**Fitur:** -- ✅ Built-in ACS server (lightweight, tanpa GenieACS eksternal opsional) -- ✅ Multi-ACS support (fallback ke GenieACS eksternal jika built-in disabled) -- ✅ Device discovery & provisioning otomatis -- ✅ Change SSID/password Wi-Fi -- ✅ Reboot CPE -- ✅ Parameter provisioning -- ✅ Monitor RX Power (optical signal strength) -- ✅ Bulk SSID update - -**Configuration:** -```json -{ - "use_builtin_acs": true, - "genieacs_url": "http://192.168.x.x:7557", - "genieacs_monitoring_enabled": true, - "genieacs_rxpower_threshold": -27 -} -``` - -**ACS URL untuk ONU:** -- `http://[IP-SERVER]:[PORT]/acs` -- Contoh: `http://192.168.1.100:3001/acs` - -### 5.4 OLT & ONU Management -**Service:** `services/oltService.js`, `services/onuProvisionService.js` - -**Fitur:** -- ✅ Multi-OLT support (Telnet, SNMP, REST API) -- ✅ SNMP monitoring: Statistik ONU per port -- ✅ Telnet: Konfigurasi ZTE OLT (OMCI) -- ✅ REST API: go-api-c320 untuk ZTE (VLAN/Bridge) -- ✅ ONU Actions: - - Reboot ONU - - Rename ONU - - Otorisasi ONU baru - - Konfigurasi WAN (Telnet/OMCI/TR069/REST) - - Konfigurasi VLAN & Bridge - -**OLT Brands Supported:** -- ZTE C-series (Telnet, REST) -- Huawei -- FiberHome -- VSOL -- C-Data -- China Mobile, Telecom, Unicom - -### 5.5 GIS Mapping & Geografis -**Services:** `routes/admin/maps.js`, `routes/tech/map` - -**Frontend Library:** Leaflet + OpenStreetMap/Google Hybrid - -**Fitur:** -- ✅ Peta interaktif dengan marker pelanggan & ODP -- ✅ Garis hubung pelanggan ke ODP -- ✅ Polyline jalur kabel per pelanggan (simpan/load) -- ✅ Popup detail: status, paket, trafik real-time -- ✅ Basemap toggle: OSM & Satelit -- ✅ GPS lokasi teknisi (peta teknisi) -- ✅ Rute Google Maps integration -- ✅ WhatsApp chat button di popup -- ✅ Drag-drop lokasi pelanggan baru - -**Koordinat Default:** -```json -{ - "office_lat": "-6.252118625253105", - "office_lng": "107.9205270612316" ← Titik acuan peta -} -``` - -### 5.6 WhatsApp Automation (Baileys) -**Service:** `services/telegramBot.js` (typo filename, actually WhatsApp) - -**Fitur:** -- ✅ Koneksi WhatsApp via Baileys (login QR code) -- ✅ Broadcast massal dengan jeda/antrian -- ✅ Notifikasi tagihan pembayaran otomatis -- ✅ Pengingat H-1 isolir (cron 09:00) -- ✅ Admin commands (menu, billing tools, pulsa Digiflazz) -- ✅ Agent commands (beli pulsa, cek saldo) -- ✅ Jeda/pause/stop broadcast -- ✅ Reset autentikasi session -- ✅ Variasi pesan otomatis (randomize) - -**Commands:** -``` -Admin: - /admin → Menu admin - /billing → Billing tools - /mikrotik → MikroTik tools - /digiflazz → Cek saldo Digiflazz - /topup → Top-up saldo agen - -Agent: - /buy → Beli pulsa Digiflazz - /status → Cek status transaksi -``` - -### 5.7 Payment Gateways -**Service:** `services/paymentService.js` - -**Supported Gateways:** -- ✅ **Midtrans** (Verifone): Snap, QRIS, e-wallet -- ✅ **Tripay**: Bank transfer, e-wallet, QRIS -- ✅ **Xendit**: Invoice API -- ✅ **Duitku**: Bank transfer, QRIS -- ✅ **Generic Webhook**: Endpoint `POST /api/webhook/v1/payment-notif` - -**Fitur Payment:** -- ✅ Multi-gateway routing -- ✅ QRIS dinamis per invoice -- ✅ QRIS statis untuk pembayaran umum -- ✅ Kode unik per invoice (automatic) -- ✅ Webhook callback notification -- ✅ Payment verification & auto-settle -- ✅ Automatic WhatsApp notification -- ✅ Offline/manual payment entry (kasir) -- ✅ Payment proof upload (foto struk) - -**Configuration:** -```json -{ - "default_gateway": "tripay", - "midtrans_enabled": true, - "tripay_enabled": false, - "xendit_enabled": true, - "duitku_enabled": true -} -``` - -### 5.8 Agen & Sales Management -**Services:** `services/agentService.js`, Digiflazz integration - -**Fitur:** -- ✅ Multi-agen support -- ✅ Saldo agen (top-up oleh admin) -- ✅ Bayar tagihan pelanggan dari saldo agen -- ✅ Jual voucher hotspot -- ✅ Transaksi pulsa/data digital Digiflazz -- ✅ Laporan transaksi agen -- ✅ Harga khusus per agen -- ✅ Commission tracking - -**Digiflazz Integration:** -- ✅ Webhook untuk update status transaksi -- ✅ Sync produk (kategori, brand, nominal) -- ✅ Cek saldo Digiflazz -- ✅ Admin dashboard Digiflazz -- ✅ Signature-based authentication - -### 5.9 Ticketing System -**Service:** `services/ticketService.js` - -**Fitur:** -- ✅ Pelanggan bisa buat tiket -- ✅ Teknisi assign tiket dari pool -- ✅ Update progress tiket -- ✅ Lampiran foto tiket -- ✅ Reply & follow-up -- ✅ Close tiket dengan resolusi - -### 5.10 Inventory & Warehouse -**Service:** `services/inventoryService.js` - -**Fitur:** -- ✅ CRUD kategori & item -- ✅ Tracking stok -- ✅ Adjustment & penyesuaian -- ✅ Alert stok rendah -- ✅ Riwayat transaksi inventory - -### 5.11 Monitoring & Health Check -**Services:** `services/monitoringService.js`, `services/diagnosticsService.js` - -**Fitur:** -- ✅ CPU, RAM, Disk usage -- ✅ Konektivitas ke GenieACS -- ✅ Konektivitas ke MikroTik -- ✅ Konektivitas ke OLT -- ✅ Database size -- ✅ Public endpoint: `GET /health` (lightweight) - -### 5.12 Cron Jobs (Otomasi Terjadwal) -**Service:** `services/cronService.js` - -**Jadwal:** -| Waktu | Fitur | Command | -|-------|-------|---------| -| **1 bulan, 00:01** | Generate tagihan bulanan | `generateMonthlyInvoices()` | -| **Setiap hari 02:00** | Isolir otomatis pelanggan jatuh tempo | `autoIsolatePlansExpired()` | -| **Setiap hari 09:00** | Pengingat tagihan H-1 via WhatsApp | `sendBillingReminders()` | -| **00:00 & 06:00** | Jam Kalong (ganti profil PPPoE) | `handleTimeBasedProfileChange()` | -| **Setiap 10 menit** | Sinkron usage PPPoE | `syncUsageTracking()` | -| **Setiap jam** | FUP check & profile tuning | `checkFUPQuota()` | - -### 5.13 Backup & Restoration -**Service:** `services/backupService.js` - -**Fitur:** -- ✅ Backup database (SQLite) -- ✅ Backup settings.json -- ✅ Backup kombinasi (database + settings) -- ✅ Restore dari backup file -- ✅ Auto-cleanup backup lama (retention policy) -- ✅ Scheduled backup (opsional) - -### 5.14 Audit Trail & Logging -**Services:** `services/auditTrailService.js`, logging via Winston/Pino - -**Fitur:** -- ✅ Log aktivitas sensitif (login, pembayaran, settings) -- ✅ Timestamp + user + action -- ✅ Cleanup audit trail otomatis (default 90 hari) -- ✅ Export audit log - -### 5.15 Attendance & Geofencing -**Service:** `services/attendanceService.js` - -**Fitur:** -- ✅ Check-in/check-out dengan GPS -- ✅ Geofencing: validasi radius dari kantor (default 100m) -- ✅ Foto kehadiran upload -- ✅ Riwayat kehadiran per karyawan -- ✅ Report kehadiran - -**Configuration:** -```json -{ - "attendance_geofencing": true, - "attendance_radius": 100, - "office_lat": "-6.252118625253105", - "office_lng": "107.9205270612316" -} -``` - ---- - -## 6. KEAMANAN & OTENTIKASI - -### 6.1 Authentication Methods -1. **Session-based (Express-session)** - - Session secret: `settings.json.session_secret` (HARUS diganti) - - Storage: Memory (upgrade ke Redis untuk production) - - TTL: Configurable - -2. **Role-based Access Control (RBAC)** - - Super Admin (unrestricted) - - Admin (most features) - - Kasir (payment-only) - - Teknisi (support tasks) - - Kolektor (approval-only) - - Agen (sales-only) - - Pelanggan (self-service) - -3. **OTP Login (Opsional)** - - via WhatsApp atau SMS - - `settings.json.login_otp_enabled` = true - -### 6.2 CSRF Protection -**Implementasi:** Referer/Origin checking (middleware di app-customer.js) -- Hanya untuk POST/PUT/DELETE -- Check header referer/origin terhadap domain lokal -- Aman untuk production tanpa perlu CSRF token di EJS - -### 6.3 Encryption & Secrets -- **Database encryption:** opsional di `config/settingsEncryption.js` -- **Session secret:** `settings.json.session_secret` (HARUS random) -- **API keys:** Stored di `settings.json` (recommended: external .env atau secrets manager) -- **Password:** TODO implement bcrypt hashing (current: plaintext risky!) - -### 6.4 Security Best Practices (TODO) -⚠️ **Recommendations for Production:** -1. ✅ Session secret → random string (24+ characters) -2. ✅ HTTPS everywhere (reverse proxy: nginx) -3. ✅ Rate limiting (brute force protection) -4. ✅ Input validation & sanitization -5. ❌ Password hashing → Implement bcrypt -6. ❌ CORS → Restrict allowed origins -7. ❌ API authentication → Token-based (JWT) -8. ❌ Audit logging → Already implemented -9. ❌ Admin API key → Currently weak, use strong random key -10. ❌ Settings encryption → For sensitive data (credentials) - ---- - -## 7. FRONTEND & UI - -### 7.1 Template Engine -- **EJS:** 78 template files total - -### 7.2 Frontend Framework -- **Bootstrap 5.x** (CDN atau local) -- **Bootstrap Icons** (bi bi-*) -- **jQuery** (minimal usage) -- **Chart.js / Apex Charts** (untuk grafik) -- **Leaflet** (untuk peta) - -### 7.3 View Structure (78 files) -``` -views/ -├── admin/ (Admin portal pages) -├── agent/ (Agen portal pages) -├── collector/ (Kolektor portal pages) -├── customer/ (Pelanggan portal pages) -├── tech/ (Teknisi portal pages) -├── partials/ (Reusable components) -├── login.ejs (Default login) -├── dashboard.ejs (Dashboard template) -├── isolated.ejs (Halaman isolir) -└── ...public pages -``` - -### 7.4 CSS & Styling -- **Bootstrap 5 utility classes** (primary framework) -- **Custom CSS:** `public/css/style.css`, `public/css/admin.css` -- **Responsive design** (mobile-first) -- **Dark mode:** opsional (implementasi partial) - -### 7.5 Frontend Features -- ✅ Lazy loading (CSS, images, icons) -- ✅ Service Worker (PWA) - `public/sw.js` -- ✅ PWA manifest - `public/manifest.webmanifest` -- ✅ Offline caching (limited) -- ✅ Real-time peta (Leaflet, WebSocket opsional) -- ✅ Form validation (client + server) -- ✅ Responsive tables (horizontal scroll pada mobile) - ---- - -## 8. INTERNATIONALIZATION (i18n) - -**Configuration:** `config/i18n.js` - -**Supported Languages:** -- 🇮🇩 Indonesian (id) - default -- 🇬🇧 English (en) - alternative - -**Translation Files:** -- `locales/id.json` (Indonesian UI strings) -- `locales/en.json` (English UI strings) - -**Usage:** -``` -GET /lang/en → Set session language to English -GET /?lang=en → Query parameter override -``` - -**Template Usage:** -```ejs -<%= i18n.t('key_name') %> -``` - ---- - -## 9. CONFIGURATION & SETTINGS - -### 9.1 settings.json Structure -```json -{ - // GenieACS - "genieacs_url": "http://...", - "genieacs_username": "...", - "genieacs_password": "...", - "genieacs_monitoring_enabled": true, - "genieacs_rxpower_threshold": -27, - - // Company Info - "company_header": "ALIJAYA NET", - "company_manager": "ALIJAYA NET", - "company_phone": "6281947215703", - "company_email": "...", - "company_address": "...", - - // Server - "server_port": 3001, - "server_host": "localhost", - "timezone": "Asia/Jakarta", - - // Security - "session_secret": "change-this-to-random-secret-key", - "admin_username": "admin", - "admin_password": "admin123", - "admin_api_key": "admin-api-key-change-this", - - // MikroTik - "mikrotik_host": "192.168.8.1", - "mikrotik_user": "admin", - "mikrotik_password": "admin", - "mikrotik_port": 8728, - - // Billing - "isolir_day": 20, - - // Payment Gateways - "default_gateway": "tripay", - "tripay_enabled": false, - "tripay_api_key": "...", - "midtrans_enabled": true, - "midtrans_server_key": "...", - "xendit_enabled": true, - "duitku_enabled": true, - - // WhatsApp - "whatsapp_enabled": true, - "whatsapp_broadcast_delay": 60, - - // Geographic - "office_lat": "-6.252...", - "office_lng": "107.920...", - "attendance_geofencing": true, - "attendance_radius": 100, - - // Features - "login_otp_enabled": false, - "telegram_enabled": false, - "use_builtin_acs": true, - "auto_backup_enabled": false -} -``` - -### 9.2 Environment Variables (.env) -- `NODE_ENV` (development/production) -- `MY_WEBHOOK_SECRET` (generic webhook security) -- Optional: sensitive credentials - -### 9.3 Settings Management API -**Endpoints:** -- `GET /api/settings` → Get cached settings -- `POST /api/settings` → Update settings (admin only) -- `POST /api/settings/test-*` → Test connectivity - ---- - -## 10. DEPENDENCIES & LIBRARIES - -### 10.1 Production Dependencies -```json -{ - "express": "^4.18.2", // Web framework - "express-session": "^1.18.1", // Session management - "ejs": "^3.1.10", // Template engine - "better-sqlite3": "^11.3.0", // SQLite driver - "multer": "^2.1.1", // File upload - "axios": "^1.6.7", // HTTP client - "node-cron": "^4.2.1", // Task scheduling - "dotenv": "^16.3.1", // ENV file loading - "@whiskeysockets/baileys": "^6.7.21", // WhatsApp API - "net-snmp": "^3.26.1", // SNMP protocol - "ssh2": "^1.15.0", // SSH/Telnet - "winston": "^3.8.2", // Logging - "pino": "^9.6.0", // Logger alternative - "node-telegram-bot-api": "^0.66.0", // Telegram bot - "qrcode": "^1.5.4", // QR code generation - "routeros-client": "^1.1.1", // MikroTik API - "jimp": "^1.6.1", // Image manipulation - "jsqr": "^1.4.0", // QR code reading - "@zxing/library": "^0.21.3", // Barcode library - "qrcode-terminal": "^0.12.0", // Terminal QR display - "xlsx": "^0.20.1" // Excel parsing -} -``` - -### 10.2 Dev Dependencies -```json -{ - "nodemon": "^3.1.14" // Auto-restart on file change -} -``` - -### 10.3 Version Constraints -- **Node.js:** ≥20.0.0 (modern features) -- **NPM:** ≥9.0.0 (recommended) -- **Overrides:** Specific fixed versions untuk security patches - ---- - -## 11. OPERATIONAL REQUIREMENTS - -### 11.1 Prerequisites -- ✅ Node.js 20+ -- ✅ Linux/Ubuntu, Armbian, Windows, atau macOS -- ✅ Network access ke: GenieACS, MikroTik, OLT, Internet (untuk CDN/gateways) -- ✅ Port availability: 3001 (configurable) - -### 11.2 Installation -```bash -git clone https://github.com/alijayanet/billing-rtrw.git -cd billing-rtrw -cp env-example.txt .env -npm install -``` - -### 11.3 Running Aplikasi - -**Development:** -```bash -npm run dev -``` - -**Production (Manual):** -```bash -npm start -``` - -**Production (PM2 - Recommended):** -```bash -npm install -g pm2 -pm2 start app-customer.js --name billing-rtrw -pm2 startup -pm2 save -``` - -### 11.4 Database Migration -Jika error "no such column: hotspot_username": - -**Opsi 1 (Auto-fix):** -```bash -bash scripts/fix-database.sh -``` - -**Opsi 2 (Manual verify):** -```bash -node scripts/verify-database.js -``` - -### 11.5 Backup Execution -**Auto-backup (jika enabled):** -```json -{ - "auto_backup_enabled": true -} -``` - -**Manual backup:** -- Via Admin Panel → Backup → Create -- Atau: `POST /api/backup/create` - ---- - -## 12. MONITORING & TROUBLESHOOTING - -### 12.1 Health Check -- **Endpoint:** `GET /health` (public) -- **Response:** `{ status: 'ok', timestamp, database, services }` - -### 12.2 Logging -- **Log files:** Konfigurasi via Winston/Pino -- **Location:** `logs/` directory (opsional) -- **Level:** info, warn, error -- **Console output:** Development mode - -### 12.3 Common Issues & Solutions - -**Issue: Aplikasi crash saat startup** -- Solusi 1: Cek `settings.json` valid JSON -- Solusi 2: Database corrupted → Hapus `database/billing.db`, restart -- Solusi 3: Port 3001 sudah digunakan → Ganti di `settings.json` - -**Issue: Database locked error** -- Solusi: SQLite WAL mode conflict → Restart aplikasi -- Atau: Hapus `database/billing.db-shm` dan `database/billing.db-wal` - -**Issue: GenieACS connection failed** -- Solusi: Cek URL di `settings.json` -- Verifikasi: `POST /api/settings/test-genieacs` - -**Issue: MikroTik tidak terhubung** -- Solusi: Cek kredensial & API port (default 8728) -- Verifikasi: `POST /api/settings/test-mikrotik` - -**Issue: WhatsApp tidak terkoneksi** -- Solusi: Login ulang via QR code -- Admin Panel → WhatsApp → Logout → Auth again - -**Issue: Payment gateway error** -- Solusi: Cek API key & secret -- Verifikasi: `POST /api/settings/test-[gateway]` - ---- - -## 13. PRODUCTION CHECKLIST - -### 13.1 Pre-Deployment - -**Security:** -- ✅ Ganti `session_secret` dengan random string 32+ char -- ✅ Ganti `admin_password` dengan password kuat -- ✅ Ganti `admin_api_key` dengan API key random -- ✅ Implementasi bcrypt untuk password hashing -- ✅ Enable HTTPS (reverse proxy: nginx) -- ✅ Setup firewall rules -- ✅ Restrict access ke admin panel (/admin) -- ✅ Remove debug logging pada production - -**Configuration:** -- ✅ Set `NODE_ENV=production` -- ✅ Konfigurasi semua payment gateways -- ✅ Setup WhatsApp authentication -- ✅ Setup backup folder (auto-backup enabled) -- ✅ Configure timezone sesuai lokasi -- ✅ Setup OLT & GenieACS credentials - -**Database:** -- ✅ Run full database verification -- ✅ Setup automated backup (cron job) -- ✅ Test restore backup process -- ✅ Monitor database size - -**Monitoring:** -- ✅ Setup error logging & alerts -- ✅ Setup uptime monitoring (healthcheck) -- ✅ Setup database backup verification -- ✅ Setup audit trail cleanup (cron) - -### 13.2 Post-Deployment - -**Verification:** -- ✅ Test semua portal (customer, admin, tech, agent, collector) -- ✅ Test billing generation -- ✅ Test payment webhook -- ✅ Test WhatsApp notification -- ✅ Test MikroTik integration -- ✅ Test GenieACS/ONU management -- ✅ Test backup & restore - -**Monitoring:** -- ✅ Monitor error logs untuk first 24 hours -- ✅ Monitor database growth -- ✅ Monitor CPU/RAM usage -- ✅ Monitor connectivity to external services - ---- - -## 14. PERFORMANCE OPTIMIZATION - -### 14.1 Already Implemented -- ✅ Lazy loading CSS & Bootstrap Icons -- ✅ Parallel database queries -- ✅ Service Worker caching -- ✅ Hotspot users cache (15 seconds) -- ✅ Settings cache (in-memory) -- ✅ Database indexes (better-sqlite3 auto-indexes) - -### 14.2 Recommendations -- ⚠️ Setup Redis untuk session store (replace memory store) -- ⚠️ Enable database query caching -- ⚠️ Implement CDN untuk static assets -- ⚠️ Setup load balancing (PM2 cluster mode atau nginx upstream) -- ⚠️ Optimize large dataset queries dengan pagination -- ⚠️ Monitor & cleanup old audit trails regularly - ---- - -## 15. FILE SIZE & STATISTICS - -### 15.1 Codebase Statistics -- **Total Template Files:** 78 EJS files -- **Total Service Files:** 27 service modules -- **Total Route Files:** 12 router modules -- **Configuration Files:** 10 config modules -- **Database File Size:** ~5-50 MB (depends on data volume) - -### 15.2 Directory Sizes (approximate) -``` -views/ ~500 KB (78 EJS templates) -public/ ~1-2 MB (static assets) -database/ ~5-50 MB (SQLite + WAL) -node_modules/ ~200-300 MB (dependencies) -scripts/ ~50 KB (utility scripts) -``` - ---- - -## 16. DOKUMENTASI & RESOURCES - -### 16.1 Official Resources -- GitHub: https://github.com/alijayanet/billing-rtrw -- License: ISC -- Author: Ali Jaya Net (081947215703) - -### 16.2 Key Documentation Files -- `README.md` - Overview fitur & instalasi -- `OLT_OID_REFERENCE.md` - OLT SNMP OID reference -- `env-example.txt` - Environment variables example -- `scripts/fix-database.sh` - Database migration helper - -### 16.3 Configuration Examples -- `settings.json` - Main configuration (DOCUMENTED above) -- `package.json` - Dependencies & scripts - ---- - -## 17. FITUR LANJUTAN & INTEGRASI - -### 17.1 TR-069 Built-in ACS (Lightweight) -**Keuntungan:** -- Tanpa GenieACS eksternal yang mahal -- Berjalan di process yang sama dengan aplikasi billing -- Lightweight: hanya ~50-100 MB RAM -- Kompatibel dengan berbagai brand ONU - -**Setup ONU:** -``` -ACS URL: http://[IP-SERVER]:3001/acs -Periodic Inform: 300-600 detik -``` - -### 17.2 Multi-language Support -- Indonesian (id) - Primary -- English (en) - Secondary -- Extensible untuk bahasa lain - -### 17.3 PWA (Progressive Web App) -- Service Worker: `public/sw.js` -- Manifest: `public/manifest.webmanifest` -- Offline support (limited) -- Installable pada mobile - -### 17.4 Advanced Payment Integration -- Multiple gateway failover -- Webhook signature verification -- Auto-settlement on payment received -- Manual payment entry untuk offline/bank transfer - -### 17.5 GIS & Location Services -- Real-time customer location -- Technician GPS tracking -- Route optimization (Google Maps integration) -- Distance-based metrics - ---- - -## 18. KESIMPULAN AUDIT - -### 18.1 Status Kesehatan Aplikasi -✅ **PRODUCTION-READY** dengan catatan: - -### 18.2 Kekuatan Sistem -1. ✅ Comprehensive feature set (billing → network management) -2. ✅ Multi-portal architecture (flexibility per role) -3. ✅ Robust integration ecosystem (MikroTik, GenieACS, OLT, payment) -4. ✅ Lightweight & efficient (SQLite, no external dependencies) -5. ✅ Good code organization (services, routes, middleware pattern) -6. ✅ Automation via cron jobs (billing, isolir, reminders) -7. ✅ Internationalization support (i18n ready) - -### 18.3 Areas for Improvement -1. ⚠️ **Security hardening:** - - Implement bcrypt untuk password storage - - Add rate limiting - - Enhance CORS configuration - - JWT-based API authentication - -2. ⚠️ **Performance optimization:** - - Redis untuk session store - - Database query caching - - CDN untuk static assets - - Load balancing setup - -3. ⚠️ **Testing coverage:** - - Unit tests (services) - - Integration tests (routes) - - API tests (endpoints) - -4. ⚠️ **Documentation:** - - API documentation (Swagger/OpenAPI) - - Database schema documentation - - Deployment guide (Docker, K8s) - -5. ⚠️ **Code quality:** - - ESLint configuration - - Code style guidelines - - Input validation framework - -### 18.4 Rekomendasi Immediate Actions -1. ✅ DONE: Generate audit documentation (file ini) -2. ⏳ NEXT: Backup aplikasi & database -3. ⏳ NEXT: Test semua fitur di staging environment -4. ⏳ NEXT: Setup monitoring & alerting -5. ⏳ NEXT: Create runbook operasional - -### 18.5 Long-term Roadmap -- [ ] Modernize dengan TypeScript -- [ ] Add comprehensive testing suite -- [ ] Containerize dengan Docker -- [ ] Setup CI/CD pipeline -- [ ] Add API documentation (Swagger) -- [ ] Enhance security (OAuth2, JWT) -- [ ] Performance monitoring (APM) - ---- - -**Audit Date:** Juni 2026 -**Audit Status:** ✅ COMPLETE -**Document Version:** 1.0 -**Last Updated:** 2026-06-19 - -**Jangan lupa:** Simpan backup dokumentasi ini di lokasi aman! - diff --git a/docs/AUDIT_SECURITY_2026.md b/docs/AUDIT_SECURITY_2026.md deleted file mode 100644 index b0a9ed8..0000000 --- a/docs/AUDIT_SECURITY_2026.md +++ /dev/null @@ -1,833 +0,0 @@ -# AUDIT KEAMANAN & KUALITAS APLIKASI BILLING RTRWNET -**Status:** ✅ AUDIT LENGKAP -**Tanggal Audit:** 14 Agustus 2026 -**Auditor:** Security & Code Quality Review -**Aplikasi Status:** 🟠 PRODUCTION WITH CRITICAL ISSUES - ---- - -## 📋 RINGKASAN EKSEKUTIF - -Aplikasi RTRWNET Billing System adalah sistem yang **comprehensive dan feature-rich** untuk manajemen ISP. Namun, audit menemukan **beberapa kerentanan keamanan KRITIS** yang harus segera diperbaiki sebelum production deployment atau jika sudah di production harus segera ditindaklanjuti. - -### Skor Keamanan: 5.5/10 🔴 -- ✅ Aspek Positif: Struktur kode baik, error handling solid, logging terimplementasi -- ⚠️ Aspek Kritis: Keamanan password, configuration management, input validation -- ❌ Aspek Negatif: Plaintext credentials, default passwords, weak hashing - ---- - -## 🔐 KEAMANAN KRITIS - SEGERA PERBAIKI - -### 1. PASSWORD DISIMPAN DALAM PLAINTEXT ❌ CRITICAL - -**Lokasi:** -- [services/techService.js](services/techService.js#L4) - Password technician tersimpan plaintext di database -- [settings.json](settings.json#L20-L21) - Admin password `admin123` dalam plaintext - -**Masalah:** -```javascript -// ❌ TIDAK AMAN - Line 4 di techService.js -const tech = db.prepare('SELECT * FROM technicians WHERE username = ? AND password = ? AND is_active = 1').get(username, password); -// Password dibandingkan langsung tanpa hashing - -// ❌ TIDAK AMAN - settings.json -"admin_username": "admin", -"admin_password": "admin123", // Password plaintext! -``` - -**Risiko:** -- Jika database bocor, semua password terekspos -- Jika settings.json terlihat, credentials admin langsung ketahuan -- Tidak compliance dengan standar keamanan (OWASP, ISO27001) -- Database breach = total kompromis sistem - -**Rekomendasi - HARUS DILAKUKAN:** - -1. **Implementasi bcrypt untuk hashing password:** -```javascript -// Install bcrypt terlebih dahulu -// npm install bcrypt - -// Saat register/create user: -const bcrypt = require('bcrypt'); -const hashedPassword = await bcrypt.hash(plainPassword, 10); -// Simpan hashedPassword ke database - -// Saat authenticate: -const isValid = await bcrypt.compare(plainPassword, hashedPassword); -if (isValid) { - // Login berhasil -} -``` - -2. **Update database schema:** -```sql --- Tambahkan kolom password_hash -ALTER TABLE technicians ADD COLUMN password_hash TEXT; -ALTER TABLE administrators ADD COLUMN password_hash TEXT; - --- Update existing passwords dengan hash --- (Lakukan migration script terpisah) -``` - -3. **Jangan simpan password di settings.json:** -```json -// ❌ SEBELUM -{ - "admin_password": "admin123" -} - -// ✅ SESUDAH - Gunakan database atau environment variable -{ - "admin_user_id": 1 // Reference ke database saja -} - -// Atau gunakan .env file: -ADMIN_PASSWORD_HASH="$2b$10$..." -``` - -**Timeline:** IMMEDIATE - Sebelum production - ---- - -### 2. DEFAULT CREDENTIALS (admin/admin123) ❌ CRITICAL - -**Lokasi:** [settings.json](settings.json#L19-L21) - -**Masalah:** -- Default username/password yang sangat lemah -- Siapapun yang tahu dokumentasi aplikasi bisa login -- OWASP Top 10: A01:2021 - Broken Access Control - -**Rekomendasi:** -```bash -# Script untuk force password change saat first-time setup -node scripts/setup-admin-password.js - -# Atau implementasikan setup wizard: -- Saat pertama kali aplikasi dijalankan -- Wajib setup admin username & password baru -- Simpan di database dengan hash bcrypt -- Tandai setup selesai di flag di database -``` - -**Timeline:** IMMEDIATE - ---- - -### 3. API KEY & CREDENTIALS DALAM PLAINTEXT ❌ CRITICAL - -**Lokasi:** [settings.json](settings.json) -```json -"genieacs_password": "admin", -"midtrans_server_key": "", -"xendit_api_key": "", -"tripay_private_key": "", -"digiflazz_api_key": "", -"radius_secret": "secret123" -``` - -**Masalah:** -- Semua credentials eksternal dalam plaintext di file JSON -- File bisa terlihat di source code management -- Risiko exposure jika server dikompromis -- Tidak praktis untuk berbagai environment (dev/staging/production) - -**Rekomendasi - HARUS DILAKUKAN:** - -1. **Gunakan environment variables (.env):** -```bash -# File: .env (JANGAN commit ke git!) -GENIEACS_URL=http://192.168.8.189:7557 -GENIEACS_USERNAME=admin -GENIEACS_PASSWORD=SecurePassword123! -MIDTRANS_SERVER_KEY=Mid-xxxxx-xxx -XENDIT_API_KEY=xnd_development_xxxxx -TRIPAY_API_KEY=xxxxx -DIGIFLAZZ_API_KEY=xxxxx -RADIUS_SECRET=RadiusSecret123! -SESSION_SECRET=RandomSecure123!SecretHere -ADMIN_API_KEY=AdminApiKey123!Secure -``` - -2. **Implementasi di code:** -```javascript -// ✅ AMAN -const settings = { - genieacs_password: process.env.GENIEACS_PASSWORD || getSetting('genieacs_password'), - midtrans_server_key: process.env.MIDTRANS_SERVER_KEY, - xendit_api_key: process.env.XENDIT_API_KEY, - // ... dll -}; -``` - -3. **Update .gitignore:** -```bash -# Jangan commit file ini! -.env -.env.local -.env.*.local -settings.json # Alternatif: commit template saja -``` - -4. **Implementasi encryption untuk settings.json (jika diperlukan):** -```javascript -// Gunakan settingsEncryption.js yang sudah ada -const { encryptValue, decryptValue } = require('./config/settingsEncryption'); - -// Encrypt credentials: -const encrypted = encryptValue(credentialValue); - -// Decrypt saat digunakan: -const plainValue = decryptValue(encryptedValue); -``` - -**Timeline:** IMMEDIATE - ---- - -### 4. WEAK PASSWORD HASHING ⚠️ HIGH - -**Lokasi Lainnya:** -- [config/database.js](config/database.js#L627) - SHA256 untuk password -- [services/agentService.js](services/agentService.js#L27) - MD5 hash -- [routes/adminPortal.js](routes/adminPortal.js#L98) - MD5 hash - -**Masalah:** -```javascript -// ❌ TIDAK AMAN - SHA256 bukan untuk password hashing -const hash = crypto.createHash('sha256').update(input).digest('hex'); - -// ❌ TIDAK AMAN - MD5 sudah deprecated -const sign = crypto.createHash('md5').update(username + apiKey).digest('hex'); -``` - -- SHA256/MD5 = algoritma hashing cepat (bisa di-brute force) -- Tidak ada salt random -- Tidak ada rate limiting pada hashing -- Bisa di-crack dengan GPU dalam hitungan jam - -**Rekomendasi:** -```javascript -// ✅ AMAN - Gunakan bcrypt atau Argon2 -const bcrypt = require('bcrypt'); -const hash = await bcrypt.hash(password, 10); // 10 = cost factor -const isValid = await bcrypt.compare(plainPassword, hash); - -// Atau Argon2 (lebih kuat): -const argon2 = require('argon2'); -const hash = await argon2.hash(password); -const isValid = await argon2.verify(hash, password); -``` - -**Timeline:** HIGH - Dalam 1 minggu - ---- - -## 🔒 KEAMANAN SEDANG - TINGKATKAN - -### 5. SESSION MANAGEMENT ⚠️ MEDIUM - -**Lokasi:** [app-customer.js](app-customer.js#L79-L90) - -**Status Saat Ini:** ✅ Baik -```javascript -app.use(session({ - secret: getSetting('session_secret', 'default-secret'), - resave: false, - saveUninitialized: false, - cookie: { - secure: Boolean(cookieSecure), // ✅ HTTPS only (jika production) - httpOnly: true, // ✅ JavaScript tidak bisa akses - sameSite: 'lax', // ✅ CSRF protection - maxAge: 24 * 60 * 60 * 1000 // ✅ Timeout 24 jam - }, - name: 'customer.sid' -})); -``` - -**Rekomendasi Improvement:** - -1. **Gunakan session store eksternal:** -```javascript -// Jangan gunakan default memory store di production -const SessionStore = require('better-sqlite3-session-store')(session); -const store = new SessionStore({ - client: db, - expired: { - clear: true, - intervalMs: 15 * 60 * 1000 // Clear expired sessions tiap 15 menit - } -}); - -app.use(session({ - store: store, - // ... config lainnya -})); -``` - -2. **Regenerate session ID saat login:** -```javascript -// Saat login berhasil -req.session.regenerate((err) => { - if (err) return res.status(500).json({ error: 'Session error' }); - req.session.userId = user.id; - req.session.userRole = user.role; - // ... simpan data user lainnya - res.redirect('/dashboard'); -}); -``` - -3. **Validasi session pada setiap request:** -```javascript -app.use((req, res, next) => { - // Cek timeout session - const lastActivity = req.session.lastActivity || Date.now(); - const inactivityTimeout = 30 * 60 * 1000; // 30 menit - - if (Date.now() - lastActivity > inactivityTimeout) { - req.session.destroy(); - return res.status(401).json({ error: 'Session expired' }); - } - - req.session.lastActivity = Date.now(); - next(); -}); -``` - -**Timeline:** MEDIUM - 2 minggu - ---- - -### 6. CSRF PROTECTION ⚠️ MEDIUM - -**Status Saat Ini:** ⚠️ Terbatas -```javascript -// Hanya check Referer/Origin, tidak ada CSRF token explicit -if (origin) { - const originHost = new URL(origin).host; - if (originHost !== host) { - return res.status(403).json({ error: 'Forbidden - Invalid Origin' }); - } -} -``` - -**Masalah:** -- Referer bisa di-spoof dalam beberapa kasus -- Browser lama atau proxy bisa hilangkan Referer header -- Tidak ada explicit CSRF token di form - -**Rekomendasi:** - -1. **Implementasi CSRF token library:** -```javascript -const csrf = require('csurf'); -const csrfProtection = csrf({ cookie: false }); // Gunakan session, bukan cookie - -app.post('/admin/action', csrfProtection, (req, res) => { - // CSRF token sudah tervalidasi otomatis - // Proses request -}); -``` - -2. **Di EJS templates:** -```ejs -
-``` - -**Timeline:** MEDIUM - 2 minggu - ---- - -### 7. INPUT VALIDATION & SANITIZATION ⚠️ MEDIUM - -**Issue:** -Beberapa endpoint tidak melakukan validasi input yang ketat sebelum: -- Memasukkan ke database -- Menampilkan ke user (XSS risk) -- Digunakan dalam query - -**Contoh lokasi yang perlu improvement:** -- [routes/adminPortal.js](routes/adminPortal.js) - Bulk operations -- [routes/customerPortal.js](routes/customerPortal.js) - Customer data update -- File upload handling - -**Rekomendasi:** - -1. **Gunakan input validation library:** -```bash -npm install joi express-validator -``` - -2. **Implementasi validation:** -```javascript -const { body, validationResult } = require('express-validator'); - -router.post('/admin/customers/add', [ - body('name').trim().notEmpty().isLength({ max: 100 }), - body('phone').trim().isMobilePhone('id-ID'), - body('email').isEmail().normalizeEmail(), - body('address').trim().isLength({ max: 255 }), - body('package_id').isInt({ gt: 0 }), -], (req, res) => { - const errors = validationResult(req); - if (!errors.isEmpty()) { - return res.status(400).json({ errors: errors.array() }); - } - // Lanjutkan proses -}); -``` - -3. **Sanitize output di EJS:** -```ejs - -<%= customer.name %> - - -<%- cleanHtml(customer.name) %> - - -``` - -**Timeline:** MEDIUM - 2 minggu - ---- - -## ⚠️ KEAMANAN RENDAH - PERHATIAN - -### 8. FILE UPLOAD SECURITY ⚠️ LOW - -**Status Saat Ini:** ⚠️ Cukup -```javascript -// ✅ Ada validasi MIME type -const allowedTypes = /jpeg|jpg|png|gif|webp/; -const mimetype = allowedTypes.test(file.mimetype); - -// ✅ Ada file size limit (5MB) -limits: { fileSize: 5 * 1024 * 1024 } -``` - -**Rekomendasi Improvement:** - -1. **Validasi file lebih ketat:** -```javascript -const FileType = require('file-type'); - -// Validasi magic bytes (bukan hanya extension) -const fileType = await FileType.fromBuffer(file.buffer); -if (!['image/jpeg', 'image/png', 'image/webp'].includes(fileType?.mime)) { - throw new Error('Invalid file type'); -} -``` - -2. **Scan file dengan antivirus:** -```javascript -const ClamScan = require('clamscan'); -const clamscan = await new ClamScan().init({ - clamdscan: { host: 'localhost', port: 3310 } -}); - -const { isInfected } = await clamscan.scanFile(filePath); -if (isInfected) { - fs.unlinkSync(filePath); - throw new Error('Malicious file detected'); -} -``` - -**Timeline:** LOW - Dalam 1 bulan - ---- - -### 9. LOGGING & MONITORING ⚠️ LOW - -**Status Saat Ini:** ✅ Baik -- Winston logger terimplementasi dengan baik -- Terpisah antara error.log, combined.log, exceptions.log -- Console output di development - -**Rekomendasi:** - -1. **Audit trail untuk sensitive operations:** -```javascript -const auditTrailSvc = require('./services/auditTrailService'); - -// Log setiap action sensitive -auditTrailSvc.logAction({ - user_id: req.session.adminId, - action: 'invoice_generated', - resource_type: 'invoice', - resource_id: invoiceId, - changes: { status: 'generated' }, - ip_address: req.ip, - timestamp: new Date() -}); -``` - -2. **Centralized log aggregation:** -```javascript -// Contoh: Kirim logs ke ELK Stack atau Datadog -const winston = require('winston'); -const WinstonCloudWatch = require('winston-cloudwatch'); - -logger.add(new WinstonCloudWatch({ - logGroupName: 'billing-rtrwnet', - logStreamName: 'production', - awsRegion: 'ap-southeast-1' -})); -``` - -**Timeline:** LOW - Dalam 1 bulan - ---- - -## 🎯 KUALITAS KODE - -### 10. ERROR HANDLING ✅ BAIK - -**Status:** ✅ Baik -- Middleware error handler sudah terimplementasi -- Custom error classes (ValidationError, UnauthorizedError, etc) -- Proper HTTP status codes - -**Minor Improvements:** -```javascript -// Pastikan semua error di-catch dan di-log -router.get('/api/data', async (req, res, next) => { - try { - const data = await fetchData(); - res.json(data); - } catch (err) { - logger.error(`API Error: ${err.message}`, { - stack: err.stack, - endpoint: req.path, - method: req.method, - user_id: req.session?.userId - }); - next(err); // Pass ke error handler middleware - } -}); -``` - ---- - -### 11. DATABASE QUERIES ✅ BAIK - -**Status:** ✅ Baik -- Menggunakan parameterized queries (prepared statements) -- Tidak ada string concatenation pada SQL queries -- Foreign key constraints aktif - -**Contoh aman:** -```javascript -// ✅ AMAN - Parameterized query -const customer = db.prepare('SELECT * FROM customers WHERE id = ?').get(customerId); - -// ✅ AMAN - Multiple parameters -const result = db.prepare('SELECT * FROM customers WHERE router_id = ? AND status = ?').all(routerId, 'active'); -``` - -**Minor Issue - Dynamic SQL:** -```javascript -// ⚠️ PERLU REVIEW - Jika search input tidak di-sanitize -const base = `SELECT * FROM customers WHERE ...${userInput}...`; - -// ✅ SOLUSI - Gunakan parameterized dengan conditions array -const whereClauses = []; -const params = []; -if (search) { - whereClauses.push('name LIKE ?'); - params.push(`%${search}%`); -} -``` - ---- - -### 12. ASYNC/AWAIT HANDLING ⚠️ MEDIUM - -**Issue:** -Beberapa function masih menggunakan callback style yang bisa error-prone. - -**Contoh yang perlu improvement:** -```javascript -// ❌ CALLBACK STYLE -fs.readFile(path, (err, data) => { - if (err) handleError(err); - // process data -}); - -// ✅ ASYNC/AWAIT STYLE -try { - const data = await fs.promises.readFile(path); - // process data -} catch (err) { - handleError(err); -} -``` - -**Timeline:** LOW - Refactoring gradual - ---- - -## 🗄️ DATABASE INTEGRITY - -### 13. Database Schema ✅ SOLID - -**Status:** ✅ Sudah baik -- Foreign key constraints aktif -- Proper data types -- Indexes pada frequently queried fields -- WAL mode untuk reliability - -**Rekomendasi:** -```sql --- Pastikan ada indexes pada frequently queried columns -CREATE INDEX IF NOT EXISTS idx_customers_router_id ON customers(router_id); -CREATE INDEX IF NOT EXISTS idx_invoices_customer_id ON invoices(customer_id); -CREATE INDEX IF NOT EXISTS idx_invoices_status ON invoices(status); -CREATE INDEX IF NOT EXISTS idx_pppoe_users_username ON pppoe_users(username); -``` - ---- - -### 14. Backup & Recovery ⚠️ MEDIUM - -**Status Saat Ini:** ⚠️ Ada backup service tapi belum clear -- `backupService.js` sudah ada -- `auto_backup_enabled: false` di settings.json (disabled!) - -**Rekomendasi:** - -```javascript -// Enable automatic backup -const settings = { - "auto_backup_enabled": true, - "auto_backup_interval": "0 2 * * *", // Jam 2 pagi setiap hari - "auto_backup_retention_days": 30, - "backup_encryption_enabled": true -}; - -// Implementasi di cronService.js -const backup = require('./services/backupService'); -schedule.scheduleJob('0 2 * * *', async () => { - try { - const result = await backup.createBackup(); - logger.info(`Backup created: ${result.filename}`); - } catch (err) { - logger.error(`Backup failed: ${err.message}`); - } -}); -``` - -**Timeline:** MEDIUM - 2 minggu - ---- - -## 📋 ACTION ITEMS & TIMELINE - -### IMMEDIATE (Hari ini - 48 jam) 🔴 -- [ ] Implementasi bcrypt untuk password hashing -- [ ] Hapus default credentials dari settings.json -- [ ] Setup .env file untuk credentials -- [ ] Update .gitignore untuk .env dan settings.json -- [ ] Create setup wizard untuk first-time admin password - -### HIGH PRIORITY (Minggu 1) 🟠 -- [ ] Migrate semua password di database dengan bcrypt -- [ ] Implementasi CSRF token protection -- [ ] Setup session store eksternal (SQLite session) -- [ ] Enable auto backup dalam cron jobs -- [ ] Update API key management - -### MEDIUM PRIORITY (Minggu 2-3) 🟡 -- [ ] Input validation dengan joi/express-validator -- [ ] Enhanced file upload scanning -- [ ] Session regeneration saat login -- [ ] Centralized logging setup -- [ ] Database query audit - -### LOW PRIORITY (Bulan 1) 🟢 -- [ ] Antivirus integration untuk file upload -- [ ] Log aggregation (ELK/Datadog) -- [ ] Async/await refactoring -- [ ] Performance optimization -- [ ] Documentation update - ---- - -## 📊 SECURITY CHECKLIST - PRODUCTION DEPLOYMENT - -Sebelum go live ke production, pastikan: - -- [ ] **Authentication** - - [ ] Password menggunakan bcrypt (cost ≥ 10) - - [ ] Admin password bukan default - - [ ] Session timeout implemented - - [ ] Session regeneration saat login - -- [ ] **Authorization** - - [ ] Role-based access control diterapkan - - [ ] API endpoints check permission - - [ ] Admin endpoints protected - -- [ ] **Data Protection** - - [ ] Sensitive data encrypted at rest - - [ ] HTTPS enforced (secure cookie flag) - - [ ] CSRF protection aktif - - [ ] XSS protection aktif - -- [ ] **Configuration** - - [ ] Semua credentials di .env - - [ ] .env tidak di-commit - - [ ] settings.json di-review untuk sensitive data - - [ ] API keys di-rotate - -- [ ] **Logging & Monitoring** - - [ ] Audit trail untuk sensitive operations - - [ ] Error logging configured - - [ ] Monitoring alerts setup - -- [ ] **Backup & Recovery** - - [ ] Automated backup enabled - - [ ] Backup encryption enabled - - [ ] Recovery procedure tested - - [ ] Backup storage off-site - -- [ ] **Network** - - [ ] Firewall configured - - [ ] Only needed ports open - - [ ] Rate limiting implemented - - [ ] DDoS protection (jika applicable) - -- [ ] **Testing** - - [ ] Security testing completed - - [ ] Penetration testing done (jika budget ada) - - [ ] Load testing completed - - [ ] Recovery testing done - ---- - -## 📞 REKOMENDASI LANJUTAN - -### 1. Security Code Review -Jadwalkan code review berkala (monthly) oleh developer berpengalaman untuk: -- Review pull requests sebelum merge -- Check untuk security vulnerabilities -- Update dependencies - -### 2. Dependency Management -```bash -# Regular security audit -npm audit - -# Update dependencies (carefully) -npm update - -# Check for outdated packages -npm outdated -``` - -### 3. Environment Management -```bash -# Development -NODE_ENV=development npm start - -# Staging -NODE_ENV=staging npm start - -# Production -NODE_ENV=production npm start -``` - -### 4. Rate Limiting -```javascript -const rateLimit = require('express-rate-limit'); - -const loginLimiter = rateLimit({ - windowMs: 15 * 60 * 1000, // 15 menit - max: 5, // 5 attempts - message: 'Terlalu banyak login attempts, coba lagi nanti' -}); - -router.post('/login', loginLimiter, authController.login); -``` - -### 5. Security Headers -```javascript -const helmet = require('helmet'); -app.use(helmet()); // Adds various HTTP headers for security -``` - ---- - -## 📈 PERFORMANCE OPTIMIZATION - -### Database Performance -```javascript -// Add connection pooling -const DatabasePool = require('pg-pool'); - -// Add query optimization -EXPLAIN ANALYZE SELECT ...; // Check query plans -``` - -### Caching Strategy -```javascript -// Implement Redis caching untuk frequently accessed data -const redis = require('redis'); -const client = redis.createClient(); - -// Cache customer data -const getCachedCustomer = async (id) => { - const cached = await client.get(`customer:${id}`); - if (cached) return JSON.parse(cached); - - const customer = db.prepare('SELECT * FROM customers WHERE id = ?').get(id); - await client.setex(`customer:${id}`, 3600, JSON.stringify(customer)); - return customer; -}; -``` - -### API Response Compression -```javascript -const compression = require('compression'); -app.use(compression()); // Compress responses -``` - ---- - -## 🎓 DEVELOPER TRAINING - -Recommended training topics untuk team: -1. OWASP Top 10 vulnerabilities -2. Secure coding practices -3. Dependency vulnerability scanning -4. Database security -5. API security -6. Authentication & Authorization best practices - ---- - -## 📝 KESIMPULAN - -Aplikasi RTRWNET Billing System memiliki **foundation yang kuat** dengan: -- ✅ Arsitektur yang well-structured -- ✅ Comprehensive feature set -- ✅ Good error handling & logging -- ✅ Proper database design - -Namun ada **beberapa kerentanan keamanan KRITIS** yang harus diperbaiki: -- 🔴 Password plaintext storage -- 🔴 Default credentials -- 🔴 Unencrypted credentials in config - -Dengan mengikuti rekomendasi di audit ini, aplikasi dapat mencapai **production-ready security level** dalam waktu 2-3 minggu. - ---- - -**Status Audit: COMPLETE** -**Recommendation: DO NOT DEPLOY TO PRODUCTION** sampai critical issues di-fix. -**Next Review:** 30 hari setelah fixes di-implementasi diff --git a/docs/AUDIT_SUMMARY.md b/docs/AUDIT_SUMMARY.md deleted file mode 100644 index c623e40..0000000 --- a/docs/AUDIT_SUMMARY.md +++ /dev/null @@ -1,458 +0,0 @@ -# AUDIT SUMMARY - Aplikasi Billing B481 - -**Tanggal Audit:** Juni 2026 -**Status:** ✅ COMPLETE & DOCUMENTED -**Aplikasi Status:** 🟢 PRODUCTION READY - ---- - -## 📌 Executive Summary - -Telah dilakukan audit **lengkap & teliti** terhadap aplikasi Billing RTRWnet (B481) yang sedang berjalan. Aplikasi ini merupakan sistem **comprehensive ISP billing & network management** dengan 15+ portal dan fitur-fitur advanced. - -**Hasil:** Aplikasi dalam kondisi **BAIK & SIAP PRODUCTION** dengan beberapa rekomendasi improvement untuk keamanan & performance. - ---- - -## 📦 Dokumentasi yang Telah Dibuat - -### 1. **AUDIT_LENGKAP.md** (Komprehensif) - - Informasi umum aplikasi - - Arsitektur sistem lengkap - - Database schema overview - - Endpoints & routes (semua portal) - - Fitur-fitur utama (15+ modul) - - Keamanan & otentikasi - - Frontend & UI - - Configurasi sistem - - Production checklist - - Performance optimization - - 📊 **Size:** ~50 KB (detailed reference) - -### 2. **QUICK_REFERENCE.md** (Panduan Cepat) - - Quick start commands - - Common tasks (5 menit selesai) - - Security settings (MUST DO) - - Important endpoints - - Database commands - - Cron jobs schedule - - Troubleshooting guide - - Multi-language info - - Pre-launch checklist - - 📊 **Size:** ~10 KB (quick lookup) - -### 3. **DATABASE_SCHEMA.md** (Struktur Database) - - Tabel-tabel lengkap dengan struktur - - Detailed field descriptions - - Foreign key relationships - - Query examples - - Optimization tips - - Backup & recovery procedures - - 📊 **Size:** ~30 KB (database reference) - -### 4. **BACKUP_CHECKLIST.md** (Backup & Recovery) - - Pre-audit backup procedures - - Step-by-step backup guide - - Restore procedures (multiple scenarios) - - Automated backup setup (cron) - - Disaster recovery plan - - Backup verification checklist - - 📊 **Size:** ~20 KB (operational guide) - -### 5. **AUDIT_SUMMARY.md** (File ini) - - Executive overview - - Quick links - - Key statistics - - Next steps - ---- - -## 🎯 Key Findings - -### ✅ Strengths -1. **Comprehensive Feature Set** - 15+ portal dengan integrasi lengkap -2. **Well-Organized Architecture** - Services, routes, middleware pattern -3. **Multi-Integration** - MikroTik, GenieACS, OLT, Payment Gateways -4. **Automation Ready** - Cron jobs untuk billing, isolir, reminders -5. **Lightweight** - SQLite, no external database required -6. **Scalable Design** - Multi-router, multi-ACS, multi-gateway support -7. **Built-in ACS** - TR-069 server tanpa GenieACS eksternal - -### ⚠️ Areas for Improvement -1. **Password Security** - Need bcrypt implementation (currently plaintext risk) -2. **API Security** - Implement JWT or token-based authentication -3. **Rate Limiting** - Prevent brute force attacks -4. **Performance** - Add Redis session store, implement caching -5. **Testing** - Add comprehensive test suite -6. **Documentation** - API documentation (Swagger/OpenAPI) - ---- - -## 📊 Application Statistics - -### Codebase Size -``` -Templates (EJS): 78 files -Services: 27 modules -Routes: 12 modules -Configuration: 10 files -Views/Partials: ~100+ components -``` - -### Features Count -| Category | Count | -|----------|-------| -| Portals | 6 (Customer, Admin, Tech, Agent, Collector, Finance) | -| API Endpoints | 100+ | -| Database Tables | 30+ | -| Cron Jobs | 6 | -| Payment Gateways | 4 | -| External Integrations | 6+ | - -### Database Typical Size -``` -Small deployment: 10-50 MB -Medium deployment: 50-150 MB -Large deployment: 200-500 MB -(Depends on data retention & transaction volume) -``` - ---- - -## 🚀 Quick Start - -### 1. Review Documentation -``` -Read in this order: -1. QUICK_REFERENCE.md (5 min) -2. AUDIT_LENGKAP.md (30 min) -3. DATABASE_SCHEMA.md (20 min) -4. BACKUP_CHECKLIST.md (10 min) -``` - -### 2. Initial Backup -```bash -bash scripts/fix-database.sh # Optional: fix any DB issues -node scripts/verify-database.js # Verify DB integrity -npm start # Start application -``` - -### 3. Configuration -```bash -# Edit settings.json: -# - Change admin password -# - Configure MikroTik connection -# - Setup payment gateway -# - Configure WhatsApp (optional) -``` - -### 4. Verify All Portals -``` -http://localhost:3001/admin/login ← Admin panel -http://localhost:3001/customer/login ← Customer self-service -http://localhost:3001/tech/login ← Technician portal -http://localhost:3001/agent/login ← Agent sales -http://localhost:3001/health ← Health check -``` - ---- - -## 🔒 Security Checklist (CRITICAL) - -**Before Production Deployment:** - -- [ ] Change `session_secret` → Random 32+ characters -- [ ] Change `admin_password` → Strong password -- [ ] Change `admin_api_key` → Random string -- [ ] Enable HTTPS (via reverse proxy: nginx) -- [ ] Restrict admin panel access (/admin via IP whitelist) -- [ ] Setup firewall rules -- [ ] Implement bcrypt for password hashing -- [ ] Setup audit logging -- [ ] Test backup & restore procedure -- [ ] Verify all external connections (MikroTik, GenieACS, OLT) - ---- - -## 📋 Operational Runbook - -### Daily Tasks -``` -✓ Monitor CPU/RAM usage -✓ Check /health endpoint -✓ Review error logs -✓ Monitor WhatsApp connection -``` - -### Weekly Tasks -``` -✓ Verify backups completed -✓ Check database size -✓ Review payment transactions -✓ Test restore procedures (weekly) -``` - -### Monthly Tasks -``` -✓ Cleanup old audit trails -✓ Cleanup old traffic samples -✓ Review performance metrics -✓ Update SSL certificates (if HTTPS) -``` - -### Ad-Hoc Tasks -``` -✓ Billing generation (manual) -✓ Customer isolir (manual) -✓ Settings updates -✓ Emergency procedures -``` - ---- - -## 🔧 Maintenance Procedures - -### Adding New Customer -``` -Admin Panel → Customers → Add New -- Enter basic info (name, phone, address) -- Assign package & MikroTik router -- Set install date -- System auto-generates invoice on billing cycle -``` - -### Updating Payment Gateway -``` -Admin Panel → Settings → Payment Gateway -- Select gateway (Midtrans, Tripay, Xendit, Duitku) -- Enter API credentials -- Test connection -- Save & restart if needed -``` - -### Generating Vouchers -``` -Admin Panel → MikroTik → Vouchers -- Create batch (name, quantity, nominal) -- Generate codes -- Print codes -- Distribute to agents -``` - -### Monitoring System -``` -Admin Panel → Monitoring -- Check CPU/RAM usage -- Check disk space -- Check database size -- Check connectivity status -``` - ---- - -## 🎓 Training Resources - -### For Admin -1. QUICK_REFERENCE.md → Common admin tasks -2. AUDIT_LENGKAP.md section 5.1-5.5 → Billing, MikroTik, GenieACS -3. Admin portal built-in help - -### For Technician -1. QUICK_REFERENCE.md → Tech portal features -2. AUDIT_LENGKAP.md section 4.3 → Tech routes -3. Ticket management system - -### For Agent/Cashier -1. Portal home page → Help section -2. QUICK_REFERENCE.md → Agent features -3. Dashboard tutorial - ---- - -## 📞 Support & Escalation - -### Level 1: Self-Service -- Check QUICK_REFERENCE.md -- Check built-in help in portals -- Review error messages - -### Level 2: Admin Support -- Check AUDIT_LENGKAP.md troubleshooting -- Review application logs: `pm2 logs` -- Check database: `node scripts/verify-database.js` - -### Level 3: Developer Support -- Check GitHub: https://github.com/alijayanet/billing-rtrw -- Contact: Ali Jaya Net (081947215703) -- Email: alijayanet@gmail.com - ---- - -## 📁 Document File Locations - -All documentation saved in application root: - -``` -billing-B481/ -├── AUDIT_LENGKAP.md ← Comprehensive audit (50 KB) -├── QUICK_REFERENCE.md ← Quick start guide (10 KB) -├── DATABASE_SCHEMA.md ← Database reference (30 KB) -├── BACKUP_CHECKLIST.md ← Backup procedures (20 KB) -└── AUDIT_SUMMARY.md ← This file (15 KB) - -Total documentation: ~125 KB -``` - -**Backup these files also!** Add to your backup script: - -```bash -tar -czf audit-docs-backup.tar.gz \ - AUDIT_LENGKAP.md \ - QUICK_REFERENCE.md \ - DATABASE_SCHEMA.md \ - BACKUP_CHECKLIST.md \ - AUDIT_SUMMARY.md -``` - ---- - -## ✨ Next Steps - -### Immediate (This Week) -1. ✅ Review all documentation -2. ✅ Create full backup (database + files + code) -3. ✅ Store backup in safe location -4. ✅ Test restore procedure -5. ✅ Verify all portals functional - -### Short-term (This Month) -1. ⏳ Setup automated daily backup -2. ⏳ Implement monitoring & alerting -3. ⏳ Setup log rotation -4. ⏳ Document any customizations -5. ⏳ Create runbook in internal wiki - -### Long-term (This Quarter) -1. ⏳ Add comprehensive test suite -2. ⏳ Implement bcrypt for passwords -3. ⏳ Setup Redis session store -4. ⏳ Create API documentation (Swagger) -5. ⏳ Performance optimization & tuning - ---- - -## 🎖️ Audit Completion Status - -| Task | Status | Notes | -|------|--------|-------| -| Application Review | ✅ Complete | All features examined | -| Code Structure | ✅ Complete | Well-organized & maintainable | -| Database Schema | ✅ Complete | Proper design & relationships | -| Security Analysis | ✅ Complete | Identified areas for improvement | -| Documentation | ✅ Complete | 125 KB comprehensive docs created | -| Backup Procedures | ✅ Complete | Ready to implement | -| Testing Guide | ✅ Complete | Quick reference provided | -| Troubleshooting | ✅ Complete | Common issues documented | - -**Overall Status: 🟢 PRODUCTION READY** - ---- - -## 📝 Document Versions - -| Document | Version | Date | Status | -|----------|---------|------|--------| -| AUDIT_LENGKAP.md | 1.0 | 2026-06-19 | ✅ Final | -| QUICK_REFERENCE.md | 1.0 | 2026-06-19 | ✅ Final | -| DATABASE_SCHEMA.md | 1.0 | 2026-06-19 | ✅ Final | -| BACKUP_CHECKLIST.md | 1.0 | 2026-06-19 | ✅ Final | -| AUDIT_SUMMARY.md | 1.0 | 2026-06-19 | ✅ Final | - ---- - -## 🔍 Audit Methodology - -This audit was conducted using: -1. **Code Review** - All source files examined -2. **Architecture Analysis** - System design & patterns reviewed -3. **Security Assessment** - Authentication, encryption, data protection -4. **Database Analysis** - Schema, queries, relationships -5. **Feature Mapping** - All portals & endpoints documented -6. **Documentation** - Comprehensive guides created for operations - ---- - -## ✅ Final Checklist - -Before considering audit complete: - -- ✅ Application analyzed thoroughly -- ✅ All features documented -- ✅ Database schema documented -- ✅ Backup procedures defined -- ✅ Security recommendations provided -- ✅ Troubleshooting guide created -- ✅ Quick reference created -- ✅ Production readiness confirmed - ---- - -## 🎯 Success Criteria - -**Application meets production standards when:** - -- ✅ All documentation read & understood -- ✅ Full backup created & tested -- ✅ Security settings updated (passwords, secrets) -- ✅ All portals verified working -- ✅ Monitoring setup -- ✅ Escalation procedures defined -- ✅ Runbook available to operations team - ---- - -## 📞 Questions or Issues? - -**For questions about this audit:** -- Review relevant documentation section -- Check troubleshooting guides -- Contact application owner: Ali Jaya Net (081947215703) - -**For operational issues:** -- Check QUICK_REFERENCE.md -- Review application logs -- Use health check: `GET /health` - ---- - -## 🏁 Conclusion - -Aplikasi Billing B481 (RTRWnet) telah selesai di-audit secara teliti. Sistem berada dalam kondisi **BAIK & SIAP UNTUK PRODUKSI** dengan dokumentasi lengkap untuk operasional. - -**Dokumentasi yang telah dibuat mencakup:** -- Comprehensive feature audit (50 KB) -- Quick reference guide (10 KB) -- Database schema documentation (30 KB) -- Backup & recovery procedures (20 KB) -- This summary (15 KB) - -**Total: 125 KB documentation untuk operasional jangka panjang.** - -Semua file dokumentasi tersimpan di root aplikasi dan siap untuk di-backup. - ---- - -**Audit Completion Date:** June 19, 2026 -**Audit Version:** 1.0 - Final -**Status:** ✅ APPROVED FOR PRODUCTION - ---- - -**Jangan lupa untuk:** -1. ✅ Backup semua dokumentasi ini -2. ✅ Share dengan tim operasional -3. ✅ Update dokumentasi saat ada perubahan -4. ✅ Review & test ulang secara berkala - -**Terima kasih telah menggunakan dokumentasi audit lengkap ini! 🎉** - diff --git a/docs/DATABASE_SCHEMA.md b/docs/DATABASE_SCHEMA.md index 3bf14aa..80d1b47 100644 --- a/docs/DATABASE_SCHEMA.md +++ b/docs/DATABASE_SCHEMA.md @@ -63,7 +63,6 @@ - `tickets` - Tiket support pelanggan ### 10. Payment & Digital -- `digiflazz_transactions` - Transaksi pulsa/data Digiflazz - `vomit_log` - Log webhook pembayaran (generic) --- @@ -439,23 +438,6 @@ CREATE TABLE vouchers ( --- -### digiflazz_transactions -```sql -CREATE TABLE digiflazz_transactions ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - agent_id INTEGER NOT NULL REFERENCES agents(id), - ref_id TEXT NOT NULL UNIQUE, -- Digiflazz reference ID - phone_or_code TEXT NOT NULL, -- Tujuan nomor / kode - product_sku TEXT NOT NULL, - amount INTEGER NOT NULL, - status TEXT DEFAULT 'pending', -- pending, success, failed - response_data TEXT, -- JSON response - created_at DATETIME DEFAULT (NOW_LOCAL()) -); -``` - ---- - ## Query Examples ### Generate Invoice (Monthly) diff --git a/docs/DOKUMENTASI_INDEX.md b/docs/DOKUMENTASI_INDEX.md deleted file mode 100644 index a6e0ae2..0000000 --- a/docs/DOKUMENTASI_INDEX.md +++ /dev/null @@ -1,494 +0,0 @@ -# 📚 INDEX DOKUMENTASI AUDIT - Aplikasi Billing B481 - -**Tanggal Audit:** Juni 2026 -**Total Dokumentasi:** 6 file (91 KB) -**Status:** ✅ LENGKAP & SIAP PAKAI - ---- - -## 📖 Panduan Membaca Dokumentasi - -### Untuk Pengguna Pertama (5-15 menit) -``` -START HERE: -1. AUDIT_SUMMARY.md ← Ringkasan eksekutif (5 min) -2. QUICK_REFERENCE.md ← Perintah dasar (10 min) -3. README.md ← (Original README aplikasi) -``` - -### Untuk Admin/Operator (30-60 menit) -``` -RECOMMENDED PATH: -1. QUICK_REFERENCE.md ← Common tasks & troubleshooting -2. AUDIT_LENGKAP.md ← Section 4 (Endpoints & Routes) -3. BACKUP_CHECKLIST.md ← Backup & recovery procedures -4. DATABASE_SCHEMA.md ← Untuk query tertentu -``` - -### Untuk Developer/Maintenance (1-2 jam) -``` -COMPREHENSIVE PATH: -1. AUDIT_LENGKAP.md ← Full architecture & features -2. DATABASE_SCHEMA.md ← Complete schema with examples -3. QUICK_REFERENCE.md ← Common tasks reference -4. BACKUP_CHECKLIST.md ← Operational procedures -``` - ---- - -## 📄 File Documentation Details - -### 1. AUDIT_LENGKAP.md (45.57 KB) -**Purpose:** Comprehensive audit report dengan semua detail - -**Sections:** -- 📍 Section 1: Informasi Umum Aplikasi -- 📍 Section 2: Arsitektur Sistem (directory structure, flow) -- 📍 Section 3: Database & Schema (overview) -- 📍 Section 4: Endpoints & Routes (SEMUA API endpoints) - - 4.1: Portal Pelanggan (/customer) - - 4.2: Portal Admin (/admin) - - 4.3: Portal Teknisi (/tech) - - 4.4: Portal Agen (/agent) - - 4.5: Portal Kolektor (/collector) - - 4.6: Portal Finance (/finance) - - 4.7: Public Routes - - 4.8: Settings & Configuration API - - 4.9: Voucher Payment API -- 📍 Section 5: Fitur-Fitur Utama (15+ modul) - - 5.1 Billing & Invoicing - - 5.2 MikroTik Integration - - 5.3 GenieACS & TR-069 - - 5.4 OLT & ONU Management - - 5.5 GIS Mapping - - 5.6 WhatsApp Automation - - 5.7 Payment Gateways - - 5.8 Agen & Sales - - 5.9-5.15 Additional features -- 📍 Section 6: Keamanan & Otentikasi -- 📍 Section 7: Frontend & UI -- 📍 Section 8: Internationalization (i18n) -- 📍 Section 9: Configuration & Settings -- 📍 Section 10: Dependencies & Libraries -- 📍 Section 11: Operational Requirements -- 📍 Section 12: Monitoring & Troubleshooting -- 📍 Section 13: Production Checklist -- 📍 Section 14: Performance Optimization -- 📍 Section 15: File Size & Statistics -- 📍 Section 16: Documentation & Resources -- 📍 Section 17: Advanced Features & Integration -- 📍 Section 18: Conclusion & Recommendations - -**When to use:** Referensi lengkap untuk semua aspek aplikasi - -**Example queries:** -- "Apa saja endpoint admin?" → See section 4.2 -- "Bagaimana cara kerja billing?" → See section 5.1 -- "Apa saja database tables?" → See section 3.2 -- "Bagaimana setup MikroTik?" → See section 5.2 - ---- - -### 2. QUICK_REFERENCE.md (6.67 KB) -**Purpose:** Quick lookup guide untuk task-task umum - -**Sections:** -- Quick Start (npm commands) -- Portal access URLs -- Key Files location -- Common Tasks (5 tasks) - - Change Port - - Change Company Name - - Enable WhatsApp - - Setup MikroTik - - Setup GenieACS -- Security Settings (MUST DO) -- Important Endpoints -- Database Commands -- Cron Jobs Schedule -- Troubleshooting (7 common issues) -- Multi-Language -- Useful Scripts -- Pre-Launch Checklist - -**When to use:** Sehari-hari untuk quick answers - -**Example queries:** -- "Port berapa aplikasi?" → See "Quick Start" -- "MikroTik tidak connect, apa solusinya?" → See "Troubleshooting" -- "Bagaimana aktifkan WhatsApp?" → See "Common Tasks" -- "Kapan billing dijalankan?" → See "Cron Jobs" - ---- - -### 3. DATABASE_SCHEMA.md (15.75 KB) -**Purpose:** Complete database schema documentation - -**Sections:** -- Schema Overview -- Detailed Table Structures (20+ tables) -- Table relationships & foreign keys -- Query Examples (4 examples) -- Optimization Tips -- Backup & Recovery procedures -- Index recommendations - -**Tables Documented:** -- settings, packages, customers, routers, olts, odps -- invoices, payments, payment_approvals -- pppoe_users, pppoe_profiles, pppoe_traffic_samples, pppoe_sessions -- hotspot_users, hotspot_profiles, hotspot_sessions -- voucher_batches, vouchers -- acsdevices, acs_sessions, acs_device_params -- onu_mapping, onu_provision, olu_ports -- audit_trail, expenses, cash_in -- technicians, cashiers, agents, collectors -- inventory_items, attendance, tickets -- digiflazz_transactions, vomit_log - -**When to use:** Ketika perlu memahami struktur data atau membuat query - -**Example queries:** -- "Bagaimana struktur tabel customers?" → See "customers" section -- "Query apa untuk cek overdue invoice?" → See "Query Examples" -- "Tabel apa untuk tracking PPPoE usage?" → See "pppoe_traffic_samples" - ---- - -### 4. BACKUP_CHECKLIST.md (10.58 KB) -**Purpose:** Comprehensive backup & disaster recovery guide - -**Sections:** -- Pre-Audit Backup (CRITICAL) - - Step 1-5: Database, Settings, Aplikasi, Uploads -- Backup Checklist (verification checklist) -- Restore Procedures (5 scenarios) - - Restore Database Only - - Restore Settings - - Full Application Restore - - Restore Upload Files -- Backup Inventory (tracking template) -- Secure Backup Storage (4 options) - - Local Storage (USB) - - Network Drive (NAS/SMB) - - Cloud Storage (rclone, S3) - - Encrypted Backup (GPG) -- Automated Backup (Cron Job setup) -- Disaster Recovery Plan (5 scenarios) - - Database Corrupted - - Aplikasi Crashed - - Akses Denied - - HDD Full - - Settings Misconfiguration -- Best Practices (DO & DON'T) -- Recovery Time Objective (RTO/RPO) -- Backup Verification Checklist - -**When to use:** Sebelum & sesudah deployment, disaster recovery - -**Example queries:** -- "Gimana backup database?" → See "Backup Procedures" Step 1 -- "Gimana restore jika database corrupt?" → See "Disaster Recovery" Scenario 1 -- "Setup automated backup gimana?" → See "Automated Backup (Cron Job)" - ---- - -### 5. AUDIT_SUMMARY.md (12.31 KB) -**Purpose:** Executive summary & quick links - -**Sections:** -- Executive Summary -- Dokumentasi yang Dibuat (daftar lengkap) -- Key Findings (Strengths & Areas for Improvement) -- Application Statistics -- Quick Start (4 steps) -- Security Checklist (CRITICAL) -- Operational Runbook - - Daily, Weekly, Monthly, Ad-Hoc tasks -- Maintenance Procedures (5 procedures) -- Training Resources -- Support & Escalation (3 levels) -- Document File Locations -- Next Steps (Immediate, Short-term, Long-term) -- Audit Completion Status -- Document Versions -- Audit Methodology -- Final Checklist -- Success Criteria - -**When to use:** Overview & planning - -**Example queries:** -- "Aplikasi ready untuk production?" → See "Audit Completion Status" -- "Apa saja dokumentasi yang dibuat?" → See "Dokumentasi yang Telah Dibuat" -- "Langkah pertama gimana?" → See "Quick Start" - ---- - -### 6. DOKUMENTASI_INDEX.md (This file) -**Purpose:** Navigation guide untuk semua dokumentasi - -**Sections:** -- Panduan Membaca Dokumentasi (paths untuk berbagai user) -- File Documentation Details (overview setiap file) -- Quick Links & Search Tips -- Related Documentation -- How to Update Documentation -- Troubleshooting Documentation Issues - ---- - -## 🔗 Quick Links - -### By Topic - -#### Billing & Invoicing -- AUDIT_LENGKAP.md → Section 5.1 -- DATABASE_SCHEMA.md → invoices, payments tables - -#### MikroTik Management -- QUICK_REFERENCE.md → "Setup MikroTik" -- AUDIT_LENGKAP.md → Section 5.2 -- DATABASE_SCHEMA.md → routers, pppoe_users tables - -#### Payment Gateways -- AUDIT_LENGKAP.md → Section 5.7 -- QUICK_REFERENCE.md → "Setup Payment Gateway" - -#### Database -- DATABASE_SCHEMA.md → All sections -- BACKUP_CHECKLIST.md → Backup procedures - -#### Security -- QUICK_REFERENCE.md → "Security Settings" -- AUDIT_SUMMARY.md → "Security Checklist" -- AUDIT_LENGKAP.md → Section 6 - -#### Troubleshooting -- QUICK_REFERENCE.md → "Troubleshooting" -- AUDIT_LENGKAP.md → Section 12 - ---- - -## 🔍 How to Search Documentation - -### Using Text Editor Find (Ctrl+F) - -**Search by feature:** -``` -"billing" → Find billing-related content -"whatsapp" → Find WhatsApp integration -"endpoint" → Find API endpoints -"table" → Find database tables -"cron" → Find scheduled tasks -"error" → Find error handling -``` - -**Search by section:** -``` -"## " (two hashes) → Find main sections -"### " (three hashes) → Find subsections -"- [ ]" → Find checklist items -"| " → Find tables -``` - -### Using grep (Linux/Mac) -```bash -# Find all mentions of "WhatsApp" -grep -n "whatsapp" *.md - -# Find all table structures -grep -n "CREATE TABLE" DATABASE_SCHEMA.md - -# Find all endpoints -grep -n "GET\|POST\|PUT\|DELETE" AUDIT_LENGKAP.md - -# Find all endpoints for /admin -grep -n "/admin" AUDIT_LENGKAP.md -``` - ---- - -## 📋 Documentation Cross-References - -### Related Files to Read Together - -**For Admin Portal:** -- AUDIT_LENGKAP.md section 4.2 -- QUICK_REFERENCE.md "Common Tasks" -- AUDIT_SUMMARY.md "Operational Runbook" - -**For Customer Portal:** -- AUDIT_LENGKAP.md section 4.1 -- AUDIT_LENGKAP.md section 5.1 (Billing) - -**For Database Operations:** -- DATABASE_SCHEMA.md (all sections) -- BACKUP_CHECKLIST.md (all procedures) -- QUICK_REFERENCE.md "Database Commands" - -**For Security:** -- QUICK_REFERENCE.md "Security Settings" -- AUDIT_SUMMARY.md "Security Checklist" -- AUDIT_LENGKAP.md section 6 - -**For Troubleshooting:** -- QUICK_REFERENCE.md "Troubleshooting" -- AUDIT_LENGKAP.md section 12 -- AUDIT_LENGKAP.md section 13 - ---- - -## 🔄 How to Update Documentation - -When application changes, update relevant docs: - -1. **New Feature Added:** - - Update AUDIT_LENGKAP.md section 5 (Fitur-Fitur) - - Update QUICK_REFERENCE.md if it's a common task - -2. **New Endpoint Added:** - - Update AUDIT_LENGKAP.md section 4 (Routes) - - Add to QUICK_REFERENCE.md "Important Endpoints" - -3. **Database Schema Changed:** - - Update DATABASE_SCHEMA.md with new tables - - Add query examples if applicable - -4. **Backup Procedure Changed:** - - Update BACKUP_CHECKLIST.md - - Update QUICK_REFERENCE.md "Database Commands" - -5. **Security Changes:** - - Update AUDIT_SUMMARY.md "Security Checklist" - - Update AUDIT_LENGKAP.md section 6 - -**Version Control:** -```markdown -Example header update: - -### 6. AUDIT_SUMMARY.md (12.31 KB) → Last updated: 2026-06-20 -``` - ---- - -## ❓ FAQ - Documentation - -**Q: File mana yang harus dibaca duluan?** -A: Mulai dengan AUDIT_SUMMARY.md (5 min), lalu QUICK_REFERENCE.md (10 min) - -**Q: Gimana cari informasi tentang endpoint tertentu?** -A: Cari di AUDIT_LENGKAP.md section 4, atau grep dengan `/endpoint-name` - -**Q: Database tables untuk X ada di file mana?** -A: DATABASE_SCHEMA.md, section "Detailed Table Structures" - -**Q: Backup gimana?** -A: Baca BACKUP_CHECKLIST.md dari atas sampai bawah - -**Q: Troubleshooting error X gimana?** -A: Lihat QUICK_REFERENCE.md "Troubleshooting", atau AUDIT_LENGKAP.md section 12 - -**Q: Dokumentasi sudah lengkap?** -A: Ya, 6 file (91 KB) sudah cover semua aspek aplikasi - -**Q: Dokumentasi perlu diupdate?** -A: Ya, ikuti "How to Update Documentation" section di atas - ---- - -## 📊 Documentation Statistics - -| File | Size | Sections | Tables | Sections Covered | -|------|------|----------|--------|------------------| -| AUDIT_LENGKAP.md | 45 KB | 18 | 5+ | Features, API, Security | -| QUICK_REFERENCE.md | 7 KB | 10 | 3+ | Common tasks, Quick links | -| DATABASE_SCHEMA.md | 16 KB | 6 | 20+ | Database, Tables, Queries | -| BACKUP_CHECKLIST.md | 11 KB | 8 | 2+ | Backup, Recovery, RTO/RPO | -| AUDIT_SUMMARY.md | 12 KB | 15 | 2+ | Executive, Roadmap | -| DOKUMENTASI_INDEX.md | 9 KB | 6 | - | Navigation, Index | - -**Total:** 6 files, ~100 KB, 18+ sections, 30+ tables documented - ---- - -## ✅ Verification Checklist - -Pastikan dokumentasi lengkap: - -- [x] AUDIT_LENGKAP.md → 18 sections ✓ -- [x] QUICK_REFERENCE.md → 10 sections ✓ -- [x] DATABASE_SCHEMA.md → 20+ tables ✓ -- [x] BACKUP_CHECKLIST.md → 8 sections ✓ -- [x] AUDIT_SUMMARY.md → 15 sections ✓ -- [x] DOKUMENTASI_INDEX.md → Navigation ✓ - -**All files created:** ✅ COMPLETE - ---- - -## 🎯 Documentation Roadmap - -### Current Status (2026-06-19) -- ✅ 6 documentation files created -- ✅ ~100 KB comprehensive documentation -- ✅ All major features documented -- ✅ Backup procedures documented -- ✅ Troubleshooting guide created - -### Future Enhancements -- ⏳ API Swagger/OpenAPI documentation -- ⏳ Video tutorials for common tasks -- ⏳ Deployment guide (Docker, K8s) -- ⏳ Performance tuning guide -- ⏳ Custom integration examples - ---- - -## 🔐 Documentation Backup - -**Backup documentation juga!** - -```bash -# Create backup -tar -czf audit-docs-backup-$(date +%Y-%m-%d).tar.gz \ - AUDIT_LENGKAP.md \ - QUICK_REFERENCE.md \ - DATABASE_SCHEMA.md \ - BACKUP_CHECKLIST.md \ - AUDIT_SUMMARY.md \ - DOKUMENTASI_INDEX.md - -# Store in safe location -cp audit-docs-backup-*.tar.gz /mnt/backup/ -``` - ---- - -## 📞 Documentation Support - -**Questions about documentation?** - -1. First, try searching the relevant file -2. Check cross-references at the end of each section -3. Review FAQ section (above) -4. Contact: Ali Jaya Net (081947215703) - ---- - -## 🏁 Next Steps - -1. **READ:** Mulai dengan AUDIT_SUMMARY.md -2. **UNDERSTAND:** Baca AUDIT_LENGKAP.md sections yang relevan -3. **REFERENCE:** Simpan QUICK_REFERENCE.md untuk daily use -4. **BACKUP:** Ikuti BACKUP_CHECKLIST.md procedures -5. **MAINTAIN:** Update docs saat ada changes - ---- - -**Documentation Version:** 1.0 - Complete -**Last Updated:** June 19, 2026 -**Status:** ✅ READY FOR PRODUCTION - -**Happy Reading! 📖** - diff --git a/docs/FITUR_APLIKASI_LENGKAP.md b/docs/FITUR_APLIKASI_LENGKAP.md deleted file mode 100644 index 9e5f7f0..0000000 --- a/docs/FITUR_APLIKASI_LENGKAP.md +++ /dev/null @@ -1,2269 +0,0 @@ -# DOKUMENTASI FITUR APLIKASI - RTRWNET BILLING & MANAGEMENT SYSTEM -**Status:** ✅ COMPREHENSIVE FEATURE DOCUMENTATION -**Tanggal:** 14 Agustus 2026 -**Tujuan:** Complete reference for all built-in features & functionality - ---- - -## 📑 DAFTAR ISI - -1. [Overview Sistem](#overview-sistem) -2. [Portal & Akses](#portal--akses) -3. [Fitur Billing & Invoicing](#fitur-billing--invoicing) -4. [Fitur Manajemen Pelanggan](#fitur-manajemen-pelanggan) -5. [Fitur MikroTik Integration](#fitur-mikrotik-integration) -6. [Fitur GenieACS & TR-069](#fitur-genieacs--tr-069) -7. [Fitur OLT & ONU Management](#fitur-olt--onu-management) -8. [Fitur Payment Gateway](#fitur-payment-gateway) -9. [Fitur GIS & Mapping](#fitur-gis--mapping) -10. [Fitur WhatsApp & Telegram](#fitur-whatsapp--telegram) -11. [Fitur Inventory & Logistics](#fitur-inventory--logistics) -12. [Fitur Ticketing & Support](#fitur-ticketing--support) -13. [Fitur Agent & Sales](#fitur-agent--sales) -14. [Fitur Monitoring & Health](#fitur-monitoring--health) -15. [Fitur Automation & Cron](#fitur-automation--cron) -16. [Fitur Internal User Management](#fitur-internal-user-management) - ---- - -## 📊 OVERVIEW SISTEM - -### Informasi Dasar -- **Nama:** RTRWNET Management & Billing System -- **Versi:** 1.0.0 -- **Runtime:** Node.js ≥20.0.0 -- **Database:** SQLite (better-sqlite3) -- **Main File:** `app-customer.js` -- **Port Default:** 3001 (dapat diubah di settings.json) -- **License:** Terbuka (lihat LICENSE file) - -### Target User -1. **Admin/Manajemen ISP** - Pengelola bisnis & konfigurasi sistem -2. **Teknisi Lapangan** - Support & maintenance perangkat pelanggan -3. **Operator Billing** - Penagihan & administrasi keuangan -4. **Agent/Mitra Penjualan** - Penjualan paket & pembayaran -5. **Pelanggan** - Portal self-service -6. **Kolektor** - Approval pembayaran tertangguh - -### Tech Stack Utama -```javascript -- Express.js 4.18.2 // Web framework -- SQLite (better-sqlite3) // Database ringan & reliable -- EJS 3.1.10 // Template engine -- Bootstrap 5 // CSS framework -- Leaflet // Map/GIS -- Baileys 6.7.21 // WhatsApp unofficial -- node-routeros-client // MikroTik API -- net-snmp // OLT SNMP -- Axios // HTTP client -- node-cron // Task scheduling -``` - ---- - -## 🚪 PORTAL & AKSES - -### 1. Portal Pelanggan (Public/Private) -**URL:** `http://localhost:3001/customer` - -**Sub-Fitur:** -- ✅ Login/Registrasi (dengan opsi OTP) -- ✅ Dashboard - ringkasan tagihan & status -- ✅ Cek tagihan (tanpa login via `/customer/check-billing`) -- ✅ Riwayat invoice & pembayaran -- ✅ Grafik traffic PPPoE real-time -- ✅ Ubah SSID/Password Wi-Fi -- ✅ Reboot CPE/ONU -- ✅ Beli voucher hotspot -- ✅ Buat tiket support -- ✅ Profil & setting pribadi - -**Authentication:** Session-based + OTP optional - -**Views:** -``` -views/customer/ -├── dashboard.ejs // Halaman utama -├── billing.ejs // Riwayat tagihan -├── topup.ejs // Pembayaran online -├── register.ejs // Registrasi -├── device.ejs // Manajemen Wi-Fi -├── ppob.ejs // Pembelian voucher -├── tickets.ejs // Support tickets -``` - ---- - -### 2. Portal Admin -**URL:** `http://localhost:3001/admin` - -**Sub-Fitur:** -- ✅ Dashboard - statistik & ringkasan -- ✅ Manajemen pelanggan (CRUD) -- ✅ Manajemen paket & harga -- ✅ Billing & invoice generation -- ✅ MikroTik configuration & monitoring -- ✅ GenieACS device management -- ✅ OLT/ONU management -- ✅ Peta jaringan (GIS) dengan Leaflet -- ✅ Whatsapp administration -- ✅ Manajemen agent/agen -- ✅ Laporan keuangan -- ✅ Inventory management -- ✅ Settings & configuration -- ✅ Audit trail & logs -- ✅ Backup & restore -- ✅ Multi-language support - -**Authentication:** Session admin-only - -**Main Routes:** -``` -/admin/login → Admin login -/admin → Dashboard -/admin/customers → Manajemen pelanggan -/admin/packages → Paket layanan -/admin/invoices → Tagihan -/admin/mikrotik → MikroTik tools -/admin/genieacs → Device management -/admin/olts → OLT management -/admin/map → Peta jaringan -/admin/whatsapp → WhatsApp config -/admin/agents → Manajemen agen -/admin/reports → Laporan -/admin/inventory → Gudang -/admin/settings → Pengaturan -``` - ---- - -### 3. Portal Teknisi (Field Support) -**URL:** `http://localhost:3001/tech` - -**Sub-Fitur:** -- ✅ Dashboard teknis -- ✅ Pool tiket (ticket queue) -- ✅ Peta lokasi pelanggan & ODP -- ✅ Chat WhatsApp integration -- ✅ GPS tracking teknisi -- ✅ Input pelanggan baru (lapangan) -- ✅ Device monitoring (GenieACS) -- ✅ Performance monitoring (CPU, RAM, disk) -- ✅ Riwayat tiket & penanganan - -**Authentication:** Session tech-only - -**Features:** -``` -/tech/ → Dashboard -/tech/tickets → Daftar tiket -/tech/tickets/:id → Detail tiket -/tech/map → Peta jaringan -/tech/devices/:id → Detail device -/tech/monitoring → System monitoring -``` - ---- - -### 4. Portal Agen (Agent/Sales) -**URL:** `http://localhost:3001/agent` - -**Sub-Fitur:** -- ✅ Login & dashboard -- ✅ Pembayaran tagihan pelanggan (dari saldo agen) -- ✅ Pembelian voucher hotspot -- ✅ Penjualan pulsa & data (Digiflazz) -- ✅ Cetak struk transaksi -- ✅ Riwayat & laporan transaksi -- ✅ Manajemen saldo - -**Authentication:** Session agent-only - -**Payment Methods:** -- Direct payment dari saldo agen -- E-voucher purchase -- Digital product (pulsa, data, dll via Digiflazz) - ---- - -### 5. Portal Kolektor (Payment Collector) -**URL:** `http://localhost:3001/collector` - -**Sub-Fitur:** -- ✅ Login & dashboard -- ✅ Cek tagihan pelanggan per area -- ✅ Buat pengajuan pembayaran -- ✅ Riwayat pengajuan -- ✅ Approval workflow - -**Authentication:** Session collector-only - -**Workflow:** -``` -1. Kolektor cek tagihan pelanggan -2. Kolektor buat pengajuan pembayaran -3. Admin/Kasir approve pengajuan -4. Sistem catat pembayaran -5. Pelanggan dapat notifikasi via WhatsApp -``` - ---- - -### 6. Portal Finance (Keuangan) -**URL:** `http://localhost:3001/finance` - -**Sub-Fitur:** -- ✅ Laporan pendapatan -- ✅ Kategori pengeluaran -- ✅ Entry pengeluaran operasional -- ✅ Cash in/out tracking -- ✅ Financial dashboard -- ✅ Export laporan - -**Authentication:** Admin-only access - ---- - -### 7. Portal Public (Publik) -**Tanpa Login:** -- ✅ Cek tagihan tanpa login: `/customer/check-billing` -- ✅ Halaman status isolated: `/isolated` -- ✅ QRIS static payment: `/qris/static.ejs` -- ✅ Public voucher info: `/public/voucher` -- ✅ TOS/Privacy/About/Contact pages - ---- - -## 💰 FITUR BILLING & INVOICING - -### 1. Invoice Generation - -**Jenis Billing:** -- ✅ Bulanan otomatis (automatic monthly billing) -- ✅ Per pelanggan (single customer) -- ✅ Massal (bulk billing) -- ✅ Prorata (untuk bulan pertama) - -**Komponen Invoice:** -```javascript -{ - id: number, - customer_id: number, - period_month: number, // 1-12 - period_year: number, // 2026 - amount: number, // Total tagihan - status: 'unpaid'|'paid'|'cancelled', - qris_amount_unique: number, // QRIS nominal unik - notes: string, // Promo & prorata info - created_at: datetime, - due_date: datetime, - paid_at: datetime, - payment_method: string // 'admin', 'agent', 'tripay', dll -} -``` - -**Fitur Promo & Prorata:** -``` -Promo: -- Paket bisa set harga promo untuk N siklus pertama -- Setiap pelanggan track promo_cycles_used -- Promo berakhir → kembali ke harga normal - -Prorata: -- Jika tanggal pasang (install_date) = bulan tagihan -- Invoice pertama dihitung per hari (proporsi bulan) -- Otomatis di-apply berdasarkan paket setting -``` - -**Contoh Workflow:** -``` -1. Admin generate invoice untuk periode 08/2026 -2. Sistem hitung nominal per pelanggan: - - Status promo? → gunakan promo_price - - Paket punya FUP? → cek kuota bulanan - - Bulan pertama & prorata aktif? → hitung prorata -3. Invoice di-create dengan status 'unpaid' -4. Notifikasi WhatsApp ke pelanggan -5. Pelanggan bayar (online atau manual) -6. Sistem update status menjadi 'paid' -7. Notifikasi paid ke pelanggan -8. Isolir otomatis jika lewat due date -``` - ---- - -### 2. Payment Gateway Integration - -**Gateway Terintegasi:** -```javascript -1. Midtrans (Snap API) - - Status: Aktif/Nonaktif di settings - - Fitur: Multiple payment methods (CC, transfer, GCash, etc) - -2. Tripay - - Status: Aktif/Nonaktif - - Fitur: Bank transfer, E-wallet, QRIS - -3. Xendit - - Status: Aktif/Nonaktif - - Fitur: Invoice, VA, QR codes - -4. Duitku - - Status: Aktif/Nonaktif - - Fitur: Aggregator pembayaran - -5. QRIS Static (Built-in) - - QR code fixed untuk donasi/pembayaran unik - - Nominal unik auto-assign per invoice - - Mudah match payment dari notifikasi bank -``` - -**Payment Flow:** -``` -Customer → Choose Payment Method - → Redirect to Gateway - → Process Payment - → Gateway Webhook/Callback - → Mark Invoice as PAID - → Send WhatsApp confirmation -``` - -**Webhook Payment Generic:** -``` -Endpoint: POST /api/webhook/v1/payment-notif -Fitur: -- Generic webhook untuk bank/e-wallet notification -- Auto-match nominal dengan invoice -- Auto-mark paid jika cocok -- Log semua webhook untuk audit -- Manual cleanup jika perlu -``` - ---- - -### 3. Pembayaran Manual & Offline - -**Tipe Pembayaran Manual:** -```javascript -1. Admin bayar (dari panel) - - Pilih invoice - - Catat nominal pembayaran - - Catat metode pembayaran - - Mark as paid - - Otomatis kirim notifikasi WhatsApp - -2. Agent bayar (dari saldo agen) - - Agent login - - Pilih pelanggan - - Cek tagihan - - Bayar dari saldo agen - - Struk otomatis print/download - -3. Kolektor ajukan (pending approval) - - Kolektor input pembayaran - - Pending approval (admin/kasir) - - Approval → mark as paid - - Rejection → return ke pending - -4. Kasir bayar (kasir portal) - - Kasir login - - Input pembayaran - - Mark paid - - Print bukti -``` - ---- - -### 4. Invoice Management - -**Fitur:** -``` -- ✅ Lihat daftar invoice (admin/customer) -- ✅ Cetak invoice (PDF via pdfKit) -- ✅ Export invoice list (CSV/Excel) -- ✅ Batalkan pembayaran (unpay) - jika ada kesalahan -- ✅ Reschedule due date -- ✅ Bulk action (multiple invoices) -- ✅ Invoice status tracking -- ✅ Payment reminder via WhatsApp -``` - -**Invoice Status Flow:** -``` -unpaid → (payment received) → paid - ↓ - cancelled (oleh admin) - -Isolir status linked ke unpaid invoices -Auto-isolir trigger jika lewat due date -``` - ---- - -## 👥 FITUR MANAJEMEN PELANGGAN - -### 1. CRUD Pelanggan - -**Data Pelanggan:** -```javascript -{ - id: number, - name: string, // Nama pelanggan - phone: string, // Nomor HP - email: string, // Email - address: string, // Alamat fisik - latitude: float, // Koordinat GPS - longitude: float, - - // Network - package_id: number, // Paket yang digunakan - router_id: number, // MikroTik router - pppoe_username: string, // Username PPPoE - pppoe_secret: string, // Password PPPoE - hotspot_username: string, // Username hotspot - static_ip: string, // IP statis (jika ada) - - // Device - olt_id: number, // OLT yang digunakan - onu_port: number, // Port ONU - genieacs_tag: string, // Tag di GenieACS - - // Location - odp_id: number, // ODP terdekat - area: string, // Area/kabupaten - - // Status & Billing - status: 'active'|'suspended'|'inactive', - install_date: date, // Tanggal pasang - isolate_day: number, // Tanggal isolir otomatis (1-31) - auto_isolate: boolean, // Enable isolir otomatis - - // Promo - promo_cycles_used: number, // Berapa siklus promo sudah dipakai - - // Other - nik: string, // No ID pelanggan - notes: string, // Catatan - created_at: datetime, - updated_at: datetime -} -``` - -**Operasi:** -``` -- ✅ Tambah pelanggan baru -- ✅ Edit data pelanggan -- ✅ Hapus pelanggan (soft delete) -- ✅ Import pelanggan dari Excel -- ✅ Export pelanggan list -- ✅ Bulk action (status change, package change, dll) -- ✅ Search & filter (by name, phone, area, status) -``` - ---- - -### 2. Isolir / Suspend Customer - -**Isolir Manual:** -``` -Admin klik "Isolir" di halaman pelanggan - ↓ -Sistem suspend ke MikroTik: - - PPPoE: hapus user atau disable - - Hotspot: suspend user - - Static IP: redirect ke "Isolated" page - ↓ -Status pelanggan: 'suspended' - ↓ -Pelanggan kembali online setelah bayar + admin buka isolir -``` - -**Isolir Otomatis (Cron):** -``` -Cron job berjalan setiap hari jam 2 pagi - ↓ -Cek semua pelanggan: - - Status = 'active' - - auto_isolate = true - - Tanggal hari ini >= isolate_day - - Ada unpaid invoices - ↓ -Trigger isolir otomatis - ↓ -Notifikasi WhatsApp ke pelanggan -``` - -**Buka Isolir (Unisolir):** -``` -Admin klik "Buka Isolir" setelah pembayaran - ↓ -Sistem restore di MikroTik: - - PPPoE: tambah kembali user atau enable - - Hotspot: reactivate user - ↓ -Status pelanggan: 'active' - ↓ -Pelanggan bisa online lagi - ↓ -Notifikasi WhatsApp konfirmasi -``` - ---- - -### 3. Manajemen Paket Layanan - -**Data Paket:** -```javascript -{ - id: number, - name: string, // Nama paket (Starter, Pro, Premium) - description: string, - price: number, // Harga reguler per bulan - promo_price: number, // Harga promo (opsional) - promo_cycles: number, // N siklus pertama dapat promo - - // Speed - speed_down: number, // Download Mbps - speed_up: number, // Upload Mbps - - // FUP (Fair Usage Policy) - use_fup: boolean, // Enable FUP? - fup_limit_gb: number, // Limit data per bulan (GB) - fup_profile_name: string, // Profile MikroTik saat FUP - - // Night Mode (Jam Kalong) - use_night_mode: boolean, // Enable night mode? - night_profile_name: string, // Profile MikroTik malam (23:00-06:00) - - // Tax - use_ppn: boolean, // Charge PPN? - ppn_percentage: number, // % PPN (default 11%) - - // Prorata - prorate_first_invoice: boolean, // Prorata invoice pertama? - - is_active: boolean, - created_at: datetime -} -``` - -**Operasi:** -``` -- ✅ Tambah paket -- ✅ Edit paket -- ✅ Hapus paket -- ✅ Set promo per paket -- ✅ Set night mode profile -- ✅ Set FUP limit & profile -``` - ---- - -## 🌐 FITUR MIKROTIK INTEGRATION - -### 1. Koneksi & Konfigurasi - -**Setup MikroTik:** -``` -1. Admin setting: - - Host: 192.168.8.1 - - Username: billing - - Password: password123 - - Port: 8711 - -2. Di MikroTik router: - - Enable API service - - Create user 'billing' dengan permission - - Whitelist IP aplikasi - -3. Tes koneksi dari panel admin -``` - -**Multi-Router Support:** -``` -- Aplikasi bisa kelola banyak MikroTik router -- Per pelanggan assign ke router mana -- Cron job sinkron ke router tersesuai -- Fallback ke default router jika tidak specify -``` - ---- - -### 2. PPPoE Management - -**PPPoE User:** -```javascript -{ - username: string, // PPPoE username - secret: string, // PPPoE password - password_hashed: string, // Disimpan via PPPoE protocol - profile: string, // Bandwidth profile - disabled: boolean, - created_at: datetime -} -``` - -**Operasi:** -``` -- ✅ Create PPPoE user -- ✅ Change secret/password -- ✅ Disable/enable user -- ✅ View active sessions -- ✅ Monitor traffic (bytes in/out) -- ✅ Set speed profile -- ✅ Delete user -``` - -**Traffic Monitoring:** -``` -Real-time: -- ✅ Monitor sesi PPPoE aktif -- ✅ Grafik traffic per session -- ✅ Bytes sent/received -- ✅ Session duration -- ✅ IP address - -Historical: -- ✅ Store pemakaian per hari/bulan -- ✅ Aggregate data per customer -- ✅ Usage history dashboard -``` - ---- - -### 3. Hotspot Management - -**Hotspot User:** -```javascript -{ - name: string, // Hotspot username - password: string, - profile: string, // Speed profile - limit_uptime: number, // Session time limit - limit_bytes_total: number, // Data limit - limit_bytes_down: number, // Download limit - limit_bytes_up: number, // Upload limit - disabled: boolean -} -``` - -**Fitur:** -``` -- ✅ Create/edit hotspot user -- ✅ Active session monitoring -- ✅ View real-time data usage -- ✅ Disconnect session -- ✅ Set speed & data limits -``` - ---- - -### 4. Voucher Hotspot - -**Voucher System:** -``` -Workflow: -1. Admin create voucher batch -2. Sistem generate N kode voucher -3. Kode disimpan di database & MikroTik -4. Customer bisa gunakan di hotspot portal -5. Agent bisa jual voucher ke customer -6. Pelanggan bayar → dapat voucher code -``` - -**Voucher Batch:** -```javascript -{ - id: number, - name: string, // Nama batch - quantity: number, // Jumlah voucher - profile_name: string, // Speed profile - validity: number, // Hari berlaku - price: number, // Harga jual per voucher - status: 'pending'|'created'|'synced', - qty_created: number, // Berapa sudah dibuat - qty_failed: number, // Berapa gagal - created_at: datetime -} -``` - -**Fitur:** -``` -- ✅ Generate batch voucher -- ✅ Sync ke MikroTik -- ✅ Print voucher code -- ✅ Export CSV -- ✅ Track status (created/active/used/expired) -- ✅ Delete batch -- ✅ Sell via agent portal -- ✅ Sell via customer portal -``` - ---- - -### 5. Firewall & Rate Limiting - -**Built-in Firewall Setup:** -``` -Admin bisa setup firewall rules: -- Rate limiting per user -- Block ports tertentu -- Whitelist IP -- Queue management -- Priority traffic (VoIP, dst) -``` - ---- - -### 6. Bandwidth Profile (Jam Kalong) - -**Night Mode Automation:** -``` -Setup: -- Paket A: default 10Mbps, night 20Mbps (more speed at night) -- Paket B: default 5Mbps, night 2Mbps (throttle at night) - -Cron: -- 00:00 (midnight): Switch ke night profile -- 06:00 (pagi): Switch ke day profile - -Fitur: -- ✅ Set profile per paket -- ✅ Custom time (tidak harus fixed 00:00-06:00) -- ✅ Override manual per user -- ✅ Log profile changes -``` - ---- - -### 7. Backup MikroTik - -**Fitur:** -``` -- ✅ Backup konfigurasi MikroTik dari panel -- ✅ Schedule backup otomatis -- ✅ Download backup file -- ✅ Restore dari backup -- ✅ Version history -``` - ---- - -## 🎛️ FITUR GENIEACS & TR-069 - -### 1. Built-in ACS (Auto Configuration Server) - -Aplikasi memiliki ACS internal ringan untuk TR-069 tanpa perlu GenieACS eksternal. - -**Keuntungan:** -``` -✅ Lightweight - langsung di Node.js -✅ Tidak perlu MongoDB/Redis -✅ Hemat resource VPS -✅ Support banyak brand ONU (ZTE, Huawei, FiberHome, dll) -✅ Auto-detect device properties -✅ Provision WAN & VLAN otomatis -``` - -**Setting:** -```json -{ - "use_builtin_acs": true|false, - "acs_port": 7547 // TR-069 port -} -``` - ---- - -### 2. ONU/CPE Management - -**Device List:** -```javascript -{ - id: number, - device_id: string, // Identifier unik (MAC/Serial) - manufacturer: string, // Brand (ZTE, Huawei, dll) - model: string, - serial_number: string, - firmware_version: string, - - // Customer Link - customer_id: number, - customer_name: string, - customer_phone: string, - - // Status - status: 'online'|'offline'|'error', - last_contact: datetime, - - // Wi-Fi - ssid: string, // Wi-Fi name - password: string, // Wi-Fi password - - // VLAN - vlan_id: number, - management_ip: string, - - created_at: datetime -} -``` - ---- - -### 3. Device Operations - -**Fitur:** -``` -- ✅ View device list (dengan search & filter) -- ✅ Device detail (parameter, status, logs) -- ✅ Change SSID / Password Wi-Fi -- ✅ Bulk SSID change (multiple devices sekaligus) -- ✅ Reboot device -- ✅ View device logs & history -- ✅ Parameter configuration -- ✅ Provision WAN (VLAN, bridge, etc) -``` - -**SSID Change Workflow:** -``` -1. Admin/Tech buka device detail -2. Edit SSID & Password baru -3. Click "Update SSID" -4. Sistem send perintah via TR-069 -5. Device update Wi-Fi config -6. Notifikasi customer via WhatsApp -7. Log activity di audit trail -``` - ---- - -### 4. GenieACS Integration (Optional) - -Jika gunakan GenieACS eksternal: - -**Konfigurasi:** -```json -{ - "genieacs_url": "http://192.168.8.189:7557", - "genieacs_username": "admin", - "genieacs_password": "admin", - "genieacs_timeout": 30000, - "genieacs_monitoring_enabled": true, - "genieacs_monitoring_interval": 6, // Jam - "genieacs_rxpower_threshold": -27 // dBm -} -``` - -**Fitur:** -``` -- ✅ Sync device dari GenieACS ke aplikasi -- ✅ View GenieACS parameters -- ✅ Kirim command (SSID, reboot, dll) -- ✅ Monitor RX power (signal strength) -- ✅ Alert jika signal lemah -- ✅ Bulk operation -``` - ---- - -## 🔌 FITUR OLT & ONU MANAGEMENT - -### 1. OLT Configuration - -**OLT Data:** -```javascript -{ - id: number, - name: string, // Nama OLT (OLT-1, OLT-Jakarta, dll) - host: string, // IP address - snmp_community: string, // SNMP community string - snmp_port: number, // SNMP port (161) - brand: string, // Brand (HIOSO, ZTE, Huawei, dll) - model: string, - - // Telnet (untuk konfigurasi WAN) - telnet_host: string, - telnet_port: number, - telnet_username: string, - telnet_password: string, - telnet_enable_password: string, - - // Web interface - web_url: string, - web_username: string, - web_password: string, - - // API (untuk ZTE C320) - api_base_url: string, - - is_active: boolean, - created_at: datetime -} -``` - ---- - -### 2. ONU Status & Monitoring - -**ONU Info:** -```javascript -{ - olt_id: number, - port: number, // Port OLT (1-128 tergantung OLT) - onu_index: number, - - // Hardware - sn: string, // Serial number - model: string, - firmware_version: string, - mac_address: string, - - // Status - status: 'online'|'offline'|'dying_gasp'|'error', - admin_state: 'enable'|'disable', - optical_signal: number, // dBm - - // Customer link - customer_id: number, - customer_name: string, - - // Distance - distance: number, // KM to OLT - - // Last contact - last_contact: datetime -} -``` - ---- - -### 3. ONU Operations - -**Fitur:** -``` -- ✅ View ONU list per port -- ✅ View ONU statistics (signal strength, status) -- ✅ Reboot ONU -- ✅ Rename ONU (friendly name) -- ✅ Authorize ONU (EPON) -- ✅ Configure WAN (VLAN, bridge, PPPoE) -- ✅ View ONU logs -- ✅ Bulk operation -``` - -**Configure WAN Methods:** -``` -1. Telnet (OMCI commands) - - For ZTE, Huawei, FiberHome - - Direksi jalankan commands Telnet - -2. TR-069 (GenieACS) - - If GenieACS configured - - Use parameter modification - -3. REST API (go-api-c320) - - For ZTE C320 specifically - - Direct API call to OLT - -4. Web Interface - - Manual via OLT web UI - - Backup method jika automation gagal -``` - ---- - -### 4. OLT Port Management - -**Port Info:** -```javascript -{ - olt_id: number, - port_number: number, // 1-N - port_type: 'EPON'|'GPON'|'hybrid', - - // Capacity - total_onus: number, // Max ONU di port ini - active_onus: number, // ONU yang online - - // Status - status: 'up'|'down'|'error', - admin_state: 'enable'|'disable', - - // Statistics - bytes_rx: number, - bytes_tx: number, - packets_rx: number, - packets_tx: number, - errors: number, - - // Monitoring - optical_power: number, - temperature: number -} -``` - ---- - -## 💳 FITUR PAYMENT GATEWAY - -### 1. Multi-Gateway Architecture - -**Supported Gateways:** -``` -1. Midtrans (Snap API) - Status: Enable/Disable di settings - Methods: CC, Transfer, GCash, Gopay, OVO, Dana - -2. Tripay - Status: Enable/Disable - Methods: Bank Transfer, Ewallet, QRIS - -3. Xendit - Status: Enable/Disable - Methods: Virtual Account, QR, Invoice - -4. Duitku - Status: Enable/Disable - Methods: Aggregator pembayaran - -5. QRIS Static (Built-in) - Status: Always available - Methods: QR Code fixed -``` - ---- - -### 2. Payment Integration Flow - -**Customer Bayar Invoice:** -``` -1. Customer lihat invoice di portal -2. Click "Bayar" -3. Pilih payment method dari gateway aktif -4. Redirect ke payment gateway -5. Customer input data pembayaran -6. Gateway proses pembayaran -7. Success/Failure notification -8. Aplikasi terima webhook dari gateway -9. Verify payment amount & signature -10. Mark invoice as PAID (jika success) -11. Send WhatsApp confirmation -12. Customer notif pembayaran berhasil -``` - ---- - -### 3. Payment Verification - -**Verification Process:** -```javascript -function verifyPayment(invoice, payment) { - // 1. Check nominal cocok - if (payment.amount !== invoice.amount) { - return false; - } - - // 2. Check signature (tergantung gateway) - const signature = crypto.createHmac('sha256', secretKey) - .update(payment.order_id + payment.amount) - .digest('hex'); - if (signature !== payment.signature) { - return false; - } - - // 3. Check status (sudah dibayar di gateway) - if (payment.status !== 'success' && payment.status !== 'paid') { - return false; - } - - // 4. Check duplikasi (jangan bayar 2x) - const existing = findPaymentByExternalId(payment.gateway_id); - if (existing) { - return false; - } - - return true; -} -``` - ---- - -### 4. Webhook Handling - -**Generic Webhook:** -``` -Endpoint: POST /api/webhook/v1/payment-notif -Header: Authorization: Bearer MY_WEBHOOK_SECRET - -Fitur: -- ✅ Accept webhook dari bank/e-wallet apapun -- ✅ Parse notifikasi pembayaran -- ✅ Match nominal dengan invoice/voucher -- ✅ Auto-mark paid jika cocok -- ✅ Log semua webhook (audit trail) -- ✅ Manual review & cleanup di admin -``` - -**Webhook Log:** -```javascript -{ - id: number, - service: string, // "bank_abc", "ewallet_xyz" - content: string, // Raw webhook content - parsed_amount: number, // Parsed dari notifikasi - parsed_ok: boolean, // Berhasil di-parse? - matched_invoice: number, // Invoice ID yang matched - matched_voucher: number, // Voucher ID yang matched - ip: string, // Source IP - user_agent: string, - created_at: datetime, - status: 'pending'|'processed'|'error' -} -``` - ---- - -### 5. Payment Report - -**Fitur:** -``` -- ✅ Daily transaction report -- ✅ Gateway settlement report -- ✅ Payment method breakdown -- ✅ Failed payment report -- ✅ Refund tracking -- ✅ Revenue trending -``` - ---- - -## 🗺️ FITUR GIS & MAPPING - -### 1. Peta Admin (`/admin/map`) - -**Fitur Dasar:** -``` -- ✅ Leaflet map dengan OpenStreetMap -- ✅ Hybrid view (satellite + road) -- ✅ Zoom in/out -- ✅ Locate kantor (center point dari office_lat/office_lng) -``` - -**Marker & Layer:** -``` -1. Customer Marker - - Merah: offline/suspended - - Hijau: online - - Biru: pending - - Click → popup detail customer - -2. ODP Marker - - Orange icon - - Click → ODP info & available ports - -3. Cable Path (Polyline) - - Garis dari customer ke ODP - - Bisa edit/draw manually - - Simpan rute untuk setiap customer -``` - -**Popup Info:** -``` -Customer Popup: -- Name, phone, email -- Paket, status, speed -- IP address (PPPoE/hotspot) -- Unpaid invoices count -- Traffic graph (PPPoE real-time) -- Action buttons: isolir, edit, view detail - -ODP Popup: -- ODP name -- Available ports -- Customers connected -- Port status summary -``` - -**Interactive Fitur:** -``` -- ✅ Draw cable path (customer to ODP) -- ✅ Save cable route -- ✅ Edit customer location (via location picker) -- ✅ Bulk action dari peta (select multiple customers) -- ✅ Real-time PPPoE traffic graph -``` - ---- - -### 2. Peta Teknisi (`/tech/map`) - -**Fitur:** -``` -- ✅ Sama seperti admin map (read-only untuk tech) -- ✅ View customer & ODP locations -- ✅ Click customer → show WhatsApp chat button -- ✅ Open route di Google Maps -- ✅ GPS tracking teknisi (optional) -- ✅ Nearby customers (dalam radius tertentu) -``` - -**Tech GPS Tracking:** -``` -Setting: -- Aktifkan attendance_geofencing di settings -- Radius perimeter kantor (attendance_radius meter) - -Fitur: -- Tech login di mobile portal -- Sistem track GPS lokasi tech -- Visualisasi di peta -- Geofence alert (keluar/masuk area) -``` - ---- - -### 3. Location Picker (Form Customer) - -**Fitur:** -``` -- ✅ Modal dengan peta satellite view -- ✅ Click di peta → set customer location -- ✅ Drag marker untuk adjust posisi -- ✅ Coordinate display (lat/lng) -- ✅ Address lookup (reverse geocoding jika ada) -- ✅ Done → save ke form -``` - ---- - -### 4. Cable Path Management - -**Data:** -```javascript -{ - customer_id: number, - olt_id: number, - odp_id: number, - - // Polyline coordinates - path: [ // Array of [lat, lng] - [-6.2521, 107.9205], - [-6.2522, 107.9206], - [-6.2523, 107.9207] - ], - - length_km: number, // Calculated distance - description: string, // Cable detail (aerial/underground, etc) - - created_at: datetime, - updated_at: datetime -} -``` - -**Operasi:** -``` -- ✅ Draw path (click-click di peta) -- ✅ Edit existing path -- ✅ Delete path -- ✅ Calculate distance automatically -- ✅ Save to database -``` - ---- - -## 💬 FITUR WHATSAPP & TELEGRAM - -### 1. WhatsApp Integration (Baileys) - -**Setup:** -``` -Setting di settings.json: -{ - "whatsapp_enabled": true, - "whatsapp_auth_folder": "auth_info_baileys", - "whatsapp_admin_numbers": ["081947215703", "087820851413"], - "company_phone": "6287820851413" -} -``` - -**Authentication:** -``` -1. Admin login ke /admin/whatsapp -2. Sistem tampilkan QR code -3. Scan QR code dengan WhatsApp app -4. Verifikasi di WhatsApp -5. Bot siap mengirim pesan -``` - ---- - -### 2. WhatsApp Features - -**Incoming Message Handler:** -``` -Admin/authorized nomor bisa kirim command: - -1. BILLING - - List unpaid invoices - - Customer status - - Payment info - -2. MIKROTIK - - Active users - - Session info - - Bandwidth status - -3. PULSA (Digiflazz) - - Check balance - - Buy pulsa - - Transaction status - -4. TOPUP AGENT - - Top-up saldo agent - - Check agent balance -``` - -**Incoming Command Examples:** -``` -From admin: -"billing" → Kirim laporan billing hari ini - -"pppoe" → List active PPPoE sessions - -"balance" → Cek saldo Digiflazz - -"topup 1000000" → Top-up agen Rp 1jt - -"saldo" → Cek saldo agent -``` - ---- - -### 3. WhatsApp Automated Messages - -**Invoice Notification:** -``` -When: -- Invoice created (otomatis kirim ke customer) -- Invoice paid (kirim konfirmasi) -- Invoice due (reminder H-1 isolir) - -Content: -"Tagihan Internet RTRWnet -Periode: Agustus 2026 -Nominal: Rp 350.000 -Due: 10 Agustus 2026 - -Bayar di: [link portal] - -Isolir jika belum bayar: 10 Agustus 2026" -``` - -**Payment Confirmation:** -``` -When: Invoice marked as paid - -Content: -"✅ Pembayaran Anda diterima! - -Tagihan: Rp 350.000 -Tanggal: 05 Agustus 2026 -Status: LUNAS - -Terima kasih atas pembayaran Anda. -Layanan Anda tetap aktif. - -- RTRWnet Admin" -``` - -**Isolir Notice:** -``` -When: Isolir automatic atau manual - -Content: -"⚠️ PEMBERITAHUAN ISOLIR - -Layanan internet Anda telah diputus -Alasan: Tagihan belum dibayar - -Tagihan: Rp 350.000 -Due date: 10 Agustus 2026 - -Hubungi: [support number] - -Buka isolir setelah pembayaran" -``` - ---- - -### 4. WhatsApp Broadcast - -**Fitur:** -``` -- ✅ Select customer list -- ✅ Create message (dengan template variable) -- ✅ Schedule send time -- ✅ Set delay antar message (untuk hindari spam) -- ✅ View delivery status -- ✅ Pause/resume/stop broadcast -- ✅ Retry failed messages -``` - -**Broadcast Example:** -``` -Template: -"Halo {{customer_name}}, -Tagihan internet bulan ini sudah siap. -Nominal: {{amount_idr}} -Bayar di: {{payment_link}}" - -Broadcast: -1. Select customers: Area Bekasi (200 customer) -2. Template: "Tagihan Bulanan" -3. Schedule: 09:00 (9 pagi) -4. Delay: 3 detik antar pesan -5. Total: 200 pesan dalam 10 menit -6. Status: Sent 198, Failed 2, Pending 0 -``` - ---- - -### 5. WhatsApp Live Chat - -**Fitur (Upcoming):** -``` -- ✅ Inbox untuk semua chat masuk/keluar -- ✅ Reply message dari admin panel -- ✅ Chat history per customer -- ✅ Quick reply template -- ✅ Attachment support -``` - ---- - -### 6. Telegram Integration (Optional) - -**Setup:** -```json -{ - "telegram_enabled": true|false, - "telegram_bot_token": "xxx:yyy", - "telegram_admin_id": "123456789" -} -``` - -**Fitur:** -``` -- ✅ Bot untuk admin (same as WhatsApp commands) -- ✅ Alert notifications -- ✅ Daily report -- ✅ System monitoring -``` - ---- - -## 📦 FITUR INVENTORY & LOGISTICS - -### 1. Inventory System - -**Kategori Inventory:** -``` -- Perangkat ONU/CPE (stock) -- Kabel & Connector -- Power Supply -- Accessories (splitter, dll) -- Tools & Equipment -``` - -**Item Data:** -```javascript -{ - id: number, - category_id: number, - name: string, // Product name - sku: string, // SKU code - description: string, - unit: string, // 'pcs', 'meter', 'kg', dll - quantity: number, // Current stock - minimum_qty: number, // Alert jika stock < ini - unit_cost: number, // Cost per unit - supplier: string, - location: string, // Lokasi di gudang - created_at: datetime -} -``` - ---- - -### 2. Inventory Operation - -**Fitur:** -``` -- ✅ Add item ke inventory -- ✅ Adjust stock (add/remove) -- ✅ Stock transfer -- ✅ Low stock alert -- ✅ Item history -- ✅ Search & filter -- ✅ Export inventory list -``` - -**Stock Alert:** -``` -When stock < minimum_qty: -- Dashboard alert -- Email notification (jika ada) -- Request PO (Purchase Order) -``` - ---- - -### 3. Asset Tracking - -**Asset Assignment:** -``` -Teknisi bisa assign asset ke task: -- Ticket → use ONU -- Installation → use cable x10m -- Repair → use power supply 1pc -``` - -**Asset History:** -``` -Track item dari stock → assignment → return -- What item used -- When used -- Who used -- For what task -- Status (used/returned/lost) -``` - ---- - -## 🎫 FITUR TICKETING & SUPPORT - -### 1. Ticket System - -**Ticket Data:** -```javascript -{ - id: number, - - // Customer & Technician - customer_id: number, - customer_name: string, - customer_phone: string, - customer_email: string, - - technician_id: number, - technician_name: string, - - // Content - subject: string, // Judul keluhan - message: string, // Deskripsi masalah - - // Status - status: 'open'|'in_progress'|'resolved'|'closed', - - // Details - priority: 'low'|'medium'|'high'|'urgent', - category: string, // 'billing', 'technical', 'general' - - // Attachments - customer_photos: string, // JSON array of file paths - customer_photo_metadata: string, // Photo GPS/timestamp - technician_photos: string, - technician_notes: string, - - // Timeline - created_at: datetime, - updated_at: datetime, - resolved_at: datetime -} -``` - ---- - -### 2. Ticket Workflow - -**Open (Customer):** -``` -1. Customer buka portal -2. Click "Buat Tiket" -3. Input subject, deskripsi, foto (optional) -4. Submit -5. Ticket created dengan status 'open' -6. Notifikasi ke admin & teknisi via WhatsApp -``` - -**Assign (Admin):** -``` -1. Admin lihat daftar open tickets -2. Assign ke teknisi -3. Ticket status: 'open' → tidak berubah (tunggu teknisi accept) -``` - -**In Progress (Technician):** -``` -1. Tech buka portal -2. Lihat pool tickets (assigned to tech) -3. Click "Ambil Tiket" (take ticket) -4. Ticket status: 'open' → 'in_progress' -5. Tech bisa input notes & foto -6. Status update ke customer via WhatsApp -``` - -**Resolve (Technician):** -``` -1. Tech selesaikan pekerjaan -2. Input resolution notes -3. Upload foto (before/after) -4. Click "Selesai" -5. Ticket status: 'in_progress' → 'resolved' -6. Notifikasi ke customer -``` - -**Close (Customer/Admin):** -``` -1. Customer lihat resolved ticket -2. Click "Tutup Tiket" (jika puas) -3. Ticket status: 'resolved' → 'closed' -4. Customer optional bisa rate 1-5 -5. Feedback saved untuk quality control -``` - ---- - -### 3. Ticket Features - -**Admin Panel:** -``` -- ✅ Dashboard tickets (open, in_progress, resolved, closed) -- ✅ Assign tickets ke technician -- ✅ Reassign jika perlu -- ✅ View ticket history -- ✅ Add internal notes -- ✅ Override status -- ✅ Filter by status/category/tech -- ✅ Ticket aging report -- ✅ SLA tracking -``` - -**Tech Portal:** -``` -- ✅ Pool tiket (tickets assigned to me) -- ✅ View ticket detail -- ✅ Take ticket -- ✅ Upload photos -- ✅ Add resolution notes -- ✅ Mark resolved -- ✅ View ticket history -``` - -**Customer Portal:** -``` -- ✅ Create ticket -- ✅ View my tickets -- ✅ View ticket status -- ✅ Add comment/photo -- ✅ Mark resolved (jika tech bilang done) -- ✅ Rate satisfaction -- ✅ View ticket history -``` - ---- - -## 👔 FITUR AGENT & SALES - -### 1. Agent Management - -**Agent Data:** -```javascript -{ - id: number, - username: string, // Login username - password_hash: string, // Hashed password - name: string, // Agent name - phone: string, - email: string, - area: string, // Area operasi - status: 'active'|'inactive', - - // Financial - balance: number, // Saldo agent (Rp) - commission_percent: number, // Komisi % - - // Reference - id_number: string, // KTP/ID number - bank_account: string, - bank_name: string, - - created_at: datetime -} -``` - ---- - -### 2. Agent Portal - -**Fitur:** -``` -Dashboard: -- ✅ Total balance -- ✅ Today's transaction -- ✅ Commission earned -- ✅ Top customers - -Pembayaran: -- ✅ Cari customer by name/phone -- ✅ Lihat unpaid invoices -- ✅ Pilih invoice → bayar dari saldo agent -- ✅ Print struk pembayaran -- ✅ Kirim struk ke customer (WhatsApp/Email) - -Voucher: -- ✅ Lihat inventory voucher -- ✅ Pilih voucher untuk dijual -- ✅ Customer bayar → agent terima stok -- ✅ Print voucher code -- ✅ Track voucher sale - -Digiflazz: -- ✅ Browse produk (pulsa, data, dll) -- ✅ Category → Brand → Nominal flow -- ✅ Buy produk (debit saldo agent) -- ✅ Manual input customer nomor -- ✅ Delivery otomatis -- ✅ Webhook status update -``` - ---- - -### 3. Admin Agent Management - -**Fitur:** -``` -- ✅ Add agent (create account) -- ✅ Edit agent (name, area, commission) -- ✅ Deactivate agent -- ✅ Top-up agent balance (from admin) -- ✅ View agent transaction history -- ✅ Set special price per agent -- ✅ View agent commission report -- ✅ Agent performance dashboard -``` - -**Top-up Agent:** -``` -Admin: -1. Open agent list -2. Click "Top-up" pada agent -3. Input amount (Rp 1.000.000) -4. Mark as "top-up" in cash_in table -5. Agent balance += amount -6. Notifikasi ke agent via WhatsApp -``` - ---- - -### 4. Special Price Management - -**Fitur:** -``` -Admin bisa set special price per agent: - -Paket A: Normal price Rp 350.000 -- Agent A commission: Rp 30.000 (jadi agent harus charge min 350k) -- Agent B commission: Rp 50.000 (better agent) - -atau - -Special pricing: -- Agent A harga khusus: Rp 320.000/bulan -- Agent A komisi: Rp 20.000 -- Total untuk agent: Rp 340.000 -``` - ---- - -### 5. Digiflazz Integration - -**Setup:** -```json -{ - "digiflazz_username": "your_account", - "digiflazz_api_key": "api_key_xxx", - "digiflazz_webhook_secret": "webhook_secret", - "digiflazz_markup": 0 // Markup % (0-100) -} -``` - -**Flow:** -``` -1. Agent login → menu "Beli Produk" -2. Pilih kategori (Pulsa, Data, dll) -3. Pilih brand (Telkomsel, Indosat, dll) -4. Pilih nominal (Rp 5rb, 10rb, dll) -5. Input customer nomor -6. Confirm & bayar -7. Sistem kirim ke Digiflazz API -8. Produk dikirim otomatis -9. Webhook notif status -10. Status di-update di aplikasi -11. Agent terima notif -``` - -**Product Display:** -``` -[Telkomsel] [Indosat] [XL] [3] [Smartfren] - ↓ -[Rp 5rb] [Rp 10rb] [Rp 20rb] [Rp 50rb] [Rp 100rb] - ↓ -Input nomor → Konfirm → Proses -``` - ---- - -## 📊 FITUR MONITORING & HEALTH - -### 1. System Monitoring - -**Metrics:** -``` -Real-time: -- CPU Usage (%) -- Memory Usage (%) -- Disk Usage (%) -- Process uptime -- Load average - -Database: -- Connection status -- Table count -- Database size -- WAL status - -Services: -- MikroTik connectivity -- GenieACS connectivity -- Payment gateway status -- WhatsApp connection status -- OLT SNMP status -``` - ---- - -### 2. Monitoring Dashboard - -**Views:** -``` -Admin Portal (/admin/monitoring): -- System metrics card -- Graph history (CPU, RAM, Disk) -- Service status indicators -- Alert log - -Tech Portal (/tech/monitoring): -- Same as admin (read-only) -``` - ---- - -### 3. Health Check Endpoint - -**Endpoint:** -``` -GET /health - -Response: -{ - "status": "healthy", - "timestamp": "2026-08-14T10:30:00Z", - "services": { - "database": "ok", - "mikrotik": "ok", - "payment_gateway": "ok", - "whatsapp": "connected" - } -} -``` - ---- - -### 4. Alert System - -**Alert Types:** -``` -- ✅ High CPU (> 80%) -- ✅ Low disk space (< 10%) -- ✅ Memory warning (> 85%) -- ✅ Service disconnected -- ✅ Failed backup -- ✅ Unpaid invoices threshold -``` - -**Alert Delivery:** -``` -- Dashboard alert badge -- Email notification -- WhatsApp notification (admin) -- Telegram notification (jika aktif) -``` - ---- - -## ⚙️ FITUR AUTOMATION & CRON - -### 1. Cron Jobs Schedule - -**1. Auto Invoice Generation** -``` -Schedule: 1 Jan, Feb, Mar, ... Dec @ 00:01 -Action: Generate monthly invoices untuk semua customer -Config: Automatic di app startup -Detail: -- Hitung promo price / regular price -- Hitung prorata jika bulan pertama -- Hitung tax/PPN jika applicable -- Create invoice record -- Notify customer via WhatsApp -``` - -**2. Auto Isolir** -``` -Schedule: Every day @ 02:00 -Action: Isolir customers yang lewat due date -Config: Otomatis -Detail: -- Cek semua customer dengan status 'active' -- Cek auto_isolate flag = true -- Cek tanggal hari ini >= isolate_day -- Cek ada unpaid invoices -- Suspend ke MikroTik (PPPoE/hotspot) -- Notif customer via WhatsApp -``` - -**3. WhatsApp Reminder** -``` -Schedule: Every day @ 09:00 -Action: Send billing reminder (H-1 isolir) -Config: Enable whatsapp_auto_billing_enabled = true -Detail: -- Cek customers yg isolir besok -- Send reminder message -- Template: tagihan amount, due date, payment link -- Delay 3-5 detik antar pesan (hindari spam) -``` - -**4. Night Mode Switch (Jam Kalong)** -``` -Schedule: 00:00 (midnight) & 06:00 (pagi) -Action: Ganti PPPoE profile malam/siang -Config: Per paket, if use_night_mode = true -Detail: -- 00:00: Switch ke night_profile (contoh: 20Mbps) -- 06:00: Switch ke day_profile (contoh: 10Mbps) -- Custom time possible -``` - -**5. FUP Check (Fair Usage Policy)** -``` -Schedule: Every hour @ 00 (00:00, 01:00, 02:00, ...) -Action: Check monthly data usage vs FUP limit -Config: Per paket, if use_fup = true -Detail: -- Cek total data used bulan ini -- Jika > fup_limit_gb: switch ke fup_profile -- Profile FUP usually slower (contoh: 1Mbps) -- Revert ke normal profile next month (1 Jan) -``` - -**6. Usage Sync** -``` -Schedule: Every 10 minutes -Action: Sync PPPoE traffic dari MikroTik -Config: Enable usage_tracking_enabled = true -Detail: -- Query sesi PPPoE aktif dari MikroTik -- Aggregate bytes_in/out -- Store di customer_usage table -- Accumulate untuk FUP checking -``` - -**7. Backup Database** -``` -Schedule: Daily @ 02:00 (configurable) -Action: Backup database billing.db -Config: Enable auto_backup_enabled = true -Detail: -- Copy database/billing.db → backups/ -- Timestamp: billing-YYYYMMDD-HHMMSS.db -- Keep latest N backups (retention_days) -- Delete old backup automatically -``` - ---- - -### 2. Manual Trigger - -**Admin bisa manual trigger:** -``` -/admin/billing/generate-invoices → Generate now -/admin/isolate-customers → Run isolir check -/admin/whatsapp/send-reminder → Send broadcast -/admin/backup/create → Backup now -``` - ---- - -## 👨💼 FITUR INTERNAL USER MANAGEMENT - -### 1. User Roles - -**Role Hierarchy:** -``` -1. Super Admin (Tertinggi) - - Full access semua fitur - - User management - - Settings & configuration - - Audit trail access - -2. Admin - - Customer management - - Billing & payment - - MikroTik & device management - - WhatsApp administration - - Limited setting access - -3. Kasir (Cashier) - - Payment recording only - - Invoice marking (paid/unpaid) - - Report viewing (finance) - -4. Teknisi (Technician) - - Ticket management - - Device configuration - - Customer support - - Map & location - - No payment/billing access - -5. Kolektor (Collector) - - View customer billing - - Create payment requests - - No payment mark (approval flow) - -6. Agent/Agen (Sales) - - Pembayaran dari saldo agent - - Voucher sales - - Pulsa/data sales - - No admin/config access -``` - ---- - -### 2. User Data - -**User Record:** -```javascript -{ - id: number, - username: string, - password_hash: string, - role: 'superadmin'|'admin'|'kasir'|'tech'|'collector'|'agent', - name: string, - email: string, - phone: string, - area: string, // For tech/collector scope - is_active: boolean, - created_at: datetime, - last_login: datetime -} -``` - ---- - -### 3. Access Control - -**Portal Restrictions:** -``` -Superadmin: -- /admin (all features) -- /finance (all features) -- /settings (system settings) -- /audit-trail - -Admin: -- /admin (except system settings) -- /finance (reports only) -- /settings (limited) - -Kasir: -- /admin/invoices -- /admin/payments -- /finance (read-only) - -Teknisi: -- /tech (all features) -- /admin/tickets (read-write) - -Kolektor: -- /collector (all features) - -Agent: -- /agent (all features) - -Pelanggan: -- /customer (self-service) -``` - ---- - -### 4. Audit Trail - -**Logged Actions:** -``` -Sensitive actions logged: -- User login/logout -- Invoice mark as paid -- Customer isolir/unisolir -- Payment manual input -- SSID/password change -- Settings modification -- Backup creation -- User creation/modification -- Bulk operations -``` - -**Audit Record:** -```javascript -{ - id: number, - user_id: number, - user_role: string, - action: string, // 'invoice_paid', 'customer_isolir', dll - resource_type: string, // 'invoice', 'customer', 'device' - resource_id: number, - changes: object, // Before/after data - timestamp: datetime, - ip_address: string, - status: 'success'|'fail' -} -``` - ---- - -## 📱 FITUR MULTI-LANGUAGE (i18n) - -**Supported Languages:** -``` -- English (en) -- Indonesian (id) -``` - -**Implementation:** -``` -config/i18n.js: -- Load translation files from locales/ -- locales/en.json -- locales/id.json - -Usage: -- Query parameter: ?lang=id -- Route: /lang/id (set session) -- Session key: req.session.lang -- Template helper: res.locals.t('key', 'fallback') -``` - -**EJS Usage:** -```ejs - -