# TANRAIL ONE — Phase Next Recommendation: Phase 4 Core Invoicing & Sub-Ledger Architecture

## 1. Executive Summary
Following the comprehensive reconciliation of the TANRAIL ONE master roadmap (`docs/12-development-roadmap.md`), the Core completeness audit (`docs/phase-core-completeness-audit.md`), and the actual codebase (`app/Domains/Core/`), this document defines the **true, correct next phase** for the project:

### Recommended Phase:
**PHASE 4 — CORE INVOICING, VENDOR BILLS & COMMERCIAL SUB-LEDGER ARCHITECTURE**

---

## 2. Why Phase 4 Is the Correct Next Phase

### 2.1 Reconciling the Missing Commercial Loop
In Phase 3.2.3 and Phase 3.3.1, the platform established order taking, payments, and general ledger journal creation. However:
1. **No Invoices Exist**: Customer payments link directly to `Order` records. There is no `Invoice` entity, no invoice numbering, and no tax invoice record.
2. **One-Sided Accounts Receivable (AR)**:
   - When payment is received, `RecordSalesPaymentListener` credits AR (`CREDIT AR`).
   - However, AR was **never debited** because no invoice or sales recognition journal was posted!
   - Over time, AR becomes an artificial negative liability instead of reflecting customer receivables.
3. **One-Sided Accounts Payable (AP)**:
   - When a supplier payment is recorded, `RecordSupplierPaymentListener` debits AP (`DEBIT AP`).
   - However, AP was **never credited** because no vendor bill or receipt accrual journal was posted!
   - Over time, AP becomes an artificial positive asset instead of reflecting supplier obligations.
4. **No Credit Notes**: Reversals of customer billing currently have no commercial mechanism.

### 2.2 Why Jumping to Phase 5 (Production/BOM) Was Inappropriate
- Jumping to Phase 5.1 (Production/BOM) skips Phase 4 of the roadmap.
- Manufacturing finished goods when the system cannot generate formal invoices or balance accounts receivable creates severe architectural distortion.
- Completing Phase 4 closes the generic Core financial loop, making every commercial transaction legally compliant and accounting-sound across all future business units.

---

## 3. Classification
- **Classification**: **Core Capability** (`app/Domains/Core/`)
- **Reasoning**: Invoices, Vendor Bills, Credit Notes, and AR/AP recognition are universal business concepts required by every enterprise entity (Restaurant, Catering, Water, Transport, Retail). They belong in `Core/` and must remain 100% business-agnostic.

---

## 4. Proposed Scope for Phase 4

### 4.1 Major Entities
1. **`Invoice`**:
   - `id`, `business_unit_id`, `branch_id`, `order_id`, `customer_id`, `invoice_number` (sequential/unique per BU), `issue_date`, `due_date`, `subtotal`, `tax_total`, `total`, `amount_paid`, `balance_due`, `status` (`DRAFT`, `ISSUED`, `PARTIALLY_PAID`, `PAID`, `VOIDED`), `created_by`, `timestamps`.
2. **`InvoiceLine`**:
   - `id`, `invoice_id`, `item_id`, `quantity`, `unit_price`, `tax_amount`, `subtotal`, `total`, `timestamps`.
3. **`SupplierInvoice` (Vendor Bill)**:
   - `id`, `business_unit_id`, `branch_id`, `purchase_order_id`, `supplier_id`, `bill_number`, `bill_date`, `due_date`, `subtotal`, `tax_total`, `total`, `amount_paid`, `balance_due`, `status` (`DRAFT`, `RECEIVED`, `APPROVED`, `PARTIALLY_PAID`, `PAID`, `VOIDED`), `timestamps`.
4. **`CreditNote`**:
   - `id`, `business_unit_id`, `branch_id`, `invoice_id`, `credit_note_number`, `amount`, `reason`, `status`, `timestamps`.

### 4.2 Financial Posting Invariants to Complete
1. **Sales Recognition (Invoice Issuance / Order Confirmation)**:
   - `DEBIT Accounts Receivable` (total)
   - `CREDIT Sales Revenue` (subtotal)
   - `CREDIT Tax Liability` (tax)
2. **Payment Application**:
   - `DEBIT Cash / Bank / Mobile Money`
   - `CREDIT Accounts Receivable`
   - Updates `Invoice.amount_paid` and `Invoice.balance_due`
3. **Bill Recognition (Supplier Bill Approval / Goods Receipt)**:
   - `DEBIT Expense / Inventory` (subtotal)
   - `CREDIT Accounts Payable` (total)
4. **Disbursement Application**:
   - `DEBIT Accounts Payable`
   - `CREDIT Cash / Bank`
   - Updates `SupplierInvoice.amount_paid` and `SupplierInvoice.balance_due`

---

## 5. Security & Scoping Model
- Both `Invoice` and `SupplierInvoice` will strictly inherit `BusinessUnitScope`.
- Strict validation that customer/supplier belongs to the same Organization as the Business Unit.
- `Payment` records re-linked to validate against specific `Invoice` balances, preventing overpayment beyond invoice total.
- Immutability observers: `ISSUED` invoices and `APPROVED` vendor bills cannot be deleted; adjustments must happen through `CreditNote` or reversing journals.

---

## 6. Integration Points
- **Core Sales**: `OrderService` triggers invoice issuance upon order confirmation or explicit billing.
- **Core Procurement**: `PurchaseService` matches receipts to `SupplierInvoice`.
- **Core Finance**: Full integration with `AccountResolver` (`default_sales_revenue_account_id`, `default_accounts_receivable_account_id`, `default_accounts_payable_account_id`, `default_tax_liability_account_id`).
- **Core Idempotency**: `ProcessedEvent` prevents duplicate invoice generation.

---

## 7. Risks & Mitigations
- **Backward Compatibility Risk**: Existing tests (`Phase323SalesEngineTest`, `Phase34CoreIntegrationTest`) currently attach `Payment` directly to `Order`.
  - *Mitigation*: Maintain `Payment.order_id` as optional/legacy alongside `Payment.invoice_id`, or automatically generate an `Invoice` on payment recording during transition.

---

## 8. Human Decisions Required
1. **Confirm Phase Title & Number**:
   - Confirm that the next implementation phase is officially **Phase 4 — Core Invoicing, Vendor Bills & Commercial Sub-Ledgers**.
2. **Direct Cash Sales Invoicing Model**:
   - Confirm whether point-of-sale cash transactions automatically generate and immediately mark an `Invoice` as `PAID` (standard ERP practice).
3. **3-Way Matching Rigor**:
   - Confirm whether Vendor Bills require strict 3-way matching (PO quantity == Receipt quantity == Bill quantity) or allow flexible manual entry in Phase 4.

---

## 9. Recommended Next Action
Awaiting human review and explicit authorization of this recommendation before writing any code or migrations.
