# Liv Hospital International — Patient Transfer Management Platform
## Master Project Plan

### 1. Project Overview & Objectives
The **Liv Hospital International Patient Transfer Management Platform** is an enterprise-grade medical logistics and passenger transfer orchestration system designed for Liv Hospital. It manages patient transportation across hospital branches, contracted hotels, international airports (e.g., IST, SAW), and custom locations.

Key capabilities include:
- **Dual Fleet Execution Models**: Internal hospital fleet (**Sabit**) and external contracted transfer providers (**Destek**).
- **Independent Round Trips**: Strict decoupling of outbound and return journeys with stable transfer references and separate operational lifecycles.
- **Multilingual Support**: Turkish (staff default), English, and Arabic with comprehensive Right-to-Left (RTL) layout switching.
- **Real-Time Operational Command**: Centralized coordinator dispatch workspace, live telemetry ingestion, and geofence-assisted arrival prompts.
- **Resilient Incident & Replacement Workflows**: In-transit breakdown management, coordinator-approved roadside safety waypoints, passenger handovers, and atomic transfer of execution authority.
- **Event-Driven Multilingual WhatsApp Notifications**: Transactional outbox engine with webhook feedback, language-tailored templates, and zero disclosure of sensitive clinical data.
- **Secure Ephemeral Patient Tracking**: Zero-login tokenized web views with cryptographic token hashing, rate limiting, and strictly scoped location visibility.
- **Mobile Driver Ecosystem**: High-performance Flutter application with background location services, complemented by a mobile-optimized web workflow.

---

### 2. Implementation Methodology & Execution Protocol
Development proceeds strictly under a 24-task phased execution model. Only one task is executed per user `start` authorization. Each task must satisfy all verification checks before moving forward.

```mermaid
flowchart TD
    T01["Task 01: Audit & Planning"] --> T02["Task 02: Domain & State Rules"]
    T02 --> T03["Task 03: Foundation & Dev Env"]
    T03 --> T04["Task 04: Brand & Multilingual Shell"]
    T04 --> T05["Task 05: Migrations, Models, Auditing"]
    T05 --> T06["Task 06: Auth & RBAC"]
    T06 --> T07["Task 07: Master Data Management"]
    T07 --> T08["Task 08: Patients & Contacts"]
    T08 --> T09["Task 09: Transfer Requests"]
    T09 --> T10["Task 10: Internal Sabit Assignment"]
    T10 --> T11["Task 11: External Destek Dispatch"]
    T11 --> T12["Task 12: Trip State Machine & Driver Web"]
    T12 --> T13["Task 13: Incidents & Replacements"]
    T13 --> T14["Task 14: Live Location & Maps"]
    T14 --> T15["Task 15: Flutter Driver App"]
    T15 --> T16["Task 16: Patient Tracking Page"]
    T16 --> T17["Task 17: WhatsApp Engine"]
    T17 --> T18["Task 18: Geofences, Delays & Escalations"]
    T18 --> T19["Task 19: Changes, Cancellations & No-Shows"]
    T19 --> T20["Task 20: Operations Dashboard"]
    T20 --> T21["Task 21: Costs, Reports & Exports"]
    T21 --> T22["Task 22: Settings, Security & Reliability"]
    T22 --> T23["Task 23: Demo Data & End-to-End QA"]
    T23 --> T24["Task 24: Final Documentation & Handover"]
```

---

### 3. Numbered Task Breakdown & Completion Criteria

#### Task 01: Project Audit and Implementation Plan
- **Scope**: Audit workspace, catalog assets (logo, background), verify runtimes (PHP 8.2, Composer, Node.js, Flutter, MySQL), define architecture, create protocol documentation.
- **Dependencies**: Initial workspace.
- **Completion Criteria**: Complete audit report, brand color extraction, project plan, architecture guide, progress log, and integrations registry created without destructive actions.

#### Task 02: Domain Architecture, Database Design, and State Rules
- **Scope**: Comprehensive entity relationship modeling (33+ tables), finite state machine definition, atomic authority rules, incident handling rules, and data retention guidelines.
- **Dependencies**: Task 01.
- **Completion Criteria**: Detailed ERD, unambiguous transition tables, UTC/Europe/Istanbul timezone rules, concurrency handling specifications.

#### Task 03: Application Foundation and Development Environment
- **Scope**: Initialize Laravel 11 application, Sanctum, Tailwind CSS, Livewire, database configuration, mock/live service container bindings, `.env.example`.
- **Dependencies**: Task 02.
- **Completion Criteria**: Clean build, working database connection, front-end pipeline verified, mock services clearly distinct from live APIs.

#### Task 04: Brand Design System and Multilingual Shell
- **Scope**: Implement Liv Hospital visual identity (extracted `#0080BF` primary cyan-blue, `#002869` deep navy), responsive layout shell, top navigation, sidebar, RTL/LTR layout switcher, TR/EN/AR translations.
- **Dependencies**: Task 03.
- **Completion Criteria**: Logo preserved with accurate aspect ratio, background integrated on auth screens, seamless TR/EN/AR switching with full RTL rendering.

#### Task 05: Database Migrations, Models, and Auditing
- **Scope**: Run all migrations, define Eloquent models with relations, custom casts, scopes, concurrency-safe reference generator (`TR-YYYY-XXXXX`), and immutable audit logging.
- **Dependencies**: Task 04.
- **Completion Criteria**: Clean migration execution, relational constraints verified, historical integrity maintained upon entity deactivation.

#### Task 06: Authentication, Roles, and Access Control
- **Scope**: 6 system roles (Admin, Transport Coordinator, Patient Relations, External Dispatcher, Driver, Supervisor/Monitor), policy enforcement, branch/company tenant scoping.
- **Dependencies**: Task 05.
- **Completion Criteria**: Server-side permission guards, cross-company isolation verified, zero data leaks via ID manipulation.

#### Task 07: Master Data Management
- **Scope**: CRUD screens for Hospital Branches, Saved Locations (airports, hotels, clinics with meeting points and arrival radii), Vehicles, Drivers, and External Transport Companies.
- **Dependencies**: Task 06.
- **Completion Criteria**: Input validation, capacity rules, vehicle status guards (maintenance/broken vehicles disqualified from dispatch).

#### Task 08: Patients, Contacts, and Language Preferences
- **Scope**: Patient profiles, authorized companions, E.164 phone validation, country code to language heuristics, communication consents, strict medical privacy safeguards.
- **Dependencies**: Task 07.
- **Completion Criteria**: Consent logs preserved, language preferences independently configurable per contact, zero diagnosis/clinical notes collected.

#### Task 09: Transfer Request Creation and Management
- **Scope**: Transfer booking wizard, flight tracking inputs, accessibility equipment flags (wheelchair, boarding assistance), separate linked return trips, timeline initialization.
- **Dependencies**: Task 08.
- **Completion Criteria**: Idempotent request creation, duplicate warnings, unique reference assignment, medical transport review trigger.

#### Task 10: Internal Sabit Assignment
- **Scope**: Fleet vehicle/driver allocation, capacity and accessibility matching, conflict avoidance with buffer intervals, driver acceptance workflow with response timeouts.
- **Dependencies**: Task 09.
- **Completion Criteria**: Atomic lock against double-booking, rollback upon expiration/rejection, patient notification withheld until confirmed.

#### Task 11: External Destek Dispatch and Company Portal
- **Scope**: Company referral mechanism, service level deadlines, external vendor portal for vehicle/driver assignment, referral retraction/superseding logic.
- **Dependencies**: Task 10.
- **Completion Criteria**: Absolute data isolation between external companies, superseded referral rejection, atomic status update.

#### Task 12: Trip State Machine and Driver Web Workflow
- **Scope**: Driver web interface, step-by-step trip progression (En Route, Arrived at Pickup, Passenger Onboard, Arrived at Destination, Completed, No-Show, Incident).
- **Dependencies**: Task 11.
- **Completion Criteria**: Server-side transition validation, distinct pickup arrival vs destination arrival, tamper-proof state logging.

#### Task 13: Incidents, Vehicle Replacement, and Sabit-to-Destek Transfer
- **Scope**: Breakdown handling, coordinator incident room, roadside passenger handover waypoint, atomic execution authority switch, Sabit-to-Destek fallback.
- **Dependencies**: Task 12.
- **Completion Criteria**: Single execution authority guarantee, patient tracking token unchanged, replacement leg tracked separately.

#### Task 14: Live Location Backend and Map Integration
- **Scope**: High-throughput telemetry ingestion, coordinate validation, sequence verification (drop out-of-order stale GPS packets), WebSocket broadcast, map provider adapter.
- **Dependencies**: Task 13.
- **Completion Criteria**: Stale/offline telemetry detection, private channel broadcasting, graceful fallback when map providers are unavailable.

#### Task 15: Flutter Driver Application
- **Scope**: Cross-platform driver app, secure session token storage, background location service during active trips, offline telemetry spooling, incident dispatch.
- **Dependencies**: Task 14.
- **Completion Criteria**: Clean compilation, background tracking lifecycle verified, offline buffer flush verified, driver web interface maintained as fallback.

#### Task 16: Secure Patient and Companion Tracking Page
- **Scope**: Ephemeral tokenized web interface (`/track/{token}`), SHA-256 hashed lookup, rate limiting, vehicle/driver info, live tracking during trip window, multilingual RTL support.
- **Dependencies**: Task 15.
- **Completion Criteria**: Token revocation/expiry enforced, zero sensitive clinical data exposed, seamless continuity through vehicle replacements.

#### Task 17: Multilingual WhatsApp Notification Engine
- **Scope**: Transactional notification outbox, template engine (TR/EN/AR), event matrix, webhook handler, mock sandbox provider with UI debugger.
- **Dependencies**: Task 16.
- **Completion Criteria**: Verified webhook signature verification, outbox deduplication, retry with exponential backoff, mock mode visibly labeled.

#### Task 18: Arrival Detection, Delays, Reminders, and Escalation
- **Scope**: Haversine/geofence arrival candidate prompts, driver dwell verification, automated delay warnings, unattended referral escalation.
- **Dependencies**: Task 17.
- **Completion Criteria**: Accurate arrival prompting without false airport/perimeter triggers, scheduler idempotency.

#### Task 19: Changes, Cancellation, No-Show, and Early Termination
- **Scope**: Pre-boarding cancellation, post-boarding early termination with safe drop-off logging, no-show waiting counter and coordinator approval.
- **Dependencies**: Task 18.
- **Completion Criteria**: Post-boarding cancellation blocked, audit trail of reasons, automated notification of cancelled resources.

#### Task 20: Operations Dashboard and Dispatch Workspace
- **Scope**: Real-time operations cockpit, active trip kanban/table, filterable dispatch matrix, incident center, vehicle status board.
- **Dependencies**: Task 19.
- **Completion Criteria**: Real-time metrics powered by database queries, preserved filter state, role-scoped data visibility.

#### Task 21: Costs, Reports, and Exports
- **Scope**: Operational KPI reporting (punctuality, waiting times, SLA compliance), multi-currency external cost tracking, formula-injection-safe Excel & PDF exports.
- **Dependencies**: Task 20.
- **Completion Criteria**: Currency-isolated cost sums, sanitized export files, reconciled operational figures.

#### Task 22: Settings, Retention, Security, and Reliability
- **Scope**: Configurable operational parameters, telemetry auto-purging, session security, sensitive log redaction, disaster recovery plan.
- **Dependencies**: Task 21.
- **Completion Criteria**: Zero plain tokens in logs, automated retention routines tested, rate-limiting active on public endpoints.

#### Task 23: Demo Data and End-to-End Quality Assurance
- **Scope**: Comprehensive realistic seeder (branches, airports, hotels, patients, internal/external fleets), simulated trip lifecycle, full automated test suite.
- **Dependencies**: Task 22.
- **Completion Criteria**: End-to-end breakdown and replacement scenario successfully executed and tested with 100% assertions passing.

#### Task 24: Final Documentation and Handover
- **Scope**: Full operational manual, API reference, deployment runbook, WhatsApp template submission guide, integration status sign-off.
- **Dependencies**: Task 23.
- **Completion Criteria**: Production handover package complete, zero mock items presented as live, operational handoff verified.

---

### 4. Risk Assessment & Mitigation Strategies
| Risk | Severity | Mitigation Strategy |
| :--- | :---: | :--- |
| Driver GPS packet loss in tunnels/roaming | High | Client-side SQLite telemetry buffer in Flutter app with timestamp preservation and monotonic sequence checks. |
| Double assignment under high dispatch volume | High | Atomic database transactions using pessimistic row locking (`lockForUpdate`) on vehicle and driver availability slots. |
| Disclosure of sensitive patient health data | Critical | Strict separation of transport logistics and clinical records. WhatsApp templates only contain operational details (names, times, flight codes). |
| Race conditions in vehicle replacement | High | Single active execution authority constraint enforced by database unique conditional indexing and atomic state swap actions. |
| Third-party API rate limits (Maps/WhatsApp) | Medium | Adapter pattern with asynchronous queued outbox, Redis/database rate limiting, and fallbacks. |
