ข้ามไปที่เนื้อหา

Software Requirements Specification (SRS)

ระบบงานห้องฉุกเฉิน (Emergency Room System) - โรงพยาบาลจังหวัด

Document Version: 1.0
Date: 28 สิงหาคม 2025
Project: Hospital Information System - Emergency Room Module
Target Hospital: โรงพยาบาลระดับจังหวัด (500+ เตียง, 100+ ผู้ใช้พร้อมกัน)
Based on: ร่าง TOR ระบบงานห้องฉุกเฉิน และ OVERALL_SYSTEM_ARCHITECTURE.md


📋 Table of Contents

  1. บทนำและขอบเขตโครงการ
  2. ความต้องการเชิงหน้าที่ (Functional Requirements)
  3. ความต้องการด้านประสิทธิภาพ (Performance Requirements)
  4. ความต้องการด้านความปลอดภัย (Security Requirements)
  5. ความต้องการด้านการเชื่อมต่อ (Integration Requirements)
  6. ความต้องการด้านการใช้งาน (Usability Requirements)
  7. ความต้องการด้านการปฏิบัติตามกฎหมาย (Compliance Requirements)
  8. ความต้องการทางเทคนิค (Technical Requirements)
  9. ความต้องการด้านการติดตาม (Monitoring Requirements)
  10. การจัดการความเสี่ยง (Risk Management)
  11. การทดสอบและประกันคุณภาพ (Testing & Quality Assurance)
  12. การฝึกอบรมและการเปลี่ยนแปลง (Training & Change Management)
  13. ข้อกำหนด API และการเชื่อมต่อ (API Specifications & Integration)
  14. การส่งมอบและการดูแลระบบ (Delivery & Maintenance)
  15. สรุปและการอนุมัติ (Summary & Approval)
  16. ภาคผนวก (Appendices)

1. บทนำและขอบเขตโครงการ

1.1 วัตถุประสงค์ของเอกสาร

เอกสารนี้กำหนดความต้องการทางซอฟต์แวร์สำหรับระบบงานห้องฉุกเฉิน (Emergency Room System) เป็นส่วนหนึ่งของระบบสารสนเทศโรงพยาบาล MediTech ที่ครอบคลุม:

  • ระบบรับผู้ป่วยฉุกเฉินและการคัดแยก (Emergency Triage System)
  • ระบบงานแพทย์ ER พร้อม CPOE AI Assist
  • ระบบการจัดการยาและความปลอดภัยในห้องฉุกเฉิน
  • ระบบจัดการข้อมูลอุบัติเหตุและ EMS
  • ระบบติดตามงานและแดชบอร์ดสำหรับห้องฉุกเฉิน
  • การเชื่อมต่อกับระบบอื่นในโรงพยาบาล

1.2 ขอบเขตของระบบ

ระบบที่รวมอยู่ใน Scope: - ระบบรับผู้ป่วยฉุกเฉินหลากหลายช่องทาง (Walk-in, EMS, Referral) - ระบบคัดแยกผู้ป่วยตาม ESI (Emergency Severity Index) - ระบบการทำงานของแพทย์และพยาบาลในห้องฉุกเฉิน - ระบบการจัดการเตียงและทรัพยากรห้องฉุกเฉิน - ระบบแจ้งเตือนและการสื่อสารกับญาติ - ระบบรายงานและสถิติห้องฉุกเฉิน

ระบบที่เชื่อมต่อแต่ไม่รวมใน Scope: - ระบบเวชระเบียนหลัก (EMR Core) - ระบบห้องปฏิบัติการกลาง - ระบบรังสีวินิจฉัย - ระบบเภสัชกรรม - ระบบการเงิน

1.3 ผู้ใช้งานหลัก

  1. แพทย์ห้องฉุกเฉิน - การตรวจรักษาและให้คำสั่ง
  2. พยาบาลห้องฉุกเฉิน - การคัดแยก การดูแล และติดตามคำสั่ง
  3. เจ้าหน้าที่รับไว้รักษา - การลงทะเบียนผู้ป่วย
  4. หัวหน้าพยาบาล/แพทย์ - การดูแลและติดตามระบบ
  5. EMS Personnel - การส่งต่อข้อมูลผู้ป่วย
  6. ผู้ดูแลระบบ - การบำรุงรักษาระบบ

2. ความต้องการเชิงหน้าที่ (Functional Requirements)

2.1 ระบบรับผู้ป่วยฉุกเฉินและการคัดแยก (Emergency Triage System)

2.1.1 การรับผู้ป่วยฉุกเฉิน

REQ-ER-001: ระบบต้องรองรับการรับข้อมูลผู้ป่วยจากหลายช่องทาง - Smart Card Reader (บัตรประชาชน/บัตรประกันสุขภาพ) - Barcode Scanner (สำหรับผู้ป่วยเก่า) - Manual Entry (สำหรับกรณีฉุกเฉิน) - EMS Data Transfer (จากระบบ EMS)

REQ-ER-002: ระบบต้องบันทึกข้อมูลการมาถึง - เวลามาถึง (Automatic timestamp) - วิธีการมา: Walk-in, EMS, Referral, Transfer - ประเภทผู้ป่วย: Accident, Emergency, General Check-up - ผู้นำส่ง/ผู้ติดตาม

2.1.2 ระบบคัดแยกผู้ป่วย (Triage System)

REQ-ER-003: ระบบต้องรองรับการประเมิน Triage ตาม ESI Level - Level 1 (Red): Resuscitation - ต้องการการช่วยเหลือทันที - Level 2 (Orange): Emergent - ต้องได้รับการรักษาภายใน 15 นาที - Level 3 (Yellow): Urgent - ต้องได้รับการรักษาภายใน 30 นาที - Level 4 (Green): Semi-urgent - ต้องได้รับการรักษาภายใน 60 นาที - Level 5 (Blue): Non-urgent - ต้องได้รับการรักษาภายใน 120 นาที

REQ-ER-004: ระบบต้องคำนวณคะแนน Triage อัตโนมัติ - Vital Signs (BP, HR, RR, SpO2, Temp) - Glasgow Coma Scale (GCS) - AVPU Scale (Alert, Voice, Pain, Unresponsive) - Pain Score - Chief Complaint Analysis

REQ-ER-005: ระบบต้องบันทึกการประเมิน Triage - ชื่อพยาบาลผู้ประเมิน - เวลาประเมิน - ลายเซ็นอิเล็กทรอนิกส์ - หมายเหตุเพิ่มเติม

2.1.3 การแสดงสถานะและแจ้งเตือน

REQ-ER-006: ระบบต้องแสดงสถานะผู้ป่วยแบบเรียลไทม์ - Dashboard แสดงรายชื่อผู้ป่วยพร้อม Triage Level - การแสดงผลผ่านจอทีวี/จอมอนิเตอร์ - สถานะ: รอตรวจ, กำลังตรวจ, รอผล, รอ Admit, รอ Transfer

REQ-ER-007: ระบบต้องมีระบบแจ้งเตือน - แจ้งเตือนผู้ป่วย Critical (Level 1-2) - แจ้งเตือนเวลารอเกินมาตรฐาน - แจ้งเตือนการเปลี่ยนแปลงสถานะ

2.2 ระบบงานแพทย์ ER (SOAP + CPOE AI Assist)

2.2.1 การบันทึกผลตรวจ SOAP Note

REQ-ER-008: ระบบต้องรองรับการบันทึก SOAP Note - S (Subjective): อาการที่ผู้ป่วยบอก, History Taking - O (Objective): ผลการตรวจร่างกาย, Vital Signs, Physical Examination - A (Assessment): การวินิจฉัย, ICD-10 Diagnosis - P (Plan): แผนการรักษา, คำสั่งแพทย์

REQ-ER-009: ระบบต้องรองรับ Template และ Smart Forms - Emergency-specific templates (Chest Pain, Trauma, Stroke, etc.) - Body Map integration สำหรับบันทึกตำแหน่งบาดเจ็บ - Sketch tools สำหรับวาดภาพประกอบ - การนำเข้า Template ที่กำหนดเอง

2.2.2 ระบบ CPOE AI Assist

REQ-ER-010: ระบบต้องมี AI Assistant สำหรับการวิเคราะห์คำสั่ง - แปลงข้อความใน Plan เป็นคำสั่งโครงสร้าง - แยกประเภทคำสั่ง: Lab, X-ray, Procedure, Medication, Admission, Follow-up - แสดงราคาและสิทธิการรักษา - แปลง Diagnosis เป็น ICD-10 codes อัตโนมัติ

REQ-ER-011: ระบบต้องรองรับการจัดการคำสั่งแพทย์ - Re-Order จากการมาครั้งก่อน - Package Order สำหรับกลุมคำสั่งที่ใช้บ่อย - Order Sets สำหรับโรคเฉพาะ (MI, Stroke, Trauma) - การแชร์ Order Templates ระหว่างแพทย์

2.2.3 การจัดการสื่อมัลติมีเดีย

REQ-ER-012: ระบบต้องรองรับการจัดการรูปภาพและวิดีโอ - การถ่ายภาพบาดแผล/อาการ - Image Annotation (การทำเครื่องหมายตำแหน่ง) - การบันทึกวิดีโอ (เช่น seizure, movement disorders) - การเก็บรักษาในเวชระเบียนอิเล็กทรอนิกส์

2.3 ระบบการจัดการยาและความปลอดภัย (Emergency Medication Management)

2.3.1 การสั่งยาในห้องฉุกเฉิน

REQ-ER-013: ระบบต้องรองรับการสั่งยาเฉพาะห้องฉุกเฉิน - STAT Orders (คำสั่งเร่งด่วน) - IV Drip/Fluid management - High Alert Drug warnings - Emergency Drug Protocols

REQ-ER-014: ระบบต้องมีระบบความปลอดภัยด้านยา - Drug Allergy checking - Drug-Drug Interaction warnings - Dosage calculation assistance - Contraindication alerts

2.3.2 ระบบ e-MAR สำหรับห้องฉุกเฉิน

REQ-ER-015: ระบบต้องรองรับ Electronic Medication Administration Record - Barcode scanning ผู้ป่วย + ยา - Real-time medication tracking - การบันทึกเวลาและผู้ให้ยา - การแจ้งเตือนเวลาให้ยา

2.4 การจัดการข้อมูลอุบัติเหตุและ EMS Integration

2.4.1 ข้อมูลอุบัติเหตุและเหตุการณ์

REQ-ER-016: ระบบต้องบันทึกข้อมูลเหตุการณ์ - ประเภทเหตุการณ์ (RTA, Fall, Assault, Medical Emergency) - เวลาและสถานที่เกิดเหตุ - รายละเอียดเหตุการณ์ - การบาดเจ็บ/อาการเบื้องต้น

REQ-ER-017: ระบบต้องเชื่อมต่อกับ EMS - รับข้อมูลจาก EMS Pre-hospital Care Record - Handover Report จาก EMT - Vital Signs และการดูแลระหว่างการขนส่ง - Timeline ของการดูแล

2.5 ระบบติดตามงานและ Dashboard

2.5.1 Emergency Dashboard

REQ-ER-018: ระบบต้องมี Real-time Dashboard - ภาพรวมผู้ป่วยใน ER พร้อม Triage Colors - เวลารอแพทย์ / เวลาค้างในระบบ - สถานะเตียงและทรัพยากร - การแสดงผลแบบ Graphical และ Tabular

REQ-ER-019: ระบบต้องมีระบบกรองและค้นหา - กรองตาม Triage Level - กรองตามสถานะ (รอตรวจ, ตรวจแล้ว, รอผล) - ค้นหาผู้ป่วยตามชื่อ/HN - การแสดงผลแบบ Real-time

2.5.2 Nursing Task Management

REQ-ER-020: ระบบต้องสร้าง Nursing Tasks อัตโนมัติ - แปลงคำสั่งแพทย์เป็น Nursing Tasks - แยกประเภท: Lab collection, X-ray transport, IV management, Monitoring - การกำหนดผู้รับผิดชอบและเวลา - การติดตามการดำเนินงาน

REQ-ER-021: ระบบต้องมีการแจ้งเตือน Tasks - แจ้งเตือน Tasks ที่ค้าง/เกินเวลา - การจัดลำดับความสำคัญ - การรายงานผลการดำเนินงาน - Task Summary รายวัน/รายเวร


3. ความต้องการด้านประสิทธิภาพ (Performance Requirements)

3.1 ความต้องการด้านเวลาตอบสนอง

REQ-PERF-001: Triage Assessment Response Time - การคำนวณ Triage Score: < 3 วินาที - การบันทึกข้อมูล Triage: < 5 วินาที - การแสดงผล Dashboard: < 2 วินาที

REQ-PERF-002: CPOE AI Assist Performance - การวิเคราะห์ Plan text: < 5 วินาที - การแปลง ICD-10: < 3 วินาที - การตรวจสอบ Drug Interaction: < 2 วินาที

REQ-PERF-003: Emergency Data Access - การเรียกดูเวชระเบียน: < 3 วินาที - การค้นหาผู้ป่วย: < 2 วินาที - การแสดง Vital Signs: < 1 วินาที

3.2 ความต้องการด้านปริมาณงาน

REQ-PERF-004: Concurrent User Support - รองรับผู้ใช้พร้อมกัน: 50+ users - Peak load handling: 200+ simultaneous connections - Emergency surge capacity: 500% normal load

REQ-PERF-005: Data Volume Handling - ผู้ป่วยใหม่ต่อวัน: 500+ cases - การบันทึกข้อมูลต่อชั่วโมง: 1,000+ entries - Concurrent Triage assessments: 20+ simultaneous

3.3 ความต้องการด้านความพร้อมใช้งาน

REQ-PERF-006: System Availability - Uptime requirement: 99.9% (8.76 ชั่วโมง downtime ต่อปี) - Maximum planned downtime: 4 ชั่วโมง/เดือน - Emergency fail-over time: < 30 วินาที


4. ความต้องการด้านความปลอดภัย (Security Requirements)

4.1 การควบคุมการเข้าถึง

REQ-SEC-001: Role-Based Access Control (RBAC) - Emergency Physician: Full access to ER module - Emergency Nurse: Limited to nursing functions and triage - Registration Staff: Patient registration only - ER Supervisor: Full access plus administrative functions

REQ-SEC-002: Authentication และ Authorization - Multi-factor authentication สำหรับ Critical functions - Single Sign-On (SSO) integration - Session timeout: 30 นาที (configurable) - Automatic logout สำหรับ workstations ที่ไม่ได้ใช้งาน

4.2 การปกป้องข้อมูล

REQ-SEC-003: Data Encryption - Data at rest: AES-256 encryption - Data in transit: TLS 1.3 - Database field-level encryption สำหรับข้อมูลสำคัญ - Key management system

REQ-SEC-004: Patient Privacy Protection - PDPA compliance - Access logging และ audit trails - Data masking สำหรับ non-authorized users - Right to be forgotten implementation

4.3 การตรวจสอบและติดตาม

REQ-SEC-005: Audit Trail Requirements - บันทึกการเข้าถึงข้อมูลผู้ป่วยทั้งหมด - การแก้ไขข้อมูล with before/after values - Login/logout tracking - Failed access attempts monitoring


5. ความต้องการด้านการเชื่อมต่อ (Integration Requirements)

5.1 การเชื่อมต่อกับระบบภายใน

REQ-INT-001: EMR System Integration - Real-time patient data synchronization - Shared patient demographics - Medical history access - Allergy and medication history

REQ-INT-002: Laboratory System Integration - Electronic lab order transmission - Real-time result retrieval - Critical value alerts - STAT order prioritization

REQ-INT-003: Radiology System Integration - CPOE integration for imaging orders - DICOM image viewing - Radiology report integration - Critical findings alerts

REQ-INT-004: Pharmacy System Integration - Electronic prescription transmission - Drug interaction checking - Inventory level checking - Medication administration confirmation

5.2 การเชื่อมต่อกับระบบภายนอก

REQ-INT-005: NHSO/SSO Integration - Real-time eligibility verification - Insurance coverage checking - Claim submission preparation - Authorization requirement checking

REQ-INT-006: EMS System Integration - Pre-hospital care data import - ETA notifications - Patient condition updates during transport - Handover documentation

REQ-INT-007: Referral System Integration - Electronic referral processing - Hospital capacity checking - Transfer documentation - Follow-up coordination

5.3 Standards และ Protocols

REQ-INT-008: Healthcare Standards Compliance - HL7 FHIR R4 for data exchange - ICD-10-TM for diagnosis coding - ICD-9-CM for procedure coding - SNOMED CT for clinical terminology

REQ-INT-009: Communication Protocols - REST API for web services - WebSocket for real-time updates - Message queuing for reliable data transfer - Event-driven architecture implementation


6. ความต้องการด้านการใช้งาน (Usability Requirements)

6.1 User Interface Requirements

REQ-UI-001: Emergency-Optimized Interface - Large, touch-friendly buttons - Color-coded priority indicators - Minimal clicks to complete tasks - Mobile-responsive design

REQ-UI-002: Accessibility Requirements - Screen reader compatibility - Keyboard navigation support - High contrast color schemes - Multilingual support (Thai/English)

6.2 Workflow Optimization

REQ-UI-003: Clinical Workflow Support - Task-oriented interface design - Context-sensitive information display - Workflow shortcuts for common procedures - Customizable dashboard layouts

REQ-UI-004: Error Prevention - Input validation with clear error messages - Confirmation dialogs for critical actions - Auto-save functionality - Undo/redo capabilities where appropriate


7. ความต้องการด้านการปฏิบัติตามกฎหมาย (Compliance Requirements)

7.1 การปฏิบัติตามกฎหมายด้านสุขภาพ

REQ-COMP-001: Thai Healthcare Regulations - Ministry of Public Health guidelines compliance - Medical Record Act compliance - Emergency Medicine regulations - Professional licensing requirements verification

REQ-COMP-002: Data Protection Compliance - Personal Data Protection Act (PDPA) compliance - Patient consent management - Data retention policies - Cross-border data transfer restrictions

7.2 Medical Standards Compliance

REQ-COMP-003: Clinical Documentation Standards - Complete and accurate medical records - Legally defensible documentation - Provider identification and authentication - Timestamp integrity

REQ-COMP-004: Quality and Safety Standards - Clinical decision support integration - Patient safety alerts - Quality metric tracking - Incident reporting integration


8. ความต้องการทางเทคนิค (Technical Requirements)

8.1 Technology Stack

REQ-TECH-001: Backend Technology - Framework: NestJS with TypeScript - Database: PostgreSQL 15+ - ORM: Prisma - Authentication: JWT + Refresh Token - API: RESTful with OpenAPI documentation

REQ-TECH-002: Frontend Technology - Framework: Next.js 14 with TypeScript - UI Library: Ant Design + Tailwind CSS - State Management: Zustand + React Query - PWA Support: Service Workers for offline capability

8.2 Database Requirements

REQ-TECH-003: Database Design - Normalized schema with appropriate indexing - Foreign key relationships with existing EMR tables - Partitioning for large tables (visits, orders) - Backup and recovery procedures

REQ-TECH-004: Data Retention - Active data: 2 years online - Archive data: 10 years offline storage - Purge policies for temporary data - Compliance with legal retention requirements

8.3 Infrastructure Requirements

REQ-TECH-005: Server Infrastructure - Load balancing for high availability - Auto-scaling capability - Container orchestration (Docker/Kubernetes) - Monitoring and logging infrastructure

REQ-TECH-006: Network Requirements - Dedicated network segment for ER - VPN access for remote connectivity - Bandwidth: 100 Mbps minimum - Redundant internet connections


9. ความต้องการด้านการติดตาม (Monitoring Requirements)

9.1 System Monitoring

REQ-MON-001: Performance Monitoring - Real-time system performance metrics - Database query performance tracking - API response time monitoring - Resource utilization tracking

REQ-MON-002: Business Process Monitoring - Patient flow metrics - Triage time tracking - Length of stay monitoring - Workflow bottleneck identification

9.2 Alerting และ Notification

REQ-MON-003: Critical Alerts - System downtime notifications - Database connection failures - Integration service failures - Security incident alerts

REQ-MON-004: Clinical Alerts - Critical patient notifications - Overdue task alerts - Capacity limit warnings - Quality metric violations


10. การจัดการความเสี่ยง (Risk Management)

10.1 Technical Risks

RISK-001: System Failure During Emergency - Mitigation: Redundant systems, offline capability, manual backups - Impact: High - Could affect patient care - Probability: Low with proper infrastructure

RISK-002: Data Loss or Corruption - Mitigation: Regular backups, database replication, transaction logs - Impact: High - Legal and clinical implications - Probability: Low with proper safeguards

10.2 Operational Risks

RISK-003: User Adoption Resistance - Mitigation: Comprehensive training, change management, user involvement - Impact: Medium - Could slow implementation - Probability: Medium in healthcare environments

RISK-004: Integration Failures - Mitigation: Thorough testing, fallback procedures, vendor coordination - Impact: Medium - Could affect workflow efficiency - Probability: Medium with complex integrations

10.3 Security Risks

RISK-005: Data Breach - Mitigation: Encryption, access controls, security monitoring, staff training - Impact: High - Legal and reputational damage - Probability: Low with proper security measures


11. การทดสอบและประกันคุณภาพ (Testing & Quality Assurance)

11.1 Testing Strategy

TEST-001: Unit Testing - Minimum 80% code coverage - Automated testing for critical functions - Mocking for external dependencies - Continuous integration testing

TEST-002: Integration Testing - End-to-end workflow testing - External system integration testing - API contract testing - Database integration testing

TEST-003: Performance Testing - Load testing for concurrent users - Stress testing for peak periods - Scalability testing - Failover testing

11.2 Clinical Validation

TEST-004: Clinical Workflow Testing - Healthcare professional involvement - Real-world scenario testing - Usability testing with end users - Clinical decision support validation

TEST-005: Regulatory Compliance Testing - PDPA compliance verification - Healthcare regulation compliance - Security standard compliance - Audit trail verification


12. การฝึกอบรมและการเปลี่ยนแปลง (Training & Change Management)

12.1 Training Requirements

TRAIN-001: User Training Program - Role-based training modules - Hands-on practice sessions - Super-user certification program - Ongoing education and updates

TRAIN-002: Training Materials - User manuals and quick reference guides - Video tutorials - Online learning platform - Mobile learning support

12.2 Change Management

CHANGE-001: Implementation Strategy - Phased rollout approach - Pilot testing in select departments - Go-live support team - Post-implementation optimization

CHANGE-002: User Support - 24/7 help desk during initial rollout - On-site support team - User feedback collection and response - Continuous improvement process


13. ข้อกำหนด API และการเชื่อมต่อ (API Specifications & Integration)

13.1 API Design Standards

13.1.1 RESTful API Design Principles

const apiStandards = {
  base_url: '/api/v1/er/',
  authentication: 'JWT Bearer Token',
  content_type: 'application/json',
  charset: 'UTF-8',
  versioning: 'URL path versioning (/api/v1/, /api/v2/)',
  naming_convention: 'kebab-case for endpoints, camelCase for JSON fields'
};

// Standard API Response Format
interface ApiResponse<T> {
  success: boolean;
  data: T;
  message: string;
  timestamp: string;
  requestId: string;
  pagination?: {
    page: number;
    limit: number;
    total: number;
    totalPages: number;
  };
}

// Standard Error Response Format
interface ApiErrorResponse {
  success: false;
  error: {
    code: string;
    message: string;
    details?: any;
    field?: string; // For validation errors
  };
  timestamp: string;
  requestId: string;
  statusCode: number;
}

13.1.2 Authentication & Authorization Standards

const authenticationStandards = {
  method: 'JWT Bearer Token',
  token_expiry: {
    access_token: '15 minutes',
    refresh_token: '24 hours',
    emergency_override: '2 hours'
  },

  // JWT Token Structure
  jwt_payload: {
    sub: 'user-uuid-123',
    hospitalId: 'hospital-uuid-123',
    roles: ['ER_PHYSICIAN', 'TRAUMA_TEAM_LEADER'],
    departments: ['emergency-dept-uuid'],
    permissions: [
      'TRIAGE_ASSESSMENT',
      'EMERGENCY_ORDERS',
      'CRITICAL_CARE_ACCESS',
      'TRAUMA_ACTIVATION'
    ],
    emergency_override: false,
    iat: 1692347400,
    exp: 1692433800
  },

  // Role-based Permissions
  roles: {
    'ER_PHYSICIAN': [
      'READ_PATIENT_DATA',
      'WRITE_CLINICAL_NOTES',
      'CREATE_ORDERS',
      'DISPOSITION_DECISIONS',
      'TRAUMA_ACTIVATION'
    ],
    'ER_NURSE': [
      'READ_PATIENT_DATA',
      'TRIAGE_ASSESSMENT',
      'MEDICATION_ADMINISTRATION',
      'VITAL_SIGNS_RECORDING'
    ],
    'TRIAGE_NURSE': [
      'PATIENT_REGISTRATION',
      'TRIAGE_ASSESSMENT',
      'QUEUE_MANAGEMENT'
    ],
    'CHARGE_NURSE': [
      'ALL_NURSING_PERMISSIONS',
      'BED_MANAGEMENT',
      'STAFF_COORDINATION'
    ]
  }
};

// Authentication Header Example
const authHeaders = {
  'Authorization': 'Bearer eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...',
  'X-Hospital-ID': 'hospital-uuid-123',
  'X-Department-ID': 'emergency-dept-uuid',
  'Content-Type': 'application/json'
};

13.1.3 Performance & Rate Limiting Standards

const performanceStandards = {
  response_time_sla: {
    critical_endpoints: '< 200ms', // Triage, resuscitation
    standard_clinical: '< 500ms',  // Orders, documentation
    complex_queries: '< 2s',       // Reports, statistics
    dashboard_updates: '< 100ms'   // Real-time data
  },

  rate_limiting: {
    'CRITICAL_ENDPOINTS': '200 requests/minute',
    'CLINICAL_ENDPOINTS': '100 requests/minute', 
    'ADMINISTRATIVE': '50 requests/minute',
    'REPORTING': '20 requests/minute'
  },

  caching_strategy: {
    patient_data: 'Redis - 5 minutes',
    vital_signs: 'In-memory - 30 seconds',
    queue_status: 'Real-time WebSocket',
    static_data: 'Redis - 1 hour'
  }
};

13.2 Triage Management APIs

13.2.1 Emergency Triage Assessment

POST /api/v1/er/triage/assessment

// Create new triage assessment for incoming patient
const createTriageAssessmentRequest = {
  method: 'POST',
  endpoint: '/api/v1/er/triage/assessment',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <jwt_token>',
    'X-Hospital-ID': 'hospital-uuid-123',
    'X-Department-ID': 'emergency-dept-uuid'
  },
  body: {
    patientId: 'pt-uuid-123',
    arrivalMethod: 'walk-in', // walk-in, ems, referral, transfer
    arrivalTime: '2024-08-18T10:30:00.000Z',
    chiefComplaint: 'Chest pain radiating to left arm, 8/10 severity',
    vitalSigns: {
      systolicBP: 140,
      diastolicBP: 90,
      heartRate: 95,
      respiratoryRate: 18,
      oxygenSaturation: 97,
      temperature: 36.8,
      painScore: 8,
      measurementTime: '2024-08-18T10:35:00.000Z'
    },
    consciousness: {
      gcs: 15,
      avpu: 'alert',
      neurologicalDeficits: false
    },
    allergies: [
      { allergen: 'Penicillin', reaction: 'Rash', severity: 'moderate' },
      { allergen: 'Shellfish', reaction: 'Anaphylaxis', severity: 'severe' }
    ],
    currentMedications: [
      { medication: 'Metformin', dose: '500mg', frequency: 'BID' },
      { medication: 'Lisinopril', dose: '10mg', frequency: 'Daily' }
    ],
    medicalHistory: ['Diabetes Type 2', 'Hypertension'],
    assessment: {
      triageNurse: 'nurse-uuid-123',
      nurseName: 'พยาบาลสมหญิง ใจดี',
      esiLevel: 2, // Auto-calculated based on protocols
      urgency: 'emergent',
      notes: 'Possible acute coronary syndrome - needs immediate physician evaluation',
      reassessmentRequired: true,
      reassessmentInterval: 15 // minutes
    }
  }
};

const createTriageAssessmentResponse = {
  success: true,
  data: {
    assessmentId: 'triage-uuid-123',
    patientId: 'pt-uuid-123',
    esiLevel: 2,
    urgencyCategory: 'emergent',
    queuePosition: 3,
    estimatedWaitTime: '15 minutes',
    targetPhysicianTime: '2024-08-18T10:45:00.000Z',
    triageScore: {
      calculated: 85,
      factors: {
        vitalSigns: 25,
        painScore: 20,
        chiefComplaint: 30,
        mentalStatus: 10
      }
    },
    alerts: [
      {
        type: 'HIGH_RISK_CHEST_PAIN',
        severity: 'urgent',
        message: 'Patient meets criteria for possible ACS protocol'
      }
    ],
    createdAt: '2024-08-18T10:35:00.000Z',
    createdBy: {
      userId: 'nurse-uuid-123',
      name: 'พยาบาลสมหญิง ใจดี',
      role: 'TRIAGE_NURSE'
    }
  },
  message: 'Triage assessment completed successfully',
  timestamp: '2024-08-18T10:35:00.000Z',
  requestId: 'req-triage-001'
};

PUT /api/v1/er/triage/{assessmentId}
- Purpose: Update existing triage assessment or re-triage patient - Authentication: Required (triage_nurse, er_physician, charge_nurse) - Request Body: Same as POST with updated fields - Response: Updated assessment with audit trail

GET /api/v1/er/triage/patient/{patientId}
- Purpose: Retrieve patient's triage information and history - Authentication: Required (all ER staff) - Response: Complete triage history with timestamps and assessor details

GET /api/v1/er/triage/queue
- Purpose: Get current triage queue sorted by priority and wait time - Authentication: Required (all ER staff) - Query Parameters: - priority: Filter by ESI level (1-5) - status: Filter by patient status - limit: Number of results (default: 50) - Response: Real-time queue with patient summaries and wait times

POST /api/v1/er/triage/vital-signs
- Purpose: Record additional vital signs measurements - Authentication: Required (nursing staff) - Request Body:
{
  "patientId": "string",
  "vitalSigns": {
    "systolicBP": "number",
    "diastolicBP": "number",
    "heartRate": "number",
    "respiratoryRate": "number",
    "oxygenSaturation": "number",
    "temperature": "number",
    "painScore": "number",
    "bloodGlucose": "number"
  },
  "measuredBy": "string",
  "measurementTime": "datetime",
  "notes": "string"
}

GET /api/v1/er/triage/esi-calculator
- Purpose: Calculate ESI level based on clinical parameters - Authentication: Required (clinical staff) - Query Parameters: Clinical assessment parameters - Response: Calculated ESI level with reasoning

13.3 Patient Registration APIs

REQ-API-020: Emergency Patient Registration

POST /api/v1/er/patients/register
- Purpose: Register new emergency patient or update existing patient - Authentication: Required (registration_staff, nursing_staff) - Request Body:
{
  "demographics": {
    "nationalId": "string",
    "hn": "string",
    "firstName": "string",
    "lastName": "string",
    "dateOfBirth": "date",
    "gender": "male|female|other",
    "phoneNumber": "string",
    "address": "object"
  },
  "insurance": {
    "scheme": "nhso|sso|private|self-pay",
    "policyNumber": "string",
    "eligibilityStatus": "string"
  },
  "emergency": {
    "arrivalTime": "datetime",
    "arrivalMethod": "walk-in|ems|referral",
    "accompaniedBy": "string",
    "emergencyContact": "object"
  }
}
- Response: Patient registration confirmation with HN and visit number

POST /api/v1/er/patients/unknown
- Purpose: Register unknown/unconscious patient with minimal information - Authentication: Required (clinical staff) - Request Body:
{
  "estimatedAge": "number",
  "gender": "male|female|unknown",
  "arrivalMethod": "ems|police|unknown",
  "foundLocation": "string",
  "initialAssessment": "string",
  "personalEffects": ["string"]
}
- Response: Temporary patient ID for tracking until identification

PUT /api/v1/er/patients/{patientId}/identity
- Purpose: Update patient identity when unknown patient is identified - Authentication: Required (registration_staff, charge_nurse) - Request Body: Complete demographic information - Response: Updated patient record with merged data

GET /api/v1/er/patients/search
- Purpose: Search emergency patients by various criteria - Authentication: Required (all ER staff) - Query Parameters: - query: Name, HN, or National ID - status: Current status filter - dateRange: Arrival date range - limit: Results limit - Response: Matching patient list with current status

POST /api/v1/er/patients/mass-casualty
- Purpose: Register multiple patients from mass casualty incident - Authentication: Required (charge_nurse, er_physician) - Request Body: Array of patient objects with incident details - Response: Batch registration results with tracking numbers

13.4 Emergency Treatment APIs

REQ-API-030: Clinical Documentation and Orders

POST /api/v1/er/treatments/orders
- Purpose: Create emergency medical orders (CPOE) - Authentication: Required (er_physician, resident_physician) - Request Body:
{
  "patientId": "string",
  "visitId": "string",
  "orders": [
    {
      "type": "medication|lab|imaging|procedure|consultation",
      "category": "stat|urgent|routine",
      "orderDetails": {
        "itemCode": "string",
        "itemName": "string",
        "quantity": "string",
        "instructions": "string",
        "frequency": "string",
        "duration": "string"
      },
      "priority": "immediate|urgent|routine",
      "scheduledTime": "datetime"
    }
  ],
  "diagnosis": [
    {
      "icd10Code": "string",
      "description": "string",
      "type": "primary|secondary|provisional"
    }
  ],
  "clinicalNotes": "string"
}
- Response: Order confirmation with tracking numbers and estimated completion times

GET /api/v1/er/treatments/patient/{patientId}
- Purpose: Retrieve complete treatment history for patient - Authentication: Required (clinical staff) - Response: Chronological treatment history with orders, results, and outcomes

POST /api/v1/er/treatments/procedures
- Purpose: Document emergency procedures performed - Authentication: Required (er_physician, er_nurse) - Request Body:
{
  "patientId": "string",
  "procedureCode": "string",
  "procedureName": "string",
  "performedBy": "string",
  "assistants": ["string"],
  "startTime": "datetime",
  "endTime": "datetime",
  "complications": "string",
  "outcome": "string",
  "images": ["string"],
  "consent": {
    "obtained": "boolean",
    "consentType": "verbal|written|implied",
    "witness": "string"
  }
}

PUT /api/v1/er/treatments/medications
- Purpose: Update medication administration record (e-MAR) - Authentication: Required (nursing_staff) - Request Body:
{
  "orderIds": ["string"],
  "administrationRecords": [
    {
      "orderId": "string",
      "administeredBy": "string",
      "administrationTime": "datetime",
      "dosageGiven": "string",
      "route": "string",
      "site": "string",
      "patientResponse": "string",
      "sideEffects": "string"
    }
  ]
}

GET /api/v1/er/treatments/protocols
- Purpose: Retrieve emergency treatment protocols and guidelines - Authentication: Required (clinical staff) - Query Parameters: - condition: Medical condition or chief complaint - age: Patient age group - category: Protocol category - Response: Relevant protocols with step-by-step guidelines

13.5 Critical Care & Monitoring APIs

REQ-API-040: Critical Patient Management

POST /api/v1/er/critical/monitoring
- Purpose: Initiate critical patient monitoring with continuous vital signs - Authentication: Required (er_physician, critical_care_nurse) - Request Body:
{
  "patientId": "string",
  "monitoringType": "continuous|intermittent|event-based",
  "parameters": [
    "heartRate", "bloodPressure", "oxygenSaturation", 
    "respiratoryRate", "temperature", "ecg", "capnography"
  ],
  "alertThresholds": {
    "heartRate": {"min": 60, "max": 100},
    "systolicBP": {"min": 90, "max": 180},
    "oxygenSaturation": {"min": 92}
  },
  "frequency": "1min|5min|15min|continuous"
}

GET /api/v1/er/critical/alerts
- Purpose: Retrieve active critical patient alerts - Authentication: Required (clinical staff) - Response: Real-time alerts with patient details and recommended actions

POST /api/v1/er/critical/interventions
- Purpose: Record critical interventions and emergency procedures - Authentication: Required (er_physician) - Request Body:
{
  "patientId": "string",
  "interventionType": "airway|breathing|circulation|disability|exposure",
  "procedure": "string",
  "indication": "string",
  "performedBy": "string",
  "timestamp": "datetime",
  "outcome": "successful|failed|partial",
  "complications": "string",
  "nextSteps": "string"
}

GET /api/v1/er/critical/scores
- Purpose: Calculate and track severity scores (APACHE II, SOFA, qSOFA) - Authentication: Required (clinical staff) - Query Parameters: - patientId: Patient identifier - scoreType: Type of severity score - Response: Calculated scores with trending data

WebSocket Endpoints:

ws://api/v1/er/critical/realtime/{patientId}
- Purpose: Real-time vital signs streaming for critical patients - Authentication: Required (clinical staff) - Data Format: JSON stream of vital signs with timestamps

13.6 Resuscitation Management APIs

REQ-API-050: Resuscitation Documentation

POST /api/v1/er/resuscitation/start
- Purpose: Start resuscitation timer and documentation - Authentication: Required (er_physician, resuscitation_team) - Request Body:
{
  "patientId": "string",
  "arrestType": "cardiac|respiratory|combined",
  "witnesses": "boolean",
  "cprStartTime": "datetime",
  "initialRhythm": "string",
  "teamLeader": "string",
  "teamMembers": ["string"],
  "downtime": "number"
}

POST /api/v1/er/resuscitation/events
- Purpose: Log time-stamped resuscitation events - Authentication: Required (resuscitation_team) - Request Body:
{
  "resuscitationId": "string",
  "events": [
    {
      "timestamp": "datetime",
      "eventType": "compression|ventilation|medication|defibrillation|rosc|asystole",
      "description": "string",
      "performedBy": "string",
      "dosage": "string",
      "route": "string",
      "response": "string"
    }
  ]
}

GET /api/v1/er/resuscitation/{resuscitationId}/timeline
- Purpose: Retrieve complete resuscitation timeline - Authentication: Required (clinical staff) - Response: Chronological timeline with all events, interventions, and outcomes

POST /api/v1/er/resuscitation/medications
- Purpose: Record emergency medications during resuscitation - Authentication: Required (er_physician, pharmacist) - Request Body:
{
  "resuscitationId": "string",
  "medications": [
    {
      "medication": "string",
      "dose": "string",
      "route": "IV|IO|ET|IM",
      "time": "datetime",
      "indication": "string",
      "administeredBy": "string",
      "witnessedBy": "string"
    }
  ]
}

PUT /api/v1/er/resuscitation/outcome
- Purpose: Update resuscitation outcome and end procedure - Authentication: Required (team_leader) - Request Body:
{
  "resuscitationId": "string",
  "outcome": "rosc|death|ongoing",
  "endTime": "datetime",
  "totalDuration": "number",
  "finalDisposition": "icu|ward|morgue|ongoing",
  "familyNotified": "boolean",
  "organDonation": "boolean"
}

13.7 Bed Management APIs

REQ-API-060: ER Bed and Zone Management

GET /api/v1/er/beds/status
- Purpose: Get real-time ER bed availability and occupancy - Authentication: Required (all ER staff) - Response:
{
  "zones": [
    {
      "zoneName": "Resuscitation",
      "zoneColor": "red",
      "totalBeds": 4,
      "availableBeds": 1,
      "beds": [
        {
          "bedId": "R1",
          "status": "occupied|available|maintenance|cleaning",
          "patientId": "string",
          "assignedSince": "datetime",
          "estimatedTurnover": "datetime"
        }
      ]
    }
  ]
}

PUT /api/v1/er/beds/{bedId}/assign
- Purpose: Assign patient to specific ER bed - Authentication: Required (charge_nurse, er_physician) - Request Body:
{
  "patientId": "string",
  "triageLevel": "1-5",
  "expectedDuration": "number",
  "specialRequirements": ["isolation", "monitoring", "oxygen"],
  "assignedBy": "string"
}

PUT /api/v1/er/beds/{bedId}/release
- Purpose: Release ER bed and update availability - Authentication: Required (nursing_staff) - Request Body:
{
  "dischargeTime": "datetime",
  "cleaningRequired": "boolean",
  "maintenanceRequired": "boolean",
  "nextAvailable": "datetime",
  "releasedBy": "string"
}

GET /api/v1/er/beds/zones
- Purpose: Get ER zone configuration and capacity - Authentication: Required (ER staff) - Response: Zone definitions with capacity and current utilization

POST /api/v1/er/beds/transfer
- Purpose: Transfer patient between ER zones or beds - Authentication: Required (charge_nurse) - Request Body:
{
  "patientId": "string",
  "fromBedId": "string",
  "toBedId": "string",
  "reason": "clinical|capacity|isolation",
  "authorizedBy": "string",
  "transferTime": "datetime"
}

13.8 Diagnostic Orders APIs

REQ-API-070: Laboratory and Imaging Integration

POST /api/v1/er/diagnostics/lab/stat
- Purpose: Place STAT laboratory orders for emergency patients - Authentication: Required (er_physician) - Request Body:
{
  "patientId": "string",
  "orderingPhysician": "string",
  "priority": "stat|urgent|routine",
  "tests": [
    {
      "testCode": "string",
      "testName": "string",
      "specimenType": "blood|urine|csf|other",
      "collectionTime": "datetime",
      "clinicalIndication": "string"
    }
  ],
  "expectedTurnaround": "15min|30min|1hr|2hr"
}

POST /api/v1/er/diagnostics/imaging/urgent
- Purpose: Order urgent imaging studies - Authentication: Required (er_physician) - Request Body:
{
  "patientId": "string",
  "studyType": "xray|ct|ultrasound|mri",
  "bodyPart": "string",
  "contrast": "boolean",
  "clinicalHistory": "string",
  "urgency": "stat|urgent|routine",
  "portableRequired": "boolean",
  "specialInstructions": "string"
}

GET /api/v1/er/diagnostics/results/{patientId}
- Purpose: Retrieve all diagnostic results for patient - Authentication: Required (clinical staff) - Query Parameters: - type: lab|imaging|all - status: pending|complete|critical - dateRange: Result date range - Response: Complete results with critical value flagging

POST /api/v1/er/diagnostics/point-of-care
- Purpose: Record point-of-care testing results (glucose, ABG, I-STAT) - Authentication: Required (nursing_staff, er_physician) - Request Body:
{
  "patientId": "string",
  "deviceType": "glucometer|abg|istat|ecg",
  "testResults": {
    "glucose": "number",
    "ph": "number",
    "pco2": "number",
    "po2": "number",
    "hco3": "number",
    "lactate": "number"
  },
  "performedBy": "string",
  "testTime": "datetime",
  "qualityControl": "passed|failed"
}

GET /api/v1/er/diagnostics/critical-values
- Purpose: Get critical lab values requiring immediate attention - Authentication: Required (clinical staff) - Response: Critical results with notification status and physician acknowledgment

13.9 Disposition Management APIs

REQ-API-080: Patient Disposition and Transfer

POST /api/v1/er/disposition/admit
- Purpose: Admit patient to inpatient unit - Authentication: Required (er_physician) - Request Body:
{
  "patientId": "string",
  "admittingService": "medicine|surgery|icu|ccu|stepdown",
  "admittingPhysician": "string",
  "bedRequest": "string",
  "acuity": "stable|monitoring|critical",
  "transferSummary": "string",
  "pendingOrders": ["string"],
  "continuityOfCare": "string"
}

POST /api/v1/er/disposition/discharge
- Purpose: Discharge patient from emergency department - Authentication: Required (er_physician) - Request Body:
{
  "patientId": "string",
  "dischargeDisposition": "home|home-health|snf|rehabilitation",
  "dischargeInstructions": "string",
  "medications": [
    {
      "medication": "string",
      "dosage": "string",
      "frequency": "string",
      "duration": "string",
      "instructions": "string"
    }
  ],
  "followUpInstructions": {
    "provider": "string",
    "timeframe": "string",
    "appointmentScheduled": "boolean"
  },
  "returnPrecautions": "string"
}

POST /api/v1/er/disposition/transfer
- Purpose: Transfer patient to another facility - Authentication: Required (er_physician, social_worker) - Request Body:
{
  "patientId": "string",
  "receivingFacility": "string",
  "transferReason": "higher-level-care|specialty-service|bed-availability",
  "acceptingPhysician": "string",
  "transportMethod": "ambulance|helicopter|private",
  "transferSummary": "string",
  "stabilization": "completed|ongoing",
  "consentObtained": "boolean"
}

POST /api/v1/er/disposition/ama
- Purpose: Document Against Medical Advice discharge - Authentication: Required (er_physician, nursing_supervisor) - Request Body:
{
  "patientId": "string",
  "reasonForLeaving": "string",
  "risksExplained": ["string"],
  "patientUnderstanding": "demonstrated|questionable",
  "witness": "string",
  "consentSigned": "boolean",
  "followUpRecommended": "string"
}

GET /api/v1/er/disposition/pending
- Purpose: Get patients awaiting disposition decisions - Authentication: Required (clinical staff) - Response: List of patients with disposition status and delays

13.10 Consultation Management APIs

REQ-API-090: Specialist Consultation

POST /api/v1/er/consultations/request
- Purpose: Request specialist consultation for ER patient - Authentication: Required (er_physician) - Request Body:
{
  "patientId": "string",
  "consultingService": "cardiology|surgery|neurology|psychiatry|other",
  "urgency": "stat|urgent|routine",
  "clinicalQuestion": "string",
  "relevantHistory": "string",
  "currentFindings": "string",
  "requestingPhysician": "string",
  "preferredConsultant": "string",
  "timeframe": "immediate|within-hour|within-day"
}

GET /api/v1/er/consultations/pending
- Purpose: View pending consultation requests - Authentication: Required (clinical staff, consultants) - Query Parameters: - service: Filter by consulting service - urgency: Filter by urgency level - status: Filter by response status - Response: Pending consultations with wait times

PUT /api/v1/er/consultations/{consultationId}/response
- Purpose: Consultant response to consultation request - Authentication: Required (consulting_physician) - Request Body:
{
  "consultantName": "string",
  "responseTime": "datetime",
  "recommendations": "string",
  "additionalWorkup": ["string"],
  "followUpRequired": "boolean",
  "admissionRecommended": "boolean",
  "urgentIntervention": "boolean",
  "consultationNote": "string"
}

GET /api/v1/er/consultations/on-call
- Purpose: Get current on-call specialist schedule - Authentication: Required (ER staff) - Response: On-call specialists by service with contact information

13.11 Trauma Management APIs

REQ-API-100: Trauma Team Activation

POST /api/v1/er/trauma/activation
- Purpose: Activate trauma team for incoming trauma patient - Authentication: Required (er_physician, ems_coordinator) - Request Body:
{
  "patientInfo": {
    "estimatedAge": "number",
    "gender": "male|female|unknown",
    "mechanismOfInjury": "string"
  },
  "traumaLevel": "level-1|level-2|level-3",
  "eta": "datetime",
  "vitalSigns": {
    "systolicBP": "number",
    "heartRate": "number",
    "gcs": "number",
    "respiratoryRate": "number"
  },
  "injuries": ["string"],
  "activatedBy": "string",
  "teamMembers": ["string"]
}

POST /api/v1/er/trauma/assessment
- Purpose: Document primary and secondary trauma survey - Authentication: Required (trauma_physician) - Request Body:
{
  "patientId": "string",
  "surveyType": "primary|secondary",
  "airway": "patent|compromised|secured",
  "breathing": "adequate|inadequate|assisted",
  "circulation": "stable|unstable|shock",
  "disability": {
    "gcs": "number",
    "pupils": "reactive|non-reactive|unequal",
    "motorFunction": "string"
  },
  "exposure": "string",
  "injuries": [
    {
      "bodyRegion": "head|neck|chest|abdomen|pelvis|extremities",
      "injuryType": "penetrating|blunt|burn",
      "severity": "minor|moderate|severe|critical",
      "description": "string"
    }
  ]
}

GET /api/v1/er/trauma/protocols
- Purpose: Retrieve trauma management protocols - Authentication: Required (trauma_team) - Query Parameters: - mechanism: Mechanism of injury - bodyRegion: Affected body region - severity: Injury severity - Response: Relevant protocols and management guidelines

POST /api/v1/er/trauma/injuries
- Purpose: Document detailed injury assessment - Authentication: Required (trauma_physician, trauma_nurse) - Request Body:
{
  "patientId": "string",
  "injuries": [
    {
      "injuryCode": "string",
      "anatomicLocation": "string",
      "description": "string",
      "severity": "1-6",
      "images": ["string"],
      "interventionsRequired": ["string"]
    }
  ]
}

GET /api/v1/er/trauma/scores
- Purpose: Calculate injury severity scores (ISS, RTS, TRISS) - Authentication: Required (trauma_team) - Query Parameters: - patientId: Patient identifier - scoreType: Type of trauma score - Response: Calculated scores with survival probability

13.12 Dashboard and Monitoring APIs

REQ-API-110: Real-time Dashboard

GET /api/v1/er/dashboard/overview
- Purpose: Get comprehensive ER dashboard metrics - Authentication: Required (all ER staff) - Response:
{
  "census": {
    "totalPatients": "number",
    "byTriageLevel": {
      "level1": "number",
      "level2": "number",
      "level3": "number",
      "level4": "number",
      "level5": "number"
    },
    "bedOccupancy": {
      "total": "number",
      "occupied": "number",
      "available": "number",
      "blocked": "number"
    }
  },
  "waitTimes": {
    "averageToTriage": "number",
    "averageToProvider": "number",
    "averageLength": "number",
    "byTriageLevel": {}
  },
  "throughput": {
    "arrivals": "number",
    "discharges": "number",
    "admissions": "number",
    "transfers": "number"
  }
}

GET /api/v1/er/dashboard/wait-times
- Purpose: Get current wait times by triage level - Authentication: Required (ER staff) - Response: Real-time wait times with trending data

GET /api/v1/er/dashboard/capacity
- Purpose: Get ER capacity and utilization metrics - Authentication: Required (management staff) - Response: Capacity metrics with forecasting

GET /api/v1/er/dashboard/los
- Purpose: Get length of stay metrics and analytics - Authentication: Required (management staff) - Query Parameters: - period: Time period for analysis - triageLevel: Filter by triage level - disposition: Filter by discharge disposition - Response: LOS metrics with statistical analysis

WebSocket Endpoints:

ws://api/v1/er/dashboard/updates
- Purpose: Real-time dashboard updates - Authentication: Required (ER staff) - Data Format: JSON stream of dashboard metric updates

13.13 Integration and External APIs

REQ-API-120: External System Integration

POST /api/v1/er/ambulance/incoming
- Purpose: EMS pre-arrival notification and patient information - Authentication: Required (ems_system, dispatch_center) - Request Body:
{
  "ambulanceId": "string",
  "eta": "datetime",
  "patient": {
    "estimatedAge": "number",
    "gender": "string",
    "chiefComplaint": "string",
    "vitalSigns": {},
    "treatments": ["string"]
  },
  "incident": {
    "type": "string",
    "location": "string",
    "mechanismOfInjury": "string"
  },
  "crew": {
    "paramedic": "string",
    "emt": "string",
    "contactNumber": "string"
  }
}

GET /api/v1/er/referrals/incoming
- Purpose: Get incoming referrals from other facilities - Authentication: Required (ER staff) - Response: Pending referrals with patient information and transfer details

POST /api/v1/er/notifications/code
- Purpose: Activate hospital-wide emergency codes - Authentication: Required (er_physician, charge_nurse) - Request Body:
{
  "codeType": "blue|stroke|stemi|sepsis|trauma",
  "location": "string",
  "patientId": "string",
  "activatedBy": "string",
  "timestamp": "datetime",
  "additionalInfo": "string"
}

POST /api/v1/er/handoff/nursing
- Purpose: Document nursing handoff and shift reports - Authentication: Required (nursing_staff) - Request Body:
{
  "patientId": "string",
  "fromNurse": "string",
  "toNurse": "string",
  "shift": "day|evening|night",
  "handoffTime": "datetime",
  "patientCondition": "string",
  "pendingTasks": ["string"],
  "keyInformation": "string",
  "familyUpdates": "string"
}

13.14 WebSocket Real-time Endpoints

13.14.1 Real-time Vital Signs Monitoring

WebSocket Connection: ws://api/v1/er/monitoring/vitals/{patientId}

// WebSocket for real-time vital signs monitoring
const vitalSignsWebSocket = {
  connection_url: 'ws://api.meditech.hospital.th/v1/er/monitoring/vitals/pt-uuid-123',
  authentication: {
    protocol: 'WebSocket subprotocol',
    token: 'Bearer <jwt_token>',
    headers: {
      'Authorization': 'Bearer <jwt_token>',
      'X-Hospital-ID': 'hospital-uuid-123',
      'X-Department-ID': 'emergency-dept-uuid'
    }
  },

  // Subscribe to patient vital signs
  subscribe_message: {
    action: 'SUBSCRIBE',
    patientId: 'pt-uuid-123',
    monitoringDevice: 'bedside-monitor-001',
    parameters: ['heartRate', 'bloodPressure', 'oxygenSaturation', 'temperature']
  },

  // Real-time vital signs data stream
  vital_signs_data: {
    patientId: 'pt-uuid-123',
    deviceId: 'bedside-monitor-001',
    timestamp: '2024-08-18T10:30:15.000Z',
    measurements: {
      heartRate: {
        value: 75,
        unit: 'bpm',
        trend: 'stable'
      },
      bloodPressure: {
        systolic: 120,
        diastolic: 80,
        unit: 'mmHg',
        trend: 'decreasing'
      },
      oxygenSaturation: {
        value: 98,
        unit: '%',
        trend: 'stable'
      },
      temperature: {
        value: 36.5,
        unit: '°C',
        trend: 'stable'
      }
    },
    alerts: [
      {
        type: 'VITAL_SIGN_ALERT',
        parameter: 'heartRate',
        severity: 'medium',
        message: 'Heart rate trending upward',
        threshold: 100,
        currentValue: 95
      }
    ],
    quality: {
      signalStrength: 'strong',
      artifactDetection: false,
      calibrationStatus: 'valid'
    }
  }
};

13.14.2 Real-time Queue Management

WebSocket Connection: ws://api/v1/er/queue/updates

// WebSocket connection for real-time queue updates
const queueWebSocket = {
  connection_url: 'ws://api.meditech.hospital.th/v1/er/queue/updates',
  authentication: {
    protocol: 'WebSocket subprotocol',
    token: 'Bearer <jwt_token>',
    headers: {
      'Authorization': 'Bearer <jwt_token>',
      'X-Department-ID': 'emergency-dept-uuid'
    }
  },

  // Client subscribes to queue channels
  subscribe_message: {
    action: 'SUBSCRIBE',
    channels: [
      'queue.department.emergency-dept-uuid',
      'queue.triage-level.1',
      'queue.triage-level.2'
    ],
    filters: {
      triageLevel: [1, 2, 3],
      status: ['waiting', 'in-progress']
    }
  },

  // Server sends real-time queue updates
  queue_update_message: {
    channel: 'queue.department.emergency-dept-uuid',
    event: 'QUEUE_UPDATED',
    timestamp: '2024-08-18T10:30:00.000Z',
    data: {
      patientId: 'pt-uuid-123',
      queueNumber: 'ER-025',
      triageLevel: 2,
      status: 'called', // waiting, called, in-progress, completed
      estimatedWaitTime: 15, // minutes
      currentPosition: 3,
      totalInQueue: 12,
      physicianAssigned: 'dr-uuid-456',
      bedAssigned: 'ER-BED-05',
      lastUpdate: '2024-08-18T10:29:45.000Z'
    }
  }
};

13.14.3 Critical Patient Alerts

WebSocket Connection: ws://api/v1/er/alerts/critical

// WebSocket for critical patient alerts and notifications
const criticalAlertsWebSocket = {
  connection_url: 'ws://api.meditech.hospital.th/v1/er/alerts/critical',
  authentication: {
    protocol: 'WebSocket subprotocol',
    token: 'Bearer <jwt_token>'
  },

  // Subscribe to critical alert types
  subscribe_message: {
    action: 'SUBSCRIBE',
    alertTypes: [
      'CARDIAC_ARREST',
      'RESPIRATORY_FAILURE', 
      'TRAUMA_ACTIVATION',
      'SEPSIS_ALERT',
      'STROKE_ALERT'
    ],
    departments: ['emergency-dept-uuid']
  },

  // Critical alert message format
  critical_alert_message: {
    alertId: 'alert-uuid-123',
    alertType: 'CARDIAC_ARREST',
    priority: 'critical',
    timestamp: '2024-08-18T10:30:00.000Z',
    patient: {
      patientId: 'pt-uuid-123',
      name: 'สมชาย ใจดี',
      age: 55,
      gender: 'male',
      bedLocation: 'ER-BED-01'
    },
    details: {
      vitalSigns: {
        heartRate: 0,
        bloodPressure: '0/0',
        oxygenSaturation: 85
      },
      witness: true,
      cprStarted: true,
      teamActivated: true,
      estimatedDownTime: '2 minutes'
    },
    actions: [
      {
        label: 'Acknowledge Alert',
        action: 'ACKNOWLEDGE',
        requiresRole: 'ER_PHYSICIAN'
      },
      {
        label: 'Start Resuscitation Timer',
        action: 'START_RESUSCITATION',
        requiresRole: 'TRAUMA_TEAM_LEADER'
      }
    ],
    autoActions: {
      traumaTeamNotified: true,
      bedCleared: true,
      equipmentPrepared: true
    }
  }
};

13.14.4 Real-time Bed Status

WebSocket Connection: ws://api/v1/er/beds/status

// WebSocket for real-time bed status updates
const bedStatusWebSocket = {
  connection_url: 'ws://api.meditech.hospital.th/v1/er/beds/status',
  authentication: {
    protocol: 'WebSocket subprotocol',
    token: 'Bearer <jwt_token>'
  },

  // Subscribe to bed status updates
  subscribe_message: {
    action: 'SUBSCRIBE',
    zones: ['resuscitation', 'acute', 'fast-track'],
    bedTypes: ['all']
  },

  // Bed status update message
  bed_status_update: {
    bedId: 'ER-BED-05',
    zoneName: 'Acute Care',
    status: 'occupied', // available, occupied, cleaning, maintenance, blocked
    patientId: 'pt-uuid-123',
    assignedSince: '2024-08-18T09:45:00.000Z',
    estimatedTurnover: '2024-08-18T12:00:00.000Z',
    specialRequirements: ['isolation', 'monitoring'],
    equipment: {
      monitor: 'connected',
      oxygen: 'available',
      suction: 'available'
    },
    cleaning: {
      required: false,
      inProgress: false,
      completedAt: null
    },
    assignedStaff: {
      primaryNurse: 'nurse-uuid-789',
      physician: 'dr-uuid-456'
    },
    timestamp: '2024-08-18T10:30:00.000Z'
  }
};

13.15 API Security and Compliance

13.15.1 Authentication & Authorization Framework

const apiSecurity = {
  authentication: {
    method: 'JWT Bearer Token',
    token_expiry: {
      access_token: '15 minutes',
      refresh_token: '24 hours',
      emergency_override: '2 hours'
    },
    token_structure: {
      header: {
        alg: 'RS256',
        typ: 'JWT'
      },
      payload: {
        sub: 'user-uuid-123',
        hospitalId: 'hospital-uuid-123',
        roles: ['ER_PHYSICIAN', 'TRAUMA_TEAM_LEADER'],
        departments: ['emergency-dept-uuid'],
        permissions: [
          'TRIAGE_ASSESSMENT',
          'EMERGENCY_ORDERS', 
          'CRITICAL_CARE_ACCESS',
          'TRAUMA_ACTIVATION'
        ],
        emergency_override: false,
        iat: 1692347400,
        exp: 1692433800
      }
    }
  },

  authorization: {
    rbac_model: {
      roles: [
        {
          name: 'ER_PHYSICIAN',
          permissions: [
            'READ_PATIENT_DATA',
            'WRITE_CLINICAL_NOTES',
            'CREATE_ORDERS',
            'DISPOSITION_DECISIONS',
            'TRAUMA_ACTIVATION',
            'RESUSCITATION_CONTROL'
          ]
        },
        {
          name: 'TRIAGE_NURSE',
          permissions: [
            'PATIENT_REGISTRATION',
            'TRIAGE_ASSESSMENT',
            'VITAL_SIGNS_RECORDING',
            'QUEUE_MANAGEMENT'
          ]
        },
        {
          name: 'ER_NURSE', 
          permissions: [
            'READ_PATIENT_DATA',
            'MEDICATION_ADMINISTRATION',
            'VITAL_SIGNS_RECORDING',
            'TASK_MANAGEMENT',
            'BED_ASSIGNMENT'
          ]
        },
        {
          name: 'CHARGE_NURSE',
          permissions: [
            'ALL_NURSING_PERMISSIONS',
            'BED_MANAGEMENT',
            'STAFF_COORDINATION',
            'RESOURCE_ALLOCATION'
          ]
        }
      ]
    }
  }
};

// Authentication Flow Examples
const authenticationFlow = {
  // 1. Login Request
  loginRequest: {
    method: 'POST',
    endpoint: '/api/v1/auth/login',
    body: {
      username: 'dr.somchai',
      password: 'secure_password',
      department: 'emergency-dept-uuid',
      deviceInfo: {
        deviceId: 'workstation-er-01',
        ipAddress: '192.168.1.100',
        userAgent: 'Mozilla/5.0...'
      }
    }
  },

  // 2. Login Response
  loginResponse: {
    success: true,
    data: {
      accessToken: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...',
      refreshToken: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...',
      expiresIn: 900, // 15 minutes
      user: {
        userId: 'dr-uuid-123',
        username: 'dr.somchai',
        displayName: 'นพ.สมชาย ใจดี',
        roles: ['ER_PHYSICIAN'],
        departments: ['emergency-dept-uuid']
      }
    },
    message: 'Authentication successful',
    timestamp: '2024-08-18T10:00:00.000Z'
  },

  // 3. Token Refresh Request
  refreshTokenRequest: {
    method: 'POST',
    endpoint: '/api/v1/auth/refresh',
    body: {
      refreshToken: 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9...'
    }
  }
};

13.15.2 Audit Trail and Compliance APIs

GET /api/v1/er/audit-logs/patient/{patientId}

// Patient access audit logs
const getPatientAuditRequest = {
  method: 'GET',
  endpoint: '/api/v1/er/audit-logs/patient/pt-uuid-123',
  headers: {
    'Authorization': 'Bearer <jwt_token>',
    'Content-Type': 'application/json'
  },
  query_params: {
    startDate: '2024-08-01',
    endDate: '2024-08-18',
    action: 'READ', // CREATE, READ, UPDATE, DELETE, EXPORT
    userId: 'user-uuid-123', // Optional
    page: 1,
    limit: 50
  }
};

const getPatientAuditResponse = {
  success: true,
  data: {
    patient: {
      patientId: 'pt-uuid-123',
      name: 'สมชาย ใจดี',
      hn: 'HN001234567'
    },
    logs: [
      {
        logId: 'log-uuid-123',
        timestamp: '2024-08-18T10:30:00.000Z',
        userId: 'dr-uuid-123',
        userName: 'นพ.สมชาย ใจดี',
        role: 'ER_PHYSICIAN',
        action: 'READ',
        resource: 'patient_medical_record',
        details: {
          recordId: 'rec-uuid-123',
          visitId: 'visit-uuid-123',
          dataAccessed: ['demographics', 'vital_signs', 'triage_assessment']
        },
        ipAddress: '192.168.1.100',
        userAgent: 'Mozilla/5.0...',
        sessionId: 'session-uuid-123',
        justification: 'Emergency care consultation'
      }
    ],
    pagination: {
      page: 1,
      limit: 50,
      total: 125,
      totalPages: 3
    }
  },
  message: 'Audit logs retrieved successfully',
  timestamp: '2024-08-18T10:31:00.000Z'
};

POST /api/v1/er/consent/patient/{patientId}

// Record patient consent for emergency care
const recordConsentRequest = {
  method: 'POST',
  endpoint: '/api/v1/er/consent/patient/pt-uuid-123',
  body: {
    consentType: 'EMERGENCY_TREATMENT', // EMERGENCY_TREATMENT, DATA_PROCESSING, RESEARCH_PARTICIPATION
    consentGiven: true,
    consentDate: '2024-08-18T09:00:00.000Z',
    consentMethod: 'VERBAL_WITNESSED', // VERBAL_WITNESSED, DIGITAL_SIGNATURE, WRITTEN_FORM, IMPLIED_CONSENT
    emergencyCircumstances: {
      unconsciousPatient: false,
      lifeThreateningCondition: true,
      unableToConsent: false,
      familyNotAvailable: false
    },
    consentDetails: {
      treatmentTypes: ['EMERGENCY_PROCEDURES', 'MEDICATION_ADMINISTRATION', 'DIAGNOSTIC_TESTS'],
      dataUsage: ['TREATMENT', 'CLINICAL_DOCUMENTATION', 'QUALITY_IMPROVEMENT'],
      disclosures: ['CONSULTING_PHYSICIANS', 'NURSING_STAFF', 'INSURANCE_REPORTING']
    },
    witnessId: 'nurse-uuid-123',
    witnessName: 'พยาบาลสมหญิง ใจดี',
    documentId: 'consent-form-uuid-123'
  }
};

const recordConsentResponse = {
  success: true,
  data: {
    consentId: 'consent-uuid-123',
    patientId: 'pt-uuid-123',
    status: 'ACTIVE',
    effectiveDate: '2024-08-18T09:00:00.000Z',
    expiryDate: null, // Emergency consent doesn't expire
    digitalSignature: null,
    auditTrail: {
      recordedBy: 'dr-uuid-123',
      recordedAt: '2024-08-18T09:00:00.000Z',
      ipAddress: '192.168.1.100'
    }
  },
  message: 'Emergency consent recorded successfully',
  timestamp: '2024-08-18T09:01:00.000Z'
};

13.15.3 API Performance Requirements

const apiPerformanceStandards = {
  response_time_targets: {
    critical_endpoints: {
      target: '< 200ms',
      measurement: '95th percentile',
      timeout: '5 seconds',
      endpoints: [
        '/api/v1/er/triage/assessment',
        '/api/v1/er/critical/alerts',
        '/api/v1/er/resuscitation/start'
      ]
    },
    standard_clinical: {
      target: '< 500ms',
      measurement: '95th percentile', 
      timeout: '10 seconds',
      endpoints: [
        '/api/v1/er/treatments/orders',
        '/api/v1/er/patients/register',
        '/api/v1/er/beds/assign'
      ]
    },
    complex_queries: {
      target: '< 2s',
      measurement: '90th percentile',
      timeout: '30 seconds',
      endpoints: [
        '/api/v1/er/dashboard/overview',
        '/api/v1/er/reports/generate',
        '/api/v1/er/statistics/analytics'
      ]
    }
  },

  rate_limiting: {
    'CRITICAL_ENDPOINTS': {
      limit: '200 requests/minute',
      burst: 50,
      window: '60 seconds'
    },
    'CLINICAL_ENDPOINTS': {
      limit: '100 requests/minute', 
      burst: 25,
      window: '60 seconds'
    },
    'ADMINISTRATIVE': {
      limit: '50 requests/minute',
      burst: 10,
      window: '60 seconds'
    }
  },

  high_availability: {
    uptime_requirement: '99.99%',
    maximum_downtime_per_month: '4.32 minutes',
    failover_time: '< 30 seconds',
    data_replication: 'Real-time',
    backup_frequency: 'Every 15 minutes',
    disaster_recovery_rto: '< 4 hours',
    disaster_recovery_rpo: '< 15 minutes'
  }
};

13.15.4 Data Encryption and Privacy

const dataProtectionStandards = {
  encryption: {
    in_transit: 'TLS 1.3',
    at_rest: 'AES-256',
    key_management: 'Hardware Security Module (HSM)',
    sensitive_fields: [
      'nationalId',
      'passportNumber', 
      'phoneNumber',
      'email',
      'emergencyContactInfo',
      'medicalRecordNumber'
    ]
  },

  privacy_compliance: {
    pdpa_requirements: {
      consent_management: true,
      data_portability: true,
      right_to_erasure: true,
      data_minimization: true,
      purpose_limitation: true
    },

    anonymization: {
      patient_identifiers_masked: true,
      statistical_disclosure_control: true,
      k_anonymity_level: 5
    }
  },

  access_controls: {
    principle_of_least_privilege: true,
    need_to_know_basis: true,
    emergency_break_glass: {
      enabled: true,
      requires_justification: true,
      automatic_audit_flag: true
    }
  }
};

13.15.5 Error Handling and Monitoring

// Standard Error Response Format
interface ApiErrorResponse {
  success: false;
  error: {
    code: string;
    message: string;
    details?: any;
    field?: string; // For validation errors
    errorId: string; // Unique error tracking ID
  };
  timestamp: string;
  requestId: string;
  statusCode: number;
}

// Error Categories and Codes
const errorCodes = {
  AUTHENTICATION: {
    'AUTH_001': 'Invalid credentials',
    'AUTH_002': 'Token expired',
    'AUTH_003': 'Insufficient permissions',
    'AUTH_004': 'Account locked'
  },
  VALIDATION: {
    'VAL_001': 'Required field missing',
    'VAL_002': 'Invalid data format',
    'VAL_003': 'Data out of range',
    'VAL_004': 'Business rule violation'
  },
  CLINICAL: {
    'CLIN_001': 'Patient not found',
    'CLIN_002': 'Invalid clinical data',
    'CLIN_003': 'Triage assessment incomplete',
    'CLIN_004': 'Order cannot be processed'
  },
  SYSTEM: {
    'SYS_001': 'Database connection failed',
    'SYS_002': 'External service unavailable',
    'SYS_003': 'Rate limit exceeded',
    'SYS_004': 'Internal server error'
  }
};

// Monitoring and Alerting
const monitoringRequirements = {
  metrics: {
    response_times: 'Real-time percentile tracking',
    error_rates: 'Alert if > 1% for critical endpoints',
    throughput: 'Requests per second monitoring',
    availability: 'Uptime monitoring with 1-minute granularity'
  },

  alerts: {
    critical_errors: 'Immediate notification to on-call team',
    performance_degradation: 'Alert if response time > 2x normal',
    security_incidents: 'Real-time security team notification',
    capacity_limits: 'Alert at 80% capacity utilization'
  }
};

14. การส่งมอบและการดูแลระบบ (Delivery & Maintenance)

14.1 Delivery Requirements

DEL-001: Implementation Phases - Phase 1: Core triage and registration (Month 1-2) - Phase 2: CPOE and clinical documentation (Month 3-4) - Phase 3: Integration and reporting (Month 5-6) - Phase 4: Advanced features and optimization (Month 7-8)

DEL-002: Go-Live Support - Technical support team on-site - Clinical workflow support - Issue escalation procedures - Performance monitoring

14.2 Maintenance and Support

MAINT-001: Ongoing Support - 24/7 emergency support - Regular maintenance windows - Software updates and patches - Hardware maintenance coordination

MAINT-002: System Enhancement - Feature enhancement requests - Performance optimization - Integration updates - Regulatory compliance updates


15. สรุปและการอนุมัติ (Summary & Approval)

15.1 Key Success Factors

  1. Clinical Workflow Alignment: System must seamlessly integrate with existing emergency medicine workflows
  2. Performance Reliability: System must perform reliably under high-stress emergency conditions
  3. Integration Success: Successful integration with existing hospital systems
  4. User Adoption: High user adoption rates among clinical staff
  5. Regulatory Compliance: Full compliance with healthcare regulations

15.2 Project Success Metrics

  • Clinical Metrics:
  • Triage time reduction: 25%
  • Length of stay reduction: 15%
  • Clinical documentation completeness: >95%

  • Technical Metrics:

  • System availability: >99.9%
  • Response time compliance: >95%
  • Integration success rate: 100%

  • User Metrics:

  • User satisfaction score: >4.5/5
  • Training completion rate: 100%
  • User adoption rate: >90%

15.3 Approval Process

Stakeholder Sign-offs Required: - Chief Medical Officer - Emergency Department Director - IT Director - Quality Assurance Manager - Project Sponsor


16. ภาคผนวก (Appendices)

Appendix A: Emergency Severity Index (ESI) Guidelines

Level 1 - Resuscitation (Red) - Requires immediate life-saving intervention - Examples: Cardiac arrest, respiratory failure, severe trauma - Target time to physician: Immediate

Level 2 - Emergent (Orange) - High-risk situation, confused/lethargic/disoriented - Examples: Chest pain, difficulty breathing, severe pain - Target time to physician: ≤ 15 minutes

Level 3 - Urgent (Yellow) - Potentially serious, many resources needed - Examples: Moderate pain, fever, vomiting - Target time to physician: ≤ 30 minutes

Level 4 - Less Urgent (Green) - Potentially serious, few resources needed - Examples: Minor injuries, simple complaints - Target time to physician: ≤ 60 minutes

Level 5 - Non-urgent (Blue) - Not serious, minimal resources needed - Examples: Prescription refills, routine follow-ups - Target time to physician: ≤ 120 minutes

Appendix B: Technical Architecture Diagram

[Emergency Department System Architecture]

Frontend Layer:
├── Next.js 14 Web Application
├── Mobile PWA
├── Kiosk Interface (Electron)
└── Dashboard Displays

API Gateway:
├── Authentication Service
├── Rate Limiting
├── Load Balancing
└── Request Routing

Backend Services (NestJS):
├── Triage Service
├── Clinical Documentation Service
├── CPOE Service
├── Notification Service
├── Integration Service
└── Reporting Service

Data Layer:
├── PostgreSQL Primary Database
├── Redis Cache
├── File Storage (Images/Videos)
└── Backup Systems

External Integrations:
├── EMR Core System
├── Laboratory System
├── Radiology System
├── Pharmacy System
├── NHSO/SSO APIs
└── EMS Systems

Appendix C: Database Schema Overview

Core ER Tables: - er_visits - Emergency department visits - triage_assessments - Triage evaluations - er_clinical_notes - Clinical documentation - er_orders - Medical orders specific to ER - er_tasks - Nursing and clinical tasks - er_bed_management - Bed assignment tracking

Integration Tables: - ems_handovers - EMS to hospital handover data - er_transfers - Patient transfer records - er_discharge_summaries - Discharge documentation

Appendix D: API Endpoints Specification

Core API Endpoints:

POST /api/v1/er/triage - Create triage assessment
GET /api/v1/er/dashboard - Get ER dashboard data
POST /api/v1/er/clinical-notes - Save clinical documentation
GET /api/v1/er/patient/{id}/timeline - Get patient timeline
POST /api/v1/er/orders - Create medical orders
GET /api/v1/er/tasks/nursing - Get nursing tasks
PUT /api/v1/er/tasks/{id}/complete - Mark task complete

Appendix E: Compliance Checklist

PDPA Compliance: - [ ] Data consent management - [ ] Right to access implementation - [ ] Right to rectification - [ ] Right to erasure - [ ] Data portability - [ ] Privacy impact assessment

Healthcare Regulations: - [ ] Medical record completeness - [ ] Provider authentication - [ ] Audit trail completeness - [ ] Data retention compliance - [ ] Emergency medicine standards


Document Approval:

Role Name Signature Date
Project Manager
Emergency Department Director
IT Director
Chief Medical Officer
Quality Assurance Manager

Document History:

Version Date Author Description
1.0 28 สิงหาคม 2025 System Analyst Initial SRS document

This document serves as the comprehensive Software Requirements Specification for the Emergency Room System as part of the MediTech Hospital Information System. All requirements outlined herein must be validated and approved by relevant stakeholders before proceeding with system development.