# Phase 5.4 Pre-Implementation Audit

## Executive Summary
A comprehensive audit of the Phase 4 and Phase 5 architecture has been conducted to prepare for Phase 5.4 (Production & Event GL Financial Integration). The audit reveals that while the core GL architecture (FinancialService, ProcessedEvent, FiscalPeriod) is robust and correctly implemented, there are **critical architectural gaps** that prevent immediate implementation of Production and Event GL integration without violating the strict instructions not to invent financial logic or modify core without approval.

## 1. Production Costing Gap
### Problem
The prompt strictly forbids inventing a costing methodology: *"DO NOT simply calculate: quantity × arbitrary price unless the existing architecture explicitly defines that as the authoritative valuation method."* 

### Evidence
- The `Item` model and migration only define a `base_price` (used for sales/invoicing). There is no `unit_cost` or `standard_cost`.
- The `StockMovement` and `StockBalance` models do not track the value of inventory, only quantity.
- `InventoryService` handles quantities but contains no financial valuation logic.
- There is no existing `CostingService` or `InventoryValuationService`.

### Financial Risk
Without an authoritative cost, the GL journal for Production (DR Finished Goods, CR Raw Materials) cannot be accurately calculated. Using `base_price` would inflate inventory values to retail prices, recognizing unrealized margin as inventory value.

### Proposed Solution
We need authorization to either:
1. Add a `standard_cost` field to the `items` table and use Standard Costing for production journals.
2. Add cost tracking to `StockMovement` (e.g., Moving Average Cost).

## 2. Missing Account Configuration
### Problem
Production GL posting requires Raw Materials Inventory and Finished Goods Inventory accounts.

### Evidence
- `FinancialSettings` (and its database migration) only supports: `default_cash_account_id`, `default_accounts_receivable_account_id`, `default_sales_revenue_account_id`, etc.
- There are **no inventory or cost of goods sold (COGS) accounts** configured in `FinancialSettings`.
- `AccountResolver` cannot resolve accounts that do not exist in the settings schema.

### Financial Risk
Hardcoding account IDs is strictly forbidden by the prompt. Without configuration, the system cannot resolve the correct ledger accounts for the Production journal.

### Proposed Solution
Modify the `financial_settings` migration and `FinancialSettings` model to include:
- `default_raw_materials_account_id`
- `default_finished_goods_account_id`
- (Optional but recommended) `default_customer_deposit_liability_account_id` for Event Management.

## 3. Event Booking Revenue Double-Counting
### Problem
The current `EventBookingService` leverages the Phase 4 `InvoiceService`, which is good, but it results in double-counting revenue.

### Evidence
1. `confirmBooking()` generates a Deposit Invoice for the deposit amount. `PostInvoiceToGlListener` will post this entire amount to `default_sales_revenue_account_id`.
2. `completeBooking()` generates a Final Invoice for the **full amount** of all packages (if balance > 0). `PostInvoiceToGlListener` will post this entire full amount to `default_sales_revenue_account_id`.

### Financial Risk
The deposit amount is recognized as revenue twice. Furthermore, standard accounting dictates that a deposit should typically be credited to a Customer Deposit Liability account, not Revenue, until the event is delivered.

### Proposed Solution
1. **Deposit Invoice:** The deposit invoice should map to a Liability account (requires adding `default_customer_deposit_liability_account_id` to settings and intercepting the GL posting for deposit invoices).
2. **Final Invoice:** The final invoice should include a negative line item (Discount/Deposit Applied) that debits the Liability account and credits Accounts Receivable, ensuring the net invoice balance is only the remaining amount and Revenue is only recognized once.

## Audit Questions Answered

1. **How does the current FinancialService post journals?** Atomically via `DB::transaction`, validates debits == credits, checks fiscal periods, checks tenant scopes.
2. **How does AccountResolver determine accounts?** Reads from BU-specific `FinancialSettings`, falling back to Organization-level settings. 
3. **How are existing invoices posted to GL?** Via `PostInvoiceToGlListener` intercepting `InvoiceIssued`.
4. **How is idempotency implemented?** Using the `ProcessedEvent::process()` wrapper which uses database locks and a processed events table.
5. **How are closed fiscal periods enforced?** `FinancialService->validatePeriodOpen()` throws `FiscalPeriodClosedException`.
6. **How are journal entries balanced?** `FinancialService` asserts `totalDebit == totalCredit` down to 4 decimal places using bcmath.
7. **How are financial settings configured?** Through the `financial_settings` table (Organization / BU scopes).
8. **How can ProductionOrder safely trigger GL posting?** We need to fire a `ProductionCompleted` event from `ProductionService::completeProduction()` and handle it in a listener, wrapped in `ProcessedEvent::process()`.
9. **How can EventBooking safely trigger GL posting?** It already does via `InvoiceIssued`. However, the invoice composition needs adjustment to prevent double-counting.
10. **What accounting accounts are required?** Finished Goods Inventory, Raw Materials Inventory, Customer Deposit Liability. (NONE of these exist in `FinancialSettings`).
11. **Can existing account resolution be reused?** Yes, if the settings schema is updated.
12. **Are database changes actually required?** **YES.** To `financial_settings` (for new accounts) and potentially `items` (for standard cost).
13. **Are new financial settings required?** **YES.**
14. **Are new events required?** **YES.** `ProductionCompleted`.
15. **Are new listeners required?** **YES.** `PostProductionCompletedToGlListener`.
16. **Are existing services sufficient?** Mostly, but `EventBookingService` requires adjustments to the invoice lines it generates.
17. **Are any core files required to change?** `FinancialSettings`, `AccountResolver`, `EventBookingService`.

## HARD STOP
Due to the missing standard costing architecture and the absence of inventory accounts in `FinancialSettings`, I cannot proceed with the implementation without violating the strict instruction: *"DO NOT assume... If the current architecture does not support a defensible production cost calculation, STOP and document the architectural gap rather than inventing financial logic."*

Please advise on how to proceed regarding:
1. Production Costing (Standard Cost on Item?)
2. Database modifications for `FinancialSettings`
3. Event Deposit revenue recognition.
