# Secretary Module Permissions Guide

## Overview

The Secretary module uses Spatie Laravel Permission package for comprehensive role-based access control. This guide covers all permissions, roles, and implementation details.

## Installation & Setup

### 1. Run the Permission Seeder
```bash
php artisan db:seed --class=Modules\\Secretary\\Database\\Seeders\\SecretaryPermissionSeeder
```

### 2. Clear Permission Cache
```bash
php artisan permission:cache-reset
```

### 3. Assign Roles to Users
```php
// Assign Secretary Admin role
$user->assignRole('Secretary Admin');

// Assign Secretary Manager role
$user->assignRole('Secretary Manager');

// Assign Secretary Agent role
$user->assignRole('Secretary Agent');

// Assign Secretary Viewer role
$user->assignRole('Secretary Viewer');

// Assign Secretary Client role
$user->assignRole('Secretary Client');
```

## Permission Structure

### Dashboard Permissions
- `secretary-dashboard-view` - View the Secretary dashboard

### Ticket Management Permissions
- `secretary-ticket-list` - View ticket list
- `secretary-ticket-create` - Create new tickets
- `secretary-ticket-view` - View ticket details
- `secretary-ticket-edit` - Edit existing tickets
- `secretary-ticket-delete` - Delete tickets
- `secretary-ticket-assign` - Assign tickets to users
- `secretary-ticket-status-update` - Update ticket status
- `secretary-ticket-priority-update` - Update ticket priority
- `secretary-ticket-close` - Close tickets
- `secretary-ticket-reopen` - Reopen closed tickets

### Comment Management Permissions
- `secretary-comment-create` - Create comments
- `secretary-comment-edit` - Edit comments
- `secretary-comment-delete` - Delete comments
- `secretary-comment-view` - View comments
- `secretary-comment-internal` - Create internal comments

### File Attachment Permissions
- `secretary-attachment-upload` - Upload attachments
- `secretary-attachment-download` - Download attachments
- `secretary-attachment-delete` - Delete attachments

### Reporting Permissions
- `secretary-report-view` - View reports
- `secretary-report-analytics` - View analytics reports
- `secretary-report-performance` - View performance reports
- `secretary-report-export` - Export reports

### Settings Permissions
- `secretary-settings-view` - View settings
- `secretary-settings-categories` - Manage categories
- `secretary-settings-priorities` - Manage priorities
- `secretary-settings-update` - Update settings

### Advanced Permissions
- `secretary-ticket-bulk-actions` - Perform bulk actions
- `secretary-ticket-export` - Export tickets
- `secretary-ticket-import` - Import tickets
- `secretary-ticket-merge` - Merge tickets
- `secretary-ticket-duplicate` - Duplicate tickets

### Admin Permissions
- `secretary-admin-all` - Full admin access
- `secretary-admin-settings` - Admin settings access
- `secretary-admin-users` - Admin user management
- `secretary-admin-reports` - Admin reports access

## Predefined Roles

### Secretary Admin
Full access to all Secretary module features including:
- All ticket management operations
- All comment operations
- All attachment operations
- All reporting features
- All settings management
- All advanced features
- Admin privileges

### Secretary Manager
Management-level access including:
- View and create tickets
- Edit and assign tickets
- Update status and priority
- Manage comments (including internal)
- Upload and download attachments
- View reports and analytics
- Perform bulk actions
- Export data

### Secretary Agent
Basic ticket handling including:
- View and create tickets
- Edit assigned tickets
- Update ticket status
- Create and edit comments
- Upload and download attachments

### Secretary Viewer
Read-only access including:
- View dashboard
- View ticket list and details
- View comments
- Download attachments
- View basic reports

### Secretary Client
Limited access for external users including:
- Create tickets
- View own tickets
- Create and view comments
- Upload and download attachments

## Implementation Examples

### Controller Permission Checks
```php
// Check permission in controller method
public function index(Request $request)
{
    if (!auth()->user()->can('secretary-ticket-list')) {
        abort(403, 'You do not have permission to view tickets.');
    }
    // ... rest of method
}
```

### Route Protection
```php
// Protect routes with middleware
Route::get('/tickets', [SecretaryTicketController::class, 'index'])
    ->middleware('secretary.permission:secretary-ticket-list')
    ->name('tickets.index');
```

### Blade Template Permission Checks
```blade
{{-- Using @can directive --}}
@can('secretary-ticket-create')
    <a href="{{ route('secretary.tickets.create') }}" class="btn btn-primary">
        Create New Ticket
    </a>
@endcan

{{-- Using custom @secretarycan directive --}}
@secretarycan('secretary-ticket-edit')
    <button class="btn btn-warning">Edit Ticket</button>
@endsecretarycan

{{-- Using role-based directives --}}
@secretaryadmin
    <div class="admin-panel">
        <!-- Admin-only content -->
    </div>
@endsecretaryadmin

@secretarymanager
    <div class="manager-panel">
        <!-- Manager content -->
    </div>
@endsecretarymanager
```

### JavaScript Permission Checks
```javascript
// Check permissions in JavaScript
function checkPermission(permission) {
    // This would typically be passed from the backend
    return window.userPermissions.includes(permission);
}

if (checkPermission('secretary-ticket-delete')) {
    // Show delete button
}
```

## Permission Helper Trait

Use the `SecretaryPermissionTrait` in your controllers or services:

```php
use Modules\Secretary\Traits\SecretaryPermissionTrait;

class MyController extends Controller
{
    use SecretaryPermissionTrait;
    
    public function someMethod()
    {
        if ($this->canCreateTickets()) {
            // User can create tickets
        }
        
        if ($this->isSecretaryAdmin()) {
            // User has admin privileges
        }
    }
}
```

## Custom Middleware

The module includes a custom middleware `SecretaryPermissionMiddleware` that:
- Checks if user is authenticated
- Validates specific permissions
- Provides custom error responses for API and web requests
- Allows bypass for Secretary Admin and SuperAdmin roles

## Testing Permissions

### Test Permission Assignment
```php
// In tinker or test
$user = User::find(1);
$user->givePermissionTo('secretary-ticket-create');
$user->can('secretary-ticket-create'); // Should return true
```

### Test Role Assignment
```php
$user = User::find(1);
$user->assignRole('Secretary Manager');
$user->hasRole('Secretary Manager'); // Should return true
```

### Test Permission in Blade
```php
// Check if user has any Secretary permissions
$user->getAllPermissions()->filter(function($permission) {
    return str_starts_with($permission->name, 'secretary-');
});
```

## Common Commands

```bash
# Clear permission cache
php artisan permission:cache-reset

# List all permissions
php artisan tinker
>>> Permission::all()->pluck('name');

# List Secretary permissions
php artisan tinker
>>> Permission::where('name', 'like', 'secretary-%')->get();

# Check user permissions
php artisan tinker
>>> User::find(1)->getAllPermissions();

# Assign permission to role
php artisan tinker
>>> Role::findByName('Secretary Manager')->givePermissionTo('secretary-ticket-export');
```

## Security Best Practices

1. **Always check permissions** in controllers before performing actions
2. **Use middleware** for route protection
3. **Validate permissions** in JavaScript for better UX
4. **Regular permission audits** to ensure proper access control
5. **Principle of least privilege** - only grant necessary permissions
6. **Regular testing** of permission scenarios

## Troubleshooting

### Permission Not Working
1. Check if permission exists in database
2. Verify user has the permission or role
3. Clear permission cache: `php artisan permission:cache-reset`
4. Check middleware registration

### Role Not Working
1. Verify role exists in database
2. Check user role assignment
3. Ensure role has required permissions
4. Clear permission cache

### Middleware Issues
1. Check middleware registration in service provider
2. Verify route middleware syntax
3. Check authentication status
4. Review middleware logic

## Migration from Existing System

If migrating from an existing permission system:

1. **Map existing permissions** to new Secretary permissions
2. **Create migration script** to assign new roles to users
3. **Update views** to use new permission checks
4. **Test thoroughly** before going live
5. **Document changes** for team reference

## Support

For issues with the permission system:
1. Check the logs in `storage/logs/`
2. Verify database connectivity
3. Review permission assignments
4. Test with different user roles
5. Check middleware configuration
