# Source User Implementation Summary

## Overview

This document summarizes the implementation of the Source User feature, which allows users to be assigned as managers for specific PX Sources, enabling them to create and manage complaints and inquiries from those sources.

## What Was Implemented

### 1. SourceUser Model
**File:** `apps/px_sources/models.py`

A new model that links users to PX Sources with permissions:
- **User**: One-to-one relationship with User model
- **Source**: Foreign key to PXSource
- **is_active**: Boolean flag for activation/deactivation
- **can_create_complaints**: Permission flag for creating complaints
- **can_create_inquiries**: Permission flag for creating inquiries

Key features:
- Unique constraint on (user, source) combination
- Helper methods: `activate()`, `deactivate()`, `get_active_source_user()`
- Database indexes for performance optimization

### 2. Serializer Updates
**File:** `apps/px_sources/serializers.py`

Added two new serializers:
- **SourceUserSerializer**: Full serializer with all fields
- **SourceUserListSerializer**: Simplified version for list views

Both include computed fields for user details and source names.

### 3. Admin Interface
**File:** `apps/px_sources/admin.py`

Added `SourceUserAdmin` class with:
- List display showing user email, source name, and status
- Filtering by source, status, and creation date
- Search functionality on user and source fields
- Custom badge display for active status

### 4. UI Views
**File:** `apps/px_sources/ui_views.py`

Added `source_user_dashboard()` view that:
- Retrieves the user's active source user profile
- Displays statistics (total/open complaints and inquiries)
- Shows recent complaints and inquiries from the user's source
- Provides quick action buttons for creating complaints/inquiries
- Handles non-source users with an error message and redirect

### 5. Dashboard Template
**File:** `templates/px_sources/source_user_dashboard.html`

A comprehensive dashboard featuring:
- Statistics cards with totals and open counts
- Quick action buttons (Create Complaint/Inquiry)
- Recent complaints table with status and priority badges
- Recent inquiries table with status badges
- Responsive design using Bootstrap 5
- Internationalization support (i18n)

### 6. URL Configuration
**File:** `apps/px_sources/urls.py`

Added route: `/px-sources/dashboard/` → `source_user_dashboard` view

### 7. Inquiry Model Update
**File:** `apps/complaints/models.py`

Added `source` field to the Inquiry model:
- Foreign key to `PXSource`
- `on_delete=PROTECT` to prevent accidental deletion
- Nullable and blank for backward compatibility
- Related name: `inquiries`

Note: Complaint model already had a source field.

### 8. Migrations
Created and applied migrations:
- `px_sources.0005_sourceuser.py`: Creates SourceUser model
- `complaints.0005_inquiry_source.py`: Adds source field to Inquiry

## Original Question: Do We Need SourceUsage Model?

### The SourceUsage Model

The `SourceUsage` model was designed to track usage of sources across the system, providing:
- Historical tracking of when sources were used
- Analytics and reporting capabilities
- Usage patterns and trends
- Hospital and user context for each usage

### Analysis

**Is SourceUsage Needed?**

**Arguments FOR keeping it:**
1. **Analytics & Reporting**: Provides detailed usage statistics over time
2. **Pattern Analysis**: Helps identify trends in source usage
3. **Multi-object Support**: Can track usage for any content type (not just complaints/inquiries)
4. **Historical Data**: Maintains audit trail of source selections
5. **Hospital Context**: Tracks which hospital used which source

**Arguments AGAINST it:**
1. **Redundancy**: Complaint and Inquiry now have direct source fields
2. **Maintenance Overhead**: Additional model to manage
3. **Complexity**: Requires content types and generic foreign keys
4. **Alternative**: Can query Complaint/Inquiry models directly for analytics

### Recommendation

**KEEP the SourceUsage model** but make it optional for now:

1. **Current State**: SourceUsage exists but is not actively used in the UI
2. **Future Enhancement**: Can be utilized when advanced analytics are needed
3. **No Harm**: Having it available provides flexibility for future requirements
4. **Direct Queries**: For now, analytics can be done by querying Complaint/Inquiry directly

**Example of how SourceUsage could be used later:**
```python
# Analytics: Which sources are most popular?
from django.db.models import Count
popular_sources = SourceUsage.objects.values('source__name_en').annotate(
    count=Count('id')
).order_by('-count')

# Trends: Source usage over time
from django.db.models.functions import TruncDate
daily_usage = SourceUsage.objects.annotate(
    date=TruncDate('created_at')
).values('date', 'source__name_en').annotate(
    count=Count('id')
).order_by('date', '-count')
```

## How to Use the Source User Feature

### 1. Assign a User as Source User

**Via Django Admin:**
1. Go to `/admin/px_sources/sourceuser/`
2. Click "Add Source User"
3. Select a User and PX Source
4. Set permissions and status
5. Save

**Via Django Shell:**
```python
from apps.px_sources.models import SourceUser, PXSource
from apps.accounts.models import User

user = User.objects.get(email='user@example.com')
source = PXSource.objects.get(name_en='Call Center')

source_user = SourceUser.objects.create(
    user=user,
    source=source,
    is_active=True,
    can_create_complaints=True,
    can_create_inquiries=True
)
```

### 2. Access Source User Dashboard

Once assigned, the user can access their dashboard at:
```
http://yourdomain.com/px-sources/dashboard/
```

The dashboard will show:
- Their assigned source
- Statistics for complaints/inquiries from that source
- Quick action buttons to create new items
- Recent activity tables

### 3. Create Complaint/Inquiry with Source

When a source user creates a complaint or inquiry, the source is automatically set:

**For Complaints:**
```python
from apps.complaints.models import Complaint
from apps.px_sources.models import SourceUser

source_user = SourceUser.get_active_source_user(request.user)
if source_user and source_user.can_create_complaints:
    complaint = Complaint.objects.create(
        patient=patient,
        hospital=hospital,
        source=source_user.source,  # Automatically set
        title="Title",
        description="Description",
        # ... other fields
    )
```

**For Inquiries:**
```python
from apps.complaints.models import Inquiry
from apps.px_sources.models import SourceUser

source_user = SourceUser.get_active_source_user(request.user)
if source_user and source_user.can_create_inquiries:
    inquiry = Inquiry.objects.create(
        hospital=hospital,
        source=source_user.source,  # Automatically set
        subject="Subject",
        message="Message",
        # ... other fields
    )
```

## Future Enhancements

1. **Auto-Populate Source**: Modify complaint/inquiry create forms to auto-populate source when user is a source user
2. **Permission Checks**: Add permission decorators to prevent non-source users from accessing dashboard
3. **Email Notifications**: Send notifications to source users when new complaints/inquiries are created from their source
4. **Source User Role**: Add a dedicated role in the User model for source users
5. **Bulk Assignment**: Allow assigning multiple users to a single source
6. **Analytics Dashboard**: Create analytics dashboard for source usage (potentially using SourceUsage model)

## Database Schema Changes

### SourceUser Table
```sql
CREATE TABLE px_sources_sourceuser (
    id UUID PRIMARY KEY,
    user_id UUID UNIQUE REFERENCES accounts_user(id),
    source_id UUID REFERENCES px_sources_pxsource(id),
    is_active BOOLEAN DEFAULT TRUE,
    can_create_complaints BOOLEAN DEFAULT TRUE,
    can_create_inquiries BOOLEAN DEFAULT TRUE,
    created_at TIMESTAMP,
    updated_at TIMESTAMP,
    UNIQUE(user_id, source_id)
);

CREATE INDEX px_source_user_user_active ON px_sources_sourceuser(user_id, is_active);
CREATE INDEX px_source_user_source_active ON px_sources_sourceuser(source_id, is_active);
```

### Inquiry Table Update
```sql
ALTER TABLE complaints_inquiry 
ADD COLUMN source_id UUID REFERENCES px_sources_pxsource(id);
```

## Testing Checklist

- [ ] Create a source user via admin
- [ ] Verify source user can access dashboard
- [ ] Verify non-source users get redirected with error
- [ ] Create complaint from source user dashboard
- [ ] Create inquiry from source user dashboard
- [ ] Verify source is correctly set on created items
- [ ] Test permission flags (can_create_complaints, can_create_inquiries)
- [ ] Test activate/deactivate functionality
- [ ] Verify statistics are accurate on dashboard
- [ ] Test with inactive source users

## Migration History

- `px_sources.0005_sourceuser.py` (applied)
  - Created SourceUser model
  
- `complaints.0005_inquiry_source.py` (applied)
  - Added source field to Inquiry model

## Related Files

- `apps/px_sources/models.py` - SourceUser model definition
- `apps/px_sources/serializers.py` - SourceUser serializers
- `apps/px_sources/admin.py` - SourceUser admin interface
- `apps/px_sources/ui_views.py` - Dashboard view
- `templates/px_sources/source_user_dashboard.html` - Dashboard template
- `apps/px_sources/urls.py` - URL routing
- `apps/complaints/models.py` - Inquiry source field

## Conclusion

The Source User feature has been successfully implemented, providing a complete solution for assigning users to manage specific PX Sources. The implementation includes:

1. Database models and migrations
2. Admin interface for management
3. User dashboard for source-specific operations
4. Permission-based access control
5. Statistics and reporting

The SourceUsage model remains in the codebase for future analytics capabilities but is not actively used in the current implementation. It can be leveraged when advanced reporting and trend analysis requirements emerge.