| | | 1 | | using System.Collections.Concurrent; |
| | | 2 | | using FAU.DataAccess; |
| | | 3 | | using Microsoft.EntityFrameworkCore; |
| | | 4 | | |
| | | 5 | | namespace FAU.Logica.Services; |
| | | 6 | | |
| | | 7 | | public sealed class AuditoriaCatalogoResolver : IAuditoriaCatalogoResolver |
| | | 8 | | { |
| | | 9 | | private readonly ApplicationDbContext _context; |
| | | 10 | | |
| | | 11 | | // Cache por nombre (case-insensitive) |
| | 0 | 12 | | private readonly ConcurrentDictionary<string, long> _acciones = new(StringComparer.OrdinalIgnoreCase); |
| | 0 | 13 | | private readonly ConcurrentDictionary<string, long> _contextos = new(StringComparer.OrdinalIgnoreCase); |
| | | 14 | | |
| | 0 | 15 | | public AuditoriaCatalogoResolver(ApplicationDbContext context) |
| | | 16 | | { |
| | 0 | 17 | | _context = context; |
| | 0 | 18 | | } |
| | | 19 | | |
| | | 20 | | public async Task<long> GetAccionIdAsync(string nombreAccion) |
| | | 21 | | { |
| | 0 | 22 | | if (string.IsNullOrWhiteSpace(nombreAccion)) |
| | 0 | 23 | | throw new ArgumentException("El nombre de acción es requerido", nameof(nombreAccion)); |
| | | 24 | | |
| | 0 | 25 | | if (_acciones.TryGetValue(nombreAccion, out var id)) |
| | 0 | 26 | | return id; |
| | | 27 | | |
| | 0 | 28 | | var accion = await _context.Set<FAU.Entidades.Accion>() |
| | 0 | 29 | | .AsNoTracking() |
| | 0 | 30 | | .FirstOrDefaultAsync(a => a.Nombre == nombreAccion); |
| | | 31 | | |
| | 0 | 32 | | if (accion == null) |
| | 0 | 33 | | throw new InvalidOperationException($"No existe la acción '{nombreAccion}' en el catálogo de auditoría."); |
| | | 34 | | |
| | 0 | 35 | | _acciones[nombreAccion] = accion.Id; |
| | 0 | 36 | | return accion.Id; |
| | 0 | 37 | | } |
| | | 38 | | |
| | | 39 | | public async Task<long> GetContextoIdAsync(string nombreContexto) |
| | | 40 | | { |
| | 0 | 41 | | if (string.IsNullOrWhiteSpace(nombreContexto)) |
| | 0 | 42 | | throw new ArgumentException("El nombre de contexto es requerido", nameof(nombreContexto)); |
| | | 43 | | |
| | 0 | 44 | | if (_contextos.TryGetValue(nombreContexto, out var id)) |
| | 0 | 45 | | return id; |
| | | 46 | | |
| | 0 | 47 | | var contexto = await _context.Set<FAU.Entidades.Contexto>() |
| | 0 | 48 | | .AsNoTracking() |
| | 0 | 49 | | .FirstOrDefaultAsync(c => c.Nombre == nombreContexto); |
| | | 50 | | |
| | 0 | 51 | | if (contexto == null) |
| | 0 | 52 | | throw new InvalidOperationException($"No existe el contexto '{nombreContexto}' en el catálogo de auditoría." |
| | | 53 | | |
| | 0 | 54 | | _contextos[nombreContexto] = contexto.Id; |
| | 0 | 55 | | return contexto.Id; |
| | 0 | 56 | | } |
| | | 57 | | } |