Init Commit
This commit is contained in:
74
Backend/GestorFacturas.API/Services/AuthService.cs
Normal file
74
Backend/GestorFacturas.API/Services/AuthService.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using System.IdentityModel.Tokens.Jwt;
|
||||
using System.Security.Claims;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using Microsoft.IdentityModel.Tokens;
|
||||
using GestorFacturas.API.Models;
|
||||
using GestorFacturas.API.Data;
|
||||
using BCrypt.Net;
|
||||
|
||||
namespace GestorFacturas.API.Services;
|
||||
|
||||
public class AuthService
|
||||
{
|
||||
private readonly IConfiguration _config;
|
||||
private readonly ApplicationDbContext _context;
|
||||
|
||||
public AuthService(IConfiguration config, ApplicationDbContext context)
|
||||
{
|
||||
_config = config;
|
||||
_context = context;
|
||||
}
|
||||
|
||||
public bool VerificarPassword(string password, string hash)
|
||||
{
|
||||
try { return BCrypt.Net.BCrypt.Verify(password, hash); } catch { return false; }
|
||||
}
|
||||
|
||||
public string GenerarHash(string password)
|
||||
{
|
||||
return BCrypt.Net.BCrypt.HashPassword(password);
|
||||
}
|
||||
|
||||
// Generar JWT (Access Token) - Vida corta (ej. 15 min)
|
||||
public string GenerarAccessToken(Usuario usuario)
|
||||
{
|
||||
var keyStr = _config["Jwt:Key"] ?? throw new InvalidOperationException("Jwt:Key no configurada");
|
||||
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(keyStr));
|
||||
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
||||
|
||||
var claims = new[]
|
||||
{
|
||||
new Claim(ClaimTypes.NameIdentifier, usuario.Id.ToString()),
|
||||
new Claim(ClaimTypes.Name, usuario.Username)
|
||||
};
|
||||
|
||||
var token = new JwtSecurityToken(
|
||||
_config["Jwt:Issuer"],
|
||||
_config["Jwt:Audience"],
|
||||
claims,
|
||||
expires: DateTime.UtcNow.AddMinutes(15),
|
||||
signingCredentials: credentials);
|
||||
|
||||
return new JwtSecurityTokenHandler().WriteToken(token);
|
||||
}
|
||||
|
||||
// Generar Refresh Token - Vida larga (ej. 7 días)
|
||||
public RefreshToken GenerarRefreshToken(int usuarioId, bool isPersistent)
|
||||
{
|
||||
// Si es persistente: 30 días.
|
||||
// Si NO es persistente: 12 horas.
|
||||
var duracion = isPersistent ? TimeSpan.FromDays(30) : TimeSpan.FromHours(12);
|
||||
|
||||
var refreshToken = new RefreshToken
|
||||
{
|
||||
Token = Convert.ToBase64String(RandomNumberGenerator.GetBytes(64)),
|
||||
Expires = DateTime.UtcNow.Add(duracion),
|
||||
Created = DateTime.UtcNow,
|
||||
UsuarioId = usuarioId,
|
||||
IsPersistent = isPersistent
|
||||
};
|
||||
|
||||
return refreshToken;
|
||||
}
|
||||
}
|
||||
78
Backend/GestorFacturas.API/Services/EncryptionService.cs
Normal file
78
Backend/GestorFacturas.API/Services/EncryptionService.cs
Normal file
@@ -0,0 +1,78 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using GestorFacturas.API.Services.Interfaces;
|
||||
|
||||
namespace GestorFacturas.API.Services;
|
||||
|
||||
public class EncryptionService : IEncryptionService
|
||||
{
|
||||
private readonly string _key;
|
||||
|
||||
public EncryptionService(IConfiguration config)
|
||||
{
|
||||
// La clave debe venir del .env / appsettings
|
||||
_key = config["EncryptionKey"] ?? throw new ArgumentNullException("EncryptionKey no configurada");
|
||||
|
||||
// Ajustar si la clave no tiene el tamaño correcto (AES-256 requiere 32 bytes)
|
||||
// Aquí hacemos un hash SHA256 de la clave para asegurar que siempre tenga 32 bytes válidos
|
||||
using var sha256 = SHA256.Create();
|
||||
var keyBytes = sha256.ComputeHash(Encoding.UTF8.GetBytes(_key));
|
||||
_key = Convert.ToBase64String(keyBytes);
|
||||
}
|
||||
|
||||
public string Encrypt(string plainText)
|
||||
{
|
||||
if (string.IsNullOrEmpty(plainText)) return plainText;
|
||||
|
||||
var key = Convert.FromBase64String(_key);
|
||||
using var aes = Aes.Create();
|
||||
aes.Key = key;
|
||||
aes.GenerateIV(); // Generar vector de inicialización aleatorio
|
||||
|
||||
using var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
|
||||
using var ms = new MemoryStream();
|
||||
|
||||
// Escribir el IV al principio del stream (necesario para desencriptar)
|
||||
ms.Write(aes.IV, 0, aes.IV.Length);
|
||||
|
||||
using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
|
||||
using (var sw = new StreamWriter(cs))
|
||||
{
|
||||
sw.Write(plainText);
|
||||
}
|
||||
|
||||
return Convert.ToBase64String(ms.ToArray());
|
||||
}
|
||||
|
||||
public string Decrypt(string cipherText)
|
||||
{
|
||||
if (string.IsNullOrEmpty(cipherText)) return cipherText;
|
||||
|
||||
try
|
||||
{
|
||||
var fullCipher = Convert.FromBase64String(cipherText);
|
||||
var key = Convert.FromBase64String(_key);
|
||||
|
||||
using var aes = Aes.Create();
|
||||
aes.Key = key;
|
||||
|
||||
// Extraer el IV (los primeros 16 bytes)
|
||||
var iv = new byte[16];
|
||||
Array.Copy(fullCipher, 0, iv, 0, iv.Length);
|
||||
aes.IV = iv;
|
||||
|
||||
using var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
|
||||
using var ms = new MemoryStream(fullCipher, 16, fullCipher.Length - 16);
|
||||
using var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read);
|
||||
using var sr = new StreamReader(cs);
|
||||
|
||||
return sr.ReadToEnd();
|
||||
}
|
||||
catch
|
||||
{
|
||||
// Si falla al desencriptar (ej. porque el dato viejo no estaba encriptado),
|
||||
// devolvemos el texto original para no romper la app en la migración.
|
||||
return cipherText;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
namespace GestorFacturas.API.Services.Interfaces;
|
||||
|
||||
public interface IEncryptionService
|
||||
{
|
||||
string Encrypt(string plainText);
|
||||
string Decrypt(string cipherText);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
namespace GestorFacturas.API.Services.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Interfaz para el servicio de envío de correos electrónicos
|
||||
/// </summary>
|
||||
public interface IMailService
|
||||
{
|
||||
/// <summary>
|
||||
/// Envía un correo electrónico
|
||||
/// </summary>
|
||||
/// <param name="destinatario">Dirección del destinatario</param>
|
||||
/// <param name="asunto">Asunto del correo</param>
|
||||
/// <param name="cuerpo">Cuerpo del mensaje (puede incluir HTML)</param>
|
||||
/// <param name="esHTML">Indica si el cuerpo es HTML</param>
|
||||
Task<bool> EnviarCorreoAsync(string destinatario, string asunto, string cuerpo, bool esHTML = true);
|
||||
|
||||
/// <summary>
|
||||
/// Prueba la configuración SMTP
|
||||
/// </summary>
|
||||
Task<bool> ProbarConexionAsync();
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
namespace GestorFacturas.API.Services.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Interfaz para el servicio principal de procesamiento de facturas
|
||||
/// </summary>
|
||||
public interface IProcesadorFacturasService
|
||||
{
|
||||
/// <summary>
|
||||
/// Ejecuta el proceso de búsqueda y organización de facturas
|
||||
/// </summary>
|
||||
/// <param name="fechaDesde">Fecha desde la cual buscar facturas</param>
|
||||
Task EjecutarProcesoAsync(DateTime fechaDesde);
|
||||
}
|
||||
143
Backend/GestorFacturas.API/Services/MailService.cs
Normal file
143
Backend/GestorFacturas.API/Services/MailService.cs
Normal file
@@ -0,0 +1,143 @@
|
||||
using MailKit.Net.Smtp;
|
||||
using MailKit.Security;
|
||||
using MimeKit;
|
||||
using GestorFacturas.API.Data;
|
||||
using GestorFacturas.API.Services.Interfaces;
|
||||
using GestorFacturas.API.Models;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace GestorFacturas.API.Services;
|
||||
|
||||
public class MailService : IMailService
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly ILogger<MailService> _logger;
|
||||
private readonly IEncryptionService _encryptionService;
|
||||
|
||||
public MailService(ApplicationDbContext context, ILogger<MailService> logger, IEncryptionService encryptionService)
|
||||
{
|
||||
_context = context;
|
||||
_logger = logger;
|
||||
_encryptionService = encryptionService;
|
||||
}
|
||||
|
||||
public async Task<bool> EnviarCorreoAsync(string destinatario, string asunto, string cuerpo, bool esHTML = true)
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
|
||||
if (config == null || string.IsNullOrEmpty(config.SMTPServidor))
|
||||
{
|
||||
_logger.LogWarning("No hay configuración SMTP disponible");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!config.AvisoMail)
|
||||
{
|
||||
_logger.LogInformation("Envío de correos desactivado en configuración");
|
||||
return false;
|
||||
}
|
||||
|
||||
// --- CORRECCIÓN AQUÍ ---
|
||||
// Desencriptamos las credenciales AL PRINCIPIO para usarlas en el 'From' y en el 'Authenticate'
|
||||
string usuarioSmtp = string.IsNullOrEmpty(config.SMTPUsuario)
|
||||
? "sistema@eldia.com"
|
||||
: _encryptionService.Decrypt(config.SMTPUsuario);
|
||||
|
||||
string claveSmtp = string.IsNullOrEmpty(config.SMTPClave)
|
||||
? ""
|
||||
: _encryptionService.Decrypt(config.SMTPClave);
|
||||
// -----------------------
|
||||
|
||||
var mensaje = new MimeMessage();
|
||||
// Usamos la variable desencriptada
|
||||
mensaje.From.Add(new MailboxAddress("Gestor Facturas El Día", usuarioSmtp));
|
||||
mensaje.To.Add(MailboxAddress.Parse(destinatario));
|
||||
mensaje.Subject = asunto;
|
||||
|
||||
var builder = new BodyBuilder();
|
||||
if (esHTML) builder.HtmlBody = cuerpo;
|
||||
else builder.TextBody = cuerpo;
|
||||
|
||||
mensaje.Body = builder.ToMessageBody();
|
||||
|
||||
using var cliente = new SmtpClient();
|
||||
|
||||
// Bypass de certificado SSL para redes internas
|
||||
cliente.ServerCertificateValidationCallback = (s, c, h, e) => true;
|
||||
|
||||
var secureSocketOptions = config.SMTPSSL
|
||||
? SecureSocketOptions.StartTls
|
||||
: SecureSocketOptions.Auto;
|
||||
|
||||
await cliente.ConnectAsync(config.SMTPServidor, config.SMTPPuerto, secureSocketOptions);
|
||||
|
||||
// Usamos las variables que ya desencriptamos arriba
|
||||
if (!string.IsNullOrEmpty(usuarioSmtp) && !string.IsNullOrEmpty(claveSmtp))
|
||||
{
|
||||
await cliente.AuthenticateAsync(usuarioSmtp, claveSmtp);
|
||||
}
|
||||
|
||||
await cliente.SendAsync(mensaje);
|
||||
await cliente.DisconnectAsync(true);
|
||||
|
||||
_logger.LogInformation("Correo enviado exitosamente a {destinatario}", destinatario);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al enviar correo a {destinatario}", destinatario);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> ProbarConexionAsync()
|
||||
{
|
||||
// Este método no se está usando actualmente en el flujo crítico (usamos ProbarSMTP en el controller),
|
||||
// pero por consistencia deberías aplicar la misma lógica de desencriptación si planeas usarlo.
|
||||
return true;
|
||||
}
|
||||
|
||||
/*
|
||||
public async Task<bool> ProbarConexionAsync()
|
||||
{
|
||||
try
|
||||
{
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
|
||||
if (config == null || string.IsNullOrEmpty(config.SMTPServidor))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
using var cliente = new SmtpClient();
|
||||
|
||||
cliente.ServerCertificateValidationCallback = (s, c, h, e) => true;
|
||||
|
||||
var secureSocketOptions = config.SMTPSSL
|
||||
? SecureSocketOptions.StartTls
|
||||
: SecureSocketOptions.Auto;
|
||||
|
||||
await cliente.ConnectAsync(config.SMTPServidor, config.SMTPPuerto, secureSocketOptions);
|
||||
|
||||
if (!string.IsNullOrEmpty(config.SMTPUsuario) && !string.IsNullOrEmpty(config.SMTPClave))
|
||||
{
|
||||
// DESENCRIPTAR AQUÍ
|
||||
var usuario = _encryptionService.Decrypt(config.SMTPUsuario);
|
||||
var clave = _encryptionService.Decrypt(config.SMTPClave);
|
||||
|
||||
await cliente.AuthenticateAsync(usuario, clave);
|
||||
}
|
||||
|
||||
await cliente.DisconnectAsync(true);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al probar conexión SMTP");
|
||||
return false;
|
||||
}
|
||||
}*/
|
||||
}
|
||||
483
Backend/GestorFacturas.API/Services/ProcesadorFacturasService.cs
Normal file
483
Backend/GestorFacturas.API/Services/ProcesadorFacturasService.cs
Normal file
@@ -0,0 +1,483 @@
|
||||
using Microsoft.Data.SqlClient;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using GestorFacturas.API.Data;
|
||||
using GestorFacturas.API.Models;
|
||||
using GestorFacturas.API.Services.Interfaces;
|
||||
using System.Data;
|
||||
|
||||
namespace GestorFacturas.API.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Servicio principal de procesamiento de facturas.
|
||||
/// </summary>
|
||||
public class ProcesadorFacturasService : IProcesadorFacturasService
|
||||
{
|
||||
private readonly ApplicationDbContext _context;
|
||||
private readonly ILogger<ProcesadorFacturasService> _logger;
|
||||
private readonly IMailService _mailService;
|
||||
private readonly IEncryptionService _encryptionService;
|
||||
private readonly IConfiguration _configuration;
|
||||
|
||||
private const int MAX_REINTENTOS = 10;
|
||||
private const int DELAY_SEGUNDOS = 60;
|
||||
|
||||
public ProcesadorFacturasService(
|
||||
ApplicationDbContext context,
|
||||
ILogger<ProcesadorFacturasService> logger,
|
||||
IMailService mailService,
|
||||
IEncryptionService encryptionService,
|
||||
IConfiguration configuration)
|
||||
{
|
||||
_context = context;
|
||||
_logger = logger;
|
||||
_mailService = mailService;
|
||||
_encryptionService = encryptionService;
|
||||
_configuration = configuration;
|
||||
}
|
||||
|
||||
public async Task EjecutarProcesoAsync(DateTime fechaDesde)
|
||||
{
|
||||
var config = await _context.Configuraciones.FirstOrDefaultAsync(c => c.Id == 1);
|
||||
if (config == null)
|
||||
{
|
||||
await RegistrarEventoAsync("No se encontró configuración del sistema", TipoEvento.Error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Actualizamos la fecha de ejecución
|
||||
config.UltimaEjecucion = DateTime.Now;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
await RegistrarEventoAsync($"Iniciando proceso de facturas desde {fechaDesde:dd/MM/yyyy}", TipoEvento.Info);
|
||||
|
||||
try
|
||||
{
|
||||
var facturas = await ObtenerFacturasDesdeERPAsync(config, fechaDesde);
|
||||
|
||||
if (facturas.Count == 0)
|
||||
{
|
||||
await RegistrarEventoAsync($"No se encontraron facturas desde {fechaDesde:dd/MM/yyyy}", TipoEvento.Warning);
|
||||
config.Estado = true;
|
||||
await _context.SaveChangesAsync();
|
||||
return;
|
||||
}
|
||||
|
||||
await RegistrarEventoAsync($"Se encontraron {facturas.Count} facturas para procesar", TipoEvento.Info);
|
||||
|
||||
int procesadas = 0;
|
||||
int errores = 0;
|
||||
List<FacturaParaProcesar> pendientes = new();
|
||||
List<string> detallesErroresParaMail = new();
|
||||
|
||||
// Lista para rastrear las entidades de Evento y actualizar su flag 'Enviado' luego
|
||||
List<Evento> eventosDeErrorParaActualizar = new();
|
||||
|
||||
// --- 1. Primer intento ---
|
||||
foreach (var factura in facturas)
|
||||
{
|
||||
bool exito = await ProcesarFacturaAsync(factura, config);
|
||||
if (exito) procesadas++;
|
||||
else pendientes.Add(factura);
|
||||
}
|
||||
|
||||
// --- 2. Sistema de Reintentos ---
|
||||
if (pendientes.Count > 0)
|
||||
{
|
||||
await RegistrarEventoAsync($"{pendientes.Count} archivos no encontrados. Iniciando sistema de reintentos...", TipoEvento.Warning);
|
||||
|
||||
for (int intento = 1; intento <= MAX_REINTENTOS && pendientes.Count > 0; intento++)
|
||||
{
|
||||
await Task.Delay(TimeSpan.FromSeconds(DELAY_SEGUNDOS));
|
||||
|
||||
var aunPendientes = new List<FacturaParaProcesar>();
|
||||
|
||||
foreach (var factura in pendientes)
|
||||
{
|
||||
bool exito = await ProcesarFacturaAsync(factura, config);
|
||||
if (exito)
|
||||
{
|
||||
procesadas++;
|
||||
_logger.LogInformation("Archivo encontrado en reintento {intento}: {archivo}", intento, factura.NombreArchivoOrigen);
|
||||
}
|
||||
else
|
||||
{
|
||||
aunPendientes.Add(factura);
|
||||
}
|
||||
}
|
||||
pendientes = aunPendientes;
|
||||
}
|
||||
|
||||
// --- 3. Registro de Errores Finales ---
|
||||
if (pendientes.Count > 0)
|
||||
{
|
||||
errores = pendientes.Count;
|
||||
foreach (var factura in pendientes)
|
||||
{
|
||||
string msgError = $"El archivo NO EXISTE después de {MAX_REINTENTOS} intentos: {factura.NombreArchivoOrigen}";
|
||||
|
||||
var eventoError = new Evento
|
||||
{
|
||||
Fecha = DateTime.Now,
|
||||
Mensaje = msgError,
|
||||
Tipo = TipoEvento.Error.ToString(),
|
||||
Enviado = false
|
||||
};
|
||||
|
||||
_context.Eventos.Add(eventoError);
|
||||
|
||||
// Guardamos referencias
|
||||
eventosDeErrorParaActualizar.Add(eventoError);
|
||||
detallesErroresParaMail.Add(factura.NombreArchivoOrigen);
|
||||
}
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
|
||||
// --- 4. Actualización de Estado General ---
|
||||
config.Estado = errores == 0;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
// --- 5. Limpieza automática ---
|
||||
try
|
||||
{
|
||||
var fechaLimiteBorrado = DateTime.Now.AddMonths(-1);
|
||||
var eventosViejos = _context.Eventos.Where(e => e.Fecha < fechaLimiteBorrado);
|
||||
if (eventosViejos.Any())
|
||||
{
|
||||
_context.Eventos.RemoveRange(eventosViejos);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
catch { }
|
||||
|
||||
// --- 6. Evento Final ---
|
||||
var mensajeFinal = $"Proceso finalizado. Procesadas: {procesadas}, Errores: {errores}";
|
||||
await RegistrarEventoAsync(mensajeFinal, errores > 0 ? TipoEvento.Warning : TipoEvento.Info);
|
||||
|
||||
// --- 7. Envío de Mail Inteligente (Solo 1 vez por archivo) ---
|
||||
if (errores > 0 && config.AvisoMail && !string.IsNullOrEmpty(config.SMTPDestinatario))
|
||||
{
|
||||
// 1. Buscamos en la historia de la DB si estos archivos ya fueron reportados previamente.
|
||||
// Buscamos en TODOS los logs disponibles (que suelen ser los últimos 30 días según la limpieza).
|
||||
// Filtramos por Tipo Error y Enviado=true.
|
||||
var historialErroresEnviados = await _context.Eventos
|
||||
.Where(e => e.Tipo == TipoEvento.Error.ToString() && e.Enviado == true)
|
||||
.Select(e => e.Mensaje)
|
||||
.ToListAsync();
|
||||
|
||||
// 2. Filtramos la lista actual:
|
||||
// Solo queremos los archivos que NO aparezcan en ningún mensaje del historial.
|
||||
var archivosNuevosParaNotificar = detallesErroresParaMail.Where(archivoFallido =>
|
||||
{
|
||||
// El mensaje en BD es: "El archivo NO EXISTE...: nombre_archivo.pdf"
|
||||
// Chequeamos si el nombre del archivo está contenido en algún mensaje viejo.
|
||||
bool yaFueNotificado = historialErroresEnviados.Any(msgHistorico => msgHistorico.Contains(archivoFallido));
|
||||
return !yaFueNotificado;
|
||||
}).ToList();
|
||||
|
||||
// 3. Decidir si enviar mail
|
||||
bool mailEnviado = false;
|
||||
|
||||
if (archivosNuevosParaNotificar.Count > 0)
|
||||
{
|
||||
// Si hay archivos NUEVOS, enviamos mail SOLO con esos.
|
||||
// Nota: Pasamos 'errores' (total técnico) y 'archivosNuevosParaNotificar' (detalle visual)
|
||||
mailEnviado = await EnviarNotificacionErroresAsync(
|
||||
config.SMTPDestinatario,
|
||||
procesadas,
|
||||
errores,
|
||||
archivosNuevosParaNotificar
|
||||
);
|
||||
|
||||
if (mailEnviado)
|
||||
{
|
||||
_logger.LogInformation("Correo de alerta enviado con {count} archivos nuevos.", archivosNuevosParaNotificar.Count);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
_logger.LogInformation("Se omitió el envío de correo: Los {count} errores ya fueron notificados anteriormente.", errores);
|
||||
// Simulamos que se "envió" (se gestionó) para marcar los flags en BD
|
||||
mailEnviado = true;
|
||||
}
|
||||
|
||||
// 4. Actualizar flag en BD (CRÍTICO)
|
||||
// Si gestionamos la notificación correctamente (ya sea enviándola o detectando que ya estaba enviada),
|
||||
// marcamos los eventos actuales como Enviado=true para que pasen al historial y no se vuelvan a procesar.
|
||||
if (mailEnviado && eventosDeErrorParaActualizar.Count > 0)
|
||||
{
|
||||
foreach (var evento in eventosDeErrorParaActualizar)
|
||||
{
|
||||
evento.Enviado = true;
|
||||
}
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error crítico en el proceso de facturas");
|
||||
string mensajeCritico = $"ERROR CRÍTICO DEL SISTEMA: {ex.Message}";
|
||||
|
||||
await RegistrarEventoAsync(mensajeCritico, TipoEvento.Error);
|
||||
|
||||
if (config != null)
|
||||
{
|
||||
config.Estado = false;
|
||||
await _context.SaveChangesAsync();
|
||||
|
||||
if (config.AvisoMail && !string.IsNullOrEmpty(config.SMTPDestinatario))
|
||||
{
|
||||
var listaErroresCriticos = new List<string> { mensajeCritico };
|
||||
await EnviarNotificacionErroresAsync(config.SMTPDestinatario, 0, 1, listaErroresCriticos);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<List<FacturaParaProcesar>> ObtenerFacturasDesdeERPAsync(Configuracion config, DateTime fechaDesde)
|
||||
{
|
||||
var facturas = new List<FacturaParaProcesar>();
|
||||
var connectionString = ConstruirCadenaConexion(config);
|
||||
|
||||
try
|
||||
{
|
||||
using var conexion = new SqlConnection(connectionString);
|
||||
await conexion.OpenAsync();
|
||||
|
||||
var query = @"
|
||||
SELECT DISTINCT
|
||||
NUMERO_FACTURA,
|
||||
TIPO_FACTURA,
|
||||
CLIENTE,
|
||||
SUCURSAL_FACTURA,
|
||||
DIVISION_FACTURA,
|
||||
FECHACOMPLETA_FACTURA,
|
||||
NRO_CAI
|
||||
FROM VISTA_FACTURACION_ELDIA
|
||||
WHERE SUCURSAL_FACTURA = '70'
|
||||
AND NRO_CAI IS NOT NULL
|
||||
AND NRO_CAI != ''
|
||||
AND FECHACOMPLETA_FACTURA >= @FechaDesde
|
||||
AND CONVERT(DATE, FECHACOMPLETA_FACTURA) <= CONVERT(DATE, GETDATE())
|
||||
ORDER BY FECHACOMPLETA_FACTURA DESC";
|
||||
|
||||
using var comando = new SqlCommand(query, conexion);
|
||||
comando.Parameters.AddWithValue("@FechaDesde", fechaDesde);
|
||||
|
||||
using var reader = await comando.ExecuteReaderAsync();
|
||||
|
||||
while (await reader.ReadAsync())
|
||||
{
|
||||
var factura = new FacturaParaProcesar
|
||||
{
|
||||
NumeroFactura = (reader["NUMERO_FACTURA"].ToString() ?? "").Trim().PadLeft(10, '0'),
|
||||
TipoFactura = (reader["TIPO_FACTURA"].ToString() ?? "").Trim(),
|
||||
Cliente = (reader["CLIENTE"].ToString() ?? "").Trim().PadLeft(6, '0'),
|
||||
Sucursal = (reader["SUCURSAL_FACTURA"].ToString() ?? "").Trim().PadLeft(4, '0'),
|
||||
CodigoEmpresa = (reader["DIVISION_FACTURA"].ToString() ?? "").Trim().PadLeft(4, '0'),
|
||||
FechaFactura = Convert.ToDateTime(reader["FECHACOMPLETA_FACTURA"])
|
||||
};
|
||||
|
||||
factura.NombreEmpresa = MapearNombreEmpresa(factura.CodigoEmpresa);
|
||||
factura.NombreArchivoOrigen = ConstruirNombreArchivoOrigen(factura);
|
||||
factura.NombreArchivoDestino = ConstruirNombreArchivoDestino(factura);
|
||||
factura.CarpetaDestino = ConstruirRutaCarpetaDestino(factura);
|
||||
|
||||
facturas.Add(factura);
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
await RegistrarEventoAsync($"Error al conectar con el ERP: {ex.Message}", TipoEvento.Error);
|
||||
throw;
|
||||
}
|
||||
|
||||
return facturas;
|
||||
}
|
||||
|
||||
private async Task<bool> ProcesarFacturaAsync(FacturaParaProcesar factura, Configuracion config)
|
||||
{
|
||||
try
|
||||
{
|
||||
string rutaBaseOrigen = config.RutaFacturas;
|
||||
string rutaBaseDestino = config.RutaDestino;
|
||||
|
||||
string rutaOrigen = Path.Combine(rutaBaseOrigen, factura.NombreArchivoOrigen);
|
||||
string carpetaDestinoFinal = Path.Combine(rutaBaseDestino, factura.CarpetaDestino);
|
||||
|
||||
if (!File.Exists(rutaOrigen)) return false;
|
||||
|
||||
if (!Directory.Exists(carpetaDestinoFinal))
|
||||
{
|
||||
Directory.CreateDirectory(carpetaDestinoFinal);
|
||||
}
|
||||
|
||||
string rutaDestinoCompleta = Path.Combine(carpetaDestinoFinal, factura.NombreArchivoDestino);
|
||||
FileInfo infoOrigen = new FileInfo(rutaOrigen);
|
||||
FileInfo infoDestino = new FileInfo(rutaDestinoCompleta);
|
||||
|
||||
if (infoDestino.Exists)
|
||||
{
|
||||
if (infoDestino.Length == infoOrigen.Length) return true;
|
||||
}
|
||||
|
||||
File.Copy(rutaOrigen, rutaDestinoCompleta, overwrite: true);
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogDebug(ex, "Fallo al copiar {archivo}", factura.NombreArchivoOrigen);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// --- MÉTODOS DE MAPEO (CONFIGURABLES) ---
|
||||
|
||||
private string MapearNombreEmpresa(string codigoEmpresa)
|
||||
{
|
||||
var nombre = _configuration[$"EmpresasMapping:{codigoEmpresa}"];
|
||||
return string.IsNullOrEmpty(nombre) ? "DESCONOCIDA" : nombre;
|
||||
}
|
||||
|
||||
private string AjustarTipoFactura(string tipoOriginal)
|
||||
{
|
||||
if (string.IsNullOrEmpty(tipoOriginal)) return tipoOriginal;
|
||||
|
||||
// 1. Buscamos mapeo en appsettings.json
|
||||
var tipoMapeado = _configuration[$"FacturaTiposMapping:{tipoOriginal}"];
|
||||
if (!string.IsNullOrEmpty(tipoMapeado))
|
||||
{
|
||||
return tipoMapeado;
|
||||
}
|
||||
|
||||
// 2. Fallback Legacy si no está mapeado
|
||||
return tipoOriginal[^1].ToString();
|
||||
}
|
||||
|
||||
// --- CONSTRUCCIÓN DE NOMBRES ---
|
||||
|
||||
private string ConstruirNombreArchivoOrigen(FacturaParaProcesar factura)
|
||||
{
|
||||
return $"{factura.Cliente}-{factura.CodigoEmpresa}-{factura.Sucursal}-{factura.TipoFactura}-{factura.NumeroFactura}.pdf";
|
||||
}
|
||||
|
||||
private string ConstruirNombreArchivoDestino(FacturaParaProcesar factura)
|
||||
{
|
||||
// El archivo final conserva el Tipo ORIGINAL
|
||||
return $"{factura.Cliente}-{factura.CodigoEmpresa}-{factura.Sucursal}-{factura.TipoFactura}-{factura.NumeroFactura}.pdf";
|
||||
}
|
||||
|
||||
private string ConstruirRutaCarpetaDestino(FacturaParaProcesar factura)
|
||||
{
|
||||
// La carpeta usa el Tipo AJUSTADO
|
||||
string tipoAjustado = AjustarTipoFactura(factura.TipoFactura);
|
||||
string anioMes = factura.FechaFactura.ToString("yyyy-MM");
|
||||
|
||||
string nombreCarpetaFactura = $"{factura.Cliente}-{factura.CodigoEmpresa}-{factura.Sucursal}-{tipoAjustado}-{factura.NumeroFactura}";
|
||||
|
||||
return Path.Combine(factura.NombreEmpresa, anioMes, nombreCarpetaFactura);
|
||||
}
|
||||
|
||||
// --- UTILIDADES ---
|
||||
|
||||
private string ConstruirCadenaConexion(Configuracion config)
|
||||
{
|
||||
var builder = new SqlConnectionStringBuilder
|
||||
{
|
||||
DataSource = config.DBServidor,
|
||||
InitialCatalog = config.DBNombre,
|
||||
IntegratedSecurity = config.DBTrusted,
|
||||
TrustServerCertificate = true,
|
||||
ConnectTimeout = 30
|
||||
};
|
||||
|
||||
if (!config.DBTrusted)
|
||||
{
|
||||
builder.UserID = _encryptionService.Decrypt(config.DBUsuario ?? "");
|
||||
builder.Password = _encryptionService.Decrypt(config.DBClave ?? "");
|
||||
}
|
||||
|
||||
return builder.ConnectionString;
|
||||
}
|
||||
|
||||
private async Task RegistrarEventoAsync(string mensaje, TipoEvento tipo)
|
||||
{
|
||||
try
|
||||
{
|
||||
var evento = new Evento
|
||||
{
|
||||
Fecha = DateTime.Now,
|
||||
Mensaje = mensaje,
|
||||
Tipo = tipo.ToString(),
|
||||
Enviado = false
|
||||
};
|
||||
_context.Eventos.Add(evento);
|
||||
await _context.SaveChangesAsync();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al registrar evento");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<bool> EnviarNotificacionErroresAsync(string destinatario, int procesadas, int errores, List<string> detalles)
|
||||
{
|
||||
try
|
||||
{
|
||||
var asunto = errores == 1 && detalles.Count > 0 && detalles[0].StartsWith("ERROR CRÍTICO")
|
||||
? "ALERTA CRÍTICA: Fallo del Sistema Gestor de Facturas"
|
||||
: "Alerta: Errores en Procesamiento de Facturas";
|
||||
|
||||
string listaArchivosHtml = "";
|
||||
if (detalles != null && detalles.Count > 0)
|
||||
{
|
||||
listaArchivosHtml = "<h3>Detalle de Errores:</h3><ul>";
|
||||
foreach (var archivo in detalles)
|
||||
{
|
||||
listaArchivosHtml += $"<li>{archivo}</li>";
|
||||
}
|
||||
listaArchivosHtml += "</ul>";
|
||||
}
|
||||
|
||||
var cuerpo = $@"
|
||||
<html>
|
||||
<body style='font-family: Arial, sans-serif;'>
|
||||
<h2 style='color: #d9534f;'>{asunto}</h2>
|
||||
<p><strong>Fecha de Ejecución:</strong> {DateTime.Now:dd/MM/yyyy HH:mm:ss}</p>
|
||||
<div style='background-color: #f8f9fa; padding: 15px; border-radius: 5px; border: 1px solid #dee2e6;'>
|
||||
<p><strong>Facturas procesadas exitosamente:</strong> {procesadas}</p>
|
||||
<p><strong>Facturas con error:</strong> <span style='color: red; font-weight: bold;'>{errores}</span></p>
|
||||
</div>
|
||||
<div style='margin-top: 20px;'>{listaArchivosHtml}</div>
|
||||
<hr style='margin-top: 30px;'>
|
||||
<p style='color: #6c757d; font-size: 12px;'>Sistema Gestor de Facturas El Día.</p>
|
||||
</body>
|
||||
</html>";
|
||||
|
||||
return await _mailService.EnviarCorreoAsync(destinatario, asunto, cuerpo, true);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogError(ex, "Error al preparar notificación de errores");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Clase auxiliar para representar una factura a procesar
|
||||
/// </summary>
|
||||
public class FacturaParaProcesar
|
||||
{
|
||||
public string NumeroFactura { get; set; } = string.Empty;
|
||||
public string TipoFactura { get; set; } = string.Empty;
|
||||
public string Cliente { get; set; } = string.Empty;
|
||||
public string Sucursal { get; set; } = string.Empty;
|
||||
public string CodigoEmpresa { get; set; } = string.Empty;
|
||||
public string NombreEmpresa { get; set; } = string.Empty;
|
||||
public DateTime FechaFactura { get; set; }
|
||||
public string NombreArchivoOrigen { get; set; } = string.Empty;
|
||||
public string NombreArchivoDestino { get; set; } = string.Empty;
|
||||
public string CarpetaDestino { get; set; } = string.Empty;
|
||||
}
|
||||
Reference in New Issue
Block a user