# Complaint Dual Assignment Feature

## Overview

Complaints in PX360 support **two separate assignment types** to clearly distinguish between:

1. **Case Manager** (`assigned_to`) - The admin who will manage and follow up on the complaint
2. **Staff Member** (`staff`) - The specific staff member that the complaint is about

## Assignment Types

### 1. Case Manager Assignment

**Purpose**: Assign an admin to manage the complaint lifecycle

**Field**: `assigned_to` (ForeignKey to User)

**Who can assign**: All admins (PX Admins, Hospital Admins, Department Managers)

**Location**: Sidebar → Assignments section → Case Manager

**API Endpoint**: `POST /complaints/api/complaints/{id}/assign/`

**Features**:
- Dropdown to select from assignable users
- Shows currently assigned manager (if any)
- Creates timeline entry on assignment
- Logs audit event
- Includes assignment timestamp

**Workflow**:
1. Admin opens complaint details
2. In sidebar "Assignments" section, selects case manager from dropdown
3. Clicks submit button
4. Complaint is updated with new `assigned_to` user
5. Timeline entry created: "Assigned to [Manager Name]"
6. Audit event logged: "complaint assigned"

### 2. Staff Member Assignment

**Purpose**: Assign the specific staff member that the complaint is about

**Field**: `staff` (ForeignKey to Staff)

**Who can assign**: PX Admins only (restricted permission)

**Location**: 
- Sidebar → Assignments section → Staff Member
- Details tab → Staff Suggestions section
- Staff Selection Modal

**API Endpoint**: `POST /complaints/api/complaints/{id}/assign_staff/`

**Features**:
- AI-powered staff matching with confidence scores
- Manual staff search and selection
- Filter by department
- Shows current staff with edit option
- Supports assignment reasons
- Clears AI "needs_staff_review" flag on manual assignment

**Workflow**:
1. **AI Assignment** (automatic):
   - Complaint is created
   - AI analyzes complaint text
   - Extracts potential staff names
   - Matches against staff database
   - Assigns staff with highest confidence score

2. **Manual Assignment from Suggestions**:
   - PX Admin views complaint details
   - In Details tab → Staff Suggestions section
   - Views AI-suggested matches with confidence scores
   - Clicks "Select" button on desired staff
   - Staff is assigned immediately

3. **Manual Assignment from Search**:
   - PX Admin clicks "Assign Staff" button in sidebar
   - Staff Selection Modal opens
   - Filters by department or searches by name/job title
   - Selects staff from list
   - Provides optional reason for assignment
   - Clicks "Assign Selected Staff"
   - Staff is assigned

## UI Layout

### Sidebar Assignments Section

```html
<!-- Card Header -->
Assignments [People icon]

<!-- Case Manager Assignment -->
Case Manager [Person Badge icon]
Admin who will manage this complaint
[Dropdown: Select manager...] [Assign button]

<!-- Staff Assignment (PX Admin only) -->
Staff Member [Person icon]
Staff member that complaint is about
[Display current staff] OR [Assign Staff button]
```

### Details Tab - Staff Assignment

When staff is already assigned:
```
Staff Member
[Staff Name] [AI Matched badge]
[Job Title]
AI Extracted Names: ["Name1", "Name2"]
Primary: "Primary Name"
Confidence: 85%
```

When staff needs review:
```
Staff Suggestions [Needs Review badge]
AI Extracted Names: ["Name1", "Name2"]
Primary: "Primary Name"
[Match 1: Name A] [85% confidence] [Select button]
[Match 2: Name B] [70% confidence] [Select button]
[Search All Staff] button
```

### Staff Selection Modal

```
Filter by Department: [Dropdown]
Search Staff: [Input]

[Staff List]
  └─ Department A
     ├─ Staff 1 [Radio]
     └─ Staff 2 [Radio]
  └─ Department B
     ├─ Staff 3 [Radio]
     └─ Staff 4 [Radio]

[Cancel] [Assign Selected Staff button]
```

## API Endpoints

### Assign Case Manager

**Endpoint**: `POST /complaints/api/complaints/{id}/assign/`

**Request Body**:
```json
{
  "user_id": "uuid-of-manager-user"
}
```

**Response**:
```json
{
  "message": "Complaint assigned successfully"
}
```

### Assign Staff Member

**Endpoint**: `POST /complaints/api/complaints/{id}/assign_staff/`

**Request Body**:
```json
{
  "staff_id": "uuid-of-staff",
  "reason": "Manual selection from hospital staff list"
}
```

**Response**:
```json
{
  "message": "Staff assigned successfully",
  "staff_id": "uuid-of-staff",
  "staff_name": "Staff Full Name"
}
```

### Get Hospital Staff

**Endpoint**: `GET /complaints/api/complaints/{id}/hospital_staff/`

**Query Parameters**:
- `department_id` (optional): Filter by department
- `search` (optional): Search by name or job title

**Response**:
```json
{
  "hospital_id": "uuid",
  "hospital_name": "Hospital Name",
  "staff_count": 15,
  "staff": [
    {
      "id": "uuid",
      "name_en": "John Doe",
      "name_ar": "جون دو",
      "job_title": "Nurse",
      "specialization": "ICU",
      "department": "Emergency",
      "department_id": "uuid"
    }
  ]
}
```

### Get Staff Suggestions

**Endpoint**: `GET /complaints/api/complaints/{id}/staff_suggestions/`

**Response**:
```json
{
  "extracted_name": "John from nursing",
  "staff_matches": [
    {
      "id": "uuid",
      "name_en": "John Doe",
      "name_ar": "جون دو",
      "confidence": 0.85,
      "job_title": "Nurse",
      "specialization": "ICU",
      "department": "Emergency"
    }
  ],
  "current_staff_id": "uuid",
  "needs_staff_review": true,
  "staff_match_count": 3
}
```

## Workflow Examples

### Example 1: AI Auto-Assignment

1. New complaint submitted about "rude nurse named Sarah"
2. AI analyzes complaint text
3. AI extracts: "Sarah", "nurse"
4. System searches staff database
5. Matches found:
   - Sarah Johnson (ICU Nurse) - 92% confidence
   - Sarah Ahmed (ER Nurse) - 85% confidence
6. System automatically assigns: Sarah Johnson
7. Timeline entry: "Staff assigned to Sarah Johnson (AI Matched)"
8. Staff Sarah Johnson receives explanation request email

### Example 2: Manual Assignment by PX Admin

1. Complaint created with AI match confidence: 65% (low)
2. System sets: `needs_staff_review = true`
3. PX Admin opens complaint details
4. Sees warning: "This complaint needs staff review"
5. Views AI suggestions:
   - Staff A - 65% confidence
   - Staff B - 60% confidence
6. Clicks "Search All Staff"
7. Opens Staff Selection Modal
8. Filters by "Emergency" department
9. Searches for "Ahmed"
10. Finds: Dr. Ahmed Al-Farsi (Emergency Physician)
11. Selects and assigns
12. Timeline entry: "Staff assigned to Dr. Ahmed Al-Farsi (Emergency Physician). Manual selection from hospital staff list"
13. Metadata updated: `staff_manually_assigned = true`

### Example 3: Case Manager Assignment

1. Complaint assigned to Dr. Ahmed Al-Farsi
2. Department Manager opens complaint
3. In sidebar, selects Case Manager dropdown
4. Chooses: "Mohammed Hassan" (Patient Relations Manager)
5. Clicks assign
6. Timeline entry: "Assigned to Mohammed Hassan"
7. Mohammed receives notification email
8. Mohammed manages complaint resolution

## Permissions

### Assign Case Manager

- **PX Admin**: Can assign any admin to any complaint
- **Hospital Admin**: Can assign admins from their hospital
- **Department Manager**: Can assign admins from their department
- **Other Users**: Cannot assign (no permission)

### Assign Staff Member

- **PX Admin**: Can assign any staff member (PX-wide)
- **Hospital Admin**: Cannot assign (restricted)
- **Department Manager**: Cannot assign (restricted)
- **Other Users**: Cannot assign (no permission)

## Notifications

### Case Manager Assignment

When a complaint is assigned to a case manager:

1. **Email Notification**: Sent to assigned manager
   - Subject: "Complaint Notification - #ID"
   - Includes: Complaint details, summary, link to complaint

2. **Timeline Entry**: Created
   - Type: "assignment"
   - Message: "Assigned to [Manager Name]"

3. **Audit Log**: Created
   - Event: "assignment"
   - Description: "Complaint assigned to [Manager Name]"

### Staff Member Assignment

When a staff member is assigned:

1. **Email Notification**: Sent to request explanation
   - Subject: "Explanation Request - Complaint #ID"
   - Includes: Complaint details, explanation submission link
   - Only sent if staff has email address

2. **Timeline Entry**: Created
   - Type: "assignment"  
   - Message: "Staff assigned to [Staff Name]"
   - Metadata: Includes assignment reason

3. **Audit Log**: Created
   - Event: "staff_assigned"
   - Description: "Staff [Staff Name] manually assigned to complaint by [User Name]"
   - Metadata: Includes old_staff_id, new_staff_id, reason

4. **AI Metadata Updated**:
   - `needs_staff_review` = false
   - `staff_manually_assigned` = true
   - `staff_assigned_by` = user_id
   - `staff_assigned_at` = timestamp
   - `staff_assignment_reason` = reason

## Best Practices

### For PX Admins

1. **Review AI Suggestions First**: Check AI-matched staff before manual assignment
2. **Use High Confidence Matches**: Accept matches > 80% confidence
3. **Provide Assignment Reasons**: Add reasons for manual assignments for audit trail
4. **Monitor Low Confidence**: Review complaints with `needs_staff_review` flag

### For Case Managers

1. **Own Your Complaints**: When assigned, actively manage the complaint
2. **Request Explanations**: Use explanation request feature early in process
3. **Follow Up Regularly**: Check for staff responses and escalate if needed
4. **Document Actions**: Add notes and timeline entries

### For Hospital Admins

1. **Assign Appropriate Managers**: Match complaint type to manager expertise
2. **Monitor SLA Compliance**: Watch for overdue complaints
3. **Escalate When Needed**: Use escalation feature for complex cases
4. **Review Assignment Patterns**: Analyze staff complaint trends

## Troubleshooting

### Issue: Can't see Staff Assignment

**Cause**: User is not PX Admin

**Solution**: 
- Only PX Admins can assign staff members
- Contact PX Admin for staff assignment
- Request PX Admin role if needed

### Issue: No staff in dropdown

**Cause**: No staff created or no staff in hospital

**Solution**:
- Check if staff records exist in hospital
- Import staff data if needed
- Use staff seed command: `python manage.py seed_staff`

### Issue: AI match is wrong

**Cause**: AI misinterpreted complaint text

**Solution**:
- Use "Search All Staff" to manually find correct staff
- Assign manually with reason explaining correction
- Consider updating AI prompts for better matching

### Issue: Can't find staff in search

**Cause**: Staff not in database or search criteria too specific

**Solution**:
- Check staff spelling variations
- Use broader search terms (first name only)
- Filter by department first to narrow results
- Verify staff is active (not terminated)

## Future Enhancements

### Potential Improvements

1. **Staff Assignment to Hospital Admins**: Extend permission to hospital admins
2. **Bulk Assignment**: Assign multiple complaints to same staff
3. **Assignment Templates**: Pre-defined assignment patterns based on department/category
4. **Assignment Dashboard**: Overview of all assignments and workload
5. **Auto-Assignment Rules**: Rule-based auto-assignment based on criteria
6. **Assignment History**: Track assignment changes over time
7. **Performance Metrics**: Track assignment effectiveness and resolution times
8. **Staff Notification Preferences**: Allow staff to set notification preferences

## Related Features

- **Explanation Request**: Request explanation from assigned staff
- **Escalation**: Automatically escalate to manager/staff chain
- **SLA Monitoring**: Track response times against SLA deadlines
- **Timeline Updates**: Complete audit trail of all activities
- **Notification System**: Email notifications for all key events

## Support

For questions or issues with the dual assignment feature:

1. Check documentation in `/docs/` folder
2. Review API endpoints in API documentation
3. Contact PX360 support team
4. Submit issue requests through support channels
