# Complaint Seeding Guide

## Overview

The `seed_complaints` management command creates realistic test complaint data with bilingual support (English and Arabic) for testing the PX360 complaint management system.

## Features

- **Bilingual Support**: Creates complaints in both English and Arabic (70% Arabic, 30% English by default)
- **Staff-Mentioned Complaints**: ~60% of complaints mention specific staff members (nurses, physicians, admin staff)
- **General Complaints**: ~40% of complaints are general (facility, billing, wait time, etc.)
- **Severity Distribution**: Critical, High, Medium, Low complaints
- **Priority Distribution**: Urgent, High, Medium, Low priorities
- **Category-Based**: Matches complaints to appropriate categories (clinical_care, staff_behavior, facility, wait_time, billing, communication, other)
- **Timeline Entries**: Automatically creates initial timeline entries
- **Reference Numbers**: Generates unique complaint reference numbers
- **AI Analysis**: Django signals will automatically trigger AI analysis for new complaints

## Prerequisites

Before running this command, ensure you have:

1. **Active Hospitals**: Hospitals with status='active'
   ```bash
   python manage.py seed_departments
   ```

2. **Complaint Categories**: System-wide complaint categories
   ```bash
   python manage.py seed_complaint_configs
   ```

3. **Staff Data** (optional but recommended): Staff members in the database
   ```bash
   python manage.py seed_staff
   ```

## Usage

### Basic Usage (Create 10 complaints)

```bash
python manage.py seed_complaints
```

This creates:
- 10 total complaints
- 7 Arabic complaints (70%)
- 3 English complaints (30%)
- 6 staff-mentioned complaints (60%)
- 4 general complaints (40%)
- All with status: OPEN

### Custom Number of Complaints

```bash
python manage.py seed_complaints --count 50
```

Create 50 complaints with default percentages.

### Custom Language Distribution

```bash
python manage.py seed_complaints --count 20 --arabic-percent 50
```

Create 20 complaints:
- 10 Arabic (50%)
- 10 English (50%)

### Target Specific Hospital

```bash
python manage.py seed_complaints --hospital-code ALH
```

Create complaints only for hospital with code 'ALH'.

### Custom Staff-Mention Percentage

```bash
python manage.py seed_complaints --staff-mention-percent 80
```

Create complaints with 80% staff-mentioned and 20% general.

### Preview Without Creating (Dry Run)

```bash
python manage.py seed_complaints --dry-run
```

Shows what would be created without actually creating complaints.

### Clear Existing Complaints First

```bash
python manage.py seed_complaints --clear
```

Deletes all existing complaints before creating new ones.

### Combined Options

```bash
python manage.py seed_complaints --count 100 --arabic-percent 60 --staff-mention-percent 70 --hospital-code ALH --clear
```

Create 100 complaints for hospital 'ALH':
- 60 Arabic, 40 English
- 70 staff-mentioned, 30 general
- Delete existing complaints first

## Command Arguments

| Argument | Type | Default | Description |
|----------|------|---------|-------------|
| `--count` | int | 10 | Number of complaints to create |
| `--arabic-percent` | int | 70 | Percentage of Arabic complaints (0-100) |
| `--hospital-code` | str | - | Target hospital code (default: all hospitals) |
| `--staff-mention-percent` | int | 60 | Percentage of staff-mentioned complaints (0-100) |
| `--dry-run` | flag | False | Preview without making changes |
| `--clear` | flag | False | Delete existing complaints first |

## Complaint Templates

### English Complaints

**Staff-Mentioned Examples:**
- Rude behavior from nurse during shift
- Physician misdiagnosed my condition
- Nurse ignored call button for over 30 minutes
- Physician did not explain treatment plan clearly
- Nurse made medication error
- Admin staff was unhelpful with billing inquiry
- Nurse was compassionate and helpful
- Physician provided excellent care

**General Complaints:**
- Long wait time in emergency room
- Room was not clean upon admission
- Air conditioning not working properly
- Billing statement has incorrect charges
- Difficulty getting prescription refills
- Parking is inadequate for visitors
- Food quality has declined

### Arabic Complaints

**Staff-Mentioned Examples:**
- سلوك غير مهذب من الممرضة أثناء المناوبة
- الطبيب تشخص خطأ في حالتي
- الممرضة تجاهلت زر الاستدعاء لأكثر من 30 دقيقة
- الطبيب لم يوضح خطة العلاج بوضوح
- الممرضة ارتكبت خطأ في الدواء
- موظف الإدارة كان غير مفيد في استفسار الفوترة
- الممرضة كانت متعاطفة ومساعدة
- الطبيب قدم رعاية ممتازة

**General Complaints:**
- وقت انتظار طويل في الطوارئ
- الغرفة لم تكن نظيفة عند القبول
- التكييف لا يعمل بشكل صحيح
- كشف الفاتورة يحتوي على رسوم غير صحيحة
- صعوبة الحصول على وصفات طبية
- مواقف السيارات غير كافية للزوار
- جودة الطعام انخفضت

## Complaint Categories

| Code | English Name | Arabic Name |
|------|--------------|-------------|
| `clinical_care` | Clinical Care | الرعاية السريرية |
| `staff_behavior` | Staff Behavior | سلوك الموظفين |
| `facility` | Facility & Environment | المرافق والبيئة |
| `wait_time` | Wait Time | وقت الانتظار |
| `billing` | Billing | الفواتير |
| `communication` | Communication | التواصل |
| `other` | Other | أخرى |

## Severity and Priority Distribution

### Staff-Mentioned Complaints
- **Critical/Urgent**: Medication errors, misdiagnosis, severe rude behavior
- **High/High**: Ignored call button, unclear treatment plans
- **Medium/Medium**: Unhelpful admin staff
- **Low/Low**: Positive feedback about compassionate care

### General Complaints
- **High/High**: Long wait times in emergency, incorrect billing charges
- **Medium/Medium**: Unclean rooms, non-working AC, prescription refill issues, food quality
- **Low/Low**: Parking issues, minor facility concerns

## What Gets Created

For each complaint, the command creates:

1. **Complaint Record**:
   - Unique reference number (format: CMP-{hospital_code}-{year}-{UUID})
   - Title and description (bilingual)
   - Severity and priority
   - Category assignment
   - Hospital and department (linked to staff if applicable)
   - Patient name (bilingual)
   - Contact information (email/phone)
   - Source (patient, family, call_center, online, in_person)
   - Status: OPEN
   - Mentioned staff (if staff-mentioned complaint)

2. **Timeline Entry**:
   - Initial status change to 'open'
   - Description: "Complaint created and registered"
   - System-created (no user)

3. **Automatic Processing** (via Django signals):
   - SLA deadline calculation (based on severity/priority)
   - AI analysis (sentiment, categorization, etc.)
   - Assignment logic (if configured)
   - Notifications (if configured)

## Example Output

```
============================================================
Complaint Data Seeding Command
============================================================

Found 2 hospital(s)

Configuration:
  Total complaints to create: 10
  Arabic complaints: 7 (70%)
  English complaints: 3 (30%)
  Staff-mentioned: 6 (60%)
  General: 4 (40%)
  Status: All OPEN
  Dry run: False

============================================================
Summary:
  Total complaints created: 10
  Arabic: 7
  English: 3
  Staff-mentioned: 6
  General: 4
============================================================

Complaint seeding completed successfully!
```

## Testing SLA with Seeded Complaints

After seeding complaints, you can test the SLA system:

1. **Check SLA Deadlines**:
   ```bash
   python manage.py shell
   >>> from apps.complaints.models import Complaint
   >>> for c in Complaint.objects.all():
   ...     print(f"{c.reference}: {c.due_at}, Overdue: {c.is_overdue}")
   ```

2. **Manually Trigger SLA Reminders**:
   ```bash
   python manage.py shell
   >>> from apps.complaints.tasks import send_sla_reminders
   >>> send_sla_reminders()
   ```

3. **Run SLA Functionality Tests**:
   ```bash
   python test_sla_functionality.py
   ```

## Troubleshooting

### No Hospitals Found
```
ERROR: No active hospitals found. Please create hospitals first.
```
**Solution**: Run `python manage.py seed_departments` to create hospitals.

### No Complaint Categories Found
```
ERROR: No complaint categories found. Please run seed_complaint_configs first.
```
**Solution**: Run `python manage.py seed_complaint_configs` to create categories.

### No Staff Found
```
WARNING: No staff found. Staff-mentioned complaints will not have linked staff.
```
**Solution**: Run `python manage.py seed_staff` to create staff data (optional but recommended).

### Import Errors
```
ModuleNotFoundError: No module named 'apps.complaints'
```
**Solution**: Ensure you're running the command from the project root directory.

## Best Practices

1. **Start Small**: Test with 5-10 complaints first using `--dry-run`
2. **Check Data**: Verify complaints in Django Admin before running in production
3. **Monitor AI Analysis**: Check that AI analysis is being triggered via signals
4. **Test SLA**: Use seeded complaints to test SLA reminders and escalation
5. **Clear Carefully**: Use `--clear` option carefully as it deletes all existing complaints

## Related Commands

- `seed_complaint_configs` - Creates SLA configs, categories, thresholds, escalation rules
- `seed_staff` - Creates staff data
- `seed_departments` - Creates hospital and department data
- `test_sla_functionality` - Tests SLA system

## Support

For issues or questions:
1. Check the main documentation: `docs/SLA_TESTING_PLAN.md`
2. Review the code: `apps/complaints/management/commands/seed_complaints.py`
3. Check Django Admin to verify created data
