# TANRAIL ONE — Phase 4.0 Implementation Plan

## 1. Overview
This implementation plan outlines the sequential execution stages for **Phase 4.0: Core Invoicing, Vendor Bills & Commercial Sub-Ledgers** once human authorization is granted.

---

## 2. Stage Breakdown

### Stage 1: Enums & Domain Exceptions
- Create `InvoiceStatus`, `SupplierInvoiceStatus`, `CreditNoteStatus`, `MatchStatus`.
- Create domain exceptions: `InvalidAllocationException`, `DiscrepancyException`, `CrossBusinessUnitException`.

### Stage 2: Database Migrations
- `2026_09_05_000001_create_invoices_tables.php` (`invoices`, `invoice_lines`)
- `2026_09_05_000002_create_supplier_invoices_tables.php` (`supplier_invoices`, `supplier_invoice_lines`)
- `2026_09_05_000003_create_credit_notes_tables.php` (`credit_notes`, `credit_note_lines`)
- `2026_09_05_000004_create_payment_allocations_table.php` (`payment_allocations`)
- `2026_09_05_000005_add_invoice_id_to_payments_tables.php` (update `payments`, `supplier_payments`)

### Stage 3: Core Domain Models & Observers
- Create `Invoice`, `InvoiceLine`, `SupplierInvoice`, `SupplierInvoiceLine`, `CreditNote`, `CreditNoteLine`, `PaymentAllocation`.
- Attach `OrganizationScope` and `BusinessUnitScope`.
- Implement observer guards for immutability and cross-tenant validation.

### Stage 4: Service Layer Implementation
- `InvoiceService`: `createDraft()`, `issueInvoice()`, `voidInvoice()`.
- `SupplierInvoiceService`: `createBill()`, `approveBill()`, `performThreeWayMatch()`.
- `CreditNoteService`: `issueCreditNote()`, `applyCreditNote()`.
- `PaymentAllocationService`: `allocateCustomerPayment()`, `allocateSupplierPayment()`.

### Stage 5: Domain Events & GL Posting Integration
- Events: `InvoiceIssued`, `SupplierInvoiceApproved`, `PaymentAllocated`, `SupplierPaymentAllocated`, `CreditNoteIssued`.
- Listeners: `RecordInvoiceRevenueListener`, `RecordSupplierBillPayableListener`, `RecordPaymentAllocationListener`, `RecordCreditNoteReversalListener`.
- Integrate with `FinancialService` and `AccountResolver`.

### Stage 6: Automated Test Suite & Boundary Scan
- Create `tests/Feature/Core/Phase4InvoicingTest.php` implementing all 15 adversarial test scenarios.
- Run `Phase34BoundaryTest` to confirm zero business jargon leaks.

### Stage 7: Regression & Final Gate Review
- Run `php artisan test` (verify 142 baseline + Phase 4 tests pass with 0 failures).
- Produce Phase 4 Implementation Report & Gate Verification.
