# AB MES — Architecture Roadmap & Build Phases

> **Reference:** `G:\My Drive\ERP\dyehouse_mes_handoff.md` — Full architecture spec  
> **Stack:** Laravel 13 + Livewire 3 + SQLite (dev) / MySQL (prod)  
> **Last updated:** 2026-06-21

---

## Current State (Built ✅)

### Phase 1 — Master Data & Curve Engine ✅
| Component | Status | Notes |
|---|---|---|
| `dye_curves` + `dye_curve_steps` | ✅ Built | Step builder in ColorManagement (Curves section). action_type enum (Load/Heat/Maintain/…) |
| `dyestuffs` catalog | ✅ Built | Supplier, energy_level, fixation_chemistry_type, default_ppe |
| `DyeCurve`, `DyeCurveStep`, `Dyestuff` models | ✅ Built | Explicit fillable, casts, proper relationships |
| Curve builder UI | ✅ Built | ColorManagement → 🎨 Colores / 📈 Curvas toggle |

### Phase 2 — Color Holder & Lab Formulation ✅
| Component | Status | Notes |
|---|---|---|
| `dye_colors` (CustomerColor) | ✅ Built | `target_l/a/b`, `customer_tolerance_de`, SoftDeletes |
| `lab_formulas` | ✅ Built | Status state machine: Draft→Formulated→Dyed→Measured→Approved_in_Lab. `parent_lab_formula_id` versioning |
| `lab_formula_items` | ✅ Built | Replaced polymorphic formula_items. `uom` (owf/g_l) |
| `production_formulas` | ✅ Built | Absorbed Recipe: `dye_curve_id`, `nombre`, `status`, `water_ratio`. `parent_production_formula_id` versioning |
| `production_formula_items` | ✅ Built | Per curve-step chemical assignments. `concentration_pct_owf` + `concentration_gr_l` |
| Color Management UI | ✅ Built | 4-tab: Info / Lab Trials / Fórmula Producción / Análisis. Grid + list view |
| ΔE calculation | ✅ Built | `DyeColor::deltaE()`, `LabFormula::pass_fail` (PASS/MARGINAL/FAIL) |

### Phase 3 — Approval State Machine ✅
| Component | Status | Notes |
|---|---|---|
| `FormulaApprovalService` | ✅ Built | Atomic transaction. Supersedes old versions. Audit log. Guards against invalid states |
| `production_formula_approvals` | ✅ Built | Pointer table: O(1) lookup per spec §1.3 |
| State machine (ProductionFormula) | ✅ Built | Pending → Approved → Superseded |
| Approval UI | ✅ Built | Version pills in Tab 3. Approve/Archive buttons |

### Supporting Modules (Built by Antigravity or existing) ✅
| Module | Status |
|---|---|
| MES Dashboard | ✅ |
| Looms + Roll Cutting | ✅ |
| Greige Warehouse | ✅ |
| Yarn Warehouse | ✅ |
| AsignacionRollos | ✅ |
| DyehouseBoard (Gantt scheduling) | ✅ |
| FMS (Article/Construction/Yarn) | ✅ |
| ERP (Warehouse/Kardex) | ✅ |
| Sales Orders | ✅ (basic) |
| Tech Specs / Fichas Técnicas | ✅ |

---

## Next Phases (To Build 🔲)

### Phase 4 — Warehouse & Weighing Room ✅
**Scope:** Lab requests chemicals from stock → Warehouse issues lots → Weighing room preps containers per batch.

**New Tables:**
```sql
dyestuff_lots              -- lot_barcode (unique), received_date, expiry_date, qc_status, qty_received, qty_remaining
lot_certificates           -- COA docs per lot (no hard delete)
dyestuff_documents         -- MSDS/TDS per dyestuff (no hard delete)
chemical_requisitions      -- production_formula_id, batch_id, dyestuff_id, required_qty, status
warehouse_issues           -- requisition_id, lot_id, qty_issued, scale_reading (no hard delete)
preparation_groups         -- batch_id, curve_step_id, container_label, dilution_volume_l
preparation_group_items    -- group_id, pf_item_id, lot_id, planned_weight, actual_weight (no hard delete)
```

**New Livewire Components:**
- `ChemicalRequisition` — pending requisitions per batch, lot barcode scan → confirm issue
- `WeighingRoomConsole` — tablet UI: scan lot → tare → scale read → variance (green/amber/red) → confirm

**Business Rules:**
- FEFO (First Expired, First Out) lot selection
- Warehouse issue blocked if COA/MSDS missing or expired (Compliance gate)
- Variance tolerance: ±2% (configurable per dyestuff)
- Lot barcode scan must match requisitioned dyestuff

**Models to create:** `DyestuffLot`, `LotCertificate`, `DyestuffDocument`, `ChemicalRequisition`, `WarehouseIssue`, `PreparationGroup`, `PreparationGroupItem`

---

### Phase 5 — Batch Execution & Planning ✅
**Scope:** Link preparation groups to running batches, track consumptions vs. plan.

**Tables to add to existing `batches`:**
```sql
-- Add to batches:
rework_generation INT DEFAULT 0   -- guard: max 3 (spec §1.8)
order_line_id BIGINT NULLABLE     -- FK to order_lines (integration stub)

batch_rolls          -- batch_id, roll_clave (etiqueta), weight_kg, length_m
batch_consumptions   -- batch_id, lot_id, planned_qty, actual_qty (reconciliation)
machine_schedules    -- machine_id, batch_id, planned_start, planned_end, actual_start, actual_end
```

**Enhancements:**
- `DyehouseBoard` — show actual consumption vs. planned when batch completes
- Formula Print (`/planning/formula-print/{batchId}`) — include batch_rolls, actual weights
- `Batch.rework_generation` guard: reject if > 3 without manager override

**Key integration point:** `Batch.order_line_id` links back to `sales_orders` for reject/rework flow.

---

### Phase 6 — QC, Disposition & Rework ✅
**Scope:** Spectrophotometer readings, Accept/Rework/Reject decision, rework child batches.

**New Tables:**
```sql
batch_dispositions   -- batch_id, measurement_id, disposition_type (enum), decided_by, customer_approved_by (no hard delete)
rework_orders        -- original_batch_id, new_batch_id, rework_curve_id, reason
order_lines          -- article_id, color_id, qty_required, qty_fulfilled, status (integration stub)
```

**New Livewire Components:**
- `QcMeasurementEntry` — L*/a*/b* entry per stage (wet/dry/finished), instant ΔE, scatter plot inline
- `DispositionDecision` — triggered after FAIL: Accept with Variance / Rework / Reject
  - Accept with Variance → capture customer approval
  - Rework → spawn child Batch (parent_batch_id, rework_generation+1)
  - Reject → write back to order_line (re-open required qty)

**Color Analytics Tab 4** (already built in ColorManagement) → wire up real `color_measurements` data.

**Business rules:**
- Batch dispositions: no hard delete (spec §1.10)
- Rework: max generation 3 before requiring manager override
- Accept with Variance: must capture customer_approved_by

---

### Phase 7 — Compliance Gates ✅
**Scope:** Block warehouse issues if compliance documents are missing or expired.

**New Tables:** (defined in Phase 4, gated here)
```sql
dyestuff_documents  -- MSDS/TDS version, expiry_date, is_active
lot_certificates    -- COA per lot, tested_parameters (json)
```

**New Livewire Component:**
- `ComplianceDashboard` — expiring MSDS/TDS alerts, lots missing COA, restricted chemical/customer conflicts

**Integration Points:**
- `ChemicalRequisition` store → check `dyestuff_documents.is_active` and `lot_certificates` exists
- `DyehouseBoard` → show compliance warning on batch card if formula uses restricted dyestuff

---

### Phase 8 — Reports & Dashboards ✅
**Scope:** Operational visibility across the full color workflow.

**Reports to build:**
| Report | Data Source | Key Metrics |
|---|---|---|
| Variance Analysis | `batch_consumptions` vs `production_formula_items` | Planned vs actual chemical usage per batch |
| First-Time-Right (FTR) | `batch_dispositions` | % accepted first pass, by article/dyer/machine/shift |
| Lot Traceability | `batch_consumptions` → `dyestuff_lots` | Full lot-to-batch chain for audit |
| Formula Performance | `color_measurements` + `lab_formulas` | ΔE trend per color/formula over time |
| Compliance Status | `dyestuff_documents` + `lot_certificates` | Expiry calendar, missing docs |

**Tech approach:** Livewire components with Chart.js (already installed). Export via `phpoffice/phpspreadsheet` (already in composer).

---

## Architecture Decisions Needed (from spec §6)

| # | Question | Default Proposed | Status |
|---|---|---|---|
| 1 | Does an `OrderLine`/`SalesOrder` model exist already? | `sales_orders` exists (basic) | ✅ Basic stub in place |
| 2 | Scale/barcode hardware integration (serial/Bluetooth)? | Manual entry for v1 | 🔲 Decide before Phase 4 |
| 3 | Max rework generations before manager override | 3 (spec suggestion) | 🔲 Confirm with client |
| 4 | Warehouse issue variance tolerance | ±2% configurable per dyestuff | 🔲 Confirm with client |

---

## Technical Debt (to address in parallel)

| # | Issue | Priority | File |
|---|---|---|---|
| 1 | `ColorManagement.php` is 820+ lines | HIGH | Split into child Livewire components |
| 2 | `Looms.php` is 800+ lines | MEDIUM | Extract modal logic |
| 3 | No authorization policies (`gate()`/`Policy`) | HIGH | Add role-based access before production |
| 4 | Dashboard KPI queries uncached | MEDIUM | Add `Cache::remember()` |
| 5 | `LivewireIntegrationTest` tests Antigravity components | LOW | Keep isolated |
| 6 | `DyeColors`, `FormulaBuilder`, `LabTrials`, `RecetasTintura` Livewire classes still exist | LOW | Safe to delete (routes redirect) |

---

## Test Coverage

| Area | Tests | Gap |
|---|---|---|
| Color CRUD | ✅ 6 tests | Authorization (role-based) |
| Lab Trials + ΔE | ✅ 14 tests | Stage-specific ΔE (wet vs dry vs finished) |
| Formula Approval | ✅ 9 tests | Rework integration, order_line write-back |
| Warehouse CRUD | ✅ 5 tests | Inventory operations, FEFO lot selection |
| DyehouseBoard | ❌ None | Scheduling logic, linked-list batch ordering |
| QC / Disposition | ❌ None | Entire Phase 6 |
| Compliance | ❌ None | Entire Phase 7 |
| Reports | ❌ None | Entire Phase 8 |
