# SwiftPay Error Logs Feature

## Overview

The Error Logs feature provides comprehensive error tracking and management capabilities for the SwiftPay application. It allows administrators to monitor, track, and resolve errors that occur throughout the system.

## Features

### 1. **Comprehensive Error Tracking**

-   Tracks errors from multiple sources across the application
-   Records detailed error information including stack traces, file paths, and user context
-   Categorizes errors by source and severity levels

### 2. **Admin Management Interface**

-   Table view with filtering and sorting capabilities
-   Detailed modal view for each error log entry
-   Status updates with admin notes
-   Real-time error tracking

### 3. **Error Sources**

The system tracks errors from the following sources:

-   **Authentication**: Login/logout issues, security violations
-   **Wallet Transactions**: Payment processing, balance updates
-   **Crypto Trading**: Quidax API issues, trading failures
-   **Bill Payments**: E-Bills API errors, payment processing
-   **Bank Transfers**: DOT MFB API issues, transfer failures
-   **International Transfers**: Currency exchange, cross-border payments
-   **KYC Verification**: Document processing, verification failures
-   **API Integration**: Third-party service failures
-   **Database**: Connection issues, query failures
-   **System**: Background jobs, server issues
-   **Payment Gateway**: Flutterwave webhook issues
-   **Other**: Miscellaneous errors

### 4. **Status Management**

-   **Open**: New errors that need attention
-   **In Progress**: Errors currently being investigated
-   **Resolved**: Errors that have been fixed
-   **Closed**: Errors that are resolved and archived

### 5. **Severity Levels**

-   **Low**: Minor issues that don't affect core functionality
-   **Medium**: Issues that may impact some users
-   **High**: Significant issues affecting system functionality
-   **Critical**: System-wide issues requiring immediate attention

## Database Schema

The `error_logs` table includes the following fields:

```sql
- id: Primary key
- user_id: Associated user (nullable for system errors)
- error_source: Source of the error (enum)
- error_message: Brief error description
- error_details: Detailed error information (stack trace, etc.)
- error_code: Application-specific error code
- status: Current status (open, in_progress, resolved, closed)
- admin_notes: Admin comments when resolving
- resolved_by: Admin who resolved the error
- resolved_at: Resolution timestamp
- severity: Error severity (low, medium, high, critical)
- file_path: File where error occurred
- line_number: Line number where error occurred
- request_url: URL where error occurred
- user_agent: Browser/app information
- ip_address: User's IP address
- created_at: Error occurrence timestamp
- updated_at: Last update timestamp
```

## Usage

### 1. **Logging Errors (Developer)**

Use the static `logError` method in your application code:

```php
use App\Models\ErrorLog;

// Basic error logging
ErrorLog::logError(
    ErrorLog::SOURCE_WALLET_TRANSACTION,
    'Failed to process wallet funding'
);

// Detailed error logging
try {
    // Some operation that might fail
    $result = $walletService->fundWallet($amount);
} catch (Exception $e) {
    ErrorLog::logError(
        ErrorLog::SOURCE_WALLET_TRANSACTION,
        'Failed to process wallet funding - ' . $e->getMessage(),
        [
            'error_details' => $e->getTraceAsString(),
            'error_code' => 'WT_001',
            'severity' => 'high',
            'user_id' => auth()->id(),
            'file_path' => $e->getFile(),
            'line_number' => $e->getLine()
        ]
    );

    // Handle the error appropriately
    throw $e;
}
```

### 2. **Admin Interface**

#### Accessing Error Logs

1. Login to the admin panel
2. Navigate to **Error Logs** in the sidebar (requires `manage_error_logs` permission)
3. View the table of all error logs

#### Filtering and Searching

-   **Status Filter**: Filter by Open, In Progress, Resolved, or Closed
-   **Error Source Filter**: Filter by specific error sources
-   **Severity Filter**: Filter by error severity levels
-   **Search**: Search in error messages and user names

#### Managing Error Logs

1. **View Details**: Click the "View" button to see complete error information
2. **Update Status**: Change the error status and add admin notes
3. **Resolution Tracking**: System automatically tracks who resolved errors and when

### 3. **Best Practices**

#### For Developers

1. **Use Appropriate Sources**: Choose the most specific error source constant
2. **Provide Context**: Include relevant error details and codes
3. **Set Correct Severity**: Use appropriate severity levels
4. **Don't Log Everything**: Focus on errors that need admin attention
5. **Include User Context**: Associate errors with users when applicable

#### For Administrators

1. **Regular Monitoring**: Check error logs regularly for new issues
2. **Prioritize by Severity**: Address critical and high-severity errors first
3. **Document Resolutions**: Add clear admin notes when resolving errors
4. **Track Patterns**: Look for recurring errors that might need systematic fixes
5. **Close Resolved Errors**: Mark errors as closed after verification

## Permissions

The error logs feature requires the `manage_error_logs` permission. This permission allows users to:

-   View the error logs table
-   Access detailed error information
-   Update error statuses
-   Add resolution notes

## Integration Examples

### In Exception Handlers

```php
// In app/Exceptions/Handler.php
public function report(Throwable $exception)
{
    if ($this->shouldReport($exception)) {
        ErrorLog::logError(
            ErrorLog::SOURCE_SYSTEM,
            'Unhandled exception: ' . $exception->getMessage(),
            [
                'error_details' => $exception->getTraceAsString(),
                'severity' => 'high',
                'file_path' => $exception->getFile(),
                'line_number' => $exception->getLine()
            ]
        );
    }

    parent::report($exception);
}
```

### In API Controllers

```php
// In API controllers
try {
    $response = $externalService->makeRequest($data);
} catch (RequestException $e) {
    ErrorLog::logError(
        ErrorLog::SOURCE_API_INTEGRATION,
        'External API request failed: ' . $e->getMessage(),
        [
            'error_details' => $e->getResponse()->getBody(),
            'error_code' => 'API_' . $e->getCode(),
            'severity' => 'medium'
        ]
    );

    return $this->error('Service temporarily unavailable');
}
```

### In Background Jobs

```php
// In job classes
public function failed(Throwable $exception)
{
    ErrorLog::logError(
        ErrorLog::SOURCE_SYSTEM,
        'Background job failed: ' . get_class($this),
        [
            'error_details' => $exception->getMessage(),
            'error_code' => 'JOB_FAILED',
            'severity' => 'medium'
        ]
    );
}
```

## Routes

-   **Admin Error Logs**: `/admin/error-logs` (GET) - Main error logs management page

## Files Created/Modified

### New Files

-   `app/Models/ErrorLog.php` - Main model with error sources, statuses, and logging methods
-   `app/Livewire/Admin/ErrorLogs.php` - Admin page component
-   `app/Livewire/Admin/ErrorLogTable.php` - Data table component
-   `app/Livewire/Admin/ErrorLogModal.php` - Modal component for viewing/updating errors
-   `database/migrations/2025_07_27_214213_create_error_logs_table.php` - Database migration
-   `database/seeders/ErrorLogSeeder.php` - Sample data seeder
-   `resources/views/livewire/admin/error-logs.blade.php` - Admin page view
-   `resources/views/livewire/admin/error-log-modal.blade.php` - Modal view
-   `resources/views/admin/columns/error-log-button.blade.php` - Table action button

### Modified Files

-   `app/Helpers/PermissionHelper.php` - Added `MANAGE_ERROR_LOGS` permission
-   `database/seeders/PermissionSeeder.php` - Added error logs permission
-   `routes/web.php` - Added error logs route and import
-   `resources/views/livewire/admin/admin-side-bar.blade.php` - Added menu item
-   `resources/css/app.css` - Added CSS classes for error severity levels

## Future Enhancements

1. **Email Notifications**: Send alerts for critical errors
2. **Error Grouping**: Group similar errors to reduce noise
3. **Auto-Resolution**: Automatically resolve certain types of errors
4. **Dashboard Widget**: Show error statistics on admin dashboard
5. **API Endpoints**: Provide API access for external monitoring tools
6. **Export Functionality**: Export error logs for analysis
7. **Error Metrics**: Track error trends and patterns over time

## Troubleshooting

### Common Issues

1. **Permission Denied**: Ensure the user has the `manage_error_logs` permission
2. **Table Not Found**: Run the migration: `php artisan migrate`
3. **CSS Not Loading**: Build assets: `npm run build`
4. **No Sample Data**: Run the seeder: `php artisan db:seed --class=ErrorLogSeeder`

### Performance Considerations

1. **Index Usage**: The table includes indexes on commonly filtered columns
2. **Data Retention**: Consider implementing automatic cleanup of old resolved errors
3. **Bulk Operations**: Use bulk updates for status changes on multiple errors
4. **Caching**: Consider caching error statistics for dashboard displays

## Testing

Test the error logging functionality:

```php
// Test basic error logging
ErrorLog::logError(
    ErrorLog::SOURCE_SYSTEM,
    'Test error message',
    ['severity' => 'low']
);

// Verify error was created
$error = ErrorLog::latest()->first();
```

## Conclusion

The Error Logs feature provides a robust foundation for error tracking and management in the SwiftPay application. It helps administrators maintain system reliability by providing visibility into issues and tracking their resolution progress.
