# Dokumen Desain Sistem: Enterprise POS Retail (Final Gold Standard)
**Arsitektur:** Python Native Edge Client & PHP 5.6 CodeIgniter 3 Backend

---

## 1. Pendahuluan
Dokumen ini merupakan versi final hasil penggabungan dua desain sebelumnya, mengombinasikan **operasional retail yang kuat** dengan **kontrol finansial, kepatuhan akuntansi, dan standar audit tertinggi**.

Tujuan utama:
- Operasional toko tanpa gangguan (offline-first)
- Kepatuhan pajak & akuntansi
- Pencegahan fraud & kebocoran margin
- Skalabilitas enterprise

---

## 2. Arsitektur: Hybrid Edge Computing

### 2.1 Python Client (Edge)
- Database lokal terenkripsi (SQLite/PostgreSQL + SQLCipher)
- Multithreading (UI & Sync terpisah)
- Direct hardware access (Printer, Scanner, Cash Drawer)
- Offline-first (tetap jualan tanpa internet)

### 2.2 CI3 Backend (Central)
- Stateless API (HMAC Authentication)
- Single Source of Truth (produk, harga, promo)
- Reporting & Analytics (Laba rugi, tren)

---

## 3. Modul Penjualan (Sales)

### 3.1 Core Sales
- Multi-payment & split bill
- Transaction hold (parkir transaksi)
- Integrated payment (EDC/e-wallet)

### 3.2 Guard System (Critical Control)
- Guard HPP: larangan jual di bawah modal
- Guard Settlement: wajib tutup shift
- Guard Price: larangan jual tanpa harga resmi

### 3.3 Return & Refund
- Validasi struk asli
- Reason code wajib
- Retur parsial/full

---

## 4. Standar Akuntansi & Pajak (Compliance)

- Tax Separation Logic (DPP & PPN)
- Price Versioning (historical pricing)
- Inter-branch invoicing (utang-piutang cabang)
- Automatic tax reporting preparation (e-Faktur ready)

---

## 5. Promo Engine & Profit Protection

### 5.1 Promo Stacking Rule (Hierarki)
1. Produk
2. Bundling
3. Member
4. Transaksi

### 5.2 Promo Type
- Accumulative
- Exclusive (ambil terbaik)

### 5.3 Nett Price Calculation
- Diskon dihitung berurutan (bukan dari harga awal)

### 5.4 Loyalty System
- Tier member (Silver/Gold)
- Point accumulation & redemption

---

## 6. Manajemen Inventaris

- Global stock lookup (antar cabang)
- Inventory adjustment + reason code
- Automated Reorder Point (ARO)
- Inter-branch stock transfer & invoicing

---

## 7. Sinkronisasi Data (Data Integrity)

### 7.1 Upload
- JSON chunking
- Atomic transaction (rollback jika gagal)
- Retry queue

### 7.2 Download
- Delta sync (berbasis timestamp)

---

## 8. Keamanan & Fraud Prevention

- HMAC-SHA256 authentication
- Encryption at rest (SQLCipher)
- Audit trail (semua aktivitas non-sales)

### Blind Balancing
- Kasir hitung uang manual
- Selisih tercatat permanen

---

## 9. Database Design

### Local (Python)
- sales_header
- sales_detail
- sync_queue

### Backend (CI3)
- t_sales
- m_products
- m_audit_logs

---

## 10. Profit vs Effort Analysis

| Fitur | Dampak Profit | Efisiensi |
|------|--------------|----------|
| Promo Stacking | Lindungi margin | Otomatis diskon |
| Blind Balancing | Kurangi shrinkage | Minim audit manual |
| Tax Logic | Hindari denda | Otomatis pajak |
| Offline Mode | No downtime | Operasional stabil |
| ARO | Hindari lost sales | Auto procurement |

---

## 11. Kesimpulan

Sistem ini merupakan kombinasi terbaik antara:
- Kecepatan operasional
- Kontrol finansial
- Kepatuhan regulasi
- Skalabilitas enterprise

Level sistem:
**Setara POS + ERP Lite (Retail Grade Enterprise System)**

Siap untuk:
- Multi-cabang
- Audit eksternal (Big4)
- Integrasi sistem keuangan lanjutan

---

## 12. Rekomendasi Lanjutan (Next Level)

- Integrasi ke ERP (SAP / Odoo)
- Real-time dashboard (BI tools)
- AI demand forecasting
- Fraud detection berbasis pattern

---

## 13. Diagram Arsitektur & Data Flow

### 13.1 High-Level Architecture
```text
+-----------------------+            Internet / VPN            +-----------------------------+
|   POS Terminal Store  |  <--------------------------------> |   Central Backend (CI3)     |
|-----------------------|                                      |-----------------------------|
| Python Native Client  |                                      | Stateless API               |
| Local DB (SQLCipher)  |                                      | Master Data Service         |
| Sync Engine           |                                      | Promo Engine                |
| Hardware Controller   |                                      | Tax & Accounting Service    |
+-----------------------+                                      | Reporting & Analytics       |
         |                                                     +-----------------------------+
         |
         v
+-----------------------+
| Printer / Scanner /   |
| Cash Drawer / EDC     |
+-----------------------+
```

### 13.2 Transaction Flow (Sales)
```text
Kasir Scan Barang
      ↓
Harga + Promo + Guard Validation di POS Lokal
      ↓
Pembayaran (Cash / Card / E-wallet / Split)
      ↓
Simpan ke Local DB
      ↓
Cetak Struk
      ↓
Masuk Sync Queue
      ↓
Upload Berkala ke Backend
      ↓
Backend Validasi Signature + Atomic Save
      ↓
Masuk ke Reporting, Pajak, dan Konsolidasi Pusat
```

### 13.3 Master Data Sync Flow
```text
Pusat Update Produk / Harga / Promo
      ↓
Backend Simpan updated_at
      ↓
POS kirim last_sync_timestamp
      ↓
Backend kirim Delta Data
      ↓
POS Update Master Lokal
      ↓
Audit log sinkronisasi tersimpan
```

### 13.4 Return / Refund Flow
```text
Input No. Struk Asli
      ↓
Validasi transaksi lokal / pusat
      ↓
Pilih item retur (full / partial)
      ↓
Wajib isi reason code
      ↓
Hitung reversal penjualan + pajak
      ↓
Simpan audit trail
      ↓
Sync ke pusat sebagai transaksi koreksi
```

### 13.5 Blind Balancing Flow
```text
Shift Berakhir
      ↓
Kasir hitung uang fisik manual
      ↓
Input nominal ke sistem tanpa lihat saldo sistem
      ↓
Sistem bandingkan expected vs actual
      ↓
Selisih dicatat permanen
      ↓
Supervisor review / approval bila perlu
```

---

## 14. Modul ERP-Ready (Finance & Accounting Layer)

Agar sistem naik kelas dari POS enterprise menjadi **POS + ERP Lite**, dibutuhkan lapisan akuntansi otomatis.

### 14.1 General Ledger Integration
Setiap transaksi yang tersinkron harus dapat menghasilkan jurnal otomatis.

Contoh jurnal penjualan tunai:
- Debit Kas
- Kredit Penjualan
- Kredit PPN Keluaran

Contoh jurnal penjualan kartu:
- Debit Piutang Settlement / Bank Clearing
- Kredit Penjualan
- Kredit PPN Keluaran
- Debit Expense MDR (jika fee langsung dipotong)

Contoh jurnal retur:
- Debit Retur Penjualan
- Debit PPN Keluaran
- Kredit Kas / Bank / Piutang Settlement

### 14.2 Chart of Accounts (COA) Minimum
- Kas Kecil Toko
- Bank / Payment Gateway Clearing
- Piutang Settlement EDC
- Persediaan Barang Dagang
- HPP
- Penjualan Retail
- Diskon Penjualan
- Retur Penjualan
- PPN Keluaran
- Selisih Kas
- Hutang Antar Cabang
- Piutang Antar Cabang
- Biaya MDR / Payment Fee

### 14.3 Auto Journal Rules
- Penjualan menghasilkan jurnal revenue + tax
- Retur menghasilkan reversal journal
- Inventory adjustment menghasilkan koreksi persediaan
- Stock transfer antar cabang menghasilkan jurnal due to / due from
- Blind balancing menghasilkan jurnal selisih kas bila di-posting

### 14.4 Costing & Inventory Valuation
Sistem harus mendukung minimal salah satu metode berikut:
- Moving Average
- FIFO

Rekomendasi retail multi-cabang:
- Gunakan **Moving Average** untuk kesederhanaan operasional
- Simpan **historical purchase cost** untuk audit dan analitik margin

### 14.5 Financial Period Control
- Tutup harian per shift
- Tutup bulanan untuk posting akuntansi
- Lock period agar transaksi backdate tidak merusak laporan
- Otorisasi khusus untuk reopening period

### 14.6 Tax Readiness
- Pisahkan DPP dan PPN per baris transaksi
- Simpan tax code per item
- Siapkan export format e-Faktur / tax reporting
- Bedakan item taxable vs non-taxable

---

## 15. Roadmap Implementasi (Phased Delivery)

### Phase 1 — Foundation POS Core
Target:
- Transaksi jual beli stabil
- Offline-first berjalan
- Hardware integration siap

Scope:
- Master produk
- Scan barcode
- Keranjang & pembayaran
- Cetak struk
- Local DB
- Sync queue dasar
- Login user & role dasar

Deliverable:
- MVP kasir siap pilot 1 toko

### Phase 2 — Sync & Central Control
Target:
- Data pusat dan cabang konsisten
- Operasional multi-cabang mulai stabil

Scope:
- API CI3
- Delta sync
- Upload transaksi chunking
- Global stock lookup
- Price sync
- Promo sync
- Audit log dasar

Deliverable:
- Pilot multi-store

### Phase 3 — Financial Control & Fraud Prevention
Target:
- Sistem siap audit internal

Scope:
- Blind balancing
- Guard HPP / Price / Settlement
- Advanced return & refund
- Reason code enforcement
- Inventory adjustment
- Encryption at rest
- Signature validation penuh

Deliverable:
- Audit-grade POS

### Phase 4 — Advanced Promo & Loyalty
Target:
- Meningkatkan revenue tanpa merusak margin

Scope:
- Promo stacking engine
- Exclusive vs accumulative rule
- Tiered discount
- Member loyalty point
- Voucher / bank promo

Deliverable:
- Revenue optimization layer

### Phase 5 — ERP Lite & Accounting Integration
Target:
- Jurnal otomatis dan rekonsiliasi keuangan

Scope:
- COA mapping
- Auto journal posting
- Settlement reconciliation
- Inter-branch invoicing
- Tax export
- Financial period locking

Deliverable:
- POS + ERP Lite

### Phase 6 — Analytics & Forecasting
Target:
- Manajemen dapat data real-time dan prediksi operasional

Scope:
- BI dashboard
- Margin analysis
- Sell-through analysis
- Reorder recommendation
- Fraud pattern detection
- Demand forecasting

Deliverable:
- Data-driven retail platform

---

## 16. Breakdown Modul Implementasi Teknis

### 16.1 POS Client Modules (Python)
- Auth & User Session Module
- Product Cache Module
- Cart & Pricing Engine
- Payment Processing Module
- Receipt Printing Module
- Hardware Adapter Module
- Local Database Repository
- Sync Queue Worker
- Audit Logger
- Settlement Module

### 16.2 Backend Modules (CI3)
- API Authentication Middleware
- Master Data Service
- Price Service
- Promo Service
- Transaction Ingestion Service
- Accounting Mapping Service
- Inventory Service
- Tax Service
- Audit & Monitoring Service
- Reporting API

### 16.3 Integration Modules
- Payment Gateway / EDC Integration
- ERP Connector
- Tax Export Connector
- Notification / Alert Connector
- BI Export Connector

---

## 17. Standar Best Practice Tertinggi

### 17.1 Operasional
- Offline-first mandatory
- Semua transaksi dapat direkonstruksi dari local log
- Tidak ada blocking UI saat sync berjalan

### 17.2 Keamanan
- Signature per request
- Secret rotation policy
- Database encryption di endpoint
- Role-based access control
- Device binding untuk terminal POS

### 17.3 Audit
- Immutable audit trail
- Reason code wajib untuk tindakan sensitif
- Supervisor override dengan jejak approval
- Clock synchronization untuk akurasi timestamp

### 17.4 Akuntansi
- Historical price disimpan permanen
- DPP dan PPN terpisah
- Jurnal otomatis dapat ditelusuri ke transaksi asal
- Rekonsiliasi settlement non-tunai wajib tersedia

### 17.5 Reliability
- Retry queue idempotent
- Duplicate transaction prevention
- Conflict resolution rule untuk master sync
- Health monitoring untuk terminal dan backend

---

## 18. KPI Keberhasilan Implementasi

### KPI Operasional
- Waktu transaksi rata-rata < 10 detik
- Uptime kasir > 99.5%
- Sinkronisasi berhasil > 98%

### KPI Finansial
- Selisih kas turun signifikan
- Shrinkage menurun
- Akurasi margin per produk meningkat
- Rekonsiliasi settlement lebih cepat

### KPI Audit & Compliance
- Temuan audit berkurang
- Kepatuhan pajak meningkat
- Semua retur punya reason code & referensi struk

---

## 19. Risiko Utama & Mitigasi

### Risiko Teknis
- PHP 5.6 bottleneck
  - Mitigasi: chunking, queue, caching, throttling
- Data duplikat saat retry
  - Mitigasi: idempotency key
- Local DB corrupt
  - Mitigasi: journaling, backup, integrity check

### Risiko Operasional
- Kasir bypass prosedur
  - Mitigasi: guard + role approval
- Promo salah konfigurasi
  - Mitigasi: sandbox validation + effective date
- Salah mapping jurnal
  - Mitigasi: UAT finance + approval matrix

---

## 20. Rekomendasi Final

Untuk standar tertinggi, sistem final sebaiknya diposisikan sebagai:

**Enterprise Retail POS with Accounting Control Layer**

---

# 🔧 21. Technical Specification (Developer Guide)

Dokumen ini diturunkan menjadi spesifikasi teknis implementatif untuk tim development.

---

## 21.1 Arsitektur Teknis Detail

### POS Client (Python)
- Framework: PyQt / Tkinter (UI)
- Database: SQLite + SQLCipher
- ORM: SQLAlchemy (recommended)
- Background Worker: Threading / Async Queue

### Backend (CI3)
- PHP 5.6 + CodeIgniter 3
- Database: MySQL
- API: REST (JSON)

---

## 21.2 Database Schema (Core Tables)

### Local POS (SQLite)

#### sales_header
- id (PK)
- invoice_no
- datetime
- subtotal
- discount_total
- tax_dpp
- tax_ppn
- grand_total
- payment_method
- payment_reference
- is_synced
- created_at

#### sales_detail
- id (PK)
- sales_id (FK)
- product_id
- qty
- price
- discount
- dpp
- ppn
- total
- hpp

#### sync_queue
- id
- payload_json
- status (pending/sent/failed)
- retry_count
- created_at

#### audit_log
- id
- user_id
- action
- reference_id
- timestamp

---

### Backend (MySQL)

#### t_sales
- id
- store_id
- invoice_no
- datetime
- total
- tax
- created_at

#### t_sales_detail
- id
- sales_id
- product_id
- qty
- price
- discount
- tax

#### m_products
- id
- name
- price
- hpp
- tax_code
- updated_at

#### m_coa
- id
- account_code
- account_name

#### t_journal
- id
- journal_date
- reference
- total_debit
- total_credit

#### t_journal_detail
- id
- journal_id
- account_code
- debit
- credit

---

## 21.3 API Endpoint Design

### Authentication
POST /api/auth
Body:
{
  "client_id": "STORE01",
  "timestamp": "",
  "signature": ""
}

---

### Upload Sales
POST /api/sales/upload
Headers:
- X-SIGNATURE

Body:
{
  "transactions": [ ... ]
}

Response:
{
  "status": "success"
}

---

### Get Master Data
GET /api/master?last_sync=timestamp

Response:
{
  "products": [],
  "prices": [],
  "promos": []
}

---

## 21.4 Promo Engine Logic (Pseudo Code)

```
price = base_price

price = apply_product_discount(price)
price = apply_bundle(price)
price = apply_member(price)
price = apply_transaction(price)

return price
```

---

## 21.5 Sync Engine Logic

```
for trx in unsynced_transactions:
    try:
        send_to_server(trx)
        mark_as_synced(trx)
    except:
        retry_queue.append(trx)
```

---

## 21.6 Accounting Auto Journal Mapping

### Sales Cash
- Debit Kas
- Credit Penjualan
- Credit PPN

### Sales Non-Cash
- Debit Piutang Settlement
- Credit Penjualan
- Credit PPN

### Return
- Debit Retur
- Debit PPN
- Credit Kas / Bank

---

## 21.7 Error Handling Standard

- Retry max 3x
- Log semua error
- Tidak boleh crash UI
- Gunakan idempotency key

---

## 21.8 Security Standard

- HMAC SHA256
- Timestamp validation (max 5 min)
- Encrypt local DB
- API rate limiting

---

## 21.9 Deployment Standard

### POS
- Windows / Linux terminal
- Auto update client

### Backend
- Apache / Nginx
- MySQL replication (optional)
- Redis (optional for cache)

---

## 21.10 Testing Checklist

### Functional
- Sales normal
- Return
- Multi payment

### Sync
- Offline → online
- Duplicate prevention

### Accounting
- Jurnal balance
- Tax correct

---

## 21.11 Coding Guideline

- Modular code (separate service layer)
- Logging wajib
- No hardcoded config
- Use environment config

---

## 21.12 Definition of Done (DoD)

Fitur dianggap selesai jika:
- Lulus unit test
- Lulus UAT
- Tidak merusak jurnal
- Tidak menyebabkan selisih kas

---

## 21.13 Enterprise Scale Blueprint (>10.000 Cabang)

### Prinsip Scale-Out
- API backend wajib stateless; session tidak boleh disimpan di memory server lokal.
- Kontrak endpoint legacy tetap dipertahankan (backward compatible), optimasi skala dilakukan di layer infrastruktur dan orchestration.
- Operasi tulis kritikal (upload transaksi, settlement, retur) wajib idempotent.
- Untuk kompatibilitas CI3/PHP 5.6, adaptasi dilakukan bertahap tanpa memaksa rewrite besar.

### Ingestion & Processing Model
- Endpoint kritikal melakukan validasi cepat, simpan minimal, lalu enqueue pekerjaan berat.
- Proses berat (kompilasi upload, posting jurnal, rekonsiliasi) dijalankan oleh worker asynchronous.
- Terapkan retry policy, exponential backoff, dan dead-letter queue untuk kasus gagal berulang.
- Audit trail wajib ditulis walau proses utama gagal, agar investigasi tetap lengkap.

### Data Layer untuk Skala Besar
- Data transaksi dipartisi berdasarkan periode dan/atau region/tenant.
- Query baca berat (reporting/monitoring) diarahkan ke read replica.
- Pisahkan penyimpanan audit immutable dari database OLTP transaksi utama.
- Terapkan lifecycle data (hot/warm/cold) agar performa query harian tetap stabil.

### Traffic Protection & Burst Control
- Rate limit per `machine_id`, `branch_id`, dan endpoint.
- Backpressure policy saat jam puncak settlement serentak.
- Circuit breaker untuk dependency eksternal (payment, service pihak ketiga).
- Batch window untuk job non-kritis agar tidak mengganggu transaksi kasir.

### Observability & Reliability
- Metric minimum: request rate, p95 latency, error rate, queue lag, worker failure rate.
- Trace ID end-to-end: POS -> API -> queue -> worker -> database.
- Alert berbasis SLO operasional, bukan hanya CPU/RAM.
- Disaster recovery drill berkala: restore backup, failover replica, replay queue.

### Target Non-Functional Minimum (>10.000 Cabang)

| Area | Target Minimum |
|------|----------------|
| Availability upload/settlement | >= 99.9% per bulan |
| Duplicate write committed | 0 (idempotency enforced) |
| RTO | <= 60 menit |
| RPO | <= 5 menit |
| Queue lag saat peak settlement | <= 15 menit (dengan surge policy) |

### Tahapan Implementasi Skala (Tanpa Breaking Contract)
1. Aktifkan idempotency, trace ID, dan rate limit di endpoint kritikal.
2. Introduce queue ingestion untuk upload/settlement; worker dapat scale horizontal.
3. Implement partitioning + read replica + pemisahan storage audit.
4. Implement DR automation dan uji failover berkala per region.

---

Dokumen ini sekarang siap digunakan langsung oleh:
- Backend Developer
- POS Developer
- QA Engineer
- System Architect

Sebagai acuan implementasi sistem end-to-end.


# 🧠 22. Value-Added Enhancements (Next-Level Enterprise Retail)

Untuk meningkatkan sistem dari **Enterprise POS + ERP Lite** menjadi **Retail Operating System (Retail OS)**, berikut adalah layer tambahan bernilai tinggi.

## 22.1 Decision Intelligence Layer

Mengubah sistem dari sekadar reporting menjadi pengambil keputusan otomatis.

Fitur:

* Auto Insight Engine (deteksi penurunan margin, anomali penjualan)
* Anomaly Detection (per kasir, produk, waktu)
* Prescriptive Recommendation (rekomendasi harga, promo, restock)

Tujuan:

* Membantu manajemen mengambil keputusan berbasis data secara real-time

---

## 22.2 Customer 360 & Omnichannel Integration

Menggabungkan seluruh interaksi customer dalam satu profil.

Fitur:

* Unified customer profile lintas cabang
* Integrasi e-commerce & marketplace
* Integrasi CRM (WhatsApp, loyalty, campaign)
* Customer segmentation (RFM model)

Tujuan:

* Meningkatkan revenue melalui personalisasi

---

## 22.3 Advanced Fraud & Risk Scoring Engine

Upgrade dari rule-based guard menjadi risk-based system.

Fitur:

* Risk score per transaksi
* Risk score per kasir
* Pattern detection (refund abnormal, void mencurigakan)
* Alert otomatis ke supervisor

Tujuan:

* Pencegahan fraud proaktif, bukan reaktif

---

## 22.4 Operational Automation Layer

Menuju sistem semi-otonom.

Fitur:

* Auto Purchase Order generation
* Auto stock redistribution antar cabang
* Dynamic pricing berdasarkan demand & aging stock

Tujuan:

* Mengurangi intervensi manual dan meningkatkan efisiensi

---

## 22.5 Data Platform & Analytics Layer

Fondasi untuk skala besar dan AI.

Fitur:

* Data warehouse (BigQuery / Snowflake)
* ETL/ELT pipeline
* Data lake untuk audit & raw log
* Advanced BI & dashboard

Tujuan:

* Mendukung analitik skala enterprise dan machine learning

---

## 22.6 Enterprise Governance & Control

Standar untuk perusahaan besar dan audit tingkat tinggi.

Fitur:

* Segregation of Duties (SoD)
* Approval workflow engine
* Policy-based rule configuration

Tujuan:

* Kepatuhan terhadap audit internal & eksternal (Big4-ready)

---

## 22.7 Platform & Extensibility

Mengubah sistem menjadi platform terbuka.

Fitur:

* Plugin system
* Public API untuk partner
* Webhook event system

Tujuan:

* Mendukung ekosistem integrasi (fintech, supplier, loyalty)

---

## 22.8 Supply Chain & Distribution (Advanced Layer)

Untuk skala retail besar (>1000 cabang).

Fitur:

* Warehouse Management System (WMS)
* Distribution Center management
* Supplier & procurement planning
* Lead time optimization
* Fill rate monitoring

Tujuan:

* Mengoptimalkan operasional dari hulu ke hilir

---

## 22.9 Positioning Akhir Sistem

Dengan seluruh enhancement ini, sistem diposisikan sebagai:

**Retail Operating System (Retail OS)**

---

## 22.10 Strategi Implementasi

Rekomendasi prioritas:

1. Decision Intelligence
2. Fraud Detection
3. Customer 360
4. Data Platform
5. Supply Chain (jika scale besar)

---

## 22.11 Catatan Penting

* Modular (bisa aktif/nonaktif)
* Premium layer untuk enterprise
* Tidak wajib untuk POS basic

---

Dokumen ini kini mencakup arah evolusi menuju platform retail enterprise kelas dunia.