> ## Documentation Index
> Fetch the complete documentation index at: https://docs.quinnsambal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

<style>
  {`
    [class*="max-w-none"][class*="table"] {
      display: block !important;
      overflow-x: auto !important;
      max-width: 100% !important;
      width: 100% !important;
      flex-grow: 0 !important;
    }
    [class*="max-w-none"][class*="table"] > table {
      width: 100% !important;
      max-width: 100% !important;
      table-layout: fixed !important;
    }
    .mermaid {
      max-width: 100% !important;
      overflow-x: auto !important;
    }
    article svg[role="img"] {
      max-width: 100% !important;
      height: auto !important;
    }
    article img, .prose img {
      max-width: 100% !important;
      height: auto !important;
    }
    img[src*="LOGO"], img[src*="logo"] {
      max-width: 120px !important;
      max-height: 40px !important;
      width: auto !important;
      height: auto !important;
      object-fit: contain !important;
    }
    `}
</style>

***

title: "Arsitektur Sistem"
description: "Dokumentasi komprehensif arsitektur sistem Quinn of Spicy ERP - Multi-tenant, modular, scalable, dan secure"
--------------------------------------------------------------------------------------------------------------------------

# Arsitektur Sistem

Quinn of Spicy ERP adalah sistem ERP (Enterprise Resource Planning) modern yang dirancang khusus untuk industri F\&B (Food & Beverage) di Indonesia. Sistem ini dibangun dengan arsitektur **multi-tenant**, **modular**, dan **cloud-native** yang mampu mendukung operasional bisnis dari skala UMKM hingga enterprise.

## Ringkasan Arsitektur

```mermaid theme={null}
graph TB
    subgraph "Client Layer"
        PWA[PWA Mobile App]
        WEB[Web Dashboard]
        POS[POS Terminal]
    end
    
    subgraph "Application Layer"
        REACT[React 19 Frontend]
        VITE[Vite Build System]
        ROUTER[React Router]
    end
    
    subgraph "Business Logic Layer"
        API[Base44 Server Functions]
        AUTH[Authentication Service]
        RBAC[Role-Based Access Control]
    end
    
    subgraph "Data Layer"
        PG[(PostgreSQL)]
        RLS[Row Level Security]
        CACHE[Redis Cache]
    end
    
    subgraph "Integration Layer"
        AI[AI/ML Services]
        PAY[Payment Gateways]
        WA[WhatsApp API]
        MAP[Maps & Geolocation]
    end
    
    PWA --> REACT
    WEB --> REACT
    POS --> REACT
    REACT --> VITE
    REACT --> ROUTER
    ROUTER --> API
    API --> AUTH
    API --> RBAC
    AUTH --> PG
    RBAC --> RLS
    RLS --> PG
    API --> CACHE
    API --> AI
    API --> PAY
    API --> WA
    API --> MAP
```

## Arsitektur Multi-Tenant

### Konsep Multi-Company

Sistem Quinn of Spicy mendukung **multi-tenancy** dengan isolasi data yang ketat. Setiap perusahaan (tenant) memiliki:

* **Data terisolasi**: Data satu perusahaan tidak dapat diakses oleh perusahaan lain
* **Konfigurasi independen**: Setiap perusahaan dapat mengatur modul, role, dan workflow sendiri
* **Branding kustom**: Logo, warna, dan identitas perusahaan dapat dikustomisasi
* **User management terpisah**: Employee dan role management per perusahaan

### Company ID Isolation

**67% dari 162 entities** dalam sistem memiliki field `company_id` untuk memastikan isolasi data:

| Kategori Entity | Jumlah Entity | Persentase | Contoh |
| - | - | - | - |
| **Core Entities** | 12 | 100% | Company, CompanyMember, CompanyModuleSettings |
| **POS Entities** | 8 | 100% | CompanyPOSTransaction, CompanyPOSProduct, CompanyPOSCategory |
| **Inventory Entities** | 15 | 100% | Product, StockMovement, StockOpname, WarehouseLocation |
| **Manufacturing Entities** | 10 | 100% | ProductionOrder, BillOfMaterials, LotBatch, QualityCase |
| **Finance Entities** | 18 | 100% | Invoice, FinancialRecord, Account, BankAccount |
| **HR Entities** | 12 | 100% | Employee, AttendanceRecord, CompanyPayroll, CompanyLeave |
| **CRM Entities** | 8 | 100% | Customer, CustomerLoyaltyLedger, SalesPipeline |
| **AI Entities** | 6 | 100% | AIAgent, AIAgentRun, AIAgentSchedule |
| **Shared Entities** | 5 | 0% | User, ReferralCode, BlogContent, AboutContent |

### Implementasi Company ID

Setiap entity dengan company\_id memiliki struktur sebagai berikut:

```javascript theme={null}
// Contoh: Product Entity
{
  "id": "prod_abc123",
  "company_id": "comp_xyz789",        // ← Isolasi data
  "name": "Sambal Matah Premium",
  "sku": "SMP-001",
  "category": "sambal",
  "price": 25000,
  "cost": 12000,
  "stock": 150,
  "unit": "botol",
  "created_at": "2026-01-15T08:30:00Z",
  "updated_at": "2026-10-09T14:22:00Z"
}
```

### Security Policy Enforcement

Sistem menerapkan **multiple layers of security** untuk mencegah cross-company data access:

#### Layer 1: Client-Side Validation

```javascript theme={null}
// src/components/utils/companyAccessPolicy.js
export const validateCompanyAccess = (userCompanyId, requestedCompanyId) => {
  if (userCompanyId !== requestedCompanyId) {
    console.error(`Cross-company access attempt: User ${userCompanyId} tried to access ${requestedCompanyId}`);
    throw new SecurityError('Cross-company access denied');
  }
  return true;
};
```

#### Layer 2: Server-Side Policy (Base44 Functions)

```javascript theme={null}
// base44/functions/enforceCompanyAccess/policy.js
export const policy = async (context, params) => {
  const userCompanyId = context.auth?.company_id;
  const requestedCompanyId = params?.company_id;
  
  if (!userCompanyId) {
    throw new Error('User company context not found');
  }
  
  if (userCompanyId !== requestedCompanyId) {
    throw new Error('Access denied: Cross-company data access is prohibited');
  }
  
  return true;
};
```

#### Layer 3: Database Row Level Security (RLS)

```sql theme={null}
-- PostgreSQL RLS Policy (contoh)
CREATE POLICY company_isolation_policy ON products
  USING (company_id = current_setting('app.current_company_id')::uuid);
```

### Data Isolation Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Frontend
    participant API
    participant Database
    
    User->>Frontend: Request data (company_id: ABC)
    Frontend->>Frontend: Validate user company context
    Frontend->>API: GET /api/products?company_id=ABC
    API->>API: Check auth token & company_id
    API->>API: Enforce company access policy
    API->>Database: Query with RLS filter
    Database->>Database: Apply RLS policy
    Database->>API: Return filtered results
    API->>Frontend: Return data (only company ABC)
    Frontend->>User: Display data
```

## Modular Architecture

Sistem dibagi menjadi **8 modul utama** yang saling terintegrasi namun independen:

### 1. POS (Point of Sale) Module

**Tujuan**: Mengelola transaksi penjualan di kasir dan online

**Fitur Utama**:

* **Kasir (Cashier)**: Interface POS untuk transaksi cepat
* **Order Management**: Manajemen pesanan dine-in, takeaway, delivery
* **Payment Processing**: Integrasi multi-payment gateway (Midtrans, Xendit, Stripe, PayPal)
* **Receipt Printing**: Cetak struk via Bluetooth printer
* **Order Queue**: Antrian pesanan real-time
* **Channel Management**: Multi-channel (dine-in, GoFood, GrabFood, ShopeeFood)
* **POS Reports**: Laporan penjualan harian, mingguan, bulanan

**Entities**:

* `CompanyPOSTransaction` - Transaksi POS
* `CompanyPOSProduct` - Produk POS
* `CompanyPOSCategory` - Kategori produk
* `CompanyPOSSettings` - Pengaturan POS
* `CompanyPOSInventory` - Inventory POS

**Server Functions**:

* `finalizeCompanyPOSCashierSale` - Finalisasi transaksi kasir
* `voidCompanyPOSTransaction` - Void transaksi
* `transitionPOSOrderStatus` - Update status order
* `reserveOnlineOrderStock` - Reserve stok order online

### 2. Inventory Module

**Tujuan**: Mengelola stok barang, gudang, dan pergerakan inventory

**Fitur Utama**:

* **Stock Management**: Stok masuk, keluar, transfer
* **Stock Opname**: Stock opname dengan approval workflow
* **Multi-Location**: Multi-gudang dan lokasi penyimpanan
* **Barcode Scanning**: Scan barcode untuk quick entry
* **Discount Management**: Manajemen diskon produk
* **HPP Calculation**: Perhitungan Harga Pokok Penjualan (FIFO/Average)
* **Supplier Management**: Manajemen supplier dan purchase order
* **Stock Alerts**: Notifikasi stok rendah dan anomali

**Entities**:

* `Product` - Master produk
* `StockMovement` - Pergerakan stok
* `StockOpname` - Stock opname records
* `StockTransfer` - Transfer antar lokasi
* `WarehouseLocation` - Lokasi gudang
* `Supplier` - Data supplier
* `PurchaseOrder` - Purchase order

**Server Functions**:

* `processStockInOut` - Proses stok masuk/keluar
* `approveStockOpname` - Approval stock opname
* `transferInventoryLots` - Transfer lot inventory
* `receiveInventoryTransfer` - Terima transfer inventory

### 3. Manufacturing Module

**Tujuan**: Mengelola proses produksi dan manufaktur

**Fitur Utama**:

* **Production Orders**: Manajemen order produksi
* **Bill of Materials (BOM)**: Resep dan komposisi bahan
* **Quality Control**: QC dan inspeksi kualitas
* **HACCP Verification**: Verifikasi HACCP untuk food safety
* **Lot/Batch Tracking**: Tracking lot dan batch produksi
* **Raw Material Management**: Manajemen bahan baku
* **Production Timer**: Timer produksi real-time

**Entities**:

* `ProductionOrder` - Order produksi
* `BillOfMaterials` - BOM/resep
* `LotBatch` - Lot dan batch
* `QualityCase` - Case quality control
* `RawMaterial` - Bahan baku

**Server Functions**:

* `completeProductionBatch` - Selesaikan batch produksi
* `verifyAndReleaseProductionBatch` - Verifikasi dan release batch
* `holdLotBatch` - Hold lot batch
* `releaseLotBatchHold` - Release hold lot batch
* `saveBillOfMaterials` - Simpan BOM

### 4. Finance Module

**Tujuan**: Mengelola keuangan, akuntansi, dan pelaporan finansial

**Fitur Utama**:

* **Invoices**: Faktur penjualan dan pembelian
* **Expenses**: Manajemen pengeluaran
* **Bank Accounts**: Multi-rekening bank
* **General Ledger**: Jurnal umum dan akuntansi
* **Financial Reports**: Laporan laba rugi, neraca, arus kas
* **Budget Planner**: Perencanaan anggaran
* **Financial Goals**: Target keuangan
* **AI Profit Report**: Laporan profit berbasis AI
* **Saldo Management**: Manajemen saldo dan kas

**Entities**:

* `Invoice` - Faktur
* `FinancialRecord` - Catatan keuangan
* `Account` - Akun akuntansi
* `BankAccount` - Rekening bank
* `Budget` - Anggaran
* `CompanyBalance` - Saldo perusahaan

**Server Functions**:

* `generateDraftInvoice` - Generate draft invoice
* `recordCompanyInvoicePayment` - Catat pembayaran invoice
* `extractFinanceData` - Extract data keuangan (AI)
* `financeChatAI` - AI assistant untuk finance

### 5. HR (Human Resources) Module

**Tujuan**: Mengelola karyawan, kehadiran, payroll, dan performa

**Fitur Utama**:

* **Attendance**: Absensi dengan GPS dan foto
* **Payroll**: Perhitungan gaji otomatis
* **Employee Portal**: Portal karyawan self-service
* **Performance Reviews**: Review performa karyawan
* **Recruitment ATS**: Applicant Tracking System
* **Company Leave**: Manajemen cuti
* **Company Loan**: Manajemen pinjaman karyawan

**Entities**:

* `Employee` - Data karyawan
* `AttendanceRecord` - Record kehadiran
* `CompanyPayroll` - Payroll perusahaan
* `CompanyLeave` - Cuti karyawan
* `CompanyLoan` - Pinjaman karyawan
* `Applicant` - Pelamar kerja

**Server Functions**:

* `createCompanyEmployee` - Buat karyawan baru
* `calculatePayroll` - Hitung payroll
* `submitAttendance` - Submit absensi

### 6. CRM (Customer Relationship Management) Module

**Tujuan**: Mengelola pelanggan, membership, dan sales pipeline

**Fitur Utama**:

* **Customer Management**: Database pelanggan
* **Membership**: Program membership dan loyalitas
* **Sales Pipeline**: Pipeline penjualan dengan stages
* **WhatsApp Integration**: Integrasi WhatsApp untuk komunikasi
* **Customer Loyalty**: Program loyalitas dan rewards
* **Company Membership**: Membership level perusahaan

**Entities**:

* `Customer` - Data pelanggan
* `CustomerLoyaltyLedger` - Ledger loyalitas
* `CompanyMember` - Member perusahaan
* `SalesPipeline` - Pipeline penjualan
* `Commission` - Komisi sales

**Server Functions**:

* `createPOSCustomer` - Buat customer dari POS
* `manageCustomerLoyalty` - Kelola loyalitas customer
* `triggerBTTNotifications` - Trigger notifikasi BTT

### 7. AI (Artificial Intelligence) Module

**Tujuan**: Menyediakan fitur AI untuk automasi dan insights

**Fitur Utama**:

* **AI Assistant**: Asisten AI untuk query dan analisis
* **AI Agents**: Agent AI otomatis untuk tugas berulang
* **Content Studio**: Studio untuk generate konten marketing
* **Forecasting**: Prediksi penjualan dan demand
* **AI Profit Report**: Analisis profit berbasis AI
* **Agent Dashboard**: Dashboard monitoring AI agents
* **AI Learning**: Machine learning dari data historis

**Entities**:

* `AIAgent` - Definisi AI agent
* `AIAgentRun` - Execution run AI agent
* `AIAgentSchedule` - Schedule AI agent
* `AIAgentSettings` - Pengaturan AI
* `AIAgentTemplate` - Template AI agent
* `AILearningData` - Data pembelajaran AI

**Server Functions**:

* `executeAIAgent` - Execute AI agent
* `aiAssistantQuery` - Query AI assistant
* `createAIAgentFromChat` - Buat AI agent dari chat
* `runDueAgentSchedules` - Run scheduled agents
* `processAgentTrigger` - Process agent trigger

### 8. Core Module

**Tujuan**: Menyediakan infrastruktur dasar sistem

**Fitur Utama**:

* **Authentication**: Login, register, session management
* **RBAC (Role-Based Access Control)**: Manajemen role dan permission
* **Company Settings**: Pengaturan perusahaan
* **Dashboard**: Dashboard executive dan operational
* **Workspace Management**: Multi-workspace support
* **Offline Mode**: Mode offline dengan sync
* **Notification System**: Sistem notifikasi real-time
* **Audit Trail**: Log semua aktivitas penting

**Entities**:

* `User` - User accounts
* `Company` - Data perusahaan
* `CompanyMember` - Member perusahaan
* `CompanyModuleSettings` - Pengaturan modul
* `AuditLog` - Audit trail
* `Notification` - Notifikasi

**Server Functions**:

* `enforceCompanyAccess` - Enforce company access
* `ensureQuinnCompany` - Ensure company exists
* `getOwnerExecutiveDashboard` - Get executive dashboard data

## Teknologi Stack

### Frontend Technology

| Technology | Version | Purpose | Key Features |
| - | - | - | - |
| **React** | 19.x | UI Framework | Hooks, Context, Concurrent Mode |
| **Vite** | 5.x | Build Tool | Fast HMR, ESM-native, Rollup bundling |
| **React Router** | 6.x | Routing | Dynamic routes, lazy loading, nested routes |
| **Tailwind CSS** | 3.x | Styling | Utility-first, responsive, dark mode |
| **Framer Motion** | 11.x | Animation | Gestures, layout animations, shared layout |
| **PWA** | - | Mobile App | Service Worker, offline, installable |
| **Lucide Icons** | Latest | Icons | 1000+ icons, tree-shakeable |
| **Sonner** | Latest | Toast Notifications | Beautiful, accessible toasts |

### Backend Technology

| Technology | Purpose | Scale | Features |
| - | - | - | - |
| **Base44** | Serverless Platform | 170+ functions | Auto-scaling, edge deployment |
| **PostgreSQL** | Database | 162 entities | RLS, JSONB, full-text search |
| **Redis** | Cache Layer | Session & query cache | Sub-ms latency |
| **BroadcastChannel API** | Real-time Sync | Cross-tab communication | Instant updates |

### Security Stack

| Layer | Technology | Implementation |
| - | - | - |
| **Authentication** | JWT + Session | Token-based auth with refresh |
| **Authorization** | RBAC | Role-based access control |
| **Data Isolation** | RLS | Row-level security in PostgreSQL |
| **API Security** | Policy Functions | Server-side validation |
| **Audit Trail** | AuditLog Entity | Complete activity logging |
| **Encryption** | TLS 1.3 | End-to-end encryption |

### Integration Stack

| Service | Provider | Purpose |
| - | - | - |
| **Payment Gateway** | Midtrans, Xendit, Stripe, PayPal | Payment processing |
| **WhatsApp API** | Wablas | Customer communication |
| **Maps & Geolocation** | Google Maps API | Location services |
| **Cloud Storage** | Cloudinary | Image & file storage |
| **Email Service** | SMTP/SES | Transactional emails |
| **AI/ML** | OpenAI, Custom Models | AI features |

## Data Flow Architecture

### POS Transaction Flow

```mermaid theme={null}
sequenceDiagram
    participant Cashier
    participant POS_UI
    participant API
    participant Inventory
    participant Payment
    participant Receipt
    
    Cashier->>POS_UI: Scan product / Select item
    POS_UI->>API: Get product details
    API->>Inventory: Check stock availability
    Inventory->>API: Return stock status
    API->>POS_UI: Return product info
    POS_UI->>Cashier: Display in cart
    
    Cashier->>POS_UI: Checkout
    POS_UI->>API: Create transaction
    API->>Inventory: Reserve stock
    API->>Payment: Initiate payment
    Payment->>API: Payment confirmation
    API->>Inventory: Deduct stock
    API->>Receipt: Generate receipt
    Receipt->>Cashier: Print receipt
```

### Manufacturing Flow

```mermaid theme={null}
sequenceDiagram
    participant Manager
    participant Production_UI
    participant BOM
    participant Inventory
    participant Production
    participant QC
    
    Manager->>Production_UI: Create production order
    Production_UI->>BOM: Get recipe/components
    BOM->>Production_UI: Return BOM details
    Production_UI->>Inventory: Check raw material stock
    Inventory->>Production_UI: Confirm availability
    
    Manager->>Production_UI: Start production
    Production_UI->>Production: Begin batch
    Production->>Production: Process (with timer)
    Production->>QC: Request quality check
    QC->>Production: QC approved
    Production->>Inventory: Add finished goods
    Inventory->>Manager: Production complete
```

### Inventory Flow

```mermaid theme={null}
stateDiagram-v2
    [*] --> StockIn: Stock masuk (pembelian/produksi)
    StockIn --> StockLevelUpdate: Update level
    StockLevelUpdate --> NormalOperation: Stok tersedia
    
    NormalOperation --> StockOut: Stock keluar (penjualan)
    StockOut --> StockLevelUpdate: Update level
    
    NormalOperation --> StockOpname: Stock opname
    StockOpname --> DiscrepancyCheck: Hitung selisih
    DiscrepancyCheck --> ApprovalWorkflow: Jika ada selisih
    ApprovalWorkflow --> FinalStockUpdate: Approved
    FinalStockUpdate --> NormalOperation: Stok final
    
    NormalOperation --> LowStockAlert: Stok < minimum
    LowStockAlert --> PurchaseOrder: Auto-generate PO
    PurchaseOrder --> StockIn: Supplier delivery
```

### Multi-Tenant Data Isolation Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Frontend
    participant Auth
    participant API
    participant RLS
    participant Database
    
    User->>Frontend: Login (company: ABC)
    Frontend->>Auth: Authenticate
    Auth->>Frontend: Return token + company_id
    Frontend->>API: Request data (with token)
    API->>Auth: Validate token
    Auth->>API: Return user context (company_id: ABC)
    API->>RLS: Set current_company_id = ABC
    RLS->>Database: Apply RLS policy
    Database->>API: Return data (only company ABC)
    API->>Frontend: Return filtered data
    Frontend->>User: Display company-specific data
```

## Performance Architecture

### Performance Metrics

| Metric | Target | Actual | Measurement Method |
| - | - | - | - |
| **Page Load Time** | \< 2s | 1.2s avg | Lighthouse, Web Vitals |
| **API Response Time** | \< 500ms | 280ms avg | Base44 monitoring |
| **Concurrent Users** | 100+ | 150 tested | Load testing |
| **Data Sync Latency** | \< 1s | 500ms | BroadcastChannel API |
| **PWA Install Time** | \< 30s | 15s avg | Manual testing |
| **Offline Mode Uptime** | 99% | 99.5% | Service Worker monitoring |

### Optimization Strategies

#### 1. Code Splitting & Lazy Loading

```javascript theme={null}
// React Router lazy loading
const POS = lazy(() => import('@/pages/pos/POS'));
const Inventory = lazy(() => import('@/pages/inventory/Inventory'));
const Manufacturing = lazy(() => import('@/pages/Manufacturing'));

// Route definition
<Route path="/pos" element={<POS />} />
<Route path="/inventory" element={<Inventory />} />
```

#### 2. Image Optimization

* **Cloudinary CDN**: Automatic image optimization
* **WebP Format**: Modern image format with better compression
* **Lazy Loading**: Images load on demand
* **Responsive Images**: Different sizes for different devices

#### 3. Caching Strategy

```javascript theme={null}
// Global data cache with TTL
const globalCache = {
  products: { data: [], ttl: 300000 }, // 5 minutes
  categories: { data: [], ttl: 600000 }, // 10 minutes
  company: { data: null, ttl: 3600000 } // 1 hour
};
```

#### 4. Bundle Optimization

* **Tree Shaking**: Remove unused code
* **Code Splitting**: Split by route and feature
* **Dynamic Imports**: Load modules on demand
* **Vite Build**: Optimized production builds

### Performance Monitoring

```mermaid theme={null}
graph LR
    A[User Action] --> B[Performance Timer Start]
    B --> C[API Request]
    C --> D[Response Received]
    D --> E[Render Complete]
    E --> F[Performance Timer End]
    F --> G[Send to Analytics]
    G --> H[Dashboard Display]
```

## Deployment Architecture

### Environment Strategy

| Environment | Purpose | URL | Branch |
| - | - | - | - |
| **Development** | Local development | localhost:5173 | feature/\* |
| **Staging** | Pre-production testing | staging.quinnsambal.com | develop |
| **Production** | Live application | app.quinnsambal.com | main |

### Deployment Pipeline

```mermaid theme={null}
graph LR
    A[Developer] -->|Push Code| B[GitHub]
    B -->|Trigger| C[Base44 Build]
    C -->|Build Success| D[Run Tests]
    D -->|Tests Pass| E[Deploy to Staging]
    E -->|Manual Approval| F[Deploy to Production]
    F -->|Success| G[Live Application]
```

### PWA Deployment

Quinn of Spicy dapat diinstall sebagai **Progressive Web App** di:

* **Mobile**: Android (Chrome), iOS (Safari)
* **Desktop**: Windows, macOS, Linux
* **POS Terminal**: Dedicated POS devices

**Benefits**:

* Offline capability
* Fast loading (cached assets)
* Native-like experience
* No app store dependency

### Scaling Strategy

```mermaid theme={null}
graph TB
    subgraph "Horizontal Scaling"
        LB[Load Balancer]
        S1[Server Instance 1]
        S2[Server Instance 2]
        S3[Server Instance 3]
    end
    
    subgraph "Database Scaling"
        PG_PRIMARY[(Primary DB)]
        PG_REPLICA[(Replica DB)]
    end
    
    subgraph "Cache Layer"
        REDIS[Redis Cluster]
    end
    
    LB --> S1
    LB --> S2
    LB --> S3
    S1 --> PG_PRIMARY
    S2 --> PG_PRIMARY
    S3 --> PG_PRIMARY
    PG_PRIMARY --> PG_REPLICA
    S1 --> REDIS
    S2 --> REDIS
    S3 --> REDIS
```

## Security Architecture

### Security Layers

```mermaid theme={null}
graph TB
    subgraph "Layer 1: Network Security"
        TLS[TLS 1.3 Encryption]
        WAF[Web Application Firewall]
        DDoS[DDoS Protection]
    end
    
    subgraph "Layer 2: Application Security"
        AUTH[Authentication - JWT]
        RBAC[Authorization - RBAC]
        INPUT[Input Validation]
        XSS[XSS Protection]
        CSRF[CSRF Protection]
    end
    
    subgraph "Layer 3: Data Security"
        RLS[Row Level Security]
        ENCRYPT[Encryption at Rest]
        BACKUP[Automated Backups]
        AUDIT[Audit Trail]
    end
    
    subgraph "Layer 4: Operational Security"
        MONITOR[Security Monitoring]
        ALERT[Alert System]
        INCIDENT[Incident Response]
    end
    
    TLS --> AUTH
    WAF --> INPUT
    DDoS --> AUTH
    AUTH --> RBAC
    RBAC --> RLS
    INPUT --> XSS
    INPUT --> CSRF
    RLS --> ENCRYPT
    ENCRYPT --> BACKUP
    BACKUP --> AUDIT
    AUDIT --> MONITOR
    MONITOR --> ALERT
    ALERT --> INCIDENT
```

### Authentication Flow

```mermaid theme={null}
sequenceDiagram
    participant User
    participant Frontend
    participant Auth API
    participant Database
    participant Session
    
    User->>Frontend: Enter credentials
    Frontend->>Auth API: POST /auth/login
    Auth API->>Database: Verify credentials
    Database->>Auth API: User found
    Auth API->>Auth API: Generate JWT token
    Auth API->>Session: Store session
    Auth API->>Frontend: Return token + user data
    Frontend->>Frontend: Store token in localStorage
    Frontend->>User: Redirect to dashboard
```

### Role-Based Access Control (RBAC)

| Role | Permissions | Access Level |
| - | - | - |
| **Owner** | Full access | All modules, all data |
| **Manager** | Operational access | All modules, company data only |
| **Cashier** | POS access | POS module only |
| **Warehouse Staff** | Inventory access | Inventory module only |
| **Accountant** | Finance access | Finance module only |
| **HR Staff** | HR access | HR module only |
| **Viewer** | Read-only | Dashboard & reports only |

## Monitoring & Observability

### System Monitoring

| Component | Metric | Tool | Alert Threshold |
| - | - | - | - |
| **API** | Response time | Base44 Dashboard | > 1000ms |
| **Database** | Query performance | PostgreSQL Stats | > 500ms |
| **Frontend** | Page load time | Lighthouse | > 3s |
| **Cache** | Hit rate | Redis Metrics | \< 80% |
| **Errors** | Error rate | Sentry | > 1% |
| **Uptime** | Availability | Uptime Robot | \< 99% |

### Logging Strategy

```javascript theme={null}
// Structured logging example
const log = {
  timestamp: '2026-10-10T10:30:00Z',
  level: 'INFO',
  service: 'pos-api',
  action: 'finalizeTransaction',
  company_id: 'comp_abc123',
  user_id: 'user_xyz789',
  transaction_id: 'txn_001',
  amount: 150000,
  duration_ms: 245,
  status: 'success'
};
```

## Future Architecture Enhancements

### Planned Improvements

1. **Microservices Migration**
   * Split monolith into domain-specific services
   * Independent scaling per module
   * Technology flexibility per service

2. **Event-Driven Architecture**
   * Event sourcing for critical operations
   * CQRS for read/write separation
   * Real-time event streaming

3. **Advanced AI Integration**
   * Predictive analytics for demand forecasting
   * Automated inventory optimization
   * AI-powered customer insights

4. **Blockchain Integration**
   * Supply chain traceability
   * Immutable audit trail
   * Smart contracts for B2B transactions

5. **IoT Integration**
   * Smart warehouse sensors
   * Temperature monitoring for HACCP
   * Automated stock counting

6. **Multi-Language Support**
   * i18n for international expansion
   * Localized content per region
   * Multi-currency support

## Conclusion

Arsitektur Quinn of Spicy ERP dirancang untuk:

* **Scalability**: Mendukung pertumbuhan dari UMKM ke enterprise
* **Security**: Multi-layer security dengan isolasi data ketat
* **Performance**: Optimized untuk kecepatan dan efisiensi
* **Reliability**: High availability dengan backup dan recovery
* **Flexibility**: Modular design untuk kustomisasi
* **Maintainability**: Clean code dengan dokumentasi lengkap

Sistem ini siap mendukung operasional bisnis F\&B modern dengan fitur lengkap dari POS, inventory, manufacturing, finance, HR, CRM, hingga AI-powered insights.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.