> ## 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.

# Introduction

<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: "Pengenalan Quinn of Spicy ERP"
description: "Sistem ERP terintegrasi untuk bisnis kuliner F\&B - Mengelola produksi, inventori, penjualan, keuangan, SDM, dan AI-powered insights"
---------------------------------------------------------------------------------------------------------------------------------------------------

# Quinn of Spicy ERP

**Sistem ERP (Enterprise Resource Planning) terintegrasi** yang dirancang khusus untuk industri Food & Beverage (F\&B) di Indonesia. Quinn of Spicy ERP mengelola seluruh operasional bisnis dari hulu ke hilir: produksi, inventori, penjualan multi-channel, keuangan, SDM, CRM, hingga AI-powered business insights.

<img src="https://mintcdn.com/quinnofspicy/e4f_upKhVWcjsUmM/docs/mintlify/screenshots/core/dashboard.png?fit=max&auto=format&n=e4f_upKhVWcjsUmM&q=85&s=11c75c245d75996e20bffec7bedc9d38" alt="Dashboard Quinn of Spicy" width="1920" height="1080" data-path="docs/mintlify/screenshots/core/dashboard.png" />

## Tentang Quinn of Spicy

**Quinn of Spicy** adalah merek sambal premium asli Medan yang menggunakan:

* **Cabai Berastagi** pilihan dari dataran tinggi Karo
* **Andaliman** khas Batak untuk cita rasa autentik
* **Racikan tangan** ibu-ibu berpengalaman 20+ tahun
* **Sertifikasi Halal** MUI dan terdaftar **BPOM**
* **Kualitas ekspor** dengan standar internasional

Perusahaan: **PT Selera Pedas Nusantara**

## Visi & Misi Sistem

### Visi

Menjadi sistem ERP F\&B terlengkap dan paling mudah digunakan di Indonesia, mendukung transformasi digital UMKM hingga enterprise.

### Misi

1. **Integrasi End-to-End**: Satu platform untuk semua operasional bisnis
2. **Mobile-First**: Akses dari mana saja, kapan saja
3. **AI-Powered**: Insights dan automasi berbasis kecerdasan buatan
4. **Scalable**: Tumbuh bersama bisnis, dari startup hingga enterprise
5. **Affordable**: Harga terjangkau untuk UMKM Indonesia

## Filosofi & Prinsip Desain

Sistem Quinn of Spicy ERP dibangun di atas prinsip-prinsip berikut:

### 1. Single Source of Truth

Seluruh data bisnis tersimpan dalam satu database terpusat. Tidak ada duplikasi data antar modul -- setiap transaksi POS langsung mempengaruhi inventori, setiap produksi mempengaruhi HPP, dan setiap invoice tercatat di jurnal otomatis.

### 2. Multi-Tenant by Design

Setiap perusahaan (Company) beroperasi dalam lingkungan terisolasi menggunakan Row-Level Security (RLS) di PostgreSQL. Data antar perusahaan tidak saling bocor, bahkan ketika berbagi infrastruktur database yang sama.

### 3. Role-Based Everything

Akses terhadap fitur, data, dan aksi ditentukan oleh role dan permission granular. Seorang `cashier` hanya melihat modul POS, sementara `stock_admin` fokus pada inventori dan `finance_admin` mengelola keuangan.

### 4. Offline-First & Real-Time Sync

Aplikasi dibangun sebagai PWA (Progressive Web App) yang tetap berfungsi tanpa koneksi internet. Sinkronisasi data antar tab dan perangkat dilakukan secara real-time melalui BroadcastChannel API.

### 5. Traceability & Auditability

Setiap pergerakan stok, transaksi produksi, dan perubahan data dicatat dengan idempotency key, batch/lot tracking, dan audit trail lengkap. Ini penting untuk kepatuhan HACCP, BPOM, dan standar food safety.

## Fitur Unggulan

### All-in-One ERP

Satu sistem untuk mengelola:

* Point of Sale (POS) multi-channel
* Inventori & warehouse management
* Manufacturing & production
* Akuntansi & keuangan
* HR & payroll
* CRM & customer loyalty
* AI assistant & automation
* E-commerce & marketplace integration

### Mobile-First Design

* **PWA (Progressive Web App)**: Install di mobile & desktop
* **Responsive**: Optimal di semua ukuran layar
* **Offline Mode**: Tetap produktif tanpa internet
* **Touch-Optimized**: Interface ramah sentuhan

### AI-Powered Features

* **AI Assistant**: Tanya jawab tentang bisnis dalam bahasa natural
* **AI Agents**: Automasi tugas berulang (follow-up, reminder, report)
* **Forecasting**: Prediksi penjualan dan demand planning
* **Content Studio**: Generate konten marketing otomatis
* **Smart Insights**: Rekomendasi bisnis berbasis data

### Enterprise-Grade Security

* **Multi-Tenant**: Isolasi data antar perusahaan
* **RBAC**: Role-based access control granular
* **RLS**: Row-level security di database
* **Audit Trail**: Log semua aktivitas penting
* **Encryption**: TLS 1.3 end-to-end

## Arsitektur Multi-Tenant

Quinn of Spicy ERP menggunakan arsitektur **shared-database, shared-schema** dengan isolasi berbasis Row-Level Security (RLS) di PostgreSQL. Berikut adalah cara kerjanya:

```
┌─────────────────────────────────────────────────────────┐
│                    Quinn of Spicy ERP                     │
├─────────────────────────────────────────────────────────┤
│  Frontend (React 19 + Vite 5 + PWA)                     │
│  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐   │
│  │ Company A │ │ Company B │ │ Company C │ │ Personal  │   │
│  │ Workspace │ │ Workspace │ │ Workspace │ │ Workspace │   │
│  └─────┬────┘ └─────┬────┘ └─────┬────┘ └─────┬────┘   │
├────────┼────────────┼────────────┼────────────┼─────────┤
│  Backend (Base44 Serverless - 170+ functions)            │
│  ┌──────────────────────────────────────────────────┐   │
│  │  RLS Policy: WHERE company_id = active_company_id │   │
│  └──────────────────────────────────────────────────┘   │
├─────────────────────────────────────────────────────────┤
│  PostgreSQL (162 entities + RLS)     │  Redis Cache      │
│  ┌────────┐ ┌────────┐ ┌────────┐  │  ┌────────────┐   │
│  │Tenant A│ │Tenant B│ │Tenant C│  │  │  Session &  │   │
│  │  Data  │ │  Data  │ │  Data  │  │  │  Query Cache│   │
│  └────────┘ └────────┘ └────────┘  │  └────────────┘   │
└─────────────────────────────────────────────────────────┘
```

### Hierarki Multi-Tenant

1. **User** -- Pengguna individual yang memiliki akun dan subscription
2. **Company** -- Entitas bisnis/perusahaan; satu user bisa menjadi owner dari satu atau lebih Company
3. **CompanyMember** -- Relasi antara User dan Company dengan role & permission spesifik
4. **Workspace** -- Ruang kerja dalam Company (atau personal); mengelompokkan tasks, notes, dan anggota
5. **WorkspaceMember** -- Anggota workspace dengan role tersendiri

Setiap data bisnis (Inventory, Invoice, ProductionOrder, dll.) selalu terikat pada `company_id`, sehingga RLS dapat memfilter data secara otomatis berdasarkan `active_company_id` user yang sedang login.

## Modul Sistem

Quinn of Spicy ERP terdiri dari **8 modul utama** yang saling terintegrasi:

### 1. Dashboard & Core

**Pusat kendali bisnis** dengan real-time metrics dan quick actions.

**Fitur**:

* Executive dashboard dengan KPI real-time
* Widget metrics: penjualan, order, stok, keuangan
* Chart interaktif: trend, perbandingan, forecasting
* Quick actions: akses cepat ke fitur sering digunakan
* Multi-workspace support
* Company settings & configuration
* Offline mode dengan auto-sync

**Screenshot**:

<img src="https://mintcdn.com/quinnofspicy/e4f_upKhVWcjsUmM/docs/mintlify/screenshots/core/dashboard.png?fit=max&auto=format&n=e4f_upKhVWcjsUmM&q=85&s=11c75c245d75996e20bffec7bedc9d38" alt="Dashboard" width="1920" height="1080" data-path="docs/mintlify/screenshots/core/dashboard.png" />

### 2. POS & Kasir

**Sistem kasir modern** untuk transaksi cepat dan akurat.

**Fitur**:

* Kasir interface dengan touch optimization
* Multi-channel: dine-in, takeaway, delivery, GoFood, GrabFood
* Payment gateway: Midtrans, Xendit, Stripe, PayPal
* Split payment & multiple payment methods
* Bluetooth thermal printer integration
* Order queue management real-time
* Receipt customization
* POS reports & analytics
* Member & loyalty integration
* Discount & promotion management

**Entitas utama**: `POSTransaction`, `CompanyPOSProduct`, `CompanyPOSCategory`, `CompanyPOSInventory`, `CompanyPOSSettings`

**Screenshot**:

<img src="https://mintcdn.com/quinnofspicy/e4f_upKhVWcjsUmM/docs/mintlify/screenshots/pos/cashier.png?fit=max&auto=format&n=e4f_upKhVWcjsUmM&q=85&s=6a864d9a662dc715c4214a19c4fc39d7" alt="POS Kasir" width="1920" height="1080" data-path="docs/mintlify/screenshots/pos/cashier.png" />

### 3. Inventori

**Manajemen stok lengkap** dengan multi-location support.

**Fitur**:

* Stock management: masuk, keluar, transfer
* Stock opname dengan approval workflow
* Multi-location & warehouse management
* Barcode scanning untuk quick entry
* HPP calculation (FIFO/Average method)
* Discount management
* Supplier management
* Purchase order automation
* Stock alerts & anomaly detection
* Batch & lot tracking
* Channel allocation (offline, online, marketplace, B2B)
* Geographic zone distribution (same\_city, other\_cities, export)

**Entitas utama**: `Inventory`, `StockMovement`, `StockOpname`, `StockTransfer`, `StockAlert`, `LotBatch`, `WarehouseLocation`, `Supplier`, `PurchaseOrder`, `HPPCalculation`

**Screenshot**:

<img src="https://mintcdn.com/quinnofspicy/e4f_upKhVWcjsUmM/docs/mintlify/screenshots/inventory/stock-management.png?fit=max&auto=format&n=e4f_upKhVWcjsUmM&q=85&s=f58c675c52c010be3a38f1f82bcdc8f1" alt="Inventory" width="1920" height="1080" data-path="docs/mintlify/screenshots/inventory/stock-management.png" />

### 4. Manufaktur

**Production management** untuk bisnis F\&B dengan dukungan HACCP dan traceability.

**Fitur**:

* Production orders management (planned, in\_progress, completed, on\_hold, cancelled)
* Bill of Materials (BOM) / Resep dengan versioning
* Quality control & inspection (QC result: pass, fail, pending, rework)
* HACCP verification untuk food safety
* Lot/batch tracking & traceability (input lot -> output lot)
* Raw material management dengan FIFO/FEFO allocation
* Production timer & monitoring (duration, efficiency\_status)
* Yield calculation (mass\_yield\_percentage, productivity\_ratio)
* Production cost analysis (direct material, semi-finished, packaging, labor, overhead)
* WIP (Work In Process) tracking: primary\_semi\_finished -> final\_finished\_good
* Spoilage treatment: absorbed\_normal vs expense\_abnormal

**Entitas utama**: `ProductionOrder`, `BillOfMaterials`, `HACCPVerification`, `QualityCheck`, `QualityCase`, `RawMaterial`, `LotBatch`

**Screenshot**:

<img src="https://mintlify.s3.us-west-1.amazonaws.com/quinnofspicy/docs/mintlify/screenshots/manufacturing/production.png" alt="Manufacturing" />

### 5. Keuangan

**Akuntansi & financial management** lengkap dengan dukungan multi-bank dan jurnal otomatis.

**Fitur**:

* Invoice management (invoice, quotation, proforma) dengan partial delivery & payment
* Expense tracking & categorization
* Multi-bank account management
* General ledger & journal entries (debit/credit balanced)
* Financial reports: P\&L, Balance Sheet, Cash Flow
* Budget planner & tracking
* Financial goals setting
* AI-powered profit analysis
* Saldo & cash management
* Tax calculation (PPh, PPN) dengan mode inclusive/exclusive
* Fixed asset management & depreciation

**Entitas utama**: `Invoice`, `InvoicePayment`, `Expense`, `GLJournalEntry`, `GLAccount`, `BankAccount`, `Budget`, `FinancialRecord`, `FinancialGoal`, `FinancialReportSnapshot`, `FixedAsset`, `CompanyBalance`, `CompanyWithdrawal`

**Screenshot**:

<img src="https://mintcdn.com/quinnofspicy/e4f_upKhVWcjsUmM/docs/mintlify/screenshots/finance/reports.png?fit=max&auto=format&n=e4f_upKhVWcjsUmM&q=85&s=f4d52673b39c8240fd3e53d2bff7a4c9" alt="Finance" width="1920" height="1080" data-path="docs/mintlify/screenshots/finance/reports.png" />

### 6. SDM & Kehadiran

**Human resources management** modern dengan GPS geofence dan automasi payroll.

**Fitur**:

* Attendance dengan GPS geofence & foto (clock\_in/clock\_out with location)
* Payroll automation dengan PPh 21
* Employee self-service portal
* Performance reviews & KPI tracking
* Recruitment ATS (Applicant Tracking System)
* Leave management
* Loan management
* Employee documents
* Shift scheduling
* Company-level attendance settings & policies

**Entitas utama**: `Employee`, `AttendanceRecord`, `CompanyAttendance`, `CompanyAttendanceSettings`, `Payroll`, `CompanyPayroll`, `PayrollConfiguration`, `PayslipTemplate`, `PerformanceReview`, `KPI`, `KPITemplate`, `Leave`, `CompanyLeave`, `CompanyLoan`, `JobPosting`, `Applicant`, `InterviewSchedule`, `OfferLetter`, `Training`

**Screenshot**:

<img src="https://mintcdn.com/quinnofspicy/e4f_upKhVWcjsUmM/docs/mintlify/screenshots/hr/attendance.png?fit=max&auto=format&n=e4f_upKhVWcjsUmM&q=85&s=73b815061b588bdbf74edfc7536ce695" alt="HR" width="1920" height="1080" data-path="docs/mintlify/screenshots/hr/attendance.png" />

### 7. CRM & Pelanggan

**Customer relationship management** terintegrasi dengan loyalty program dan sales pipeline.

**Fitur**:

* Customer database & segmentation (individual, business, retail, reseller, distributor, modern\_market)
* Membership program dengan poin & stempel (loyalty ledger)
* Sales pipeline management (prospect -> qualified -> proposal -> negotiation -> won/lost)
* WhatsApp integration untuk komunikasi
* Customer loyalty & rewards (points earned/used, stamp collection)
* B2B partner portal (credit limit, payment terms, billing/shipping address)
* Distribution tracking (shipment, return)
* Customer service tools (support tickets, conversations)
* Referral program dengan kode referral & komisi

**Entitas utama**: `Customer`, `CustomerMembership`, `CustomerLoyaltyLedger`, `CustomerPO`, `SalesPipeline`, `Conversation`, `Referral`, `ReferralCode`, `PartnershipApplication`, `DistributionShipment`, `DistributionReturn`, `SupportTicket`

**Screenshot**:

<img src="https://mintcdn.com/quinnofspicy/e4f_upKhVWcjsUmM/docs/mintlify/screenshots/crm/customers.png?fit=max&auto=format&n=e4f_upKhVWcjsUmM&q=85&s=4adb40922901c31014cb2c2fdac867b1" alt="CRM" width="1920" height="1080" data-path="docs/mintlify/screenshots/crm/customers.png" />

### 8. AI & Analitik

**Artificial Intelligence** untuk business insights dan automasi.

**Fitur**:

* AI Assistant: natural language queries
* AI Agents: automated task execution dengan scheduling & templates
* Content Studio: marketing content generation
* Sales forecasting & demand prediction
* AI profit report & analysis
* Agent dashboard & monitoring (run\_count, total\_cost tracking)
* AI learning from historical data (AILearningData)
* Advanced analytics & visualization
* Custom dashboard configuration

**Entitas utama**: `AIAgent`, `AIAgentRun`, `AIAgentModel`, `AIAgentSchedule`, `AIAgentSettings`, `AIAgentTemplate`, `AILearningData`, `CustomDashboardConfig`, `Automation`, `WorkflowAutomation`

**Screenshot**:

<img src="https://mintcdn.com/quinnofspicy/e4f_upKhVWcjsUmM/docs/mintlify/screenshots/ai/assistant.png?fit=max&auto=format&n=e4f_upKhVWcjsUmM&q=85&s=a1414b091bfd320a8880c01ac328203d" alt="AI" width="1920" height="1080" data-path="docs/mintlify/screenshots/ai/assistant.png" />

## Modul Pendukung

Selain 8 modul utama, sistem juga memiliki modul pendukung:

### Produktivitas

* Documents management (`Document`)
* Notes & knowledge base (`Note`)
* Tasks & project management (`Task`, `Project`, `RecurringTask`)
* Goals & OKR tracking (`Goal`, `PersonalGoal`, `CompanyKPI`)
* Habits tracking (`Habit`, `HabitLog`)
* Appointments & scheduling (`Appointment`)
* Time tracking (`TimeEntry`)

### Komunikasi

* Team chat internal (`TeamChat`, `ChatChannel`)
* WhatsApp Web integration (`WhatsAppChatLog`, `WhatsAppContact`, `WhatsAppSession`, `WhatsAppFinanceBot`)
* Email marketing campaigns (`EmailCampaign`, `NewsletterSubscriber`)
* Internal messages & notifications (`InternalMessage`, `Notification`)

### Marketing & B2B

* Marketplace integration (`MarketplaceOrder`, `MarketplaceCart`, `MarketplaceCommissionSettings`)
* Partnership management (`PartnershipApplication`, `PartnershipContent`)
* Referral program (`Referral`, `ReferralCode`, `ReferralSetting`, `Commission`)
* Marketing automation (`Automation`)
* Live streaming integration (`LiveStreamingActivity`)
* Blog & content marketing (`BlogContent`, `BlogComment`)

### Toko Online

* E-commerce storefront (`QuinnOrder`, `DigitalProduct`)
* Shopping cart & checkout (`MarketplaceCart`)
* Product catalog (`POSProduct`, `CompanyPOSProduct`)
* Order management (`ProductOrder`, `QuinnOrder`)
* Voucher & discount (`Voucher`, `VoucherUsage`, `ProductVoucher`, `Discount`)

### Admin & Pengaturan

* RBAC (Role-Based Access Control) (`MenuAccessProfile`)
* Multi-tenant configuration (`CompanyModuleSettings`)
* Company settings (`Company`, `HomeSettings`, `ShopSettings`)
* Security & audit trail (`AuditLog`, `ApprovalRequest`, `ApprovalWorkflow`)
* Backup & recovery (`CompanyBackup`)
* Printer settings (`PrinterSettings`)
* Payment gateway settings (`PaymentGatewaySettings`)

## Sistem Subscription & Pricing

Quinn of Spicy ERP menggunakan model subscription berbasis paket dengan fitur yang progressively unlocked:

| Paket | Harga | AI Credits | Max Companies | Fitur Utama |
| - | - | - | - | - |
| **Free** | Gratis | 10/bulan | 0 | Tasks, Notes, Personal workspace |
| **Pro** | Bulanan/Tahunan | 10/bulan | 1 | + POS, CRM dasar |
| **Business** | Bulanan/Tahunan | Higher | 1-2 | + Inventory, Invoice, HR, Manufacturing |
| **Advanced** | Bulanan/Tahunan | Higher | 2-3 | + Analytics, WhatsApp, Email Marketing |
| **Enterprise** | Custom | Unlimited | Unlimited | + Semua fitur, priority support, custom integration |

**Durasi membership**: `monthly`, `yearly`, `custom`, `lifetime`

**Grace period**: 3 hari setelah expired dengan mode `is_readonly_mode = true`

**Add-on**: Pembelian slot company tambahan (`company_slots_purchased`) dan AI credit tambahan (`ai_addon_quota`)

## Teknologi Stack

### Frontend

| Technology | Purpose |
| - | - |
| React 19 | UI framework dengan hooks & context |
| Vite 5.x | Build tool dengan fast HMR |
| React Router 6.x | Dynamic routing & lazy loading |
| Tailwind CSS 3.x | Utility-first styling |
| Framer Motion | Animation & gestures |
| PWA | Mobile app experience |
| Lucide Icons | 1000+ icons library |

### Backend

| Technology | Purpose |
| - | - |
| Base44 | Serverless platform (170+ functions) |
| PostgreSQL | Database dengan RLS (162 entities) |
| Redis | Cache layer untuk performance |
| BroadcastChannel API | Real-time cross-tab sync |

### Security

| Layer | Implementation |
| - | - |
| Authentication | JWT + Session management |
| Authorization | RBAC dengan granular permissions |
| Data Isolation | Row-level security (RLS) |
| API Security | Server-side policy functions |
| Audit Trail | Complete activity logging |
| Encryption | TLS 1.3 end-to-end |

### Integrasi

| Service | Provider |
| - | - |
| Payment Gateway | Midtrans, Xendit, Stripe, PayPal |
| WhatsApp API | Wablas |
| Maps & Geolocation | Google Maps API |
| Cloud Storage | Cloudinary |
| Email Service | SMTP/SES |
| AI/ML | OpenAI, Custom Models |

## Statistik Sistem

| Metrik | Jumlah | Keterangan |
| - | - | - |
| **Halaman** | 93 | Halaman unik dalam aplikasi |
| **File Kode** | 2,798 | Total file source code |
| **Baris Kode** | 378,149 | Lines of code (LOC) |
| **Entities** | 162 | Database entities/tables |
| **Server Functions** | 170 | API endpoints & business logic |
| **Commits** | 1,712+ | Version control history |
| **Modules** | 8 | Modul utama ERP |
| **User Roles** | 13 | Owner, Admin, Supervisor, Cashier, dll |
| **Payment Gateways** | 4 | Midtrans, Xendit, Stripe, PayPal |
| **AI Features** | 10+ | Assistant, agents, forecasting, dll |

## Use Cases

### Untuk UMKM F\&B

* Kelola produksi sambal, keripik, makanan ringan
* POS untuk warung, cafe, restoran kecil
* Inventory multi-gudang
* Laporan keuangan sederhana

### Untuk Restoran & Cafe

* POS dengan table management
* Kitchen display system
* Recipe & BOM management
* Staff scheduling & payroll
* Customer loyalty program

### Untuk Food Manufacturing

* Production planning & scheduling
* Raw material procurement
* Quality control & HACCP
* Batch tracking & traceability
* Distribution management

### Untuk F\&B Chain

* Multi-outlet management
* Centralized inventory
* Standardized recipes
* Consolidated reporting
* Franchise management

## Keunggulan Kompetitif

### vs. Spreadsheet Manual

* Otomatis & real-time
* Multi-user collaboration
* Data terpusat & aman
* Reporting instan
* Mobile access

### vs. Software Legacy

* Cloud-native, no installation
* Always up-to-date
* Scalable on-demand
* Modern UI/UX
* AI-powered features

### vs. Generic ERP

* Designed khusus untuk F\&B
* Harga terjangkau UMKM
* Implementasi cepat (hari, bukan bulan)
* Support lokal Indonesia
* Compliance BPOM, Halal, PPh 21

## Roadmap Pengembangan

### Q4 2026

* [ ] Advanced AI forecasting
* [ ] IoT integration untuk smart warehouse
* [ ] Blockchain untuk supply chain traceability
* [ ] Multi-language support (English, Mandarin)

### Q1 2027

* [ ] Microservices migration
* [ ] Event-driven architecture
* [ ] Advanced analytics dashboard
* [ ] Mobile app native (iOS/Android)

### Q2 2027

* [ ] Marketplace automation
* [ ] Automated marketing campaigns
* [ ] Predictive maintenance
* [ ] Voice commands untuk POS

## Dokumentasi Lengkap

Jelajahi dokumentasi per modul:

* [Dashboard & Core](/docs/core/dashboard)
* [POS & Kasir](/docs/pos/overview)
* [Inventori](/docs/inventory/overview)
* [Manufaktur](/docs/manufacturing/overview)
* [Keuangan](/docs/finance/overview)
* [SDM & Kehadiran](/docs/hr/overview)
* [CRM & Pelanggan](/docs/crm/overview)
* [AI & Analitik](/docs/ai/overview)
* [Arsitektur Sistem](/docs/getting-started/architecture)

## Lisensi

**Hak Cipta Dilindungi** (c) 2026 PT Selera Pedas Nusantara

Quinn of Spicy ERP adalah proprietary software. Dilarang mendistribusikan, memodifikasi, atau menggunakan tanpa izin tertulis dari pemegang hak cipta.

***

## Relasi Entitas Utama (Entity Relationship Diagram)

Berikut adalah diagram relasi entitas lintas modul yang menunjukkan bagaimana data saling terhubung dalam sistem:

```mermaid theme={null}
erDiagram
    User ||--o{ CompanyMember : "memiliki role di"
    User ||--o| User : "active_company_id"
    User ||--o{ WorkspaceMember : "anggota workspace"
    User ||--o{ Subscription : "berlangganan"

    Company ||--o{ CompanyMember : "memiliki anggota"
    Company ||--o{ Workspace : "memiliki workspace"
    Company ||--o{ Employee : "memiliki karyawan"
    Company ||--o{ Customer : "melayani"
    Company ||--o{ Inventory : "mengelola stok"
    Company ||--o{ ProductionOrder : "menjalankan produksi"
    Company ||--o{ Invoice : "menerbitkan invoice"
    Company ||--o{ BillOfMaterials : "menyimpan resep"
    Company ||--o{ SalesPipeline : "mengelola pipeline"
    Company ||--o{ AIAgent : "menggunakan AI"
    Company ||--o{ POSTransaction : "transaksi POS"
    Company ||--o{ GLJournalEntry : "jurnal akuntansi"
    Company ||--o{ StockMovement : "pergerakan stok"
    Company ||--o{ AttendanceRecord : "absensi"

    CompanyMember }o--|| Employee : "terhubung ke data karyawan"
    CompanyMember }o--o{ WarehouseLocation : "ditugaskan di lokasi"

    Workspace ||--o{ WorkspaceMember : "memiliki anggota"
    Workspace ||--o{ Task : "memiliki tugas"
    Workspace ||--o{ Note : "memiliki catatan"

    BillOfMaterials ||--o{ ProductionOrder : "digunakan di produksi"
    ProductionOrder ||--o{ LotBatch : "menghasilkan lot output"
    ProductionOrder ||--o{ StockMovement : "konsumsi bahan"
    ProductionOrder ||--o{ HACCPVerification : "verifikasi food safety"

    Inventory ||--o{ StockMovement : "catatan pergerakan"
    Inventory ||--o{ LotBatch : "lot/batch tracking"
    Inventory }o--|| WarehouseLocation : "tersimpan di"

    Customer ||--o{ Invoice : "memiliki tagihan"
    Customer ||--o{ CustomerMembership : "program loyalitas"
    Customer ||--o{ SalesPipeline : "prospek penjualan"
    Customer ||--o{ POSTransaction : "transaksi member"

    Invoice ||--o{ InvoicePayment : "riwayat pembayaran"
    Invoice ||--o{ GLJournalEntry : "jurnal otomatis"

    POSTransaction ||--o{ StockMovement : "mengurangi stok otomatis"
    POSTransaction }o--o| Customer : "transaksi member"

    Employee ||--o{ AttendanceRecord : "record absensi"
    Employee ||--o{ Payroll : "slip gaji"
    Employee ||--o{ PerformanceReview : "evaluasi kinerja"
```

## Schema Entitas Inti

Berikut adalah definisi field lengkap untuk entitas-entitas inti sistem.

### Company

Entitas perusahaan -- unit utama isolasi data multi-tenant.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `name` | string | Ya | Nama perusahaan |
| `owner_id` | string | Ya | ID owner perusahaan |
| `owner_email` | string | Ya | Email owner |
| `owner_subscription_plan` | enum | - | Plan membership: `free`, `pro`, `business`, `advanced`, `enterprise` |
| `description` | string | - | Deskripsi perusahaan |
| `industry` | enum | - | Sektor industri: `retail`, `manufacturing`, `services`, `technology`, `food_beverage`, `healthcare`, `education`, `other` |
| `address` | string | - | Alamat lengkap |
| `phone` | string | - | Nomor telepon |
| `email` | string | - | Email perusahaan |
| `website` | string | - | URL website |
| `logo_url` | string | - | URL logo perusahaan |
| `tax_id` | string | - | NPWP perusahaan |
| `employee_count` | number | - | Jumlah karyawan (default: 0) |
| `business_type` | string | - | Kategori bisnis dari onboarding |
| `active_modules` | string | - | JSON array ID modul yang aktif |
| `landing_page_config` | object | - | Konfigurasi landing page (tema, konten, pembayaran) |
| `metadata` | object | - | Data tambahan / legacy |
| `settings.working_hours_start` | string | - | Jam mulai kerja (default: `09:00`) |
| `settings.working_hours_end` | string | - | Jam akhir kerja (default: `17:00`) |
| `settings.working_days` | array | - | Hari kerja aktif (default: `[1,2,3,4,5]`) |
| `settings.batch_allocation_strategy` | enum | - | Strategi alokasi batch: `fifo` atau `fefo` |
| `settings.spoilage_default_treatment` | enum | - | Perlakuan spoilage: `absorbed_normal` atau `expense_abnormal` |
| `settings.tax.enabled` | boolean | - | Apakah pajak diaktifkan |
| `settings.tax.rate` | number | - | Tarif PPN dalam persen (default: 11) |
| `settings.tax.mode` | enum | - | Mode pajak: `inclusive` atau `exclusive` |
| `settings.expiry_thresholds.critical` | number | - | Ambang hari kedaluwarsa kritis (default: 7) |
| `settings.expiry_thresholds.warning` | number | - | Ambang hari kedaluwarsa peringatan (default: 30) |
| `settings.expiry_thresholds.info` | number | - | Ambang hari kedaluwarsa info (default: 90) |

### User

Entitas pengguna individual -- pemilik akun yang bisa menjadi member di satu atau lebih Company.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `email` | string | Ya | Email pengguna |
| `full_name` | string | Ya | Nama lengkap |
| `role` | enum | - | Role global: `admin`, `user` |
| `subscription_plan` | enum | - | Paket langganan: `free`, `pro`, `business`, `advanced`, `enterprise` (default: `free`) |
| `subscription_start` | datetime | - | Tanggal mulai langganan |
| `subscription_end` | datetime | - | Tanggal akhir langganan |
| `membership_duration_type` | enum | - | Durasi membership: `monthly`, `yearly`, `custom`, `lifetime` |
| `membership_start_date` | date | - | Tanggal mulai membership |
| `membership_end_date` | date | - | Tanggal akhir membership |
| `is_readonly_mode` | boolean | - | Mode read-only saat grace period expired (default: `false`) |
| `trial_end` | datetime | - | Tanggal akhir trial |
| `active_company_id` | string | - | ID company yang sedang aktif |
| `company_slots_purchased` | number | - | Slot company tambahan yang dibeli (default: 0) |
| `ai_monthly_usage` | number | - | Penggunaan AI bulan ini (default: 0) |
| `ai_credits` | number | - | Kredit AI tersedia (default: 10) |
| `ai_addon_quota` | number | - | Kuota addon AI tambahan (default: 0) |
| `balance` | number | - | Saldo deposit untuk membership/addon (default: 0) |
| `commission_balance` | number | - | Saldo komisi referral yang bisa ditarik (default: 0) |
| `admin_type` | enum | - | Tipe admin aplikasi: `owner` atau `basic` |
| `admin_tier` | enum | - | Tier admin: `none`, `business`, `advanced`, `enterprise` |
| `productivity_score` | number | - | Skor produktivitas (default: 0) |
| `current_streak` | number | - | Streak hari berturut-turut (default: 0) |
| `user_level` | number | - | Level berdasarkan achievement points (default: 1) |
| `preferences.theme` | string | - | Tema UI pilihan |
| `preferences.primary_color` | string | - | Warna utama UI |
| `preferences.wallpaper_url` | string | - | URL wallpaper dashboard |

### CompanyMember

Entitas relasi antara User dan Company -- mendefinisikan role, permission, dan penugasan anggota dalam perusahaan.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `company_id` | string | Ya | ID perusahaan |
| `user_id` | string | - | ID pengguna |
| `user_email` | string | Ya | Email pengguna |
| `user_name` | string | - | Nama pengguna |
| `role` | enum | - | Role dalam company (lihat tabel enum di bawah) |
| `employee_id` | string | - | Link ke entitas Employee |
| `department` | string | - | Departemen |
| `position` | string | - | Jabatan |
| `status` | enum | - | Status keanggotaan: `active`, `inactive`, `pending` |
| `joined_date` | date | - | Tanggal bergabung |
| `invited_by` | string | - | Email pengundang |
| `salary` | number | - | Gaji karyawan |
| `assigned_locations` | array | - | Daftar ID lokasi gudang/outlet yang diizinkan |
| `working_hours.start` | string | - | Jam mulai kerja (default: `09:00`) |
| `working_hours.end` | string | - | Jam akhir kerja (default: `17:00`) |
| `permissions.can_view_dashboard` | boolean | - | Akses lihat dashboard (default: true) |
| `permissions.can_view_pos` | boolean | - | Akses lihat modul POS |
| `permissions.can_use_pos` | boolean | - | Akses gunakan kasir POS |
| `permissions.can_view_inventory` | boolean | - | Akses lihat inventori |
| `permissions.can_edit_inventory` | boolean | - | Akses edit inventori |
| `permissions.can_view_finance` | boolean | - | Akses lihat keuangan |
| `permissions.can_edit_finance` | boolean | - | Akses edit keuangan |
| `permissions.can_view_hr` | boolean | - | Akses lihat SDM |
| `permissions.can_edit_hr` | boolean | - | Akses edit SDM |
| `permissions.can_manage_members` | boolean | - | Akses kelola anggota |
| `permissions.can_approve_stock_opname` | boolean | - | Akses approve stock opname |
| `permissions.can_create_production_batch` | boolean | - | Akses buat batch produksi |
| `permissions.can_release_production_qc` | boolean | - | Akses rilis QC produksi |
| `permissions.can_view_hpp` | boolean | - | Akses lihat HPP |
| `permissions.can_manage_channel_pricing` | boolean | - | Akses kelola pricing per channel |
| `permissions.can_create_b2b_invoice` | boolean | - | Akses buat invoice B2B |

### Workspace

Entitas ruang kerja -- mengelompokkan tasks, notes, dan anggota dalam satu konteks kerja.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `name` | string | Ya | Nama workspace |
| `owner_id` | string | Ya | ID pemilik workspace |
| `company_id` | string | - | ID perusahaan (null untuk personal workspace) |
| `description` | string | - | Deskripsi workspace |
| `icon` | string | - | Icon workspace |
| `color` | string | - | Warna tema (default: `#2563eb`) |
| `is_personal` | boolean | - | Apakah workspace pribadi (default: `false`) |
| `settings.allow_public_sharing` | boolean | - | Izinkan berbagi publik (default: `false`) |
| `settings.default_task_priority` | enum | - | Prioritas task default: `low`, `medium`, `high`, `urgent` |

### Subscription

Entitas langganan layanan -- mencatat subscription aktif user terhadap suatu layanan.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `user_id` | string | Ya | ID pengguna pemilik langganan |
| `service_name` | string | Ya | Nama layanan/produk berlangganan |
| `cost` | number | Ya | Biaya langganan per periode |
| `next_due_date` | date | Ya | Tanggal jatuh tempo berikutnya |
| `company_id` | string | - | ID perusahaan (null untuk personal) |
| `currency` | string | - | Mata uang (default: `IDR`) |
| `billing_cycle` | enum | - | Siklus tagihan: `weekly`, `monthly`, `quarterly`, `yearly` |
| `start_date` | date | - | Tanggal mulai langganan |
| `end_date` | date | - | Tanggal akhir langganan |
| `status` | enum | - | Status: `active`, `paused`, `cancelled` |
| `payment_method` | string | - | Metode pembayaran |
| `auto_renew` | boolean | - | Perpanjangan otomatis (default: `true`) |
| `notes` | string | - | Catatan tambahan |

## Arsitektur Modul

Diagram berikut menunjukkan hubungan antar modul dan aliran data utama dalam sistem:

```mermaid theme={null}
graph TB
    subgraph Core["Core & Foundation"]
        User[User]
        Company[Company]
        CompanyMember[CompanyMember]
        Workspace[Workspace]
        Subscription[Subscription]
        PricingPlan[PricingPlan]
    end

    subgraph POS["Modul POS"]
        POSTransaction[POSTransaction]
        POSProduct[CompanyPOSProduct]
        POSCategory[CompanyPOSCategory]
        POSMember[POSMember]
    end

    subgraph INV["Modul Inventori"]
        Inventory[Inventory]
        StockMovement[StockMovement]
        StockOpname[StockOpname]
        StockTransfer[StockTransfer]
        LotBatch[LotBatch]
        WarehouseLocation[WarehouseLocation]
        Supplier[Supplier]
        PurchaseOrder[PurchaseOrder]
        HPPCalc[HPPCalculation]
    end

    subgraph MFG["Modul Manufaktur"]
        ProductionOrder[ProductionOrder]
        BOM[BillOfMaterials]
        HACCP[HACCPVerification]
        QualityCheck[QualityCheck]
        RawMaterial[RawMaterial]
    end

    subgraph FIN["Modul Keuangan"]
        Invoice[Invoice]
        InvoicePayment[InvoicePayment]
        Expense[Expense]
        GLJournal[GLJournalEntry]
        GLAccount[GLAccount]
        BankAccount[BankAccount]
        Budget[Budget]
    end

    subgraph HR["Modul SDM"]
        Employee[Employee]
        Attendance[AttendanceRecord]
        Payroll[Payroll]
        PerformanceReview[PerformanceReview]
        Leave[Leave]
    end

    subgraph CRM["Modul CRM"]
        Customer[Customer]
        CustomerMembership[CustomerMembership]
        SalesPipeline[SalesPipeline]
        Conversation[Conversation]
        Referral[Referral]
    end

    subgraph AI["Modul AI"]
        AIAgent[AIAgent]
        AIAgentRun[AIAgentRun]
        AIAgentTemplate[AIAgentTemplate]
        Automation[Automation]
    end

    User --> CompanyMember
    CompanyMember --> Company
    Company --> POS
    Company --> INV
    Company --> MFG
    Company --> FIN
    Company --> HR
    Company --> CRM
    Company --> AI

    POSTransaction --> StockMovement
    StockMovement --> Inventory
    ProductionOrder --> StockMovement
    ProductionOrder --> BOM
    Invoice --> GLJournal
    Invoice --> Customer
    POSTransaction --> Customer
    Customer --> CustomerMembership
    Attendance --> Employee
    Payroll --> Employee
    AIAgent --> AIAgentRun
```

## Alur Kerja Pengguna (Sequence Diagram)

Diagram berikut menunjukkan alur kerja tipikal seorang pengguna dalam menjalankan operasional bisnis harian:

```mermaid theme={null}
sequenceDiagram
    actor Kasir as Kasir (POS)
    actor Operator as Operator Produksi
    actor Admin as Stock Admin
    actor Owner as Owner / Manager
    actor System as Sistem (Automated)

    Note over Kasir,System: === Alur Operasional Harian ===

    rect rgb(240, 248, 255)
        Note over Kasir,POS: 1. Transaksi POS Pagi Hari
        Kasir->>POSTransaction: Input order pelanggan
        POSTransaction->>Inventory: Kurangi stok otomatis (StockMovement)
        POSTransaction->>Customer: Tambah poin loyalty member
        POSTransaction->>GLJournal: Catat jurnal pendapatan
    end

    rect rgb(255, 248, 240)
        Note over Admin,INV: 2. Cek & Kelola Stok
        System->>Inventory: Deteksi stok rendah (stock_status = low_stock)
        System->>Admin: Kirim alert (StockAlert)
        Admin->>PurchaseOrder: Buat purchase order ke supplier
        Admin->>StockOpname: Jalankan stock opname
        StockOpname->>Inventory: Sesuaikan stok aktual
    end

    rect rgb(240, 255, 240)
        Note over Operator,MFG: 3. Produksi Harian
        Owner->>ProductionOrder: Buat production order (status: planned)
        ProductionOrder->>BOM: Load resep & bahan baku
        Operator->>ProductionOrder: Mulai produksi (status: in_progress)
        ProductionOrder->>StockMovement: Konsumsi bahan baku (FIFO/FEFO)
        Operator->>HACCP: Verifikasi HACCP & QC
        HACCP->>ProductionOrder: Update qc_result (pass/fail)
        ProductionOrder->>Inventory: Tambah stok produk jadi (LotBatch)
        ProductionOrder->>ProductionOrder: Hitung HPP per unit
    end

    rect rgb(248, 240, 255)
        Note over Owner,FIN: 4. Monitoring & Laporan
        Owner->>Invoice: Buat invoice B2B untuk distributor
        Invoice->>GLJournal: Catat piutang & pendapatan
        Owner->>Budget: Review budget vs actual
        System->>AIAgent: Generate AI insights & forecasting
        AIAgent->>Owner: Rekomendasi bisnis (restock, promo, dll)
    end

    rect rgb(255, 255, 240)
        Note over Owner,HR: 5. Kelola Tim
        Owner->>Employee: Review attendance hari ini
        Attendance->>Payroll: Akumulasi data untuk payroll
        Owner->>PerformanceReview: Evaluasi kinerja karyawan
    end
```

## Referensi Enum Entitas Inti

Berikut adalah daftar lengkap nilai enum untuk field-field penting pada entitas inti sistem.

### Company

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `owner_subscription_plan` | `free` | Paket gratis -- akses terbatas |
| | `pro` | Paket profesional -- fitur dasar bisnis |
| | `business` | Paket bisnis -- fitur lengkap |
| | `advanced` | Paket lanjutan -- analytics & marketing |
| | `enterprise` | Paket enterprise -- semua fitur + custom |
| `industry` | `retail` | Industri ritel |
| | `manufacturing` | Industri manufaktur |
| | `services` | Industri jasa |
| | `technology` | Industri teknologi |
| | `food_beverage` | Industri makanan & minuman |
| | `healthcare` | Industri kesehatan |
| | `education` | Industri pendidikan |
| | `other` | Industri lainnya |
| `settings.batch_allocation_strategy` | `fifo` | First-In-First-Out (masuk pertama, keluar pertama) |
| | `fefo` | First-Expiry-First-Out (kedaluwarsa pertama, keluar pertama) |
| `settings.spoilage_default_treatment` | `absorbed_normal` | Spoilage masuk HPP produk baik |
| | `expense_abnormal` | Spoilage dipisah sebagai beban periode |
| `settings.tax.mode` | `inclusive` | Pajak sudah termasuk dalam harga |
| | `exclusive` | Pajak ditambah ke harga |
| `settings.tax.rounding` | `per_line` | Pembulatan per baris item |
| | `per_transaction` | Pembulatan per total transaksi |

### User

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `role` | `admin` | Administrator global aplikasi |
| | `user` | Pengguna biasa |
| `subscription_plan` | `free` | Paket gratis |
| | `pro` | Paket profesional |
| | `business` | Paket bisnis |
| | `advanced` | Paket lanjutan |
| | `enterprise` | Paket enterprise |
| `membership_duration_type` | `monthly` | Berlangganan bulanan |
| | `yearly` | Berlangganan tahunan |
| | `custom` | Durasi kustom |
| | `lifetime` | Akses seumur hidup |
| `admin_type` | `owner` | Full access ke seluruh aplikasi |
| | `basic` | Hanya transaksi produk digital |
| `admin_tier` | `none` | Bukan admin company management |
| | `business` | Admin tier business |
| | `advanced` | Admin tier advanced |
| | `enterprise` | Admin tier enterprise |

### CompanyMember

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `role` | `owner` | Pemilik perusahaan -- akses penuh |
| | `admin` | Administrator -- akses hampir penuh |
| | `supervisor` | Supervisor -- pengawasan operasional |
| | `store_admin` | Admin toko -- kelola outlet |
| | `stock_admin` | Admin gudang -- kelola inventori |
| | `finance_admin` | Admin keuangan -- kelola finansial |
| | `hr_admin` | Admin SDM -- kelola karyawan & absensi |
| | `transaction_admin` | Admin transaksi -- kelola transaksi |
| | `employee` | Karyawan biasa |
| | `production_operator` | Operator produksi |
| | `qc_inspector` | Inspektor quality control |
| | `sales_marketing` | Sales & marketing |
| | `partner_distributor` | Partner/distributor |
| `status` | `active` | Anggota aktif |
| | `inactive` | Anggota nonaktif |
| | `pending` | Undangan menunggu respons |

### WorkspaceMember

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `role` | `owner` | Pemilik workspace |
| | `admin` | Admin workspace |
| | `member` | Anggota biasa |
| | `viewer` | Hanya bisa melihat |

### Subscription

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `billing_cycle` | `weekly` | Tagihan mingguan |
| | `monthly` | Tagihan bulanan |
| | `quarterly` | Tagihan triwulanan |
| | `yearly` | Tagihan tahunan |
| `status` | `active` | Langganan aktif |
| | `paused` | Langganan dijeda |
| | `cancelled` | Langganan dibatalkan |

### Inventory

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `stock_status` | `in_stock` | Stok tersedia |
| | `low_stock` | Stok rendah (di bawah min\_stock) |
| | `out_of_stock` | Stok habis |
| | `overstock` | Stok berlebihan (di atas max\_stock) |

### StockMovement

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `movement_type` | `in` | Stok masuk |
| | `out` | Stok keluar |
| | `transfer` | Transfer antar lokasi |
| | `adjustment` | Penyesuaian stok |
| | `return` | Retur barang |
| | `damaged` | Barang rusak |
| | `hold` | Tahan stok untuk QC |
| | `hold_release` | Lepas tahanan QC |
| `reference_type` | `purchase` | Dari pembelian |
| | `sale` | Dari penjualan |
| | `cashier_sale` | Dari transaksi kasir |
| | `production` | Dari produksi |
| | `raw_material_outbound` | Bahan baku keluar ke produksi |
| | `qc_release` | Rilis dari QC |
| | `transfer` | Transfer internal |
| | `adjustment` | Penyesuaian manual |
| | `opname_adjustment` | Penyesuaian stock opname |
| | `return` | Retur |
| | `manual` | Input manual |
| | `distribution_shipment` | Pengiriman distribusi |
| | `quality_hold` | Tahanan kualitas |

### ProductionOrder

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `status` | `planned` | Terencana, belum dimulai |
| | `in_progress` | Sedang berjalan |
| | `completed` | Selesai |
| | `on_hold` | Ditahan sementara |
| | `cancelled` | Dibatalkan |
| `priority` | `low` | Prioritas rendah |
| | `normal` | Prioritas normal |
| | `high` | Prioritas tinggi |
| | `urgent` | Prioritas mendesak |
| `qc_result` | `pass` | Lolos quality control |
| | `fail` | Gagal quality control |
| | `pending` | Menunggu inspeksi |
| | `rework` | Perlu pengerjaan ulang |
| `production_tier` | `primary_semi_finished` | Olahan bahan mentah jadi setengah jadi |
| | `final_finished_good` | Assembling jadi produk akhir siap edar |
| `efficiency_status` | `efficient` | Lebih cepat dari standard time |
| | `normal` | Sesuai standard time |
| | `inefficient` | Lebih dari 120% standard time |
| `wip_status` | `draft` | Belum masuk WIP |
| | `in_wip` | Sedang dalam proses WIP |
| | `transferred_to_fg` | Sudah ditransfer ke finished good |
| | `cancelled` | Dibatalkan |
| `cost_status` | `complete` | Biaya lengkap dan HPP finalized |
| | `provisional_incomplete` | Biaya sementara, ada input belum lengkap |
| | `zero_output_pending` | Output baik 0, HPP belum bisa dihitung |

### BillOfMaterials

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `status` | `draft` | Masih draft, bisa diedit bebas |
| | `active` | Aktif digunakan untuk produksi |
| | `archived` | Diarsipkan, tidak aktif |
| | `obsolete` | Usang, tidak digunakan lagi |
| `output_type` | `finished_good` | Barang jadi siap edar |
| | `semi_finished` | Barang setengah jadi olahan |

### Invoice

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `invoice_type` | `invoice` | Tagihan resmi |
| | `quotation` | Penawaran harga |
| | `proforma` | Invoice proforma |
| `status` | `draft` | Draft, bisa diedit |
| | `sent` | Sudah dikirim ke customer |
| | `partially_paid` | Dibayar sebagian |
| | `paid` | Lunas |
| | `overdue` | Jatuh tempo |
| | `cancelled` | Dibatalkan |
| `source_type` | `manual` | Dibuat manual |
| | `customer_po` | Dari Customer Purchase Order |
| | `order` | Dari order |
| | `quotation` | Dari quotation yang di-approve |
| | `pos_transaction` | Dari transaksi POS |
| `delivery_status` | `pending` | Belum dikirim |
| | `partially_delivered` | Dikirim sebagian |
| | `delivered` | Sudah dikirim lengkap |

### Employee

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `department` | `Management` | Departemen manajemen |
| | `Sales` | Departemen penjualan |
| | `Marketing` | Departemen pemasaran |
| | `Operations` | Departemen operasional |
| | `Finance` | Departemen keuangan |
| | `IT` | Departemen teknologi informasi |
| | `HR` | Departemen SDM |
| | `Customer Service` | Departemen layanan pelanggan |
| `employment_type` | `full_time` | Karyawan tetap |
| | `part_time` | Karyawan paruh waktu |
| | `contract` | Kontraktor |
| | `intern` | Magang |
| `status` | `active` | Aktif bekerja |
| | `on_leave` | Sedang cuti |
| | `terminated` | Sudah berhenti/di-PHK |

### Customer

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `customer_type` | `individual` | Perorangan |
| | `business` | Perusahaan/B2B |
| | `retail` | Ritel |
| | `reseller` | Reseller |
| | `distributor` | Distributor |
| | `modern_market` | Pasar modern (minimarket, supermarket) |
| `status` | `lead` | Prospek baru |
| | `prospect` | Calon pelanggan |
| | `customer` | Pelanggan aktif |
| | `inactive` | Tidak aktif |
| `payment_terms` | `cash` | Tunai |
| | `net_7` | 7 hari |
| | `net_14` | 14 hari |
| | `net_30` | 30 hari |
| | `net_60` | 60 hari |
| | `custom` | Ketentuan khusus |

### SalesPipeline

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `pipeline_stage` | `prospect` | Tahap prospek awal |
| | `qualified` | Sudah terqualifikasi |
| | `proposal` | Proposal dikirim |
| | `negotiation` | Dalam negosiasi |
| | `won` | Menang/deal closed |
| | `lost` | Kalah/deal gagal |
| `source_lead` | `website` | Dari website |
| | `referral` | Dari referensi |
| | `advertisement` | Dari iklan |
| | `cold_call` | Dari telepon langsung |
| | `social_media` | Dari media sosial |
| | `event` | Dari acara/event |
| | `other` | Sumber lainnya |

### POSTransaction

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `payment_method` | `cash` | Tunai |
| | `card` | Kartu debit/kredit |
| | `transfer` | Transfer bank |
| | `ewallet` | E-wallet (GoPay, OVO, Dana, dll) |
| | `qris` | QRIS |
| `status` | `completed` | Transaksi selesai |
| | `refunded` | Transaksi direfund |
| | `cancelled` | Transaksi dibatalkan |

### AttendanceRecord

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `status` | `present` | Hadir tepat waktu |
| | `late` | Hadir terlambat |
| | `absent` | Tidak hadir |
| | `sick` | Sakit |
| | `leave` | Cuti/izin |

### AIAgent

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `category` | `business` | Agent untuk analisis bisnis |
| | `content` | Agent untuk generate konten |
| | `writing` | Agent untuk penulisan |
| | `social` | Agent untuk media sosial |
| | `other` | Kategori lainnya |
| `status` | `active` | Berjalan otomatis sesuai jadwal |
| | `paused` | Tidak otomatis, bisa dijalankan manual |
| | `inactive` | Nonaktif sepenuhnya |

### GLJournalEntry

| Field | Nilai Enum | Deskripsi |
| - | - | - |
| `reference_type` | `manual` | Entri jurnal manual |
| | `invoice` | Dari invoice |
| | `purchase_order` | Dari purchase order |
| | `transfer` | Dari transfer |
| | `expense` | Dari expense |
| `status` | `draft` | Draft, bisa diedit |
| | `posted` | Sudah diposting ke ledger |
| | `reversed` | Sudah dibalik (reversal) |

### Employee

Entitas data karyawan -- menyimpan informasi lengkap karyawan perusahaan untuk modul SDM & Payroll.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `company_id` | string | Ya | ID perusahaan tempat karyawan bekerja |
| `employee_id` | string | Ya | ID karyawan unik (NIP) |
| `full_name` | string | Ya | Nama lengkap karyawan |
| `email` | string | Ya | Email karyawan |
| `user_id` | string | - | Link ke entitas User (jika sudah diaktivasi) |
| `phone` | string | - | Nomor telepon |
| `department` | enum | Ya | Departemen: `Management`, `Sales`, `Marketing`, `Operations`, `Finance`, `IT`, `HR`, `Customer Service` |
| `position` | string | Ya | Jabatan / posisi |
| `description` | string | - | Catatan tambahan mengenai karyawan (maks 1000 karakter) |
| `employment_type` | enum | - | Tipe employment: `full_time`, `part_time`, `contract`, `intern` (default: `full_time`) |
| `hire_date` | date | Ya | Tanggal mulai bekerja |
| `salary` | number | - | Gaji bulanan |
| `date_of_birth` | date | - | Tanggal lahir |
| `address` | string | - | Alamat tempat tinggal |
| `status` | enum | - | Status karyawan: `active`, `on_leave`, `terminated` (default: `active`) |
| `avatar_url` | string | - | URL foto profil |
| `bank_account.bank_name` | string | - | Nama bank untuk transfer gaji |
| `bank_account.account_number` | string | - | Nomor rekening bank |
| `bank_account.account_name` | string | - | Nama pemilik rekening |
| `emergency_contact.name` | string | - | Nama kontak darurat |
| `emergency_contact.relationship` | string | - | Hubungan dengan kontak darurat |
| `emergency_contact.phone` | string | - | Nomor telepon kontak darurat |

### Customer

Entitas pelanggan -- menyimpan data customer untuk modul CRM, POS member, dan B2B.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `company_id` | string | Ya | ID perusahaan pemilik data customer |
| `name` | string | Ya | Nama lengkap customer |
| `phone` | string | Ya | Nomor telepon |
| `email` | string | - | Alamat email |
| `whatsapp_number` | string | - | Nomor WhatsApp untuk follow up |
| `company` | string | - | Nama perusahaan customer (untuk B2B) |
| `address` | string | - | Alamat lengkap |
| `customer_type` | enum | - | Tipe customer: `individual`, `business`, `retail`, `reseller`, `distributor`, `modern_market` (default: `individual`) |
| `status` | enum | - | Status: `lead`, `prospect`, `customer`, `inactive` (default: `lead`) |
| `source` | string | - | Sumber customer (ads, referral, walk-in, dll) |
| `tags` | array | - | Tag/label untuk segmentasi |
| `membership_level_id` | string | - | ID level membership customer |
| `membership_level_name` | string | - | Nama level membership |
| `membership_since` | date | - | Tanggal mulai menjadi member |
| `membership_points` | number | - | Total poin member saat ini (default: 0) |
| `lifetime_points` | number | - | Total poin sepanjang waktu (default: 0) |
| `stamps` | number | - | Total stamp loyalty (default: 0) |
| `lifetime_value` | number | - | Total nilai transaksi sepanjang waktu (default: 0) |
| `total_orders` | number | - | Jumlah total transaksi (default: 0) |
| `average_order_value` | number | - | Rata-rata nilai transaksi (default: 0) |
| `last_purchase_date` | date | - | Tanggal transaksi terakhir |
| `last_contact_date` | date | - | Tanggal terakhir di-follow up |
| `last_contact_method` | enum | - | Metode follow up terakhir: `phone`, `whatsapp`, `email`, `meeting` |
| `birthday` | date | - | Tanggal ulang tahun |
| `payment_terms` | enum | - | Ketentuan pembayaran B2B: `cash`, `net_7`, `net_14`, `net_30`, `net_60`, `custom` (default: `net_30`) |
| `payment_terms_days` | number | - | Jumlah hari jatuh tempo (default: 30) |
| `credit_limit` | number | - | Batas plafon piutang kredit B2B (default: 0) |
| `tax_id` | string | - | NPWP / identitas pajak |
| `billing_address` | string | - | Alamat penagihan resmi B2B |
| `shipping_address` | string | - | Alamat pengiriman default B2B |
| `parent_customer_id` | string | - | ID perusahaan induk (untuk outlet/cabang) |
| `outlet_name` | string | - | Nama cabang / outlet |
| `is_active` | boolean | - | Status aktif customer B2B (default: `true`) |
| `auth_user_id` | string | - | ID autentikasi dari Auth provider |
| `default_address_id` | string | - | ID alamat default di buku alamat |
| `preferences.preferred_contact` | enum | - | Kontak pilihan: `phone`, `whatsapp`, `email` |
| `preferences.language` | string | - | Bahasa pilihan (default: `id`) |

### Inventory

Entitas stok produk -- mencatat kuantitas stok per produk per lokasi gudang/outlet.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `company_id` | string | Ya | ID perusahaan |
| `product_id` | string | Ya | ID produk dari CompanyPOSProduct |
| `location_id` | string | Ya | ID lokasi gudang/toko |
| `product_name` | string | - | Nama produk |
| `product_sku` | string | - | SKU produk |
| `location_name` | string | - | Nama lokasi gudang/toko |
| `category_key` | string | - | Kunci kategori produk |
| `category_name` | string | - | Nama kategori produk |
| `variant_key` | string | - | Kunci varian produk |
| `variant_label` | string | - | Label varian (Merah-L, Biru-XL, dll) |
| `size_grams` | number | - | Ukuran dalam gram |
| `base_product_key` | string | - | Kunci produk dasar |
| `quantity` | number | - | Stok saat ini (default: 0) |
| `reserved_quantity` | number | - | Stok yang di-reserve untuk order (default: 0) |
| `available_quantity` | number | - | Stok tersedia = quantity - reserved - blocked (default: 0) |
| `in_transit_quantity` | number | - | Stok dalam perjalanan transfer (default: 0) |
| `blocked_quantity` | number | - | Stok ditahan untuk QC/karantina (default: 0) |
| `min_stock` | number | - | Minimum stok untuk alert (default: 5) |
| `max_stock` | number | - | Maksimum stok (default: 1000) |
| `reorder_point` | number | - | Titik reorder otomatis (default: 10) |
| `reorder_quantity` | number | - | Jumlah reorder (default: 50) |
| `auto_reorder` | boolean | - | Auto buat purchase order saat low stock (default: `false`) |
| `unit_cost` | number | - | Harga modal per unit (default: 0) |
| `total_value` | number | - | Total nilai stok = quantity x unit\_cost (default: 0) |
| `stock_status` | enum | - | Status stok: `in_stock`, `low_stock`, `out_of_stock`, `overstock` |
| `last_stock_in` | datetime | - | Waktu terakhir stok masuk |
| `last_stock_out` | datetime | - | Waktu terakhir stok keluar |
| `rack` | string | - | Lokasi rak penyimpanan (misal: A1, B2) |
| `channel_allocations.offline` | number | - | Alokasi stok channel offline (default: 0) |
| `channel_allocations.online` | number | - | Alokasi stok channel online (default: 0) |
| `channel_allocations.marketplace` | number | - | Alokasi stok channel marketplace (default: 0) |
| `channel_allocations.b2b` | number | - | Alokasi stok channel B2B (default: 0) |
| `geographic_zones.same_city` | number | - | Distribusi geografis satu kota (default: 0) |
| `geographic_zones.other_cities` | number | - | Distribusi geografis luar kota (default: 0) |
| `geographic_zones.export` | number | - | Distribusi geografis ekspor (default: 0) |
| `alert_sent` | boolean | - | Apakah alert sudah dikirim (default: `false`) |

### ProductionOrder

Entitas perintah produksi -- mengelola proses produksi dari perencanaan hingga selesai, termasuk konsumsi bahan, QC, dan perhitungan HPP.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `company_id` | string | Ya | ID perusahaan |
| `bom_id` | string | Ya | ID Bill of Materials (resep) |
| `quantity_to_produce` | number | Ya | Jumlah yang akan diproduksi |
| `production_start_date` | date | Ya | Tanggal rencana mulai produksi |
| `po_number` | string | - | Nomor perintah produksi |
| `production_batch_id` | string | - | Batch ID unik (PROD-YYYYMMDD-XXX) |
| `product_id` | string | - | ID produk output |
| `product_sku` | string | - | SKU master output dari BOM |
| `product_name` | string | - | Nama produk output |
| `product_type` | string | - | Jenis produk output |
| `category_key` | string | - | Kunci kategori produk |
| `variant_key` | string | - | Kunci varian produk |
| `variant_name` | string | - | Nama varian |
| `size_grams` | number | - | Ukuran dalam gram |
| `priority` | enum | - | Prioritas: `low`, `normal`, `high`, `urgent` (default: `normal`) |
| `status` | enum | - | Status: `planned`, `in_progress`, `completed`, `on_hold`, `cancelled` (default: `planned`) |
| `production_tier` | enum | - | Tingkat produksi: `primary_semi_finished`, `final_finished_good` (default: `final_finished_good`) |
| `production_start_time` | datetime | - | Waktu mulai aktual produksi |
| `expected_completion_date` | date | - | Tanggal target selesai |
| `actual_completion_date` | date | - | Tanggal aktual selesai |
| `production_end_time` | datetime | - | Waktu selesai aktual |
| `duration_minutes` | number | - | Durasi produksi aktual (auto: end - start) |
| `standard_time_minutes` | number | - | Standard time untuk analisa efisiensi |
| `efficiency_status` | enum | - | Status efisiensi: `efficient`, `normal`, `inefficient` |
| `quantity_produced` | number | - | Jumlah yang berhasil diproduksi (default: 0) |
| `quantity_defected` | number | - | Jumlah yang cacat/defect (default: 0) |
| `fail_rate` | number | - | Persentase gagal = defected / produced x 100 |
| `qc_result` | enum | - | Hasil QC: `pass`, `fail`, `pending`, `rework` (default: `pending`) |
| `haccp_verified` | boolean | - | Apakah HACCP sudah diverifikasi (default: `false`) |
| `haccp_verification_id` | string | - | ID HACCPVerification terkait |
| `operator_id` | string | - | ID user operator produksi |
| `operator_name` | string | - | Nama operator produksi |
| `supervisor_id` | string | - | ID user supervisor |
| `supervisor_name` | string | - | Nama supervisor |
| `location_id` | string | - | ID lokasi dapur/gudang produksi |
| `location_name` | string | - | Nama lokasi produksi |
| `wip_status` | enum | - | Status WIP: `draft`, `in_wip`, `transferred_to_fg`, `cancelled` (default: `draft`) |
| `cost_status` | enum | - | Status biaya: `complete`, `provisional_incomplete`, `zero_output_pending` (default: `complete`) |
| `total_material_cost` | number | - | Total biaya bahan baku & kemasan |
| `direct_raw_material_cost` | number | - | Subtotal biaya bahan mentah |
| `semi_finished_cost` | number | - | Subtotal biaya bahan intermediate |
| `packaging_cost` | number | - | Subtotal biaya bahan kemasan |
| `direct_labor_cost` | number | - | Biaya tenaga kerja langsung |
| `overhead_cost` | number | - | Biaya overhead pabrik teralokasi |
| `total_batch_cost` | number | - | Total biaya aktual batch produksi |
| `unit_hpp` | number | - | HPP per unit produk baik |
| `mass_yield_percentage` | number | - | Persentase rendemen massa output vs input |
| `productivity_ratio` | number | - | Rasio produktivitas unit per kg |
| `raw_materials_used` | array | - | Bahan baku yang digunakan (untuk traceability) |
| `materials_actual` | array | - | Pencatatan konsumsi bahan riil vs rencana |
| `returned_materials` | array | - | Sisa bahan kembali ke stok vs waste |
| `input_lot_ids` | array | - | Daftar LotBatch input yang dikonsumsi |
| `output_lot_id` | string | - | ID LotBatch output hasil produksi |
| `manual_form_number` | string | - | Nomor form manual fisik pencatatan dapur |
| `cancellation_reason` | string | - | Alasan pembatalan production order |
| `hold_reason` | string | - | Alasan penahanan order produksi |

### CompanyInvitation

Entitas undangan bergabung perusahaan -- merekam proses invitasi anggota baru ke dalam Company.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `company_id` | string | Ya | ID perusahaan yang mengundang |
| `invited_email` | string | Ya | Email calon anggota yang diundang |
| `invited_by` | string | Ya | Email pengguna yang mengirim undangan |
| `company_name` | string | - | Nama perusahaan (untuk tampilan) |
| `invited_by_name` | string | - | Nama pengundang (untuk tampilan) |
| `role` | enum | - | Role yang diberikan: `owner`, `admin`, `supervisor`, `store_admin`, `stock_admin`, `finance_admin`, `hr_admin`, `transaction_admin`, `employee` (default: `employee`) |
| `department` | string | - | Departemen yang ditugaskan |
| `position` | string | - | Jabatan yang diberikan |
| `description` | string | - | Pesan yang disertakan dalam undangan (maks 1000 karakter) |
| `status` | enum | - | Status undangan: `pending`, `accepted`, `rejected`, `expired`, `cancelled` (default: `pending`) |
| `expires_at` | datetime | - | Waktu kedaluwarsa undangan |
| `accepted_at` | datetime | - | Waktu undangan diterima |
| `rejected_at` | datetime | - | Waktu undangan ditolak |
| `cancelled_at` | datetime | - | Waktu undangan dibatalkan |

### PricingPlan

Entitas paket harga -- mendefinisikan paket langganan yang tersedia beserta fitur dan limitasinya.

| Field | Tipe | Required | Deskripsi |
| - | - | - | - |
| `planKey` | string | Ya | Kunci unik paket (misal: `free`, `pro`, `business`, `custom`, `corporate`) |
| `name` | string | Ya | Nama paket yang ditampilkan ke pengguna |
| `price` | number | Ya | Harga bulanan (dalam Rupiah) |
| `yearlyPrice` | number | Ya | Harga tahunan (dalam Rupiah) |
| `description` | string | - | Deskripsi paket |
| `features` | array | - | Daftar fitur yang disertakan |
| `limitations` | array | - | Daftar batasan paket |
| `color` | string | - | Gradient color CSS class |
| `popular` | boolean | - | Ditandai sebagai paket populer (default: `false`) |
| `isActive` | boolean | - | Status aktif paket (default: `true`) |
| `order` | number | - | Urutan tampilan (default: 0) |
| `ai_credits_per_month` | number | - | Jumlah kredit AI per bulan (default: 10) |
| `max_tasks` | number | - | Maksimal tugas, 0 = unlimited (default: 0) |
| `max_notes` | number | - | Maksimal catatan, 0 = unlimited (default: 0) |
| `max_workspaces` | number | - | Maksimal workspace, 0 = unlimited (default: 0) |
| `max_storage_mb` | number | - | Maksimal penyimpanan dalam MB (default: 100) |
| `max_team_members` | number | - | Maksimal anggota tim per workspace (default: 0) |
| `max_companies` | number | - | Maksimal company yang bisa dibuat (default: 0) |
| `company_slots` | number | - | Jumlah slot company (default: 0) |
| `allow_company_features` | boolean | - | Izinkan fitur bisnis/company (default: `false`) |
| `is_custom_plan` | boolean | - | Paket custom yang bisa pilih fitur per fitur (default: `false`) |
| `enabled_features` | object | - | Fitur yang diaktifkan (untuk paket Custom) |
| `feature_prices` | object | - | Harga per fitur untuk paket Custom (Rupiah/bulan) |

## Siklus Hidup Pengguna (State Diagram)

Diagram berikut menunjukkan siklus hidup pengguna sejak registrasi hingga menjadi pengguna aktif dalam sistem ERP:

```mermaid theme={null}
stateDiagram-v2
    [*] --> Registrasi : Pengguna mendaftar akun baru

    state "Registrasi" as Registrasi
    state "Verifikasi Email" as VerifikasiEmail
    state "Trial Aktif" as TrialAktif
    state "Onboarding Perusahaan" as OnboardingPerusahaan
    state "Undangan Dikirim" as UndanganDikirim
    state "Menunggu Respons" as MenungguRespons
    state "Bergabung ke Perusahaan" as BergabungPerusahaan
    state "Setup Workspace" as SetupWorkspace
    state "Aktif Berlangganan" as AktifBerlangganan
    state "Mode Read-Only" as ModeReadOnly
    state "Kedaluwarsa" as Kedaluwarsa
    state "Nonaktif" as Nonaktif

    Registrasi --> VerifikasiEmail : Email verifikasi dikirim
    VerifikasiEmail --> TrialAktif : Email terverifikasi, trial dimulai
    VerifikasiEmail --> Nonaktif : Verifikasi gagal/kedaluwarsa

    TrialAktif --> OnboardingPerusahaan : Owner membuat company baru
    TrialAktif --> AktifBerlangganan : Langsung berlangganan

    OnboardingPerusahaan --> AktifBerlangganan : Memilih paket & melakukan pembayaran
    OnboardingPerusahaan --> TrialAktif : Melewati onboarding, tetap di trial

    AktifBerlangganan --> UndanganDikirim : Owner mengundang anggota baru
    UndanganDikirim --> MenungguRespons : Email undangan dikirim
    MenungguRespons --> BergabungPerusahaan : Undangan diterima (accepted)
    MenungguRespons --> Nonaktif : Undangan ditolak/kedaluwarsa (rejected/expired/cancelled)

    BergabungPerusahaan --> SetupWorkspace : CompanyMember dibuat dengan status active
    SetupWorkspace --> AktifBerlangganan : Workspace siap digunakan

    AktifBerlangganan --> ModeReadOnly : Membership expired, masuk grace period 3 hari
    ModeReadOnly --> AktifBerlangganan : Perpanjang membership sebelum grace period habis
    ModeReadOnly --> Kedaluwarsa : Grace period 3 hari terlewati

    Kedaluwarsa --> AktifBerlangganan : Membeli membership baru
    Kedaluwarsa --> Nonaktif : Tidak memperpanjang

    Nonaktif --> [*]
```

## Alur Registrasi & Onboarding (Sequence Diagrams)

Diagram berikut menunjukkan detail teknis alur registrasi pengguna baru hingga aktif menggunakan sistem.

### 1. Alur Registrasi Pengguna Baru

```mermaid theme={null}
sequenceDiagram
    actor User as Pengguna Baru
    participant FE as Frontend (React)
    participant Auth as Auth Provider
    participant DB as PostgreSQL
    participant Email as Email Service

    User->>FE: Buka halaman registrasi
    FE->>FE: Tampilkan form (email, nama, password)
    User->>FE: Isi form & klik "Daftar"
    FE->>Auth: POST /auth/register (email, full_name, password)
    Auth->>DB: INSERT INTO User (email, full_name, role='user', subscription_plan='free')
    DB-->>Auth: User record created (id, email, full_name)
    Auth->>Auth: Generate verification token
    Auth->>Email: Kirim email verifikasi
    Email-->>User: Email verifikasi diterima
    User->>FE: Klik link verifikasi
    FE->>Auth: POST /auth/verify (token)
    Auth->>DB: UPDATE User SET verified = true
    DB-->>Auth: User verified
    Auth-->>FE: Registrasi berhasil, redirect ke login
    User->>FE: Login dengan email & password
    FE->>Auth: POST /auth/login
    Auth->>DB: SELECT User WHERE email = ? AND verified = true
    DB-->>Auth: User record
    Auth-->>FE: JWT token + user data
    FE->>FE: Redirect ke dashboard (subscription_plan = 'free', trial dimulai)
```

### 2. Alur Pembuatan Perusahaan (Company Creation)

```mermaid theme={null}
sequenceDiagram
    actor Owner as Owner / User
    participant FE as Frontend (React)
    participant API as Base44 API
    participant DB as PostgreSQL
    participant Pay as Payment Gateway

    Owner->>FE: Klik "Buat Perusahaan Baru"
    FE->>FE: Tampilkan wizard onboarding (nama, industri, bisnis)
    Owner->>FE: Isi detail perusahaan & pilih paket
    FE->>API: POST /Company (name, industry, business_type, owner_id)
    API->>DB: INSERT INTO Company (name, owner_id, owner_email, industry, business_type)
    DB-->>API: Company record created (id)

    API->>API: Cek company_slots_purchased pada User
    alt Paket gratis & belum punya company
        API-->>FE: Error: perlu upgrade paket
        FE->>Owner: Tampilkan prompt upgrade
        Owner->>FE: Pilih paket & bayar
        FE->>Pay: Proses pembayaran (Midtrans/Xendit/Stripe)
        Pay-->>FE: Pembayaran berhasil
        FE->>API: POST /User/upgrade (plan, payment_reference)
        API->>DB: UPDATE User SET subscription_plan = 'business', membership_start_date = NOW()
    end

    API->>DB: UPDATE User SET active_company_id = Company.id
    API->>DB: INSERT INTO CompanyMember (company_id, user_id, user_email, role='owner', status='active')
    API->>DB: INSERT INTO Workspace (name='Default', owner_id, company_id, is_personal=false)
    API->>DB: INSERT INTO WorkspaceMember (workspace_id, user_id, role='owner')

    API->>DB: Inisialisasi modul default (POS, Inventory, Finance)
    API->>DB: INSERT INTO CompanyModuleSettings (company_id, active_modules)
    API->>DB: INSERT INTO CompanyPOSSettings (company_id)
    API->>DB: INSERT INTO CompanyAttendanceSettings (company_id)

    API-->>FE: Company berhasil dibuat
    FE->>FE: Redirect ke dashboard company baru
```

### 3. Alur Setup Workspace & Undangan Anggota

```mermaid theme={null}
sequenceDiagram
    actor Admin as Admin / Owner
    participant FE as Frontend (React)
    participant API as Base44 API
    participant DB as PostgreSQL
    participant Email as Email Service
    actor Member as Anggota Baru

    Admin->>FE: Buka halaman "Kelola Tim"
    FE->>API: GET /CompanyMember?company_id={active_company_id}
    API->>DB: SELECT CompanyMember WHERE company_id = ?
    DB-->>API: Daftar anggota saat ini
    API-->>FE: Tampilkan daftar anggota

    Admin->>FE: Klik "Undang Anggota Baru"
    FE->>FE: Form undangan (email, role, department, permissions)
    Admin->>FE: Isi detail & klik "Kirim Undangan"

    FE->>API: POST /CompanyInvitation (company_id, invited_email, role, permissions)
    API->>DB: INSERT INTO CompanyInvitation (company_id, invited_email, invited_by, role, status='pending', expires_at=NOW()+7days)
    DB-->>API: Invitation created
    API->>Email: Kirim email undangan ke invited_email
    Email-->>Member: Email undangan diterima ("Anda diundang bergabung ke PT Selera Pedas Nusantara")

    Note over Member: ... Anggota membuka email & klik link ...

    Member->>FE: Klik link undangan
    FE->>API: GET /CompanyInvitation/{id}
    API->>DB: SELECT CompanyInvitation WHERE id = ? AND status = 'pending'
    DB-->>API: Invitation detail
    API-->>FE: Tampilkan detail undangan & form terima/tolak

    alt Menerima Undangan
        Member->>FE: Klik "Terima Undangan"
        FE->>API: POST /CompanyInvitation/{id}/accept
        API->>DB: UPDATE CompanyInvitation SET status='accepted', accepted_at=NOW()
        API->>DB: INSERT INTO CompanyMember (company_id, user_email, role, status='active', invited_by)
        API->>DB: INSERT INTO WorkspaceMember (workspace_id, user_id, role='member')
        API->>DB: UPDATE User SET active_company_id = Company.id (jika belum punya)
        API-->>FE: Berhasil bergabung
        FE->>FE: Redirect ke dashboard company
    else Menolak Undangan
        Member->>FE: Klik "Tolak"
        FE->>API: POST /CompanyInvitation/{id}/reject
        API->>DB: UPDATE CompanyInvitation SET status='rejected', rejected_at=NOW()
    end
```

### 4. Alur Login Pertama Kali & Switch Company

```mermaid theme={null}
sequenceDiagram
    actor User as Pengguna
    participant FE as Frontend (React)
    participant Auth as Auth Provider
    participant API as Base44 API
    participant DB as PostgreSQL

    User->>FE: Buka aplikasi & klik "Login"
    FE->>Auth: POST /auth/login (email, password)
    Auth->>DB: Validasi kredensial
    DB-->>Auth: User record
    Auth-->>FE: JWT token + user data

    FE->>FE: Cek state user

    alt User punya active_company_id
        FE->>API: GET /CompanyMember?user_id={id}&company_id={active_company_id}
        API->>DB: SELECT CompanyMember WHERE user_id = ? AND company_id = ?
        DB-->>API: CompanyMember record
        API-->>FE: Role & permissions

        alt membership masih aktif
            FE->>FE: Load modul sesuai permissions
            FE->>FE: Redirect ke dashboard company
            Note over User: Langsung masuk ke workspace perusahaan
        else membership expired (is_readonly_mode = true)
            FE->>FE: Tampilkan mode read-only
            FE->>User: "Membership Anda telah expired. Silakan perpanjang."
            User->>FE: Klik "Perpanjang Membership"
            FE->>FE: Redirect ke halaman pricing
        end

    else User TIDAK punya active_company_id (personal user)
        FE->>FE: Redirect ke personal dashboard
        FE->>User: Tampilkan opsi "Buat Perusahaan" atau "Terima Undangan"

        alt Ada CompanyInvitation pending
            FE->>API: GET /CompanyInvitation?invited_email={email}&status=pending
            API-->>FE: Daftar undangan pending
            FE->>User: Tampilkan notifikasi "Anda memiliki {n} undangan perusahaan"
        end
    end

    Note over User,FE: === Switch Company (untuk Business+ users) ===

    User->>FE: Klik avatar > "Ganti Perusahaan"
    FE->>API: GET /CompanyMember?user_id={id}
    API->>DB: SELECT CompanyMember WHERE user_id = ? AND status = 'active'
    DB-->>API: Daftar company yang diikuti user
    API-->>FE: List company dengan nama & role
    FE->>User: Tampilkan daftar perusahaan
    User->>FE: Pilih perusahaan tujuan
    FE->>API: PATCH /User/{id} (active_company_id = selected_company_id)
    API->>DB: UPDATE User SET active_company_id = ?
    FE->>FE: Reload seluruh modul dengan context company baru
    FE->>FE: Redirect ke dashboard company yang dipilih
```

***

**Butuh Bantuan?**

* Email: [support@quinnofspicy.com](mailto:support@quinnofspicy.com)
* WhatsApp: +62 812-3456-7890
* Website: [https://quinnofspicy.com](https://quinnofspicy.com)
* Dokumentasi: [https://quinnofspicy.mintlify.site](https://quinnofspicy.mintlify.site)


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