81 lines
2.5 KiB
PHP
81 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use CodeIgniter\Model;
|
|
|
|
class AuditLogModel extends Model
|
|
{
|
|
protected $table = 'audit_logs';
|
|
protected $primaryKey = 'id';
|
|
protected $useAutoIncrement = true;
|
|
protected $returnType = 'array';
|
|
protected $useSoftDeletes = false;
|
|
protected $protectFields = true;
|
|
protected $allowedFields = [
|
|
'workspace_id',
|
|
'user_id',
|
|
'action',
|
|
'resource_type',
|
|
'resource_id',
|
|
'old_value',
|
|
'new_value',
|
|
'ip_address',
|
|
'user_agent',
|
|
];
|
|
|
|
protected $useTimestamps = false;
|
|
|
|
/**
|
|
* @param array{user_id?: int, action?: string, date_from?: string, date_to?: string, workspace_id?: int|null} $filters
|
|
* @return array{data: list<array<string, mixed>>, pager: \CodeIgniter\Pager\Pager}
|
|
*/
|
|
public function paginateFiltered(int $perPage, array $filters): array
|
|
{
|
|
$this->select('audit_logs.*, users.name AS user_name, users.email AS user_email')
|
|
->join('users', 'users.id = audit_logs.user_id', 'left')
|
|
->orderBy('audit_logs.id', 'DESC');
|
|
|
|
if (array_key_exists('workspace_id', $filters)) {
|
|
if ($filters['workspace_id'] === null) {
|
|
$this->where('audit_logs.workspace_id IS NULL', null, false);
|
|
} else {
|
|
$this->where('audit_logs.workspace_id', (int) $filters['workspace_id']);
|
|
}
|
|
}
|
|
|
|
if (! empty($filters['user_id'])) {
|
|
$this->where('audit_logs.user_id', (int) $filters['user_id']);
|
|
}
|
|
|
|
if (! empty($filters['action'])) {
|
|
$this->like('audit_logs.action', (string) $filters['action'], 'both');
|
|
}
|
|
|
|
if (! empty($filters['date_from'])) {
|
|
$this->where('audit_logs.created_at >=', (string) $filters['date_from'] . ' 00:00:00');
|
|
}
|
|
|
|
if (! empty($filters['date_to'])) {
|
|
$this->where('audit_logs.created_at <=', (string) $filters['date_to'] . ' 23:59:59');
|
|
}
|
|
|
|
return [
|
|
'data' => $this->paginate($perPage),
|
|
'pager' => $this->pager,
|
|
];
|
|
}
|
|
|
|
public function findWithUser(int $id): ?array
|
|
{
|
|
$row = $this->builder()
|
|
->select('audit_logs.*, users.name AS user_name, users.email AS user_email')
|
|
->join('users', 'users.id = audit_logs.user_id', 'left')
|
|
->where('audit_logs.id', $id)
|
|
->get()
|
|
->getRowArray();
|
|
|
|
return $row ?: null;
|
|
}
|
|
}
|