# TANRAIL ONE — Phase 4.0 Commercial Sub-Ledgers & Invoicing Architecture

## 1. Executive Summary & Objective
Phase 4.0 introduces the business-agnostic **Commercial Sub-Ledger Layer** to TANRAIL ONE. This layer bridges the gap between operational commercial transactions (Sales Orders, Purchase Orders, Receipts) and the foundational General Ledger (`Journal`, `JournalEntry`).

Without this layer, financial event listeners in Phase 3.3.1 recorded one-sided Cash vs. AR/AP postings without prior revenue or expense recognition. Phase 4.0 completes the core financial loop:
- **Sales Loop**: Order → Invoice (`DR AR`, `CR Revenue`, `CR Tax`) → Payment Allocation (`DR Cash`, `CR AR`).
- **Procurement Loop**: Purchase Order → Purchase Receipt → Vendor Bill (`DR Inventory/Expense`, `CR AP`) → Supplier Payment Allocation (`DR AP`, `CR Cash`).

All components remain strictly within `app/Domains/Core/` and maintain 100% business-agnostic neutrality across Restaurant, Catering, Water, Transport, Retail, and future extensions.

---

## 2. High-Level Commercial Sub-Ledger Architecture

```text
[ SALES ENGINE ]                           [ GENERAL LEDGER ]
   Sales Order
        │                                ┌──────────────────┐
        ▼                                │   JOURNAL &      │
   Customer Invoice  ──────(post)───────►│   JOURNAL ENTRY  │
        │                                │                  │
        ▼                                │  DR AR           │
   Payment Allocation ────(post)────────►│  CR Revenue      │
        │                                │  CR Tax          │
        ▼                                └──────────────────┘
   Payment (Cash/Bank)                           ▲
                                                 │
[ PROCUREMENT ENGINE ]                           │
   Purchase Order                                │
        │                                        │
        ▼                                        │
   Purchase Receipt                              │
        │                                        │
        ▼                                        │
   Supplier Bill     ──────(post)────────────────┘
        │                                (DR Inventory/Expense, CR AP)
        ▼
   Supplier Payment Allocation
```

---

## 3. Sub-System Components

### 3.1 Customer Invoicing Sub-System
- **Purpose**: Generates auditable, tax-compliant commercial sales documents for goods or services rendered.
- **Key Entities**: `Invoice`, `InvoiceLine`.
- **Integrations**: Linked optionally to source `Order` records. Supports direct point-of-sale invoicing as well as deferred billing.

### 3.2 Accounts Receivable (AR) Sub-Ledger
- **Purpose**: Tracks outstanding claims against customers.
- **Mechanism**: The General Ledger control account (`default_accounts_receivable_account_id`) is supported by the `Invoice` sub-ledger where `balance_due = total - amount_paid`.
- **Auditability**: Total AR control account balance equals the sum of uncollected `Invoice` balances.

### 3.3 Accounts Payable (AP) Sub-Ledger & Vendor Bills
- **Purpose**: Records supplier claims against the organization for received goods or services.
- **Key Entities**: `SupplierInvoice` (Vendor Bill), `SupplierInvoiceLine`.
- **Integrations**: Linked to `PurchaseOrder` and `PurchaseReceipt`.

### 3.4 Payment Allocation Engine
- **Purpose**: Decouples money movement (`Payment`, `SupplierPayment`) from billing document settlement (`Invoice`, `SupplierInvoice`).
- **Key Entity**: `PaymentAllocation`.
- **Flexibility**: Supports 1:1, 1:N, N:1, partial payments, and unallocated credits.

### 3.5 Credit Notes & Adjustments
- **Purpose**: Enables auditable, non-destructive corrections to issued commercial documents.
- **Key Entities**: `CreditNote`, `CreditNoteLine`.
- **Impact**: Reverses revenue/tax and reduces AR balance without mutating issued invoices.

### 3.6 Three-Way Matching Engine
- **Purpose**: Validates vendor bills against purchase orders and goods receipts prior to bill approval.
- **Controls**: Detects quantity, unit price, and tax discrepancies; enforces configurable tolerance limits.

---

## 4. Key Architectural Decisions

### ADR-010: Commercial Document Immutability
Issued `Invoice` and approved `SupplierInvoice` records are strictly immutable. Application-level `update()` and `delete()` operations are blocked by model observers. Corrections MUST occur through `CreditNote` records or reversing journals.

### ADR-011: Decoupled Payment Allocation
Payments record the flow of cash/funds. Allocations map funds to specific invoices/bills. Overpayments remain unallocated on the customer/supplier sub-ledger until applied to future invoices or refunded via Credit Note.

### ADR-012: Document Value Snapshotting
`InvoiceLine` and `SupplierInvoiceLine` store explicit snapshots of item name, description, unit price, tax rate, and tax category ID at the moment of issuance. Future master data price or tax rate changes will NEVER alter historical commercial documents.

---

## 5. Architectural Boundaries
1. **No Inventory Re-invention**: Phase 4 does not create stock balance tables; it consumes `InventoryService` and `StockMovement`.
2. **No Competitor Ledger**: AR/AP sub-ledgers derive directly from `Invoice` and `SupplierInvoice` line items and allocations, with GL journals serving as the sole financial source of truth.
3. **No Industry Jargon**: Zero terms related to tables, kitchens, menus, tickets, drivers, or routes exist in `app/Domains/Core/`.
