# Simplified Permissions System

This document describes the simplified permissions management system that provides a streamlined interface for managing user permissions in the loan management application.

## Overview

The simplified permissions system focuses on the core pages and actions that users need access to, making it easier for administrators to manage permissions without getting overwhelmed by granular details.

## Core Modules

The system is organized around these main modules:

### 1. Dashboard
- **Purpose**: Main application dashboard with metrics and overview
- **Key Actions**: Access, view metrics, generate reports, monitor performance

### 2. Clients
- **Purpose**: Customer/borrower management
- **Key Actions**: Create, edit, view, assign to officers, manage KYC documents

### 3. Loans
- **Purpose**: Loan application and management
- **Key Actions**: Create applications, approve/reject, disburse funds, calculate interest

### 4. Repayments
- **Purpose**: Payment processing and tracking
- **Key Actions**: Record payments, verify transactions, reconcile M-Pesa payments

### 5. Portfolio
- **Purpose**: Portfolio management for loan officers
- **Key Actions**: View portfolio performance, manage client assignments

### 6. Reports & Statements
- **Purpose**: Generate various reports and statements
- **Key Actions**: Generate reports, export data, email statements to clients

### 7. Documents
- **Purpose**: General document management
- **Key Actions**: Upload, download, organize, share documents

### 8. Customer Documents
- **Purpose**: KYC and customer-specific documents
- **Key Actions**: Upload KYC documents, verify identity, approve/reject documents

### 9. Payment Receipts
- **Purpose**: Generate and manage payment receipts
- **Key Actions**: Generate receipts, print, email to clients

### 10. Notifications
- **Purpose**: System notifications and communications
- **Key Actions**: Send notifications, manage templates, configure settings

### 11. Settings
- **Purpose**: General system settings
- **Key Actions**: Configure system parameters (Admin only)

### 12. Branch Settings
- **Purpose**: Branch-specific configurations
- **Key Actions**: Manage branch information, M-Pesa settings

### 13. System Settings
- **Purpose**: Advanced system administration
- **Key Actions**: Database management, security settings (Admin only)

## Permission Actions

Each module supports these standardized actions:

### Core Actions
- **Access**: Basic permission to view the module
- **Create**: Add new records or items
- **Edit**: Modify existing records
- **Delete**: Remove records (usually restricted)

### Workflow Actions
- **Approve**: Approve applications or requests
- **Reject**: Reject applications or requests
- **Verify**: Verify information or documents
- **Validate**: Validate data integrity

### Data Management Actions
- **Export**: Export data to files
- **Import**: Import data from files
- **Download**: Download files or reports
- **Upload**: Upload files or documents
- **Print**: Print reports or documents

### Processing Actions
- **Process**: Process applications or requests
- **Calculate**: Perform calculations (interest, fees, etc.)
- **Generate**: Generate reports or documents
- **Record**: Record activities or transactions
- **Reconcile**: Reconcile data or payments

### Assignment Actions
- **Assign**: Assign tasks or clients to users
- **Reassign**: Reassign existing assignments
- **Manage**: General management permissions
- **Configure**: Configure settings or parameters

### Communication Actions
- **Send**: Send communications
- **Email**: Send emails
- **Notify**: Send notifications
- **Share**: Share information or documents

### Status Control Actions
- **Activate**: Activate features or accounts
- **Deactivate**: Deactivate features or accounts
- **Suspend**: Suspend access or processing
- **Close**: Close accounts or transactions

### Administrative Actions
- **Monitor**: Monitor system activity
- **Audit**: Audit actions and changes
- **Backup**: Backup data
- **Restore**: Restore data

## Role-Based Default Permissions

### Admin
- **Access Level**: Full access to all modules and actions
- **Purpose**: Complete system administration

### Team Leader
- **Access Level**: Broad access excluding system administration
- **Key Permissions**:
  - Full client and loan management
  - Portfolio oversight
  - Report generation
  - Branch settings management
  - No system settings access

### Loan Officer
- **Access Level**: Client and loan focused
- **Key Permissions**:
  - Client management (assigned portfolio)
  - Loan application processing
  - Payment recording
  - Basic reporting
  - No administrative functions

### Secretary
- **Access Level**: Administrative support
- **Key Permissions**:
  - Client data entry
  - Document management
  - Basic loan processing
  - Receipt generation
  - No approval permissions

### Auditor
- **Access Level**: Read-only access for compliance
- **Key Permissions**:
  - View all modules
  - Export and download capabilities
  - Generate reports
  - No create, edit, or delete permissions

### Borrower
- **Access Level**: Self-service only
- **Key Permissions**:
  - View own dashboard
  - View own loans and payments
  - Access own documents
  - View notifications

## Using the Simplified Permissions Interface

### Accessing the Interface
1. Go to Staff Management (`/users/admins/`)
2. Find the user you want to manage
3. Click the purple shield icon (🛡️) for "Simplified Permissions"

### Interface Features

#### Quick Actions
- **Select All**: Check all permission checkboxes
- **Deselect All**: Uncheck all permission checkboxes
- **Select All Access**: Check all "Access" permissions across modules
- **Select All Create**: Check all "Create" permissions across modules
- **Select All Edit**: Check all "Edit" permissions across modules

#### Module-Level Actions
- **Select All** (per module): Check all permissions for a specific module
- **Deselect All** (per module): Uncheck all permissions for a specific module

#### Visual Indicators
- **Green highlight**: Permission is granted
- **Orange asterisk (*)**: Custom override (differs from role default)
- **Module icons**: Visual identification of different modules

### Custom Permissions
- The system allows creating custom permissions that override role defaults
- Custom permissions are marked with an orange asterisk (*)
- Only permissions that differ from the role default are stored as custom overrides

## Setup Instructions

### 1. Run the Setup Script
```bash
python setup_simplified_permissions.py
```

### 2. Verify Installation
- Check that permissions are created in the database
- Access the admin panel to test the interface
- Verify that role-based defaults are working correctly

### 3. Customize Role Permissions (Optional)
- Modify the default permissions in the management command
- Re-run the setup script to apply changes

## API Endpoints

### Get Role Permissions
```
GET /users/api/simplified-role-permissions/<role>/
```
Returns default permissions for a specific role.

### Bulk Update Permissions
```
POST /users/api/bulk-update-simplified-permissions/
```
Update permissions for multiple users at once.

## Database Schema

### Tables Used
- `role_permissions`: Default permissions for each role
- `default_role_permissions`: Template permissions for roles
- `user_permissions`: Custom user-specific permission overrides

### Key Fields
- `role`: User role (admin, team_leader, loan_officer, etc.)
- `module`: Permission module (dashboard, clients, loans, etc.)
- `action`: Permission action (access, create, edit, etc.)
- `is_allowed`: Whether the permission is granted
- `granted_by`: User who granted the custom permission
- `reason`: Reason for the custom permission

## Troubleshooting

### Common Issues

#### Permissions Not Showing
- Ensure the setup script has been run
- Check that the database tables exist
- Verify that default permissions are created

#### Custom Permissions Not Saving
- Check that the user has admin privileges
- Verify the form is submitting correctly
- Check for database constraint errors

#### Role Defaults Not Working
- Ensure DefaultRolePermission records exist
- Check that the role names match exactly
- Verify the permission lookup logic

### Debug Commands
```bash
# Check permission counts
python manage.py shell -c "from users.models import RolePermission; print(RolePermission.objects.count())"

# List permissions for a role
python manage.py shell -c "from users.models import RolePermission; print(list(RolePermission.objects.filter(role='loan_officer', is_allowed=True).values_list('module', 'action')))"
```

## Security Considerations

### Permission Inheritance
- Users inherit permissions from their role by default
- Custom permissions override role defaults
- Admin users always have full access regardless of custom permissions

### Audit Trail
- All permission changes are logged
- User access is tracked for compliance
- Permission grants include reason and granting user

### Best Practices
- Regularly review user permissions
- Use role-based defaults as much as possible
- Document reasons for custom permission overrides
- Monitor permission usage through audit logs

## Future Enhancements

### Planned Features
- Permission templates for common scenarios
- Bulk permission updates
- Permission expiration dates
- Advanced audit reporting
- Permission request workflow

### Integration Points
- LDAP/Active Directory integration
- Single Sign-On (SSO) support
- API-based permission management
- Mobile app permission sync