Files
Asegasa.NET/bdAsegasa/Utilidades.cs
2026-04-28 11:52:16 +02:00

724 lines
37 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using bdAsegasa.dbcontext;
using Microsoft.VisualBasic;
namespace bdAsegasa.db
{
public class Utilidades
{
public static string Usuario;
public static int idUsuario;
public static usuarios UsuarioActual;
public static string VersionPrograma { get; set; }
public static EventLog el;
public static string DirectorioLogs;
private static object oBloqueoLog = new object();
public static bool CorreoLogsHabilitado = true;
public static bool tsNotificacionesHabilitado = true;
public static DateOnly FechaActualDateOnly()
{
DateOnly hoy = new DateOnly(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
return hoy;
}
public static async Task EnviaAlertaExcepcion(string Titulo, string Mensaje, byte[] FicheroImagen = null)
{
try
{
await tsUtilidades.TsNotificacionesClient.RegistrarAsync(Titulo, Mensaje, tsUtilidades.TsNotificacionesClient.TipoNotificacionEnum.ERROR);
}
catch (Exception Exc)
{
throw new Exception(Exc.Message, Exc);
}
}
public static async void AñadeLog(tsUtilidades.Enumeraciones.TipoLog Tipo, string Asunto, 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:
// ===============
string sFicheroLog = DirectorioLogs + "Log-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + ".txt";
try
{
// if (!(e == null))
if (e != null) //davrod
{
if (el is not null)
el.WriteEntry(e.Message + Constants.vbCrLf + e.StackTrace, EventLogEntryType.Error);
string sStackTrace = "Tipo excepción: " + e.ToString() + Constants.vbCrLf;
var exError = e;
do
{
sStackTrace += exError.StackTrace + Constants.vbCrLf;
exError = exError.InnerException;
}
while (exError != null);
if (!string.IsNullOrEmpty(sStackTrace))
Mensaje += Constants.vbCrLf + "StackTrace: " + sStackTrace;
Anadelogtxt(Mensaje + " --- " + e.StackTrace, sFicheroLog);
}
switch (Tipo)
{
case tsUtilidades.Enumeraciones.TipoLog.Fallo:
case tsUtilidades.Enumeraciones.TipoLog.Advertencia:
{
if (Tipo == tsUtilidades.Enumeraciones.TipoLog.Fallo)
{
sFicheroLog = DirectorioLogs + "Errores-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + ".txt";
Mensaje = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + " Error enviado desde " + Environment.MachineName + " VERSION: " + VersionPrograma + ". " + Mensaje;
}
else
{
Mensaje = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss") + " Advertencia enviado desde " + Environment.MachineName + " VERSION: " + VersionPrograma + ". " + Mensaje;
}
string sDireccionesEnvio = "sevilla@tecnosis.net";
string sServidorSMTP = "mail.tecnosis.net";
string sRemitente = "logs@tecnosis.es";
if (Environment.MachineName.ToUpper().Trim() == "INTI" || Environment.MachineName.ToUpper().Trim() == "CERBERO")
{
sDireccionesEnvio = "danmun@tecnosis.net";
Asunto = "[`" + Environment.MachineName.Trim() + "`] " + Asunto;
}
bool FuerzaCorreo = false;
if (tsNotificacionesHabilitado)
{
try
{
await EnviaAlertaExcepcion(Asunto, Mensaje);
}
catch (Exception ex1)
{
FuerzaCorreo = true;
string sStackTrace2 = "Tipo excepción Alerta: " + ex1.ToString() + "\r\n";
var exError2 = ex1;
do
{
sStackTrace2 += exError2.StackTrace + "\r\n";
exError2 = exError2.InnerException;
}
while (exError2 != null);
if (!string.IsNullOrEmpty(sStackTrace2))
Mensaje += "\r\nStackTrace: " + sStackTrace2;
}
}
else
{
FuerzaCorreo = true;
}
if (CorreoLogsHabilitado || FuerzaCorreo)
{
// Mantenemos los parámetros editados originariamente por #davrod (jtvdzklmujkechje y puerto 587)
tsUtilidades.Correo.Funciones.EnviaCorreo(sServidorSMTP, sRemitente, sDireccionesEnvio, Asunto, Mensaje, null, "", "", sRemitente, "jtvdzklmujkechje", 587, true);
}
break;
}
}
// Anadelogtxt(Mensaje + " --- " + e.StackTrace, sFicheroLog);
}
catch (Exception ex)
{
sFicheroLog = DirectorioLogs + @"Errores\Errores-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString().PadLeft(2, '0') + ".txt";
if (e is not null)
Mensaje += " --- " + e.StackTrace;
Anadelogtxt(Mensaje + " ---" + ex.Message + " --- " + ex.StackTrace, sFicheroLog);
}
}
public static void Anadelogtxt(string Mensaje, string FicheroLog)
{
System.IO.StreamWriter sw = null;
try
{
Mensaje = Mensaje.Replace(Constants.vbCrLf, "---");
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(FicheroLog)))
tsUtilidades.Utilidades.CreaEstructuraDirectorio(System.IO.Path.GetDirectoryName(FicheroLog));
if (System.IO.File.Exists(FicheroLog))
{
sw = System.IO.File.AppendText(FicheroLog);
}
else
{
sw = System.IO.File.CreateText(FicheroLog);
}
Mensaje = DateTime.Now.ToString() + "|" + "Ws: " + Process.GetCurrentProcess().WorkingSet64.ToString().PadLeft(20) + " PMS: " + Process.GetCurrentProcess().PrivateMemorySize64.ToString().PadLeft(20) + "|" + Mensaje;
sw.WriteLine(Mensaje);
}
catch (Exception ex)
{
try
{
string sDireccionesEnvio = "sevilla@tecnosis.net";
string sServidorSMTP = "mail.tecnosis.net";
string sRemitente = "logs@tecnosis.es";
// tsUtilidades.Correo.Funciones.EnviaCorreo(sServidorSMTP, sRemitente, sDireccionesEnvio, Asunto, Mensaje,,,,, "se9608dc.g")
tsUtilidades.Correo.Funciones.EnviaCorreo(sServidorSMTP, sRemitente, sDireccionesEnvio, "Error Anadelogtxt. " + Mensaje, Environment.MachineName + ".- " + ex.Message + Constants.vbCrLf + ex.StackTrace + Constants.vbCrLf + ex.Source, null, "", "", sRemitente, "jtvdzklmujkechje", 587, true); //Cambiar contraseña de logs -> LoGs20i9.
}
catch (Exception ex2)
{
}
}
finally
{
try
{
sw.Close();
}
catch
{
}
}
}
public static string NombreUsuario { get; set; }
public static tsUtilidades.Datos.DatosSesionCliente dsc = new tsUtilidades.Datos.DatosSesionCliente();
public static bool? EsRemoto = null;
private static string FicheroLog = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\Asegasa\GestionAsegasaLog.txt";
internal static int? idTippPE { get; set; }
internal static int? idTippBA { get; set; }
internal static int? idtrCx { get; set; }
internal static int? idtrEx { get; set; }
public static int? idSitr1 { get; set; }
private static void ActualizaConexion(tscgestionasegasa deGestionAsegasa)
{
try
{
int idMYSQL = Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.ExecuteSqlRaw(deGestionAsegasa.Database, "select connection_id() as id");
conexiones cn;
if (deGestionAsegasa.conexiones.Any(x => x.idMysql == idMYSQL))
{
cn = deGestionAsegasa.conexiones.First(x => x.idMysql == idMYSQL);
}
else
{
cn = new conexiones();
cn.idMysql = idMYSQL;
deGestionAsegasa.conexiones.Add(cn);
}
cn.ip = "unknown"; // Not selecting host here to simplify EF Core migration
if (deGestionAsegasa.usuarios.Any(x => x.Usuario == Usuario))
{
if (cn.Usuario != Usuario)
{
cn.Usuario = Usuario;
cn.FechaHora = AhoraMysql(deGestionAsegasa);
deGestionAsegasa.SaveChanges();
}
}
else
{
cn.Usuario = Usuario + " * NO ENCONTRADO *";
cn.FechaHora = AhoraMysql(deGestionAsegasa);
deGestionAsegasa.SaveChanges();
}
}
catch (Exception ex)
{
Debug.Write(ex.Message);
}
}
public static DateTime AhoraMysql(tscgestionasegasa deGestionAsegasa)
{
try
{
return DateTime.Now;
}
catch (Exception)
{
return DateTime.Now;
}
}
public static void AñadeLogNombre(string nombreLog, tsUtilidades.Enumeraciones.TipoLog Tipo, string Asunto, string Mensaje, bool forzarEnviarCorreoE = false, string forzarDestinatario = "", bool forzarEnviarSlack = false, Exception excepcion = null)
{
string sFicheroLog = DirectorioLogs + "Log-" + nombreLog + "-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + ".txt";
try
{
bool enviarCorreoE = false;
StringBuilder sbAsunto = new StringBuilder();
string sSeguimientoDePila = "";
sbAsunto.AppendFormat("[`{0}`] ", System.Diagnostics.Process.GetCurrentProcess().ProcessName);
sbAsunto.Append(Asunto);
if (excepcion != null)
{
if (el != null) el.WriteEntry(excepcion.Message + "\r\n" + excepcion.StackTrace, EventLogEntryType.Error);
}
Mensaje = sbAsunto.ToString() + "\r\n" + Mensaje + "\r\n";
if (Tipo == tsUtilidades.Enumeraciones.TipoLog.Fallo || Tipo == tsUtilidades.Enumeraciones.TipoLog.Advertencia) enviarCorreoE = true;
if (forzarEnviarCorreoE || excepcion != null) enviarCorreoE = true;
if (enviarCorreoE)
{
string sDireccionesEnvio = "sevilla@tecnosis.net";
string sServidorSMTP = "correo.tecnosis.net";
string sRemitente = "logs@tecnosis.es";
if (!string.IsNullOrWhiteSpace(forzarDestinatario)) sDireccionesEnvio = forzarDestinatario;
if (Environment.MachineName.ToUpper().Trim() == "INTI" || Environment.MachineName.ToUpper().Trim() == "CERBERO") sDireccionesEnvio = "danmun@tecnosis.net";
tsUtilidades.Correo.Funciones.EnviaCorreo(sServidorSMTP, sRemitente, sDireccionesEnvio, sbAsunto.ToString().Replace("`", ""), Mensaje.Replace("`", ""),null,null, "","", "logs@tecnosis.es","LoGs20i9.",25,false,false,"");
}
if (forzarEnviarSlack || Tipo == tsUtilidades.Enumeraciones.TipoLog.Fallo || Tipo == tsUtilidades.Enumeraciones.TipoLog.Advertencia || excepcion != null)
{
string destinoSlack = forzarEnviarSlack ? "Avant2" : "asegasa";
tsUtilidades.Utilidades.EnviarNotificacionSlack(Asunto, destinoSlack, System.Reflection.MethodBase.GetCurrentMethod().ToString());
}
Anadelogtxt(Mensaje, sFicheroLog);
}
catch (Exception ex)
{
Anadelogtxt(ex.Message, DirectorioLogs + "Errores-" + nombreLog + ".txt");
}
}
public static void AñadeLogNombreConFicheroTexto(string nombreLog, tsUtilidades.Enumeraciones.TipoLog Tipo, string descripcion, string nombreDelFichero, string textoDelFichero, bool forzarEnviarCorreoE = false, string forzarDestinatario = "", bool forzarEnviarSlack = false, Exception excepcion = null)
{
// Placeholder logic linking AñadeLogNombre
AñadeLogNombre(nombreLog, Tipo, descripcion, textoDelFichero, forzarEnviarCorreoE, forzarDestinatario, forzarEnviarSlack, excepcion);
}
public static async void GeneraRegistroCorreoExcepcion(Exception ex, string Rutina, bool MostrarMensajeError = false, byte[] FicheroImagen = null, string CabeceraAsunto = "")
{
bool FuerzaCorreo = false;
try
{
var bd = tscgestionasegasa.NuevoContexto();
string sMensaje = (CabeceraAsunto != "" ? CabeceraAsunto + " \r\n" : "") + "Usuario: " + Usuario + " Versión: " + VersionPrograma + "\r\n";
string sStackTrace = "Tipo excepción: " + ex.ToString() + "\r\n";
Exception exError = ex;
do
{
sStackTrace += exError.StackTrace + "\r\n";
exError = exError.InnerException;
} while (exError != null);
if (!string.IsNullOrEmpty(sStackTrace)) sMensaje += "\r\nStackTrace: " + sStackTrace;
string Titulo = "Mensaje Automático. Error en " + Rutina;
if (tsNotificacionesHabilitado)
{
try
{
await EnviaAlertaExcepcion(Titulo, sMensaje, FicheroImagen);
}
catch (Exception ex1)
{
FuerzaCorreo = true;
string sStackTrace2 = "Tipo excepción Alerta: " + ex1.ToString() + "\r\n";
var exError2 = ex1;
do
{
sStackTrace2 += exError2.StackTrace + "\r\n";
exError2 = exError2.InnerException;
} while (exError2 != null);
if (!string.IsNullOrEmpty(sStackTrace2)) sMensaje += "\r\nStackTrace: " + sStackTrace2;
}
}
else
{
FuerzaCorreo = true;
}
if (CorreoLogsHabilitado || FuerzaCorreo)
{
var cuentaorigen = bd.cuentascorreo.First(c => c.Codigo == "TECNOSIS");
GeneraRegistroCorreo(bd, Titulo, sMensaje, cuentaorigen, "sevilla@tecnosis.net", FicheroImagen, null, "ERROR");
}
}
catch (Exception ex2)
{
Anadelogtxt(ex2.Message, FicheroLog);
throw new Exception (ex2.Message + "\r\n" + ex2.StackTrace + "Error Generando Correo Excepcion");
}
}
public static void GeneraRegistroCorreoExcepcion(tscgestionasegasa bd, Exception ex, string sAsunto, string sCuerpo, bool MostrarMensajeError = false, byte[] FicheroImagen = null)
{
try
{
string sMensaje = sCuerpo + "\r\n\r\nUsuario: " + Usuario + "\r\n\r\n";
string sStackTrace = "Excepción: " + ex.ToString() + "\r\n";
Exception exError = ex;
do
{
sStackTrace += exError.StackTrace + "\r\n\r\n";
exError = exError.InnerException;
} while (exError != null);
if (!string.IsNullOrEmpty(sStackTrace)) sMensaje += "\r\nStackTrace: " + sStackTrace;
var cuentaorigen = bd.cuentascorreo.First(c => c.Codigo == "TECNOSIS");
GeneraRegistroCorreo(bd, sAsunto, sMensaje, cuentaorigen, "sevilla@tecnosis.net", FicheroImagen, null, "ERROR");
}
catch (Exception ex2)
{
Anadelogtxt(ex2.Message, FicheroLog);
throw new Exception(ex2.Message + "\r\n" + ex2.StackTrace + "Error Generando Correo Excepcion");
}
}
public static void GeneraRegistroCorreo(tscgestionasegasa bd, string Asunto, string Cuerpo)
{
try
{
var cuentaorigen = bd.cuentascorreo.First(c => c.Codigo == "TECNOSIS");
var correo = new bdAsegasa.db.correos
{
Asunto = Asunto,
Cuerpo = Cuerpo,
Destinatario = "sevilla@tecnosis.net",
DireccionRespuesta = cuentaorigen.Remitente,
FechaCreacion = AhoraMysql(bd),
idcuenta = cuentaorigen.idCuenta,
Remitente = cuentaorigen.Remitente
};
if (Environment.MachineName.ToUpper() == "INTI" || Environment.MachineName.ToUpper().Trim() == "CERBERO") correo.Destinatario = "danmun@tecnosis.net";
bd.correos.Add(correo);
bd.SaveChanges();
}
catch (Exception ex)
{
Debug.Write(ex.Message);
throw;
}
}
public static void GeneraRegistroCorreo(tscgestionasegasa bd, string Asunto, string Cuerpo, cuentascorreo cuenta, string Destinatario, byte[] CapturaPantallaError = null, int? idAplicacion = null, string CodigoAplicacion = "")
{
try
{
var correo = new bdAsegasa.db.correos
{
Asunto = Asunto,
Cuerpo = Cuerpo,
Destinatario = Destinatario,
DireccionRespuesta = cuenta.Remitente,
FechaCreacion = AhoraMysql(bd),
idcuenta = cuenta.idCuenta,
Remitente = cuenta.Remitente,
idAplicacion = idAplicacion,
CodigoAplicacion = CodigoAplicacion
};
if (CapturaPantallaError != null)
{
var idtipocapturaerror = bd.enumeraciones.First(x => x.Codigo == "TIPFIC.CAPERROR").idEnumeracion;
var f = new bdAsegasa.db.ficheros();
f.NombreFichero = "CapturaPantallaError_" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".jpg";
f.Fichero = CapturaPantallaError;
f.idTipo = idtipocapturaerror;
bd.ficheros.Add(f);
// Mapped dynamically if possible (usually a list or direct relation)
if (correo.ficherosadjuntos == null) correo.ficherosadjuntos = new List<ficherosadjuntos>();
correo.ficherosadjuntos.Add(new ficherosadjuntos { idFicheroNavigation = f });
}
if (Environment.MachineName.ToUpper() == "INTI" || Environment.MachineName.ToUpper().Trim() == "CERBERO") Destinatario = "danmun@tecnosis.net";
bd.correos.Add(correo);
bd.SaveChanges();
}
catch (Exception ex)
{
Debug.Write(ex.Message);
throw;
}
}
public static void GenerarRegistroCorreoAvant2Agente3(tscgestionasegasa bd, ref polizassg linea, string sQuotationID, string usuarioAvant2 = "")
{
try
{
var lineasEnumeraciones = bd.enumeraciones.Where(x => x.idGrupoEnumeracion == 62).ToList();
string sDireccionRespuesta = lineasEnumeraciones.FirstOrDefault(x => x.Codigo == "AVANT2.EMAIL.IP.RESPUESTA")?.ValorAlfabetico1;
var sDireccionesDestino = new List<string>();
foreach (var le in lineasEnumeraciones)
{
if (le.Codigo != null && le.Codigo.StartsWith("AVANT2.EMAIL.IP.DESTINO")) sDireccionesDestino.Add(le.ValorAlfabetico1);
}
StringBuilder sbAsuntoEmail = new StringBuilder();
StringBuilder sbCuerpoEmail = new StringBuilder();
sbAsuntoEmail.Append("Avant2: se procederá a la incorporación de una póliza al agente 3");
sbCuerpoEmail.AppendLine("Avant2: se procederá a la incorporación de una póliza al agente 3.<br/>");
sbCuerpoEmail.AppendLine("No es posible transferir la póliza a su usuario original porque no se encuentra la información del usuario que la emitió desde Avant2.<br/>");
sbCuerpoEmail.AppendLine("Hay que revisar que el usuario de Avant2 que realizó la emisión de esta póliza esté correctamente identificado en la aplicación Gestión Asegasa.<br/>");
sbCuerpoEmail.AppendLine("Datos de la póliza importada al agente 3:<br/>");
sbCuerpoEmail.AppendLine(string.Format("quotationID: {0} <br/>", sQuotationID));
try { sbCuerpoEmail.AppendLine(string.Format("Nº de póliza: {0} <br/>", linea.NumeroPoliza)); } catch { }
try { sbCuerpoEmail.AppendLine(string.Format("Compañía: {0} <br/>", linea.idCompaniaNavigation?.Nombre)); } catch { }
try { sbCuerpoEmail.AppendLine(string.Format("Ramo: {0} <br/>", linea.idRamoNavigation?.Descripcion)); } catch { }
try { sbCuerpoEmail.AppendLine(string.Format("CIF del tomador: {0} <br/>", linea.Tomador?.CIF)); } catch { }
try { sbCuerpoEmail.AppendLine(string.Format("Nombre del tomador: {0} <br/>", (linea.Tomador?.Nombre + " " + linea.Tomador?.Apellidos).Trim())); } catch { }
try { sbCuerpoEmail.AppendLine(string.Format("Fecha de efecto: {0} <br/>", linea.FechaEfecto)); } catch { }
try { if (!string.IsNullOrWhiteSpace(usuarioAvant2)) sbCuerpoEmail.AppendLine(string.Format("Identificador del usuario de Avant 2 que realizó el alta: {0} <br/>", usuarioAvant2.Trim())); } catch { }
sbCuerpoEmail.AppendLine("<br/>Fin del correo electrónico.");
var cuentaorigen = bd.cuentascorreo.First(c => c.Codigo == "TECNOSIS");
foreach (var destinatario in sDireccionesDestino)
{
GeneraRegistroCorreo(bd, sbAsuntoEmail.ToString(), sbCuerpoEmail.ToString(), cuentaorigen, destinatario);
}
}
catch (Exception ex2)
{
Anadelogtxt(ex2.Message, FicheroLog);
}
}
public static void GenerarRegistroCorreoAvant2IncorporacionParcial(tscgestionasegasa bd, ref polizassg linea, string sQuotationID)
{
try
{
var lineasEnumeraciones = bd.enumeraciones.Where(x => x.idGrupoEnumeracion == 62).ToList();
string sDireccionRespuesta = lineasEnumeraciones.FirstOrDefault(x => x.Codigo == "AVANT2.EMAIL.IP.RESPUESTA")?.ValorAlfabetico1;
var sDireccionesDestino = new List<string>();
foreach (var le in lineasEnumeraciones)
{
if (le.Codigo != null && le.Codigo.StartsWith("AVANT2.EMAIL.IP.DESTINO")) sDireccionesDestino.Add(le.ValorAlfabetico1);
}
StringBuilder sbAsuntoEmail = new StringBuilder();
StringBuilder sbCuerpoEmail = new StringBuilder();
sbAsuntoEmail.AppendFormat("Avant2: incorporación parcial de poliza nº {0}, {1}", linea.NumeroPoliza, linea.idRamoNavigation?.Descripcion);
sbCuerpoEmail.AppendLine("Avant2, incorporación parcial de póliza.\r\n");
sbCuerpoEmail.AppendLine("Esto es una incorporación parcial. Avant2 de Codeoscopic no proporciona varios datos de la póliza.\r\n");
sbCuerpoEmail.AppendLine(string.Format("quotationID: {0}", sQuotationID));
try { sbCuerpoEmail.AppendLine(string.Format("Numero de póliza: {0}", linea.NumeroPoliza)); } catch { }
try { sbCuerpoEmail.AppendLine(string.Format("Compañía: {0}", linea.idCompaniaNavigation?.Nombre)); } catch { }
try { sbCuerpoEmail.AppendLine(string.Format("Ramo: {0}", linea.idRamoNavigation?.Descripcion)); } catch { }
try { sbCuerpoEmail.AppendLine(string.Format("CIF del tomador: {0}", linea.Tomador?.CIF)); } catch { }
try { sbCuerpoEmail.AppendLine(string.Format("Nombre del tomador: {0}", (linea.Tomador?.Nombre + " " + linea.Tomador?.Apellidos).Trim())); } catch { }
try { sbCuerpoEmail.AppendLine(string.Format("Fecha de efecto: {0}", linea.FechaEfecto)); } catch { }
sbCuerpoEmail.AppendLine("\r\nFin del correo electronico.");
var cuentaorigen = bd.cuentascorreo.First(c => c.Codigo == "TECNOSIS");
foreach (var destinatario in sDireccionesDestino)
{
GeneraRegistroCorreo(bd, sbAsuntoEmail.ToString(), sbCuerpoEmail.ToString(), cuentaorigen, destinatario);
}
}
catch (Exception ex2)
{
Anadelogtxt(ex2.Message, FicheroLog);
}
}
public static tsUtilidades.Permisos ObtienePermisos(tscgestionasegasa bd, int? idPermiso, int idUsuario)
{
var per = new tsUtilidades.Permisos();
var usuario = bd.usuarios.First(u => u.idUsuario == idUsuario);
var grupoUsuario = bd.gruposusuarios.FirstOrDefault(g => g.idGrupo == usuario.idGrupo);
if (grupoUsuario != null && grupoUsuario.Descripcion == "TECNOSIS")
{
per.Consultar = true; per.Eliminar = true; per.Nuevos = true; per.Otros = true; per.Modificar = true; per.Impresion = true; per.Exportar = true;
}
else
{
if (idPermiso == null)
{
per.Consultar = false; per.Eliminar = false; per.Nuevos = false; per.Otros = false; per.Modificar = false; per.Impresion = false; per.Exportar = false;
}
else
{
var au = bd.autorizacionesusuarios.Where(a => a.idPermiso == idPermiso && a.idUsuario == idUsuario).ToList();
if (au.Count == 0)
{
var ag = bd.autorizacionesgrupos.Where(g => g.idPermiso == idPermiso && g.idGrupo == usuario.idGrupo).ToList();
if (ag.Count == 0)
{
per.Consultar = false; per.Eliminar = false; per.Nuevos = false; per.Otros = false; per.Modificar = false; per.Impresion = false; per.Exportar = false;
}
else
{
per.Consultar = ag.First().PermitirConsultas;
per.Eliminar = ag.First().PermitirEliminaciones;
per.Nuevos = ag.First().PermitirNuevos;
per.Otros = ag.First().OtrosPermisos;
per.Modificar = ag.First().PermitirModificaciones;
per.Impresion = ag.First().PermitirImpresiones;
per.Exportar = ag.First().PermitirExportar;
}
}
else
{
per.Consultar = au.First().PermitirConsultas;
per.Eliminar = au.First().PermitirEliminaciones;
per.Nuevos = au.First().PermitirNuevos;
per.Otros = au.First().OtrosPermisos;
per.Modificar = au.First().PermitirModificaciones;
per.Impresion = au.First().PermitirImpresiones;
per.Exportar = au.First().PermitirExportar;
}
}
}
return per;
}
public static tsUtilidades.Permisos ObtienePermisos(tscgestionasegasa bd, string Codigo, int idUsuario)
{
try
{
var per = new tsUtilidades.Permisos();
var usuario = bd.usuarios.First(u => u.idUsuario == idUsuario);
var grupoUsuario = bd.gruposusuarios.FirstOrDefault(g => g.idGrupo == usuario.idGrupo);
if (grupoUsuario != null && grupoUsuario.Descripcion == "TECNOSIS")
{
per.Consultar = true; per.Eliminar = true; per.Nuevos = true; per.Otros = true; per.Modificar = true; per.Impresion = true; per.Exportar = true;
}
else
{
var au = bd.autorizacionesusuarios.Where(a => a.idPermisoNavigation.CodigoPermiso == Codigo && a.idUsuario == idUsuario).ToList();
if (au.Count == 0)
{
var ag = bd.autorizacionesgrupos.Where(g => g.idPermisoNavigation.CodigoPermiso == Codigo && g.idGrupo == usuario.idGrupo).ToList();
if (ag.Count == 0)
{
per.Consultar = false; per.Eliminar = false; per.Nuevos = false; per.Otros = false; per.Modificar = false; per.Impresion = false; per.Exportar = false;
}
else
{
per.Consultar = ag.First().PermitirConsultas;
per.Eliminar = ag.First().PermitirEliminaciones;
per.Nuevos = ag.First().PermitirNuevos;
per.Otros = ag.First().OtrosPermisos;
per.Modificar = ag.First().PermitirModificaciones;
per.Impresion = ag.First().PermitirImpresiones;
per.Exportar = ag.First().PermitirExportar;
}
}
else
{
per.Consultar = au.First().PermitirConsultas;
per.Eliminar = au.First().PermitirEliminaciones;
per.Nuevos = au.First().PermitirNuevos;
per.Otros = au.First().OtrosPermisos;
per.Modificar = au.First().PermitirModificaciones;
per.Impresion = au.First().PermitirImpresiones;
per.Exportar = au.First().PermitirExportar;
}
}
return per;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public static string ObtenerNumeroDePolizaDisponibleTractoresAXA(tscgestionasegasa bd, uint n = 0)
{
try
{
string resultado = "";
enumeraciones inicio;
enumeraciones fin;
uint actual = 0;
bool bEncontrado = false;
var enumNumeracion = bd.enumeraciones.Where(x => x.Codigo != null && x.Codigo.StartsWith("AXATRACTORES.numeracion.") && x.ValorAlfabetico1.ToUpper().Trim() == "DISPONIBLE").OrderBy(x => x.Codigo).ToList();
int idRamoTractores = 0;
int idRamoRemolques = 0;
int.TryParse(bd.ramos.Where(x => x.Codigo == "1-1").Select(x => x.idRamo).FirstOrDefault().ToString(), out idRamoTractores);
int.TryParse(bd.ramos.Where(x => x.Codigo == "1-1-1").Select(x => x.idRamo).FirstOrDefault().ToString(), out idRamoRemolques);
inicio = enumNumeracion.FirstOrDefault(x => x.Codigo != null && x.Codigo.EndsWith(".inicio"));
fin = enumNumeracion.FirstOrDefault(x => x.Codigo != null && x.Codigo.EndsWith(".fin"));
try
{
if (n == 0)
{
string strActual = bd.polizassg.Where(x => x.NumeroPoliza.CompareTo(inicio.ValorNumerico1.ToString()) >= 0 && x.NumeroPoliza.CompareTo(fin.ValorNumerico1.ToString()) <= 0 && (x.idRamo == idRamoTractores || x.idRamo == idRamoRemolques)).OrderByDescending(x => x.NumeroPoliza).Select(x => x.NumeroPoliza).Take(10).FirstOrDefault();
if (strActual != null)
{
uint.TryParse(strActual, out actual);
}
}
else
{
actual = n;
}
}
catch (Exception) { }
if (actual == 0)
{
resultado = inicio?.ValorNumerico1?.ToString();
bEncontrado = true;
}
else
{
if (actual < inicio?.ValorNumerico1)
{
resultado = inicio?.ValorNumerico1?.ToString();
bEncontrado = true;
}
else if (actual == fin?.ValorNumerico1)
{
inicio.ValorAlfabetico1 = "Usado";
fin.ValorAlfabetico1 = "Usado";
bd.SaveChanges();
resultado = ObtenerNumeroDePolizaDisponibleTractoresAXA(bd);
}
else if (actual > fin?.ValorNumerico1)
{
resultado = "-1";
bEncontrado = true;
string asunto = "TractoresAXA: Se han acabado los nºs de pólizas reservados para el servicio de TractoresAXA.";
string cuerpo = asunto + "\r\n Hay que avisar a ASEGASA para que gestionen con AXA la asignación de un nuevo rango de nºs de pólizas para este servicio.\r\nEn método `" + System.Reflection.MethodBase.GetCurrentMethod().ToString() + "`. \r\n" + Environment.MachineName;
AñadeLog(tsUtilidades.Enumeraciones.TipoLog.Fallo, asunto, cuerpo);
tsUtilidades.Utilidades.EnviarNotificacionSlack(asunto, "asegasa", System.Reflection.MethodBase.GetCurrentMethod().ToString());
}
else
{
resultado = (actual + 1).ToString();
bEncontrado = true;
}
}
return resultado;
}
catch(Exception)
{
return "-1";
}
}
}
}