Init Commit

This commit is contained in:
2025-12-12 15:40:34 -03:00
commit 5ddef72f06
78 changed files with 11451 additions and 0 deletions

15
.env.example Normal file
View File

@@ -0,0 +1,15 @@
# Copiar este archivo a .env y completar los valores
# --- SQL SERVER ---
DB_HOST=192.168.x.x,1433
DB_NAME=AdminFacturasApp
DB_USER=gestorFacturasApi
DB_PASSWORD=cambiar_esto
# --- JWT ---
JWT_KEY=cambiar_por_clave_larga_min_32_chars
JWT_ISSUER=GestorFacturasAPI
JWT_AUDIENCE=GestorFacturasFrontend
# --- FRONTEND ---
API_PUBLIC_URL=http://localhost:5000/api

90
.gitignore vendored Normal file
View File

@@ -0,0 +1,90 @@
# ===========================
# SISTEMA OPERATIVO & IDEs
# ===========================
.DS_Store
Thumbs.db
.idea/
.vscode/
*.swp
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio Code / Visual Studio
.vs/
*.njsproj
*.sln
!*.sln # (Opcional: Si quieres versionar la solución, comenta la línea de arriba y descomenta esta. Generalmente sí se versiona el .sln)
# ===========================
# BACKEND (.NET / C#)
# ===========================
# Build results
[Bb]in/
[Oo]bj/
# Nuget
[Pp]ackages/
*.nupkg
*.snupkg
# User-specific files
*.csproj.user
*.pubxml.user
# Configuración local / Secretos
# Mantenemos appsettings.json y appsettings.Development.json
# Pero ignoramos configuraciones locales que puedan contener secretos reales
appsettings.Local.json
appsettings.Production.json
secrets.json
# Logs
*.log
# ===========================
# FRONTEND (React / Vite / Node)
# ===========================
# Dependencies
node_modules/
.pnp
.pnp.js
# Testing coverage
coverage/
# Production build
dist/
build/
dist-ssr/
# Environment variables
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
# Logs
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
# Vite
*.local
# ===========================
# DOCKER & INFRAESTRUCTURA
# ===========================
docker-compose.override.yml
.docker/
# Si mapeaste volúmenes de datos SQL localmente dentro del proyecto (ej: ./sql-data)
sql-data/
mssql_data/
# Archivos temporales
tmp/
temp/

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

View File

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

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

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

View File

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

View 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"]

View 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>

View File

@@ -0,0 +1,6 @@
@GestorFacturas.API_HostAddress = http://localhost:5036
GET {{GestorFacturas.API_HostAddress}}/weatherforecast/
Accept: application/json
###

View 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
}
}
}

View File

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

View 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
}
}
}

View File

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

View 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
}
}
}

View File

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

View 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
}
}
}

View File

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

View 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
}
}
}

View File

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

View 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
}
}
}

View File

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

View 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.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
}
}
}

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

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

View 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
}

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

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

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

View 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"
}
}
}
}

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

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

View File

@@ -0,0 +1,7 @@
namespace GestorFacturas.API.Services.Interfaces;
public interface IEncryptionService
{
string Encrypt(string plainText);
string Decrypt(string cipherText);
}

View File

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

View File

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

View 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;
}
}*/
}

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

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

View File

@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}

View 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": "*"
}

158
README.md Normal file
View File

@@ -0,0 +1,158 @@
---
# 📄 Gestor de Facturas - Sistema Automatizado
![Build Status](https://img.shields.io/badge/Build-Passing-brightgreen)
![Platform](https://img.shields.io/badge/Platform-Docker-blue)
![Backend](https://img.shields.io/badge/.NET-10.0-purple)
![Frontend](https://img.shields.io/badge/React-Vite-cyan)
Sistema integral para la automatización, organización y monitoreo de archivos de facturación electrónica. Este proyecto es la **migración y modernización** del sistema legacy (VB.NET), reimplementado con una arquitectura orientada a microservicios, contenerización y una interfaz web reactiva.
---
## 🚀 Características Principales
* **Procesamiento en Segundo Plano (Worker):** Servicio continuo que monitorea la base de datos del ERP y busca los archivos PDF correspondientes en la red.
* **Lógica de Reintentos Inteligente:** Sistema de reintentos ante fallos de I/O y notificaciones por correo con lógica "anti-spam" (evita alertar repetidamente sobre el mismo error).
* **Dashboard en Tiempo Real:** Interfaz web para visualizar el estado del servicio, próxima ejecución, logs de eventos y estadísticas diarias.
* **Configuración Dinámica:** Permite ajustar la periodicidad (minutos, días, meses), rutas y credenciales sin detener el contenedor.
* **Seguridad:** Autenticación mediante JWT, encriptación de credenciales sensibles en base de datos (AES-256) y protección de rutas.
* **Compatibilidad Legacy:** Replica exactamente la estructura de carpetas y nomenclatura de archivos del sistema anterior para asegurar la continuidad del negocio.
---
## 🛠️ Stack Tecnológico
### Backend (`/Backend`)
* **Framework:** .NET 10.0 (C#)
* **Tipo:** Web API + Hosted Service (Worker)
* **Base de Datos:** SQL Server (Entity Framework Core)
* **Logging:** Serilog (Salida a Consola para integración con Grafana/Loki)
### Frontend (`/frontend`)
* **Framework:** React 24 + TypeScript
* **Build Tool:** Vite
* **Estilos:** Tailwind CSS
* **Estado:** TanStack Query
### Infraestructura
* **Docker:** Orquestación con Docker Compose.
* **Nginx:** Servidor web y Proxy Inverso para la API.
---
## 📦 Instalación y Despliegue
### Prerrequisitos
* Docker y Docker Compose instalados en el servidor.
* Acceso a los volúmenes de red donde se alojan las facturas.
### 1. Clonar el Repositorio
```bash
git clone https://repo.eldiaservicios.com/dmolinari/GestorWebFacturas.git
cd GestorWebFacturas
```
### 2. Configuración de Entorno (.env)
Crea un archivo `.env` en la raíz del proyecto basándote en el siguiente ejemplo.
```ini
# --- BASE DE DATOS SQL SERVER (ERP) ---
DB_HOST=192.168.X.X,1433
DB_NAME=AdminFacturasApp
DB_USER=usuario_sql
DB_PASSWORD=tu_password_seguro
# --- SEGURIDAD (JWT & Encriptación) ---
# Generar claves seguras (mínimo 32 caracteres)
JWT_KEY=Clave_Secreta_Para_Firmar_Tokens_JWT_!
JWT_ISSUER=GestorFacturasAPI
JWT_AUDIENCE=GestorFacturasFrontend
ENCRYPTION_KEY=Clave_32_Bytes_Para_AES_DB_Config
# --- FRONTEND ---
API_PUBLIC_URL=/api
```
### 3. Ejecutar con Docker Compose
```bash
docker-compose up -d --build
```
El sistema estará disponible en el puerto 80 del servidor (o el configurado en el `docker-compose.yml`).
---
## ⚙️ Configuración del Sistema
El sistema utiliza dos niveles de configuración:
### 1. `appsettings.json` (Backend)
Define mapeos estáticos de negocio.
* **EmpresasMapping:** Relaciona códigos de empresa (ej: "0001") con nombres de carpeta (ej: "ELDIA").
* **FacturaTiposMapping:** Define la traducción de tipos de comprobante (ej: "FSR" -> "A", "CAI" -> "NCA").
### 2. Base de Datos (Tabla `Configuraciones`)
Editable desde el **Frontend > Configuración**. Controla:
* Periodicidad de ejecución.
* Rutas de origen y destino (rutas internas del contenedor).
* Credenciales SMTP y de la base de datos externa (se guardan encriptadas).
---
## 📂 Estructura de Directorios y Volúmenes
Para que el sistema funcione, los volúmenes de Docker deben mapearse correctamente a las rutas de red del servidor host.
| Ruta en Contenedor | Descripción | Configuración en Panel Web |
| :--- | :--- | :--- |
| `/app/data/origen` | Carpeta donde el ERP deposita los PDFs originales | `/app/data/origen` |
| `/app/data/destino` | Carpeta donde el sistema organiza los PDFs procesados | `/app/data/destino` |
**Estructura de salida generada:**
```text
/destino
/NOMBRE_EMPRESA
/YYYY-MM (Año-Mes de la factura)
/CLIENTE-EMPRESA-SUCURSAL-TIPO_AJUSTADO-NUMERO (Carpeta)
/CLIENTE-EMPRESA-SUCURSAL-TIPO_ORIGINAL-NUMERO.pdf (Archivo)
```
---
## 🛡️ Notas de Migración (Legacy vs Moderno)
Se han respetado las siguientes reglas críticas para mantener compatibilidad:
1. **Nomenclatura:**
* **Carpeta:** Usa el "Tipo Ajustado" (ej: `NCA` para Notas de Crédito A).
* **Archivo:** Conserva el "Tipo Original" del ERP (ej: `CAI`).
2. **Alertas:**
* El sistema Legacy enviaba correos informativos en cada ejecución.
* El sistema Moderno opera por **Gestión de Excepción**: Solo envía correo si hay errores no reportados previamente (Lógica Anti-Spam / Anti-Fatiga).
3. **Logs:**
* Salida estándar (`stdout`) habilitada para recolección por Grafana/Portainer.
* Registro en base de datos para auditoría interna visible desde el Dashboard.
---
## 👨‍💻 Desarrollo Local
Para levantar el entorno de desarrollo fuera de Docker:
**Backend:**
```bash
cd Backend/GestorFacturas.API
dotnet restore
dotnet user-secrets init
# Configurar secretos locales (ver documentación interna)
dotnet run
```
**Frontend:**
```bash
cd frontend
npm install
npm run dev
```

42
docker-compose.yml Normal file
View File

@@ -0,0 +1,42 @@
services:
# --- BACKEND ---
backend:
build:
context: ./Backend/GestorFacturas.API
dockerfile: Dockerfile
container_name: gestor_facturas_api
restart: always
environment:
- EncryptionKey=${ENCRYPTION_KEY}
# Construcción dinámica de la cadena de conexión
- ConnectionStrings__DefaultConnection=Server=${DB_HOST};Database=${DB_NAME};User Id=${DB_USER};Password=${DB_PASSWORD};TrustServerCertificate=True;MultipleActiveResultSets=true
# Variables de JWT
- Jwt__Key=${JWT_KEY}
- Jwt__Issuer=${JWT_ISSUER}
- Jwt__Audience=${JWT_AUDIENCE}
# Entorno
- ASPNETCORE_ENVIRONMENT=Production
expose:
- "8080"
volumes:
- /mnt/autofs/Facturas:/app/data/origen
- /mnt/autofs/PDFs:/app/data/destino
- ./logs:/app/logs
# --- FRONTEND ---
frontend:
build:
context: ./frontend
dockerfile: Dockerfile
args:
# Pasamos la variable del .env al proceso de build de Docker
- VITE_API_URL=${API_PUBLIC_URL}
container_name: gestor_facturas_web
restart: always
ports:
- "80:80"
depends_on:
- backend

2
frontend/.env.example Normal file
View File

@@ -0,0 +1,2 @@
# Backend API URL
VITE_API_URL=http://localhost:5036/api

24
frontend/.gitignore vendored Normal file
View File

@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

29
frontend/Dockerfile Normal file
View File

@@ -0,0 +1,29 @@
# Etapa 1: Construcción
FROM node:24-alpine AS build
WORKDIR /app
# Argumento para la URL de la API (se pasa desde el docker-compose al construir)
ARG VITE_API_URL
ENV VITE_API_URL=$VITE_API_URL
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# Etapa 2: Servidor Web Nginx
FROM nginx:alpine
WORKDIR /usr/share/nginx/html
# Limpiar default
RUN rm -rf ./*
# Copiar build de React
COPY --from=build /app/dist .
# Copiar configuración de Nginx
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

73
frontend/README.md Normal file
View File

@@ -0,0 +1,73 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Babel](https://babeljs.io/) (or [oxc](https://oxc.rs) when used in [rolldown-vite](https://vite.dev/guide/rolldown)) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules:
```js
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Remove tseslint.configs.recommended and replace with this
tseslint.configs.recommendedTypeChecked,
// Alternatively, use this for stricter rules
tseslint.configs.strictTypeChecked,
// Optionally, add this for stylistic rules
tseslint.configs.stylisticTypeChecked,
// Other configs...
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```
You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules:
```js
// eslint.config.js
import reactX from 'eslint-plugin-react-x'
import reactDom from 'eslint-plugin-react-dom'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
// Other configs...
// Enable lint rules for React
reactX.configs['recommended-typescript'],
// Enable lint rules for React DOM
reactDom.configs.recommended,
],
languageOptions: {
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
// other options...
},
},
])
```

23
frontend/eslint.config.js Normal file
View File

@@ -0,0 +1,23 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
import { defineConfig, globalIgnores } from 'eslint/config'
export default defineConfig([
globalIgnores(['dist']),
{
files: ['**/*.{ts,tsx}'],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
},
])

13
frontend/index.html Normal file
View File

@@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/png" href="/folder.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

23
frontend/nginx.conf Normal file
View File

@@ -0,0 +1,23 @@
server {
listen 80;
root /usr/share/nginx/html;
index index.html;
# 1. Configuración para React Router
location / {
try_files $uri $uri/ /index.html;
}
# 2. PROXY INVERSO
location /api/ {
proxy_pass http://backend:8080;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_cache_bypass $http_upgrade;
}
}

4299
frontend/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

40
frontend/package.json Normal file
View File

@@ -0,0 +1,40 @@
{
"name": "frontend",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"@tanstack/react-query": "^5.90.12",
"axios": "^1.13.2",
"date-fns": "^4.1.0",
"lucide-react": "^0.559.0",
"react": "^19.2.0",
"react-dom": "^19.2.0",
"react-router-dom": "^7.10.1",
"sonner": "^2.0.7"
},
"devDependencies": {
"@eslint/js": "^9.39.1",
"@tailwindcss/postcss": "^4.1.17",
"@types/node": "^24.10.1",
"@types/react": "^19.2.5",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^5.1.1",
"autoprefixer": "^10.4.22",
"eslint": "^9.39.1",
"eslint-plugin-react-hooks": "^7.0.1",
"eslint-plugin-react-refresh": "^0.4.24",
"globals": "^16.5.0",
"postcss": "^8.5.6",
"tailwindcss": "^4.1.17",
"typescript": "~5.9.3",
"typescript-eslint": "^8.46.4",
"vite": "^7.2.4"
}
}

View File

@@ -0,0 +1,6 @@
export default {
plugins: {
'@tailwindcss/postcss': {},
autoprefixer: {},
},
}

BIN
frontend/public/folder.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 44 KiB

42
frontend/src/App.css Normal file
View File

@@ -0,0 +1,42 @@
#root {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.react:hover {
filter: drop-shadow(0 0 2em #61dafbaa);
}
@keyframes logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@media (prefers-reduced-motion: no-preference) {
a:nth-of-type(2) .logo {
animation: logo-spin infinite 20s linear;
}
}
.card {
padding: 2em;
}
.read-the-docs {
color: #888;
}

34
frontend/src/App.tsx Normal file
View File

@@ -0,0 +1,34 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { Toaster } from 'sonner';
import { AuthProvider, useAuth } from './context/AuthContext';
import Login from './components/Login';
import Dashboard from './components/Dashboard/Dashboard';
import './index.css';
const queryClient = new QueryClient({
defaultOptions: {
queries: {
refetchOnWindowFocus: false,
retry: 1,
staleTime: 30000,
},
},
});
// Componente para manejar la lógica de rutas protegidas
function AppContent() {
const { isAuthenticated } = useAuth();
return isAuthenticated ? <Dashboard /> : <Login />;
}
function App() {
return (
<QueryClientProvider client={queryClient}>
<AuthProvider>
<AppContent />
<Toaster position="top-right" richColors closeButton />
</AuthProvider>
</QueryClientProvider>
);
}
export default App;

View File

@@ -0,0 +1,239 @@
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { Database, FolderOpen, Loader2, Info, AlertTriangle } from 'lucide-react';
import { toast } from 'sonner';
import { configuracionApi } from '../../services/api';
import type { Configuracion } from '../../types';
import { Save } from 'lucide-react';
interface ConfiguracionAccesosProps {
configuracion: Configuracion;
onChange: (updates: Partial<Configuracion>) => void;
onSave: () => void; // Nuevo prop
isSaving: boolean; // Nuevo prop
}
export default function ConfiguracionAccesos({ configuracion, onChange, onSave, isSaving }: ConfiguracionAccesosProps) {
const [probandoSQL, setProbandoSQL] = useState(false);
const probarSQLMutation = useMutation({
mutationFn: () =>
configuracionApi.probarConexionSQL({
servidor: configuracion.dbServidor,
nombreDB: configuracion.dbNombre,
usuario: configuracion.dbUsuario,
clave: configuracion.dbClave,
trustedConnection: configuracion.dbTrusted,
}),
onSuccess: (data) => {
if (data.exito) {
toast.success('✓ ' + data.mensaje);
} else {
toast.error('✗ ' + data.mensaje);
}
setProbandoSQL(false);
},
onError: (error) => {
toast.error(`Error: ${error.message}`);
setProbandoSQL(false);
},
});
return (
<div className="space-y-8">
{/* ==============================================
SECCIÓN 1: BASE DE DATOS EXTERNA
============================================== */}
<div className="bg-white rounded-lg">
<div className="flex items-center gap-2 text-primary-600 mb-4 border-b border-gray-100 pb-2">
<Database className="w-5 h-5" />
<h3 className="text-lg font-semibold">Conexión a Base de Datos (DB del Tercero)</h3>
</div>
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="label-text">Servidor SQL Server:</label>
<input
type="text"
value={configuracion.dbServidor}
onChange={(e) => onChange({ dbServidor: e.target.value })}
className="input-field"
placeholder="Ej: FEBO o 192.168.1.X"
/>
</div>
<div>
<label className="label-text">Nombre de Base de Datos:</label>
<input
type="text"
value={configuracion.dbNombre}
onChange={(e) => onChange({ dbNombre: e.target.value })}
className="input-field"
placeholder="Nombre de la BD Externa"
/>
</div>
</div>
{/* Tipo de autenticación */}
<div className="bg-gray-50 p-3 rounded-md border border-gray-200">
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={configuracion.dbTrusted}
onChange={(e) => onChange({ dbTrusted: e.target.checked })}
className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
/>
<span className="text-sm font-medium text-gray-700">
Usar Autenticación de Windows
</span>
</label>
{configuracion.dbTrusted && (
<div className="mt-2 flex items-start gap-2 text-xs text-amber-700 bg-amber-50 p-2 rounded">
<AlertTriangle className="w-4 h-4 mt-0.5 shrink-0" />
<p>
<strong>Atención:</strong> La autenticación de Windows no suele funcionar en contenedores Docker Linux.
Se recomienda usar <strong>Autenticación de SQL Server</strong> (Usuario/Clave).
</p>
</div>
)}
</div>
{/* Credenciales SQL (Mostrar si NO es Trusted o para forzar edición) */}
<div className={`grid grid-cols-1 md:grid-cols-2 gap-4 transition-all duration-300 ${configuracion.dbTrusted ? 'opacity-50 grayscale pointer-events-none' : 'opacity-100'}`}>
<div>
<label className="label-text">Usuario SQL:</label>
<input
type="text"
value={configuracion.dbUsuario || ''}
onChange={(e) => onChange({ dbUsuario: e.target.value })}
className="input-field"
placeholder="Ej: sa"
disabled={configuracion.dbTrusted}
/>
</div>
<div>
<label className="label-text">Contraseña SQL:</label>
<input
type="password"
value={configuracion.dbClave || ''}
onChange={(e) => onChange({ dbClave: e.target.value })}
className="input-field"
placeholder="••••••••"
disabled={configuracion.dbTrusted}
/>
</div>
</div>
{/* Botón probar conexión */}
<div className="flex justify-end pt-2">
<button
onClick={() => {
setProbandoSQL(true);
probarSQLMutation.mutate();
}}
disabled={probandoSQL || !configuracion.dbNombre}
className="btn-secondary flex items-center gap-2 disabled:opacity-50 text-sm"
>
{probandoSQL ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
Conectando...
</>
) : (
<>
<Database className="w-4 h-4" />
Probar Conexión
</>
)}
</button>
</div>
</div>
</div>
{/* ==============================================
SECCIÓN 2: RUTAS DE ARCHIVOS (DOCKER VOLUMES)
============================================== */}
<div className="bg-white rounded-lg">
<div className="flex items-center gap-2 text-primary-600 mb-4 border-b border-gray-100 pb-2">
<FolderOpen className="w-5 h-5" />
<h3 className="text-lg font-semibold">Rutas de Archivos (Volúmenes Docker)</h3>
</div>
{/* Info Box para Docker */}
<div className="mb-6 bg-blue-50 border border-blue-200 rounded-lg p-4 flex items-start gap-3">
<Info className="w-5 h-5 text-blue-600 mt-0.5 shrink-0" />
<div className="text-sm text-blue-800">
<p className="font-semibold mb-1">Configuración para Docker/Linux:</p>
<p>
No uses rutas de Windows (<code>\\servidor\...</code>).
Usa las rutas internas donde montaste los volúmenes en el contenedor.
</p>
</div>
</div>
<div className="space-y-6">
{/* Ruta Origen */}
<div>
<label className="label-text">Ruta Origen (Interna del Contenedor):</label>
<div className="relative">
<input
type="text"
value={configuracion.rutaFacturas}
onChange={(e) => onChange({ rutaFacturas: e.target.value })}
className={`input-field font-mono text-sm pl-9 ${configuracion.rutaFacturas.includes('\\') ? 'border-yellow-400 focus:ring-yellow-400' : ''
}`}
placeholder="/app/data/origen"
/>
<div className="absolute left-3 top-2.5 text-gray-400">
<FolderOpen className="w-4 h-4" />
</div>
</div>
{configuracion.rutaFacturas.includes('\\') && (
<p className="text-xs text-yellow-600 mt-1 flex items-center gap-1">
<AlertTriangle className="w-3 h-3" />
Advertencia: Estás usando barras invertidas (\). Si usas Docker en Linux, usa barras normales (/).
</p>
)}
<p className="text-xs text-gray-500 mt-1 ml-1">
Debe coincidir con el volumen montado en <code>docker-compose.yml</code>
</p>
</div>
{/* Ruta Destino */}
<div>
<label className="label-text">Ruta Destino (Interna del Contenedor):</label>
<div className="relative">
<input
type="text"
value={configuracion.rutaDestino}
onChange={(e) => onChange({ rutaDestino: e.target.value })}
className="input-field font-mono text-sm pl-9"
placeholder="/app/data/destino"
/>
<div className="absolute left-3 top-2.5 text-gray-400">
<FolderOpen className="w-4 h-4" />
</div>
</div>
<p className="text-xs text-gray-500 mt-1 ml-1">
Donde el sistema guardará los archivos procesados
</p>
</div>
</div>
</div>
{/* BOTÓN GUARDAR SECCIÓN (Al final de todo) */}
<div className="flex justify-end pt-6 border-t border-gray-100">
<button
onClick={onSave}
disabled={isSaving}
className="btn-primary flex items-center gap-2 disabled:opacity-50"
>
{isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
Guardar Configuración de Accesos
</button>
</div>
</div >
);
}

View File

@@ -0,0 +1,200 @@
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { Mail, Send, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { configuracionApi } from '../../services/api';
import type { Configuracion } from '../../types';
import { Save } from 'lucide-react';
interface ConfiguracionAlertasProps {
configuracion: Configuracion;
onChange: (updates: Partial<Configuracion>) => void;
onSave: () => void; // Nuevo prop
isSaving: boolean; // Nuevo prop
}
export default function ConfiguracionAlertas({ configuracion, onChange, onSave, isSaving }: ConfiguracionAlertasProps) {
const [probandoSMTP, setProbandoSMTP] = useState(false);
const probarSMTPMutation = useMutation({
mutationFn: () => {
if (!configuracion.smtpServidor || !configuracion.smtpUsuario || !configuracion.smtpDestinatario) {
throw new Error('Completa todos los campos SMTP antes de probar');
}
return configuracionApi.probarSMTP({
servidor: configuracion.smtpServidor,
puerto: configuracion.smtpPuerto,
usuario: configuracion.smtpUsuario,
clave: configuracion.smtpClave || '',
ssl: configuracion.smtpSSL,
destinatario: configuracion.smtpDestinatario,
});
},
onSuccess: (data) => {
if (data.exito) {
toast.success('✓ ' + data.mensaje);
} else {
toast.error('✗ ' + data.mensaje);
}
setProbandoSMTP(false);
},
onError: (error) => {
toast.error(`Error: ${error.message}`);
setProbandoSMTP(false);
},
});
return (
<div className="space-y-6">
<div className="flex items-center gap-2 text-primary-600 mb-4">
<Mail className="w-5 h-5" />
<h3 className="text-lg font-semibold">Configuración de Alertas por Correo</h3>
</div>
<p className="text-sm text-gray-600 mb-6">
Configura el envío de notificaciones por email cuando ocurran errores en el procesamiento.
</p>
{/* Switch para activar/desactivar */}
<div className="bg-gray-50 border border-gray-200 rounded-lg p-4">
<label className="flex items-center justify-between cursor-pointer">
<div>
<span className="text-sm font-medium text-gray-900">Activar Alertas por Correo</span>
<p className="text-xs text-gray-500 mt-1">
Enviar email cuando haya errores en el procesamiento
</p>
</div>
<div className="relative inline-block w-12 h-6">
<input
type="checkbox"
checked={configuracion.avisoMail}
onChange={(e) => onChange({ avisoMail: e.target.checked })}
className="sr-only peer"
/>
<div className="w-12 h-6 bg-gray-300 rounded-full peer peer-checked:bg-green-500 transition-colors"></div>
<div className="absolute left-1 top-1 w-4 h-4 bg-white rounded-full transition-transform peer-checked:translate-x-6"></div>
</div>
</label>
</div>
{/* Configuración SMTP */}
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="label-text">Servidor SMTP:</label>
<input
type="text"
value={configuracion.smtpServidor || ''}
onChange={(e) => onChange({ smtpServidor: e.target.value })}
className="input-field"
placeholder="smtp.ejemplo.com"
disabled={!configuracion.avisoMail}
/>
</div>
<div>
<label className="label-text">Puerto:</label>
<input
type="number"
value={configuracion.smtpPuerto}
onChange={(e) => onChange({ smtpPuerto: parseInt(e.target.value) || 587 })}
className="input-field"
placeholder="587"
disabled={!configuracion.avisoMail}
/>
</div>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<label className="label-text">Usuario SMTP:</label>
<input
type="text"
value={configuracion.smtpUsuario || ''}
onChange={(e) => onChange({ smtpUsuario: e.target.value })}
className="input-field"
placeholder="usuario@ejemplo.com"
disabled={!configuracion.avisoMail}
/>
</div>
<div>
<label className="label-text">Contraseña SMTP:</label>
<input
type="password"
value={configuracion.smtpClave || ''}
onChange={(e) => onChange({ smtpClave: e.target.value })}
className="input-field"
placeholder="••••••••"
disabled={!configuracion.avisoMail}
/>
</div>
</div>
<div>
<label className="label-text">Email Destinatario:</label>
<input
type="email"
value={configuracion.smtpDestinatario || ''}
onChange={(e) => onChange({ smtpDestinatario: e.target.value })}
className="input-field"
placeholder="admin@empresa.com"
disabled={!configuracion.avisoMail}
/>
<p className="text-xs text-gray-500 mt-1">
Dirección que recibirá las alertas de errores
</p>
</div>
<div>
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
checked={configuracion.smtpSSL}
onChange={(e) => onChange({ smtpSSL: e.target.checked })}
className="w-4 h-4 text-primary-600 border-gray-300 rounded focus:ring-primary-500"
disabled={!configuracion.avisoMail}
/>
<span className="text-sm font-medium text-gray-700">
Usar SSL/TLS (Recomendado)
</span>
</label>
</div>
{/* Botón probar SMTP */}
<button
onClick={() => {
setProbandoSMTP(true);
probarSMTPMutation.mutate();
}}
disabled={probandoSMTP || !configuracion.avisoMail || !configuracion.smtpServidor}
className="btn-secondary flex items-center gap-2 disabled:opacity-50"
>
{probandoSMTP ? (
<>
<Loader2 className="w-4 h-4 animate-spin" />
Enviando correo de prueba...
</>
) : (
<>
<Send className="w-4 h-4" />
Enviar Correo de Prueba
</>
)}
</button>
</div>
{/* BOTÓN GUARDAR SECCIÓN */}
<div className="flex justify-end pt-6 border-t border-gray-100 mt-6">
<button
onClick={onSave}
disabled={isSaving}
className="btn-primary flex items-center gap-2 disabled:opacity-50"
>
{isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
Guardar Configuración de Alertas
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,209 @@
import { useState, useEffect } from 'react';
import { useQuery, useMutation } from '@tanstack/react-query';
import { Loader2, Trash2 } from 'lucide-react'; // Agregado Trash2
import { toast } from 'sonner';
import { configuracionApi, operacionesApi } from '../../services/api'; // Agregado operacionesApi
import ConfiguracionTiempos from './ConfiguracionTiempos';
import ConfiguracionAccesos from './ConfiguracionAccesos';
import ConfiguracionAlertas from './ConfiguracionAlertas';
import type { Configuracion } from '../../types';
interface ConfiguracionPanelProps {
onGuardar: () => void;
}
export default function ConfiguracionPanel({ onGuardar }: ConfiguracionPanelProps) {
const [seccionActiva, setSeccionActiva] = useState<'tiempos' | 'accesos' | 'alertas'>('tiempos');
const [showConfirm, setShowConfirm] = useState(false);
const { data: configuracion, isLoading, refetch } = useQuery({
queryKey: ['configuracion'],
queryFn: configuracionApi.obtener,
});
const [formData, setFormData] = useState<Configuracion | null>(null);
// Sincronizar estado local cuando llega la data del servidor
useEffect(() => {
if (configuracion && !formData) {
setFormData(configuracion);
}
}, [configuracion, formData]);
// Mutación para guardar configuración
const guardarMutation = useMutation({
mutationFn: (data: Configuracion) => configuracionApi.actualizar(data),
onSuccess: (data) => {
toast.success('✓ Configuración guardada correctamente');
setFormData(data);
refetch();
onGuardar();
},
onError: (error) => {
toast.error(`Error al guardar: ${error.message}`);
},
});
// --- NUEVO: Mutación para limpiar logs ---
const limpiarLogsMutation = useMutation({
mutationFn: () => operacionesApi.limpiarLogs(30), // Borra logs de +30 días
onSuccess: (data) => {
toast.success(data.mensaje || 'Logs eliminados correctamente');
},
onError: (error) => {
toast.error(`Error al limpiar logs: ${error.message}`);
},
});
// Función genérica que pasaremos a los hijos para guardar
const handleGuardar = () => {
if (!formData) return;
guardarMutation.mutate(formData);
};
// --- NUEVO: Función que faltaba ---
const handleLimpiar = () => {
limpiarLogsMutation.mutate();
};
const secciones = [
{ id: 'tiempos' as const, nombre: 'Tiempos y Periodicidad' },
{ id: 'accesos' as const, nombre: 'Accesos y Rutas' },
{ id: 'alertas' as const, nombre: 'Alertas por Correo' },
];
if (isLoading || !configuracion) {
return (
<div className="card flex items-center justify-center py-12">
<Loader2 className="w-8 h-8 animate-spin text-primary-500" />
<span className="ml-3 text-gray-600">Cargando configuración...</span>
</div>
);
}
const currentData = formData || configuracion;
const isSaving = guardarMutation.isPending;
const hayCambios = JSON.stringify(formData) !== JSON.stringify(configuracion);
return (
<div className="space-y-6">
<div className="card min-h-[500px]">
{/* Header con Título y Botón de Limpieza */}
<div className="flex justify-between items-center mb-6">
<div className="flex items-center gap-4">
<h2 className="text-2xl font-bold text-gray-900">
Configuración del Sistema
</h2>
{/* Indicador Global de Cambios */}
{hayCambios && (
<span className="text-xs font-medium text-amber-600 bg-amber-50 px-2 py-1 rounded-full border border-amber-200 animate-pulse">
Cambios sin guardar
</span>
)}
</div>
{/* Botón para abrir el modal de limpieza */}
<button
onClick={() => setShowConfirm(true)}
className="flex items-center gap-2 px-3 py-2 text-sm font-medium text-red-600 bg-red-50 hover:bg-red-100 rounded-lg transition-colors border border-red-200"
title="Limpiar logs antiguos"
>
<Trash2 className="w-4 h-4" />
<span className="hidden sm:inline">Limpiar Logs</span>
</button>
</div>
{/* Pestañas */}
<div className="border-b border-gray-200 mb-6">
<nav className="flex space-x-8 overflow-x-auto">
{secciones.map((seccion) => (
<button
key={seccion.id}
onClick={() => setSeccionActiva(seccion.id)}
className={`py-4 px-1 border-b-2 font-medium text-sm transition-colors whitespace-nowrap flex items-center gap-2 ${seccionActiva === seccion.id
? 'border-primary-500 text-primary-600'
: 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300'
}`}
>
{seccion.nombre}
{seccionActiva === seccion.id && hayCambios && (
<span className="w-2 h-2 bg-amber-500 rounded-full" title="Hay cambios sin guardar" />
)}
</button>
))}
</nav>
</div>
{/* Contenido */}
<div className="mt-6 pb-6">
{seccionActiva === 'tiempos' && (
<ConfiguracionTiempos
configuracion={currentData}
onChange={(updates) => setFormData((prev) => ({ ...(prev || configuracion), ...updates }))}
onSave={handleGuardar}
isSaving={isSaving}
/>
)}
{seccionActiva === 'accesos' && (
<ConfiguracionAccesos
configuracion={currentData}
onChange={(updates) => setFormData((prev) => ({ ...(prev || configuracion), ...updates }))}
onSave={handleGuardar}
isSaving={isSaving}
/>
)}
{seccionActiva === 'alertas' && (
<ConfiguracionAlertas
configuracion={currentData}
onChange={(updates) => setFormData((prev) => ({ ...(prev || configuracion), ...updates }))}
onSave={handleGuardar}
isSaving={isSaving}
/>
)}
</div>
{/* Modal de Confirmación */}
{showConfirm && (
<div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 backdrop-blur-sm">
<div className="bg-white rounded-lg p-6 max-w-sm w-full shadow-2xl transform transition-all scale-100 animate-in fade-in zoom-in duration-200">
<div className="flex items-center gap-3 mb-4 text-red-600">
<Trash2 className="w-6 h-6" />
<h3 className="text-lg font-bold text-gray-900">¿Estás seguro?</h3>
</div>
<p className="text-gray-600 mb-6 text-sm">
Esta acción eliminará todos los logs con más de <strong>30 días de antigüedad</strong>.
<br /><br />
Esta acción no se puede deshacer.
</p>
<div className="flex justify-end gap-3">
<button
onClick={() => setShowConfirm(false)}
className="px-4 py-2 text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-lg font-medium transition-colors"
>
Cancelar
</button>
<button
onClick={() => {
handleLimpiar();
setShowConfirm(false);
}}
className="px-4 py-2 bg-red-600 text-white hover:bg-red-700 rounded-lg font-medium transition-colors flex items-center gap-2"
>
{limpiarLogsMutation.isPending ? (
<Loader2 className="w-4 h-4 animate-spin" />
) : (
'Sí, eliminar'
)}
</button>
</div>
</div>
</div>
)}
</div>
</div>
);
}

View File

@@ -0,0 +1,158 @@
import { Clock, Save, Loader2, Info } from 'lucide-react';
import type { Configuracion } from '../../types';
import { addMinutes, addDays, addMonths, format } from 'date-fns';
interface ConfiguracionTiemposProps {
configuracion: Configuracion;
onChange: (updates: Partial<Configuracion>) => void;
onSave: () => void;
isSaving: boolean;
}
export default function ConfiguracionTiempos({ configuracion, onChange, onSave, isSaving }: ConfiguracionTiemposProps) {
// Determinamos el valor mínimo según el tipo seleccionado
const minimoPermitido = configuracion.periodicidad === 'Minutos' ? 15 : 1;
const calcularProyeccion = () => {
if (!configuracion.valorPeriodicidad) return null;
const ahora = new Date();
let proxima = ahora;
const tipo = configuracion.periodicidad;
const valor = configuracion.valorPeriodicidad;
if (tipo === 'Minutos') {
proxima = addMinutes(ahora, valor);
} else if (tipo === 'Dias') {
proxima = addDays(ahora, valor);
} else if (tipo === 'Meses') {
proxima = addMonths(ahora, valor);
}
return format(proxima, 'dd/MM/yyyy HH:mm:ss');
};
const proximaEstimada = calcularProyeccion();
// Manejador inteligente para el cambio de tipo
const handleTipoChange = (nuevoTipo: string) => {
let nuevoValor = configuracion.valorPeriodicidad;
// Si cambia a Minutos y el valor es menor a 15, lo corregimos a 15
if (nuevoTipo === 'Minutos' && nuevoValor < 15) {
nuevoValor = 15;
}
// Si cambia a Días/Meses y el valor es 0 o negativo, lo corregimos a 1
else if (nuevoTipo !== 'Minutos' && nuevoValor < 1) {
nuevoValor = 1;
}
onChange({
periodicidad: nuevoTipo,
valorPeriodicidad: nuevoValor
});
};
// Manejador para el cambio de valor numérico
const handleValorChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const val = parseInt(e.target.value) || 0;
// Permitimos escribir, la validación estricta ocurre al cambiar tipo o guardar en backend,
// pero aquí respetamos el min del input HTML para las flechas.
onChange({ valorPeriodicidad: val });
};
// Validación para deshabilitar el botón si no cumple la regla
const esValido = !(configuracion.periodicidad === 'Minutos' && configuracion.valorPeriodicidad < 15) && configuracion.valorPeriodicidad > 0;
return (
<div className="space-y-6">
<div className="flex items-center gap-2 text-primary-600 mb-4">
<Clock className="w-5 h-5" />
<h3 className="text-lg font-semibold">Configuración de Periodicidad</h3>
</div>
<p className="text-sm text-gray-600 mb-6">
Define cada cuánto tiempo debe ejecutarse el proceso de organización de facturas.
</p>
{/* inputs */}
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
<div>
<label className="label-text">Tipo de Periodicidad:</label>
<select
value={configuracion.periodicidad}
onChange={(e) => handleTipoChange(e.target.value)}
className="input-field"
>
<option value="Minutos">Minutos</option>
<option value="Dias">Días</option>
<option value="Meses">Meses</option>
</select>
</div>
<div>
<label className="label-text">Cada cuánto:</label>
<div className="relative">
<input
type="number"
min={minimoPermitido}
value={configuracion.valorPeriodicidad}
onChange={handleValorChange}
className={`input-field ${!esValido ? 'border-red-300 focus:ring-red-200' : ''}`}
/>
{!esValido && (
<span className="absolute right-3 top-2.5 text-xs text-red-500 font-medium">
Mínimo {minimoPermitido}
</span>
)}
</div>
{configuracion.periodicidad === 'Minutos' && (
<p className="text-xs text-gray-500 mt-1 flex items-center gap-1">
<Info className="w-3 h-3" /> Mínimo permitido: 15 minutos
</p>
)}
</div>
{(configuracion.periodicidad === 'Dias' || configuracion.periodicidad === 'Meses') && (
<div>
<label className="label-text">Hora de Ejecución:</label>
<input
type="time"
step="1"
value={configuracion.horaEjecucion}
onChange={(e) => onChange({ horaEjecucion: e.target.value })}
className="input-field"
/>
</div>
)}
</div>
<div className="bg-blue-50 border-l-4 border-blue-400 p-4 rounded-r-lg mt-4">
<div className="flex">
<div className="ml-3">
<p className="text-sm text-blue-700">
<span className="font-bold">Proyección:</span> Si guardas esta configuración,
la próxima ejecución estimada sería alrededor del:
</p>
<p className="text-lg font-bold text-blue-900 mt-1">
{proximaEstimada}
</p>
</div>
</div>
</div>
{/* BOTÓN GUARDAR SECCIÓN */}
<div className="flex justify-end pt-6 border-t border-gray-100 mt-6">
<button
onClick={onSave}
disabled={isSaving || !esValido}
className="btn-primary flex items-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{isSaving ? <Loader2 className="w-4 h-4 animate-spin" /> : <Save className="w-4 h-4" />}
Guardar Cambios
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,124 @@
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { Play, Square, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { configuracionApi } from '../../services/api';
import type { Configuracion } from '../../types';
interface ControlServicioProps {
configuracion?: Configuracion;
onUpdate: () => void;
onExecute: () => void;
}
export default function ControlServicio({ configuracion, onUpdate, onExecute }: ControlServicioProps) {
const [isToggling, setIsToggling] = useState(false);
const toggleMutation = useMutation({
mutationFn: async (nuevoEstado: boolean) => {
if (!configuracion) throw new Error('No hay configuración');
const updated = { ...configuracion, enEjecucion: nuevoEstado };
return configuracionApi.actualizar(updated);
},
onSuccess: (_, nuevoEstado) => {
toast.success(
nuevoEstado ? '✓ Servicio iniciado correctamente' : '⏸️ Servicio detenido'
);
onUpdate();
onExecute();
},
onError: (error) => {
toast.error(`Error al cambiar estado del servicio: ${error.message}`);
},
onSettled: () => {
setIsToggling(false);
},
});
const handleToggle = () => {
if (!configuracion) {
toast.error('No se ha cargado la configuración');
return;
}
// Validar configuración antes de iniciar
if (!configuracion.enEjecucion) {
if (!configuracion.dbNombre || !configuracion.rutaFacturas || !configuracion.rutaDestino) {
toast.error('Debes configurar la base de datos y las rutas antes de iniciar el servicio');
return;
}
}
setIsToggling(true);
toggleMutation.mutate(!configuracion.enEjecucion);
};
const estaActivo = configuracion?.enEjecucion || false;
return (
<div className="card">
<h3 className="text-xl font-bold text-gray-900 mb-4">Control del Servicio</h3>
<div className="flex flex-col items-center justify-center py-8 space-y-6">
{/* Indicador visual */}
<div
className={`w-32 h-32 rounded-full flex items-center justify-center transition-all duration-300 ${estaActivo
? 'bg-green-100 shadow-lg shadow-green-200'
: 'bg-gray-100 shadow-md'
}`}
>
{estaActivo ? (
<div className="relative">
<div className="w-16 h-16 bg-green-500 rounded-full animate-pulse" />
<div className="absolute inset-0 flex items-center justify-center">
<Play className="w-8 h-8 text-white fill-white" />
</div>
</div>
) : (
<Square className="w-18 h-18 text-red-700" />
)}
</div>
{/* Estado textual */}
<div className="text-center">
<p className="text-2xl font-bold text-gray-900">
{estaActivo ? 'Servicio en Ejecución' : 'Servicio Detenido'}
</p>
<p className="text-sm text-gray-600 mt-1">
{estaActivo
? 'El proceso se ejecutará según la periodicidad configurada'
: 'El servicio está pausado y no procesará facturas'}
</p>
</div>
{/* Botón de control */}
<button
onClick={handleToggle}
disabled={isToggling || !configuracion}
className={`flex items-center gap-2 px-8 py-4 rounded-lg font-bold text-lg transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed ${estaActivo
? 'bg-red-500 hover:bg-red-600 text-white shadow-lg hover:shadow-xl'
: 'bg-green-500 hover:bg-green-600 text-white shadow-lg hover:shadow-xl'
}`}
>
{isToggling ? (
<>
<Loader2 className="w-6 h-6 animate-spin" />
Procesando...
</>
) : estaActivo ? (
<>
<Square className="w-6 h-6" />
Detener Servicio
</>
) : (
<>
<Play className="w-6 h-6" />
Iniciar Servicio
</>
)}
</button>
</div>
</div>
);
}

View File

@@ -0,0 +1,88 @@
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { operacionesApi, configuracionApi } from '../../services/api';
import Header from '../Layout/Header';
import ControlServicio from './ControlServicio';
import EstadisticasCards from './EstadisticasCards';
import EjecucionManual from './EjecucionManual';
import TablaEventos from '../Eventos/TablaEventos';
import ConfiguracionPanel from '../Configuracion/ConfiguracionPanel';
// CONFIGURACIÓN CENTRALIZADA DEL TIEMPO DE REFRESCO
const REFRESH_INTERVAL = 5000; // Sugiero bajarlo a 5s para pruebas, luego subirlo a 10s
export default function Dashboard() {
const [vistaActual, setVistaActual] = useState<'dashboard' | 'configuracion'>('dashboard');
// 1. Obtener estadísticas
const { data: estadisticas, refetch: refetchEstadisticas } = useQuery({
queryKey: ['estadisticas'],
queryFn: operacionesApi.obtenerEstadisticas,
refetchInterval: REFRESH_INTERVAL,
// IMPORTANTE: Esto permite que siga actualizando aunque minimices la ventana
refetchIntervalInBackground: true,
// IMPORTANTE: Anulamos el global de 30s para que siempre acepte datos frescos
staleTime: 0,
});
// 2. Obtener configuración
const { data: configuracion, refetch: refetchConfig } = useQuery({
queryKey: ['configuracion'],
queryFn: configuracionApi.obtener,
refetchInterval: REFRESH_INTERVAL,
refetchIntervalInBackground: true, // Permitir actualización en segundo plano
staleTime: 0,
});
return (
<div className="min-h-screen bg-gradient-to-br from-gray-50 to-gray-100">
<Header
vistaActual={vistaActual}
setVistaActual={setVistaActual}
estadisticas={estadisticas}
/>
<main className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
{vistaActual === 'dashboard' ? (
<div className="space-y-8">
{/* Estadísticas */}
<EstadisticasCards
estadisticas={estadisticas}
configuracion={configuracion}
/>
{/* Control del servicio */}
<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
<ControlServicio
configuracion={configuracion}
onUpdate={refetchConfig}
onExecute={refetchEstadisticas}
/>
<EjecucionManual onExecute={refetchEstadisticas} />
</div>
{/* Tabla de eventos */}
<div className="card">
<div className="flex justify-between items-center mb-6">
<h2 className="text-2xl font-bold text-gray-900">
Registro de Eventos
</h2>
<span className="flex items-center gap-2 text-xs font-medium text-green-600 bg-green-50 px-2 py-1 rounded-full border border-green-100 animate-pulse">
<span className="relative flex h-2 w-2">
<span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
<span className="relative inline-flex rounded-full h-2 w-2 bg-green-500"></span>
</span>
En Vivo
</span>
</div>
<TablaEventos refreshInterval={REFRESH_INTERVAL} />
</div>
</div>
) : (
<ConfiguracionPanel onGuardar={refetchConfig} />
)}
</main>
</div>
);
}

View File

@@ -0,0 +1,101 @@
import { useState } from 'react';
import { useMutation } from '@tanstack/react-query';
import { Calendar, PlayCircle, Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { operacionesApi } from '../../services/api';
interface EjecucionManualProps {
onExecute: () => void;
}
export default function EjecucionManual({ onExecute }: EjecucionManualProps) {
const [fechaDesde, setFechaDesde] = useState<string>(
new Date().toISOString().split('T')[0]
);
const ejecutarMutation = useMutation({
mutationFn: () => operacionesApi.ejecutarManual({ fechaDesde }),
onSuccess: () => {
toast.success('✓ Proceso iniciado correctamente');
toast.info('Revisa los eventos para ver el progreso');
onExecute();
},
onError: (error) => {
toast.error(`Error al ejecutar: ${error.message}`);
},
});
const handleEjecutar = () => {
if (!fechaDesde) {
toast.error('Debes seleccionar una fecha');
return;
}
ejecutarMutation.mutate();
};
return (
<div className="card">
<h3 className="text-xl font-bold text-gray-900 mb-4">
Ejecución Manual
</h3>
<p className="text-sm text-gray-600 mb-6">
Ejecuta el proceso inmediatamente sin esperar al cronograma programado.
Selecciona la fecha desde la cual buscar facturas.
</p>
<div className="space-y-4">
{/* Selector de fecha */}
<div>
<label htmlFor="fechaDesde" className="label-text">
Fecha desde:
</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Calendar className="w-5 h-5 text-gray-400" />
</div>
<input
type="date"
id="fechaDesde"
value={fechaDesde}
onChange={(e) => setFechaDesde(e.target.value)}
max={new Date().toISOString().split('T')[0]}
className="input-field pl-10"
/>
</div>
<p className="text-xs text-gray-500 mt-1">
Se procesarán todas las facturas desde esta fecha hasta hoy
</p>
</div>
{/* Botón de ejecución */}
<button
onClick={handleEjecutar}
disabled={ejecutarMutation.isPending || !fechaDesde}
className="w-full btn-primary flex items-center justify-center gap-2 disabled:opacity-50 disabled:cursor-not-allowed"
>
{ejecutarMutation.isPending ? (
<>
<Loader2 className="w-5 h-5 animate-spin" />
Ejecutando proceso...
</>
) : (
<>
<PlayCircle className="w-5 h-5" />
Ejecutar Ahora
</>
)}
</button>
{/* Información adicional */}
<div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
<p className="text-sm text-blue-800">
<strong>Nota:</strong> El proceso se ejecutará en segundo plano. Los resultados
aparecerán en la tabla de eventos más abajo.
</p>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,114 @@
import { Activity, AlertCircle, CheckCircle2, Info } from 'lucide-react';
import type { Estadisticas, Configuracion } from '../../types';
import ExecutionCard from './ExecutionCard';
interface EstadisticasCardsProps {
estadisticas?: Estadisticas;
configuracion?: Configuracion;
}
export default function EstadisticasCards({ estadisticas, configuracion }: EstadisticasCardsProps) {
// Extraemos los valores para usarlos más fácilmente
const errores = estadisticas?.eventosHoy?.errores || 0;
const advertencias = estadisticas?.eventosHoy?.advertencias || 0;
const standardCards = [
{
titulo: 'Estado Último Proceso',
valor: estadisticas?.ultimaEjecucion
? estadisticas.estado
? 'Exitoso'
: 'Con Fallas'
: 'Sin datos',
icono: estadisticas?.estado ? CheckCircle2 : AlertCircle,
color: estadisticas?.estado ? 'text-green-600 bg-green-50' : 'text-red-600 bg-red-50',
borde: estadisticas?.estado ? 'border-green-100' : 'border-red-100',
},
{
titulo: 'Eventos de Hoy',
valor: estadisticas?.eventosHoy?.total?.toString() || '0',
subtext: 'Registros totales',
extraInfo: (
<div className="flex flex-wrap gap-1">
{errores > 0 && (
<span className="text-xs font-bold text-red-600 bg-red-50 px-2 py-0.5 rounded-full border border-red-100">
{errores} errores
</span>
)}
{advertencias > 0 && (
<span className="text-xs font-bold text-amber-600 bg-amber-50 px-2 py-0.5 rounded-full border border-amber-100">
{advertencias} advert.
</span>
)}
{errores === 0 && advertencias === 0 && (
<span className="text-xs text-gray-400">Sin incidentes</span>
)}
</div>
),
icono: Activity,
color: 'text-purple-600 bg-purple-50',
// Lógica de color del borde basada directamente en los valores
borde: errores > 0 ? 'border-red-200' : (advertencias > 0 ? 'border-amber-200' : 'border-purple-100'),
},
{
titulo: 'Informativos de Hoy',
valor: estadisticas?.eventosHoy?.info?.toString() || '0',
subtext: 'Logs informativos',
icono: Info,
color: 'text-blue-600 bg-blue-50',
borde: 'border-blue-100',
},
];
return (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
{/* 1. Tarjeta Timeline */}
<div className="h-full">
<ExecutionCard
ultimaEjecucion={configuracion?.ultimaEjecucion}
proximaEjecucion={configuracion?.proximaEjecucion}
enEjecucion={configuracion?.enEjecucion ?? false}
/>
</div>
{/* 2, 3, 4. Tarjetas Estándar */}
{standardCards.map((card, index) => {
const Icono = card.icono;
return (
<div
key={index}
className={`bg-white rounded-lg shadow-sm border p-4 h-full flex flex-col justify-between hover:shadow-md transition-shadow ${card.borde || 'border-gray-200'}`}
>
{/* Parte Superior: Título e Icono */}
<div className="flex justify-between items-start mb-2">
<span className="text-xs font-bold text-gray-500 uppercase tracking-wider">
{card.titulo}
</span>
<div className={`p-2 rounded-lg ${card.color}`}>
<Icono className="w-5 h-5" />
</div>
</div>
{/* Parte Inferior: Valor Grande y Detalles */}
<div className="mt-2">
<p className="text-3xl font-bold text-gray-900 tracking-tight">
{card.valor}
</p>
<div className="flex items-center gap-2 mt-1 min-h-[24px]">
{card.extraInfo ? (
card.extraInfo
) : (
<p className="text-xs text-gray-400 font-medium">
{card.subtext || '\u00A0'}
</p>
)}
</div>
</div>
</div>
);
})}
</div>
);
}

View File

@@ -0,0 +1,106 @@
import { Clock, PauseCircle, Hourglass } from 'lucide-react';
import { format, formatDistanceToNow, isPast, addSeconds } from 'date-fns';
import { es } from 'date-fns/locale';
interface ExecutionCardProps {
ultimaEjecucion: string | null | undefined;
proximaEjecucion: string | null | undefined;
enEjecucion: boolean;
}
export default function ExecutionCard({ ultimaEjecucion, proximaEjecucion, enEjecucion }: ExecutionCardProps) {
const formatDate = (dateString: string) => {
return format(new Date(dateString), "dd/MM, HH:mm", { locale: es }); // Formato más corto
};
const formatRelative = (dateString: string) => {
return formatDistanceToNow(new Date(dateString), { addSuffix: true, locale: es });
};
const isOverdue = proximaEjecucion ? isPast(addSeconds(new Date(proximaEjecucion), -10)) : false;
return (
<div className="bg-white rounded-lg shadow-sm border border-gray-200 relative overflow-hidden flex flex-col h-full hover:shadow-md transition-shadow">
{/* Barra de estado */}
<div className={`h-1 w-full ${enEjecucion ? 'bg-green-500' : 'bg-gray-300'}`} />
<div className="p-4 flex-1 flex flex-col"> {/* Padding reducido a p-4 */}
{/* Encabezado Compacto */}
<div className="flex justify-between items-center mb-3"> {/* Margin reducido */}
<div className="flex items-center gap-2">
<Clock className="w-4 h-4 text-gray-400" />
<span className="text-xs font-bold text-gray-500 uppercase tracking-wider">
Sincronización
</span>
</div>
<span className={`text-[10px] font-bold px-1.5 py-0.5 rounded border ${enEjecucion
? 'bg-green-50 text-green-700 border-green-200'
: 'bg-gray-50 text-gray-600 border-gray-200'
}`}>
{enEjecucion ? 'AUTO' : 'MANUAL'}
</span>
</div>
<div className="space-y-4 pl-1 flex-1 flex flex-col justify-center"> {/* Espaciado reducido a space-y-4 */}
{/* ÚLTIMA EJECUCIÓN */}
<div className="relative pl-5 border-l-2 border-gray-100">
<div className="absolute -left-[5px] top-1.5 w-2 h-2 rounded-full bg-gray-300 ring-2 ring-white" />
<p className="text-[10px] text-gray-400 font-medium uppercase mb-0.5">Última</p>
{ultimaEjecucion ? (
<div>
<p className="text-sm font-semibold text-gray-800">
{formatRelative(ultimaEjecucion)}
</p>
<p className="text-[10px] text-gray-400">
{formatDate(ultimaEjecucion)}
</p>
</div>
) : (
<p className="text-xs text-gray-400 italic">--</p>
)}
</div>
{/* PRÓXIMA EJECUCIÓN */}
<div className="relative pl-5 border-l-2 border-transparent">
<div className={`absolute -left-[5px] top-1.5 w-2 h-2 rounded-full ring-2 ring-white transition-colors duration-500 ${enEjecucion ? (isOverdue ? 'bg-amber-500' : 'bg-green-500') : 'bg-gray-300'
}`} />
<p className="text-[10px] text-gray-400 font-medium uppercase mb-0.5">Próxima</p>
{enEjecucion && proximaEjecucion ? (
<div className="animate-in fade-in duration-500">
{isOverdue ? (
<div>
<p className="text-sm font-bold text-amber-600 flex items-center gap-1.5">
En cola...
<Hourglass className="w-3 h-3 animate-spin-slow" />
</p>
</div>
) : (
<div>
<p className="text-sm font-bold text-primary-700">
{formatDate(proximaEjecucion)} hs
</p>
<p className="text-[10px] text-primary-600/70">
aprox. {formatRelative(proximaEjecucion)}
</p>
</div>
)}
</div>
) : (
<div className="text-xs text-gray-400 font-medium flex items-center gap-1">
<PauseCircle className="w-3 h-3" /> Detenido
</div>
)}
</div>
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,223 @@
import { useState } from 'react';
import { useQuery } from '@tanstack/react-query';
import { AlertCircle, Info, AlertTriangle, ChevronLeft, ChevronRight, RefreshCw, Search, Copy, Check } from 'lucide-react';
import { format } from 'date-fns';
import { es } from 'date-fns/locale';
import { operacionesApi } from '../../services/api';
import type { Evento } from '../../types';
import { toast } from 'sonner';
// Definimos las props para recibir el intervalo desde el padre
interface TablaEventosProps {
refreshInterval?: number;
}
export default function TablaEventos({ refreshInterval = 30000 }: TablaEventosProps) {
const [pageNumber, setPageNumber] = useState(1);
const [tipoFiltro, setTipoFiltro] = useState<string>('');
const [busqueda, setBusqueda] = useState('');
const pageSize = 15;
const CopyButton = ({ text }: { text: string }) => {
const [copied, setCopied] = useState(false);
const handleCopy = () => {
navigator.clipboard.writeText(text);
setCopied(true);
toast.success("Mensaje copiado");
setTimeout(() => setCopied(false), 2000);
};
return (
<button
onClick={handleCopy}
className="text-gray-400 hover:text-primary-600 p-1 rounded transition-colors"
title="Copiar mensaje"
>
{copied ? <Check className="w-4 h-4 text-green-500" /> : <Copy className="w-4 h-4" />}
</button>
);
};
const { data, isLoading, refetch, isFetching } = useQuery({
queryKey: ['eventos', pageNumber, tipoFiltro],
queryFn: () => operacionesApi.obtenerLogs(pageNumber, pageSize, tipoFiltro || undefined),
refetchInterval: refreshInterval,
refetchIntervalInBackground: true, // Clave para que no se detenga al cambiar de pestaña
staleTime: 0, // Asegura que React Query sepa que los datos "caducan" inmediatamente
placeholderData: (previousData) => previousData,
});
const getTipoIcon = (tipo: string) => {
switch (tipo) {
case 'Error': return <AlertCircle className="w-5 h-5 text-red-500" />;
case 'Warning': return <AlertTriangle className="w-5 h-5 text-yellow-500" />;
default: return <Info className="w-5 h-5 text-blue-500" />;
}
};
const getTipoClass = (tipo: string) => {
switch (tipo) {
case 'Error': return 'bg-red-50 text-red-700 border-red-200';
case 'Warning': return 'bg-yellow-50 text-yellow-700 border-yellow-200';
default: return 'bg-blue-50 text-blue-700 border-blue-200';
}
};
const renderMensaje = (msg: string) => {
const parts = msg.split(/(\S+\.pdf)/g);
return (
<span>
{parts.map((part, i) =>
part.endsWith('.pdf') ? (
<span key={i} className="font-mono text-xs bg-gray-100 px-1 py-0.5 rounded border border-gray-300 font-semibold text-gray-800">
{part}
</span>
) : part
)}
</span>
);
};
// Filtrado simple en cliente para la búsqueda (si la API no tiene endpoint de búsqueda textual)
// Si la API soporta búsqueda, deberías añadir 'busqueda' al queryKey y a la llamada API.
const itemsFiltrados = data?.items?.filter(item =>
item.mensaje.toLowerCase().includes(busqueda.toLowerCase())
) ?? [];
return (
<div className="space-y-4">
{/* Filtros y acciones */}
<div className="flex flex-wrap justify-between items-center gap-4">
<div className="flex items-center gap-2">
<label className="text-sm font-medium text-gray-700">Filtrar por tipo:</label>
<select
value={tipoFiltro}
onChange={(e) => {
setTipoFiltro(e.target.value);
setPageNumber(1);
}}
className="px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500"
>
<option value="">Todos</option>
<option value="Info">Información</option>
<option value="Warning">Advertencia</option>
<option value="Error">Error</option>
</select>
</div>
<div className="relative flex-1 min-w-[200px]">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Search className="h-4 w-4 text-gray-400" />
</div>
<input
type="text"
placeholder="Buscar en esta página..."
value={busqueda}
onChange={(e) => setBusqueda(e.target.value)}
className="input-field pl-9 py-2 text-sm"
/>
</div>
<button
onClick={() => refetch()}
disabled={isFetching}
className="flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors disabled:opacity-50"
>
<RefreshCw className={`w-4 h-4 ${isFetching ? 'animate-spin' : ''}`} />
{/* Ocultar texto en móvil para ahorrar espacio */}
<span className="hidden sm:inline">Actualizar</span>
</button>
</div>
{/* Tabla */}
<div className="overflow-x-auto border border-gray-200 rounded-lg">
<table className="min-w-full divide-y divide-gray-200">
<thead className="bg-gray-50">
<tr>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-48">Fecha</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider w-32">Tipo</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Mensaje</th>
</tr>
</thead>
<tbody className="bg-white divide-y divide-gray-200">
{isLoading ? (
<tr>
<td colSpan={3} className="px-6 py-12 text-center">
<div className="flex items-center justify-center">
<RefreshCw className="w-6 h-6 animate-spin text-primary-500" />
<span className="ml-2 text-gray-600">Cargando eventos...</span>
</div>
</td>
</tr>
) : itemsFiltrados.length > 0 ? (
itemsFiltrados.map((evento: Evento) => (
<tr key={evento.id} className="hover:bg-gray-50 transition-colors">
<td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 font-mono">
{format(new Date(evento.fecha), 'dd/MM/yyyy HH:mm:ss', { locale: es })}
</td>
<td className="px-6 py-4 whitespace-nowrap">
<span className={`inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium border ${getTipoClass(evento.tipo)}`}>
{getTipoIcon(evento.tipo)}
{evento.tipo}
</span>
</td>
<td className="px-6 py-4 text-sm text-gray-700">
<div className="flex justify-between items-start gap-2 group">
<span className="break-all">{renderMensaje(evento.mensaje)}</span>
<div className="opacity-0 group-hover:opacity-100 transition-opacity">
<CopyButton text={evento.mensaje} />
</div>
</div>
</td>
</tr>
))
) : (
<tr>
<td colSpan={3} className="px-6 py-16 text-center">
<div className="flex flex-col items-center justify-center text-gray-400">
<div className="bg-gray-50 p-4 rounded-full mb-3">
<AlertCircle className="w-8 h-8 text-gray-300" />
</div>
<p className="text-lg font-medium text-gray-900">Sin eventos</p>
<p className="text-sm">No hay registros para mostrar.</p>
</div>
</td>
</tr>
)}
</tbody>
</table>
</div>
{/* Paginación */}
{data && data.totalPages > 1 && (
<div className="flex items-center justify-between border-t border-gray-200 pt-4">
<div className="text-sm text-gray-700 hidden sm:block">
Página <span className="font-medium">{pageNumber}</span> de <span className="font-medium">{data.totalPages}</span>
</div>
<div className="flex gap-2 w-full sm:w-auto justify-between sm:justify-end">
<button
onClick={() => setPageNumber((p) => Math.max(1, p - 1))}
disabled={pageNumber === 1}
className="flex items-center gap-1 px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm"
>
<ChevronLeft className="w-4 h-4" />
Anterior
</button>
<button
onClick={() => setPageNumber((p) => Math.min(data.totalPages, p + 1))}
disabled={pageNumber === data.totalPages}
className="flex items-center gap-1 px-3 py-2 border border-gray-300 rounded-lg hover:bg-gray-50 disabled:opacity-50 disabled:cursor-not-allowed transition-colors text-sm"
>
Siguiente
<ChevronRight className="w-4 h-4" />
</button>
</div>
</div>
)}
</div>
);
}

View File

@@ -0,0 +1,130 @@
import { FileText, Settings, LogOut, User } from 'lucide-react';
import { useAuth } from '../../context/AuthContext';
import { authApi } from '../../services/api';
import { getRefreshToken } from '../../utils/storage';
import { toast } from 'sonner';
import type { Estadisticas } from '../../types';
interface HeaderProps {
vistaActual: 'dashboard' | 'configuracion';
setVistaActual: (vista: 'dashboard' | 'configuracion') => void;
estadisticas?: Estadisticas;
}
export default function Header({ vistaActual, setVistaActual, estadisticas }: HeaderProps) {
const { usuario, logout } = useAuth();
const handleLogout = async () => {
try {
// 1. Intentar invalidar en el servidor (Seguridad)
const token = getRefreshToken();
if (token) {
await authApi.logout(token);
}
} catch (error) {
console.error('Error al notificar cierre de sesión al servidor', error);
// No bloqueamos el logout visual si falla el servidor
} finally {
// 2. Limpiar cliente y redirigir (UX)
logout();
toast.success('Sesión cerrada correctamente');
}
};
return (
<header className="bg-white shadow-sm border-b border-gray-200">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex justify-between items-center py-4">
{/* Logo y Título */}
<div className="flex flex-col sm:flex-row sm:items-center space-y-2 sm:space-y-0 sm:space-x-4">
<div className="flex items-center gap-3">
<div className="bg-primary-600 rounded-lg p-2.5 shadow-lg shadow-primary-500/30">
<FileText className="w-6 h-6 text-white" />
</div>
<div>
<h1 className="text-xl font-bold text-gray-900 flex items-center gap-2">
Gestor de Facturas
{/* Indicador visible en móvil (punto simple) */}
<span className={`flex md:hidden h-3 w-3 rounded-full ${estadisticas?.enEjecucion ? 'bg-green-500 animate-pulse' : 'bg-gray-400'}`} />
</h1>
<div className="flex items-center gap-1 text-xs text-gray-500 font-medium">
<User className="w-3 h-3" />
<span>{usuario}</span>
</div>
</div>
</div>
</div>
{/* Estado del servicio y Navegación */}
<div className="flex items-center gap-6">
{/* Indicador de Estado (Solo visible en desktop) */}
<div className="hidden md:flex items-center gap-2 bg-gray-50 px-3 py-1.5 rounded-full border border-gray-100 group cursor-help relative">
{/* Tooltip nativo simple */}
<div className="absolute top-full mt-2 left-1/2 -translate-x-1/2 w-48 bg-gray-800 text-white text-xs rounded py-1 px-2 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none z-10 text-center">
{estadisticas?.enEjecucion
? "El worker está activo buscando facturas nuevas automáticamente."
: "El servicio está detenido. No se procesarán facturas."}
</div>
<div className="relative">
<div
className={`w-2.5 h-2.5 rounded-full transition-colors ${estadisticas?.enEjecucion ? 'bg-green-500' : 'bg-gray-400'
}`}
/>
{/* Anillo de pulso animado solo si está activo */}
{estadisticas?.enEjecucion && (
<div className="absolute inset-0 rounded-full bg-green-500 animate-ping opacity-75"></div>
)}
</div>
<span className="text-xs font-medium text-gray-600">
{estadisticas?.enEjecucion ? 'Monitor Activo' : 'Servicio Detenido'}
</span>
</div>
{/* Separador vertical */}
<div className="h-8 w-px bg-gray-200 hidden md:block"></div>
{/* Botones de acción */}
<div className="flex items-center gap-2">
<button
onClick={() => setVistaActual('dashboard')}
className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${vistaActual === 'dashboard'
? 'bg-primary-50 text-primary-700 ring-1 ring-primary-200'
: 'text-gray-600 hover:bg-gray-50'
}`}
>
<FileText className="w-4 h-4" />
Dashboard
</button>
<button
onClick={() => setVistaActual('configuracion')}
className={`flex items-center gap-2 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${vistaActual === 'configuracion'
? 'bg-primary-50 text-primary-700 ring-1 ring-primary-200'
: 'text-gray-600 hover:bg-gray-50'
}`}
>
<Settings className="w-4 h-4" />
Configuración
</button>
{/* Botón Cerrar Sesión */}
<button
onClick={handleLogout}
className="flex items-center gap-2 px-3 py-2 ml-2 rounded-lg text-sm font-medium text-red-600 hover:bg-red-50 hover:text-red-700 transition-colors border border-transparent hover:border-red-100"
title="Cerrar Sesión"
>
<LogOut className="w-4 h-4" />
<span className="hidden md:inline">Salir</span>
</button>
</div>
</div>
</div>
</div>
</header>
);
}

View File

@@ -0,0 +1,123 @@
import React, { useState } from 'react';
import axios from 'axios';
import { toast } from 'sonner';
import { Lock, User, Building2, Eye, EyeOff } from 'lucide-react';
import { useAuth } from '../context/AuthContext';
export default function Login() {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [rememberMe, setRememberMe] = useState(false);
const [loading, setLoading] = useState(false);
const [showPassword, setShowPassword] = useState(false);
const { login } = useAuth();
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setLoading(true);
try {
const API_URL = import.meta.env.VITE_API_URL || 'http://localhost:5000/api';
const { data } = await axios.post(`${API_URL}/auth/login`, {
username,
password,
rememberMe // true o false
});
// Pasamos rememberMe al contexto para que decida el storage
login(data.token, data.refreshToken, data.usuario, rememberMe);
toast.success(rememberMe ? 'Sesión segura por 30 días' : 'Bienvenido');
} catch (error) {
console.error(error);
toast.error('Credenciales inválidas');
} finally {
setLoading(false);
}
};
return (
<div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-gray-100 to-gray-200">
<div className="bg-white p-8 rounded-xl shadow-xl w-full max-w-md border border-gray-100">
<div className="flex justify-center mb-6">
<div className="bg-primary-600 p-3 rounded-xl">
<Building2 className="w-10 h-10 text-white" />
</div>
</div>
<div className="text-center mb-8">
<h2 className="text-2xl font-bold text-gray-900">Iniciar Sesión</h2>
<p className="text-gray-500 mt-2">Gestor de Facturas El Día</p>
</div>
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Usuario</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<User className="h-5 w-5 text-gray-400" />
</div>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="input-field pl-10"
placeholder="admin"
required
/>
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-2">Contraseña</label>
<div className="relative">
<div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
<Lock className="h-5 w-5 text-gray-400" />
</div>
<input
type={showPassword ? "text" : "password"} // Toggle tipo
value={password}
onChange={(e) => setPassword(e.target.value)}
className="input-field pl-10 pr-10" // Padding derecho extra para el ojo
placeholder="••••••"
required
/>
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute inset-y-0 right-0 pr-3 flex items-center cursor-pointer text-gray-400 hover:text-gray-600"
>
{showPassword ? <EyeOff className="h-5 w-5" /> : <Eye className="h-5 w-5" />}
</button>
</div>
</div>
{/* CHECKBOX REMEMBER ME */}
<div className="flex items-center">
<input
id="remember-me"
type="checkbox"
checked={rememberMe}
onChange={(e) => setRememberMe(e.target.checked)}
className="h-4 w-4 text-primary-600 focus:ring-primary-500 border-gray-300 rounded cursor-pointer"
/>
<label htmlFor="remember-me" className="ml-2 block text-sm text-gray-900 cursor-pointer select-none">
Mantener sesión iniciada por 30 días
</label>
</div>
<button
type="submit"
disabled={loading}
className="w-full btn-primary flex justify-center py-3"
>
{loading ? 'Ingresando...' : 'Ingresar'}
</button>
</form>
<div className="mt-6 text-center text-xs text-gray-400">
Versión 1.0.0 &copy; 2025 El Día
</div>
</div>
</div>
);
}

View File

@@ -0,0 +1,44 @@
import { createContext, useContext, useState, type ReactNode } from 'react';
import { getToken, getUsuario, setAuthData, clearAuthData } from '../utils/storage';
interface AuthContextType {
usuario: string | null;
login: (token: string, refreshToken: string, usuario: string, rememberMe: boolean) => void;
logout: () => void;
isAuthenticated: boolean;
}
const AuthContext = createContext<AuthContextType | null>(null);
export const AuthProvider = ({ children }: { children: ReactNode }) => {
// Inicializamos leyendo de cualquiera de los dos storages
const [token, setToken] = useState<string | null>(getToken());
const [usuario, setUsuario] = useState<string | null>(getUsuario());
const login = (newToken: string, newRefreshToken: string, newUser: string, rememberMe: boolean) => {
// Usamos la utilidad para guardar en el lugar correcto
setAuthData(newToken, newRefreshToken, newUser, rememberMe);
setToken(newToken);
setUsuario(newUser);
};
const logout = () => {
clearAuthData();
setToken(null);
setUsuario(null);
window.location.href = '/';
};
return (
<AuthContext.Provider value={{ usuario, login, logout, isAuthenticated: !!token }}>
{children}
</AuthContext.Provider>
);
};
export const useAuth = () => {
const context = useContext(AuthContext);
if (!context) throw new Error('useAuth must be used within an AuthProvider');
return context;
};

85
frontend/src/index.css Normal file
View File

@@ -0,0 +1,85 @@
@import "tailwindcss";
@theme {
--color-primary-50: #f0f9ff;
--color-primary-100: #e0f2fe;
--color-primary-200: #bae6fd;
--color-primary-300: #7dd3fc;
--color-primary-400: #38bdf8;
--color-primary-500: #0ea5e9;
--color-primary-600: #0284c7;
--color-primary-700: #0369a1;
--color-primary-800: #075985;
--color-primary-900: #0c4a6e;
}
:root {
font-family: 'Inter', system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;
color-scheme: light;
color: #1f2937;
/* text-gray-800 - oscuro para fondos claros */
background-color: #f5f5f5;
font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
margin: 0;
display: flex;
min-width: 320px;
min-height: 100vh;
color: #1f2937;
}
#root {
width: 100%;
}
@layer components {
.card {
@apply bg-white rounded-lg shadow-md p-6;
}
.btn-primary {
@apply bg-primary-600 hover:bg-primary-700 text-white font-semibold py-2 px-4 rounded-lg transition-colors duration-200;
}
.btn-secondary {
@apply bg-gray-200 hover:bg-gray-300 text-gray-800 font-semibold py-2 px-4 rounded-lg transition-colors duration-200;
}
.input-field {
@apply w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-primary-500 focus:border-transparent text-gray-900 bg-white;
}
.label-text {
@apply block text-sm font-medium text-gray-700 mb-1;
}
}
/* Estilos adicionales para inputs, selects y textareas */
input,
select,
textarea {
color: #111827 !important;
/* text-gray-900 - texto oscuro */
background-color: white !important;
}
input::placeholder,
textarea::placeholder {
color: #9ca3af;
/* text-gray-400 - placeholder gris claro */
}
/* Asegurar que los options en select sean legibles */
select option {
color: #111827;
background-color: white;
}

10
frontend/src/main.tsx Normal file
View File

@@ -0,0 +1,10 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import './index.css'
import App from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)

View File

@@ -0,0 +1,129 @@
import axios from 'axios';
import type {
Configuracion,
Evento,
PagedResult,
Estadisticas,
ProbarConexionDto,
ProbarSMTPDto,
EjecucionManualDto,
ApiResponse,
} from '../types';
import { clearAuthData, getRefreshToken, getToken, updateTokens } from '../utils/storage';
const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:5000/api';
const api = axios.create({
baseURL: API_BASE_URL,
headers: {
'Content-Type': 'application/json',
},
});
// Interceptor Request
api.interceptors.request.use((config) => {
const token = getToken(); // Usa la utilidad que busca en ambos
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Interceptor Response
api.interceptors.response.use(
(response) => response,
async (error) => {
const originalRequest = error.config;
if (error.response?.status === 401 && !originalRequest._retry) {
originalRequest._retry = true;
try {
const refreshToken = getRefreshToken(); // Usa la utilidad
if (!refreshToken) throw new Error('No refresh token');
const { data } = await axios.post(`${API_BASE_URL}/auth/refresh-token`, {
token: refreshToken
});
// IMPORTANTE: Actualizamos en el storage correspondiente
updateTokens(data.token, data.refreshToken);
originalRequest.headers.Authorization = `Bearer ${data.token}`;
return api(originalRequest);
} catch (refreshError) {
console.error('Sesión expirada', refreshError);
clearAuthData();
window.location.href = '/';
return Promise.reject(refreshError);
}
}
return Promise.reject(error);
}
);
// ===== CONFIGURACIÓN =====
export const configuracionApi = {
obtener: async (): Promise<Configuracion> => {
const { data } = await api.get<Configuracion>('/configuracion');
return data;
},
actualizar: async (config: Configuracion): Promise<Configuracion> => {
const { data } = await api.put<Configuracion>('/configuracion', config);
return data;
},
probarConexionSQL: async (dto: ProbarConexionDto): Promise<ApiResponse> => {
const { data } = await api.post<ApiResponse>('/configuracion/probar-conexion-sql', dto);
return data;
},
probarSMTP: async (dto: ProbarSMTPDto): Promise<ApiResponse> => {
const { data } = await api.post<ApiResponse>('/configuracion/probar-smtp', dto);
return data;
},
};
// ===== OPERACIONES =====
export const operacionesApi = {
ejecutarManual: async (dto: EjecucionManualDto): Promise<ApiResponse> => {
const { data } = await api.post<ApiResponse>('/operaciones/ejecutar-manual', dto);
return data;
},
obtenerLogs: async (
pageNumber: number = 1,
pageSize: number = 20,
tipo?: string
): Promise<PagedResult<Evento>> => {
const params: any = { pageNumber, pageSize };
if (tipo) params.tipo = tipo;
const { data } = await api.get<PagedResult<Evento>>('/operaciones/logs', { params });
return data;
},
obtenerEstadisticas: async (): Promise<Estadisticas> => {
const { data } = await api.get<Estadisticas>('/operaciones/estadisticas');
return data;
},
limpiarLogs: async (diasAntiguedad: number = 30): Promise<ApiResponse> => {
const { data } = await api.delete<ApiResponse>('/operaciones/logs/limpiar', {
params: { diasAntiguedad },
});
return data;
},
};
export const authApi = {
logout: async (refreshToken: string) => {
// No esperamos respuesta, es un "fire and forget" para el usuario
return api.post('/auth/revoke', { token: refreshToken });
}
};
export default api;

View File

@@ -0,0 +1,81 @@
// Tipos y interfaces para el sistema de gestión de facturas
export interface Configuracion {
id: number;
periodicidad: string;
valorPeriodicidad: number;
horaEjecucion: string;
ultimaEjecucion: string | null;
proximaEjecucion?: string | null;
estado: boolean;
enEjecucion: boolean;
dbServidor: string;
dbNombre: string;
dbUsuario: string | null;
dbClave: string | null;
dbTrusted: boolean;
rutaFacturas: string;
rutaDestino: string;
smtpServidor: string | null;
smtpPuerto: number;
smtpUsuario: string | null;
smtpClave: string | null;
smtpSSL: boolean;
smtpDestinatario: string | null;
avisoMail: boolean;
}
export interface Evento {
id: number;
fecha: string;
mensaje: string;
tipo: 'Info' | 'Error' | 'Warning';
enviado: boolean;
}
export interface PagedResult<T> {
items: T[];
totalCount: number;
pageNumber: number;
pageSize: number;
totalPages: number;
}
export interface Estadisticas {
ultimaEjecucion: string | null;
estado: boolean;
enEjecucion: boolean;
eventosHoy: {
total: number;
errores: number;
advertencias: number;
info: number;
};
}
export interface ProbarConexionDto {
servidor: string;
nombreDB: string;
usuario: string | null;
clave: string | null;
trustedConnection: boolean;
}
export interface ProbarSMTPDto {
servidor: string;
puerto: number;
usuario: string;
clave: string;
ssl: boolean;
destinatario: string;
}
export interface EjecucionManualDto {
fechaDesde: string;
}
export interface ApiResponse<T = any> {
exito?: boolean;
mensaje?: string;
data?: T;
}

View File

@@ -0,0 +1,44 @@
// Detecta dónde están guardados los tokens actualmente
export const getStorageType = (): 'local' | 'session' | null => {
if (localStorage.getItem('token')) return 'local';
if (sessionStorage.getItem('token')) return 'session';
return null;
};
export const getToken = () => {
return localStorage.getItem('token') || sessionStorage.getItem('token');
};
export const getRefreshToken = () => {
return localStorage.getItem('refreshToken') || sessionStorage.getItem('refreshToken');
};
export const getUsuario = () => {
return localStorage.getItem('usuario') || sessionStorage.getItem('usuario');
};
export const setAuthData = (token: string, refreshToken: string, usuario: string, rememberMe: boolean) => {
const storage = rememberMe ? localStorage : sessionStorage;
// Limpiamos el otro storage por si acaso había residuos
if (rememberMe) sessionStorage.clear();
else localStorage.clear();
storage.setItem('token', token);
storage.setItem('refreshToken', refreshToken);
storage.setItem('usuario', usuario);
};
export const updateTokens = (token: string, refreshToken: string) => {
// Detectamos dónde están guardados para actualizarlos en el mismo lugar
const type = getStorageType();
const storage = type === 'local' ? localStorage : sessionStorage;
storage.setItem('token', token);
storage.setItem('refreshToken', refreshToken);
};
export const clearAuthData = () => {
localStorage.clear();
sessionStorage.clear();
};

View File

@@ -0,0 +1,26 @@
/** @type {import('tailwindcss').Config} */
export default {
content: [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme: {
extend: {
colors: {
primary: {
50: '#f0f9ff',
100: '#e0f2fe',
200: '#bae6fd',
300: '#7dd3fc',
400: '#38bdf8',
500: '#0ea5e9',
600: '#0284c7',
700: '#0369a1',
800: '#075985',
900: '#0c4a6e',
},
},
},
},
plugins: [],
}

View File

@@ -0,0 +1,28 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2022",
"useDefineForClassFields": true,
"lib": ["ES2022", "DOM", "DOM.Iterable"],
"module": "ESNext",
"types": ["vite/client"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

7
frontend/tsconfig.json Normal file
View File

@@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2023",
"lib": ["ES2023"],
"module": "ESNext",
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

17
frontend/vite.config.ts Normal file
View File

@@ -0,0 +1,17 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
proxy: {
// Cuando el frontend pida "/api", Vite lo redirigirá al backend
'/api': {
target: 'http://localhost:5036',
changeOrigin: true,
secure: false,
}
}
}
})