# Enhanced Permissions System

This document explains the new enhanced permissions system that provides more granular, page-specific permissions for your loan management application.

## Overview

The enhanced permissions system replaces the generic module-action permissions with specific, feature-based permissions that align with your actual application pages and functionality.

## Key Features

### 1. Page-Specific Permissions
Instead of generic "view", "create", "edit" permissions, the system now provides specific permissions like:
- `clients_create_new` - Create new client
- `loans_approve_application` - Approve loan applications
- `repayments_reconcile_mpesa` - Reconcile M-Pesa payments
- `reports_export_all` - Export all reports

### 2. Organized by Application Pages
Permissions are grouped by the actual pages in your application:

#### Dashboard
- Access dashboard overview
- View key metrics and analytics
- View performance charts
- Access quick actions

#### Clients
- View clients list
- Create new clients
- Edit client profiles
- Manage KYC documents
- Assign to portfolio managers
- Manage registration fees
- Export client data

#### Loans
- View loans list
- Create loan applications
- Approve/reject applications
- Disburse funds
- Process rollovers
- Calculate interest
- Generate receipts
- Modify loan terms
- Close loans

#### All Repayments
- View all repayments
- Record new payments
- Verify payments
- Reconcile M-Pesa payments
- Generate receipts
- View payment analytics
- Export repayment data

#### Portfolio
- View portfolio overview
- Manage client assignments
- Reassign clients
- View performance metrics
- Generate portfolio reports

#### Reports & Statements
- Access various reports (loans due, delinquent, processing fees, etc.)
- Generate loan and client statements
- Download PDF statements
- Email statements to clients
- Export report data

#### Documents & Customer Documents
- Upload and manage documents
- Verify KYC documents
- Approve customer documents
- Organize document folders

#### Payment Receipts
- Generate receipts
- Print receipts
- Email receipts to clients
- Manage receipt templates

#### Notifications
- Send individual notifications
- Send bulk notifications
- Manage notification templates
- Configure notification settings

#### Settings
- General settings management
- Branch settings configuration
- System settings (admin only)
- User management
- M-Pesa configuration

## Role-Based Default Permissions

### Admin
- Full access to all features
- System administration capabilities
- User and permission management
- Database and security settings

### Team Leader
- Most permissions except system administration
- Can approve loans and manage staff
- Full portfolio management
- Advanced reporting capabilities

### Loan Officer
- Client and loan management
- Cannot approve loans (depends on configuration)
- Basic reporting
- Portfolio viewing
- Payment recording

### Secretary
- Document management focus
- Basic client creation
- KYC document handling
- Receipt generation
- Individual notifications

## Implementation

### 1. Update Permissions Structure
Run the management command to update your permissions:

```bash
python manage.py update_enhanced_permissions
```

### 2. Access Enhanced Permissions UI
Navigate to the enhanced permissions page for any staff member:
- Go to Staff Management
- Select a staff member
- Click "Enhanced Permissions" (new button)

### 3. Configure Permissions
The new interface shows permissions organized by page/feature:
- Each section represents an actual page in your application
- Permissions are grouped logically by functionality
- Clear labels indicate what each permission allows

### 4. Template Integration
Update your templates to use the new permission structure:

```html
<!-- Check for specific permission -->
{% if user.has_permission 'loans_approve_application' 'approve' %}
    <button>Approve Loan</button>
{% endif %}

<!-- Check for page access -->
{% if user.has_permission 'dashboard' 'access' %}
    <a href="{% url 'dashboard' %}">Dashboard</a>
{% endif %}
```

### 5. View Integration
Update your views to check specific permissions:

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

@login_required
@permission_required('loans_approve_application', 'approve')
def approve_loan(request, loan_id):
    # Only users with loan approval permission can access
    pass

@login_required
@permission_required('clients_create_new', 'create')
def create_client(request):
    # Only users who can create clients can access
    pass
```

## Benefits

### 1. More Intuitive
- Permissions match actual application features
- Clear understanding of what each permission allows
- Organized by page structure users are familiar with

### 2. Better Security
- Granular control over specific features
- Easier to audit and manage permissions
- Reduced risk of over-permissioning

### 3. Easier Management
- Visual organization by application pages
- Bulk permission templates for common roles
- Clear permission inheritance and overrides

### 4. Scalable
- Easy to add new permissions as features are added
- Flexible role-based defaults
- Custom user-specific overrides

## Migration from Old System

The enhanced permissions system is designed to replace the old generic permissions. When you run the update command:

1. **Old permissions are cleared** - All existing RolePermission and UserPermission records are removed
2. **New structure is created** - Enhanced permissions are created based on role defaults
3. **User accounts are updated** - Staff status is properly set based on roles

### Backup Recommendation
Before running the update, consider backing up your existing permissions if you have custom configurations:

```sql
-- Backup existing permissions
CREATE TABLE role_permissions_backup AS SELECT * FROM role_permissions;
CREATE TABLE user_permissions_backup AS SELECT * FROM user_permissions;
```

## Customization

### Adding New Permissions
To add new permissions for new features:

1. **Update the MODEL_CHOICES** in `users/models.py`:
```python
MODULE_CHOICES = [
    # ... existing choices ...
    ('new_feature', 'New Feature'),
    ('new_feature_specific_action', 'New Feature Specific Action'),
]
```

2. **Update the management command** to include default permissions for roles
3. **Update the enhanced permissions template** to include the new permissions in the UI
4. **Update views and templates** to check for the new permissions

### Creating Permission Templates
You can create permission templates for quick assignment:

```python
# In enhanced_permissions_views.py
templates = {
    'senior_loan_officer': {
        'name': 'Senior Loan Officer',
        'permissions': {
            'loans_approve_application_approve': True,
            'loans_reject_application_reject': True,
            # ... more permissions
        }
    }
}
```

## Troubleshooting

### Permission Not Working
1. Check if the user has the specific permission
2. Verify the permission exists in the database
3. Check if there's a custom user permission override
4. Ensure the view/template is checking the correct permission

### Missing Permissions
1. Run the update command again
2. Check if the permission is defined in MODULE_CHOICES
3. Verify the role has the default permission

### UI Issues
1. Clear browser cache
2. Check if the template is using the correct permission keys
3. Verify the enhanced permissions view is properly configured

## Support

For issues or questions about the enhanced permissions system:
1. Check the Django admin for permission records
2. Review the management command output for errors
3. Test permissions in the Django shell
4. Check the enhanced permissions template for UI issues

The enhanced permissions system provides a much more intuitive and secure way to manage user permissions that aligns with your actual application structure and user workflows.