medOS ultra

Bed Board & EHR Suite

Complete inventory of the 24-page inpatient system: floor plan, command center, 24 event handlers, bed state machine, order system.

27 min read diagramsUpdated 2026-05-26docs/architecture/bed-board-ehr-suite.md

Last updated: 2026-05-25 Status: Living document — inventory + gap analysis + roadmap


Table of Contents

  1. Executive Summary
  2. System Architecture
  3. What’s Built — Inventory
  4. Component Map
  5. Data Architecture
  6. Route Map
  7. Feature Matrix
  8. Gap Analysis & Roadmap
  9. Entity Contracts
  10. Event Flow
  11. Teaching Hospital Extensions
  12. Cross-References

1. Executive Summary

The Bed Board EHR Suite is the inpatient nervous system of medOS — a collection of 24 routed pages, 140+ components, 24 event handlers, and 6 Supabase read-model tables that together deliver a hospital-grade inpatient experience from admission request through discharge invoicing.

What it covers

┌─────────────────────────────────────────────────────────────────┐
│                    BED BOARD EHR SUITE                           │
│                                                                 │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────────┐   │
│  │ Admission │→│ Floor    │→│ Command  │→│ Discharge     │   │
│  │ Pipeline  │  │ Plan     │  │ Center   │  │ Pipeline      │   │
│  └──────────┘  └──────────┘  └──────────┘  └──────────────┘   │
│       ↕              ↕              ↕              ↕             │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────────┐   │
│  │ Nurse    │  │ Doctor   │  │ Ward     │  │ Discharge    │   │
│  │ Worklist │  │ Worklist │  │ Kanban   │  │ Cockpit      │   │
│  └──────────┘  └──────────┘  └──────────┘  └──────────────┘   │
│       ↕              ↕              ↕              ↕             │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────────┐   │
│  │ e-MAR    │  │ Ward     │  │ Code     │  │ Med          │   │
│  │          │  │ Round    │  │ Blue/RRT │  │ Reconciliatn │   │
│  └──────────┘  └──────────┘  └──────────┘  └──────────────┘   │
│       ↕              ↕              ↕              ↕             │
│  ┌──────────┐  ┌──────────┐  ┌──────────┐  ┌──────────────┐   │
│  │ Device   │  │ POCT     │  │ Case     │  │ Statistics   │   │
│  │ Capture  │  │          │  │ Present. │  │ & Census     │   │
│  └──────────┘  └──────────┘  └──────────┘  └──────────────┘   │
└─────────────────────────────────────────────────────────────────┘

By the numbers

Metric Count
Routed pages (/ipd/*) 24
React containers 24 directories
Floor plan components 17 files
Command center components 18+ files
Command center cards 6 specialized
Patient slider tabs 10 tabs
Inpatient event handlers 24 Deno modules
Supabase read-model tables 6 primary
Backend bed transitions 13 state transitions
Order channels 9 (lab, imaging, medication, procedure, pharmacy, nutrition, blood, surgery, labour)
Admission status values 8
Bed status values 6 (Supabase) / 16 (MongoDB)
Ward kanban card statuses 7
Miniapps (IPD-specific) 15+
Architecture docs 12+ files

2. System Architecture

Three-Layer Stack

┌─────────────────────────────────────────────────────────────┐
│ PRESENTATION LAYER                                          │
│                                                             │
│  Floor Plan ─── Command Center ─── Worklists ─── Dashboards│
│       │               │                │             │      │
│  BedTile    PatientSlider     ManifestWorklist    Charts    │
│  FloorGrid  SafetyCards       WorkflowTabs       Census    │
│  WardStrip  VitalsTrend       ActionButtons      Stats     │
├─────────────────────────────────────────────────────────────┤
│ DATA LAYER (Dual Source)                                    │
│                                                             │
│  ┌──────────────────────┐    ┌────────────────────────┐    │
│  │ Supabase (Read Model)│    │ MongoDB (Write Truth)  │    │
│  │                      │    │                        │    │
│  │ encounter_journey_   │    │ Bed (16 statuses)      │    │
│  │   cache              │←──│ Admission              │    │
│  │ department_queues    │    │ Encounter (IMP)        │    │
│  │ ipd_admissions_      │    │ BedAuditLog            │    │
│  │   dashboard          │    │ Ward                   │    │
│  │ ipd_ward_bed_        │    │ Room                   │    │
│  │   summaries          │    │                        │    │
│  │ ipd_ward_shift_      │    └────────────────────────┘    │
│  │   summaries          │              ↑                    │
│  │ nursing_shifts       │         REST API                  │
│  │ kanban_card_status   │    (NestJS + Moleculer)           │
│  └──────────────────────┘                                   │
│           ↑ Realtime                                        │
├─────────────────────────────────────────────────────────────┤
│ EVENT LAYER                                                 │
│                                                             │
│  hospital_events ──trigger──→ encounter-orchestrator (Deno) │
│                                    │                        │
│                        ┌───────────┼───────────┐            │
│                        ↓           ↓           ↓            │
│                  encounter_   department_  ipd_admissions_   │
│                  journey_     queues       dashboard         │
│                  cache                                       │
└─────────────────────────────────────────────────────────────┘

Bed Status State Machine

                    ┌─────────┐
          reserve   │         │  cancel_reservation
       ┌───────────→│ RESERVED│←──────────────┐
       │            │         │               │
       │            └────┬────┘               │
       │                 │ admit               │
  ┌────┴────┐            ↓                    │
  │         │  admit  ┌─────────┐             │
  │ VACANT  │────────→│         │             │
  │         │←──┐     │ADMITTED │             │
  └────┬────┘   │     │         │             │
    ↑  │        │     └──┬───┬──┘             │
    │  │ close  │        │   │                │
    │  ↓        │        │   │ discharge_     │
  ┌─┴──────────┐│        │   │ planned        │
  │OUT_OF_     ││        │   ↓                │
  │SERVICE     ││        │ ┌──────────────┐   │
  └────────────┘│        │ │ DISCHARGE    │   │
    reopen ↑    │        │ │ PENDING      │   │
                │        │ └──────┬───────┘   │
                │        │        │            │
                │        │ transfer discharge_ │
                │        │ _out   completed    │
                │        ↓        ↓            │
                │     ┌──────────────┐         │
                └─────│  CLEANING    │         │
                      │              │         │
          clean_done  └──────────────┘         │

13 Transitions: reserve · cancel_reservation · admit · transfer_in · transfer_out · discharge_planned · discharge_completed · clean_done · close · reopen (+ 3 compound variants)


3. What’s Built — Inventory

3.1 Frontend Containers (24 pages)

Container Route Purpose Status
ipd-floor-plan /ipd Ward floor plan with per-bed tiles, patient slider Production
ipd-command-center /ipd/command-center Landing hub with patient list + quick links Production
ipd-command-center (Shell) /ipd/command-center/full Multi-view ops dashboard (grid/list/card/ward/floor-mgr) Production
ipd-patient-command-center /ipd/patient/:id/command-center Per-encounter 6-step command center Production
ipd-admission-request /ipd/admission-request Admission pipeline (pending bed → admitted) Production
nurse-ipd-dashboard /ipd/dashboard Nurse IPD dashboard (manifest-driven) Production
nurse-ipd-worklist /ipd/work-list Nurse IPD worklist (manifest-driven) Production
doctor-ipd-worklist /ipd/doctor-worklist Doctor IPD worklist (manifest-driven) Production
ipd-discharge-pipeline /ipd/discharge-pipeline 7-phase discharge workflow Production
ipd-discharge-cockpit /ipd/discharge-cockpit FHIR R4 discharge summary view Production
ipd-quick-entry /ipd/quick-entry Quick vital/lab/MAR/antibiotic entry Production
ipd-ward-round /ipd/ward-round Mobile/tablet ward rounding UAT
ipd-device-capture /ipd/device-capture EKG/EST/NST device integration UAT
ipd-coverage /ipd/coverage Insurance/coverage display UAT
ipd-poct /ipd/poct Point-of-care testing entry UAT
ipd-patient-info-edit /ipd/patient-info-edit Ward-level patient info edit UAT
ipd-case-presentation /ipd/case-presentation Grand rounds / M&M / teaching cases UAT
ipd-code-blue /ipd/code-blue Code Blue / RRT event logging UAT
ipd-med-reconciliation /ipd/med-reconciliation Medication reconciliation (NPSG #3) UAT
ipd-progress-note /ipd/progress-note SOAP progress notes Demo
emar (enhanced) /ipd/emar-enhanced Enhanced e-MAR demo Demo
ipd-statistics /ipd/statistics IPD statistics dashboard Production
ipd-statistics (ward) /ipd/statistics/ward Per-ward statistics Production
ipd-uat /ipd/uat UAT hub: TOR 3.7 coverage map Internal
ipd-systems-showcase /ipd/systems IPD mini-app catalog Internal
pharmacy-ipd (pharmacy routes) IPD pharmacy dispense Production

3.2 Floor Plan Components (17 files)

ipd-floor-plan/
├── page.tsx                    # Entry point
├── types.ts                    # IpdBedRow, WardSummary, OrderChannel, etc.
├── components/
│   ├── FloorPlanGrid.tsx       # CSS grid ward renderer (smart bed sorting)
│   ├── BedTile.tsx             # Per-bed card (patient info, acuity, order chips)
│   ├── BedLegend.tsx           # Status legend
│   ├── WardSelector.tsx        # Ward picker
│   ├── WardSummaryStrip.tsx    # Ward-level stats bar
│   ├── SafetyChips.tsx         # Safety indicator chips (code status, isolation, NPO, fall risk)
│   ├── PatientSliderDrawer.tsx # Right-side patient detail drawer
│   ├── SliderHeader.tsx        # Patient banner + clinical team
│   ├── SliderVitalsTab.tsx     # Vital signs trend
│   ├── SliderOrdersTab.tsx     # Active orders by channel
│   ├── SliderChargesTab.tsx    # Running bill / charges
│   ├── SliderNotesTab.tsx      # Clinical notes
│   ├── SliderConsultsTab.tsx   # Consultation requests
│   ├── SliderAlertsTab.tsx     # CDS + safety alerts
│   ├── SliderTasksTab.tsx      # Pending tasks / reminders
│   ├── SliderTeamTab.tsx       # Care team roster
│   └── SliderActionsBar.tsx    # Discharge/transfer/order actions
├── hooks/
│   ├── useIpdFloorPlan.ts      # Floor plan data orchestration
│   ├── useIpdFloorPlanRealtime.ts  # Supabase realtime subscription
│   ├── useIpdWardSummary.ts    # Ward summary stats
│   └── useOrdersForEncounter.ts    # Per-patient order hydration
└── data/
    └── statusTokens.ts         # Status definitions + rank computation

3.3 Command Center Components (18+ files)

ipd-command-center/
├── page.tsx                            # Landing page
├── patient-command-center-page.tsx      # Per-encounter 6-step view
├── types.ts                            # IpdCommandRow (extends IpdBedRow)
├── components/
│   ├── IpdCommandCenterShell.tsx       # Multi-view ops dashboard
│   ├── IpdLandingHub.tsx               # Quick-link landing
│   ├── IpdGridView.tsx                 # DataGrid Pro view
│   ├── IpdListView.tsx                 # List/table view
│   ├── IpdCardView.tsx                 # Card gallery view
│   ├── IpdWardView.tsx                 # Single-ward floor plan
│   ├── IpdFloorMgrView.tsx             # Floor manager (multi-ward)
│   ├── ViewModeToggle.tsx              # View mode switcher
│   ├── RoleFilterChip.tsx              # Role-based filtering
│   ├── cards/
│   │   ├── PatientHeaderCard.tsx       # Patient demographics
│   │   ├── VitalsTrendCard.tsx         # Vital signs sparkline
│   │   ├── OrdersByDomainCard.tsx      # Orders by dept type
│   │   ├── SafetyIndicatorCard.tsx     # Safety flags
│   │   ├── ExceptionQueueCard.tsx      # Exception/alert queue
│   │   └── OrderStatusBadge.tsx        # Status chip renderer
│   ├── left-rail/
│   │   ├── IpdLeftRail.tsx             # Left sidebar nav
│   │   └── PendingAcksPanel.tsx        # Pending acknowledgments
│   └── right-slider/
│       ├── IpdPatientDetailSlider.tsx  # Right-side detail panel
│       ├── PatientStickyBanner.tsx     # Sticky patient header
│       ├── InlineExpander.tsx          # Expandable sections
│       └── tabs/
│           ├── VitalsTab.tsx           # Vitals
│           ├── OrdersTab.tsx           # Orders
│           ├── BedsideMarTab.tsx       # e-MAR at bedside
│           ├── MarBcmaTab.tsx          # MAR + BCMA
│           ├── NutritionTab.tsx        # Nutrition orders
│           ├── CareTeamTab.tsx         # Care team
│           ├── SafetyTab.tsx           # Safety indicators
│           ├── JourneyTab.tsx          # Patient journey
│           ├── AcknowledgementsTab.tsx  # Ack requests
│           └── AuditTab.tsx            # Audit trail
└── hooks/
    ├── useIpdCommandCenterRows.ts      # Grid data
    ├── useIpdWardSummaries.ts          # Multi-ward stats
    ├── useIpdPatientJourney.ts         # Timeline
    ├── useIpdRealtime.ts               # Realtime subscription
    ├── useIpdPendingAcks.ts            # Ack queries
    └── useIpdRoleScope.ts              # Role filtering

3.4 Backend Services

Module Location Key Methods
Bed CRUD services/administration/modules/bed/ listBed, createBed, updateBed, deleteBed
Bed Status Machine services/clinical/modules/bedStatusMachine/ 13 transitions (reserve, admit, transfer, discharge, clean, close, reopen)
Bed Request services/administration/modules/bedRequest/ Reservation management
Bed Type services/administration/modules/bedType/ Bed type configuration
Bed Audit Log services/administration/modules/bedAuditLog/ Transition audit trail
Admission Service services/administration/modules/admission/ IPD encounter creation, bed assignment, AN generation
Encounter Service services/clinical/ Multi-doctor discharge gate, coderStatus workflow

3.5 Encounter Orchestrator (24 Inpatient Handlers)

infrastructure/medbase/functions/inpatient-handlers/
├── handleAdmissionRequested.ts          # Admission event creation
├── handleAdmissionConfirmed.ts          # bed.status → admitted, queue ipd_ward_arrival
├── handleBedTransferred.ts              # Atomic dual-update (source + target bed)
├── handleDischargePlanned.ts            # Discharge order created
├── handleDischargeCompleted.ts          # Discharge finalized
├── handleOrScheduled.ts                 # OR case scheduled
├── handleOrStarted.ts                   # OR case started
├── handlePacuAdmitted.ts               # PACU admission
├── handlePorterRequested.ts             # Transport request + ack
├── handlePorterCompleted.ts             # Transport completed
├── handleRxPrescribed.ts               # Medication prescribed
├── handleRxVerified.ts                  # Pharmacist verification
├── handleRxDispensed.ts                 # Medication dispensed
├── handleMedicationHoldRelease.ts       # Medication hold/release cycle
├── handleMedicationSafetyVerdict.ts     # Safety checking verdict
├── handleCertIssued.ts                  # Certificate issued
├── handleAdrReported.ts                 # Adverse drug reaction
├── handleReferralReceived.ts            # Referral intake
├── handleReferralAccepted.ts            # Bridge to admission_log + auto-AN
└── README.md                            # Integration recipe

3.6 Ward Kanban System

Supabase tables:
├── nursing_shifts          # Shift instances (morning/noon/night)
├── improvement_cards       # Nurse-filed feature/bug/policy requests
├── kanban_card_status      # Drag-drop overlay (preserves source table integrity)
├── kanban_card_comments    # Per-card discussion threads
└── ward_kanban_cards (VIEW)# Union of focus_list + improvement_cards + overlay

Frontend:
├── wardKanban.service.ts   # Full CRUD + realtime + presence
└── useWardKanban.ts        # State hook

4. Component Map

4.1 Full Page Hierarchy

/ipd (IPDRoutes)
│
├── / ────────────────────────── IpdFloorPlanPage
│   ├── FloorPlanGrid
│   │   └── BedTile (×N per ward)
│   │       ├── SafetyChips (code status, isolation, NPO, fall risk)
│   │       └── OrderStatusChips (9 channels)
│   ├── WardSelector
│   ├── WardSummaryStrip
│   ├── BedLegend
│   └── PatientSliderDrawer
│       ├── SliderHeader (patient info + clinical team)
│       ├── SliderVitalsTab
│       ├── SliderOrdersTab
│       ├── SliderChargesTab
│       ├── SliderNotesTab
│       ├── SliderConsultsTab
│       ├── SliderAlertsTab
│       ├── SliderTasksTab
│       ├── SliderTeamTab
│       └── SliderActionsBar
│
├── /command-center ──────────── IpdCommandCenterPage (IpdLandingHub)
│
├── /command-center/full ─────── IpdCommandCenterShell
│   ├── ViewModeToggle (grid | list | card | ward | floor-mgr)
│   ├── RoleFilterChip
│   ├── IpdLeftRail + PendingAcksPanel
│   ├── [View]:
│   │   ├── IpdGridView (DataGrid Pro)
│   │   ├── IpdListView
│   │   ├── IpdCardView
│   │   ├── IpdWardView (reuses FloorPlanGrid)
│   │   └── IpdFloorMgrView
│   └── IpdPatientDetailSlider
│       ├── PatientStickyBanner
│       ├── PatientHeaderCard
│       ├── VitalsTrendCard
│       ├── OrdersByDomainCard
│       ├── SafetyIndicatorCard
│       ├── ExceptionQueueCard
│       └── Tabs: Vitals | Orders | BedsideMAR | MarBcma | Nutrition
│                 CareTeam | Safety | Journey | Acks | Audit
│
├── /patient/:id/command-center ─ PatientCommandCenter
│   ├── Step1AdmitPanel
│   ├── Step2AssessmentPanel
│   ├── Step3CarePanel
│   ├── Step4ProcedurePanel
│   ├── Step5DischargePanel
│   └── Step6CloseoutPanel
│
├── /admission-request ───────── IpdAdmissionRequestPage
│   └── WardBedVisualizer (DnD bed assignment)
│
├── /dashboard ───────────────── NurseIpdDashboardPage (manifest-driven)
│   └── WardViewSupabase (realtime bed cards)
│
├── /work-list ───────────────── NurseIpdWorklistPage (manifest-driven)
├── /doctor-worklist ─────────── DoctorIpdWorklistPage (manifest-driven)
│
├── /discharge-pipeline ──────── IpdDischargePipelinePage (7 phases)
├── /discharge-cockpit ───────── IpdDischargeCockpitPage (FHIR R4)
│
├── /ward-round ──────────────── IpdWardRoundDemo
├── /device-capture ──────────── IpdDeviceCaptureDemo
├── /coverage ────────────────── IpdCoverageDemo
├── /poct ────────────────────── IpdPoctDemo
├── /quick-entry ─────────────── IpdQuickEntryPage
├── /med-reconciliation ──────── IpdMedReconciliationPage
├── /code-blue ───────────────── IpdCodeBluePage
├── /case-presentation ───────── IpdCasePresentationPage
├── /progress-note ───────────── IPDProgressNoteDemo
├── /emar-enhanced ───────────── EmarEnhancedDemo
├── /statistics ──────────────── IpdStatisticsPage
├── /statistics/ward ─────────── IpdWardStatisticsPage
├── /uat ─────────────────────── IpdUatLanding
└── /systems ─────────────────── IpdSystemsShowcasePage

5. Data Architecture

5.1 Supabase Read-Model Tables

Table Purpose Key Columns Realtime?
encounter_journey_cache Per-encounter clinical snapshot encounter_id, patient_id, clinical_context.admission_context, pending_tickets, safety_snapshot Yes
department_queues Operational worklist rows dept_type, ticket_id, encounter_id, status, priority, location_id Yes
ipd_admissions_dashboard Denormalized active admissions admission_id, encounter_id, ward_id, bed_number, *_status (9 channels) Yes
ipd_ward_bed_summaries Per-ward bed counts ward_id, total_beds, available_beds, occupied_beds, pending_discharge Yes
ipd_ward_shift_summaries Patient movement per shift ward_id, shift_type, carry_over, admitted, discharged, deceased Yes
nursing_shifts Shift sprint instances ward, shift_type, shift_date, charge_nurse, status Yes

5.2 MongoDB Entities (Write Truth)

Entity Key Fields Relationships
Bed code, name, status (16 values), ward, room, bedType, gender, age → Ward, Room, BedType; ← Admission.bedNumber
Ward code, name, wardType, floor, building → many Beds
Room code, name, roomType, ward → Ward; → many Beds
Admission status, approvalStatus, bedNumber, encounterIpd, encounterID → Bed, → Encounter (IMP), → Encounter (source OPD/ER)
Encounter (IMP) encounterClass: 'IMP', status, coderStatus, dischargedAt ← Admission.encounterIpd
BedAuditLog bed, fromStatus, toStatus, transitionedBy, timestamp → Bed

5.3 Status Enum Mapping

MongoDB Bed (16)                    Supabase Bed (6)
─────────────────                   ─────────────────
empty_bed           ──────────────→ vacant
have_patient        ──────────────→ admitted
have_reservation    ──────────────→ reserved
regis_bed           ──────────────→ reserved
pending             ──────────────→ reserved
wait_clean          ──────────────→ cleaning
wait_discharge      ──────────────→ discharge_pending
closed              ──────────────→ out_of_service
select_bed          ──────────────→ vacant
+ 7 more substates  ──────────────→ (mapped to nearest)

5.4 IpdBedRow — The Core Data Shape

The IpdBedRow interface (ipd-floor-plan/types.ts) is the canonical client-side shape for one bed:

Category Fields
Identity admission_id, encounter_id, hn, patient_name
Location ward_id, ward_name, bed_number
Timing admission_date, los_days, expected_discharge_date, last_updated
Status status, admit_type
Orders (9 channels) lab_status, imaging_status, medication_status, procedure_status, pharmacy_status, nutrition_status, blood_status, surgery_status, labour_status
Clinical team primary_doctor, attending_physician, fellow_physician, resident_physician, intern_physician, team_name, clinical_unit
Safety / Acuity code_status, isolation_type, npo, fall_risk, pressure_ulcer_risk, pain_score, gcs_total, map_mmhg, ews_score, on_respirator, on_inotrope, blood_type, allergy_summary
Tasks pending_tasks[], tasks_pending_count, consult_pending_count, resident_note_signed
Rounding rounded_today, rounded_at
Financial payor

6. Route Map

6.1 Admission-to-Discharge Flow

Patient Arrives (OPD/ER)
       │
       ↓
┌──────────────────────┐
│ /ipd/admission-request│ ← Admission pipeline
│  4 states:           │
│  pending-bed         │
│  bed-reserved        │
│  ready-to-admit      │
│  admitted            │
└──────────┬───────────┘
           │
    ┌──────┴──────┐
    ↓             ↓
┌──────────┐  ┌──────────────────────────┐
│ /ipd     │  │ /ipd/command-center/full │
│(floor    │  │ (5 view modes)           │
│ plan)    │  │  grid · list · card ·    │
│          │  │  ward · floor-mgr        │
└────┬─────┘  └───────────┬──────────────┘
     │                    │
     └────────┬───────────┘
              ↓
┌─────────────────────────────────────┐
│ /ipd/patient/:id/command-center     │
│  6-step per-patient workflow:       │
│  ①Admit ②Assess ③Care ④Procedure   │
│  ⑤Discharge ⑥Closeout              │
└──────────────┬──────────────────────┘
               │
    ┌──────────┼──────────────┐
    ↓          ↓              ↓
┌────────┐ ┌──────────┐ ┌──────────────┐
│/ipd/   │ │/ipd/     │ │/ipd/         │
│work-   │ │doctor-   │ │ward-round    │
│list    │ │worklist  │ │              │
│(nurse) │ │          │ │              │
└────────┘ └──────────┘ └──────────────┘
               │
               ↓
┌──────────────────────────────┐
│ /ipd/discharge-pipeline      │
│  7 phases:                   │
│  ① Doctor discharge          │
│  ② Nurse discharge           │
│  ③ Account close (ปิดบัญชี)  │
│  ④ Medical coder             │
│  ⑤ Validation (13 rules)     │
│  ⑥ Claim submission          │
│  ⑦ Invoice generation        │
└──────────────┬───────────────┘
               ↓
┌──────────────────────────────┐
│ /ipd/discharge-cockpit       │
│  FHIR R4 discharge summary   │
└──────────────────────────────┘

6.2 Supporting Routes

Route Purpose Primary User
/ipd/quick-entry Rapid vital/lab/MAR/antibiotic data entry Nurse
/ipd/emar-enhanced Electronic Medication Admin Record Nurse
/ipd/device-capture EKG/EST/NST device capture Nurse/Tech
/ipd/poct Point-of-care testing Nurse/Tech
/ipd/coverage Insurance/coverage display Admin
/ipd/patient-info-edit Ward-level patient info edit Ward clerk
/ipd/med-reconciliation Medication reconciliation (NPSG #3) Pharmacist
/ipd/code-blue Code Blue / RRT event log Code team
/ipd/case-presentation Grand rounds / M&M / journal club Attending/Resident
/ipd/statistics IPD statistics dashboard Management
/ipd/statistics/ward Per-ward census analytics Charge nurse

7. Feature Matrix

7.1 Bed Board Core Features

Feature Status Component(s) Notes
Ward floor plan grid ✅ Built FloorPlanGrid, BedTile CSS grid, smart bed sorting
Per-bed patient card ✅ Built BedTile Demographics, LOS, orders, safety
9-channel order chips ✅ Built BedTile chips lab/imaging/med/proc/pharm/nutr/blood/surg/labour
Safety indicators ✅ Built SafetyChips Code status, isolation, NPO, fall risk, pressure ulcer
Acuity scores ✅ Built BedTile fields GCS, MAP, EWS/NEWS2/MEWS, pain score
Ward summary strip ✅ Built WardSummaryStrip Total/available/occupied/pending-discharge/respirator
Ward selector ✅ Built WardSelector Multi-ward navigation
Patient detail slider ✅ Built PatientSliderDrawer 10 tabs (vitals, orders, charges, notes, consults, alerts, tasks, team, actions)
Realtime updates ✅ Built useIpdFloorPlanRealtime Supabase realtime subscription
Multi-view ops dashboard ✅ Built IpdCommandCenterShell Grid/list/card/ward/floor-mgr toggle
Per-patient command center ✅ Built 6-step panels Admit → Assess → Care → Procedure → Discharge → Closeout
DnD bed assignment ✅ Built WardBedVisualizer Drag-drop in admission request
Bed status machine ✅ Built bedStatusMachine.service.ts 13 transitions, server-validated
Bed audit trail ✅ Built bedAuditLog Every transition logged

7.2 Clinical EHR Features

Feature Status Component(s) Notes
CDS rules engine ✅ Built cdsEngine, cdsEngineDb NEWS2/MEWS/qSOFA/hypoxia/HTN/fever/sepsis seeds
CDS alert surfaces ✅ Built CdsAlertSurface, InlineCdsAlertBadge Global FAB + drawer + modal + toast + inline
e-MAR ✅ Built emar.service.ts Full medication administration records
Central order manager ✅ Built CentralOrderManager Lab/imaging/rx/nutrition orders
Drug interaction checking ✅ Built useDrugInteractionCheck Real-time allergy + interaction alerts
Voice order entry ✅ Built VoiceOrderFAB Voice-driven order creation
Vital signs charting ✅ Built DynamicGraphicSheet Flowsheet/charting component
Observation write-through ✅ Built observation-write-through.ts Unified pipeline → CDS auto-fire + EWS recompute
Patient profile system ✅ Built PatientProfile, tabs Configurable, multi-view patient chart
Nursing assessment ✅ Built IpdNursingAssessment Age-routed forms (4 brackets), 2 tabs
NANDA care plans ✅ Built nanda-care-plan miniapp NANDA-NIC-NOC nursing diagnoses
Progress notes ✅ Built ipd-progress-note SOAP format
Ward round ✅ Built ipd-ward-round Mobile/tablet rounding
Ward kanban ✅ Built wardKanban.service.ts Shift management, improvement cards, DnD
Code Blue/RRT ✅ Built ipd-code-blue Joint Commission event logging
Med reconciliation ✅ Built ipd-med-reconciliation NPSG #3 compliance
Case presentation ✅ Built ipd-case-presentation Teaching cases queue
Device capture ✅ Built ipd-device-capture EKG/EST/NST integration
POCT ✅ Built ipd-poct Point-of-care testing

7.3 Workflow Features

Feature Status Component(s) Notes
Admission request pipeline ✅ Built Manifest-driven 4 states + cancel
7-phase discharge pipeline ✅ Built Manifest-driven Doctor → Nurse → Account → Coder → Validate → Claim → Invoice
FHIR R4 discharge summary ✅ Built ipd-discharge-cockpit IPS-compliant export
Manifest worklists ✅ Built Nurse + Doctor worklists Workflow template driven
Acknowledgement system ✅ Built AcknowledgementRequest Multi-channel (app/web/email/SMS/push)
IPD dispense cycles ✅ Built dispense-cycle-runner Configurable rounds + hold rules
Policy gates ✅ Built policy_gates table Configurable workflow rules

8. Gap Analysis & Roadmap

8.1 Gaps Identified

Gap Priority Complexity Description
Bed DnD on floor plan High Medium DnD exists in admission-request but not on the main floor plan page — nurses want drag-drop bed swap directly from /ipd
Housekeeping queue High Low No dedicated cleaning crew view; cleaning beds only visible in floor plan, no dispatch/assignment for EVS staff
Bed request dashboard Medium Medium Bed requests exist in backend but no dedicated admin queue page for bed managers to triage requests
Isolation room tracker Medium Low Safety chips show isolation type per-bed, but no aggregate ward-level or hospital-level isolation tracking
Acuity-based auto-assignment Medium High No algorithm to suggest optimal bed based on acuity, gender, age, isolation requirements
Census / MoH reports Medium Medium Ward statistics exist but lack MoH-mandated census report formats (Thai สสจ, Japan MHLW, PH DOH)
Bed turnaround analytics Medium Medium Bed audit log has the data but no analytics page (avg clean time, avg LOS, turnover rate)
Inter-ward transfer wizard Low Medium Transfer is backend-complete but frontend is single-step; could use a multi-step wizard with checklist
Bed reservation calendar Low High No calendar view for future bed reservations / elective admission scheduling
Patient photo on bed tile Low Low BedTile shows text only; adding photo thumbnail from filestore
Night-shift mode Low Low No dark/low-light theme toggle specifically for night shift use
Whiteboard mode Low Medium No TV/monitor “situation display” mode with auto-scrolling wards
Family notification portal Low High No patient-family status updates (linked to QR self-service pattern)

8.2 Enhancement Opportunities

Enhancement Priority Notes
Floor plan spatial editor Medium Admin tool to visually arrange beds on a floor layout (drag rooms/beds onto a blueprint)
Predictive discharge Medium ML-based expected discharge date prediction from diagnosis + LOS patterns
Capacity forecasting Medium Predict bed availability based on scheduled admissions + avg LOS
Nurse-patient ratio tracking High Real-time ratio calculation per ward per shift, alert when threshold exceeded
Fall risk / pressure injury timers Medium Countdown timers on bed tile for repositioning reminders
Bedside barcode scanning Medium Integrate with BCMA tab for positive patient ID at medication admin
Room rate auto-calculation Medium Link bed type → rate table → running bill for automatic room charges
Clinical handoff (I-PASS / SBAR) High Structured handoff template in shift transition, currently informal (JourneyTab)

8.3 Phased Roadmap

Phase 1: Foundation Hardening (2-3 weeks)
├── Housekeeping queue + EVS dispatch
├── Nurse-patient ratio tracking
├── Clinical handoff (I-PASS format)
└── Bed turnaround analytics page

Phase 2: Operational Excellence (3-4 weeks)
├── Floor plan DnD bed swap
├── Bed request triage dashboard
├── Isolation room tracker (hospital-wide)
├── Census / MoH report templates (TH/JP/PH)
└── Night-shift mode + whiteboard/TV mode

Phase 3: Intelligence Layer (4-6 weeks)
├── Acuity-based auto-assignment engine
├── Predictive discharge model
├── Capacity forecasting dashboard
├── Fall risk / pressure injury timers
└── Floor plan spatial editor (admin)

Phase 4: Patient Engagement (3-4 weeks)
├── Family notification portal (QR-based)
├── Patient photo on bed tile
├── Bedside barcode scanning (BCMA)
└── Room rate auto-calculation

9. Entity Contracts

9.1 Admission Status Flow

                              ┌──────────────┐
                              │   REQUEST    │
                              │  (created)   │
                              └──────┬───────┘
                                     │
                              ┌──────▼───────┐
                              │   PENDING    │
                              │ (awaiting    │
                              │  bed/review) │
                              └──────┬───────┘
                                     │
                    ┌────────────────┬┴───────────────┐
                    │                │                 │
             ┌──────▼───────┐ ┌─────▼──────┐  ┌──────▼───────┐
             │  RESERVED    │ │RECEIVE     │  │ APPOINTMENT  │
             │ (bed held)   │ │PENDING     │  │ (scheduled)  │
             │              │ │ADMIT       │  │              │
             └──────┬───────┘ └─────┬──────┘  └──────┬───────┘
                    │               │                 │
                    └───────┬───────┘─────────────────┘
                            │
                     ┌──────▼───────┐
                     │   ADMITTED   │
                     │ (in ward)    │
                     └──────┬───────┘
                            │
               ┌────────────┼────────────┐
               │            │            │
        ┌──────▼──────┐     │     ┌──────▼───────┐
        │ DISCHARGED  │     │     │  CANCELLED   │
        │             │     │     │              │
        └─────────────┘     │     └──────────────┘
                            │
                     ┌──────▼───────┐
                     │ CANCEL       │
                     │ REQUEST      │
                     └──────────────┘

9.2 Encounter (IMP) Status Flow

PLANNED → ARRIVED → IN_PROGRESS → FINISHED → DISCHARGED
                                      ↓
                             (coderStatus flow)
                             AWAIT_REGISTER
                                  ↓
                             IN_PROGRESS
                                  ↓
                          PENDING_VALIDATION
                            ↓          ↓
                     ACKNOWLEDGED  VALIDATION_FAILED
                                       ↓
                              AWAIT_RECONSIDER
                                       ↓
                              (loop back to IN_PROGRESS)

10. Event Flow

10.1 Admission Event Pipeline

1. Doctor creates admission request
   └→ REST PUT /v2/administration/admissions/{id}
      └→ MongoDB Admission.status = PENDING
         └→ Moleculer event → hospital_events INSERT
            └→ trigger → encounter-orchestrator
               ├→ department_queues INSERT (dept_type='admission')
               └→ encounter_journey_cache UPDATE (admission_context)

2. Bed assigned + admission confirmed
   └→ REST PUT /v2/administration/admissions/{id}/acknowledgeadmission
      └→ MongoDB Admission.status = ADMITTED, Bed.status = HAVE_PATIENT
         └→ hospital_events (admission.confirmed)
            └→ handleAdmissionConfirmed
               ├→ Supabase bed.status = 'admitted'
               ├→ ipd_admissions_dashboard UPSERT
               ├→ department_queues INSERT (ipd_ward_arrival)
               └→ encounter_journey_cache UPDATE

3. Bed transfer
   └→ REST PUT /v2/clinical/bed-status-machine/transfer
      └→ MongoDB: source bed → empty, target bed → HAVE_PATIENT
         └→ hospital_events (bed.transferred)
            └→ handleBedTransferred
               ├→ Supabase: atomic dual-update (source=vacant, target=admitted)
               ├→ department_queues INSERT (ipd_ward_transfer_in/out)
               └→ ipd_admissions_dashboard UPDATE (ward_id, bed_number)

4. Discharge
   └→ 7-phase pipeline:
      Doctor discharge → Nurse discharge → Account close →
      Medical coder → Validation → Claim submit → Invoice
      └→ hospital_events at each phase
         └→ handleDischargePlanned / handleDischargeCompleted
            ├→ bed.status = cleaning → vacant
            ├→ ipd_admissions_dashboard DELETE
            └→ ipd_ward_bed_summaries recalc

10.2 Realtime Fan-Out

Supabase Realtime
     │
     ├── encounter_journey_cache
     │   └→ useIpdFloorPlanRealtime() → BedTile re-render
     │
     ├── department_queues
     │   └→ NurseIpdDashboard / DoctorIpdWorklist subscription
     │
     ├── ipd_admissions_dashboard
     │   └→ useIpdCommandCenterRows() → grid/list/card update
     │
     ├── ipd_ward_bed_summaries
     │   └→ useIpdWardSummary() → WardSummaryStrip update
     │
     ├── nursing_shifts
     │   └→ useWardKanban() → shift transition
     │
     └── kanban_card_status
         └→ subscribeWardKanban() → card movement

11. Teaching Hospital Extensions

For teaching hospitals (Vajira model), the bed board extends with:

Field Type Purpose
attending_physician string Attending doctor name
fellow_physician string Fellow name
resident_physician string Resident name
intern_physician string Intern/medical student name
team_name string Clinical team (e.g. “Med A — Cardio”)
clinical_unit string Academic unit
rounded_today boolean Whether ward round completed today
rounded_at timestamp Last round time
working_diagnosis string ICD-10 working diagnosis text
chief_complaint string Admission chief complaint
resident_note_signed boolean Whether resident note for today is signed
consult_pending_count number Pending consultation requests

Ward Summary Teaching Extensions

Aggregate Purpose
consults_pending Total pending consults in ward
critical_count Critically ill patients
npo_count NPO patients
isolation_count Patients in isolation
rounds_completed Teams that completed rounds
rounds_pending Teams still pending rounds
surgeries_today Scheduled surgeries for today
on_duty_team Resident/fellow on duty
tasks_pending_count Aggregate pending tasks

All teaching-hospital fields are optional — components render them fail-soft (skip chip if null/undefined).


12. Cross-References

Architecture Documents

Document Location Scope
Admission-to-Ward Unified Contract docs/architecture/admission-to-ward-unified-contract.md Entity contracts, status enums, sequence diagrams, 8 invariants
Bed Management System docs/architecture/bed-management-system.md Dual-source design, status mapping, transfer atomic transaction
IPD Floor Plan (6-part series) docs/architecture/ipd-ward-floor-plan/ Overview, grid data contract, patient slider, order actions, implementation plan, Vajira fields
IPD Command Center Deployment docs/architecture/ipd-command-center-deployment.md Multi-view shell deployment
IPD Dashboard Row Navigation docs/architecture/ipd-dashboard-row-navigation.md Click-through navigation patterns
IPD Full Lifecycle Contract docs/architecture/ipd-full-lifecycle-contract.md End-to-end admission-to-discharge contract
IPD Nursing Assessment docs/architecture/ipd-nursing-assessment.md Assessment modal, age-routed forms, write-through vitals
IPD Medication Order Master docs/architecture/ipd-medication-order-master-contracts.md 12 status enums, 7 event payloads, dispense cycles
IPD Dispense Cycles docs/architecture/ipd-dispense-cycles.md Configurable pharmacy materialization
Admission Discharge Workflow docs/IPD_ADMISSION_DISCHARGE_WORKFLOW_ARCHITECTURE.md Manifest-driven workflows, 2 pipelines, entity linkages
Ward Kanban Board docs/architecture/nursing-kanban-board.md Shift-based kanban, improvement cards
Queue Management Floater docs/architecture/queue-management-floater.md Reusable per-dept FAB + side panel
Encounter Orchestrator Triggers docs/architecture/encounter-orchestrator-triggers.md Master reference for read-model event flow

Key Source Files

File Purpose
web/src/containers/ipd-floor-plan/types.ts Canonical IpdBedRow, WardSummary, OrderChannel types
web/src/routes/IPDRoutes.tsx All IPD route definitions
services/clinical/modules/bedStatusMachine/transitionMap.ts 13-transition state machine
infrastructure/medbase/functions/encounter-orchestrator/index.ts Orchestrator dispatcher (2000+ LOC)
infrastructure/medbase/functions/inpatient-handlers/ 24 modular event processors
infrastructure/medbase/migrations/20260209_ipd_dashboard_tables.sql Core IPD read-model schema
infrastructure/medbase/migrations/20260514_ward_kanban.sql Ward kanban schema
web/src/services/supabase/ipdWard.supabase.service.ts IPD Supabase service layer
web/src/services/wardKanban.service.ts Ward kanban CRUD + realtime
web/packages/medical-kit/src/ipd-system/ 140+ files: command center, hooks, contracts

Appendix A: Order Channel Matrix

Channel Status Column Ticket Key API Type Color
Lab lab_status labRequest diagnostic.labRequest Blue
Imaging imaging_status imagingRequest diagnostic.imagingRequest Indigo
Medication medication_status medicationRequest medication.medicationRequest Green
Procedure procedure_status procedureRequest clinical.procedureRequest Orange
Pharmacy pharmacy_status productDispense medication.productDispense Teal
Nutrition nutrition_status nutritionRequest clinical.nutritionRequest Amber
Blood blood_status bloodRequest clinical.bloodRequest Red
Surgery surgery_status operatingRoomRequest medication.operatingRoomRequest Purple
Labour labour_status labourRequest clinical.labourRequest Pink

Appendix B: Bed Status Colors (UI)

Status Color Hex Use
Vacant Green #22c55e Available for assignment
Reserved Orange #f97316 Held for incoming patient
Admitted Purple #8b5cf6 Patient occupying bed
Discharge Pending Amber #f59e0b Discharge ordered
Cleaning Cyan #06b6d4 EVS cleaning in progress
Out of Service Red #ef4444 Maintenance / closed

Appendix C: IPD Miniapp Inventory

Miniapp Package Purpose
admission-request miniapps Bed reservation + admission pipeline
admission-request-workflow miniapps Manifest-driven admission
admission-tab miniapps Admission dashboard tab
ipd-admission-hp miniapps Historical admissions
ipd-progress-note miniapps SOAP progress notes
ipd-continue-oneday miniapps Same-day admission continuation
ipd-nursing-assessment (integrated) Age-routed nursing assessment
ipd-graphic-sheet (integrated) Vital signs graphing
ipd-medication-hub (integrated) Medication orders/admin
ipd-blood-reservation (integrated) Blood bank orders
ipd-sales-order-summary (integrated) Sales order tracking
ipd-order-edit-cancel (integrated) Order modification
nanda-care-plan inpatient-iter2 NANDA nursing diagnoses
cdi-query-worklist inpatient-iter2 Clinical documentation improvement
discharge-barriers inpatient-iter2 Discharge planning obstacles
hai-surveillance inpatient-iter2 Hospital-acquired infection tracking
isolation-order inpatient-iter2 Isolation management
multidisciplinary-rounding inpatient-iter2 Collaborative rounding
ipd-incident-report inpatient-iter2 Incident tracking
core-measures-tr1 inpatient-iter2 Core measure tracking
Ask Anything