CRM/backend/app/Services/ActivityLogger.php

53 خطوط
1.5 KiB
PHP

<?php
namespace App\Services;
use App\Models\ActivityLog;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class ActivityLogger
{
public static function log(
string $action,
?string $description = null,
?Model $subject = null,
?array $before = null,
?array $after = null,
): void {
try {
ActivityLog::create([
'user_id' => auth()->id(),
'action' => $action,
'description' => $description,
'before_data' => self::redact($before),
'after_data' => self::redact($after),
'request_id' => request()->header('X-Request-ID') ?: (string) Str::uuid(),
'subject_type' => $subject ? get_class($subject) : null,
'subject_id' => $subject?->id,
'ip_address' => request()->ip(),
'user_agent' => request()->userAgent(),
]);
} catch (\Exception $e) {
// Silent fail for logging
}
}
private static function redact(?array $data): ?array
{
if ($data === null) {
return null;
}
foreach ($data as $key => $value) {
if (in_array((string) $key, ['password', 'token', 'content', 'notes', 'recording_url'], true)) {
$data[$key] = '[REDACTED]';
} elseif (is_array($value)) {
$data[$key] = self::redact($value);
}
}
return $data;
}
}