# Source User Filtered Views Implementation

## Overview

Implemented dedicated filtered views for Source Users to view only complaints and inquiries from their assigned source, instead of seeing all complaints/inquiries in the system.

## Problem Statement

Previously, when Source Users clicked "My Complaints" or "My Inquiries" in their navigation, they were redirected to generic complaint/inquiry list pages that showed ALL complaints/inquiries in the system, not just those from their assigned source.

## Solution

Created dedicated filtered views specifically for Source Users that:
1. Identify the user's assigned PX Source
2. Filter complaints/inquiries to show only those from their source
3. Provide filtering, search, and pagination capabilities
4. Use a simplified UI optimized for Source Users

## Implementation Details

### 1. New Views (`apps/px_sources/ui_views.py`)

#### `source_user_complaint_list(request)`
- **URL**: `/px-sources/complaints/`
- **Purpose**: Display complaints filtered to user's assigned source
- **Features**:
  - Filters: Status, Priority, Category
  - Search: Title, Description, Patient Name
  - Pagination: 20 items per page
  - Shows total complaint count
  - Permission check: Only active Source Users can access
- **Related Fields**: `patient`, `hospital`, `assigned_to`, `created_by`

#### `source_user_inquiry_list(request)`
- **URL**: `/px-sources/inquiries/`
- **Purpose**: Display inquiries filtered to user's assigned source
- **Features**:
  - Filters: Status, Category
  - Search: Subject, Message, Contact Name
  - Pagination: 20 items per page
  - Shows total inquiry count
  - Permission check: Only active Source Users can access
- **Related Fields**: `patient`, `hospital`, `assigned_to`, `created_by`

### 2. New URL Patterns (`apps/px_sources/urls.py`)

```python
path('complaints/', ui_views.source_user_complaint_list, name='source_user_complaint_list'),
path('inquiries/', ui_views.source_user_inquiry_list, name='source_user_inquiry_list'),
```

### 3. New Templates

#### `templates/px_sources/source_user_complaint_list.html`
- Extends: `layouts/source_user_base.html`
- Shows:
  - Page header with complaint count badge
  - "Create Complaint" button (if permission granted)
  - Filter panel (Search, Status, Priority, Category)
  - Complaints table with relevant columns
  - Pagination controls
- Features:
  - Permission-based "Create Complaint" button display
  - Empty state with prompt to create complaint
  - Filter persistence in pagination links
  - Responsive table design

#### `templates/px_sources/source_user_inquiry_list.html`
- Extends: `layouts/source_user_base.html`
- Shows:
  - Page header with inquiry count badge
  - "Create Inquiry" button (if permission granted)
  - Filter panel (Search, Status, Category)
  - Inquiries table with relevant columns
  - Pagination controls
- Features:
  - Permission-based "Create Inquiry" button display
  - Empty state with prompt to create inquiry
  - Filter persistence in pagination links
  - Handles both patient and non-patient inquiries

### 4. Updated Navigation (`templates/layouts/source_user_base.html`)

Changed both desktop sidebar and mobile offcanvas navigation:

**Before:**
```html
<a href="{% url 'complaints:complaint_list' %}">My Complaints</a>
<a href="{% url 'complaints:inquiry_list' %}">My Inquiries</a>
```

**After:**
```html
<a href="{% url 'px_sources:source_user_complaint_list' %}">My Complaints</a>
<a href="{% url 'px_sources:source_user_inquiry_list' %}">My Inquiries</a>
```

Active state detection updated:
- Desktop: `{% if 'source_user_complaint_list' in request.path %}active{% endif %}`
- Mobile: No active state (simplified)

## Features

### Filtering Capabilities

#### Complaints:
- **Search**: Title, Description, Patient First Name, Patient Last Name
- **Status**: All, Open, In Progress, Resolved, Closed
- **Priority**: All, Low, Medium, High
- **Category**: All, Clinical Care, Staff Behavior, Facility & Environment, Wait Time, Billing, Communication, Other

#### Inquiries:
- **Search**: Subject, Message, Contact Name
- **Status**: All, Open, In Progress, Resolved, Closed
- **Category**: All, Clinical Care, Staff Behavior, Facility & Environment, Wait Time, Billing, Communication, Other

### Permission Checks

Both views verify:
1. User is authenticated (`@login_required` decorator)
2. User has an active SourceUser profile
3. User's source user status is active

If checks fail:
- Shows error message: "You are not assigned as a source user. Please contact your administrator."
- Redirects to home page (`/`)

### Permission-Based UI

Create buttons only display if user has permission:
- `source_user.can_create_complaints` → Show "Create Complaint" button
- `source_user.can_create_inquiries` → Show "Create Inquiry" button

### Data Display

#### Complaint List Columns:
1. ID (truncated to 8 characters)
2. Title (truncated to 8 words)
3. Patient Name + MRN
4. Category (badge)
5. Status (color-coded badge)
6. Priority (color-coded badge)
7. Assigned To (name or "Unassigned")
8. Created Date
9. Actions (View button)

#### Inquiry List Columns:
1. ID (truncated to 8 characters)
2. Subject (truncated to 8 words)
3. Contact (Patient info or Contact Name/Email)
4. Category (badge)
5. Status (color-coded badge)
6. Assigned To (name or "Unassigned")
7. Created Date
8. Actions (View button)

## Security Considerations

1. **Source-Based Filtering**: Views automatically filter to user's assigned source - users cannot bypass this
2. **Authentication**: All views require login
3. **Active Status Check**: Only active Source Users can access
4. **No Cross-Source Access**: Source Users from different sources cannot see each other's data
5. **Permission-Based Creation**: Create buttons only show for users with appropriate permissions

## Bug Fixes Applied

### Field Name Correction

**Issue**: Used incorrect field name `'creator'` in `select_related()` calls.

**Error Messages**:
```
Invalid field name(s) given in select_related: 'creator'. 
Choices are: patient, hospital, department, source, created_by, assigned_to, responded_by
```

**Fix**: Changed `'creator'` to `'created_by'` in both views:

```python
# Complaints
complaints_queryset = Complaint.objects.filter(source=source).select_related(
    'patient', 'hospital', 'assigned_to', 'created_by'  # ✅ Correct field
)

# Inquiries
inquiries_queryset = Inquiry.objects.filter(source=source).select_related(
    'patient', 'hospital', 'assigned_to', 'created_by'  # ✅ Correct field
)
```

## Testing Checklist

### Desktop Navigation
- [ ] Login as Source User
- [ ] Click "My Complaints" → See only complaints from your source
- [ ] Click "My Inquiries" → See only inquiries from your source
- [ ] Active state highlights correctly in sidebar

### Mobile Navigation
- [ ] Open mobile menu (hamburger icon)
- [ ] Click "My Complaints" → See only complaints from your source
- [ ] Click "My Inquiries" → See only inquiries from your source

### Filtering & Search
- [ ] Filter complaints by status
- [ ] Filter complaints by priority
- [ ] Filter complaints by category
- [ ] Search complaints by title
- [ ] Search complaints by patient name
- [ ] Filter inquiries by status
- [ ] Filter inquiries by category
- [ ] Search inquiries by subject
- [ ] Clear filters → See all items again

### Pagination
- [ ] View first page of results
- [ ] Navigate to next page
- [ ] Navigate to last page
- [ ] Navigate to previous page
- [ ] Filters persist across page navigation

### Permission Checks
- [ ] Non-logged-in user redirected to login
- [ ] Non-Source User redirected with error message
- [ ] Inactive Source User redirected with error message
- [ ] "Create Complaint" button shows only if `can_create_complaints = True`
- [ ] "Create Inquiry" button shows only if `can_create_inquiries = True`

### Security Tests
- [ ] Source User from Source A cannot see complaints from Source B
- [ ] Source User from Source A cannot see inquiries from Source B
- [ ] Cannot access filtered views directly without proper permissions

## Related Documentation

- [Source User Login Redirect Implementation](./SOURCE_USER_LOGIN_REDIRECT_IMPLEMENTATION.md)
- [Source User Base Layout Implementation](./SOURCE_USER_BASE_LAYOUT_IMPLEMENTATION.md)
- [Source User Implementation Summary](./apps/px_sources/SOURCE_USER_IMPLEMENTATION_SUMMARY.md)

## Summary

This implementation provides Source Users with dedicated, filtered views that show only the complaints and inquiries from their assigned source. The views include comprehensive filtering and search capabilities, are secure against cross-source data access, and provide a clean, user-friendly interface optimized for Source Users' workflows.

**Key Benefits:**
- ✅ Source Users see only relevant data from their source
- ✅ Comprehensive filtering and search capabilities
- ✅ Secure access controls
- ✅ Permission-based UI elements
- ✅ Pagination for large datasets
- ✅ Consistent with Source User theme and layout
- ✅ Works seamlessly with existing complaint/inquiry detail views