# Enhanced Staff Management System

## Overview

This comprehensive staff management system provides role-based access control with granular permissions, default permission templates, and individual user customization capabilities.

## Features

### 🔐 Role-Based Permissions
- **20 Modules**: Dashboard, Users, Clients, Loans, Applications, Repayments, Reports, Documents, Settings, Notifications, Audit, KYC, Payments, Communications, Portfolio, Receipts, Statements, Media, Backup, System
- **20 Actions**: View, Create, Edit, Delete, Approve, Reject, Export, Import, Manage, Assign, Reassign, Suspend, Activate, Verify, Generate, Download, Upload, Share, Print

### 👥 Staff Roles
1. **Administrator**: Full system access
2. **Team Leader**: Management and oversight capabilities
3. **Loan Officer**: Client and loan management
4. **Secretary**: Administrative and documentation tasks

### 🎯 Key Capabilities

#### Default Permission Management
- Set default permissions for each role
- Automatically apply to new staff members
- Bulk update existing staff permissions
- Export/import permission configurations

#### Individual Permission Customization
- Override role defaults for specific users
- Temporary permissions with expiration dates
- Detailed audit trail of permission changes
- Copy permissions between users

#### Advanced Features
- Permission templates for quick assignment
- Bulk permission operations
- Comprehensive audit logging
- Visual permission status indicators
- Real-time permission validation

## Installation & Setup

### 1. Run Migrations
```bash
python manage.py migrate
```

### 2. Setup Enhanced Permissions
```bash
python manage.py setup_enhanced_permissions
```

### 3. Access the System
- **Staff Dashboard**: `/users/staff/dashboard/`
- **Default Permissions**: `/users/staff/default-permissions/`
- **Staff List**: `/users/admin/list/`

## Usage Guide

### Managing Default Permissions

1. **Access Default Permissions**
   - Navigate to `/users/staff/default-permissions/`
   - Select the role tab you want to configure
   - Check/uncheck permissions as needed
   - Save changes

2. **Role-Specific Defaults**
   - **Admin**: All permissions enabled by default
   - **Team Leader**: Management and oversight permissions
   - **Loan Officer**: Client and loan handling permissions
   - **Secretary**: Administrative and documentation permissions

### Managing Individual Staff Permissions

1. **View Staff List**
   - Go to `/users/admin/list/`
   - Click the shield icon next to any staff member

2. **Customize Permissions**
   - Toggle "Custom" checkbox for specific permissions
   - Set custom allowed/denied status
   - Add reason for custom permission
   - Save changes

3. **Reset to Defaults**
   - Click "Reset to Defaults" to remove all custom permissions
   - User will inherit role-based defaults

### Creating New Staff Members

1. **Add Staff User**
   - Click "Add Staff Member" from dashboard
   - Fill in basic information
   - Select role (permissions auto-populate)
   - Customize permissions if needed
   - Save user

2. **Permission Inheritance**
   - New users automatically get role defaults
   - Custom permissions can be set during creation
   - Changes are logged for audit purposes

## Permission System Architecture

### Three-Layer Permission Model

1. **System Defaults**: Hard-coded baseline permissions
2. **Role Defaults**: Customizable defaults per role (stored in `DefaultRolePermission`)
3. **User Overrides**: Individual customizations (stored in `UserPermission`)

### Permission Resolution Order

1. Check for active user-specific permissions
2. Fall back to role-based permissions
3. Default to system baseline (usually denied)

### Database Tables

- `default_role_permissions`: Default permissions for each role
- `role_permissions`: Current role-based permissions
- `user_permissions`: Individual user permission overrides
- `user_access_logs`: Audit trail of permission changes

## API Endpoints

### Staff Management
- `GET /users/staff/dashboard/` - Staff management dashboard
- `GET /users/staff/default-permissions/` - Manage default permissions
- `POST /users/staff/default-permissions/` - Update default permissions
- `GET /users/staff/permissions/<user_id>/` - Individual permission management
- `POST /users/staff/permissions/<user_id>/` - Update individual permissions

### Bulk Operations
- `POST /users/staff/bulk-update/` - Bulk permission updates
- `POST /users/staff/apply-defaults/<user_id>/` - Apply role defaults to user
- `POST /users/staff/copy-permissions/<from_user>/<to_user>/` - Copy permissions

### AJAX Endpoints
- `GET /users/api/role-permissions/<role>/` - Get permissions for role
- `GET /users/staff-list-ajax/` - Get staff list for dropdowns

## Security Features

### Access Control
- Only administrators can manage staff permissions
- All permission changes are logged
- User session validation for sensitive operations
- CSRF protection on all forms

### Audit Trail
- Complete history of permission changes
- User identification for all modifications
- Timestamp and reason tracking
- IP address and session logging

### Permission Validation
- Real-time permission checking
- Expired permission handling
- Role-based access enforcement
- Module and action-level granularity

## Customization

### Adding New Modules
1. Update `MODULE_CHOICES` in `users/models.py`
2. Add module icon in template tags
3. Update default permissions in management command
4. Run migrations and setup command

### Adding New Actions
1. Update `ACTION_CHOICES` in `users/models.py`
2. Update default permissions for each role
3. Run setup command to populate new permissions

### Custom Permission Logic
- Override `has_permission()` method in `CustomUser` model
- Add custom validation in views
- Implement middleware for automatic permission checking

## Troubleshooting

### Common Issues

1. **Permissions Not Working**
   - Ensure migrations are applied
   - Run `setup_enhanced_permissions` command
   - Check user role assignment

2. **Missing Permissions**
   - Verify role defaults are set
   - Check for expired user permissions
   - Confirm module/action combinations exist

3. **Performance Issues**
   - Use `select_related()` for permission queries
   - Cache frequently accessed permissions
   - Consider permission denormalization for high-traffic areas

### Debug Commands
```bash
# Check permission setup
python manage.py shell
>>> from users.models import DefaultRolePermission
>>> DefaultRolePermission.objects.count()

# Verify user permissions
>>> from users.models import CustomUser
>>> user = CustomUser.objects.get(username='testuser')
>>> user.get_effective_permissions()
```

## Best Practices

### Permission Design
- Follow principle of least privilege
- Group related permissions logically
- Use descriptive permission names
- Document permission purposes

### User Management
- Regularly audit staff permissions
- Remove unused custom permissions
- Update role defaults as system evolves
- Train staff on permission system

### Security
- Monitor permission change logs
- Implement permission expiration for temporary access
- Use strong authentication for admin accounts
- Regular security reviews of permission assignments

## Future Enhancements

### Planned Features
- Permission groups for easier management
- Time-based permission scheduling
- Advanced reporting and analytics
- Integration with external authentication systems
- Mobile-responsive permission management
- Automated permission recommendations

### API Improvements
- RESTful API for external integrations
- Webhook notifications for permission changes
- Bulk import/export capabilities
- Permission comparison tools

## Support

For issues or questions regarding the staff management system:

1. Check the troubleshooting section above
2. Review the audit logs for permission changes
3. Verify role and user configurations
4. Test with a clean user account

The system is designed to be robust and user-friendly while maintaining security and auditability.