# Sifa Medical Management System — Full Module Specifications

> Companion reference for `SIFA-MEDICAL-PLAN.md`. Source: original requirements dump, reorganized. All entity/field/feature definitions are preserved verbatim inside the code blocks.

## Table of Contents

1. [Project Brief](#project-brief)
2. [Business Types & Module Presets](#business-types--module-presets)
3. [System Setup Wizard (UI Flow)](#system-setup-wizard-ui-flow)
4. [Permissions Model (RBAC / ABAC / Data Scopes)](#permissions-model-rbac--abac--data-scopes)
5. [Module: organization](#module-organization)
6. [Module: module_registry](#module-moduleregistry)
7. [Module: notifications](#module-notifications)
8. [Module: documents](#module-documents)
9. [Module: medical_core](#module-medicalcore)
10. [Module: dental](#module-dental)
11. [Module: derma (Dermatology)](#module-derma-dermatology)
12. [Module: ophthalmology](#module-ophthalmology)
13. [Module: inpatient](#module-inpatient)
14. [Module: bed_management](#module-bedmanagement)
15. [Module: emergency](#module-emergency)
16. [Module: surgery](#module-surgery)
17. [Module: laboratory](#module-laboratory)
18. [Module: blood_bank](#module-bloodbank)
19. [Module: radiology](#module-radiology)
20. [Module: pharmacy](#module-pharmacy)
21. [Module: icu](#module-icu)
22. [Module: billing](#module-billing)
23. [Module: inventory](#module-inventory)
24. [Module: hr_payroll](#module-hrpayroll)
25. [Module: accounting](#module-accounting)
26. [Module: patient_portal](#module-patientportal)

---

## Project Brief

I need to enhance sifa project to cover following (note: we already have erp system with basics (inventory, contacts 'sutomer and supplier', hr, and include the md task to check current script functions and feature and use it and build missed only):
I need to have full medical management system, it must be fixable and scalable to manage different scale and types of medical providers like (hospital with in/out patients - clinics (one specific or multiable clinic "bioclinic" - medical centers - laboratories, center of examinations like x-ray, ultrasound , ct , mri , imaging center , .... etc) , pharmacies - ...etc)
all of previous points can be found in one place or different place so select the business type and enable the modules which fit the requirements so if medical center has dental , derma clinic so I will enable the medical core module and modules of dental and derma 

## Business Types & Module Presets

```yaml
** expected_modules:
      - medical_core
      - scheduling
      - inpatient
      - outpatient
      - emergency
      - surgery
      - pharmacy
      - laboratory
      - radiology
      - bed_management
      - billing
      - inventory
      - hr_payroll
      - accounting
      - ambulance
      - icu
      - blood_bank
      - nicu
      - dialysis
      - physiotherapy
      - mortuary
      - all_specialty_modules

  polyclinic:
    label: "Polyclinic / Medical Center"
    description: "Multi-specialty outpatient facility"
    default_modules:
      - medical_core
      - scheduling
      - outpatient
      - pharmacy
      - laboratory
      - billing
      - inventory
    optional_modules:
      - radiology
      - all_specialty_modules

  single_clinic:
    label: "Single Specialty Clinic"
    description: "One-specialty outpatient clinic (e.g., dental, derma, ophthalmology)"
    default_modules:
      - medical_core
      - scheduling
      - outpatient
      - billing
    optional_modules:
      - pharmacy
      - one_specialty_module_of_choice

  bioclinic:
    label: "BioClinic (Multi-Clinic Brand)"
    description: "Multiple clinics under one brand, possibly different specialties per location"
    default_modules:
      - medical_core
      - scheduling
      - outpatient
      - billing
      - inventory
    optional_modules:
      - pharmacy
      - laboratory
      - all_specialty_modules
    note: "Each facility (branch) enables its own specialty modules"

  laboratory:
    label: "Laboratory / Pathology Lab"
    description: "Standalone lab accepting samples from external providers"
    default_modules:
      - medical_core
      - laboratory
      - billing
      - inventory
    optional_modules:
      - specimen_tracking
      - outreach_management

  imaging_center:
    label: "Imaging / Radiology Center"
    description: "Standalone diagnostic imaging facility"
    default_modules:
      - medical_core
      - radiology
      - scheduling
      - billing
    optional_modules:
      - teleradiology

  pharmacy:
    label: "Pharmacy"
    description: "Retail or institutional pharmacy"
    default_modules:
      - medical_core
      - pharmacy
      - billing
      - inventory
    optional_modules:
      - drug_interaction_engine
      - insurance_claims

  dialysis_center:
    label: "Dialysis Center"
    description: "Standalone dialysis facility"
    default_modules:
      - medical_core
      - scheduling
      - dialysis
      - billing
      - inventory

  physiotherapy_center:
    label: "Physiotherapy / Rehab Center"
    description: "Standalone rehabilitation facility"
    default_modules:
      - medical_core
      - scheduling
      - physiotherapy
      - billing

  diagnostic_center:
    label: "Comprehensive Diagnostic Center"
    description: "Combined lab + imaging + examination facility"
    default_modules:
      - medical_core
      - laboratory
      - radiology
      - scheduling
      - billing
      - inventory
    optional_modules:
      - ecg_echo
      - endoscopy
      - pulmonary_function
      - audiometry
      - vision_testing
      
```

## System Setup Wizard (UI Flow)

```text
┌─────────────────────────────────────────────┐
│         System Setup Wizard                 │
├─────────────────────────────────────────────┤
│                                             │
│  "What type of facility are you setting up?"│
│                                             │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  │
│  │ Hospital │  │Polyclinic│  │  Clinic  │  │
│  └──────────┘  └──────────┘  └──────────┘  │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  │
│  │   Lab    │  │ Imaging  │  │ Pharmacy │  │
│  └──────────┘  └──────────┘  └──────────┘  │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  │
│  │ Dialysis │  │ Physio   │  │Diagnostic│  │
│  └──────────┘  └──────────┘  └──────────┘  │
│  ┌──────────┐  ┌──────────┐               │
│  │BioClinic │  │  Custom  │               │
│  └──────────┘  └──────────┘               │
│                                             │
│  [Custom] → Manual module selection         │
│                                             │
└─────────────────────────────────────────────┘
          │
          ▼
┌─────────────────────────────────────────────┐
│  Pre-selected modules shown for confirmation│
│                                             │
│  ☑ Medical Core          (required)         │
│  ☑ Scheduling            (required)         │
│  ☑ Outpatient            (required)         │
│  ☑ Billing               (required)         │
│  ☐ Pharmacy              (optional)         │
│  ☐ Laboratory            (optional)         │
│  ☐ Dental Module         (optional)         │
│  ☐ Dermatology Module    (optional)         │
│  ...                                       │
│                                             │
│           [Confirm & Install]               │
└─────────────────────────────────────────────┘
```

## Permissions Model (RBAC / ABAC / Data Scopes)

```yaml
      predefined_roles:
        - super_admin
        - facility_admin
        - department_head
        - doctor
        - nurse
        - pharmacist
        - lab_technician
        - radiologist
        - receptionist
        - billing_clerk
        - accountant
        - hr_manager
        - inventory_manager
        - patient
    abac:
      description: "Attribute-Based Access Control — fine-grained overrides"
      examples:
        - "Doctor can only view patients assigned to them"
        - "Nurse can only modify vitals, not diagnosis"
        - "Billing clerk cannot view clinical notes"
        - "Pharmacist can view prescriptions but not edit diagnoses"

    data_scope:
      levels:
        - tenant: "Access all data within tenant"
        - facility: "Access all data within one facility"
        - department: "Access all data within one department"
        - own: "Access only own data"
        - custom: "Attribute-based custom scope"

    permission_granularity:
      - module_level: "Can access module X"
      - feature_level: "Can use feature Y in module X"
      - action_level: "Can perform action Z on feature Y"
      - field_level: "Can view/edit field F on entity E"
      - record_level: "Can access record R based on attributes"
```

## Module: organization

```yaml
module: organization
version: "1.0.0"
dependencies: []
features:
  tenant:
    fields:
      - id: "uuid"
      - name: "string(255)"
      - legal_name: "string(255)"
      - registration_number: "string(100)"
      - tax_id: "string(100)"
      - logo: "file"
      - primary_color: "hex"
      - secondary_color: "hex"
      - timezone: "string(50)"
      - locale: "string(10)"
      - currency: "string(3)"
      - date_format: "string(20)"
      - time_format: "string(10)"
      - address: "json"
      - contact: "json"
      - subscription: "json"
      - settings: "jsonb"
      - status: "enum(active, suspended, trial, expired)"
      - created_at: "timestamp"
      - updated_at: "timestamp"

  facility:
    fields:
      - id: "uuid"
      - tenant_id: "uuid FK"
      - name: "string(255)"
      - code: "string(20) unique per tenant"
      - type: "enum(hospital, clinic, lab, imaging, pharmacy, dialysis, physio, diagnostic, other)"
      - parent_facility_id: "uuid FK nullable"
      - address: "json"
      - geo_location: "point"
      - contact: "json"
      - working_hours: "jsonb"
        description: "Per day of week, per department"
      - timezone_override: "string(50) nullable"
      - modules_enabled: "array(string)"
      - capacity:
          - beds: "integer nullable"
          - daily_outpatient: "integer nullable"
          - daily_lab_samples: "integer nullable"
          - daily_imaging: "integer nullable"
      - status: "enum(active, inactive, under_construction)"
      - metadata: "jsonb"

    hierarchy:
      description: "Facilities can be nested (campus → building → floor → unit)"
      max_depth: 5
      examples:
        - "Main Hospital Campus"
          - "Building A"
            - "Floor 1 — Emergency"
            - "Floor 2 — Surgery"
            - "Floor 3 — ICU"
          - "Building B"
            - "Outpatient Clinics"
            - "Radiology Center"

  department:
    fields:
      - id: "uuid"
      - facility_id: "uuid FK"
      - parent_department_id: "uuid FK nullable"
      - name: "string(255)"
      - code: "string(20)"
      - type: "enum(clinical, diagnostic, administrative, support)"
      - head_user_id: "uuid FK nullable"
      - working_hours: "jsonb"
      - location_within_facility: "string(255)"
      - modules_enabled: "array(string)"
      - settings: "jsonb"
      - sort_order: "integer"

  room:
    fields:
      - id: "uuid"
      - department_id: "uuid FK"
      - name: "string(100)"
      - code: "string(20)"
      - type: "enum(consultation, operating, emergency, lab, imaging, pharmacy, waiting, admin, storage, other)"
      - floor: "integer"
      - capacity: "integer"
      - equipment: "array(json)"
      - status: "enum(available, occupied, maintenance, reserved)"
      - scheduling_enabled: "boolean"

  user_management:
    features:
      - user_crud: "Create, read, update, deactivate users"
      - bulk_import: "CSV/Excel user import"
      - user_assignment:
          - to_facility: "many-to-many"
          - to_department: "many-to-many"
          - to_role: "many-to-many"
      - license_tracking:
          - medical_license_number
          - license_expiry
          - specialization_certifications
          - continuing_education_credits
      - credentialing:
          - document_upload
          - verification_workflow
          - expiry_alerts
      - status: "enum(active, inactive, suspended, terminated, on_leave)"
```

## Module: module_registry

```yaml
      module: module_registry
version: "1.0.0"
dependencies: []
features:
  registry:
    description: "Central catalog of all available modules"
    per_module_metadata:
      - id: "string (e.g., 'dental')"
      - version: "semver"
      - display_name: "string"
      - description: "text"
      - icon: "string"
      - category: "enum(core, medical, specialty, facility, support, integration)"
      - dependencies: "array(string)"
      - optional_dependencies: "array(string)"
      - conflicts_with: "array(string)"
      - installable_per: "enum(tenant, facility, department)"
      - schema_version: "integer"
      - migration_count: "integer"
      - size_mb: "float"
      - author: "string"
      - license: "string"
      - changelog_url: "string"
      - documentation_url: "string"

  lifecycle:
    operations:
      - install:
          steps:
            1. "Validate dependencies satisfied"
            2. "Acquire schema migration lock"
            3. "Run pre-install hooks"
            4. "Execute schema migrations"
            5. "Seed default data"
            6. "Register module permissions"
            7. "Register module API routes"
            8. "Register module event handlers"
            9. "Register module menu items"
            10. "Run post-install hooks"
            11. "Release locks"
            12. "Set status to active"
          rollback: true

      - uninstall:
          steps:
            1. "Verify no active dependencies"
            2. "Soft-lock module (reject new operations)"
            3. "Run pre-uninstall hooks"
            4. "Optionally: hard delete data or archive"
            5. "Execute down migrations"
            6. "Unregister routes, events, menus, permissions"
            7. "Run post-uninstall hooks"
          data_retention_options:
            - archive: "Move data to archive schema"
            - soft_delete: "Mark as deleted, keep in place"
            - hard_delete: "Permanently remove"

      - update:
          steps:
            1. "Download new version"
            2. "Verify compatibility with platform core version"
            3. "Run pre-update hooks"
            4. "Execute incremental migrations"
            5. "Run data migration scripts if needed"
            6. "Update module registry entry"
            7. "Run post-update hooks"
          rollback: true

      - pause:
          description: "Hide from UI, disable API, keep data"
          instant: true

      - resume:
          description: "Restore to active state"
          instant: true

  configuration:
    per_module_settings:
      stored_as: "jsonb in module_instance table"
      schema_validated: true
      ui: "Auto-generated from module's settings schema definition"
      example:
        dental_module_settings:
          tooth_chart_style: "fdi|universal|palmer"
          default_procedure_duration_minutes: 30
          auto_generate_treatment_plan: true
          allow_online_booking: true
          xray_integration: "enabled|disabled"
```

## Module: notifications

```yaml
          module: notifications
version: "1.0.0"
dependencies: []
features:
  channels:
    - in_app:
        delivery: "real-time via websocket"
        retention_days: 90
        read_tracking: true
        action_buttons: true
    - email:
        providers:
          - smtp
          - sendgrid
          - aws_ses
          - mailgun
        templates: "per-module, editable, with variables"
        queue: "background job"
    - sms:
        providers:
          - twilio
          - vonage
          - aws_sns
          - custom_smpp
        templates: "with variables, character counting"
    - push:
        providers:
          - firebase_fcm
          - apns
          - web_push
    - whatsapp:
        providers:
          - twilio_whatsapp
          - meta_cloud_api
        template_based: true
    - voice_call:
        providers:
          - twilio
        use_cases:
          - appointment_reminders
          - emergency_alerts

  event_to_notification_mapping:
    configurable: true
    per_tenant_overridable: true
    examples:
      - event: "appointment.created"
        default_channels: ["in_app", "sms"]
        recipients: ["patient"]
      - event: "lab.result.ready"
        default_channels: ["in_app", "email", "sms"]
        recipients: ["ordering_doctor", "patient"]
      - event: "prescription.ready"
        default_channels: ["in_app", "sms"]
        recipients: ["patient"]
      - event: "invoice.overdue"
        default_channels: ["email", "sms", "whatsapp"]
        recipients: ["patient"]
      - event: "bed.available"
        default_channels: ["in_app"]
        recipients: ["admission_department"]

  preferences:
    per_user: true
    per_channel: true
    per_event_type: true
    quiet_hours: true
    digest_mode:
      - immediate
      - hourly_digest
      - daily_digest
```

## Module: documents

```yaml
      module: documents
version: "1.0.0"
dependencies: []
features:
  storage:
    backends:
      - local_filesystem
      - aws_s3
      - azure_blob
      - google_cloud_storage
      - minio
    strategy: "configurable per tenant"
    encryption: "aes-256 at rest"

  document_types:
    system_defined:
      - patient_id_proof
      - insurance_card
      - consent_form
      - medical_report
      - lab_report
      - imaging_report
      - prescription
      - referral_letter
      - discharge_summary
      - invoice
      - receipt
      - contract
      - cv
      - license
      - certificate
    custom_types: true

  features:
    - upload: "Multi-file, drag-drop, with progress"
    - versioning: "Full version history, diff view for text"
    - preview: "PDF, images, common document formats"
    - ocr: "Extract text from scanned documents"
    - categorization: "Auto-categorize based on type and content"
    - tagging: "Custom tags, searchable"
    - sharing: "Secure links with expiry"
    - e_signature:
        integration:
          - docuSign
          - adobe_sign
          - hello_sign
          - internal_basic_sign
    - printing: "Print-ready formatting"
    - bulk_operations: "Download zip, bulk delete, bulk reclassify"

  access_control:
    per_document: true
    based_on: "document_type + patient_assignment + role"
    watermarking: "Dynamic watermark with viewer info"
    audit_trail: "Every view, download, print logged"
```

## Module: medical_core

```yaml
    module: medical_core
version: "1.0.0"
dependencies: ["organization"]
category: "medical"
installable_per: "tenant"


patient:
  entity: "patient"
  description: "Central patient record — shared across all medical modules"
  fields:
    identity:
      - id: "uuid"
      - patient_id: "string(20) auto-generated, configurable format"
        formats: ["YYYYMMDD-NNNN", "FAC-NNNNNN", "custom"]
      - tenant_id: "uuid FK"
      - registered_facility_id: "uuid FK"
      - first_name: "string(100)"
      - last_name: "string(100)"
      - middle_name: "string(100) nullable"
      - preferred_name: "string(100) nullable"
      - date_of_birth: "date"
      - sex: "enum(male, female, other, prefer_not_to_say)"
      - gender_identity: "string(50) nullable"
      - pronouns: "string(50) nullable"
      - national_id: "string(50) nullable"
      - passport_number: "string(50) nullable"
      - blood_type: "enum(A+, A-, B+, B-, AB+, AB-, O+, O-) nullable"
      - marital_status: "enum(single, married, divorced, widowed) nullable"
      - nationality: "string(100) nullable"
      - primary_language: "string(50) nullable"
      - photo: "file nullable"

    contact:
      - phone_primary: "string(30)"
      - phone_secondary: "string(30) nullable"
      - email: "string(255) nullable"
      - address: "json"
        structure:
          - line1: "string"
          - line2: "string nullable"
          - city: "string"
          - state: "string nullable"
          - postal_code: "string"
          - country: "string"
      - emergency_contacts: "array(json)"
        structure:
          - name: "string"
          - relationship: "string"
          - phone: "string"
          - email: "string nullable"
          - address: "json nullable"

    clinical_baseline:
      - known_allergies: "array(json)"
        structure:
          - allergen: "string"
          - type: "enum(drug, food, environmental, latex, other)"
          - severity: "enum(mild, moderate, severe, life_threatening)"
          - reaction: "text"
          - source: "enum(patient_reported, test_confirmed, clinical_observation)"
          - since: "date nullable"
          - verified_by: "uuid FK nullable"
          - verified_at: "timestamp nullable"
      - chronic_conditions: "array(json)"
        structure:
          - condition: "string (ICD-10 coded)"
          - icd_code: "string"
          - since: "date nullable"
          - status: "enum(active, resolved, managed)"
          - notes: "text nullable"
      - current_medications: "array(json)"
        structure:
          - medication_name: "string"
          - dosage: "string"
          - frequency: "string"
          - route: "string"
          - prescriber: "uuid FK nullable"
          - start_date: "date"
          - end_date: "date nullable"
          - ongoing: "boolean"
      - surgical_history: "array(json)"
      - family_history: "array(json)"
      - social_history:
          - smoking: "enum(never, former, current)"
          - alcohol: "enum(none, occasional, moderate, heavy)"
          - drugs: "enum(none, former, current)"
          - occupation: "string nullable"
          - exercise_frequency: "string nullable"
      - obstetric_history: "json nullable"
        structure:
          - gravida: "integer"
          - para: "integer"
          - living_children: "integer"
          - complications: "array(string)"
          - last_menstrual_period: "date nullable"

    administrative:
      - insurance: "array(json)"
        structure:
          - provider_name: "string"
          - policy_number: "string"
          - group_number: "string nullable"
          - plan_type: "string"
          - effective_date: "date"
          - expiry_date: "date nullable"
          - copay_amount: "decimal nullable"
          - pre_auth_required: "boolean"
          - documents: "array(uuid) FK to documents"
          - status: "enum(active, expired, pending)"
      - referring_source: "string nullable"
      - registration_date: "timestamp"
      - registered_by: "uuid FK"
      - status: "enum(active, deceased, transferred, inactive)"

  features:
    - search:
        fields: ["name", "phone", "national_id", "patient_id", "date_of_birth"]
        fuzzy: true
        phonetic: true
        combined_filters: true
    - merge:
      description: "Merge duplicate patient records"
      workflow: "review → select master → map fields → confirm → execute"
      audit: "Full before/after logging"
    - deduplication:
      automatic_detection: true
      algorithm: "fuzzy match on name + DOB + phone"
      confidence_score: "0.0 - 1.0"
      action: "flag_for_review"
    - export: "HL7 FHIR, C-CDA, CSV, PDF"
    - patient_portal_link: true
    - qr_code_generation: "For patient ID card"
    - barcode_generation: "For wristband printing"


    encounter:
  entity: "encounter"
  description: "A clinical encounter is the container for all clinical activities during a patient visit"
  fields:
    - id: "uuid"
    - encounter_number: "string(30) auto-generated"
    - tenant_id: "uuid FK"
    - facility_id: "uuid FK"
    - patient_id: "uuid FK"
    - department_id: "uuid FK"
    - provider_id: "uuid FK"
    - type: "enum(outpatient, inpatient, emergency, telemedicine, home_visit, day_care)"
    - status: "enum(scheduled, in_progress, on_hold, completed, cancelled, no_show)"
    - priority: "enum(routine, urgent, emergency)"
    - check_in_time: "timestamp nullable"
    - start_time: "timestamp nullable"
    - end_time: "timestamp nullable"
    - discharge_time: "timestamp nullable"
    - diagnosis: "array(json)"
      structure:
        - code: "string (ICD-10)"
        - description: "string"
        - type: "enum(primary, secondary, differential)"
        - confidence: "enum(confirmed, probable, possible, rule_out)"
        - source: "enum(clinical, lab, imaging, pathological)"
    - chief_complaint: "text nullable"
    - notes: "text nullable"
    - vitals_id: "uuid FK nullable"
    - referral_id: "uuid FK nullable"
    - parent_encounter_id: "uuid FK nullable"
      description: "For follow-ups, transfers between departments"
    - metadata: "jsonb"

  features:
    - timeline_view: "Chronological view of all encounter events"
    - encounter_summary: "Auto-generated summary of encounter"
    - encounter_print: "Formatted printout with facility header"
    - encounter_transfer: "Transfer between departments/providers"
    - encounter_linking: "Link related encounters"


    clinical_notes:
  entity: "clinical_note"
  fields:
    - id: "uuid"
    - encounter_id: "uuid FK"
    - patient_id: "uuid FK"
    - author_id: "uuid FK"
    - type: "enum(soap, progress, consultation, procedure, discharge, referral, follow_up, nursing, anesthesia, operative, other)"
    - template_id: "uuid FK nullable"
    - content: "jsonb"
      structure_for_soap:
        subjective:
          chief_complaint: "text"
          history_of_present_illness: "text"
          review_of_systems: "json"
            description: "Per-system checklist + free text"
        objective:
          vitals: "json"
          physical_examination: "json"
            description: "Per-body-system findings"
          lab_results_summary: "array(json)"
          imaging_results_summary: "array(json)"
        assessment:
          diagnosis_list: "array(json)"
          clinical_impression: "text"
          differential_diagnosis: "array(json)"
        plan:
          medications: "array(json)"
          investigations: "array(json)"
          procedures: "array(json)"
          referrals: "array(json)"
          follow_up: "json"
          patient_education: "text"
    - attachments: "array(uuid) FK to documents"
    - signed_by: "uuid FK nullable"
    - signed_at: "timestamp nullable"
    - amended: "boolean"
    - amendment_history: "array(json)"
    - locked: "boolean"
    - created_at: "timestamp"
    - updated_at: "timestamp"

  features:
    - templates:
        per_specialty: true
        per_facility: true
        per_provider: true
        editor: "rich text with structured fields"
        variables: "Auto-populate patient data, vitals, previous notes"
    - auto_save: "Every 30 seconds"
    - versioning: "Full version history"
    - co_signing: "Require second signature for specific note types"
    - lock_after_sign: "Signed notes become read-only (amendment workflow available)"
    - voice_dictation: "Integration with speech-to-text APIs"
    - ai_assist:
        - "Suggest ICD-10 codes from free text"
        - "Auto-generate assessment from subjective+objective"
        - "Grammar and clarity improvements"
        - "Never auto-submits — always requires human review"



        vitals:
  entity: "vitals"
  fields:
    - id: "uuid"
    - encounter_id: "uuid FK nullable"
    - patient_id: "uuid FK"
    - recorded_by: "uuid FK"
    - recorded_at: "timestamp"
    - source: "enum(manual, device_import, iot_device)"
    - device_id: "string nullable"
    - measurements: "jsonb"
      standard_set:
        - temperature:
            value: "decimal"
            unit: "enum(celsius, fahrenheit)"
            method: "enum(oral, axillary, tympanic, rectal, forehead)"
        - heart_rate:
            value: "integer (bpm)"
            rhythm: "enum(regular, irregular) nullable"
        - blood_pressure:
            systolic: "integer (mmHg)"
            diastolic: "integer (mmHg)"
            position: "enum(sitting, standing, lying)"
            arm: "enum(left, right)"
        - respiratory_rate:
            value: "integer (breaths/min)"
        - oxygen_saturation:
            value: "decimal (%)"
            method: "enum(pulse_oximetry, abg)"
            supplemental_o2: "boolean"
            o2_flow_rate: "decimal nullable"
        - weight:
            value: "decimal"
            unit: "enum(kg, lb)"
        - height:
            value: "decimal"
            unit: "enum(cm, in)"
        - bmi:
            value: "decimal (auto-calculated)"
        - pain_score:
            value: "integer (0-10)"
            scale: "enum(wong_baker, numeric, faces)"
        - blood_glucose:
            value: "decimal"
            unit: "enum(mg_dl, mmol_l)"
            timing: "enum(fasting, random, post_prandial)"
        - gcs:
            eye: "integer (1-4)"
            verbal: "integer (1-5)"
            motor: "integer (1-6)"
            total: "integer (3-15) auto-calculated"
      extended_set:
        - waist_circumference: "decimal"
        - head_circumference: "decimal"
        - peak_flow: "integer"
        - temperature_multiple_sites: "array(json)"
        - pediatric_specific:
            - length: "decimal"
            - fontanelle: "enum(open, closed, bulging, sunken)"
            - weight_percentile: "decimal"
            - height_percentile: "decimal"

  features:
    - growth_charts: "WHO/CDC percentiles for pediatrics"
    - trend_visualization: "Line charts over time per measurement"
    - abnormal_alerts: "Configurable thresholds with color coding"
    - device_integration: "Bluetooth, serial port, HL7"
    - batch_entry: "For ward rounds — enter vitals for multiple patients"



    prescriptions:
  entity: "prescription"
  fields:
    - id: "uuid"
    - prescription_number: "string(30)"
    - encounter_id: "uuid FK"
    - patient_id: "uuid FK"
    - prescriber_id: "uuid FK"
    - facility_id: "uuid FK"
    - type: "enum(outpatient, inpatient, discharge)"
    - status: "enum(draft, active, completed, discontinued, expired, cancelled)"
    - items: "array(json)"
      structure:
        - medication_id: "uuid FK nullable"
        - generic_name: "string"
        - brand_name: "string nullable"
        - strength: "string (e.g., '500mg')"
        - form: "enum(tablet, capsule, syrup, injection, cream, drops, inhaler, patch, suppository, other)"
        - dosage: "string (e.g., '1 tablet')"
        - route: "enum(oral, iv, im, sc, topical, inhalation, nasal, ophthalmic, otic, rectal, vaginal, other)"
        - frequency: "string (e.g., 'twice daily', 'q8h')"
        - duration: "string (e.g., '7 days', 'as needed')"
        - quantity: "decimal"
        - refills: "integer default 0"
        - refills_used: "integer default 0"
        - instructions: "text (e.g., 'Take with food')"
        - start_date: "date"
        - end_date: "date nullable"
        - prn: "boolean"
        - prn_reason: "string nullable"
        - notes: "text nullable"
        - substitutions_allowed: "boolean default true"
        - dawa_code: "string nullable"
        - ndc_code: "string nullable"
        - atc_code: "string nullable"
    - diagnosis_reference: "array(string) ICD-10 codes"
    - dispense_at_pharmacy_id: "uuid FK nullable"
    - signed_at: "timestamp nullable"
    - printed_at: "timestamp nullable"
    - created_at: "timestamp"

  features:
    - drug_database:
        source: "Local drug index + optional WHO/ national formulary integration"
        fields_per_drug:
          - generic_name, brand_names, strengths, forms
          - atc_code, dawa_code, ndc_code
          - contraindications, interactions, side_effects
          - pregnancy_category, pediatric_dosing
          - storage_requirements
          - controlled_substance_schedule
    - interaction_checker:
        - drug_drug: "Check all items against each other"
        - drug_allergy: "Check against patient's known allergies"
        - drug_condition: "Check against patient's conditions"
        - drug_food: "Known food interactions"
        - severity_levels: "contraindicated, severe, moderate, mild"
        - action: "Block, warn with override, inform only"
    - dosage_calculator:
        - weight_based: "mg/kg"
        - bsa_based: "mg/m²"
        - renal_adjustment: "CrCl-based"
        - hepatic_adjustment: "Child-Pugh based"
        - pediatric: "Age/weight bands"
    - prescription_templates: "Frequently prescribed combinations"
    - electronic_prescribing: "e-Prescribe to external pharmacies"
    - controlled_substance_tracking: "Schedule I-V with extra logging"
    - prescription_history: "Full patient medication history across encounters"
    - refill_management: "Track and process refills"



    orders:
  entity: "order"
  description: "Universal order system — lab, imaging, procedures, consultations"
  fields:
    - id: "uuid"
    - order_number: "string(30)"
    - encounter_id: "uuid FK"
    - patient_id: "uuid FK"
    - ordering_provider_id: "uuid FK"
    - facility_id: "uuid FK"
    - department_id: "uuid FK nullable"
    - type: "enum(lab, imaging, procedure, consultation, other)"
    - category: "string (e.g., 'blood chemistry', 'x-ray', 'ecg')"
    - items: "array(json)"
      structure:
        - service_code: "string (LOINC/CPT/local)"
        - service_name: "string"
        - description: "text nullable"
        - urgency: "enum(routine, stat, asap, timed)"
        - scheduled_datetime: "timestamp nullable"
        - clinical_indication: "text"
        - laterality: "enum(left, right, bilateral, n/a)"
        - quantity: "integer default 1"
    - status: "enum(ordered, collected, in_progress, resulted, verified, cancelled)"
    - priority: "enum(routine, urgent, emergency)"
    - notes: "text nullable"
    - diagnosis_reference: "array(string)"
    - results: "array(json) nullable"
      structure:
        - item_code: "string"
        - item_name: "string"
        - value: "string"
        - unit: "string nullable"
        - reference_range: "string nullable"
        - abnormal_flag: "enum(high, low, critical_high, critical_low, normal) nullable"
        - status: "enum(preliminary, final, corrected, cancelled)"
        - performed_at: "timestamp nullable"
        - performed_by: "uuid FK nullable"
        - verified_by: "uuid FK nullable"
        - verified_at: "timestamp nullable"
        - comment: "text nullable"
    - resulting_department_id: "uuid FK nullable"
    - created_at: "timestamp"
    - updated_at: "timestamp"

  features:
    - order_sets: "Pre-defined groups of orders (e.g., 'CBC + CMP + Urinalysis')"
    - favorite_orders: "Per-provider quick-pick list"
    - duplicate_detection: "Warn if same order exists within timeframe"
    - critical_value_alert: "Immediate notification for critical lab/imaging results"
    - result_acknowledgment: "Ordering provider must acknowledge results"
    - auto-verify: "Configurable auto-verification for normal results"




    scheduling:
  entity: "appointment"
  fields:
    - id: "uuid"
    - appointment_number: "string(30)"
    - tenant_id: "uuid FK"
    - facility_id: "uuid FK"
    - department_id: "uuid FK"
    - patient_id: "uuid FK"
    - provider_id: "uuid FK"
    - room_id: "uuid FK nullable"
    - service_id: "uuid FK nullable"
    - type: "enum(consultation, follow_up, procedure, lab_collection, imaging, therapy, other)"
    - status: "enum(scheduled, checked_in, in_progress, completed, no_show, cancelled, rescheduled)"
    - start_time: "timestamp"
    - end_time: "timestamp"
    - duration_minutes: "integer"
    - notes: "text nullable"
    - source: "enum(walk_in, online, phone, referral, internal)"
    - reminder_sent: "boolean default false"
    - reminder_sent_at: "timestamp nullable"
    - cancel_reason: "text nullable"
    - rescheduled_from_id: "uuid FK nullable"
    - created_by: "uuid FK"
    - created_at: "timestamp"

  provider_schedules:
    entity: "provider_schedule"
    description: "Define when each provider is available"
    fields:
      - id: "uuid"
      - provider_id: "uuid FK"
      - facility_id: "uuid FK"
      - department_id: "uuid FK nullable"
      - effective_from: "date"
      - effective_to: "date nullable"
      - patterns: "array(json)"
        structure:
          - day_of_week: "integer (0-6)"
          - start_time: "time"
          - end_time: "time"
          - slot_duration_minutes: "integer"
          - max_patients_per_slot: "integer default 1"
          - overbooking_allowed: "boolean"
          - overbooking_max: "integer default 0"
          - break_periods: "array(json)"
            structure:
              - start: "time"
              - end: "time"
              - label: "string (e.g., 'Lunch')"
          - service_types: "array(string)"
          - room_id: "uuid FK nullable"
      - exceptions: "array(json)"
        structure:
          - date: "date"
          - type: "enum(unavailable, modified, extra)"
          - start_time: "time nullable"
          - end_time: "time nullable"
          - reason: "string nullable"

  features:
    - availability_calendar: "Visual calendar showing open slots"
    - booking:
        modes:
          - manual: "Receptionist books on behalf of patient"
          - online: "Patient self-books via portal"
          - kiosk: "Self-service kiosk at facility"
          - api: "Third-party integration booking"
        rules:
          - min_advance_hours: "configurable per service type"
          - max_advance_days: "configurable per service type"
          - new_patient_vs_follow_up: "Different durations"
          - required_pre_conditions: "e.g., referral needed for specialist"
    - waitlist: "Automatic fill from cancellations"
    - recurring_appointments: "For therapy, dialysis, etc."
    - multi_provider: "Appointments involving multiple providers"
    - resource_conflict_detection: "Room + provider + equipment conflicts"
    - queue_management:
        - virtual_queue: "Patient checks in, gets queue number"
        - display_boards: "TV/monitor display integration"
        - sms_queue_updates: "Your turn in N patients"
        - estimated_wait_time: "Algorithm-based"
    - telemedicine_link:
        - auto_generate_meeting: "Zoom, Teams, Google Meet, or built-in"
        - send_link_to_patient: "Via SMS/email"
        - join_from_encounter: "One-click join for provider"
    - no_show_tracking: "Flag chronic no-shows, implement policies"
    - appointment_analytics:
        - utilization_rate
        - no_show_rate
        - cancellation_rate
        - average_wait_time
        - provider_productivity



        referrals:
  entity: "referral"
  fields:
    - id: "uuid"
    - referral_number: "string(30)"
    - tenant_id: "uuid FK"
    - from_facility_id: "uuid FK"
    - from_provider_id: "uuid FK"
    - from_department_id: "uuid FK nullable"
    - to_facility_id: "uuid FK nullable"
    - to_provider_id: "uuid FK nullable"
    - to_department_id: "uuid FK nullable"
    - patient_id: "uuid FK"
    - encounter_id: "uuid FK nullable"
    - type: "enum(internal, external_incoming, external_outgoing)"
    - urgency: "enum(routine, urgent, emergency)"
    - reason: "text"
    - clinical_summary: "text"
    - requested_services: "array(json)"
      structure:
        - service: "string"
        - icd_code: "string nullable"
        - notes: "text nullable"
    - attached_documents: "array(uuid) FK to documents"
    - status: "enum(sent, received, accepted, in_progress, completed, rejected, cancelled)"
    - response_notes: "text nullable"
    - response_documents: "array(uuid) FK to documents"
    - created_at: "timestamp"
    - updated_at: "timestamp"

  features:
    - referral_network: "Directory of frequently referred-to providers/facilities"
    - referral_tracking: "Track status of outgoing referrals"
    - incoming_referral_workflow: "Receive, accept/reject, schedule, complete"
    - referral_letter_generation: "Template-based with auto-populated clinical data"
    - bidirectional_communication: "Send/receive referral updates"
    - hl7_referral_support: "HL7 REF messages"
    - analytics: "Referral volumes, acceptance rates, turnaround times"



    problem_list:
  entity: "problem"
  description: "Longitudinal list of all patient problems across encounters"
  fields:
    - id: "uuid"
    - patient_id: "uuid FK"
    - encounter_id: "uuid FK nullable"
    - code: "string (ICD-10 / SNOMED-CT)"
    - description: "string"
    - type: "enum(diagnosis, symptom, finding, condition, risk_factor)"
    - status: "enum(active, resolved, chronic, recurrent)"
    - onset_date: "date nullable"
    - resolved_date: "date nullable"
    - certainty: "enum(confirmed, probable, possible)"
    - source: "enum(clinical, lab, imaging, patient_reported, family_history)"
    - noted_by: "uuid FK"
    - notes: "text nullable"
    - linked_encounters: "array(uuid)"
    - linked_orders: "array(uuid)"
    - created_at: "timestamp"
    - updated_at: "timestamp"

  features:
    - chronological_view: "Timeline of problem onset and resolution"
    - filter_by_status: "Active / resolved / all"
    - auto_suggest: "From encounter diagnoses, suggest adding to problem list"
    - snomed_ct_mapping: "Optional SNOMED-CT coding alongside ICD-10"



    medical_alerts:
  description: "System-wide patient safety alerts displayed contextually"

  alert_types:
    - allergy_alert:
      trigger: "Any medication order or procedure involving allergen"
      display: "Red banner with allergen details"
      action_required: "Acknowledge and override or cancel"
      audit: "Every override logged with reason"

    - drug_interaction_alert:
      trigger: "Prescription interaction detected"
      severity_levels:
        - contraindicated: "Must cancel, cannot override without pharmacy approval"
        - severe: "Requires senior provider acknowledgment"
        - moderate: "Warn, allow override with reason"
        - mild: "Inform only"

    - duplicate_therapy_alert:
      trigger: "Same drug class prescribed by different providers"
      display: "Warning during prescription entry"

    - critical_value_alert:
      trigger: "Lab or vital result exceeds critical threshold"
      routing: "Immediate notification to ordering provider + department head"
      escalation: "If not acknowledged within configurable time"

    - fall_risk_alert:
      trigger: "Assessment score indicates fall risk"
      display: "Yellow star on patient banner, nursing board"

    - isolation_alert:
      trigger: "Infection control flag on patient"
      display: "Icon on patient banner, room sign auto-printed"

    - consent_missing_alert:
      trigger: "Procedure ordered without signed consent"
      action: "Block procedure until consent uploaded"

    - vte_risk_alert:
      trigger: "Venous thromboembolism risk assessment score"
      display: "On admission and daily"

  alert_configuration:
    per_tenant: true
    per_facility: true
    per_department: true
    options:
      - enable/disable per alert type
      - severity override
      - routing rules (who gets notified)
      - escalation timing
      - sound/visual indicator
```

## Module: dental

```yaml
      module: dental
version: "1.0.0"
dependencies: ["medical_core", "scheduling"]
category: "specialty"
installable_per: "facility"

entities:
  dental_chart:
    description: "Permanent tooth chart — updated across encounters"
    fields:
      - id: "uuid"
      - patient_id: "uuid FK"
      - notation_system: "enum(fdi, universal, palmer)"
      - teeth: "jsonb"
        structure:
          "36":
            present: true
            status: "enum(healthy, carious, restored, crowned, bridge_abutment, missing,_implant, deciduous)"
            restorations:
              - surface: "enum(occlusal, mesial, distal, buccal, lingual, multiple)"
                material: "enum(composite, amalgam, ceramic, gold, gic, other)"
                date: "date"
                notes: "text nullable"
            caries:
              - surface: "string"
                severity: "enum(initial, moderate, deep, pulpal)"
                recorded_date: "date"
            periodontal:
              probing_depth_mm: "decimal"
              recession_mm: "decimal"
              bleeding_on_probing: "boolean"
              mobility: "enum(0, 1, 2, 3)"
              furcation: "enum(0, 1, 2, 3)"
              attachment_level_mm: "decimal"
            endodontic:
              status: "enum(normal, treated, retreated, pending)"
              pulp_status: "enum(vital, non_vital, previously_treated)"
              obturation_date: "date nullable"
            implant:
              brand: "string nullable"
              diameter_mm: "decimal nullable"
              length_mm: "decimal nullable"
              placement_date: "date nullable"
              abutment_type: "string nullable"
              crown_date: "date nullable"
          # ... repeated for all 32 teeth
      - extra_oral_findings: "text nullable"
      - tmj_assessment: "json nullable"
      - occlusion: "enum(class_i, class_ii_div_1, class_ii_div_2, class_iii, open_bite, cross_bite, other)"
      - last_updated: "timestamp"
      - updated_by: "uuid FK"

  dental_note:
    extends: "clinical_note (type = 'dental')"
    content:
      chief_complaint: "text"
      history: "text"
      examination:
        extra_oral: "text"
        intra_oral_soft_tissues: "text"
        hard_tissues: "reference to dental_chart"
        periodontal: "reference to dental_chart"
      radiographs_taken: "array(json)"
        structure:
          - type: "enum(periapical, bitewing, panoramic, ceph, cbct, occlusal)"
            teeth_included: "array(string)"
            findings: "text"
            file_id: "uuid FK to documents"
      diagnosis: "array(json)"
        structure:
          - tooth: "string nullable"
            code: "string (ICD-10-PCS dental)"
            description: "string"
      treatment_plan:
        - procedure: "string"
          tooth: "string nullable"
          code: "string (CDT code)"
          urgency: "enum(elective, soon, urgent, emergency)"
          estimated_cost: "decimal nullable"
          status: "enum(proposed, accepted, in_progress, completed, cancelled)"
          scheduled_date: "date nullable"
          completed_date: "date nullable"
          notes: "text nullable"

  dental_procedure_log:
    fields:
      - id: "uuid"
      - encounter_id: "uuid FK"
      - patient_id: "uuid FK"
      - provider_id: "uuid FK"
      - procedure_date: "timestamp"
      - tooth: "string nullable"
      - surfaces: "array(string) nullable"
      - cdt_code: "string"
      - procedure_name: "string"
      - anesthesia_type: "string nullable"
      - anesthesia_cartridges: "integer nullable"
      - materials_used: "array(json)"
        structure:
          - material_name: "string"
            lot_number: "string nullable"
            quantity: "string"
      - complications: "text nullable"
      - post_op_instructions: "text nullable"
      - next_visit: "date nullable"
      - duration_minutes: "integer nullable"
      - notes: "text nullable"

  features:
    - visual_tooth_chart:
        interactive: true
        click_tooth_to_record: true
        color_coded_status: true
        zoom_pan: true
        print_friendly: true
    - panoramic_viewer:
        dicom_support: true
        annotations: true
        measurements: true
    - treatment_plan_builder:
        drag_and_drop: true
        cost_estimation: true
        insurance_coverage_preview: true
        patient_approval_workflow: true
        pdf_export: true
    - recall_system:
        intervals_per_procedure: true
        automated_reminders: true
        recall_dashboard: true
    - dental_inventory:
        materials: "Composites, impression materials, etc."
        consumables: "Gloves, masks, bibs"
        tracking: "Per-procedure consumption logging"
```

## Module: derma (Dermatology)

```yaml
        module: derma
version: "1.0.0"
dependencies: ["medical_core", "scheduling"]
category: "specialty"
installable_per: "facility"

entities:
  skin_examination:
    fields:
      - id: "uuid"
      - encounter_id: "uuid FK"
      - patient_id: "uuid FK"
      - skin_type: "enum(fitzpatrick_1, fitzpatrick_2, fitzpatrick_3, fitzpatrick_4, fitzpatrick_5, fitzpatrick_6)"
      - body_map: "jsonb"
        description: "Anatomical diagram with lesion markers"
        structure:
          - region: "enum(head, face, neck, chest, back, abdomen, left_arm, right_arm, left_hand, right_hand, left_leg, right_leg, left_foot, right_foot, genital, other)"
            lesions:
              - id: "string"
                position_x: "decimal (0-100)"
                position_y: "decimal (0-100)"
                reference_id: "uuid FK to skin_lesion"
      - general_skin_findings: "text nullable"
      - photo_documentation: "array(uuid) FK to documents"
      - examined_by: "uuid FK"

  skin_lesion:
    fields:
      - id: "uuid"
      - encounter_id: "uuid FK"
      - patient_id: "uuid FK"
      - body_region: "string"
      - location_description: "text"
      - morphology: "enum(macule, patch, papule, plaque, nodule, tumor, vesicle, bulla, pustule, wheal, comedo, scar, atrophy, ulcer, erosion, fissure, scale, crust, other)"
      - color: "array(string) — e.g., ['red', 'brown', 'hyperpigmented']"
      - size_mm:
          length: "decimal"
          width: "decimal"
          height: "decimal nullable"
      - shape: "enum(round, oval, irregular, linear, annular, target, other)"
      - border: "enum(well_defined, ill_defined, irregular, raised)"
      - surface: "enum(smooth, rough, scaly, crusted, verrucous, umbilicated, other)"
      - consistency: "enum(soft, firm, hard, cystic, fluctuant)"
      - tenderness: "enum(none, mild, moderate, severe)"
      - associated_symptoms: "array(string) — itching, pain, burning, bleeding"
      - duration: "string (e.g., '3 months', '2 years')"
      - evolution: "enum(stable, growing, shrinking, new, recurrent)"
      - dermoscopy_findings: "text nullable"
      - differential_diagnosis: "array(string)"
      - photos: "array(uuid) FK to documents"
      - biopsy_taken: "boolean"
      - biopsy_site: "text nullable"
      - biopsy_type: "enum(shave, punch, excisional, incisional) nullable"

  derma_note:
    extends: "clinical_note (type = 'dermatology')"
    content:
      history:
        - onset: "text"
          evolution: "text"
          triggering_factors: "array(string)"
          previous_treatments: "array(json)"
          family_history_skin: "text"
          medication_history: "text"
          allergies_relevant: "text"
          sun_exposure: "enum(minimal, moderate, high, occupational)"
          occupational_exposure: "text nullable"
      examination: "reference to skin_examination"
      diagnosis: "array(json)"
        structure:
          - condition: "string"
            icd_code: "string"
            confidence: "enum(definite, probable, possible)"
            criteria_met: "array(string)"
      treatment_plan:
        - topical: "array(json)"
            structure:
              - medication: "string"
                strength: "string"
                formulation: "string"
                application_site: "string"
                frequency: "string"
                duration: "string"
              - systemic: "array(json)"
                  structure:
                    - medication: "string"
                      dose: "string"
                      frequency: "string"
                      duration: "string"
                      monitoring_required: "boolean"
                      baseline_labs: "array(string)"
              - procedural: "array(json)"
                  structure:
                    - procedure: "string"
                      body_site: "string"
                      anesthesia: "string nullable"
                      scheduled_date: "date nullable"
              - phototherapy: "json nullable"
                  structure:
                    - type: "enum(nbuvb, puva, excimer)"
                      body_areas: "array(string)"
                      starting_dose: "string"
                      frequency: "string"
              - patient_education: "text"

  features:
    - body_map_editor:
        interactive_anatomy_diagram: true
        click_to_add_lesion_marker: true
        drag_to_reposition: true
        link_marker_to_lesion_record: true
        zoom_per_region: true
    - photo_comparison:
        side_by_side: true
        overlay: true
        timeline_slider: true
        before_after: true
    - dermoscopy_integration:
        import_from_device: true
        annotate_images: true
        pattern_analysis_assist: true
    - skin_cancer_checklist:
        abcde_criteria: true
        ugly_duckling_sign: true
        seven_point_checklist: true
        breslow_thickness: "For melanoma staging"
    - chronic_disease_tracking:
        conditions: ["psoriasis", "eczema", "acne", "vitiligo", "alopecia"]
        scoring_systems:
          - pasi_score: "Psoriasis Area and Severity Index"
          - easi_score: "Eczema Area and Severity Index"
          - dlqi: "Dermatology Life Quality Index"
          - iga: "Investigator's Global Assessment"
        trend_charts: true
    - cosmetic_dermatology:
        treatment_log: "Botox, fillers, lasers, peels"
        product_batch_tracking: true
        before_after_photos: true
        consent_forms: true
        follow_up_scheduling: true
```

## Module: ophthalmology

```yaml
        module: ophthalmology
version: "1.0.0"
dependencies: ["medical_core", "scheduling"]
category: "specialty"
installable_per: "facility"

entities:
  eye_examination:
    fields:
      - id: "uuid"
      - encounter_id: "uuid FK"
      - patient_id: "uuid FK"
      - visual_acuity:
          right_eye:
            uncorrected: "string (e.g., '6/6', '20/20')"
            corrected: "string nullable"
            pinhole: "string nullable"
          left_eye:
            uncorrected: "string"
            corrected: "string nullable"
            pinhole: "string nullable"
          binocular: "string nullable"
      - refraction:
          right_eye:
            sphere: "decimal"
            cylinder: "decimal nullable"
            axis: "integer nullable"
            add: "decimal nullable"
            va: "string nullable"
          left_eye:
            sphere: "decimal"
            cylinder: "decimal nullable"
            axis: "integer nullable"
            add: "decimal nullable"
            va: "string nullable"
      - intraocular_pressure:
          right_eye: "decimal (mmHg)"
          left_eye: "decimal (mmHg)"
          method: "enum(goldmann, air_puff, icare, tonopen)"
          time: "time"
      - pupils:
          right_eye:
            size_mm: "decimal"
            shape: "enum(round, irregular)"
            reaction: "enum(brisk, sluggish, fixed)"
            afferent_pupillary_defect: "boolean"
          left_eye: "same structure"
      - slit_lamp:
          right_eye:
            eyelids: "text nullable"
            conjunctiva: "text nullable"
            cornea: "text nullable"
            anterior_chamber: "enum(deep, shallow, normal)"
            iris: "text nullable"
            lens: "enum(clear, nuclear_sclerosis, cortical_spoke, posterior_subcapsular, other)"
          left_eye: "same structure"
      - fundus:
          right_eye:
            disc: "text (color, cup_disc_ratio, margins)"
            macula: "text"
            vessels: "text"
            periphery: "text"
          left_eye: "same structure"
      - extraocular_movements: "enum(full, restricted, other)"
      - visual_field: "json nullable"
      - oct: "json nullable"
      - topography: "json nullable"
      - dry_eye_assessment:
          schirmer_test:
            right_eye_mm: "integer nullable"
            left_eye_mm: "integer nullable"
          tear_film_breakup_time:
            right_eye_sec: "integer nullable"
            left_eye_sec: "integer nullable"

  features:
    - prescription_glasses:
        sphere_cylinder_axis_entry: true
        lens_options: "single vision, bifocal, progressive, photochromic"
        frame_selection: "Integration with optical shop"
        order_to_lab: "Electronic order to optical lab"
    - contact_lens_fitting:
        brand_catalog: true
        parameters: "BC, diameter, power, cylinder, axis, material"
        trial_lens_tracking: true
        follow_up_scheduling: true
    - glaucoma_tracking:
        iop_trend: "Graph over time"
        visual_field_series: "Compare sequential fields"
        oct_rnfl_trend: "Retinal nerve fiber layer thickness over time"
        target_iop: "Per-patient target"
    - diabetic_retinopathy_screening:
        grading: "R0-R3, M0-M1, P0-P1"
        photo_documentation: true
        referral_criteria: "Auto-alert when referral needed"
    - cataract_surgery_workflow:
        biometry_integration: "IOLMaster, Lenstar"
        iol_calculation: "SRK-T, Hoffer Q, Haigis"
        surgical_plan: "Eye, IOL model, power"
        consent: "Template-based"
        post_op_tracking: "Day 1, week 1, month 1, month 3"
    - optical_shop:
        inventory: "Frames, lenses, contact lenses, accessories"
        sales: "POS integration"
        lab_orders: "Track orders to external lab"
        warranty_tracking: true



        specialty_modules_summary:

  cardiology:
    dependencies: ["medical_core", "scheduling"]
    key_entities:
      - ecg_interpretation: "12-lead ECG findings, auto-measurements"
      - echocardiogram: "Chamber sizes, EF, valve assessment"
      - cardiac_catheterization_report: "Findings, interventions, stents"
      - stress_test: "Protocol, results, interpretation"
      - holter_report: "24/48h rhythm analysis"
      - cardiac_risk_score: "Framingham, ASCVD, HEART score"
    key_features:
      - ecg_viewer: "Upload, view, annotate ECG tracings"
      - ef_trend: "Ejection fraction over time"
      - anticoagulation_tracking: "INR monitoring for warfarin patients"
      - cardiac_rehabilitation: "Exercise program tracking"
      - device_follow_up: "Pacemaker/ICD interrogation results"

  orthopedics:
    dependencies: ["medical_core", "scheduling"]
    key_entities:
      - musculoskeletal_examination: "ROM, strength, special tests per joint"
      - fracture_record: "Classification (AO/OTA), displacement, treatment"
      - joint_replacement_record: "Implant details, approach, complications"
      - physiotherapy_prescription: "Exercises, modalities, duration"
    key_features:
      - joint_diagram: "Anatomical diagrams for marking pathology"
      - rom_comparison: "Side-to-side and over-time range of motion"
      - implant_registry: "Track implanted devices for recall tracking"
      - surgical_planning: "Template-based pre-op plans"
      - post_op_score_tracking: "Oxford Knee Score, Harris Hip Score, DASH"

  pediatrics:
    dependencies: ["medical_core", "scheduling"]
    key_entities:
      - growth_record: "Weight, height/length, head circumference, BMI"
      - developmental_assessment: "Denver II, ASQ, milestones"
      - immunization_record: "Full vaccination history per schedule"
      - newborn_screening: "Metabolic, hearing, vision screening results"
      - nutrition_assessment: "Feeding history, dietary recall"
    key_features:
      - growth_chart: "WHO/CDC charts with percentile tracking"
      - immunization_scheduler: "Auto-calculate due/overdue vaccines"
      - age_calculated_dosing: "Auto-adjust doses by age/weight"
      - developmental_milestone_tracker: "Visual timeline"
      - parent_handouts: "Age-appropriate education materials"

  obstetrics_gynecology:
    dependencies: ["medical_core", "scheduling"]
    key_entities:
      - antenatal_record: "Visits, findings, investigations per gestation"
      - delivery_record: "Mode, complications, neonatal outcome"
      - postnatal_record: "Mother and baby follow-up"
      - gynecological_examination: "Speculum, bimanual, pap smear"
      - fertility_treatment_cycle: "Medications, scans, outcomes"
    key_features:
      - edd_calculator: "LMP-based, scan-based, with comparison"
      - pregnancy_timeline: "Visual gestation progress"
      - anc_schedule: "WHO/recommended visit schedule with tracking"
      - partogram: "Labor progress graph"
      - gdm_tracking: "Glucose monitoring, diet, insulin"

  ent:
    dependencies: ["medical_core", "scheduling"]
    key_entities:
      - otoscopic_examination: "Canal, TMJ findings per ear"
      - audiometry_result: "Pure tone thresholds, speech audiometry"
      - nasal_examination: "Septum, turbinates, discharge"
      - throat_examination: "Tonsils, pharynx, larynx"
      - hearing_aid_record: "Brand, model, fitting parameters"
    key_features:
      - audiogram_chart: "Interactive audiogram plotting"
      - hearing_loss_classification: "ASHA grading"
      - surgery_planning: "Tonsillectomy, septoplasty, myringotomy"
      - allergy_testing_results: "Skin prick, specific IgE"

  neurology:
    dependencies: ["medical_core", "scheduling"]
    key_entities:
      - neurological_examination: "Mental status, cranial nerves, motor, sensory, reflexes, gait"
      - eeg_report: "Background, epileptiform activity, interpretation"
      - emg_ncv_report: "Nerve conduction velocities, EMG findings"
      - headache_diary: "Frequency, severity, triggers, medications"
      - seizure_diary: "Date, duration, type, trigger, post-ictal"
    key_features:
      - seizure_tracker: "Calendar view, trigger analysis"
      - headache_calendar: "Visual pattern recognition"
      - cognitive_screening: "MoCA, MMSE tracking over time"
      - ms_disability_scale: "EDSS tracking"
      - Parkinson_rating: "UPDRS scoring"

  urology:
    dependencies: ["medical_core", "scheduling"]
    key_entities:
      - urological_examination: "Abdomen, genitalia, digital rectal exam"
      - urinalysis_record: "Dipstick, microscopy, culture"
      - uroflowmetry: "Flow rate, voided volume, residual"
      - psa_tracking: "PSA values over time with trend"
      - stone_record: "Location, size, composition, treatment"
    key_features:
      - ipss_score: "International Prostate Symptom Score"
      - psa_velocity: "Rate of change calculation"
      - stone_passage_diary: "Track stone passage"
      - catheter_log: "Type, size, date inserted, planned removal"
```

## Module: inpatient

```yaml
      module: inpatient
version: "1.0.0"
dependencies: ["medical_core", "bed_management"]
category: "facility"
installable_per: "facility"

entities:
  admission:
    fields:
      - id: "uuid"
      - admission_number: "string(30)"
      - patient_id: "uuid FK"
      - encounter_id: "uuid FK"
      - facility_id: "uuid FK"
      - department_id: "uuid FK"
      - admitting_provider_id: "uuid FK"
      - admitting_diagnosis: "array(json)"
      - admission_type: "enum(elective, emergency, transfer, maternity, observation)"
      - admission_source: "enum(er, outpatient, external_transfer, physician_referral, other)"
      - admission_date_time: "timestamp"
      - expected_discharge_date: "date nullable"
      - actual_discharge_date_time: "timestamp nullable"
      - discharge_type: "enum(recovered, improved, transferred, absconded, expired, referred, other)"
      - discharge_diagnosis: "array(json)"
      - discharge_summary: "text nullable"
      - discharge_instructions: "text nullable"
      - follow_up_date: "date nullable"
      - status: "enum(admitted, in_progress, discharge_pending, discharged)"
      - insurance_approval_number: "string nullable"
      - room_assignment_history: "array(json)"
      - metadata: "jsonb"

  bed_assignment:
    fields:
      - id: "uuid"
      - admission_id: "uuid FK"
      - bed_id: "uuid FK"
      - assigned_at: "timestamp"
      - released_at: "timestamp nullable"
      - assigned_by: "uuid FK"
      - reason_for_move: "text nullable"

  nursing_care_plan:
    fields:
      - id: "uuid"
      - admission_id: "uuid FK"
      - patient_id: "uuid FK"
      - assessments: "array(json)"
        structure:
          - type: "enum(admission, shift, as_needed, discharge)"
            date_time: "timestamp"
            performed_by: "uuid FK"
            findings: "jsonb"
            score: "string nullable (e.g., Braden score, Morse fall scale)"
      - nursing_diagnoses: "array(json)"
      - interventions: "array(json)"
      - outcomes: "array(json)"
      - evaluation_notes: "text nullable"

  medication_administration_record:
    fields:
      - id: "uuid"
      - admission_id: "uuid FK"
      - patient_id: "uuid FK"
      - prescription_item_id: "uuid FK"
      - scheduled_time: "timestamp"
      - administered_time: "timestamp nullable"
      - administered_by: "uuid FK nullable"
      - status: "enum(given, held, refused, missed, delayed)"
      - dose_given: "string"
      - route_given: "string"
      - site: "string nullable"
      - reason_if_held: "text nullable"
      - adverse_reaction: "text nullable"
      - witnessed_by: "uuid FK nullable"
      - notes: "text nullable"

  fluid_balance:
    fields:
      - id: "uuid"
      - admission_id: "uuid FK"
      - patient_id: "uuid FK"
      - date: "date"
      - shift: "enum(morning, evening, night, 24h_total)"
      - intake: "jsonb"
        structure:
          - oral: "decimal (ml)"
          - iv_fluids: "decimal (ml)"
          - iv_medications: "decimal (ml)"
          - blood_products: "decimal (ml)"
          - tube_feeding: "decimal (ml)"
          - other: "decimal (ml)"
          - total: "decimal (ml) auto-calculated"
      - output: "jsonb"
        structure:
          - urine: "decimal (ml)"
          - feces: "string (estimated or measured)"
          - vomit: "decimal (ml)"
          - nasogastric: "decimal (ml)"
          - drain: "decimal (ml)"
          - other: "decimal (ml)"
          - total: "decimal (ml) auto-calculated"
      - balance: "decimal (ml) auto-calculated"
      - recorded_by: "uuid FK"
      - notes: "text nullable"

features:
  - admission_workflow:
      steps:
        1. "Create admission order (from ER, OPD, or direct)"
        2. "Verify bed availability"
        3. "Assign bed"
        4. "Complete admission assessment"
        5. "Activate medication administration schedule"
        6. "Initiate nursing care plan"
        7. "Notify relevant departments (dietary, pharmacy, lab)"
  - discharge_workflow:
      steps:
        1. "Discharge order by attending physician"
        2. "Complete discharge medication reconciliation"
        3. "Generate discharge summary"
        4. "Schedule follow-up appointments"
        5. "Process billing"
        6. "Release bed"
        7. "Patient education and instructions"
  - ward_dashboard:
      - bed_status_board: "Color-coded bed occupancy"
      - patient_list_per_ward: "With key indicators"
      - tasks_per_nurse: "Medication due, vitals due, assessments due"
      - alerts_summary: "Critical values, falls risk, etc."
  - shift_handover:
      - structured_handover_template
      - isbar_format: "Identify, Situation, Background, Assessment, Recommendation"
      - electronic_sign_off: "Outgoing and incoming nurse sign"
  - ward_rounds:
      - patient_list_for_rounding
      - quick_vitals_entry
      - quick_note_entry
      - order_entry_during_rounds
      - task_assignment_to_nursing
```

## Module: bed_management

```yaml
      module: bed_management
version: "1.0.0"
dependencies: ["organization"]
category: "facility"
installable_per: "facility"

entities:
  ward:
    fields:
      - id: "uuid"
      - facility_id: "uuid FK"
      - name: "string(100)"
      - code: "string(20)"
      - type: "enum(general, icu, nicu, picu, maternity, surgical, medical, isolation, step_down, other)"
      - floor: "integer"
      - location_description: "string(255)"
      - total_beds: "integer"
      - nursing_station_phone: "string(30) nullable"
      - in_charge_nurse_id: "uuid FK nullable"
      - working_hours: "jsonb"
      - visitor_policy: "text nullable"
      - status: "enum(active, inactive, maintenance)"

  bed:
    fields:
      - id: "uuid"
      - ward_id: "uuid FK"
      - bed_number: "string(20)"
      - type: "enum(standard, electric, pediatric, incubator, isolation_negative_pressure, isolation_positive_pressure, other)"
      - side: "enum(left, right, center, window)"
      - position: "json (x, y coordinates for floor plan)"
      - equipment_attached: "array(string)"
        options: ["oxygen_outlet", "suction", "call_bell", "monitoring_port", "iv_pole", "bedside_monitor"]
      - current_status: "enum(available, occupied, reserved, maintenance, blocked)"
      - current_patient_admission_id: "uuid FK nullable"
      - current_patient_name: "string nullable (denormalized for performance)"
      - cleaning_status: "enum(clean, dirty, cleaning_in_progress)"
      - last_cleaned_at: "timestamp nullable"

  bed_reservation:
    fields:
      - id: "uuid"
      - bed_id: "uuid FK"
      - patient_id: "uuid FK nullable"
      - reserved_for: "enum(admission, transfer, surgery, icu_step_down)"
      - reserved_by: "uuid FK"
      - reserved_at: "timestamp"
      - expected_utilization: "timestamp nullable"
      - released_at: "timestamp nullable"
      - status: "enum(active, utilized, released, expired)"
      - notes: "text nullable"

features:
  - real_time_bed_board:
      - visual floor plan per ward
      - color coding by status
      - click bed for details
      - drag-and-drop patient transfer
  - bed forecasting:
      - expected_discharges_today/tomorrow
      - pending admissions awaiting beds
      - occupancy trends
  - bed turnover_tracking:
      - average_turnover_time
      - cleaning turnaround time
  - infection_control:
      - isolation bed management
      - cohort nursing assignment
      - contact tracing by bed proximity
```

## Module: emergency

```yaml
      module: emergency
version: "1.0.0"
dependencies: ["medical_core"]
category: "facility"
installable_per: "facility"

entities:
  er_visit:
    fields:
      - id: "uuid"
      - visit_number: "string(30)"
      - patient_id: "uuid FK"
      - facility_id: "uuid FK"
      - arrival_datetime: "timestamp"
      - arrival_mode: "enum(walk_in, ambulance, police, transferred, other)"
      - triage:
          level: "enum(resuscitation, emergent, urgent, less_urgent, non_urgent)"
          score_system: "enum(esi, manchester, ctsi)"
          score: "integer"
          chief_complaint: "string"
          vital_signs_at_triage: "json"
          triaged_by: "uuid FK"
          triaged_at: "timestamp"
      - assigned_provider_id: "uuid FK nullable"
      - assigned_bed_id: "uuid FK nullable"
      - disposition: "enum(discharged, admitted, transferred, expired, left_without_being_seen, left_against_medical_advice)"
      - disposition_datetime: "timestamp nullable"
      - disposition_destination: "string nullable"
      - key_times:
          triage_to_provider_minutes: "integer nullable"
          provider_to_disposition_minutes: "integer nullable"
          total_er_duration_minutes: "integer nullable"

  er_board:
    description: "Real-time ER dashboard"
    columns:
      - triage: "Patients awaiting triage"
      - to_be_seen: "Triaged, awaiting provider"
      - in_progress: "With provider"
      - pending_results: "Awaiting lab/imaging"
      - pending_disposition: "Decision made, awaiting bed/discharge"
      - admitted_awaiting_bed: "Will be admitted, no bed yet"

features:
  - triage_workflow: "Structured triage form with auto-level suggestion"
  - fast_track: "Low-acuity stream for quick discharge"
  - trauma_activation: "One-button trauma team notification"
  - er_order_sets: "Pre-packaged order sets per complaint (chest pain, abdominal pain, trauma, etc.)"
  - er_note_template: "Structured ER note with chief complaint, history, exam, orders, disposition"
  - boarding_management: "Track admitted patients awaiting inpatient beds"
  - er_metrics:
      - door_to_triage_time
      - door_to_provider_time
      - door_to_disposition_time
      - left_without_being_seen_rate
      - er_utilization_rate
      - mortality_rate
```

## Module: surgery

```yaml
      module: surgery
version: "1.0.0"
dependencies: ["medical_core"]
category: "facility"
installable_per: "facility"

entities:
  surgical_case:
    fields:
      - id: "uuid"
      - case_number: "string(30)"
      - patient_id: "uuid FK"
      - encounter_id: "uuid FK"
      - facility_id: "uuid FK"
      - primary_surgeon_id: "uuid FK"
      - assistant_surgeon_ids: "array(uuid)"
      - anesthesiologist_id: "uuid FK"
      - scrub_nurse_id: "uuid FK nullable"
      - circulating_nurse_id: "uuid FK nullable"
      - proposed_procedures: "array(json)"
        structure:
          - procedure_name: "string"
            cpt_code: "string"
            laterality: "enum(left, right, bilateral, n/a)"
            approach: "string nullable"
          - diagnosis: "array(json)"
          - asa_class: "enum(1, 2, 3, 4, 5, 6)"
          - surgical_priority: "enum(elective, urgent, emergency)"
          - estimated_duration_minutes: "integer"
          - estimated_blood_loss: "enum(minimal, moderate, significant, massive)"
          - consent_signed: "boolean"
          - consent_document_id: "uuid FK nullable"
          - pre_op_checklist_completed: "boolean"
          - anesthesia_type: "enum(general, spinal, epidural, regional, local, sedation, combined)"
          - scheduled_date: "date"
          - scheduled_or_room_id: "uuid FK nullable"
          - scheduled_start_time: "time"
          - actual_or_room_id: "uuid FK nullable"
          - actual_start_time: "timestamp nullable"
          - actual_end_time: "timestamp nullable"
          - actual_procedures: "array(json)"
          - findings: "text nullable"
          - complications: "text nullable"
          - specimens: "array(json)"
            structure:
              - description: "string"
                sent_to: "enum(pathology, microbiology, cytology, other)"
                lab_number: "string nullable"
          - implant_used: "array(json)"
            structure:
              - name: "string"
                manufacturer: "string"
                serial_number: "string"
                lot_number: "string"
                size: "string"
          - blood_products_used: "array(json)"
          - status: "enum(scheduled, pre_op, in_or, post_op, completed, cancelled, postponed)"
          - cancellation_reason: "text nullable"

  or_room:
    fields:
      - id: "uuid"
      - facility_id: "uuid FK"
      - name: "string(50)"
      - type: "enum(general, cardiac, ortho, neuro, ophthalmic, endoscopy, c_section, other)"
      - availability_schedule: "jsonb"
      - equipment_list: "array(string)"
      - status: "enum(available, in_use, cleaning, maintenance, reserved)"

  pre_op_checklist:
    fields:
      - id: "uuid"
      - case_id: "uuid FK"
      - patient_id: "uuid FK"
      - items: "array(json)"
        structure:
          - item: "string"
            category: "enum(consent, labs, imaging, anesthesia_eval, blood_type_crossmatch, npo_status, jewelry_removal, site_marking, antibiotic_prophylaxis, dvt_prophylaxis, equipment_check, other)"
            completed: "boolean"
            completed_by: "uuid FK nullable"
            completed_at: "timestamp nullable"
            comments: "text nullable"
      - who_sign_off:
          nurse: "uuid FK nullable"
          anesthesiologist: "uuid FK nullable"
          surgeon: "uuid FK nullable"
          signed_at: "timestamp nullable"

  post_op_orders:
    fields:
      - id: "uuid"
      - case_id: "uuid FK"
      - patient_id: "uuid FK"
      - diet: "enum(npo, clear_liquids, full_liquids, soft, regular, other)"
      - activity: "enum(bed_rest, bathroom_privileges, up_ad_lib, other)"
      - iv_fluids: "json nullable"
      - pain_management: "json nullable"
      - dvt_prophylaxis: "json nullable"
      - drain_care: "json nullable"
      - wound_care: "json nullable"
      - follow_up_imaging: "json nullable"
      - lab_orders: "array(json)"
      - notes: "text nullable"

features:
  - or_scheduling_board:
      - daily/weekly view of all OR rooms
      - drag-and-drop case scheduling
      - conflict detection
      - turnaround time tracking between cases
  - surgical_safety_checklist:
      - who_compliant: "Sign In, Time Out, Sign Out"
      - mandatory_before_incision: "Cannot proceed without Time Out completion"
  - sponge_count:
      - pre_incision_count
      - before_closure_count
      - final_count
      - discrepancy_alert: "Immediate notification, cannot close until resolved"
  - or_utilization_analytics:
      - utilization_rate per room
      - turnover time
      - cancellation rate and reasons
      - first_case_on-time start rate
      - surgeon-specific metrics
  - implant_registry:
      - track all implanted devices
      - recall notification integration
      - patient notification for recalled implants
```

## Module: laboratory

```yaml
      module: laboratory
version: "1.0.0"
dependencies: ["medical_core"]
category: "facility"
installable_per: "facility"

entities:
  test_catalog:
    fields:
      - id: "uuid"
      - code: "string (LOINC or local)"
      - name: "string"
      - category: "enum(hematology, chemistry, microbiology, serology, molecular, histopathology, cytology, immunology, toxicology, special)"
      - specimen_requirements: "array(json)"
        structure:
          - specimen_type: "enum(blood, serum, plasma, urine, stool, csf, sputum, swab, tissue, body_fluid, other)"
            container: "string (e.g., 'EDTA tube', 'plain tube', 'urine container')"
            volume: "string (e.g., '5ml')"
            temperature: "enum(room_temp, refrigerated, frozen, warm)"
            stability_hours: "integer nullable"
            fasting_required: "boolean"
      - result_parameters: "array(json)"
        structure:
          - parameter_name: "string"
            loinc_code: "string nullable"
            unit: "string"
            reference_ranges: "array(json)"
              structure:
                - age_group: "string (e.g., '0-1 year', 'adult male')"
                  sex: "enum(male, female, both)"
                  low: "decimal"
                  high: "decimal"
                  critical_low: "decimal nullable"
                  critical_high: "decimal nullable"
            data_type: "enum(numeric, text, coded, multiple_choice)"
            options: "array(string) nullable — for coded/multiple_choice"
            default_value: "string nullable"
      - turnaround_time_minutes: "integer"
      - price: "decimal nullable"
      - method: "string nullable"
      - status: "enum(active, inactive)"

  specimen:
    fields:
      - id: "uuid"
      - specimen_number: "string(30) — barcode"
      - order_id: "uuid FK"
      - patient_id: "uuid FK"
      - encounter_id: "uuid FK nullable"
      - specimen_type: "string"
      - container: "string"
      - collection_datetime: "timestamp nullable"
      - collected_by: "uuid FK nullable"
      - received_datetime: "timestamp nullable"
      - received_by: "uuid FK nullable"
      - rejection:
          rejected: "boolean"
          reason: "enum(hemolyzed, clotted, insufficient_volume, wrong_container, mislabeled, expired, other) nullable"
          rejected_by: "uuid FK nullable"
          rejected_at: "timestamp nullable"
      - status: "enum(collected, in_transit, received, processing, resulted, stored, disposed)"
      - storage_location: "string nullable"
      - tests: "array(string) — test codes to perform"

  lab_result:
    fields:
      - id: "uuid"
      - specimen_id: "uuid FK"
      - order_id: "uuid FK"
      - test_code: "string"
      - parameter_results: "array(json)"
        structure:
          - parameter_name: "string"
            value: "string"
            unit: "string"
            reference_range: "string"
            abnormal_flag: "enum(high, low, critical_high, critical_low, normal, abnormal_text) nullable"
            comment: "text nullable"
      - methodology: "string nullable"
      - performed_by: "uuid FK"
      - performed_at: "timestamp"
      - verified_by: "uuid FK nullable"
      - verified_at: "timestamp nullable"
      - status: "enum(preliminary, final, corrected, cancelled)"
      - correction_reason: "text nullable"
      - instrument_id: "string nullable"

  microbiology_specific:
    culture:
      fields:
        - id: "uuid"
        - specimen_id: "uuid FK"
        - culture_type: "enum(blood, urine, stool, sputum, wound, csf, other)"
        - media_used: "array(string)"
        - incubation_conditions: "json"
        - growth: "enum(no_growth, scant, moderate, heavy, mixed)"
        - organisms: "array(json)"
          structure:
            - organism_name: "string"
              gram_stain: "string nullable"
              quantity: "string nullable"
              identification_method: "enum(automated, manual_biochemical, malditof, pcr, other)"
              sensitivity: "array(json)"
                structure:
                  - antibiotic: "string"
                    result: "enum(sensitive, intermediate, resistant, dose_dependent)"
                    mic_value: "string nullable"
                    breakpoint: "string nullable"
        - final_report: "text nullable"
        - reported_by: "uuid FK nullable"
        - reported_at: "timestamp nullable"

features:
  - specimen_tracking:
      - barcode_generation_and_printing
      - collection_list: "By ward/department/time
      - courier_tracking: "For pickup services"
      - chain_of_custody: "Full tracking from collection to disposal"
  - analyzer_integration:
      - bidirectional_interface: "Send worklist, receive results"
      - supported_protocols: "HL7 v2.x, ASTM, serial RS-232, TCP/IP"
      - auto_verification: "Rules-based auto-verification for normal results"
      - instrument_quality_control: "Levey-Jennings charts, Westgard rules"
  - worklist_management:
      - pending_worklist: "All specimens awaiting processing"
      - by_test: "Filter by test type"
      - by_priority: "STAT vs routine"
      - by_instrument: "Assign to specific analyzer"
  - quality_control:
      - qc_sample_tracking
      - levey_jennings_charts
      - westgard_rule_violations
      - corrective_action_logs
      - proficiency_testing_tracking
  - blood_bank: "(See 7.6)"
  - outreach_management:
      - external_provider_registration
      - pickup_scheduling
      - result_delivery: "HL7, PDF, portal, fax"
      - outreach_billing
  - lab_analytics:
      - test_volume_trends
      - turnaround_time_by_test
      - rejection_rate
      - critical_value_response_time
      - revenue_per_test
```

## Module: blood_bank

```yaml
      module: blood_bank
version: "1.0.0"
dependencies: ["laboratory", "inventory"]
category: "facility"
installable_per: "facility"

entities:
  blood_donation:
    fields:
      - id: "uuid"
      - donor_id: "uuid FK"
      - donation_date: "timestamp"
      - donation_type: "enum(voluntary, replacement, autologous, apheresis)"
      - blood_product: "enum(whole_blood, prbc, ffp, platelets, cryoprecipitate)"
      - volume_ml: "decimal"
      - bag_number: "string unique"
      - blood_group: "enum(A+, A-, B+, B-, AB+, AB-, O+, O-)"
      - rh: "enum(positive, negative)"
      - screening_results: "json"
        - hiv: "enum(negative, reactive, indeterminate)"
        - hbv: "enum(negative, reactive, indeterminate)"
        - hcv: "enum(negative, reactive, indeterminate)"
        - syphilis: "enum(negative, reactive, indeterminate)"
        - malaria: "enum(negative, reactive) nullable"
        - other: "json nullable"
      - collected_by: "uuid FK"
      - status: "enum(collected, screened, safe, unsafe, quarantined, issued, expired, discarded)"

  crossmatch:
    fields:
      - id: "uuid"
      - patient_id: "uuid FK"
      - order_id: "uuid FK"
      - patient_blood_group: "string"
      - patient_rh: "string"
      - antibody_screen: "enum(negative, positive)"
      - antibody_identification: "text nullable"
      - donor_bag_id: "uuid FK"
      - donor_blood_group: "string"
      - donor_rh: "string"
      - crossmatch_result: "enum(compatible, incompatible, incompatible_major, incompatible_minor)"
      - method: "enum(gel, tube, electronic)"
      - performed_by: "uuid FK"
      - performed_at: "timestamp"
      - verified_by: "uuid FK nullable"

  blood_issue:
    fields:
      - id: "uuid"
      - crossmatch_id: "uuid FK"
      - patient_id: "uuid FK"
      - bag_id: "uuid FK"
      - issued_by: "uuid FK"
      - issued_at: "timestamp"
      - issued_to: "enum(or, ward, er, other)"
      - transfusion_started_at: "timestamp nullable"
      - transfusion_completed_at: "timestamp nullable"
      - transfused_by: "uuid FK nullable"
      - transfusion_reaction:
          occurred: "boolean"
          type: "enum(hemolytic, febrile, allergic, trali, tag, bacterial, other) nullable"
          severity: "enum(mild, moderate, severe, life_threatening) nullable"
          management: "text nullable"
          reported: "boolean"
      - status: "enum(issued, transfusing, completed, returned, expired)"

  blood_inventory:
    fields:
      - id: "uuid"
      - bag_id: "uuid FK"
      - blood_group: "string"
      - rh: "string"
      - product_type: "string"
      - storage_location: "string (e.g., 'Fridge 1, Shelf A')"
      - expiry_date: "timestamp"
      - status: "enum(available, reserved, issued, expired, discarded)"
      - reserved_for_patient_id: "uuid FK nullable"

features:
  - inventory_dashboard: "Stock levels by blood group and product, with minimum stock alerts"
  - expiry_management: "FIFO issuance, 30/15/7 day expiry warnings"
  - demand_forecasting: "Based on historical usage"
  - donor_management: "Donor registration, history, deferral tracking, recall list"
  - transfusion_reaction_reporting: "Full adverse event workflow"
  - blood_component_preparation: "Track splitting of whole blood into components"
```

## Module: radiology

```yaml
  module: radiology
version: "1.0.0"
dependencies: ["medical_core"]
category: "facility"
installable_per: "facility"

entities:
  imaging_order:
    extends: "order (type = 'imaging')"
    imaging_specific_fields:
      - modality: "enum(xray, ct, mri, ultrasound, fluoroscopy, mammography, nuclear_medicine, pet_ct, dexa, angiography, other)"
      - body_part: "string"
      - view_position: "array(string) — e.g., ['AP', 'lateral'] for X-ray"
      - contrast:
          required: "boolean"
          type: "enum(iv, oral, rectal, intra_articular, none)"
          agent: "string nullable"
          volume: "string nullable"
          concentration: "string nullable"
      - clinical_question: "text"
      - prior_imaging_comparison: "boolean"
      - pregnancy_status: "enum(confirmed, excluded, unknown, not_applicable)"
      - creatinine_level: "decimal nullable — for contrast risk assessment"
      - allergy_to_contrast: "boolean"
      - sedation_required: "boolean"
      - special_instructions: "text nullable"

  imaging_study:
    fields:
      - id: "uuid"
      - order_id: "uuid FK"
      - study_instance_uid: "string (DICOM UID)"
      - accession_number: "string(30)"
      - patient_id: "uuid FK"
      - modality: "string"
      - body_part: "string"
      - study_datetime: "timestamp"
      - performing_technologist_id: "uuid FK"
      - machine_id: "string nullable"
      - images_count: "integer"
      - dicom_series: "array(json)"
        structure:
          - series_number: "integer"
            series_description: "string"
            images_count: "integer"
            modality: "string"
      - status: "enum(scheduled, in_progress, images_acquired, awaiting_interpretation, interpreted, verified, cancelled)"
      - radiation_dose: "json nullable"
        structure:
          - dap: "decimal nullable (Gy·cm²)"
            dose_length_product: "decimal nullable (mGy·cm)"
            ct_divols: "decimal nullable (mGy)"
            effective_dose: "decimal nullable (mSv)"

  imaging_report:
    fields:
      - id: "uuid"
      - study_id: "uuid FK"
      - order_id: "uuid FK"
      - patient_id: "uuid FK"
      - interpreting_radiologist_id: "uuid FK"
      - structured_findings: "jsonb"
        example_mri_brain:
          - region: "Ventricles"
            finding: "Normal in size and configuration"
            abnormality: false
          - region: "Parenchyma"
            finding: "No focal lesion identified"
            abnormality: false
          - region: "Posterior fossa"
            finding: "Cerebellum and brainstem appear normal"
            abnormality: false
      - narrative_findings: "text"
      - impression: "text"
      - recommendation: "text nullable"
      - comparison: "text nullable — reference to prior studies"
      - critical_findings:
          has_critical: "boolean"
          critical_finding_description: "text nullable"
          critical_finding_communicated_to: "uuid FK nullable"
          critical_finding_communicated_at: "timestamp nullable"
      - report_status: "enum(draft, preliminary, final, amended, addendum)"
      - signed_at: "timestamp nullable"
      - amended_at: "timestamp nullable"
      - amendment_reason: "text nullable"

features:
  - dicom_integration:
      - dicom_worklist: "Send modality worklist to imaging machines"
      - dicom_store: "Receive and store DICOM images"
      - dicom_viewer: "Built-in zero-footprint web viewer"
        capabilities:
          - windowing_level
          - zoom_pan
          - measurements: "distance, angle, area"
          - annotations
          - mpr_recon: "Multi-planar reconstruction"
          - 3d_rendering: "Volume rendering, surface rendering"
          - fusion: "PET/CT, MRI/CT fusion"
          - hanging_protocols: "Per-study-type default layouts"
      - dicom_routing: "Route studies to specific radiologists based on modality/body part"
      - dicom_compression: "Lossless JPEG 2000 storage"
  - radiologist_worklist:
      - unread_studies_queue
      - priority_sorting: "STAT first, then by wait time"
      - filter_by_modality_body_part
      - prior_study_comparison: "Side-by-side with prior studies"
      - voice_dictation: "Integrated dictation for report narrative"
      - structured_reporting: "Template-based for common studies (mammography BI-RADS, lung nodule Lung-RADS, etc.)"
  - critical_value_communication:
      - mandatory_read_back: "Receiving provider must read back critical finding"
      - timeout_escalation: "If not acknowledged within 30 minutes, escalate to department head"
  - radiation_safety:
      - dose_tracking_per_study
      - cumulative_patient_dose
      - dose_alerts: "Alert if cumulative dose exceeds thresholds"
      - regulatory_reporting: "Generate dose reports for regulatory bodies"
  - scheduling:
      - modality-specific_schedules: "Different slots for MRI (30-60 min) vs X-ray (5-10 min)"
      - contrast_preparation_reminder: "Alert for creatinine check before contrast
      - prep_instructions: "Auto-send preparation instructions to patient"
  - teleradiology:
      - outsource_read: "Send studies to external teleradiology service"
      - receive_read: "Accept incoming teleradiology interpretations"
      - hl7_integration: "Send/receive via HL7"
```

## Module: pharmacy

```yaml
      module: pharmacy
version: "1.0.0"
dependencies: ["medical_core", "inventory"]
category: "facility"
installable_per: "facility"

entities:
  pharmacy_prescription:
    extends: "prescription (with pharmacy-specific workflow)"
    pharmacy_fields:
      - dispensing_facility_id: "uuid FK"
      - dispensing_pharmacist_id: "uuid FK nullable"
      - dispensing_started_at: "timestamp nullable"
      - dispensing_completed_at: "timestamp nullable"
      - items_dispensed: "array(json)"
        structure:
          - prescription_item_index: "integer"
            dispensed: "boolean"
            dispensed_medication_id: "uuid FK"
            dispensed_brand: "string"
            dispensed_strength: "string"
            dispensed_form: "string"
            dispensed_quantity: "decimal"
            batch_number: "string"
            expiry_date: "date"
            selling_price: "decimal"
            cost_price: "decimal"
            substitution_made: "boolean"
            substitution_reason: "text nullable"
            label_instructions: "text"
            counseling_notes: "text nullable"
      - dispense_status: "enum(pending, in_progress, ready, dispensed, partially_dispensed, returned)"
      - patient_counseled: "boolean"
      - counseling_notes: "text nullable"

  medication_stock:
    fields:
      - id: "uuid"
      - facility_id: "uuid FK"
      - medication_id: "uuid FK"
      - batch_number: "string"
      - expiry_date: "date"
      - quantity_received: "decimal"
      - quantity_current: "decimal"
      - cost_price: "decimal"
      - selling_price: "decimal"
      - supplier_id: "uuid FK"
      - supplier_invoice_number: "string nullable"
      - received_date: "date"
      - received_by: "uuid FK"
      - storage_location: "string (e.g., 'Shelf A-3, Row 2')"
      - temperature_zone: "enum(ambient, refrigerated, frozen, controlled_room)"
      - controlled_substance: "boolean"
      - schedule: "enum(I, II, III, IV, V) nullable — for controlled substances"
      - status: "enum(available, quarantined, expired, recalled, damaged, dispensed)"

  stock_movement:
    fields:
      - id: "uuid"
      - medication_stock_id: "uuid FK"
      - type: "enum(received, dispensed, returned, transferred, adjusted, expired, damaged, recalled)"
      - quantity: "decimal (positive for in, negative for out)"
      - reference_id: "uuid FK nullable — prescription, transfer order, etc."
      - reference_type: "string nullable"
      - performed_by: "uuid FK"
      - performed_at: "timestamp"
      - notes: "text nullable"
      - new_quantity: "decimal"

  pharmacy_transfer:
    fields:
      - id: "uuid"
      - from_facility_id: "uuid FK"
      - to_facility_id: "uuid FK"
      - items: "array(json)"
        structure:
          - medication_id: "uuid FK"
            medication_name: "string"
            batch_number: "string"
            quantity_requested: "decimal"
            quantity_sent: "decimal"
            quantity_received: "decimal"
      - status: "enum(requested, approved, in_transit, received, partial, cancelled)"
      - requested_by: "uuid FK"
      - approved_by: "uuid FK nullable"
      - sent_at: "timestamp nullable"
      - received_by: "uuid FK nullable"
      - received_at: "timestamp nullable"
      - notes: "text nullable"

features:
  - dispensing_workflow:
      1. "Receive prescription (internal or external)"
      2. "Validate: prescription validity, dose, interactions, allergies"
      3. "Check stock availability"
      4. "Select batch (FEFO — First Expiry First Out)"
      5. "Dispense and label"
      6. "Pharmacist clinical review"
      7. "Patient counseling"
      8. "Hand over to patient"
      9. "Record dispensing"
  - pos_interface:
      - for retail pharmacies
      - barcode scanning
      - payment integration
      - receipt printing
      - cash drawer management
  - inventory_management:
      - current_stock_dashboard
      - low_stock_alerts: "Configurable minimum stock levels"
      - expiry_alerts: "90/60/30/15 day warnings"
      - fefo_dispensing: "Auto-select earliest expiry batch"
      - stock_take: "Periodic physical count vs system count"
      - variance_reporting: "Discrepancy investigation"
  - controlled_substance_management:
      - perpetual_inventory: "Every unit tracked"
      - double_verification: "Two authorized persons for dispensing"
      - daily_reconciliation: "Opening + received - dispensed = closing"
      - wastage_documentation: "Require witness for wastage"
      - regulatory_reports: "DEA, national equivalent"
  - clinical_pharmacy:
      - therapeutic_drug_monitoring: "Track levels (vancomycin, aminoglycosides, etc.)"
      - medication_reconciliation: "On admission, transfer, discharge"
      - drug_information_service: "Query and response tracking"
      - adverse_drug_reaction_reporting: "Formal ADR reports"
      - antimicrobial_stewardship:
          - restricted_antibiotic_approval_workflow
          - days_of_therapy_tracking
          - resistance_pattern_monitoring
  - external_prescription:
      - receive_external_prescriptions: "From outside providers"
      - ocr_prescription: "Scan and OCR paper prescriptions"
      - validation: "Verify prescriber credentials"
```

## Module: icu

```yaml
      module: icu
version: "1.0.0"
dependencies: ["medical_core", "inpatient", "bed_management"]
category: "facility"
installable_per: "facility"

entities:
  icu_admission:
    extends: "admission (with ICU-specific fields)"
    icu_fields:
      - admission_source: "enum(er, or, ward, external_transfer)"
      - icu_type: "enum(medical, surgical, cardiac, neuro, pediatric, neonatal, step_down)"
      - apache_ii_score: "integer nullable"
      - sofa_score: "integer nullable"
      - gmrs_score: "integer nullable"
      - attending_intensivist_id: "uuid FK"
      - primary_nurse_id: "uuid FK"
      - ventilator_required: "boolean"
      - ventilator_mode: "enum(ac, simv, psv, cpap, prvc, hfov, other) nullable"
      - dialysis_required: "boolean"
      - isolation_required: "boolean"

  icu_flow_sheet:
    description: "High-frequency data recording (hourly or more frequent)"
    fields:
      - id: "uuid"
      - admission_id: "uuid FK"
      - patient_id: "uuid FK"
      - recorded_at: "timestamp"
      - recorded_by: "uuid FK"
      - neurology:
          - gcs: "json (eye, verbal, motor, total)"
          - pupils: "json (left_size, right_size, reactivity)"
          - sedation_level: "enum(agitated, restless, calm, sedated, unresponsive)"
          - rass_score: "integer nullable"
          - pain_score: "integer nullable"
      - cardiovascular:
          - heart_rate: "integer"
          - blood_pressure_systolic: "integer"
          - blood_pressure_diastolic: "integer"
          - map: "integer auto-calculated"
          - cvp: "decimal nullable"
          - cardiac_output: "decimal nullable"
          - rhythm: "string nullable"
          - vasoactive_agents: "array(json)"
            structure:
              - agent: "string"
                rate: "string (e.g., '5 mcg/kg/min')"
                route: "string"
      - respiratory:
          - respiratory_rate: "integer"
          - spo2: "decimal"
          - fio2: "decimal nullable"
          - peep: "decimal nullable"
          - tidal_volume: "decimal nullable"
          - peak_pressure: "decimal nullable"
          - plateau_pressure: "decimal nullable"
          - etco2: "decimal nullable"
          - sputum: "string nullable (color, quantity, consistency)"
      - fluids:
          - intake_total: "decimal (ml)"
          - output_total: "decimal (ml)"
          - balance: "decimal (ml) auto-calculated"
          - iv_fluids_running: "array(json)"
            structure:
              - fluid: "string"
                rate: "string (e.g., '100 ml/hr')"
                volume_remaining: "decimal"
          - dialysis: "json nullable"
      - labs:
          - latest_arterial_blood_gas: "json nullable"
          - latest_cbc: "json nullable"
          - latest_chemistry: "json nullable"
          - latest_coagulation: "json nullable"
      - drains_tubes_catheters: "array(json)"
        structure:
          - type: "string (e.g., 'ET tube', 'NG tube', 'urinary catheter', 'chest tube')"
            size: "string nullable"
            site: "string nullable"
            output: "decimal nullable (ml)"
            output_characteristics: "string nullable"
      - interventions: "array(json)"
        structure:
          - time: "timestamp"
            intervention: "string"
            response: "text nullable"

  icu_daily_note:
    extends: "clinical_note (type = 'icu_daily')"
    content:
      - systems_review: "Per-organ-system assessment"
      - problem_list_update: "Active problems with status change"
      - plan_per_problem: "Specific interventions per problem"
      - goals_of_care: "Code status, family discussions"
      - nutrition: "Enteral/parenteral nutrition plan"
      - sedation_and_pain_plan: "Target levels, adjustments"
      - antimicrobial_plan: "Current antibiotics, duration, de-escalation plan"
      - weaning_plan: "Ventilator weaning readiness assessment"
      - prognosis: "Estimated, communicated to family"

features:
  - icu_dashboard:
      - patient_strips: "One row per patient with key parameters"
      - color_coded_alerts: "Red for critical, yellow for caution, green for stable"
      - trend_mini-charts: "Sparkline trends for HR, BP, SpO2"
      - task_list: "Due assessments, medication times, lab draws"
  - ventilator_management:
      - ventilator_settings_tracking
      - weaning_protocol_checklist
      - spontaneous_breathing_trial_tracking
      - extubation_readiness_score
  - scoring_systems:
      - auto_calculate: "APACHE II, SOFA, Glasgow Coma Scale, RASS, CPOT, etc."
      - trend_over_time: "Score trajectories"
      - benchmark: "Compare to expected mortality"
  - icu_rounds_template:
      - structured_per-system assessment
      - quick_order_entry
      - task_assignment
  - family_communication_log:
      - family_meeting_notes
      - goals_of_care_discussions
      - consent_documentation




      additional_facility_modules:

  ambulance:
    dependencies: ["medical_core"]
    key_entities:
      - ambulance_vehicle: "Vehicle info, equipment, location, status"
      - ambulance_call: "Emergency call details, dispatch, response times"
      - ambulance_run_sheet: "Patient condition, interventions during transport, handover"
      - crew_assignment: "EMT, paramedic, driver per shift"
    key_features:
      - gps_tracking: "Real-time vehicle location"
      - dispatch_management: "Assign nearest available ambulance"
      - response_time_tracking: "Dispatch to scene, scene to hospital"
      - online_medical_direction: "Communication with base physician"

  mortuary:
    dependencies: ["medical_core"]
    key_entities:
      - body_record: "Patient info, death details, cause of death"
      - mortuary_slot: "Storage location, temperature, status"
      - body_release: "Release to family, documentation"
    key_features:
      - slot_management: "Available/occupied slots"
      - death_certificate_workflow: "Draft, review, sign"
      - chain_of_custody: "Strict tracking"
      - autopsy_coordination: "If required"

  dialysis:
    dependencies: ["medical_core", "scheduling", "inventory"]
    key_entities:
      - dialysis_prescription: "Modality, frequency, duration, dry weight, blood flow rate, dialysate composition"
      - dialysis_session: "Pre-dialysis assessment, treatment parameters, intradialytic events, post-dialysis assessment"
      - vascular_access: "Type, site, creation date, last used, complications"
    key_features:
      - recurring_session_scheduling: "3x/week, Mon-Wed-Fri patterns"
      - machine_assignment: "Track machine per patient per session"
      - treatment_parameter_logging: "Hourly vitals, UF goal, complications"
      - dry_weight_tracking: "Trend over time"
      - ktv_calculation: "Dialysis adequacy"
      - vascular_access_tracking: "Complications, interventions"

  physiotherapy:
    dependencies: ["medical_core", "scheduling"]
    key_entities:
      - physio_assessment: "Initial evaluation, functional scores, goal setting"
      - treatment_plan: "Modalities, exercises, frequency, duration"
      - treatment_session: "Session notes, modalities used, patient response"
    key_features:
      - exercise_library: " Illustrated exercise database with instructions"
      - outcome_measures: "ROM, MMT, gait analysis, functional scores"
      - home_exercise_program: "Generate patient-friendly exercise handouts"
      - progress_charts: "Visual progress tracking"
      - attendance_tracking: "Session completion rates"

  nicu:
    dependencies: ["medical_core", "inpatient", "bed_management"]
    key_entities:
      - neonatal_admission: "Birth details, gestational age, birth weight, apgar scores"
      - neonatal_flow_sheet: "High-frequency monitoring data"
      - neonatal_nutrition: "Breast milk, formula, TPN tracking"
      - neonatal_growth: "Weight, length, head circumference, growth charts (Fenton)"
    key_features:
      - fenton_growth_charts: "Preterm growth tracking"
      - apgar_scoring: "1-min and 5-min tracking"
      - kangaroo_mother_care_log: "Duration tracking"
      - parenteral_nutrition_calculator: "Per-weight calculations"
      - discharge_readiness_checklist: "Temperature stability, feeding, weight gain"

  specimen_tracking:
    dependencies: ["laboratory"]
    key_entities:
      - specimen_courier: "Courier info, route, current location"
      - specimen_pickup_request: "From external provider"
      - specimen_transit_log: "Temperature, timestamps, chain of custody"
    key_features:
      - mobile_app_for_courier: "Scan, update status, capture temperature"
      - real_time_tracking: "Specimen location at any point"
      - temperature_excursion_alerts: "If specimen goes out of range"
      - sliptime_analysis: "Collection to receipt time tracking"
```

## Module: billing

```yaml
      module: billing
version: "1.0.0"
dependencies: ["medical_core"]
category: "support"
installable_per: "tenant"

entities:
  charge_capture:
    fields:
      - id: "uuid"
      - encounter_id: "uuid FK"
      - patient_id: "uuid FK"
      - service_date: "date"
      - items: "array(json)"
        structure:
          - item_type: "enum(professional_fee, facility_fee, consumable, drug, other)"
            service_code: "string (CPT/HCPCS/local)"
            description: "string"
            quantity: "decimal"
            unit_price: "decimal"
            discount: "decimal default 0"
            tax: "decimal default 0"
            total: "decimal auto-calculated"
            performing_provider_id: "uuid FK nullable"
            department_id: "uuid FK"
            reference_order_id: "uuid FK nullable"
      - subtotal: "decimal auto-calculated"
      - total_discount: "decimal auto-calculated"
      - total_tax: "decimal auto-calculated"
      - grand_total: "decimal auto-calculated"
      - status: "enum(draft, submitted, approved, billed, partial_paid, paid, written_off, cancelled)"
      - approved_by: "uuid FK nullable"
      - approved_at: "timestamp nullable"

  invoice:
    fields:
      - id: "uuid"
      - invoice_number: "string(30)"
      - patient_id: "uuid FK"
      - encounter_id: "uuid FK nullable"
      - charge_ids: "array(uuid)"
      - subtotal: "decimal"
      - discount: "decimal"
      - tax: "decimal"
      - insurance_coverage: "decimal nullable"
      - patient_responsibility: "decimal auto-calculated"
      - payments: "array(json)"
        structure:
          - payment_id: "uuid FK"
            amount: "decimal"
            method: "string"
            date: "date"
      - balance_due: "decimal auto-calculated"
      - due_date: "date"
      - status: "enum(draft, issued, partial_paid, paid, overdue, cancelled, written_off)"
      - issued_at: "timestamp"
      - paid_at: "timestamp nullable"

  payment:
    fields:
      - id: "uuid"
      - payment_number: "string(30)"
      - invoice_id: "uuid FK"
      - patient_id: "uuid FK"
      - amount: "decimal"
      - method: "enum(cash, card, bank_transfer, mobile_payment, insurance, waiver, other)"
      - card_details:
          last_four: "string nullable"
          card_type: "string nullable"
          transaction_id: "string nullable"
      - bank_reference: "string nullable"
      - received_by: "uuid FK"
      - received_at: "timestamp"
      - receipt_number: "string(30)"
      - status: "enum(completed, refunded, failed)"

  insurance_claim:
    fields:
      - id: "uuid"
      - claim_number: "string(30)"
      - patient_id: "uuid FK"
      - insurance_id: "uuid FK"
      - invoice_id: "uuid FK"
      - encounter_id: "uuid FK"
      - claim_type: "enum(professional, institutional, pharmacy, lab, imaging, other)"
      - items: "array(json)"
        structure:
          - service_code: "string"
            diagnosis_code: "string"
            quantity: "decimal"
            charged_amount: "decimal"
            allowed_amount: "decimal nullable"
            approved_amount: "decimal nullable"
      - total_claimed: "decimal"
      - total_approved: "decimal nullable"
      - total_denied: "decimal nullable"
      - denial_reasons: "array(json) nullable"
      - copay: "decimal nullable"
      - deductible: "decimal nullable"
      - patient_responsibility: "decimal nullable"
      - status: "enum(draft, submitted, acknowledged, under_review, approved, partially_approved, denied, paid, appealed)"
      - submitted_at: "timestamp nullable"
      - adjudicated_at: "timestamp nullable"
      - paid_at: "timestamp nullable"
      - payment_reference: "string nullable"
      - appeal_deadline: "date nullable"
      - appeal_reason: "text nullable"
      - documents: "array(uuid) FK to documents"

  price_list:
    fields:
      - id: "uuid"
      - tenant_id: "uuid FK"
      - name: "string(100)"
      - effective_from: "date"
      - effective_to: "date nullable"
      - items: "array(json)"
        structure:
          - service_code: "string"
            service_name: "string"
            category: "string"
            default_price: "decimal"
            insurance_price: "decimal nullable"
            discount_eligible: "boolean"
          - is_default: "boolean"

features:
  - charge_entry:
      - manual: "Billing clerk enters charges"
      - automatic: "Triggered by encounters, orders, prescriptions"
      - fee_sheet: "Encounter-based charge capture form"
  - claims_management:
      - claim_scrubbing: "Validate before submission (missing info, code validity, etc.)"
      - electronic_submission: "EDI 837P/837I or local format"
      - remittance_processing: "Parse ERA/835 for automated payment posting"
      - denial_management: "Categorize, appeal workflow, trending"
      - authorization_tracking: "Pre-authorization status and expiry"
  - patient_billing:
      - statement_generation: "Monthly/periodic patient statements"
      - online_payment: "Patient portal payment integration"
      - payment_plan: "Installment plans for large balances"
      - collection_management: "Track overdue accounts, escalation"
  - revenue_analytics:
      - revenue_by_provider
      - revenue_by_department
      - revenue_by_service
      - collection_rate
      - days_in_ar
      - denial_rate by reason
      - net_collection_rate
  - multi_currency: "For facilities operating in multiple currencies"
  - tax_management: "Configurable tax rules by service type and region"
```

## Module: inventory

```yaml
  module: inventory
version: "1.0.0"
dependencies: ["organization"]
category: "support"
installable_per: "facility"

entities:
  item:
    fields:
      - id: "uuid"
      - tenant_id: "uuid FK"
      - item_code: "string(30) unique"
      - name: "string(255)"
      - description: "text nullable"
      - category: "enum(drug, medical_supply, lab_reagent, imaging_supply, office_supply, food, linen, cleaning, other)"
      - subcategory: "string nullable"
      - unit_of_measure: "string (e.g., 'tablet', 'ml', 'box', 'piece', 'pair', 'set')"
      - default_supplier_id: "uuid FK nullable"
      - min_stock_level: "decimal"
      - max_stock_level: "decimal"
      - reorder_quantity: "decimal"
      - lead_time_days: "integer"
      - expiry_tracking: "boolean"
      - batch_tracking: "boolean"
      - serial_tracking: "boolean"
      - temperature_sensitive: "boolean"
      - storage_conditions: "text nullable"
      - unit_cost: "decimal"
      - selling_price: "decimal nullable"
      - tax_category: "string nullable"
      - status: "enum(active, inactive, discontinued)"

  stock:
    fields:
      - id: "uuid"
      - item_id: "uuid FK"
      - facility_id: "uuid FK"
      - storage_location: "string"
      - batch_number: "string nullable"
      - serial_number: "string nullable"
      - expiry_date: "date nullable"
      - manufacturer: "string nullable"
      - quantity_on_hand: "decimal"
      - quantity_reserved: "decimal default 0"
      - quantity_available: "decimal auto-calculated (on_hand - reserved)"
      - unit_cost: "decimal"
      - status: "enum(available, quarantined, expired, damaged)"

  stock_movement:
    fields:
      - id: "uuid"
      - stock_id: "uuid FK"
      - type: "enum(purchase_received, sale_issued, transfer_out, transfer_in, adjustment_in, adjustment_out, return_to_supplier, patient_return, expired, damaged, consumed)"
      - quantity: "decimal"
      - reference_id: "uuid FK nullable"
      - reference_type: "string nullable"
      - from_location: "string nullable"
      - to_location: "string nullable"
      - performed_by: "uuid FK"
      - performed_at: "timestamp"
      - notes: "text nullable"
      - new_quantity: "decimal"

  purchase_order:
    fields:
      - id: "uuid"
      - po_number: "string(30)"
      - facility_id: "uuid FK"
      - supplier_id: "uuid FK"
      - items: "array(json)"
        structure:
          - item_id: "uuid FK"
            item_name: "string"
            quantity_ordered: "decimal"
            unit_cost: "decimal"
            total: "decimal"
            quantity_received: "decimal default 0"
      - total_amount: "decimal"
      - status: "enum(draft, submitted, approved, partially_received, received, cancelled)"
      - ordered_date: "date"
      - expected_delivery_date: "date nullable"
      - approved_by: "uuid FK nullable"
      - notes: "text nullable"

  supplier:
    fields:
      - id: "uuid"
      - tenant_id: "uuid FK"
      - name: "string(255)"
      - contact_person: "string nullable"
      - phone: "string nullable"
      - email: "string nullable"
      - address: "json nullable"
      - tax_id: "string nullable"
      - payment_terms: "string nullable (e.g., 'Net 30')"
      - rating: "integer nullable (1-5)"
      - supplied_items: "array(uuid) FK to items"
      - status: "enum(active, inactive)"

features:
  - stock_dashboard:
      - current_stock_levels
      - low_stock_items
      - expiring_soon_items
      - stock_value_summary
  - auto_reorder:
      - when_quantity_falls_below_min_stock: "Auto-generate purchase order"
      - economic_order_quantity: "Optional EOQ calculation"
  - stock_take:
      - schedule_periodic_stock_takes
      - mobile_app_for_counting: "Barcode scan, enter count"
      - variance_report: "System vs physical count"
      - adjustment_approval_workflow
  - expiry_management:
      - fefo_issuance: "First Expiry First Out"
      - expiry_alerts: "90/60/30/15/7 day warnings"
      - auto_quarantine: "Move expired items to quarantine"
      - return_to_supplier: "For items within return window"
  - demand_forecasting:
      - based_on_historical_consumption: "Rolling average, seasonal adjustment"
      - special_event_adjustment: "Manual overrides for known events"
  - multi_location:
      - transfer_between_facilities
      - transfer_between_storage_locations within facility
      - consolidated_view_across_all_facilities
  - integration_with_medical_modules:
      - pharmacy: "Drug dispensing auto-deducts from stock"
      - laboratory: "Reagent usage tracking"
      - radiology: "Contrast media tracking"
      - surgery: "Implant and consumable tracking"
      - inpatient: "Ward supplies tracking"
```

## Module: hr_payroll

```yaml
      module: hr_payroll
version: "1.0.0"
dependencies: ["organization"]
category: "support"
installable_per: "tenant"

entities:
  employee:
    extends: "user (with HR-specific fields)"
    hr_fields:
      - employee_id: "string(20)"
      - hire_date: "date"
      - employment_type: "enum(full_time, part_time, contract, locum, intern, volunteer)"
      - department_id: "uuid FK"
      - position: "string"
      - position_title: "string"
      - grade_level: "string nullable"
      - reporting_to: "uuid FK nullable"
      - salary: "decimal"
      - currency: "string(3)"
      - pay_frequency: "enum(monthly, semi_monthly, bi_weekly, weekly)"
      - bank_details: "json"
      - tax_details: "json"
      - contract_end_date: "date nullable"
      - probation_end_date: "date nullable"

  attendance:
    fields:
      - id: "uuid"
      - employee_id: "uuid FK"
      - date: "date"
      - check_in: "timestamp nullable"
      - check_out: "timestamp nullable"
      - source: "enum(biometric, rfid, manual, mobile_gps)"
      - work_hours_scheduled: "decimal"
      - work_hours_actual: "decimal nullable"
      - overtime_hours: "decimal nullable"
      - status: "enum(present, absent, late, half_day, on_leave, holiday, weekend)"
      - leave_type: "string nullable"
      - notes: "text nullable"

  leave:
    fields:
      - id: "uuid"
      - employee_id: "uuid FK"
      - leave_type: "enum(annual, sick, maternity, paternity, emergency, unpaid, study, other)"
      - start_date: "date"
      - end_date: "date"
      - days_requested: "decimal"
      - reason: "text"
      - status: "enum(requested, approved, rejected, cancelled)"
      - approved_by: "uuid FK nullable"
      - approved_at: "timestamp nullable"
      - attachment_id: "uuid FK nullable"

  payroll:
    fields:
      - id: "uuid"
      - payroll_period: "string (e.g., '2025-01')"
      - employee_id: "uuid FK"
      - basic_salary: "decimal"
      - allowances: "array(json)"
        structure:
          - type: "string (housing, transport, medical, etc.)"
            amount: "decimal"
      - deductions: "array(json)"
        structure:
          - type: "string (tax, insurance, pension, loan, etc.)"
            amount: "decimal"
      - overtime: "decimal"
      - bonus: "decimal default 0"
      - gross_pay: "decimal auto-calculated"
      - total_deductions: "decimal auto-calculated"
      - net_pay: "decimal auto-calculated"
      - pay_status: "enum(pending, processed, paid, cancelled)"
      - paid_at: "timestamp nullable"
      - payslip_generated: "boolean"
      - payslip_id: "uuid FK nullable"

  shift:
    fields:
      - id: "uuid"
      - name: "string (e.g., 'Morning', 'Evening', 'Night')"
      - start_time: "time"
      - end_time: "time"
      - facility_id: "uuid FK"
      - department_id: "uuid FK nullable"
      - break_minutes: "integer"
      - night_shift_allowance: "boolean"

  staff_scheduling:
    fields:
      - id: "uuid"
      - employee_id: "uuid FK"
      - date: "date"
      - shift_id: "uuid FK"
      - department_id: "uuid FK"
      - facility_id: "uuid FK"
      - assigned_by: "uuid FK"
      - status: "enum(scheduled, confirmed, swapped, cancelled, no_show)"
      - swap_with_employee_id: "uuid FK nullable"
      - notes: "text nullable"

features:
  - leave_management:
      - leave_balance_tracking
      - leave_calendar: "Team view of who is on leave"
      - leave_encashment: "Carry forward and encashment rules
      - leave_approval_workflow: "Multi-level approval"
  - shift_roster:
      - visual_roster_calendar: "Weekly/monthly view by department"
      - auto_schedule: "Rule-based scheduling (fair distribution, skill matching)"
      - swap_request: "Employee-initiated shift swap with approval"
      - conflict_detection: "No double-booking, minimum rest between shifts"
      - on_call_scheduling: "Separate on-call roster"
  - payroll_processing:
      - batch_payroll_run: "Process all employees for a period"
      - manual_adjustments: "One-off additions/deductions"
      - payslip_generation: "PDF payslips with detailed breakdown"
      - payslip_distribution: "Email, portal, print"
      - payroll_register: "Summary report for accounting"
  - performance:
      - kpi_tracking: "Per-role KPIs (patients seen, surgeries performed, etc.)"
      - appraisal_cycle: "Periodic appraisal workflow"
      - 360_feedback: "Multi-rater feedback"
  - compliance:
      - license_expiry_tracking: "Alerts before expiry"
      - mandatory_training: "Track completion of required trainings"
      - credentialing_status: "Verified, pending, expired"
```

## Module: accounting

```yaml
      module: accounting
version: "1.0.0"
dependencies: ["organization"]
category: "support"
installable_per: "tenant"

entities:
  chart_of_accounts:
    fields:
      - id: "uuid"
      - tenant_id: "uuid FK"
      - code: "string(20) hierarchical (e.g., '1000', '1100', '1110')"
      - name: "string(255)"
      - type: "enum(asset, liability, equity, revenue, expense)"
      - sub_type: "string nullable (e.g., 'current_asset', 'fixed_asset', 'current_liability')"
      - parent_id: "uuid FK nullable"
      - description: "text nullable"
      - is_active: "boolean"
      - default_tax_rate: "decimal nullable"

  journal_entry:
    fields:
      - id: "uuid"
      - entry_number: "string(30)"
      - tenant_id: "uuid FK"
      - date: "date"
      - description: "text"
      - reference_type: "string nullable (e.g., 'invoice', 'payment', 'payroll')"
      - reference_id: "uuid FK nullable"
      - lines: "array(json)"
        structure:
          - account_id: "uuid FK"
            account_code: "string"
            account_name: "string"
            debit: "decimal default 0"
            credit: "decimal default 0"
            description: "text nullable"
            cost_center_id: "uuid FK nullable"
      - total_debit: "decimal auto-calculated"
      - total_credit: "decimal auto-calculated"
      - status: "enum(draft, posted, reversed)"
      - posted_by: "uuid FK nullable"
      - posted_at: "timestamp nullable"

  accounts_receivable:
    - extends: "invoice (with accounting integration)"
    - aging_report: "30/60/90/120+ day buckets"
    - customer_statement: "Periodic statements"

  accounts_payable:
    fields:
      - id: "uuid"
      - bill_number: "string(30)"
      - supplier_id: "uuid FK"
      - bill_date: "date"
      - due_date: "date"
      - items: "array(json)"
        - description: "string"
          quantity: "decimal"
          unit_price: "decimal"
          total: "decimal"
          account_id: "uuid FK"
          cost_center_id: "uuid FK nullable"
      - subtotal: "decimal"
      - tax: "decimal"
      - total: "decimal"
      - status: "enum(draft, approved, partially_paid, paid, overdue, cancelled)"
      - payments: "array(json)"

  financial_report:
    - balance_sheet: "Auto-generated from chart of accounts"
    - income_statement: "Revenue vs expenses, by period"
    - cash_flow_statement: "Operating, investing, financing activities"
    - trial_balance: "Debit vs credit verification"
    - general_ledger: "Per-account transaction listing"
    - departmental_p_l: "Profit and loss per department/cost center"

features:
  - auto_journal_entries:
      - patient_payment: "Debit Cash/Bank, Credit Accounts Receivable"
      - insurance_payment: "Debit Bank, Credit Accounts Receivable"
      - payroll: "Debit Salary Expense, Credit Bank, Credit Tax Payable"
      - purchase: "Debit Inventory, Credit Accounts Payable"
      - expense: "Debit Expense, Credit Cash/Bank or Accounts Payable"
  - bank_reconciliation: "Match bank statement to system transactions"
  - multi_cost_center: "Allocate costs by department, facility, or project"
  - budget_management: "Set budgets per account/department, track variance"
  - period_management: "Open/close accounting periods, prevent backdating"
  - audit_trail: "Every journal entry change logged"
```

## Module: patient_portal

```yaml
  module: patient_portal
version: "1.0.0"
dependencies: ["medical_core"]
category: "support"
installable_per: "tenant"

features:
  registration_and_authentication:
    - self_registration: "With identity verification (OTP, national ID)"
    - login: "Email/phone + password, OTP, biometric"
    - dependent_management: "Add family members, especially for pediatrics"

  appointments:
    - view_upcoming: "List and calendar view"
    - book_new: "Available slots, provider selection"
    - reschedule: "Change date/time within policy"
    - cancel: "With reason"
    - waitlist: "Join waitlist for full slots"
    - history: "Past appointments with details"

  medical_records:
    - view_clinical_notes: "After provider release"
    - view_lab_results: "With reference ranges and interpretation notes"
    - view_imaging_reports: "With link to image viewer if enabled"
    - view_prescriptions: "Current and past"
    - view_vitals: "With trend charts"
    - view_allergies_and_conditions: "Problem list"
    - download_records: "PDF or structured format"
    - share_records: "Temporarily share with another provider"

  communications:
    - secure_messaging: "With providers/facility"
    - notifications: "Appointment reminders, result availability, billing"
    - educational_content: "Condition-specific materials"

  billing:
    - view_invoices: "Current and past"
    - make_payment: "Online payment integration"
    - payment_history: "All transactions"
    - insurance_info: "View and update insurance details"
    - estimates: "Cost estimates for planned procedures"

  documents:
    - upload: "ID, insurance card, consent forms"
    - view: "Documents shared by facility"
    - download: "Own documents"

  telemedicine:
    - join_consultation: "One-click join video call"
    - chat: "Text-based consultation"
    - waiting_room: "Virtual waiting room before consultation

  health_tools:
    - symptom_checker: "Guided triage (not diagnosis)"
    - medication_reminder: "Set reminders for current medications"
    - wellness_tracking: "Weight, blood pressure, blood glucose logging"
    - health_questionnaires: "PHQ-9, GAD-7, etc."
```
