EMR System Sequence Diagrams
Medical Records and Statistics System (ระบบงานเวชระเบียนและเวชสถิติ)
Document Version: 1.0
Date: September 2, 2025
Project: MediTech Hospital Information System - EMR Module
Based on: TOR ระบบเวชระเบียน.md, SRS ระบบงานเวชระเบียนและเวชสถิติ.md
Table of Contents
- Overview and Notation
- Patient Registration Flows
- Insurance Verification Flows
- Medical Visit Management Flows
- External System Integration Flows
- Multi-Channel Integration Flows
- Audit and Security Flows
- Error Handling and Fallback Flows
1. Overview and Notation
1.1 System Architecture Context
The Medical Records and Statistics System is a foundation system within the MediTech HIS ecosystem that provides: - Multi-channel patient registration capabilities - Real-time insurance eligibility verification - Patient visit management and queue integration - Master patient index and demographic management - Integration APIs for other clinical modules
1.2 Diagram Notation Legend
Actors:
👤 Patient - End user seeking medical services
👨💼 Registration Staff - Hospital registration personnel
👩⚕️ Medical Staff - Doctors, nurses, medical personnel
🤖 System - Backend services and databases
📱 Kiosk - Self-service registration terminal
📲 Mobile App - Patient mobile application
💬 Line Bot - Line messaging integration
Components:
🌐 Frontend - Web/Mobile user interfaces
⚡ API Gateway - Request routing and authentication
🔒 Auth Service - Authentication and authorization
💾 Database - PostgreSQL with Prisma ORM
🔍 Search Service - Patient search and indexing
📋 Queue Service - Queue management system
🏥 External APIs - NHSO, SSO, Civil Registry services
📤 Notification - SMS, Email, Line messaging
📊 Audit Service - Logging and compliance tracking
1.3 Response Time Requirements
Based on SRS performance requirements: - Patient Registration: ≤ 3 seconds - Patient Search: ≤ 2 seconds (exact), ≤ 5 seconds (fuzzy) - Visit Creation: ≤ 2 seconds - Insurance Verification: ≤ 5 seconds - Smart Card Reading: ≤ 5 seconds
2. Patient Registration Flows
2.1 New Patient Registration - Staff Channel
This sequence covers the complete flow of registering a new patient through the staff interface, including smart card reading, duplicate checking, and photo capture.
sequenceDiagram
participant Staff as 👨💼 Registration Staff
participant Frontend as 🌐 Staff Interface
participant API as ⚡ API Gateway
participant Auth as 🔒 Auth Service
participant SearchSvc as 🔍 Search Service
participant DB as 💾 Database
participant SmartCard as 📱 Smart Card Reader
participant PhotoSvc as 📷 Photo Service
participant AuditSvc as 📊 Audit Service
Note over Staff, AuditSvc: Patient Registration - Staff Channel (TOR 1.1.1)
Staff->>Frontend: Open patient registration form
Frontend->>API: GET /api/v1/registration/form
API->>Auth: Validate session token
Auth-->>API: Session valid
API-->>Frontend: Registration form template
Frontend-->>Staff: Display registration form
Note over Staff, AuditSvc: Smart Card Reading (TOR AC-004.3)
Staff->>Frontend: Click "Read Smart Card"
Frontend->>SmartCard: Initialize card reader
SmartCard-->>Frontend: Reader ready
Frontend->>SmartCard: Read card data
SmartCard->>SmartCard: Extract personal data
SmartCard-->>Frontend: Card data (encrypted)
Frontend->>Frontend: Auto-fill form fields
Frontend-->>Staff: Form populated with card data
Note over Staff, AuditSvc: Duplicate Checking (TOR AC-004.2)
Staff->>Frontend: Complete form entry
Frontend->>API: POST /api/v1/patients/duplicate-check
API->>SearchSvc: Check for duplicates
SearchSvc->>DB: Search by name, national_id, phone
alt Potential duplicates found
DB-->>SearchSvc: Matching records found
SearchSvc-->>API: Duplicate candidates
API-->>Frontend: Show duplicate warning
Frontend-->>Staff: Display potential matches
Staff->>Frontend: Confirm "Create New" or "Use Existing"
alt Staff selects "Use Existing"
Frontend->>API: GET /api/v1/patients/{existingId}
API->>DB: Retrieve patient data
DB-->>API: Patient data
API-->>Frontend: Existing patient data
Frontend-->>Staff: Load existing patient
Note over Staff: Flow ends - return to existing patient
end
else No duplicates found
SearchSvc-->>API: No duplicates
API-->>Frontend: Clear to proceed
end
Note over Staff, AuditSvc: Photo Capture (TOR AC-004.1)
Staff->>Frontend: Click "Capture Photo"
Frontend->>PhotoSvc: Initialize camera
PhotoSvc-->>Frontend: Camera ready
Staff->>Frontend: Take photo
Frontend->>PhotoSvc: Capture image
PhotoSvc->>PhotoSvc: Compress and validate image
PhotoSvc-->>Frontend: Photo data (base64)
Frontend-->>Staff: Show photo preview
Note over Staff, AuditSvc: Patient Creation and HN Generation
Staff->>Frontend: Submit registration
Frontend->>API: POST /api/v1/patients
API->>Auth: Validate permissions
Auth-->>API: Authorized
API->>DB: BEGIN transaction
API->>DB: INSERT INTO patients (trigger generates HN)
DB->>DB: Execute generate_hn() trigger
DB->>DB: Validate patient data trigger
DB-->>API: Patient created (with HN)
API->>PhotoSvc: Store patient photo
PhotoSvc->>PhotoSvc: Encrypt and store image
PhotoSvc-->>API: Photo path
API->>DB: UPDATE patients SET photo_path
API->>DB: COMMIT transaction
API->>AuditSvc: Log patient creation
AuditSvc->>DB: INSERT INTO patient_audit_log
API-->>Frontend: Registration success + HN
Frontend-->>Staff: Show success message with HN
Note over Staff, AuditSvc: Registration Document Generation
Frontend->>API: GET /api/v1/patients/{id}/registration-card
API->>DB: Get patient data
DB-->>API: Patient details
API->>API: Generate registration document
API-->>Frontend: PDF document
Frontend-->>Staff: Print registration card
Preconditions: - Staff is authenticated and has registration permissions - Smart card reader is connected and functional - Camera/webcam is available for photo capture
Postconditions: - New patient record created with unique HN - Patient photo stored and encrypted - Registration audit trail logged - Registration card available for printing - Patient searchable in system
Error Scenarios: - Smart card reader failure → Manual data entry fallback - Duplicate detection system failure → Manual verification required - Photo capture failure → Continue without photo (flag for later) - Database transaction failure → Rollback and retry
2.2 New Patient Registration - Kiosk Self-Service
This sequence shows patient self-registration through the kiosk interface with staff verification.
sequenceDiagram
participant Patient as 👤 Patient
participant Kiosk as 📱 Kiosk Interface
participant API as ⚡ API Gateway
participant SearchSvc as 🔍 Search Service
participant DB as 💾 Database
participant Staff as 👨💼 Registration Staff
participant StaffUI as 🌐 Staff Interface
participant QueueSvc as 📋 Queue Service
participant NotifSvc as 📤 Notification Service
Note over Patient, NotifSvc: Patient Self-Registration - Kiosk (TOR 1.1.2)
Patient->>Kiosk: Touch screen to start
Kiosk->>API: GET /api/v1/kiosk/registration/start
API-->>Kiosk: Registration form (Thai/English)
Kiosk-->>Patient: Display language selection
Patient->>Kiosk: Select language (Thai/English)
Kiosk-->>Patient: Show registration form
Note over Patient, NotifSvc: QR Code / Smart Card Reading
Patient->>Kiosk: Place ID card on reader
Kiosk->>Kiosk: Read smart card data
Kiosk->>API: POST /api/v1/kiosk/card-data
API->>SearchSvc: Check existing patient
SearchSvc->>DB: Search by national_id
alt Existing patient found
DB-->>SearchSvc: Patient found
SearchSvc-->>API: Existing patient data
API-->>Kiosk: Show existing patient info
Kiosk-->>Patient: "Welcome back! Confirm details?"
Patient->>Kiosk: Confirm or update details
Note over Patient: Flow continues to visit creation
else New patient
SearchSvc-->>API: No existing patient
API-->>Kiosk: Proceed with registration
Kiosk->>Kiosk: Auto-fill form from card data
Kiosk-->>Patient: Review and complete form
end
Patient->>Kiosk: Complete additional details
Patient->>Kiosk: Submit registration
Kiosk->>API: POST /api/v1/kiosk/registration/submit
API->>DB: Create pending_registration record
API->>QueueSvc: Add to verification queue
API-->>Kiosk: Registration submitted (pending)
Kiosk-->>Patient: "Please wait for staff verification"
Note over Patient, NotifSvc: Staff Verification Process
QueueSvc->>NotifSvc: Notify registration staff
NotifSvc->>StaffUI: Show verification alert
StaffUI-->>Staff: New kiosk registration pending
Staff->>StaffUI: Review pending registration
StaffUI->>API: GET /api/v1/registrations/pending/{id}
API->>DB: Get pending registration data
DB-->>API: Registration details
API-->>StaffUI: Show registration for review
alt Staff approves registration
Staff->>StaffUI: Approve registration
StaffUI->>API: PUT /api/v1/registrations/{id}/approve
API->>DB: Move to patients table (generate HN)
API->>DB: DELETE from pending_registrations
API->>NotifSvc: Send approval notification
API-->>StaffUI: Registration approved
NotifSvc->>Kiosk: Patient registration approved
Kiosk-->>Patient: "Registration complete! Your HN: {hn}"
else Staff requests corrections
Staff->>StaffUI: Request corrections (with notes)
StaffUI->>API: PUT /api/v1/registrations/{id}/corrections
API->>NotifSvc: Send correction request
NotifSvc->>Kiosk: Show correction needed
Kiosk-->>Patient: "Please correct the following..."
Note over Patient: Return to form completion
end
Kiosk->>API: GET /api/v1/patients/{hn}/registration-receipt
API-->>Kiosk: Registration receipt
Kiosk-->>Patient: Print registration receipt
Preconditions: - Kiosk is operational and connected to network - Smart card reader is functional - Registration staff are available for verification
Postconditions: - Patient registration created upon staff approval - Registration receipt provided to patient - Patient can proceed to visit creation or appointment
Key Features: - Multi-language support (Thai/English) - Real-time staff verification workflow - Self-service document printing - Fallback to manual data entry if card reading fails
2.3 New Patient Registration - Mobile App Pre-Registration
This sequence shows advance patient registration through the mobile app with later verification.
sequenceDiagram
participant Patient as 👤 Patient
participant MobileApp as 📲 Mobile App
participant API as ⚡ API Gateway
participant Auth as 🔒 Auth Service
participant DB as 💾 Database
participant Staff as 👨💼 Registration Staff
participant StaffUI as 🌐 Staff Interface
participant NotifSvc as 📤 Notification Service
participant QueueSvc as 📋 Queue Service
Note over Patient, QueueSvc: Mobile App Pre-Registration (TOR 1.1.3)
Patient->>MobileApp: Open MediTech app
MobileApp->>API: GET /api/mobile/registration/start
API-->>MobileApp: Registration form
Note over Patient, QueueSvc: Patient Authentication
MobileApp-->>Patient: Show registration options
Patient->>MobileApp: Select "New Patient Registration"
MobileApp-->>Patient: Phone number verification required
Patient->>MobileApp: Enter phone number
MobileApp->>API: POST /api/mobile/auth/verify-phone
API->>NotifSvc: Send OTP via SMS
NotifSvc-->>Patient: SMS with OTP code
Patient->>MobileApp: Enter OTP code
MobileApp->>API: POST /api/mobile/auth/confirm-otp
API->>Auth: Generate mobile session token
Auth-->>API: JWT token created
API-->>MobileApp: Authentication successful
Note over Patient, QueueSvc: Registration Data Entry
MobileApp-->>Patient: Show registration form
Patient->>MobileApp: Fill out personal details
Patient->>MobileApp: Upload ID card photo (front/back)
MobileApp->>MobileApp: Validate form data
Patient->>MobileApp: Submit pre-registration
MobileApp->>API: POST /api/mobile/registration/submit
API->>DB: INSERT INTO pending_mobile_registrations
API->>QueueSvc: Add to verification queue
API-->>MobileApp: Pre-registration submitted
MobileApp-->>Patient: "Pre-registration complete. Verification pending."
Note over Patient, QueueSvc: Staff Verification Process
QueueSvc->>StaffUI: New mobile registration in queue
Staff->>StaffUI: Review mobile pre-registration
StaffUI->>API: GET /api/v1/registrations/mobile/pending/{id}
API->>DB: Get mobile registration data
DB-->>API: Registration details + ID photos
API-->>StaffUI: Show registration for verification
alt Staff approves registration
Staff->>StaffUI: Approve registration
StaffUI->>API: PUT /api/v1/registrations/mobile/{id}/approve
API->>DB: Move to patients table (generate HN)
API->>DB: SET mobile_pre_registered = TRUE
API->>NotifSvc: Send approval notification
NotifSvc->>MobileApp: Push notification
NotifSvc-->>Patient: SMS with HN number
MobileApp-->>Patient: "Registration approved! HN: {hn}"
else Staff requests corrections
Staff->>StaffUI: Request more information
StaffUI->>API: PUT /api/v1/registrations/mobile/{id}/corrections
API->>NotifSvc: Send correction request
NotifSvc->>MobileApp: Push notification
MobileApp-->>Patient: "Additional information required"
end
Note over Patient, QueueSvc: First Hospital Visit
Patient->>MobileApp: "Schedule first visit"
MobileApp->>API: GET /api/mobile/patients/{hn}/visit-options
API->>DB: Get approved registration
DB-->>API: Patient data (mobile pre-registered)
API-->>MobileApp: Available departments/time slots
Patient->>MobileApp: Select department and time
MobileApp->>API: POST /api/mobile/visits/pre-book
API->>QueueSvc: Create visit with pre-registration flag
QueueSvc-->>API: Visit pre-booked
API-->>MobileApp: Visit confirmation
MobileApp-->>Patient: "Visit booked. Please arrive 15 min early for final verification"
Preconditions: - Patient has smartphone with MediTech app installed - Patient has valid phone number for OTP verification - Staff verification process is operational
Postconditions: - Patient pre-registered with HN generated - First visit can be pre-booked - Patient can expedite hospital check-in process
Key Features: - Phone number verification for security - ID card photo upload for verification - Push notifications for status updates - Integration with appointment booking
2.4 Emergency Patient Registration - Temporary HN
This sequence handles emergency situations where patient identity is unknown.
sequenceDiagram
participant MedStaff as 👩⚕️ Medical Staff
participant ERSystem as 🏥 ER System
participant API as ⚡ API Gateway
participant DB as 💾 Database
participant AuditSvc as 📊 Audit Service
participant SuperVisor as 👨💼 Supervisor
Note over MedStaff, SuperVisor: Emergency Registration - Temporary HN (TOR AC-004.5)
MedStaff->>ERSystem: Emergency patient arrived
ERSystem-->>MedStaff: Patient identity unknown/unconscious
MedStaff->>ERSystem: Create emergency registration
ERSystem->>API: POST /api/v1/patients/emergency
Note over API: Emergency Registration Parameters
Note over API: - Emergency reason<br/>- Medical staff ID<br/>- Estimated demographics<br/>- Emergency department
API->>DB: BEGIN transaction
API->>DB: INSERT INTO patients (is_temporary_hn=TRUE)
DB->>DB: Generate temporary HN (prefix: TEMP)
API->>DB: SET temporary_hn_reason, temporary_hn_created_at
API->>DB: COMMIT transaction
API->>AuditSvc: Log emergency registration
AuditSvc->>DB: INSERT INTO patient_audit_log
API-->>ERSystem: Temporary HN created: TEMP{hn}
ERSystem-->>MedStaff: Emergency patient registered
Note over MedStaff, SuperVisor: Patient Identity Discovery Process
loop Patient Identity Search
alt Patient regains consciousness
MedStaff->>ERSystem: Patient can provide identity
ERSystem->>API: POST /api/v1/patients/{tempHN}/identity-update
else Family/friend identifies patient
MedStaff->>ERSystem: Identity confirmed by relative
ERSystem->>API: POST /api/v1/patients/{tempHN}/identity-confirmed
else Medical records found
MedStaff->>ERSystem: Existing medical records located
ERSystem->>API: POST /api/v1/patients/{tempHN}/records-match
end
API->>DB: Search for existing patient
alt Existing patient found
DB-->>API: Matching patient found
API->>SuperVisor: Approval required for merge
SuperVisor->>API: Approve patient merge
API->>DB: UPDATE original patient with temp data
API->>DB: UPDATE temporary patient (merge_status='merged')
API->>DB: SET original_patient_id
API-->>ERSystem: Patients merged successfully
else New patient confirmed
API->>DB: UPDATE patient (is_temporary_hn=FALSE)
API->>DB: Generate permanent HN
API-->>ERSystem: Permanent HN assigned
end
end
Note over MedStaff, SuperVisor: Temporary HN Monitoring
loop Daily Temporary HN Review
SuperVisor->>API: GET /api/v1/patients/temporary/pending
API->>DB: SELECT * FROM patients WHERE is_temporary_hn=TRUE AND merge_status='pending'
DB-->>API: List of pending temporary registrations
API-->>SuperVisor: Show pending cases
alt Resolution found
SuperVisor->>API: Resolve temporary case
else Extended emergency care
SuperVisor->>API: Extend temporary status
else Convert to permanent
SuperVisor->>API: Convert to permanent registration
end
end
Preconditions: - Emergency medical situation exists - Patient identity cannot be immediately determined - Medical staff have emergency registration permissions
Postconditions: - Temporary HN created for immediate medical care - Audit trail for emergency registration maintained - Resolution workflow initiated for identity confirmation
Key Features: - Temporary HN with special prefix (TEMP) - Supervisor approval required for merging - Daily review process for pending cases - Complete audit trail for compliance
3. Insurance Verification Flows
3.1 Real-time NHSO Eligibility Checking
This sequence demonstrates real-time verification of National Health Security Office (สปสช.) eligibility.
sequenceDiagram
participant Staff as 👨💼 Registration Staff
participant Frontend as 🌐 Staff Interface
participant API as ⚡ API Gateway
participant EligibilitySvc as 🔍 Eligibility Service
participant NHSO as 🏥 NHSO API
participant DB as 💾 Database
participant Cache as ⚡ Redis Cache
participant AuditSvc as 📊 Audit Service
Note over Staff, AuditSvc: NHSO Real-time Eligibility Verification (FR-006)
Staff->>Frontend: Enter patient national ID
Frontend->>API: POST /api/v1/eligibility/check/nhso
Note over API: Request Parameters:<br/>- national_id: "1234567890123"<br/>- check_type: "NHSO"<br/>- service_date: "2025-09-02"
API->>Cache: Check cached eligibility
Cache-->>API: Cache miss or expired
API->>EligibilitySvc: Verify NHSO eligibility
EligibilitySvc->>EligibilitySvc: Validate national ID format
alt Valid national ID format
EligibilitySvc->>NHSO: POST /nhso/api/v1/eligibility/check
Note over EligibilitySvc, NHSO: NHSO API Request:<br/>{<br/> "citizenId": "1234567890123",<br/> "serviceDate": "2025-09-02",<br/> "hospitalCode": "12345"<br/>}
alt NHSO API Success
NHSO-->>EligibilitySvc: HTTP 200 - Eligibility Response
Note over NHSO, EligibilitySvc: NHSO Response:<br/>{<br/> "eligible": true,<br/> "schemeType": "UCS",<br/> "schemeName": "บัตรทอง",<br/> "mainHospital": "โรงพยาบาลXXX",<br/> "validUntil": "2025-12-31"<br/>}
EligibilitySvc->>DB: Store eligibility check result
EligibilitySvc->>Cache: Cache result (TTL: 4 hours)
EligibilitySvc->>AuditSvc: Log successful check
EligibilitySvc-->>API: Eligibility confirmed
else NHSO API Error
NHSO-->>EligibilitySvc: HTTP 4xx/5xx - Error Response
Note over NHSO, EligibilitySvc: Error Response:<br/>{<br/> "error": "INVALID_CITIZEN_ID",<br/> "message": "บัตรประชาชนไม่ถูกต้อง"<br/>}
EligibilitySvc->>DB: Store error result
EligibilitySvc->>AuditSvc: Log failed check
EligibilitySvc-->>API: Eligibility check failed
end
else Invalid national ID format
EligibilitySvc-->>API: Invalid ID format error
end
API-->>Frontend: Eligibility result
alt Eligible for NHSO coverage
Frontend-->>Staff: ✅ "UCS (บัตรทอง) - Valid until 2025-12-31"
Staff->>Frontend: Proceed with UCS coverage
Frontend->>API: POST /api/v1/patients/{id}/insurance/activate
API->>DB: UPDATE patient_insurance SET is_primary=TRUE
else Not eligible or error
Frontend-->>Staff: ❌ "No UCS coverage / Error occurred"
Staff->>Frontend: Check alternative insurance or cash payment
alt Staff chooses manual verification
Staff->>Frontend: "Manual verification"
Frontend->>API: POST /api/v1/eligibility/manual
API->>DB: Store manual verification (requires supervisor approval)
else Staff chooses cash payment
Staff->>Frontend: "Cash payment"
Frontend->>API: POST /api/v1/patients/{id}/insurance/cash
end
end
Note over Staff, AuditSvc: Eligibility Result Caching and Monitoring
loop Eligibility Status Monitoring
API->>DB: Check eligibility expiration
DB-->>API: Eligibilities expiring soon
API->>EligibilitySvc: Refresh expiring eligibilities
EligibilitySvc->>NHSO: Bulk eligibility refresh
NHSO-->>EligibilitySvc: Updated eligibility statuses
EligibilitySvc->>Cache: Update cached results
end
Preconditions: - Patient has valid Thai national ID - NHSO API connection is available - Staff has insurance verification permissions
Postconditions: - Eligibility status determined and cached - Insurance information updated in patient record - Audit trail created for compliance
Error Handling: - API timeout → Fallback to manual verification - Invalid response → Log error and retry - Network failure → Queue for later verification
3.2 SSO (Social Security Office) Integration
This sequence shows verification of Social Security Office eligibility for employed patients.
sequenceDiagram
participant Staff as 👨💼 Registration Staff
participant API as ⚡ API Gateway
participant EligibilitySvc as 🔍 Eligibility Service
participant SSO as 🏥 SSO API
participant DB as 💾 Database
participant NotifSvc as 📤 Notification Service
Note over Staff, NotifSvc: SSO Eligibility Verification (Social Security)
Staff->>API: POST /api/v1/eligibility/check/sso
API->>EligibilitySvc: Check SSO eligibility
EligibilitySvc->>SSO: POST /sso/api/eligibility
Note over EligibilitySvc, SSO: SSO Request:<br/>{<br/> "citizenId": "1234567890123",<br/> "employerId": "optional",<br/> "serviceDate": "2025-09-02"<br/>}
alt Patient is SSO covered
SSO-->>EligibilitySvc: SSO Coverage confirmed
Note over SSO, EligibilitySvc: SSO Response:<br/>{<br/> "eligible": true,<br/> "schemeType": "SSS",<br/> "employer": "บริษัท ABC จำกัด",<br/> "coverage": {<br/> "outpatient": true,<br/> "inpatient": true,<br/> "emergency": true<br/> },<br/> "validUntil": "2025-12-31"<br/>}
EligibilitySvc->>DB: Store SSO eligibility
EligibilitySvc-->>API: SSO eligibility confirmed
API-->>Staff: ✅ "SSO Coverage - Company: บริษัท ABC จำกัด"
else Patient not covered by SSO
SSO-->>EligibilitySvc: Not covered
EligibilitySvc-->>API: No SSO coverage
API-->>Staff: ❌ "No SSO coverage found"
end
Note over Staff, NotifSvc: Cross-verification with NHSO
alt SSO not available but NHSO eligible
Staff->>API: "Check NHSO as secondary"
API->>EligibilitySvc: Check NHSO eligibility
Note over Staff: Flow continues with NHSO verification
end
3.3 Multiple Insurance Scheme Selection
This sequence handles patients with multiple valid insurance schemes.
sequenceDiagram
participant Staff as 👨💼 Registration Staff
participant Frontend as 🌐 Staff Interface
participant API as ⚡ API Gateway
participant DB as 💾 Database
Note over Staff, DB: Multiple Insurance Scheme Selection (FR-006.2)
Staff->>Frontend: Complete eligibility checks
Frontend->>API: GET /api/v1/patients/{id}/insurance/all
API->>DB: Get all valid insurance schemes
DB-->>API: Multiple schemes found
Note over DB, API: Found Schemes:<br/>1. UCS (NHSO) - Primary<br/>2. SSS (SSO) - Secondary<br/>3. Private Insurance - Active
API-->>Frontend: Available insurance options
Frontend-->>Staff: Show insurance selection dialog
Staff->>Frontend: Select primary insurance for this visit
Frontend->>API: POST /api/v1/visits/{id}/insurance/select
Note over API: Request:<br/>{<br/> "visitId": "uuid",<br/> "primaryInsurance": "UCS",<br/> "secondaryInsurance": "SSS",<br/> "reason": "Better coverage for procedure"<br/>}
API->>DB: Update visit insurance selection
API->>DB: Log insurance selection decision
API-->>Frontend: Insurance selection confirmed
Frontend-->>Staff: ✅ "Using UCS as primary, SSS as secondary"
4. Medical Visit Management Flows
4.1 OPD Visit Creation with Multi-Department Support
This sequence shows creating outpatient visits with support for multiple departments simultaneously.
sequenceDiagram
participant Staff as 👨💼 Registration Staff
participant Frontend as 🌐 Staff Interface
participant API as ⚡ API Gateway
participant VisitSvc as 🏥 Visit Service
participant QueueSvc as 📋 Queue Service
participant DB as 💾 Database
participant PrintSvc as 🖨️ Print Service
participant NotifSvc as 📤 Notification Service
Note over Staff, NotifSvc: OPD Visit Creation - Multi-Department (FR-005)
Staff->>Frontend: Select patient for visit creation
Frontend->>API: GET /api/v1/patients/{id}/visit-eligibility
API->>DB: Check patient registration status
alt Patient fully registered
DB-->>API: Patient ready for visits
API-->>Frontend: Show visit creation form
Frontend-->>Staff: Display department selection
Staff->>Frontend: Select departments (multiple)
Note over Staff: Selected Departments:<br/>- Internal Medicine<br/>- Cardiology<br/>- Laboratory
Staff->>Frontend: Submit visit creation
Frontend->>API: POST /api/v1/visits/create-multi
Note over API: Visit Request:<br/>{<br/> "patientId": "uuid",<br/> "departments": [<br/> {"id": "dept-01", "priority": 1},<br/> {"id": "dept-02", "priority": 2},<br/> {"id": "lab-01", "priority": 3}<br/> ],<br/> "visitType": "OPD",<br/> "referral": null<br/>}
API->>VisitSvc: Create multi-department visit
VisitSvc->>DB: BEGIN transaction
loop For each selected department
VisitSvc->>DB: INSERT INTO medical_visits
VisitSvc->>QueueSvc: Generate queue number
QueueSvc->>QueueSvc: Calculate estimated wait time
QueueSvc-->>VisitSvc: Queue details
VisitSvc->>DB: INSERT INTO visit_queues
end
VisitSvc->>DB: COMMIT transaction
VisitSvc-->>API: Visits created successfully
API->>PrintSvc: Generate visit documents
PrintSvc->>DB: Get visit and patient details
PrintSvc->>PrintSvc: Generate combined visit slip
Note over PrintSvc: Document Contents:<br/>- Patient demographics<br/>- Visit numbers for each dept<br/>- Queue numbers and wait times<br/>- Department locations<br/>- Insurance information
PrintSvc-->>API: Documents ready
API-->>Frontend: Visit creation successful
Frontend->>PrintSvc: Print visit documents
PrintSvc-->>Staff: Print visit slip with all queues
API->>NotifSvc: Send notifications to departments
NotifSvc->>NotifSvc: Notify each department of new patient
else Patient registration incomplete
DB-->>API: Registration pending
API-->>Frontend: Registration incomplete error
Frontend-->>Staff: "Complete registration first"
end
Preconditions: - Patient registration is complete and verified - Selected departments are operational - Queue management system is active
Postconditions: - Multiple visits created with unique visit numbers - Queue positions assigned for each department - Visit slip printed with all department information - Department notifications sent
4.2 Queue Management Integration
This sequence demonstrates integration with the queue management system for real-time queue updates.
sequenceDiagram
participant Patient as 👤 Patient
participant Display as 📺 Queue Display
participant QueueSvc as 📋 Queue Service
participant VisitSvc as 🏥 Visit Service
participant MedStaff as 👩⚕️ Medical Staff
participant MedSystem as 🏥 Medical System
participant NotifSvc as 📤 Notification Service
participant DB as 💾 Database
Note over Patient, DB: Queue Management Integration (FR-007)
Patient->>Display: Check current queue status
Display->>QueueSvc: GET /api/v1/queue/status/{deptId}
QueueSvc->>DB: Get current queue status
DB-->>QueueSvc: Queue positions and wait times
QueueSvc-->>Display: Current queue information
Display-->>Patient: Show queue position and estimated wait
Note over Patient, DB: Patient Called for Service
MedStaff->>MedSystem: Call next patient
MedSystem->>QueueSvc: POST /api/v1/queue/call-next/{deptId}
QueueSvc->>DB: Get next patient in queue
DB-->>QueueSvc: Next patient details
QueueSvc->>VisitSvc: Update visit status to "in_progress"
VisitSvc->>DB: UPDATE medical_visits SET status='in_progress'
QueueSvc->>NotifSvc: Send patient notification
NotifSvc->>Display: Update queue display
NotifSvc-->>Patient: "Please proceed to Room 3"
Display-->>Patient: "Queue A01 - Room 3"
QueueSvc->>QueueSvc: Recalculate wait times for remaining patients
QueueSvc->>Display: Update estimated wait times
Note over Patient, DB: Visit Completion
MedStaff->>MedSystem: Complete patient consultation
MedSystem->>VisitSvc: POST /api/v1/visits/{id}/complete
VisitSvc->>DB: UPDATE medical_visits SET status='completed'
VisitSvc->>QueueSvc: Release queue position
QueueSvc->>Display: Update queue display
5. External System Integration Flows
5.1 Civil Registration API Integration
This sequence shows integration with the Civil Registration system for population database verification.
sequenceDiagram
participant Staff as 👨💼 Registration Staff
participant API as ⚡ API Gateway
participant CivilRegSvc as 🏛️ Civil Registration Service
participant CivilRegAPI as 🏥 Civil Registry API
participant DB as 💾 Database
participant AuditSvc as 📊 Audit Service
Note over Staff, AuditSvc: Civil Registration Verification
Staff->>API: POST /api/v1/verification/civil-registry
API->>CivilRegSvc: Verify citizen information
CivilRegSvc->>CivilRegAPI: POST /civil-reg/api/v1/verify
Note over CivilRegSvc, CivilRegAPI: Request:<br/>{<br/> "citizenId": "1234567890123",<br/> "requestType": "demographic_verification",<br/> "hospitalCode": "12345"<br/>}
alt Citizen record found
CivilRegAPI-->>CivilRegSvc: Citizen data verified
Note over CivilRegAPI, CivilRegSvc: Response:<br/>{<br/> "verified": true,<br/> "citizenData": {<br/> "titleTh": "นาย",<br/> "firstNameTh": "สมชาย",<br/> "lastNameTh": "ใจดี",<br/> "birthDate": "1985-06-15",<br/> "address": "123 หมู่ 5...",<br/> "status": "alive"<br/> }<br/>}
CivilRegSvc->>DB: Store verification result
CivilRegSvc->>AuditSvc: Log successful verification
CivilRegSvc-->>API: Verification successful
API-->>Staff: ✅ "Citizen data verified"
else Citizen not found or deceased
CivilRegAPI-->>CivilRegSvc: Verification failed
CivilRegSvc->>AuditSvc: Log failed verification
CivilRegSvc-->>API: Verification failed
API-->>Staff: ⚠️ "Cannot verify citizen data"
end
5.2 Line Bot Integration for Patient Registration
This sequence shows patient registration through Line Bot integration.
sequenceDiagram
participant Patient as 👤 Patient
participant LineApp as 💬 Line App
participant LinePlatform as 🔗 Line Platform
participant WebhookSvc as 🎣 Webhook Service
participant API as ⚡ API Gateway
participant DB as 💾 Database
participant Staff as 👨💼 Registration Staff
Note over Patient, Staff: Line Bot Patient Registration (TOR 1.1.3)
Patient->>LineApp: Add MediTech Line Bot as friend
LineApp->>LinePlatform: Follow event
LinePlatform->>WebhookSvc: POST /webhook (follow event)
WebhookSvc->>API: Register new Line user
API->>DB: Store Line user information
WebhookSvc->>LinePlatform: Send welcome message
LinePlatform->>LineApp: Welcome message with rich menu
LineApp-->>Patient: Show registration options
Patient->>LineApp: Select "ลงทะเบียนผู้ป่วยใหม่"
LineApp->>LinePlatform: Text message event
LinePlatform->>WebhookSvc: POST /webhook (message event)
WebhookSvc->>WebhookSvc: Parse registration intent
WebhookSvc->>LinePlatform: Send registration form link
LinePlatform->>LineApp: Flex message with web form
LineApp-->>Patient: Show registration web form
Patient->>LineApp: Open web form
LineApp->>API: GET /api/line/registration/form?userId={lineUserId}
API-->>LineApp: Registration form (mobile-optimized)
Patient->>LineApp: Fill and submit form
LineApp->>API: POST /api/line/registration/submit
API->>DB: Store pending Line registration
API->>WebhookSvc: Registration submitted
WebhookSvc->>LinePlatform: Send confirmation message
LinePlatform->>LineApp: "ได้รับข้อมูลการลงทะเบียนแล้ว รอการตรวจสอบ"
LineApp-->>Patient: Registration confirmation
Note over Patient, Staff: Staff Verification Process
Staff->>API: Review Line registrations
API->>DB: Get pending Line registrations
alt Staff approves registration
Staff->>API: Approve Line registration
API->>DB: Create patient record (generate HN)
API->>WebhookSvc: Registration approved
WebhookSvc->>LinePlatform: Send approval message
LinePlatform->>LineApp: "การลงทะเบียนสำเร็จ! HN ของคุณคือ: {hn}"
LineApp-->>Patient: Registration approved with HN
else Staff requests more info
Staff->>API: Request additional information
API->>WebhookSvc: Send info request
WebhookSvc->>LinePlatform: Request more information
LinePlatform->>LineApp: "กรุณาแนบเอกสารเพิ่มเติม"
LineApp-->>Patient: Additional info request
end
6. Multi-Channel Integration Flows
6.1 Cross-Channel Patient Data Synchronization
This sequence shows how patient data is synchronized across different registration channels.
sequenceDiagram
participant MobileApp as 📲 Mobile App
participant KioskSystem as 📱 Kiosk System
participant StaffSystem as 🌐 Staff System
participant API as ⚡ API Gateway
participant SyncService as ⚔️ Sync Service
participant DB as 💾 Database
participant Cache as ⚡ Redis Cache
Note over MobileApp, Cache: Cross-Channel Data Synchronization
Note over MobileApp, Cache: Patient updates data via Mobile App
MobileApp->>API: PUT /api/mobile/patients/{id}/update
API->>DB: UPDATE patients SET mobile_updated_at=NOW()
API->>SyncService: Trigger cross-channel sync
SyncService->>Cache: Invalidate patient cache
SyncService->>SyncService: Update patient search index
Note over MobileApp, Cache: Staff system accesses updated data
StaffSystem->>API: GET /api/v1/patients/{id}
API->>Cache: Check cached patient data
Cache-->>API: Cache miss (invalidated)
API->>DB: Get latest patient data
DB-->>API: Updated patient data
API->>Cache: Cache updated data
API-->>StaffSystem: Current patient information
Note over MobileApp, Cache: Kiosk system real-time sync
KioskSystem->>API: GET /api/kiosk/patients/{hn}/current
API->>DB: Get real-time patient data
DB-->>API: Latest patient information
API-->>KioskSystem: Synchronized patient data
6.2 Channel-Specific Authentication Flow
This sequence demonstrates different authentication methods for each channel.
sequenceDiagram
participant Staff as 👨💼 Registration Staff
participant Patient as 👤 Patient (Mobile)
participant KioskUser as 👤 Patient (Kiosk)
participant AuthSvc as 🔒 Auth Service
participant DB as 💾 Database
Note over Staff, DB: Channel-Specific Authentication
Note over Staff, DB: Staff Authentication (JWT + Session)
Staff->>AuthSvc: POST /api/auth/staff/login
AuthSvc->>DB: Validate staff credentials
DB-->>AuthSvc: Staff data + permissions
AuthSvc->>AuthSvc: Generate JWT + refresh token
AuthSvc-->>Staff: Authentication tokens
Note over Staff, DB: Mobile App Authentication (OTP + JWT)
Patient->>AuthSvc: POST /api/mobile/auth/otp-request
AuthSvc->>AuthSvc: Generate and send OTP
Patient->>AuthSvc: POST /api/mobile/auth/otp-verify
AuthSvc->>AuthSvc: Verify OTP and generate mobile JWT
AuthSvc-->>Patient: Mobile authentication token
Note over Staff, DB: Kiosk Authentication (Session-based)
KioskUser->>AuthSvc: POST /api/kiosk/auth/start-session
AuthSvc->>AuthSvc: Generate kiosk session (30-min timeout)
AuthSvc-->>KioskUser: Kiosk session token
7. Audit and Security Flows
7.1 Comprehensive Audit Trail Creation
This sequence shows how all patient data changes are logged for compliance and security.
sequenceDiagram
participant User as 👨💼 User (Any Channel)
participant API as ⚡ API Gateway
participant AuditSvc as 📊 Audit Service
participant DB as 💾 Database
participant ComplianceSvc as 🛡️ Compliance Service
participant AlertSvc as 🚨 Alert Service
Note over User, AlertSvc: Audit Trail Creation (PDPA Compliance)
User->>API: PUT /api/v1/patients/{id}
Note over API: Pre-change audit capture
API->>DB: Get current patient data
DB-->>API: Current patient state
API->>DB: UPDATE patients SET ...
Note over API: Post-change audit logging
API->>AuditSvc: Log patient data change
Note over AuditSvc: Audit Log Entry:<br/>{<br/> "action": "UPDATE_PATIENT",<br/> "userId": "uuid",<br/> "patientId": "uuid",<br/> "beforeData": {...},<br/> "afterData": {...},<br/> "changeReason": "Contact info update",<br/> "ipAddress": "192.168.1.100",<br/> "userAgent": "Mozilla/5.0...",<br/> "timestamp": "2025-09-02T10:30:00Z"<br/>}
AuditSvc->>DB: INSERT INTO patient_audit_log
AuditSvc->>ComplianceSvc: Check for sensitive data changes
alt Sensitive data changed (national_id, name, birth_date)
ComplianceSvc->>AlertSvc: Trigger security alert
AlertSvc->>AlertSvc: Send supervisor notification
ComplianceSvc->>AuditSvc: Mark as high-risk change
end
AuditSvc-->>API: Audit logged successfully
API-->>User: Patient updated successfully
Note over User, AlertSvc: Periodic Audit Review
loop Daily Audit Review
ComplianceSvc->>DB: Get high-risk audit entries
DB-->>ComplianceSvc: Sensitive data changes
ComplianceSvc->>ComplianceSvc: Generate compliance report
ComplianceSvc->>AlertSvc: Send daily audit summary
end
7.2 Data Privacy and PDPA Compliance
This sequence demonstrates data privacy controls and patient consent management.
sequenceDiagram
participant Patient as 👤 Patient
participant System as 🌐 System
participant API as ⚡ API Gateway
participant PrivacySvc as 🔐 Privacy Service
participant ConsentSvc as 📋 Consent Service
participant DB as 💾 Database
participant AuditSvc as 📊 Audit Service
Note over Patient, AuditSvc: PDPA Compliance - Patient Consent Management
Patient->>System: Request data privacy options
System->>API: GET /api/v1/privacy/patient/{id}/options
API->>ConsentSvc: Get current consent status
ConsentSvc->>DB: Get patient consent records
DB-->>ConsentSvc: Consent history
ConsentSvc-->>API: Current consent status
API-->>System: Privacy options available
System-->>Patient: Show privacy controls
alt Patient opts out of data sharing
Patient->>System: Opt out of data sharing
System->>API: PUT /api/v1/privacy/consent/opt-out
API->>ConsentSvc: Record opt-out consent
ConsentSvc->>DB: UPDATE consent records
ConsentSvc->>PrivacySvc: Apply data restrictions
PrivacySvc->>DB: SET data_sharing_restricted=TRUE
API->>AuditSvc: Log consent change
AuditSvc->>DB: Record consent audit trail
else Patient requests data deletion
Patient->>System: Request data deletion (Right to be forgotten)
System->>API: POST /api/v1/privacy/deletion-request
API->>PrivacySvc: Process deletion request
PrivacySvc->>PrivacySvc: Validate deletion eligibility
alt Deletion approved
PrivacySvc->>DB: Anonymize patient data
PrivacySvc->>AuditSvc: Log data anonymization
PrivacySvc-->>API: Deletion completed
else Deletion denied (active medical records)
PrivacySvc-->>API: Deletion denied - active records
API-->>System: Cannot delete - active medical care
end
end
8. Error Handling and Fallback Flows
8.1 External API Failure Handling
This sequence shows how the system handles failures in external API integrations.
sequenceDiagram
participant Staff as 👨💼 Registration Staff
participant API as ⚡ API Gateway
participant EligibilitySvc as 🔍 Eligibility Service
participant NHSO as 🏥 NHSO API
participant FallbackSvc as 🔄 Fallback Service
participant DB as 💾 Database
participant NotifSvc as 📤 Notification Service
Note over Staff, NotifSvc: External API Failure Handling
Staff->>API: Check NHSO eligibility
API->>EligibilitySvc: Verify eligibility
EligibilitySvc->>NHSO: POST /nhso/api/eligibility
alt NHSO API timeout/error
NHSO-->>EligibilitySvc: Timeout / HTTP 500
EligibilitySvc->>FallbackSvc: Trigger fallback mode
FallbackSvc->>DB: Check cached eligibility
alt Recent cached result available
DB-->>FallbackSvc: Cached eligibility (< 24 hours)
FallbackSvc-->>EligibilitySvc: Use cached result
EligibilitySvc-->>API: Eligibility from cache
API-->>Staff: ⚠️ "Using cached eligibility (NHSO unavailable)"
else No cached result
FallbackSvc->>DB: Store manual verification request
FallbackSvc->>NotifSvc: Notify supervisors
FallbackSvc-->>EligibilitySvc: Manual verification required
EligibilitySvc-->>API: Fallback to manual
API-->>Staff: ❌ "NHSO unavailable - manual verification required"
end
Note over FallbackSvc: Queue for retry when service returns
FallbackSvc->>DB: Queue eligibility check for retry
else NHSO API returns invalid data
NHSO-->>EligibilitySvc: Malformed response
EligibilitySvc->>EligibilitySvc: Validate response schema
EligibilitySvc->>FallbackSvc: Invalid response received
FallbackSvc->>NotifSvc: Alert IT support
FallbackSvc-->>EligibilitySvc: Use fallback procedure
end
Note over Staff, NotifSvc: Automatic Retry Mechanism
loop Every 5 minutes
FallbackSvc->>NHSO: Health check
alt NHSO API restored
NHSO-->>FallbackSvc: HTTP 200 - Service restored
FallbackSvc->>DB: Process queued eligibility checks
FallbackSvc->>NotifSvc: Service restoration notification
end
end
8.2 Data Validation and Error Recovery
This sequence demonstrates comprehensive data validation and error recovery mechanisms.
sequenceDiagram
participant User as 👨💼 User
participant Frontend as 🌐 Frontend
participant API as ⚡ API Gateway
participant ValidationSvc as ✅ Validation Service
participant DB as 💾 Database
participant AuditSvc as 📊 Audit Service
participant NotifSvc as 📤 Notification Service
Note over User, NotifSvc: Data Validation and Error Recovery
User->>Frontend: Submit patient registration
Frontend->>API: POST /api/v1/patients
API->>ValidationSvc: Validate patient data
ValidationSvc->>ValidationSvc: Client-side validation
alt Validation errors found
ValidationSvc-->>API: Validation errors
Note over ValidationSvc: Errors:<br/>- Invalid national ID checksum<br/>- Birth date in future<br/>- Missing required fields
API-->>Frontend: HTTP 422 - Validation errors
Frontend-->>User: Show field-specific error messages
User->>Frontend: Correct validation errors
Frontend->>API: POST /api/v1/patients (retry)
end
ValidationSvc->>DB: Check business rule constraints
alt Business rule violations
DB-->>ValidationSvc: Constraint violations
ValidationSvc->>AuditSvc: Log validation failure
ValidationSvc-->>API: Business rule errors
API-->>Frontend: Show business rule violations
else Validation successful
ValidationSvc-->>API: Data valid
API->>DB: INSERT INTO patients
alt Database constraint violation
DB-->>API: Unique constraint violation
API->>API: Handle duplicate data scenario
API-->>Frontend: "Similar patient found - review duplicates"
else Database connection error
DB-->>API: Connection timeout
API->>NotifSvc: Alert database team
API-->>Frontend: "System temporarily unavailable - try again"
else Success
DB-->>API: Patient created successfully
API->>AuditSvc: Log successful creation
API-->>Frontend: Registration complete
Frontend-->>User: ✅ "Patient registered - HN: {hn}"
end
end
Summary
This comprehensive sequence diagram documentation covers all major workflows in the Medical Records and Statistics System, including:
Key Workflows Documented:
- Patient Registration Flows
- Staff-based registration with smart card integration
- Kiosk self-service registration with verification
- Mobile app pre-registration
-
Emergency temporary HN creation
-
Insurance Verification Flows
- Real-time NHSO eligibility checking
- SSO integration for employed patients
-
Multiple insurance scheme selection
-
Medical Visit Management
- Multi-department OPD visit creation
- Queue management integration
-
Visit document generation
-
External System Integration
- Civil Registration API integration
- Line Bot patient registration
-
Cross-channel data synchronization
-
Audit and Security
- Comprehensive audit trail creation
- PDPA compliance and consent management
-
Data privacy controls
-
Error Handling
- External API failure fallback mechanisms
- Data validation and error recovery
- Automatic retry and notification systems
Technical Implementation Notes:
- All sequences follow the established API patterns with
/api/v1/versioning - Response times adhere to SRS performance requirements
- Error handling includes both technical failures and business rule violations
- Audit trails are comprehensive for regulatory compliance
- Multi-channel support is built into all core workflows
This documentation serves as a comprehensive guide for developers implementing the EMR system, ensuring proper integration between all components and compliance with healthcare regulations.