Files
SIG-CM/src/SIGCM.Infrastructure/Repositories/AuditRepository.cs
2025-12-23 15:12:57 -03:00

40 lines
1.4 KiB
C#

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 });
}
}