# PX360 Development Environment Setup Guide

## Overview

This guide explains how to set up a complete development environment for PX360 using the `setup_dev_environment` management command.

## What Gets Created

### 1. Organization Structure
- **Organization**: Al Hammadi Healthcare Group (DEV)
- **3 Hospitals**: NUZHA-DEV, OLAYA-DEV, SUWAIDI-DEV
- **Departments**: Emergency, OPD, Inpatient, ICU, Pharmacy, Laboratory, Radiology, Administration

### 2. User Roles & Permissions
- PX Admin (Full system access)
- Hospital Admin (Hospital-level access)
- Department Manager (Department-level access)
- PX Staff (PX actions & complaints)
- Physician (View feedback)
- Nurse (View department feedback)
- Staff (Basic access)
- Viewer (Read-only)
- PX Source User (External source users)

### 3. Survey Templates (4 types)
1. **Inpatient Post-Discharge Survey**
   - Nursing care
   - Doctor's care
   - Room cleanliness
   - Food quality
   - Treatment information
   - NPS question
   - Comments

2. **OPD Patient Experience Survey**
   - Registration process
   - Waiting time
   - Doctor consultation
   - Pharmacy service
   - NPS question
   - Comments

3. **EMS Emergency Services Survey**
   - Ambulance response time
   - Paramedic care
   - Emergency department care
   - Communication
   - NPS question
   - Comments

4. **Day Case Patient Survey**
   - Pre-procedure preparation
   - Procedure quality
   - Post-procedure care
   - Discharge process
   - NPS question
   - Comments

### 4. Complaint System Configuration
- **Complaint Categories**: Clinical Care, Management, Relationships, Facility, Communication, Access, Billing, Other
- **PX Sources**: Patient, Family Member, Staff, Survey, MOH, CCHI
- **SLA Configurations** (per hospital):
  - MOH: 24 hours (reminders at 12h/18h)
  - CCHI: 48 hours (reminders at 24h/36h)
  - Internal: 72 hours (reminders at 24h/48h)
- **Escalation Rules** (per hospital):
  - Default: Department Manager (immediate)
  - Critical: Hospital Admin (4h overdue)
  - Final: PX Admin (24h overdue)
- **Thresholds**: Resolution survey < 50% → Create PX Action
- **Explanation SLA**: 48 hours response time

### 5. Journey Templates
**OPD Journey Stages**:
1. Registration (trigger: REGISTRATION)
2. Waiting (trigger: WAITING)
3. MD Consultation (trigger: Consultation)
4. MD Visit (trigger: Doctor Visited)
5. Clinical Assessment (trigger: Clinical Condition)
6. Patient Assessment (trigger: ChiefComplaint)
7. Pharmacy (trigger: Prescribed Drugs)
8. Discharge (trigger: DISCHARGED)

**Other Journey Types**:
- Inpatient Journey
- EMS Journey
- Day Case Journey

### 6. Survey Mappings
- Patient Type 1 (Inpatient) → Inpatient Survey
- Patient Type 2 (Outpatient) → OPD Survey
- Patient Type 3 (Emergency) → EMS Survey
- Patient Type 4 (Day Case) → Day Case Survey

### 7. Observation Categories (15)
1. Patient Safety
2. Clinical Quality
3. Infection Control
4. Medication Safety
5. Equipment & Devices
6. Facility & Environment
7. Staff Behavior
8. Communication
9. Documentation
10. Process & Workflow
11. Security
12. IT & Systems
13. Housekeeping
14. Food Services
15. Other

### 8. Notification Templates
- Onboarding Invitation
- Onboarding Reminder
- Onboarding Completion
- Survey Invitation
- Survey Reminder
- Complaint Acknowledgment
- Complaint Update
- Action Assignment
- SLA Reminder
- SLA Breach

### 9. Standards Setup
**Standard Sources**:
- CBAHI (Saudi Central Board for Accreditation)
- JCI (Joint Commission International)
- ISO (International Organization for Standardization)

**Standard Categories**:
- Patient Safety
- Quality Management
- Infection Control
- Medication Safety
- Environment of Care
- Leadership
- Information Management

### 10. HIS Integration
- API URL: From `.env` (HIS_API_URL)
- Username: From `.env` (HIS_API_USERNAME)
- Password: From `.env` (HIS_API_PASSWORD)
- Event Mappings configured for OPD workflow

## Usage

### Basic Setup (All Components)
```bash
python manage.py setup_dev_environment
```

### Dry Run (Preview Only)
```bash
python manage.py setup_dev_environment --dry-run
```

### Setup Specific Hospital
```bash
python manage.py setup_dev_environment --hospital-code NUZHA-DEV
```

### Skip Specific Components
```bash
# Skip surveys
python manage.py setup_dev_environment --skip-surveys

# Skip complaints
python manage.py setup_dev_environment --skip-complaints

# Skip journeys
python manage.py setup_dev_environment --skip-journeys

# Skip HIS integration
python manage.py setup_dev_environment --skip-integration

# Combine multiple skips
python manage.py setup_dev_environment --skip-surveys --skip-integration
```

## Environment Variables Required

Add these to your `.env` file:

```env
# HIS Integration
HIS_API_URL=https://his.alhammadi.med.sa:54380/SSRCE/API/FetchPatientVisitTimeStamps
HIS_API_USERNAME=AlhhSUNZHippo
HIS_API_PASSWORD=*#$@PAlhh^2106

# Database
DATABASE_URL=sqlite:///db.sqlite3

# Redis/Celery
CELERY_BROKER_URL=redis://localhost:6379/0
CELERY_RESULT_BACKEND=redis://localhost:6379/0

# SMS Gateway
SMS_API_URL=http://localhost:8000/api/simulator/send-sms/
SMS_API_KEY=simulator-test-key
SMS_ENABLED=True
SMS_PROVIDER=console

# Email Gateway
EMAIL_API_URL=http://localhost:8000/api/simulator/send-email/
EMAIL_API_KEY=simulator-test-key
EMAIL_ENABLED=True
EMAIL_PROVIDER=console

# AI Configuration
OPENROUTER_API_KEY=your-api-key-here
AI_MODEL=stepfun/step-3.5-flash:free
AI_TEMPERATURE=0.3
AI_MAX_TOKENS=500
```

## Post-Setup Steps

### 1. Create Admin Users
After running the setup, create admin users for each hospital:

```bash
python manage.py createsuperuser
```

Then assign them to hospitals via the admin interface or:
```python
from apps.accounts.models import HospitalUser
from apps.organizations.models import Hospital
from django.contrib.auth import get_user

User = get_user_model()
hospital = Hospital.objects.get(code='NUZHA-DEV')
user = User.objects.get(email='admin@example.com')

HospitalUser.objects.create(
    user=user,
    hospital=hospital,
    role='hospital_admin'
)
```

### 2. Start Celery Workers
```bash
# Start Celery worker
celery -A config worker -l info

# Start Celery beat (for scheduled tasks)
celery -A config beat -l info
```

### 3. Verify Setup
```bash
# Check organization
python manage.py shell
>>> from apps.organizations.models import Organization
>>> Organization.objects.count()
1

# Check hospitals
>>> from apps.organizations.models import Hospital
>>> Hospital.objects.count()
3

# Check survey templates
>>> from apps.surveys.models import SurveyTemplate
>>> SurveyTemplate.objects.count()
12  # 4 templates × 3 hospitals
```

### 4. Test HIS Integration
```bash
python manage.py test_his_connection
```

### 5. Run Initial HIS Sync
```bash
python manage.py fetch_his_surveys
```

## Idempotent Operation

The command is **idempotent** - it can be run multiple times safely:
- Uses `get_or_create()` for all models
- Won't create duplicates
- Updates existing records if needed
- Safe to re-run after errors

## Troubleshooting

### Issue: "No module named 'django'"
**Solution**: Activate virtual environment
```bash
source .venv/bin/activate
```

### Issue: "Command not found"
**Solution**: Run from project root
```bash
cd /path/to/HH
python manage.py setup_dev_environment
```

### Issue: Database locked
**Solution**: Stop all running processes and try again
```bash
pkill -f celery
pkill -f python
python manage.py setup_dev_environment
```

### Issue: Permission denied
**Solution**: Check file permissions
```bash
chmod +x manage.py
```

## Next Steps After Setup

1. **Configure SMS Gateway** (for production)
2. **Configure Email Gateway** (for production)
3. **Load SHCT Taxonomy** (detailed complaint categories)
4. **Import Staff Data** (via CSV import commands)
5. **Set Up Department Managers** (via admin interface)
6. **Configure HIS Integration** (fine-tune event mappings)
7. **Create Additional Survey Templates** (as needed)
8. **Set Up Standards** (add CBAHI/JCI standards)
9. **Configure Notification Templates** (add SMS/email content)
10. **Test Complete Workflow** (create test complaint → resolve → survey)

## Related Management Commands

```bash
# Load SHCT complaint taxonomy
python manage.py load_shct_taxonomy

# Seed departments
python manage.py seed_departments

# Import staff from CSV
python manage.py import_staff_csv path/to/staff.csv

# Create notification templates
python manage.py init_notification_templates

# Create appreciation category
python manage.py create_patient_feedback_category

# Seed observation categories
python manage.py seed_observation_categories

# Seed acknowledgement categories
python manage.py seed_acknowledgements
```

## Support

For issues or questions:
1. Check logs: `tail -f logs/debug.log`
2. Check Celery logs
3. Review environment variables
4. Check database integrity
5. Contact: support@px360.sa
