# 📚 AIPOS3 — Enterprise ERP + POS Technical Manual
# Version 1.2.0 — May 2026

> This document contains comprehensive technical documentation, installation guides, Dockerized branch setups, sync troubleshooting, and architectural specifications for the AIPOS3 Multi-Branch Offline-First ERP & POS system.

---

## 1. 📋 Progress Log & Release Notes

| Phase | Milestone | Features Integrated | Status |
|-------|-----------|---------------------|--------|
| **Phase 1** | Foundation | Laravel 12 setup, schema migrations, models & UUID v7 traits | ✅ Selesai |
| **Phase 2** | Accounting | Dynamic Chart of Accounts (COA), balanced Double-Entry Jurnal Umum, Buku Besar, Neraca, Laba Rugi | ✅ Selesai |
| **Phase 3** | Inventory | Stock balances, real-time movements, inter-warehouse transfers, physical count opname | ✅ Selesai |
| **Phase 4** | Sync Engine | Triple-Redis Pattern (Queue, Streams, Pub/Sub), HMAC signatures, version conflict resolvers | ✅ Selesai |
| **Phase 5** | POS PWA | Dexie.js offline catalog cache, keyboard scanner hook, split payments, suspensions, thermal receipt print | ✅ Selesai |
| **Phase 6** | Infrastructure | Docker Compose orchestration, Swoole (Octane) configs, Horizon & Reverb configurations | ✅ Selesai |
| **Phase 7** | Verification | 12 Feature integration tests (100% green validation) | ✅ Selesai |

---

## 2. 🛠️ Installation Guide (Cara Pasang)

### System Requirements

| Core Dependency | Required Version | Purpose |
|-----------------|------------------|---------|
| **PHP** | 8.4+ | Core Backend Language (Strict Typing, Property Hooks) |
| **MySQL / MariaDB** | 8.0+ / 10.6+ | Main Relational Store (Source of Truth) |
| **Redis** | 7.0+ | Triple-Redis Pattern (Queues, Streams, Pub/Sub) |
| **Node.js & NPM** | 20+ | PWA Service-Worker, Alpine.js & CSS building |

### Production PHP Extensions
Ensure these extensions are active in `php.ini`:
- `pdo_mysql`, `bcmath`, `gd`, `xml`, `redis`
- `swoole` (Highly recommended for high-performance Octane deployments)

---

### Step-by-Step Installation

#### Step 1: Clone and Enter Directory
```bash
git clone https://github.com/your-enterprise/aipos3.git
cd aipos3
```

#### Step 2: Install PHP & JS Packages
```bash
composer install --no-dev --optimize-autoloader
npm install
```

#### Step 3: Configure Environment Variables
Copy the template and modify the properties:
```bash
cp .env.example .env
```
Ensure key environment params are configured in `.env`:
```ini
APP_ENV=production
APP_DEBUG=false
APP_KEY=base64:xxx...

# Branch Setup (0 for HO, >0 for Branch nodes)
APP_BRANCH_ID=1

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=aipos3_db
DB_USERNAME=root
DB_PASSWORD=secret

# Redis Configuration (Triple-Redis Connections)
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
```

#### Step 4: Generate Application Secret Cryptography
```bash
php artisan key:generate
```

#### Step 5: Run Database Migrations and Seed Master Data
```bash
php artisan migrate --force
php artisan db:seed --class=DatabaseSeeder --force
```

#### Step 6: Start Application Services
For a standard dev or production stack, run these processes via systemd or Supervisor:
```bash
# Start Laravel Octane (Swoole high-performance engine)
php artisan octane:start --server=swoole --host=0.0.0.0 --port=8000

# Start Horizon background queue manager
php artisan horizon

# Start Reverb WebSockets for real-time channel notifications
php artisan reverb:start --host=0.0.0.0 --port=8080
```

---

## 3. 🐳 Dockerized Branch Server Deployment

Branch servers can be deployed instantly using Docker containers. The stack packages the Swoole Octane app, Redis (configured for Triple-Redis), MySQL, Horizon, and Reverb inside a virtual network boundary.

### `Dockerfile`
The docker container is pre-optimized for high-performance Swoole and caching extensions:
```dockerfile
FROM php:8.4-cli-alpine

RUN apk add --no-cache \
    curl libpng-dev libxml2-dev zip unzip git nodejs npm autoconf g++ make linux-headers

RUN docker-php-ext-install pdo_mysql bcmath gd xml
RUN pecl install swoole redis && docker-php-ext-enable swoole redis

COPY --from=composer:latest /usr/bin/composer /usr/bin/composer
WORKDIR /var/www/html
COPY . .
RUN composer install --no-dev --optimize-autoloader
RUN npm install && npm run build

EXPOSE 8000 8080
CMD ["php", "artisan", "octane:start", "--server=swoole", "--host=0.0.0.0", "--port=8000"]
```

### Deploying the Stack
1. Ensure Docker and Docker Compose are installed on the Branch server.
2. Spin up the containers using the command:
   ```bash
   docker-compose up -d --build
   ```
3. Initialize the database schema and seed standard data:
   ```bash
   docker-compose exec app php artisan migrate --force
   docker-compose exec app php artisan db:seed --force
   ```

---

## 4. ⚡ "Triple-Redis" Synchronization & Cryptography Architecture

To support massive scalability up to 1000 branches while guaranteeing sub-second response times, AIPOS3 utilizes a dedicated Redis instance segmented into three distinct connections inside `config/database.php`:

```php
'redis' => [
    'queue' => ['database' => 0],    // Horizon jobs (Push, Pull, Broadcasts)
    'streams' => ['database' => 1],  // Immutable transaction event sourcing logs
    'pubsub' => ['database' => 2],   // Realtime dashboard updates & notification alerts
]
```

### Sync Flow
When a POS transaction is saved locally on a branch node:
1. **Local Save**: Persists to MySQL (Source of truth).
2. **Immutable Log (Streams)**: Event written to `transactions_stream` (db 1).
3. **Queue Job Dispatch**: `PushTransactionJob` queued on `sync_high` (db 0) to execute background HTTP delivery.
4. **Pub/Sub Notification**: Real-time push alert published to channel `branch.{id}.sync` (db 2) to update the dashboard instantly without browser polling.

### security: HMAC-SHA256 Webhook Verification
M2M webhook routes (`/api/sync/upload`, `/api/sync/broadcast`, `/api/sync/pull`) require secure signatures.
1. The sender sorts the payload alphabetically (`ksort`).
2. Calculates the signature:
   $$\text{Signature} = \text{hash\_hmac}('sha256', \text{json\_encode}(\text{payload}), \text{secret\_key})$$
3. Sends signature in the `X-AIPOS3-Signature` HTTP header.
4. The receiver middleware (`ValidateApiSignature`) intercepts, recalculates the HMAC, and validates using `hash_equals` to protect against payload tampering and replay attacks.

---

## 5. 📱 PWA & Offline-First POS System

The POS Terminal (`/pos`) is designed to operate 100% offline (e.g., during network drops or in isolated areas) by leveraging IndexedDB and browser PWA capabilities.

### Client-Side Database (Dexie.js / IndexedDB)
Stores local products, customers, transactions, items, payments, and drafts securely:
- **`products`**: Product details, SKUs, and barcodes cached for fast scanning.
- **`customers`**: Complete customer profiles (offline created customers are flagged with `sync_status = 'pending'`).
- **`pos_transactions`**, **`pos_transaction_items`**, **`pos_payments`**: Transaction records queued locally for sync.
- **`suspended_transactions`**: Caches cart states for drafts/suspensions.

### Barcode Scanner Hook
The POS UI actively intercepts rapid keystrokes (<50ms intervals) typical of USB/Bluetooth physical scanners. Once an `Enter` key terminates the buffer, the app triggers a high-speed catalog lookup (<10ms) and adds the item to the cart immediately.

### Online Synchronization
A network status handler evaluates connectivity (`navigator.onLine`). When internet is restored:
1. Retrieves all records from Dexie where `sync_status === 'pending'`.
2. Packages records as an array matching the endpoint contract:
   `POST /api/sync/offline/sync`
3. The server receives the payload, resolves potential conflict versions, registers accounting double-entries, adjusts stock card balances, and returns a success response.
4. The PWA marks those records as `'synced'` in IndexedDB, preventing duplicate uploads.

---

## 6. 🔍 Troubleshooting Sync Conflicts

If synchronization experiences delays or conflicts:

### Aturan Resolusi Konflik (Conflict Rules)
When a record sync packet arrives at Head Office (HO) or Branch:
1. **Rule 1 (Higher Version Wins)**: The engine compares `sync_version`. The higher version overwrites the existing row.
2. **Rule 2 (Last Write Wins)**: If versions are identical, the row with the most recent `updated_at` timestamp is written.
3. **Fallback (Manual Override)**: If both version and timestamp are equal, the incoming payload is written to the `sync_conflicts` table for manual administrator review:

```sql
SELECT * FROM sync_conflicts WHERE resolution_status = 'pending';
```

### Sync Log Diagnostics
Use Redis CLI command line to audit streams and jobs:
```bash
# Check raw immutable sync stream records
redis-cli -n 1 xrange transactions_stream - +

# Monitor Horizon queue status
php artisan horizon:status
```

---
*Dokumen manual teknis ini dikelola oleh Lead Architect AIPOS3.*  
*Bahasa: Indonesia / Inggris (Formal)*
