# Phase 4 — Rollout, performance, finance validation

## Shadow → live (recommended sequence)

1. **Shadow (read-only week 1–2)**  
   - Open `analytics.html` only; do **not** change pricing or purchasing based on KPIs yet.  
   - Compare **Total COGS / Gross profit / Margin %** to a manual spreadsheet for 3–5 sample days.

2. **Writer validation (week 2–3)**  
   - After deploying POS + dashboard sale/refund ledger rows with `unitCost` / `costMethod`, spot-check Firebase `inventoryLedger` for new `sale` / `refund` events.

3. **Team validation week**  
   - Finance signs off that **refund-aware** net qty matches `items[].refundedQty` and order totals.  
   - Review **low-margin** and **high-shrinkage** lists for false positives.

4. **Live KPI + alerts**  
   - Set `siteSettings.marginAnalytics` thresholds (or use defaults).  
   - Use weekly cadence: shrinkage review, low-margin SKU → `purchase-add.html` / `inventory.html`.

5. **Monthly margin audit**  
   - Reconcile: sum(order line net revenue) vs POS totals; COGS vs purchase roll-forward (approximate for v1 moving average).

## Performance guardrails

- Analytics loads **orders + products + purchases + inventoryLedger** once per page load; acceptable for typical SMB SKU counts.  
- If RTDB payload exceeds ~5–10 MB: add **date-windowed order fetch** (last 90 days) or server summary nodes (future).  
- Charts: keep **30-day** fixed window to bound labels.

## Finance validation playbook (day close)

1. Pick one calendar day `D`.  
2. Sum **gross sales** from orders with `createdAt` on `D` (channel filter as needed).  
3. Sum **COGS** from analytics engine (same filter) — should align with Σ(net qty × moving-avg unit cost).  
4. **Refunds**: confirm refunded lines reduce net qty vs `refundedQty`.  
5. **Shrinkage**: sum ledger `wastage` + negative `adjustment` cost column vs KPI.  
6. Document variance; if &gt; agreed band, check missing purchase lines and `quality === missing` SKUs.

## Regression / fixtures

- Run in browser console on a dev build (optional):  
  `import { runMarginAnalyticsFixtureChecks } from './margin-analytics-fixtures.js'` then `runMarginAnalyticsFixtureChecks()` — should report `ok: true`.

## Rollback

- Margin KPIs are read-only; rollback = hide Phase 4 cards or revert analytics script imports.  
- Ledger rows with extra fields are backward-compatible; old readers ignore `unitCost` / `costMethod`.
