# TANRAIL ONE — PHASE 5 PRE-IMPLEMENTATION ARCHITECTURE AUDIT
## Phase 5.0 — Reusable Capabilities (Production & Event Booking)

---

### 1. Executive Summary

This Pre-Implementation Architecture Audit evaluates **Phase 5.0 — Reusable Capabilities** following the formal completion and verification of **Phase 4.0 (Core Invoicing, Vendor Bills & Commercial Sub-Ledgers)**.

The analysis reconciles the official TANRAIL ONE master roadmap (`docs/12-development-roadmap.md`), the Core capability map (`docs/03-core-capability-map.md`), and the live codebase (`app/Domains/Core/`). 

Empirical test verification confirms the starting baseline is **100% green**:
- **247 / 247 automated tests passing**
- **498 assertions**
- **0 failures, 0 errors, 0 skipped**
- **Laravel Pint 100% clean**

Phase 5.0 is defined in the official project roadmap as **Reusable Capabilities** — shared modules needed by initial Business Units (Restaurant, Catering, Water, Transport). Specifically, Phase 5 encompasses:
1. **Production / Manufacturing (BOM & Assembly)**: Recipes, Bill of Materials (BOM), Production Orders, raw material consumption, finished goods receipt.
2. **Event Booking & Management**: Event engagements, package quotes, guest/attendee tracking, deposit invoicing integration.

This audit establishes the explicit requirements, dependency graph, database schema requirements, financial integration points, security controls, risk register, and recommended implementation sequence for Phase 5.0.

---

### 2. Official Phase 5 Scope

From `docs/12-development-roadmap.md`:

> **PHASE 5 — Reusable Capabilities**
> - **Objective:** Build shared modules needed by initial BUs.
> - **Tasks:** Production (BOM/Recipes), Event Booking.

From `docs/03-core-capability-map.md` (Section 3: Reusable Business Capabilities):
- **Production / Manufacturing**: Converting raw materials into finished goods / prep items. Used by Restaurant (Kitchen prep), Catering (Food prep), Water (Bottling). Main Entities: `Recipe` / `BillOfMaterials` (BOM), `ProductionOrder`.
- **Event Management**: Managing scheduled, date-specific engagements. Used by Catering, Equipment Rental. Main Entities: `Event`, `EventBooking`, `Schedule`, `AttendeeList`.

---

### 3. Roadmap Evidence

Inspection of project architecture documentation reveals:
1. **`docs/12-development-roadmap.md`**: Outlines Phase 5 directly following Phase 4.
2. **`docs/03-core-capability-map.md`**: Defines Reusable Capabilities as optional modules built outside the bare Core, enabled by specific BUs.
3. **`docs/08-workflow-and-transaction-specification.md`**: Details the Catering Event workflow (Inquiry → Proposal → Contracted → Preparation → Execution → Completed) and Kitchen Prep / Production Order transactions.

---

### 4. Current Architecture

The platform architecture stands at Phase 4.0 complete:
- **Core Domain**: `app/Domains/Core/` containing Auth, Multi-Tenancy, Catalogs (`Item`, `Unit`, `TaxCategory`), Inventory (`StockBalance`, `StockMovement`, `InventoryLocation`), Sales (`Order`), Procurement (`PurchaseOrder`, `PurchaseReceipt`), Commercial Sub-Ledger (`Invoice`, `SupplierInvoice`, `PaymentAllocation`, `CreditNote`), 3-Way Matching (`ThreeWayMatchingEngine`), and General Ledger (`FinancialService`, `AccountResolver`, `Journal`, `FiscalPeriod`, `ProcessedEvent`).
- **Reusable Modules Location**: `app/Domains/Modules/` is an initialized, clean directory designated for Phase 5 reusable capabilities (`Production` and `EventManagement`).

---

### 5. Existing Capabilities Inventory

| Existing Core Capability | Status in Codebase | Phase 5 Consumption |
|---|---|---|
| Multi-Tenant Scoping | Complete (`OrganizationScope`, `BusinessUnitScope`) | Applies to BOMs, Production Orders, Event Bookings |
| Master Item Catalog | Complete (`Item`, `Unit`, `TaxCategory`) | Items act as raw ingredients, BOM components, finished goods |
| Inventory & Warehouses | Complete (`StockBalance`, `StockMovement`, `InventoryService`) | Production consumes raw stock & receives finished stock |
| Commercial Invoicing | Complete (`InvoiceService`, `Invoice`, `PaymentAllocationService`) | Event Bookings trigger deposit & final invoices |
| General Ledger Engine | Complete (`FinancialService`, `AccountResolver`, `Journal`) | Production order completion posts GL inventory transformation journals |

---

### 6. Requirement Classification Matrix

| Requirement | Current Implementation Status | Classification | Evidence | Action for Phase 5 |
|---|---|---|---|---|
| **Inventory & Warehouse Engine** | Complete | **A — ALREADY IMPLEMENTED** | `InventoryService.php` | Consume for stock movements |
| **Commercial Sub-Ledger & Invoicing** | Complete | **A — ALREADY IMPLEMENTED** | `InvoiceService.php` | Consume for event deposits |
| **GL Double-Entry Engine** | Complete | **A — ALREADY IMPLEMENTED** | `FinancialService.php` | Consume for production journals |
| **Bill of Materials (BOM) / Recipe Schema** | None | **C — MISSING** | No BOM models in `app/` | Create `BillOfMaterials` & `BillOfMaterialsItem` |
| **Production Order Engine** | None | **C — MISSING** | No Production models in `app/` | Create `ProductionOrder` & `ProductionService` |
| **Event Booking Engine** | None | **C — MISSING** | No Event models in `app/` | Create `EventBooking` & `EventBookingService` |
| **Production GL Accrual Listener** | Partial (GL engine exists) | **B — PARTIALLY IMPLEMENTED** | `FinancialService` active; needs production event listener | Create `PostProductionCompletedToGlListener` |

---

### 7. Architectural Dependency Analysis

Phase 5 depends on and consumes existing capabilities from earlier phases:

```text
[ PHASE 1 & 2: MULTI-TENANCY ] ──► Organization, BusinessUnit, Scopes, Policies
                                         │
[ PHASE 3: MASTER DATA & STOCK ] ──► Item Catalog, Units, InventoryService (StockMovement)
                                         │
[ PHASE 4: INVOICING & FINANCE ] ──► InvoiceService, FinancialService, AccountResolver
                                         │
                                         ▼
                             [ PHASE 5: REUSABLE CAPABILITIES ]
                             ┌────────────────────────────────┐
                             │  Production (BOM & Assembly)   │
                             │  Event Booking & Management    │
                             └────────────────────────────────┘
```

---

### 8. Database Impact

Phase 5 requires new database migrations to support Reusable Capabilities:

1. **`bill_of_materials`**:
   - `id`, `organization_id`, `business_unit_id`, `finished_item_id`, `name`, `code`, `yield_quantity`, `is_active`, `created_by`, `timestamps`.
2. **`bill_of_materials_items`**:
   - `id`, `bill_of_materials_id`, `ingredient_item_id`, `quantity`, `unit_id`, `scrap_percentage`, `timestamps`.
3. **`production_orders`**:
   - `id`, `organization_id`, `business_unit_id`, `branch_id`, `bill_of_materials_id`, `production_number`, `target_quantity`, `actual_quantity`, `status` (`DRAFT`, `PLANNED`, `IN_PROGRESS`, `COMPLETED`, `CANCELLED`), `source_location_id`, `destination_location_id`, `created_by`, `timestamps`.
4. **`event_bookings`**:
   - `id`, `organization_id`, `business_unit_id`, `branch_id`, `customer_id`, `booking_number`, `event_name`, `event_date`, `guest_count`, `subtotal`, `tax_amount`, `total`, `deposit_amount`, `status` (`DRAFT`, `CONFIRMED`, `IN_PROGRESS`, `COMPLETED`, `CANCELLED`), `invoice_id`, `created_by`, `timestamps`.

> [!NOTE]
> Database changes are required for Phase 5. Migrations WILL be created during Phase 5 implementation upon explicit authorization.

---

### 9. Financial / Accounting Impact

- **Production Assembly GL Journal**: Completing a `ProductionOrder` converts raw ingredients into finished goods. The system will post a balanced GL entry:
  - `DEBIT Finished Goods Inventory Account` (value of produced items)
  - `CREDIT Raw Materials Inventory Account` (value of consumed ingredients)
- **Event Deposit Invoicing**: Event booking confirmation generates a Phase 4 `Invoice` and posts GL entry:
  - `DEBIT Accounts Receivable / Cash`
  - `CREDIT Sales Revenue / Unearned Revenue`
- **Rule**: `FinancialService` and `AccountResolver` will be consumed cleanly; the underlying General Ledger engine will NOT be altered.

---

### 10. Security Impact

- **Tenant Isolation**: All Phase 5 entities (`BillOfMaterials`, `ProductionOrder`, `EventBooking`) MUST include `organization_id` and `business_unit_id` and enforce `OrganizationScope` and `BusinessUnitScope`.
- **Server-Side Authorization**: New policies (`BillOfMaterialsPolicy`, `ProductionOrderPolicy`, `EventBookingPolicy`) must evaluate `hasAccessToScope()` and deny cross-tenant or roleless requests.
- **Fail-Closed Immutability**: Completed production orders and finalized event bookings must be immutable.

---

### 11. Test Gap Analysis

The existing 247 passing tests cover Phase 1 to Phase 4. Phase 5 will require dedicated test suites:

1. `Phase51ProductionFoundationTest.php`: BOM creation, ingredient linking, tenant scoping.
2. `Phase52ProductionExecutionTest.php`: Production order lifecycle, raw material stock deduction, finished goods stock receipt, GL inventory transformation journal.
3. `Phase53EventBookingTest.php`: Event booking lifecycle, deposit invoicing, guest list tracking.
4. `Phase54ReusableSecurityTest.php`: Cross-tenant attack vectors on BOMs, production orders, and event bookings.

---

### 12. Risk Register

| Risk ID | Risk Description | Probability | Impact | Severity | Mitigation Strategy |
|---|---|---|---|---|---|
| `RISK-5.1` | Raw stock insufficiency during production order execution | High | High | High | Enforce pre-execution inventory balance check before deducting raw materials. |
| `RISK-5.2` | Cross-tenant ingredient mixing in BOM definition | Medium | High | High | Validate ingredient `organization_id` matches BOM `organization_id`. |
| `RISK-5.3` | GL journal imbalance on fractional ingredient rounding | Low | High | Medium | Use `bcadd`/`bcmul` math with 4-decimal precision on ingredient cost rollups. |
| `RISK-5.4` | Duplicate event deposit invoicing | Low | Medium | Medium | Use `ProcessedEvent` idempotency locks for event booking invoice generation. |

---

### 13. Recommended Implementation Sequence

To maintain controlled implementation quality, Phase 5 should be executed in 6 structured sub-phases:

```text
Phase 5.1 — Production Foundation & Bill of Materials (BOM)
  ↓
Phase 5.2 — Production Order & Inventory Assembly Engine
  ↓
Phase 5.3 — Event Management & Booking Engine
  ↓
Phase 5.4 — Production & Event GL Financial Integration
  ↓
Phase 5.5 — Security Hardening, Policies & Tenant Isolation
  ↓
Phase 5.6 — Full System Regression & Phase 5 Completion Certification
```

---

### 14. Files Expected to Change / Be Created

#### Expected New Files
- `app/Domains/Modules/Production/Models/BillOfMaterials.php`
- `app/Domains/Modules/Production/Models/BillOfMaterialsItem.php`
- `app/Domains/Modules/Production/Models/ProductionOrder.php`
- `app/Domains/Modules/Production/Services/ProductionService.php`
- `app/Domains/Modules/EventManagement/Models/EventBooking.php`
- `app/Domains/Modules/EventManagement/Services/EventBookingService.php`
- `database/migrations/2026_09_05_000001_create_bill_of_materials_table.php`
- `database/migrations/2026_09_05_000002_create_production_orders_table.php`
- `database/migrations/2026_09_05_000003_create_event_bookings_table.php`
- Dedicated test suites in `tests/Feature/Modules/`

---

### 15. Files That MUST NOT Be Changed

1. **DO NOT** modify existing Phase 4 commercial services (`InvoiceService`, `SupplierInvoiceService`, `CreditNoteService`, `PaymentAllocationService`, `ThreeWayMatchingEngine`).
2. **DO NOT** modify foundational GL services (`FinancialService`, `AccountResolver`).
3. **DO NOT** modify existing database migrations from Phase 1 through Phase 4.
4. **DO NOT** weaken `OrganizationScope`, `BusinessUnitScope`, or existing Gate policies.

---

### 16. Authorization Requirements

Implementation of Phase 5 (or Sub-Phase 5.1) requires explicit human authorization.

---

### 17. Final Architecture Gate

Phase 5 Pre-Implementation Audit is **COMPLETE AND VERIFIED**.
