# TANRAIL ONE — Phase 3.4 Pre-Implementation Review

## 1. Current Architecture Status
The Core Platform consists of interconnected modules: Identity, Inventory, Sales, Procurement, and Finance. These modules are integrated primarily via synchronous Laravel Events (e.g., `OrderConfirmed`, `SalesPaymentReceived`). The core business rules (immutability, cross-BU isolation, mathematical invariants) are solidly enforced via Model Observers and Services.

## 2. Integration Risks
While the services are state-machine protected (e.g., you cannot confirm an already confirmed order), the event listeners themselves are completely naive. If a developer accidentally dispatches an event twice, or if the event is later refactored to be queued and retries due to a timeout, the listener will blindly execute its logic again (deducting stock twice, posting two journals).

## 3. Idempotency Assessment
**Finding**: The current architecture lacks generic idempotency protection at the listener level.
**Proposed Solution**: Introduce a `ProcessedEvent` (or `IdempotentEvent`) table. This table will record the `event_class` and a unique `reference_id` (e.g., Order ID, Payment ID). A database-level unique constraint on `(event_class, reference_id)` will mathematically guarantee that an event is processed exactly once, regardless of retries or duplicate dispatches. Listeners will wrap their execution in a check/insert against this table.

## 4. Transaction Boundary Assessment
**Finding**: Excellent. The system relies heavily on nested database transactions. Because Laravel handles nested transactions via savepoints, an exception thrown deep in a listener (e.g., Inventory issue failure due to negative stock) perfectly bubbles up and rolls back the outer service transaction (e.g., Order confirmation). This ensures true end-to-end atomicity.

## 5. Database Constraint Assessment
**Finding**: The database accurately utilizes foreign keys, `restrictOnDelete`, and appropriate decimal precisions.
**Improvement**: We will rely on the new `processed_events` table for duplicate protection rather than modifying `journals` or `stock_movements`, as one operational event (like Order Cancellation) could theoretically restore multiple items (resulting in multiple stock movements). The generic event log is the cleanest idempotency guard.

## 6. Security Assessment
**Finding**: The `BusinessUnitScope` and `OrganizationScope` successfully isolate data.
**Improvement**: We will write aggressive adversarial integration tests (e.g., BU A1 attempts to receive a Purchase Order belonging to BU A2, or pay a supplier belonging to Org B) to prove these boundaries hold up under end-to-end workflows.

## 7. Required Changes (Phase 3.4 Implementation)
1. **Migrations**: Create `processed_events` table (`id`, `event_class`, `reference_id`, `created_at`).
2. **Models**: Create `ProcessedEvent` model.
3. **Traits/Logic**: Implement an `IdempotentIntegration` trait or directly update the 5 critical listeners (`DeductInventoryListener`, `RestoreInventoryListener`, `ReceiveInventoryListener`, `RecordSalesPaymentListener`, `RecordSupplierPaymentListener`) to check/insert the `ProcessedEvent`.
4. **Testing**: Build `Phase34CoreIntegrationTest.php` with the 16 mandated scenarios.
5. **Architectural Test**: Add a test that scans `app/Domains/Core` for forbidden terminology (e.g., "Restaurant", "Transport") to ensure no scope creep has occurred.

## 8. Optional Changes
- No performance optimizations (like Redis or index restructuring) are currently necessary, as there are no detected N+1 queries or significant performance bottlenecks in the foundational core yet. We will adhere strictly to the "Do NOT prematurely optimize" rule.

## 9. Human Decisions Required
- **Idempotency Approach**: Does the proposed `processed_events` table satisfy the architectural vision for idempotency, or do you prefer unique constraints directly on the integration records (e.g., making `reference_type` + `reference_id` + `event_name` unique on `journals` and `stock_movements`)? *Recommendation: `processed_events` is far more scalable and decoupled.*

## 10. Exact Implementation Sequence
1. Generate `processed_events` migration and model.
2. Refactor the 5 core integration listeners to utilize idempotency checks.
3. Construct `Phase34CoreIntegrationTest.php` and implement Scenarios 01-16.
4. Construct `Phase34BoundaryTest.php` for anti-scope-creep assertions.
5. Execute full regression suite and generate final documentation.
