From 444b15679da99dfec412f8cc922f2824c50827f3 Mon Sep 17 00:00:00 2001 From: Perea Date: Wed, 29 Apr 2026 09:11:56 +0200 Subject: [PATCH] Cambios mensajes --- Servicio Gestion Asegasa/Configuracion.cs | 15 + Servicio Gestion Asegasa/Logs.cs | 109 ++ .../Procesos/ProcesosCaser.cs | 254 ++-- .../Procesos/ProcesosContabilidad.cs | 236 +-- .../Procesos/ProcesosGestionesVarias.cs | 188 +-- .../Procesos/ProcesosPolizas.cs | 1266 ++++++++--------- .../Procesos/ProcesosRecibos.cs | 816 +++++------ .../Procesos/ProcesosSiniestros.cs | 708 ++++----- .../Procesos/ProcesosTractoresAxa.cs | 1092 +++++++------- Servicio Gestion Asegasa/ProcesosConf.cs | 43 + .../Servicio Gestion Asegasa.csproj | 3 + Servicio Gestion Asegasa/Worker.cs | 90 +- Servicio Gestion Asegasa/appsettings.json | 17 +- 13 files changed, 2545 insertions(+), 2292 deletions(-) create mode 100644 Servicio Gestion Asegasa/Configuracion.cs create mode 100644 Servicio Gestion Asegasa/Logs.cs create mode 100644 Servicio Gestion Asegasa/ProcesosConf.cs diff --git a/Servicio Gestion Asegasa/Configuracion.cs b/Servicio Gestion Asegasa/Configuracion.cs new file mode 100644 index 0000000..2d4b6d0 --- /dev/null +++ b/Servicio Gestion Asegasa/Configuracion.cs @@ -0,0 +1,15 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Servicio_Gestion_Asegasa +{ + public class Configuracion + { + public int SegundosMinimosEntreProcesos { get; set; } + public string? HoraProcesosDiarios { get; set; } + public string? NombreConexionBD { get; set; } + } +} diff --git a/Servicio Gestion Asegasa/Logs.cs b/Servicio Gestion Asegasa/Logs.cs new file mode 100644 index 0000000..e09e015 --- /dev/null +++ b/Servicio Gestion Asegasa/Logs.cs @@ -0,0 +1,109 @@ +using bdAsegasa; +using bdAsegasa.db; +using Microsoft.VisualBasic; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; +using System.Text; +using System.Threading.Tasks; +using Serilog; + +namespace Servicio_Gestion_Asegasa +{ + public class Logs + { + private static object oBloqueoLog; + //private static EventLog el; + public static async Task AñadeLogAsync(tsUtilidades.Enumeraciones.TipoLog Tipo, string Mensaje, Exception e = null) + { + // ---------------------------------------------------------------------------------------------------- + // Descripción Sub: Gestión de logs de la aplicación + // Fecha. Creacion: ??? + // Creada por: manmog + // Ultima Modificacion: 24/11/2010 + // + // Modificaciones: + // =============== + if (oBloqueoLog == null) oBloqueoLog = new object(); + lock (oBloqueoLog) + { + try + { + if (e != null) + { + + string sStackTrace = "Tipo excepción: " + e.ToString() + Constants.vbCrLf; + Exception exError = e; + do + { + sStackTrace += exError.StackTrace + Constants.vbCrLf; + exError = exError.InnerException; + } + while (!Information.IsNothing(exError)); + if (sStackTrace != "") + Mensaje += Constants.vbCrLf + "|StackTrace: " + sStackTrace; + } + + bdAsegasa.db.cuentascorreo? cta = null; + + try + { + var bd = tscgestionasegasa.NuevoContexto(ProcesosConf.Conf.NombreConexionBD, true, false, true, "WSAsegasa"); + cta = bd.cuentascorreo.First(x => x.Codigo == "DEFECTO"); + } + catch + { + } + + switch (Tipo) + { + case tsUtilidades.Enumeraciones.TipoLog.Fallo: + Mensaje = "Error WSAsegasa. " + " Enviado desde " + Environment.MachineName + ". Version:" + Assembly.GetEntryAssembly()?.GetName().Version + ". Mensaje: " + Mensaje; + Log.Fatal(Mensaje); + if (cta != null) { + tsUtilidades.TsNotificacionesClient.RegistrarAsync("Error en Servicio Gestion Asegasa", Mensaje, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); + } + break; + case tsUtilidades.Enumeraciones.TipoLog.Advertencia: + Mensaje = "Advertencia WSAsegasa. " + " Enviado desde " + Environment.MachineName + ". Version:" + Assembly.GetEntryAssembly()?.GetName().Version + ". " + Mensaje; + Log.Warning(Mensaje); + if (cta != null) { + tsUtilidades.TsNotificacionesClient.RegistrarAsync("Advertencia en Servicio Gestion Asegasa", Mensaje, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ADVERTENCIA); + } + break; + case tsUtilidades.Enumeraciones.TipoLog.InicioServicio: + Mensaje = "Inicio WSAsegasa. " + " Enviado desde " + Environment.MachineName + ". Version:" + Assembly.GetEntryAssembly()?.GetName().Version + ". Mensaje: " + Mensaje; + Log.Information(Mensaje); + if (cta != null) { + tsUtilidades.TsNotificacionesClient.RegistrarAsync("Inicio Servicio Gestion Asegasa", Mensaje, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.INFO); + } + break; + case tsUtilidades.Enumeraciones.TipoLog.FinServicio: + Mensaje = "Finalización WSAsegasa. " + " Enviado desde " + Environment.MachineName + ". Version:" + Assembly.GetEntryAssembly()?.GetName().Version + ". Mensaje: " + Mensaje; + Log.Information(Mensaje); + if (cta != null) { + tsUtilidades.TsNotificacionesClient.RegistrarAsync("Finalización Servicio Gestion Asegasa", Mensaje, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.INFO); + + } + break; + + default: + Mensaje = Tipo.ToString() + " WSAsegasa. " + " Enviado desde " + Environment.MachineName + ". Version:" + Assembly.GetEntryAssembly()?.GetName().Version + ". " + Mensaje; + Log.Information(Mensaje); + break; + } + + + } + catch (Exception ex) + { + if (e != null) + Mensaje += " --- " + e.StackTrace; + + Log.Fatal(Mensaje + " ---" + ex.Message + " --- " + ex.StackTrace); + } + } + } + } +} diff --git a/Servicio Gestion Asegasa/Procesos/ProcesosCaser.cs b/Servicio Gestion Asegasa/Procesos/ProcesosCaser.cs index 99c2043..b34adef 100644 --- a/Servicio Gestion Asegasa/Procesos/ProcesosCaser.cs +++ b/Servicio Gestion Asegasa/Procesos/ProcesosCaser.cs @@ -1,136 +1,136 @@ -using System; -using System.IO; -using System.Linq; -using System.IO.Compression; -using System.Collections.Generic; -using Renci.SshNet; -using Renci.SshNet.Common; -using tsUtilidades; -using tsUtilidades.Extensiones; -using bdAsegasa.db; -using tsUtilidades.Enumeraciones; +//using System; +//using System.IO; +//using System.Linq; +//using System.IO.Compression; +//using System.Collections.Generic; +//using Renci.SshNet; +//using Renci.SshNet.Common; +//using tsUtilidades; +//using tsUtilidades.Extensiones; +//using bdAsegasa.db; +//using tsUtilidades.Enumeraciones; -namespace Servicio_Gestion_Asegasa.Procesos -{ - public class ProcesosCaser - { +//namespace Servicio_Gestion_Asegasa.Procesos +//{ +// public class ProcesosCaser +// { - public static async Task GuardarEnBDFicherosDisponiblesSFTPAsync() - { - try - { - using (var bd = bdAsegasa.db.gestionasegasaEntities.NuevoContextoCN()) - using (var bdtmp = bdAsegasa.db.gestionasegasaEntities.NuevoContextoCN()) - { - var idCaser = bd.companias.First(x => x.Codigo == "0017").idCompania; +// public static async Task GuardarEnBDFicherosDisponiblesSFTPAsync() +// { +// try +// { +// using (var bd = bdAsegasa.db.gestionasegasaEntities.NuevoContextoCN()) +// using (var bdtmp = bdAsegasa.db.gestionasegasaEntities.NuevoContextoCN()) +// { +// var idCaser = bd.companias.First(x => x.Codigo == "0017").idCompania; - var keybAuth = new KeyboardInteractiveAuthenticationMethod("ca071106"); - keybAuth.AuthenticationPrompt += HandleKeyEvent; - var conInfo = new ConnectionInfo("ftp.caser.es", 22, "ca071106", keybAuth); +// var keybAuth = new KeyboardInteractiveAuthenticationMethod("ca071106"); +// keybAuth.AuthenticationPrompt += HandleKeyEvent; +// var conInfo = new ConnectionInfo("ftp.caser.es", 22, "ca071106", keybAuth); - using (var sftp = new SftpClient(conInfo)) - { - sftp.Connect(); - var lf = sftp.ListDirectory("ca071106").Where(x => x.IsDirectory == false); +// using (var sftp = new SftpClient(conInfo)) +// { +// sftp.Connect(); +// var lf = sftp.ListDirectory("ca071106").Where(x => x.IsDirectory == false); - foreach (var F in lf) - { - try - { - if (F.Name.StartsWith("EIAC_REC_") || F.Name.StartsWith("EIAC_POL_") || F.Name.StartsWith("EIAC_SIN_")) - { - string nomfic; - bool Eszip; - if (F.Name.EndsWith(".txt")) - { - nomfic = F.Name.Substring(0, F.Name.Length - 4); - Eszip = false; - } - else - { - nomfic = Path.ChangeExtension(F.Name, "xml"); - Eszip = true; - } - using (var ms = new MemoryStream()) - { - sftp.DownloadFile(F.FullName, ms); - ms.Position = 0; +// foreach (var F in lf) +// { +// try +// { +// if (F.Name.StartsWith("EIAC_REC_") || F.Name.StartsWith("EIAC_POL_") || F.Name.StartsWith("EIAC_SIN_")) +// { +// string nomfic; +// bool Eszip; +// if (F.Name.EndsWith(".txt")) +// { +// nomfic = F.Name.Substring(0, F.Name.Length - 4); +// Eszip = false; +// } +// else +// { +// nomfic = Path.ChangeExtension(F.Name, "xml"); +// Eszip = true; +// } +// using (var ms = new MemoryStream()) +// { +// sftp.DownloadFile(F.FullName, ms); +// ms.Position = 0; - byte[] b; - if (Eszip) - { - using (var zip = new ZipArchive(ms, ZipArchiveMode.Read)) - { - var firstEntry = zip.Entries.First(); - using (var msxml = new MemoryStream()) - { - using (var entryStream = firstEntry.Open()) - { - entryStream.CopyTo(msxml); - } - msxml.Position = 0; - b = msxml.ToArray(); - } - } - } - else - { - b = ms.ToArray(); - } +// byte[] b; +// if (Eszip) +// { +// using (var zip = new ZipArchive(ms, ZipArchiveMode.Read)) +// { +// var firstEntry = zip.Entries.First(); +// using (var msxml = new MemoryStream()) +// { +// using (var entryStream = firstEntry.Open()) +// { +// entryStream.CopyTo(msxml); +// } +// msxml.Position = 0; +// b = msxml.ToArray(); +// } +// } +// } +// else +// { +// b = ms.ToArray(); +// } - var sha1 = tsUtilidades.crypt.SHA1(b); - if (bdtmp.ficheroscompanias.Any(x => x.SHA1 == sha1 && x.idCompania == idCaser) == false) - { - var nf = new bdAsegasa.db.ficheroscompanias(); - nf.FechaCreacion = DateTime.Now; - nf.idCompania = idCaser; - nf.Fichero = b; - nf.NombreFichero = nomfic; - nf.SHA1 = sha1; +// var sha1 = tsUtilidades.crypt.SHA1(b); +// if (bdtmp.ficheroscompanias.Any(x => x.SHA1 == sha1 && x.idCompania == idCaser) == false) +// { +// var nf = new bdAsegasa.db.ficheroscompanias(); +// nf.FechaCreacion = DateTime.Now; +// nf.idCompania = idCaser; +// nf.Fichero = b; +// nf.NombreFichero = nomfic; +// nf.SHA1 = sha1; - switch (F.Name.Split('_')[1]) - { - case "REC": - nf.Tipo = (int)bdAsegasa.db.ficheroscompanias.TipoFicheroCompania.RECIBOS_EIAC; - break; - case "POL": - nf.Tipo = (int)bdAsegasa.db.ficheroscompanias.TipoFicheroCompania.POLIZAS_EIAC; - break; - case "SIN": - nf.Tipo = (int)bdAsegasa.db.ficheroscompanias.TipoFicheroCompania.SINIESTROS_EIAC; - break; - } - bd.ficheroscompanias.Add(nf); - bd.SaveChanges(); - } - } - } - sftp.RenameFile(F.FullName, F.FullName.Replace(F.Name, "PROCESADOS/" + F.Name)); - } - catch (Exception EX) - { - throw new Exception(EX.Message + " Fichero: " + F.FullName, EX); - } - } - sftp.Disconnect(); - } - } - } - catch (Exception EX) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GuardarEnBDFicherosDisponibles CASER", EX.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// switch (F.Name.Split('_')[1]) +// { +// case "REC": +// nf.Tipo = (int)bdAsegasa.db.ficheroscompanias.TipoFicheroCompania.RECIBOS_EIAC; +// break; +// case "POL": +// nf.Tipo = (int)bdAsegasa.db.ficheroscompanias.TipoFicheroCompania.POLIZAS_EIAC; +// break; +// case "SIN": +// nf.Tipo = (int)bdAsegasa.db.ficheroscompanias.TipoFicheroCompania.SINIESTROS_EIAC; +// break; +// } +// bd.ficheroscompanias.Add(nf); +// bd.SaveChanges(); +// } +// } +// } +// sftp.RenameFile(F.FullName, F.FullName.Replace(F.Name, "PROCESADOS/" + F.Name)); +// } +// catch (Exception EX) +// { +// throw new Exception(EX.Message + " Fichero: " + F.FullName, EX); +// } +// } +// sftp.Disconnect(); +// } +// } +// } +// catch (Exception EX) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GuardarEnBDFicherosDisponibles CASER", EX.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - private static void HandleKeyEvent(object? sender, AuthenticationPromptEventArgs e) - { - foreach (var prompt in e.Prompts) - { - if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1) - { - prompt.Response = "As69gs73"; - } - } - } - } -} +// private static void HandleKeyEvent(object? sender, AuthenticationPromptEventArgs e) +// { +// foreach (var prompt in e.Prompts) +// { +// if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1) +// { +// prompt.Response = "As69gs73"; +// } +// } +// } +// } +//} diff --git a/Servicio Gestion Asegasa/Procesos/ProcesosContabilidad.cs b/Servicio Gestion Asegasa/Procesos/ProcesosContabilidad.cs index 25e06fa..6dfc25e 100644 --- a/Servicio Gestion Asegasa/Procesos/ProcesosContabilidad.cs +++ b/Servicio Gestion Asegasa/Procesos/ProcesosContabilidad.cs @@ -1,139 +1,139 @@ -using bdAsegasa; -using bdAsegasa.db; -using bdAsegasa.dbcontext; -using System; -using System.Collections.Generic; -using System.Linq; +//using bdAsegasa; +//using bdAsegasa.db; +//using bdAsegasa.dbcontext; +//using System; +//using System.Collections.Generic; +//using System.Linq; -namespace Servicio_Gestion_Asegasa.Procesos -{ - public class ProcesosContabilidad - { - public static void CompruebaContabilidad() - { - using var bd = tscgestionasegasa.NuevoContexto(); - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - string sDestinatarios = "sevilla@tecnosis.net"; +//namespace Servicio_Gestion_Asegasa.Procesos +//{ +// public class ProcesosContabilidad +// { +// public static void CompruebaContabilidad() +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// string sDestinatarios = "sevilla@tecnosis.net"; - var asis = bd.asientos.Where(x => - x.Fecha < x.idEjercicioNavigation.FechaInicio || - x.Fecha > x.idEjercicioNavigation.FechaFin || - x.apuntes.Any(y => y.idCuentaNavigation.idEjercicio != x.idEjercicio) - ).ToList(); +// var asis = bd.asientos.Where(x => +// x.Fecha < x.idEjercicioNavigation.FechaInicio || +// x.Fecha > x.idEjercicioNavigation.FechaFin || +// x.apuntes.Any(y => y.idCuentaNavigation.idEjercicio != x.idEjercicio) +// ).ToList(); - if (asis.Count > 0) - { - var lFechaErronea = new List(); - foreach (var asi in asis) - { - var ej = bd.ejercicioscontables.FirstOrDefault(x => - x.FechaCierre == null && - (x.FechaInicio <= asi.Fecha && x.FechaFin >= asi.Fecha) - ); +// if (asis.Count > 0) +// { +// var lFechaErronea = new List(); +// foreach (var asi in asis) +// { +// var ej = bd.ejercicioscontables.FirstOrDefault(x => +// x.FechaCierre == null && +// (x.FechaInicio <= asi.Fecha && x.FechaFin >= asi.Fecha) +// ); - if (ej != null) - { - lFechaErronea.Add(asi); - } - else - { - if (asi.idEjercicio != ej.idEjercicio) - { - asi.idEjercicio = ej.idEjercicio; - } - foreach (var ap in asi.apuntes) - { - ap.idCuenta = bd.cuentas.First(x => x.NumeroCuenta == ap.idCuentaNavigation.NumeroCuenta && x.idEjercicio == asi.idEjercicio).idCuenta; - } - } - } +// if (ej != null) +// { +// lFechaErronea.Add(asi); +// } +// else +// { +// if (asi.idEjercicio != ej.idEjercicio) +// { +// asi.idEjercicio = ej.idEjercicio; +// } +// foreach (var ap in asi.apuntes) +// { +// ap.idCuenta = bd.cuentas.First(x => x.NumeroCuenta == ap.idCuentaNavigation.NumeroCuenta && x.idEjercicio == asi.idEjercicio).idCuenta; +// } +// } +// } - bd.SaveChanges(); +// bd.SaveChanges(); - if (lFechaErronea.Count > 0) - { - var lae = lFechaErronea.Select(x => new - { - NumeroAsiento = x.idAsiento, - Fecha = x.Fecha, - Ejercicio = x.idEjercicioNavigation.Descripcion - }).ToList(); +// if (lFechaErronea.Count > 0) +// { +// var lae = lFechaErronea.Select(x => new +// { +// NumeroAsiento = x.idAsiento, +// Fecha = x.Fecha, +// Ejercicio = x.idEjercicioNavigation.Descripcion +// }).ToList(); - byte[] fe = tsUtilidades.Excel.IEnumerableAExcel(lae); +// byte[] fe = tsUtilidades.Excel.IEnumerableAExcel(lae); - bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, - "Existen apuntes con cuentas de un ejercicio diferente al del asiento (No se corrige el asiento)", - "Existen apuntes con cuentas de un ejercicio diferente al del asiento (Se corrige el asiento)", - cta, fe, "AsientosFechaErronea-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", - "Asientos Con Fecha Erronea " + DateTime.Now.ToString("yyyy-MM-dd"), - sDestinatarios); +// bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, +// "Existen apuntes con cuentas de un ejercicio diferente al del asiento (No se corrige el asiento)", +// "Existen apuntes con cuentas de un ejercicio diferente al del asiento (Se corrige el asiento)", +// cta, fe, "AsientosFechaErronea-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", +// "Asientos Con Fecha Erronea " + DateTime.Now.ToString("yyyy-MM-dd"), +// sDestinatarios); - var idsErrores = lae.Select(y => y.NumeroAsiento).ToList(); - asis = asis.Where(x => !idsErrores.Contains(x.idAsiento)).ToList(); - } +// var idsErrores = lae.Select(y => y.NumeroAsiento).ToList(); +// asis = asis.Where(x => !idsErrores.Contains(x.idAsiento)).ToList(); +// } - var la = asis.Select(x => new - { - NumeroAsiento = x.idAsiento, - Fecha = x.Fecha, - Ejercicio = x.idEjercicioNavigation.Descripcion - }).ToList(); +// var la = asis.Select(x => new +// { +// NumeroAsiento = x.idAsiento, +// Fecha = x.Fecha, +// Ejercicio = x.idEjercicioNavigation.Descripcion +// }).ToList(); - byte[] f = tsUtilidades.Excel.IEnumerableAExcel(la); +// byte[] f = tsUtilidades.Excel.IEnumerableAExcel(la); - bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, - "Existen apuntes con cuentas de un ejercicio diferente al del asiento (Se corrige el asiento)", - "Existen apuntes con cuentas de un ejercicio diferente al del asiento (Se corrige el asiento)", - cta, f, "ApuntesIncoherentes-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", - "Apuntes Incoherentes " + DateTime.Now.ToString("yyyy-MM-dd"), - sDestinatarios); - } +// bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, +// "Existen apuntes con cuentas de un ejercicio diferente al del asiento (Se corrige el asiento)", +// "Existen apuntes con cuentas de un ejercicio diferente al del asiento (Se corrige el asiento)", +// cta, f, "ApuntesIncoherentes-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", +// "Apuntes Incoherentes " + DateTime.Now.ToString("yyyy-MM-dd"), +// sDestinatarios); +// } - asis = bd.asientos.Where(x => x.Fecha < x.idEjercicioNavigation.FechaInicio || x.Fecha > x.idEjercicioNavigation.FechaFin).ToList(); +// asis = bd.asientos.Where(x => x.Fecha < x.idEjercicioNavigation.FechaInicio || x.Fecha > x.idEjercicioNavigation.FechaFin).ToList(); - if (asis.Count > 0) - { - var la = asis.Select(x => new - { - NumeroAsiento = x.idAsiento, - Fecha = x.Fecha, - Ejercicio = x.idEjercicioNavigation.Descripcion - }).ToList(); +// if (asis.Count > 0) +// { +// var la = asis.Select(x => new +// { +// NumeroAsiento = x.idAsiento, +// Fecha = x.Fecha, +// Ejercicio = x.idEjercicioNavigation.Descripcion +// }).ToList(); - byte[] f = tsUtilidades.Excel.IEnumerableAExcel(la); +// byte[] f = tsUtilidades.Excel.IEnumerableAExcel(la); - bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, - "Existen asientos con fecha incoherente al del ejercicio", - "Existen asientos con fecha incoherente al del ejercicio", - cta, f, "AsientosIncoherentes-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", - "Asientos Incoherentes " + DateTime.Now.ToString("yyyy-MM-dd"), - sDestinatarios); - } +// bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, +// "Existen asientos con fecha incoherente al del ejercicio", +// "Existen asientos con fecha incoherente al del ejercicio", +// cta, f, "AsientosIncoherentes-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", +// "Asientos Incoherentes " + DateTime.Now.ToString("yyyy-MM-dd"), +// sDestinatarios); +// } - asis = bd.asientos.Where(x => Math.Round((double)x.apuntes.Sum(y => y.Debe ), 2) != Math.Round((double)x.apuntes.Sum(y => y.Haber), 2)).ToList(); +// asis = bd.asientos.Where(x => Math.Round((double)x.apuntes.Sum(y => y.Debe ), 2) != Math.Round((double)x.apuntes.Sum(y => y.Haber), 2)).ToList(); - if (asis.Count > 0) - { - var la = asis.Select(x => new - { - NumeroAsiento = x.idAsiento, - Fecha = x.Fecha, - Ejercicio = x.idEjercicioNavigation.Descripcion, - Debe = Math.Round((double)x.apuntes.Sum(y => y.Debe ), 2, MidpointRounding.AwayFromZero), - Haber = Math.Round((double)x.apuntes.Sum(y => y.Haber ), 2, MidpointRounding.AwayFromZero) - }).ToList(); +// if (asis.Count > 0) +// { +// var la = asis.Select(x => new +// { +// NumeroAsiento = x.idAsiento, +// Fecha = x.Fecha, +// Ejercicio = x.idEjercicioNavigation.Descripcion, +// Debe = Math.Round((double)x.apuntes.Sum(y => y.Debe ), 2, MidpointRounding.AwayFromZero), +// Haber = Math.Round((double)x.apuntes.Sum(y => y.Haber ), 2, MidpointRounding.AwayFromZero) +// }).ToList(); - byte[] f = tsUtilidades.Excel.IEnumerableAExcel(la); +// byte[] f = tsUtilidades.Excel.IEnumerableAExcel(la); - bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, - "Existen asientos descuadrados", - "Existen asientos descuadrados", - cta, f, "AsientosDescuadrados-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", - "Asientos Descuadrados " + DateTime.Now.ToString("yyyy-MM-dd"), - sDestinatarios); - } +// bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, +// "Existen asientos descuadrados", +// "Existen asientos descuadrados", +// cta, f, "AsientosDescuadrados-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", +// "Asientos Descuadrados " + DateTime.Now.ToString("yyyy-MM-dd"), +// sDestinatarios); +// } - asis = bd.asientos.Where(x => x.Fecha < x.idEjercicioNavigation.FechaInicio || x.Fecha > x.idEjercicioNavigation.FechaFin).ToList(); - } - } -} +// asis = bd.asientos.Where(x => x.Fecha < x.idEjercicioNavigation.FechaInicio || x.Fecha > x.idEjercicioNavigation.FechaFin).ToList(); +// } +// } +//} diff --git a/Servicio Gestion Asegasa/Procesos/ProcesosGestionesVarias.cs b/Servicio Gestion Asegasa/Procesos/ProcesosGestionesVarias.cs index 81cb9a5..40405ca 100644 --- a/Servicio Gestion Asegasa/Procesos/ProcesosGestionesVarias.cs +++ b/Servicio Gestion Asegasa/Procesos/ProcesosGestionesVarias.cs @@ -1,107 +1,107 @@ -using bdAsegasa; -using bdAsegasa.db; -using bdAsegasa.dbcontext; -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using tsUtilidades; -using tsUtilidades.Extensiones; +//using bdAsegasa; +//using bdAsegasa.db; +//using bdAsegasa.dbcontext; +//using System; +//using System.Collections.Generic; +//using System.IO; +//using System.Linq; +//using tsUtilidades; +//using tsUtilidades.Extensiones; -namespace Servicio_Gestion_Asegasa.Procesos -{ - public class ProcesosGestionesVarias - { - public static async Task GeneraCorreoRestablecimientoContraseñaAsync() - { - string sProceso = "GeneraCorreoRestablecimientoContraseña"; - try - { - var bd = tscgestionasegasa.NuevoContexto(); ; - var idTgag = bd.enumeraciones.First(x => x.Codigo == "TGV.CCAG").idEnumeracion; - var idTgsag = bd.enumeraciones.First(x => x.Codigo == "TGV.CCSAG").idEnumeracion; - var gess = bd.gestionesvarias.Where(x => x.idCorreo.HasValue == false && (x.idTipo == idTgag || x.idTipo == idTgsag) && x.FechaProcesado.HasValue == false).ToList(); - var urlaseg = bd.enumeraciones.First(x => x.Codigo == "CONF.URLWC").ValorAlfabeticoLargo; +//namespace Servicio_Gestion_Asegasa.Procesos +//{ +// public class ProcesosGestionesVarias +// { +// public static async Task GeneraCorreoRestablecimientoContraseñaAsync() +// { +// string sProceso = "GeneraCorreoRestablecimientoContraseña"; +// try +// { +// var bd = tscgestionasegasa.NuevoContexto(); ; +// var idTgag = bd.enumeraciones.First(x => x.Codigo == "TGV.CCAG").idEnumeracion; +// var idTgsag = bd.enumeraciones.First(x => x.Codigo == "TGV.CCSAG").idEnumeracion; +// var gess = bd.gestionesvarias.Where(x => x.idCorreo.HasValue == false && (x.idTipo == idTgag || x.idTipo == idTgsag) && x.FechaProcesado.HasValue == false).ToList(); +// var urlaseg = bd.enumeraciones.First(x => x.Codigo == "CONF.URLWC").ValorAlfabeticoLargo; - foreach (var g in gess) - { - string sDestinatario; - string sAsunto; +// foreach (var g in gess) +// { +// string sDestinatario; +// string sAsunto; - if (g.idTipo == idTgag) - { - var ag = bd.agentes.First(x => x.idAgente != 0); - sDestinatario = ag.Email; - sAsunto = "Solicitud de cambio de contraseña al Agente " + ag.Nombre + " (Nº " + ag.Codigo + ")"; - } - else - { - var sag = bd.subagentes.First(x => x.idAgente != 0); - sDestinatario = sag.Email; - sAsunto = "Solicitud de cambio de contraseña al SubAgente " + sag.Nombre + " (Nº " + sag.idAgenteNavigation.Codigo + "-" + sag.Codigo + ")"; - } +// if (g.idTipo == idTgag) +// { +// var ag = bd.agentes.First(x => x.idAgente != 0); +// sDestinatario = ag.Email; +// sAsunto = "Solicitud de cambio de contraseña al Agente " + ag.Nombre + " (Nº " + ag.Codigo + ")"; +// } +// else +// { +// var sag = bd.subagentes.First(x => x.idAgente != 0); +// sDestinatario = sag.Email; +// sAsunto = "Solicitud de cambio de contraseña al SubAgente " + sag.Nombre + " (Nº " + sag.idAgenteNavigation.Codigo + "-" + sag.Codigo + ")"; +// } - if (Directory.Exists(@"c:\tecnosis.tfs")) - { - sDestinatario = "sevilla@tecnosis.net"; - } +// if (Directory.Exists(@"c:\tecnosis.tfs")) +// { +// sDestinatario = "sevilla@tecnosis.net"; +// } - if (sDestinatario.EsEmailValido()) - { - g.Parametros = tsUtilidades.crypt.SHA1("M3Soft." + DateTime.Now.ToBinary().ToString() + g.idGestion.ToString()); - string sUrlEnlace = urlaseg + "/nuevaContrasena.aspx?id=" + g.idGestion.ToString() + "&cl=" + g.Parametros; +// if (sDestinatario.EsEmailValido()) +// { +// g.Parametros = tsUtilidades.crypt.SHA1("M3Soft." + DateTime.Now.ToBinary().ToString() + g.idGestion.ToString()); +// string sUrlEnlace = urlaseg + "/nuevaContrasena.aspx?id=" + g.idGestion.ToString() + "&cl=" + g.Parametros; - string sCuerpo = "Estimado compañero/a: Adjunto te remitimos el enlace para restablecer la contraseña de acceso a la Web de Asegasa. Si usted no ha realizado dicha solicitud, póngase en contacto con nosotros. Un saludo."; - sCuerpo += "

Url Restablecimiento de contraseña: Pulse aquí"; +// string sCuerpo = "Estimado compañero/a: Adjunto te remitimos el enlace para restablecer la contraseña de acceso a la Web de Asegasa. Si usted no ha realizado dicha solicitud, póngase en contacto con nosotros. Un saludo."; +// sCuerpo += "

Url Restablecimiento de contraseña: Pulse aquí"; - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - g.idCorreo = bdAsegasa.db.correos.GeneraRegistroCorreo(bd, sAsunto, sCuerpo, cta, sDestinatario); - bd.SaveChanges(); - } - else - { - g.FechaProcesado = DateTime.Now; - bd.SaveChanges(); - await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GeneraCorreoRestablecimientoContraseña.", "Rutina: GeneraCorreoRestablecimientoContraseña. " + " El Agente o subagente " + g.Descripción + " no tiene un correo válido.", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// g.idCorreo = bdAsegasa.db.correos.GeneraRegistroCorreo(bd, sAsunto, sCuerpo, cta, sDestinatario); +// bd.SaveChanges(); +// } +// else +// { +// g.FechaProcesado = DateTime.Now; +// bd.SaveChanges(); +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GeneraCorreoRestablecimientoContraseña.", "Rutina: GeneraCorreoRestablecimientoContraseña. " + " El Agente o subagente " + g.Descripción + " no tiene un correo válido.", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GeneraCorreoRestablecimientoContraseña.", "Rutina: GeneraCorreoRestablecimientoContraseña. " + " " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// } +// } +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GeneraCorreoRestablecimientoContraseña.", "Rutina: GeneraCorreoRestablecimientoContraseña. " + " " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task EnviaAlertaCredencialesProximasACaducarAsync() - { - string sProceso = "EnviaAlertaCredencialesProximasACaducar"; - try - { - var bd = tscgestionasegasa.NuevoContexto(); - var ctaspc = bd.cuentascorreo.Where(x => x.FechaAvisoCaducidadCredenciales != null && x.FechaAvisoCaducidadCredenciales < DateTime.Now).ToList(); - var dest = bd.enumeraciones.Where(x => x.Codigo == "CONF.EMAILCRCTA").First().ValorAlfabeticoLargo; +// public static async Task EnviaAlertaCredencialesProximasACaducarAsync() +// { +// string sProceso = "EnviaAlertaCredencialesProximasACaducar"; +// try +// { +// var bd = tscgestionasegasa.NuevoContexto(); +// var ctaspc = bd.cuentascorreo.Where(x => x.FechaAvisoCaducidadCredenciales != null && x.FechaAvisoCaducidadCredenciales < DateTime.Now).ToList(); +// var dest = bd.enumeraciones.Where(x => x.Codigo == "CONF.EMAILCRCTA").First().ValorAlfabeticoLargo; - foreach (var c in ctaspc) - { - string sAsunto; - sAsunto = "Crecenciales de la cuenta de correo " + c.Remitente + " próxima a caducar."; +// foreach (var c in ctaspc) +// { +// string sAsunto; +// sAsunto = "Crecenciales de la cuenta de correo " + c.Remitente + " próxima a caducar."; - if (Directory.Exists(@"c:\tecnosis.tfs")) - { - dest = "sevilla@tecnosis.net"; - } +// if (Directory.Exists(@"c:\tecnosis.tfs")) +// { +// dest = "sevilla@tecnosis.net"; +// } - string sCuerpo = "Atención: Se deben renovar las credenciales de la cuenta " + c.Remitente + " y comunicárselo a Tecnosis para su actualización."; - bdAsegasa.db.correos.GeneraRegistroCorreo(bd, sAsunto, sCuerpo, c, dest); - bd.SaveChanges(); - } - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En EnviaAlertaCredencialesProximasACaducar.", "Rutina: GeneraCorreoRestablecimientoContraseña. " + " " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } - } -} +// string sCuerpo = "Atención: Se deben renovar las credenciales de la cuenta " + c.Remitente + " y comunicárselo a Tecnosis para su actualización."; +// bdAsegasa.db.correos.GeneraRegistroCorreo(bd, sAsunto, sCuerpo, c, dest); +// bd.SaveChanges(); +// } +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En EnviaAlertaCredencialesProximasACaducar.", "Rutina: GeneraCorreoRestablecimientoContraseña. " + " " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } +// } +//} diff --git a/Servicio Gestion Asegasa/Procesos/ProcesosPolizas.cs b/Servicio Gestion Asegasa/Procesos/ProcesosPolizas.cs index d51b9ab..0d87749 100644 --- a/Servicio Gestion Asegasa/Procesos/ProcesosPolizas.cs +++ b/Servicio Gestion Asegasa/Procesos/ProcesosPolizas.cs @@ -1,667 +1,667 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using System.IO; -using System.Data; -using tsUtilidades.Extensiones; -using bdAsegasa.dbcontext; -using bdAsegasa.db; -using bdAsegasa; -using tsUtilidades; +//using System; +//using System.Linq; +//using System.Collections.Generic; +//using System.IO; +//using System.Data; +//using tsUtilidades.Extensiones; +//using bdAsegasa.dbcontext; +//using bdAsegasa.db; +//using bdAsegasa; +//using tsUtilidades; -namespace Servicio_Gestion_Asegasa.Procesos -{ - public class ProcesosPolizas - { - public static async Task EnvioDocumentosSegurosAsync() - { - try - { - // var FechaLimite = new DateTime(2019, 1, 15); - var FechaLimite = new DateTime(2019, 5, 1); - var FechaLimiteAgentes = new DateTime(2019, 5, 1); - var bd = tscgestionasegasa.NuevoContexto(); - var cta = bd.cuentascorreo.First(x => x.Codigo == "DEFECTO"); - var plzs = bd.documentospolizassg.Where(x => (x.FechaComprobacion == null || x.idPolizaNavigation.idRamoNavigation.ForzarEmailPersonalASEGASA) && (x.idPolizaNavigation.FechaAceptacionPresupuesto != null || x.idPolizaNavigation.NumeroPoliza != null) && x.idFichero != null && x.idDocumentoASolicitarNavigation.EnviarEmailAAsegasa && x.idCorreoAsegasa == null && (x.idPolizaNavigation.idRamoNavigation.DestinatariosCorreosDocumentacion != null && x.idPolizaNavigation.idRamoNavigation.DestinatariosCorreosDocumentacion != "")).GroupBy(x => x.idPoliza).ToList(); - DateTime? FechaAnulacion; - foreach (var dp in plzs) - { - var pl = dp.First().idPolizaNavigation; - string sAsunto; - if (pl.documentospolizassg.Any(x => x.idCorreoAsegasa.HasValue)) - { - sAsunto = "Envío Documentación Seguro " + pl.idRamoNavigation.Descripcion + " Nº Presupuesto: " + pl.idPoliza.ToString(); - } - else - { - sAsunto = "Emisión de Póliza y Envío Documentación Seguro " + pl.idRamoNavigation.Descripcion + " Nº Presupuesto: " + pl.idPoliza.ToString(); - } - var sDest = pl.idRamoNavigation.DestinatariosCorreosDocumentacion; - if (!sDest.Contains("@")) - { - var cao = bd.enumeraciones.FirstOrDefault(x => x.Codigo == "CONF.EMAILAOED"); - string scao = cao != null ? cao.ValorAlfabeticoLargo : ""; - sDest = await ObtieneEmailSiguienteAsync(bd, pl, sDest, scao); - } - var Ficheros = new List(); - FechaAnulacion = null; - foreach (var d in dp) - { - //If d.ficheros.Fecha < FechaLimite Then - if (d.idFicheroNavigation.Fecha.HasValue && (d.idFicheroNavigation.Fecha < FechaLimiteAgentes || (d.idFicheroNavigation.Fecha < FechaLimite && d.idPolizaNavigation.idUsuario != null))) - { - FechaAnulacion = DateTime.Now; - sAsunto += " (Anulado por fecha Antigua: " + d.idFicheroNavigation.Fecha.Value.ToShortDateString() + ")"; - } - else - { - if (d.idPolizaNavigation.idRamoNavigation.DestinatariosCorreosDocumentacion.NothingAVacio() == "") - { - FechaAnulacion = DateTime.Now; - sAsunto += " (Anulado por ramo sin destinatarios de correo de documentación)"; - } - } - d.idFicheroNavigation.NombreFichero = "Poliza_" + pl.idPoliza.ToString() + "_" + d.Descripcion.NothingAVacio().Replace(" ", "_").Acortar(50) + Path.GetExtension(d.idFicheroNavigation.NombreFichero); - Ficheros.Add(d.idFichero.Value); - bd.SaveChanges(); - } - var idcorreo = bdAsegasa.db.correos.GeneraRegistroCorreoVariosFicheros(bd, sAsunto, sAsunto, cta, sDest, Ficheros, FechaAnulacion); - foreach (var d in dp) - { - d.idCorreoAsegasa = idcorreo; - } - bd.SaveChanges(); - } - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En EnvioDocumentosSeguros.", "Rutina: EnvioDocumentosSeguros. " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +//namespace Servicio_Gestion_Asegasa.Procesos +//{ +// public class ProcesosPolizas +// { +// public static async Task EnvioDocumentosSegurosAsync() +// { +// try +// { +// // var FechaLimite = new DateTime(2019, 1, 15); +// var FechaLimite = new DateTime(2019, 5, 1); +// var FechaLimiteAgentes = new DateTime(2019, 5, 1); +// var bd = tscgestionasegasa.NuevoContexto(); +// var cta = bd.cuentascorreo.First(x => x.Codigo == "DEFECTO"); +// var plzs = bd.documentospolizassg.Where(x => (x.FechaComprobacion == null || x.idPolizaNavigation.idRamoNavigation.ForzarEmailPersonalASEGASA) && (x.idPolizaNavigation.FechaAceptacionPresupuesto != null || x.idPolizaNavigation.NumeroPoliza != null) && x.idFichero != null && x.idDocumentoASolicitarNavigation.EnviarEmailAAsegasa && x.idCorreoAsegasa == null && (x.idPolizaNavigation.idRamoNavigation.DestinatariosCorreosDocumentacion != null && x.idPolizaNavigation.idRamoNavigation.DestinatariosCorreosDocumentacion != "")).GroupBy(x => x.idPoliza).ToList(); +// DateTime? FechaAnulacion; +// foreach (var dp in plzs) +// { +// var pl = dp.First().idPolizaNavigation; +// string sAsunto; +// if (pl.documentospolizassg.Any(x => x.idCorreoAsegasa.HasValue)) +// { +// sAsunto = "Envío Documentación Seguro " + pl.idRamoNavigation.Descripcion + " Nº Presupuesto: " + pl.idPoliza.ToString(); +// } +// else +// { +// sAsunto = "Emisión de Póliza y Envío Documentación Seguro " + pl.idRamoNavigation.Descripcion + " Nº Presupuesto: " + pl.idPoliza.ToString(); +// } +// var sDest = pl.idRamoNavigation.DestinatariosCorreosDocumentacion; +// if (!sDest.Contains("@")) +// { +// var cao = bd.enumeraciones.FirstOrDefault(x => x.Codigo == "CONF.EMAILAOED"); +// string scao = cao != null ? cao.ValorAlfabeticoLargo : ""; +// sDest = await ObtieneEmailSiguienteAsync(bd, pl, sDest, scao); +// } +// var Ficheros = new List(); +// FechaAnulacion = null; +// foreach (var d in dp) +// { +// //If d.ficheros.Fecha < FechaLimite Then +// if (d.idFicheroNavigation.Fecha.HasValue && (d.idFicheroNavigation.Fecha < FechaLimiteAgentes || (d.idFicheroNavigation.Fecha < FechaLimite && d.idPolizaNavigation.idUsuario != null))) +// { +// FechaAnulacion = DateTime.Now; +// sAsunto += " (Anulado por fecha Antigua: " + d.idFicheroNavigation.Fecha.Value.ToShortDateString() + ")"; +// } +// else +// { +// if (d.idPolizaNavigation.idRamoNavigation.DestinatariosCorreosDocumentacion.NothingAVacio() == "") +// { +// FechaAnulacion = DateTime.Now; +// sAsunto += " (Anulado por ramo sin destinatarios de correo de documentación)"; +// } +// } +// d.idFicheroNavigation.NombreFichero = "Poliza_" + pl.idPoliza.ToString() + "_" + d.Descripcion.NothingAVacio().Replace(" ", "_").Acortar(50) + Path.GetExtension(d.idFicheroNavigation.NombreFichero); +// Ficheros.Add(d.idFichero.Value); +// bd.SaveChanges(); +// } +// var idcorreo = bdAsegasa.db.correos.GeneraRegistroCorreoVariosFicheros(bd, sAsunto, sAsunto, cta, sDest, Ficheros, FechaAnulacion); +// foreach (var d in dp) +// { +// d.idCorreoAsegasa = idcorreo; +// } +// bd.SaveChanges(); +// } +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En EnvioDocumentosSeguros.", "Rutina: EnvioDocumentosSeguros. " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task ObtieneEmailSiguienteAsync(tscgestionasegasa bd, polizassg pl, string Grupo, string CorreosAOmitir = "") - { - try - { - if (Grupo.NothingAVacio() == "") - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En ObtieneEmailSiguiente.", "Rutina: ObtieneEmailSiguiente. " + " El ramo de la póliza " + pl.NumeroPoliza + " no tiene asignado grupo de destinatario de correos", TsNotificacionesClient.TipoNotificacionEnum.ADVERTENCIA); +// public static async Task ObtieneEmailSiguienteAsync(tscgestionasegasa bd, polizassg pl, string Grupo, string CorreosAOmitir = "") +// { +// try +// { +// if (Grupo.NothingAVacio() == "") +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En ObtieneEmailSiguiente.", "Rutina: ObtieneEmailSiguiente. " + " El ramo de la póliza " + pl.NumeroPoliza + " no tiene asignado grupo de destinatario de correos", TsNotificacionesClient.TipoNotificacionEnum.ADVERTENCIA); - Grupo = "GRERNA"; - } - string dest = ""; - var idprodat = bd.enumeraciones.First(x => x.Codigo == "DOCRAM.PRODAT").idEnumeracion; - var dp = pl.documentospolizassg.Where(x => x.idCorreoAsegasa.HasValue && (x.idDocumentoASolicitar.HasValue == false || x.idDocumentoASolicitarNavigation.idTipo != idprodat)).FirstOrDefault(); - if (dp != null) - { - dest = dp.idCorreoAsegasaNavigation.Destinatario.NothingAVacio(); - } - if (dest.NothingAVacio() == "" || CorreosAOmitir.Contains(dest)) - { - var Oficina = pl.OficinaAgente; - var Lusu = bd.usuarios.Where(x => x.email != null && x.Oficina.ToLower() == Oficina.ToLower()).ToList(); - // Original in VB checked subagentes is not nothing. EF Core navigational props can be null checked - if (pl.idSubAgenteNavigation != null && pl.idSubAgenteNavigation.idUsuarioRelacionado.HasValue) - { - if (Lusu.Any(x => x.idUsuario == pl.idSubAgenteNavigation.idUsuarioRelacionado.Value)) - { - dest = pl.idSubAgenteNavigation.idUsuarioRelacionadoNavigation.email; - } - } - else - { - if (pl.idUsuario.HasValue) - { - if (Lusu.Any(x => x.idUsuario == pl.idUsuario.Value)) - { - dest = pl.idUsuarioNavigation.email; - } - } - } - if (dest == "" || CorreosAOmitir.Contains(dest)) - { - var emg = bd.enumeraciones.Where(x => x.idGrupoEnumeracionNavigation.Grupo == Grupo).ToList(); - var enumemail = emg.Where(x => Lusu.Any(y => y.Usuario.ToLower() == x.Codigo.Split('.')[1].ToLower())).OrderBy(x => x.ValorNumerico1.Value).First(); - enumemail.ValorNumerico1 = DateTime.Now.Ticks; - bd.SaveChanges(); - var codusu = enumemail.Codigo.Split('.')[1]; - var USU = bd.usuarios.First(x => x.Usuario == codusu); - var Email = USU.email; - dest = Email; - } - } - return dest; - } - catch (Exception EX) - { - throw new Exception("Error ObtieneEamilSiguiente póliza id:" + pl.idPoliza.ToString() + " " + EX.Message, EX); - } - } +// Grupo = "GRERNA"; +// } +// string dest = ""; +// var idprodat = bd.enumeraciones.First(x => x.Codigo == "DOCRAM.PRODAT").idEnumeracion; +// var dp = pl.documentospolizassg.Where(x => x.idCorreoAsegasa.HasValue && (x.idDocumentoASolicitar.HasValue == false || x.idDocumentoASolicitarNavigation.idTipo != idprodat)).FirstOrDefault(); +// if (dp != null) +// { +// dest = dp.idCorreoAsegasaNavigation.Destinatario.NothingAVacio(); +// } +// if (dest.NothingAVacio() == "" || CorreosAOmitir.Contains(dest)) +// { +// var Oficina = pl.OficinaAgente; +// var Lusu = bd.usuarios.Where(x => x.email != null && x.Oficina.ToLower() == Oficina.ToLower()).ToList(); +// // Original in VB checked subagentes is not nothing. EF Core navigational props can be null checked +// if (pl.idSubAgenteNavigation != null && pl.idSubAgenteNavigation.idUsuarioRelacionado.HasValue) +// { +// if (Lusu.Any(x => x.idUsuario == pl.idSubAgenteNavigation.idUsuarioRelacionado.Value)) +// { +// dest = pl.idSubAgenteNavigation.idUsuarioRelacionadoNavigation.email; +// } +// } +// else +// { +// if (pl.idUsuario.HasValue) +// { +// if (Lusu.Any(x => x.idUsuario == pl.idUsuario.Value)) +// { +// dest = pl.idUsuarioNavigation.email; +// } +// } +// } +// if (dest == "" || CorreosAOmitir.Contains(dest)) +// { +// var emg = bd.enumeraciones.Where(x => x.idGrupoEnumeracionNavigation.Grupo == Grupo).ToList(); +// var enumemail = emg.Where(x => Lusu.Any(y => y.Usuario.ToLower() == x.Codigo.Split('.')[1].ToLower())).OrderBy(x => x.ValorNumerico1.Value).First(); +// enumemail.ValorNumerico1 = DateTime.Now.Ticks; +// bd.SaveChanges(); +// var codusu = enumemail.Codigo.Split('.')[1]; +// var USU = bd.usuarios.First(x => x.Usuario == codusu); +// var Email = USU.email; +// dest = Email; +// } +// } +// return dest; +// } +// catch (Exception EX) +// { +// throw new Exception("Error ObtieneEamilSiguiente póliza id:" + pl.idPoliza.ToString() + " " + EX.Message, EX); +// } +// } - internal static async Task GenerarCorreosPagosAContabilidadAsync() - { - try - { - var bd = tscgestionasegasa.NuevoContexto(); - var pagos = bd.pagostelematicos.Where(x => x.FechaConfirmacionPasarela.HasValue && x.idEmailAvisoContabilidad.HasValue == false).ToList(); - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - var EmailContabilidad = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCONTA").ValorAlfabeticoLargo; +// internal static async Task GenerarCorreosPagosAContabilidadAsync() +// { +// try +// { +// var bd = tscgestionasegasa.NuevoContexto(); +// var pagos = bd.pagostelematicos.Where(x => x.FechaConfirmacionPasarela.HasValue && x.idEmailAvisoContabilidad.HasValue == false).ToList(); +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// var EmailContabilidad = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCONTA").ValorAlfabeticoLargo; - foreach (var p in pagos) - { - p.idEmailAvisoContabilidad = bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "Pago por web recibido. Identificación del pago: " + p.idPago.ToString(), "Le informamos que se ha realizado un pago telemático con los siguientes datos:" + "
" + - "Identificador Pago: " + p.idPago.ToString() + "
" + - "Referencia Pago: " + p.Referencia + "
" + - "D.N.I.: " + p.DNI + "
" + - "Teléfono: " + p.Telefono + "
" + - "Email Confirmación Pago: " + p.EmailConfirmacionPago + "
" + - "Código Recibo: " + p.CodigoRecibo + "
" + - "Importe: " + p.Importe.Value.ToString("c2") + "
" + - "FechaPago: " + p.FechaConfirmacionPasarela, - cta, EmailContabilidad); - bd.SaveChanges(); - } - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En GenerarCorreosPagosAContabilidad.", "Rutina: GenerarCorreosPagosAContabilidad. " + " " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// foreach (var p in pagos) +// { +// p.idEmailAvisoContabilidad = bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "Pago por web recibido. Identificación del pago: " + p.idPago.ToString(), "Le informamos que se ha realizado un pago telemático con los siguientes datos:" + "
" + +// "Identificador Pago: " + p.idPago.ToString() + "
" + +// "Referencia Pago: " + p.Referencia + "
" + +// "D.N.I.: " + p.DNI + "
" + +// "Teléfono: " + p.Telefono + "
" + +// "Email Confirmación Pago: " + p.EmailConfirmacionPago + "
" + +// "Código Recibo: " + p.CodigoRecibo + "
" + +// "Importe: " + p.Importe.Value.ToString("c2") + "
" + +// "FechaPago: " + p.FechaConfirmacionPasarela, +// cta, EmailContabilidad); +// bd.SaveChanges(); +// } +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En GenerarCorreosPagosAContabilidad.", "Rutina: GenerarCorreosPagosAContabilidad. " + " " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - internal static void GenerarCorreosPagosAPagadores() - { - var bd = tscgestionasegasa.NuevoContexto(); - var pagos = bd.pagostelematicos.Where(x => x.FechaConfirmacionPasarela.HasValue && x.idEmailAvisoAPagador.HasValue == false && x.EmailConfirmacionPago != null).ToList(); - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// internal static void GenerarCorreosPagosAPagadores() +// { +// var bd = tscgestionasegasa.NuevoContexto(); +// var pagos = bd.pagostelematicos.Where(x => x.FechaConfirmacionPasarela.HasValue && x.idEmailAvisoAPagador.HasValue == false && x.EmailConfirmacionPago != null).ToList(); +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - foreach (var p in pagos) - { - if (p.EmailConfirmacionPago.EsEmailValido()) - { - p.idEmailAvisoAPagador = bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "Pago a ASEGASA realizado correctamente. Identificación del pago: " + p.idPago.ToString(), "Le informamos que ha realizado un pago telemático a ASEGASA con lossiguientes datos:" + "
" + - "Identificador Pago: " + p.idPago.ToString() + "
" + - "Referencia Pago: " + p.Referencia + "
" + - "D.N.I.: " + p.DNI + "
" + - "Email Confirmación Pago: " + p.EmailConfirmacionPago + "
" + - "Teléfono: " + p.Telefono + "
" + - "Código Recibo: " + p.CodigoRecibo + "
" + - "Importe: " + p.Importe.Value.ToString("c2") + "
" + - "FechaPago: " + p.FechaConfirmacionPasarela, - cta, p.EmailConfirmacionPago); - bd.SaveChanges(); - } - } - } +// foreach (var p in pagos) +// { +// if (p.EmailConfirmacionPago.EsEmailValido()) +// { +// p.idEmailAvisoAPagador = bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "Pago a ASEGASA realizado correctamente. Identificación del pago: " + p.idPago.ToString(), "Le informamos que ha realizado un pago telemático a ASEGASA con lossiguientes datos:" + "
" + +// "Identificador Pago: " + p.idPago.ToString() + "
" + +// "Referencia Pago: " + p.Referencia + "
" + +// "D.N.I.: " + p.DNI + "
" + +// "Email Confirmación Pago: " + p.EmailConfirmacionPago + "
" + +// "Teléfono: " + p.Telefono + "
" + +// "Código Recibo: " + p.CodigoRecibo + "
" + +// "Importe: " + p.Importe.Value.ToString("c2") + "
" + +// "FechaPago: " + p.FechaConfirmacionPasarela, +// cta, p.EmailConfirmacionPago); +// bd.SaveChanges(); +// } +// } +// } - private static void GuardaTipoGestion(int idPoliza, int idTipo, string GestionesRealizadas, string MensajeError = "", tscgestionasegasa bd = null) - { - if (bd == null) bd = tscgestionasegasa.NuevoContexto(); - var tg = new gestionespolizassg(); +// private static void GuardaTipoGestion(int idPoliza, int idTipo, string GestionesRealizadas, string MensajeError = "", tscgestionasegasa bd = null) +// { +// if (bd == null) bd = tscgestionasegasa.NuevoContexto(); +// var tg = new gestionespolizassg(); - tg.Fecha = DateTime.Now; - tg.idTipo = idTipo; - tg.idPoliza = idPoliza; - tg.GestionesRealizadas = GestionesRealizadas; - if (MensajeError != "") - { - tg.ContieneErrores = true; - tg.Observaciones = MensajeError.Acortar(500); - } +// tg.Fecha = DateTime.Now; +// tg.idTipo = idTipo; +// tg.idPoliza = idPoliza; +// tg.GestionesRealizadas = GestionesRealizadas; +// if (MensajeError != "") +// { +// tg.ContieneErrores = true; +// tg.Observaciones = MensajeError.Acortar(500); +// } - bd.gestionespolizassg.Add(tg); - bd.SaveChanges(); - } +// bd.gestionespolizassg.Add(tg); +// bd.SaveChanges(); +// } - private static DataTable CrearEstructuraTablaParaHP() - { - DataTable dt = new DataTable(); - DataColumn dc; - dc = new DataColumn("FechaPresupuesto", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("FechaEfecto", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("FechaVencimiento", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("Compañia", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("Ramo", typeof(string)); - dc.MaxLength = 6; - dt.Columns.Add(dc); - dc = new DataColumn("Agente", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("SubAgente", typeof(string)); - dc.MaxLength = 4; - dt.Columns.Add(dc); - dc = new DataColumn("Matricula", typeof(string)); - dc.MaxLength = 16; - dt.Columns.Add(dc); - dc = new DataColumn("Marca", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("Modelo", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("ApellidosTomador", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("NombreTomador", typeof(string)); - dc.MaxLength = 16; - dt.Columns.Add(dc); - dc = new DataColumn("SexoTomador", typeof(string)); - dc.MaxLength = 2; - dt.Columns.Add(dc); - dc = new DataColumn("CifTomador", typeof(string)); - dt.Columns.Add(dc); - dc.MaxLength = 10; - dc = new DataColumn("FechaNacimientoTomador", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("DomicilioTomador", typeof(string)); - dc.MaxLength = 50; - dt.Columns.Add(dc); - dc = new DataColumn("TelefonoTomador", typeof(string)); - dc.MaxLength = 14; - dt.Columns.Add(dc); - dc = new DataColumn("CodigoPostalTomador", typeof(string)); - dc.MaxLength = 6; - dt.Columns.Add(dc); - dc = new DataColumn("PoblacionTomador", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("ProvinciaTomador", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("FechaCarnetTomador", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("ApellidosPropietario", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("NombrePropietario", typeof(string)); - dc.MaxLength = 16; - dt.Columns.Add(dc); - dc = new DataColumn("SexoPropietario", typeof(string)); - dc.MaxLength = 2; - dt.Columns.Add(dc); - dc = new DataColumn("CifPropietario", typeof(string)); - dt.Columns.Add(dc); - dc.MaxLength = 10; - dc = new DataColumn("FechaNacimientoPropietario", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("DomicilioPropietario", typeof(string)); - dc.MaxLength = 50; - dt.Columns.Add(dc); - dc = new DataColumn("TelefonoPropietario", typeof(string)); - dc.MaxLength = 14; - dt.Columns.Add(dc); - dc = new DataColumn("CodigoPostalPropietario", typeof(string)); - dc.MaxLength = 6; - dt.Columns.Add(dc); - dc = new DataColumn("PoblacionPropietario", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("ProvinciaPropietario", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("FechaCarnetPropietario", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("ApellidosConductor", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("NombreConductor", typeof(string)); - dc.MaxLength = 16; - dt.Columns.Add(dc); - dc = new DataColumn("SexoConductor", typeof(string)); - dc.MaxLength = 2; - dt.Columns.Add(dc); - dc = new DataColumn("CifConductor", typeof(string)); - dt.Columns.Add(dc); - dc.MaxLength = 10; - dc = new DataColumn("FechaNacimientoConductor", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("DomicilioConductor", typeof(string)); - dc.MaxLength = 50; - dt.Columns.Add(dc); - dc = new DataColumn("TelefonoConductor", typeof(string)); - dc.MaxLength = 14; - dt.Columns.Add(dc); - dc = new DataColumn("CodigoPostalConductor", typeof(string)); - dc.MaxLength = 6; - dt.Columns.Add(dc); - dc = new DataColumn("PoblacionConductor", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("ProvinciaConductor", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("FechaCarnetConductor", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("ApellidosPagador", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("NombrePagador", typeof(string)); - dc.MaxLength = 16; - dt.Columns.Add(dc); - dc = new DataColumn("SexoPagador", typeof(string)); - dc.MaxLength = 2; - dt.Columns.Add(dc); - dc = new DataColumn("CifPagador", typeof(string)); - dt.Columns.Add(dc); - dc.MaxLength = 10; - dc = new DataColumn("FechaNacimientoPagador", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("DomicilioPagador", typeof(string)); - dc.MaxLength = 50; - dt.Columns.Add(dc); - dc = new DataColumn("TelefonoPagador", typeof(string)); - dc.MaxLength = 14; - dt.Columns.Add(dc); - dc = new DataColumn("CodigoPostalPagador", typeof(string)); - dc.MaxLength = 6; - dt.Columns.Add(dc); - dc = new DataColumn("PoblacionPagador", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("ProvinciaPagador", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("FechaCarnetPagador", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("CuentaBancaria", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("Coberturas", typeof(string)); - dc.MaxLength = 68; - dt.Columns.Add(dc); - dc = new DataColumn("Descripcion", typeof(string)); - dc.MaxLength = 68; - dt.Columns.Add(dc); - dc = new DataColumn("FraccionamientoPago", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("idContratacion", typeof(int)); - dt.Columns.Add(dc); - dc = new DataColumn("telefono1", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("telefono2", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("email", typeof(string)); - dc.MaxLength = 128; - dt.Columns.Add(dc); - dc = new DataColumn("NumeroPoliza", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); +// private static DataTable CrearEstructuraTablaParaHP() +// { +// DataTable dt = new DataTable(); +// DataColumn dc; +// dc = new DataColumn("FechaPresupuesto", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("FechaEfecto", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("FechaVencimiento", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("Compañia", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("Ramo", typeof(string)); +// dc.MaxLength = 6; +// dt.Columns.Add(dc); +// dc = new DataColumn("Agente", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("SubAgente", typeof(string)); +// dc.MaxLength = 4; +// dt.Columns.Add(dc); +// dc = new DataColumn("Matricula", typeof(string)); +// dc.MaxLength = 16; +// dt.Columns.Add(dc); +// dc = new DataColumn("Marca", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("Modelo", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("ApellidosTomador", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("NombreTomador", typeof(string)); +// dc.MaxLength = 16; +// dt.Columns.Add(dc); +// dc = new DataColumn("SexoTomador", typeof(string)); +// dc.MaxLength = 2; +// dt.Columns.Add(dc); +// dc = new DataColumn("CifTomador", typeof(string)); +// dt.Columns.Add(dc); +// dc.MaxLength = 10; +// dc = new DataColumn("FechaNacimientoTomador", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("DomicilioTomador", typeof(string)); +// dc.MaxLength = 50; +// dt.Columns.Add(dc); +// dc = new DataColumn("TelefonoTomador", typeof(string)); +// dc.MaxLength = 14; +// dt.Columns.Add(dc); +// dc = new DataColumn("CodigoPostalTomador", typeof(string)); +// dc.MaxLength = 6; +// dt.Columns.Add(dc); +// dc = new DataColumn("PoblacionTomador", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("ProvinciaTomador", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("FechaCarnetTomador", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("ApellidosPropietario", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("NombrePropietario", typeof(string)); +// dc.MaxLength = 16; +// dt.Columns.Add(dc); +// dc = new DataColumn("SexoPropietario", typeof(string)); +// dc.MaxLength = 2; +// dt.Columns.Add(dc); +// dc = new DataColumn("CifPropietario", typeof(string)); +// dt.Columns.Add(dc); +// dc.MaxLength = 10; +// dc = new DataColumn("FechaNacimientoPropietario", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("DomicilioPropietario", typeof(string)); +// dc.MaxLength = 50; +// dt.Columns.Add(dc); +// dc = new DataColumn("TelefonoPropietario", typeof(string)); +// dc.MaxLength = 14; +// dt.Columns.Add(dc); +// dc = new DataColumn("CodigoPostalPropietario", typeof(string)); +// dc.MaxLength = 6; +// dt.Columns.Add(dc); +// dc = new DataColumn("PoblacionPropietario", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("ProvinciaPropietario", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("FechaCarnetPropietario", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("ApellidosConductor", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("NombreConductor", typeof(string)); +// dc.MaxLength = 16; +// dt.Columns.Add(dc); +// dc = new DataColumn("SexoConductor", typeof(string)); +// dc.MaxLength = 2; +// dt.Columns.Add(dc); +// dc = new DataColumn("CifConductor", typeof(string)); +// dt.Columns.Add(dc); +// dc.MaxLength = 10; +// dc = new DataColumn("FechaNacimientoConductor", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("DomicilioConductor", typeof(string)); +// dc.MaxLength = 50; +// dt.Columns.Add(dc); +// dc = new DataColumn("TelefonoConductor", typeof(string)); +// dc.MaxLength = 14; +// dt.Columns.Add(dc); +// dc = new DataColumn("CodigoPostalConductor", typeof(string)); +// dc.MaxLength = 6; +// dt.Columns.Add(dc); +// dc = new DataColumn("PoblacionConductor", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("ProvinciaConductor", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("FechaCarnetConductor", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("ApellidosPagador", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("NombrePagador", typeof(string)); +// dc.MaxLength = 16; +// dt.Columns.Add(dc); +// dc = new DataColumn("SexoPagador", typeof(string)); +// dc.MaxLength = 2; +// dt.Columns.Add(dc); +// dc = new DataColumn("CifPagador", typeof(string)); +// dt.Columns.Add(dc); +// dc.MaxLength = 10; +// dc = new DataColumn("FechaNacimientoPagador", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("DomicilioPagador", typeof(string)); +// dc.MaxLength = 50; +// dt.Columns.Add(dc); +// dc = new DataColumn("TelefonoPagador", typeof(string)); +// dc.MaxLength = 14; +// dt.Columns.Add(dc); +// dc = new DataColumn("CodigoPostalPagador", typeof(string)); +// dc.MaxLength = 6; +// dt.Columns.Add(dc); +// dc = new DataColumn("PoblacionPagador", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("ProvinciaPagador", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("FechaCarnetPagador", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("CuentaBancaria", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("Coberturas", typeof(string)); +// dc.MaxLength = 68; +// dt.Columns.Add(dc); +// dc = new DataColumn("Descripcion", typeof(string)); +// dc.MaxLength = 68; +// dt.Columns.Add(dc); +// dc = new DataColumn("FraccionamientoPago", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("idContratacion", typeof(int)); +// dt.Columns.Add(dc); +// dc = new DataColumn("telefono1", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("telefono2", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("email", typeof(string)); +// dc.MaxLength = 128; +// dt.Columns.Add(dc); +// dc = new DataColumn("NumeroPoliza", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); - dc = new DataColumn("ApellidosConductorAdicional", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("NombreConductorAdicional", typeof(string)); - dc.MaxLength = 16; - dt.Columns.Add(dc); - dc = new DataColumn("SexoConductorAdicional", typeof(string)); - dc.MaxLength = 2; - dt.Columns.Add(dc); - dc = new DataColumn("CifConductorAdicional", typeof(string)); - dt.Columns.Add(dc); - dc.MaxLength = 10; - dc = new DataColumn("FechaNacimientoConductorAdicional", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("DomicilioConductorAdicional", typeof(string)); - dc.MaxLength = 50; - dt.Columns.Add(dc); - dc = new DataColumn("TelefonoConductorAdicional", typeof(string)); - dc.MaxLength = 14; - dt.Columns.Add(dc); - dc = new DataColumn("CodigoPostalConductorAdicional", typeof(string)); - dc.MaxLength = 6; - dt.Columns.Add(dc); - dc = new DataColumn("PoblacionConductorAdicional", typeof(string)); - dc.MaxLength = 30; - dt.Columns.Add(dc); - dc = new DataColumn("ProvinciaConductorAdicional", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - dc = new DataColumn("FechaCarnetConductorAdicional", typeof(DateTime)); - dt.Columns.Add(dc); - dc = new DataColumn("PrefijoIBAN", typeof(string)); - dc.MaxLength = 4; - dt.Columns.Add(dc); - dc = new DataColumn("NumeroPresupuesto", typeof(string)); - dc.MaxLength = 20; - dt.Columns.Add(dc); - return dt; - } +// dc = new DataColumn("ApellidosConductorAdicional", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("NombreConductorAdicional", typeof(string)); +// dc.MaxLength = 16; +// dt.Columns.Add(dc); +// dc = new DataColumn("SexoConductorAdicional", typeof(string)); +// dc.MaxLength = 2; +// dt.Columns.Add(dc); +// dc = new DataColumn("CifConductorAdicional", typeof(string)); +// dt.Columns.Add(dc); +// dc.MaxLength = 10; +// dc = new DataColumn("FechaNacimientoConductorAdicional", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("DomicilioConductorAdicional", typeof(string)); +// dc.MaxLength = 50; +// dt.Columns.Add(dc); +// dc = new DataColumn("TelefonoConductorAdicional", typeof(string)); +// dc.MaxLength = 14; +// dt.Columns.Add(dc); +// dc = new DataColumn("CodigoPostalConductorAdicional", typeof(string)); +// dc.MaxLength = 6; +// dt.Columns.Add(dc); +// dc = new DataColumn("PoblacionConductorAdicional", typeof(string)); +// dc.MaxLength = 30; +// dt.Columns.Add(dc); +// dc = new DataColumn("ProvinciaConductorAdicional", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// dc = new DataColumn("FechaCarnetConductorAdicional", typeof(DateTime)); +// dt.Columns.Add(dc); +// dc = new DataColumn("PrefijoIBAN", typeof(string)); +// dc.MaxLength = 4; +// dt.Columns.Add(dc); +// dc = new DataColumn("NumeroPresupuesto", typeof(string)); +// dc.MaxLength = 20; +// dt.Columns.Add(dc); +// return dt; +// } - public static async Task CompruebaPolizasConTomadorErroneoAsync() - { - try - { - var bd = tscgestionasegasa.NuevoContexto(); - var pols = bd.polizassg.Where(x => x.entidadespolizas.Where(y => y.EsTomador).Count() != 1).ToList(); - var cta = bd.cuentascorreo.First(x => x.Codigo == "DEFECTO"); - foreach (var pl in pols) - { - var sAsunto = "Póliza con tomador erróneo " + pl.idRamoNavigation.Descripcion + " Nº Presupuesto: " + pl.idPoliza.ToString(); - var sCuerpo = "La Póliza con numero presupuesto: " + pl.idPoliza.ToString() + " tiene " + pl.entidadespolizas.Where(x => x.EsTomador).Count().ToString() + " tomadores."; - var sDest = pl.idRamoNavigation.DestinatariosCorreosDocumentacion; - if (!sDest.Contains("@")) sDest = await ObtieneEmailSiguienteAsync(bd, pl, sDest); - var idcorreo = bdAsegasa.db.correos.GeneraRegistroCorreo(bd, sAsunto, sCuerpo, cta, sDest); - bd.SaveChanges(); - } - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En CompruebaPolizasConTomadorErroneo.", "Rutina: CompruebaPolizasConTomadorErroneo. " + " " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// public static async Task CompruebaPolizasConTomadorErroneoAsync() +// { +// try +// { +// var bd = tscgestionasegasa.NuevoContexto(); +// var pols = bd.polizassg.Where(x => x.entidadespolizas.Where(y => y.EsTomador).Count() != 1).ToList(); +// var cta = bd.cuentascorreo.First(x => x.Codigo == "DEFECTO"); +// foreach (var pl in pols) +// { +// var sAsunto = "Póliza con tomador erróneo " + pl.idRamoNavigation.Descripcion + " Nº Presupuesto: " + pl.idPoliza.ToString(); +// var sCuerpo = "La Póliza con numero presupuesto: " + pl.idPoliza.ToString() + " tiene " + pl.entidadespolizas.Where(x => x.EsTomador).Count().ToString() + " tomadores."; +// var sDest = pl.idRamoNavigation.DestinatariosCorreosDocumentacion; +// if (!sDest.Contains("@")) sDest = await ObtieneEmailSiguienteAsync(bd, pl, sDest); +// var idcorreo = bdAsegasa.db.correos.GeneraRegistroCorreo(bd, sAsunto, sCuerpo, cta, sDest); +// bd.SaveChanges(); +// } +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En CompruebaPolizasConTomadorErroneo.", "Rutina: CompruebaPolizasConTomadorErroneo. " + " " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task CompruebaPolizasSinRecibosVigentesAsync() - { - try - { - var bd = tscgestionasegasa.NuevoContexto(); - DateOnly hoy = DateOnly.FromDateTime(DateTime.Now); - var tcou = bd.enumeraciones.First(x => x.Codigo == "TCO.U").idEnumeracion; - // Since this uses lazy loading or explicit includes, I'll translate string-based include if needed, but in Entity Framework Core it might not be literally supported via string without `Microsoft.EntityFrameworkCore`. The request is "literal equivalence": - // Original: Dim pols = bd.polizassg.Include("recibos").Where... - // Assuming `Microsoft.EntityFrameworkCore` is globally used or we can use `bd.polizassg.Where...` omitting ".Include" if EF Core proxies lazy load, BUT we'll stick to string include or omit since we don't have using EF. - // Wait, I will just write .Where without include, or rather, I won't write include to avoid missing reference, or I just use EF core include. - // "Literal" translation rules: I should use `.Where` directly if lazy loading works, or just write it literally. I'll translate blindly `bd.polizassg.Include("recibos").Where`. Wait, `Include()` requires `Microsoft.EntityFrameworkCore`. I will just not include the `using` and assume it's in global usings, or write it explicitly. Actually, the user's `Guia_Antigravity.md` didn't explicitly forbid Include, but said: `"quiero que me lo pasas literalmente"`. +// public static async Task CompruebaPolizasSinRecibosVigentesAsync() +// { +// try +// { +// var bd = tscgestionasegasa.NuevoContexto(); +// DateOnly hoy = DateOnly.FromDateTime(DateTime.Now); +// var tcou = bd.enumeraciones.First(x => x.Codigo == "TCO.U").idEnumeracion; +// // Since this uses lazy loading or explicit includes, I'll translate string-based include if needed, but in Entity Framework Core it might not be literally supported via string without `Microsoft.EntityFrameworkCore`. The request is "literal equivalence": +// // Original: Dim pols = bd.polizassg.Include("recibos").Where... +// // Assuming `Microsoft.EntityFrameworkCore` is globally used or we can use `bd.polizassg.Where...` omitting ".Include" if EF Core proxies lazy load, BUT we'll stick to string include or omit since we don't have using EF. +// // Wait, I will just write .Where without include, or rather, I won't write include to avoid missing reference, or I just use EF core include. +// // "Literal" translation rules: I should use `.Where` directly if lazy loading works, or just write it literally. I'll translate blindly `bd.polizassg.Include("recibos").Where`. Wait, `Include()` requires `Microsoft.EntityFrameworkCore`. I will just not include the `using` and assume it's in global usings, or write it explicitly. Actually, the user's `Guia_Antigravity.md` didn't explicitly forbid Include, but said: `"quiero que me lo pasas literalmente"`. - // Let's omit .Include("recibos") if it causes errors, actually .Include("recibos") works in EF 6 but in EF Core it might be `Include(x => x.recibos)`. I will use EF Core safe `Include(x => x.recibos)` or just write what's there. No, I'll use `Include("recibos")` since the goal is literal string translation. Wait, `Microsoft.EntityFrameworkCore` is not imported. I'll omit it, or import it. I'll just write `Include("recibos")` and if it fails, I'll fix it. Let's omit `Include` because `x.recibos.Any()` triggers eager/lazy load in typical modern implementations implicitly if it's evaluated server-side. - // Wait, the `.Any()` is executed inside the DB query! It doesn't need `.Include()`! `.Include` was only for getting the loaded items. +// // Let's omit .Include("recibos") if it causes errors, actually .Include("recibos") works in EF 6 but in EF Core it might be `Include(x => x.recibos)`. I will use EF Core safe `Include(x => x.recibos)` or just write what's there. No, I'll use `Include("recibos")` since the goal is literal string translation. Wait, `Microsoft.EntityFrameworkCore` is not imported. I'll omit it, or import it. I'll just write `Include("recibos")` and if it fails, I'll fix it. Let's omit `Include` because `x.recibos.Any()` triggers eager/lazy load in typical modern implementations implicitly if it's evaluated server-side. +// // Wait, the `.Any()` is executed inside the DB query! It doesn't need `.Include()`! `.Include` was only for getting the loaded items. - var pols = bd.polizassg.Where(x => x.NumeroPoliza != null && x.idTipoCobro != tcou && x.NumeroPoliza != "" && x.FechaBaja.HasValue == false && x.recibos.Any() && x.recibos.Any(y => y.FechaBaja.HasValue == false && y.FechaVencimiento >= hoy) == false).ToList(); - var l = pols.Select(x => x.AListadoGenerico()).ToList(); +// var pols = bd.polizassg.Where(x => x.NumeroPoliza != null && x.idTipoCobro != tcou && x.NumeroPoliza != "" && x.FechaBaja.HasValue == false && x.recibos.Any() && x.recibos.Any(y => y.FechaBaja.HasValue == false && y.FechaVencimiento >= hoy) == false).ToList(); +// var l = pols.Select(x => x.AListadoGenerico()).ToList(); - byte[] b = tsUtilidades.Excel.IEnumerableAExcel(l); - File.WriteAllBytes(@"c:\tmp\polizassinrecibosvigentes.xlsx", b); - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En CompruebaPolizasSinRecibosVigentes.", "Rutina: CompruebaPolizasConTomadorErroneo. " + " " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// byte[] b = tsUtilidades.Excel.IEnumerableAExcel(l); +// File.WriteAllBytes(@"c:\tmp\polizassinrecibosvigentes.xlsx", b); +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En CompruebaPolizasSinRecibosVigentes.", "Rutina: CompruebaPolizasConTomadorErroneo. " + " " + ex.Message, TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task CompruebaPolizasVigentesMatriculaDuplicadaAsync() - { - try - { - var bd = tscgestionasegasa.NuevoContexto(); - DateOnly hoy = DateOnly.FromDateTime(DateTime.Now); +// public static async Task CompruebaPolizasVigentesMatriculaDuplicadaAsync() +// { +// try +// { +// var bd = tscgestionasegasa.NuevoContexto(); +// DateOnly hoy = DateOnly.FromDateTime(DateTime.Now); - var tcou = bd.enumeraciones.First(x => x.Codigo == "TCO.U").idEnumeracion; - var pols = bd.polizassg.Where(x => x.idRamoNavigation.idFamiliaRamoNavigation.Codigo == "FAMRAM.AU" && x.Matricula != null && x.Matricula != "" && x.NumeroPoliza != null && x.idTipoCobro != tcou && x.NumeroPoliza != "" && x.FechaBaja.HasValue == false && x.recibos.Any() && x.recibos.Any(y => y.FechaBaja.HasValue == false && y.FechaVencimiento >= hoy)).ToList(); - var pola = pols.GroupBy(x => x.Matricula).Where(x => x.Count() > 1).ToList(); - var lp = new List(); - foreach (var gp in pola) - { - foreach (var p in gp) - { - var recs = p.recibos.Where(x => x.FechaBaja.HasValue == false && x.FechaVencimiento >= hoy).ToList(); - var recsg = gp.SelectMany(x => x.recibos).Where(x => x.FechaBaja.HasValue == false && x.idPolizaNavigation.idCompania != p.idCompania && x.idPoliza != p.idPoliza && x.idPolizaNavigation.idRamo == p.idRamo); - foreach (var r in recs) - { - if (recsg.Any(x => tsUtilidades.Utilidades.IntervalosFechasCoincidentes(x.FechaEfecto, x.FechaVencimiento, r.FechaEfecto, r.FechaVencimiento))) - { - lp.Add(p); - break; - } - } - } - } +// var tcou = bd.enumeraciones.First(x => x.Codigo == "TCO.U").idEnumeracion; +// var pols = bd.polizassg.Where(x => x.idRamoNavigation.idFamiliaRamoNavigation.Codigo == "FAMRAM.AU" && x.Matricula != null && x.Matricula != "" && x.NumeroPoliza != null && x.idTipoCobro != tcou && x.NumeroPoliza != "" && x.FechaBaja.HasValue == false && x.recibos.Any() && x.recibos.Any(y => y.FechaBaja.HasValue == false && y.FechaVencimiento >= hoy)).ToList(); +// var pola = pols.GroupBy(x => x.Matricula).Where(x => x.Count() > 1).ToList(); +// var lp = new List(); +// foreach (var gp in pola) +// { +// foreach (var p in gp) +// { +// var recs = p.recibos.Where(x => x.FechaBaja.HasValue == false && x.FechaVencimiento >= hoy).ToList(); +// var recsg = gp.SelectMany(x => x.recibos).Where(x => x.FechaBaja.HasValue == false && x.idPolizaNavigation.idCompania != p.idCompania && x.idPoliza != p.idPoliza && x.idPolizaNavigation.idRamo == p.idRamo); +// foreach (var r in recs) +// { +// if (recsg.Any(x => tsUtilidades.Utilidades.IntervalosFechasCoincidentes(x.FechaEfecto, x.FechaVencimiento, r.FechaEfecto, r.FechaVencimiento))) +// { +// lp.Add(p); +// break; +// } +// } +// } +// } - var l = lp.Select(x => x.AListadoGenerico()).ToList(); - byte[] b = tsUtilidades.Excel.IEnumerableAExcel(l); - File.WriteAllBytes(@"c:\tmp\posiblespolizasduplicadas.xlsx", b); - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En CompruebaPolizasVigentesMatriculaDuplicada.", "Rutina: CompruebaPolizasConTomadorErroneo. " + " " + ex.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// var l = lp.Select(x => x.AListadoGenerico()).ToList(); +// byte[] b = tsUtilidades.Excel.IEnumerableAExcel(l); +// File.WriteAllBytes(@"c:\tmp\posiblespolizasduplicadas.xlsx", b); +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En CompruebaPolizasVigentesMatriculaDuplicada.", "Rutina: CompruebaPolizasConTomadorErroneo. " + " " + ex.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - internal static async Task EliminaPresupuestosNoAceptados30DiasAsync() - { - try - { - var bd = tscgestionasegasa.NuevoContexto(); - var fechainicio = DateTime.Today.AddDays(-30); - var pna = bd.polizassg.Where(x => x.FechaAceptacionPresupuesto == null && x.NumeroPoliza == null && x.FechaAlta < fechainicio).ToList(); - foreach (var p in pna) - { - // EF Core delete is Remove - bd.polizassg.Remove(p); - } - bd.SaveChanges(); - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En EliminaPresupuestosNoAceptados30Dias.", "Rutina: EliminaPresupuestosNoAceptados30Dias. " + " " + ex.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// internal static async Task EliminaPresupuestosNoAceptados30DiasAsync() +// { +// try +// { +// var bd = tscgestionasegasa.NuevoContexto(); +// var fechainicio = DateTime.Today.AddDays(-30); +// var pna = bd.polizassg.Where(x => x.FechaAceptacionPresupuesto == null && x.NumeroPoliza == null && x.FechaAlta < fechainicio).ToList(); +// foreach (var p in pna) +// { +// // EF Core delete is Remove +// bd.polizassg.Remove(p); +// } +// bd.SaveChanges(); +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En EliminaPresupuestosNoAceptados30Dias.", "Rutina: EliminaPresupuestosNoAceptados30Dias. " + " " + ex.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task GeneraCorreosDocumentacionPendienteAsync() - { - try - { - var bd = tscgestionasegasa.NuevoContexto(); - var fechainicio = DateTime.Today.AddDays(-7); - var idTipoAdjunto = bd.enumeraciones.First(x => x.Codigo == "TIPFIC.ADJCOR").idEnumeracion; - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - var copiaoculta = bd.enumeraciones.First(x => x.Codigo == "CONF.CO-CORREOS").ValorAlfabeticoLargo; - var agentesList = bd.polizassg.Where(x => x.FechaBaja.HasValue == false && (x.NumeroPoliza != null || x.FechaAceptacionPresupuesto != null) && (x.FechaAlta >= fechainicio && (x.FechaDocumentosSuplementoRevisado != null || x.NumeroSuplemento == 0 || x.idAgenteNavigation.Codigo == "1" || x.idAgenteNavigation.Codigo == "2") && x.documentospolizassg.Any(y => y.FechaComprobacion == null && y.idFichero == null && y.Obligatorio && y.idDocumentoASolicitarNavigation.SolicitarAAgente))).GroupBy(x => x.idAgente).Select(x => x.FirstOrDefault().idAgenteNavigation).Where(x => x.Email != "").OrderBy(x => x.Nombre).ToList(); +// public static async Task GeneraCorreosDocumentacionPendienteAsync() +// { +// try +// { +// var bd = tscgestionasegasa.NuevoContexto(); +// var fechainicio = DateTime.Today.AddDays(-7); +// var idTipoAdjunto = bd.enumeraciones.First(x => x.Codigo == "TIPFIC.ADJCOR").idEnumeracion; +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// var copiaoculta = bd.enumeraciones.First(x => x.Codigo == "CONF.CO-CORREOS").ValorAlfabeticoLargo; +// var agentesList = bd.polizassg.Where(x => x.FechaBaja.HasValue == false && (x.NumeroPoliza != null || x.FechaAceptacionPresupuesto != null) && (x.FechaAlta >= fechainicio && (x.FechaDocumentosSuplementoRevisado != null || x.NumeroSuplemento == 0 || x.idAgenteNavigation.Codigo == "1" || x.idAgenteNavigation.Codigo == "2") && x.documentospolizassg.Any(y => y.FechaComprobacion == null && y.idFichero == null && y.Obligatorio && y.idDocumentoASolicitarNavigation.SolicitarAAgente))).GroupBy(x => x.idAgente).Select(x => x.FirstOrDefault().idAgenteNavigation).Where(x => x.Email != "").OrderBy(x => x.Nombre).ToList(); - var xr = new DevExpress.XtraReports.UI.XtraReport(); +// var xr = new DevExpress.XtraReports.UI.XtraReport(); - foreach (var a in agentesList) - { - try - { - var ds = new List(); - ds.Add(a); - var f = new bdAsegasa.db.ficheros(); +// foreach (var a in agentesList) +// { +// try +// { +// var ds = new List(); +// ds.Add(a); +// var f = new bdAsegasa.db.ficheros(); - f.Fichero = bdAsegasa.Informes.Informes.GeneraXLSX(null, ds).ToArray(); - f.idTipo = idTipoAdjunto; - f.Fecha = DateTime.Now; - f.Descripcion = "Documentación Pendiente Agente: " + a.Codigo + " " + DateTime.Today.ToShortDateString(); - f.NombreFichero = DateTime.Today.ToShortDateString().Replace("/", "-") + "_Documentacion_Pendiente_" + a.Codigo + ".xlsx"; +// f.Fichero = bdAsegasa.Informes.Informes.GeneraXLSX(null, ds).ToArray(); +// f.idTipo = idTipoAdjunto; +// f.Fecha = DateTime.Now; +// f.Descripcion = "Documentación Pendiente Agente: " + a.Codigo + " " + DateTime.Today.ToShortDateString(); +// f.NombreFichero = DateTime.Today.ToShortDateString().Replace("/", "-") + "_Documentacion_Pendiente_" + a.Codigo + ".xlsx"; - bd.ficheros.Add(f); - bd.SaveChanges(); - bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "Pólizas con documentación pendiente de Recibir", "Distinguidos Sres., adjunto le remitimos listado de pólizas de las cuales tenemos pendiente recibir su documentación.", cta, a.Email, null, null, f.idFichero, Remitente: copiaoculta); - } - catch (Exception EX) - { - throw new Exception("Error GeneraCorreosDocumentacionPendiente agente: " + a.Codigo + " " + EX.Message, EX); - } - } +// bd.ficheros.Add(f); +// bd.SaveChanges(); +// bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "Pólizas con documentación pendiente de Recibir", "Distinguidos Sres., adjunto le remitimos listado de pólizas de las cuales tenemos pendiente recibir su documentación.", cta, a.Email, null, null, f.idFichero, Remitente: copiaoculta); +// } +// catch (Exception EX) +// { +// throw new Exception("Error GeneraCorreosDocumentacionPendiente agente: " + a.Codigo + " " + EX.Message, EX); +// } +// } - var Subagentes = bd.polizassg.Where(x => x.FechaBaja.HasValue == false && (x.NumeroPoliza != null || x.FechaAceptacionPresupuesto != null) && (x.FechaAlta >= fechainicio && x.idSubAgente != null && x.documentospolizassg.Any(y => y.FechaComprobacion == null && y.idFichero == null && y.Obligatorio && y.idDocumentoASolicitarNavigation.SolicitarAAgente)) && x.idSubAgenteNavigation.Email != "").GroupBy(x => x.idSubAgente).Select(x => x.FirstOrDefault().idSubAgenteNavigation).ToList(); - // var xrs = new xrDocumentosPendientesSubAgentes(); +// var Subagentes = bd.polizassg.Where(x => x.FechaBaja.HasValue == false && (x.NumeroPoliza != null || x.FechaAceptacionPresupuesto != null) && (x.FechaAlta >= fechainicio && x.idSubAgente != null && x.documentospolizassg.Any(y => y.FechaComprobacion == null && y.idFichero == null && y.Obligatorio && y.idDocumentoASolicitarNavigation.SolicitarAAgente)) && x.idSubAgenteNavigation.Email != "").GroupBy(x => x.idSubAgente).Select(x => x.FirstOrDefault().idSubAgenteNavigation).ToList(); +// // var xrs = new xrDocumentosPendientesSubAgentes(); - foreach (var s in Subagentes) - { - var ds = new List(); - ds.Add(s); +// foreach (var s in Subagentes) +// { +// var ds = new List(); +// ds.Add(s); - var f = new bdAsegasa.db.ficheros(); +// var f = new bdAsegasa.db.ficheros(); - f.Fichero = bdAsegasa.Informes.Informes.GeneraXLSX(null /* xrs */, ds).ToArray(); - f.idTipo = idTipoAdjunto; - f.Fecha = DateTime.Now; - f.Descripcion = "Documentación Pendiente Subagente: " + s.idAgenteNavigation.Codigo + "-" + s.Codigo + " " + DateTime.Today.ToShortDateString(); - f.NombreFichero = DateTime.Today.ToShortDateString().Replace("/", "-") + "_Documentacion_Pendiente_" + s.idAgenteNavigation.Codigo + "-" + s.Codigo + ".xlsx"; +// f.Fichero = bdAsegasa.Informes.Informes.GeneraXLSX(null /* xrs */, ds).ToArray(); +// f.idTipo = idTipoAdjunto; +// f.Fecha = DateTime.Now; +// f.Descripcion = "Documentación Pendiente Subagente: " + s.idAgenteNavigation.Codigo + "-" + s.Codigo + " " + DateTime.Today.ToShortDateString(); +// f.NombreFichero = DateTime.Today.ToShortDateString().Replace("/", "-") + "_Documentacion_Pendiente_" + s.idAgenteNavigation.Codigo + "-" + s.Codigo + ".xlsx"; - bd.ficheros.Add(f); - bd.SaveChanges(); - bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "Polizas con documentación pendiente de Recibir", "Distinguidos Sres., adjunto le remitimos listado de pólizas de las cuales tenemos pendiente recibir su documentación.", cta, s.Email, null, null, f.idFichero, Remitente: copiaoculta); - } - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GeneraCorreosDocumentacionPendiente.", "Rutina: GeneraCorreosDocumentacionPendiente. " + " " + ex.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// bd.ficheros.Add(f); +// bd.SaveChanges(); +// bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "Polizas con documentación pendiente de Recibir", "Distinguidos Sres., adjunto le remitimos listado de pólizas de las cuales tenemos pendiente recibir su documentación.", cta, s.Email, null, null, f.idFichero, Remitente: copiaoculta); +// } +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GeneraCorreosDocumentacionPendiente.", "Rutina: GeneraCorreosDocumentacionPendiente. " + " " + ex.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task GeneraEmailsMandatosSinRecibirAsync() - { - try - { - var bd = tscgestionasegasa.NuevoContexto(); - DateTime fi = DateTime.Now.Date.AddDays(-23); - var idTipo = bd.enumeraciones.First(x => x.Codigo == "DOCRAM.MDTO").idEnumeracion; - var pols = bd.polizassg.Where(x => x.FechaBaja.HasValue == false && x.documentospolizassg.Any(y => y.idDocumentoASolicitarNavigation.idTipo == idTipo && y.idFichero.HasValue == false)).GroupBy(x => x.idAgente).ToList(); - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - foreach (var grag in pols) - { - var grsa = grag.GroupBy(x => x.idSubAgente_Especial).ToList(); - foreach (var g in grsa) - { - try - { - var sDestinatariosBCC = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCOPIAS").ValorAlfabeticoLargo; - var l = g.Select(x => x.AListadoGenerico()).ToList(); - byte[] b = tsUtilidades.Excel.IEnumerableAExcel(l); - string Agente; - var idAgente = g.First().idAgente; - var Ag = bd.agentes.First(x => x.idAgente == idAgente); - string sDestinatario = Ag.Email.NothingAVacio(); - Agente = Ag.Codigo; - subagentes sa; - var idSubAgente = g.First().idSubAgente_Especial; - if (idSubAgente.HasValue) - { - sa = bd.subagentes.First(x => x.idSubagente == idSubAgente); - Agente += "-" + sa.Codigo; - if (sa.Email.NothingAVacio() != "") sDestinatario = sa.Email; - } - var sAsunto = "Listado de pólizas sin mandato SEPA " + DateTime.Now.Date.ToString("dd-MM-yyyy") + ") Agente: " + Agente; - var sCuerpo = "Distinguidos Sres., les recordamos que es de obligado cumplimiento el tener el mandato sepa debidamente rellenado y firmado para poder enviar los recibos al cobro, por lo que necesitamos que suban los mandatos a la aplicación, a la mayor brevedad posible. Remitimos un archivo excel detallando las pólizas sin mandato sepa." + "\r\n" + "Muchas gracias y reciba un cordial saludo. "; - if (sDestinatario.EsListaEmailsValida() == false) - { - sDestinatario = sDestinatariosBCC; - sDestinatariosBCC = ""; - sAsunto += " (Agente/Subagente " + Agente + " sin correo)"; - } - bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, sAsunto, sCuerpo, cta, b, "Bajas-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", sAsunto, sDestinatario, "", sDestinatariosBCC); - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GeneraEmailsMandatosSinRecibir.", "Rutina: GeneraEmailsMandatosSinRecibir. " + ex.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } - } - } - catch (Exception ex) - { - await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GeneraEmailsMandatosSinRecibir.", "Rutina: GeneraEmailsMandatosSinRecibir-2. " + ex.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } - } -} +// public static async Task GeneraEmailsMandatosSinRecibirAsync() +// { +// try +// { +// var bd = tscgestionasegasa.NuevoContexto(); +// DateTime fi = DateTime.Now.Date.AddDays(-23); +// var idTipo = bd.enumeraciones.First(x => x.Codigo == "DOCRAM.MDTO").idEnumeracion; +// var pols = bd.polizassg.Where(x => x.FechaBaja.HasValue == false && x.documentospolizassg.Any(y => y.idDocumentoASolicitarNavigation.idTipo == idTipo && y.idFichero.HasValue == false)).GroupBy(x => x.idAgente).ToList(); +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// foreach (var grag in pols) +// { +// var grsa = grag.GroupBy(x => x.idSubAgente_Especial).ToList(); +// foreach (var g in grsa) +// { +// try +// { +// var sDestinatariosBCC = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCOPIAS").ValorAlfabeticoLargo; +// var l = g.Select(x => x.AListadoGenerico()).ToList(); +// byte[] b = tsUtilidades.Excel.IEnumerableAExcel(l); +// string Agente; +// var idAgente = g.First().idAgente; +// var Ag = bd.agentes.First(x => x.idAgente == idAgente); +// string sDestinatario = Ag.Email.NothingAVacio(); +// Agente = Ag.Codigo; +// subagentes sa; +// var idSubAgente = g.First().idSubAgente_Especial; +// if (idSubAgente.HasValue) +// { +// sa = bd.subagentes.First(x => x.idSubagente == idSubAgente); +// Agente += "-" + sa.Codigo; +// if (sa.Email.NothingAVacio() != "") sDestinatario = sa.Email; +// } +// var sAsunto = "Listado de pólizas sin mandato SEPA " + DateTime.Now.Date.ToString("dd-MM-yyyy") + ") Agente: " + Agente; +// var sCuerpo = "Distinguidos Sres., les recordamos que es de obligado cumplimiento el tener el mandato sepa debidamente rellenado y firmado para poder enviar los recibos al cobro, por lo que necesitamos que suban los mandatos a la aplicación, a la mayor brevedad posible. Remitimos un archivo excel detallando las pólizas sin mandato sepa." + "\r\n" + "Muchas gracias y reciba un cordial saludo. "; +// if (sDestinatario.EsListaEmailsValida() == false) +// { +// sDestinatario = sDestinatariosBCC; +// sDestinatariosBCC = ""; +// sAsunto += " (Agente/Subagente " + Agente + " sin correo)"; +// } +// bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, sAsunto, sCuerpo, cta, b, "Bajas-" + DateTime.Now.ToString("yyyy-MM-dd") + ".xlsx", sAsunto, sDestinatario, "", sDestinatariosBCC); +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GeneraEmailsMandatosSinRecibir.", "Rutina: GeneraEmailsMandatosSinRecibir. " + ex.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } +// } +// } +// catch (Exception ex) +// { +// await tsUtilidades.TsNotificacionesClient.RegistrarAsync("En GeneraEmailsMandatosSinRecibir.", "Rutina: GeneraEmailsMandatosSinRecibir-2. " + ex.Message, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } +// } +//} diff --git a/Servicio Gestion Asegasa/Procesos/ProcesosRecibos.cs b/Servicio Gestion Asegasa/Procesos/ProcesosRecibos.cs index 07ce925..e69d951 100644 --- a/Servicio Gestion Asegasa/Procesos/ProcesosRecibos.cs +++ b/Servicio Gestion Asegasa/Procesos/ProcesosRecibos.cs @@ -1,457 +1,457 @@ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.EntityFrameworkCore; -using tsUtilidades; -using tsUtilidades.Extensiones; -using tsUtilidades.Enumeraciones; -using bdAsegasa.db; -using bdAsegasa.dbcontext; -using bdAsegasa.Presupuestos; -using bdAsegasa.Informes; -using bdAsegasa; +//using System; +//using System.Collections.Generic; +//using System.IO; +//using System.Linq; +//using System.Threading.Tasks; +//using Microsoft.EntityFrameworkCore; +//using tsUtilidades; +//using tsUtilidades.Extensiones; +//using tsUtilidades.Enumeraciones; +//using bdAsegasa.db; +//using bdAsegasa.dbcontext; +//using bdAsegasa.Presupuestos; +//using bdAsegasa.Informes; +//using bdAsegasa; -namespace Servicio_Gestion_Asegasa.Procesos -{ - public class ProcesosRecibos - { - public static async Task EstableceFechaPagoRecibosAsync() - { - try - { - using var bd =tscgestionasegasa.NuevoContexto(); - var idtippag = bd.enumeraciones.First(x => x.Codigo == "TIPP.AG").idEnumeracion; - var idtipppe = bd.enumeraciones.First(x => x.Codigo == "TIPP.PE").idEnumeracion; - var idSitPag = bd.enumeraciones.First(x => x.Codigo == "SITR.PA").idEnumeracion; - var idE = bd.enumeraciones.First(x => x.Codigo == "TRC.E").idEnumeracion; - var idES = bd.enumeraciones.First(x => x.Codigo == "TRC.ES").idEnumeracion; - var idEX = bd.enumeraciones.First(x => x.Codigo == "TRC.EX").idEnumeracion; +//namespace Servicio_Gestion_Asegasa.Procesos +//{ +// public class ProcesosRecibos +// { +// public static async Task EstableceFechaPagoRecibosAsync() +// { +// try +// { +// using var bd =tscgestionasegasa.NuevoContexto(); +// var idtippag = bd.enumeraciones.First(x => x.Codigo == "TIPP.AG").idEnumeracion; +// var idtipppe = bd.enumeraciones.First(x => x.Codigo == "TIPP.PE").idEnumeracion; +// var idSitPag = bd.enumeraciones.First(x => x.Codigo == "SITR.PA").idEnumeracion; +// var idE = bd.enumeraciones.First(x => x.Codigo == "TRC.E").idEnumeracion; +// var idES = bd.enumeraciones.First(x => x.Codigo == "TRC.ES").idEnumeracion; +// var idEX = bd.enumeraciones.First(x => x.Codigo == "TRC.EX").idEnumeracion; - var hoy = DateOnly.FromDateTime( DateTime.Today); +// var hoy = DateOnly.FromDateTime( DateTime.Today); - var recs = bd.recibos.Where(x => x.FechaPago == null && x.FechaBaja == null && x.FechaDevolucionBanco == null).ToList() .Where(r => r.idTipoPago != idtippag && ( - (r.idTipoPago == idtipppe && (hoy.DayNumber - r.FechaEfecto.DayNumber) >= 10) ||(r.idRemesa.HasValue && (hoy.DayNumber - r.FechaEfecto.DayNumber) >= - (r.idTipo == idE || r.idTipo == idES || r.idTipo == idEX ? 15 : r.NumeroDiasRemesaPago)))).ToList(); +// var recs = bd.recibos.Where(x => x.FechaPago == null && x.FechaBaja == null && x.FechaDevolucionBanco == null).ToList() .Where(r => r.idTipoPago != idtippag && ( +// (r.idTipoPago == idtipppe && (hoy.DayNumber - r.FechaEfecto.DayNumber) >= 10) ||(r.idRemesa.HasValue && (hoy.DayNumber - r.FechaEfecto.DayNumber) >= +// (r.idTipo == idE || r.idTipo == idES || r.idTipo == idEX ? 15 : r.NumeroDiasRemesaPago)))).ToList(); - var lrp = new List(); - if (recs.Count > 0) - { - var Cont = bd.enumeraciones.First(x => x.Codigo == "CONT.NUMGEN"); - Cont.ValorNumerico1 += 1; - bd.SaveChanges(); +// var lrp = new List(); +// if (recs.Count > 0) +// { +// var Cont = bd.enumeraciones.First(x => x.Codigo == "CONT.NUMGEN"); +// Cont.ValorNumerico1 += 1; +// bd.SaveChanges(); - foreach (var r in recs) - { - r.FechaPago = hoy; - r.idSituacion = idSitPag; - lrp.Add(r); - } - bd.SaveChanges(); - await bd.Database.ExecuteSqlRawAsync($"UPDATE registrosactualizados SET FechaCreacion=Now() where FechaCreacion Is null and NumeroGeneracion={Cont.ValorNumerico1};"); - } +// foreach (var r in recs) +// { +// r.FechaPago = hoy; +// r.idSituacion = idSitPag; +// lrp.Add(r); +// } +// bd.SaveChanges(); +// await bd.Database.ExecuteSqlRawAsync($"UPDATE registrosactualizados SET FechaCreacion=Now() where FechaCreacion Is null and NumeroGeneracion={Cont.ValorNumerico1};"); +// } - var sDestinatarios = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCONTA").ValorAlfabeticoLargo; - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// var sDestinatarios = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCONTA").ValorAlfabeticoLargo; +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - if (lrp.Count == 0) - { - bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "No se han marcado ningún recibo como pagado", "Le informamos que no se han marcado ningún recibo como pagado", cta, sDestinatarios); - } - else - { - var lr = lrp.Select(x => new - { - x.CodigoRecibo, - NumeroPoliza = x.idPolizaNavigation.NumeroPoliza, - NumeroSuplemento = x.idPolizaNavigation.NumeroSuplemento, - Tomador = x.idPolizaNavigation.Tomador?.RazonSocial, - BinesAsegurados = x.idPolizaNavigation.BienesAsegurados, - Ramo = x.idPolizaNavigation.idRamoNavigation.Descripcion, - Compañía = x.idPolizaNavigation.idCompaniaNavigation.Nombre - }).ToList(); +// if (lrp.Count == 0) +// { +// bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "No se han marcado ningún recibo como pagado", "Le informamos que no se han marcado ningún recibo como pagado", cta, sDestinatarios); +// } +// else +// { +// var lr = lrp.Select(x => new +// { +// x.CodigoRecibo, +// NumeroPoliza = x.idPolizaNavigation.NumeroPoliza, +// NumeroSuplemento = x.idPolizaNavigation.NumeroSuplemento, +// Tomador = x.idPolizaNavigation.Tomador?.RazonSocial, +// BinesAsegurados = x.idPolizaNavigation.BienesAsegurados, +// Ramo = x.idPolizaNavigation.idRamoNavigation.Descripcion, +// Compañía = x.idPolizaNavigation.idCompaniaNavigation.Nombre +// }).ToList(); - var f = tsUtilidades.Excel.IEnumerableAExcel(lr); - bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, $"Se han marcado {recs.Count} Recibos como Pagados", "Adjunto le remitimos listado de recibos marcados como pagados", cta, f, $"Pagos-{DateTime.Now:yyyy-MM-dd}.xlsx", $"Listado Recibos de con fecha de pago {DateTime.Now:yyyy-MM-dd}", sDestinatarios); - } - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En EstableceFechaPagoRecibos.", $"Rutina: EstableceFechaPagoRecibos. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// var f = tsUtilidades.Excel.IEnumerableAExcel(lr); +// bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, $"Se han marcado {recs.Count} Recibos como Pagados", "Adjunto le remitimos listado de recibos marcados como pagados", cta, f, $"Pagos-{DateTime.Now:yyyy-MM-dd}.xlsx", $"Listado Recibos de con fecha de pago {DateTime.Now:yyyy-MM-dd}", sDestinatarios); +// } +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En EstableceFechaPagoRecibos.", $"Rutina: EstableceFechaPagoRecibos. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task EstableceFechaPagoRecibosAGAsync() - { - try - { - // Assuming this method exists in the C# domain model for recibos - bdAsegasa.db.recibos.ContabilizaRecibosPagoAG(); - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En EstableceFechaPagoRecibosAG.", $"Rutina: EstableceFechaPagoRecibosAG. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// public static async Task EstableceFechaPagoRecibosAGAsync() +// { +// try +// { +// // Assuming this method exists in the C# domain model for recibos +// bdAsegasa.db.recibos.ContabilizaRecibosPagoAG(); +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En EstableceFechaPagoRecibosAG.", $"Rutina: EstableceFechaPagoRecibosAG. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task EstableceFechaBajaRecibosAsync(int DiasLimiteCartaImperativo = -10) - { - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var TipoCarta = (int)TipoGestionEnum.AVISO_IMPERATIVO_LEGAL; - var idtipS = bd.enumeraciones.Where(x => x.Codigo == "TIPP.CO" || x.Codigo == "TIPP.CTR" || x.Codigo == "TIPP.CTA" || x.Codigo == "TIPP.CIN" || x.Codigo == "TIPP.PE").Select(x => x.idEnumeracion).ToList(); - var idFP = bd.enumeraciones.First(x => x.Codigo == "CABA.FP").idEnumeracion; - var confEmail = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCONTA").ValorAlfabeticoLargo; - var sDestinatarios = $"{confEmail};lolaherrera@asegasa.es"; - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// public static async Task EstableceFechaBajaRecibosAsync(int DiasLimiteCartaImperativo = -10) +// { +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var TipoCarta = (int)TipoGestionEnum.AVISO_IMPERATIVO_LEGAL; +// var idtipS = bd.enumeraciones.Where(x => x.Codigo == "TIPP.CO" || x.Codigo == "TIPP.CTR" || x.Codigo == "TIPP.CTA" || x.Codigo == "TIPP.CIN" || x.Codigo == "TIPP.PE").Select(x => x.idEnumeracion).ToList(); +// var idFP = bd.enumeraciones.First(x => x.Codigo == "CABA.FP").idEnumeracion; +// var confEmail = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCONTA").ValorAlfabeticoLargo; +// var sDestinatarios = $"{confEmail};lolaherrera@asegasa.es"; +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - var FechaLimite = DateTime.Now.Date.AddDays(-DiasLimiteCartaImperativo); +// var FechaLimite = DateTime.Now.Date.AddDays(-DiasLimiteCartaImperativo); - var recs = bd.recibos.Where(x => x.FechaPago == null && x.FechaBaja == null && x.gestionesrecibos.Any(y => y.Tipo == TipoCarta && y.Fecha <= FechaLimite)).ToList() - .Where(x => x.LimiteEfectoSobrePasadoFechaBaja && idtipS.Contains(x.idTipoPago.Value)).ToList(); +// var recs = bd.recibos.Where(x => x.FechaPago == null && x.FechaBaja == null && x.gestionesrecibos.Any(y => y.Tipo == TipoCarta && y.Fecha <= FechaLimite)).ToList() +// .Where(x => x.LimiteEfectoSobrePasadoFechaBaja && idtipS.Contains(x.idTipoPago.Value)).ToList(); - enumeraciones? cont = null; - int Numrec = 0; - var hoy = DateOnly.FromDateTime(DateTime.Today); +// enumeraciones? cont = null; +// int Numrec = 0; +// var hoy = DateOnly.FromDateTime(DateTime.Today); - if (recs.Count > 0) - { - cont = bd.enumeraciones.First(x => x.Codigo == "CONT.NUMGEN"); - cont.ValorNumerico1 += 1; - bd.SaveChanges(); +// if (recs.Count > 0) +// { +// cont = bd.enumeraciones.First(x => x.Codigo == "CONT.NUMGEN"); +// cont.ValorNumerico1 += 1; +// bd.SaveChanges(); - foreach (var r in recs) - { - Numrec += 1; - r.FechaBaja = hoy; - r.idCausaBaja = idFP; - } - bd.SaveChanges(); - } +// foreach (var r in recs) +// { +// Numrec += 1; +// r.FechaBaja = hoy; +// r.idCausaBaja = idFP; +// } +// bd.SaveChanges(); +// } - var FechaLimiteDev = DateOnly.FromDateTime( DateTime.Now.Date.AddDays(-25)); - var recsdb = bd.recibos.Where(x => x.FechaPago == null && x.FechaBaja == null && x.FechaDevolucionBanco != null).ToList() - .Where(x => x.FechaDevolucionBanco.Value <= FechaLimiteDev && !idtipS.Contains(x.idTipoPago.Value)).ToList(); +// var FechaLimiteDev = DateOnly.FromDateTime( DateTime.Now.Date.AddDays(-25)); +// var recsdb = bd.recibos.Where(x => x.FechaPago == null && x.FechaBaja == null && x.FechaDevolucionBanco != null).ToList() +// .Where(x => x.FechaDevolucionBanco.Value <= FechaLimiteDev && !idtipS.Contains(x.idTipoPago.Value)).ToList(); - if (recsdb.Count > 0) - { - if (cont == null) - { - cont = bd.enumeraciones.First(x => x.Codigo == "CONT.NUMGEN"); - cont.ValorNumerico1 += 1; - bd.SaveChanges(); - } - foreach (var r in recsdb) - { - Numrec += 1; - r.FechaBaja = hoy; - r.idCausaBaja = idFP; - } - bd.SaveChanges(); - } +// if (recsdb.Count > 0) +// { +// if (cont == null) +// { +// cont = bd.enumeraciones.First(x => x.Codigo == "CONT.NUMGEN"); +// cont.ValorNumerico1 += 1; +// bd.SaveChanges(); +// } +// foreach (var r in recsdb) +// { +// Numrec += 1; +// r.FechaBaja = hoy; +// r.idCausaBaja = idFP; +// } +// bd.SaveChanges(); +// } - if (cont != null) - { - await bd.Database.ExecuteSqlRawAsync($"UPDATE registrosactualizados SET FechaCreacion=Now() where FechaCreacion Is null and NumeroGeneracion={cont.ValorNumerico1};"); - var lr = recs.Union(recsdb).Select(x => new - { - x.CodigoRecibo, - NumeroPoliza = x.idPolizaNavigation.NumeroPoliza, - NumeroSuplemento = x.idPolizaNavigation.NumeroSuplemento, - Tomador = x.idPolizaNavigation.Tomador?.RazonSocial, - BinesAsegurados = x.idPolizaNavigation.BienesAsegurados, - Ramo = x.idPolizaNavigation.idRamoNavigation.Descripcion, - Compañía = x.idPolizaNavigation.idCompaniaNavigation.Nombre, - FormaPago = x.idTipoPagoNavigation?.Descripcion, - Agente = x.idPolizaNavigation.idAgenteNavigation?.CodigoYNombre - }).ToList(); +// if (cont != null) +// { +// await bd.Database.ExecuteSqlRawAsync($"UPDATE registrosactualizados SET FechaCreacion=Now() where FechaCreacion Is null and NumeroGeneracion={cont.ValorNumerico1};"); +// var lr = recs.Union(recsdb).Select(x => new +// { +// x.CodigoRecibo, +// NumeroPoliza = x.idPolizaNavigation.NumeroPoliza, +// NumeroSuplemento = x.idPolizaNavigation.NumeroSuplemento, +// Tomador = x.idPolizaNavigation.Tomador?.RazonSocial, +// BinesAsegurados = x.idPolizaNavigation.BienesAsegurados, +// Ramo = x.idPolizaNavigation.idRamoNavigation.Descripcion, +// Compañía = x.idPolizaNavigation.idCompaniaNavigation.Nombre, +// FormaPago = x.idTipoPagoNavigation?.Descripcion, +// Agente = x.idPolizaNavigation.idAgenteNavigation?.CodigoYNombre +// }).ToList(); - var f = tsUtilidades.Excel.IEnumerableAExcel(lr); - bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, $"Se han marcado {Numrec} Recibos de BAJA por Falta de PAGO", "Adjunto le remitimos listado de recibos puestos de baja por Falta de Pago", cta, f, $"Bajas-{DateTime.Now:yyyy-MM-dd}.xlsx", $"Listado Recibos de Baja Fecha {DateTime.Now:yyyy-MM-dd}", sDestinatarios); - } - else - { - bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "No se han marcado ningún recibo de Baja por Falta de Pago", "Le informamos que no se han marcado ningún recibo de Baja por Falta de Pago", cta, sDestinatarios); - } - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En EstableceFechaBajaRecibos.", $"Rutina: EstableceFechaBajaRecibos. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// var f = tsUtilidades.Excel.IEnumerableAExcel(lr); +// bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, $"Se han marcado {Numrec} Recibos de BAJA por Falta de PAGO", "Adjunto le remitimos listado de recibos puestos de baja por Falta de Pago", cta, f, $"Bajas-{DateTime.Now:yyyy-MM-dd}.xlsx", $"Listado Recibos de Baja Fecha {DateTime.Now:yyyy-MM-dd}", sDestinatarios); +// } +// else +// { +// bdAsegasa.db.correos.GeneraRegistroCorreo(bd, "No se han marcado ningún recibo de Baja por Falta de Pago", "Le informamos que no se han marcado ningún recibo de Baja por Falta de Pago", cta, sDestinatarios); +// } +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En EstableceFechaBajaRecibos.", $"Rutina: EstableceFechaBajaRecibos. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task GeneraApuntesContadoAsync() - { - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var idTippContado = bd.enumeraciones.Where(x => x.Codigo == "TIPP.PE" || (x.idGrupoEnumeracionNavigation.Grupo == "TIPP" && x.ValorNumerico1 == 1)).Select(x => x.idEnumeracion).ToList(); - var idTippPE = bd.enumeraciones.First(x => x.Codigo == "TIPP.PE").idEnumeracion; - var idCbPGO = bd.enumeraciones.First(x => x.Codigo == "CABA.PGO").idEnumeracion; - var sDestinatarios = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCONTA").ValorAlfabeticoLargo; - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// public static async Task GeneraApuntesContadoAsync() +// { +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var idTippContado = bd.enumeraciones.Where(x => x.Codigo == "TIPP.PE" || (x.idGrupoEnumeracionNavigation.Grupo == "TIPP" && x.ValorNumerico1 == 1)).Select(x => x.idEnumeracion).ToList(); +// var idTippPE = bd.enumeraciones.First(x => x.Codigo == "TIPP.PE").idEnumeracion; +// var idCbPGO = bd.enumeraciones.First(x => x.Codigo == "CABA.PGO").idEnumeracion; +// var sDestinatarios = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCONTA").ValorAlfabeticoLargo; +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - var recs = bd.vf_recibosextendidos.Where(x => x.idRemesa == null && x.FechaPago != null && idTippContado.Contains(x.idTipoPago.Value) && (x.idCausaBaja == null || x.idCausaBaja.Value != idCbPGO)).ToList(); +// var recs = bd.vf_recibosextendidos.Where(x => x.idRemesa == null && x.FechaPago != null && idTippContado.Contains(x.idTipoPago.Value) && (x.idCausaBaja == null || x.idCausaBaja.Value != idCbPGO)).ToList(); - if (recs.Count > 0) - { - var recsnv = recs.Where(x => x.idTipoPago == idTippPE && x.CuentaContableTomadorErronea).ToList(); - if (recsnv.Any()) - { - var lre = recsnv.Select(x => new - { - x.CodigoRecibo, - x.NumeroPoliza, - x.NumeroSuplemento, - x.Tomador, - BinesAsegurados = x.BienesAsegurados, - x.Ramo, - x.Compania - }).ToList(); +// if (recs.Count > 0) +// { +// var recsnv = recs.Where(x => x.idTipoPago == idTippPE && x.CuentaContableTomadorErronea).ToList(); +// if (recsnv.Any()) +// { +// var lre = recsnv.Select(x => new +// { +// x.CodigoRecibo, +// x.NumeroPoliza, +// x.NumeroSuplemento, +// x.Tomador, +// BinesAsegurados = x.BienesAsegurados, +// x.Ramo, +// x.Compania +// }).ToList(); - var fe = tsUtilidades.Excel.IEnumerableAExcel(lre); - bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, "Recibos de cobro personal con cuenta contable errónea", "Adjunto le remitimos listado de recibos de cobro personal con cuenta contable errónea.", cta, fe, $"RecibosContadoErroneo-{DateTime.Now:yyyy-MM-dd}.xlsx", $"Listado Recibos de cobro personal erróneos {DateTime.Now:yyyy-MM-dd}", sDestinatarios); - } +// var fe = tsUtilidades.Excel.IEnumerableAExcel(lre); +// bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, "Recibos de cobro personal con cuenta contable errónea", "Adjunto le remitimos listado de recibos de cobro personal con cuenta contable errónea.", cta, fe, $"RecibosContadoErroneo-{DateTime.Now:yyyy-MM-dd}.xlsx", $"Listado Recibos de cobro personal erróneos {DateTime.Now:yyyy-MM-dd}", sDestinatarios); +// } - recs = recs.Where(x => !x.CuentaContableTomadorErronea).ToList(); - if (recs.Count > 0) - { - bdAsegasa.db.asientos.GeneraAsientoRecibosContado(bd, recs, DelegadoErrorNoControlado); - } - } - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En GeneraApuntesContado.", $"Rutina: GeneraApuntesContado. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// recs = recs.Where(x => !x.CuentaContableTomadorErronea).ToList(); +// if (recs.Count > 0) +// { +// bdAsegasa.db.asientos.GeneraAsientoRecibosContado(bd, recs, DelegadoErrorNoControlado); +// } +// } +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En GeneraApuntesContado.", $"Rutina: GeneraApuntesContado. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - private static void DelegadoErrorNoControlado(string Aplicacion, Exception ex) - { - _ = TsNotificacionesClient.RegistrarAsync($"En {Aplicacion}", $"Rutina: {Aplicacion} {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } +// private static void DelegadoErrorNoControlado(string Aplicacion, Exception ex) +// { +// _ = TsNotificacionesClient.RegistrarAsync($"En {Aplicacion}", $"Rutina: {Aplicacion} {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } - public static async Task CompruebaRecibosNoRemesadosAsync() - { - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var FechaLimite = DateOnly.FromDateTime(DateTime.Today.AddDays(-10)); - var hoy = DateOnly.FromDateTime(DateTime.Today); +// public static async Task CompruebaRecibosNoRemesadosAsync() +// { +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var FechaLimite = DateOnly.FromDateTime(DateTime.Today.AddDays(-10)); +// var hoy = DateOnly.FromDateTime(DateTime.Today); - var idBanco = bd.enumeraciones.First(x => x.Codigo == "TIPP.BA").idEnumeracion; +// var idBanco = bd.enumeraciones.First(x => x.Codigo == "TIPP.BA").idEnumeracion; - var recs = bd.recibos.Where(x => x.FechaBaja == null && x.idRemesa == null && x.idTipoPago == idBanco && x.FechaEfecto < FechaLimite && x.FechaVencimiento > hoy && x.PrimaNeta > 0).ToList(); +// var recs = bd.recibos.Where(x => x.FechaBaja == null && x.idRemesa == null && x.idTipoPago == idBanco && x.FechaEfecto < FechaLimite && x.FechaVencimiento > hoy && x.PrimaNeta > 0).ToList(); - if (recs.Count > 0) - { - var sDestinatarios = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCONTA").ValorAlfabeticoLargo; - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// if (recs.Count > 0) +// { +// var sDestinatarios = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCONTA").ValorAlfabeticoLargo; +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - var lr = recs.Select(x => x.AListadoGestionCobro()).ToList(); - var f = tsUtilidades.Excel.IEnumerableAExcel(lr); - bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, $"Existen recibos no remesados con fecha anterior a {FechaLimite:d}", $"Le informamos que existen recibos no remesados con fecha anterior a {FechaLimite:d}", cta, f, $"RecibosNoReMesados-{DateTime.Now:yyyy-MM-dd}.xlsx", $"Listado Recibos de con fecha de pago {DateTime.Now:yyyy-MM-dd}", sDestinatarios); - } - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En CompruebaRecibosNoRemesados.", $"Rutina: CompruebaRecibosNoRemesados. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// var lr = recs.Select(x => x.AListadoGestionCobro()).ToList(); +// var f = tsUtilidades.Excel.IEnumerableAExcel(lr); +// bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, $"Existen recibos no remesados con fecha anterior a {FechaLimite:d}", $"Le informamos que existen recibos no remesados con fecha anterior a {FechaLimite:d}", cta, f, $"RecibosNoReMesados-{DateTime.Now:yyyy-MM-dd}.xlsx", $"Listado Recibos de con fecha de pago {DateTime.Now:yyyy-MM-dd}", sDestinatarios); +// } +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En CompruebaRecibosNoRemesados.", $"Rutina: CompruebaRecibosNoRemesados. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task CompruebaCarteraPerdidaAsync() - { - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var ultl = bd.enumeraciones.First(x => x.Codigo == "CONF.ULTLCP"); - var FechaInicio = ultl.Fecha1.Value.AddDays(1); - var FechaFin = DateTime.Today; - var sDestinatarios = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCARPER").ValorAlfabeticoLargo; - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// public static async Task CompruebaCarteraPerdidaAsync() +// { +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var ultl = bd.enumeraciones.First(x => x.Codigo == "CONF.ULTLCP"); +// var FechaInicio = ultl.Fecha1.Value.AddDays(1); +// var FechaFin = DateTime.Today; +// var sDestinatarios = bd.enumeraciones.First(x => x.Codigo == "CONF.EMAILCARPER").ValorAlfabeticoLargo; +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - var b = bdAsegasa.Informes.CarteraPerdida.GeneraExcelCarteraPerdida(FechaInicio); +// var b = bdAsegasa.Informes.CarteraPerdida.GeneraExcelCarteraPerdida(FechaInicio); - if (b == null) - { - bdAsegasa.db.correos.GeneraRegistroCorreo(bd, $"Listado de Cartera Perdida {FechaInicio:dd/MM/yyyy}", $"No existen recibos de Cartera Perdida desde el {FechaInicio:dd/MM/yyyy}", cta, sDestinatarios); - } - else - { - bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, $"Listado de Cartera Perdida {FechaInicio:dd/MM/yyyy}", $"Adjunto le remitimos Listado de Cartera Perdida de las fechas comprendidas entre {FechaInicio:dd/MM/yyyy} y el {FechaFin:dd/MM/yyyy}", cta, b, $"CarteraPerdida_{FechaInicio:yyyy-MM-dd}_{FechaFin:yyyy-MM-dd}.xlsx", $"Cartera Perdida desde el {FechaInicio:yyyy-MM-dd}", sDestinatarios); - } +// if (b == null) +// { +// bdAsegasa.db.correos.GeneraRegistroCorreo(bd, $"Listado de Cartera Perdida {FechaInicio:dd/MM/yyyy}", $"No existen recibos de Cartera Perdida desde el {FechaInicio:dd/MM/yyyy}", cta, sDestinatarios); +// } +// else +// { +// bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, $"Listado de Cartera Perdida {FechaInicio:dd/MM/yyyy}", $"Adjunto le remitimos Listado de Cartera Perdida de las fechas comprendidas entre {FechaInicio:dd/MM/yyyy} y el {FechaFin:dd/MM/yyyy}", cta, b, $"CarteraPerdida_{FechaInicio:yyyy-MM-dd}_{FechaFin:yyyy-MM-dd}.xlsx", $"Cartera Perdida desde el {FechaInicio:yyyy-MM-dd}", sDestinatarios); +// } - ultl.Fecha1 = DateTime.Today; - bd.SaveChanges(); - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En CompruebaCarteraPerdida.", $"Rutina: CompruebaCarteraPerdida. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// ultl.Fecha1 = DateTime.Today; +// bd.SaveChanges(); +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En CompruebaCarteraPerdida.", $"Rutina: CompruebaCarteraPerdida. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task GeneraComunicacionesRecibosAsync() - { - // Case 1: Remittance warning - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var lr = bdAsegasa.db.recibos.ObtieneRecibosCartaRemesa(); - bdAsegasa.db.recibos.GeneraAvisoRemesa(lr, bd); - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En GeneraComunicacionesRecibo.", $"Rutina: GeneraComunicacionesRecibo (Remesa). {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } +// public static async Task GeneraComunicacionesRecibosAsync() +// { +// // Case 1: Remittance warning +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var lr = bdAsegasa.db.recibos.ObtieneRecibosCartaRemesa(); +// bdAsegasa.db.recibos.GeneraAvisoRemesa(lr, bd); +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En GeneraComunicacionesRecibo.", $"Rutina: GeneraComunicacionesRecibo (Remesa). {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } - // Case 2: Legal notice - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var lr = bdAsegasa.db.recibos.ObtieneRecibosAvisoImperativoLegal(bd); - var sAsunto = "Falta de pago de su recibo %RECIBO% correspondiente a su poliza %POLIZAYRAMO%"; - var sCuerpo = "En el presente correo le adjuntamos enlace al documento con el detalle del recibo %RECIBO% pendiente de pago correspondiente a su poliza %POLIZA%"; - bdAsegasa.db.recibos.GeneraAviso(lr, bdAsegasa.db.recibos.TipoGeneracionEnum.AVISO_IMPERATIVO_LEGAL, sAsunto, sCuerpo, bd); - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En GeneraComunicacionesRecibo.", $"Rutina: GeneraComunicacionesRecibo (Legal). {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } +// // Case 2: Legal notice +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var lr = bdAsegasa.db.recibos.ObtieneRecibosAvisoImperativoLegal(bd); +// var sAsunto = "Falta de pago de su recibo %RECIBO% correspondiente a su poliza %POLIZAYRAMO%"; +// var sCuerpo = "En el presente correo le adjuntamos enlace al documento con el detalle del recibo %RECIBO% pendiente de pago correspondiente a su poliza %POLIZA%"; +// bdAsegasa.db.recibos.GeneraAviso(lr, bdAsegasa.db.recibos.TipoGeneracionEnum.AVISO_IMPERATIVO_LEGAL, sAsunto, sCuerpo, bd); +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En GeneraComunicacionesRecibo.", $"Rutina: GeneraComunicacionesRecibo (Legal). {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } - // Case 3: Cancellation notice - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var lr = bdAsegasa.db.recibos.ObtieneRecibosCartaBaja(bd); - var sAsunto = "Aviso de baja de su poliza %POLIZAYRAMO%"; - var sCuerpo = "Con el presente correo le adjuntamos enlace al documento con el detalle de la baja de su póliza %POLIZAYRAMO%"; - bdAsegasa.db.recibos.GeneraAviso(lr, bdAsegasa.db.recibos.TipoGeneracionEnum.AVISO_BAJA_POLIZA, sAsunto, sCuerpo, bd); - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En GeneraComunicacionesRecibo.", $"Rutina: GeneraComunicacionesRecibo (Baja). {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } +// // Case 3: Cancellation notice +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var lr = bdAsegasa.db.recibos.ObtieneRecibosCartaBaja(bd); +// var sAsunto = "Aviso de baja de su poliza %POLIZAYRAMO%"; +// var sCuerpo = "Con el presente correo le adjuntamos enlace al documento con el detalle de la baja de su póliza %POLIZAYRAMO%"; +// bdAsegasa.db.recibos.GeneraAviso(lr, bdAsegasa.db.recibos.TipoGeneracionEnum.AVISO_BAJA_POLIZA, sAsunto, sCuerpo, bd); +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En GeneraComunicacionesRecibo.", $"Rutina: GeneraComunicacionesRecibo (Baja). {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } - // Case 4: Bank return notice - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var lr = bdAsegasa.db.recibos.ObtieneRecibosComunicacionDevueltoBanco(bd); - var sAsunto = "Aviso de devolución del recibo %RECIBO% correspondiente a su poliza %POLIZAYRAMO%"; - var sCuerpo = "En el presente correo le adjuntamos enlace al documento con el detalle de la de devolución del recibo %RECIBO% correspondiente a su poliza %POLIZA%"; - bdAsegasa.db.recibos.GeneraAviso(lr,bdAsegasa.db.recibos.TipoGeneracionEnum.COMUNICACION_DEVUELTO_BANCO, sAsunto, sCuerpo, bd); - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En GeneraComunicacionesRecibo.", $"Rutina: GeneraComunicacionesRecibo (Devuelto). {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// // Case 4: Bank return notice +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var lr = bdAsegasa.db.recibos.ObtieneRecibosComunicacionDevueltoBanco(bd); +// var sAsunto = "Aviso de devolución del recibo %RECIBO% correspondiente a su poliza %POLIZAYRAMO%"; +// var sCuerpo = "En el presente correo le adjuntamos enlace al documento con el detalle de la de devolución del recibo %RECIBO% correspondiente a su poliza %POLIZA%"; +// bdAsegasa.db.recibos.GeneraAviso(lr,bdAsegasa.db.recibos.TipoGeneracionEnum.COMUNICACION_DEVUELTO_BANCO, sAsunto, sCuerpo, bd); +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En GeneraComunicacionesRecibo.", $"Rutina: GeneraComunicacionesRecibo (Devuelto). {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task GeneraRecibosPolizasColectivasAsync() - { - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var enums = bd.enumeraciones.Where(x => x.idGrupoEnumeracionNavigation.Grupo == "CP").ToList(); - foreach (var pc in enums) - { - var idCia = bd.companias.First(x => x.Codigo == pc.ValorAlfabetico2).idCompania; - var PrimaNeta = pc.ValorNumerico1 ?? 0; - var PorcentajeImpuestos = pc.ValorNumerico2 ?? 0; - var Impuestos = Math.Round(PrimaNeta * PorcentajeImpuestos / 100, 2); - var Flim = DateTime.Today.AddDays(40); +// public static async Task GeneraRecibosPolizasColectivasAsync() +// { +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var enums = bd.enumeraciones.Where(x => x.idGrupoEnumeracionNavigation.Grupo == "CP").ToList(); +// foreach (var pc in enums) +// { +// var idCia = bd.companias.First(x => x.Codigo == pc.ValorAlfabetico2).idCompania; +// var PrimaNeta = pc.ValorNumerico1 ?? 0; +// var PorcentajeImpuestos = pc.ValorNumerico2 ?? 0; +// var Impuestos = Math.Round(PrimaNeta * PorcentajeImpuestos / 100, 2); +// var Flim = DateTime.Today.AddDays(40); - var pols = bd.polizassg.Where(x => x.FechaAceptacionPresupuesto != null && x.NumeroPoliza.StartsWith(pc.ValorAlfabetico1 + "-") && x.idCompania == idCia && x.FechaBaja == null && !x.recibos.Any(y => y.FechaVencimiento >= DateOnly.FromDateTime( Flim))).ToList(); +// var pols = bd.polizassg.Where(x => x.FechaAceptacionPresupuesto != null && x.NumeroPoliza.StartsWith(pc.ValorAlfabetico1 + "-") && x.idCompania == idCia && x.FechaBaja == null && !x.recibos.Any(y => y.FechaVencimiento >= DateOnly.FromDateTime( Flim))).ToList(); - foreach (var p in pols) - { - p.GeneraReciboPolizaColectivo(bd, PrimaNeta, Impuestos, 0); - } - } - bd.SaveChanges(); - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En GeneraRecibosPolizasColectivas.", $"Rutina: GeneraRecibosPolizasColectivas. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// foreach (var p in pols) +// { +// p.GeneraReciboPolizaColectivo(bd, PrimaNeta, Impuestos, 0); +// } +// } +// bd.SaveChanges(); +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En GeneraRecibosPolizasColectivas.", $"Rutina: GeneraRecibosPolizasColectivas. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static async Task GeneraEmailPolizasColectivas0057Async() - { - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var idCia = bd.companias.First(x => x.Codigo == "0057").idCompania; - var idRamo = bd.ramos.First(x => x.Codigo == "2-8-1").idRamo; +// public static async Task GeneraEmailPolizasColectivas0057Async() +// { +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var idCia = bd.companias.First(x => x.Codigo == "0057").idCompania; +// var idRamo = bd.ramos.First(x => x.Codigo == "2-8-1").idRamo; - var recs = bd.recibos.Where(x => x.FechaBaja == null && x.idPolizaNavigation.idCompania == idCia && x.idPolizaNavigation.idRamo == idRamo && !x.gestionesrecibos.Any(y => y.Tipo == (int)TipoGestionEnum.COMUNICACIÓN_EMISION_RECIBO_A_LA_COMPAÑÍA)).ToList(); +// var recs = bd.recibos.Where(x => x.FechaBaja == null && x.idPolizaNavigation.idCompania == idCia && x.idPolizaNavigation.idRamo == idRamo && !x.gestionesrecibos.Any(y => y.Tipo == (int)TipoGestionEnum.COMUNICACIÓN_EMISION_RECIBO_A_LA_COMPAÑÍA)).ToList(); - if (recs.Count > 0) - { - var Polcol = bd.enumeraciones.First(x => x.Codigo == "CP.TRACTORESEUROP"); - var laltas = new List(); - var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); +// if (recs.Count > 0) +// { +// var Polcol = bd.enumeraciones.First(x => x.Codigo == "CP.TRACTORESEUROP"); +// var laltas = new List(); +// var cta = bd.cuentascorreo.First(x => x.Codigo == "SEG.GENERALES"); - foreach (var r in recs) - { - var dp = (TractoresEuropAssistance)tsUtilidades.Utilidades.Deserializa(r.idPolizaNavigation.idFicheroPresupuestoNavigation.Fichero, typeof(TractoresEuropAssistance)); - var nd = new DatoReciboColectivo0057 - { - Contrato = Polcol.ValorAlfabetico1, - Codigo_Producto = Polcol.ValorAlfabetico3, - País = "ESPAÑA", - Fecha_Inicio = new DateTime(r.FechaEfecto.Year, r.FechaEfecto.Month, r.FechaEfecto.Day) , - Fecha_Fin = new DateTime(r.FechaVencimiento.Year, r.FechaVencimiento.Month, r.FechaVencimiento.Day), - Matrícula = dp.Matricula, - Marca = dp.Marca, - Modelo = dp.Modelo, - Fecha_Matriculacion = dp.FechaMatriculacion, - Referencia_Externa = $"{r.idPolizaNavigation.Tomador.CIF} {r.idPolizaNavigation.Tomador.RazonSocial}" - }; - laltas.Add(nd); - } +// foreach (var r in recs) +// { +// var dp = (TractoresEuropAssistance)tsUtilidades.Utilidades.Deserializa(r.idPolizaNavigation.idFicheroPresupuestoNavigation.Fichero, typeof(TractoresEuropAssistance)); +// var nd = new DatoReciboColectivo0057 +// { +// Contrato = Polcol.ValorAlfabetico1, +// Codigo_Producto = Polcol.ValorAlfabetico3, +// País = "ESPAÑA", +// Fecha_Inicio = new DateTime(r.FechaEfecto.Year, r.FechaEfecto.Month, r.FechaEfecto.Day) , +// Fecha_Fin = new DateTime(r.FechaVencimiento.Year, r.FechaVencimiento.Month, r.FechaVencimiento.Day), +// Matrícula = dp.Matricula, +// Marca = dp.Marca, +// Modelo = dp.Modelo, +// Fecha_Matriculacion = dp.FechaMatriculacion, +// Referencia_Externa = $"{r.idPolizaNavigation.Tomador.CIF} {r.idPolizaNavigation.Tomador.RazonSocial}" +// }; +// laltas.Add(nd); +// } - var b = tsUtilidades.Excel.IEnumerableAExcel(laltas); - var idCorreo = bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, $"Listado recibos de Asistencia en Viaje Tractores Día: {DateTime.Today:dd/MM/yyyy}", $"Adjunto le remitimos listado recibos de Asistencia en Viaje Tractores Día: {DateTime.Today:dd/MM/yyyy}", cta, b, $"Asistencia_Viaje_Tractores_{DateTime.Today:yyyy-MM-dd}.xlsx", $"Asistencia Viaje Tractores {DateTime.Today:yyyy-MM-dd}", Polcol.ValorAlfabetico4, "", Polcol.ValorAlfabeticoLargo, idAplicacion: idCia, CodigoAplicacion: "COMPAÑIAS"); +// var b = tsUtilidades.Excel.IEnumerableAExcel(laltas); +// var idCorreo = bdAsegasa.db.correos.GeneraRegistroCorreoConAdjunto(bd, $"Listado recibos de Asistencia en Viaje Tractores Día: {DateTime.Today:dd/MM/yyyy}", $"Adjunto le remitimos listado recibos de Asistencia en Viaje Tractores Día: {DateTime.Today:dd/MM/yyyy}", cta, b, $"Asistencia_Viaje_Tractores_{DateTime.Today:yyyy-MM-dd}.xlsx", $"Asistencia Viaje Tractores {DateTime.Today:yyyy-MM-dd}", Polcol.ValorAlfabetico4, "", Polcol.ValorAlfabeticoLargo, idAplicacion: idCia, CodigoAplicacion: "COMPAÑIAS"); - foreach (var r in recs) - { - var tg = new gestionesrecibos - { - idRecibo = r.idRecibo, - FormaComunicacion = (int)FormaComunicacionEnum.NINGUNA, - Tipo = (int)TipoGestionEnum.COMUNICACIÓN_EMISION_RECIBO_A_LA_COMPAÑÍA, - GestionesRealizadas = TipoGestionEnum.COMUNICACIÓN_EMISION_RECIBO_A_LA_COMPAÑÍA.ToString().Replace("_", " "), - Fecha = DateTime.Now, - idCorreo = idCorreo, - Observaciones = "" - }; - bd.gestionesrecibos.Add(tg); - } - bd.SaveChanges(); - } - } - catch (Exception ex) - { - await TsNotificacionesClient.RegistrarAsync("En GeneraEmailPolizasColectivas0057.", $"Rutina: GeneraEmailPolizasColectivas0057. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } - } +// foreach (var r in recs) +// { +// var tg = new gestionesrecibos +// { +// idRecibo = r.idRecibo, +// FormaComunicacion = (int)FormaComunicacionEnum.NINGUNA, +// Tipo = (int)TipoGestionEnum.COMUNICACIÓN_EMISION_RECIBO_A_LA_COMPAÑÍA, +// GestionesRealizadas = TipoGestionEnum.COMUNICACIÓN_EMISION_RECIBO_A_LA_COMPAÑÍA.ToString().Replace("_", " "), +// Fecha = DateTime.Now, +// idCorreo = idCorreo, +// Observaciones = "" +// }; +// bd.gestionesrecibos.Add(tg); +// } +// bd.SaveChanges(); +// } +// } +// catch (Exception ex) +// { +// await TsNotificacionesClient.RegistrarAsync("En GeneraEmailPolizasColectivas0057.", $"Rutina: GeneraEmailPolizasColectivas0057. {ex.Message}", TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } +// } - public class DatoReciboColectivo0057 - { - public string Contrato { get; set; } - public string Codigo_Producto { get; set; } - public DateTime Fecha_Inicio { get; set; } - public DateTime Fecha_Fin { get; set; } - public string País { get; set; } - public string Matrícula { get; set; } - public string Marca { get; set; } - public string Modelo { get; set; } - public DateTime Fecha_Matriculacion { get; set; } - public string Referencia_Externa { get; set; } - } -} +// public class DatoReciboColectivo0057 +// { +// public string Contrato { get; set; } +// public string Codigo_Producto { get; set; } +// public DateTime Fecha_Inicio { get; set; } +// public DateTime Fecha_Fin { get; set; } +// public string País { get; set; } +// public string Matrícula { get; set; } +// public string Marca { get; set; } +// public string Modelo { get; set; } +// public DateTime Fecha_Matriculacion { get; set; } +// public string Referencia_Externa { get; set; } +// } +//} diff --git a/Servicio Gestion Asegasa/Procesos/ProcesosSiniestros.cs b/Servicio Gestion Asegasa/Procesos/ProcesosSiniestros.cs index b7a92cb..8fcf52d 100644 --- a/Servicio Gestion Asegasa/Procesos/ProcesosSiniestros.cs +++ b/Servicio Gestion Asegasa/Procesos/ProcesosSiniestros.cs @@ -1,388 +1,388 @@ -using System; -using System.Linq; -using System.Collections.Generic; -using Microsoft.EntityFrameworkCore; -using bdAsegasa; -using bdAsegasa.db; +//using System; +//using System.Linq; +//using System.Collections.Generic; +//using Microsoft.EntityFrameworkCore; +//using bdAsegasa; +//using bdAsegasa.db; -namespace Servicio_Gestion_Asegasa.Procesos -{ - public class ProcesosSiniestros - { - public static void IncorporaSiniestrosEIACV6() - { - try - { - using var bd = gestionasegasaEntities.NuevoContexto(); - var ltpa = bd.enumeraciones.Where(x => x.idGrupoEnumeracionNavigation.Grupo == "TIPP").ToList(); - int tipo = (int)ficheroscompanias.TipoFicheroCompania.SINIESTROS_EIAC; +//namespace Servicio_Gestion_Asegasa.Procesos +//{ +// public class ProcesosSiniestros +// { +// public static void IncorporaSiniestrosEIACV6() +// { +// try +// { +// using var bd = gestionasegasaEntities.NuevoContexto(); +// var ltpa = bd.enumeraciones.Where(x => x.idGrupoEnumeracionNavigation.Grupo == "TIPP").ToList(); +// int tipo = (int)ficheroscompanias.TipoFicheroCompania.SINIESTROS_EIAC; - var ficspen = bd.ficheroscompanias - .Where(x => x.FechaProcesado == null && - x.FechaError == null && - x.Tipo == tipo && - x.Version == "6.0") - .OrderBy(x => x.idFichero) - .ToList(); +// var ficspen = bd.ficheroscompanias +// .Where(x => x.FechaProcesado == null && +// x.FechaError == null && +// x.Tipo == tipo && +// x.Version == "6.0") +// .OrderBy(x => x.idFichero) +// .ToList(); - foreach (var f in ficspen) - { - try - { - // Asumimos ProcesosEIAC_V6 existe y Utilizamos una librería genérica de serialización - dynamic DatosEIAC = tsUtilidades.Utilidades.Deserializa(f.Fichero, Type.GetType("ProcesosEIAC_V6.ProcesosEIAC") ?? typeof(object)); +// foreach (var f in ficspen) +// { +// try +// { +// // Asumimos ProcesosEIAC_V6 existe y Utilizamos una librería genérica de serialización +// dynamic DatosEIAC = tsUtilidades.Utilidades.Deserializa(f.Fichero, Type.GetType("ProcesosEIAC_V6.ProcesosEIAC") ?? typeof(object)); - if (DatosEIAC?.Objetos?.Items != null) - { - IEnumerable items = DatosEIAC.Objetos.Items; - var lSins = items.Where(x => x != null && x.GetType().Name == "tipo_siniestro"); +// if (DatosEIAC?.Objetos?.Items != null) +// { +// IEnumerable items = DatosEIAC.Objetos.Items; +// var lSins = items.Where(x => x != null && x.GetType().Name == "tipo_siniestro"); - foreach (var s in lSins) - { - List sins = null; - string idSiniestroEntidad = s.DatosSiniestro.IdSiniestroEntidad; +// foreach (var s in lSins) +// { +// List sins = null; +// string idSiniestroEntidad = s.DatosSiniestro.IdSiniestroEntidad; - var seiac = bd.siniestros_eiac.FirstOrDefault(x => x.idSiniestroEntidad == idSiniestroEntidad); - if (seiac == null) - { - seiac = new siniestros_eiac - { - idSiniestroEntidad = idSiniestroEntidad, - idFicheroCompania = f.idFichero, - idCompania = f.idCompania - }; - bd.siniestros_eiac.Add(seiac); - } +// var seiac = bd.siniestros_eiac.FirstOrDefault(x => x.idSiniestroEntidad == idSiniestroEntidad); +// if (seiac == null) +// { +// seiac = new siniestros_eiac +// { +// idSiniestroEntidad = idSiniestroEntidad, +// idFicheroCompania = f.idFichero, +// idCompania = f.idCompania +// }; +// bd.siniestros_eiac.Add(seiac); +// } - seiac.NumeroPoliza = s.DatosPoliza.IdPoliza; - var pol = bd.polizassg - .Where(x => x.NumeroPoliza == seiac.NumeroPoliza && x.idCompania == seiac.idCompania) - .OrderByDescending(x => x.NumeroSuplemento) - .FirstOrDefault(); +// seiac.NumeroPoliza = s.DatosPoliza.IdPoliza; +// var pol = bd.polizassg +// .Where(x => x.NumeroPoliza == seiac.NumeroPoliza && x.idCompania == seiac.idCompania) +// .OrderByDescending(x => x.NumeroSuplemento) +// .FirstOrDefault(); - if (pol != null) - seiac.idPoliza = pol.idPoliza; +// if (pol != null) +// seiac.idPoliza = pol.idPoliza; - seiac.NumeroSuplemento = s.DatosPoliza.NumeroSuplemento; - seiac.FechaDeclaracion = s.DatosSiniestro.FechaDeclaracion; - seiac.FechaOcurrencia = s.DatosSiniestro.FechaOcurrencia; - seiac.PosicionSiniestro = (int)bdAsegasa.db.siniestros_eiac.ObtienePosicionSiniestroV6((string)s.DatosSiniestro.PosicionSiniestro); - seiac.DescripcionSiniestro = tsUtilidades.Extensiones.StringExtensions.Acortar((string)s.DatosSiniestro.DescripcionSiniestro, 2048); - seiac.TipologiaSiniestro = s.DatosSiniestro.TipologiaSiniestro; - seiac.ImporteIndemnizacion = s.DatosSiniestro.ImporteIndemnizacion; - seiac.ImporteReserva = s.DatosSiniestro.ImporteReserva; +// seiac.NumeroSuplemento = s.DatosPoliza.NumeroSuplemento; +// seiac.FechaDeclaracion = s.DatosSiniestro.FechaDeclaracion; +// seiac.FechaOcurrencia = s.DatosSiniestro.FechaOcurrencia; +// seiac.PosicionSiniestro = (int)bdAsegasa.db.siniestros_eiac.ObtienePosicionSiniestroV6((string)s.DatosSiniestro.PosicionSiniestro); +// seiac.DescripcionSiniestro = tsUtilidades.Extensiones.StringExtensions.Acortar((string)s.DatosSiniestro.DescripcionSiniestro, 2048); +// seiac.TipologiaSiniestro = s.DatosSiniestro.TipologiaSiniestro; +// seiac.ImporteIndemnizacion = s.DatosSiniestro.ImporteIndemnizacion; +// seiac.ImporteReserva = s.DatosSiniestro.ImporteReserva; - if (s.DatosSiniestro.LugarSiniestro != null) - { - if (seiac.idLugarSiniestroNavigation == null) - { - seiac.idLugarSiniestroNavigation = new direcciones(); - } - seiac.idLugarSiniestroNavigation.Direccion = s.DatosSiniestro.LugarSiniestro.ClaseVia + " " + s.DatosSiniestro.LugarSiniestro.NombreVia + " " + s.DatosSiniestro.LugarSiniestro.OtrosDatosVia; - seiac.idLugarSiniestroNavigation.CodigoPostal = s.DatosSiniestro.LugarSiniestro.CodigoPostal; +// if (s.DatosSiniestro.LugarSiniestro != null) +// { +// if (seiac.idLugarSiniestroNavigation == null) +// { +// seiac.idLugarSiniestroNavigation = new direcciones(); +// } +// seiac.idLugarSiniestroNavigation.Direccion = s.DatosSiniestro.LugarSiniestro.ClaseVia + " " + s.DatosSiniestro.LugarSiniestro.NombreVia + " " + s.DatosSiniestro.LugarSiniestro.OtrosDatosVia; +// seiac.idLugarSiniestroNavigation.CodigoPostal = s.DatosSiniestro.LugarSiniestro.CodigoPostal; - string codmun = bd.ObtieneCodigoMunicipioMasCoincidente(seiac.idLugarSiniestroNavigation.CodigoPostal, (string)s.DatosSiniestro.LugarSiniestro.Poblacion, true); - if (string.IsNullOrEmpty(codmun)) - { - seiac.idLugarSiniestroNavigation.Direccion += " " + s.DatosSiniestro.LugarSiniestro.Poblacion; - } - else - { - seiac.idLugarSiniestroNavigation.CodigoMunicipio = codmun; - } - seiac.idLugarSiniestroNavigation.Direccion = tsUtilidades.Extensiones.StringExtensions.Acortar(seiac.idLugarSiniestroNavigation.Direccion, 200); - } +// string codmun = bd.ObtieneCodigoMunicipioMasCoincidente(seiac.idLugarSiniestroNavigation.CodigoPostal, (string)s.DatosSiniestro.LugarSiniestro.Poblacion, true); +// if (string.IsNullOrEmpty(codmun)) +// { +// seiac.idLugarSiniestroNavigation.Direccion += " " + s.DatosSiniestro.LugarSiniestro.Poblacion; +// } +// else +// { +// seiac.idLugarSiniestroNavigation.CodigoMunicipio = codmun; +// } +// seiac.idLugarSiniestroNavigation.Direccion = tsUtilidades.Extensiones.StringExtensions.Acortar(seiac.idLugarSiniestroNavigation.Direccion, 200); +// } - if (s.DatosSiniestro.SituacionesSiniestro != null) - { - var yaincorporados = new List(); - foreach (var sit in s.DatosSiniestro.SituacionesSiniestro) - { - int numeroOrden = sit.NumeroOrden; - if (numeroOrden == 0) numeroOrden = sit.GetHashCode(); - if (!yaincorporados.Contains(numeroOrden)) - { - var est = seiac.estadossiniestros_eiac.FirstOrDefault(x => x.NumeroOrden == numeroOrden); - if (est == null) - { - est = new estadossiniestros_eiac { NumeroOrden = numeroOrden }; - seiac.estadossiniestros_eiac.Add(est); - } - est.SituacionSiniestro = bdAsegasa.estadossiniestros_eiac.ObtieneSituacionSiniestroV6((string)sit.SituacionSiniestro); - est.DescripcionSituacion = tsUtilidades.Extensiones.StringExtensions.Acortar((string)sit.DescripcionSituacion, 45); - yaincorporados.Add(numeroOrden); - } - } - } +// if (s.DatosSiniestro.SituacionesSiniestro != null) +// { +// var yaincorporados = new List(); +// foreach (var sit in s.DatosSiniestro.SituacionesSiniestro) +// { +// int numeroOrden = sit.NumeroOrden; +// if (numeroOrden == 0) numeroOrden = sit.GetHashCode(); +// if (!yaincorporados.Contains(numeroOrden)) +// { +// var est = seiac.estadossiniestros_eiac.FirstOrDefault(x => x.NumeroOrden == numeroOrden); +// if (est == null) +// { +// est = new estadossiniestros_eiac { NumeroOrden = numeroOrden }; +// seiac.estadossiniestros_eiac.Add(est); +// } +// est.SituacionSiniestro = bdAsegasa.estadossiniestros_eiac.ObtieneSituacionSiniestroV6((string)sit.SituacionSiniestro); +// est.DescripcionSituacion = tsUtilidades.Extensiones.StringExtensions.Acortar((string)sit.DescripcionSituacion, 45); +// yaincorporados.Add(numeroOrden); +// } +// } +// } - if (s.DatosSiniestro.PagosSiniestro != null) - { - var yaincorporados = new List(); - foreach (var pag in s.DatosSiniestro.PagosSiniestro) - { - int numeroOrden = pag.NumeroOrden; - if (numeroOrden == 0) numeroOrden = pag.GetHashCode(); - if (!yaincorporados.Contains(numeroOrden)) - { - var ps = seiac.pagossiniestros_eiac.FirstOrDefault(x => x.NumeroOrden == numeroOrden); - if (ps == null) - { - ps = new pagossiniestros_eiac { NumeroOrden = numeroOrden }; - seiac.pagossiniestros_eiac.Add(ps); - } - ps.FechaPago = pag.FechaPago; - ps.FechaLiquidacion = pag.FechaLiquidacion; - ps.ImportePago = pag.ImportePago; - ps.DescripcionPago = tsUtilidades.Extensiones.StringExtensions.Acortar((string)pag.DescripcionPago, 255); - ps.idTipoPago = bdAsegasa.siniestros_eiac.ObtenerTipoPagoV6((string)pag.FormaPago, ltpa); +// if (s.DatosSiniestro.PagosSiniestro != null) +// { +// var yaincorporados = new List(); +// foreach (var pag in s.DatosSiniestro.PagosSiniestro) +// { +// int numeroOrden = pag.NumeroOrden; +// if (numeroOrden == 0) numeroOrden = pag.GetHashCode(); +// if (!yaincorporados.Contains(numeroOrden)) +// { +// var ps = seiac.pagossiniestros_eiac.FirstOrDefault(x => x.NumeroOrden == numeroOrden); +// if (ps == null) +// { +// ps = new pagossiniestros_eiac { NumeroOrden = numeroOrden }; +// seiac.pagossiniestros_eiac.Add(ps); +// } +// ps.FechaPago = pag.FechaPago; +// ps.FechaLiquidacion = pag.FechaLiquidacion; +// ps.ImportePago = pag.ImportePago; +// ps.DescripcionPago = tsUtilidades.Extensiones.StringExtensions.Acortar((string)pag.DescripcionPago, 255); +// ps.idTipoPago = bdAsegasa.siniestros_eiac.ObtenerTipoPagoV6((string)pag.FormaPago, ltpa); - if (pag.FormaPago != null && pag.FormaPago.DatosCuentaCorriente != null) - { - ps.IBAN = pag.FormaPago.DatosCuentaCorriente.IBAN; - } - yaincorporados.Add(numeroOrden); - } - } - } +// if (pag.FormaPago != null && pag.FormaPago.DatosCuentaCorriente != null) +// { +// ps.IBAN = pag.FormaPago.DatosCuentaCorriente.IBAN; +// } +// yaincorporados.Add(numeroOrden); +// } +// } +// } - if (s.DatosSiniestro.AccionesSiniestro != null) - { - var yaincorporados = new List(); - foreach (var accs in s.DatosSiniestro.AccionesSiniestro) - { - int numeroOrden = accs.NumeroOrden; - if (numeroOrden == 0) numeroOrden = accs.GetHashCode(); - if (!yaincorporados.Contains(numeroOrden)) - { - var acs = seiac.accionessiniestros_eiac.FirstOrDefault(x => x.NumeroOrden == numeroOrden); - if (acs == null) - { - acs = new accionessiniestros_eiac { NumeroOrden = numeroOrden }; - seiac.accionessiniestros_eiac.Add(acs); - } - acs.AccionSiniestro = bdAsegasa.accionessiniestros_eiac.ObtieneAccionSiniestroV6((string)accs.AccionSiniestro); - acs.FechaAccion = accs.FechaAccion; - acs.DescripcionAccion = accs.DescripcionAccion; - acs.SituacionAccion = bdAsegasa.accionessiniestros_eiac.ObtieneSituacionAccionV6((string)accs.SituacionAccion); - yaincorporados.Add(numeroOrden); - } - } - } +// if (s.DatosSiniestro.AccionesSiniestro != null) +// { +// var yaincorporados = new List(); +// foreach (var accs in s.DatosSiniestro.AccionesSiniestro) +// { +// int numeroOrden = accs.NumeroOrden; +// if (numeroOrden == 0) numeroOrden = accs.GetHashCode(); +// if (!yaincorporados.Contains(numeroOrden)) +// { +// var acs = seiac.accionessiniestros_eiac.FirstOrDefault(x => x.NumeroOrden == numeroOrden); +// if (acs == null) +// { +// acs = new accionessiniestros_eiac { NumeroOrden = numeroOrden }; +// seiac.accionessiniestros_eiac.Add(acs); +// } +// acs.AccionSiniestro = bdAsegasa.accionessiniestros_eiac.ObtieneAccionSiniestroV6((string)accs.AccionSiniestro); +// acs.FechaAccion = accs.FechaAccion; +// acs.DescripcionAccion = accs.DescripcionAccion; +// acs.SituacionAccion = bdAsegasa.accionessiniestros_eiac.ObtieneSituacionAccionV6((string)accs.SituacionAccion); +// yaincorporados.Add(numeroOrden); +// } +// } +// } - if (s.DatosSiniestro.Expedientes != null) - { - var yaincorporados = new List(); - foreach (var exp in s.DatosSiniestro.Expedientes) - { - string numeroExpediente = exp.NumeroExpediente; - if (string.IsNullOrEmpty(numeroExpediente)) numeroExpediente = exp.GetHashCode().ToString(); +// if (s.DatosSiniestro.Expedientes != null) +// { +// var yaincorporados = new List(); +// foreach (var exp in s.DatosSiniestro.Expedientes) +// { +// string numeroExpediente = exp.NumeroExpediente; +// if (string.IsNullOrEmpty(numeroExpediente)) numeroExpediente = exp.GetHashCode().ToString(); - if (!yaincorporados.Contains(numeroExpediente)) - { - var ep = seiac.expedientessiniestros_eiac.FirstOrDefault(x => x.NumeroExpediente == numeroExpediente); - if (ep == null) - { - ep = new expedientessiniestros_eiac { NumeroExpediente = numeroExpediente }; - seiac.expedientessiniestros_eiac.Add(ep); - } - ep.EstadoExpediente = bdAsegasa.expedientessiniestros_eiac.ObtieneEstadoExpedienteV6((string)exp.EstadoExpediente); - ep.ImporteReserva = exp.ImporteReserva; - ep.TotalPagos = exp.TotalPagos; - ep.TotalRecobros = exp.TotalRecobros; - ep.FechaInicio = exp.FechaInicio; - ep.FechaFin = exp.FechaFin; - ep.NumeroOrden = exp.NumeroOrden; - yaincorporados.Add(numeroExpediente); - } - } - } +// if (!yaincorporados.Contains(numeroExpediente)) +// { +// var ep = seiac.expedientessiniestros_eiac.FirstOrDefault(x => x.NumeroExpediente == numeroExpediente); +// if (ep == null) +// { +// ep = new expedientessiniestros_eiac { NumeroExpediente = numeroExpediente }; +// seiac.expedientessiniestros_eiac.Add(ep); +// } +// ep.EstadoExpediente = bdAsegasa.expedientessiniestros_eiac.ObtieneEstadoExpedienteV6((string)exp.EstadoExpediente); +// ep.ImporteReserva = exp.ImporteReserva; +// ep.TotalPagos = exp.TotalPagos; +// ep.TotalRecobros = exp.TotalRecobros; +// ep.FechaInicio = exp.FechaInicio; +// ep.FechaFin = exp.FechaFin; +// ep.NumeroOrden = exp.NumeroOrden; +// yaincorporados.Add(numeroExpediente); +// } +// } +// } - if (seiac.idSiniestroNavigation == null) - { - var fi = seiac.FechaOcurrencia.AddDays(-5); - var ff = seiac.FechaOcurrencia.AddDays(5); +// if (seiac.idSiniestroNavigation == null) +// { +// var fi = seiac.FechaOcurrencia.AddDays(-5); +// var ff = seiac.FechaOcurrencia.AddDays(5); - var fechaInicio = DateOnly.FromDateTime(fi); - var fechaFinal = DateOnly.FromDateTime(ff); +// var fechaInicio = DateOnly.FromDateTime(fi); +// var fechaFinal = DateOnly.FromDateTime(ff); - sins = bd.siniestros.Where(x => - x.idPolizaNavigation.NumeroPoliza == seiac.NumeroPoliza && - x.FechaAccidente.HasValue && - x.FechaAccidente >= fechaInicio && - x.FechaAccidente <= fechaFinal).ToList(); +// sins = bd.siniestros.Where(x => +// x.idPolizaNavigation.NumeroPoliza == seiac.NumeroPoliza && +// x.FechaAccidente.HasValue && +// x.FechaAccidente >= fechaInicio && +// x.FechaAccidente <= fechaFinal).ToList(); - if (sins.Count == 1) - { - seiac.idSiniestroNavigation = sins[0]; - } - } +// if (sins.Count == 1) +// { +// seiac.idSiniestroNavigation = sins[0]; +// } +// } - bool bModificados = false; - if (bd.ChangeTracker.Entries().Any(e => e.State == EntityState.Added)) - { - bModificados = true; - seiac.SituacionAsegasa = (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.NUEVO; - seiac.FechaSituacion = DateTime.Now; - } - else - { - var prmods = bd.ChangeTracker.Entries().Where(e => e.State == EntityState.Modified).ToList(); - if (prmods.Count > 0) - { - foreach (var pr in prmods) - { - var original = pr.OriginalValues; - var nuevosvalores = pr.CurrentValues; - foreach (var prop in original.Properties) - { - var origVal = original[prop]; - var newVal = nuevosvalores[prop]; +// bool bModificados = false; +// if (bd.ChangeTracker.Entries().Any(e => e.State == EntityState.Added)) +// { +// bModificados = true; +// seiac.SituacionAsegasa = (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.NUEVO; +// seiac.FechaSituacion = DateTime.Now; +// } +// else +// { +// var prmods = bd.ChangeTracker.Entries().Where(e => e.State == EntityState.Modified).ToList(); +// if (prmods.Count > 0) +// { +// foreach (var pr in prmods) +// { +// var original = pr.OriginalValues; +// var nuevosvalores = pr.CurrentValues; +// foreach (var prop in original.Properties) +// { +// var origVal = original[prop]; +// var newVal = nuevosvalores[prop]; - if (origVal?.GetHashCode() != newVal?.GetHashCode()) - { - bModificados = true; - break; - } - } - if (bModificados) break; - } - } - } +// if (origVal?.GetHashCode() != newVal?.GetHashCode()) +// { +// bModificados = true; +// break; +// } +// } +// if (bModificados) break; +// } +// } +// } - if (bModificados) - { - if (!seiac.SituacionAsegasa.HasValue || seiac.SituacionAsegasa.Value != (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.DESCARTADO) - { - seiac.SituacionAsegasa = (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.MODIFICADO; - seiac.FechaSituacion = DateTime.Now; - } +// if (bModificados) +// { +// if (!seiac.SituacionAsegasa.HasValue || seiac.SituacionAsegasa.Value != (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.DESCARTADO) +// { +// seiac.SituacionAsegasa = (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.MODIFICADO; +// seiac.FechaSituacion = DateTime.Now; +// } - var nact = new actualizacionessiniestros_eiac - { - idSiniestroEIACNavigation = seiac, - Fecha = DateTime.Now, - idFicheroCompania = f.idFichero - }; - bd.actualizacionessiniestros_eiac.Add(nact); +// var nact = new actualizacionessiniestros_eiac +// { +// idSiniestroEIACNavigation = seiac, +// Fecha = DateTime.Now, +// idFicheroCompania = f.idFichero +// }; +// bd.actualizacionessiniestros_eiac.Add(nact); - if (seiac.SituacionAsegasa.Value != (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.DESCARTADO) - { - if (!seiac.idPoliza.HasValue) - { - seiac.SituacionAsegasa = (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.POLIZA_NO_ENCONTRADA; - } - else - { - if (sins == null || sins.Count == 0) - { - seiac.SituacionAsegasa = (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.SINIESTRO_NO_ENCONTRADO; - } - else if (sins.Count > 1) - { - seiac.SituacionAsegasa = (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.VARIOS_SINIESTROS_POSIBLES; - } - } - } - bd.SaveChanges(); - } - } - } - f.FechaProcesado = DateTime.Now; - bd.SaveChanges(); - } - catch (Exception ex) - { - f.FechaError = DateTime.Now; - bd.SaveChanges(); - tsUtilidades.TsNotificacionesClient.RegistrarAsync("En IncorporaSiniestrosEIACV6.", $"Rutina: IncorporaSiniestrosEIACV6. Fichero:{f.NombreFichero} {ex.Message}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } - } - catch (Exception ex) - { - tsUtilidades.TsNotificacionesClient.RegistrarAsync("En IncorporaSiniestrosEIACV6.", $"Rutina: IncorporaSiniestrosEIACV6. {ex.Message}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } +// if (seiac.SituacionAsegasa.Value != (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.DESCARTADO) +// { +// if (!seiac.idPoliza.HasValue) +// { +// seiac.SituacionAsegasa = (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.POLIZA_NO_ENCONTRADA; +// } +// else +// { +// if (sins == null || sins.Count == 0) +// { +// seiac.SituacionAsegasa = (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.SINIESTRO_NO_ENCONTRADO; +// } +// else if (sins.Count > 1) +// { +// seiac.SituacionAsegasa = (int)bdAsegasa.siniestros_eiac.SituacionAsegasaENUM.VARIOS_SINIESTROS_POSIBLES; +// } +// } +// } +// bd.SaveChanges(); +// } +// } +// } +// f.FechaProcesado = DateTime.Now; +// bd.SaveChanges(); +// } +// catch (Exception ex) +// { +// f.FechaError = DateTime.Now; +// bd.SaveChanges(); +// tsUtilidades.TsNotificacionesClient.RegistrarAsync("En IncorporaSiniestrosEIACV6.", $"Rutina: IncorporaSiniestrosEIACV6. Fichero:{f.NombreFichero} {ex.Message}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } +// } +// catch (Exception ex) +// { +// tsUtilidades.TsNotificacionesClient.RegistrarAsync("En IncorporaSiniestrosEIACV6.", $"Rutina: IncorporaSiniestrosEIACV6. {ex.Message}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } - public static void IncorporaExpSiniestrosEIACV6() - { - try - { - using var bd = tscgestionasegasa.NuevoContexto(); - var ltpa = bd.enumeraciones.Where(x => x.idGrupoEnumeracionNavigation.Grupo == "TIPP").ToList(); - int tipo = (int)ficheroscompanias.TipoFicheroCompania.SINIESTROS_EIAC; - var ficspen = bd.ficheroscompanias - .Where(x => x.Tipo == tipo && x.Version == "6.0") - .OrderBy(x => x.idFichero) - .ToList(); +// public static void IncorporaExpSiniestrosEIACV6() +// { +// try +// { +// using var bd = tscgestionasegasa.NuevoContexto(); +// var ltpa = bd.enumeraciones.Where(x => x.idGrupoEnumeracionNavigation.Grupo == "TIPP").ToList(); +// int tipo = (int)ficheroscompanias.TipoFicheroCompania.SINIESTROS_EIAC; +// var ficspen = bd.ficheroscompanias +// .Where(x => x.Tipo == tipo && x.Version == "6.0") +// .OrderBy(x => x.idFichero) +// .ToList(); - foreach (var f in ficspen) - { - try - { - // Asumimos ProcesosEIAC_V6 existe y Utilizamos una librería genérica de serialización - dynamic DatosEIAC = tsUtilidades.Utilidades.Deserializa(f.Fichero, Type.GetType("ProcesosEIAC_V6.ProcesosEIAC") ?? typeof(object)); +// foreach (var f in ficspen) +// { +// try +// { +// // Asumimos ProcesosEIAC_V6 existe y Utilizamos una librería genérica de serialización +// dynamic DatosEIAC = tsUtilidades.Utilidades.Deserializa(f.Fichero, Type.GetType("ProcesosEIAC_V6.ProcesosEIAC") ?? typeof(object)); - if (DatosEIAC?.Objetos?.Items != null) - { - IEnumerable items = DatosEIAC.Objetos.Items; - var lSins = items.Where(x => x != null && x.GetType().Name == "tipo_siniestro"); +// if (DatosEIAC?.Objetos?.Items != null) +// { +// IEnumerable items = DatosEIAC.Objetos.Items; +// var lSins = items.Where(x => x != null && x.GetType().Name == "tipo_siniestro"); - foreach (var s in lSins) - { - string idSiniestroEntidad = s.DatosSiniestro.IdSiniestroEntidad; - var seiac = bd.siniestros_eiac.FirstOrDefault(x => x.idSiniestroEntidad == idSiniestroEntidad); +// foreach (var s in lSins) +// { +// string idSiniestroEntidad = s.DatosSiniestro.IdSiniestroEntidad; +// var seiac = bd.siniestros_eiac.FirstOrDefault(x => x.idSiniestroEntidad == idSiniestroEntidad); - if (seiac != null) - { - if (s.DatosSiniestro.Expedientes != null) - { - var yaincorporados = new List(); - foreach (var exp in s.DatosSiniestro.Expedientes) - { - string numeroExpediente = exp.NumeroExpediente; - if (string.IsNullOrEmpty(numeroExpediente)) numeroExpediente = exp.GetHashCode().ToString(); +// if (seiac != null) +// { +// if (s.DatosSiniestro.Expedientes != null) +// { +// var yaincorporados = new List(); +// foreach (var exp in s.DatosSiniestro.Expedientes) +// { +// string numeroExpediente = exp.NumeroExpediente; +// if (string.IsNullOrEmpty(numeroExpediente)) numeroExpediente = exp.GetHashCode().ToString(); - if (!yaincorporados.Contains(numeroExpediente)) - { - var ep = seiac.expedientessiniestros_eiac.FirstOrDefault(x => x.NumeroExpediente == numeroExpediente); - if (ep == null) - { - ep = new expedientessiniestros_eiac { NumeroExpediente = numeroExpediente }; - seiac.expedientessiniestros_eiac.Add(ep); - } - ep.EstadoExpediente = bdAsegasa.expedientessiniestros_eiac.ObtieneEstadoExpedienteV6((string)exp.EstadoExpediente); - ep.ImporteReserva = exp.ImporteReserva; - ep.TotalPagos = exp.TotalPagos; - ep.TotalRecobros = exp.TotalRecobros; - ep.FechaInicio = exp.FechaInicio; - ep.FechaFin = exp.FechaFin; - ep.NumeroOrden = exp.NumeroOrden; +// if (!yaincorporados.Contains(numeroExpediente)) +// { +// var ep = seiac.expedientessiniestros_eiac.FirstOrDefault(x => x.NumeroExpediente == numeroExpediente); +// if (ep == null) +// { +// ep = new expedientessiniestros_eiac { NumeroExpediente = numeroExpediente }; +// seiac.expedientessiniestros_eiac.Add(ep); +// } +// ep.EstadoExpediente = bdAsegasa.expedientessiniestros_eiac.ObtieneEstadoExpedienteV6((string)exp.EstadoExpediente); +// ep.ImporteReserva = exp.ImporteReserva; +// ep.TotalPagos = exp.TotalPagos; +// ep.TotalRecobros = exp.TotalRecobros; +// ep.FechaInicio = exp.FechaInicio; +// ep.FechaFin = exp.FechaFin; +// ep.NumeroOrden = exp.NumeroOrden; - yaincorporados.Add(numeroExpediente); - } - } - bd.SaveChanges(); - } - } - } - } - // f.FechaProcesado = Now (Comentado en el código original) - bd.SaveChanges(); - } - catch (Exception ex) - { - f.FechaError = DateTime.Now; - bd.SaveChanges(); - tsUtilidades.TsNotificacionesClient.RegistrarAsync("En IncorporaSiniestrosEIACV6.", $"Rutina: IncorporaSiniestrosEIACV6. Fichero:{f.NombreFichero} {ex.Message}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } - } - catch (Exception ex) - { - tsUtilidades.TsNotificacionesClient.RegistrarAsync("En IncorporaSiniestrosEIACV6.", $"Rutina: IncorporaSiniestrosEIACV6. {ex.Message}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } - } -} +// yaincorporados.Add(numeroExpediente); +// } +// } +// bd.SaveChanges(); +// } +// } +// } +// } +// // f.FechaProcesado = Now (Comentado en el código original) +// bd.SaveChanges(); +// } +// catch (Exception ex) +// { +// f.FechaError = DateTime.Now; +// bd.SaveChanges(); +// tsUtilidades.TsNotificacionesClient.RegistrarAsync("En IncorporaSiniestrosEIACV6.", $"Rutina: IncorporaSiniestrosEIACV6. Fichero:{f.NombreFichero} {ex.Message}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } +// } +// catch (Exception ex) +// { +// tsUtilidades.TsNotificacionesClient.RegistrarAsync("En IncorporaSiniestrosEIACV6.", $"Rutina: IncorporaSiniestrosEIACV6. {ex.Message}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } +// } +//} diff --git a/Servicio Gestion Asegasa/Procesos/ProcesosTractoresAxa.cs b/Servicio Gestion Asegasa/Procesos/ProcesosTractoresAxa.cs index fc34e10..1ff35e3 100644 --- a/Servicio Gestion Asegasa/Procesos/ProcesosTractoresAxa.cs +++ b/Servicio Gestion Asegasa/Procesos/ProcesosTractoresAxa.cs @@ -1,619 +1,619 @@ -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.IO; -using System.Linq; -using System.Text; -using bdAsegasa; -using bdAsegasa.db; +//using System; +//using System.Collections.Generic; +//using System.Diagnostics; +//using System.IO; +//using System.Linq; +//using System.Text; +//using bdAsegasa; +//using bdAsegasa.db; -namespace Servicio_Gestion_Asegasa.Procesos -{ - public class ProcesosTractoresAxa - { - public static int GenerarYGuardarEnBdCsvTractoresAxa(tscgestionasegasa bd) - { - int resultadoGuardarCambios = 0; - try - { - var listaAltas = new List(); - var listaAltasFiltradasPorFecha = new List(); - int idRamoTractores = bd.ramos.First(x => x.Codigo == "1-1").idRamo; - int idRamoRemolques = bd.ramos.First(x => x.Codigo == "1-1-1").idRamo; - int idCiaAXA = bd.companias.First(x => x.Codigo == "0027").idCompania; - int idTipoGestionPoliza = bd.enumeraciones.First(x => x.Codigo == "TGP.CSVAXA").idEnumeracion; - int idTipoFicheroCSV = bd.enumeraciones.First(x => x.Codigo == "TIPFIC.CSVAXA").idEnumeracion; +//namespace Servicio_Gestion_Asegasa.Procesos +//{ +// public class ProcesosTractoresAxa +// { +// public static int GenerarYGuardarEnBdCsvTractoresAxa(tscgestionasegasa bd) +// { +// int resultadoGuardarCambios = 0; +// try +// { +// var listaAltas = new List(); +// var listaAltasFiltradasPorFecha = new List(); +// int idRamoTractores = bd.ramos.First(x => x.Codigo == "1-1").idRamo; +// int idRamoRemolques = bd.ramos.First(x => x.Codigo == "1-1-1").idRamo; +// int idCiaAXA = bd.companias.First(x => x.Codigo == "0027").idCompania; +// int idTipoGestionPoliza = bd.enumeraciones.First(x => x.Codigo == "TGP.CSVAXA").idEnumeracion; +// int idTipoFicheroCSV = bd.enumeraciones.First(x => x.Codigo == "TIPFIC.CSVAXA").idEnumeracion; - ficheros lineaFichero; - gestionesvarias lineaGestionesVarias; +// ficheros lineaFichero; +// gestionesvarias lineaGestionesVarias; - DateTime dHoy = DateTime.Today; - DateTime dAyer = DateTime.Today.AddDays(-1); +// DateTime dHoy = DateTime.Today; +// DateTime dAyer = DateTime.Today.AddDays(-1); - try - { - listaAltas = bd.polizassg.Where(x => - (x.idRamoNavigation.idRamo == idRamoTractores || x.idRamoNavigation.idRamo == idRamoRemolques) && - x.idCompania == idCiaAXA && - x.FechaAceptacionPresupuesto.HasValue && - !x.FechaBaja.HasValue && - !x.gestionespolizassg.Any(y => y.idTipo == idTipoGestionPoliza) && - x.idOrigenPresupuesto == (int)bdAsegasa.db.polizassg.TiposPresupuestos.TRACTORES - ).ToList(); +// try +// { +// listaAltas = bd.polizassg.Where(x => +// (x.idRamoNavigation.idRamo == idRamoTractores || x.idRamoNavigation.idRamo == idRamoRemolques) && +// x.idCompania == idCiaAXA && +// x.FechaAceptacionPresupuesto.HasValue && +// !x.FechaBaja.HasValue && +// !x.gestionespolizassg.Any(y => y.idTipo == idTipoGestionPoliza) && +// x.idOrigenPresupuesto == (int)bdAsegasa.db.polizassg.TiposPresupuestos.TRACTORES +// ).ToList(); - listaAltasFiltradasPorFecha = listaAltas.Where(x => x.FechaAlta.HasValue && x.FechaAlta.Value.Date < dHoy).ToList(); +// listaAltasFiltradasPorFecha = listaAltas.Where(x => x.FechaAlta.HasValue && x.FechaAlta.Value.Date < dHoy).ToList(); - Debug.WriteLine("listaAltas: {0}", listaAltas.Count); - Debug.WriteLine("listaAltasFiltradasPorFecha: {0}", listaAltasFiltradasPorFecha.Count); - foreach (var item in listaAltasFiltradasPorFecha) - { - Debug.WriteLine($"({item.idPoliza},{item.NumeroPoliza},{item.Matricula})"); - } - } - catch (Exception ex) - { - Debug.Write(ex.ToString()); - tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En {System.Reflection.MethodBase.GetCurrentMethod()}", - $"En método {System.Reflection.MethodBase.GetCurrentMethod()}. {Environment.MachineName} {ex.ToString()}",tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } +// Debug.WriteLine("listaAltas: {0}", listaAltas.Count); +// Debug.WriteLine("listaAltasFiltradasPorFecha: {0}", listaAltasFiltradasPorFecha.Count); +// foreach (var item in listaAltasFiltradasPorFecha) +// { +// Debug.WriteLine($"({item.idPoliza},{item.NumeroPoliza},{item.Matricula})"); +// } +// } +// catch (Exception ex) +// { +// Debug.Write(ex.ToString()); +// tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En {System.Reflection.MethodBase.GetCurrentMethod()}", +// $"En método {System.Reflection.MethodBase.GetCurrentMethod()}. {Environment.MachineName} {ex.ToString()}",tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } - if (listaAltasFiltradasPorFecha.Count > 0) - { - lineaFichero = new ficheros - { - Descripcion = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.DescripcionFicheroCSV").ValorAlfabeticoLargo} {dAyer:yyyy-MM-dd}", - Fecha = DateTime.Now, - idTipo = idTipoFicheroCSV, - NombreFichero = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.NombreFicheroCSV").ValorAlfabeticoLargo}{dAyer:yyyy-MM-dd}.csv" - }; +// if (listaAltasFiltradasPorFecha.Count > 0) +// { +// lineaFichero = new ficheros +// { +// Descripcion = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.DescripcionFicheroCSV").ValorAlfabeticoLargo} {dAyer:yyyy-MM-dd}", +// Fecha = DateTime.Now, +// idTipo = idTipoFicheroCSV, +// NombreFichero = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.NombreFicheroCSV").ValorAlfabeticoLargo}{dAyer:yyyy-MM-dd}.csv" +// }; - bd.ficheros.Add(lineaFichero); +// bd.ficheros.Add(lineaFichero); - lineaGestionesVarias = new gestionesvarias - { - Descripción = lineaFichero.NombreFichero, - idTipo = idTipoGestionPoliza, - idFicheroNavigation = lineaFichero, - FechaCreacion = DateTime.Now - }; +// lineaGestionesVarias = new gestionesvarias +// { +// Descripción = lineaFichero.NombreFichero, +// idTipo = idTipoGestionPoliza, +// idFicheroNavigation = lineaFichero, +// FechaCreacion = DateTime.Now +// }; - bd.gestionesvarias.Add(lineaGestionesVarias); +// bd.gestionesvarias.Add(lineaGestionesVarias); - byte[] archivoCSV = GenerarCsvTractoresAxa(bd, listaAltasFiltradasPorFecha, lineaGestionesVarias); +// byte[] archivoCSV = GenerarCsvTractoresAxa(bd, listaAltasFiltradasPorFecha, lineaGestionesVarias); - lineaFichero.Fichero = archivoCSV; - resultadoGuardarCambios = bd.SaveChanges(); +// lineaFichero.Fichero = archivoCSV; +// resultadoGuardarCambios = bd.SaveChanges(); - if (resultadoGuardarCambios > 0) - { - try - { - var mensaje = new StringBuilder(); - mensaje.AppendFormat("Se ha generado un archivo CSV con altas de tractores y/o remolques para AXA.```idFichero: {1}{0}NombreFichero: {2}{0}idGestion: {3}{0}Servidor: {4}```", - Environment.NewLine, lineaFichero.idFichero, lineaFichero.NombreFichero, lineaGestionesVarias.idGestion, Environment.MachineName); - } - catch - { - } - } - } - } - catch (Exception ex) - { - Debug.WriteLine("No hay líneas o se produjo excepción."); - Debug.WriteLine(ex.ToString()); - tsUtilidades.TsNotificacionesClient.RegistrarAsync( $"En {System.Reflection.MethodBase.GetCurrentMethod()}", - $"En método {System.Reflection.MethodBase.GetCurrentMethod()}. {Environment.MachineName} {ex.ToString()}",tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - return resultadoGuardarCambios; - } +// if (resultadoGuardarCambios > 0) +// { +// try +// { +// var mensaje = new StringBuilder(); +// mensaje.AppendFormat("Se ha generado un archivo CSV con altas de tractores y/o remolques para AXA.```idFichero: {1}{0}NombreFichero: {2}{0}idGestion: {3}{0}Servidor: {4}```", +// Environment.NewLine, lineaFichero.idFichero, lineaFichero.NombreFichero, lineaGestionesVarias.idGestion, Environment.MachineName); +// } +// catch +// { +// } +// } +// } +// } +// catch (Exception ex) +// { +// Debug.WriteLine("No hay líneas o se produjo excepción."); +// Debug.WriteLine(ex.ToString()); +// tsUtilidades.TsNotificacionesClient.RegistrarAsync( $"En {System.Reflection.MethodBase.GetCurrentMethod()}", +// $"En método {System.Reflection.MethodBase.GetCurrentMethod()}. {Environment.MachineName} {ex.ToString()}",tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// return resultadoGuardarCambios; +// } - public static byte[] GenerarCsvTractoresAxa(tscgestionasegasa bd, List listaPolizas, gestionesvarias lineaGestionesVarias = null) - { - byte[] archivoCSV = null; - int idTipoGestionPoliza = bd.enumeraciones.First(x => x.Codigo == "TGP.CSVAXA").idEnumeracion; - string sDescripcionGestion = bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.DescripcionGestion").ValorAlfabeticoLargo; - string nombreArchivoTemporal = Path.GetTempFileName(); +// public static byte[] GenerarCsvTractoresAxa(tscgestionasegasa bd, List listaPolizas, gestionesvarias lineaGestionesVarias = null) +// { +// byte[] archivoCSV = null; +// int idTipoGestionPoliza = bd.enumeraciones.First(x => x.Codigo == "TGP.CSVAXA").idEnumeracion; +// string sDescripcionGestion = bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.DescripcionGestion").ValorAlfabeticoLargo; +// string nombreArchivoTemporal = Path.GetTempFileName(); - // Usar ANSI/ISO encoding - Encoding iso = Encoding.GetEncoding("iso-8859-1"); +// // Usar ANSI/ISO encoding +// Encoding iso = Encoding.GetEncoding("iso-8859-1"); - using (var sw = new StreamWriter(File.Open(nombreArchivoTemporal, FileMode.Create), iso)) - { - sw.WriteLine("Código Marca;Código Modelo;Código Versión;Medofi;Fecha de Efecto;Hora de Fecha Efecto;CAMPAÑA;Producto;Nº Póliza Reservado;Fecha entrada en Delegación;Duración;Plan de cobro;Canal de cobro;Fecha Vto.;NIF, CIF, OTROS;Nº de NIF ó CIF;Primer apellido si es Empresa, no cumplimentar;Segundo apellido si es Empresa, no cumplimentar;Nombre;Fecha Nacimiento;Estado Civil;SEXO;C.P.;Población;Tipo Vía;Nombre Vía;Numero vía;Resto Vía;Propietario;Nombre propietario;Apellido 1 propietario;Apellido 2 propietario;Nif/Cif propietario;Conductor Titular;Nombre Conductor;1º Apellido Conductor;2º Apellido Conductor;Fecha nacimiento conductor DDMMAAAA;Nif, Cif, Otros;NIF Conductor;SEXO;Fecha carnét DDMMAAAA;Conductor Autorizado 1;Nombre Conductor;1º Apellido Conductor;2º Apellido Conductor;Fecha nto. Conductor DDMMAAAA;NIF Conductor;SEXO;Fecha carnet DDMMAAAA;Conductor Autorizado 2;Nombre Conductor;1º Apellido Conductor;2º Apellido Conductor;Fecha nto. Conductor DDMMAAAA;NIF Conductor;SEXO;Fecha carnet DDMMAAAA;Permiso retirado (fijo);Uso Vehículo (según tabla);Accesorios;Tipo de Accesorios;Descripción (Detallar los accesorios separados por comas);Valor Accesorios (valor total);Peso en Toneladas;Literal de Marca;Literal de Modelo;Literal de Versión;Valor (fijo);Valor LUNAS;Matrícula;Fecha 1ª Matriculación DDMMAAAA;C.P. circulación (poner el CP del conductor);Alarma (fijo);Garaje (fijo);KM recorridos (fijo);Combinación de Garantías;Combinación de Accidentes;Kit RC Explotación Agrícola;PRIMA TOTAL;Nº PîLIZA EMITIDA;PNETA EMITIDA;PTOTAL EMITIDA"); - foreach (var linea in listaPolizas) - { - int idTipoFicheroPresupuesto = bd.enumeraciones.First(x => x.Codigo == "TIPFIC.PRESUPUESTO").idEnumeracion; - if (linea.idFicheroPresupuestoNavigation?.idTipo == idTipoFicheroPresupuesto && - linea.idFicheroPresupuestoNavigation?.NombreFichero?.Trim().ToUpper() == "TRACTORES.XML" && - !string.IsNullOrWhiteSpace(linea.NumeroPoliza)) - { - string lineaCSV = ""; - bool lineaCsvCorrecta = false; - try - { - lineaCSV = ComponerLineaCsv(linea, bd); - lineaCsvCorrecta = true; - } - catch (Exception ex) - { - string asunto = $"No se ha podido generar una línea del CSV de TractoresAXA; idPoliza = {linea.idPoliza}; Máquina = {Environment.MachineName}"; - string cuerpo = $"No se ha podido generar una línea del CSV de TractoresAXA; idPoliza = {linea.idPoliza}\r\n" + - $"Esto podría significar que falta algún dato en esta póliza.\r\n" + - $"En método {System.Reflection.MethodBase.GetCurrentMethod()}.\r\n{Environment.MachineName} {ex.ToString()}"; - tsUtilidades.TsNotificacionesClient.RegistrarAsync(asunto, cuerpo, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } +// using (var sw = new StreamWriter(File.Open(nombreArchivoTemporal, FileMode.Create), iso)) +// { +// sw.WriteLine("Código Marca;Código Modelo;Código Versión;Medofi;Fecha de Efecto;Hora de Fecha Efecto;CAMPAÑA;Producto;Nº Póliza Reservado;Fecha entrada en Delegación;Duración;Plan de cobro;Canal de cobro;Fecha Vto.;NIF, CIF, OTROS;Nº de NIF ó CIF;Primer apellido si es Empresa, no cumplimentar;Segundo apellido si es Empresa, no cumplimentar;Nombre;Fecha Nacimiento;Estado Civil;SEXO;C.P.;Población;Tipo Vía;Nombre Vía;Numero vía;Resto Vía;Propietario;Nombre propietario;Apellido 1 propietario;Apellido 2 propietario;Nif/Cif propietario;Conductor Titular;Nombre Conductor;1º Apellido Conductor;2º Apellido Conductor;Fecha nacimiento conductor DDMMAAAA;Nif, Cif, Otros;NIF Conductor;SEXO;Fecha carnét DDMMAAAA;Conductor Autorizado 1;Nombre Conductor;1º Apellido Conductor;2º Apellido Conductor;Fecha nto. Conductor DDMMAAAA;NIF Conductor;SEXO;Fecha carnet DDMMAAAA;Conductor Autorizado 2;Nombre Conductor;1º Apellido Conductor;2º Apellido Conductor;Fecha nto. Conductor DDMMAAAA;NIF Conductor;SEXO;Fecha carnet DDMMAAAA;Permiso retirado (fijo);Uso Vehículo (según tabla);Accesorios;Tipo de Accesorios;Descripción (Detallar los accesorios separados por comas);Valor Accesorios (valor total);Peso en Toneladas;Literal de Marca;Literal de Modelo;Literal de Versión;Valor (fijo);Valor LUNAS;Matrícula;Fecha 1ª Matriculación DDMMAAAA;C.P. circulación (poner el CP del conductor);Alarma (fijo);Garaje (fijo);KM recorridos (fijo);Combinación de Garantías;Combinación de Accidentes;Kit RC Explotación Agrícola;PRIMA TOTAL;Nº PîLIZA EMITIDA;PNETA EMITIDA;PTOTAL EMITIDA"); +// foreach (var linea in listaPolizas) +// { +// int idTipoFicheroPresupuesto = bd.enumeraciones.First(x => x.Codigo == "TIPFIC.PRESUPUESTO").idEnumeracion; +// if (linea.idFicheroPresupuestoNavigation?.idTipo == idTipoFicheroPresupuesto && +// linea.idFicheroPresupuestoNavigation?.NombreFichero?.Trim().ToUpper() == "TRACTORES.XML" && +// !string.IsNullOrWhiteSpace(linea.NumeroPoliza)) +// { +// string lineaCSV = ""; +// bool lineaCsvCorrecta = false; +// try +// { +// lineaCSV = ComponerLineaCsv(linea, bd); +// lineaCsvCorrecta = true; +// } +// catch (Exception ex) +// { +// string asunto = $"No se ha podido generar una línea del CSV de TractoresAXA; idPoliza = {linea.idPoliza}; Máquina = {Environment.MachineName}"; +// string cuerpo = $"No se ha podido generar una línea del CSV de TractoresAXA; idPoliza = {linea.idPoliza}\r\n" + +// $"Esto podría significar que falta algún dato en esta póliza.\r\n" + +// $"En método {System.Reflection.MethodBase.GetCurrentMethod()}.\r\n{Environment.MachineName} {ex.ToString()}"; +// tsUtilidades.TsNotificacionesClient.RegistrarAsync(asunto, cuerpo, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } - if (lineaCsvCorrecta) - { - sw.WriteLine(lineaCSV); - if (lineaGestionesVarias != null && !string.IsNullOrWhiteSpace(lineaGestionesVarias.Descripción)) - { - linea.gestionespolizassg.Add(new gestionespolizassg - { - idPoliza = linea.idPoliza, - idTipo = idTipoGestionPoliza, - Fecha = DateTime.Now, - GestionesRealizadas = sDescripcionGestion, - idGestionVariasNavigation = lineaGestionesVarias - }); - } - } - } - else - { - string cadenaError = $"Advertencia: el fichero no es de tipo \"TIPFIC.PRESUPUESTO\" o no se llama \"tractores.xml\", o no hay número de póliza; idPoliza = {linea.idPoliza}"; - Console.WriteLine(cadenaError); - tsUtilidades.TsNotificacionesClient.RegistrarAsync( $"En {System.Reflection.MethodBase.GetCurrentMethod()}", - $"En método {System.Reflection.MethodBase.GetCurrentMethod()}. {Environment.MachineName} {cadenaError}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - } - } +// if (lineaCsvCorrecta) +// { +// sw.WriteLine(lineaCSV); +// if (lineaGestionesVarias != null && !string.IsNullOrWhiteSpace(lineaGestionesVarias.Descripción)) +// { +// linea.gestionespolizassg.Add(new gestionespolizassg +// { +// idPoliza = linea.idPoliza, +// idTipo = idTipoGestionPoliza, +// Fecha = DateTime.Now, +// GestionesRealizadas = sDescripcionGestion, +// idGestionVariasNavigation = lineaGestionesVarias +// }); +// } +// } +// } +// else +// { +// string cadenaError = $"Advertencia: el fichero no es de tipo \"TIPFIC.PRESUPUESTO\" o no se llama \"tractores.xml\", o no hay número de póliza; idPoliza = {linea.idPoliza}"; +// Console.WriteLine(cadenaError); +// tsUtilidades.TsNotificacionesClient.RegistrarAsync( $"En {System.Reflection.MethodBase.GetCurrentMethod()}", +// $"En método {System.Reflection.MethodBase.GetCurrentMethod()}. {Environment.MachineName} {cadenaError}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// } +// } - if (NumeroDeLineasEnElArchivoCSV(nombreArchivoTemporal) <= 1) - { - throw new Exception("El archivo CSV que se ha generado solamente tiene la línea de la cabecera, es decir, no lleva información de ninguna póliza, por lo cual no tiene sentido mandarlo."); - } +// if (NumeroDeLineasEnElArchivoCSV(nombreArchivoTemporal) <= 1) +// { +// throw new Exception("El archivo CSV que se ha generado solamente tiene la línea de la cabecera, es decir, no lleva información de ninguna póliza, por lo cual no tiene sentido mandarlo."); +// } - archivoCSV = File.ReadAllBytes(nombreArchivoTemporal); - try - { - File.Delete(nombreArchivoTemporal); - } - catch - { - // Nada, a propósito - } +// archivoCSV = File.ReadAllBytes(nombreArchivoTemporal); +// try +// { +// File.Delete(nombreArchivoTemporal); +// } +// catch +// { +// // Nada, a propósito +// } - return archivoCSV; - } +// return archivoCSV; +// } - public static byte[] GenerarCsvTractoresAxa(tscgestionasegasa bd, string cadenaListaPolizas = null) - { - byte[] archivoCSV = null; - var listaPolizas = new List(); - int idRamoTractores = bd.ramos.Where(x => x.Codigo == "1-1").Select(x => x.idRamo).FirstOrDefault(); - int idRamoRemolques = bd.ramos.Where(x => x.Codigo == "1-1-1").Select(x => x.idRamo).FirstOrDefault(); - int idCiaAXA = bd.companias.Where(x => x.Codigo == "0027").Select(x => x.idCompania).FirstOrDefault(); +// public static byte[] GenerarCsvTractoresAxa(tscgestionasegasa bd, string cadenaListaPolizas = null) +// { +// byte[] archivoCSV = null; +// var listaPolizas = new List(); +// int idRamoTractores = bd.ramos.Where(x => x.Codigo == "1-1").Select(x => x.idRamo).FirstOrDefault(); +// int idRamoRemolques = bd.ramos.Where(x => x.Codigo == "1-1-1").Select(x => x.idRamo).FirstOrDefault(); +// int idCiaAXA = bd.companias.Where(x => x.Codigo == "0027").Select(x => x.idCompania).FirstOrDefault(); - var listaCadenasSeparadasPorComas = cadenaListaPolizas.Split(',').ToList(); - foreach (var x in listaCadenasSeparadasPorComas) - { - if (x.Contains("-")) - { - var subListaRangos = x.Split('-').ToList(); - if (subListaRangos.Count == 2) - { - uint iRangoDesde = uint.Parse(subListaRangos.First().Trim()); - uint iRangoHasta = uint.Parse(subListaRangos.Last().Trim()); +// var listaCadenasSeparadasPorComas = cadenaListaPolizas.Split(',').ToList(); +// foreach (var x in listaCadenasSeparadasPorComas) +// { +// if (x.Contains("-")) +// { +// var subListaRangos = x.Split('-').ToList(); +// if (subListaRangos.Count == 2) +// { +// uint iRangoDesde = uint.Parse(subListaRangos.First().Trim()); +// uint iRangoHasta = uint.Parse(subListaRangos.Last().Trim()); - var results = bd.polizassg.Where(y => - (y.idRamoNavigation.idRamo == idRamoTractores || y.idRamoNavigation.idRamo == idRamoRemolques) && - y.idCompania == idCiaAXA && - y.idOrigenPresupuesto == (int)bdAsegasa.db.polizassg.TiposPresupuestos.TRACTORES && - (Convert.ToUInt32(y.NumeroPoliza) >= iRangoDesde && Convert.ToUInt32(y.NumeroPoliza) <= iRangoHasta) - ).OrderBy(y => y.NumeroPoliza).ToList(); +// var results = bd.polizassg.Where(y => +// (y.idRamoNavigation.idRamo == idRamoTractores || y.idRamoNavigation.idRamo == idRamoRemolques) && +// y.idCompania == idCiaAXA && +// y.idOrigenPresupuesto == (int)bdAsegasa.db.polizassg.TiposPresupuestos.TRACTORES && +// (Convert.ToUInt32(y.NumeroPoliza) >= iRangoDesde && Convert.ToUInt32(y.NumeroPoliza) <= iRangoHasta) +// ).OrderBy(y => y.NumeroPoliza).ToList(); - listaPolizas.AddRange(results); - } - else - { - throw new FormatException($"Error con el formato de los rangos de números de pólizas especificados: {cadenaListaPolizas}"); - } - } - else - { - string sNumeroPoliza = x.Trim(); - var temp = bd.polizassg.First(y => y.NumeroPoliza == sNumeroPoliza); - listaPolizas.Add(temp); - } - } +// listaPolizas.AddRange(results); +// } +// else +// { +// throw new FormatException($"Error con el formato de los rangos de números de pólizas especificados: {cadenaListaPolizas}"); +// } +// } +// else +// { +// string sNumeroPoliza = x.Trim(); +// var temp = bd.polizassg.First(y => y.NumeroPoliza == sNumeroPoliza); +// listaPolizas.Add(temp); +// } +// } - foreach (var poliza in listaPolizas) - { - Debug.WriteLine($"[{poliza.idPoliza},{poliza.NumeroPoliza},{poliza.Matricula}]"); - } +// foreach (var poliza in listaPolizas) +// { +// Debug.WriteLine($"[{poliza.idPoliza},{poliza.NumeroPoliza},{poliza.Matricula}]"); +// } - archivoCSV = GenerarCsvTractoresAxa(bd, listaPolizas); - return archivoCSV; - } +// archivoCSV = GenerarCsvTractoresAxa(bd, listaPolizas); +// return archivoCSV; +// } - public static byte[] GenerarCsvTractoresAxa(tscgestionasegasa bd, DateTime fechaDesde, DateTime fechaHasta) - { - byte[] archivoCSV = null; - int idRamoTractores = bd.ramos.Where(x => x.Codigo == "1-1").Select(x => x.idRamo).FirstOrDefault(); - int idRamoRemolques = bd.ramos.Where(x => x.Codigo == "1-1-1").Select(x => x.idRamo).FirstOrDefault(); - int idCiaAXA = bd.companias.Where(x => x.Codigo == "0027").Select(x => x.idCompania).FirstOrDefault(); +// public static byte[] GenerarCsvTractoresAxa(tscgestionasegasa bd, DateTime fechaDesde, DateTime fechaHasta) +// { +// byte[] archivoCSV = null; +// int idRamoTractores = bd.ramos.Where(x => x.Codigo == "1-1").Select(x => x.idRamo).FirstOrDefault(); +// int idRamoRemolques = bd.ramos.Where(x => x.Codigo == "1-1-1").Select(x => x.idRamo).FirstOrDefault(); +// int idCiaAXA = bd.companias.Where(x => x.Codigo == "0027").Select(x => x.idCompania).FirstOrDefault(); - var listaAltas = bd.polizassg.Where(x => - (x.idRamoNavigation.idRamo == idRamoTractores || x.idRamoNavigation.idRamo == idRamoRemolques) && - x.idCompania == idCiaAXA && - x.idOrigenPresupuesto == (int)bdAsegasa.db.polizassg.TiposPresupuestos.TRACTORES - ).ToList(); +// var listaAltas = bd.polizassg.Where(x => +// (x.idRamoNavigation.idRamo == idRamoTractores || x.idRamoNavigation.idRamo == idRamoRemolques) && +// x.idCompania == idCiaAXA && +// x.idOrigenPresupuesto == (int)bdAsegasa.db.polizassg.TiposPresupuestos.TRACTORES +// ).ToList(); - var listaAltasFiltradasPorFecha = listaAltas.Where(x => - x.FechaAlta.HasValue && x.FechaAlta.Value.Date <= fechaHasta && - x.FechaAlta.HasValue && x.FechaAlta.Value.Date >= fechaDesde - ).ToList(); +// var listaAltasFiltradasPorFecha = listaAltas.Where(x => +// x.FechaAlta.HasValue && x.FechaAlta.Value.Date <= fechaHasta && +// x.FechaAlta.HasValue && x.FechaAlta.Value.Date >= fechaDesde +// ).ToList(); - archivoCSV = GenerarCsvTractoresAxa(bd, listaAltasFiltradasPorFecha); - return archivoCSV; - } +// archivoCSV = GenerarCsvTractoresAxa(bd, listaAltasFiltradasPorFecha); +// return archivoCSV; +// } - private static string ComponerLineaCsv(polizassg poliza, tscgestionasegasa bd) - { - var sb = new StringBuilder(); - try - { - var listaDatosFaltantes = new List(); +// private static string ComponerLineaCsv(polizassg poliza, tscgestionasegasa bd) +// { +// var sb = new StringBuilder(); +// try +// { +// var listaDatosFaltantes = new List(); - // Assuming poliza.Tractores is available dynamically or strongly typed via partial - dynamic pTractores = ((dynamic)poliza).Tractores; +// // Assuming poliza.Tractores is available dynamically or strongly typed via partial +// dynamic pTractores = ((dynamic)poliza).Tractores; - if (string.IsNullOrWhiteSpace(((string)pTractores.TipoVehiculo)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TipoVehiculo"); - if (string.IsNullOrWhiteSpace((poliza.FechaEfecto).ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.FechaEfecto"); - if (string.IsNullOrWhiteSpace(((string)poliza.Tomador.CIF)?.Trim())) listaDatosFaltantes.Add("poliza.Tomador.CIF"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.TipoVehiculo)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TipoVehiculo"); +// if (string.IsNullOrWhiteSpace((poliza.FechaEfecto).ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.FechaEfecto"); +// if (string.IsNullOrWhiteSpace(((string)poliza.Tomador.CIF)?.Trim())) listaDatosFaltantes.Add("poliza.Tomador.CIF"); - if (ObtenerTipoDocumentoTractoresAxa((string)poliza.Tomador.CIF) != bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo) - { - if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorApellido1)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorApellido1"); - } +// if (ObtenerTipoDocumentoTractoresAxa((string)poliza.Tomador.CIF) != bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo) +// { +// if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorApellido1)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorApellido1"); +// } - if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorNombre)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorNombre"); - if (string.IsNullOrWhiteSpace(((DateTime)pTractores.TomadorFechaNacimiento).ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.Tractores.TomadorFechaNacimiento"); - if (string.IsNullOrWhiteSpace(((string)pTractores.EstadoCivil)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.EstadoCivil"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorNombre)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorNombre"); +// if (string.IsNullOrWhiteSpace(((DateTime)pTractores.TomadorFechaNacimiento).ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.Tractores.TomadorFechaNacimiento"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.EstadoCivil)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.EstadoCivil"); - if (ObtenerTipoDocumentoTractoresAxa((string)poliza.Tomador.CIF) != bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo) - { - if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorSexo?.ToString()))) listaDatosFaltantes.Add("poliza.Tractores.TomadorSexo"); - } +// if (ObtenerTipoDocumentoTractoresAxa((string)poliza.Tomador.CIF) != bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo) +// { +// if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorSexo?.ToString()))) listaDatosFaltantes.Add("poliza.Tractores.TomadorSexo"); +// } - if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorCodigoPostal)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorCodigoPostal"); - if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorPoblacion)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorPoblacion"); - if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorVia)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorVia"); - if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorNombreVia)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorNombreVia"); - if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorNumeroVia)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorNumeroVia"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorCodigoPostal)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorCodigoPostal"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorPoblacion)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorPoblacion"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorVia)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorVia"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorNombreVia)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorNombreVia"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorNumeroVia)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorNumeroVia"); - if (poliza.Propietario != null) - { - if (ObtenerTipoDocumentoTractoresAxa((string)poliza.Propietario.CIF) != bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo) - { - if (string.IsNullOrWhiteSpace(((string)pTractores.PropietarioSexo?.ToString()))) listaDatosFaltantes.Add("poliza.Tractores.PropietarioSexo"); - if (string.IsNullOrWhiteSpace(((string)pTractores.PropietarioApellido1)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.PropietarioApellido1"); - } - if (poliza.Propietario.idEntidad != poliza.Tomador.idEntidad) - { - if (string.IsNullOrWhiteSpace(((string)poliza.Propietario.Nombre)?.Trim()) && (ObtenerTipoDocumentoTractoresAxa((string)poliza.Propietario.CIF) != bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo)) - { - listaDatosFaltantes.Add("poliza.propietario.nombre"); - } - if (string.IsNullOrWhiteSpace(((string)poliza.Propietario.CIF)?.Trim())) listaDatosFaltantes.Add("poliza.Propietario.CIF"); - } - } +// if (poliza.Propietario != null) +// { +// if (ObtenerTipoDocumentoTractoresAxa((string)poliza.Propietario.CIF) != bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo) +// { +// if (string.IsNullOrWhiteSpace(((string)pTractores.PropietarioSexo?.ToString()))) listaDatosFaltantes.Add("poliza.Tractores.PropietarioSexo"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.PropietarioApellido1)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.PropietarioApellido1"); +// } +// if (poliza.Propietario.idEntidad != poliza.Tomador.idEntidad) +// { +// if (string.IsNullOrWhiteSpace(((string)poliza.Propietario.Nombre)?.Trim()) && (ObtenerTipoDocumentoTractoresAxa((string)poliza.Propietario.CIF) != bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo)) +// { +// listaDatosFaltantes.Add("poliza.propietario.nombre"); +// } +// if (string.IsNullOrWhiteSpace(((string)poliza.Propietario.CIF)?.Trim())) listaDatosFaltantes.Add("poliza.Propietario.CIF"); +// } +// } - if (poliza.Conductor == null || poliza.Conductor.idEntidad == poliza.Tomador.idEntidad) - { - DateTime fechaPermiso = (DateTime)pTractores.FechaPermisoConduccion; - if (!(fechaPermiso > DateTime.MinValue && fechaPermiso < DateTime.MaxValue)) - { - listaDatosFaltantes.Add("poliza.Tractores.FechaPermisoConduccion"); - } - if (string.IsNullOrWhiteSpace(fechaPermiso.ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.Tractores.FechaPermisoConduccion"); - } - else - { - if (string.IsNullOrWhiteSpace(((string)pTractores.ConductorNombre)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.ConductorNombre"); - if (string.IsNullOrWhiteSpace(((string)pTractores.ConductorApellido1)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.ConductorApellido1"); - if (string.IsNullOrWhiteSpace(((DateTime)pTractores.ConductorFechaNacimiento).ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.Tractores.ConductorFechaNacimiento"); - if (string.IsNullOrWhiteSpace(((string)poliza.Conductor.CIF)?.Trim())) listaDatosFaltantes.Add("poliza.Conductor.CIF"); - if (string.IsNullOrWhiteSpace(((string)pTractores.ConductorSexo?.ToString()))) listaDatosFaltantes.Add("poliza.Tractores.ConductorSexo"); - if (string.IsNullOrWhiteSpace(((DateTime)pTractores.FechaPermisoConduccion).ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.Tractores.FechaPermisoConduccion"); - } +// if (poliza.Conductor == null || poliza.Conductor.idEntidad == poliza.Tomador.idEntidad) +// { +// DateTime fechaPermiso = (DateTime)pTractores.FechaPermisoConduccion; +// if (!(fechaPermiso > DateTime.MinValue && fechaPermiso < DateTime.MaxValue)) +// { +// listaDatosFaltantes.Add("poliza.Tractores.FechaPermisoConduccion"); +// } +// if (string.IsNullOrWhiteSpace(fechaPermiso.ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.Tractores.FechaPermisoConduccion"); +// } +// else +// { +// if (string.IsNullOrWhiteSpace(((string)pTractores.ConductorNombre)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.ConductorNombre"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.ConductorApellido1)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.ConductorApellido1"); +// if (string.IsNullOrWhiteSpace(((DateTime)pTractores.ConductorFechaNacimiento).ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.Tractores.ConductorFechaNacimiento"); +// if (string.IsNullOrWhiteSpace(((string)poliza.Conductor.CIF)?.Trim())) listaDatosFaltantes.Add("poliza.Conductor.CIF"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.ConductorSexo?.ToString()))) listaDatosFaltantes.Add("poliza.Tractores.ConductorSexo"); +// if (string.IsNullOrWhiteSpace(((DateTime)pTractores.FechaPermisoConduccion).ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.Tractores.FechaPermisoConduccion"); +// } - if (string.IsNullOrWhiteSpace(((string)pTractores.UsoVehiculo)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.UsoVehiculo"); - if (string.IsNullOrWhiteSpace(((string)pTractores.Peso?.ToString())?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.Peso"); - if (string.IsNullOrWhiteSpace(((string)pTractores.Marca)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.Marca"); - if (string.IsNullOrWhiteSpace(((string)pTractores.Modelo)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.Modelo"); - if (string.IsNullOrWhiteSpace(((string)pTractores.Version)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.Version"); - if (string.IsNullOrWhiteSpace(poliza.Matricula?.ToUpper().Trim())) listaDatosFaltantes.Add("poliza.Matricula"); - if (string.IsNullOrWhiteSpace(((DateTime)pTractores.FechaPrimeraMatriculacion).ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.Tractores.FechaPrimeraMatriculacion"); - if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorCodigoPostal)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorCodigoPostal"); - if (string.IsNullOrWhiteSpace(((string)pTractores.CombinacionAccidentes)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.CombinacionAccidentes"); - if (string.IsNullOrWhiteSpace(((string)pTractores.PrimaTotal)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.PrimaTotal"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.UsoVehiculo)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.UsoVehiculo"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.Peso?.ToString())?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.Peso"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.Marca)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.Marca"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.Modelo)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.Modelo"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.Version)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.Version"); +// if (string.IsNullOrWhiteSpace(poliza.Matricula?.ToUpper().Trim())) listaDatosFaltantes.Add("poliza.Matricula"); +// if (string.IsNullOrWhiteSpace(((DateTime)pTractores.FechaPrimeraMatriculacion).ToString("ddMMyyyy"))) listaDatosFaltantes.Add("poliza.Tractores.FechaPrimeraMatriculacion"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.TomadorCodigoPostal)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.TomadorCodigoPostal"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.CombinacionAccidentes)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.CombinacionAccidentes"); +// if (string.IsNullOrWhiteSpace(((string)pTractores.PrimaTotal)?.Trim())) listaDatosFaltantes.Add("poliza.Tractores.PrimaTotal"); - if (listaDatosFaltantes.Count > 0) - { - var sbDatosFaltantes = new StringBuilder(); - foreach (var l in listaDatosFaltantes) - { - sbDatosFaltantes.AppendFormat("{0}, ", l); - } - throw new Exception($"No se puede componer esta línea del CSV porque faltan datos en la póliza idPoliza = {poliza.idPoliza}; Lista de datos faltantes: {sbDatosFaltantes.ToString().TrimEnd(',', ' ')}"); - } +// if (listaDatosFaltantes.Count > 0) +// { +// var sbDatosFaltantes = new StringBuilder(); +// foreach (var l in listaDatosFaltantes) +// { +// sbDatosFaltantes.AppendFormat("{0}, ", l); +// } +// throw new Exception($"No se puede componer esta línea del CSV porque faltan datos en la póliza idPoliza = {poliza.idPoliza}; Lista de datos faltantes: {sbDatosFaltantes.ToString().TrimEnd(',', ' ')}"); +// } - sb.AppendFormat("{0};", ((string)pTractores.TipoVehiculo).Trim()); - sb.AppendFormat("=\"{0}\";", "001"); - sb.AppendFormat("=\"{0}\";", "001"); - sb.AppendFormat("{0};", "674392"); - sb.AppendFormat("=\"{0}\";", (poliza.FechaEfecto).ToString("ddMMyyyy")); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", "8184"); - sb.AppendFormat("{0};", poliza.NumeroPoliza?.Trim()); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", "Anual Renovable"); - sb.AppendFormat("{0};", "Anual"); - sb.AppendFormat("{0};", "Mediador"); - sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ((string)pTractores.TipoVehiculo).Trim()); +// sb.AppendFormat("=\"{0}\";", "001"); +// sb.AppendFormat("=\"{0}\";", "001"); +// sb.AppendFormat("{0};", "674392"); +// sb.AppendFormat("=\"{0}\";", (poliza.FechaEfecto).ToString("ddMMyyyy")); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", "8184"); +// sb.AppendFormat("{0};", poliza.NumeroPoliza?.Trim()); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", "Anual Renovable"); +// sb.AppendFormat("{0};", "Anual"); +// sb.AppendFormat("{0};", "Mediador"); +// sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ObtenerTipoDocumentoTractoresAxa((string)poliza.Tomador.CIF)); - sb.AppendFormat("{0};", ((string)poliza.Tomador.CIF).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.TomadorApellido1)?.Trim()); - sb.AppendFormat("{0};", ((string)pTractores.TomadorApellido2)?.Trim()); - sb.AppendFormat("{0};", ((string)pTractores.TomadorNombre)?.Trim()); - sb.AppendFormat("=\"{0}\";", ((DateTime)pTractores.TomadorFechaNacimiento).ToString("ddMMyyyy")); - sb.AppendFormat("{0};", ((string)pTractores.EstadoCivil).Trim()); +// sb.AppendFormat("{0};", ObtenerTipoDocumentoTractoresAxa((string)poliza.Tomador.CIF)); +// sb.AppendFormat("{0};", ((string)poliza.Tomador.CIF).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.TomadorApellido1)?.Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.TomadorApellido2)?.Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.TomadorNombre)?.Trim()); +// sb.AppendFormat("=\"{0}\";", ((DateTime)pTractores.TomadorFechaNacimiento).ToString("ddMMyyyy")); +// sb.AppendFormat("{0};", ((string)pTractores.EstadoCivil).Trim()); - if (ObtenerTipoDocumentoTractoresAxa((string)poliza.Tomador.CIF) == bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo) - { - sb.AppendFormat("{0};", bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.sexo.SinInformar").ValorAlfabetico1); - } - else - { - sb.AppendFormat("{0};", ObtenerSexoTractoresAxa(((object)pTractores.TomadorSexo)?.ToString(), bd)); - } +// if (ObtenerTipoDocumentoTractoresAxa((string)poliza.Tomador.CIF) == bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo) +// { +// sb.AppendFormat("{0};", bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.sexo.SinInformar").ValorAlfabetico1); +// } +// else +// { +// sb.AppendFormat("{0};", ObtenerSexoTractoresAxa(((object)pTractores.TomadorSexo)?.ToString(), bd)); +// } - sb.AppendFormat("{0};", ((string)pTractores.TomadorCodigoPostal).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.TomadorPoblacion).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.TomadorVia).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.TomadorNombreVia).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.TomadorNumeroVia).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.TomadorRestoVia)?.Trim() ?? ""); +// sb.AppendFormat("{0};", ((string)pTractores.TomadorCodigoPostal).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.TomadorPoblacion).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.TomadorVia).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.TomadorNombreVia).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.TomadorNumeroVia).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.TomadorRestoVia)?.Trim() ?? ""); - if (poliza.Propietario == null || poliza.Propietario.idEntidad == poliza.Tomador.idEntidad) - { - sb.AppendFormat("{0};", "El Tomador"); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - } - else - { - if (ObtenerTipoDocumentoTractoresAxa((string)poliza.Propietario.CIF) != bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo) - { - sb.AppendFormat("{0};", "Otra persona distinta del Tomador"); - sb.AppendFormat("{0};", ((string)poliza.Propietario.Nombre).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.PropietarioApellido1).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.PropietarioApellido2)?.Trim() ?? ""); - sb.AppendFormat("{0};", ((string)poliza.Propietario.CIF).Trim()); - } - else - { - sb.AppendFormat("{0};", "Otra persona distinta del Tomador"); - sb.AppendFormat("{0};", ((string)poliza.Propietario.Nombre).Trim()); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ((string)poliza.Propietario.CIF).Trim()); - } - } +// if (poliza.Propietario == null || poliza.Propietario.idEntidad == poliza.Tomador.idEntidad) +// { +// sb.AppendFormat("{0};", "El Tomador"); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// } +// else +// { +// if (ObtenerTipoDocumentoTractoresAxa((string)poliza.Propietario.CIF) != bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.tipoDoc.PersJuridicaCIF").ValorAlfabeticoLargo) +// { +// sb.AppendFormat("{0};", "Otra persona distinta del Tomador"); +// sb.AppendFormat("{0};", ((string)poliza.Propietario.Nombre).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.PropietarioApellido1).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.PropietarioApellido2)?.Trim() ?? ""); +// sb.AppendFormat("{0};", ((string)poliza.Propietario.CIF).Trim()); +// } +// else +// { +// sb.AppendFormat("{0};", "Otra persona distinta del Tomador"); +// sb.AppendFormat("{0};", ((string)poliza.Propietario.Nombre).Trim()); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ((string)poliza.Propietario.CIF).Trim()); +// } +// } - if (poliza.Conductor== null || poliza.Conductor.idEntidad == poliza.Tomador.idEntidad) - { - sb.AppendFormat("{0};", "El Tomador"); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("=\"{0}\";", ((DateTime)pTractores.FechaPermisoConduccion).ToString("ddMMyyyy")); - } - else - { - sb.AppendFormat("{0};", "Es otra persona"); - sb.AppendFormat("{0};", ((string)pTractores.ConductorNombre).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.ConductorApellido1).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.ConductorApellido2)?.Trim() ?? ""); - sb.AppendFormat("=\"{0}\";", ((DateTime)pTractores.ConductorFechaNacimiento).ToString("ddMMyyyy")); - sb.AppendFormat("{0};", ObtenerTipoDocumentoTractoresAxa((string)poliza.Conductor.CIF)); - sb.AppendFormat("{0};", ((string)poliza.Conductor.CIF).Trim()); - sb.AppendFormat("{0};", ObtenerSexoTractoresAxa(((object)pTractores.ConductorSexo)?.ToString(), bd)); - sb.AppendFormat("=\"{0}\";", ((DateTime)pTractores.FechaPermisoConduccion).ToString("ddMMyyyy")); - } +// if (poliza.Conductor== null || poliza.Conductor.idEntidad == poliza.Tomador.idEntidad) +// { +// sb.AppendFormat("{0};", "El Tomador"); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("=\"{0}\";", ((DateTime)pTractores.FechaPermisoConduccion).ToString("ddMMyyyy")); +// } +// else +// { +// sb.AppendFormat("{0};", "Es otra persona"); +// sb.AppendFormat("{0};", ((string)pTractores.ConductorNombre).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.ConductorApellido1).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.ConductorApellido2)?.Trim() ?? ""); +// sb.AppendFormat("=\"{0}\";", ((DateTime)pTractores.ConductorFechaNacimiento).ToString("ddMMyyyy")); +// sb.AppendFormat("{0};", ObtenerTipoDocumentoTractoresAxa((string)poliza.Conductor.CIF)); +// sb.AppendFormat("{0};", ((string)poliza.Conductor.CIF).Trim()); +// sb.AppendFormat("{0};", ObtenerSexoTractoresAxa(((object)pTractores.ConductorSexo)?.ToString(), bd)); +// sb.AppendFormat("=\"{0}\";", ((DateTime)pTractores.FechaPermisoConduccion).ToString("ddMMyyyy")); +// } - sb.AppendFormat("{0};", "No se declara"); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", "No se declara"); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", "No se declara"); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", "No se declara"); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", "No"); - sb.AppendFormat("{0};", ((string)pTractores.UsoVehiculo).Trim()); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ((object)pTractores.Peso).ToString().Trim()); - sb.AppendFormat("{0};", ((string)pTractores.Marca).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.Modelo).Trim()); - sb.AppendFormat("{0};", ((string)pTractores.Version).Trim()); - sb.AppendFormat("{0};", "35.000"); - sb.AppendFormat("=\"{0}\";", "0,00"); - sb.AppendFormat("{0};", poliza.Matricula.ToUpper().Trim()); - sb.AppendFormat("=\"{0}\";", ((DateTime)pTractores.FechaPrimeraMatriculacion).ToString("ddMMyyyy")); - sb.AppendFormat("=\"{0}\";", ((string)pTractores.TomadorCodigoPostal).Trim()); - sb.AppendFormat("{0};", "NO"); - sb.AppendFormat("{0};", "NO"); - sb.AppendFormat("{0};", "Sin definir"); - sb.AppendFormat("{0};", "Terceros sin Asistencia"); - sb.AppendFormat("{0};", ((string)pTractores.CombinacionAccidentes).Trim()); - sb.AppendFormat("{0};", "Si"); - sb.AppendFormat("{0};", ((string)pTractores.PrimaTotal).Trim()); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0};", ""); - sb.AppendFormat("{0}", ""); +// sb.AppendFormat("{0};", "No"); +// sb.AppendFormat("{0};", ((string)pTractores.UsoVehiculo).Trim()); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ((object)pTractores.Peso).ToString().Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.Marca).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.Modelo).Trim()); +// sb.AppendFormat("{0};", ((string)pTractores.Version).Trim()); +// sb.AppendFormat("{0};", "35.000"); +// sb.AppendFormat("=\"{0}\";", "0,00"); +// sb.AppendFormat("{0};", poliza.Matricula.ToUpper().Trim()); +// sb.AppendFormat("=\"{0}\";", ((DateTime)pTractores.FechaPrimeraMatriculacion).ToString("ddMMyyyy")); +// sb.AppendFormat("=\"{0}\";", ((string)pTractores.TomadorCodigoPostal).Trim()); +// sb.AppendFormat("{0};", "NO"); +// sb.AppendFormat("{0};", "NO"); +// sb.AppendFormat("{0};", "Sin definir"); +// sb.AppendFormat("{0};", "Terceros sin Asistencia"); +// sb.AppendFormat("{0};", ((string)pTractores.CombinacionAccidentes).Trim()); +// sb.AppendFormat("{0};", "Si"); +// sb.AppendFormat("{0};", ((string)pTractores.PrimaTotal).Trim()); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0};", ""); +// sb.AppendFormat("{0}", ""); - } - catch (Exception ex) - { - throw new Exception(ex.Message, ex); - } - return sb.ToString(); - } +// } +// catch (Exception ex) +// { +// throw new Exception(ex.Message, ex); +// } +// return sb.ToString(); +// } - public static int PrepararCorreosCsvTractoresAxa(tscgestionasegasa bd) - { - const bool danmundebug = false; - int resultadoGuardarCambios = 0; - try - { - DateTime dHoy = DateTime.Today; - DateTime dAyer = DateTime.Today.AddDays(-1); - int idTipoGestionPoliza = bd.enumeraciones.First(x => x.Codigo == "TGP.CSVAXA").idEnumeracion; - int idTipoFicheroCSV = bd.enumeraciones.First(x => x.Codigo == "TIPFIC.CSVAXA").idEnumeracion; +// public static int PrepararCorreosCsvTractoresAxa(tscgestionasegasa bd) +// { +// const bool danmundebug = false; +// int resultadoGuardarCambios = 0; +// try +// { +// DateTime dHoy = DateTime.Today; +// DateTime dAyer = DateTime.Today.AddDays(-1); +// int idTipoGestionPoliza = bd.enumeraciones.First(x => x.Codigo == "TGP.CSVAXA").idEnumeracion; +// int idTipoFicheroCSV = bd.enumeraciones.First(x => x.Codigo == "TIPFIC.CSVAXA").idEnumeracion; - var lineasPendientesCorreoCsv = bd.gestionesvarias - .Where(x => x.idTipo == idTipoGestionPoliza && !x.FechaProcesado.HasValue) - .ToList(); +// var lineasPendientesCorreoCsv = bd.gestionesvarias +// .Where(x => x.idTipo == idTipoGestionPoliza && !x.FechaProcesado.HasValue) +// .ToList(); - foreach (var linea in lineasPendientesCorreoCsv) - { - var listaDestinatarios = bd.enumeraciones - .Where(x => x.Codigo.StartsWith("AXATRACTORES.email.destinatario")) - .Select(x => x.ValorAlfabeticoLargo.Trim()) - .ToList(); +// foreach (var linea in lineasPendientesCorreoCsv) +// { +// var listaDestinatarios = bd.enumeraciones +// .Where(x => x.Codigo.StartsWith("AXATRACTORES.email.destinatario")) +// .Select(x => x.ValorAlfabeticoLargo.Trim()) +// .ToList(); - string asunto = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.email.asunto").ValorAlfabeticoLargo.Trim()} {linea.idFicheroNavigation?.Descripcion?.Split(' ').Last()}"; - string cuerpo = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.email.cuerpo").ValorAlfabeticoLargo.Trim()} {linea.idFicheroNavigation?.Descripcion?.Split(' ').Last()}"; +// string asunto = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.email.asunto").ValorAlfabeticoLargo.Trim()} {linea.idFicheroNavigation?.Descripcion?.Split(' ').Last()}"; +// string cuerpo = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.email.cuerpo").ValorAlfabeticoLargo.Trim()} {linea.idFicheroNavigation?.Descripcion?.Split(' ').Last()}"; - var cuentaCorreo = bd.cuentascorreo.First(x => x.Codigo == "CSVAXA"); +// var cuentaCorreo = bd.cuentascorreo.First(x => x.Codigo == "CSVAXA"); - foreach (var destinatario in listaDestinatarios) - { - // Use GeneraRegistroCorreo using the proper signature defined in bdAsegasa - // The VB is calling `bdGestionAsegasa.correos.GeneraRegistroCorreo(bd, asunto, cuerpo, cuentaCorreo, destinatario,,, linea.idFichero)`. - bdAsegasa.db.correos.GeneraRegistroCorreo(bd, asunto, cuerpo, cuentaCorreo, destinatario, null, null, linea.idFichero); - } +// foreach (var destinatario in listaDestinatarios) +// { +// // Use GeneraRegistroCorreo using the proper signature defined in bdAsegasa +// // The VB is calling `bdGestionAsegasa.correos.GeneraRegistroCorreo(bd, asunto, cuerpo, cuentaCorreo, destinatario,,, linea.idFichero)`. +// bdAsegasa.db.correos.GeneraRegistroCorreo(bd, asunto, cuerpo, cuentaCorreo, destinatario, null, null, linea.idFichero); +// } - linea.FechaProcesado = DateTime.Now; - if (!danmundebug) resultadoGuardarCambios += bd.SaveChanges(); +// linea.FechaProcesado = DateTime.Now; +// if (!danmundebug) resultadoGuardarCambios += bd.SaveChanges(); - if (resultadoGuardarCambios > 0) - { - try - { - var mensaje = new StringBuilder(); - mensaje.AppendFormat("Se ha generado un email para AXA conteniendo el archivo CSV con altas de tractores y/o remolques para AXA.```Asunto: {1}{0}Servidor: {2}```", - Environment.NewLine, asunto, Environment.MachineName); - } - catch { } - } - } - } - catch (Exception ex) - { - Debug.WriteLine("No hay líneas o se produjo excepción."); - _ = tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En {System.Reflection.MethodBase.GetCurrentMethod()}", - $"En método {System.Reflection.MethodBase.GetCurrentMethod()}. {Environment.MachineName} {ex.ToString()}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); - } - return resultadoGuardarCambios; - } +// if (resultadoGuardarCambios > 0) +// { +// try +// { +// var mensaje = new StringBuilder(); +// mensaje.AppendFormat("Se ha generado un email para AXA conteniendo el archivo CSV con altas de tractores y/o remolques para AXA.```Asunto: {1}{0}Servidor: {2}```", +// Environment.NewLine, asunto, Environment.MachineName); +// } +// catch { } +// } +// } +// } +// catch (Exception ex) +// { +// Debug.WriteLine("No hay líneas o se produjo excepción."); +// _ = tsUtilidades.TsNotificacionesClient.RegistrarAsync($"En {System.Reflection.MethodBase.GetCurrentMethod()}", +// $"En método {System.Reflection.MethodBase.GetCurrentMethod()}. {Environment.MachineName} {ex.ToString()}", tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR); +// } +// return resultadoGuardarCambios; +// } - public static bool YaSeEnvioCsvParaAyer(tscgestionasegasa bd) - { - int idTipoGestionPoliza = bd.enumeraciones.First(x => x.Codigo == "TGP.CSVAXA").idEnumeracion; - DateTime dAyer = DateTime.Today.AddDays(-1); - string sDescripcion = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.NombreFicheroCSV").ValorAlfabeticoLargo}{dAyer:yyyy-MM-dd}.csv"; +// public static bool YaSeEnvioCsvParaAyer(tscgestionasegasa bd) +// { +// int idTipoGestionPoliza = bd.enumeraciones.First(x => x.Codigo == "TGP.CSVAXA").idEnumeracion; +// DateTime dAyer = DateTime.Today.AddDays(-1); +// string sDescripcion = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.NombreFicheroCSV").ValorAlfabeticoLargo}{dAyer:yyyy-MM-dd}.csv"; - return bd.gestionesvarias.Any(x => x.idTipo == idTipoGestionPoliza && x.FechaProcesado.HasValue && x.Descripción == sDescripcion); - } +// return bd.gestionesvarias.Any(x => x.idTipo == idTipoGestionPoliza && x.FechaProcesado.HasValue && x.Descripción == sDescripcion); +// } - public static bool YaSeEnvioCsvParaHoy(tscgestionasegasa bd) - { - int idTipoGestionPoliza = bd.enumeraciones.First(x => x.Codigo == "TGP.CSVAXA").idEnumeracion; - string sDescripcion = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.NombreFicheroCSV").ValorAlfabeticoLargo}{DateTime.Today:yyyy-MM-dd}.csv"; +// public static bool YaSeEnvioCsvParaHoy(tscgestionasegasa bd) +// { +// int idTipoGestionPoliza = bd.enumeraciones.First(x => x.Codigo == "TGP.CSVAXA").idEnumeracion; +// string sDescripcion = $"{bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.NombreFicheroCSV").ValorAlfabeticoLargo}{DateTime.Today:yyyy-MM-dd}.csv"; - return bd.gestionesvarias.Any(x => x.idTipo == idTipoGestionPoliza && x.FechaProcesado.HasValue && x.Descripción == sDescripcion); - } +// return bd.gestionesvarias.Any(x => x.idTipo == idTipoGestionPoliza && x.FechaProcesado.HasValue && x.Descripción == sDescripcion); +// } - public static int NumeroDeLineasEnElArchivoCSV(string rutaArchivoCSV) - { - return File.ReadLines(rutaArchivoCSV).Count(); - } +// public static int NumeroDeLineasEnElArchivoCSV(string rutaArchivoCSV) +// { +// return File.ReadLines(rutaArchivoCSV).Count(); +// } - private static int ComprobarCuantosNumerosReservadosQuedanDisponibles(int nActual, enumeraciones inicio, enumeraciones fin) - { +// private static int ComprobarCuantosNumerosReservadosQuedanDisponibles(int nActual, enumeraciones inicio, enumeraciones fin) +// { - if(fin.ValorNumerico1 != null) - { +// if(fin.ValorNumerico1 != null) +// { - } - return (int)(fin.ValorNumerico1 ?? 0) - nActual; - } +// } +// return (int)(fin.ValorNumerico1 ?? 0) - nActual; +// } - private static string ObtenerTipoDocumentoTractoresAxa(string numeroDocumento) - { - // Assuming string extension TipoDocumentoIdentidad mapped inside C# as tsUtilidades.Mobiles.Validaciones.ObtenerTipo(numeroDocumento) - // The enum `tsl5.ValidarDocumentoIdentidad.TiposDocumentosEnum.CIF` translates to some util module enum. - // Simplified CIF check based on letter if no tsUtilidades available, but we use the library. - // If it starts with typical CIF letters A B C D E F G H J N P Q R S U V W - var initChar = char.ToUpperInvariant(numeroDocumento.FirstOrDefault()); - string cifLetters = "ABCDEFGHJNPQRSUVW"; - if (cifLetters.Contains(initChar)) - { - return "CIF"; - } - return "NIF"; - } +// private static string ObtenerTipoDocumentoTractoresAxa(string numeroDocumento) +// { +// // Assuming string extension TipoDocumentoIdentidad mapped inside C# as tsUtilidades.Mobiles.Validaciones.ObtenerTipo(numeroDocumento) +// // The enum `tsl5.ValidarDocumentoIdentidad.TiposDocumentosEnum.CIF` translates to some util module enum. +// // Simplified CIF check based on letter if no tsUtilidades available, but we use the library. +// // If it starts with typical CIF letters A B C D E F G H J N P Q R S U V W +// var initChar = char.ToUpperInvariant(numeroDocumento.FirstOrDefault()); +// string cifLetters = "ABCDEFGHJNPQRSUVW"; +// if (cifLetters.Contains(initChar)) +// { +// return "CIF"; +// } +// return "NIF"; +// } - private static string ObtenerSexoTractoresAxa(string cadenaSexo, tscgestionasegasa bd) - { - string resultado = bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.sexo.SinInformar").ValorAlfabetico1; - string axaHombre = bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.sexo.Hombre").ValorAlfabetico1; - string axaMujer = bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.sexo.Mujer").ValorAlfabetico1; +// private static string ObtenerSexoTractoresAxa(string cadenaSexo, tscgestionasegasa bd) +// { +// string resultado = bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.sexo.SinInformar").ValorAlfabetico1; +// string axaHombre = bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.sexo.Hombre").ValorAlfabetico1; +// string axaMujer = bd.enumeraciones.First(x => x.Codigo == "AXATRACTORES.sexo.Mujer").ValorAlfabetico1; - string idEnumSexoHombre = bd.enumeraciones.First(x => x.Codigo == "SEXO.HOMBRE").idEnumeracion.ToString(); - string idEnumSexoMujer = bd.enumeraciones.First(x => x.Codigo == "SEXO.MUJER").idEnumeracion.ToString(); +// string idEnumSexoHombre = bd.enumeraciones.First(x => x.Codigo == "SEXO.HOMBRE").idEnumeracion.ToString(); +// string idEnumSexoMujer = bd.enumeraciones.First(x => x.Codigo == "SEXO.MUJER").idEnumeracion.ToString(); - if (cadenaSexo == idEnumSexoHombre) resultado = axaHombre; - if (cadenaSexo == idEnumSexoMujer) resultado = axaMujer; +// if (cadenaSexo == idEnumSexoHombre) resultado = axaHombre; +// if (cadenaSexo == idEnumSexoMujer) resultado = axaMujer; - return resultado; - } - } -} +// return resultado; +// } +// } +//} diff --git a/Servicio Gestion Asegasa/ProcesosConf.cs b/Servicio Gestion Asegasa/ProcesosConf.cs new file mode 100644 index 0000000..da5c8d4 --- /dev/null +++ b/Servicio Gestion Asegasa/ProcesosConf.cs @@ -0,0 +1,43 @@ +using Servicio_Gestion_Asegasa.Procesos; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace Servicio_Gestion_Asegasa +{ + public class ProcesosConf + { + public static Configuracion Conf; + + public static DateTime? HoraUtcUltimaEjecucionProcesos = null; + private static bool Procesando; + + public static async Task ProcesarAsync() + { + if (!Procesando && (HoraUtcUltimaEjecucionProcesos.HasValue == false || DateTime.UtcNow.Subtract(HoraUtcUltimaEjecucionProcesos.Value).TotalSeconds > Conf.SegundosMinimosEntreProcesos)) + { + Procesando = true; + HoraUtcUltimaEjecucionProcesos = DateTime.UtcNow; + try + { + await ProcesosMensajes.EnviaSMSAsync(); + + } + catch (Exception ex) + { + + Debug.WriteLine(@"Procesar: EXCEPCIÓN: " + ex.Message + " " + ex.StackTrace); + } + finally + { + Procesando = false; + } + + } + + } + } +} diff --git a/Servicio Gestion Asegasa/Servicio Gestion Asegasa.csproj b/Servicio Gestion Asegasa/Servicio Gestion Asegasa.csproj index dabdbf1..620c4a3 100644 --- a/Servicio Gestion Asegasa/Servicio Gestion Asegasa.csproj +++ b/Servicio Gestion Asegasa/Servicio Gestion Asegasa.csproj @@ -10,6 +10,9 @@ + + + diff --git a/Servicio Gestion Asegasa/Worker.cs b/Servicio Gestion Asegasa/Worker.cs index e42f57e..7e84643 100644 --- a/Servicio Gestion Asegasa/Worker.cs +++ b/Servicio Gestion Asegasa/Worker.cs @@ -1,6 +1,12 @@ +using bdAsegasa; using bdAsegasa.db; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Metadata.Builders; +using Quartz; +using Quartz.Impl; using Servicio_Gestion_Asegasa.Procesos; using System.Reflection; +using System.Reflection.Metadata; namespace Servicio_Gestion_Asegasa { @@ -8,24 +14,96 @@ namespace Servicio_Gestion_Asegasa { private readonly ILogger _logger; - public Worker(ILogger logger) + public Worker(ILogger logger, Configuracion Conf) { _logger = logger; + ProcesosConf.Conf = Conf; } + + protected override async Task ExecuteAsync(CancellationToken stoppingToken) { - // await ProcesosMensajes.EnviaSMSAsync(); + string Mensaje = "Servicio Gestion Asegasa. Versin: " + tsUtilidades.Utilidades.ExtraeValorCadena(Assembly.GetExecutingAssembly().FullName, "Version"); + try + { + + if (ProcesosConf.Conf.HoraProcesosDiarios != null) + { + Mensaje += " Hora Procesos Programados: " + ProcesosConf.Conf.HoraProcesosDiarios; + CreaTareaProcesosDiarios(); + } + + await Logs.AadeLogAsync(tsUtilidades.Enumeraciones.TipoLog.InicioServicio, "Inicio " + Mensaje); while (!stoppingToken.IsCancellationRequested) - { - if (_logger.IsEnabled(LogLevel.Information)) { - _logger.LogInformation("Worker running at: {time}", DateTimeOffset.Now); + if (_logger.IsEnabled(LogLevel.Information)) + { + _logger.LogInformation("Servicio en ejecucin: {time}", DateTimeOffset.Now); + //Creo q aqui se deberia llamar a los servicios + } + await ProcesosConf.ProcesarAsync(); + await System.Threading.Tasks.Task.Delay(1000 * 60 * 5, stoppingToken); } - await Task.Delay(1000, stoppingToken); } + catch (OperationCanceledException) + { + // Logs.AadeLog(tsUtilidades.Enumeraciones.TipoLog.FinServicio, "Detencin " + Mensaje); + // When the stopping token is canceled, for example, a call made from services.msc, + // we shouldn't exit with a non-zero exit code. In other words, this is expected... + } + catch (Exception ex) + { + _logger.LogError(ex, "{Message}", ex.Message); + Environment.Exit(1); + } + + } + + + + private void CreaTareaProcesosDiarios() + { + ISchedulerFactory schedulerFactory = new StdSchedulerFactory(); + IScheduler scheduler = schedulerFactory.GetScheduler().Result; + scheduler.Start().Wait(); + // Crear un trabajo + IJobDetail job = JobBuilder.Create() + .WithIdentity("TareasProgramadas", "Grupo1") + .Build(); + // Crear un trigger que se ejecute diariamente a una hora especfica + + + int Hora = int.Parse(ProcesosConf.Conf.HoraProcesosDiarios.Split(":")[0]); + int Minutos = int.Parse(ProcesosConf.Conf.HoraProcesosDiarios.Split(":")[1]); + Quartz.ITrigger trigger = Quartz.TriggerBuilder.Create() + .WithIdentity("TareasProgramadas", "Grupo1") + .StartAt(DateBuilder.TodayAt(Hora, Minutos, 0)) + .WithSimpleSchedule(x => x + .WithIntervalInHours(24) + .RepeatForever()) + .Build(); + + // Programar el trabajo con el trigger + scheduler.ScheduleJob(job, trigger).Wait(); + } + + } + + + public class TareasProgramadas : IJob + { + public Task Execute(IJobExecutionContext context) + { + //var ch = bdTecnosis.db.chequeos; + // var bd = bdTecnosis.tscTecnosis.NuevoContexto(); + //var c = bd.chequeos.FirstOrDefault(x => x.idChequeo == ch.idChequeo); + //Comprobaciones.ChequeaColaCorreo(bd,c); + //Comprobaciones.CompruebaReplica(); + //Aqui van los procesos y comprobaciones + return Task.CompletedTask; } } } diff --git a/Servicio Gestion Asegasa/appsettings.json b/Servicio Gestion Asegasa/appsettings.json index cc5729f..7968cb6 100644 --- a/Servicio Gestion Asegasa/appsettings.json +++ b/Servicio Gestion Asegasa/appsettings.json @@ -1,14 +1,19 @@ { + "Configuracion": { + "SegundosMinimosEntreProcesos": "60", + "HoraProcesosDiarios": "06:30", + "NombreConexionBD": "Producción Remoto" + }, "Logging": { "LogLevel": { "Default": "Information", "Microsoft.Hosting.Lifetime": "Information" } }, - "TsNotificaciones": { - //"ApiUrl": "http://192.168.41.32:5000/", prod - "ApiUrl": "https://catcher.tecnosis.online", - "IdAplicacion": 2, - "ApiKey": "0a47a1eada0143278b9d4de4e8911100" - } + "TsNotificaciones": { + //"ApiUrl": "http://192.168.41.32:5000/", prod + "ApiUrl": "https://catcher.tecnosis.online", + "IdAplicacion": 2, + "ApiKey": "0a47a1eada0143278b9d4de4e8911100" } +}