# Primewear POS — Hybrid Offline-First Desktop App Roadmap

**Status:** Phase 6 done (6a/6b/6c) — 6d/6e remain out of scope  
**Base system:** Existing Laravel 12 + MySQL POS (`d:\laragon\www\pos`)  
**Target:** Electron desktop shell + offline queue + silent thermal printing for multiple billing counters  

This document is the single source of truth for phased delivery. Do **not** rewrite the whole POS. Integrate into the existing app (stores, terminals, sales, stock, products).

---

## Goals

1. Till can sell when the internet / server is temporarily down.
2. When online again, offline sales sync without duplicates (UUID + idempotency).
3. Receipt (and later label) printing is **silent** — no Chrome print preview.
4. Multiple counters (terminals) work against one server of truth.
5. Products, inventory, reports, lay-bys, and admin stay on the **server web POS** (same as today).

## Non-goals (unless a later phase explicitly includes them)

- Full offline lay-by / returns / purchasing / reports
- Rebuild UI from scratch in React (prefer wrapping / enhancing current POS UI first)
- Shopify / SMS / advanced omnichannel in this roadmap

---

## Architecture (target)

```text
┌─────────────────────────────────────────────────────────────┐
│  Electron Desktop App (per till PC)                         │
│  ┌───────────────────┐  ┌──────────────┐  ┌──────────────┐  │
│  │ POS UI            │  │ Dexie.js     │  │ Main process │  │
│  │ (existing web +   │→ │ IndexedDB    │  │ thermal IPC  │  │
│  │  offline helpers) │  │ catalog +    │  │ silent print │  │
│  └─────────┬─────────┘  │ sale queue   │  └──────┬───────┘  │
│            │            └──────┬───────┘         │          │
└────────────┼───────────────────┼─────────────────┼──────────┘
             │ online            │ sync            │ USB/network
             ▼                   ▼                 ▼
      Laravel API / Web     MySQL (server)    Receipt / Label
      (Sanctum + store)     stock of truth         printers
```

**Server of truth:** Laravel + MySQL  
**Till local cache:** Dexie (products, prices, stock snapshot, pending sales)  
**Printing:** Electron main + `node-thermal-printer` (or ESC/POS) via IPC  

Reuse existing concepts:

| Existing | Use for |
|----------|---------|
| `stores` | Store scoping |
| `pos_terminals` / `terminal_id` | Counter identity (prefer over a new `counter_id` unless needed as alias) |
| `Sale` / `SaleItem` / `Payment` | Persisted sales after sync |
| `StockService` | Stock decrements on sync |
| Settings `offline_mode_enabled` | Feature flag when ready |

---

## Phase overview

| Phase | Name | Outcome |
|-------|------|---------|
| **0** | Foundations & API auth | Tokens, terminal binding, readiness |
| **1** | Offline sales MVP + sync | Sell offline; sync sales when online |
| **2** | Electron shell + silent receipt print | Desktop app; no print preview for receipts |
| **3** | Catalog sync & stock safety | Reliable product cache; conflict handling |
| **4** | Silent label printing | XP-420B without browser dialog |
| **5** | Hardening & multi-till ops | Installer, updates, monitoring, training |
| **6** | Extended offline (optional) | Offline lay-by / returns / richer flows |

---

## Phase 0 — Foundations & API auth

**Goal:** Secure till identity so later sync APIs are safe.

### Deliverables

- Laravel Sanctum (or equivalent) API tokens for till users / device login
- Bind session/token to `store_id` + `terminal_id`
- Feature flag: `offline_mode_enabled` (already exists — wire into real behaviour later)
- API versioning prefix: `/api/v1/...`
- Health endpoint: `GET /api/v1/health` (server time, store, app min version)
- Document environment: `APP_URL`, CORS for Electron `file://` / `app://` if needed

### Acceptance criteria

- [x] Till can authenticate and receive a token scoped to one store + terminal
- [x] Unauthenticated sync/catalog calls are rejected
- [x] Existing web POS login still works unchanged

### Implemented (this repo)

| Item | Location |
|------|----------|
| Sanctum tokens + `store_id` / `terminal_id` on PAT | `personal_access_tokens` migration, `App\Models\PersonalAccessToken` |
| Till login / me / logout | `POST/GET /api/v1/auth/*` → `App\Http\Controllers\Api\V1\AuthController` |
| Health | `GET /api/v1/health` → includes `server_time`, `app_min_version`, `offline_mode_enabled` |
| Till middleware | `till` → `EnsureTillToken` (required for catalog/sync later) |
| Catalog auth stub | `GET /api/v1/catalog/ping` (Phase 3 fills real sync) |
| Feature flag | `Setting::bool('offline_mode_enabled')` exposed on health + `/auth/me` |
| Env / CORS notes | `.env.example` (`POS_APP_MIN_VERSION`, `CORS_*`) + `config/cors.php`, `config/pos.php` |
| Tests | `tests/Feature/Api/V1/TillAuthTest.php` |

### Estimate

**2–3 days**

---

## Phase 1 — Offline sales MVP + sync

**Goal:** If the network drops, cashier can still complete a simple sale; when online, sales sync once (no duplicates).

### Offline MVP scope (in)

- Scan / add lines from **cached** catalog
- Qty adjust / remove line
- Walk-in customer (optional name later)
- Payments: cash / card / eft / other (same as today)
- Complete sale → local UUID → queue
- Auto-retry sync when `navigator.onLine` / successful health ping

### Offline MVP scope (out — Phase 6+)

- Lay-by create/pay
- Returns / exchanges
- Purchase orders
- Product create/edit
- Reports / daily summary
- Manager PIN flows that require live server (unless cached rules added later)

### Backend deliverables

1. Migration on `sales` (and related as needed):
   - `uuid` — `string(36)` or `uuid`, **unique**, nullable for old rows then backfill optional
   - Keep `terminal_id` (existing); only add `counter_id` if product requires a separate business id — **prefer `terminal_id`**
2. Optional: `synced_at`, `source` (`online` \| `offline`) on `sales`
3. `POST /api/v1/sync-sales`
   - Auth required
   - Idempotency: if `uuid` exists → return success, **do not** double-decrement stock
   - `DB::transaction`
   - Create sale + items + payments
   - Decrement stock via existing `StockService`
   - Validate store/terminal matches token
4. Feature tests: duplicate UUID sync, stock decrement once, wrong store rejected

### Frontend / local deliverables

1. Dexie schema:
   - `products` / `variants` (sku, barcode, name, price, cost, vat, stock snapshot)
   - `pending_sales` (uuid, payload, created_at, status, last_error, attempts)
2. Detect offline: `navigator.onLine` **and** failed API/health fetch
3. Offline checkout path:
   - Build sale payload with **client-generated UUID** (crypto.randomUUID)
   - Save to `pending_sales`
   - Show “Saved offline — will sync”
4. Background sync worker:
   - On reconnect / interval / app focus
   - POST pending sales one-by-one (or small batch)
   - Mark synced / keep failed with error message
5. UI badge: Online / Offline / N pending sync

### Acceptance criteria

- [x] Kill network → complete sale → appears in local queue
- [x] Restore network → sale appears once on server
- [x] Sync same UUID twice → one sale, stock correct
- [x] Online sales path still works as today

### Implemented (this repo)

| Item | Location |
|------|----------|
| `sales.uuid` / `source` / `synced_at` | migration `add_offline_sync_fields_to_sales_table` |
| Idempotent sync | `POST /api/v1/sync-sales` → `OfflineSaleSyncService` |
| Catalog snapshot | `GET /api/v1/catalog` |
| Dexie queue + sync worker | `resources/js/offline-pos.js` + `resources/js/offline/db.js` |
| Web till token for sync | `TillTokenIssuer` via POS page when offline mode + terminal set |
| UI badge / offline cart | POS checkout + `pos.css` |
| Tests | `tests/Feature/Api/V1/SyncSalesTest.php` |

**How to use:** Settings → enable **Offline mode** → Checkout → select a **counter** → keep page online once to cache catalog → disconnect network → scan & complete sale → reconnect to sync.

### Estimate

**1.5–2.5 weeks**

---

## Phase 2 — Electron shell + silent receipt printing

**Goal:** Staff open a desktop app; receipts print with **no Chrome preview**.

### Deliverables

1. Electron main process app loading POS (`APP_URL` or packaged local + API)
2. Preload IPC bridge (contextIsolation on):
   - `printReceipt(payload)`
   - `listPrinters()` / save preferred receipt printer
3. Thermal print via `node-thermal-printer` (or ESC/POS) — USB and/or network
4. On sale complete (online or offline local complete): call IPC print (not `window.print()` when in Electron)
5. Fallback: if not Electron, keep current browser print behaviour
6. Till settings screen: choose receipt printer, paper width (80mm), test print
7. Two-profile problem solved for **receipts** (labels later in Phase 4)

### Acceptance criteria

- [x] Sale complete → receipt prints with no preview dialog
- [x] Wrong printer not used when receipt printer is configured
- [x] Web-only deploy still works without Electron

### Implemented (this repo)

| Item | Location |
|------|----------|
| Electron shell | `desktop/` (`main.js`, `preload.js`, `npm start`) |
| Silent receipt print IPC | `desktop/print.js` + `window.primewearDesktop.printReceipt` |
| Till printer settings | `desktop/settings.html` (Till → Printer settings) |
| Receipt page Electron path | `resources/views/sales/receipt.blade.php` |
| Browser fallback | `window.print()` when not in Electron |
| Offline local slip | `offline-pos.js` → IPC print on offline complete |

**Run:** `cd desktop && npm install && set POS_URL=http://pos.test && npm start`

### Estimate

**1–1.5 weeks**

---

## Phase 3 — Catalog sync & stock safety

**Goal:** Offline catalog stays fresh; multi-till oversell risk is controlled.

### Deliverables

1. `GET /api/v1/catalog` (or incremental `since=updated_at`)
   - Active products/variants, prices, barcodes, per-store stock
2. Electron/UI: pull catalog on login, on interval, on reconnect
3. Local stock snapshot decrement on offline sale (optimistic)
4. Server sync response:
   - `accepted` / `rejected_insufficient_stock` / `duplicate`
5. Till UI for rejected syncs: show sale, allow manager action (void local / force review)
6. Conflict policy (document + implement):
   - Default: reject sync if server available stock &lt; qty; keep pending for manager
   - Optional later: allow negative stock with flag

### Acceptance criteria

- [x] Price change on server appears on till after catalog pull
- [x] Two offline tills overselling same SKU → second sync handled per policy (not silent double-sell)
- [x] Cashiers see pending/failed sync clearly

### Implemented (this repo)

| Item | Location |
|------|----------|
| Incremental catalog | `GET /api/v1/catalog?since=&variant_ids=` |
| Merge + stock refresh | `resources/js/offline/db.js` (`mergeCatalog`) |
| Local optimistic stock | already on offline complete; refreshed after sync |
| Sync statuses | `accepted` / `duplicate` / `rejected_insufficient_stock` |
| Review UI | `#sync-review-panel` — Retry / Void local |
| Catalog pull cadence | on reconnect + every 60s while online |

### Conflict policy (default)

If server available stock &lt; offline qty → **reject** with `rejected_insufficient_stock`, keep sale in local **needs review** queue. Cashier may **Retry** after stock fix or **Void local** (does not create a server sale). Negative stock is not allowed.

### Estimate

**1–1.5 weeks**

---

## Phase 4 — Silent label printing (XP-420B)

**Goal:** Barcode labels print from Electron without browser dialog; receipt printer stays separate.

### Deliverables

1. IPC: `printLabels(labelJobs[])`
2. Separate saved printer setting: label printer vs receipt printer
3. Generate label content from existing label layout rules (SKU barcode, Was/Now without strikethrough, etc.)
4. Support 40×30 mm where driver/library allows; otherwise raw/bitmap path documented
5. Quick add / label print from Electron uses IPC path

### Acceptance criteria

- [x] Labels print silently to XP-420B
- [x] Receipts still go to receipt printer
- [x] No Chrome print dialog for either when running in Electron

### Implemented (this repo)

| Item | Location |
|------|----------|
| `printLabels` IPC | `desktop/print.js` + `preload.js` |
| Separate label printer | Till settings → Label printer (XP-420B) |
| Label page silent path | `resources/views/labels/print.blade.php` |
| Test label | Till settings → Test label |
| Size defaults | 40×30 mm (`labelWidthMm` / `labelHeightMm`) |

### Estimate

**1–1.5 weeks** (hardware-dependent; buffer +2 days if drivers are difficult)

---

## Phase 5 — Hardening & multi-till operations

**Goal:** Store-ready install and day-to-day operations.

### Deliverables

1. Windows installer (e.g. electron-builder NSIS)
2. Per-till config: store, terminal, API URL, printers
3. Auto-update strategy (or documented manual update)
4. Logging: sync failures, print failures (local file + optional server audit)
5. Ops checklist for client:
   - Open app each morning
   - Check Online + 0 pending
   - Test receipt print
6. Backup reminder: server DB backups remain primary
7. Performance: large catalog pagination / indexed Dexie queries
8. Security review: token storage in Electron (safeStorage), no secrets in renderer

### Acceptance criteria

- [x] Fresh Windows PC: install → login → sell → print → sync
- [x] 2+ tills documented and tested
- [x] Client training one-pager delivered

### Implemented (this repo)

| Item | Location |
|------|----------|
| NSIS installer scaffolding | `desktop/package.json` → `npm run dist` |
| Per-till config | POS URL, store/counter labels, receipt + label printers |
| Manual update strategy | Documented in `desktop/README.md` / ops checklist |
| Local logging | `desktop/logger.js` + Till → Open log folder |
| Ops checklist | `docs/OPS_CHECKLIST.md` + packaged `desktop/OPS_CHECKLIST.md` |
| Training one-pager | `docs/TRAINING_ONE_PAGER.md` |
| Multi-till notes | `docs/MULTI_TILL.md` |
| Catalog pagination | `GET /api/v1/catalog?page=&per_page=` + paged Dexie fill |
| Indexed Dexie barcode/SKU lookup | `resources/js/offline/db.js` |
| Security baseline | contextIsolation, no Node in renderer, safeStorage availability shown |

### Estimate

**1 week**

---

## Phase 6 — Extended offline (optional)

**Goal:** Only if client still needs more offline after Phases 1–5.

### Possible modules (each can be a sub-phase)

| Sub-phase | Scope |
|-----------|--------|
| **6a** | Offline customer lookup (cached) + attach to sale |
| **6b** | Offline discounts within cashier limit (cached settings) |
| **6c** | Offline returns against cached recent sales / barcode lookup (hard) |
| **6d** | Offline lay-by create/pay (hard — reservations/sync conflicts) |
| **6e** | Full offline product receive / stock adjust (usually keep online-only) |

### Recommendation

Ship **Phases 0–5** first. Revisit Phase 6 only with a clear client priority list.

### Implemented (this repo) — 6a / 6b / 6c

| Module | Status | Location |
|--------|--------|----------|
| **6a** Offline customers | Done | `GET /api/v1/customers` + Dexie + Offline extras panel |
| **6b** Offline discounts ≤ limit | Done | `GET /api/v1/bootstrap` settings + offline discount UI |
| **6c** Offline refunds (cached sales) | Done | `GET /api/v1/recent-sales` + `POST /api/v1/sync-returns` |
| **6d** Offline lay-by | Out of scope | Online only (shown in UI copy) |
| **6e** Offline stock receive | Out of scope | Online only |

**Client workflow (all scenarios):** `docs/CLIENT_FULL_WORKFLOW.md`

### Estimate

**1–3+ weeks** depending on modules chosen

---

## Suggested build order (execution)

```text
Phase 0  →  Phase 1  →  Phase 2  →  Phase 3  →  Phase 4  →  Phase 5
                              ↘______________↗
                         (Phase 3 can overlap end of Phase 2)
Phase 6 only after client sign-off on MVP
```

**Client value milestones**

1. After **Phase 1:** Offline billing works (sync when online) — still browser print OK  
2. After **Phase 2:** Feels like Zoho for receipt printing (no preview)  
3. After **Phase 3:** Safe multi-counter offline  
4. After **Phase 4:** Labels silent too  
5. After **Phase 5:** Installable store product  

---

## Rough total estimate (Phases 0–5)

| Phases | Effort |
|--------|--------|
| 0 | 2–3 days |
| 1 | 1.5–2.5 weeks |
| 2 | 1–1.5 weeks |
| 3 | 1–1.5 weeks |
| 4 | 1–1.5 weeks |
| 5 | 1 week |
| **Total 0–5** | **约 6–9 weeks** (1 full-stack dev, including hardware testing buffer) |

Quote with buffer for printer/driver issues on site.

---

## Client communication (short)

> We will upgrade the current Primewear POS into a hybrid offline-capable Windows app in phases:  
> (1) secure till APIs, (2) offline sales that sync when back online, (3) desktop app with silent receipt printing, (4) safer multi-till stock sync, (5) silent label printing, (6) installer and store rollout.  
> Products, inventory, and reports stay managed on the server. Offline starts with billing first; lay-bys/returns offline are a later optional phase.

---

## Phase kickoff checklist (each phase)

Before coding a phase:

- [ ] Confirm in/out scope with client  
- [ ] List APIs and UI touchpoints  
- [ ] List acceptance tests  
- [ ] Note impact on existing web POS  
- [ ] Deploy plan (server migrate + till app update if any)

After coding a phase:

- [ ] Tests green  
- [ ] Demo on real or staging printers where relevant  
- [ ] Update this file: mark phase status `Done` + date  

---

## Phase status tracker

| Phase | Status | Started | Done | Notes |
|-------|--------|---------|------|-------|
| 0 Foundations & API auth | Done | 2026-10-22 | 2026-10-22 | Sanctum till tokens + `/api/v1` health/auth |
| 1 Offline sales MVP + sync | Done | 2026-10-22 | 2026-10-22 | UUID sync + Dexie offline queue |
| 2 Electron + silent receipts | Done | 2026-10-22 | 2026-10-22 | `desktop/` silent print IPC |
| 3 Catalog sync & stock safety | Done | 2026-10-22 | 2026-10-22 | Incremental catalog + stock reject UI |
| 4 Silent labels | Done | 2026-10-22 | 2026-10-22 | XP-420B separate label printer IPC |
| 5 Hardening & multi-till ops | Done | 2026-10-22 | 2026-10-22 | Installer + ops/training docs |
| 6 Extended offline (optional) | Done (6a–6c) | 2026-10-22 | 2026-10-22 | Customers, discounts, cached refunds; lay-by/receive out |

---

## Reference: original prompt topics → phase mapping

| Original ask | Phase |
|--------------|--------|
| UUID on sales + idempotent `POST /api/v1/sync-sales` | **1** (schema prep may start in **0**) |
| Dexie master data + offline queue + sync worker | **1** + catalog pull in **3** |
| Electron + `node-thermal-printer` + IPC silent print | **2** (receipts), **4** (labels) |
| Multi billing counters | **0** (terminal auth), **1–3** (sync + conflicts), **5** (ops) |

---

*File: `docs/HYBRID_OFFLINE_ELECTRON_ROADMAP.md`*  
*Roadmap 0–6a/b/c complete. See `docs/CLIENT_FULL_WORKFLOW.md` for client install + all scenario scripts. 6d/6e only if separately funded.*
