using System; using System.Collections.Generic; using System.Linq; using System.Net; using Microsoft.EntityFrameworkCore; using tsUtilidades.Datos; using tsEFCore8; using System.Linq.Dynamic.Core; namespace bdAsegasa.db { public partial class gestionasegasaEntities : bdAsegasa.tscgestionasegasa { public gestionasegasaEntities(DbContextOptions options) : base(options) { } public static string Usuario { get; set; } public static DatosSesionCliente dsc = new DatosSesionCliente(); public static BBDD bdga { get; set; } public static bool EsRemoto { get; set; } private static List _ListaSituacionesWeb = null; private static List _ListaPagoWeb = null; private string _Ip; private static int _TippCIA; private static int _TippFAE; private static int _CabaSupl; private static int _CabaSust; private static int _CabaPGO; public string ip { get { return _Ip; } set { _Ip = value; } } public static System.Data.Common.DbConnection Conexion { get; set; } public object Aplicacion { get; set; } public string OtrosDatos { get; set; } public static int TipoPagoCia() { if (_TippCIA == 0) { using var bd = NuevoContextoCN(); _TippCIA = bd.enumeraciones.First(x => x.Codigo == "TIPP.CIA").idEnumeracion; } return _TippCIA; } public static int TipoPagoFAE() { if (_TippFAE == 0) { using var bd = NuevoContextoCN(); _TippFAE = bd.enumeraciones.First(x => x.Codigo == "TIPP.FAE").idEnumeracion; } return _TippFAE; } public static int CabaPGO() { if (_CabaPGO == 0) { using var bd = NuevoContextoCN(); _CabaPGO = bd.enumeraciones.First(x => x.Codigo == "CABA.PGO").idEnumeracion; } return _CabaPGO; } public static int CabaSupl() { if (_CabaSupl == 0) { using var bd = NuevoContextoCN(); _CabaSupl = bd.enumeraciones.First(x => x.Codigo == "CABA.SUPL").idEnumeracion; } return _CabaSupl; } public static int CabaSust() { if (_CabaSust == 0) { using var bd = NuevoContextoCN(); _CabaSust = bd.enumeraciones.First(x => x.Codigo == "CABA.SUST").idEnumeracion; } return _CabaSust; } public override int SaveChanges() { GuardandoCambios(this, EventArgs.Empty); return base.SaveChanges(); } public int GuardarCambios() { return SaveChanges(); } private static void GuardandoCambios(object sender, EventArgs e) { var bd = sender as gestionasegasaEntities; if (bd == null) return; try { string sAplicaciones = !string.IsNullOrEmpty(bd.OtrosDatos) ? bd.OtrosDatos.ToUpper() : ""; if (bd.Aplicacion != null) { var propInfo = bd.Aplicacion.GetType().GetProperty("NombreTablaBase"); if (propInfo != null) { var propVal = propInfo.GetValue(bd.Aplicacion) as string; if (!string.IsNullOrEmpty(propVal)) sAplicaciones = propVal.ToUpper(); } } if (string.IsNullOrEmpty(sAplicaciones)) return; foreach (var saplicacion in sAplicaciones.Split('|')) { switch (saplicacion) { case "POLIZASSG": case "VF_DOCUMENTOSPOLIZASSG": // bdAsegasa.db.polizassg.GuardandoCambios(bd, saplicacion); break; case "ENTIDADES": // bdAsegasa.db.entidades.GuardandoCambios(bd, saplicacion); break; case "SINIESTROS": // bdAsegasa.db.siniestros.GuardandoCambios(bd); break; case "RECIBOS": case "INCORPORACION_RECIBOS_EIAC": // bdAsegasa.db.recibos.GuardandoCambios(bd, saplicacion); break; } } } catch (Exception ex) { // Manejo de errores silencioso como en VB } } public static new gestionasegasaEntities NuevoContexto(string NombreConexion = "", bool Lazy = true, bool SoloLectura = false, bool ConEventoSavingChanges = false, string aplicaciones = "") { var baseContext = bdAsegasa.tscgestionasegasa.NuevoContexto(NombreConexion, Lazy, SoloLectura, ConEventoSavingChanges, aplicaciones); string cnx = ""; if (string.IsNullOrEmpty(NombreConexion)) { cnx = bdAsegasa.dbcontext.Conexion.ObtieneConexionDefecto(); } else { cnx = bdAsegasa.dbcontext.Conexion.ObtieneConexionDefecto(NombreConexion); } var ob = new DbContextOptionsBuilder(); ob.UseMySql(cnx, ServerVersion.Parse("5.7.0-mysql")); if (Lazy) ob.UseLazyLoadingProxies(); if (SoloLectura) ob.UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking); var options = ob.Options; var bd = new gestionasegasaEntities(options); return bd; } public static gestionasegasaEntities NuevoContextoCN(bool ConEventos = false, bool Desarrollo = false, bool? Remoto = null, bool FuerzaSeleccion = true) { return NuevoContexto(ConEventoSavingChanges: ConEventos); } public static gestionasegasaEntities NuevoContextoCE(string Aplicaciones = "POLIZASSG|ENTIDADES", bool Desarrollo = false, bool? Remoto = null, bool FuerzaSeleccion = true, object Aplicacion = null) { var ctx = NuevoContextoCN(true, Desarrollo, Remoto, FuerzaSeleccion); ctx.OtrosDatos = Aplicaciones; ctx.Aplicacion = Aplicacion; return ctx; } public static void EstableceCBD(bool FuerzaSeleccion, bool Desarrollo = false, bool? Remoto = null) { try { EstableceLocalizacion(Remoto); var lc = bdAsegasa.dbcontext.Conexion.ListaConexiones(); bdAsegasa.dbcontext.Conexion cs; if (Desarrollo) { cs = lc.FirstOrDefault(x => x.Nombre == "Desarrollo") ?? lc[0]; } else { if (FuerzaSeleccion) { Conexion = null; cs = lc[0]; } else { cs = lc[0]; } } bdga = new BBDD(); bdga.Usuario = cs.Usuario; bdga.Password = cs.Contraseña; bdga.DataBase = cs.Database; bdga.Tipo = tsUtilidades.Enumeraciones.TipoBD.MYSQL; bdga.id = cs.Nombre; if (EsRemoto && cs.Nombre == "Producción" && Environment.MachineName.ToUpper() != "ASEGASA1") { bdga.Servidor = "sevilla.asegasa.com"; bdga.Puerto = 30002; } else { if (cs.Nombre == "Producción" && Environment.MachineName.ToUpper() == "ASEGASA1") { bdga.Servidor = "localhost"; } else { bdga.Servidor = cs.Servidor; } bdga.Puerto = cs.Puerto; } } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public static void EstableceCBD(string nombreconexion, bool remoto) { try { var lc = bdAsegasa.dbcontext.Conexion.ListaConexiones(); var cs = lc.First(x => x.Nombre == nombreconexion); bdga = new BBDD(); bdga.Usuario = cs.Usuario; bdga.Password = cs.Contraseña; bdga.DataBase = cs.Database; bdga.Tipo = tsUtilidades.Enumeraciones.TipoBD.MYSQL; bdga.id = cs.Nombre; if (remoto) { bdga.Servidor = "sevilla.asegasa.com"; bdga.Puerto = 30002; } else { if (cs.Nombre == "Producción" && Environment.MachineName.ToUpper() == "ASEGASA1") { bdga.Servidor = "localhost"; } else { bdga.Servidor = cs.Servidor; } bdga.Puerto = cs.Puerto; } } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public static void EstableceLocalizacion(bool? Remoto) { try { if (!Remoto.HasValue) { if (!System.IO.Directory.Exists(@"c:\tecnosis.tfs")) { EsRemoto = false; try { Dns.GetHostEntry("servidorbdgestionasegasa").AddressList[0].ToString(); EsRemoto = true; } catch { EsRemoto = false; } } else { EsRemoto = true; } } else { EsRemoto = Remoto.Value; } } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public bdAsegasa.db.agentes ObtenerAgente(string usuario, string pass) { var claveSha = tsUtilidades.crypt.SHA1("M3Soft." + pass); try { return this.agentes.FirstOrDefault(x => x.Codigo == usuario && x.hashContrasena == claveSha); } catch (Exception) { throw new Exception("Ha ocurrido un error al conectar con la base de datos, disculpe las molestias"); } } public bdAsegasa.db.subagentes ObtenerSubagente(string codigoAgente, string codigoSubAgente, string contraseña) { try { var claveSha = tsUtilidades.crypt.SHA1("M3Soft." + contraseña); var agente = this.agentes.FirstOrDefault(x => x.Codigo == codigoAgente); if (agente == null) return null; return this.subagentes.FirstOrDefault(x => x.idAgente == agente.idAgente && x.Codigo == codigoSubAgente && x.hashContrasena == claveSha); } catch (Exception) { throw new Exception("Ha ocurrido un error al conectar con la base de datos, disculpe las molestias"); } } internal static string ObtieneSituacionWeb(int? idSituacion, int? idTipoPago) { if (idSituacion.HasValue) { if (_ListaSituacionesWeb == null || _ListaPagoWeb == null) { using var bd = NuevoContextoCN(); if (_ListaSituacionesWeb == null) { _ListaSituacionesWeb = bd.enumeraciones.Where(x => x.idGrupoEnumeracionNavigation.Grupo == "SITR").ToList(); } if (_ListaPagoWeb == null) { _ListaPagoWeb = bd.enumeraciones.Where(x => x.idGrupoEnumeracionNavigation.Grupo == "TIPP").ToList(); } } var sitr = _ListaSituacionesWeb.First(x => x.idEnumeracion == idSituacion); if (idTipoPago.HasValue) { var tipp = _ListaPagoWeb.First(x => x.idEnumeracion == idTipoPago); if (sitr.Codigo == "SITR.BJ" && (tipp.Codigo == "TIPP.CIA" || tipp.Codigo == "TIPP.FAE")) { return tipp.Descripcion; } else { return sitr.Descripcion; } } else { return sitr.Descripcion; } } return ""; } public string ObTieneMunicipio(string CodigoPostal, string Poblacion) { try { string CodigoMunicipio = ""; CodigoPostal = (CodigoPostal ?? "").Trim(); if (CodigoPostal.Length == 5) { if (this.codigospostales.Any(x => x.CodigoPostal == CodigoPostal)) { if (this.codigospostales.Count(x => x.CodigoPostal == CodigoPostal) == 1) { CodigoMunicipio = this.codigospostales.First(x => x.CodigoPostal == CodigoPostal).CodigoMunicipio; } else { CodigoMunicipio = ObtieneCodigoMunicipioMasCoincidente(CodigoPostal, Poblacion); } } else { string cpotmp = CodigoPostal.Substring(0, 4) + "0"; if (this.codigospostales.Any(x => x.CodigoPostal == cpotmp)) { if (this.codigospostales.Count(x => x.CodigoPostal == cpotmp) == 1) { CodigoMunicipio = this.codigospostales.First(x => x.CodigoPostal == cpotmp).CodigoMunicipio; } else { CodigoMunicipio = ObtieneCodigoMunicipioMasCoincidente(CodigoPostal, Poblacion); } } else { string cpotmp2 = CodigoPostal.Substring(0, 3) + "00"; if (this.codigospostales.Any(x => x.CodigoPostal == cpotmp2)) { if (this.codigospostales.Count(x => x.CodigoPostal == cpotmp2) == 1) { CodigoMunicipio = this.codigospostales.First(x => x.CodigoPostal == cpotmp2).CodigoMunicipio; } else { CodigoMunicipio = ObtieneCodigoMunicipioMasCoincidente(CodigoPostal, Poblacion); } } } } } else { if (string.IsNullOrEmpty(Poblacion)) { return null; } else { var mun = this.municipios.FirstOrDefault(x => x.Nombre == Poblacion); if (mun != null) { CodigoMunicipio = mun.CodigoMunicipio; } else { return null; } } } if (string.IsNullOrEmpty(CodigoMunicipio)) return null; else return CodigoMunicipio; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public string ObtieneCodigoMunicipioMasCoincidente(string CodigoPostal, string Poblacion, bool SinAñadir = false) { try { Poblacion = (Poblacion ?? "").Trim(); if (string.IsNullOrEmpty(Poblacion)) return ""; var muns = this.codigospostales.Where(x => x.CodigoPostal == CodigoPostal && x.CodigoMunicipioNavigation.Nombre == Poblacion).ToList(); if (muns.Count == 1) { return muns[0].CodigoMunicipio; } else { if (CodigoPostal.Length == 5) { string codigoprovincia = CodigoPostal.Substring(0, 2); muns = this.municipios.Where(x => x.CodigoProvincia == codigoprovincia).SelectMany(x => x.codigospostales).ToList(); int IndiceMasCoincidente = 0; double Puntuacion = 0; if (muns.Count == 0) return ""; for (int i = 0; i < muns.Count; i++) { double puntuaciontmp = ComparaPalabras(muns[i].CodigoMunicipioNavigation.Nombre, Poblacion); if (i == 0 || Puntuacion < puntuaciontmp) { IndiceMasCoincidente = i; Puntuacion = puntuaciontmp; } } if (!SinAñadir) { if (Puntuacion == 100) { CrearNuevoCodigoPostal(CodigoPostal, muns[IndiceMasCoincidente].CodigoMunicipio); return muns[IndiceMasCoincidente].CodigoMunicipio; } else { return CrearNuevoMunicipio(CodigoPostal, Poblacion); } } else { return ""; } } else { return ""; } } } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public static string ObtieneCodigoMunicipioMasCoincidente(List CodigosPostales, List LMunicipios, string CodigoPostal, string Poblacion) { try { var muns = CodigosPostales.Where(x => x.CodigoPostal == CodigoPostal).ToList(); if (muns.Count == 1) { return muns[0].CodigoMunicipio; } else { if (muns.Count == 0 && CodigoPostal.Length == 5) { string codigoprovincia = CodigoPostal.Substring(0, 2); muns = LMunicipios.Where(x => x.CodigoProvincia == codigoprovincia).SelectMany(x => x.codigospostales).ToList(); } if (CodigosPostales.Any(x => x.CodigoPostal == CodigoPostal && x.CodigoMunicipioNavigation.Nombre == Poblacion)) { return CodigosPostales.First(x => x.CodigoPostal == CodigoPostal && x.CodigoMunicipioNavigation.Nombre == Poblacion).CodigoMunicipio; } else { int IndiceMasCoincidente = 0; double Puntuacion = 0; if (muns.Count == 0) return ""; for (int i = 0; i < muns.Count; i++) { double puntuaciontmp = ComparaPalabras(muns[i].CodigoMunicipioNavigation.Nombre, Poblacion); if (i == 0 || Puntuacion < puntuaciontmp) { IndiceMasCoincidente = i; Puntuacion = puntuaciontmp; } } if (Puntuacion > 49) { return muns[IndiceMasCoincidente].CodigoMunicipio; } else { return CrearNuevoMunicipio(CodigoPostal, Poblacion); } } } } catch (Exception ex) { throw new Exception(ex.Message, ex); } } private static string CrearNuevoMunicipio(string CodigoPostal, string Municipio) { Municipio = (Municipio ?? "").Trim(); if (string.IsNullOrEmpty(Municipio)) return ""; using var bd = NuevoContextoCN(); var nm = new municipios(); string codpro = CodigoPostal.Substring(0, 2); var ultmun = bd.municipios.Where(x => x.CodigoProvincia == codpro).OrderByDescending(x => x.CodigoMunicipio).First(); char Letra; int Numero = 0; if ("0123456789".Contains(ultmun.CodigoMunicipio.Substring(2, 1))) { Letra = 'A'; Numero = 0; } else { Letra = ultmun.CodigoMunicipio[2]; Numero = int.Parse(ultmun.CodigoMunicipio.Substring(3)) + 1; if (Numero > 99) { Letra = (char)(Letra + 1); Numero = 0; } } nm.CodigoProvincia = codpro; nm.Nombre = Municipio; nm.CodigoMunicipio = codpro + Letra.ToString() + Numero.ToString("D2"); bd.municipios.Add(nm); bd.SaveChanges(); var cp = new codigospostales(); cp.CodigoPostal = CodigoPostal; cp.CodigoMunicipio = nm.CodigoMunicipio; bd.codigospostales.Add(cp); bd.SaveChanges(); return nm.CodigoMunicipio; } private static void CrearNuevoCodigoPostal(string CodigoPostal, string CodigoMunicipio) { using var bd = NuevoContextoCN(); if (!bd.codigospostales.Any(x => x.CodigoMunicipio == CodigoMunicipio && x.CodigoPostal == CodigoPostal)) { var cp = new codigospostales(); cp.CodigoPostal = CodigoPostal; cp.CodigoMunicipio = CodigoMunicipio; bd.codigospostales.Add(cp); bd.SaveChanges(); } } private static double ComparaPalabras(string Cadena1, string Cadena2) { try { Cadena1 = Cadena1.ToLower() .Replace("á", "a").Replace("é", "e").Replace("í", "i").Replace("ó", "o").Replace("ú", "u") .Replace("ñ", "ñ").Replace("(", " ").Replace(")", " ").Replace("\"", "").Replace("-", " ") .Replace(",", "").Trim(); Cadena2 = Cadena2.ToLower() .Replace("á", "a").Replace("é", "e").Replace("í", "i").Replace("ó", "o").Replace("ú", "u") .Replace("ñ", "ñ").Replace("(", " ").Replace(")", " ").Replace("\"", "").Replace("-", " ") .Replace(",", "").Trim(); var Cadenas1 = Cadena1.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); var Cadenas2 = Cadena2.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries).ToList(); int Coincidente = 0; foreach (var c in Cadenas1) { if (Cadenas2.Contains(c)) Coincidente++; } foreach (var c in Cadenas2) { if (Cadenas1.Contains(c)) Coincidente++; } if (Cadenas1.Count + Cadenas2.Count == 0) return 0; return (double)Coincidente * 100 / (Cadenas1.Count + Cadenas2.Count); } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public List ObtieneRecibosPendientesDescobro() { int idDescobro = this.enumeraciones.First(x => x.Codigo == "CABA.DES").idEnumeracion; int idTipLiqDes = this.enumeraciones.First(x => x.Codigo == "TIPLIQ.DESCOBRO").idEnumeracion; int idTipLiq = this.enumeraciones.First(x => x.Codigo == "TIPLIQ.LIQUIDACION").idEnumeracion; var result = (from dcp in (from lc in this.liquidacionescompaniasrecibos where lc.idLiquidacionCiaNavigation.idTipoLiquidacion == idTipLiq && lc.idReciboNavigation.idCausaBaja == idDescobro let dc = this.liquidacionescompaniasrecibos.FirstOrDefault(dc => dc.idRecibo == lc.idRecibo && dc.idLiquidacionCiaNavigation.idTipoLiquidacion == idTipLiqDes) where dc == null select lc) join re in this.vf_recibosextendidos on dcp.idRecibo equals re.idRecibo select re).ToList(); return result; } public List ObtieneRecibosPendientesDescobroAgentes() { int idDescobro = this.enumeraciones.First(x => x.Codigo == "CABA.DES").idEnumeracion; int idTipLiq = this.enumeraciones.First(x => x.Codigo == "TIPLIQAG.LIQUIDACION").idEnumeracion; var FechaInicio = new DateTime(2020, 11, 2); var recs = (from rg in this.regularizacionespagosagentes where !rg.idLiquidacionAgente.HasValue && !rg.idAgenteNavigation.FechaBaja.HasValue join re in this.vf_recibosextendidos on rg.idRecibo equals re.idRecibo select new { Recibo = re, Regularizacion = rg }).AsNoTracking().ToList(); var lr = new List(); foreach (var rg in recs) { var r = rg.Recibo; if (r.idAgente != rg.Regularizacion.idAgente) { r.idAgente = rg.Regularizacion.idAgente; r.CodigoAgente = rg.Regularizacion.idAgenteNavigation.Codigo; r.Agente = rg.Regularizacion.idAgenteNavigation.Nombre; } r.EsRetornoComision_TMP = true; r.idRegularizacion_TMP = rg.Regularizacion.idRegularizacion; r.ComisionAgente = rg.Regularizacion.Importe; lr.Add(r); } return lr; } public List ObtieneRecibosPendientesLiquidacionAgentes() { int idCabaPGO = this.enumeraciones.First(x => x.Codigo == "CABA.PGO").idEnumeracion; int idTippCIA = this.enumeraciones.First(x => x.Codigo == "TIPP.CIA").idEnumeracion; int idTippFAE = this.enumeraciones.First(x => x.Codigo == "TIPP.FAE").idEnumeracion; int idTippCO = this.enumeraciones.First(x => x.Codigo == "TIPP.CO").idEnumeracion; int idTippCTR = this.enumeraciones.First(x => x.Codigo == "TIPP.CTR").idEnumeracion; int idagente1 = this.agentes.First(x => x.Codigo == "1").idAgente; int idagente2 = this.agentes.First(x => x.Codigo == "2").idAgente; var Fhoy = DateOnly.FromDateTime(DateTime.Now); var rs1 = (from r in this.recibos where !r.liquidacionesagenterecibos.Any(y => y.idLiquidacionesAgenteNavigation.idAgente == null || y.idLiquidacionesAgenteNavigation.idAgente == r.idAgente) && (r.liquidacionescompaniasrecibos.Any(y => y.idLiquidacionCiaNavigation.Fecha <= Fhoy) || r.idTipoPago == idTippCIA || r.idTipoPago == idTippFAE || r.idTipoPago == idTippCO || r.idTipoPago == idTippCTR) && (r.FechaPago.HasValue || r.idCausaBaja == idCabaPGO) && r.idAgente != idagente1 && r.idAgente != idagente2 && !r.idAgenteNavigation.FechaBaja.HasValue && r.idAgenteNavigation.IBAN != "" && r.idAgenteNavigation.Email != "" && r.PrimaNeta != 0 && r.ComisionAgente != 0 join v_r in this.vf_recibosextendidos on r.idRecibo equals v_r.idRecibo select v_r).AsNoTracking().ToList(); var rsp = ObtieneRecibosPendientesDescobroAgentes(); if (rsp.Count != rsp.Except(rs1).Count()) throw new Exception("Existen regularizaciones de recibos aún no liquidados"); var rs2 = rs1.Union(rsp).ToList(); var recsag = rs2.GroupBy(x => x.CodigoAgente).OrderBy(x => x.First().CodigoAgente).ToList(); var agesneg = recsag.Where(x => x.Sum(y => y.ImporteALiquidarAgente) <= 0).Select(x => x.First().idAgente).ToList(); if (agesneg.Count > 0) { rs2 = rs2.Where(x => !agesneg.Contains(x.idAgente.Value)).ToList(); } return rs2; } public List ObtieneComisionesPendientesLiquidacionAgentesAgrario() { return this.historicocomisiones.Where(x => !x.fechaLiquidacion.HasValue && x.idCodigoAgenteNavigation.Codigo.Trim() != "1" && x.idCodigoAgenteNavigation.Codigo.Trim() != "2" && x.idCodigoAgenteNavigation.IBAN != "" && x.idCodigoAgenteNavigation.Email != "" && !x.idCodigoAgenteNavigation.FechaBaja.HasValue).ToList(); } public string EjemacHP(string Macro, string Parametros = "") { try { string sUrlEjemac = this.enumeraciones.First(x => x.Codigo == "CONF.CGIEJEMAC").ValorAlfabetico1; if (System.IO.Directory.Exists(@"C:\tecnosis.tfs")) { sUrlEjemac = "http://sevilla.asegasa.com:10080/cgi-bin/ejemac"; } if (!string.IsNullOrEmpty(Parametros)) { Parametros = Parametros.Replace("¡", "?"); sUrlEjemac += "?" + Macro + "=" + WebUtility.UrlEncode(Parametros); } else { sUrlEjemac += "?" + Macro; } string sRespuesta = tsUtilidades.http.EjecutaURL(sUrlEjemac, iTimeout: 500000); if (sRespuesta.Contains("#NO ENCONTRADO#")) { return sRespuesta; } else { try { return new string(sRespuesta.Where(c => c == 0x9 || c == 0xA || c == 0xD || (c >= 0x20 && c <= 0xD7FF) || (c >= 0xE000 && c <= 0xFFFD) || (c >= 0x10000 && c <= 0x10FFFF)).ToArray()); } catch { return sRespuesta; } } } catch (Exception ex) { throw new Exception(ex.Message, ex); } } public IQueryable Obtiene_ve_amortizacionrecibos() { var ve = (from x in this.amortizacionrecibos join r in this.vf_recibosextendidos on x.idRecibo equals r.idRecibo select new ve_amortizacionrecibos { idAmortizacion = x.idAmortizacion, idRecibo = x.idRecibo, FechaInicioAmortizacion = x.FechaInicioAmortizacion, FechaFinAmortizacion = x.FechaFinAmortizacion, PorcentajeAnual = x.PorcentajeAnual, FechaBaja = x.FechaBaja, idMotivoBaja = x.idMotivoBaja, idEmpresa = x.idEmpresa, NumeroCuenta = x.NumeroCuenta, Observaciones = x.Observaciones, FechaAlta = x.FechaAlta, Ramo = r.Ramo, CausaBaja = x.idMotivoBajaNavigation.Descripcion, Empresa = x.idEmpresaNavigation.Descripcion, Compañía = r.Compania, Tomador = r.Tomador, CodigoRecibo = r.CodigoRecibo, CIFTomador = r.CIFTomador, TotalRecibo = r.TotalRecibo.Value }); return ve; } public IQueryable Obtiene_ve_detallesamortizacionrecibos(DateOnly fechaInicio, DateOnly FechaFin) { int MesInicio = fechaInicio.Year * 100 + fechaInicio.Month; int Mesfin = FechaFin.Year * 100 + FechaFin.Month; var ve = from da in this.detallesamortizacionrecibos where da.Mes >= MesInicio && da.Mes <= Mesfin join x in this.amortizacionrecibos on da.idAmortizacion equals x.idAmortizacion join r in this.vf_recibosextendidos on x.idRecibo equals r.idRecibo select new ve_detallesamortizacionrecibos { idDetalle = da.idDetalle, idAmortizacion = x.idAmortizacion, idRecibo = x.idRecibo, ValorAmortizado = da.ValorAmortizado, ValorAcumulado = da.ValorAcumulado, ValorResidual = da.ValorResidual, Mes = da.Mes, FechaAplicacion = da.FechaAplicacion, FechaInicioAmortizacion = x.FechaInicioAmortizacion, FechaFinAmortizacion = x.FechaFinAmortizacion, PorcentajeAnual = x.PorcentajeAnual, FechaBaja = x.FechaBaja, idMotivoBaja = x.idMotivoBaja, idEmpresa = x.idEmpresa, NumeroCuenta = x.NumeroCuenta, Observaciones = x.Observaciones, FechaAlta = x.FechaAlta, Ramo = r.Ramo, CausaBaja = x.idMotivoBajaNavigation.Descripcion, Empresa = x.idEmpresaNavigation.Descripcion, Compañía = r.Compania, Tomador = r.Tomador, CodigoRecibo = r.CodigoRecibo, FechaEfecto = r.FechaEfecto, CIFTomador = r.CIFTomador, TotalRecibo = r.TotalRecibo.Value }; return ve; } public IQueryable Obtiene_ve_entidades() { var ents = this.entidades.Select(x => new ve_entidades { idEntidad = x.idEntidad, CIF = x.CIF, Direccion = x.idDireccionPrincipal.HasValue ? x.idDireccionPrincipalNavigation.Direccion : "", Poblacion = (x.idDireccionPrincipal.HasValue && x.idDireccionPrincipalNavigation.CodigoMunicipio != "") ? x.idDireccionPrincipalNavigation.CodigoMunicipioNavigation.Nombre : "", Provincia = (x.idDireccionPrincipal.HasValue && x.idDireccionPrincipalNavigation.CodigoMunicipio != "") ? x.idDireccionPrincipalNavigation.CodigoMunicipioNavigation.CodigoProvinciaNavigation.Nombre : "", email = x.Email, RazonSocial = x.RazonSocial, FechaNacimiento = x.FechaNacimiento, Telefono1 = x.Telefono1, EsClienteSA = x.EsClienteSA, EsClienteSG = x.EsClienteSG, EsContrarioSiniestro = x.EsContrarioSiniestro, EsTaller = x.EsTaller }); return ents; } public List Obtiene_ve_recibos(IQueryable queryRecibos, string ExpresionBusqueda = "", object[] Parametros = null) { var recs = from x in queryRecibos join t in this.v_tomadores on x.idPoliza equals t.idPoliza join lqc in this.v_liquidacion_cia on x.idRecibo equals lqc.idrecibo into glqc from lqc in glqc.DefaultIfEmpty() join lqcd in this.v_liquidacion_cia_devuelto on x.idRecibo equals lqcd.idrecibo into glqcd from lqcd in glqcd.DefaultIfEmpty() join lqa in this.v_liquidacion_agente on x.idRecibo equals lqa.idrecibo into glqa from lqa in glqa.DefaultIfEmpty() select new ve_recibos { idRecibo = x.idRecibo, idPoliza = x.idPoliza, FechaFacturacion = x.FechaFacturacion, FechaPago = x.FechaPago, CodigoRecibo = x.CodigoRecibo, Tomador = t.RazonSocial, CIFTomador = t.CIF, Telefono1Tomador = t.Telefono1, Telefono2Tomador = t.Telefono2, NumeroPoliza = x.idPolizaNavigation.NumeroPoliza, Matricula = x.idPolizaNavigation.Matricula, FechaEfecto = x.FechaEfecto, FechaRecepcionCia = x.FechaRecepcionCia, FechaVencimiento = x.FechaVencimiento, FechaRemesa = x.idRemesa.HasValue ? x.idRemesaNavigation.Fecha : (DateOnly?)null, Compania = x.idPolizaNavigation.idCompaniaNavigation != null ? x.idPolizaNavigation.idCompaniaNavigation.Nombre : null, Agente = x.idAgenteNavigation != null ? x.idAgenteNavigation.Nombre : null, SubAgente = x.idSubagenteNavigation != null ? x.idSubagenteNavigation.Nombre : null, Ramo = x.idPolizaNavigation.idRamoNavigation != null ? x.idPolizaNavigation.idRamoNavigation.Descripcion : null, FechaExpedicion = x.FechaExpedicion, BienesAsegurados = x.idPolizaNavigation.BienesAsegurados, FechaBaja = x.FechaBaja, FechaDevolucionBanco = x.FechaDevolucionBanco, CausaBaja = x.idCausaBaja.HasValue ? x.idCausaBajaNavigation.Descripcion : null, TipoRecibo = x.idTipo != 0 ? x.idTipoNavigation.Descripcion : null, TipoPago = x.idTipoPago.HasValue ? x.idTipoPagoNavigation.Descripcion : null, PrimaNeta = x.PrimaNeta, BonificacionORecargo = x.BonificacionORecargo, Consorcio = x.Consorcio, Impuesto = x.Impuesto, RecargoExterno = x.RecargoExterno, TotalRecibo = x.TotalRecibo, ComisionReciboPrimaNeta = x.ComisionReciboPrimaNeta, PorcentajeReciboPrimaNeta = x.PorcentajeReciboPrimaNeta, TotalComision = x.TotalComision, SobreComision = x.Sobrecomision, ComisionPrevista = x.ComisionPrevista, PorcentajeComisionAgente = x.PorcentajeComisionAgente, ComisionAgente = x.ComisionAgente, ComisionAsegasaPrimaNeta = x.ComisionAsegasaPrimaNeta, AsegasaRecargoExterno = x.AsegasaRecargoExterno, AsegasaComisionConsorcio = x.AsegasaComisionConsorcio, AsegasaComisionTotal = x.AsegasaComisionTotal, idSituacion = x.idSituacion, Observaciones = x.Observaciones, ObservacionesPoliza = x.idPolizaNavigation.Observaciones, FechaLiquidacionCia = lqc != null ? lqc.UltimaFecha : null, FechaLiquidacionCiaDevuelto = lqcd != null ? lqcd.UltimaFecha : null, FechaLiquidacionAgente = lqa != null ? lqa.UltimaFecha : null }; if (!string.IsNullOrEmpty(ExpresionBusqueda)) { recs = recs.Where(ExpresionBusqueda, Parametros); } return recs.ToList(); } public List Obtiene_ve_recibosNuevo(bool IncluirBajas, DateOnly? FechaInicio, DateOnly? FechaFin, string TextoBusqueda = "") { string[] CamposBusquedaDobles = { "TotalRecibo" }; string[] CamposBusquedaAlfabeticos = { "Tomador", "NumeroPoliza", "Matricula", "CodigoRecibo", "CIFTomador" }; object[] parametros = null; bool BusquedaRapida = false; TextoBusqueda = (TextoBusqueda ?? "").Trim(); if (!string.IsNullOrEmpty(TextoBusqueda) && !TextoBusqueda.Contains(" ")) { BusquedaRapida = true; } List rs = new List(); List rlas = new List(); List rlcs = new List(); List rlcds = new List(); do { if (BusquedaRapida) { if (TextoBusqueda.Contains("/")) { rs = this.vp_recibosextendidos.Where(x => x.CodigoRecibo.Contains(TextoBusqueda) || x.NumeroPoliza.Contains(TextoBusqueda) || x.Tomador.Contains(TextoBusqueda) || x.Matricula.Contains(TextoBusqueda) || x.CIFTomador.Contains(TextoBusqueda)).ToList(); } else { rs = this.vp_recibosextendidos.Where(x => x.NumeroRecibo.Contains(TextoBusqueda) || x.NumeroPoliza.Contains(TextoBusqueda) || x.Tomador.Contains(TextoBusqueda) || x.Matricula.Contains(TextoBusqueda) || x.CIFTomador.Contains(TextoBusqueda)).ToList(); } } else { var iqrs = this.vp_recibosextendidos.AsQueryable(); if (!IncluirBajas) { var hoy = DateOnly.FromDateTime(DateTime.Now); iqrs = iqrs.Where(x => x.FechaBaja == null && x.FechaVencimiento >= hoy); } if (FechaInicio.HasValue) { iqrs = iqrs.Where(x => x.FechaEfecto >= FechaInicio); } if (FechaFin.HasValue) { iqrs = iqrs.Where(x => x.FechaEfecto <= FechaFin); } if (!string.IsNullOrEmpty(TextoBusqueda)) { string q = "Tomador.Contains(@0) or NumeroPoliza.Contains(@0) or Matricula.Contains(@0) or CodigoRecibo.Contains(@0) or CIFTomador.Contains(@0)"; parametros = new object[] { TextoBusqueda }; iqrs = iqrs.Where(q, parametros); } rs = iqrs.ToList(); } if (rs.Count == 0 && BusquedaRapida) { BusquedaRapida = false; } else { break; } } while (true); if (rs.Count == 0) return new List(); if (BusquedaRapida) { if (TextoBusqueda.Contains("/")) { rlas = this.vp_liquidacionesagentesrecibos.Where(x => x.CodigoRecibo.Contains(TextoBusqueda) || x.NumeroPoliza.Contains(TextoBusqueda) || x.Tomador.Contains(TextoBusqueda) || x.Matricula.Contains(TextoBusqueda) || x.CIFTomador.Contains(TextoBusqueda)).ToList(); rlcs = this.vp_liquidacionescompaniasrecibos.Where(x => x.CodigoRecibo.Contains(TextoBusqueda) || x.NumeroPoliza.Contains(TextoBusqueda) || x.Tomador.Contains(TextoBusqueda) || x.Matricula.Contains(TextoBusqueda) || x.CIFTomador.Contains(TextoBusqueda)).ToList(); rlcds = this.vp_liquidacionescompaniasrecibos_devueltos.Where(x => x.CodigoRecibo.Contains(TextoBusqueda) || x.NumeroPoliza.Contains(TextoBusqueda) || x.Tomador.Contains(TextoBusqueda) || x.Matricula.Contains(TextoBusqueda) || x.CIFTomador.Contains(TextoBusqueda)).ToList(); } else { rlas = this.vp_liquidacionesagentesrecibos.Where(x => x.NumeroRecibo == TextoBusqueda || x.NumeroPoliza == TextoBusqueda || x.CodigoRecibo == TextoBusqueda).ToList(); rlcs = this.vp_liquidacionescompaniasrecibos.Where(x => x.NumeroRecibo == TextoBusqueda || x.NumeroPoliza == TextoBusqueda || x.CodigoRecibo == TextoBusqueda).ToList(); rlcds = this.vp_liquidacionescompaniasrecibos_devueltos.Where(x => x.NumeroRecibo == TextoBusqueda || x.NumeroPoliza == TextoBusqueda || x.CodigoRecibo == TextoBusqueda).ToList(); } } else { var hoy = DateOnly.FromDateTime(DateTime.Now); var iqrlas = this.vp_liquidacionesagentesrecibos.AsQueryable(); if (!IncluirBajas) iqrlas = iqrlas.Where(x => x.FechaBaja == null && x.FechaVencimiento >= hoy); if (FechaInicio.HasValue) iqrlas = iqrlas.Where(x => x.FechaEfecto >= FechaInicio); if (FechaFin.HasValue) iqrlas = iqrlas.Where(x => x.FechaEfecto <= FechaFin); if (!string.IsNullOrEmpty(TextoBusqueda)) iqrlas = iqrlas.Where("Tomador.Contains(@0) or NumeroPoliza.Contains(@0) or CodigoRecibo.Contains(@0) or CIFTomador.Contains(@0)", new object[] { TextoBusqueda }); rlas = iqrlas.ToList(); var iqrlcs = this.vp_liquidacionescompaniasrecibos.AsQueryable(); if (!IncluirBajas) iqrlcs = iqrlcs.Where(x => x.FechaBaja == null && x.FechaVencimiento >= hoy); if (FechaInicio.HasValue) iqrlcs = iqrlcs.Where(x => x.FechaEfecto >= FechaInicio); if (FechaFin.HasValue) iqrlcs = iqrlcs.Where(x => x.FechaEfecto <= FechaFin); if (!string.IsNullOrEmpty(TextoBusqueda)) iqrlcs = iqrlcs.Where("Tomador.Contains(@0) or NumeroPoliza.Contains(@0) or CodigoRecibo.Contains(@0) or CIFTomador.Contains(@0)", new object[] { TextoBusqueda }); rlcs = iqrlcs.ToList(); var iqrlcds = this.vp_liquidacionescompaniasrecibos_devueltos.AsQueryable(); if (!IncluirBajas) iqrlcds = iqrlcds.Where(x => x.FechaBaja == null && x.FechaVencimiento >= hoy); if (FechaInicio.HasValue) iqrlcds = iqrlcds.Where(x => x.FechaEfecto >= FechaInicio); if (FechaFin.HasValue) iqrlcds = iqrlcds.Where(x => x.FechaEfecto <= FechaFin); if (!string.IsNullOrEmpty(TextoBusqueda)) iqrlcds = iqrlcds.Where("Tomador.Contains(@0) or NumeroPoliza.Contains(@0) or CodigoRecibo.Contains(@0) or CIFTomador.Contains(@0)", new object[] { TextoBusqueda }); rlcds = iqrlcds.ToList(); } var result = (from x in rs join lqc in rlcs on x.idRecibo equals lqc.idRecibo into glqc from lqc in glqc.DefaultIfEmpty() join lqcd in rlcds on x.idRecibo equals lqcd.idRecibo into glqcd from lqcd in glqcd.DefaultIfEmpty() join lqa in rlas on x.idRecibo equals lqa.idRecibo into glqa from lqa in glqa.DefaultIfEmpty() select new ve_recibos { idRecibo = x.idRecibo, idPoliza = x.idPoliza, FechaFacturacion = x.FechaFacturacion, FechaPago = x.FechaPago, CodigoRecibo = x.CodigoRecibo, Tomador = x.Tomador, CIFTomador = x.CIFTomador, Telefono1Tomador = x.Telefono1Tomador, Telefono2Tomador = x.Telefono2Tomador, NumeroPoliza = x.NumeroPoliza, Matricula = x.Matricula, FechaEfecto = x.FechaEfecto, FechaRecepcionCia = x.FechaRecepcionCia, FechaVencimiento = x.FechaVencimiento, FechaRemesa = x.idRemesa.HasValue ? x.FechaRemesa : null, Compania = x.Compania, Agente = x.Agente, SubAgente = x.SubAgente, Ramo = x.Ramo, FechaExpedicion = x.FechaExpedicion, BienesAsegurados = x.BienesAsegurados, FechaBaja = x.FechaBaja, FechaDevolucionBanco = x.FechaDevolucionBanco, CausaBaja = x.CausaBaja, TipoRecibo = x.TipoRecibo, TipoPago = x.TipoPago, PrimaNeta = x.PrimaNeta, BonificacionORecargo = x.BonificacionORecargo, Consorcio = x.Consorcio, Impuesto = x.Impuesto, RecargoExterno = x.RecargoExterno, TotalRecibo = x.TotalRecibo, ComisionReciboPrimaNeta = x.ComisionReciboPrimaNeta, PorcentajeReciboPrimaNeta = x.PorcentajeReciboPrimaNeta, TotalComision = x.TotalComision, SobreComision = x.Sobrecomision, ComisionPrevista = x.ComisionPrevista, PorcentajeComisionAgente = x.PorcentajeComisionAgente, ComisionAgente = x.ComisionAgente, ComisionAsegasaPrimaNeta = x.ComisionAsegasaPrimaNeta, AsegasaRecargoExterno = x.AsegasaRecargoExterno, AsegasaComisionConsorcio = x.AsegasaComisionConsorcio, AsegasaComisionTotal = x.AsegasaComisionTotal, idSituacion = x.idSituacion, Observaciones = x.Observaciones, ObservacionesPoliza = x.ObservacionesPoliza, FechaLiquidacionCia = lqc != null ? lqc.FechaLiquidacionCia : null, FechaLiquidacionCiaDevuelto = lqcd != null ? lqcd.FechaLiquidacionDevueltoCia : null, FechaLiquidacionAgente = lqa != null ? lqa.FechaLiquidacionAgente : null }).ToList(); return result; } } }