Init Commit
This commit is contained in:
115
Backend/GestorFacturas.API/Controllers/AuthController.cs
Normal file
115
Backend/GestorFacturas.API/Controllers/AuthController.cs
Normal file
@@ -0,0 +1,115 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using GestorFacturas.API.Data;
|
||||
using GestorFacturas.API.Services;
|
||||
using GestorFacturas.API.Models;
|
||||
|
||||
namespace GestorFacturas.API.Controllers;
|
||||
|
||||
[Route("api/[controller]")]
|
||||
[ApiController]
|
||||
public class AuthController : ControllerBase
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly AuthService _authService;
|
||||
|
||||
public AuthController(ApplicationDbContext context, AuthService authService)
|
||||
{
|
||||
_context = context;
|
||||
_authService = authService;
|
||||
}
|
||||
|
||||
[HttpPost("login")]
|
||||
public async Task<IActionResult> Login([FromBody] LoginDto login)
|
||||
{
|
||||
var usuario = await _context.Usuarios.FirstOrDefaultAsync(u => u.Username == login.Username);
|
||||
|
||||
if (usuario == null || !_authService.VerificarPassword(login.Password, usuario.PasswordHash))
|
||||
{
|
||||
return Unauthorized(new { mensaje = "Credenciales incorrectas" });
|
||||
}
|
||||
|
||||
// Generar Tokens
|
||||
var accessToken = _authService.GenerarAccessToken(usuario);
|
||||
|
||||
// Pasamos la elección del usuario (true/false)
|
||||
var refreshToken = _authService.GenerarRefreshToken(usuario.Id, login.RememberMe);
|
||||
|
||||
_context.RefreshTokens.Add(refreshToken);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
token = accessToken,
|
||||
refreshToken = refreshToken.Token,
|
||||
usuario = usuario.Username
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPost("refresh-token")]
|
||||
public async Task<IActionResult> RefreshToken([FromBody] RefreshTokenRequest request)
|
||||
{
|
||||
var oldRefreshToken = await _context.RefreshTokens
|
||||
.Include(r => r.Usuario)
|
||||
.FirstOrDefaultAsync(r => r.Token == request.Token);
|
||||
|
||||
if (oldRefreshToken == null || !oldRefreshToken.IsActive)
|
||||
{
|
||||
return Unauthorized(new { mensaje = "Token inválido" });
|
||||
}
|
||||
|
||||
// Revocar el anterior
|
||||
oldRefreshToken.Revoked = DateTime.UtcNow;
|
||||
|
||||
// Generamos el nuevo token heredando la persistencia del anterior.
|
||||
// Si el usuario marcó "Recordarme" hace 20 días, el nuevo token seguirá siendo persistente.
|
||||
// Si no lo marcó, seguirá siendo de corta duración.
|
||||
var newRefreshToken = _authService.GenerarRefreshToken(oldRefreshToken.UsuarioId, oldRefreshToken.IsPersistent);
|
||||
|
||||
var newAccessToken = _authService.GenerarAccessToken(oldRefreshToken.Usuario!);
|
||||
|
||||
_context.RefreshTokens.Add(newRefreshToken);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
token = newAccessToken,
|
||||
refreshToken = newRefreshToken.Token,
|
||||
usuario = oldRefreshToken.Usuario!.Username
|
||||
});
|
||||
}
|
||||
|
||||
[HttpPost("revoke")]
|
||||
public async Task<IActionResult> Revoke([FromBody] RefreshTokenRequest request)
|
||||
{
|
||||
var token = request.Token;
|
||||
|
||||
// Buscamos el token en la BD
|
||||
var refreshToken = await _context.RefreshTokens
|
||||
.FirstOrDefaultAsync(r => r.Token == token);
|
||||
|
||||
if (refreshToken == null)
|
||||
return NotFound(new { mensaje = "Token no encontrado" });
|
||||
|
||||
// Lo revocamos inmediatamente
|
||||
refreshToken.Revoked = DateTime.UtcNow;
|
||||
|
||||
_context.Update(refreshToken);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
return Ok(new { mensaje = "Sesión cerrada correctamente" });
|
||||
}
|
||||
}
|
||||
|
||||
// DTOs
|
||||
public class LoginDto
|
||||
{
|
||||
public string Username { get; set; } = string.Empty;
|
||||
public string Password { get; set; } = string.Empty;
|
||||
public bool RememberMe { get; set; } = false;
|
||||
}
|
||||
|
||||
public class RefreshTokenRequest
|
||||
{
|
||||
public string Token { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Data.SqlClient;
|
||||
using GestorFacturas.API.Data;
|
||||
using GestorFacturas.API.Models;
|
||||
using GestorFacturas.API.Models.DTOs;
|
||||
using GestorFacturas.API.Services.Interfaces;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace GestorFacturas.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize]
|
||||
public class ConfiguracionController : ControllerBase
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly IMailService _mailService;
|
||||
private readonly ILogger<ConfiguracionController> _logger;
|
||||
private readonly IEncryptionService _encryptionService;
|
||||
|
||||
public ConfiguracionController(
|
||||
ApplicationDbContext context,
|
||||
IMailService mailService,
|
||||
ILogger<ConfiguracionController> logger,
|
||||
IEncryptionService encryptionService)
|
||||
{
|
||||
_context = context;
|
||||
_mailService = mailService;
|
||||
_logger = logger;
|
||||
_encryptionService = encryptionService;
|
||||
}
|
||||
|
||||
[HttpGet]
|
||||
public async Task<ActionResult<ConfiguracionDto>> ObtenerConfiguracion()
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
|
||||
if (config == null)
|
||||
{
|
||||
return NotFound(new { mensaje = "No se encontró la configuración del sistema" });
|
||||
}
|
||||
|
||||
var dto = MapearADto(config);
|
||||
|
||||
// --- LÓGICA PARA CALCULAR PRÓXIMA EJECUCIÓN ---
|
||||
if (config.EnEjecucion && config.UltimaEjecucion.HasValue)
|
||||
{
|
||||
dto.ProximaEjecucion = CalcularFechaProxima(config);
|
||||
}
|
||||
else
|
||||
{
|
||||
dto.ProximaEjecucion = null; // Si está detenido o nunca corrió
|
||||
}
|
||||
|
||||
// DESENCRIPTAR PARA MOSTRAR AL USUARIO
|
||||
dto.DBUsuario = _encryptionService.Decrypt(config.DBUsuario ?? "");
|
||||
dto.DBClave = _encryptionService.Decrypt(config.DBClave ?? "");
|
||||
dto.SMTPUsuario = _encryptionService.Decrypt(config.SMTPUsuario ?? "");
|
||||
dto.SMTPClave = _encryptionService.Decrypt(config.SMTPClave ?? "");
|
||||
|
||||
return Ok(dto);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener configuración");
|
||||
return StatusCode(500, new { mensaje = "Error al obtener la configuración" });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPut]
|
||||
public async Task<ActionResult<ConfiguracionDto>> ActualizarConfiguracion([FromBody] ConfiguracionDto dto)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (dto.Periodicidad == "Minutos" && dto.ValorPeriodicidad < 15)
|
||||
{
|
||||
return BadRequest(new { mensaje = "La periodicidad mínima permitida es de 15 minutos." });
|
||||
}
|
||||
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
|
||||
if (config == null)
|
||||
{
|
||||
return NotFound(new { mensaje = "No se encontró la configuración del sistema" });
|
||||
}
|
||||
|
||||
config.Periodicidad = dto.Periodicidad;
|
||||
config.ValorPeriodicidad = dto.ValorPeriodicidad;
|
||||
config.HoraEjecucion = dto.HoraEjecucion;
|
||||
config.EnEjecucion = dto.EnEjecucion;
|
||||
|
||||
config.DBServidor = dto.DBServidor;
|
||||
config.DBNombre = dto.DBNombre;
|
||||
config.DBTrusted = dto.DBTrusted;
|
||||
|
||||
config.RutaFacturas = dto.RutaFacturas;
|
||||
config.RutaDestino = dto.RutaDestino;
|
||||
|
||||
config.SMTPServidor = dto.SMTPServidor;
|
||||
config.SMTPPuerto = dto.SMTPPuerto;
|
||||
config.SMTPSSL = dto.SMTPSSL;
|
||||
config.SMTPDestinatario = dto.SMTPDestinatario;
|
||||
config.AvisoMail = dto.AvisoMail;
|
||||
|
||||
// ENCRIPTAR ANTES DE GUARDAR
|
||||
config.DBUsuario = _encryptionService.Encrypt(dto.DBUsuario ?? "");
|
||||
config.DBClave = _encryptionService.Encrypt(dto.DBClave ?? "");
|
||||
config.SMTPUsuario = _encryptionService.Encrypt(dto.SMTPUsuario ?? "");
|
||||
config.SMTPClave = _encryptionService.Encrypt(dto.SMTPClave ?? "");
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
_logger.LogInformation("Configuración actualizada correctamente");
|
||||
|
||||
var evento = new Evento
|
||||
{
|
||||
Fecha = DateTime.Now,
|
||||
Mensaje = "Configuración del sistema actualizada",
|
||||
Tipo = "Info"
|
||||
};
|
||||
_context.Eventos.Add(evento);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Devolvemos el DTO tal cual vino (ya tiene los textos planos que el usuario ingresó)
|
||||
return Ok(dto);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al actualizar configuración");
|
||||
return StatusCode(500, new { mensaje = "Error al actualizar la configuración" });
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("probar-conexion-sql")]
|
||||
public async Task<ActionResult<object>> ProbarConexionSQL([FromBody] ProbarConexionDto dto)
|
||||
{
|
||||
try
|
||||
{
|
||||
var builder = new SqlConnectionStringBuilder
|
||||
{
|
||||
DataSource = dto.Servidor,
|
||||
InitialCatalog = dto.NombreDB,
|
||||
IntegratedSecurity = dto.TrustedConnection,
|
||||
TrustServerCertificate = true,
|
||||
ConnectTimeout = 10
|
||||
};
|
||||
|
||||
if (!dto.TrustedConnection)
|
||||
{
|
||||
// Aquí usamos los datos directos del DTO (texto plano) porque es una prueba en vivo
|
||||
builder.UserID = dto.Usuario;
|
||||
builder.Password = dto.Clave;
|
||||
}
|
||||
|
||||
using var conexion = new SqlConnection(builder.ConnectionString);
|
||||
await conexion.OpenAsync();
|
||||
|
||||
_logger.LogInformation("Prueba de conexión SQL exitosa a {servidor}/{database}",
|
||||
dto.Servidor, dto.NombreDB);
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
exito = true,
|
||||
mensaje = $"Conexión exitosa a {dto.Servidor}\\{dto.NombreDB}"
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex, "Fallo en prueba de conexión SQL");
|
||||
return Ok(new
|
||||
{
|
||||
exito = false,
|
||||
mensaje = $"Error: {ex.Message}"
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
[HttpPost("probar-smtp")]
|
||||
public async Task<ActionResult<object>> ProbarSMTP([FromBody] ProbarSMTPDto dto)
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
if (config == null)
|
||||
{
|
||||
return NotFound(new { mensaje = "No se encontró la configuración" });
|
||||
}
|
||||
|
||||
// Guardar estado original
|
||||
var smtpOriginal = (config.SMTPServidor, config.SMTPPuerto, config.SMTPUsuario,
|
||||
config.SMTPClave, config.SMTPSSL, config.AvisoMail);
|
||||
|
||||
try
|
||||
{
|
||||
// Configurar temporalmente para la prueba
|
||||
config.SMTPServidor = dto.Servidor;
|
||||
config.SMTPPuerto = dto.Puerto;
|
||||
config.SMTPSSL = dto.SSL;
|
||||
config.AvisoMail = true;
|
||||
|
||||
// IMPORTANTE: Encriptar también para la prueba, ya que MailService espera datos encriptados
|
||||
config.SMTPUsuario = _encryptionService.Encrypt(dto.Usuario);
|
||||
config.SMTPClave = _encryptionService.Encrypt(dto.Clave);
|
||||
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
var exito = await _mailService.EnviarCorreoAsync(
|
||||
dto.Destinatario,
|
||||
"Prueba de Configuración SMTP - Gestor Facturas",
|
||||
"<h2>✓ Prueba Exitosa</h2><p>La configuración SMTP está correcta y funcionando.</p>",
|
||||
true);
|
||||
|
||||
if (exito)
|
||||
{
|
||||
return Ok(new { exito = true, mensaje = "Correo de prueba enviado correctamente" });
|
||||
}
|
||||
else
|
||||
{
|
||||
return Ok(new { exito = false, mensaje = "No se pudo enviar el correo de prueba" });
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
// Restaurar configuración original
|
||||
config.SMTPServidor = smtpOriginal.SMTPServidor;
|
||||
config.SMTPPuerto = smtpOriginal.SMTPPuerto;
|
||||
config.SMTPUsuario = smtpOriginal.SMTPUsuario;
|
||||
config.SMTPClave = smtpOriginal.SMTPClave;
|
||||
config.SMTPSSL = smtpOriginal.SMTPSSL;
|
||||
config.AvisoMail = smtpOriginal.AvisoMail;
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error en prueba SMTP");
|
||||
return Ok(new { exito = false, mensaje = $"Error: {ex.Message}" });
|
||||
}
|
||||
}
|
||||
|
||||
private ConfiguracionDto MapearADto(Configuracion config)
|
||||
{
|
||||
return new ConfiguracionDto
|
||||
{
|
||||
Id = config.Id,
|
||||
Periodicidad = config.Periodicidad,
|
||||
ValorPeriodicidad = config.ValorPeriodicidad,
|
||||
HoraEjecucion = config.HoraEjecucion,
|
||||
UltimaEjecucion = config.UltimaEjecucion,
|
||||
Estado = config.Estado,
|
||||
EnEjecucion = config.EnEjecucion,
|
||||
DBServidor = config.DBServidor,
|
||||
DBNombre = config.DBNombre,
|
||||
// Nota: Usuario/Clave se mapean vacíos aquí y se llenan desencriptados en el método GET
|
||||
DBTrusted = config.DBTrusted,
|
||||
RutaFacturas = config.RutaFacturas,
|
||||
RutaDestino = config.RutaDestino,
|
||||
SMTPServidor = config.SMTPServidor,
|
||||
SMTPPuerto = config.SMTPPuerto,
|
||||
SMTPSSL = config.SMTPSSL,
|
||||
SMTPDestinatario = config.SMTPDestinatario,
|
||||
AvisoMail = config.AvisoMail
|
||||
};
|
||||
}
|
||||
|
||||
private DateTime CalcularFechaProxima(Configuracion config)
|
||||
{
|
||||
// Aunque el método que lo llama ya valida, el compilador necesita seguridad dentro de este bloque.
|
||||
if (!config.UltimaEjecucion.HasValue)
|
||||
{
|
||||
return DateTime.Now;
|
||||
}
|
||||
|
||||
var ultima = config.UltimaEjecucion.Value;
|
||||
DateTime proxima = ultima;
|
||||
|
||||
// Parsear hora configurada
|
||||
TimeSpan horaConfig;
|
||||
if (!TimeSpan.TryParse(config.HoraEjecucion, out horaConfig))
|
||||
{
|
||||
horaConfig = TimeSpan.Zero;
|
||||
}
|
||||
|
||||
switch (config.Periodicidad.ToUpper())
|
||||
{
|
||||
case "MINUTOS":
|
||||
proxima = ultima.AddMinutes(config.ValorPeriodicidad);
|
||||
break;
|
||||
case "DIAS":
|
||||
case "DÍAS":
|
||||
// Sumar días
|
||||
proxima = ultima.AddDays(config.ValorPeriodicidad);
|
||||
// Ajustar a la hora específica
|
||||
proxima = new DateTime(proxima.Year, proxima.Month, proxima.Day, horaConfig.Hours, horaConfig.Minutes, 0);
|
||||
|
||||
// Si al ajustar la hora, la fecha quedó en el pasado (ej: corrió tarde hoy), sumar un día más si es periodicidad diaria
|
||||
if (proxima < DateTime.Now && config.ValorPeriodicidad == 1)
|
||||
{
|
||||
proxima = proxima.AddDays(1);
|
||||
}
|
||||
break;
|
||||
case "MESES":
|
||||
proxima = ultima.AddMonths(config.ValorPeriodicidad);
|
||||
proxima = new DateTime(proxima.Year, proxima.Month, proxima.Day, horaConfig.Hours, horaConfig.Minutes, 0);
|
||||
break;
|
||||
}
|
||||
|
||||
// Si por alguna razón la próxima calculada es menor a ahora (retraso), la próxima es YA.
|
||||
if (proxima < DateTime.Now) return DateTime.Now;
|
||||
|
||||
return proxima;
|
||||
}
|
||||
}
|
||||
224
Backend/GestorFacturas.API/Controllers/OperacionesController.cs
Normal file
224
Backend/GestorFacturas.API/Controllers/OperacionesController.cs
Normal file
@@ -0,0 +1,224 @@
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using GestorFacturas.API.Data;
|
||||
using GestorFacturas.API.Models;
|
||||
using GestorFacturas.API.Models.DTOs;
|
||||
using GestorFacturas.API.Services.Interfaces;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
|
||||
namespace GestorFacturas.API.Controllers;
|
||||
|
||||
[ApiController]
|
||||
[Route("api/[controller]")]
|
||||
[Authorize]
|
||||
public class OperacionesController : ControllerBase
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly IServiceScopeFactory _scopeFactory;
|
||||
private readonly ILogger<OperacionesController> _logger;
|
||||
|
||||
public OperacionesController(
|
||||
ApplicationDbContext context,
|
||||
IServiceScopeFactory scopeFactory,
|
||||
ILogger<OperacionesController> logger)
|
||||
{
|
||||
_context = context;
|
||||
_scopeFactory = scopeFactory;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ejecuta el proceso de facturas manualmente sin esperar al cronograma
|
||||
/// </summary>
|
||||
[HttpPost("ejecutar-manual")]
|
||||
public async Task<ActionResult<object>> EjecutarManual([FromBody] EjecucionManualDto dto)
|
||||
{
|
||||
try
|
||||
{
|
||||
// Usamos _context acá solo para validar config rápida (esto es seguro porque es antes del OK)
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
if (config == null)
|
||||
{
|
||||
return NotFound(new { mensaje = "No se encontró la configuración del sistema" });
|
||||
}
|
||||
|
||||
_logger.LogInformation("Iniciando ejecución manual desde {fecha}", dto.FechaDesde);
|
||||
|
||||
// Registrar evento inicial
|
||||
var evento = new Evento
|
||||
{
|
||||
Fecha = DateTime.Now,
|
||||
Mensaje = $"Ejecución manual solicitada desde {dto.FechaDesde:dd/MM/yyyy}",
|
||||
Tipo = "Info"
|
||||
};
|
||||
_context.Eventos.Add(evento);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// Ejecutar el proceso en segundo plano (Fire-and-Forget SEGURO)
|
||||
_ = Task.Run(async () =>
|
||||
{
|
||||
// CRÍTICO: Creamos un nuevo Scope para que el DbContext viva
|
||||
// independientemente de la petición HTTP original.
|
||||
using var scope = _scopeFactory.CreateScope();
|
||||
|
||||
try
|
||||
{
|
||||
// Obtenemos el servicio DESDE el nuevo scope
|
||||
var procesadorService = scope.ServiceProvider.GetRequiredService<IProcesadorFacturasService>();
|
||||
|
||||
await procesadorService.EjecutarProcesoAsync(dto.FechaDesde);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Es importante loguear acá porque este hilo no tiene contexto HTTP
|
||||
var logger = scope.ServiceProvider.GetRequiredService<ILogger<OperacionesController>>();
|
||||
logger.LogError(ex, "Error crítico durante ejecución manual en background");
|
||||
}
|
||||
});
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
mensaje = "Proceso iniciado correctamente",
|
||||
fechaDesde = dto.FechaDesde
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al iniciar ejecución manual");
|
||||
return StatusCode(500, new { mensaje = "Error al iniciar el proceso" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Obtiene los eventos/logs del sistema con paginación
|
||||
/// </summary>
|
||||
[HttpGet("logs")]
|
||||
public async Task<ActionResult<PagedResult<EventoDto>>> ObtenerLogs(
|
||||
[FromQuery] int pageNumber = 1,
|
||||
[FromQuery] int pageSize = 20,
|
||||
[FromQuery] string? tipo = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
if (pageNumber < 1) pageNumber = 1;
|
||||
if (pageSize < 1 || pageSize > 100) pageSize = 20;
|
||||
|
||||
var query = _context.Eventos.AsQueryable();
|
||||
|
||||
// Filtrar por tipo si se especifica
|
||||
if (!string.IsNullOrEmpty(tipo))
|
||||
{
|
||||
query = query.Where(e => e.Tipo == tipo);
|
||||
}
|
||||
|
||||
// Ordenar por fecha descendente (más recientes primero)
|
||||
query = query.OrderByDescending(e => e.Fecha);
|
||||
|
||||
var totalCount = await query.CountAsync();
|
||||
|
||||
var eventos = await query
|
||||
.Skip((pageNumber - 1) * pageSize)
|
||||
.Take(pageSize)
|
||||
.Select(e => new EventoDto
|
||||
{
|
||||
Id = e.Id,
|
||||
Fecha = e.Fecha,
|
||||
Mensaje = e.Mensaje,
|
||||
Tipo = e.Tipo,
|
||||
Enviado = e.Enviado
|
||||
})
|
||||
.ToListAsync();
|
||||
|
||||
var result = new PagedResult<EventoDto>
|
||||
{
|
||||
Items = eventos,
|
||||
TotalCount = totalCount,
|
||||
PageNumber = pageNumber,
|
||||
PageSize = pageSize
|
||||
};
|
||||
|
||||
return Ok(result);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener logs");
|
||||
return StatusCode(500, new { mensaje = "Error al obtener los logs" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Obtiene estadísticas del día actual
|
||||
/// </summary>
|
||||
[HttpGet("estadisticas")]
|
||||
public async Task<ActionResult<object>> ObtenerEstadisticas()
|
||||
{
|
||||
try
|
||||
{
|
||||
var hoy = DateTime.Today;
|
||||
|
||||
var eventosHoy = await _context.Eventos
|
||||
.Where(e => e.Fecha >= hoy)
|
||||
.GroupBy(e => e.Tipo)
|
||||
.Select(g => new { Tipo = g.Key, Cantidad = g.Count() })
|
||||
.ToListAsync();
|
||||
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
ultimaEjecucion = config?.UltimaEjecucion,
|
||||
estado = config?.Estado ?? false,
|
||||
enEjecucion = config?.EnEjecucion ?? false,
|
||||
eventosHoy = new
|
||||
{
|
||||
total = eventosHoy.Sum(e => e.Cantidad),
|
||||
errores = eventosHoy.FirstOrDefault(e => e.Tipo == "Error")?.Cantidad ?? 0,
|
||||
advertencias = eventosHoy.FirstOrDefault(e => e.Tipo == "Warning")?.Cantidad ?? 0,
|
||||
info = eventosHoy.FirstOrDefault(e => e.Tipo == "Info")?.Cantidad ?? 0
|
||||
}
|
||||
});
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al obtener estadísticas");
|
||||
return StatusCode(500, new { mensaje = "Error al obtener estadísticas" });
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Limpia los logs antiguos (opcional)
|
||||
/// </summary>
|
||||
[HttpDelete("logs/limpiar")]
|
||||
public async Task<ActionResult<object>> LimpiarLogsAntiguos([FromQuery] int diasAntiguedad = 30)
|
||||
{
|
||||
try
|
||||
{
|
||||
var fechaLimite = DateTime.Now.AddDays(-diasAntiguedad);
|
||||
|
||||
var eventosAntiguos = await _context.Eventos
|
||||
.Where(e => e.Fecha < fechaLimite)
|
||||
.ToListAsync();
|
||||
|
||||
if (eventosAntiguos.Count > 0)
|
||||
{
|
||||
_context.Eventos.RemoveRange(eventosAntiguos);
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
_logger.LogInformation("Se eliminaron {count} eventos antiguos", eventosAntiguos.Count);
|
||||
|
||||
return Ok(new
|
||||
{
|
||||
mensaje = $"Se eliminaron {eventosAntiguos.Count} eventos",
|
||||
cantidad = eventosAntiguos.Count
|
||||
});
|
||||
}
|
||||
|
||||
return Ok(new { mensaje = "No hay eventos antiguos para eliminar", cantidad = 0 });
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al limpiar logs antiguos");
|
||||
return StatusCode(500, new { mensaje = "Error al limpiar los logs" });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user