# User Roles & Permissions Guide

## Overview

Qaya HRM implements a comprehensive Role-Based Access Control (RBAC) system using Spatie Laravel Permission package, providing granular control over user access and capabilities.

---

## Permission System Architecture

### Three-Layer Security

```
┌─────────────────────────────────────────┐
│ Layer 1: Organization Isolation          │
│ (Multi-tenancy - organization_id)        │
└──────────────┬──────────────────────────┘
               │
┌──────────────▼──────────────────────────┐
│ Layer 2: Role-Based Access Control       │
│ (Roles assigned to users)                │
└──────────────┬──────────────────────────┘
               │
┌──────────────▼──────────────────────────┐
│ Layer 3: Permission-Based Authorization  │
│ (Granular permissions per action)        │
└─────────────────────────────────────────┘
```

---

## Default Roles

### 1. System Administrator

**Description**: Super admin with full system access across all organizations

**Characteristics**:
- `is_system_admin = true`
- No organization_id
- Bypasses all permission checks
- Manages organizations
- System-wide access

**Capabilities**:
- Create/manage organizations
- View all organization data
- System configuration
- User management across organizations
- Security monitoring
- System maintenance

**Access Level**: FULL SYSTEM ACCESS

---

### 2. Administrator (Organization Admin)

**Description**: Full access within their organization

**Key Permissions** (All permissions):
```
✓ All employee management
✓ All attendance management
✓ All leave management
✓ All payroll management
✓ All performance management
✓ All training management
✓ All recruitment management
✓ All reporting
✓ All settings management
✓ User and role management
```

**Typical Users**:
- CEO
- Managing Director
- Organization Owner

**Access Level**: FULL ORGANIZATION ACCESS

---

### 3. HR Manager

**Description**: Comprehensive HR management capabilities

**Key Permissions**:
```
Employee Management:
✓ view_employees
✓ create_employees
✓ edit_employees
✓ delete_employees
✓ import_employees
✓ export_employees

Attendance:
✓ view_attendance
✓ manage_attendance
✓ view_attendance_reports

Leave:
✓ view_all_leaves
✓ approve_leaves
✓ manage_leave_types
✓ adjust_leave_balances

Performance:
✓ view_all_performance
✓ conduct_reviews
✓ manage_competencies

Training:
✓ manage_training
✓ approve_training
✓ view_all_training

Recruitment:
✓ create_job_postings
✓ manage_applications
✓ schedule_interviews
✓ make_offers

Settings:
✓ manage_attendance_settings
✓ manage_leave_types
✓ manage_positions
✓ manage_holidays

Reports:
✓ view_reports
✓ create_reports
✓ export_reports
```

**Cannot Do**:
- Manage payroll
- Approve payroll
- Manage users/roles
- System settings

**Typical Users**:
- HR Manager
- HR Director
- People Operations Manager

**Access Level**: HR FULL ACCESS

---

### 4. Accountant

**Description**: Financial and payroll management

**Key Permissions**:
```
Payroll:
✓ view_payroll
✓ manage_payroll
✓ approve_payroll
✓ manage_payroll_settings

Loans:
✓ view_loans
✓ manage_loans
✓ approve_loans

Employees (Limited):
✓ view_employees (for payroll purposes)

Reports:
✓ view_payroll_reports
✓ view_financial_reports
✓ export_reports
```

**Cannot Do**:
- Manage employees
- Approve leaves
- Conduct performance reviews
- Manage recruitment

**Typical Users**:
- Accountant
- Finance Manager
- Payroll Officer

**Access Level**: FINANCIAL ACCESS

---

### 5. Department Manager

**Description**: Team management and approvals

**Key Permissions**:
```
Team Management:
✓ view_team_employees
✓ view_team_attendance
✓ view_team_performance

Leave:
✓ view_team_leaves
✓ approve_leaves (for team)

Performance:
✓ view_team_performance
✓ conduct_reviews (for team)
✓ manage_team_goals

Training:
✓ approve_training (for team)
✓ recommend_training

Attendance:
✓ view_team_attendance
✓ mark_attendance (for team)

Reports:
✓ view_team_reports
```

**Cannot Do**:
- Manage payroll
- Create employees
- System settings
- Organization-wide changes

**Typical Users**:
- Department Manager
- Team Lead
- Project Manager

**Access Level**: TEAM MANAGEMENT

---

### 6. Employee

**Description**: Self-service access

**Key Permissions**:
```
Self-Service:
✓ view_own_profile
✓ edit_own_profile
✓ view_own_attendance
✓ check_in_out
✓ view_own_leaves
✓ apply_for_leave
✓ view_own_payslips
✓ view_own_performance
✓ create_own_goals
✓ enroll_in_training
✓ view_training_catalog

Limited Views:
✓ view_announcements
✓ view_holidays
✓ view_organization_calendar
```

**Cannot Do**:
- View other employees' data
- Approve anything
- Manage any module
- Access settings
- View reports

**Typical Users**:
- All regular employees
- Staff members
- Individual contributors

**Access Level**: SELF-SERVICE ONLY

---

## Complete Permission List

### Employee Management (8 permissions)

```
view_employees          - View employee list and details
create_employees        - Add new employees
edit_employees          - Modify employee information
delete_employees        - Remove employees
import_employees        - Bulk import employees
export_employees        - Export employee data
view_employee_documents - View employee documents
manage_employee_documents - Upload/delete documents
```

### Department Management (4 permissions)

```
view_departments        - View departments
create_departments      - Create new departments
edit_departments        - Modify departments
delete_departments      - Remove departments
```

### Attendance Management (5 permissions)

```
view_attendance         - View attendance records
manage_attendance       - Mark/edit attendance
view_team_attendance    - View team attendance
view_attendance_reports - Access attendance reports
manage_attendance_settings - Configure attendance rules
```

### Leave Management (7 permissions)

```
view_leaves             - View own leaves
view_team_leaves        - View team leaves
view_all_leaves         - View all leaves
approve_leaves          - Approve/reject leaves
manage_leave_types      - Configure leave types
adjust_leave_balances   - Manually adjust balances
cancel_leaves           - Cancel approved leaves
```

### Payroll Management (6 permissions)

```
view_payroll            - View payroll records
manage_payroll          - Create/edit payroll
approve_payroll         - Approve payroll
process_payroll         - Process payments
manage_payroll_settings - Configure payroll settings
view_payroll_reports    - Access payroll reports
```

### Loan Management (4 permissions)

```
view_loans              - View loan records
manage_loans            - Create/edit loans
approve_loans           - Approve loan applications
process_loan_repayments - Record repayments
```

### Performance Management (6 permissions)

```
view_performance        - View own performance
view_team_performance   - View team performance
view_all_performance    - View all performance
conduct_reviews         - Perform reviews
approve_reviews         - Approve reviews
manage_competencies     - Configure competencies
```

### Training Management (5 permissions)

```
view_training           - View training catalog
enroll_in_training      - Self-enrollment
manage_training         - Create/edit programs
approve_training        - Approve enrollments
view_all_training       - View all training data
```

### Recruitment Management (6 permissions)

```
view_job_postings       - View job postings
create_job_postings     - Create postings
manage_applications     - Review applications
schedule_interviews     - Arrange interviews
evaluate_candidates     - Provide feedback
make_offers             - Extend offers
```

### Reports & Analytics (4 permissions)

```
view_reports            - Access standard reports
create_reports          - Build custom reports
schedule_reports        - Automate reports
export_reports          - Download reports
```

### User Management (5 permissions)

```
view_users              - View user list
create_users            - Create new users
edit_users              - Modify users
delete_users            - Remove users
manage_user_roles       - Assign roles
```

### Role Management (4 permissions)

```
view_roles              - View roles
create_roles            - Create new roles
edit_roles              - Modify roles
delete_roles            - Remove roles
```

### Permission Management (4 permissions)

```
view_permissions        - View permissions
create_permissions      - Create permissions
edit_permissions        - Modify permissions
delete_permissions      - Remove permissions
```

### Settings Management (6 permissions)

```
view_settings           - Access settings
edit_organization       - Modify organization
manage_attendance_settings - Configure attendance
manage_leave_types      - Configure leaves
manage_positions        - Configure positions
manage_holidays         - Configure holidays
```

### Security & Audit (5 permissions)

```
view_security_dashboard - Access security dashboard
view_audit_logs         - View audit trail
manage_ip_whitelist     - Configure IP restrictions
manage_security_settings - Configure security
view_security_reports   - Access security reports
```

### Announcements (4 permissions)

```
view_announcements      - View announcements
create_announcements    - Create announcements
edit_announcements      - Modify announcements
delete_announcements    - Remove announcements
```

**Total: 100+ granular permissions**

---

## Role Assignment

### Assigning Roles to Users

**Via User Management**:
```
1. Navigate to Users → User List
2. Click on user
3. Go to "Roles & Permissions" tab
4. Select role(s) from dropdown
5. Click "Assign Role"
6. User immediately gets role permissions
```

**Via Role Management**:
```
1. Navigate to Roles → Role List
2. Click on role
3. Go to "Users" tab
4. Click "Add Users"
5. Select users
6. Click "Assign"
```

### Multiple Roles

**Users can have multiple roles**:
- Permissions are cumulative
- User gets all permissions from all roles
- Useful for hybrid positions

**Example**:
```
User: Jane Doe
Roles: 
  - Department Manager
  - HR Manager

Effective Permissions:
  All Department Manager permissions
  + All HR Manager permissions
```

---

## Custom Roles

### Creating Custom Roles

**Steps**:
```
1. Navigate to Roles → Create Role
2. Enter role details:
   - Role Name *
   - Description
   - Display Name
3. Select permissions:
   - Browse by category
   - Search permissions
   - Select/deselect
4. Save role
5. Assign to users
```

**Example Custom Roles**:

**Payroll Assistant**:
```
Permissions:
✓ view_employees
✓ view_payroll
✓ view_payroll_reports
✗ manage_payroll
✗ approve_payroll
```

**Recruitment Coordinator**:
```
Permissions:
✓ view_job_postings
✓ create_job_postings
✓ manage_applications
✓ schedule_interviews
✗ make_offers
✗ evaluate_candidates
```

**Training Coordinator**:
```
Permissions:
✓ view_training
✓ manage_training
✓ view_all_training
✗ approve_training
```

---

## Permission Checking

### In Code

**Check Permission**:
```php
// Check if user has permission
if (auth()->user()->can('edit_employees')) {
    // Allow action
}

// Check multiple permissions (any)
if (auth()->user()->hasAnyPermission(['edit_employees', 'view_employees'])) {
    // Allow action
}

// Check multiple permissions (all)
if (auth()->user()->hasAllPermissions(['edit_employees', 'delete_employees'])) {
    // Allow action
}
```

**Check Role**:
```php
// Check if user has role
if (auth()->user()->hasRole('HR Manager')) {
    // Allow action
}

// Check multiple roles
if (auth()->user()->hasAnyRole(['HR Manager', 'Administrator'])) {
    // Allow action
}
```

### In Blade Templates

**Show/Hide Elements**:
```blade
@can('edit_employees')
    <button>Edit Employee</button>
@endcan

@role('HR Manager')
    <a href="/hr-dashboard">HR Dashboard</a>
@endrole

@hasanyrole('HR Manager|Administrator')
    <a href="/settings">Settings</a>
@endhasanyrole
```

### In Routes

**Protect Routes**:
```php
// Single permission
Route::middleware(['permission:edit_employees'])->group(function () {
    Route::get('/employees/{id}/edit', [EmployeeController::class, 'edit']);
});

// Multiple permissions (any)
Route::middleware(['permission:edit_employees|view_employees'])->group(function () {
    // Routes
});

// Role-based
Route::middleware(['role:HR Manager'])->group(function () {
    // Routes
});
```

---

## Best Practices

### For System Administrators

1. **Principle of Least Privilege**
   - Grant minimum necessary permissions
   - Review permissions regularly
   - Remove unused permissions
   - Audit role assignments

2. **Role Design**
   - Create roles based on job functions
   - Keep roles simple and clear
   - Document role purposes
   - Avoid role proliferation

3. **Permission Management**
   - Group related permissions
   - Use consistent naming
   - Document permission purposes
   - Regular permission audits

4. **Security**
   - Monitor privileged access
   - Log permission changes
   - Regular access reviews
   - Enforce separation of duties

### For Organization Admins

1. **User Management**
   - Assign appropriate roles
   - Review assignments quarterly
   - Remove access for terminated users
   - Document role assignments

2. **Custom Roles**
   - Create only when necessary
   - Base on actual job functions
   - Test thoroughly
   - Document clearly

3. **Training**
   - Train users on their permissions
   - Explain access limitations
   - Provide role documentation
   - Support users

---

## Troubleshooting

### Common Issues

**Issue**: User cannot access feature
- **Solution**: Check role assignment, verify permissions, check organization scope

**Issue**: Permission changes not reflecting
- **Solution**: Clear cache, logout/login, check role assignment

**Issue**: User has too much access
- **Solution**: Review roles, remove unnecessary roles, adjust permissions

**Issue**: Cannot assign role
- **Solution**: Verify admin permissions, check role exists, check user status

---

## Permission Matrix

### Quick Reference

| Feature | Admin | HR Mgr | Accountant | Dept Mgr | Employee |
|---------|-------|--------|------------|----------|----------|
| View Employees | ✓ | ✓ | ✓ | Team | Self |
| Edit Employees | ✓ | ✓ | ✗ | ✗ | Self |
| Manage Payroll | ✓ | ✗ | ✓ | ✗ | ✗ |
| Approve Leaves | ✓ | ✓ | ✗ | Team | ✗ |
| Conduct Reviews | ✓ | ✓ | ✗ | Team | Self |
| Manage Training | ✓ | ✓ | ✗ | ✗ | ✗ |
| View Reports | ✓ | ✓ | ✓ | Team | ✗ |
| Manage Settings | ✓ | Partial | ✗ | ✗ | ✗ |
| Manage Users | ✓ | ✗ | ✗ | ✗ | ✗ |

---

## Future Enhancements

- [ ] Dynamic permission groups
- [ ] Time-based permissions
- [ ] Location-based permissions
- [ ] Approval workflows for role changes
- [ ] Permission templates
- [ ] Advanced audit trails
- [ ] Permission analytics
- [ ] Self-service role requests

---

**Last Updated**: February 2026
