# TANRAIL ONE — Phase 3.4 Core Integration Architecture

## 1. Overview
Phase 3.4 establishes the robust, decoupled, and idempotent end-to-end integration between the Core Platform's distinct services: Identity, Inventory, Sales, Procurement, and Finance.

## 2. Decoupled Event-Driven Integration
To prevent tight coupling between distinct business domains, the integration utilizes a synchronous Event/Listener architecture:
- `OrderConfirmed` -> `DeductInventoryListener`
- `OrderCancelled` -> `RestoreInventoryListener`
- `PurchaseReceiptConfirmed` -> `ReceiveInventoryListener`
- `SalesPaymentReceived` -> `RecordSalesPaymentListener`
- `SupplierPaymentRecorded` -> `RecordSupplierPaymentListener`

## 3. The Idempotency Layer
To resolve the critical risk of double-processing in the event listeners, a generalized idempotency constraint mechanism was established.

**`ProcessedEvent`**:
A new `processed_events` table enforces uniqueness via a database-level constraint on `(event_class, reference_id)`. Listeners now wrap their primary logic in `ProcessedEvent::process()`. If an event is dispatched twice, the second dispatch gracefully catches a `UniqueConstraintViolationException` and skips execution, guaranteeing absolute idempotency without requiring domain-specific table logic.

## 4. Transaction Boundaries
Because Laravel's synchronous events are fired within the database transaction of the producer (e.g., `OrderService`), all listener-initiated mutations occur within a nested database transaction (utilizing savepoints).
- If an inventory mutation fails (e.g., negative stock constraint hit), the exception bubbles up, terminating the event and rolling back the parent Order transaction.
- Complete Atomicity is achieved end-to-end.

## 5. Architectural Strictness
The architecture explicitly remains completely agnostic of "Restaurant", "Transport", "Catering", etc. A strict boundary test (`Phase34BoundaryTest`) enforces that no industry-specific code contaminates the `Domains/Core` boundary.
