# 13 — Implementation Plan

A ten-phase build plan. It expands the six-phase roadmap in [11 — Roadmap](11-roadmap.md)
and folds in the stack decisions from [12 — Stack & Platform](12-stack-and-platform.md) —
kernel-first, staging-table sync, hardware verification — while preserving the roadmap's
sequencing rules: POS before inventory, one branch before five, accounts before rollout.

---

## Overview

| # | Phase | Maps to roadmap | Indicative duration |
|---|---|---|---|
| 1 | Foundations & de-risking | Pre-Phase-1 decisions + doc 12 §7/§10 | 4–6 wks |
| 2 | Master data, access & catalog | Phase 1 (partial) | 4–5 wks |
| 3 | Branch POS core — offline trading | Phase 1 (partial) | 6–8 wks |
| 4 | Sync pipeline & central reporting | Phase 1 (completion) | 4–6 wks |
| 5 | Accounts, credit & funding at the counter | Phase 2 (partial) | 5–6 wks |
| 6 | Billing engine & collections | Phase 2 (completion) | 6–8 wks + 2 parallel cycles |
| 7 | Multi-branch rollout & owner visibility | Phase 3 | 6–8 wks (staggered) |
| 8 | Inventory, recipes & purchasing | Phase 4 | 6–8 wks |
| 9 | Expenses, payroll & branch profit | Phase 5 | 6–8 wks |
| 10 | Optimization & extensions | Phase 6 | ongoing |

Durations assume the 31-developer team split into the parallel streams from
[12 §10](12-stack-and-platform.md), so later phases overlap: the accounts stream can start
Phase 5 while Phase 4 hardens, and inventory (8) can begin while rollout (7) is staggering
across branches. The strict dependency chain is 1 → 2 → 3 → 4 → 5 → 6 → 7; phases 8 and 9
need only a stable POS plus rollout underway.

---

## Phase 1 — Foundations & de-risking

**Goal:** every "must be settled before code" item from docs 11–12 is settled, and the
shared kernel exists so 31 developers don't invent 31 frameworks.

- Confirm hosting: PHP ≥ 8.2, cron reliability, `mysqldump` reachable
  ([12 §12](12-stack-and-platform.md)). If it fails, change the plan **now**.
- Buy **one** full hardware set (PC, 80mm thermal printer, drawer, UPS) and verify Arabic
  ESC/POS rendering before committing to five ([10 §9](10-cross-cutting-rules.md)).
- Get answers to the open business questions in [00 §6](00-business-context.md) —
  especially VAT and legal invoice format, which touch the receipt and invoice designs.
- Build and freeze the kernel ([12 §7](12-stack-and-platform.md)): router,
  request/response, PDO layer working against **both SQLite and MySQL**, migration runner,
  validator, auth/session/RBAC, audit writer, money type (integer IQD/USD, cash rounding,
  FX).
- Agree and version the sync API contract ([12 §9](12-stack-and-platform.md)) so branch
  and centre teams can work in parallel.
- CI running PHPUnit against both dialects on every PR; written conventions document;
  release pipeline (Composer on dev machines, `vendor/` bundled, FTPS deploy, migration
  endpoint).
- Central backup job with off-host storage and dead-man's-switch alert — doc 12 calls this
  the single largest risk; it starts existence in Phase 1, not at go-live.

**Exit criteria:** kernel API frozen and documented; CI green on both dialects; Arabic
receipt printed from real hardware; hosting confirmed; backup restore-tested once.

---

## Phase 2 — Master data, access & catalog

**Goal:** everything the POS will depend on exists and is editable in the back office.

- Organization, branches, buildings, business-day cutoff, **business calendar** with
  owner-declared closures (docs [01](01-organization-and-access.md),
  [10 §3.1](10-cross-cutting-rules.md)).
- Users, roles, capability matrix, PIN vs password auth, branch scoping enforced at the
  data layer, time-bounded access, audit log wired to every mutation.
- Catalog: categories, items, modifier groups/options, recipes schema (entry optional for
  now), price versioning with `effective_from`, branch overrides, the three availability
  switches including one-tap 86.
- Server-rendered back-office screens for all of the above, Arabic-first RTL.
- Master-data pull side of sync (`/api/sync/pull` with cursor).

**Exit criteria:** the full real menu of the pilot branch is entered by a non-developer; a
price change is versioned and audited; a closure declared centrally appears in the
branch's pulled data.

---

## Phase 3 — Branch POS core — offline trading

**Goal:** one branch runs its entire day on the branch PC with **zero network calls on the
sale path**.

> **Revision (2026-08-05, [D17](14-conventions.md)):** the branch-service bullet is
> superseded — the POS is a client-installed **PWA** (service worker + IndexedDB,
> receipts via the OS print dialog). The goal reads: one branch runs its entire day
> **in the installed PWA** with zero network calls on the sale path. Working tracker:
> [19 — Phase 3 Checklist](19-phase-3-checklist.md).

- Branch service: PHP under NSSM/WinSW, SQLite WAL, kiosk-mode browser startup, bundled
  installer.
- SPA POS: order lifecycle ([04 §1](04-sales-and-pos.md)), walk-in-and-cash as the
  zero-extra-tap default, modifiers with defaults, favourites screen, quick-quantity,
  ≤3-tap target.
- Settlement: cash/card/wallet, mixed tender, cash rounding to 250 IQD on the cash leg
  only, USD tender with FX snapshot.
- Discounts with cashier limits, voids with reason codes and supervisor PIN, refunds as
  opposing documents.
- Receipts (Arabic-first), prep tickets, on-screen prep queue panel, deliver-to-office
  marking.
- Shifts: counted float, drawer movements, no-sale-open logging, **blind close**, variance
  tolerance and review, business-day close with frozen Z-report.
- Outbox written locally for every domain event (consumed in Phase 4).

**Exit criteria:** a simulated full trading day — including a mid-day power cut and no
internet at all — ends with cash reconciling and a correct Z-report.

---

## Phase 4 — Sync pipeline & central reporting

**Goal:** completes roadmap Phase 1 — the branch's data reaches the centre reliably, and
the pilot proves it live.

- Sync client on Task Scheduler; push endpoint with staging table, unique `event_id`,
  accept-and-flag semantics; cron `sync:process` idempotent, chunked, resumable.
- Device token auth and central revocation; sync status on the POS; stale-device alerting;
  late-arrival posting to the next open day.
- Central reporting v1: daily sales summary, sales by item, voids/discounts by cashier,
  sync exceptions — read from rollup tables that are rebuildable from source.
- Nightly SQLite backup (local copy + push to centre); **rehearse the branch-PC recovery
  procedure** ([10 §9.1](10-cross-cutting-rules.md)) end to end.
- **Pilot:** the first real branch trades for a full week with the internet deliberately
  cut for a day.

**Exit criteria:** the roadmap's Phase-1 done-when — a week of live trading, one day
offline, cash reconciles, and every order is visible centrally with no duplicates.

---

## Phase 5 — Accounts, credit & funding at the counter

**Goal:** tenants can charge to account correctly, including the hardest counter-flow:
split settlement on cap overflow.

- Customers, accounts (company/individual, parent rollup), contacts, billing-terms
  structure on the account, credit limits, on-hold states.
- Authorized persons with funding overrides, cap amounts/periods, `on_cap_exceeded`
  behaviours; cap accounting derived from charges, never a counter.
- POS: account search (< 200 ms, Arabic-normalized, matches office number), charge to
  account, computed — never asked — split settlement, charge/split slips with
  remaining-cap display, repeat-last-order.
- Credit check at charge time; offline provisional checks against cached balances;
  supervisor override with audit.
- Receiving an account payment **at the POS**, entering the shift's cash count
  ([05 §5](05-receivables-and-billing.md) rule 4).

**Exit criteria:** an employee exhausts a cap mid-order and the excess settles personally
on one order with correct slips; an over-limit charge blocks and an override is audited;
all of it works offline as provisional.

---

## Phase 6 — Billing engine & collections

**Goal:** completes roadmap Phase 2 — the highest-risk module in the system, built slowly
and proven against a spreadsheet.

- Billing runs on central cron: period grids for all four modes, idempotent on
  `(account, period)`, late-arrival roll-forward, zero-activity handling, terms changes
  effective next cycle.
- Invoices: gapless central numbering, immutability, three statement groupings, cap
  summary block, cancellation rules.
- Payments and allocations (oldest-first default), unapplied credit, credit notes,
  write-offs with approvals.
- Aging from `due_date`, overdue automation, auto-hold and auto-release, reminder queue,
  collections activity log.
- AR report suite: aging, unbilled charges, DSO, cap utilization/exceptions, credit
  exceptions, write-offs.
- **Run two full billing cycles reconciled line-by-line against a manual spreadsheet**
  before trusting it (doc 11's explicit instruction).

**Exit criteria:** a month runs end-to-end on all four cycle types; one account goes
overdue and is auto-held then auto-released on payment, with no manual intervention; two
cycles match the spreadsheet exactly.

---

## Phase 7 — Multi-branch rollout & owner visibility

**Goal:** all five branches live, staggered, with the owner managing by report.

- Roll out branch-by-branch (not all four at once): hardware install, master data load,
  tenant onboarding, staff training, recovery drill **per branch** before its go-live.
- Cross-branch account charging and payment collection; sync hardening under real
  five-branch load; conflict and credit-exception reporting.
- **Owner daily digest (push via WhatsApp/Telegram)** — ship first in this phase; doc 11
  flags it as the best value-to-effort item in the project. Digest still sends on closure
  days.
- Branch comparison report (the [09 §2](09-reporting.md) table), consolidated sales,
  trading-day-aware comparisons.
- Full anti-fraud exception suite, comparative and ranked across branches (docs
  [06 §6](06-cash-and-shifts.md), [09 §7](09-reporting.md)).

**Exit criteria:** the owner in Baghdad answers "how did Karbala do yesterday and why is
it different from Basrah" from the digest and dashboard alone; every branch has passed a
recovery drill.

---

## Phase 8 — Inventory, recipes & purchasing

**Goal:** roadmap Phase 4 — stock numbers staff believe, and a shrinkage figure the owner
trusts. Starts only once POS transactions are demonstrably stable (sequencing rule 1).

- Inventory items, unit conversions, per-branch stock derived from the movement ledger,
  weighted-average cost per branch.
- Recipes completed and versioned; modifier recipe deltas; automatic deduction at
  confirmation; void reversal; auto-86 warnings.
- Suppliers (global), supplier price lists, per-branch POs with approval thresholds, GRN
  at received cost, price-change alerts, reorder suggestions.
- Inter-branch transfers (two-sided, in-transit state, discrepancy flow);
  waste/staff-consumption/sample flows as one-tap actions; blind stock counts
  (spot/cycle/full).
- Reporting: stock value, shrinkage (theoretical vs actual), waste %, gross margin by
  item, purchase price variance by branch.

**Exit criteria:** a full monthly count reconciles at the pilot branch and shrinkage is a
stable, explained number for two consecutive months.

---

## Phase 9 — Expenses, payroll & branch profit

**Goal:** roadmap Phase 5 — the `Sales − COGS − Rent − Payroll − Opex` line computes per
branch without a spreadsheet.

- Expense engine: categories (with the grid/generator electricity split), approvals,
  receipt photos, automatic till pay-out linkage, immutability once paid.
- Recurring schedules and rent contracts: currency per contract, advance payment,
  **accrual vs cash** treatment, deposit tracking, renewal/notice/escalation alerts.
- Employees, allowances, optional PIN time-clock, closure-day pay rules.
- Payroll runs: gross/deduction components, advances (سلفة) with automatic repayment,
  payment confirmation per employee, salary visibility restricted to Owner/Accountant.
- Supplier payables: invoices from GRNs, **three-way match blocking payment on mismatch**,
  supplier aging and payments.
- Reporting: branch P&L (accrued rent), consolidated P&L, labour cost % on trading days,
  cash-flow forecast ([08 §7](08-expenses-payroll.md)).

**Exit criteria:** branch net profit for a closed month matches the external accountant's
independent calculation.

---

## Phase 10 — Optimization & extensions

**Goal:** roadmap Phase 6 — earned features once the first nine phases are stable,
prioritized by observed operational data.

- Standing/scheduled orders (suppressed on closure days) — likely first, given morning
  office volume.
- Loyalty for walk-ins (phone-number stamps, cross-branch balance).
- Combos and time-window promotions; corporate price lists if not already demanded in
  Phase 5.
- Staff rostering, demand forecasting for reorders, accounting-package export.
- Platform investments: branch self-update mechanism ([12 §12](12-stack-and-platform.md)
  item 3), rollup performance tuning, and the VPS migration path if shared hosting shows
  strain.

**Exit criteria:** open-ended; each item ships independently with its own measure.

---

## Cross-phase disciplines (every phase, not a phase)

- **QA stream** ([12 §10](12-stack-and-platform.md)): dialect-parity tests, billing/money
  under heaviest coverage, restore drills on a schedule, hardware verification.
- **Immutability and derived balances** enforced in review from Phase 2 onward —
  [10 §5](10-cross-cutting-rules.md) calls the mutable stored total "the defining bug of
  this class of system."
- **Backups**: dead-man's-switch monitored from Phase 1; restore-tested monthly.
- **Trust rule** (sequencing rule 3): no report ships on transactions still churning — a
  report whose numbers change destroys trust permanently.

## Watch-items

1. **Phase 6 is the schedule risk.** The docs themselves call it the highest-risk phase —
   protect its two reconciliation cycles from compression.
2. **The Phase 1 hardware and hosting checks are cheap now but plan-breaking if
   discovered late.** Neither the printer nor the hosting plan is proven until tested.
