2025-12-23 15:12:57 -03:00
|
|
|
using Dapper;
|
|
|
|
|
using SIGCM.Domain.Entities;
|
|
|
|
|
using SIGCM.Infrastructure.Data;
|
|
|
|
|
|
|
|
|
|
namespace SIGCM.Infrastructure.Repositories;
|
|
|
|
|
|
|
|
|
|
public class AuditRepository
|
|
|
|
|
{
|
|
|
|
|
private readonly IDbConnectionFactory _db;
|
|
|
|
|
public AuditRepository(IDbConnectionFactory db) => _db = db;
|
|
|
|
|
|
|
|
|
|
public async Task AddLogAsync(AuditLog log)
|
|
|
|
|
{
|
|
|
|
|
using var conn = _db.CreateConnection();
|
|
|
|
|
var sql = @"INSERT INTO AuditLogs (UserId, Action, EntityId, EntityType, Details)
|
|
|
|
|
VALUES (@UserId, @Action, @EntityId, @EntityType, @Details)";
|
|
|
|
|
await conn.ExecuteAsync(sql, log);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<IEnumerable<AuditLog>> GetRecentLogsAsync(int limit = 50)
|
|
|
|
|
{
|
|
|
|
|
using var conn = _db.CreateConnection();
|
|
|
|
|
var sql = @"SELECT TOP (@Limit) a.*, u.Username
|
|
|
|
|
FROM AuditLogs a
|
|
|
|
|
JOIN Users u ON a.UserId = u.Id
|
|
|
|
|
ORDER BY a.CreatedAt DESC";
|
|
|
|
|
return await conn.QueryAsync<AuditLog>(sql, new { Limit = limit });
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public async Task<IEnumerable<AuditLog>> GetLogsByUserAsync(int userId, int limit = 20)
|
|
|
|
|
{
|
|
|
|
|
using var conn = _db.CreateConnection();
|
|
|
|
|
var sql = @"SELECT TOP (@Limit) a.*, u.Username
|
|
|
|
|
FROM AuditLogs a
|
|
|
|
|
JOIN Users u ON a.UserId = u.Id
|
|
|
|
|
WHERE a.UserId = @UserId
|
|
|
|
|
ORDER BY a.CreatedAt DESC";
|
|
|
|
|
return await conn.QueryAsync<AuditLog>(sql, new { UserId = userId, Limit = limit });
|
|
|
|
|
}
|
2026-01-06 10:34:06 -03:00
|
|
|
|
|
|
|
|
public async Task<IEnumerable<AuditLog>> GetFilteredLogsAsync(DateTime from, DateTime to, int? userId = null)
|
|
|
|
|
{
|
|
|
|
|
using var conn = _db.CreateConnection();
|
|
|
|
|
var sql = @"SELECT a.*, u.Username
|
|
|
|
|
FROM AuditLogs a
|
|
|
|
|
JOIN Users u ON a.UserId = u.Id
|
|
|
|
|
WHERE a.CreatedAt >= @From AND a.CreatedAt <= @To";
|
|
|
|
|
|
|
|
|
|
if (userId.HasValue) sql += " AND a.UserId = @UserId";
|
|
|
|
|
|
|
|
|
|
sql += " ORDER BY a.CreatedAt DESC";
|
|
|
|
|
|
|
|
|
|
return await conn.QueryAsync<AuditLog>(sql, new { From = from, To = to, UserId = userId });
|
|
|
|
|
}
|
2025-12-23 15:12:57 -03:00
|
|
|
}
|