# Transaction Permissions System

## Overview
This document outlines the permission system implemented for the AIPT Transaction Management System, specifically for the `/acc-transactions/toggle-has-bill` route and related transaction operations.

## Permissions Structure

### Transaction Management Permissions
- `transaction-list` - View list of transactions
- `transaction-create` - Create new transactions
- `transaction-edit` - Edit existing transactions
- `transaction-delete` - Delete transactions
- `transaction-view` - View individual transaction details
- `transaction-approve` - Approve transactions in workflow
- `transaction-toggle-bill` - Toggle billing status of transactions
- `transaction-export` - Export transaction data
- `transaction-report` - Generate transaction reports

### Action Type Transaction Permissions
- `action-type-list` - View list of action types
- `action-type-create` - Create new action types
- `action-type-edit` - Edit existing action types
- `action-type-delete` - Delete action types

## Implementation Details

### 1. Middleware Protection
The `/acc-transactions/toggle-has-bill` route is protected by the `transaction.permission:transaction-toggle-bill` middleware, which:
- Checks if the user is authenticated
- Verifies the user has the `transaction-toggle-bill` permission
- Performs additional business logic validation for billing status changes

### 2. Business Logic Validation
The `TransactionPermissionMiddleware` includes specific logic for the toggle bill functionality:
- Users can toggle billing status if they are the transaction creator
- Admin users (role_id = 1 or 'admin' role) can toggle any transaction
- Users in the approval chain for the transaction can toggle billing
- Users in the same department as the transaction can toggle billing

### 3. Controller-Level Protection
The `toggleHasBill` method in `AccTransactionController` includes:
- Permission check using Laravel's `can()` method
- Detailed logging for security auditing
- Proper error responses for unauthorized access

## Role-Based Access Control

### Admin Role
- Full access to all transaction operations
- Can toggle billing status for any transaction
- Can manage action types

### Manager Role
- Most transaction permissions except delete
- Can toggle billing status
- Can manage action types (except delete)

### Accountant Role
- Focus on billing and financial operations
- Can toggle billing status
- Can view and export transaction data

### Department Head Role
- Department-specific transaction management
- Can toggle billing status for department transactions
- Can manage action types for their department

### User Role
- Basic view-only access
- Cannot toggle billing status

## Security Features

### 1. Multi-Layer Protection
- Route-level middleware protection
- Controller-level permission checks
- Business logic validation

### 2. Audit Logging
- All permission denials are logged
- Transaction modifications are tracked
- User actions are recorded with timestamps

### 3. Error Handling
- Graceful error responses
- No sensitive information exposure
- Consistent error format across the API

## Usage Examples

### Assigning Permissions to Users
```php
// Assign specific permission to user
$user->givePermissionTo('transaction-toggle-bill');

// Assign multiple permissions
$user->givePermissionTo([
    'transaction-list',
    'transaction-view',
    'transaction-toggle-bill'
]);

// Assign role with permissions
$user->assignRole('accountant');
```

### Checking Permissions in Code
```php
// Check if user can toggle billing
if (auth()->user()->can('transaction-toggle-bill')) {
    // Allow toggle operation
}

// Check multiple permissions
if (auth()->user()->hasAnyPermission(['transaction-edit', 'transaction-approve'])) {
    // Allow operation
}
```

### Frontend Permission Checks
```javascript
// Check permission before showing toggle button
if (userPermissions.includes('transaction-toggle-bill')) {
    // Show toggle button
}
```

## Database Schema

### Permissions Table
```sql
CREATE TABLE permissions (
    id bigint unsigned NOT NULL AUTO_INCREMENT,
    name varchar(255) NOT NULL,
    guard_name varchar(255) NOT NULL,
    created_at timestamp NULL DEFAULT NULL,
    updated_at timestamp NULL DEFAULT NULL,
    PRIMARY KEY (id),
    UNIQUE KEY permissions_name_guard_name_unique (name,guard_name)
);
```

### Role Has Permissions Table
```sql
CREATE TABLE role_has_permissions (
    permission_id bigint unsigned NOT NULL,
    role_id bigint unsigned NOT NULL,
    PRIMARY KEY (permission_id,role_id),
    KEY role_has_permissions_role_id_foreign (role_id),
    CONSTRAINT role_has_permissions_permission_id_foreign FOREIGN KEY (permission_id) REFERENCES permissions (id) ON DELETE CASCADE,
    CONSTRAINT role_has_permissions_role_id_foreign FOREIGN KEY (role_id) REFERENCES roles (id) ON DELETE CASCADE
);
```

## Migration and Seeding

### Running Migrations
```bash
php artisan migrate
```

### Seeding Permissions
```bash
php artisan db:seed --class=TransactionPermissionsSeeder
```

### Clearing Permission Cache
```bash
php artisan permission:cache-reset
```

## Testing Permissions

### Test User Access
```php
// Test if user can toggle billing
$user = User::find(1);
$canToggle = $user->can('transaction-toggle-bill');

// Test role-based access
$user->hasRole('accountant');
```

### API Testing
```bash
# Test with valid permission
curl -X POST /acc-transactions/toggle-has-bill \
  -H "Authorization: Bearer {token}" \
  -d "transaction_id=1&has_bills=true"

# Expected response for unauthorized user
{
  "success": false,
  "message": "You do not have permission to perform this action",
  "required_permission": "transaction-toggle-bill"
}
```

## Troubleshooting

### Common Issues

1. **Permission Not Found**
   - Ensure permissions are seeded in the database
   - Check permission cache is cleared
   - Verify permission name spelling

2. **Middleware Not Working**
   - Check middleware is registered in Kernel.php
   - Verify route has middleware applied
   - Ensure user is authenticated

3. **Business Logic Validation Failing**
   - Check transaction exists
   - Verify user relationship to transaction
   - Review department and role assignments

### Debug Commands
```bash
# Check user permissions
php artisan tinker
>>> $user = User::find(1);
>>> $user->getAllPermissions();

# Check role permissions
>>> $role = Role::find(1);
>>> $role->permissions;

# Clear all caches
php artisan cache:clear
php artisan config:clear
php artisan permission:cache-reset
```

## Security Considerations

1. **Regular Permission Audits**
   - Review user permissions quarterly
   - Remove unused permissions
   - Monitor permission usage logs

2. **Principle of Least Privilege**
   - Assign minimum required permissions
   - Regular access reviews
   - Immediate removal of unused access

3. **Monitoring and Alerting**
   - Log all permission denials
   - Monitor for suspicious access patterns
   - Alert on privilege escalation attempts

## Future Enhancements

1. **Time-Based Permissions**
   - Temporary permission grants
   - Scheduled permission changes
   - Expiring access tokens

2. **Context-Aware Permissions**
   - Department-specific restrictions
   - Client-based access controls
   - Geographic restrictions

3. **Advanced Audit Features**
   - Permission change history
   - Access pattern analysis
   - Compliance reporting
