# Public Complaint Form Implementation

## Overview
A public-facing complaint submission form that allows patients and visitors to submit complaints without requiring authentication. The form is fully bilingual (English/Arabic) and provides a seamless user experience.

## Features Implemented

### 1. Form Components
- **PublicComplaintForm** (apps/complaints/forms.py)
  - Django form with validation for all complaint fields
  - Supports file attachments (up to 5 files, 10MB each)
  - Validates national ID format (10 digits)
  - Dynamic field requirements based on patient lookup

### 2. Templates
- **public_complaint_form.html** - Main submission form
  - Patient Information Section
    - National ID lookup with auto-fill
    - Auto-generated MRN display
    - Contact information (name, phone, email)
    - Preferred language selection

  - Complaint Details Section
    - Hospital and department dropdowns (cascading)
    - Complaint category and subcategory
    - Title and description fields
    - Severity and priority selectors
    - Encounter ID (optional)

  - Attachments Section
    - Multi-file upload with preview
    - File size and type validation

  - AJAX-powered interactions
    - Patient lookup by National ID
    - Department dropdown based on hospital selection
    - Form submission with loading states
    - Success modal with reference number

- **public_complaint_success.html** - Success confirmation page
  - Displays complaint reference number
  - Next steps information
  - Contact information for urgent cases
  - Navigation options

### 3. View Handlers (apps/complaints/ui_views.py)

#### public_complaint_submit
- Handles GET (display form) and POST (submit complaint)
- Creates new patient records when needed
- Generates unique reference numbers
- Handles file attachments
- Supports both traditional and AJAX submissions
- Validates all form inputs
- Creates initial complaint update

#### public_complaint_success
- Displays success page with reference number
- No authentication required

#### api_lookup_patient
- AJAX endpoint for patient lookup by National ID
- Returns patient MRN, name, phone, email
- No authentication required
- Handles patient not found cases

#### api_load_departments
- AJAX endpoint for cascading department dropdown
- Returns active departments for selected hospital
- No authentication required

### 4. URL Routes (apps/complaints/urls.py)
- `/complaints/public/submit/` - Public form
- `/complaints/public/success/<reference>/` - Success page
- `/complaints/public/api/lookup-patient/` - Patient lookup API
- `/complaints/public/api/load-departments/` - Department loading API

### 5. Key Features

#### National ID Lookup
- Real-time patient lookup with debounce (500ms)
- Auto-fills MRN, name, phone, email
- Shows loading spinner during lookup
- Handles not found case with fallback to manual entry

#### Cascading Dropdowns
- Hospital selection loads corresponding departments
- Departments disabled until hospital selected
- Shows error message on failure

#### File Upload
- Multiple file support
- Preview shows file names and sizes
- Client-side validation
- Server-side validation (type, size, count)

#### Form Validation
- Required field validation
- National ID format validation
- File type and size validation
- AJAX error handling with detailed messages
- SweetAlert2 for user-friendly error messages

#### Bilingual Support
- All text uses Django i18n templates
- Arabic and English translations
- RTL language support
- Language-aware date/time formatting

#### User Experience
- Responsive design for mobile and desktop
- Loading states for all async operations
- Success modal with reference number
- Clear visual feedback for all interactions
- Informative help text throughout

### 6. Security Considerations
- CSRF protection enabled
- File type validation (images, PDF, DOC, DOCX)
- File size limits (10MB per file, 5 files max)
- Input sanitization via Django forms
- Rate limiting should be added in production

### 7. Patient Creation Logic
When a patient is not found:
- Auto-generates MRN using Patient.generate_mrn()
- Splits full name into first/last name
- Sets selected hospital as primary
- Sets status to 'active'
- Stores all provided contact information

### 8. Complaint Creation Logic
- Sets source='public' to identify public submissions
- Starts with status='open'
- Creates initial update note
- Links to patient (new or existing)
- Stores all form data

### 9. Integration Points
- Uses existing Patient model from apps.organizations
- Uses Hospital and Department models
- Creates Complaint and ComplaintAttachment records
- Creates initial ComplaintUpdate for audit trail
- Reference number format: CMP-{YYYYMMDD}-{unique_id}

## Usage

### Accessing the Form
The public form is accessible at:
```
/complaints/public/submit/
```

No authentication required.

### Example Submission Flow
1. User enters National ID (10 digits)
2. System looks up patient and auto-fills data
3. If not found, user manually enters contact info
4. User selects hospital (loads departments)
5. User optionally selects department
6. User selects complaint category
7. User enters title and description
8. User sets severity and priority
9. User optionally uploads attachments
10. User submits form
11. System creates patient (if needed) and complaint
12. User sees success page with reference number

## Testing Checklist

- [ ] Form loads without authentication
- [ ] National ID lookup works with valid patient
- [ ] National ID lookup shows not found message for invalid ID
- [ ] Hospital dropdown loads active hospitals
- [ ] Department dropdown cascades correctly
- [ ] File upload preview shows file info
- [ ] Form validates required fields
- [ ] Form validates file types and sizes
- [ ] Complaint is created successfully
- [ ] Patient is created when not found
- [ ] Reference number is generated
- [ ] Success page displays correctly
- [ ] AJAX submissions work
- [ ] Traditional submissions work
- [ ] Bilingual switching works
- [ ] RTL layout displays correctly
- [ ] Mobile responsive design works

## Future Enhancements

1. **Email Notifications**
   - Send confirmation email to patient
   - Send notification to hospital staff

2. **SMS Notifications**
   - Send SMS with reference number
   - Send status update notifications

3. **Complaint Tracking**
   - Allow users to check status by reference number
   - Public status page

4. **Rate Limiting**
   - Prevent abuse from same IP
   - CAPTCHA for suspicious activity

5. **Additional Validation**
   - Phone number format validation
   - Email format validation
   - Custom validation rules per hospital

6. **Enhanced UX**
   - Progress indicator
   - Save draft functionality
   - Multi-step form with review

## Dependencies
- Django (form handling)
- jQuery (AJAX)
- SweetAlert2 (alerts)
- Bootstrap 4 (styling)
- Django i18n (translations)

## Files Modified/Created

### Created
- apps/complaints/forms.py - PublicComplaintForm
- templates/complaints/public_complaint_form.html - Main form
- templates/complaints/public_complaint_success.html - Success page

### Modified
- apps/complaints/ui_views.py - Added public form views
- apps/complaints/urls.py - Added public form routes

## Deployment Notes

1. Ensure media files are properly configured for file uploads
2. Set up email backend for notifications
3. Configure CORS if needed for AJAX requests
4. Review and adjust file size limits as needed
5. Ensure translation files are updated for new strings
6. Consider adding analytics tracking
7. Set up monitoring for form submissions

## Support
For issues or questions about the public complaint form, contact:
- Development Team
- Patient Relations Department
