From b2b57296288564df385b40ae1e3d931e2c38d69f Mon Sep 17 00:00:00 2001 From: sigma Date: Tue, 14 Apr 2026 01:01:51 +0700 Subject: [PATCH 01/27] update comiit changes and adding issue.md --- docker-compose.yml | 138 +++ eslint.config.mjs | 11 + next.config.ts | 3 + prompt/DEPLOY_CLOUDFLARE.md | 116 ++ prompt/INDEX.md | 47 + prompt/PRISMA_PROJECT_PROMPT.md | 1023 +++++++++++++++++ prompt/README.md | 189 +++ prompt/TESTING_REPORT.md | 382 ++++++ prompt/datasccience prisma.txt | 17 + public/api/database/keuangan-monthly.json | 166 ++- public/api/database/keuangan-summary.json | 42 +- scripts/bot-runner.ps1 | 68 +- scripts/data-store.json | 2 +- scripts/feedback-log.json | 31 + scripts/knowledge-base.json | 80 ++ scripts/learning-engine.ts | 331 ++++++ scripts/setup-autostart.ps1 | 48 + scripts/start-bot.bat | 19 + scripts/telegram-bot.ts | 189 ++- services/ai-service/Dockerfile | 8 + services/ai-service/index.js | 165 +++ services/ai-service/package.json | 14 + services/gateway/Dockerfile | 7 + services/gateway/index.js | 107 ++ services/gateway/package.json | 15 + services/keamanan-service/Dockerfile | 9 + services/keamanan-service/index.js | 103 ++ services/keamanan-service/package.json | 15 + services/keuangan-service/Dockerfile | 9 + services/keuangan-service/index.js | 74 ++ services/keuangan-service/package.json | 14 + services/surat-service/Dockerfile | 8 + services/surat-service/index.js | 88 ++ services/surat-service/package.json | 14 + services/warga-service/Dockerfile | 9 + services/warga-service/index.js | 135 +++ services/warga-service/package.json | 15 + src/Services/ServiceRegistry.ts | 121 ++ src/Services/api/AIApiClient.ts | 48 + src/Services/api/ApiClient.ts | 131 +++ src/Services/api/KeamananApiClient.ts | 28 + src/Services/api/KeuanganApiClient.ts | 32 + src/Services/api/WargaApiClient.ts | 45 + src/Services/local/MockDataSource.ts | 44 + src/Services/local/SqliteDataSource.ts | 68 ++ src/app/_api-disabled/chat/route.ts | 177 --- src/app/_api-disabled/finance/route.ts | 56 - src/app/_api-disabled/health/route.ts | 47 - src/app/_api-disabled/middleware.ts | 156 --- src/app/_api-disabled/monitoring/route.ts | 74 -- .../_api-disabled/security-reports/route.ts | 129 --- src/app/_api-disabled/warga/route.ts | 122 -- src/app/_api-disabled/ws/route.ts | 139 --- src/app/keuangan/laporan/page.tsx | 69 +- src/app/layanan/administrasi/page.tsx | 69 +- src/app/layanan/page.tsx | 45 +- src/app/surat/keamanan/page.tsx | 79 +- src/app/surat/page.tsx | 66 +- src/components/chat/chatbot.tsx | 5 +- src/components/home/administration-hub.tsx | 37 +- src/components/layout/footer.tsx | 2 +- src/models/entities/Keamanan.ts | 110 ++ src/models/entities/Keuangan.ts | 99 ++ src/models/entities/Surat.ts | 83 ++ src/models/entities/User.ts | 90 ++ src/models/entities/Warga.ts | 69 ++ src/models/mappers/KeuanganMapper.ts | 120 ++ src/models/mappers/WargaMapper.ts | 102 ++ src/models/repositories/BaseRepository.ts | 96 ++ src/models/repositories/KeamananRepository.ts | 109 ++ src/models/repositories/KeuanganRepository.ts | 106 ++ src/models/repositories/SuratRepository.ts | 79 ++ src/models/repositories/WargaRepository.ts | 114 ++ src/viewmodels/useAIViewModel.ts | 128 +++ src/viewmodels/useAuthViewModel.ts | 183 +++ src/viewmodels/useDashboardViewModel.ts | 83 ++ src/viewmodels/useKeamananViewModel.ts | 117 ++ src/viewmodels/useKeuanganViewModel.ts | 120 ++ src/viewmodels/useSuratViewModel.ts | 151 +++ src/viewmodels/useWargaViewModel.ts | 120 ++ 80 files changed, 6399 insertions(+), 1180 deletions(-) create mode 100644 docker-compose.yml create mode 100644 prompt/DEPLOY_CLOUDFLARE.md create mode 100644 prompt/INDEX.md create mode 100644 prompt/PRISMA_PROJECT_PROMPT.md create mode 100644 prompt/README.md create mode 100644 prompt/TESTING_REPORT.md create mode 100644 prompt/datasccience prisma.txt create mode 100644 scripts/feedback-log.json create mode 100644 scripts/knowledge-base.json create mode 100644 scripts/learning-engine.ts create mode 100644 scripts/setup-autostart.ps1 create mode 100644 scripts/start-bot.bat create mode 100644 services/ai-service/Dockerfile create mode 100644 services/ai-service/index.js create mode 100644 services/ai-service/package.json create mode 100644 services/gateway/Dockerfile create mode 100644 services/gateway/index.js create mode 100644 services/gateway/package.json create mode 100644 services/keamanan-service/Dockerfile create mode 100644 services/keamanan-service/index.js create mode 100644 services/keamanan-service/package.json create mode 100644 services/keuangan-service/Dockerfile create mode 100644 services/keuangan-service/index.js create mode 100644 services/keuangan-service/package.json create mode 100644 services/surat-service/Dockerfile create mode 100644 services/surat-service/index.js create mode 100644 services/surat-service/package.json create mode 100644 services/warga-service/Dockerfile create mode 100644 services/warga-service/index.js create mode 100644 services/warga-service/package.json create mode 100644 src/Services/ServiceRegistry.ts create mode 100644 src/Services/api/AIApiClient.ts create mode 100644 src/Services/api/ApiClient.ts create mode 100644 src/Services/api/KeamananApiClient.ts create mode 100644 src/Services/api/KeuanganApiClient.ts create mode 100644 src/Services/api/WargaApiClient.ts create mode 100644 src/Services/local/MockDataSource.ts create mode 100644 src/Services/local/SqliteDataSource.ts delete mode 100644 src/app/_api-disabled/chat/route.ts delete mode 100644 src/app/_api-disabled/finance/route.ts delete mode 100644 src/app/_api-disabled/health/route.ts delete mode 100644 src/app/_api-disabled/middleware.ts delete mode 100644 src/app/_api-disabled/monitoring/route.ts delete mode 100644 src/app/_api-disabled/security-reports/route.ts delete mode 100644 src/app/_api-disabled/warga/route.ts delete mode 100644 src/app/_api-disabled/ws/route.ts create mode 100644 src/models/entities/Keamanan.ts create mode 100644 src/models/entities/Keuangan.ts create mode 100644 src/models/entities/Surat.ts create mode 100644 src/models/entities/User.ts create mode 100644 src/models/entities/Warga.ts create mode 100644 src/models/mappers/KeuanganMapper.ts create mode 100644 src/models/mappers/WargaMapper.ts create mode 100644 src/models/repositories/BaseRepository.ts create mode 100644 src/models/repositories/KeamananRepository.ts create mode 100644 src/models/repositories/KeuanganRepository.ts create mode 100644 src/models/repositories/SuratRepository.ts create mode 100644 src/models/repositories/WargaRepository.ts create mode 100644 src/viewmodels/useAIViewModel.ts create mode 100644 src/viewmodels/useAuthViewModel.ts create mode 100644 src/viewmodels/useDashboardViewModel.ts create mode 100644 src/viewmodels/useKeamananViewModel.ts create mode 100644 src/viewmodels/useKeuanganViewModel.ts create mode 100644 src/viewmodels/useSuratViewModel.ts create mode 100644 src/viewmodels/useWargaViewModel.ts diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..9f6f505 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,138 @@ +version: '3.9' + +services: + # ─── API Gateway ─────────────────────────────────────── + gateway: + build: + context: ./services/gateway + dockerfile: Dockerfile + ports: + - "4000:4000" + environment: + - NODE_ENV=production + - PORT=4000 + - WARGA_SERVICE_URL=http://warga-service:4001 + - KEUANGAN_SERVICE_URL=http://keuangan-service:4002 + - KEAMANAN_SERVICE_URL=http://keamanan-service:4003 + - SURAT_SERVICE_URL=http://surat-service:4004 + - AI_SERVICE_URL=http://ai-service:4005 + - CORS_ORIGINS=http://localhost:3000,https://prisma-rt04.pages.dev + depends_on: + - warga-service + - keuangan-service + - keamanan-service + - surat-service + - ai-service + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:4000/health"] + interval: 30s + timeout: 5s + retries: 3 + networks: + - prisma-network + + # ─── Domain Services ─────────────────────────────────── + warga-service: + build: + context: ./services/warga-service + dockerfile: Dockerfile + ports: + - "4001:4001" + environment: + - NODE_ENV=production + - PORT=4001 + volumes: + - warga-data:/app/data + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:4001/health"] + interval: 30s + timeout: 5s + retries: 3 + networks: + - prisma-network + + keuangan-service: + build: + context: ./services/keuangan-service + dockerfile: Dockerfile + ports: + - "4002:4002" + environment: + - NODE_ENV=production + - PORT=4002 + volumes: + - keuangan-data:/app/data + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:4002/health"] + interval: 30s + timeout: 5s + retries: 3 + networks: + - prisma-network + + keamanan-service: + build: + context: ./services/keamanan-service + dockerfile: Dockerfile + ports: + - "4003:4003" + environment: + - NODE_ENV=production + - PORT=4003 + volumes: + - keamanan-data:/app/data + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:4003/health"] + interval: 30s + timeout: 5s + retries: 3 + networks: + - prisma-network + + surat-service: + build: + context: ./services/surat-service + dockerfile: Dockerfile + ports: + - "4004:4004" + environment: + - NODE_ENV=production + - PORT=4004 + volumes: + - surat-data:/app/data + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:4004/health"] + interval: 30s + timeout: 5s + retries: 3 + networks: + - prisma-network + + ai-service: + build: + context: ./services/ai-service + dockerfile: Dockerfile + ports: + - "4005:4005" + environment: + - NODE_ENV=production + - PORT=4005 + - OLLAMA_API_URL=http://host.docker.internal:11434/api/chat + - OLLAMA_MODEL=llama3.2:1b + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:4005/health"] + interval: 30s + timeout: 5s + retries: 3 + networks: + - prisma-network + +networks: + prisma-network: + driver: bridge + +volumes: + warga-data: + keuangan-data: + keamanan-data: + surat-data: diff --git a/eslint.config.mjs b/eslint.config.mjs index 05e726d..3fba119 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -5,6 +5,15 @@ import nextTs from "eslint-config-next/typescript"; const eslintConfig = defineConfig([ ...nextVitals, ...nextTs, + { + rules: { + // Allow _-prefixed params (standard for intentionally unused interface args) + "@typescript-eslint/no-unused-vars": ["warn", { + argsIgnorePattern: "^_", + varsIgnorePattern: "^_", + }], + }, + }, // Override default ignores of eslint-config-next. globalIgnores([ // Default ignores of eslint-config-next: @@ -12,6 +21,8 @@ const eslintConfig = defineConfig([ "out/**", "build/**", "next-env.d.ts", + // Standalone microservices — CommonJS, not subject to Next.js rules + "services/**", ]), ]); diff --git a/next.config.ts b/next.config.ts index 81180b5..c34b057 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,6 +1,9 @@ import type { NextConfig } from 'next'; import withSerwistInit from '@serwist/next'; +// Suppress harmless Turbopack warning — Serwist is already disabled in non-production via `disable` flag +process.env.SERWIST_SUPPRESS_TURBOPACK_WARNING = '1'; + const withSerwist = withSerwistInit({ swSrc: 'src/app/sw.ts', swDest: 'public/sw.js', diff --git a/prompt/DEPLOY_CLOUDFLARE.md b/prompt/DEPLOY_CLOUDFLARE.md new file mode 100644 index 0000000..20dcec3 --- /dev/null +++ b/prompt/DEPLOY_CLOUDFLARE.md @@ -0,0 +1,116 @@ +# Panduan Deploy ke Cloudflare Pages + +## Persiapan + +### 1. Buat Akun Cloudflare (Jika Belum Punya) +- Kunjungi https://dash.cloudflare.com/sign-up +- Daftar dengan email + +### 2. Build Project Lokal +```bash +npm run build +``` +Hasil build akan ada di folder `out/` + +--- + +## Opsi A: Deploy via Git (Rekomendasi) + +### Langkah 1: Push ke GitHub/GitLab +```bash +git add . +git commit -m "Ready for Cloudflare Pages deployment" +git push origin main +``` + +### Langkah 2: Connect di Cloudflare +1. Buka https://dash.cloudflare.com +2. Pilih **Workers & Pages** di sidebar +3. Klik **Create application** → **Pages** +4. Pilih **Connect to Git** +5. Authorize dan pilih repository Anda + +### Langkah 3: Konfigurasi Build +- **Framework preset**: Next.js (Static HTML Export) +- **Build command**: `npm run build` +- **Build output directory**: `out` +- **Root directory**: `/` (kosongkan) + +### Langkah 4: Deploy +- Klik **Save and Deploy** +- Tunggu build selesai (~2-3 menit) +- Akses site di: `https://[project-name].pages.dev` + +--- + +## Opsi B: Deploy Manual (Drag & Drop) + +### Langkah 1: Build +```bash +npm run build +``` + +### Langkah 2: Upload +1. Buka https://dash.cloudflare.com +2. Pilih **Workers & Pages** → **Create application** → **Pages** +3. Pilih **Upload assets** +4. Drag & drop folder `out/` ke area upload +5. Klik **Deploy site** + +--- + +## Opsi C: Deploy via Wrangler CLI + +### Langkah 1: Install Wrangler +```bash +npm install -g wrangler +``` + +### Langkah 2: Login +```bash +wrangler login +``` + +### Langkah 3: Deploy +```bash +npm run build +npx wrangler pages deploy out --project-name=prisma-rt04 +``` + +--- + +## Custom Domain (Opsional) + +1. Di dashboard Cloudflare Pages, pilih project Anda +2. Klik tab **Custom domains** +3. Klik **Set up a custom domain** +4. Masukkan domain Anda (misal: `prisma-rt04.com`) +5. Ikuti instruksi DNS + +--- + +## Environment Variables (Jika Diperlukan) + +1. Di dashboard, pilih project → **Settings** → **Environment variables** +2. Tambahkan variabel yang diperlukan (jika ada) + +--- + +## Troubleshooting + +### Error: 404 pada halaman selain homepage +- Pastikan `trailingSlash: true` di `next.config.ts` ✅ (sudah dikonfigurasi) + +### Error: Asset tidak ditemukan +- Pastikan folder `public/` ter-include dalam build + +### Build gagal +- Cek log build di dashboard Cloudflare +- Pastikan Node.js version compatible (gunakan v18+) + +--- + +## Tips +- Setiap push ke branch `main` akan auto-deploy +- Preview deployment tersedia untuk pull request +- Analytics gratis tersedia di dashboard diff --git a/prompt/INDEX.md b/prompt/INDEX.md new file mode 100644 index 0000000..f741cec --- /dev/null +++ b/prompt/INDEX.md @@ -0,0 +1,47 @@ +# 📚 PRISMA — Dokumentasi Proyek untuk Jurnal & Makalah + +> **Folder ini berisi kumpulan dokumen teknis proyek PRISMA** yang disusun untuk keperluan penulisan jurnal akademik, makalah, paper, dan dokumentasi resmi proyek. + +--- + +## 📋 Daftar Dokumen + +| # | File | Deskripsi | Halaman / Baris | +|---|------|-----------|-----------------| +| 1 | [PRISMA_PROJECT_PROMPT.md](./PRISMA_PROJECT_PROMPT.md) | **Prompt Terstruktur Full Lifecycle** — Arsitektur, desain UI/UX, build, development, security, database schema, API, AI, testing, deployment | ~1024 baris | +| 2 | [README.md](./README.md) | **Gambaran Umum Proyek** — Tech stack, database, UI/UX, scalability, optimization, security, AI agents, quick start, API reference | ~190 baris | +| 3 | [TESTING_REPORT.md](./TESTING_REPORT.md) | **Laporan Testing Komprehensif** — PortSwigger web security, API testing, ISTQB Foundation test cases, defect log | ~383 baris | +| 4 | [CREDENTIALS.md](./CREDENTIALS.md) | **Developer Credentials** — Akun demo untuk testing (admin, sekretaris, bendahara, warga, tamu) | ~58 baris | +| 5 | [DEPLOY_CLOUDFLARE.md](./DEPLOY_CLOUDFLARE.md) | **Panduan Deployment** — Deploy via Git, manual upload, Wrangler CLI ke Cloudflare Pages | ~117 baris | +| 6 | [datasccience prisma.txt](./datasccience%20prisma.txt) | **Kebutuhan Data Science** — Spesifikasi AI/ML (deep learning, NLP, computer vision, analisis prediktif) | ~17 baris | + +--- + +## 🗂️ Panduan Penggunaan untuk Jurnal/Paper + +### Bab yang Dapat Disusun dari Dokumen Ini + +| Bab Jurnal/Paper | Sumber Dokumen | +|-------------------|----------------| +| **BAB I — Pendahuluan** | `README.md` (bagian identitas, tujuan, tech stack) | +| **BAB II — Tinjauan Pustaka** | `PRISMA_PROJECT_PROMPT.md` (arsitektur, framework, design system) | +| **BAB III — Metodologi** | `PRISMA_PROJECT_PROMPT.md` (development guidelines, data flow, security framework) | +| **BAB IV — Perancangan Sistem** | `PRISMA_PROJECT_PROMPT.md` (database schema, ERD, API layer, arsitektur diagram) | +| **BAB V — Implementasi** | `DEPLOY_CLOUDFLARE.md` + `PRISMA_PROJECT_PROMPT.md` (build config, deployment) | +| **BAB VI — Pengujian** | `TESTING_REPORT.md` (security testing, API testing, ISTQB test cases) | +| **BAB VII — Analisis AI** | `datasccience prisma.txt` + `PRISMA_PROJECT_PROMPT.md` (AI agents, NLP, computer vision) | +| **Lampiran** | `CREDENTIALS.md` (demo credentials untuk reviewer) | + +--- + +## ⚠️ Catatan Penting + +> [!CAUTION] +> File `CREDENTIALS.md` mengandung informasi login demo. **JANGAN** disertakan dalam publikasi jurnal publik. + +> [!NOTE] +> Semua dokumen ini adalah salinan dari file root proyek. File asli tetap berada di direktori root `prisma/`. + +--- + +*Terakhir diperbarui: 27 Maret 2026* diff --git a/prompt/PRISMA_PROJECT_PROMPT.md b/prompt/PRISMA_PROJECT_PROMPT.md new file mode 100644 index 0000000..5267d45 --- /dev/null +++ b/prompt/PRISMA_PROJECT_PROMPT.md @@ -0,0 +1,1023 @@ +# 🏛️ PRISMA — Platform Informasi & Sistem Manajemen RT 04 +## Structured Project Prompt — Full Lifecycle Documentation + +> **Dokumen ini adalah prompt terstruktur, detail, dan spesifik** yang mencakup seluruh siklus hidup proyek PRISMA: +> Kerangka → Desain → Build → Develop → Maintain → Security → Database Schema + +--- + +## 📋 Daftar Isi + +1. [Gambaran Umum Proyek](#1-gambaran-umum-proyek) +2. [Arsitektur & Kerangka Sistem](#2-arsitektur--kerangka-sistem) +3. [Desain UI/UX Web](#3-desain-uiux-web) +4. [Build & Konfigurasi](#4-build--konfigurasi) +5. [Development Guidelines](#5-development-guidelines) +6. [Maintenance & Operasional](#6-maintenance--operasional) +7. [Security Framework](#7-security-framework) +8. [Database Schema Design](#8-database-schema-design) +9. [API & Service Layer](#9-api--service-layer) +10. [AI & Bot Integration](#10-ai--bot-integration) +11. [Testing Strategy](#11-testing-strategy) +12. [Deployment Pipeline](#12-deployment-pipeline) + +--- + +## 1. Gambaran Umum Proyek + +### 1.1 Identitas Proyek + +| Atribut | Detail | +|---|---| +| **Nama Proyek** | PRISMA (Platform Informasi & Sistem Manajemen RT 04) | +| **Versi** | 0.1.0 | +| **Repositori** | `github.com/ProgrammingDevelopment/PRISMA` | +| **Domain** | Tata kelola RT/RW digital berbasis AI | +| **Target User** | Warga RT 04/RW 09, Pengurus RT, Staff Administrasi | +| **Lokasi** | Kelurahan Kemayoran, Jakarta Pusat | + +### 1.2 Tujuan Proyek + +1. **Digitalisasi Administrasi** — Menggantikan proses manual pencatatan warga, surat-menyurat, dan kas RT menjadi digital. +2. **Transparansi Keuangan** — Membuka akses real-time data keuangan kas RT kepada seluruh warga. +3. **Keamanan Lingkungan** — Menyediakan sistem pelaporan insiden terintegrasi dengan notifikasi instan. +4. **Pelayanan AI** — Menghadirkan asisten virtual cerdas (Siaga) via web chatbot dan Telegram bot. +5. **Aksesibilitas** — Dapat diakses dari smartphone (PWA), tablet, dan desktop oleh seluruh lapisan usia warga. + +### 1.3 Tech Stack Summary + +``` +┌─────────────────────────────────────────────────────┐ +│ PRISMA STACK │ +├──────────────┬──────────────────────────────────────┤ +│ Frontend │ Next.js 16.1.4, React 19, TypeScript │ +│ Styling │ Tailwind CSS v4, PostCSS, Framer Mo. │ +│ Component │ Radix UI Primitives (@radix-ui/*) │ +│ State/Theme │ next-themes, clsx, tailwind-merge │ +│ Database │ sql.js (SQLite in-browser), Supabase │ +│ AI Frontend │ @google/generative-ai, Ollama Client │ +│ AI Backend │ Python FastAPI + Ollama LLM │ +│ Bot Engine │ node-telegram-bot-api + pdfkit │ +│ PWA │ @serwist/next (Service Worker) │ +│ Testing │ Vitest + @testing-library/react │ +│ Security │ bcryptjs, dompurify, xss, sanitize │ +│ Deploy │ Cloudflare Pages, Vercel │ +│ I18n │ next-intl (ID, EN, ZH) │ +│ SEO │ next-sitemap │ +└──────────────┴──────────────────────────────────────┘ +``` + +--- + +## 2. Arsitektur & Kerangka Sistem + +### 2.1 Arsitektur Diagram + +```mermaid +graph TB + subgraph Client["🌐 Client Layer"] + WEB["Next.js Web App
(Port 3000)"] + PWA["PWA / Mobile Browser"] + TG["Telegram Bot Client"] + end + + subgraph Presentation["🎨 Presentation (Next.js App Router)"] + PAGES["23 Pages/Routes"] + COMP["Reusable Components"] + THEME["Theme System
Dark/Light Mode"] + end + + subgraph Services["⚙️ Service Layer"] + DBSVC["databaseService.ts"] + AISVC["ai-service.ts"] + SECSVC["security.ts"] + HOOKS["security-hooks.ts"] + end + + subgraph Data["🗄️ Data Layer"] + SQLITE["sql.js (SQLite)"] + MOCK["MockDB (localStorage)"] + SUPA["Supabase (Cloud)"] + end + + subgraph AI["🤖 AI Layer"] + OLLAMA["Ollama LLM Server
(Port 11434)"] + FASTAPI["FastAPI Backend
(Port 8000)"] + RAG["RAG Chat Backend
(Port 8001)"] + end + + subgraph Bot["📱 Bot Layer"] + TGBOT["telegram-bot.ts"] + PDFGEN["PDFKit Generator"] + DSTORE["data-store.json"] + end + + Client --> Presentation + Presentation --> Services + Services --> Data + Services --> AI + TG --> Bot + Bot --> OLLAMA + Bot --> DSTORE + Bot --> PDFGEN +``` + +### 2.2 Struktur Direktori + +``` +prisma/ +├── src/ +│ ├── app/ # Next.js App Router (Pages & Routes) +│ │ ├── page.tsx # Landing/Dashboard Page +│ │ ├── layout.tsx # Root Layout + Security Init +│ │ ├── globals.css # Global Design Tokens (Tailwind v4) +│ │ ├── admin/ # Admin Panel +│ │ │ ├── page.tsx # Admin Dashboard +│ │ │ ├── audit/page.tsx # Audit Log Viewer +│ │ │ ├── files/page.tsx # File Manager +│ │ │ ├── infrastruktur/page.tsx# Infrastructure Management +│ │ │ └── login/page.tsx # Admin Login +│ │ ├── auth/ # Authentication +│ │ │ ├── login/page.tsx # User Login +│ │ │ └── register/page.tsx # User Registration +│ │ ├── galeri/page.tsx # Photo Gallery +│ │ ├── keuangan/ # Financial Module +│ │ │ ├── laporan/page.tsx # Financial Reports +│ │ │ ├── iuran/page.tsx # Monthly Dues +│ │ │ ├── pembayaran/page.tsx # Payment Processing +│ │ │ ├── custom/page.tsx # Custom Reports +│ │ │ ├── event-budget/page.tsx # Event Budget +│ │ │ └── share/page.tsx # Share Reports +│ │ ├── layanan/ # Service Center +│ │ │ ├── page.tsx # Service Hub +│ │ │ └── administrasi/page.tsx # Administration Services +│ │ ├── surat/ # Document Management +│ │ │ ├── page.tsx # Letter Templates +│ │ │ └── keamanan/page.tsx # Security Report Form +│ │ ├── profile/page.tsx # User Profile +│ │ ├── search/page.tsx # Search Page +│ │ ├── settings/database/page.tsx# Database Settings +│ │ ├── telegram-webapp/page.tsx # Telegram WebApp View +│ │ ├── sw.ts # Service Worker (Serwist) +│ │ └── manifest.ts # PWA Manifest +│ ├── components/ # Reusable UI Components +│ │ ├── chat/chatbot.tsx # AI Chatbot Widget (Floating) +│ │ ├── home/ # Landing Page Components +│ │ ├── layout/ # Navbar, Sidebar, Footer +│ │ ├── surat/ # Letter Form Components +│ │ ├── ui/ # Radix UI Primitives +│ │ ├── pwa-install-prompt.tsx # PWA Install Banner +│ │ ├── theme-provider.tsx # Dark/Light Mode Provider +│ │ ├── theme-toggle.tsx # Theme Switch Button +│ │ └── whatsapp-direct.tsx # WhatsApp Integration +│ ├── Services/ # Business Logic Services +│ │ ├── databaseService.ts # Central DB API (SQLite + MockDB) +│ │ ├── aiService.ts # AI Backend Client +│ │ ├── dataService.ts # Data Transformation +│ │ └── nlpService.ts # NLP Processing Client +│ ├── lib/ # Core Library +│ │ ├── security.ts # OWASP Security Core (567 lines) +│ │ ├── security-hooks.ts # React Security Hooks (346 lines) +│ │ ├── sqliteDB.ts # SQLite In-Browser Engine +│ │ ├── mockDatabase.ts # Mock/Seed Data Fallback +│ │ ├── ai-service.ts # Ollama AI Client +│ │ ├── demo-credentials.ts # Demo Auth Credentials +│ │ ├── financial-utils.ts # Financial Calculations +│ │ ├── performance.ts # Performance Monitoring +│ │ └── strategic-recommendations.ts # AI Recommendations +│ ├── hooks/ # Custom React Hooks +│ │ ├── useSafeNavigation.ts # Safe Navigation Hook +│ │ └── use-click-outside.ts # Click Outside Detection +│ └── config/ +│ └── apiConfig.ts # API URL Configuration +├── scripts/ # Background Scripts +│ ├── telegram-bot.ts # Telegram Bot Engine (787 lines) +│ ├── generate_db.js # SQLite DB Seeder +│ ├── data-store.json # Bot Real-Time Data Store +│ └── bot-runner.ps1 # Bot Startup Script +├── public/ # Static Assets +├── messages/ # i18n Translation Files +├── types/ # TypeScript Type Definitions +├── next.config.ts # Next.js Configuration +├── vitest.config.ts # Test Configuration +├── tsconfig.json # TypeScript Configuration +├── wrangler.json # Cloudflare Pages Config +├── vercel.json # Vercel Config +└── prisma_demo.db # SQLite Demo Database File +``` + +### 2.3 Layer Architecture + +| Layer | Tanggung Jawab | File Utama | +|---|---|---| +| **Presentation** | UI rendering, routing, theme | `src/app/**/*.tsx`, `src/components/**` | +| **Hook** | State management, side effects | `src/hooks/*`, `src/lib/security-hooks.ts` | +| **Service** | Business logic, API orchestration | `src/Services/*` | +| **Data Access** | Database CRUD, query engine | `src/lib/sqliteDB.ts`, `src/lib/mockDatabase.ts` | +| **Security** | Auth, encryption, sanitization | `src/lib/security.ts` | +| **AI/Bot** | LLM integration, bot commands | `src/lib/ai-service.ts`, `scripts/telegram-bot.ts` | + +--- + +## 3. Desain UI/UX Web + +### 3.1 Design System + +``` +┌─────────────────────────────────────────────────────┐ +│ DESIGN SYSTEM │ +├──────────────┬──────────────────────────────────────┤ +│ Framework │ Tailwind CSS v4 (utility-first) │ +│ Components │ Radix UI Primitives (A11y) │ +│ Animations │ Framer Motion (fluid transitions) │ +│ Theming │ next-themes (Dark/Light auto) │ +│ Icons │ Lucide React + React Icons │ +│ Typography │ System fonts, Inter (Google Fonts) │ +│ Approach │ Mobile-First Responsive │ +└──────────────┴──────────────────────────────────────┘ +``` + +### 3.2 Color Palette & Theming + +```css +/* Light Mode — Warm Professional */ +--primary: #0f172a /* Slate 900 (Headers, Nav) */ +--primary-accent: #1e40af /* Blue 800 (CTA, Links) */ +--surface: #ffffff /* White (Cards, Panels) */ +--background: #f8fafc /* Slate 50 (Page BG) */ +--success: #16a34a /* Green 600 */ +--warning: #f59e0b /* Amber 500 */ +--danger: #dc2626 /* Red 600 */ +--text-primary: #1e293b /* Slate 800 */ +--text-secondary: #64748b /* Slate 500 */ + +/* Dark Mode — Deep Professional */ +--primary: #e2e8f0 /* Slate 200 (Headers) */ +--primary-accent: #60a5fa /* Blue 400 */ +--surface: #1e293b /* Slate 800 (Cards) */ +--background: #0f172a /* Slate 900 (Page BG) */ +``` + +### 3.3 Layout Structure + +``` +┌──────────────────────────────────────────────────┐ +│ [≡ NAVBAR] 🏠 PRISMA RT 04 [🔍] [🌙/☀️] [👤] │ +├──────────────────────────────────────────────────┤ +│ │ +│ ┌─ MAIN CONTENT ──────────────────────────────┐ │ +│ │ │ │ +│ │ 📊 Dashboard / Page Content │ │ +│ │ ┌──────┐ ┌──────┐ ┌──────┐ ┌──────┐ │ │ +│ │ │Stat 1│ │Stat 2│ │Stat 3│ │Stat 4│ │ │ +│ │ └──────┘ └──────┘ └──────┘ └──────┘ │ │ +│ │ │ │ +│ │ ┌──── Feature Cards Grid ───────────────┐ │ │ +│ │ │ 💰 Keuangan │ 📝 Surat │ 🚨 Keamanan│ │ │ +│ │ │ 👥 Warga │ 📢 Info │ ⚙️ Pengaturan│ │ │ +│ │ └────────────────────────────────────────┘ │ │ +│ │ │ │ +│ └──────────────────────────────────────────────┘ │ +│ │ +│ ┌─ FLOATING CHATBOT ─┐ │ +│ │ 🤖 Siaga │ │ +│ │ Tanya saya! │ │ +│ └────────────────────┘ │ +├──────────────────────────────────────────────────┤ +│ [FOOTER] © PRISMA RT 04 • Links • Contacts │ +└──────────────────────────────────────────────────┘ +``` + +### 3.4 Halaman/Route Map + +| # | Route | Fungsi | Akses | +|---|---|---|---| +| 1 | `/` | Landing/Dashboard utama | Public | +| 2 | `/auth/login` | Login warga | Public | +| 3 | `/auth/register` | Registrasi warga baru | Public | +| 4 | `/admin` | Panel admin dashboard | Admin | +| 5 | `/admin/login` | Login admin | Public | +| 6 | `/admin/audit` | Audit log viewer | Admin | +| 7 | `/admin/files` | File management | Admin | +| 8 | `/admin/infrastruktur` | Infrastruktur RT | Admin | +| 9 | `/keuangan/laporan` | Laporan keuangan bulanan | Warga | +| 10 | `/keuangan/iuran` | Status iuran warga | Warga | +| 11 | `/keuangan/pembayaran` | Proses pembayaran | Warga | +| 12 | `/keuangan/custom` | Custom financial report | Admin | +| 13 | `/keuangan/event-budget` | Anggaran event RT | Admin | +| 14 | `/keuangan/share` | Share laporan keuangan | Warga | +| 15 | `/layanan` | Hub layanan mandiri | Warga | +| 16 | `/layanan/administrasi` | Administrasi kependudukan | Warga | +| 17 | `/surat` | Template surat RT | Warga | +| 18 | `/surat/keamanan` | Form lapor keamanan | Warga | +| 19 | `/galeri` | Galeri foto RT | Public | +| 20 | `/profile` | Profil pengguna | Warga | +| 21 | `/search` | Pencarian global | Warga | +| 22 | `/settings/database` | Pengaturan database | Admin | +| 23 | `/telegram-webapp` | Telegram WebApp view | Public | + +### 3.5 Komponen Reusable + +| Komponen | Lokasi | Fungsi | +|---|---|---| +| `chatbot.tsx` | `components/chat/` | Floating AI chatbot widget | +| `pwa-install-prompt.tsx` | `components/` | Banner install PWA | +| `theme-provider.tsx` | `components/` | Dark/Light mode context | +| `theme-toggle.tsx` | `components/` | Toggle switch tema | +| `whatsapp-direct.tsx` | `components/` | Quick WA action button | +| `ui/*` | `components/ui/` | Button, Card, Input, Dialog, Accordion, etc. | + +--- + +## 4. Build & Konfigurasi + +### 4.1 Next.js Configuration + +```typescript +// next.config.ts — Key Settings +{ + output: 'export', // Static HTML Export (SSG) + images: { unoptimized: true }, + trailingSlash: true, // URL compatibility + compress: true, // Gzip compression + poweredByHeader: false, // Remove X-Powered-By (security) + turbopack: {}, // Turbopack engine + logging: { fetches: { fullUrl: true } } +} +// + @serwist/next PWA wrapper (Service Worker) +``` + +### 4.2 Build Scripts + +| Script | Perintah | Fungsi | +|---|---|---| +| `dev` | `next dev` | Development server (port 3000) | +| `build` | `next build` | Production build + static export | +| `start` | `next start` | Production server | +| `lint` | `eslint` | Code linting | +| `test` | `vitest run` | Run unit tests | +| `test:watch` | `vitest` | Watch mode testing | +| `test:ci` | `vitest run --reporter=verbose` | CI verbose tests | +| `deploy:cf` | `npm run build && npx wrangler pages deploy out` | Cloudflare Pages deploy | +| `bot` | `ts-node ... scripts/telegram-bot.ts` | Start Telegram bot | + +### 4.3 Environment Variables + +```bash +# .env.local — Web Application +NEXT_PUBLIC_AI_BACKEND_URL="http://localhost:8000" # FastAPI AI Backend +NEXT_PUBLIC_CHAT_API_URL="http://localhost:8001/chat" # RAG Chat Backend +DB_HOST=localhost # Legacy MySQL fallback +DB_PORT=3306 +DB_NAME=admin_rt + +# .env.bot — Telegram Bot +TELEGRAM_BOT_TOKEN= # Bot @mayoran04Bot +OLLAMA_API_URL=http://localhost:11434/api/chat # Ollama LLM endpoint +OLLAMA_MODEL= # Primary AI model +OLLAMA_API_KEY= # API key (if needed) +ADMIN_CHAT_ID= # Admin notification target +NEXT_PUBLIC_AI_BACKEND_URL=http://localhost:3000 # Website monitoring URL +``` + +--- + +## 5. Development Guidelines + +### 5.1 Coding Standards + +| Aspek | Standar | +|---|---| +| **Language** | TypeScript strict mode | +| **Naming** | camelCase (vars/functions), PascalCase (components/types) | +| **Components** | Functional components + hooks only | +| **Imports** | Absolute paths via `@/` alias | +| **State** | React hooks (`useState`, `useCallback`, `useEffect`) | +| **Side Effects** | Custom hooks pattern (e.g., `useSecureAuth`) | +| **Styling** | Tailwind utility classes, `clsx()` for conditionals | +| **Sanitization** | ALL user input MUST pass through `sanitizeInput()` | +| **Error Handling** | try/catch with `logSecurityEvent()` | + +### 5.2 Component Development Pattern + +```typescript +// Template: Server-safe Client Component +"use client" + +import { useState, useCallback } from 'react' +import { sanitizeInput } from '@/lib/security' +import { Button } from '@/components/ui/button' + +interface Props { + // Always define explicit interfaces +} + +export function FeatureComponent({ ...props }: Props) { + const [data, setData] = useState(initial) + + const handleAction = useCallback(async () => { + const sanitized = sanitizeInput(rawInput) // ALWAYS sanitize + // ... business logic + }, [dependencies]) + + return ( +
+ {/* Mobile-first responsive layout */} +
+ ) +} +``` + +### 5.3 Data Flow Pattern + +``` +User Input → sanitizeInput() → Service Layer → Database Layer → Response + │ │ + └── checkRateLimit() ──────────┘ + └── logSecurityEvent() ────────┘ +``` + +--- + +## 6. Maintenance & Operasional + +### 6.1 Monitoring Checklist + +| Item | Tool | Frekuensi | +|---|---|---| +| Website uptime | Telegram Bot auto-ping (5 min interval) | Real-time | +| Bot status | `/status` command | On-demand | +| Security audit log | `getAuditLog()` + Admin panel | Harian | +| Database size | Settings > Database page | Mingguan | +| Dependency updates | `npm audit` | Bulanan | +| SSL certificate | Cloudflare/Vercel auto-managed | Otomatis | + +### 6.2 Backup Strategy + +| Data | Metode | Lokasi Backup | +|---|---|---| +| SQLite Database | `SqliteDB.exportDB()` → download `.db` file | Manual download | +| data-store.json | Git version control | GitHub repository | +| Environment vars | Terpisah dari repo (`.gitignore`) | Secure vault | +| User uploads | Cloudflare/Vercel CDN | CDN edge nodes | + +### 6.3 Performance Targets + +| Metrik | Target | Cara Pencapaian | +|---|---|---| +| First Contentful Paint | < 1.5s | SSG + Turbopack | +| Time to Interactive | < 3s | Code splitting, lazy load | +| Lighthouse Score | > 90 | PWA, compression, semantic HTML | +| API Response Time | < 200ms | SQLite in-memory, debounced save | +| Bot Response Time | < 5s | Ollama streaming, fallback model | + +### 6.4 Scaling Plan + +``` +Level 1 (Current): Monolith SSG + Client SQLite + ↓ +Level 2: Supabase Cloud DB + Edge Functions + ↓ +Level 3: Microservices (Next.js + FastAPI + RAG separated) + ↓ +Level 4: Kubernetes orchestration + dedicated ML serving +``` + +--- + +## 7. Security Framework + +### 7.1 OWASP Top 10 Coverage + +| OWASP | Implementasi di PRISMA | File | +|---|---|---| +| **A01: Broken Access Control** | Role-based auth (`admin/staff/warga`), session fingerprinting | `security.ts` | +| **A02: Cryptographic Failures** | XOR encryption (demo) + bcryptjs hashing, runtime key derivation | `security.ts` | +| **A03: Injection** | `sanitizeInput()` — multi-layer XSS/SQL inject strip, `dompurify`, `xss` lib | `security.ts` | +| **A05: Security Misconfiguration** | `poweredByHeader: false`, console suppression in prod | `next.config.ts` | +| **A07: Auth Failures** | Rate limiting (5 login/min, 5 min block), password strength validator | `security.ts` | +| **A08: Data Integrity** | CSRF token management (`generateCSRFToken`, `validateCSRFToken`) | `security.ts` | +| **A09: Logging Failures** | Audit log system (`logSecurityEvent()`, max 1000 entries) | `security.ts` | + +### 7.2 Security Module Map + +``` +┌─────────────────────────────────────────────────────────┐ +│ security.ts (Core) │ +├─────────────────────────────────────────────────────────┤ +│ ✅ encryptData() / decryptData() — XOR + Base64 │ +│ ✅ secureStorage — Encrypted session │ +│ ✅ generateFingerprint() — Browser-based │ +│ ✅ sanitizeInput() / sanitizeObject()— Multi-layer clean │ +│ ✅ checkRateLimit() / resetRateLimit() │ +│ ✅ maskPhoneNumber/Email/NIK/Name — PII masking │ +│ ✅ storeCredentials/getCredentials — Secure session │ +│ ✅ generateCSRFToken/validateCSRF — Anti-CSRF │ +│ ✅ secureFetch() — Protected HTTP │ +│ ✅ validatePasswordStrength() — Password scoring │ +│ ✅ logSecurityEvent() / getAuditLog()— Audit trail │ +│ ✅ initSecurityProtections() — Anti-clickjack │ +└─────────────────────────────────────────────────────────┘ + +┌─────────────────────────────────────────────────────────┐ +│ security-hooks.ts (React) │ +├─────────────────────────────────────────────────────────┤ +│ ✅ useSecureAuth() — Login/logout + rate limit │ +│ ✅ useDataMasking() — Toggle sensitive data display │ +│ ✅ useSecureForm() — Auto-sanitize form inputs │ +│ ✅ useSecureApi() — Protected API calls │ +│ ✅ usePasswordStrength()— Real-time password scoring │ +│ ✅ useSecureStorage() — Encrypted localStorage hook │ +└─────────────────────────────────────────────────────────┘ +``` + +### 7.3 Bot Security (Telegram) + +| Perlindungan | Implementasi | +|---|---| +| Input Sanitization | `sanitizeBotInput()` — strip `` +**Injection Points:** + +- Login email field → **BLOCKED** (sanitizeInput strips `` + +- **BEFORE FIX:** ⚠️ Null byte could bypass WAF +- **AFTER FIX:** ✅ BLOCKED - null bytes removed + +--- + +#### TC-SEC-002: SQL Injection + +**Test Vector:** `' OR '1'='1' --` +**Injection Points:** + +- Login email field → **BLOCKED** (quotes stripped by sanitizeInput) +- Admin search → **BLOCKED** (parameterized queries in SqliteDB) + +**Test Vector (UNION):** `' UNION SELECT * FROM users --` + +- **RESULT:** ✅ BLOCKED - semicolons and quotes stripped + +**Note:** SQLite runs client-side only (sql.js in browser). No server-side SQL = reduced attack surface. + +--- + +#### TC-SEC-003: CSRF Protection + +**Test Method:** Craft external HTML form targeting PRISMA endpoints + +- **secureFetch()** adds `X-CSRF-Token` header automatically +- **X-Requested-With: XMLHttpRequest** prevents simple CSRF +- **SameSite cookie policy** enforced via CORS `same-origin` +- **RESULT:** ✅ PASS + +--- + +#### TC-SEC-004: Clickjacking + +**Test Method:** Embed PRISMA in `