# TANRAIL ONE — Core Completeness & Financial Audit

## 1. Audit Overview
This audit examines the actual state of the TANRAIL ONE Core (`app/Domains/Core/`) against enterprise operational requirements to determine whether the Core is genuinely complete and self-consistent before any Reusable Modules (Phase 5) or Business Extensions (Phase 6/7) are introduced.

---

## 2. Comprehensive Financial Core Audit

### 2.1 What Finance Core Currently Controls (Verified in Code)

1. **Chart of Accounts (`Account`)**:
   - Organization-scoped model with types: `ASSET`, `LIABILITY`, `EQUITY`, `REVENUE`, `EXPENSE`.
   - `is_active` status flag.
2. **Account Hierarchy**:
   - `parent_id` self-referencing foreign key on `accounts`.
   - Enforces tree invariants in `Account::booted()`:
     - Prevents self-parenting (`$account->parent_id === $account->id`).
     - Prevents cross-Organization parent relationships (`$parent->organization_id === $account->organization_id`).
     - Prevents circular references via recursive ancestor traversal (`AccountHierarchyException`).
3. **Fiscal Periods (`FiscalPeriod`)**:
   - Organization-scoped model with start date, end date, and `is_closed` boolean.
   - `FinancialService::postJournal()` and `reverseJournal()` validate that the posting date falls within an open period. Closed or missing periods throw `FiscalPeriodClosedException`.
4. **Journal Types (`JournalType`)**:
   - Native PHP backed enum: `OPERATIONAL`, `MANUAL`, `OPENING_BALANCE`, `CLOSING`, `REVERSAL`.
   - `Journal::type` cast and stored on all journals.
5. **Double-Entry General Ledger (`Journal` & `JournalEntry`)**:
   - `Journal` is header, scoped by `BusinessUnitScope`.
   - `JournalEntry` is immutable line (debit or credit).
   - Polymorphic linkage (`reference_type`, `reference_id`) to business transactions.
6. **Debit / Credit Balancing**:
   - Mathematical invariant strictly verified using `bcadd`/`bccomp` at 4 decimal places.
   - Requires `SUM(debit) == SUM(credit)`.
   - Single lines cannot have both debit and credit; negative values are strictly prohibited (`FinancialConfigurationException`, `JournalImbalanceException`).
7. **Journal Immutability**:
   - Model observers on `Journal` prevent `delete()` and prevent `update()` unless specifically transitioning `status` to `REVERSED`.
   - Model observers on `JournalEntry` unconditionally throw `JournalImmutableException` on `update()` or `delete()`.
8. **Reversal Journals**:
   - `FinancialService::reverseJournal()` locks original journal with `lockForUpdate()`, marks original as `REVERSED`, creates a new journal with `type = JournalType::REVERSAL`, links `reverses_journal_id`, and inverts debits and credits atomically.
9. **Payment Posting**:
   - `RecordSalesPaymentListener`: Debits resolved asset account (Cash, Bank, Mobile Money, Card) and credits Accounts Receivable (`AR`).
   - `RecordSupplierPaymentListener`: Debits Accounts Payable (`AP`) and credits resolved disbursement asset account.
10. **Tax Liability Posting Architecture**:
    - `TaxCategory` model has `liability_account_id` and `organization_id` foreign keys.
    - Model observer validates that `liability_account_id` belongs to the same Organization.
    - `AccountResolver::resolveTaxLiabilityAccount()` resolves category liability or organization fallback.
11. **Financial Account Configuration (`FinancialSettings` & `AccountResolver`)**:
    - Centralized `financial_settings` table mapping default accounts per Organization with optional Business Unit overrides.
    - Zero hardcoded codes (`'CASH'`, `'AR'`, `'AP'`, `'SALES'`, `'TAX'`).
    - Deterministic resolution: BU override → Organization default → `FinancialConfigurationException` (triggers database rollback).
12. **Organization & BU Financial Isolation**:
    - Enforced via `OrganizationScope` and `BusinessUnitScope`.
    - Cross-tenant account usage rejected at service layer with `CrossOrganizationException`.
13. **Auditability**:
    - Captures `created_by` (User ID), timestamps, and operational reference on every journal.
14. **Integration with Sales**:
    - Event listener `RecordSalesPaymentListener` subscribed to `SalesPaymentReceived`.
15. **Integration with Procurement**:
    - Event listener `RecordSupplierPaymentListener` subscribed to `SupplierPaymentRecorded`.

---

### 2.2 What Finance Core DOES NOT Yet Control (Gaps & Deferred Capabilities)

1. **Inventory Valuation**:
   - Stock items have `base_price` (selling price), but NO unit cost or inventory valuation method (FIFO, LIFO, Moving Average, Standard Cost).
   - Core Inventory only tracks physical quantities, not inventory monetary asset value.
2. **Cost of Goods Sold (COGS)**:
   - When an Order is confirmed or fulfilled, stock is depleted via `DeductInventoryListener`, but **NO journal entry is posted to the General Ledger** (no `DEBIT COGS`, `CREDIT Inventory Asset`).
3. **Accounts Receivable (AR) Recognition & Lifecycle**:
   - **No `Invoice` model exists.**
   - When a sale is confirmed, NO journal entry is posted to recognize revenue or establish Accounts Receivable.
   - Consequently, when `RecordSalesPaymentListener` credits AR upon receiving payment, AR is being credited against an unestablished debit!
   - No customer aging reports, credit limits, payment terms, or customer balance statements.
4. **Accounts Payable (AP) Recognition & Lifecycle**:
   - **No `SupplierInvoice` / `VendorBill` model exists.**
   - When goods are received via `PurchaseReceipt`, NO journal entry is posted to recognize the payable.
   - Consequently, when `RecordSupplierPaymentListener` debits AP upon payment, AP is being debited against an unestablished credit!
   - No 3-way matching (PO vs Receipt vs Invoice), no supplier aging, no vendor balance statements.
5. **Credit Notes & Customer Refunds**:
   - No formal `CreditNote` entity or workflow to reverse an issued invoice or issue customer refunds with corresponding GL journal reversals.
6. **Expense Tracking**:
   - No `Expense` model or direct operational expense voucher system exists in Core.
7. **Bank Reconciliation**:
   - Formally deferred. No bank statement import, bank ledger account matching, or uncleared checks/deposits workflow.
8. **Financial Statements Generation**:
   - No reporting service to generate a Trial Balance, Balance Sheet, or Profit & Loss (Income Statement) from `JournalEntry` rows.
9. **Budgeting & Cost Centers**:
   - No budget allocation, departmental cost centers, or budget-vs-actual variance tracking.
10. **Fixed Assets & Depreciation**:
    - No fixed asset register, capitalization workflows, or depreciation schedules.
11. **Payroll Accounting**:
    - No payroll liability journals, gross salary, tax withholdings, or net pay disbursement tracking.
12. **Period Closing Workflow**:
    - `FiscalPeriod.is_closed` is currently a manual boolean switch. There is no automated period closing routine that calculates net profit/loss and posts closing entries (`JournalType::CLOSING`) into Retained Earnings equity.
13. **Tax Reporting**:
    - Only tax liability routing exists. No VAT return reports, tax summary generation, or electronic tax filing integrations.

---

## 3. Core Architecture Completeness Audit

### 3.1 Inventory Core Completeness
- **Present**: Multi-location stock balances, immutable movements, stock transfers, negative stock protection.
- **Missing**: Valuation (unit cost), stocktaking (physical inventory reconciliation adjustments), batch/serial tracking, scrap/spoilage reason codes.

### 3.2 Sales Core Completeness
- **Present**: `Order`, `OrderLine`, `Payment`, order confirmation, inventory deduction, payment receipt journal.
- **Missing**: **Formal `Invoice` generation**, invoice numbering sequences, payment terms, customer credit management, return/refund credit notes.

### 3.3 Procurement Core Completeness
- **Present**: `PurchaseOrder`, `PurchaseOrderLine`, `PurchaseReceipt`, `PurchaseReceiptLine`, `SupplierPayment`, receipt inventory increase, payment disbursement journal.
- **Missing**: **Vendor Bill (`SupplierInvoice`)**, 3-way matching between PO, Receipt, and Bill, landed cost allocation, return to vendor (RTV).

---

## 4. Architectural Verdict
The platform has a rock-solid **General Ledger and Operational Transaction Engine**, but is missing the **Commercial Invoicing & Sub-Ledger Layer (Invoices, Bills, Credit Notes, AR/AP Recognition)**.

Proceeding directly to Business Extensions (Restaurant/Catering) or Reusable Manufacturing (Phase 5) without formalizing Invoicing and Sub-Ledgers leaves the core financial loop structurally incomplete:
- Sales transactions currently take customer money without generating a legal, tax-compliant invoice.
- Procurement transactions disburse supplier funds without matching a vendor bill.
- Accounts Receivable and Accounts Payable ledger balances do not reflect actual outstanding claims because only the payment side is booked.

**RECOMMENDATION**: The missing commercial financial loop (formal Invoices, Vendor Bills, AR/AP recognition) must be addressed as **Phase 4: Core Invoicing & Sub-Ledger Architecture** before external reusable or extension modules are layered on top.
