# Liv Hospital International — Technical Architecture & System Design

### 1. Architectural Principles & Overview
The **Liv Hospital International Patient Transfer Management Platform** is engineered following clean architecture principles, domain-driven design (DDD) patterns, and strict transactional state integrity.

```mermaid
graph TB
    subgraph Client Layer
        WebStaff["Staff Operations Web (Blade + Livewire + Tailwind)"]
        WebExternal["External Company Portal (Livewire)"]
        WebDriver["Driver Mobile Web App"]
        MobileFlutter["Flutter Driver Mobile App (Background GPS)"]
        PublicTracking["Patient Ephemeral Tracking (/track/{token})"]
    end

    subgraph Application & Gateway Layer
        HTTP["Nginx / Web Server"]
        Sanctum["Laravel Sanctum Auth & Token Guards"]
        Policies["Role & Tenant Scoped Policies"]
        Reverb["Laravel Reverb / WebSockets"]
    end

    subgraph Domain & Services Layer
        DispatchService["Dispatch & Assignment Engine"]
        StateMachine["Trip Finite State Machine (FSM)"]
        ReplacementService["Incident & Authority Transfer Engine"]
        NotificationOutbox["Transactional Notification Outbox"]
        TrackingService["Telemetry Ingestion & Filtering Engine"]
    end

    subgraph Integration Adapters
        WhatsAppAdapter["WhatsApp Business Adapter (Meta Cloud API / Sandbox)"]
        MapsAdapter["Map & Routing Adapter (Google Maps / OSRM / OpenLayers)"]
        FlightAdapter["Flight Telemetry / Schedule Adapter"]
    end

    subgraph Persistence & Infrastructure
        MySQL["Relational Database (MySQL 8 / SQLite)"]
        RedisQueue["Queue & Cache Subsystem"]
        AuditLog["Immutable Event & Audit Store"]
    end

    Client Layer --> Application & Gateway Layer
    Application & Gateway Layer --> Domain & Services Layer
    Domain & Services Layer --> Integration Adapters
    Domain & Services Layer --> Persistence & Infrastructure
```

---

### 2. Core Domain Subsystems

#### 2.1 Transport Execution Decoupling (Sabit vs. Destek)
- **Sabit (Hospital Fleet)**:
  - Vehicles and drivers are internal assets owned or contracted directly by Liv Hospital.
  - Assignments require coordinator allocation followed by internal driver acceptance.
- **Destek (External Transport Providers)**:
  - Dispatched via time-bounded referrals to contracted external companies.
  - The external dispatcher assigns company-vetted drivers and vehicles.
  - A referral does **not** grant execution authority until full vehicle and driver details are supplied and confirmed.

#### 2.2 Execution Authority Invariance
At any given instant $t$, for any trip $T$, there exists **at most one active execution authority**:
$$\sum_{a \in \text{Assignments}(T)} \mathbb{I}(\text{status}(a) = \text{AUTHORITY\_GRANTED}) \le 1$$
When an in-transit breakdown occurs and a replacement is assigned (whether Sabit or Destek):
1. The incident is opened and the operational flag is set to `WAITING_FOR_REPLACEMENT`.
2. The primary trip status (e.g. `PASSENGER_ONBOARD`) is strictly preserved.
3. Upon acceptance of the replacement, the transition executes within an atomic database transaction:
   - Former driver's authority is revoked (`REVOKED`).
   - Replacement driver is granted execution authority (`ACTIVE`).
   - Roadside handover point is pinned as an intermediate waypoint.
   - Patient tracking URL remains completely unchanged.

#### 2.3 Trip Lifecycle & State Transitions
Trips evolve through clean, non-reversible primary states complemented by orthogonal operational flags:

```mermaid
stateDiagram-v2
    [*] --> New
    New --> AwaitingAssignment: Submit for dispatch
    AwaitingAssignment --> Confirmed: Driver/Company accepted & verified
    Confirmed --> EnRouteToPickup: Driver begins journey
    EnRouteToPickup --> ArrivedAtPickup: Arrival geofence / manual confirmation
    ArrivedAtPickup --> InProgress: Passenger onboard verified
    InProgress --> ArrivedAtDestination: Destination reached
    ArrivedAtDestination --> Completed: Patient handed over & trip closed
    Completed --> [*]

    %% Exception States
    New --> Cancelled: Cancelled pre-boarding
    AwaitingAssignment --> Cancelled: Cancelled pre-boarding
    Confirmed --> Cancelled: Cancelled pre-boarding
    EnRouteToPickup --> Cancelled: Cancelled pre-boarding
    ArrivedAtPickup --> NoShow: Grace period exceeded & attempts logged
    InProgress --> Terminated: Early medical/emergency termination
    NoShow --> [*]
    Cancelled --> [*]
    Terminated --> [*]
```

#### 2.4 Orthogonal Operational Flags
Independent of the primary status, trips track operational health:
- `DELAYED`: Estimated arrival or pickup exceeds schedule by threshold $> 15$ min.
- `INCIDENT_OPEN`: Active operational or mechanical disruption under coordinator review.
- `WAITING_FOR_REPLACEMENT`: Vehicle immobilized; pending vehicle swap.
- `TRACKING_OFFLINE`: No GPS telemetry received for $> 5$ min during an active leg.

---

### 3. Data Integrity & Security Standards

#### 3.1 Timezone & Financial Handling
- **Database Storage**: All timestamps are persisted in strict **UTC** (`DATETIME` / `TIMESTAMP`).
- **Operational Presentation**: Rendered using configurable timezone, defaulting to **`Europe/Istanbul`** (UTC+3) with explicit offset display.
- **Currency & Costing**: Decimals with 2 decimal precision (`DECIMAL(10, 2)`) coupled with ISO-4217 currency codes (`EUR`, `USD`, `TRY`). Never sum different currencies without recorded conversion rates.

#### 3.2 Ephemeral Patient Tracking Security
- Patient access occurs through an unguessable 64-character hex token:
  $$\text{URL} = \text{https://platform/track/}\{\text{token}\}$$
- The raw token is **never stored** in plain text. The database stores $\text{SHA-256}(\text{token})$.
- Tracking pages enforce strict rate-limiting (e.g., 60 req/min per IP) and expire automatically 6 hours post-completion.
- Zero clinical or diagnostic records are accessible through this token.

#### 3.3 Event-Driven Notification Outbox
WhatsApp notifications use a transactional outbox pattern to prevent message loss or phantom dispatches:
1. Business event occurs inside database transaction.
2. An outbox record is inserted in the same transaction with payload, target recipient, language, and idempotency key.
3. Queue worker pulls from outbox, calls the WhatsApp API adapter, records provider message ID, and handles webhooks (`sent`, `delivered`, `read`, `failed`).
4. Monotonic state progression: A `delivered` status is never downgraded to `sent` by out-of-order webhooks.

---

### 4. Technology Stack Specifications
- **Backend Framework**: Laravel 11 (PHP 8.2+)
- **API & Authentication**: Laravel Sanctum (Stateful session cookies for web, Bearer tokens for mobile app)
- **Frontend Architecture**: Laravel Blade, Livewire 3, Alpine.js, Tailwind CSS
- **Styling & Assets**: Liv Hospital custom color tokens (`#0080BF`, `#002869`), responsive mobile-first grids, full bidirectional RTL support for Arabic
- **Relational Storage**: MySQL / SQLite (with strict foreign keys, transactional isolation, and compound indexes)
- **Real-Time Broadcasting**: Laravel Reverb / WebSockets for live coordinator dispatch updates
- **Mobile Client**: Flutter 3.x with Android/iOS background geolocation service and local SQLite telemetry spooler
- **Integration Layer**: Modular adapters with comprehensive Mock Providers for map rendering and WhatsApp Business API
