# FlowRise HMS - Executive Summary

> **Version:** 1.0.0  
> **Last Updated:** 2026-07-17  
> **Status:** Core through Inventory, AI, and Website are complete for operational use; FHIR API and Api (REST auth) remain in progress. See [Module Status](docs/shared/module-status.md) for the canonical matrix.

---

## 1. Project Overview

### 1.1 What is FlowRise HMS?

**FlowRise HMS** (Hospital Management System) is a modular, FHIR-compliant healthcare information system built with Laravel and Filament. It is designed to support healthcare facilities of all sizes, from small clinics to multi-branch hospital networks.

### 1.2 Mission Statement

> *"To empower healthcare providers with a modern, interoperable, and extensible hospital management system that puts patient care first while respecting the realities of resource-constrained healthcare environments."*

### 1.3 Core Values

| Value | Description |
|-------|-------------|
| **Interoperability** | FHIR-compliant data models for seamless integration with national health systems |
| **Accessibility** | Works fully offline and with limited connectivity |
| **Security** | PII encryption at rest, role-based access control |
| **Extensibility** | Modular architecture allows adding functionality without modifying core |
| **Affordability** | Insurance-agnostic design supports cash patients alongside any insurance scheme |

---

## 2. System Vision

### 2.1 Long-Term Vision

FlowRise HMS aims to become the **de facto hospital management system** for healthcare facilities across Africa and beyond, particularly in environments where:

1. **Multi-scheme insurance** needs to be supported (NHIS, private insurance, cash payments)
2. **Limited connectivity** requires offline-first capabilities
3. **National health data exchange** is becoming mandatory (FHIR compliance)
4. **Resource constraints** demand efficient, well-designed software

### 2.2 Five-Year Roadmap

```
Year 1: Foundation + Core Operations
├── Phase 1: Foundation (Organization, Branch, Location, Department)
├── Phase 2: Patient Module (Registration, Identifiers, Demographics)
├── Phase 3: Staff Module (Employee profiles, Specialties, Roles)
└── Phase 11: Interoperability (FHIR R4 API foundation)

Year 2: Clinical Operations
├── Phase 4: Clinical Module (Encounters, Orders, Tasks, Workspace)
├── Phase 5: Pharmacy Module (Medication Catalog, Stock, Dispensing)
└── Phase 6: Appointments Module (Scheduling, Calendar, Waitlist)

Year 3: Diagnostics & Inventory
├── Phase 7: Diagnostics Module (Fulfillment, Reports, Lab/Radiology/Pathology) — Complete
└── Phase 8: Inventory Module (Central stock, procurement, requisitions, transfers) — Complete

Year 4: Billing & Insurance
├── Phase 9: Billing Module (Invoicing, Payments, Service Catalog)
└── Phase 10: Insurance Module (Claims, NHIS integration, Plugins)

Year 5: Advanced Features & Scale
├── Multitenancy Module
├── Telemedicine Integration
├── Advanced Analytics
└── Mobile Applications
```

### 2.3 Design Philosophy

1. **Insurance-Agnostic by Default**: The system works completely without insurance. Insurance schemes are plugins, not core functionality.

2. **FHIR-First**: All data models are designed to map to FHIR resources, enabling easy national health data exchange.

3. **Branch-Centric Security**: Multi-branch organizations have complete data isolation with optional cross-branch read access for super administrators.

4. **Offline-Ready**: Core operations function without internet connectivity; sync mechanisms handle connectivity restoration.

---

## 3. Technical Architecture

### 3.1 Technology Stack

| Layer | Technology |
|-------|------------|
| Backend Framework | Laravel 13 |
| Admin Panel | Filament 5.x |
| Database | MySQL 8+ / SQLite (dev) |
| Authentication | Laravel Sanctum + Breezy + Passkeys |
| Authorization | Spatie Permission + Filament Shield |
| API | RESTful + FHIR R4 |
| Encryption | Laravel Encryption (AES-256) |
| Coding Standards | ICD-11 (primary), ICD-10 (fallback) |

### 3.2 Module Architecture

```
flowrise-hms/
├── Modules/
│   ├── Core/                    # Foundation module
│   │   ├── Models/             # Organization, Branch, Location, Department
│   │   ├── Enums/              # LocationType, ServiceType, etc.
│   │   ├── Classes/            # Services, Helpers
│   │   ├── Filament/           # Admin panel resources
│   │   ├── Http/               # Requests, Controllers
│   │   ├── Policies/           # Authorization policies
│   │   └── database/           # Migrations, Seeders, Factories
│   ├── Patient/                # Patient management module
│   │   ├── Models/             # Patient, PatientIdentifier, EmergencyContact
│   │   ├── Enums/              # Gender, BloodType, IdentifierType
│   │   └── Services/           # PatientService, etc.
│   ├── Staff/                  # Staff management module
│   ├── Clinical/               # Encounters, notes, vitals, orders, tasks
│   ├── Appointment/            # Scheduling, waitlist, calendar integration
│   ├── Pharmacy/               # Medication, stock, dispensing
│   ├── Billing/                # Invoices, payments, gateways, reporting
│   ├── Insurance/              # Policies, claims, reconciliation
│   ├── Diagnostics/            # Fulfillment, templates, reports, files, studies
│   ├── Inventory/              # Central stock, procurement, requisitions, transfers
│   ├── FHIR/                   # FHIR R4 API infrastructure and resource endpoints
│   ├── AI/                     # FlowRise assistant (agents, copilot, Reverb streaming)
│   ├── Website/                # Public CMS and hybrid online booking
│   └── Api/                    # Optional Sanctum token auth + Scribe docs tooling
├── docs/                       # Documentation
└── tests/                      # Test suites
```

### 3.3 Data Flow Architecture

```
┌─────────────────────────────────────────────────────────────────┐
│                        FHIR R4 API Layer                        │
│         (Phase 11 - FHIR Endpoints for National Exchange)        │
└───────────────────────────────┬─────────────────────────────────┘
                                │
┌───────────────────────────────▼─────────────────────────────────┐
│                      Admin Panel (Filament)                      │
│  ┌─────────────┐  ┌─────────────┐  ┌─────────────┐               │
│  │ Organizations│  │  Patients   │  │  Clinical   │  ...          │
│  │  Branches   │  │  Staff      │  │ Diagnostics │               │
│  │  Locations  │  │  Reports    │  │  Billing    │               │
│  │ Departments│  │  Settings   │  │  Pharmacy   │               │
│  └─────────────┘  └─────────────┘  └─────────────┘               │
└───────────────────────────────┬─────────────────────────────────┘
                                │
┌───────────────────────────────▼─────────────────────────────────┐
│                      Service Layer                                │
│  ┌─────────────────────────────────────────────────────────────┐│
│  │ PatientService | BranchService | LocationService | etc.      ││
│  └─────────────────────────────────────────────────────────────┘│
└───────────────────────────────┬─────────────────────────────────┘
                                │
┌───────────────────────────────▼─────────────────────────────────┐
│                      Model Layer                                 │
│  ┌─────────────────────────────────────────────────────────────┐│
│  │ Organization → Branch → Location ↔ Department                ││
│  │                    ↓                                         ││
│  │                    Patient → Encounter → Observation         ││
│  └─────────────────────────────────────────────────────────────┘│
└───────────────────────────────┬─────────────────────────────────┘
                                │
┌───────────────────────────────▼─────────────────────────────────┐
│                      Database (MySQL)                            │
│  ┌─────────────────────────────────────────────────────────────┐│
│  │ UUID Primary Keys | Encrypted PII | JSON Metadata           ││
│  └─────────────────────────────────────────────────────────────┘│
└─────────────────────────────────────────────────────────────────┘
```

---

## 4. Current Module Delivery

### 4.1 Phase 1: Foundation

| Component | Status | Description |
|-----------|--------|-------------|
| Organization | ✅ Complete | Multi-organization support with branding |
| Branch | ✅ Complete | Multi-branch facilities per organization |
| Location | ✅ Complete | Hierarchical locations (facility→building→floor→room→bed) |
| Department | ✅ Complete | Multi-location departments with service types |
| Address/Contact Traits | ✅ Complete | Reusable JSON-based address and contact fields |
| Filament Resources | ✅ Complete | Full CRUD for all foundation entities |
| Form Requests | ✅ Complete | Validation for all create/update operations |
| Services | ✅ Complete | Business logic layer for all entities |
| Tests | ✅ Complete | Project-wide automated unit and feature suites are in active use across the current module set |

### 4.2 Phase 2: Patient Module

| Component | Status | Description |
|-----------|--------|-------------|
| Patient Registration | ✅ Complete | UUID-based patient records |
| Patient Demographics | ✅ Complete | Full demographic data with encryption |
| Patient Identifiers | ✅ Complete | MRN auto-generation, multiple identifier types |
| Emergency Contacts | ✅ Complete | Next-of-kin with relationship types |
| PII Encryption | ✅ Complete | Phone, email, national ID encrypted at rest |
| Patient Schools | ✅ Complete | Education information (for pediatric care) |
| Patient Documents | ✅ Complete | Document attachments |
| Services | ✅ Complete | PatientService, PatientIdentifierService |
| Filament Resources | ✅ Complete | Full CRUD for patient management |

### 4.3 Phase 3: Staff Module

| Component | Status | Description |
|-----------|--------|-------------|
| Staff Profiles | ✅ Complete | Employee/provider records with status and role metadata |
| Department Assignments | ✅ Complete | Many-to-many assignment with primary department support |
| Credentials | ✅ Complete | License/certification tracking and verification workflow |
| Specialties | ✅ Complete | Specialty tagging and management |
| Staff Resource | ✅ Complete | Full Filament CRUD, search, and filtering |

### 4.4 Phase 4: Clinical Module

| Component | Status | Description |
|-----------|--------|-------------|
| Encounters | ✅ Complete | Inpatient/outpatient/emergency/virtual encounters |
| Allergies | ✅ Complete | Structured allergy and adverse reaction tracking |
| Vital Signs | ✅ Complete | Structured vital sign recording |
| Clinical Notes | ✅ Complete | Clinical note capture and history |
| Service Requests | ✅ Complete | Order capture with request items |
| Tasks | ✅ Complete | Workflow fulfillment tracking |
| Medication Administration (MAR) | ✅ Complete | Board, service, dose reminders, pending-fulfillment widget, relation manager, flow tests |
| ADT Location Events | ✅ Complete | Encounter location event tracking for admit/transfer/discharge bed flows |
| Workspace Views | ✅ Complete | Patient profile, timeline, notes, orders, and vitals workspace pages |
| Test Coverage Expansion | ⏳ Pending | Functional scope is built; dedicated module tests (19 files) can still be expanded |

### 4.5 Phase 5: Pharmacy Module (Lean)

| Component | Status | Description |
|-----------|--------|-------------|
| Medication Catalog | ✅ Complete | Medication and drug master data management |
| Stock Items | ✅ Complete | Stock records and inventory-on-hand tracking |
| Dispensing | ✅ Complete | Dispense records tied to clinical request items |
| Medication Ordering | ✅ Complete | Clinical-to-pharmacy ordering flow via existing request items |
| Pharmacy UI | ✅ Complete | Filament cluster, resources, POS page, and queue widget |

### 4.6 Phase 6: Appointment Module

| Component | Status | Description |
|-----------|--------|-------------|
| Scheduling | ✅ Complete | Appointment CRUD and lifecycle status tracking |
| Calendar | ✅ Complete | Calendar page and widget integration |
| Waitlist | ✅ Complete | Waitlist entry resources and prioritization support |
| Sync Outbox | ✅ Complete | Outbound appointment event queue for integrations |
| Factory Coverage | ✅ Complete | Model factories exist across appointment domain models |

### 4.7 Phase 7: Diagnostics Module

| Component | Status | Description |
|-----------|--------|-------------|
| Clinical Bridge | ✅ Complete | Request-item creation/cancellation flows create and update diagnostics fulfillments |
| Core Schema | ✅ Complete | Profiles, fulfillments, specimens, observations, reports, report signatures, files, studies, and media tables exist |
| Filament Resources | ✅ Complete | Fulfillment, service profile, and result template resources are available |
| Permissions and Seeders | ✅ Complete | Shield/resource permissions, workflow permissions, and starter diagnostic catalog are present |
| Workflow Depth | ✅ Complete | Structured observation entry, panels on service profiles, discipline workflows, lab result printing, and relation managers are built; HL7/FHIR export deferred |

### 4.8 Phase 9: Billing Module

| Component | Status | Description |
|-----------|--------|-------------|
| Invoices | ✅ Complete | Invoice creation, issue, totals, and line management |
| Payments | ✅ Complete | Payment recording, allocations, intents, and status handling |
| Gateways | ✅ Complete | Paystack, Stripe, Flutterwave, and Hubtel driver support |
| Outputs | ✅ Complete | Receipts, invoice PDFs, revenue CSV/reporting, and webhooks |
| Factory Coverage | ✅ Complete | Model factories exist across billing domain models |
| Filament UI | ✅ Complete | Invoice, payment, gateway, billing desk, revenue report, payment plans, deposits, refunds, and webhook surfaces are built |

### 4.9 Phase 10: Insurance Module

| Component | Status | Description |
|-----------|--------|-------------|
| Patient Policies | ✅ Complete | Patient-to-policy and payer relationship models are present |
| Claims Workflow | ✅ Complete | Claim generation, submission, and feedback persistence are implemented |
| Connectors | ✅ Complete | NHIS XML connector path and generic private-insurer extension point exist |
| Reconciliation | ✅ Complete | Claim feedback and reconciliation services are implemented |
| Admin UI | ✅ Complete | Payer admin, claim batches, generate-claims page, NHIS settings, and patient insurance schema on patient forms are built; dedicated PatientPolicy/TariffItem resources remain deferred |
| Connector Expansion | ⏳ Deferred | NHIS catalog sync placeholder, private insurer connector stub, Phase 2 feedback XML import |

### 4.10 Phase 8: Inventory Module

| Component | Status | Description |
|-----------|--------|-------------|
| Schema & Models | ✅ Complete | 14 migrations (including lot tracking), 13 models including `DocumentSequence`, document numbering |
| Stock Ledger | ✅ Complete | `StockLedgerService` with lot balances and FEFO decrement, transaction audit trail |
| Procurement | ✅ Complete | Purchase orders, partial receipt, GRN PDF, auto-reorder draft PO |
| Requisitions & Transfers | ✅ Complete | Approve/decline/issue/close in Filament; partial receive on PO and transfers |
| Pharmacy Bridge | ✅ Complete | `IssueToPharmacyService` via Core `StockProviderContract` → Pharmacy `StockService` |
| Filament UI | ✅ Complete | 7 resources, analytics report (8 widgets), CSV export, `MyWardRequestsWidget`, adjustment UI, PDF routes, feature toggles enforced |
| Reorder Alerts | ✅ Complete | `inventory:check-stock-alerts` command, daily/weekly/monthly scheduler via `NotificationSettings`, `InventoryReorderAlertNotification` |
| Tests | ✅ Complete | 21 test files covering ledger, PO, requisition, issue/close, adjustment, pharmacy bridge, toggles, lot/FEFO, PDFs, report, widget, stock alerts |
| Deferred interoperability | ⏳ Deferred | FHIR SupplyDelivery (Phase 11) |

### 4.11 Phase 11: FHIR Module

| Component | Status | Description |
|-----------|--------|-------------|
| API Infrastructure | ✅ Complete | Validator, search, pagination, metadata/capability statement |
| Patient API | ✅ Complete | CRUD + search via Patient module transformer |
| Practitioner API | ✅ Complete | Practitioner and PractitionerRole CRUD + search via Staff transformers |
| Core Clinical Read API | ✅ Complete | Organization, Location, HealthcareService, Encounter, Condition, AllergyIntolerance read/search |
| Diagnostics Read API | ✅ Complete | Observation read/search via Diagnostics transformer |
| Appointment Read API | ✅ Complete | Appointment and AppointmentResponse read/search |
| Inventory Read API | ✅ Complete | InventoryItem read/search |
| Additional Resources | ⏳ Planned | DiagnosticReport, Claim, Coverage, ServiceRequest, Medication*, Schedule/Slot |
| SMART / Bulk Export | ⏳ Planned | SMART on FHIR and `$export` not yet implemented |

---

## 5. Hospital Flow Board

### 5.1 Core Entity Hierarchy

```mermaid
graph TB
    subgraph "Organization Level"
        ORG["🏢 Organization"]
    end

    subgraph "Branch Level"
        BRANCH1["🏥 Branch: Main Hospital"]
        BRANCH2["🏥 Branch: Downtown Clinic"]
        BRANCH3["🏥 Branch: Community Health"]
    end

    subgraph "Location Hierarchy"
        LOC1_1["📍 Facility<br/>Main Hospital Building"]
        LOC1_2["📍 Facility<br/>Emergency Center"]
        
        LOC2_1["🏢 Building A<br/>Clinical Services"]
        LOC2_2["🏢 Building B<br/>Diagnostics"]
        LOC2_3["🏢 Building C<br/>Administrative"]
        
        LOC3_1["🛏️ Floor 1 - ICU"]
        LOC3_2["🛏️ Floor 2 - Wards"]
        LOC3_3["🚪 Floor G - Outpatient"]
        
        LOC4_1["🚪 Room 101 - ER"]
        LOC4_2["🚪 Room 102 - Triage"]
        LOC4_3["🚪 ICU-1 - ICU Bed 1"]
        LOC4_4["🚪 ICU-2 - ICU Bed 2"]
    end

    subgraph "Department Structure"
        DEPT1["💊 Emergency Medicine"]
        DEPT2["🏥 Cardiology"]
        DEPT3["🩺 Radiology"]
        DEPT4["💉 Laboratory"]
        DEPT5["💊 Pharmacy"]
        DEPT6["📋 Administration"]
    end

    subgraph "Staff Roles"
        STAFF1["👨‍⚕️ Physicians"]
        STAFF2["👩‍⚕️ Nurses"]
        STAFF3["🔬 Lab Technicians"]
        STAFF4["💼 Administrative"]
    end

    subgraph "Patient Journey"
        PATIENT["👤 Patient"]
        VISIT["📋 Visit/Encounter"]
        ORDER["📝 Orders"]
        RESULT["📊 Results"]
        BILL["💰 Bill"]
    end

    ORG --> BRANCH1
    ORG --> BRANCH2
    ORG --> BRANCH3

    BRANCH1 --> LOC1_1
    BRANCH1 --> LOC1_2
    BRANCH2 --> LOC1_1
    BRANCH3 --> LOC1_1

    LOC1_1 --> LOC2_1
    LOC1_1 --> LOC2_2
    LOC1_1 --> LOC2_3
    LOC1_2 --> LOC2_1

    LOC2_1 --> LOC3_1
    LOC2_1 --> LOC3_2
    LOC2_1 --> LOC3_3

    LOC3_1 --> LOC4_1
    LOC3_1 --> LOC4_2
    LOC3_1 --> LOC4_3
    LOC3_1 --> LOC4_4

    LOC4_1 --> DEPT1
    LOC4_3 --> DEPT1
    LOC2_1 --> DEPT2
    LOC2_2 --> DEPT3
    LOC2_2 --> DEPT4
    LOC2_3 --> DEPT5
    LOC2_3 --> DEPT6

    DEPT1 --> STAFF1
    DEPT2 --> STAFF1
    DEPT3 --> STAFF3
    DEPT4 --> STAFF3
    DEPT5 --> STAFF4
    DEPT6 --> STAFF4

    PATIENT --> VISIT
    VISIT --> LOC4_1
    VISIT --> DEPT1
    VISIT --> STAFF1
    VISIT --> ORDER
    ORDER --> DEPT4
    ORDER --> DEPT3
    ORDER --> DEPT5
    DEPT4 --> RESULT
    DEPT3 --> RESULT
    VISIT --> BILL
```

### 5.2 Patient Registration Flow

```mermaid
flowchart TD
    START(["Patient Arrives"]) --> REGISTRATION
    
    subgraph REGISTRATION ["Registration Desk"]
        A1["Verify/Collect Demographics"] --> A2["Assign MRN"]
        A2 --> A3["Create Patient Record"]
        A3 --> A4["Register Identifier<br/>(NHIS, National ID, etc.)"]
        A4 --> A5["Add Emergency Contact"]
    end
    
    A5 --> TRIAGE
    
    subgraph TRIAGE ["Triage Area"]
        B1["Vital Signs Recorded"] --> B2["Triage Category Assigned"]
        B2 --> B3["Location Assigned"]
    end
    
    B3 --> CLINICAL
    
    subgraph CLINICAL ["Clinical Encounter"]
        C1["Physician Assessment"] --> C2["Diagnosis (ICD-11)"]
        C2 --> C3["Orders Placed"]
        C3 --> C4["Medications?"]
        C3 --> C5["Lab Tests?"]
        C3 --> C6["Imaging?"]
    end
    
    C4 -->|Yes| PHARMACY
    C5 --> LAB
    C6 --> RADIOLOGY
    
    PHARMACY["Pharmacy<br/>Dispensing"] --> BILLING
    LAB["Laboratory<br/>Testing"] --> BILLING
    RADIOLOGY["Radiology<br/>Imaging"] --> BILLING
    
    BILLING["Billing/Claims"] --> DISCHARGE
    
    DISCHARGE["Patient Discharge"] --> FOLLOWUP
    
    FOLLOWUP["Follow-up Scheduled?"] -->|Yes| APPOINTMENT
    FOLLOWUP -->|No| END
    
    APPOINTMENT["Schedule Follow-up"] --> END
    
    style START fill:#90EE90
    style END fill:#FFB6C1
    style REGISTRATION fill:#E6F3FF
    style TRIAGE fill:#FFF0E6
    style CLINICAL fill:#E6FFE6
    style BILLING fill:#FFE6E6
```

### 5.3 Location Hierarchy Flow

```mermaid
flowchart TD
    ROOT["🌍 ORGANIZATION<br/>Habana Healthcare Group"] --> FACILITY1
    
    subgraph FACILITY1 ["FACILITY: Main Hospital"]
        direction TB
        BLDG_A["🏢 Building A<br/>Clinical Services"] 
        BLDG_B["🏢 Building B<br/>Diagnostics"]
        BLDG_C["🏢 Building C<br/>Pharmacy & Admin"]
        
        FACILITY1 --- BLDG_A
        FACILITY1 --- BLDG_B
        FACILITY1 --- BLDG_C
    end
    
    BLDG_A --> FLOOR_G
    BLDG_A --> FLOOR_1
    BLDG_A --> FLOOR_2
    BLDG_B --> FLOOR_G
    BLDG_B --> FLOOR_1
    BLDG_C --> FLOOR_G
    
    FLOOR_G["🛖 Ground Floor<br/>Emergency, Reception, Outpatient"] --> ROOM_ER
    FLOOR_G --> ROOM_RECEP
    FLOOR_G --> ROOM_C1
    FLOOR_G --> ROOM_C2
    
    FLOOR_1["🛏️ First Floor<br/>ICU, Surgery, Pharmacy"] --> ROOM_ICU1
    FLOOR_1 --> ROOM_ICU2
    FLOOR_1 --> ROOM_SURG1
    FLOOR_1 --> ROOM_PHARM
    
    FLOOR_2["🛏️ Second Floor<br/>Wards"] --> ROOM_WARD1
    FLOOR_2 --> ROOM_WARD2
    
    ROOM_ER["🚪 Emergency Room"] 
    ROOM_RECEP["🚪 Reception"]
    ROOM_C1["🚪 Consultation 1"]
    ROOM_C2["🚪 Consultation 2"]
    ROOM_ICU1["🛏️ ICU Bed 1"]
    ROOM_ICU2["🛏️ ICU Bed 2"]
    ROOM_SURG1["🔪 Surgery 1"]
    ROOM_PHARM["💊 Pharmacy"]
    ROOM_WARD1["🛏️ Ward 2A"]
    ROOM_WARD2["🛏️ Ward 2B"]
    
    ROOM_ER --> DEPT_ER
    ROOM_ICU1 --> DEPT_ICU
    ROOM_C1 --> DEPT_CARD
    ROOM_C2 --> DEPT_PED
    ROOM_SURG1 --> DEPT_SURG
    ROOM_PHARM --> DEPT_PHARM
    
    DEPT_ER["💊 Emergency Medicine"]
    DEPT_ICU["💊 Intensive Care Unit"]
    DEPT_CARD["💊 Cardiology"]
    DEPT_PED["💊 Pediatrics"]
    DEPT_SURG["💊 Surgery"]
    DEPT_PHARM["💊 Pharmacy"]
    
    DEPT_ER --- DEPT1{{"Clinical"}}
    DEPT_ICU --- DEPT1
    DEPT_CARD --- DEPT1
    DEPT_PED --- DEPT1
    DEPT_SURG --- DEPT1
    DEPT_PHARM --- DEPT3{{"Support"}}
    
    DEPT1["SERVICE TYPE: Clinical"]
    DEPT2["SERVICE TYPE: Diagnostic"]
    DEPT3["SERVICE TYPE: Support"]
    DEPT4["SERVICE TYPE: Administrative"]
    
    style ROOT fill:#4169E1,color:#fff
    style FACILITY1 fill:#87CEEB
    style DEPT1 fill:#90EE90
    style DEPT2 fill:#FFD700
    style DEPT3 fill:#D3D3D3
    style DEPT4 fill:#FFA500
```

### 5.4 Department-Location Relationship Flow

```mermaid
erDiagram
    ORGANIZATION ||--o{ BRANCH : has
    BRANCH ||--o{ LOCATION : contains
    LOCATION ||--o{ LOCATION : parent_child
    LOCATION }o--o{ DEPARTMENT : operates_at
    DEPARTMENT ||--|{ PATIENT : serves
    PATIENT ||--o{ ENCOUNTER : has
    ENCOUNTER ||--o{ ORDER : generates
    ORDER ||--o{ RESULT : produces
    
    ORGANIZATION {
        uuid id PK
        string name
        string slug
        string tax_id
        boolean is_active
    }
    
    BRANCH {
        uuid id PK
        uuid organization_id FK
        string name
        string code
        json address
        json contact
        boolean is_default
        boolean is_active
        string timezone
    }
    
    LOCATION {
        uuid id PK
        uuid branch_id FK
        uuid parent_id FK
        enum type "facility|building|floor|room|bed"
        string name
        string code
        string description
        boolean is_active
        json address
        json contact
    }
    
    DEPARTMENT {
        uuid id PK
        string name
        string slug
        string code
        enum service_type "clinical|diagnostic|administrative|support"
        boolean is_active
        json contact
    }
    
    DEPARTMENT_LOCATION {
        uuid department_id FK
        uuid location_id FK
        boolean is_primary
    }
    
    PATIENT {
        uuid id PK
        uuid global_uuid
        uuid user_id FK
        uuid branch_id FK
        string mrn
        enum title
        string first_name
        string last_name
        date date_of_birth
        enum gender
        enum blood_type
        json address
        json contact
        boolean is_active
        boolean is_deceased
    }
    
    ENCOUNTER {
        uuid id PK
        uuid patient_id FK
        uuid location_id FK
        uuid practitioner_id FK
        enum type "inpatient|outpatient|emergency"
        datetime start_time
        datetime end_time
        enum status
    }
    
    ORDER {
        uuid id PK
        uuid encounter_id FK
        uuid patient_id FK
        enum type "lab|imaging|medication|procedure"
        json items
        enum status
    }
    
    RESULT {
        uuid id PK
        uuid order_id FK
        json data
        datetime result_time
        string notes
    }
```

---

## 6. Security Architecture

### 6.1 Access Control Matrix

| Role | Organization | Branch | Location | Department | Patient | Clinical | Billing |
|------|-------------|--------|----------|------------|---------|----------|---------|
| Super Admin | Full | Full | Full | Full | Full | Full | Full |
| Org Admin | Full | Full | Full | Full | Full | View | Full |
| Branch Manager | View | Full | Full | Full | Full | View | Full |
| Department Head | View | View | View | Full | Full | Full | View |
| Physician | View | View | View | View | Full | Full | View |
| Nurse | View | View | View | View | Full | View | No |
| Lab Tech | View | View | View | View | View | View | No |
| Admin Staff | View | View | View | View | View | No | Full |
| Receptionist | View | View | View | View | Full | No | View |

### 6.2 Data Encryption

| Field Type | Encryption | At Rest |
|------------|------------|---------|
| Patient Phone | AES-256 | ✅ |
| Patient Email | AES-256 | ✅ |
| National ID | AES-256 | ✅ |
| Emergency Contact Info | AES-256 | ✅ |
| Medical Records | AES-256 | ✅ |
| Patient Identifiers | AES-256 | ✅ |
| Billing Information | AES-256 | ✅ |

---

## 7. FHIR Compliance

### 7.1 Resource Mapping

| FlowRise Entity | FHIR Resource | Status |
|-----------------|---------------|--------|
| Organization | [Organization](https://www.hl7.org/fhir/organization.html) | ✅ Mapped |
| Branch | [Organization](https://www.hl7.org/fhir/organization.html) | ✅ Mapped |
| Location | [Location](https://www.hl7.org/fhir/location.html) | ✅ Mapped |
| Department | [HealthcareService](https://www.hl7.org/fhir/healthcareservice.html) | ✅ Mapped |
| Patient | [Patient](https://www.hl7.org/fhir/patient.html) | ✅ API available (FHIR module) |
| Practitioner (Staff) | [Practitioner](https://www.hl7.org/fhir/practitioner.html) | ✅ API available (FHIR module) |
| PractitionerRole (Staff) | [PractitionerRole](https://www.hl7.org/fhir/practitionerrole.html) | ✅ API available (FHIR module) |
| Encounter | [Encounter](https://www.hl7.org/fhir/encounter.html) | ✅ Read/search API (FHIR module) |
| Condition | [Condition](https://www.hl7.org/fhir/condition.html) | ✅ Read/search API (FHIR module) |
| AllergyIntolerance | [AllergyIntolerance](https://www.hl7.org/fhir/allergyintolerance.html) | ✅ Read/search API (FHIR module) |
| Observation | [Observation](https://www.hl7.org/fhir/observation.html) | ✅ Read/search API (FHIR module) |
| Appointment | [Appointment](https://www.hl7.org/fhir/appointment.html) | ✅ Read/search API (FHIR module) |
| MedicationRequest | [MedicationRequest](https://www.hl7.org/fhir/medicationrequest.html) | 🔄 Planned |
| DiagnosticReport | [DiagnosticReport](https://www.hl7.org/fhir/diagnosticreport.html) | 🔄 Planned (export deferred) |
| Coverage | [Coverage](https://www.hl7.org/fhir/coverage.html) | 🔄 Planned |
| Organization / Location / HealthcareService | Core entities | ✅ Read/search API (FHIR module) |
| InventoryItem | [InventoryItem](https://www.hl7.org/fhir/inventoryitem.html) | ✅ Read/search API (FHIR module) |

### 7.2 FHIR API Endpoints (In Progress)

Authenticated via Sanctum (`/api/v1/fhir/...`):

```
GET    /api/v1/fhir/metadata
GET    /api/v1/fhir/Patient
POST   /api/v1/fhir/Patient
GET    /api/v1/fhir/Patient/{id}
PUT    /api/v1/fhir/Patient/{id}
DELETE /api/v1/fhir/Patient/{id}
GET    /api/v1/fhir/Practitioner
GET    /api/v1/fhir/Practitioner/{id}
GET    /api/v1/fhir/PractitionerRole
GET    /api/v1/fhir/PractitionerRole/{id}
GET    /api/v1/fhir/Organization
GET    /api/v1/fhir/Location
GET    /api/v1/fhir/HealthcareService
GET    /api/v1/fhir/Encounter
GET    /api/v1/fhir/Condition
GET    /api/v1/fhir/AllergyIntolerance
GET    /api/v1/fhir/Observation
GET    /api/v1/fhir/Appointment
GET    /api/v1/fhir/AppointmentResponse
GET    /api/v1/fhir/InventoryItem
... Claim, Coverage, DiagnosticReport, ServiceRequest, Schedule/Slot planned
```

---

## 8. Testing & Quality Assurance

### 8.1 Test Coverage

Current coverage is distributed across the root application and multiple modules rather than the earlier core-only split.

Operationally, the codebase now has:

- **1,350+** automated tests across root and module test suites (~217 test files)
- broad Core coverage for shared services, traits, helpers, and foundational models
- targeted Patient, Staff, Clinical, Appointment, Billing, Insurance, Diagnostics, Inventory, FHIR, AI, Website, and Api coverage
- a remaining need to deepen dedicated Clinical module tests (22 files today) and expand Api domain REST endpoints beyond auth

### 8.2 Code Quality Gates

- **Pint**: Code style enforcement ( Laravel Pint)
- **PHPStan**: Static analysis (Level 0+)
- **Pest**: Unit and feature testing
- **Coverage**: Minimum 80% for new code

---

## 9. Deployment Architecture

### 9.1 Recommended Infrastructure

```
┌─────────────────────────────────────────────────────────────┐
│                     Load Balancer                           │
│                    (SSL Termination)                         │
└───────────────────────────┬─────────────────────────────────┘
                            │
┌───────────────────────────▼─────────────────────────────────┐
│                    Application Servers                       │
│              ┌─────────┐  ┌─────────┐  ┌─────────┐         │
│              │  App 1  │  │  App 2  │  │  App 3  │         │
│              └─────────┘  └─────────┘  └─────────┘         │
└───────────────────────────┬─────────────────────────────────┘
                            │
┌───────────────────────────▼─────────────────────────────────┐
│                        Cache Layer                           │
│                    (Redis Cluster)                           │
└───────────────────────────┬─────────────────────────────────┘
                            │
┌───────────────────────────▼─────────────────────────────────┐
│                      Database                                │
│                   (MySQL Primary +                           │
│                    Replica Setup)                            │
└─────────────────────────────────────────────────────────────┘
```

### 9.2 Branch Isolation Strategy

```
Production Database
├── Organization: Habana Healthcare Group
│   ├── Branch: Main Hospital (Tamale)
│   │   ├── Locations: [facility, buildings, floors, rooms]
│   │   ├── Departments: [Emergency, Cardiology, Lab, etc.]
│   │   └── Patients: [registered patients]
│   ├── Branch: Downtown Clinic
│   │   └── ...
│   └── Branch: Community Health
│       └── ...
│
├── Organization: Volta Medical Services
│   └── ...
│
└── Super Admin View (cross-organization, read-only)
```

---

## 10. Glossary

| Term | Definition |
|------|------------|
| **MRN** | Medical Record Number - Unique patient identifier |
| **FHIR** | Fast Healthcare Interoperability Resources - HL7 standard for healthcare data exchange |
| **ICD-11** | International Classification of Diseases, 11th Revision |
| **NHIS** | National Health Insurance Scheme (Ghana) |
| **UUID** | Universally Unique Identifier - 128-bit identifier |
| **PII** | Personally Identifiable Information |
| **FHIR R4** | FHIR Release 4 - Current major FHIR version |
| **LOINC** | Logical Observation Identifiers Names and Codes |
| **SMART** | Substitutable Medical Applications, Reusable Technologies - OAuth2 framework for healthcare apps |

---

## 11. Document History

| Version | Date | Author | Changes |
|---------|------|--------|---------|
| 1.0.0 | 2026-03-28 | AI Assistant | Initial comprehensive documentation |

---

*This document is maintained by the FlowRise HMS development team. For questions or updates, please refer to the project repository.*
