# TANRAIL ONE — PHASE 5.3 PRE-IMPLEMENTATION ARCHITECTURE AUDIT
## EVENT MANAGEMENT & BOOKING ENGINE

**Date:** September 4, 2026  
**Status:** COMPLETE & READY FOR AUTHORIZATION  
**Author:** Lead Software Architect, Senior Laravel Engineer, ERP Domain Architect, Security Architect, and QA Engineer

---

### 1. Executive Summary

This Pre-Implementation Architecture Audit establishes the technical blueprint for **PHASE 5.3 — EVENT MANAGEMENT & BOOKING ENGINE** within TANRAIL ONE. 

The baseline system state following Phase 5.2 completion is **100% verified**:
- **271 / 271 automated tests passing**
- **548 assertions**
- **0 failures, 0 errors, 0 skipped**
- **Laravel Pint clean**
- **Phase 5.1 BOM Foundation & Phase 5.2 Production Engine verified**

Phase 5.3 introduces date-specific event scheduling, package selection, attendee tracking, and deposit/final invoicing integration for commercial operational units (specifically Catering, Restaurant Private Events, Equipment & Venue Rental).

This audit defines the domain models, database schema, state machine lifecycle, Phase 4 commercial engine integration flow, security/tenant isolation rules, concurrency controls, test strategy, and risk mitigations for Phase 5.3.

**IMPORTANT:** No production code, database migrations, or core domain services have been created or modified during this pre-implementation audit phase.

---

### 2. Authoritative Phase 5.3 Scope

Reconciled against the master development roadmap (`docs/12-development-roadmap.md`), Core capability map (`docs/03-core-capability-map.md`), and transaction specification (`docs/08-workflow-and-transaction-specification.md`):

1. **Event Booking Domain Engine:**
   - Manage scheduled, date-and-time-specific commercial engagements.
   - Support venue/location tracking, guest/attendee capacity, and event package configuration.
   - Maintain lifecycle states: `DRAFT` → `QUOTED` → `CONFIRMED` → `IN_PROGRESS` → `COMPLETED` / `CANCELLED`.
2. **Core Commercial Engine Integration:**
   - Link event bookings to Phase 3 `Customer` master records.
   - Integrate with Phase 4 `InvoiceService` to issue deposit invoices upon booking confirmation and final balance invoices upon completion.
   - Integrate with Phase 4 `PaymentAllocationService` for deposit payment tracking.
3. **Multi-Tenant & Security Controls:**
   - Strict `OrganizationScope` and `BusinessUnitScope` enforcement on bookings, packages, and attendees.
   - Fail-closed authorization via `EventBookingPolicy`.
   - Complete record immutability for completed/finalized bookings.
4. **Accounting Boundary:**
   - Pure commercial booking workflow in Phase 5.3. General Ledger double-entry posting for event revenue/unearned revenue is deferred to Phase 5.4.

---

### 3. Existing Capabilities Inventory (REUSE)

| Existing Component | Location in Codebase | Reusability in Phase 5.3 |
|---|---|---|
| **Organization & BusinessUnit** | `app/Domains/Core/Models/` | Multi-tenant ownership and boundary enforcement. |
| **Branch & InventoryLocation** | `app/Domains/Core/Models/` | Venue, branch, and catering kitchen location context. |
| **Customer Catalog** | `app/Domains/Core/Models/Customer.php` | Link event booking to organization customer records. |
| **Item Catalog** | `app/Domains/Core/Models/Item.php` | Reused as catering package items or addon event services. |
| **Commercial Invoicing** | `app/Domains/Core/Services/InvoiceService.php` | Generate deposit and final invoices directly via existing methods. |
| **Payment Allocation** | `app/Domains/Core/Services/PaymentAllocationService.php` | Track deposit payments against event invoices. |
| **Tenant Scopes** | `OrganizationScope`, `BusinessUnitScope` | Automatic multi-tenant filtering on queries. |
| **Context Manager** | `App\Domains\Core\Services\ContextManager` | Resolve active tenant organization and business unit context. |
| **ProcessedEvent** | `App\Domains\Core\Models\ProcessedEvent` | Idempotency locking for confirmation invoice generation. |

---

### 4. Missing Capabilities (TO BE BUILT IN PHASE 5.3)

| Proposed Component | Target Location | Purpose |
|---|---|---|
| `EventBooking` Model | `app/Domains/Modules/EventManagement/Models/EventBooking.php` | Header record for event bookings, schedule, status, and financial totals. |
| `EventBookingPackage` Model | `app/Domains/Modules/EventManagement/Models/EventBookingPackage.php` | Line item detail linking items/packages, quantities, and agreed prices. |
| `EventBookingAttendee` Model | `app/Domains/Modules/EventManagement/Models/EventBookingAttendee.php` | Optional attendee/guest tracking per booking. |
| `EventBookingStatus` Enum | `app/Domains/Modules/EventManagement/Enums/EventBookingStatus.php` | Explicit lifecycle state enum. |
| `EventBookingService` | `app/Domains/Modules/EventManagement/Services/EventBookingService.php` | Core domain service managing booking lifecycle, quotes, and deposit invoicing. |
| `EventBookingPolicy` | `app/Domains/Modules/EventManagement/Policies/EventBookingPolicy.php` | Authorization policy gating booking operations. |
| Migration | `database/migrations/2026_09_05_000003_create_event_bookings_tables.php` | Database schema for event bookings, packages, and attendees. |
| Feature Test Suite | `tests/Feature/Modules/Phase53EventBookingTest.php` | Dedicated feature test suite. |

---

### 5. Proposed Domain Architecture

Namespace: `App\Domains\Modules\EventManagement\`

#### Entity: `EventBooking`
- `id` (bigint, PK)
- `organization_id` (foreign key -> `organizations`)
- `business_unit_id` (foreign key -> `business_units`)
- `branch_id` (foreign key -> `branches`)
- `customer_id` (foreign key -> `customers`)
- `booking_number` (string, unique per BU)
- `event_name` (string)
- `event_type` (string, e.g. 'Catering', 'Banquet', 'Rental')
- `venue_location` (string)
- `start_date_time` (datetime)
- `end_date_time` (datetime)
- `guest_count` (integer)
- `subtotal` (decimal:4)
- `tax_amount` (decimal:4)
- `total_amount` (decimal:4)
- `deposit_required_amount` (decimal:4)
- `deposit_paid_amount` (decimal:4)
- `status` (string, enum: `DRAFT`, `QUOTED`, `CONFIRMED`, `IN_PROGRESS`, `COMPLETED`, `CANCELLED`)
- `deposit_invoice_id` (nullable foreign key -> `invoices`)
- `final_invoice_id` (nullable foreign key -> `invoices`)
- `created_by` (foreign key -> `users`)
- `confirmed_by` (nullable foreign key -> `users`)
- `completed_by` (nullable foreign key -> `users`)
- `timestamps`

#### Entity: `EventBookingPackage` (Line Items)
- `id` (bigint, PK)
- `event_booking_id` (foreign key -> `event_bookings`)
- `item_id` (foreign key -> `items`)
- `unit_id` (foreign key -> `units`)
- `quantity` (decimal:4)
- `unit_price` (decimal:4)
- `subtotal` (decimal:4)
- `tax_category_id` (nullable foreign key -> `tax_categories`)
- `tax_amount` (decimal:4)
- `total` (decimal:4)
- `notes` (text, nullable)
- `timestamps`

#### Entity: `EventBookingAttendee`
- `id` (bigint, PK)
- `event_booking_id` (foreign key -> `event_bookings`)
- `name` (string)
- `email` (string, nullable)
- `phone` (string, nullable)
- `vip_status` (boolean, default false)
- `dietary_requirements` (string, nullable)
- `timestamps`

---

### 6. Database Design & Indexes

- `event_bookings`:
  - `UNIQUE INDEX idx_event_bookings_bu_number (business_unit_id, booking_number)`
  - `INDEX idx_event_bookings_tenant (organization_id, business_unit_id)`
  - `INDEX idx_event_bookings_customer (customer_id)`
  - `INDEX idx_event_bookings_dates (start_date_time, end_date_time)`
  - `INDEX idx_event_bookings_status (status)`
- `event_booking_packages`:
  - `INDEX idx_event_pkg_booking (event_booking_id)`
  - `FOREIGN KEY (event_booking_id) REFERENCES event_bookings(id) ON DELETE CASCADE`
- `event_booking_attendees`:
  - `INDEX idx_event_att_booking (event_booking_id)`
  - `FOREIGN KEY (event_booking_id) REFERENCES event_bookings(id) ON DELETE CASCADE`

---

### 7. Event Booking Lifecycle

```
  DRAFT
    ↓ (send quote)
  QUOTED
    ↓ (confirm & generate deposit invoice)
CONFIRMED
    ↓ (event starts)
IN_PROGRESS
    ↓ (event finishes & generate final invoice)
COMPLETED

(DRAFT / QUOTED / CONFIRMED) ──► CANCELLED
```

**State Machine Rules:**
- `DRAFT` → `QUOTED`, `CONFIRMED`, `CANCELLED`
- `QUOTED` → `CONFIRMED`, `CANCELLED`
- `CONFIRMED` → `IN_PROGRESS`, `CANCELLED`
- `IN_PROGRESS` → `COMPLETED`
- `COMPLETED` → Cannot be cancelled or updated (Immutable).
- `CANCELLED` → Cannot be reopened or updated.

---

### 8. Invoice & Payment Integration

When an `EventBooking` is confirmed:
1. `EventBookingService::confirmBooking(EventBooking $booking, User $user)` runs inside a database transaction.
2. If `$booking->deposit_required_amount > 0`, it calls Phase 4 `InvoiceService::createDraft(...)` creating a Deposit Invoice linked to the booking's `customer_id` and `branch_id`.
3. An invoice line is added via `InvoiceService::addLine(...)` representing "Event Deposit for Booking #{$booking->booking_number}".
4. `InvoiceService::issue(...)` finalizes the deposit invoice.
5. `$booking->deposit_invoice_id` is saved with the deposit invoice reference.

When an `EventBooking` is completed:
1. `EventBookingService::completeBooking(EventBooking $booking, User $user)` checks if a final balance invoice is required.
2. If remaining balance (`total_amount - deposit_paid_amount`) > 0, it calls `InvoiceService::createDraft(...)` for the remaining balance.
3. Packages are attached as invoice lines using `InvoiceService::addLine(...)`.
4. `InvoiceService::issue(...)` finalizes the final invoice.

---

### 9. Deposit Architecture

- Deposits are handled as formal commercial Invoices issued through Phase 4 `InvoiceService`.
- Payments received against deposit invoices use Phase 4 `PaymentAllocationService`.
- No secondary or parallel accounting ledger is introduced. The financial chain remains:
  `EventBooking` → `Invoice` → `Payment` → `PaymentAllocation` → `General Ledger`.

---

### 10. Tenant Isolation

All queries and operations on Event Booking entities enforce tenant boundaries:
- `OrganizationScope` & `BusinessUnitScope` registered globally on `EventBooking`.
- Cross-tenant validation:
  - `$customer->organization_id === $bu->organization_id` (throws `CrossOrganizationException`).
  - Item packages must belong to the same organization as the booking.
  - Branch location must belong to the active Business Unit.
- `EventBookingPolicy` verifies user access using `HasContextualRoles`.

---

### 11. Authorization (Policy Architecture)

Policy class: `App\Domains\Modules\EventManagement\Policies\EventBookingPolicy`
Dual registration in `App\Providers\AppServiceProvider` and `app/Policies/EventBookingPolicy.php`.

Gated Actions:
- `viewAny`: User has active role in target Business Unit.
- `view`: User belongs to booking's Business Unit.
- `create`: User has contextual permission to create bookings.
- `update`: User has permission AND booking is in `DRAFT` or `QUOTED` status.
- `confirm`: User has manager role in Business Unit.
- `complete`: User has manager role in Business Unit.
- `cancel`: User has manager role AND booking is NOT `COMPLETED`.
- `delete`: Denied for all confirmed/completed bookings.

---

### 12. Data Integrity

- Atomic Transactions: All state changes involving invoice generation are wrapped in `DB::transaction(...)`.
- Precision: Financial amounts (`subtotal`, `tax_amount`, `total_amount`, `deposit_required_amount`) use 4-decimal precision (`decimal:4`) with `bcmath`.
- Validation: Guest count must be > 0; start date must be before end date; deposit amount cannot exceed total booking amount.

---

### 13. Concurrency & Idempotency

- Row Locking: `EventBooking::where('id', $id)->lockForUpdate()->first()` used during state transitions.
- Duplicate Confirmation Protection: Attempting to confirm an already confirmed or completed booking throws `InvalidStateTransitionException`.
- Invoice Idempotency: `ProcessedEvent` record prevents duplicate deposit invoice generation if confirmation is retried.

---

### 14. Accounting Boundary

- Phase 5.3 handles the commercial booking workflow and delegates invoice/payment creation to Phase 4 `InvoiceService`.
- Automatic General Ledger posting for Event Revenue / Unearned Deposit Revenue is deferred to **Phase 5.4 (Production & Event GL Financial Integration)**.
- No modifications will be made to `FinancialService` or `AccountResolver` in Phase 5.3.

---

### 15. Migration Impact

- New Migration: `database/migrations/2026_09_05_000003_create_event_bookings_tables.php`
- Tables created: `event_bookings`, `event_booking_packages`, `event_booking_attendees`.
- No modification of existing Phase 1-5.2 migrations.

---

### 16. Test Strategy

New Feature Test Suite: `tests/Feature/Modules/Phase53EventBookingTest.php`

Minimum Test Scenarios:
1. `test_can_create_draft_event_booking`
2. `test_can_add_package_items_to_booking`
3. `test_can_quote_event_booking`
4. `test_confirm_event_booking_generates_deposit_invoice`
5. `test_reject_invalid_event_dates`
6. `test_reject_negative_guest_count`
7. `test_reject_deposit_exceeding_total`
8. `test_complete_event_booking_generates_final_invoice`
9. `test_prevent_duplicate_booking_confirmation`
10. `test_cross_organization_customer_rejection`
11. `test_cross_organization_package_item_rejection`
12. `test_completed_booking_cannot_be_mutated`
13. `test_completed_booking_cannot_be_deleted`
14. `test_can_cancel_uncompleted_booking`
15. `test_policy_authorizes_accessible_user`
16. `test_policy_denies_unauthorized_user`
17. `test_policy_denies_roleless_user`

---

### 17. Regression Strategy

- Run full test suite baseline: `php artisan test --compact`.
- Format code: `vendor/bin/pint --format agent`.
- Verify zero breaking changes to existing 271 unit & feature tests.

---

### 18. Risks & Mitigations

| Risk | Impact | Mitigation Strategy |
|---|---|---|
| **Duplicate Deposit Invoices** | High | Use `DB::transaction()` and row locking on `EventBooking` during confirmation. |
| **Cross-Tenant Customer Association** | Critical | Explicit `CrossOrganizationException` check in `EventBookingService` + `OrganizationScope`. |
| **Package Price Tampering** | Medium | Snapshot package item price into `event_booking_packages` at agreement time. |
| **Completed Booking Deletion** | High | Policy denial and model deleting event hook throwing exception. |

---

### 19. Exact Implementation Sequence (Upon Authorization)

1. **STEP 1:** Create migration `2026_09_05_000003_create_event_bookings_tables.php`.
2. **STEP 2:** Create Enum `EventBookingStatus`.
3. **STEP 3:** Create Models `EventBooking`, `EventBookingPackage`, `EventBookingAttendee`.
4. **STEP 4:** Create Service `EventBookingService`.
5. **STEP 5:** Create Policy `EventBookingPolicy` and register in `AppServiceProvider`.
6. **STEP 6:** Create Feature Test Suite `tests/Feature/Modules/Phase53EventBookingTest.php`.
7. **STEP 7:** Run `php artisan test --compact` and `vendor/bin/pint --format agent`.
8. **STEP 8:** Create Implementation Report `docs/phase-5.3-implementation-report.md` and Verification Gate `docs/phase-5.3-verification-gate.md`.

---

### 20. Final Architecture Gate

============================================================  
TANRAIL ONE — PHASE 5.3  
PRE-IMPLEMENTATION ARCHITECTURE GATE  

STATUS:  
READY FOR AUTHORIZATION  

PRODUCTION CODE:  
NOT MODIFIED  

DATABASE:  
NOT MODIFIED  

ACCOUNTING CORE:  
NOT MODIFIED  

SECURITY MODEL:  
NOT WEAKENED  

WAITING FOR HUMAN AUTHORIZATION  
============================================================
