# Survey-Feedback Integration

## Overview

This document describes the integration between the Survey and Feedback systems, enabling a closed-loop workflow for handling negative survey responses.

## Workflow

### 1. Negative Survey Detection
When a patient completes a survey with a score below the threshold (default: 3.0/5.0):
- Survey is automatically marked as `is_negative=True`
- Staff receives notification/alert about the negative feedback
- Survey detail page displays a warning banner with follow-up actions

### 2. Patient Contact
Staff member contacts the patient to discuss the negative feedback:
- **Action**: Click "Log Patient Contact" button on survey detail page
- **Required**: Contact notes documenting the conversation
- **Optional**: Mark issue as "Resolved" or "Explained"
- **Tracked**: Who contacted, when, and what was discussed

### 3. Send Satisfaction Feedback
After contacting the patient, staff can send a satisfaction check:
- **Action**: Click "Send Satisfaction Feedback" button
- **Creates**: New Feedback record of type `SATISFACTION_CHECK`
- **Links**: Feedback is linked to the original survey via `related_survey` field
- **Sends**: Notification to patient with feedback form link (TODO: implement notification)

### 4. Patient Completes Feedback
Patient receives and completes the satisfaction feedback form:
- Rates their satisfaction with how concerns were addressed
- Provides additional comments if needed
- Feedback is tracked in the system

### 5. Close Loop
Staff reviews the satisfaction feedback:
- If satisfied → Close both survey and feedback
- If still unsatisfied → Escalate or repeat process

## Database Schema

### Feedback Model Changes
```python
# New field in Feedback model
related_survey = ForeignKey(
    'surveys.SurveyInstance',
    on_delete=models.SET_NULL,
    null=True,
    blank=True,
    related_name='follow_up_feedbacks'
)

# New feedback type
FeedbackType.SATISFACTION_CHECK = 'satisfaction_check', 'Satisfaction Check'
```

### SurveyInstance Model Changes
```python
# Patient contact tracking
patient_contacted = BooleanField(default=False)
patient_contacted_at = DateTimeField(null=True, blank=True)
patient_contacted_by = ForeignKey('accounts.User', ...)
contact_notes = TextField(blank=True)
issue_resolved = BooleanField(default=False)

# Satisfaction feedback tracking
satisfaction_feedback_sent = BooleanField(default=False)
satisfaction_feedback_sent_at = DateTimeField(null=True, blank=True)
```

## API Endpoints

### Survey Actions
- `POST /surveys/instances/<uuid>/log-contact/` - Log patient contact
- `POST /surveys/instances/<uuid>/send-satisfaction/` - Send satisfaction feedback

### Views
- `survey_log_patient_contact(request, pk)` - Handle patient contact logging
- `survey_send_satisfaction_feedback(request, pk)` - Trigger satisfaction feedback

## Background Tasks

### `send_satisfaction_feedback`
```python
@shared_task(bind=True, max_retries=3)
def send_satisfaction_feedback(self, survey_instance_id, user_id=None):
    """
    Creates and sends satisfaction feedback form to patient.
    
    - Validates patient was contacted
    - Creates Feedback record linked to survey
    - Sends notification to patient
    - Updates survey tracking fields
    """
```

## UI Components

### Survey Detail Page
For negative surveys, displays:
1. **Warning Alert**: "Action Required: Contact patient to discuss negative feedback"
2. **Contact Form**: 
   - Contact notes textarea
   - Issue resolved checkbox
   - Submit button
3. **Contact Summary** (after logging):
   - Who contacted and when
   - Contact notes
   - Resolution status
4. **Send Satisfaction Button** (after contact):
   - Disabled until patient contacted
   - Triggers satisfaction feedback creation

### Feedback Detail Page
For satisfaction check feedbacks, displays:
1. **Related Survey Card**:
   - Original survey name and score
   - Survey completion date
   - Patient contact information
   - Link to view original survey

## Permissions

- **Log Patient Contact**: Hospital Admin or PX Admin
- **Send Satisfaction Feedback**: Hospital Admin or PX Admin
- **View Related Survey**: Same as survey permissions

## Audit Trail

All actions are logged:
- `survey_patient_contacted` - When patient is contacted
- `satisfaction_feedback_sent` - When satisfaction feedback is sent
- Standard feedback audit events for the satisfaction check

## Migration

Run migrations to apply database changes:
```bash
python3 manage.py migrate feedback
python3 manage.py migrate surveys
```

## Future Enhancements

1. **Notifications**: Implement SMS/WhatsApp/Email notifications for satisfaction feedback
2. **Automated Reminders**: Send reminders if satisfaction feedback not completed
3. **Analytics**: Track satisfaction improvement rates
4. **Templates**: Customizable satisfaction feedback templates
5. **Multi-language**: Support for Arabic satisfaction feedback forms

## Testing Checklist

- [ ] Create survey with negative score
- [ ] Verify warning appears on survey detail
- [ ] Log patient contact with notes
- [ ] Verify contact information is saved
- [ ] Send satisfaction feedback
- [ ] Verify feedback record is created and linked
- [ ] View feedback detail and verify survey link
- [ ] View survey detail and verify feedback link
- [ ] Test permissions for different user roles
- [ ] Verify audit logs are created

## Related Files

### Models
- `apps/feedback/models.py` - Feedback model with related_survey field
- `apps/surveys/models.py` - SurveyInstance model with contact tracking

### Views
- `apps/surveys/ui_views.py` - Survey contact and satisfaction views
- `apps/feedback/views.py` - Feedback views (no changes needed)

### Tasks
- `apps/surveys/tasks.py` - send_satisfaction_feedback task

### Templates
- `templates/surveys/instance_detail.html` - Survey detail with follow-up actions
- `templates/feedback/feedback_detail.html` - Feedback detail with survey link

### URLs
- `apps/surveys/urls.py` - New URL patterns for contact and satisfaction

### Migrations
- `apps/feedback/migrations/0002_add_survey_linkage.py`
- `apps/surveys/migrations/0003_add_survey_linkage.py`

## Configuration

### Settings
```python
# Survey token expiry (default: 30 days)
SURVEY_TOKEN_EXPIRY_DAYS = 30

# Negative survey threshold (default: 3.0 out of 5.0)
# Configured per survey template in database
```

## Support

For questions or issues, contact the development team or refer to the main project documentation.
