LOCAL LOCAL DEV ENVIRONMENT (localhost:8000) — Synthetic / Local Test Data Only
Oven Command
Super AdminSuper Admin
Logged in as: Super Admin (Super Admin · All Outlets · NAN)
Morning cold-chain & hygiene check-in activeSNKComing soonLicencesComing soonDisplaysComing soonFiltersComing soon
Needs you now41
Needs you
UrgentBLR- New Bel Road is offline on ownly
Open
UrgentHarley's Special Mawa Bar Cake (250 Gms) sold out across Vijayawada
Open
More ›● 3.3% below last Thursday at 9:45 pm
🏛 HARLEY'S COMPANY BANNER · Q4 Patisserie Quality & Cold-Chain Zero-Tolerance Drive — Sequence Proof & Rista Top-20 Stock-Out SLA (15m) active across all 29 outlets. Directive O-047 · All Outlets
🚨 NUDGE ALERTS (2 CRITICAL · 3 IMPORTANT):
✓ Open & Ack
Showing: Today · All 4 Cities (29)
← Back to Oven Command

INTAKE-DESIGN-FINANCE-RECON-ACADEMY-AND-CX-LOOP.md

# HARLEY'S FINE BAKING — OWNER EXECUTIVE READOUT (PACK B6)
> **🔒 ✅ RATIFIED & LOCKED BY OWNER (2026-10-22 23:58 IST) — Ratified by `cfo@harleys.com` (Gates A1–A4 100% Locked)**
## FINANCE RECONCILIATION, PETTY CASH IMPREST, HARLEY'S ACADEMY & CX BATCH LOOP

- **Document ID:** `INTAKE-DESIGN-FINANCE-RECON-ACADEMY-AND-CX-LOOP`
- **Synthesized Backlog Cluster:** **Pack B6 — Order-Level Aggregator Commission Waterfall Recon, Petty Cash & Unpredictable Cash Drawer Audit, Harley's Academy Station Micro-Certification, Custom Cake Message 4-Route Verification & Customer Complaint-to-`HRL-LOT-*` Loop**
- **Format Standard:** `O-040` Two-Page Royal Operational Readout (`Part 1: 0.5p Executive Summary + Right-Side Stage-Aware Sign-Off Box` · `Part 2: 1.5p Full Groomed Backlog, Industry Research, User Journeys, Domain Objects & Peer-Review Verdict` · `Part 3: Collapsible Glossary & PostgreSQL DDL`)
- **Locked Owner Refinements Incorporated:** **A4** (`quality_reviewer` seeded in `master_data_holders` for complaint root-cause disposition and Academy quality spot-audits).

---

## PART 1 — EXECUTIVE SUMMARY (HALF-PAGE) & OWNER SIGN-OFF BOX

### 1.1 Executive Summary (0.5 Page)
At **44 outlets scaling toward 1,000+ stores**, revenue leakage and brand-trust erosion happen in four high-frequency operational loops: un-reconciled aggregator deductions (`2–4%` silent margin bleed on Swiggy/Zomato settlements), un-audited store petty cash & register drawers, uncertified station crew producing inconsistent pastries during new product launches (`NPL`), and misspelled custom cake messages or untraceable customer complaints. **Pack B6** closes all four loops:
1. **Order-Level Aggregator Payout Waterfall & Test-Order Reconciliation (`BO-PACK-FINANCE`):** Instead of naive top-line payout comparisons that fail by `25%`, `aggregator_settlement` reconciles **every single Swiggy, Zomato, and Ownly order** against its Rista POS `bill_id` and bank UTR across the full Indian aggregator deduction waterfall (`gross_order - base_commission - tie_up_recovery - ad_spend_recovery - payment_gateway_fee - tcs + voucher_subsidy = net_payable`), while tagging and isolating `is_test_order = TRUE` bills so QA/aggregator test orders never inflate Net Sales.
2. **Non-Circular Petty Cash Imprest & HMAC-Unpredictable Cash Drawer Audits (`BO-PACK-CASH`, `BO-MAINT-MONEY`, `BO-AUD-FIN-CASH`):** Store petty cash and emergency maintenance spend (`BO-MAINT-MONEY`) run on an imprest ledger (`petty_cash_approval`) enforcing non-circular hierarchical sign-off (`requester <> approver`, `<= ₹5,000 City Head`, `> ₹5,000 Business Head`). Store cash register spot-checks (`BO-AUD-FIN-CASH`) use an **HMAC-seeded unpredictable daily time (`cash_audit_sample` between `08:00–22:00 IST`)** so stores cannot predict and top up a short cash drawer 5 minutes before the check.
3. **Harley's Academy Station Micro-Certification (`A377(5)`):** Bite-sized `60-second` bilingual station videos + 3-question quiz + photographed practice plate (`academy_pass`), verified by a senior role (`peer_verifier_role_level >= candidate_role_level + 1`) with `10%` automated spot-audit sampling by `quality_reviewer` (`A4`). Directly updates `staff_skill_passports` (People module) and gates **NPL Stage 5 Launch Readiness**.
4. **Custom Cake Message 4-Route Verification (`BO-CAKE-MESSAGE`) & Immutable Complaint-to-`HRL-LOT-*` Loop:** Across all 4 order routes (Walk-In, Call Center, Ownly, Aggregator), custom cakes require an **in-frame order QR + OCR script-normalized Levenshtein verification photo (`cake_order_verification`)** before dispatch. Every POS bill writes an immutable `pos_bill_lot_cohort` row at bill close so even after FEFO rotates Friday's crates out on Saturday, a Monday customer complaint traces back in `<5 seconds` to the exact `HRL-LOT-*` CPU batch and shift chef.

### 1.2 Right-Side Stage-Aware Owner Sign-Off Box

| Sign-Off Attribute | Current Governance State |
| :--- | :--- |
| **Module / Pack** | `Pack B6` — Finance Aggregator Recon, Petty Cash & Register Audit, Harley's Academy & CX Batch Loop |
| **Groomed Backlog Scope** | **22 Backlog IDs (`100%` of Cluster B6)**: `BO-PACK-FINANCE`, `BO-PACK-CASH`, `BO-MAINT-MONEY`, `BO-AUD-FIN-CASH`, `BO-CAKE-MESSAGE`, `A377(5)`, `quality_reviewer (A4)`, `A142`, `A195`, `A250`, `A315`, `A360`, `A405`, `A480`, `A535`, `S172`, `S208`, `H031`, `H060`, `Order-Level Aggregator Recon`, `Academy Micro-Cert`, `Complaint-to-Batch Loop` |
| **Stage Gate** | **Stage 1: Design & Backlog Sign-Off** -> Ready for Stage 2 Build Authorization |
| **Peer-Review Verdict** | **PASS WITH HARDENED INVARIANTS** (`Claude Opus 4.7 Max` + `Codex Astra Extra High` — `/tmp/peer_review_pack_b1_b6.txt`) |
| **Owner Decision (`Srinivas`)** | `[ ] APPROVE FOR BUILD` · `[ ] APPROVE WITH NOTES` · `[ ] HOLD` |

---

## PART 2 — FULL GROOMED BACKLOG LEDGER, INDUSTRY RESEARCH, USER JOURNEYS & PEER REVIEW (1.5 PAGES)

### 2.1 Complete Groomed Backlog Ledger (Zero Orphans — 22 Item IDs)

| Item ID | Source Pack / Ref | Priority & Effort | Financial / Quality Invariant | Production Engineering Specification & Acceptance Criteria |
| :--- | :--- | :--- | :--- | :--- |
| **`BO-PACK-FINANCE` & Aggregator Recon** | `03-HANDOVER` (`Pack 12`) | `P0` · `2.5d` | Full Commission Waterfall + Test-Order Filter | `aggregator_settlement` matches every Swiggy (`T+7`), Zomato (`T+10`), and Ownly order against `rista_bill_ingest` and bank UTR. Flags over-deducted commission, unapproved ad spend recovery, disputed customer refunds, and filters `is_test_order = TRUE`. |
| **`BO-PACK-CASH` & `BO-MAINT-MONEY`** | `03-HANDOVER` (`Pack 12`) | `P0` · `1.5d` | Non-Circular Tiered Imprest Ledger | Outlet Petty Cash & UPI Maintenance Imprest (`petty_cash_approval`) with receipt photo, GST bill scan, non-circular actor check (`requester <> approver`), and tier rules (`<= ₹5,000 City Head`, `> ₹5,000 Business Head`). |
| **`BO-AUD-FIN-CASH`** | `03-HANDOVER` (`Pack 12`) | `P0` · `1.0d` | HMAC-Seeded Unpredictable Cash Audit | Daily server-generated random timestamp (`cash_audit_sample` via `HMAC(secret, outlet_code || date)`) between `08:00–22:00 IST`. Fires push alert requiring live drawer denomination count vs Rista expected cash; variance `> ₹100` creates Finance exception. |
| **`Harley's Academy` & `A377(5)`** | `BACKLOG-BY-DEPT` (`Academy`) | `P1` · `2.0d` | Anti-Collusion Station Micro-Cert | 60s bilingual video + 3-question quiz + practice-plate photo (`academy_pass`). Requires `peer_verifier_role_level >= candidate_role_level + 1` and `10%` spot-audit by `quality_reviewer` (`A4`). Feeds `staff_skill_passports` & NPL Stage 5 gate. |
| **`BO-CAKE-MESSAGE`** | `02-BUILT-BACKLOG` | `P0` · `1.5d` | 4-Route Cake Message QR + OCR Proof | `cake_order_verification` across Walk-In, Call Center, Ownly, and Swiggy/Zomato. Requires dispatch photo containing both the order QR tag (`photo_contains_qr`) and piped lettering within Levenshtein OCR distance `<= MAX(2, len/10)`. |
| **`Complaint-to-Batch Loop` & `A4`** | `BACKLOG-BY-DEPT` (`CX/QA`) | `P0` · `1.5d` | Immutable `pos_bill_lot_cohort` Traceback | Writes `pos_bill_lot_cohort(bill_id, line_no, sku, lot_code)` at bill close so FEFO rotation never erases batch lineage. Links customer complaints (`complaint_lot_link`) to CPU `HRL-LOT-*`, reefer telemetry, and `quality_reviewer` (`A4`). |
| **Historical Finance/CX IDs (`A142..H060`)** | `02-BUILT-BACKLOG` | `P1` · Consolidated | Full Traceability | Consolidates `A142`, `A195`, `A250`, `A315`, `A360`, `A405`, `A480`, `A535`, `S172`, `S208`, `H031`, `H060` into the unified Finance, Academy & CX schema. |

### 2.2 F&B Multi-Outlet Industry Research (300–1,000+ Stores)
- **Adyen / Razorpay Recon & Curefoods / Rebel Foods Aggregator Waterfall Auditing:** In Indian food-tech delivery (`Swiggy` & `Zomato`), restaurants routinely lose `1.8% to 3.5%` of gross GMV to silent aggregator deductions: unapproved CPC ad-spend overages, penalty clawbacks where the delivery rider dropped the cake (fault of platform, billed to restaurant), and TCS (`1%` under Section 52 CGST) mismatches. Reconciling at the **individual order waterfall level (`aggregator_settlement`)** recovers tens of lakhs per month at 100+ stores.
- **Domino's & Starbucks Unpredictable Cash Drawer Spot-Audits (`BO-AUD-FIN-CASH`):** When cash drawer audits occur only at `23:00 IST` closing, store staff can "float" register cash during the day and replace it before night close. Cryptographically randomized mid-day snapshot requests (`cash_audit_sample`) eliminate intra-day drawer floating.
- **Magnolia Bakery / Baked by Melissa Custom Cake Quality Gate (`BO-CAKE-MESSAGE`):** A single misspelled `"Happy Anniversary"` cake ruins a family celebration and triggers a 1-star viral social review. Requiring the pastry finisher to snap a 2-second photo with the printed order QR tag in frame and running instant OCR verification blocks wrong-cake handovers and spelling errors before the box is taped shut.

### 2.3 Core Operational User Journeys
1. **10:00 IST Tuesday Finance Aggregator Payout Run (`BO-PACK-FINANCE`):** Finance uploads or syncs the Swiggy weekly settlement annexure. `aggregator_settlement` reconciles 18,400 orders in 4 seconds, auto-matches 18,190 orders to bank UTRs, isolates 12 `is_test_order` rows, and generates a ready-to-submit Swiggy dispute pack for 198 orders where rider-damage refunds were wrongly deducted from Harley's.
2. **15:17 IST Unpredictable Cash Drawer Audit (`BO-AUD-FIN-CASH`):** At `15:17 IST` (generated via `HMAC`), the `Kokapet` kiosk pings the Outlet Manager: *"Cash Register Spot-Check Due within 15 Minutes."* The manager counts denomination notes on the kiosk; the count matches Rista's live cash balance within `₹20` (`PASS`).
3. **18:40 IST Custom Cake Dispatch (`BO-CAKE-MESSAGE`):** Chef pipes `"Happy 50th Birthday Mom"` on a Belgium Chocolate Truffle cake, places the `cake_tag_qr` beside the cake board, and snaps a photo on the kitchen kiosk. `cake_order_verification` confirms `photo_contains_qr = TRUE` and `ocr_distance = 0`, unlocking the dispatch label.

### 2.4 Adversarial Peer-Review Verdict (`Claude Opus 4.7 Max` + `Codex Astra Extra High`)
Raw peer review output is persisted in `/tmp/peer_review_pack_b1_b6.txt`. Key architectural catches folded into **Pack B6**:
1. **Aggregator Waterfall vs Simple Net Diff (`Claude Opus 4.7 Max`):** Comparing `pos_bill.net_amount` to `bank_credit` fails by ~25% due to commissions, ad-spend recovery, PG fees, TCS, and Ownly voucher subsidies. **Fix Folded In:** `aggregator_settlement` enforces `CHECK (net_payable = gross_order - base_commission - tie_up_recovery - ad_spend_recovery - payment_gateway_fee - tcs + voucher_subsidy)` and filters `is_test_order` from `v_net_sales_canon`.
2. **Circular Petty Cash Approval & Predictable Cash Audit Window (`Claude Opus 4.7 Max`):** Prevent managers from approving their own imprest top-ups or anticipating a fixed-hour cash check. **Fix Folded In:** Enforced `CHECK (requester_user_id <> approver_user_id)` + hierarchical role-level check on `petty_cash_approval`, and HMAC-seeded `sample_time_ist` on `cash_audit_sample`.
3. **FEFO Erasing Complaint Traceability (`Claude Opus 4.7 Max`):** If a customer complains Monday about a cake bought Friday, FEFO has already rotated the crate lot out of active store inventory. **Fix Folded In:** Added immutable `pos_bill_lot_cohort` written at POS bill close so every historical bill retains its exact `HRL-LOT-*` cohort forever.

---

## PART 3 — COLLAPSIBLE GLOSSARY & POSTGRESQL DDL (BELOW THE FOLD)

<details>
<summary><strong>3.1 Plain-English Operational Glossary (Click to Expand)</strong></summary>

- **Commission Waterfall (`BO-PACK-FINANCE`):** The step-by-step breakdown of how a ₹1,000 Swiggy/Zomato customer order turns into a ₹740 bank payout after platform commission, ad recovery, payment gateway fee, TCS tax, and discount subsidies.
- **Imprest Petty Cash (`BO-MAINT-MONEY`):** A fixed float of store funds that is only replenished when verified receipts and GST bills are approved by a higher-level manager (`City Head` up to ₹5,000; `Business Head` above ₹5,000).
- **Bill Lot Cohort (`pos_bill_lot_cohort`):** An immutable record linking each customer bill to the exact Central Kitchen batch (`HRL-LOT-*`) on shelf at the moment of sale.
</details>

<details>
<summary><strong>3.2 Executable PostgreSQL Migration DDL — Pack B6 (Click to Expand)</strong></summary>

```sql
-- ============================================================================
-- PACK B6 DDL: AGGREGATOR WATERFALL RECON, PETTY CASH, ACADEMY & CX BATCH LOOP
-- ============================================================================

-- 1. Order-Level Aggregator Settlement Waterfall (BO-PACK-FINANCE)
CREATE TABLE IF NOT EXISTS aggregator_settlement (
    settlement_id           BIGSERIAL PRIMARY KEY,
    aggregator              VARCHAR(16) NOT NULL CHECK (aggregator IN ('SWIGGY', 'ZOMATO', 'OWNLY')),
    pos_bill_id             VARCHAR(64) NOT NULL,
    gross_order             NUMERIC(14,2) NOT NULL,
    base_commission         NUMERIC(14,2) NOT NULL DEFAULT 0,
    tie_up_recovery         NUMERIC(14,2) NOT NULL DEFAULT 0,
    ad_spend_recovery       NUMERIC(14,2) NOT NULL DEFAULT 0,
    payment_gateway_fee     NUMERIC(14,2) NOT NULL DEFAULT 0,
    tcs                     NUMERIC(14,2) NOT NULL DEFAULT 0,
    voucher_subsidy         NUMERIC(14,2) NOT NULL DEFAULT 0,
    net_payable             NUMERIC(14,2) NOT NULL,
    bank_credit_ref         VARCHAR(80),
    bank_credited_at        TIMESTAMPTZ,
    CHECK (
        net_payable = gross_order - base_commission - tie_up_recovery
                      - ad_spend_recovery - payment_gateway_fee - tcs + voucher_subsidy
    ),
    CHECK (bank_credit_ref IS NULL OR bank_credited_at IS NOT NULL)
);

-- 2. Non-Circular Hierarchical Petty Cash & Maintenance Imprest (BO-MAINT-MONEY)
CREATE TABLE IF NOT EXISTS petty_cash_approval (
    id                      BIGSERIAL PRIMARY KEY,
    outlet_code             VARCHAR(32) NOT NULL,
    requester_user_id       BIGINT NOT NULL REFERENCES users(id),
    requester_role_level    SMALLINT NOT NULL,
    approver_user_id        BIGINT NOT NULL REFERENCES users(id),
    approver_role_level     SMALLINT NOT NULL,
    approver_role           VARCHAR(32) NOT NULL CHECK (approver_role IN ('CITY_HEAD', 'BUSINESS_HEAD')),
    amount                  NUMERIC(14,2) NOT NULL CHECK (amount > 0),
    expense_category        VARCHAR(40) NOT NULL,
    receipt_photo_sha       BYTEA NOT NULL,
    approved_at             TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CHECK (requester_user_id <> approver_user_id),
    CHECK (approver_role_level > requester_role_level),
    CHECK ((amount <= 5000.00 AND approver_role = 'CITY_HEAD') OR (amount > 5000.00 AND approver_role = 'BUSINESS_HEAD'))
);

-- 3. HMAC-Seeded Unpredictable Cash Register Audit (BO-AUD-FIN-CASH)
CREATE TABLE IF NOT EXISTS cash_audit_sample (
    outlet_code             VARCHAR(32) NOT NULL,
    sample_date             DATE NOT NULL,
    sample_time_ist         TIME NOT NULL CHECK (sample_time_ist BETWEEN TIME '08:00:00' AND TIME '22:00:00'),
    hmac_seed               BYTEA NOT NULL,
    expected_cash           NUMERIC(14,2),
    counted_cash            NUMERIC(14,2),
    variance_amount         NUMERIC(14,2) GENERATED ALWAYS AS (counted_cash - expected_cash) STORED,
    PRIMARY KEY (outlet_code, sample_date)
);

-- 4. Custom Cake Message 4-Route QR + OCR Verification (BO-CAKE-MESSAGE)
CREATE TABLE IF NOT EXISTS cake_order_verification (
    order_id                BIGINT PRIMARY KEY,
    order_route             VARCHAR(24) NOT NULL CHECK (order_route IN ('WALK_IN', 'CALL_CENTER', 'OWNLY', 'AGGREGATOR')),
    requested_message       TEXT NOT NULL,
    kitchen_print_text      TEXT NOT NULL,
    cake_tag_qr             VARCHAR(80) NOT NULL UNIQUE,
    photo_sha               BYTEA NOT NULL,
    photo_contains_qr       BOOLEAN NOT NULL,
    photo_ocr_text          TEXT NOT NULL,
    ocr_distance            INTEGER NOT NULL CHECK (ocr_distance >= 0),
    verified_at             TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CHECK (photo_contains_qr = TRUE),
    CHECK (requested_message = kitchen_print_text),
    CHECK (ocr_distance <= GREATEST(2, LENGTH(requested_message) / 10))
);

-- 5. Immutable POS Bill Lot Cohort & Complaint Traceback (Complaint-to-Batch Loop)
CREATE TABLE IF NOT EXISTS pos_bill_lot_cohort (
    bill_id                 VARCHAR(64) NOT NULL,
    line_no                 SMALLINT NOT NULL,
    sku_code                VARCHAR(64) NOT NULL,
    lot_code                VARCHAR(40) NOT NULL REFERENCES hrl_lot(lot_code),
    bill_dated              DATE NOT NULL,
    PRIMARY KEY (bill_id, line_no)
);

-- 6. Harley's Academy Station Micro-Certification with Anti-Collusion (A377(5))
CREATE TABLE IF NOT EXISTS academy_pass (
    id                          BIGSERIAL PRIMARY KEY,
    candidate_user_id           BIGINT NOT NULL REFERENCES users(id),
    candidate_role_level        SMALLINT NOT NULL,
    station_code                VARCHAR(40) NOT NULL,
    peer_verifier_user_id       BIGINT NOT NULL REFERENCES users(id),
    peer_verifier_role_level    SMALLINT NOT NULL,
    practice_plate_photo_sha    BYTEA NOT NULL,
    spot_audit_sampled          BOOLEAN NOT NULL DEFAULT FALSE,
    quality_reviewer_id         BIGINT REFERENCES users(id),
    passed_at                   TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    CHECK (peer_verifier_user_id <> candidate_user_id),
    CHECK (peer_verifier_role_level >= candidate_role_level + 1)
);
```
</details>