# Phase 4 Final Implementation Plan

**Document Status:** Pending Authorization  
**Phase:** 4.0 — Core Invoicing, Vendor Bills & Commercial Sub-Ledgers  
**Target:** Business-Agnostic Core (`app/Domains/Core/`)  

---

## Controlled Implementation Stages

### Stage 4.1 — Database Schema & Migrations
- Migration `create_invoices_table`
- Migration `create_invoice_lines_table`
- Migration `create_supplier_invoices_table`
- Migration `create_supplier_invoice_lines_table`
- Migration `create_payment_allocations_table`
- Migration `create_credit_notes_table`
- Migration `create_credit_note_lines_table`
- Migration `modify_payments_table_add_invoice_id_make_order_id_nullable`
- Migration `modify_supplier_payments_table_add_supplier_invoice_id_make_po_id_nullable`

### Stage 4.2 — Invoice & InvoiceLine Models & Service
- Models: `Invoice`, `InvoiceLine`
- Enums: `InvoiceStatus` (`DRAFT`, `ISSUED`, `PARTIALLY_PAID`, `PAID`, `VOIDED`, `CANCELLED`)
- Boot hooks enforcing immutability after issuance.
- `InvoiceService::createInvoice()`, `InvoiceService::issueInvoice()`.

### Stage 4.3 — SupplierInvoice & SupplierInvoiceLine Models & Service
- Models: `SupplierInvoice`, `SupplierInvoiceLine`
- Enums: `SupplierInvoiceStatus` (`DRAFT`, `PENDING_MATCH`, `DISCREPANCY`, `APPROVED`, `PARTIALLY_PAID`, `PAID`, `VOIDED`)
- Immutability boot hooks.
- `SupplierInvoiceService::createBill()`, `SupplierInvoiceService::approveBill()`.

### Stage 4.4 — PaymentAllocation Core Engine
- Model: `PaymentAllocation`
- Polymorphic / direct allocation support (Customer Payments -> Invoices, Supplier Payments -> Supplier Invoices).
- `PaymentAllocationService::allocate()` with pessimistic DB locking (`lockForUpdate`).
- Invariants: `allocated <= payment.unallocated`, `allocated <= invoice.balance_due`, Organization/BU match validation.

### Stage 4.5 — CreditNote & Customer Adjustments
- Models: `CreditNote`, `CreditNoteLine`
- Enums: `CreditNoteStatus` (`DRAFT`, `ISSUED`, `APPLIED`, `VOIDED`)
- `CreditNoteService::issueCreditNote()`, `CreditNoteService::applyToInvoice()`.

### Stage 4.6 — Three-Way Matching Engine
- Service: `ThreeWayMatchingEngine`
- Compare PO vs Purchase Receipt vs Supplier Invoice line quantities and prices.
- Auto-set status to `APPROVED` if matched, or `DISCREPANCY` if mismatched.
- Manager override method `overrideDiscrepancy(SupplierInvoice $bill, User $manager, string $reason)`.

### Stage 4.7 — Financial Ledger Integration & GL Automations
- Integration listeners:
  - `InvoiceIssued` -> Post GL Journal (`DR Accounts Receivable`, `CR Sales Revenue`, `CR Tax Liability`)
  - `PaymentAllocated` -> Post GL Journal (`DR Cash/Bank`, `CR Accounts Receivable` or `DR Accounts Payable`, `CR Cash/Bank`)
  - `SupplierInvoiceApproved` -> Post GL Journal (`DR Inventory/Expense`, `DR Input Tax Recoverable`, `CR Accounts Payable`)
  - `CreditNoteIssued` -> Post GL Journal (`DR Sales Revenue`, `DR Tax Liability`, `CR Accounts Receivable`)

### Stage 4.8 — Security Hardening & Tenant Isolation
- Global scopes: `OrganizationScope`, `BusinessUnitScope` applied to all Phase 4 models.
- Policy enforcement: `InvoicePolicy`, `SupplierInvoicePolicy`, `PaymentAllocationPolicy`.
- Server-side payload validation preventing cross-BU / cross-Org ID manipulation.

### Stage 4.9 — Adversarial & Security Testing
- Test suites covering cross-tenant attacks, over-allocation attempts, concurrent allocation, closed fiscal period posting, tax calculation edge cases, and double-event delivery idempotency.

### Stage 4.10 — Full System Regression
- Execute full PHPUnit test suite ensuring 100% pass rate across Phase 1, Phase 2, Phase 3 (3.1, 3.2.2, 3.2.3, 3.2.4, 3.3, 3.3.1, 3.4), and Phase 4.
