# Permission System Migration Guide

This guide covers the migration from the legacy permission system to the enhanced granular permission system.

## Overview

The enhanced granular permission system provides:
- Page-specific permissions with granular action controls
- Role-based permission templates
- Custom user permission overrides
- Permission dependencies and expiration
- Comprehensive audit trails
- Backward compatibility with the legacy system

## Migration Process

### Phase 1: Preparation

1. **Backup Current Permissions**
   ```bash
   python manage.py migrate_permissions_to_granular --backup --dry-run
   ```

2. **Validate Current System**
   ```python
   from users.permission_validation import validate_permission_system
   results = validate_permission_system('legacy')
   print(results)
   ```

3. **Review Migration Plan**
   - Identify all existing permissions
   - Map legacy modules to new page structure
   - Plan role template configurations

### Phase 2: Testing Migration

1. **Enable Testing Mode**
   ```python
   from users.feature_flags import set_migration_mode
   set_migration_mode('testing')
   ```

2. **Run Migration in Dry-Run Mode**
   ```bash
   python manage.py migrate_permissions_to_granular --dry-run --validate-only
   ```

3. **Test with Sample Users**
   ```python
   from users.feature_flags import enable_granular_for_user
   enable_granular_for_user(test_user, expires_in=3600)  # 1 hour
   ```

### Phase 3: Gradual Migration

1. **Set Gradual Migration Mode**
   ```python
   set_migration_mode('gradual')
   ```

2. **Run Full Migration**
   ```bash
   python manage.py migrate_permissions_to_granular --backup --force
   ```

3. **Validate Migration**
   ```python
   results = validate_permission_system('migration')
   if results['migration']['is_valid']:
       print("Migration successful!")
   else:
       print("Issues found:", results['migration']['issues'])
   ```

### Phase 4: Complete Migration

1. **Set Complete Migration Mode**
   ```python
   set_migration_mode('complete')
   ```

2. **Disable Legacy Fallback** (Optional)
   ```python
   from users.feature_flags import feature_flags
   feature_flags.set_flag('fallback_to_legacy', False)
   ```

## Rollback Procedure

If issues are encountered, you can rollback to the legacy system:

1. **Rollback Migration**
   ```bash
   python manage.py rollback_permission_migration --backup-file=permission_backup_YYYYMMDD_HHMMSS.json --confirm
   ```

2. **Disable Granular Permissions**
   ```python
   set_migration_mode('disabled')
   ```

## Configuration Options

### Django Settings

Add these settings to your Django configuration:

```python
# Permission system configuration
USE_GRANULAR_PERMISSIONS = True
FALLBACK_TO_LEGACY_PERMISSIONS = True
PERMISSION_CACHE_TIMEOUT = 300  # 5 minutes

# Feature flags (optional - can also be set via code)
PERMISSION_FLAG_USE_GRANULAR_PERMISSIONS = True
PERMISSION_FLAG_ENABLE_PERMISSION_CACHING = True
PERMISSION_FLAG_ENABLE_PERMISSION_AUDIT = True
PERMISSION_FLAG_DEBUG_PERMISSIONS = False
```

### Feature Flags

Feature flags allow fine-grained control over the migration:

```python
from users.feature_flags import feature_flags

# Global flags
feature_flags.set_flag('use_granular_permissions', True)
feature_flags.set_flag('enable_role_templates', True)
feature_flags.set_flag('enable_page_permissions', True)

# User-specific flags (for testing)
feature_flags.enable_granular_permissions_for_user(user, expires_in=3600)
```

## Usage Examples

### Checking Permissions

```python
# Legacy method (still works)
if user.has_permission('loans', 'create'):
    # Allow action

# New granular method
if user.has_page_permission('loans', 'loans_create_application'):
    # Allow action

# Compatibility layer (works with both systems)
from users.permission_compatibility import check_page_permission
if check_page_permission(user, 'loans', 'loans_create_application'):
    # Allow action
```

### Getting User Permissions

```python
# Enhanced permissions with source tracking
permissions = user.get_effective_permissions_enhanced()
print(permissions['system'])  # 'granular' or 'legacy'

# Page-specific permissions
loans_permissions = user.get_page_permissions('loans')
for action, allowed in loans_permissions.items():
    print(f"{action}: {allowed}")

# Available actions for a page
available_actions = user.get_available_page_actions('loans')
```

### Template Usage

```html
<!-- Check page permission in templates -->
{% load permission_tags %}

{% if user|has_page_permission:'loans,loans_create_application' %}
    <a href="{% url 'create_loan' %}" class="btn btn-primary">Create Loan</a>
{% endif %}

<!-- Get available actions -->
{% get_available_actions user 'loans' as loan_actions %}
{% for action in loan_actions %}
    <button data-action="{{ action }}">{{ action|title }}</button>
{% endfor %}
```

## Permission Structure

### Page Permissions

The new system organizes permissions by page:

- **Dashboard**: `dashboard_*`
- **Clients**: `clients_*`
- **Loans**: `loans_*`
- **Repayments**: `repayments_*`
- **Portfolio**: `portfolio_*`
- **Reports**: `reports_*`
- **Documents**: `documents_*`
- **Settings**: `settings_*`

### Permission Categories

Permissions are categorized by type:

- **View**: Access and viewing permissions
- **Create**: Creation and addition permissions
- **Edit**: Modification and update permissions
- **Delete**: Deletion and removal permissions
- **Approve**: Approval and rejection permissions
- **Export**: Export and download permissions
- **Manage**: Management and configuration permissions
- **Process**: Processing and execution permissions

### Role Templates

Default permissions for each role:

- **Admin**: Full access to all permissions
- **Team Leader**: Management permissions for their branch
- **Loan Officer**: Client and loan management permissions
- **Secretary**: Data entry and basic reporting permissions
- **Auditor**: Read-only access with full audit capabilities

## Troubleshooting

### Common Issues

1. **Migration Fails**
   - Check for duplicate permissions in legacy system
   - Validate data integrity before migration
   - Use `--validate-only` flag to identify issues

2. **Permissions Not Working**
   - Check feature flags configuration
   - Verify migration completed successfully
   - Enable debug mode for detailed logging

3. **Performance Issues**
   - Enable permission caching
   - Optimize database queries
   - Consider using Redis for caching

### Debug Mode

Enable debug mode for detailed permission checking logs:

```python
feature_flags.set_flag('debug_permissions', True)
```

### Validation Commands

```bash
# Validate legacy permissions
python manage.py shell -c "
from users.permission_validation import validate_permission_system
print(validate_permission_system('legacy'))
"

# Validate granular permissions
python manage.py shell -c "
from users.permission_validation import validate_permission_system
print(validate_permission_system('granular'))
"

# Validate migration integrity
python manage.py shell -c "
from users.permission_validation import validate_permission_system
print(validate_permission_system('migration'))
"
```

## Best Practices

1. **Always Backup**: Create backups before migration
2. **Test Thoroughly**: Use testing mode with sample users
3. **Gradual Rollout**: Enable for small groups first
4. **Monitor Performance**: Watch for performance impacts
5. **Document Changes**: Keep track of custom permissions
6. **Regular Validation**: Run validation checks periodically

## Support

For issues or questions:

1. Check the validation results for specific error messages
2. Review the migration logs for detailed information
3. Use debug mode to trace permission checking
4. Consult the test cases for usage examples

## Migration Checklist

- [ ] Backup current permissions
- [ ] Validate legacy system integrity
- [ ] Run migration in dry-run mode
- [ ] Test with sample users
- [ ] Run full migration with backup
- [ ] Validate migration results
- [ ] Test application functionality
- [ ] Monitor performance
- [ ] Document any custom configurations
- [ ] Train users on new features (if applicable)

## Advanced Features

### Permission Dependencies

```python
# Set up permission dependencies
page_permission.required_permissions.add(prerequisite_permission)
```

### Permission Expiration

```python
# Set expiring permissions
UserPagePermission.objects.create(
    user=user,
    page_permission=permission,
    is_allowed=True,
    expires_at=timezone.now() + timedelta(days=30)
)
```

### Critical Permissions

```python
# Mark permissions as critical
page_permission.is_critical = True
page_permission.save()
```

### Bulk Permission Updates

```python
# Apply role template to multiple users
from users.services import RolePermissionTemplateManager
template_manager = RolePermissionTemplateManager()
template_manager.apply_defaults_to_users('loan_officer', update_existing=True)
```