# User Multiple Roles Migration Guide

## Overview
The UserProfile model has been updated to support multiple roles per user instead of a single role. This allows users to have combinations like "Sponsor + Guardian" or "Admin + Sponsor".

## Changes Made

### 1. Models (appauthentication/models.py)
- **New Model**: `Role` - Stores available roles (sponsor, guardian, admin)
- **Updated**: `UserProfile.roles` - Changed from `CharField` to `ManyToManyField(Role)`
- **New Methods**:
  - `get_roles_display()` - Returns comma-separated list of roles
  - `has_role(role_name)` - Check if user has a specific role
  - `add_role(role_name)` - Add a role to user
  - `remove_role(role_name)` - Remove a role from user

### 2. Admin Panels
- **appauthentication/admin.py**:
  - Added `RoleAdmin` for managing roles
  - Updated `UserProfileAdmin` with `filter_horizontal` for easy role selection
  - Display all user roles in list view

- **appsponsor/admin.py**:
  - Added user email column
  - Added user roles column in Sponsorship and Donation admin
  - Better filtering and search capabilities

## Migration Steps

### Step 1: Create Database Migration
```bash
python manage.py makemigrations appauthentication
```

### Step 2: Apply Migration
```bash
python manage.py migrate appauthentication
```

### Step 3: Migrate Existing Data (Optional)
If you have existing users with the old single `role` field, run the migration script:

```bash
python migrate_roles.py
```

This script will:
1. Create the default roles (sponsor, guardian, admin)
2. Convert existing single roles to the new many-to-many relationship
3. Assign 'sponsor' as default role to users without roles

### Step 4: Verify in Admin Panel
1. Go to Django admin: `http://localhost:8000/admin/`
2. Check "Roles" - you should see 3 roles
3. Check "User Profiles" - users should have their roles migrated
4. Try adding/removing roles from users

## Usage Examples

### In Python Code

```python
from appauthentication.models import UserProfile, Role

# Get a user profile
profile = UserProfile.objects.get(user__username='john')

# Check if user has a specific role
if profile.has_role('admin'):
    print("User is an admin")

# Add a role
profile.add_role('guardian')

# Remove a role
profile.remove_role('sponsor')

# Get all roles as display string
roles = profile.get_roles_display()  # Returns: "Sponsor, Guardian"

# Get all role objects
all_roles = profile.roles.all()

# Filter users by role
sponsors = UserProfile.objects.filter(roles__name='sponsor')
admins = UserProfile.objects.filter(roles__name='admin')
```

### In Templates

```django
{% if user.user_profile.has_role('admin') %}
    <!-- Admin content -->
{% endif %}

<!-- Display all roles -->
<p>Roles: {{ user.user_profile.get_roles_display }}</p>

<!-- Loop through roles -->
{% for role in user.user_profile.roles.all %}
    <span class="badge">{{ role.get_name_display }}</span>
{% endfor %}
```

### In Views

```python
from django.contrib.auth.decorators import login_required

@login_required
def sponsor_dashboard(request):
    user_profile = request.user.user_profile
    
    if user_profile.has_role('sponsor'):
        # Show sponsor content
        pass
    
    if user_profile.has_role('admin'):
        # Show admin content
        pass
```

## Admin Interface Features

### User Profile Admin
- **Filter by roles**: Use the filter sidebar to see users with specific roles
- **Horizontal filter widget**: Easy multi-select interface for assigning roles
- **Display roles column**: See all user roles at a glance

### Sponsorship/Donation Admin
- **User email column**: Quickly identify users
- **User roles column**: See user roles without clicking through
- **Enhanced search**: Search by username and email

## Notes

- Users can now have multiple roles simultaneously
- The default role for new users should be set in your registration logic
- Consider using Django permissions for more granular access control
- The Role model is separate, making it easier to add new roles in the future

## Troubleshooting

### Migration Issues
If you encounter issues during migration:

```bash
# Check for migration conflicts
python manage.py showmigrations appauthentication

# If needed, fake the migration and handle manually
python manage.py migrate appauthentication --fake

# Then run the data migration script
python migrate_roles.py
```

### Existing Code References
Update any code that references the old `role` field:
- Change `user_profile.role` to `user_profile.roles.all()`
- Change `user_profile.role == 'sponsor'` to `user_profile.has_role('sponsor')`

## Future Enhancements

Potential improvements:
1. Add role permissions system
2. Create role groups (e.g., "Staff" group with admin + guardian)
3. Add role expiration dates
4. Implement role hierarchy
5. Add audit logging for role changes
