> ## Documentation Index
> Fetch the complete documentation index at: https://alan-ramirez-dev.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 📜 Audit Log and Privacy

> Immutable transactional log and anonymization of sensitive data.

The auditing module acts as the system's main observer. Its goal is to maintain an unalterable record of critical actions (logins, creations, and logical deletions) complying with strict privacy policies in the handling of sensitive data (demo mode).

## 📡 Event-Driven Architecture

To avoid coupling the audit logic within controllers, the application leverages Laravel's **Events and Listeners** system.

For example, during the authentication flow, the `AuthController` only issues the token. It is the `AuditLoginListener` that passively intercepts the event, collects the `User-Agent`, captures the request context, and inserts it into the audit log's JSON payload.

## 🕵️‍♂️ Privacy by Design

To comply with modern data protection regulations for users (where an IP address is considered personal information), the system does not store exact addresses. This responsibility was extracted into a reusable **Trait** (`AuditableIp`).

```php theme={null}
// Snippet from Trait AuditableIp.php
protected function anonymizeIp(?string $ip): string
{
    if (!$ip) return '0.0.0.0';

    // Masking for IPv4 (Hides the last two octets)
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $segmentos = explode('.', $ip);
        if (count($segmentos) === 4) {
            $segmentos[2] = str_repeat('*', strlen($segmentos[2]));
            $segmentos[3] = str_repeat('*', strlen($segmentos[3]));
            return implode('.', $segmentos);
        }
    }
    
    // (Includes analogous logic for IPv6 segmentation and masking)
    return $ip;
}
```

## 🔄 Automatic Rotation and Maintenance (Model Events)

To ensure that the database does not become saturated with unnecessary historical records and to optimize query performance, the system features a "log rotation" mechanism integrated directly into the Eloquent model lifecycle.

Through the `booted()` method, the `AuditLog` model intercepts the creation event. Every time a new record is inserted, the system dynamically checks if the maximum allowed threshold (50 events) has been exceeded and, if so, automatically purges the oldest records.

```php theme={null}
// Snippet from AuditLog.php (Model Events)
protected static function booted()
{
    static::created(function ($log) {
        $maxRecords = 50;
        $currentCount = DB::table('audit_logs')->count();
        
        if ($currentCount > $maxRecords) {
            $exceso = $currentCount - $maxRecords;
            
            $idsToDelete = DB::table('audit_logs')
                ->whereNotIn('id', [1, 2, 3, 4, 5]) // Protection of immutable demo events
                ->orderBy('id', 'asc')
                ->limit($exceso)
                ->pluck('id');
                
            DB::table('audit_logs')->whereIn('id', $idsToDelete)->delete();
        }
    });
}
```
