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" });
|
||||
}
|
||||
}
|
||||
}
|
||||
66
Backend/GestorFacturas.API/Data/ApplicationDbContext.cs
Normal file
66
Backend/GestorFacturas.API/Data/ApplicationDbContext.cs
Normal file
@@ -0,0 +1,66 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using GestorFacturas.API.Models;
|
||||
namespace GestorFacturas.API.Data;
|
||||
|
||||
public class ApplicationDbContext : DbContext
|
||||
{
|
||||
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
|
||||
: base(options)
|
||||
{
|
||||
}
|
||||
public DbSet<Configuracion> Configuraciones { get; set; }
|
||||
public DbSet<Evento> Eventos { get; set; }
|
||||
public DbSet<Usuario> Usuarios { get; set; }
|
||||
public DbSet<RefreshToken> RefreshTokens { get; set; }
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
base.OnModelCreating(modelBuilder);
|
||||
|
||||
modelBuilder.Entity<Configuracion>(entity =>
|
||||
{
|
||||
entity.ToTable("Configuraciones");
|
||||
entity.HasData(new Configuracion
|
||||
{
|
||||
Id = 1,
|
||||
Periodicidad = "Dias",
|
||||
ValorPeriodicidad = 1,
|
||||
HoraEjecucion = "00:00:00",
|
||||
Estado = true,
|
||||
EnEjecucion = false,
|
||||
DBServidor = "TECNICA3",
|
||||
DBNombre = "",
|
||||
DBTrusted = true,
|
||||
RutaFacturas = "",
|
||||
RutaDestino = "",
|
||||
SMTPPuerto = 587,
|
||||
SMTPSSL = true,
|
||||
AvisoMail = false
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity<Evento>(entity =>
|
||||
{
|
||||
entity.ToTable("Eventos");
|
||||
entity.HasIndex(e => e.Fecha);
|
||||
entity.HasIndex(e => e.Tipo);
|
||||
});
|
||||
|
||||
// Seed de Usuario Admin
|
||||
// Pass: admin123
|
||||
modelBuilder.Entity<Usuario>().HasData(new Usuario
|
||||
{
|
||||
Id = 1,
|
||||
Username = "admin",
|
||||
Nombre = "Administrador",
|
||||
PasswordHash = "$2a$11$l5UnZIE8bVWSUhYorVqlW.f0qgvK2zsD8aYDyTRXKjtFwwdiAfAvW" // Hash placeholder, se actualiza al loguear si es necesario o usar uno real
|
||||
});
|
||||
|
||||
// Configuración de RefreshToken (Opcional si usas convenciones, pero bueno para ser explícito)
|
||||
modelBuilder.Entity<Usuario>()
|
||||
.HasMany<RefreshToken>()
|
||||
.WithOne(r => r.Usuario)
|
||||
.HasForeignKey(r => r.UsuarioId)
|
||||
.OnDelete(DeleteBehavior.Cascade);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Design;
|
||||
|
||||
namespace GestorFacturas.API.Data;
|
||||
|
||||
public class ApplicationDbContextFactory : IDesignTimeDbContextFactory<ApplicationDbContext>
|
||||
{
|
||||
public ApplicationDbContext CreateDbContext(string[] args)
|
||||
{
|
||||
var optionsBuilder = new DbContextOptionsBuilder<ApplicationDbContext>();
|
||||
|
||||
optionsBuilder.UseSqlServer("Server=TECNICA3;Database=AdminFacturasApp;User Id=gestorFacturasApi;Password=Diagonal423;TrustServerCertificate=True;");
|
||||
|
||||
return new ApplicationDbContext(optionsBuilder.Options);
|
||||
}
|
||||
}
|
||||
33
Backend/GestorFacturas.API/Dockerfile
Normal file
33
Backend/GestorFacturas.API/Dockerfile
Normal file
@@ -0,0 +1,33 @@
|
||||
# Etapa de compilación
|
||||
FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build
|
||||
WORKDIR /src
|
||||
|
||||
# Copiar csproj y restaurar dependencias
|
||||
COPY ["GestorFacturas.API.csproj", "./"]
|
||||
RUN dotnet restore "GestorFacturas.API.csproj"
|
||||
|
||||
# Copiar todo el código y compilar
|
||||
COPY . .
|
||||
RUN dotnet publish "GestorFacturas.API.csproj" -c Release -o /app/publish
|
||||
|
||||
# Etapa final (Runtime)
|
||||
FROM mcr.microsoft.com/dotnet/aspnet:10.0
|
||||
WORKDIR /app
|
||||
COPY --from=build /app/publish .
|
||||
|
||||
# Instalar tzdata para tener las definiciones de zona horaria
|
||||
USER root
|
||||
RUN apt-get update && \
|
||||
apt-get install -y tzdata && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Configurar zona horaria
|
||||
ENV TZ=America/Buenos_Aires
|
||||
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
|
||||
# -----------------------
|
||||
|
||||
# Crear directorios
|
||||
RUN mkdir -p /app/data/origen && mkdir -p /app/data/destino
|
||||
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["dotnet", "GestorFacturas.API.dll"]
|
||||
27
Backend/GestorFacturas.API/GestorFacturas.API.csproj
Normal file
27
Backend/GestorFacturas.API/GestorFacturas.API.csproj
Normal file
@@ -0,0 +1,27 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<Nullable>enable</Nullable>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<UserSecretsId>c46298eb-1188-434a-a5ff-accd7e3e25e9</UserSecretsId>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="BCrypt.Net-Next" Version="4.0.3" />
|
||||
<PackageReference Include="FluentValidation.AspNetCore" Version="11.3.1" />
|
||||
<PackageReference Include="MailKit" Version="4.14.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.1" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.1" />
|
||||
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.1">
|
||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||
<PrivateAssets>all</PrivateAssets>
|
||||
</PackageReference>
|
||||
<PackageReference Include="Serilog.AspNetCore" Version="10.0.0" />
|
||||
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
|
||||
<PackageReference Include="Serilog.Sinks.MSSqlServer" Version="9.0.2" />
|
||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="10.0.1" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
6
Backend/GestorFacturas.API/GestorFacturas.API.http
Normal file
6
Backend/GestorFacturas.API/GestorFacturas.API.http
Normal file
@@ -0,0 +1,6 @@
|
||||
@GestorFacturas.API_HostAddress = http://localhost:5036
|
||||
|
||||
GET {{GestorFacturas.API_HostAddress}}/weatherforecast/
|
||||
Accept: application/json
|
||||
|
||||
###
|
||||
172
Backend/GestorFacturas.API/Migrations/20251210145015_InitialCreate.Designer.cs
generated
Normal file
172
Backend/GestorFacturas.API/Migrations/20251210145015_InitialCreate.Designer.cs
generated
Normal file
@@ -0,0 +1,172 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using GestorFacturas.API.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20251210145015_InitialCreate")]
|
||||
partial class InitialCreate
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.1")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Configuracion", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("AvisoMail")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBClave")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("DBNombre")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<string>("DBServidor")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<bool>("DBTrusted")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBUsuario")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<bool>("EnEjecucion")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<bool>("Estado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("HoraEjecucion")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("nvarchar(10)");
|
||||
|
||||
b.Property<string>("Periodicidad")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.Property<string>("RutaDestino")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("RutaFacturas")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("SMTPClave")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPDestinatario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<int>("SMTPPuerto")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<bool>("SMTPSSL")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("SMTPServidor")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPUsuario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<DateTime?>("UltimaEjecucion")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<int>("ValorPeriodicidad")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Configuraciones", (string)null);
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvisoMail = false,
|
||||
DBNombre = "",
|
||||
DBServidor = "TECNICA3",
|
||||
DBTrusted = true,
|
||||
EnEjecucion = false,
|
||||
Estado = true,
|
||||
HoraEjecucion = "00:00:00",
|
||||
Periodicidad = "Dias",
|
||||
RutaDestino = "",
|
||||
RutaFacturas = "",
|
||||
SMTPPuerto = 587,
|
||||
SMTPSSL = true,
|
||||
ValorPeriodicidad = 1
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Evento", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("Enviado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTime>("Fecha")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Mensaje")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Tipo")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Fecha");
|
||||
|
||||
b.HasIndex("Tipo");
|
||||
|
||||
b.ToTable("Eventos", (string)null);
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class InitialCreate : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Configuraciones",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("SqlServer:Identity", "1, 1"),
|
||||
Periodicidad = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: false),
|
||||
ValorPeriodicidad = table.Column<int>(type: "int", nullable: false),
|
||||
HoraEjecucion = table.Column<string>(type: "nvarchar(10)", maxLength: 10, nullable: false),
|
||||
UltimaEjecucion = table.Column<DateTime>(type: "datetime2", nullable: true),
|
||||
Estado = table.Column<bool>(type: "bit", nullable: false),
|
||||
EnEjecucion = table.Column<bool>(type: "bit", nullable: false),
|
||||
DBServidor = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: false),
|
||||
DBNombre = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: false),
|
||||
DBUsuario = table.Column<string>(type: "nvarchar(100)", maxLength: 100, nullable: true),
|
||||
DBClave = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true),
|
||||
DBTrusted = table.Column<bool>(type: "bit", nullable: false),
|
||||
RutaFacturas = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: false),
|
||||
RutaDestino = table.Column<string>(type: "nvarchar(500)", maxLength: 500, nullable: false),
|
||||
SMTPServidor = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true),
|
||||
SMTPPuerto = table.Column<int>(type: "int", nullable: false),
|
||||
SMTPUsuario = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true),
|
||||
SMTPClave = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true),
|
||||
SMTPSSL = table.Column<bool>(type: "bit", nullable: false),
|
||||
SMTPDestinatario = table.Column<string>(type: "nvarchar(200)", maxLength: 200, nullable: true),
|
||||
AvisoMail = table.Column<bool>(type: "bit", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Configuraciones", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Eventos",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("SqlServer:Identity", "1, 1"),
|
||||
Fecha = table.Column<DateTime>(type: "datetime2", nullable: false),
|
||||
Mensaje = table.Column<string>(type: "nvarchar(max)", nullable: false),
|
||||
Tipo = table.Column<string>(type: "nvarchar(20)", maxLength: 20, nullable: false),
|
||||
Enviado = table.Column<bool>(type: "bit", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Eventos", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "Configuraciones",
|
||||
columns: new[] { "Id", "AvisoMail", "DBClave", "DBNombre", "DBServidor", "DBTrusted", "DBUsuario", "EnEjecucion", "Estado", "HoraEjecucion", "Periodicidad", "RutaDestino", "RutaFacturas", "SMTPClave", "SMTPDestinatario", "SMTPPuerto", "SMTPSSL", "SMTPServidor", "SMTPUsuario", "UltimaEjecucion", "ValorPeriodicidad" },
|
||||
values: new object[] { 1, false, null, "", "TECNICA3", true, null, false, true, "00:00:00", "Dias", "", "", null, null, 587, true, null, null, null, 1 });
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Eventos_Fecha",
|
||||
table: "Eventos",
|
||||
column: "Fecha");
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_Eventos_Tipo",
|
||||
table: "Eventos",
|
||||
column: "Tipo");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Configuraciones");
|
||||
|
||||
migrationBuilder.DropTable(
|
||||
name: "Eventos");
|
||||
}
|
||||
}
|
||||
}
|
||||
207
Backend/GestorFacturas.API/Migrations/20251210155728_AgregaAutenticacion.Designer.cs
generated
Normal file
207
Backend/GestorFacturas.API/Migrations/20251210155728_AgregaAutenticacion.Designer.cs
generated
Normal file
@@ -0,0 +1,207 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using GestorFacturas.API.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20251210155728_AgregaAutenticacion")]
|
||||
partial class AgregaAutenticacion
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.1")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Configuracion", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("AvisoMail")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBClave")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("DBNombre")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<string>("DBServidor")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<bool>("DBTrusted")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBUsuario")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<bool>("EnEjecucion")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<bool>("Estado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("HoraEjecucion")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("nvarchar(10)");
|
||||
|
||||
b.Property<string>("Periodicidad")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.Property<string>("RutaDestino")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("RutaFacturas")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("SMTPClave")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPDestinatario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<int>("SMTPPuerto")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<bool>("SMTPSSL")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("SMTPServidor")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPUsuario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<DateTime?>("UltimaEjecucion")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<int>("ValorPeriodicidad")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Configuraciones", (string)null);
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvisoMail = false,
|
||||
DBNombre = "",
|
||||
DBServidor = "TECNICA3",
|
||||
DBTrusted = true,
|
||||
EnEjecucion = false,
|
||||
Estado = true,
|
||||
HoraEjecucion = "00:00:00",
|
||||
Periodicidad = "Dias",
|
||||
RutaDestino = "",
|
||||
RutaFacturas = "",
|
||||
SMTPPuerto = 587,
|
||||
SMTPSSL = true,
|
||||
ValorPeriodicidad = 1
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Evento", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("Enviado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTime>("Fecha")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Mensaje")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Tipo")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Fecha");
|
||||
|
||||
b.HasIndex("Tipo");
|
||||
|
||||
b.ToTable("Eventos", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("Usuario", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Nombre")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("nvarchar(50)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Usuarios");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Nombre = "Administrador",
|
||||
PasswordHash = "$2a$11$Z5.Cg.y.u.e.t.c.h.a.n.g.e.m.e",
|
||||
Username = "admin"
|
||||
});
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AgregaAutenticacion : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "Usuarios",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("SqlServer:Identity", "1, 1"),
|
||||
Username = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: false),
|
||||
PasswordHash = table.Column<string>(type: "nvarchar(max)", nullable: false),
|
||||
Nombre = table.Column<string>(type: "nvarchar(max)", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_Usuarios", x => x.Id);
|
||||
});
|
||||
|
||||
migrationBuilder.InsertData(
|
||||
table: "Usuarios",
|
||||
columns: new[] { "Id", "Nombre", "PasswordHash", "Username" },
|
||||
values: new object[] { 1, "Administrador", "$2a$11$Z5.Cg.y.u.e.t.c.h.a.n.g.e.m.e", "admin" });
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "Usuarios");
|
||||
}
|
||||
}
|
||||
}
|
||||
207
Backend/GestorFacturas.API/Migrations/20251210164013_UpdateAdminPassword.Designer.cs
generated
Normal file
207
Backend/GestorFacturas.API/Migrations/20251210164013_UpdateAdminPassword.Designer.cs
generated
Normal file
@@ -0,0 +1,207 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using GestorFacturas.API.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20251210164013_UpdateAdminPassword")]
|
||||
partial class UpdateAdminPassword
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.1")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Configuracion", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("AvisoMail")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBClave")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("DBNombre")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<string>("DBServidor")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<bool>("DBTrusted")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBUsuario")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<bool>("EnEjecucion")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<bool>("Estado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("HoraEjecucion")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("nvarchar(10)");
|
||||
|
||||
b.Property<string>("Periodicidad")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.Property<string>("RutaDestino")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("RutaFacturas")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("SMTPClave")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPDestinatario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<int>("SMTPPuerto")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<bool>("SMTPSSL")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("SMTPServidor")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPUsuario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<DateTime?>("UltimaEjecucion")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<int>("ValorPeriodicidad")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Configuraciones", (string)null);
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvisoMail = false,
|
||||
DBNombre = "",
|
||||
DBServidor = "TECNICA3",
|
||||
DBTrusted = true,
|
||||
EnEjecucion = false,
|
||||
Estado = true,
|
||||
HoraEjecucion = "00:00:00",
|
||||
Periodicidad = "Dias",
|
||||
RutaDestino = "",
|
||||
RutaFacturas = "",
|
||||
SMTPPuerto = 587,
|
||||
SMTPSSL = true,
|
||||
ValorPeriodicidad = 1
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Evento", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("Enviado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTime>("Fecha")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Mensaje")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Tipo")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Fecha");
|
||||
|
||||
b.HasIndex("Tipo");
|
||||
|
||||
b.ToTable("Eventos", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Usuario", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Nombre")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("nvarchar(50)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Usuarios");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Nombre = "Administrador",
|
||||
PasswordHash = "$2a$11$l5UnZIE8bVWSUhYorVqlW.f0qgvK2zsD8aYDyTRXKjtFwwdiAfAvW",
|
||||
Username = "admin"
|
||||
});
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class UpdateAdminPassword : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Usuarios",
|
||||
keyColumn: "Id",
|
||||
keyValue: 1,
|
||||
column: "PasswordHash",
|
||||
value: "$2a$11$l5UnZIE8bVWSUhYorVqlW.f0qgvK2zsD8aYDyTRXKjtFwwdiAfAvW");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.UpdateData(
|
||||
table: "Usuarios",
|
||||
keyColumn: "Id",
|
||||
keyValue: 1,
|
||||
column: "PasswordHash",
|
||||
value: "$2a$11$Z5.Cg.y.u.e.t.c.h.a.n.g.e.m.e");
|
||||
}
|
||||
}
|
||||
}
|
||||
249
Backend/GestorFacturas.API/Migrations/20251210171018_AddRefreshTokens.Designer.cs
generated
Normal file
249
Backend/GestorFacturas.API/Migrations/20251210171018_AddRefreshTokens.Designer.cs
generated
Normal file
@@ -0,0 +1,249 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using GestorFacturas.API.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20251210171018_AddRefreshTokens")]
|
||||
partial class AddRefreshTokens
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.1")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Configuracion", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("AvisoMail")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBClave")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("DBNombre")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<string>("DBServidor")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<bool>("DBTrusted")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBUsuario")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<bool>("EnEjecucion")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<bool>("Estado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("HoraEjecucion")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("nvarchar(10)");
|
||||
|
||||
b.Property<string>("Periodicidad")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.Property<string>("RutaDestino")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("RutaFacturas")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("SMTPClave")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPDestinatario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<int>("SMTPPuerto")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<bool>("SMTPSSL")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("SMTPServidor")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPUsuario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<DateTime?>("UltimaEjecucion")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<int>("ValorPeriodicidad")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Configuraciones", (string)null);
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvisoMail = false,
|
||||
DBNombre = "",
|
||||
DBServidor = "TECNICA3",
|
||||
DBTrusted = true,
|
||||
EnEjecucion = false,
|
||||
Estado = true,
|
||||
HoraEjecucion = "00:00:00",
|
||||
Periodicidad = "Dias",
|
||||
RutaDestino = "",
|
||||
RutaFacturas = "",
|
||||
SMTPPuerto = 587,
|
||||
SMTPSSL = true,
|
||||
ValorPeriodicidad = 1
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Evento", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("Enviado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTime>("Fecha")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Mensaje")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Tipo")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Fecha");
|
||||
|
||||
b.HasIndex("Tipo");
|
||||
|
||||
b.ToTable("Eventos", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.RefreshToken", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<DateTime>("Created")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<DateTime>("Expires")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<DateTime?>("Revoked")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<int>("UsuarioId")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UsuarioId");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Usuario", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Nombre")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("nvarchar(50)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Usuarios");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Nombre = "Administrador",
|
||||
PasswordHash = "$2a$11$l5UnZIE8bVWSUhYorVqlW.f0qgvK2zsD8aYDyTRXKjtFwwdiAfAvW",
|
||||
Username = "admin"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("GestorFacturas.API.Models.Usuario", "Usuario")
|
||||
.WithMany()
|
||||
.HasForeignKey("UsuarioId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Usuario");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
using System;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddRefreshTokens : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.CreateTable(
|
||||
name: "RefreshTokens",
|
||||
columns: table => new
|
||||
{
|
||||
Id = table.Column<int>(type: "int", nullable: false)
|
||||
.Annotation("SqlServer:Identity", "1, 1"),
|
||||
Token = table.Column<string>(type: "nvarchar(max)", nullable: false),
|
||||
Expires = table.Column<DateTime>(type: "datetime2", nullable: false),
|
||||
Created = table.Column<DateTime>(type: "datetime2", nullable: false),
|
||||
Revoked = table.Column<DateTime>(type: "datetime2", nullable: true),
|
||||
UsuarioId = table.Column<int>(type: "int", nullable: false)
|
||||
},
|
||||
constraints: table =>
|
||||
{
|
||||
table.PrimaryKey("PK_RefreshTokens", x => x.Id);
|
||||
table.ForeignKey(
|
||||
name: "FK_RefreshTokens_Usuarios_UsuarioId",
|
||||
column: x => x.UsuarioId,
|
||||
principalTable: "Usuarios",
|
||||
principalColumn: "Id",
|
||||
onDelete: ReferentialAction.Cascade);
|
||||
});
|
||||
|
||||
migrationBuilder.CreateIndex(
|
||||
name: "IX_RefreshTokens_UsuarioId",
|
||||
table: "RefreshTokens",
|
||||
column: "UsuarioId");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropTable(
|
||||
name: "RefreshTokens");
|
||||
}
|
||||
}
|
||||
}
|
||||
252
Backend/GestorFacturas.API/Migrations/20251210174020_AddIsPersistentToRefreshToken.Designer.cs
generated
Normal file
252
Backend/GestorFacturas.API/Migrations/20251210174020_AddIsPersistentToRefreshToken.Designer.cs
generated
Normal file
@@ -0,0 +1,252 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using GestorFacturas.API.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20251210174020_AddIsPersistentToRefreshToken")]
|
||||
partial class AddIsPersistentToRefreshToken
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.1")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Configuracion", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("AvisoMail")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBClave")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("DBNombre")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<string>("DBServidor")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<bool>("DBTrusted")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBUsuario")
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<bool>("EnEjecucion")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<bool>("Estado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("HoraEjecucion")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("nvarchar(10)");
|
||||
|
||||
b.Property<string>("Periodicidad")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.Property<string>("RutaDestino")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("RutaFacturas")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("SMTPClave")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPDestinatario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<int>("SMTPPuerto")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<bool>("SMTPSSL")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("SMTPServidor")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPUsuario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<DateTime?>("UltimaEjecucion")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<int>("ValorPeriodicidad")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Configuraciones", (string)null);
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvisoMail = false,
|
||||
DBNombre = "",
|
||||
DBServidor = "TECNICA3",
|
||||
DBTrusted = true,
|
||||
EnEjecucion = false,
|
||||
Estado = true,
|
||||
HoraEjecucion = "00:00:00",
|
||||
Periodicidad = "Dias",
|
||||
RutaDestino = "",
|
||||
RutaFacturas = "",
|
||||
SMTPPuerto = 587,
|
||||
SMTPSSL = true,
|
||||
ValorPeriodicidad = 1
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Evento", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("Enviado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTime>("Fecha")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Mensaje")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Tipo")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Fecha");
|
||||
|
||||
b.HasIndex("Tipo");
|
||||
|
||||
b.ToTable("Eventos", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.RefreshToken", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<DateTime>("Created")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<DateTime>("Expires")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<bool>("IsPersistent")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTime?>("Revoked")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<int>("UsuarioId")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UsuarioId");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Usuario", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Nombre")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("nvarchar(50)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Usuarios");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Nombre = "Administrador",
|
||||
PasswordHash = "$2a$11$l5UnZIE8bVWSUhYorVqlW.f0qgvK2zsD8aYDyTRXKjtFwwdiAfAvW",
|
||||
Username = "admin"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("GestorFacturas.API.Models.Usuario", "Usuario")
|
||||
.WithMany()
|
||||
.HasForeignKey("UsuarioId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Usuario");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class AddIsPersistentToRefreshToken : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AddColumn<bool>(
|
||||
name: "IsPersistent",
|
||||
table: "RefreshTokens",
|
||||
type: "bit",
|
||||
nullable: false,
|
||||
defaultValue: false);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.DropColumn(
|
||||
name: "IsPersistent",
|
||||
table: "RefreshTokens");
|
||||
}
|
||||
}
|
||||
}
|
||||
252
Backend/GestorFacturas.API/Migrations/20251211135755_IncreaseConfigColumnsSize.Designer.cs
generated
Normal file
252
Backend/GestorFacturas.API/Migrations/20251211135755_IncreaseConfigColumnsSize.Designer.cs
generated
Normal file
@@ -0,0 +1,252 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using GestorFacturas.API.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
[Migration("20251211135755_IncreaseConfigColumnsSize")]
|
||||
partial class IncreaseConfigColumnsSize
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void BuildTargetModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.1")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Configuracion", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("AvisoMail")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBClave")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("DBNombre")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<string>("DBServidor")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<bool>("DBTrusted")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBUsuario")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<bool>("EnEjecucion")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<bool>("Estado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("HoraEjecucion")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("nvarchar(10)");
|
||||
|
||||
b.Property<string>("Periodicidad")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.Property<string>("RutaDestino")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("RutaFacturas")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("SMTPClave")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("SMTPDestinatario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<int>("SMTPPuerto")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<bool>("SMTPSSL")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("SMTPServidor")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPUsuario")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<DateTime?>("UltimaEjecucion")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<int>("ValorPeriodicidad")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Configuraciones", (string)null);
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvisoMail = false,
|
||||
DBNombre = "",
|
||||
DBServidor = "TECNICA3",
|
||||
DBTrusted = true,
|
||||
EnEjecucion = false,
|
||||
Estado = true,
|
||||
HoraEjecucion = "00:00:00",
|
||||
Periodicidad = "Dias",
|
||||
RutaDestino = "",
|
||||
RutaFacturas = "",
|
||||
SMTPPuerto = 587,
|
||||
SMTPSSL = true,
|
||||
ValorPeriodicidad = 1
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Evento", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("Enviado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTime>("Fecha")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Mensaje")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Tipo")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Fecha");
|
||||
|
||||
b.HasIndex("Tipo");
|
||||
|
||||
b.ToTable("Eventos", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.RefreshToken", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<DateTime>("Created")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<DateTime>("Expires")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<bool>("IsPersistent")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTime?>("Revoked")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<int>("UsuarioId")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UsuarioId");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Usuario", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Nombre")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("nvarchar(50)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Usuarios");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Nombre = "Administrador",
|
||||
PasswordHash = "$2a$11$l5UnZIE8bVWSUhYorVqlW.f0qgvK2zsD8aYDyTRXKjtFwwdiAfAvW",
|
||||
Username = "admin"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("GestorFacturas.API.Models.Usuario", "Usuario")
|
||||
.WithMany()
|
||||
.HasForeignKey("UsuarioId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Usuario");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
using Microsoft.EntityFrameworkCore.Migrations;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public partial class IncreaseConfigColumnsSize : Migration
|
||||
{
|
||||
/// <inheritdoc />
|
||||
protected override void Up(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "SMTPUsuario",
|
||||
table: "Configuraciones",
|
||||
type: "nvarchar(500)",
|
||||
maxLength: 500,
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "nvarchar(200)",
|
||||
oldMaxLength: 200,
|
||||
oldNullable: true);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "SMTPClave",
|
||||
table: "Configuraciones",
|
||||
type: "nvarchar(500)",
|
||||
maxLength: 500,
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "nvarchar(200)",
|
||||
oldMaxLength: 200,
|
||||
oldNullable: true);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "DBUsuario",
|
||||
table: "Configuraciones",
|
||||
type: "nvarchar(500)",
|
||||
maxLength: 500,
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "nvarchar(100)",
|
||||
oldMaxLength: 100,
|
||||
oldNullable: true);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "DBClave",
|
||||
table: "Configuraciones",
|
||||
type: "nvarchar(500)",
|
||||
maxLength: 500,
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "nvarchar(200)",
|
||||
oldMaxLength: 200,
|
||||
oldNullable: true);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void Down(MigrationBuilder migrationBuilder)
|
||||
{
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "SMTPUsuario",
|
||||
table: "Configuraciones",
|
||||
type: "nvarchar(200)",
|
||||
maxLength: 200,
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "nvarchar(500)",
|
||||
oldMaxLength: 500,
|
||||
oldNullable: true);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "SMTPClave",
|
||||
table: "Configuraciones",
|
||||
type: "nvarchar(200)",
|
||||
maxLength: 200,
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "nvarchar(500)",
|
||||
oldMaxLength: 500,
|
||||
oldNullable: true);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "DBUsuario",
|
||||
table: "Configuraciones",
|
||||
type: "nvarchar(100)",
|
||||
maxLength: 100,
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "nvarchar(500)",
|
||||
oldMaxLength: 500,
|
||||
oldNullable: true);
|
||||
|
||||
migrationBuilder.AlterColumn<string>(
|
||||
name: "DBClave",
|
||||
table: "Configuraciones",
|
||||
type: "nvarchar(200)",
|
||||
maxLength: 200,
|
||||
nullable: true,
|
||||
oldClrType: typeof(string),
|
||||
oldType: "nvarchar(500)",
|
||||
oldMaxLength: 500,
|
||||
oldNullable: true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
// <auto-generated />
|
||||
using System;
|
||||
using GestorFacturas.API.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using Microsoft.EntityFrameworkCore.Metadata;
|
||||
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
|
||||
|
||||
#nullable disable
|
||||
|
||||
namespace GestorFacturas.API.Migrations
|
||||
{
|
||||
[DbContext(typeof(ApplicationDbContext))]
|
||||
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
|
||||
{
|
||||
protected override void BuildModel(ModelBuilder modelBuilder)
|
||||
{
|
||||
#pragma warning disable 612, 618
|
||||
modelBuilder
|
||||
.HasAnnotation("ProductVersion", "10.0.1")
|
||||
.HasAnnotation("Relational:MaxIdentifierLength", 128);
|
||||
|
||||
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Configuracion", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("AvisoMail")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBClave")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("DBNombre")
|
||||
.IsRequired()
|
||||
.HasMaxLength(100)
|
||||
.HasColumnType("nvarchar(100)");
|
||||
|
||||
b.Property<string>("DBServidor")
|
||||
.IsRequired()
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<bool>("DBTrusted")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("DBUsuario")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<bool>("EnEjecucion")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<bool>("Estado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("HoraEjecucion")
|
||||
.IsRequired()
|
||||
.HasMaxLength(10)
|
||||
.HasColumnType("nvarchar(10)");
|
||||
|
||||
b.Property<string>("Periodicidad")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.Property<string>("RutaDestino")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("RutaFacturas")
|
||||
.IsRequired()
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("SMTPClave")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<string>("SMTPDestinatario")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<int>("SMTPPuerto")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.Property<bool>("SMTPSSL")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<string>("SMTPServidor")
|
||||
.HasMaxLength(200)
|
||||
.HasColumnType("nvarchar(200)");
|
||||
|
||||
b.Property<string>("SMTPUsuario")
|
||||
.HasMaxLength(500)
|
||||
.HasColumnType("nvarchar(500)");
|
||||
|
||||
b.Property<DateTime?>("UltimaEjecucion")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<int>("ValorPeriodicidad")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Configuraciones", (string)null);
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
AvisoMail = false,
|
||||
DBNombre = "",
|
||||
DBServidor = "TECNICA3",
|
||||
DBTrusted = true,
|
||||
EnEjecucion = false,
|
||||
Estado = true,
|
||||
HoraEjecucion = "00:00:00",
|
||||
Periodicidad = "Dias",
|
||||
RutaDestino = "",
|
||||
RutaFacturas = "",
|
||||
SMTPPuerto = 587,
|
||||
SMTPSSL = true,
|
||||
ValorPeriodicidad = 1
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Evento", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<bool>("Enviado")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTime>("Fecha")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Mensaje")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Tipo")
|
||||
.IsRequired()
|
||||
.HasMaxLength(20)
|
||||
.HasColumnType("nvarchar(20)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("Fecha");
|
||||
|
||||
b.HasIndex("Tipo");
|
||||
|
||||
b.ToTable("Eventos", (string)null);
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.RefreshToken", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<DateTime>("Created")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<DateTime>("Expires")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<bool>("IsPersistent")
|
||||
.HasColumnType("bit");
|
||||
|
||||
b.Property<DateTime?>("Revoked")
|
||||
.HasColumnType("datetime2");
|
||||
|
||||
b.Property<string>("Token")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<int>("UsuarioId")
|
||||
.HasColumnType("int");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.HasIndex("UsuarioId");
|
||||
|
||||
b.ToTable("RefreshTokens");
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.Usuario", b =>
|
||||
{
|
||||
b.Property<int>("Id")
|
||||
.ValueGeneratedOnAdd()
|
||||
.HasColumnType("int");
|
||||
|
||||
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
|
||||
|
||||
b.Property<string>("Nombre")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("PasswordHash")
|
||||
.IsRequired()
|
||||
.HasColumnType("nvarchar(max)");
|
||||
|
||||
b.Property<string>("Username")
|
||||
.IsRequired()
|
||||
.HasMaxLength(50)
|
||||
.HasColumnType("nvarchar(50)");
|
||||
|
||||
b.HasKey("Id");
|
||||
|
||||
b.ToTable("Usuarios");
|
||||
|
||||
b.HasData(
|
||||
new
|
||||
{
|
||||
Id = 1,
|
||||
Nombre = "Administrador",
|
||||
PasswordHash = "$2a$11$l5UnZIE8bVWSUhYorVqlW.f0qgvK2zsD8aYDyTRXKjtFwwdiAfAvW",
|
||||
Username = "admin"
|
||||
});
|
||||
});
|
||||
|
||||
modelBuilder.Entity("GestorFacturas.API.Models.RefreshToken", b =>
|
||||
{
|
||||
b.HasOne("GestorFacturas.API.Models.Usuario", "Usuario")
|
||||
.WithMany()
|
||||
.HasForeignKey("UsuarioId")
|
||||
.OnDelete(DeleteBehavior.Cascade)
|
||||
.IsRequired();
|
||||
|
||||
b.Navigation("Usuario");
|
||||
});
|
||||
#pragma warning restore 612, 618
|
||||
}
|
||||
}
|
||||
}
|
||||
138
Backend/GestorFacturas.API/Models/Configuracion.cs
Normal file
138
Backend/GestorFacturas.API/Models/Configuracion.cs
Normal file
@@ -0,0 +1,138 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace GestorFacturas.API.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Entidad que almacena la configuración completa del sistema.
|
||||
/// Solo existe un registro (ID=1) para toda la aplicación.
|
||||
/// </summary>
|
||||
public class Configuracion
|
||||
{
|
||||
[Key]
|
||||
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
|
||||
// ===== CONFIGURACIÓN DE PERIODICIDAD =====
|
||||
/// <summary>
|
||||
/// Tipo de periodicidad: "Minutos", "Dias", "Meses"
|
||||
/// </summary>
|
||||
[Required]
|
||||
[MaxLength(20)]
|
||||
public string Periodicidad { get; set; } = "Dias";
|
||||
|
||||
/// <summary>
|
||||
/// Valor numérico de la periodicidad (ej: 1, 5, 30)
|
||||
/// </summary>
|
||||
[Required]
|
||||
public int ValorPeriodicidad { get; set; } = 1;
|
||||
|
||||
/// <summary>
|
||||
/// Hora específica de ejecución (formato HH:mm:ss)
|
||||
/// </summary>
|
||||
[Required]
|
||||
[MaxLength(10)]
|
||||
public string HoraEjecucion { get; set; } = "00:00:00";
|
||||
|
||||
/// <summary>
|
||||
/// Última vez que se ejecutó el proceso
|
||||
/// </summary>
|
||||
public DateTime? UltimaEjecucion { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Resultado del último proceso (true=Exitoso, false=Con Errores)
|
||||
/// </summary>
|
||||
public bool Estado { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Indica si el servicio está activo o detenido
|
||||
/// </summary>
|
||||
public bool EnEjecucion { get; set; } = false;
|
||||
|
||||
// ===== CONFIGURACIÓN BASE DE DATOS ERP (EXTERNA) =====
|
||||
/// <summary>
|
||||
/// Servidor de SQL Server del ERP
|
||||
/// </summary>
|
||||
[Required]
|
||||
[MaxLength(200)]
|
||||
public string DBServidor { get; set; } = "TECNICA3";
|
||||
|
||||
/// <summary>
|
||||
/// Nombre de la base de datos del ERP
|
||||
/// </summary>
|
||||
[Required]
|
||||
[MaxLength(100)]
|
||||
public string DBNombre { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Usuario de SQL Server (si no usa autenticación integrada)
|
||||
/// </summary>
|
||||
[MaxLength(500)]
|
||||
public string? DBUsuario { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Contraseña de SQL Server (si no usa autenticación integrada)
|
||||
/// </summary>
|
||||
[MaxLength(500)]
|
||||
public string? DBClave { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Usar autenticación integrada de Windows (true) o credenciales SQL (false)
|
||||
/// </summary>
|
||||
public bool DBTrusted { get; set; } = true;
|
||||
|
||||
// ===== RUTAS DE ARCHIVOS =====
|
||||
/// <summary>
|
||||
/// Ruta de red donde se buscan los PDFs originales (Origen)
|
||||
/// </summary>
|
||||
[Required]
|
||||
[MaxLength(500)]
|
||||
public string RutaFacturas { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Ruta de red donde se organizan los PDFs procesados (Destino)
|
||||
/// </summary>
|
||||
[Required]
|
||||
[MaxLength(500)]
|
||||
public string RutaDestino { get; set; } = string.Empty;
|
||||
|
||||
// ===== CONFIGURACIÓN SMTP =====
|
||||
/// <summary>
|
||||
/// Servidor SMTP para envío de alertas
|
||||
/// </summary>
|
||||
[MaxLength(200)]
|
||||
public string? SMTPServidor { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Puerto del servidor SMTP
|
||||
/// </summary>
|
||||
public int SMTPPuerto { get; set; } = 587;
|
||||
|
||||
/// <summary>
|
||||
/// Usuario para autenticación SMTP
|
||||
/// </summary>
|
||||
[MaxLength(500)]
|
||||
public string? SMTPUsuario { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Contraseña para autenticación SMTP
|
||||
/// </summary>
|
||||
[MaxLength(500)]
|
||||
public string? SMTPClave { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Usar SSL/TLS para conexión SMTP
|
||||
/// </summary>
|
||||
public bool SMTPSSL { get; set; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// Dirección de correo destinatario para alertas
|
||||
/// </summary>
|
||||
[MaxLength(200)]
|
||||
public string? SMTPDestinatario { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Activar/desactivar envío de alertas por correo
|
||||
/// </summary>
|
||||
public bool AvisoMail { get; set; } = false;
|
||||
}
|
||||
95
Backend/GestorFacturas.API/Models/DTOs/ConfiguracionDto.cs
Normal file
95
Backend/GestorFacturas.API/Models/DTOs/ConfiguracionDto.cs
Normal file
@@ -0,0 +1,95 @@
|
||||
namespace GestorFacturas.API.Models.DTOs;
|
||||
|
||||
/// <summary>
|
||||
/// DTO para transferencia de datos de configuración
|
||||
/// </summary>
|
||||
public class ConfiguracionDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
|
||||
// Periodicidad
|
||||
public string Periodicidad { get; set; } = "Dias";
|
||||
public int ValorPeriodicidad { get; set; } = 1;
|
||||
public string HoraEjecucion { get; set; } = "00:00:00";
|
||||
public DateTime? UltimaEjecucion { get; set; }
|
||||
public DateTime? ProximaEjecucion { get; set; }
|
||||
public bool Estado { get; set; }
|
||||
public bool EnEjecucion { get; set; }
|
||||
|
||||
// Base de Datos Externa
|
||||
public string DBServidor { get; set; } = "127.0.0.1";
|
||||
public string DBNombre { get; set; } = string.Empty;
|
||||
public string? DBUsuario { get; set; }
|
||||
public string? DBClave { get; set; }
|
||||
public bool DBTrusted { get; set; } = true;
|
||||
|
||||
// Rutas
|
||||
public string RutaFacturas { get; set; } = string.Empty;
|
||||
public string RutaDestino { get; set; } = string.Empty;
|
||||
|
||||
// SMTP
|
||||
public string? SMTPServidor { get; set; }
|
||||
public int SMTPPuerto { get; set; } = 587;
|
||||
public string? SMTPUsuario { get; set; }
|
||||
public string? SMTPClave { get; set; }
|
||||
public bool SMTPSSL { get; set; } = true;
|
||||
public string? SMTPDestinatario { get; set; }
|
||||
public bool AvisoMail { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DTO para probar conexión a base de datos externa
|
||||
/// </summary>
|
||||
public class ProbarConexionDto
|
||||
{
|
||||
public string Servidor { get; set; } = string.Empty;
|
||||
public string NombreDB { get; set; } = string.Empty;
|
||||
public string? Usuario { get; set; }
|
||||
public string? Clave { get; set; }
|
||||
public bool TrustedConnection { get; set; } = true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DTO para probar configuración SMTP
|
||||
/// </summary>
|
||||
public class ProbarSMTPDto
|
||||
{
|
||||
public string Servidor { get; set; } = string.Empty;
|
||||
public int Puerto { get; set; } = 587;
|
||||
public string Usuario { get; set; } = string.Empty;
|
||||
public string Clave { get; set; } = string.Empty;
|
||||
public bool SSL { get; set; } = true;
|
||||
public string Destinatario { get; set; } = string.Empty;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DTO para solicitud de ejecución manual
|
||||
/// </summary>
|
||||
public class EjecucionManualDto
|
||||
{
|
||||
public DateTime FechaDesde { get; set; } = DateTime.Today;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DTO para respuesta de evento
|
||||
/// </summary>
|
||||
public class EventoDto
|
||||
{
|
||||
public int Id { get; set; }
|
||||
public DateTime Fecha { get; set; }
|
||||
public string Mensaje { get; set; } = string.Empty;
|
||||
public string Tipo { get; set; } = string.Empty;
|
||||
public bool Enviado { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// DTO para respuesta paginada
|
||||
/// </summary>
|
||||
public class PagedResult<T>
|
||||
{
|
||||
public List<T> Items { get; set; } = new();
|
||||
public int TotalCount { get; set; }
|
||||
public int PageNumber { get; set; }
|
||||
public int PageSize { get; set; }
|
||||
public int TotalPages => (int)Math.Ceiling((double)TotalCount / PageSize);
|
||||
}
|
||||
48
Backend/GestorFacturas.API/Models/Evento.cs
Normal file
48
Backend/GestorFacturas.API/Models/Evento.cs
Normal file
@@ -0,0 +1,48 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
|
||||
namespace GestorFacturas.API.Models;
|
||||
|
||||
/// <summary>
|
||||
/// Entidad para registro de eventos y auditoría del sistema
|
||||
/// </summary>
|
||||
public class Evento
|
||||
{
|
||||
[Key]
|
||||
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
|
||||
public int Id { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Fecha y hora del evento
|
||||
/// </summary>
|
||||
[Required]
|
||||
public DateTime Fecha { get; set; } = DateTime.Now;
|
||||
|
||||
/// <summary>
|
||||
/// Mensaje descriptivo del evento
|
||||
/// </summary>
|
||||
[Required]
|
||||
public string Mensaje { get; set; } = string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Tipo de evento: "Info", "Error", "Warning"
|
||||
/// </summary>
|
||||
[Required]
|
||||
[MaxLength(20)]
|
||||
public string Tipo { get; set; } = "Info";
|
||||
|
||||
/// <summary>
|
||||
/// Indica si este evento ya fue notificado por correo
|
||||
/// </summary>
|
||||
public bool Enviado { get; set; } = false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Enum para tipos de eventos
|
||||
/// </summary>
|
||||
public enum TipoEvento
|
||||
{
|
||||
Info,
|
||||
Error,
|
||||
Warning
|
||||
}
|
||||
29
Backend/GestorFacturas.API/Models/RefreshToken.cs
Normal file
29
Backend/GestorFacturas.API/Models/RefreshToken.cs
Normal file
@@ -0,0 +1,29 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.ComponentModel.DataAnnotations.Schema;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace GestorFacturas.API.Models;
|
||||
|
||||
public class RefreshToken
|
||||
{
|
||||
[Key]
|
||||
public int Id { get; set; }
|
||||
|
||||
[Required]
|
||||
public string Token { get; set; } = string.Empty;
|
||||
|
||||
public DateTime Expires { get; set; }
|
||||
public DateTime Created { get; set; } = DateTime.UtcNow;
|
||||
public DateTime? Revoked { get; set; }
|
||||
|
||||
public bool IsPersistent { get; set; }
|
||||
|
||||
public bool IsExpired => DateTime.UtcNow >= Expires;
|
||||
public bool IsActive => Revoked == null && !IsExpired;
|
||||
|
||||
public int UsuarioId { get; set; }
|
||||
|
||||
[ForeignKey("UsuarioId")]
|
||||
[JsonIgnore]
|
||||
public Usuario? Usuario { get; set; }
|
||||
}
|
||||
17
Backend/GestorFacturas.API/Models/Usuario.cs
Normal file
17
Backend/GestorFacturas.API/Models/Usuario.cs
Normal file
@@ -0,0 +1,17 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
namespace GestorFacturas.API.Models;
|
||||
|
||||
public class Usuario
|
||||
{
|
||||
[Key]
|
||||
public int Id { get; set; }
|
||||
|
||||
[Required]
|
||||
[MaxLength(50)]
|
||||
public string Username { get; set; } = string.Empty;
|
||||
|
||||
[Required]
|
||||
public string PasswordHash { get; set; } = string.Empty;
|
||||
|
||||
public string Nombre { get; set; } = string.Empty;
|
||||
}
|
||||
108
Backend/GestorFacturas.API/Program.cs
Normal file
108
Backend/GestorFacturas.API/Program.cs
Normal file
@@ -0,0 +1,108 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Serilog;
|
||||
using FluentValidation;
|
||||
using GestorFacturas.API.Data;
|
||||
using GestorFacturas.API.Services;
|
||||
using GestorFacturas.API.Services.Interfaces;
|
||||
using GestorFacturas.API.Workers;
|
||||
using Microsoft.AspNetCore.Authentication.JwtBearer;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using System.Text;
|
||||
|
||||
var builder = WebApplication.CreateBuilder(args);
|
||||
// ===== CONFIGURAR SERILOG (LIMPIO PARA PRODUCCIÓN) =====
|
||||
Log.Logger = new LoggerConfiguration()
|
||||
.ReadFrom.Configuration(builder.Configuration) // Lee filtros del appsettings
|
||||
.WriteTo.Console() // ÚNICA SALIDA: Consola (para que Docker/Grafana lo recojan)
|
||||
.CreateLogger();
|
||||
|
||||
builder.Host.UseSerilog();
|
||||
// ===== SERVICIOS =====
|
||||
builder.Services.AddControllers();
|
||||
builder.Services.AddEndpointsApiExplorer();
|
||||
builder.Services.AddSwaggerGen();
|
||||
// Entity Framework
|
||||
builder.Services.AddDbContext<ApplicationDbContext>(options =>
|
||||
options.UseSqlServer(
|
||||
builder.Configuration.GetConnectionString("DefaultConnection"),
|
||||
sqlOptions => sqlOptions.EnableRetryOnFailure()
|
||||
)
|
||||
);
|
||||
// Auth Service
|
||||
builder.Services.AddScoped<AuthService>();
|
||||
// Servicio de Encriptación
|
||||
builder.Services.AddScoped<IEncryptionService, EncryptionService>();
|
||||
// JWT Configuration
|
||||
var jwtKey = builder.Configuration["Jwt:Key"] ?? throw new InvalidOperationException("JWT Key missing");
|
||||
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
|
||||
.AddJwtBearer(options =>
|
||||
{
|
||||
options.TokenValidationParameters = new TokenValidationParameters
|
||||
{
|
||||
ValidateIssuer = true,
|
||||
ValidateAudience = true,
|
||||
ValidateLifetime = true,
|
||||
ValidateIssuerSigningKey = true,
|
||||
ValidIssuer = builder.Configuration["Jwt:Issuer"],
|
||||
ValidAudience = builder.Configuration["Jwt:Audience"],
|
||||
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey))
|
||||
};
|
||||
});
|
||||
// FluentValidation
|
||||
builder.Services.AddValidatorsFromAssemblyContaining<Program>();
|
||||
// Business Services
|
||||
builder.Services.AddScoped<IMailService, MailService>();
|
||||
builder.Services.AddScoped<IProcesadorFacturasService, ProcesadorFacturasService>();
|
||||
// Background Service
|
||||
builder.Services.AddHostedService<CronogramaWorker>();
|
||||
// CORS
|
||||
builder.Services.AddCors(options =>
|
||||
{
|
||||
options.AddPolicy("AllowReactApp", policy =>
|
||||
{
|
||||
policy.WithOrigins("http://localhost:5173", "http://localhost:3000", "http://localhost:80")
|
||||
.AllowAnyMethod()
|
||||
.AllowAnyHeader()
|
||||
.AllowCredentials();
|
||||
});
|
||||
});
|
||||
var app = builder.Build();
|
||||
// Migraciones Automáticas
|
||||
using (var scope = app.Services.CreateScope())
|
||||
{
|
||||
try
|
||||
{
|
||||
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
await context.Database.MigrateAsync();
|
||||
Log.Information("Base de datos migrada correctamente");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Error(ex, "Error al aplicar migraciones de base de datos");
|
||||
}
|
||||
}
|
||||
// Middleware Pipeline
|
||||
if (app.Environment.IsDevelopment())
|
||||
{
|
||||
app.UseSwagger();
|
||||
app.UseSwaggerUI();
|
||||
}
|
||||
app.UseSerilogRequestLogging();
|
||||
app.UseHttpsRedirection();
|
||||
app.UseCors("AllowReactApp");
|
||||
app.UseAuthentication();
|
||||
app.UseAuthorization();
|
||||
app.MapControllers();
|
||||
try
|
||||
{
|
||||
Log.Information("Aplicación Gestor de Facturas iniciada");
|
||||
app.Run();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Log.Fatal(ex, "La aplicación terminó inesperadamente");
|
||||
}
|
||||
finally
|
||||
{
|
||||
Log.CloseAndFlush();
|
||||
}
|
||||
23
Backend/GestorFacturas.API/Properties/launchSettings.json
Normal file
23
Backend/GestorFacturas.API/Properties/launchSettings.json
Normal file
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/launchsettings.json",
|
||||
"profiles": {
|
||||
"http": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "http://localhost:5036",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
},
|
||||
"https": {
|
||||
"commandName": "Project",
|
||||
"dotnetRunMessages": true,
|
||||
"launchBrowser": false,
|
||||
"applicationUrl": "https://localhost:7067;http://localhost:5036",
|
||||
"environmentVariables": {
|
||||
"ASPNETCORE_ENVIRONMENT": "Development"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
74
Backend/GestorFacturas.API/Services/AuthService.cs
Normal file
74
Backend/GestorFacturas.API/Services/AuthService.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using GestorFacturas.API.Models;
|
||||
using GestorFacturas.API.Data;
|
||||
using BCrypt.Net;
|
||||
|
||||
namespace GestorFacturas.API.Services;
|
||||
|
||||
public class AuthService
|
||||
{
|
||||
private readonly IConfiguration _config;
|
||||
private readonly ApplicationDbContext _context;
|
||||
|
||||
public AuthService(IConfiguration config, ApplicationDbContext context)
|
||||
{
|
||||
_config = config;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public bool VerificarPassword(string password, string hash)
|
||||
{
|
||||
try { return BCrypt.Net.BCrypt.Verify(password, hash); } catch { return false; }
|
||||
}
|
||||
|
||||
public string GenerarHash(string password)
|
||||
{
|
||||
return BCrypt.Net.BCrypt.HashPassword(password);
|
||||
}
|
||||
|
||||
// Generar JWT (Access Token) - Vida corta (ej. 15 min)
|
||||
public string GenerarAccessToken(Usuario usuario)
|
||||
{
|
||||
var keyStr = _config["Jwt:Key"] ?? throw new InvalidOperationException("Jwt:Key no configurada");
|
||||
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyStr));
|
||||
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, usuario.Id.ToString()),
|
||||
new Claim(ClaimTypes.Name, usuario.Username)
|
||||
};
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
_config["Jwt:Issuer"],
|
||||
_config["Jwt:Audience"],
|
||||
claims,
|
||||
expires: DateTime.UtcNow.AddMinutes(15),
|
||||
signingCredentials: credentials);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
|
||||
// Generar Refresh Token - Vida larga (ej. 7 días)
|
||||
public RefreshToken GenerarRefreshToken(int usuarioId, bool isPersistent)
|
||||
{
|
||||
// Si es persistente: 30 días.
|
||||
// Si NO es persistente: 12 horas.
|
||||
var duracion = isPersistent ? TimeSpan.FromDays(30) : TimeSpan.FromHours(12);
|
||||
|
||||
var refreshToken = new RefreshToken
|
||||
{
|
||||
Token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64)),
|
||||
Expires = DateTime.UtcNow.Add(duracion),
|
||||
Created = DateTime.UtcNow,
|
||||
UsuarioId = usuarioId,
|
||||
IsPersistent = isPersistent
|
||||
};
|
||||
|
||||
return refreshToken;
|
||||
}
|
||||
}
|
||||
78
Backend/GestorFacturas.API/Services/EncryptionService.cs
Normal file
78
Backend/GestorFacturas.API/Services/EncryptionService.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using GestorFacturas.API.Services.Interfaces;
|
||||
|
||||
namespace GestorFacturas.API.Services;
|
||||
|
||||
public class EncryptionService : IEncryptionService
|
||||
{
|
||||
private readonly string _key;
|
||||
|
||||
public EncryptionService(IConfiguration config)
|
||||
{
|
||||
// La clave debe venir del .env / appsettings
|
||||
_key = config["EncryptionKey"] ?? throw new ArgumentNullException("EncryptionKey no configurada");
|
||||
|
||||
// Ajustar si la clave no tiene el tamaño correcto (AES-256 requiere 32 bytes)
|
||||
// Aquí hacemos un hash SHA256 de la clave para asegurar que siempre tenga 32 bytes válidos
|
||||
using var sha256 = SHA256.Create();
|
||||
var keyBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(_key));
|
||||
_key = Convert.ToBase64String(keyBytes);
|
||||
}
|
||||
|
||||
public string Encrypt(string plainText)
|
||||
{
|
||||
if (string.IsNullOrEmpty(plainText)) return plainText;
|
||||
|
||||
var key = Convert.FromBase64String(_key);
|
||||
using var aes = Aes.Create();
|
||||
aes.Key = key;
|
||||
aes.GenerateIV(); // Generar vector de inicialización aleatorio
|
||||
|
||||
using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
|
||||
using var ms = new MemoryStream();
|
||||
|
||||
// Escribir el IV al principio del stream (necesario para desencriptar)
|
||||
ms.Write(aes.IV, 0, aes.IV.Length);
|
||||
|
||||
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
|
||||
using (var sw = new StreamWriter(cs))
|
||||
{
|
||||
sw.Write(plainText);
|
||||
}
|
||||
|
||||
return Convert.ToBase64String(ms.ToArray());
|
||||
}
|
||||
|
||||
public string Decrypt(string cipherText)
|
||||
{
|
||||
if (string.IsNullOrEmpty(cipherText)) return cipherText;
|
||||
|
||||
try
|
||||
{
|
||||
var fullCipher = Convert.FromBase64String(cipherText);
|
||||
var key = Convert.FromBase64String(_key);
|
||||
|
||||
using var aes = Aes.Create();
|
||||
aes.Key = key;
|
||||
|
||||
// Extraer el IV (los primeros 16 bytes)
|
||||
var iv = new byte[16];
|
||||
Array.Copy(fullCipher, 0, iv, 0, iv.Length);
|
||||
aes.IV = iv;
|
||||
|
||||
using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
|
||||
using var ms = new MemoryStream(fullCipher, 16, fullCipher.Length - 16);
|
||||
using var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
|
||||
using var sr = new StreamReader(cs);
|
||||
|
||||
return sr.ReadToEnd();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Si falla al desencriptar (ej. porque el dato viejo no estaba encriptado),
|
||||
// devolvemos el texto original para no romper la app en la migración.
|
||||
return cipherText;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace GestorFacturas.API.Services.Interfaces;
|
||||
|
||||
public interface IEncryptionService
|
||||
{
|
||||
string Encrypt(string plainText);
|
||||
string Decrypt(string cipherText);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace GestorFacturas.API.Services.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Interfaz para el servicio de envío de correos electrónicos
|
||||
/// </summary>
|
||||
public interface IMailService
|
||||
{
|
||||
/// <summary>
|
||||
/// Envía un correo electrónico
|
||||
/// </summary>
|
||||
/// <param name="destinatario">Dirección del destinatario</param>
|
||||
/// <param name="asunto">Asunto del correo</param>
|
||||
/// <param name="cuerpo">Cuerpo del mensaje (puede incluir HTML)</param>
|
||||
/// <param name="esHTML">Indica si el cuerpo es HTML</param>
|
||||
Task<bool> EnviarCorreoAsync(string destinatario, string asunto, string cuerpo, bool esHTML = true);
|
||||
|
||||
/// <summary>
|
||||
/// Prueba la configuración SMTP
|
||||
/// </summary>
|
||||
Task<bool> ProbarConexionAsync();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace GestorFacturas.API.Services.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Interfaz para el servicio principal de procesamiento de facturas
|
||||
/// </summary>
|
||||
public interface IProcesadorFacturasService
|
||||
{
|
||||
/// <summary>
|
||||
/// Ejecuta el proceso de búsqueda y organización de facturas
|
||||
/// </summary>
|
||||
/// <param name="fechaDesde">Fecha desde la cual buscar facturas</param>
|
||||
Task EjecutarProcesoAsync(DateTime fechaDesde);
|
||||
}
|
||||
143
Backend/GestorFacturas.API/Services/MailService.cs
Normal file
143
Backend/GestorFacturas.API/Services/MailService.cs
Normal file
@@ -0,0 +1,143 @@
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using MimeKit;
|
||||
using GestorFacturas.API.Data;
|
||||
using GestorFacturas.API.Services.Interfaces;
|
||||
using GestorFacturas.API.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GestorFacturas.API.Services;
|
||||
|
||||
public class MailService : IMailService
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly ILogger<MailService> _logger;
|
||||
private readonly IEncryptionService _encryptionService;
|
||||
|
||||
public MailService(ApplicationDbContext context, ILogger<MailService> logger, IEncryptionService encryptionService)
|
||||
{
|
||||
_context = context;
|
||||
_logger = logger;
|
||||
_encryptionService = encryptionService;
|
||||
}
|
||||
|
||||
public async Task<bool> EnviarCorreoAsync(string destinatario, string asunto, string cuerpo, bool esHTML = true)
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
|
||||
if (config == null || string.IsNullOrEmpty(config.SMTPServidor))
|
||||
{
|
||||
_logger.LogWarning("No hay configuración SMTP disponible");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!config.AvisoMail)
|
||||
{
|
||||
_logger.LogInformation("Envío de correos desactivado en configuración");
|
||||
return false;
|
||||
}
|
||||
|
||||
// --- CORRECCIÓN AQUÍ ---
|
||||
// Desencriptamos las credenciales AL PRINCIPIO para usarlas en el 'From' y en el 'Authenticate'
|
||||
string usuarioSmtp = string.IsNullOrEmpty(config.SMTPUsuario)
|
||||
? "sistema@eldia.com"
|
||||
: _encryptionService.Decrypt(config.SMTPUsuario);
|
||||
|
||||
string claveSmtp = string.IsNullOrEmpty(config.SMTPClave)
|
||||
? ""
|
||||
: _encryptionService.Decrypt(config.SMTPClave);
|
||||
// -----------------------
|
||||
|
||||
var mensaje = new MimeMessage();
|
||||
// Usamos la variable desencriptada
|
||||
mensaje.From.Add(new MailboxAddress("Gestor Facturas El Día", usuarioSmtp));
|
||||
mensaje.To.Add(MailboxAddress.Parse(destinatario));
|
||||
mensaje.Subject = asunto;
|
||||
|
||||
var builder = new BodyBuilder();
|
||||
if (esHTML) builder.HtmlBody = cuerpo;
|
||||
else builder.TextBody = cuerpo;
|
||||
|
||||
mensaje.Body = builder.ToMessageBody();
|
||||
|
||||
using var cliente = new SmtpClient();
|
||||
|
||||
// Bypass de certificado SSL para redes internas
|
||||
cliente.ServerCertificateValidationCallback = (s, c, h, e) => true;
|
||||
|
||||
var secureSocketOptions = config.SMTPSSL
|
||||
? SecureSocketOptions.StartTls
|
||||
: SecureSocketOptions.Auto;
|
||||
|
||||
await cliente.ConnectAsync(config.SMTPServidor, config.SMTPPuerto, secureSocketOptions);
|
||||
|
||||
// Usamos las variables que ya desencriptamos arriba
|
||||
if (!string.IsNullOrEmpty(usuarioSmtp) && !string.IsNullOrEmpty(claveSmtp))
|
||||
{
|
||||
await cliente.AuthenticateAsync(usuarioSmtp, claveSmtp);
|
||||
}
|
||||
|
||||
await cliente.SendAsync(mensaje);
|
||||
await cliente.DisconnectAsync(true);
|
||||
|
||||
_logger.LogInformation("Correo enviado exitosamente a {destinatario}", destinatario);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al enviar correo a {destinatario}", destinatario);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ProbarConexionAsync()
|
||||
{
|
||||
// Este método no se está usando actualmente en el flujo crítico (usamos ProbarSMTP en el controller),
|
||||
// pero por consistencia deberías aplicar la misma lógica de desencriptación si planeas usarlo.
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
public async Task<bool> ProbarConexionAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
|
||||
if (config == null || string.IsNullOrEmpty(config.SMTPServidor))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
using var cliente = new SmtpClient();
|
||||
|
||||
cliente.ServerCertificateValidationCallback = (s, c, h, e) => true;
|
||||
|
||||
var secureSocketOptions = config.SMTPSSL
|
||||
? SecureSocketOptions.StartTls
|
||||
: SecureSocketOptions.Auto;
|
||||
|
||||
await cliente.ConnectAsync(config.SMTPServidor, config.SMTPPuerto, secureSocketOptions);
|
||||
|
||||
if (!string.IsNullOrEmpty(config.SMTPUsuario) && !string.IsNullOrEmpty(config.SMTPClave))
|
||||
{
|
||||
// DESENCRIPTAR AQUÍ
|
||||
var usuario = _encryptionService.Decrypt(config.SMTPUsuario);
|
||||
var clave = _encryptionService.Decrypt(config.SMTPClave);
|
||||
|
||||
await cliente.AuthenticateAsync(usuario, clave);
|
||||
}
|
||||
|
||||
await cliente.DisconnectAsync(true);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al probar conexión SMTP");
|
||||
return false;
|
||||
}
|
||||
}*/
|
||||
}
|
||||
483
Backend/GestorFacturas.API/Services/ProcesadorFacturasService.cs
Normal file
483
Backend/GestorFacturas.API/Services/ProcesadorFacturasService.cs
Normal file
@@ -0,0 +1,483 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using GestorFacturas.API.Data;
|
||||
using GestorFacturas.API.Models;
|
||||
using GestorFacturas.API.Services.Interfaces;
|
||||
using System.Data;
|
||||
|
||||
namespace GestorFacturas.API.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Servicio principal de procesamiento de facturas.
|
||||
/// </summary>
|
||||
public class ProcesadorFacturasService : IProcesadorFacturasService
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly ILogger<ProcesadorFacturasService> _logger;
|
||||
private readonly IMailService _mailService;
|
||||
private readonly IEncryptionService _encryptionService;
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
private const int MAX_REINTENTOS = 10;
|
||||
private const int DELAY_SEGUNDOS = 60;
|
||||
|
||||
public ProcesadorFacturasService(
|
||||
ApplicationDbContext context,
|
||||
ILogger<ProcesadorFacturasService> logger,
|
||||
IMailService mailService,
|
||||
IEncryptionService encryptionService,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
_context = context;
|
||||
_logger = logger;
|
||||
_mailService = mailService;
|
||||
_encryptionService = encryptionService;
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public async Task EjecutarProcesoAsync(DateTime fechaDesde)
|
||||
{
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
if (config == null)
|
||||
{
|
||||
await RegistrarEventoAsync("No se encontró configuración del sistema", TipoEvento.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Actualizamos la fecha de ejecución
|
||||
config.UltimaEjecucion = DateTime.Now;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
await RegistrarEventoAsync($"Iniciando proceso de facturas desde {fechaDesde:dd/MM/yyyy}", TipoEvento.Info);
|
||||
|
||||
try
|
||||
{
|
||||
var facturas = await ObtenerFacturasDesdeERPAsync(config, fechaDesde);
|
||||
|
||||
if (facturas.Count == 0)
|
||||
{
|
||||
await RegistrarEventoAsync($"No se encontraron facturas desde {fechaDesde:dd/MM/yyyy}", TipoEvento.Warning);
|
||||
config.Estado = true;
|
||||
await _context.SaveChangesAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
await RegistrarEventoAsync($"Se encontraron {facturas.Count} facturas para procesar", TipoEvento.Info);
|
||||
|
||||
int procesadas = 0;
|
||||
int errores = 0;
|
||||
List<FacturaParaProcesar> pendientes = new();
|
||||
List<string> detallesErroresParaMail = new();
|
||||
|
||||
// Lista para rastrear las entidades de Evento y actualizar su flag 'Enviado' luego
|
||||
List<Evento> eventosDeErrorParaActualizar = new();
|
||||
|
||||
// --- 1. Primer intento ---
|
||||
foreach (var factura in facturas)
|
||||
{
|
||||
bool exito = await ProcesarFacturaAsync(factura, config);
|
||||
if (exito) procesadas++;
|
||||
else pendientes.Add(factura);
|
||||
}
|
||||
|
||||
// --- 2. Sistema de Reintentos ---
|
||||
if (pendientes.Count > 0)
|
||||
{
|
||||
await RegistrarEventoAsync($"{pendientes.Count} archivos no encontrados. Iniciando sistema de reintentos...", TipoEvento.Warning);
|
||||
|
||||
for (int intento = 1; intento <= MAX_REINTENTOS && pendientes.Count > 0; intento++)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(DELAY_SEGUNDOS));
|
||||
|
||||
var aunPendientes = new List<FacturaParaProcesar>();
|
||||
|
||||
foreach (var factura in pendientes)
|
||||
{
|
||||
bool exito = await ProcesarFacturaAsync(factura, config);
|
||||
if (exito)
|
||||
{
|
||||
procesadas++;
|
||||
_logger.LogInformation("Archivo encontrado en reintento {intento}: {archivo}", intento, factura.NombreArchivoOrigen);
|
||||
}
|
||||
else
|
||||
{
|
||||
aunPendientes.Add(factura);
|
||||
}
|
||||
}
|
||||
pendientes = aunPendientes;
|
||||
}
|
||||
|
||||
// --- 3. Registro de Errores Finales ---
|
||||
if (pendientes.Count > 0)
|
||||
{
|
||||
errores = pendientes.Count;
|
||||
foreach (var factura in pendientes)
|
||||
{
|
||||
string msgError = $"El archivo NO EXISTE después de {MAX_REINTENTOS} intentos: {factura.NombreArchivoOrigen}";
|
||||
|
||||
var eventoError = new Evento
|
||||
{
|
||||
Fecha = DateTime.Now,
|
||||
Mensaje = msgError,
|
||||
Tipo = TipoEvento.Error.ToString(),
|
||||
Enviado = false
|
||||
};
|
||||
|
||||
_context.Eventos.Add(eventoError);
|
||||
|
||||
// Guardamos referencias
|
||||
eventosDeErrorParaActualizar.Add(eventoError);
|
||||
detallesErroresParaMail.Add(factura.NombreArchivoOrigen);
|
||||
}
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
// --- 4. Actualización de Estado General ---
|
||||
config.Estado = errores == 0;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// --- 5. Limpieza automática ---
|
||||
try
|
||||
{
|
||||
var fechaLimiteBorrado = DateTime.Now.AddMonths(-1);
|
||||
var eventosViejos = _context.Eventos.Where(e => e.Fecha < fechaLimiteBorrado);
|
||||
if (eventosViejos.Any())
|
||||
{
|
||||
_context.Eventos.RemoveRange(eventosViejos);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
// --- 6. Evento Final ---
|
||||
var mensajeFinal = $"Proceso finalizado. Procesadas: {procesadas}, Errores: {errores}";
|
||||
await RegistrarEventoAsync(mensajeFinal, errores > 0 ? TipoEvento.Warning : TipoEvento.Info);
|
||||
|
||||
// --- 7. Envío de Mail Inteligente (Solo 1 vez por archivo) ---
|
||||
if (errores > 0 && config.AvisoMail && !string.IsNullOrEmpty(config.SMTPDestinatario))
|
||||
{
|
||||
// 1. Buscamos en la historia de la DB si estos archivos ya fueron reportados previamente.
|
||||
// Buscamos en TODOS los logs disponibles (que suelen ser los últimos 30 días según la limpieza).
|
||||
// Filtramos por Tipo Error y Enviado=true.
|
||||
var historialErroresEnviados = await _context.Eventos
|
||||
.Where(e => e.Tipo == TipoEvento.Error.ToString() && e.Enviado == true)
|
||||
.Select(e => e.Mensaje)
|
||||
.ToListAsync();
|
||||
|
||||
// 2. Filtramos la lista actual:
|
||||
// Solo queremos los archivos que NO aparezcan en ningún mensaje del historial.
|
||||
var archivosNuevosParaNotificar = detallesErroresParaMail.Where(archivoFallido =>
|
||||
{
|
||||
// El mensaje en BD es: "El archivo NO EXISTE...: nombre_archivo.pdf"
|
||||
// Chequeamos si el nombre del archivo está contenido en algún mensaje viejo.
|
||||
bool yaFueNotificado = historialErroresEnviados.Any(msgHistorico => msgHistorico.Contains(archivoFallido));
|
||||
return !yaFueNotificado;
|
||||
}).ToList();
|
||||
|
||||
// 3. Decidir si enviar mail
|
||||
bool mailEnviado = false;
|
||||
|
||||
if (archivosNuevosParaNotificar.Count > 0)
|
||||
{
|
||||
// Si hay archivos NUEVOS, enviamos mail SOLO con esos.
|
||||
// Nota: Pasamos 'errores' (total técnico) y 'archivosNuevosParaNotificar' (detalle visual)
|
||||
mailEnviado = await EnviarNotificacionErroresAsync(
|
||||
config.SMTPDestinatario,
|
||||
procesadas,
|
||||
errores,
|
||||
archivosNuevosParaNotificar
|
||||
);
|
||||
|
||||
if (mailEnviado)
|
||||
{
|
||||
_logger.LogInformation("Correo de alerta enviado con {count} archivos nuevos.", archivosNuevosParaNotificar.Count);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Se omitió el envío de correo: Los {count} errores ya fueron notificados anteriormente.", errores);
|
||||
// Simulamos que se "envió" (se gestionó) para marcar los flags en BD
|
||||
mailEnviado = true;
|
||||
}
|
||||
|
||||
// 4. Actualizar flag en BD (CRÍTICO)
|
||||
// Si gestionamos la notificación correctamente (ya sea enviándola o detectando que ya estaba enviada),
|
||||
// marcamos los eventos actuales como Enviado=true para que pasen al historial y no se vuelvan a procesar.
|
||||
if (mailEnviado && eventosDeErrorParaActualizar.Count > 0)
|
||||
{
|
||||
foreach (var evento in eventosDeErrorParaActualizar)
|
||||
{
|
||||
evento.Enviado = true;
|
||||
}
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error crítico en el proceso de facturas");
|
||||
string mensajeCritico = $"ERROR CRÍTICO DEL SISTEMA: {ex.Message}";
|
||||
|
||||
await RegistrarEventoAsync(mensajeCritico, TipoEvento.Error);
|
||||
|
||||
if (config != null)
|
||||
{
|
||||
config.Estado = false;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
if (config.AvisoMail && !string.IsNullOrEmpty(config.SMTPDestinatario))
|
||||
{
|
||||
var listaErroresCriticos = new List<string> { mensajeCritico };
|
||||
await EnviarNotificacionErroresAsync(config.SMTPDestinatario, 0, 1, listaErroresCriticos);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<List<FacturaParaProcesar>> ObtenerFacturasDesdeERPAsync(Configuracion config, DateTime fechaDesde)
|
||||
{
|
||||
var facturas = new List<FacturaParaProcesar>();
|
||||
var connectionString = ConstruirCadenaConexion(config);
|
||||
|
||||
try
|
||||
{
|
||||
using var conexion = new SqlConnection(connectionString);
|
||||
await conexion.OpenAsync();
|
||||
|
||||
var query = @"
|
||||
SELECT DISTINCT
|
||||
NUMERO_FACTURA,
|
||||
TIPO_FACTURA,
|
||||
CLIENTE,
|
||||
SUCURSAL_FACTURA,
|
||||
DIVISION_FACTURA,
|
||||
FECHACOMPLETA_FACTURA,
|
||||
NRO_CAI
|
||||
FROM VISTA_FACTURACION_ELDIA
|
||||
WHERE SUCURSAL_FACTURA = '70'
|
||||
AND NRO_CAI IS NOT NULL
|
||||
AND NRO_CAI != ''
|
||||
AND FECHACOMPLETA_FACTURA >= @FechaDesde
|
||||
AND CONVERT(DATE, FECHACOMPLETA_FACTURA) <= CONVERT(DATE, GETDATE())
|
||||
ORDER BY FECHACOMPLETA_FACTURA DESC";
|
||||
|
||||
using var comando = new SqlCommand(query, conexion);
|
||||
comando.Parameters.AddWithValue("@FechaDesde", fechaDesde);
|
||||
|
||||
using var reader = await comando.ExecuteReaderAsync();
|
||||
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
var factura = new FacturaParaProcesar
|
||||
{
|
||||
NumeroFactura = (reader["NUMERO_FACTURA"].ToString() ?? "").Trim().PadLeft(10, '0'),
|
||||
TipoFactura = (reader["TIPO_FACTURA"].ToString() ?? "").Trim(),
|
||||
Cliente = (reader["CLIENTE"].ToString() ?? "").Trim().PadLeft(6, '0'),
|
||||
Sucursal = (reader["SUCURSAL_FACTURA"].ToString() ?? "").Trim().PadLeft(4, '0'),
|
||||
CodigoEmpresa = (reader["DIVISION_FACTURA"].ToString() ?? "").Trim().PadLeft(4, '0'),
|
||||
FechaFactura = Convert.ToDateTime(reader["FECHACOMPLETA_FACTURA"])
|
||||
};
|
||||
|
||||
factura.NombreEmpresa = MapearNombreEmpresa(factura.CodigoEmpresa);
|
||||
factura.NombreArchivoOrigen = ConstruirNombreArchivoOrigen(factura);
|
||||
factura.NombreArchivoDestino = ConstruirNombreArchivoDestino(factura);
|
||||
factura.CarpetaDestino = ConstruirRutaCarpetaDestino(factura);
|
||||
|
||||
facturas.Add(factura);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await RegistrarEventoAsync($"Error al conectar con el ERP: {ex.Message}", TipoEvento.Error);
|
||||
throw;
|
||||
}
|
||||
|
||||
return facturas;
|
||||
}
|
||||
|
||||
private async Task<bool> ProcesarFacturaAsync(FacturaParaProcesar factura, Configuracion config)
|
||||
{
|
||||
try
|
||||
{
|
||||
string rutaBaseOrigen = config.RutaFacturas;
|
||||
string rutaBaseDestino = config.RutaDestino;
|
||||
|
||||
string rutaOrigen = Path.Combine(rutaBaseOrigen, factura.NombreArchivoOrigen);
|
||||
string carpetaDestinoFinal = Path.Combine(rutaBaseDestino, factura.CarpetaDestino);
|
||||
|
||||
if (!File.Exists(rutaOrigen)) return false;
|
||||
|
||||
if (!Directory.Exists(carpetaDestinoFinal))
|
||||
{
|
||||
Directory.CreateDirectory(carpetaDestinoFinal);
|
||||
}
|
||||
|
||||
string rutaDestinoCompleta = Path.Combine(carpetaDestinoFinal, factura.NombreArchivoDestino);
|
||||
FileInfo infoOrigen = new FileInfo(rutaOrigen);
|
||||
FileInfo infoDestino = new FileInfo(rutaDestinoCompleta);
|
||||
|
||||
if (infoDestino.Exists)
|
||||
{
|
||||
if (infoDestino.Length == infoOrigen.Length) return true;
|
||||
}
|
||||
|
||||
File.Copy(rutaOrigen, rutaDestinoCompleta, overwrite: true);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Fallo al copiar {archivo}", factura.NombreArchivoOrigen);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- MÉTODOS DE MAPEO (CONFIGURABLES) ---
|
||||
|
||||
private string MapearNombreEmpresa(string codigoEmpresa)
|
||||
{
|
||||
var nombre = _configuration[$"EmpresasMapping:{codigoEmpresa}"];
|
||||
return string.IsNullOrEmpty(nombre) ? "DESCONOCIDA" : nombre;
|
||||
}
|
||||
|
||||
private string AjustarTipoFactura(string tipoOriginal)
|
||||
{
|
||||
if (string.IsNullOrEmpty(tipoOriginal)) return tipoOriginal;
|
||||
|
||||
// 1. Buscamos mapeo en appsettings.json
|
||||
var tipoMapeado = _configuration[$"FacturaTiposMapping:{tipoOriginal}"];
|
||||
if (!string.IsNullOrEmpty(tipoMapeado))
|
||||
{
|
||||
return tipoMapeado;
|
||||
}
|
||||
|
||||
// 2. Fallback Legacy si no está mapeado
|
||||
return tipoOriginal[^1].ToString();
|
||||
}
|
||||
|
||||
// --- CONSTRUCCIÓN DE NOMBRES ---
|
||||
|
||||
private string ConstruirNombreArchivoOrigen(FacturaParaProcesar factura)
|
||||
{
|
||||
return $"{factura.Cliente}-{factura.CodigoEmpresa}-{factura.Sucursal}-{factura.TipoFactura}-{factura.NumeroFactura}.pdf";
|
||||
}
|
||||
|
||||
private string ConstruirNombreArchivoDestino(FacturaParaProcesar factura)
|
||||
{
|
||||
// El archivo final conserva el Tipo ORIGINAL
|
||||
return $"{factura.Cliente}-{factura.CodigoEmpresa}-{factura.Sucursal}-{factura.TipoFactura}-{factura.NumeroFactura}.pdf";
|
||||
}
|
||||
|
||||
private string ConstruirRutaCarpetaDestino(FacturaParaProcesar factura)
|
||||
{
|
||||
// La carpeta usa el Tipo AJUSTADO
|
||||
string tipoAjustado = AjustarTipoFactura(factura.TipoFactura);
|
||||
string anioMes = factura.FechaFactura.ToString("yyyy-MM");
|
||||
|
||||
string nombreCarpetaFactura = $"{factura.Cliente}-{factura.CodigoEmpresa}-{factura.Sucursal}-{tipoAjustado}-{factura.NumeroFactura}";
|
||||
|
||||
return Path.Combine(factura.NombreEmpresa, anioMes, nombreCarpetaFactura);
|
||||
}
|
||||
|
||||
// --- UTILIDADES ---
|
||||
|
||||
private string ConstruirCadenaConexion(Configuracion config)
|
||||
{
|
||||
var builder = new SqlConnectionStringBuilder
|
||||
{
|
||||
DataSource = config.DBServidor,
|
||||
InitialCatalog = config.DBNombre,
|
||||
IntegratedSecurity = config.DBTrusted,
|
||||
TrustServerCertificate = true,
|
||||
ConnectTimeout = 30
|
||||
};
|
||||
|
||||
if (!config.DBTrusted)
|
||||
{
|
||||
builder.UserID = _encryptionService.Decrypt(config.DBUsuario ?? "");
|
||||
builder.Password = _encryptionService.Decrypt(config.DBClave ?? "");
|
||||
}
|
||||
|
||||
return builder.ConnectionString;
|
||||
}
|
||||
|
||||
private async Task RegistrarEventoAsync(string mensaje, TipoEvento tipo)
|
||||
{
|
||||
try
|
||||
{
|
||||
var evento = new Evento
|
||||
{
|
||||
Fecha = DateTime.Now,
|
||||
Mensaje = mensaje,
|
||||
Tipo = tipo.ToString(),
|
||||
Enviado = false
|
||||
};
|
||||
_context.Eventos.Add(evento);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al registrar evento");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> EnviarNotificacionErroresAsync(string destinatario, int procesadas, int errores, List<string> detalles)
|
||||
{
|
||||
try
|
||||
{
|
||||
var asunto = errores == 1 && detalles.Count > 0 && detalles[0].StartsWith("ERROR CRÍTICO")
|
||||
? "ALERTA CRÍTICA: Fallo del Sistema Gestor de Facturas"
|
||||
: "Alerta: Errores en Procesamiento de Facturas";
|
||||
|
||||
string listaArchivosHtml = "";
|
||||
if (detalles != null && detalles.Count > 0)
|
||||
{
|
||||
listaArchivosHtml = "<h3>Detalle de Errores:</h3><ul>";
|
||||
foreach (var archivo in detalles)
|
||||
{
|
||||
listaArchivosHtml += $"<li>{archivo}</li>";
|
||||
}
|
||||
listaArchivosHtml += "</ul>";
|
||||
}
|
||||
|
||||
var cuerpo = $@"
|
||||
<html>
|
||||
<body style='font-family: Arial, sans-serif;'>
|
||||
<h2 style='color: #d9534f;'>{asunto}</h2>
|
||||
<p><strong>Fecha de Ejecución:</strong> {DateTime.Now:dd/MM/yyyy HH:mm:ss}</p>
|
||||
<div style='background-color: #f8f9fa; padding: 15px; border-radius: 5px; border: 1px solid #dee2e6;'>
|
||||
<p><strong>Facturas procesadas exitosamente:</strong> {procesadas}</p>
|
||||
<p><strong>Facturas con error:</strong> <span style='color: red; font-weight: bold;'>{errores}</span></p>
|
||||
</div>
|
||||
<div style='margin-top: 20px;'>{listaArchivosHtml}</div>
|
||||
<hr style='margin-top: 30px;'>
|
||||
<p style='color: #6c757d; font-size: 12px;'>Sistema Gestor de Facturas El Día.</p>
|
||||
</body>
|
||||
</html>";
|
||||
|
||||
return await _mailService.EnviarCorreoAsync(destinatario, asunto, cuerpo, true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al preparar notificación de errores");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clase auxiliar para representar una factura a procesar
|
||||
/// </summary>
|
||||
public class FacturaParaProcesar
|
||||
{
|
||||
public string NumeroFactura { get; set; } = string.Empty;
|
||||
public string TipoFactura { get; set; } = string.Empty;
|
||||
public string Cliente { get; set; } = string.Empty;
|
||||
public string Sucursal { get; set; } = string.Empty;
|
||||
public string CodigoEmpresa { get; set; } = string.Empty;
|
||||
public string NombreEmpresa { get; set; } = string.Empty;
|
||||
public DateTime FechaFactura { get; set; }
|
||||
public string NombreArchivoOrigen { get; set; } = string.Empty;
|
||||
public string NombreArchivoDestino { get; set; } = string.Empty;
|
||||
public string CarpetaDestino { get; set; } = string.Empty;
|
||||
}
|
||||
155
Backend/GestorFacturas.API/Workers/CronogramaWorker.cs
Normal file
155
Backend/GestorFacturas.API/Workers/CronogramaWorker.cs
Normal file
@@ -0,0 +1,155 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using GestorFacturas.API.Data;
|
||||
using GestorFacturas.API.Models;
|
||||
using GestorFacturas.API.Services.Interfaces;
|
||||
|
||||
namespace GestorFacturas.API.Workers;
|
||||
|
||||
/// <summary>
|
||||
/// Worker Service que ejecuta el procesamiento de facturas de forma programada
|
||||
/// </summary>
|
||||
public class CronogramaWorker : BackgroundService
|
||||
{
|
||||
private readonly IServiceProvider _serviceProvider;
|
||||
private readonly ILogger<CronogramaWorker> _logger;
|
||||
// Eliminamos el Timer antiguo
|
||||
|
||||
public CronogramaWorker(
|
||||
IServiceProvider serviceProvider,
|
||||
ILogger<CronogramaWorker> logger)
|
||||
{
|
||||
_serviceProvider = serviceProvider;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
|
||||
{
|
||||
_logger.LogInformation("CronogramaWorker iniciado correctamente.");
|
||||
|
||||
// PeriodicTimer espera a que termine la ejecución antes de contar el siguiente intervalo.
|
||||
// Iniciamos con un tick de 1 minuto para chequear.
|
||||
using var timer = new PeriodicTimer(TimeSpan.FromMinutes(1));
|
||||
|
||||
try
|
||||
{
|
||||
// Bucle infinito mientras el servicio esté activo
|
||||
while (await timer.WaitForNextTickAsync(stoppingToken))
|
||||
{
|
||||
await VerificarYEjecutar(stoppingToken);
|
||||
}
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
_logger.LogInformation("CronogramaWorker detenido.");
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error fatal en el ciclo del CronogramaWorker");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task VerificarYEjecutar(CancellationToken stoppingToken)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var scope = _serviceProvider.CreateScope();
|
||||
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
|
||||
|
||||
var config = await context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1, stoppingToken);
|
||||
|
||||
if (config == null)
|
||||
{
|
||||
_logger.LogWarning("No se encontró configuración del sistema");
|
||||
return;
|
||||
}
|
||||
|
||||
// Verificar si el servicio está activo
|
||||
if (!config.EnEjecucion)
|
||||
{
|
||||
// Solo loguear en nivel Debug para no saturar los logs
|
||||
_logger.LogDebug("Servicio en estado detenido");
|
||||
return;
|
||||
}
|
||||
|
||||
// Determinar si toca ejecutar según la periodicidad
|
||||
if (!DebeEjecutar(config))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogInformation("¡Es momento de ejecutar el proceso de facturas!");
|
||||
|
||||
// Ejecutar el proceso
|
||||
var procesador = scope.ServiceProvider.GetRequiredService<IProcesadorFacturasService>();
|
||||
|
||||
// Calcular fecha desde basándonos en la última ejecución o periodicidad
|
||||
DateTime fechaDesde = CalcularFechaDesde(config);
|
||||
|
||||
await procesador.EjecutarProcesoAsync(fechaDesde);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error en CronogramaWorker al verificar y ejecutar");
|
||||
}
|
||||
}
|
||||
|
||||
private bool DebeEjecutar(Configuracion config)
|
||||
{
|
||||
if (config.UltimaEjecucion == null) return true;
|
||||
|
||||
var ahora = DateTime.Now;
|
||||
var ultimaEjecucion = config.UltimaEjecucion.Value;
|
||||
|
||||
if (!TimeSpan.TryParse(config.HoraEjecucion, out TimeSpan horaConfigurada))
|
||||
{
|
||||
horaConfigurada = TimeSpan.Zero;
|
||||
}
|
||||
|
||||
switch (config.Periodicidad.ToUpper())
|
||||
{
|
||||
case "MINUTOS":
|
||||
var minutosTranscurridos = (ahora - ultimaEjecucion).TotalMinutes;
|
||||
return minutosTranscurridos >= config.ValorPeriodicidad;
|
||||
|
||||
case "DIAS":
|
||||
case "DÍAS":
|
||||
var diasTranscurridos = (ahora.Date - ultimaEjecucion.Date).Days;
|
||||
if (diasTranscurridos < config.ValorPeriodicidad) return false;
|
||||
|
||||
var horaActual = ahora.TimeOfDay;
|
||||
var yaEjecutadoHoy = ultimaEjecucion.Date == ahora.Date;
|
||||
|
||||
// Ejecuta si pasó la hora configurada Y no se ha ejecutado hoy
|
||||
return horaActual >= horaConfigurada && !yaEjecutadoHoy;
|
||||
|
||||
case "MESES":
|
||||
var mesesTranscurridos = ((ahora.Year - ultimaEjecucion.Year) * 12) + ahora.Month - ultimaEjecucion.Month;
|
||||
if (mesesTranscurridos < config.ValorPeriodicidad) return false;
|
||||
|
||||
return ahora.TimeOfDay >= horaConfigurada && !(ultimaEjecucion.Date == ahora.Date);
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private DateTime CalcularFechaDesde(Configuracion config)
|
||||
{
|
||||
// Buffer de seguridad de 10 días
|
||||
int diasBuffer = 10;
|
||||
|
||||
if (config.UltimaEjecucion != null)
|
||||
{
|
||||
return config.UltimaEjecucion.Value.Date.AddDays(-diasBuffer);
|
||||
}
|
||||
|
||||
// Si es la primera vez, usa la periodicidad + buffer
|
||||
return config.Periodicidad.ToUpper() switch
|
||||
{
|
||||
"MINUTOS" => DateTime.Now.AddMinutes(-config.ValorPeriodicidad).AddDays(-diasBuffer),
|
||||
"DIAS" or "DÍAS" => DateTime.Now.AddDays(-config.ValorPeriodicidad - diasBuffer),
|
||||
"MESES" => DateTime.Now.AddMonths(-config.ValorPeriodicidad).AddDays(-diasBuffer),
|
||||
_ => DateTime.Today.AddDays(-diasBuffer)
|
||||
};
|
||||
}
|
||||
}
|
||||
8
Backend/GestorFacturas.API/appsettings.Development.json
Normal file
8
Backend/GestorFacturas.API/appsettings.Development.json
Normal file
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"Logging": {
|
||||
"LogLevel": {
|
||||
"Default": "Information",
|
||||
"Microsoft.AspNetCore": "Warning"
|
||||
}
|
||||
}
|
||||
}
|
||||
49
Backend/GestorFacturas.API/appsettings.json
Normal file
49
Backend/GestorFacturas.API/appsettings.json
Normal file
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"ConnectionStrings": {
|
||||
"DefaultConnection": "Server=TU_SERVIDOR_SQL;Database=AdminFacturasApp;User Id=TU_USUARIO;Password=TU_PASSWORD;TrustServerCertificate=True;MultipleActiveResultSets=true"
|
||||
},
|
||||
"EmpresasMapping": {
|
||||
"0001": "ELDIA",
|
||||
"0002": "PUBLIEXITO",
|
||||
"0003": "RADIONUEVA",
|
||||
"0004": "RADIOVIEJA",
|
||||
"0005": "SIP"
|
||||
},
|
||||
"FacturaTiposMapping": {
|
||||
"FSR": "A",
|
||||
"FBR": "B",
|
||||
"CAI": "NCA",
|
||||
"CBI": "NCB",
|
||||
"CAC": "NCA",
|
||||
"CBC": "NCB",
|
||||
"DAI": "NDA",
|
||||
"DBI": "NDB",
|
||||
"DAC": "NDA",
|
||||
"DBC": "NDB"
|
||||
},
|
||||
"Jwt": {
|
||||
"Key": "CLAVE_JWT_MUY_LARGA_AQUI_MINIMO_32_CHARS",
|
||||
"Issuer": "GestorFacturasAPI",
|
||||
"Audience": "GestorFacturasFrontend"
|
||||
},
|
||||
"EncryptionKey": "CLAVE_ENCRIPTACION_32_BYTES_AQUI",
|
||||
"Serilog": {
|
||||
"MinimumLevel": {
|
||||
"Default": "Information",
|
||||
"Override": {
|
||||
"Microsoft": "Warning",
|
||||
"Microsoft.EntityFrameworkCore": "Warning",
|
||||
"System": "Warning"
|
||||
}
|
||||
},
|
||||
"WriteTo": [
|
||||
{
|
||||
"Name": "Console",
|
||||
"Args": {
|
||||
"outputTemplate": "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"AllowedHosts": "*"
|
||||
}
|
||||
Reference in New Issue
Block a user