# HIS Simulator - Complete Implementation Guide

## Overview

The HIS (Hospital Information System) simulator is a continuous event generator that simulates patient journeys through the healthcare system and sends survey invitations when journeys are complete.

## Architecture

```
┌─────────────────┐
│   HIS Simulator │
│   (Python)      │
└────────┬────────┘
         │ Sends events
         ↓
┌─────────────────┐
│   PX360 API     │
│   /api/simulator│
│   /his-events/  │
└────────┬────────┘
         │
         ├─► Creates Patient
         ├─► Creates Journey Instance
         ├─► Completes Stages
         └─► Sends Survey
                 │
                 ↓
         ┌───────────────┐
         │ Notifications │
         │ Service       │
         └───────────────┘
                 │
        ┌────────┴────────┐
        ↓                 ↓
   Email Simulator   SMS Simulator
   (Terminal + SMTP)  (Terminal)
```

## Components

### 1. Journey Templates & Surveys
**File:** `apps/simulator/management/commands/seed_journey_surveys.py`

Creates:
- **EMS Journey** (2-4 random stages)
  - Stages: Ambulance Dispatch, On Scene Care, Patient Transport, Hospital Handoff
  - Survey: EMS Experience Survey (4 questions)
  
- **Inpatient Journey** (3-6 random stages)
  - Stages: Admission, Treatment, Nursing Care, Lab Tests, Radiology, Discharge
  - Survey: Inpatient Experience Survey (7 questions)
  
- **OPD Journey** (3-5 random stages)
  - Stages: Registration, Consultation, Lab Tests, Radiology, Pharmacy
  - Survey: OPD Experience Survey (7 questions)

### 2. HIS Simulator Script
**File:** `apps/simulator/his_simulator.py`

Features:
- Continuous event generation (infinite or limited)
- Generates realistic patient data (Arabic names, Saudi phone numbers)
- Creates both full and partial journeys (40% full, 60% partial)
- Sends events to PX360 API
- Displays statistics every 10 patients
- Configurable delay between events

### 3. API Endpoint
**File:** `apps/simulator/views.py` - `his_events_handler()`

Endpoint: `POST /api/simulator/his-events/`

Processes:
1. Patient creation/retrieval
2. Journey instance creation
3. Stage instance completion
4. Post-discharge survey sending (when journey complete)

### 4. Survey Sending
**File:** `apps/simulator/views.py` - `send_post_discharge_survey()`

When journey is complete:
- Creates `SurveyInstance`
- Sends email via `NotificationService.send_survey_invitation()`
- Sends SMS via `NotificationService.send_sms()`
- Both email and SMS contain secure survey link

## Setup Instructions

### Step 1: Seed Journey Templates and Surveys

```bash
# Run management command
python manage.py seed_journey_surveys
```

This creates:
- Hospital: Al Hammadi Hospital (ALH-main)
- Departments: Emergency, Cardiology, Orthopedics, Pediatrics, Lab, Radiology, Pharmacy, Nursing
- 3 Journey Templates (EMS, Inpatient, OPD) with random stages
- 3 Survey Templates with bilingual questions

### Step 2: Start Django Server

```bash
# In one terminal
python manage.py runserver
```

### Step 3: Run HIS Simulator

```bash
# In another terminal
python apps/simulator/his_simulator.py
```

**Options:**
```bash
# Default settings (infinite patients, 5 second delay)
python apps/simulator/his_simulator.py

# Custom URL
python apps/simulator/his_simulator.py --url http://localhost:8000/api/simulator/his-events/

# Custom delay (10 seconds between patients)
python apps/simulator/his_simulator.py --delay 10

# Limited patients (stop after 20 patients)
python apps/simulator/his_simulator.py --max-patients 20

# Combined options
python apps/simulator/his_simulator.py --url http://localhost:8000/api/simulator/his-events/ --delay 3 --max-patients 50
```

## Expected Output

### HIS Simulator Output

```
======================================================================
🏥 HIS SIMULATOR - Patient Journey Event Generator
======================================================================
API URL: http://localhost:8000/api/simulator/his-events/
Delay: 5 seconds between events
Max Patients: Infinite
======================================================================

Starting simulation... Press Ctrl+C to stop

📤 Sending 4 events for Ahmed Al-Saud...

✅ 🏥 Patient Journey Created
   Patient: Ahmed Al-Saud
   Encounter ID: ENC-2024-00123
   Type: OPD - Partial Journey
   Stages: 3/5 completed
   API Status: Success
```

### Email Simulator Output (in Django terminal)

```
╔═══════════════════════════════════════════════════════════════════════════════╗
║               📧 EMAIL SIMULATOR                                         ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ Request #: 1                                                               ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ To:      ahmed.alsaud@gmail.com                                             ║
║ Subject: Your Experience Survey - Al Hammadi Hospital                        ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ Message:                                                                     ║
║         Dear Ahmed Al-Saud,                                                  ║
║         Thank you for your visit to Al Hammadi Hospital.                    ║
║         We value your feedback and would appreciate if you could take        ║
║         a few minutes to complete our survey.                               ║
║         Survey Link: http://localhost:8000/surveys/abc123xyz/               ║
╚═══════════════════════════════════════════════════════════════════════════════╝
```

### SMS Simulator Output (in Django terminal)

```
╔═══════════════════════════════════════════════════════════════════════════════╗
║               📱 SMS SIMULATOR                                              ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ Request #: 1                                                               ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ To:      +966501234567                                                       ║
║ Time:    2024-01-20 16:30:00                                                ║
╠═══════════════════════════════════════════════════════════════════════════════╣
║ Message:                                                                     ║
║         Your experience survey is ready:                                      ║
║         http://localhost:8000/surveys/abc123xyz/                             ║
╚═══════════════════════════════════════════════════════════════════════════════╝
```

## Statistics Output (every 10 patients)

```
======================================================================
📊 SIMULATION STATISTICS
======================================================================
Total Journeys: 10
Successful: 10 (100.0%)
Failed: 0
Full Journeys: 4
Partial Journeys: 6
EMS Journeys: 3
Inpatient Journeys: 4
OPD Journeys: 3
Total Events Sent: 38
======================================================================
```

## Testing Scenarios

### Scenario 1: Full Journey with Survey

1. HIS simulator generates patient with full OPD journey (5 stages)
2. All 5 events sent to API
3. Journey marked as complete
4. Survey instance created
5. Email and SMS sent with survey link

**Check:**
```bash
# Check survey was created
python manage.py shell
>>> from apps.surveys.models import SurveyInstance
>>> SurveyInstance.objects.count()  # Should be > 0
>>> survey = SurveyInstance.objects.first()
>>> survey.status  # Should be 'pending'
>>> survey.get_survey_url()  # Should return URL
```

### Scenario 2: Partial Journey (No Survey)

1. HIS simulator generates patient with partial EMS journey (2 of 4 stages)
2. Only 2 events sent to API
3. Journey NOT complete
4. NO survey created
5. NO email/SMS sent

**Check:**
```bash
# Check journey status
python manage.py shell
>>> from apps.journeys.models import PatientJourneyInstance
>>> journey = PatientJourneyInstance.objects.last()
>>> journey.is_complete()  # Should be False
```

### Scenario 3: Multiple Stages

1. Patient starts journey
2. First stage completed → journey created
3. Second stage completed → journey updated
4. Third stage completed → journey still not complete
5. Fourth stage completed → journey complete → survey sent

**Check:**
```bash
# Check stage instances
python manage.py shell
>>> from apps.journeys.models import PatientJourneyStageInstance, StageStatus
>>> journey = PatientJourneyInstance.objects.last()
>>> stages = journey.stage_instances.all()
>>> for stage in stages:
...     print(f"{stage.stage_template.name}: {stage.status}")
```

## API Response Format

**Successful Response:**
```json
{
  "success": true,
  "message": "Processed 4 events successfully",
  "results": [
    {
      "encounter_id": "ENC-2024-00123",
      "patient_id": "uuid",
      "journey_id": "uuid",
      "stage_id": "uuid",
      "stage_status": "completed",
      "survey_sent": true,
      "survey_id": "uuid",
      "survey_url": "/surveys/abc123xyz/",
      "delivery_channel": "email_and_sms"
    }
  ],
  "surveys_sent": 1,
  "survey_details": [
    {
      "encounter_id": "ENC-2024-00123",
      "survey_id": "uuid",
      "survey_url": "/surveys/abc123xyz/"
    }
  ]
}
```

**Partial Journey Response (no survey):**
```json
{
  "success": true,
  "message": "Processed 2 events successfully",
  "results": [
    {
      "encounter_id": "ENC-2024-00124",
      "patient_id": "uuid",
      "journey_id": "uuid",
      "stage_id": "uuid",
      "stage_status": "completed",
      "survey_sent": false
    }
  ],
  "surveys_sent": 0,
  "survey_details": []
}
```

## Troubleshooting

### Issue: "No active journey template found"

**Cause:** Journey templates not seeded

**Solution:**
```bash
python manage.py seed_journey_surveys
```

### Issue: Survey not sent after journey completion

**Check:**
1. Journey template has `send_post_discharge_survey = True`
2. First stage has survey template associated
3. Check logs: `grep "survey" logs/django.log`

### Issue: Email/SMS not displayed

**Check:**
1. Django server is running
2. NotificationService is configured correctly
3. Check terminal output for formatted messages

### Issue: API returns 500 error

**Check:**
1. Django logs: `logs/django.log`
2. Check if all required fields are present in event data
3. Verify database migrations are up to date

## Advanced Usage

### Custom Journey Templates

Edit `seed_journey_surveys.py` to add:
- New journey types
- Custom stage names
- Additional survey questions
- Different scoring thresholds

### Realistic Testing

For production-like testing:
```bash
# Simulate 100 patients over 10 minutes
python apps/simulator/his_simulator.py \
  --max-patients 100 \
  --delay 6 \
  --url http://localhost:8000/api/simulator/his-events/
```

### Stress Testing

```bash
# High frequency (1 second between patients)
python apps/simulator/his_simulator.py --delay 1 --max-patients 50
```

## Database Tables Created

1. **Patient** - Patient records
2. **PatientJourneyTemplate** - Journey definitions
3. **PatientJourneyStageTemplate** - Stage definitions
4. **PatientJourneyInstance** - Patient journeys
5. **PatientJourneyStageInstance** - Stage instances
6. **SurveyTemplate** - Survey definitions
7. **SurveyQuestion** - Survey questions
8. **SurveyInstance** - Survey instances
9. **SurveyResponse** - Survey responses (when patient completes survey)

## Next Steps

After successful testing:
1. Implement survey completion UI (Phase 4)
2. Add survey response scoring
3. Integrate with PX Action Center for negative feedback
4. Add analytics dashboard for survey results
5. Implement real-time notifications (Celery + Redis)

## Files Created/Modified

**Created:**
- `apps/simulator/management/commands/seed_journey_surveys.py`
- `apps/simulator/his_simulator.py`
- `apps/simulator/serializers.py`

**Modified:**
- `apps/simulator/views.py` - Added HIS events handler
- `apps/simulator/urls.py` - Added HIS events endpoint

**Documentation:**
- `docs/HIS_SIMULATOR_GUIDE.md` (this file)
