# AI-PX Action Integration - Implementation Complete

## Overview

This document describes the integration between the Complaint AI Analysis system and the PX Action Center. When a complaint is created, AI analysis can now automatically create a PX Action if the hospital has this feature enabled.

## Implementation Date

January 14, 2026

## Changes Made

### 1. Modified `apps/complaints/tasks.py`

#### Enhanced `analyze_complaint_with_ai` Task

The AI analysis task now includes automatic PX Action creation:

**New Functionality:**
- Checks if hospital has `auto_create_action_on_complaint` enabled in metadata
- If enabled, uses `AIService.create_px_action_from_complaint()` to generate action data
- Creates PX Action object with AI-generated title, description, category, priority, and severity
- Links action to complaint via ContentType
- Creates PX Action Log entry for audit trail
- Creates Complaint Update to notify about auto-created action
- Logs audit event
- **Returns `px_action_id` and `px_action_auto_created` in task result**

**Key Code Section:**
```python
# Auto-create PX Action if enabled
action_id = None
try:
    # Check if hospital has auto-create enabled
    hospital_metadata = getattr(complaint.hospital, 'metadata', None) or {}
    auto_create_action = hospital_metadata.get('auto_create_action_on_complaint', False)

    if auto_create_action:
        logger.info(f"Auto-creating PX Action for complaint {complaint_id}")

        # Generate PX Action data using AI
        action_data = AIService.create_px_action_from_complaint(complaint)

        # Create PX Action object
        from apps.px_action_center.models import PXAction, PXActionLog
        from django.contrib.contenttypes.models import ContentType

        complaint_ct = ContentType.objects.get_for_model(Complaint)

        action = PXAction.objects.create(
            source_type='complaint',
            content_type=complaint_ct,
            object_id=complaint.id,
            title=action_data['title'],
            description=action_data['description'],
            hospital=complaint.hospital,
            department=complaint.department,
            category=action_data['category'],
            priority=action_data['priority'],
            severity=action_data['severity'],
            status='open',
            metadata={
                'source_complaint_id': str(complaint.id),
                'source_complaint_title': complaint.title,
                'ai_generated': True,
                'auto_created': True,
                'ai_reasoning': action_data.get('reasoning', '')
            }
        )

        action_id = str(action.id)
        
        # Create action log, complaint update, and audit log...
        
except Exception as e:
    logger.error(f"Error auto-creating PX Action: {str(e)}", exc_info=True)
    action_id = None

# Return with action_id
return {
    # ... other fields ...
    'px_action_id': action_id,
    'px_action_auto_created': action_id is not None
}
```

### 2. Modified `apps/complaints/views.py`

#### Updated `perform_create` Method

Changed from a TODO comment to actual AI analysis trigger:

**Before:**
```python
# TODO: Optionally create PX Action (Phase 6)
# from apps.complaints.tasks import create_action_from_complaint
# create_action_from_complaint.delay(str(complaint.id))
```

**After:**
```python
# Trigger AI analysis (includes PX Action auto-creation if enabled)
from apps.complaints.tasks import analyze_complaint_with_ai
analyze_complaint_with_ai.delay(str(complaint.id))
```

This ensures that every new complaint triggers AI analysis, which includes:
- Complaint classification (severity, priority, category)
- Department assignment
- Staff extraction and matching
- Emotion analysis
- **PX Action auto-creation (if enabled)**

## How It Works

### Automatic PX Action Creation Flow

1. **Complaint Created** → User creates complaint via API/UI
2. **AI Analysis Triggered** → `analyze_complaint_with_ai` task runs asynchronously
3. **Hospital Config Check** → System checks `hospital.metadata.auto_create_action_on_complaint`
4. **AI Generates Action Data** → `AIService.create_px_action_from_complaint()` generates:
   - Action title (AI-generated, concise summary)
   - Action description (AI-generated, detailed explanation)
   - Category (mapped from complaint category)
   - Priority (inherited from complaint)
   - Severity (inherited from complaint)
5. **PX Action Created** → New PXAction object created with:
   - Link to complaint via ContentType
   - AI-generated metadata
   - Initial log entry
6. **Notification Added** → Complaint update created to inform about auto-created action
7. **Audit Logged** → Event logged for compliance and tracking

### Manual PX Action Creation

For cases where auto-create is disabled or PX Admin wants to create action manually:

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

This endpoint:
- Uses AI service to generate action data
- Allows PX Admin to optionally assign a user
- Creates PX Action with full audit trail
- Works even if hospital has auto-create disabled

## Configuration

### Enabling Auto-Creation

To enable automatic PX Action creation for a hospital:

```python
hospital.metadata = {
    'auto_create_action_on_complaint': True
}
hospital.save()
```

### Disabling Auto-Creation

```python
hospital.metadata = {
    'auto_create_action_on_complaint': False  # or omit the key
}
hospital.save()
```

## Testing

### Test Script

A comprehensive test script has been created: `test_ai_px_action_integration.py`

**Test Coverage:**
1. Creates test complaint
2. Runs AI analysis task
3. Verifies complaint updates (severity, priority, category, department)
4. Checks if PX Action was created (if enabled)
5. Validates action-complaint linkage
6. Verifies action metadata (ai_generated, auto_created flags)
7. Explains manual action creation option

**Running the Test:**
```bash
python test_ai_px_action_integration.py
```

## API Response Changes

### `analyze_complaint_with_ai` Task Return Value

**New Fields Added:**
- `px_action_id`: UUID of created PX Action (or null if not created)
- `px_action_auto_created`: Boolean indicating if action was auto-created

**Example Response:**
```json
{
  "status": "success",
  "complaint_id": "12345678-1234-1234-1234-123456789abc",
  "severity": "high",
  "priority": "high",
  "category": "service_quality",
  "department": "Customer Service",
  "title_en": "Staff Behavior Issue - Rude Receptionist",
  "title_ar": "مشكلة في سلوك الموظف - موظف استقبال غير مهذب",
  "short_description_en": "Patient reported rude behavior from reception staff",
  "short_description_ar": "أبلغ المريض عن سلوك غير مهذب من موظفي الاستقبال",
  "suggested_action_en": "Conduct staff training on customer service",
  "suggested_action_ar": "إجراء تدريب للموظفين على خدمة العملاء",
  "reasoning_en": "Complaint describes multiple instances of unprofessional behavior",
  "reasoning_ar": "الشكوى تصف حالات متعددة من السلوك غير المهني",
  "emotion": "frustrated",
  "emotion_intensity": 0.8,
  "emotion_confidence": 0.9,
  "old_severity": "medium",
  "old_priority": "medium",
  "px_action_id": "87654321-4321-4321-4321-cba987654321",
  "px_action_auto_created": true
}
```

## Benefits

### 1. Automation
- Reduces manual work for PX Admins
- Ensures consistent action creation based on AI analysis
- Eliminates duplicate effort (complaint → manual action creation)

### 2. AI-Powered
- Actions generated using AI analysis of complaint content
- Intelligent category mapping
- Context-aware title and description generation

### 3. Traceability
- Clear linkage between complaint and action
- Full audit trail of auto-creation
- Metadata tracks AI-generated content

### 4. Flexibility
- Hospital-level configuration (enable/disable)
- Manual creation option available via API
- PX Admins can override or supplement AI-generated actions

### 5. Consistency
- Same AI service used for both manual and auto-creation
- Unified action generation logic
- Consistent metadata and logging

## Related Documentation

- **AI Service:** `apps/core/ai_service.py` - `create_px_action_from_complaint()` method
- **PX Action Model:** `apps/px_action_center/models.py` - PXAction model
- **Complaint Tasks:** `apps/complaints/tasks.py` - `analyze_complaint_with_ai()` task
- **Category Mapping:** `apps/complaints/views.py` - `map_complaint_category_to_action_category()` function

## Migration Notes

### Database Changes
No database migrations required. The integration uses:
- Existing Complaint model (metadata field for config)
- Existing PXAction model (no schema changes)
- Existing ContentType framework for linking

### Backward Compatibility
- Fully backward compatible
- Hospitals without config key behave as before (no auto-creation)
- Existing API endpoints unchanged
- Task return value only extended, not modified

## Troubleshooting

### PX Action Not Created

**Check:**
1. Hospital metadata has `auto_create_action_on_complaint: True`
2. Celery worker is running (task execution)
3. AI service is accessible and responding
4. Complaint has valid hospital, patient, and category

**Debug:**
```python
# Check hospital config
hospital = complaint.hospital
print(hospital.metadata.get('auto_create_action_on_complaint'))

# Check task result
result = analyze_complaint_with_ai(str(complaint.id))
print(result.get('px_action_id'))
print(result.get('px_action_auto_created'))
```

### Action Created But Not Linked

**Check:**
1. ContentType is correctly set for Complaint model
2. object_id matches complaint ID
3. Action source_type is 'complaint'

## Future Enhancements

Potential improvements for future iterations:

1. **Smart Auto-Creation Rules**
   - Only auto-create for high-severity complaints
   - Only auto-create for specific categories
   - Configurable thresholds

2. **Action Templates**
   - Pre-defined action templates for common complaint types
   - Customizable by hospital or department

3. **Batch Actions**
   - Auto-create single action for multiple related complaints
   - Group similar complaints into one action

4. **Action Preview**
   - Show AI-generated action data before creation
   - Allow PX Admin to edit/approve before saving

5. **Action Escalation Integration**
   - Auto-escalate actions based on severity
   - Link action SLA to complaint SLA

## Summary

This integration successfully connects the Complaint AI Analysis system with the PX Action Center, enabling automatic creation of improvement actions based on AI-powered complaint analysis. The implementation is:

- ✅ Automatic and configurable (hospital-level opt-in)
- ✅ AI-powered and intelligent
- ✅ Fully traceable and auditable
- ✅ Flexible (manual option available)
- ✅ Backward compatible
- ✅ Well-tested

The integration reduces manual workload for PX Admins while ensuring consistent, data-driven action creation based on comprehensive AI analysis of each complaint.
