using AutoMapper; using Gestor.Common.Helpers; using Gestor.Infrastructure.Entities.Generic; using Gestor.Infrastructure.Entities.Seguros; using Gestor.Infrastructure.Helpers; using Gestor.Infrastructure.Mappers; using Gestor.Infrastructure.Repository.Generic; using Gestor.Infrastructure.Repository.Interface; using Gestor.Infrastructure.UnitOfWork.Generic; using Gestor.Model.Common; using Gestor.Model.Domain.Aggilizador; using Gestor.Model.Domain.Common; using Gestor.Model.Domain.Generic; using Gestor.Model.Domain.Relatorios; using Gestor.Model.Domain.Relatorios.Fechamento; using Gestor.Model.Domain.Seguros; using Gestor.Model.License; using Gestor.Model.Validation; using NHibernate; using NHibernate.Connection; using NHibernate.Impl; using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Runtime.CompilerServices; using System.Threading.Tasks; namespace Gestor.Infrastructure.Repository.Logic { public class DocumentoRepository : GenericRepository, IDocumentoRepository, IGenericRepository { private readonly GenericUnitOfWork _unitOfWork; private const string _commandoDocumento = "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE "; private const string _comandoVendedores = "SELECT DISTINCT vp.IDPARCELA, vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor, p.idsubtipo FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento LEFT OUTER JOIN parcela p on p.idparcela = vp.idparcela WHERE "; private const string _comandoArquivo = "SELECT DISTINCT a.idnewarquivodigital, a.descricao, ISNULL(s.Status ,0) as Status, s.assinado, s.DocumentoId, s.id, s.UsuarioId, s.Enviado FROM newarquivodigital a LEFT OUTER JOIN ArquivoParaAssinatura s on s.IndiceId = a.idnewarquivodigital WHERE "; private const string ComandoEndereco = "SELECT DISTINCT idcliend, cep, cidade, uf as estado, idcliente FROM cliendereco WHERE (ORDEM = '1' OR PADRAO = '1') "; private const string ComandoTelefone = "SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 "; private const string ComandoEmail = "SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') "; public DocumentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) { this._unitOfWork = unitOfWork; } public bool AtualizarNumero(long id, string numero, string endosso, int tipoDocumento) { DocumentoDb documentoDb = base.FindEntityById(id); if (documentoDb == null) { return false; } if (!documentoDb.Emissao.HasValue) { return true; } if (tipoDocumento == 0) { documentoDb.Apolice = numero; } else if (tipoDocumento == 1) { documentoDb.Apolice = numero; documentoDb.Endosso = endosso; } base.Merge(documentoDb); return true; } public List Auditoria(Filtros filtro) { List documentos; object connection; string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", from v in filtro.Status select v), ")")); string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", from v in filtro.Negocio select v), ")")); string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", from v in filtro.Seguradoras select v), ")")); string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", from v in filtro.Ramos select v), ")")); string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", from v in filtro.Produtos select v), ")")); string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", from v in filtro.Vendedores select v), ")")); string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", from v in filtro.TipoVendedor select v), ")")); string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", from v in filtro.Estipulantes select v), ")")); string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); DataTable dataTable = new DataTable(); DataTable dataTable1 = new DataTable(); DataTable dataTable2 = new DataTable(); DataTable dataTable3 = new DataTable(); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandTimeout = 15000; Auxiliar.CriarAuxiliar(sqlCommand, false); string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.datacontrole, d.idstatus, d.pasta, d.n_parc, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente ", str6, " WHERE (d.excluido IS NULL OR d.excluido = 0) "); string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; string str12 = "SELECT DISTINCT vp.idparcela, vp.iddocumento as id, ISNULL(vp.vlrcomiss, 0) as recebida, vp.idsubtipo, vp.datarec as recebimento FROM parcela vp WHERE 1=1 "; string str13 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL "; sqlCommand.CommandText = string.Format("{0} {1} AND d.vigencia1 >= '{2:yyyy-MM-dd}' AND d.vigencia1 <= '{3:yyyy-MM-dd}' AND d.tiporecebimento = 1 {4} {5} {6} {7} {8} {9} {10}", new object[] { str9, str8, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5 }); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } if (dataTable.Rows.Count != 0) { string str14 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); sqlCommand.CommandText = string.Concat(str12, (filtro.ParcelasEspeciais.Any((FiltroTipoParcela x) => x.Selecionado) ? string.Concat(" AND vp.idsubtipo IN (1,", string.Join(",", from x in filtro.ParcelasEspeciais where x.Selecionado select x into v select (int)v.Tipo), ")") : " AND vp.idsubtipo = 1 "), str14); using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) { sqlDataAdapter1.SelectCommand = sqlCommand; sqlDataAdapter1.Fill(dataTable1); } string str15 = (dataTable.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null) ? string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")") : ""); DataTable dataTable4 = new DataTable(); sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str15, " ", str5 }); using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) { sqlDataAdapter2.SelectCommand = sqlCommand; sqlDataAdapter2.Fill(dataTable4); } List dataRows3 = new List(); foreach (DataRow row in dataTable.Rows) { string str16 = string.Format("id = {0}", row["id"]); DataRow[] dataRowArray = dataTable1.Select(str16); decimal num = Math.Round(((row.Field("liquido") + (row.Field("adinacomiss") == "1" ? row.Field("liquido") : decimal.Zero)) * row.Field("comissao")) * new decimal(1, 0, 0, false, 2), 2); decimal num1 = ((IEnumerable)dataRowArray).Sum((DataRow x) => x.Field("recebida")); decimal? tolerancia = Auxiliar.Seguradoras.First((Seguradora p) => p.Id == row.Field("idseguradora")).Tolerancia; if ((num - num1) > tolerancia.GetValueOrDefault()) { if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) { continue; } string str17 = string.Format("idcontrole = {0}", row["idcontrole"]); DataRow[] dataRowArray1 = dataTable4.Select(str17); if (dataRowArray1.Length == 0) { continue; } row["idvendedor"] = dataRowArray1[0][1]; } else { dataRows3.Add(row); } } dataRows3.ForEach((DataRow x) => dataTable.Rows.Remove(x)); if (dataTable.Rows.Count != 0) { str14 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); sqlCommand.CommandText = string.Concat(str11, " ", str14); using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) { sqlDataAdapter3.SelectCommand = sqlCommand; sqlDataAdapter3.Fill(dataTable2); } string str18 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); sqlCommand.CommandText = string.Concat(str13, " ", str18); using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) { sqlDataAdapter4.SelectCommand = sqlCommand; sqlDataAdapter4.Fill(dataTable3); goto Label0; } } else { documentos = new List(); } } else { documentos = new List(); } } } return documentos; Label0: return dataTable.AsEnumerable().ToList().Select((DataRow x) => { Func func2 = null; Documento documento = new Documento() { Id = x.Field("id"), Controle = new Controle() { IdEmpresa = x.Field("idempresa"), Cliente = new Cliente() { Id = x.Field("idcliente"), Nome = x.Field("cliente"), IdEmpresa = x.Field("idempresa"), Pasta = x.Field("pastacliente"), MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) }, Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), AssistenciaId = x.Field("AssistenciaId") }, TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela), AdicionalComiss = x.Field("adinacomiss") == "1", Apolice = x.Field("apolice"), Endosso = x.Field("endosso"), Comissao = x.Field("comissao"), Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), PremioLiquido = x.Field("liquido"), PremioTotal = x.Field("total"), PremioAdicional = x.Field("adicional"), Vigencia2 = x.Field("vigenciafinal") }; DateTime? nullable = x.Field("vigenciainicial"); documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { List list = dataTable2.AsEnumerable().ToList(); Func u003cu003e9_32 = func2; if (u003cu003e9_32 == null) { Func func = (DataRow d) => d.Field("id") == x.Field("id"); Func func1 = func; func2 = func; u003cu003e9_32 = func1; } IEnumerable dataRows = list.Where(u003cu003e9_32); Func u003cu003e9_4033 = DocumentoRepository.u003cu003ec.u003cu003e9__40_33; if (u003cu003e9_4033 == null) { u003cu003e9_4033 = (DataRow d) => d.Field("idvendedor"); DocumentoRepository.u003cu003ec.u003cu003e9__40_33 = u003cu003e9_4033; } return dataRows.Select(u003cu003e9_4033).ToList().Contains(v.Id); }).ToList(); documento.Tipo = x.Field("tipo"); IEnumerable dataRows1 = from p in dataTable1.AsEnumerable().ToList() where p.Field("id") == x.Field("id") select p; Func u003cu003e9_4025 = DocumentoRepository.u003cu003ec.u003cu003e9__40_25; if (u003cu003e9_4025 == null) { u003cu003e9_4025 = (DataRow p) => new Parcela() { Id = p.Field("idparcela"), ValorComissao = p.Field("recebida"), DataRecebimento = p.Field("recebimento"), SubTipo = (p.Field("idsubtipo") == null ? SubTipo.ParcelaNormal : (SubTipo)Enum.Parse(typeof(SubTipo), p.Field("idsubtipo").ToString())) }; DocumentoRepository.u003cu003ec.u003cu003e9__40_25 = u003cu003e9_4025; } documento.Parcelas = new ObservableCollection(dataRows1.Select(u003cu003e9_4025).ToList()); documento.DataControle = x.Field("datacontrole"); documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); IEnumerable dataRows2 = from i in dataTable3.AsEnumerable().ToList() where i.Field("idcontrole") == x.Field("idcontrole") select i; Func u003cu003e9_4028 = DocumentoRepository.u003cu003ec.u003cu003e9__40_28; if (u003cu003e9_4028 == null) { u003cu003e9_4028 = (DataRow i) => new Item() { Id = i.Field("iditem"), Descricao = i.Field("descricao") }; DocumentoRepository.u003cu003ec.u003cu003e9__40_28 = u003cu003e9_4028; } documento.ItensAtivo = new List(dataRows2.Select(u003cu003e9_4028).ToList()); documento.Pasta = x.Field("Pasta"); documento.NumeroParcelas = (x.Field("n_parc") != null ? decimal.Parse(x.Field("n_parc").ToString()) : decimal.Zero); return documento; }).ToList(); } private async Task> BuscaDocumentosPorCondicao(Filtros filtro, List condicao, bool buscaAssinaturas) { NegocioCorretora fieldValue; Predicate predicate; bool flag; object connection; bool count; string str; object vendedor; bool count1; bool flag1; List itensAtivo; object produto; object obj; object statu; object banco; List statusDocumentoAssinados; bool flag2; StatusAssinatura statusAssinatura; NegocioCorretora negocioCorretora; bool count2; bool count3; Documento vendedorParcelas; Documento fieldValue1; Predicate predicate1 = null; Predicate predicate2 = null; Predicate predicate3 = null; Predicate predicate4 = null; Predicate predicate5 = null; List documentos = new List(); SqlQueryCondition sqlQueryCondition = condicao.CreateParameters(0); Vendedor vendedor1 = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { if (v.IdEmpresa != (filtro.IdEmpresa == 0 ? (long)1 : filtro.IdEmpresa)) { return false; } return v.Corretora; }); using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) { SessionFactoryImpl sessionFactoryImpl = sessionFactory; if (sessionFactoryImpl != null) { connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { bool flag3 = await this.ExisteTabelasAssinatura(); bool flag4 = flag3; using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandTimeout = 1000; string str1 = "SELECT d.IDDOCUMENTO IdDocumento,c.IDCONTROLE IdControle,c.IDEMPRESA IdEmpresa,c.IDCLIENTE IdCliente,clie.NOME NomeCliente,clie.CGCCPF DocumentoCliente,clie.PASTA PastaCliente,clie.MalaDireta MalaDireta,cm.idclimail IdEmail,cm.email,ct.idclitelefone IdTelefone,ct.ddd Prefixo,ct.fone Numero,c.IDRAMO IdRamo,r.NOME NomeRamo,c.IDCIASEG IdCiaSeg,cia.NOME NomeCia,cia.NomeSocial NomeSocialCia,c.IDPRODUTO IdProduto,pr.NOME NomeProduto,d.idestipulante IdEstipulante, d.idestipulante2 IdEstipulante2, d.idestipulante3 IdEstipulante3, d.idestipulante4 IdEstipulante4, d.idestipulante5 IdEstipulante5, e.nome NomeEstipulante,d.idstatus IdStatus,s.NOME NomeStatus,vp.idtipovendedor IdTipoVendedor,vp.VREP PorcentagemRepasse,vp.idvendedor IdVendedor,v.NOME NomeVendedor,tv.DESCRICAO DescricaoTipovendedor,d.PROPOSTA Proposta,d.CONTRATO Apolice,d.apoconferida ApoliceConferida,d.PEDADIT PropostaEndosso,d.ADITAMENTO Endosso,d.ADINACOMIS AdicionalComissao,d.COM01 Comissao,d.idnegocio Negocio,d.NegocioCorretora NegocioCorretora,d.tiporecebimento TipoRecebimento,d.TIPO Tipo,d.PR_LIQ PremioLiquido,d.PR_TOTAL PremioTotal,d.PR_ADIC PremioAdicional,d.N_PARC NumeroParcelas,d.VIGENCIA1 VigenciaInicial,d.VIGENCIA2 VigenciaFinal,d.EMISSAO Emissao,d.REMESSA Remessa,d.SITUACAO Situacao,d.datacontrole DataControleDocumento,d.propassinada PropostaAssinada,d.PASTA PastaDocumento,d.CRI_DATA DataCriacao,d.idbanco IdBanco,b.NOMEBANCO NomeBanco,d.AGENCIA Agencia,d.conta Conta FROM documento d INNER JOIN controle c ON c.IDCONTROLE = d.IDCONTROLE INNER JOIN cliente clie ON clie.IDCLIENTE = c.IDCLIENTE INNER JOIN ramo r ON r.IDRAMO = c.IDRAMO INNER JOIN ciaseg cia ON cia.IDCIASEG = c.IDCIASEG LEFT JOIN codigobanco b ON b.IDCODIGOBANCO = d.IDBANCO LEFT JOIN produto pr ON pr.IDPRODUTO = c.IDPRODUTO LEFT JOIN estipulante e ON e.idestipulante = d.idestipulante LEFT JOIN status s ON s.idstatus = d.idstatus LEFT JOIN vendedorparcela vp ON vp.IDDOCUMENTO = d.IDDOCUMENTO LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN tipovendedor tv on tv.idtipovendedor = vp.idtipovendedor LEFT JOIN clitelefone ct ON ct.IDCLIENTE = c.IDCLIENTE LEFT JOIN parcela p ON p.idparcela = vp.idparcela LEFT JOIN climail cm ON cm.IDCLIENTE = c.IDCLIENTE WHERE "; sqlCommand.CommandText = string.Concat(str1, " ", sqlQueryCondition.Condicao, " ORDER BY d.IDDOCUMENTO,d.IDCONTROLE,vp.idtipovendedor,vp.IDVENDEDOR"); sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { while (true) { if (!await sqlDataReader.ReadAsync()) { break; } TipoSeguro tipoSeguro = sqlDataReader.GetFieldValue("Situacao", true, true); if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora")) { fieldValue = sqlDataReader.GetFieldValue("NegocioCorretora", true, true); } else { flag3 = tipoSeguro == TipoSeguro.Renovacao; if (flag3) { flag3 = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio"); } negocioCorretora = (!flag3 || !(sqlDataReader.GetFieldValue("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); fieldValue = negocioCorretora; } NegocioCorretora negocioCorretora1 = fieldValue; List negocio = filtro.Negocio; if (negocio != null) { count = negocio.Count > 0; } else { count = false; } if (!count || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora1)) { List estipulantes = new List(); sqlDataReader.GetFieldValue("idestipulante", true, true); if (sqlDataReader.GetFieldValue("idestipulante", true, true) != 0) { List estipulantes1 = estipulantes; Estipulante nome = new Estipulante(); List estipulantes2 = Auxiliar.Estipulantes; Predicate predicate6 = predicate1; if (predicate6 == null) { Predicate predicate7 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante", true, true); predicate = predicate7; predicate1 = predicate7; predicate6 = predicate; } nome.Nome = estipulantes2.Find(predicate6).Nome; estipulantes1.Add(nome); } sqlDataReader.GetFieldValue("idestipulante2", true, true); if (sqlDataReader.GetFieldValue("idestipulante2", true, true) != 0) { List estipulantes3 = estipulantes; Estipulante nome1 = new Estipulante(); List estipulantes4 = Auxiliar.Estipulantes; Predicate predicate8 = predicate2; if (predicate8 == null) { Predicate predicate9 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante2", true, true); predicate = predicate9; predicate2 = predicate9; predicate8 = predicate; } nome1.Nome = estipulantes4.Find(predicate8).Nome; estipulantes3.Add(nome1); } sqlDataReader.GetFieldValue("idestipulante3", true, true); if (sqlDataReader.GetFieldValue("idestipulante3", true, true) != 0) { List estipulantes5 = estipulantes; Estipulante estipulante1 = new Estipulante(); List estipulantes6 = Auxiliar.Estipulantes; Predicate predicate10 = predicate3; if (predicate10 == null) { Predicate predicate11 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante3", true, true); predicate = predicate11; predicate3 = predicate11; predicate10 = predicate; } estipulante1.Nome = estipulantes6.Find(predicate10).Nome; estipulantes5.Add(estipulante1); } sqlDataReader.GetFieldValue("idestipulante4", true, true); if (sqlDataReader.GetFieldValue("idestipulante4", true, true) != 0) { List estipulantes7 = estipulantes; Estipulante nome2 = new Estipulante(); List estipulantes8 = Auxiliar.Estipulantes; Predicate predicate12 = predicate4; if (predicate12 == null) { Predicate predicate13 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante4", true, true); predicate = predicate13; predicate4 = predicate13; predicate12 = predicate; } nome2.Nome = estipulantes8.Find(predicate12).Nome; estipulantes7.Add(nome2); } sqlDataReader.GetFieldValue("idestipulante5", true, true); if (sqlDataReader.GetFieldValue("idestipulante5", true, true) != 0) { List estipulantes9 = estipulantes; Estipulante estipulante2 = new Estipulante(); List estipulantes10 = Auxiliar.Estipulantes; Predicate predicate14 = predicate5; if (predicate14 == null) { Predicate predicate15 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante5", true, true); predicate = predicate15; predicate5 = predicate15; predicate14 = predicate; } estipulante2.Nome = estipulantes10.Find(predicate14).Nome; estipulantes9.Add(estipulante2); } if (estipulantes.Count > 0) { List estipulantes11 = estipulantes; str = string.Join(" | ", from estipulante in estipulantes11 select estipulante.Nome); } else { str = ""; } string str2 = str; long num = sqlDataReader.GetFieldValue("IdDocumento", true, true); vendedorParcelas = documentos.Find((Documento d) => d.Id == num); if (vendedorParcelas == null) { long num1 = sqlDataReader.GetFieldValue("IdControle", true, true); long fieldValue2 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); Documento documento1 = documentos.Find((Documento p) => p.Controle.Id == num1); if (documento1 != null) { itensAtivo = documento1.ItensAtivo; } else { itensAtivo = null; } List items = itensAtivo; if (items == null) { items = await this.BuscaItemsPorIdControle(num1); } List items1 = items; fieldValue1 = new Documento() { Id = num }; Documento documento2 = fieldValue1; Controle controle = new Controle() { Id = num1, IdEmpresa = fieldValue2 }; Controle controle1 = controle; Cliente cliente = new Cliente() { Id = sqlDataReader.GetFieldValue("IdCliente", true, true), Nome = sqlDataReader.GetFieldValue("NomeCliente", true, true), Documento = sqlDataReader.GetFieldValue("DocumentoCliente", true, true), Pasta = sqlDataReader.GetFieldValue("PastaCliente", true, true) }; bool? fieldValue3 = sqlDataReader.GetFieldValue("MalaDireta", true, true); cliente.MalaDireta = new bool?(fieldValue3.GetValueOrDefault(true)); ObservableCollection observableCollection = new ObservableCollection(); ClienteTelefone clienteTelefone = new ClienteTelefone() { Id = sqlDataReader.GetFieldValue("IdTelefone", true, true), Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), Numero = sqlDataReader.GetFieldValue("Numero", true, true) }; observableCollection.Add(clienteTelefone); cliente.Telefones = observableCollection; ObservableCollection observableCollection1 = new ObservableCollection(); ClienteEmail clienteEmail = new ClienteEmail() { Id = sqlDataReader.GetFieldValue("IdEMail", true, true), Email = sqlDataReader.GetFieldValue("Email", true, true) }; observableCollection1.Add(clienteEmail); cliente.Emails = observableCollection1; controle1.Cliente = cliente; Controle controle2 = controle; Ramo ramo = new Ramo() { Id = sqlDataReader.GetFieldValue("IdRamo", true, true), Nome = sqlDataReader.GetFieldValue("NomeRamo", true, true) }; controle2.Ramo = ramo; Controle controle3 = controle; Seguradora seguradora = new Seguradora() { Id = sqlDataReader.GetFieldValue("IdCiaSeg", true, true), Nome = sqlDataReader.GetFieldValue("NomeCia", true, true), NomeSocial = sqlDataReader.GetFieldValue("NomeSocialCia", true, true) }; controle3.Seguradora = seguradora; Controle controle4 = controle; flag3 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdProduto"); Controle controle5 = controle4; if (flag3) { produto = null; } else { produto = new Gestor.Model.Domain.Seguros.Produto(); ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("IdProduto", true, true); ((Gestor.Model.Domain.Seguros.Produto)produto).Nome = sqlDataReader.GetFieldValue("NomeProduto", true, true); } controle5.Produto = (Gestor.Model.Domain.Seguros.Produto)produto; documento2.Controle = controle; Documento documento3 = fieldValue1; bool flag5 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdEstipulante"); Documento documento4 = documento3; if (flag5) { obj = null; } else { obj = new Estipulante(); ((DomainBase)obj).Id = sqlDataReader.GetFieldValue("IdEstipulante", true, true); ((Estipulante)obj).Nome = sqlDataReader.GetFieldValue("NomeEstipulante", true, true); } documento4.Estipulante1 = (Estipulante)obj; fieldValue1.Estipulantes = str2; Documento documento5 = fieldValue1; bool flag6 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdStatus"); Documento documento6 = documento5; if (flag6) { statu = null; } else { statu = new Status(); ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("IdStatus", true, true); ((Status)statu).Nome = sqlDataReader.GetFieldValue("NomeStatus", true, true); } documento6.Status = (Status)statu; fieldValue1.TipoRecebimento = new TipoRecebimento?(sqlDataReader.GetFieldValue("TipoRecebimento", true, true)); fieldValue1.Tipo = sqlDataReader.GetFieldValue("Tipo", true, true); fieldValue1.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); fieldValue1.Situacao = tipoSeguro; Documento valueOrDefault = fieldValue1; fieldValue3 = sqlDataReader.GetFieldValue("ApoliceConferida", true, true); valueOrDefault.ApoliceConferida = fieldValue3.GetValueOrDefault(); Documento valueOrDefault1 = fieldValue1; fieldValue3 = sqlDataReader.GetFieldValue("PropostaAssinada", true, true); valueOrDefault1.PropostaAssinada = fieldValue3.GetValueOrDefault(); fieldValue1.Proposta = sqlDataReader.GetFieldValue("Proposta", true, true); fieldValue1.Apolice = sqlDataReader.GetFieldValue("Apolice", true, true); fieldValue1.PropostaEndosso = sqlDataReader.GetFieldValue("PropostaEndosso", true, true); fieldValue1.Endosso = sqlDataReader.GetFieldValue("Endosso", true, true); fieldValue1.Comissao = sqlDataReader.GetFieldValue("Comissao", true, true); fieldValue1.PremioLiquido = sqlDataReader.GetFieldValue("PremioLiquido", true, true); Documento valueOrDefault2 = fieldValue1; fieldValue3 = sqlDataReader.GetFieldValue("AdicionalComissao", true, true); valueOrDefault2.AdicionalComiss = fieldValue3.GetValueOrDefault(); fieldValue1.PremioAdicional = sqlDataReader.GetFieldValue("PremioAdicional", true, true); fieldValue1.PremioTotal = sqlDataReader.GetFieldValue("PremioTotal", true, true); fieldValue1.NumeroParcelas = sqlDataReader.GetFieldValue("NumeroParcelas", true, true); fieldValue1.Vigencia1 = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); fieldValue1.Vigencia2 = sqlDataReader.GetFieldValue("VigenciaFinal", true, true); fieldValue1.Emissao = sqlDataReader.GetFieldValue("Emissao", true, true); fieldValue1.Remessa = sqlDataReader.GetFieldValue("Remessa", true, true); fieldValue1.DataControle = sqlDataReader.GetFieldValue("DataControleDocumento", true, true); fieldValue1.DataCriacao = sqlDataReader.GetFieldValue("DataCriacao", true, true); fieldValue1.Pasta = sqlDataReader.GetFieldValue("PastaDocumento", true, true); Documento documento7 = fieldValue1; flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdBanco"); Documento documento8 = documento7; if (flag) { banco = null; } else { banco = new Banco(); ((Banco)banco).Id = sqlDataReader.GetFieldValue("IdBanco", true, true); ((Banco)banco).Nome = sqlDataReader.GetFieldValue("NomeBanco", true, true); } documento8.Banco = (Banco)banco; fieldValue1.Agencia = sqlDataReader.GetFieldValue("Agencia", true, true); fieldValue1.Conta = sqlDataReader.GetFieldValue("Conta", true, true); fieldValue1.ItensAtivo = items1; vendedorParcelas = fieldValue1; documento2 = null; controle4 = null; controle = null; documento3 = null; documento5 = null; documento7 = null; fieldValue1 = null; if (flag4 & buscaAssinaturas) { List statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(vendedorParcelas.Id); string str3 = (vendedorParcelas.Tipo == 0 ? "PROPOSTA" : "PEDIDO DE ENDOSSO"); statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => { if (a.Documento.ToUpper() == str3 || a.Documento.ToUpper().Contains(str3)) { a.Selecionado = true; } }); List statusDocumentoAssinados2 = statusDocumentoAssinados1; StatusDocumentoAssinado statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault((StatusDocumentoAssinado a) => a.Selecionado); Documento documento9 = vendedorParcelas; if (statusDocumentoAssinados1 == null || statusDocumentoAssinados1.Count <= 0) { statusDocumentoAssinados = null; } else { statusDocumentoAssinados = statusDocumentoAssinados1; } documento9.Assinaturas = statusDocumentoAssinados; Documento documento10 = vendedorParcelas; flag2 = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status == StatusAssinatura.Assinado : false); documento10.AssinadaSiggner = flag2; Documento documento11 = vendedorParcelas; statusAssinatura = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status : StatusAssinatura.NaoEnviado); documento11.StatusAssinatura = statusAssinatura; } documentos.Add(vendedorParcelas); items1 = null; } if (vendedorParcelas.VendedorPrincipal == null || vendedorParcelas.VendedorPrincipal.Id == vendedor1.Id) { fieldValue1 = vendedorParcelas; flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdVendedor"); Documento documento12 = fieldValue1; if (flag) { vendedor = null; } else { vendedor = new Vendedor(); ((DomainBase)vendedor).Id = sqlDataReader.GetFieldValue("IdVendedor", true, true); ((Vendedor)vendedor).Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true); } documento12.VendedorPrincipal = (Vendedor)vendedor; fieldValue1 = null; } if (vendedorParcelas.Controle.Cliente.Telefones != null) { long num2 = sqlDataReader.GetFieldValue("IdTelefone", true, true); if (vendedorParcelas.Controle.Cliente.Telefones.FirstOrDefault((ClienteTelefone t) => t.Id == num2) == null) { ObservableCollection telefones = vendedorParcelas.Controle.Cliente.Telefones; ClienteTelefone clienteTelefone1 = new ClienteTelefone() { Id = num2, Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), Numero = sqlDataReader.GetFieldValue("Numero", true, true) }; telefones.Add(clienteTelefone1); } } if (vendedorParcelas.Controle.Cliente.Emails != null) { long num3 = sqlDataReader.GetFieldValue("IdEmail", true, true); if (vendedorParcelas.Controle.Cliente.Emails.FirstOrDefault((ClienteEmail t) => t.Id == num3) == null) { ObservableCollection emails = vendedorParcelas.Controle.Cliente.Emails; ClienteEmail clienteEmail1 = new ClienteEmail() { Id = num3, Email = sqlDataReader.GetFieldValue("Email", true, true) }; emails.Add(clienteEmail1); } } List tipoVendedor = filtro.TipoVendedor; if (tipoVendedor != null) { count1 = tipoVendedor.Count > 0; } else { count1 = false; } if (!count1) { List vendedores = filtro.Vendedores; if (vendedores != null) { flag1 = vendedores.Count > 0; } else { flag1 = false; } if (!flag1) { if (vendedorParcelas.Pagamentos == null) { vendedorParcelas.Pagamentos = new List(); } long fieldValue4 = sqlDataReader.GetFieldValue("IdTipoVendedor", true, true); long num4 = sqlDataReader.GetFieldValue("IdVendedor", true, true); if (vendedorParcelas.Pagamentos.Find((VendedorParcela vps) => { if (vps.TipoVendedor.Id != fieldValue4) { return false; } return vps.Vendedor.Id == num4; }) == null) { List pagamentos = vendedorParcelas.Pagamentos; VendedorParcela vendedorParcela1 = new VendedorParcela() { PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue("PorcentagemRepasse", true, true)) }; TipoVendedor tipoVendedor1 = new TipoVendedor() { Id = fieldValue4, Descricao = sqlDataReader.GetFieldValue("DescricaoTipovendedor", true, true) }; vendedorParcela1.TipoVendedor = tipoVendedor1; Vendedor vendedor2 = new Vendedor() { Id = num4, Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true) }; vendedorParcela1.Vendedor = vendedor2; pagamentos.Add(vendedorParcela1); } } } str2 = null; vendedorParcelas = null; } } } } sqlCommand = null; List nums = filtro.TipoVendedor; if (nums != null) { count2 = nums.Count > 0; } else { count2 = false; } if (!count2) { List vendedores1 = filtro.Vendedores; if (vendedores1 != null) { count3 = vendedores1.Count > 0; } else { count3 = false; } if (!count3) { goto Label0; } } foreach (Documento documento13 in documentos) { vendedorParcelas = documento13; List vendedorParcelas1 = await this.BuscaVendedoresPorIdDocumento(documento13.Id, documento13.Controle.IdEmpresa); vendedorParcelas.Pagamentos = vendedorParcelas1; vendedorParcelas = null; } Label0: List documentos1 = documentos; documentos1.ForEach((Documento d) => { decimal? nullable2; decimal? porcentagemRepasse; d.Vendedores = ( from tipo in d.Pagamentos orderby tipo.TipoVendedor.Id select tipo into v select v.Vendedor).ToList(); Documento documento = d; VendedorParcela vendedorParcela = d.Pagamentos.FirstOrDefault((VendedorParcela p) => { long? nullable; long id = p.Vendedor.Id; Vendedor vendedorPrincipal = d.VendedorPrincipal; nullable = (vendedorPrincipal != null ? new long?(vendedorPrincipal.Id) : null); long? nullable1 = nullable; return id == nullable1.GetValueOrDefault() & nullable1.HasValue; }); if (vendedorParcela != null) { porcentagemRepasse = vendedorParcela.PorcentagemRepasse; } else { nullable2 = null; porcentagemRepasse = nullable2; } nullable2 = porcentagemRepasse; documento.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault()); }); } sqlConnection = null; } sessionFactory = null; List documentos2 = documentos; documentos = null; sqlQueryCondition = null; vendedor1 = null; return documentos2; } public async Task> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) { string str = "CAST(d.vigencia1 AS DATE)"; string referencia = filtro.Referencia; if (referencia == "EMISSÃO") { str = "CAST(d.emissao AS DATE)"; } else if (referencia == "TRANSMISSÃO PROPOSTA") { str = "CAST(d.remessa AS DATE)"; } else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") { str = "CAST(d.cri_data AS DATE)"; } List condicaos = this.CriaCondicaoDocumento(filtro, str); Condicao condicao = new Condicao() { Campo = "d.TipoRecebimento", Valores = 1.CriarValor() }; condicaos.Add(condicao); List condicaos1 = new List(); Condicao condicao1 = new Condicao() { Campo = "d.Excluido", Valores = null, Grupo = 1, Operacao = Operacao.Or }; condicaos1.Add(condicao1); Condicao condicao2 = new Condicao() { Campo = "d.Excluido", Valores = "0".CriarValor(), Grupo = 1, Operacao = Operacao.Or }; condicaos1.Add(condicao2); condicaos.AddRange(condicaos1); return await this.BuscaDocumentosPorCondicao(filtro, condicaos, buscaAssinaturas); } private async Task> BuscaFechamento(Filtros filtro) { NegocioCorretora negocioCorretora; bool count; object connection; long num; long num1; decimal num2; decimal num3; decimal num4; decimal num5; NegocioCorretora negocioCorretora1; bool flag; List fechamentos = new List(); string str2 = "CAST(d.vigencia1 AS DATE)"; string str3 = "CAST(f.vigenciai AS DATE)"; if (filtro.Referencia == "EMISSÃO") { str2 = "CAST(d.emissao AS DATE)"; str3 = "CAST(f.emissao AS DATE)"; } List condicaos = this.CriaCondicaoDocumento(filtro, str2); List condicaos1 = this.CriaCondicaoDocumento(filtro, str3); List condicaos2 = this.CriaCondicaoDocumento(filtro, "CAST(d.vigencia1 AS DATE)"); Condicao condicao = new Condicao() { Campo = "d.TipoRecebimento", Valores = 1.CriarValor() }; condicaos.Add(condicao); List condicaos3 = new List(); Condicao condicao1 = new Condicao() { Campo = "d.Excluido", Valores = null, Grupo = 1, Operacao = Operacao.Or }; condicaos3.Add(condicao1); Condicao condicao2 = new Condicao() { Campo = "d.Excluido", Valores = "0".CriarValor(), Grupo = 1, Operacao = Operacao.Or }; condicaos3.Add(condicao2); List condicaos4 = condicaos3; condicaos.AddRange(condicaos4); condicaos1.AddRange(condicaos4); condicaos2.AddRange(condicaos4); string str4 = ""; List tipoVendedor = filtro.TipoVendedor; if (tipoVendedor != null) { count = tipoVendedor.Count > 0; } else { count = false; } if (!count) { List vendedores = filtro.Vendedores; if (vendedores != null) { flag = vendedores.Count > 0; } else { flag = false; } if (flag) { goto Label1; } str4 = "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp"; goto Label0; } Label1: str4 = "INNER JOIN vendedorparcela vp ON d.iddocumento = vp.iddocumento"; Label0: SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); SqlQueryCondition sqlQueryCondition1 = condicaos1.CreateParameters(sqlQueryCondition.Parametros.Count); using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) { SessionFactoryImpl sessionFactoryImpl = sessionFactory; if (sessionFactoryImpl != null) { connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { Auxiliar.CriarAuxiliar(sqlCommand, false); string str5 = string.Concat("SELECT DISTINCT c.IdEmpresa, d.IdControle, d.IdDocumento Id, d.Pr_Total Total, d.Pr_liq Liquido, d.Pr_Adic Adicional, ISNULL(d.com01, 0.00) Comissao, ISNULL(d.adinacomis, '0') AdinaComis, c.IdRamo, c.IdCiaSeg, c.IdProduto, CAST(d.Tipo AS INTEGER) Tipo, d.IdEstipulante, d.IdNegocio, d.Situacao, d.NegocioCorretora, vp.IdVendedor FROM documento d INNER JOIN controle c ON c.IdControle = d.IdControle ", str4, " WHERE "); string str6 = string.Concat("SELECT DISTINCT c.IdEmpresa, d.IdControle, p.IdParcela Id, p.Valor Total, p.ValorLF Liquido, 0 Adicional, p.Comiss Comissao, '0' AdinaComis, c.IdRamo, c.IdCiaSeg, c.IdProduto, 2 Tipo, d.IdEstipulante, d.IdNegocio, d.Situacao, d.NegocioCorretora, vp.IdVendedor FROM fatura f INNER JOIN parcela p ON p.idparcela = f.idparcela INNER JOIN documento d ON d.iddocumento = p.iddocumento INNER JOIN controle c ON c.idcontrole = d.idcontrole ", str4, " WHERE "); sqlCommand.CommandTimeout = 1000; SqlCommand sqlCommand1 = sqlCommand; string[] strArrays = new string[] { str5, " ", sqlQueryCondition.Condicao, " UNION ", str6, " ", sqlQueryCondition1.Condicao }; sqlCommand1.CommandText = string.Concat(strArrays); sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); sqlCommand.Parameters.AddRange(sqlQueryCondition1.Parametros.ToArray()); using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { List fechamentos1 = new List(); decimal num6 = new decimal(); while (true) { if (!await sqlDataReader.ReadAsync()) { break; } bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdCiaSeg")); if (!flag1) { flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdRamo")); } if (!flag1) { long item = (long)sqlDataReader["IdEmpresa"]; long item1 = (long)sqlDataReader["IdCiaSeg"]; long item2 = (long)sqlDataReader["IdRamo"]; flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdEstipulante")); num = (flag1 ? (long)0 : (long)sqlDataReader["IdEstipulante"]); long num7 = num; flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdVendedor")); num1 = (flag1 ? (long)0 : (long)sqlDataReader["IdVendedor"]); long id = num1; flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Total")); num2 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Total"]); decimal num8 = num2; flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Liquido")); num3 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Liquido"]); decimal num9 = num3; flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Adicional")); num4 = (flag1 || sqlDataReader["AdinaComis"].ToString() == "0" ? decimal.Zero : (decimal)sqlDataReader["Adicional"]); decimal num10 = num4; flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Comissao")); num5 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Comissao"]); decimal num11 = num5; int item3 = (int)sqlDataReader["Tipo"]; if (!await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("negociocorretora"))) { negocioCorretora = (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), sqlDataReader["negociocorretora"].ToString()); } else { flag1 = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()) == TipoSeguro.Renovacao; if (flag1) { flag1 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio")); } negocioCorretora1 = (!flag1 || !(sqlDataReader["idnegocio"].ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); negocioCorretora = negocioCorretora1; } NegocioCorretora negocioCorretora2 = negocioCorretora; if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora2)) { if (id == 0) { id = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { if (v.IdEmpresa != item) { return false; } return v.Corretora; }).Id; } decimal num12 = (num9 + num10) * num11 * new decimal(1, 0, 0, false, 2); num6 += num8; for (int i = 0; i < 4; i++) { long num13 = (long)0; switch (i) { case 0: { num13 = item1; break; } case 1: { num13 = item2; break; } case 2: { num13 = num7; break; } case 3: { num13 = id; break; } } if (num13 != 0) { Fechamento fechamento4 = fechamentos1.FirstOrDefault((Fechamento a) => { if (a.Entidade != i) { return false; } return a.Id == num13; }); if (fechamento4 == null) { fechamento4 = new Fechamento(); } Fechamento fechamento5 = fechamento4; Fechamento premioTotal = fechamento5; premioTotal.PremioTotal = premioTotal.PremioTotal + num8; Fechamento premioLiquido = fechamento5; premioLiquido.PremioLiquido = premioLiquido.PremioLiquido + num9; Fechamento fechamento6 = fechamento5; fechamento6.Fechada = fechamento6.Fechada + num11; Fechamento gerada = fechamento5; gerada.Gerada = gerada.Gerada + num12; switch (item3) { case 0: { Fechamento apolice = fechamento5; apolice.Apolice = apolice.Apolice + 1; break; } case 1: { Fechamento endosso = fechamento5; endosso.Endosso = endosso.Endosso + 1; break; } case 2: { Fechamento fatura = fechamento5; fatura.Fatura = fatura.Fatura + 1; break; } } if (fechamento5.Id == 0) { fechamento5.Entidade = i; fechamento5.Id = num13; fechamentos1.Add(fechamento5); } } } } } } fechamentos1.ForEach((Fechamento f) => { string nome; string str; string nome1; string str1; switch (f.Entidade) { case 0: { Fechamento fechamento = f; Seguradora seguradora = Auxiliar.Seguradoras.Find((Seguradora s) => s.Id == f.Id); if (seguradora != null) { nome = seguradora.Nome; } else { nome = null; } fechamento.Nome = nome; break; } case 1: { Fechamento fechamento1 = f; Ramo ramo = Auxiliar.Ramos.Find((Ramo r) => r.Id == f.Id); if (ramo != null) { str = ramo.Nome; } else { str = null; } fechamento1.Nome = str; break; } case 2: { Fechamento fechamento2 = f; Estipulante estipulante = Auxiliar.Estipulantes.Find((Estipulante e) => e.Id == f.Id); if (estipulante != null) { nome1 = estipulante.Nome; } else { nome1 = null; } fechamento2.Nome = nome1; break; } case 3: { Fechamento fechamento3 = f; Vendedor vendedor = Auxiliar.Vendedores.Find((Vendedor v) => v.Id == f.Id); if (vendedor != null) { str1 = vendedor.Nome; } else { str1 = null; } fechamento3.Nome = str1; break; } } Fechamento fechada = f; fechada.Fechada = fechada.Fechada / f.Apolice + f.Fatura + f.Endosso; f.Mix = (f.PremioTotal * new decimal(100)) / num6; }); List fechamentos2 = fechamentos1; foreach (IGrouping nums in from g in fechamentos2 group g by g.Entidade) { await this.ContaRegistros(nums.Key, fechamentos1, filtro, condicaos2); await this.SomaComissaoPaga(nums.Key, fechamentos1, filtro, condicaos2); await this.SomaComissaoRecebida(nums.Key, fechamentos1, filtro, condicaos2); } fechamentos.AddRange(fechamentos1); fechamentos1 = null; } sqlDataReader = null; } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; List fechamentos3 = fechamentos; fechamentos = null; condicaos2 = null; return fechamentos3; } private async Task> BuscaItemsPorIdControle(long idControle) { object connection; List items = new List(); using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) { SessionFactoryImpl sessionFactoryImpl = sessionFactory; if (sessionFactoryImpl != null) { connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandTimeout = 1000; sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)"; sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle; using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { while (true) { if (!await sqlDataReader.ReadAsync()) { break; } List items1 = items; Item item = new Item() { Id = (long)sqlDataReader["iditem"], Descricao = sqlDataReader["descricao"].ToString() }; items1.Add(item); } } sqlDataReader = null; } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; List items2 = items; items = null; return items2; } public List BuscarDocumentoPorEstipulante(long id) { List list = ( from x in base.All() where x.Estipulante1.Id == id || x.Estipulante2.Id == id || x.Estipulante3.Id == id || x.Estipulante4.Id == id || x.Estipulante5.Id == id select x).ToList(); return ApplicationMapper.Mapper.Map, List>(list); } public List BuscarDocumentoPorStatus(long id) { List list = ( from x in base.All() where x.Status.Id == id select x).ToList(); return ApplicationMapper.Mapper.Map, List>(list); } public string BuscarLogAntigo(long id, string conn) { object connection; string str = ""; List condicaos = new List() { new Condicao() { Campo = "id", Valores = id.CriarValor() }, new Condicao() { Campo = "idname", Valores = "iddocumento".CriarValor() } }; this._unitOfWork.CriarAuxiliar(); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; string str1 = "oldbacklog"; if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog"; SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); sqlDataReader.Read(); string str2 = sqlDataReader["bdname"].ToString(); str1 = sqlDataReader["tabela"].ToString(); sqlDataReader.Close(); if (sqlConnection.Database != str2) { conn = conn.Replace(sqlConnection.Database, str2); } } } DataTable dataTable = new DataTable(); using (SqlConnection sqlConnection1 = new SqlConnection(conn)) { sqlConnection1.Open(); using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand()) { sqlCommand1.CommandTimeout = 15000; dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), ""); } } if (dataTable == null || dataTable.Rows.Count == 0) { return ""; } if (dataTable != null) { dataTable.AsEnumerable().OrderBy((DataRow x) => x.Field("idbacklog")).ToList().ForEach((DataRow x) => { str = string.Concat(new string[] { str, "
(", x.Field("data").ToString(), ") ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("idusuario")).Nome, "
" }); str = string.Concat(str, "", x.Field("historico").ToString().Replace(Environment.NewLine, "
"), ""); }); } return str; } public List BuscarPlanilhaCompletaProspeccao(List ids) { object connection; List nums = null; if (ids == null || ids.Count == 0) { return new List(); } DataTable dataTable = new DataTable(); DataTable dataTable1 = new DataTable(); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { Auxiliar.CriarAuxiliar(sqlCommand, false); for (List i = ids; i.Count > 0; i = nums) { List list = i.Take(2100).ToList(); string str1 = string.Concat(" AND va.idvenctoaleatorio IN (", string.Join(",", list), ")"); DataTable dataTable2 = new DataTable(); string str2 = string.Concat("SELECT DISTINCT * FROM venctoaleatorio va LEFT OUTER JOIN tarefa ta on va.idtarefa = ta.id WHERE 1=1 ", str1, ";"); sqlCommand.CommandText = str2 ?? ""; using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable2); } dataTable.Merge(dataTable2); nums = (list.Count < 2100 ? new List() : i.Except(list).ToList()); } } } if (dataTable.Rows.Count == 0) { return new List(); } List planilhaCompletas = new List(); dataTable.AsEnumerable().ToList().ForEach((DataRow x) => { DateTime? nullable; string str; DateTime? nullable1; DateTime? nullable2; PlanilhaCompleta planilhaCompletum = new PlanilhaCompleta() { NumeroApolice = "PROSPECÇÃO", Status = (x.Field("situacao") == null || !(x.Field("situacao").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("situacao").ToString()) ? null : (StatusProspeccao)Enum.Parse(typeof(StatusProspeccao), x.Field("situacao").ToString()).GetDescription()) }; DateTime? nullable3 = x.Field("finalcontrato"); if (nullable3.HasValue) { nullable = x.Field("finalcontrato"); } else { nullable3 = null; nullable = nullable3; } planilhaCompletum.VigenciaFinal = nullable; DataRow dataRow = dataTable1.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")); if (dataRow != null) { str = dataRow.Field("nome"); } else { str = null; } planilhaCompletum.Estipulante = str; planilhaCompletum.Vendedor = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")).Nome : null); planilhaCompletum.NomeCliente = x.Field("nome"); nullable3 = x.Field("dtnascimento"); if (nullable3.HasValue) { nullable1 = x.Field("dtnascimento"); } else { nullable3 = null; nullable1 = nullable3; } planilhaCompletum.NascimentoCliente = nullable1; planilhaCompletum.DocumentoCliente = x.Field("cpfcnpj"); planilhaCompletum.Prefixo1 = x.Field("ddd"); planilhaCompletum.Telefone1 = x.Field("fone"); planilhaCompletum.Prefixo2 = x.Field("ddd2"); planilhaCompletum.Telefone2 = x.Field("fone2"); planilhaCompletum.Email1 = x.Field("email"); planilhaCompletum.DescricaoItem = x.Field("item"); planilhaCompletum.ObsProspeccao = x.Field("obs"); planilhaCompletum.TipoProspeccao = x.Field("tipoprospeccao"); planilhaCompletum.TituloTarefa = x.Field("titulo"); planilhaCompletum.DescricaoTarefa = x.Field("descricao"); nullable3 = x.Field("agendamento"); if (nullable3.HasValue) { nullable2 = x.Field("agendamento"); } else { nullable3 = null; nullable2 = nullable3; } planilhaCompletum.AgendamentoTarefa = nullable2; planilhaCompletas.Add(planilhaCompletum); }); return planilhaCompletas; } private async Task> BuscaStatusAssinadosPorIdDocumento(long idDocumento) { object connection; DateTime? nullable; Usuario usuario1; Func func = null; List statusDocumentoAssinados = new List(); using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) { SessionFactoryImpl sessionFactoryImpl = sessionFactory; if (sessionFactoryImpl != null) { connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandTimeout = 1000; sqlCommand.CommandText = "SELECT a.idnewarquivodigital,a.descricao,ISNULL(s.Status ,3) status,s.assinado,a.iddocumento,s.id,s.usuarioid,s.enviado FROM newarquivodigital a LEFT JOIN ArquivoParaAssinatura s ON a.idnewarquivodigital = s.indiceid WHERE a.iddocumento = @documento AND (a.excluido = 0 OR a.excluido IS NULL)"; sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento; using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { while (true) { if (!await sqlDataReader.ReadAsync()) { break; } List statusDocumentoAssinados1 = statusDocumentoAssinados; StatusDocumentoAssinado statusDocumentoAssinado = new StatusDocumentoAssinado() { Id = (long)sqlDataReader["idnewarquivodigital"], Documento = sqlDataReader["descricao"].ToString(), Status = (StatusAssinatura)((int)sqlDataReader["status"]) }; StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado; bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("enviado")); StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado1; if (flag) { nullable = null; } else { nullable = new DateTime?((DateTime)sqlDataReader["enviado"]); } statusDocumentoAssinado2.Envio = nullable; StatusDocumentoAssinado statusDocumentoAssinado3 = statusDocumentoAssinado; bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("usuarioid")); StatusDocumentoAssinado statusDocumentoAssinado4 = statusDocumentoAssinado3; if (flag1) { usuario1 = null; } else { List usuarios = Auxiliar.Usuarios; Func func1 = func; if (func1 == null) { Func id = (Usuario usuario) => usuario.Id == (long)sqlDataReader["usuarioid"]; Func func2 = id; func = id; func1 = func2; } usuario1 = usuarios.FirstOrDefault(func1); } statusDocumentoAssinado4.Usuario = usuario1; statusDocumentoAssinados1.Add(statusDocumentoAssinado); statusDocumentoAssinados1 = null; statusDocumentoAssinado1 = null; statusDocumentoAssinado3 = null; statusDocumentoAssinado = null; } } } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; List statusDocumentoAssinados2 = statusDocumentoAssinados; statusDocumentoAssinados = null; return statusDocumentoAssinados2; } private async Task> BuscaVendedoresPorIdControle(long idControle, long idEmpresa) { object connection; Func func = null; List vendedorParcelas = new List(); using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) { SessionFactoryImpl sessionFactoryImpl = sessionFactory; if (sessionFactoryImpl != null) { connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandTimeout = 1000; sqlCommand.CommandText = "SELECT DISTINCT vp.idvendedor,vp.vrep,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN parcela p ON vp.idparcela = p.idparcela INNER JOIN documento d ON d.iddocumento = vp.iddocumento WHERE d.idcontrole = @controle AND p.idsubtipo = 1"; sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle; using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { while (true) { if (!await sqlDataReader.ReadAsync()) { break; } List vendedorParcelas1 = vendedorParcelas; VendedorParcela vendedorParcela = new VendedorParcela(); TipoVendedor tipoVendedor = new TipoVendedor() { Id = sqlDataReader.GetFieldValue("idtipovendedor", true, true) }; vendedorParcela.TipoVendedor = tipoVendedor; List vendedores = Auxiliar.Vendedores; Func func1 = func; if (func1 == null) { Func id = (Vendedor vendedor) => vendedor.Id == sqlDataReader.GetFieldValue("idvendedor", true, true); Func func2 = id; func = id; func1 = func2; } vendedorParcela.Vendedor = vendedores.FirstOrDefault(func1); vendedorParcela.PorcentagemRepasse = sqlDataReader.GetFieldValue("vrep", true, true); vendedorParcelas1.Add(vendedorParcela); } List vendedorParcelas2 = vendedorParcelas; if (!vendedorParcelas2.Any((VendedorParcela v) => v.TipoVendedor.Id == (long)1)) { List vendedorParcelas3 = vendedorParcelas; VendedorParcela vendedorParcela1 = new VendedorParcela() { TipoVendedor = new TipoVendedor() { Id = (long)1 }, Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { if (v.IdEmpresa != idEmpresa) { return false; } return v.Corretora; }), PorcentagemRepasse = new decimal?(new decimal()) }; vendedorParcelas3.Add(vendedorParcela1); } } } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; List vendedorParcelas4 = vendedorParcelas; vendedorParcelas = null; return vendedorParcelas4; } private async Task> BuscaVendedoresPorIdDocumento(long idDocumento, long idEmpresa) { object connection; decimal? nullable; Func func = null; List vendedorParcelas = new List(); using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) { SessionFactoryImpl sessionFactoryImpl = sessionFactory; if (sessionFactoryImpl != null) { connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandTimeout = 1000; sqlCommand.CommandText = "SELECT DISTINCT vp.idvendedor,vp.vrep,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN parcela p ON vp.idparcela = p.idparcela WHERE vp.iddocumento = @documento AND p.idsubtipo = 1"; sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento; using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { while (true) { if (!await sqlDataReader.ReadAsync()) { break; } List vendedorParcelas1 = vendedorParcelas; VendedorParcela vendedorParcela = new VendedorParcela(); VendedorParcela vendedorParcela1 = vendedorParcela; TipoVendedor tipoVendedor = new TipoVendedor() { Id = (long)sqlDataReader["idtipovendedor"] }; vendedorParcela1.TipoVendedor = tipoVendedor; VendedorParcela vendedorParcela2 = vendedorParcela; List vendedores = Auxiliar.Vendedores; Func func1 = func; if (func1 == null) { Func id = (Vendedor vendedor) => vendedor.Id == (long)sqlDataReader["idvendedor"]; Func func2 = id; func = id; func1 = func2; } vendedorParcela2.Vendedor = vendedores.FirstOrDefault(func1); VendedorParcela vendedorParcela3 = vendedorParcela; bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vrep")); VendedorParcela vendedorParcela4 = vendedorParcela3; if (flag) { nullable = null; } else { nullable = new decimal?((decimal)sqlDataReader["vrep"]); } vendedorParcela4.PorcentagemRepasse = nullable; vendedorParcelas1.Add(vendedorParcela); vendedorParcelas1 = null; vendedorParcela3 = null; vendedorParcela = null; } List vendedorParcelas2 = vendedorParcelas; if (!vendedorParcelas2.Any((VendedorParcela v) => v.TipoVendedor.Id == (long)1)) { List vendedorParcelas3 = vendedorParcelas; VendedorParcela vendedorParcela5 = new VendedorParcela() { TipoVendedor = new TipoVendedor() { Id = (long)1 }, Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { if (v.IdEmpresa != idEmpresa) { return false; } return v.Corretora; }), PorcentagemRepasse = new decimal?(new decimal()) }; vendedorParcelas3.Add(vendedorParcela5); } } } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; List vendedorParcelas4 = vendedorParcelas; vendedorParcelas = null; return vendedorParcelas4; } private async Task ContaRegistros(int tipo, List fechamentos, Filtros filtro, List condicaoDocumento) { object connection; long num; bool count; bool flag; using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) { SessionFactoryImpl sessionFactoryImpl = sessionFactory; if (sessionFactoryImpl != null) { connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { string str = "c.IdCiaSeg"; string str1 = "COUNT(d.IdDocumento)"; string str2 = "FROM item i INNER JOIN documento d ON d.IdDocumento = i.IdDocumento INNER JOIN controle c ON c.IdControle = d.IdControle"; string str3 = "i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0) AND"; switch (tipo) { case 1: { str = "c.IdRamo"; break; } case 2: { str = "d.IdEstipulante"; break; } case 3: { str = "vp.IdVendedor"; break; } } string str4 = ""; if (tipo != 3) { List tipoVendedor = filtro.TipoVendedor; if (tipoVendedor != null) { count = tipoVendedor.Count > 0; } else { count = false; } if (!count) { List vendedores = filtro.Vendedores; if (vendedores != null) { flag = vendedores.Count > 0; } else { flag = false; } if (!flag) { goto Label0; } } } str1 = "COUNT(DISTINCT d.IdDocumento)"; str4 = "INNER JOIN vendedorparcela vp ON d.iddocumento = vp.iddocumento"; Label0: SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0); sqlCommand.CommandTimeout = 1000; SqlCommand sqlCommand1 = sqlCommand; string[] condicao = new string[] { "SELECT ", str, " Id,", str1, " Contador ", str2, " ", str4, " WHERE ", str3, " ", sqlQueryCondition.Condicao, " GROUP BY ", str }; sqlCommand1.CommandText = string.Concat(condicao); sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { while (true) { if (!await sqlDataReader.ReadAsync()) { break; } bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id")); num = (flag1 ? (long)0 : (long)sqlDataReader["Id"]); long num1 = num; int item = (int)sqlDataReader["Contador"]; if (num1 != 0) { Fechamento fechamento = fechamentos.FirstOrDefault((Fechamento f) => { if (f.Entidade != tipo) { return false; } return f.Id == num1; }); if (fechamento != null) { Fechamento itens = fechamento; itens.Itens = itens.Itens + item; } } } } sqlDataReader = null; } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; } public int Cotacoes(Filtros filtro) { int num; object connection; string str = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND u.idempresa = {0}", filtro.IdEmpresa)); try { SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandText = string.Format("SELECT COUNT(r.id) as quantidade from ResultadoCalculo r INNER JOIN usuario u ON u.idusuario = r.IdUsuario where CAST(DataAtualizacao AS DATE) >= '{0:yyyy-MM-dd}' and CAST(DataAtualizacao AS DATE) <= '{1:yyyy-MM-dd}' AND DataExclusao IS NULL AND Calculado = 1 {2};", filtro.Inicio, filtro.Fim, str); SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); sqlDataReader.Read(); num = (sqlDataReader.HasRows ? int.Parse(sqlDataReader["quantidade"].ToString()) : 0); } } } catch (Exception exception) { num = 0; } return num; } private List CriaCondicaoDocumento(Filtros filtro, string referencia) { bool count; bool flag; bool count1; bool flag1; bool count2; bool flag2; bool count3; bool flag3; List condicaos = new List() { new Condicao() { Campo = referencia, Valores = filtro.Inicio.CriarValor(), Operador = Operador.MaiorEIgual }, new Condicao() { Campo = referencia, Valores = filtro.Fim.CriarValor(), Operador = Operador.MenorEIgual } }; List seguradoras = filtro.Seguradoras; if (seguradoras != null) { count = seguradoras.Count > 0; } else { count = false; } if (count) { condicaos.Add(new Condicao() { Campo = "c.idciaseg", Valores = filtro.Seguradoras.CriarValor() }); } List ramos = filtro.Ramos; if (ramos != null) { flag = ramos.Count > 0; } else { flag = false; } if (flag) { condicaos.Add(new Condicao() { Campo = "c.idramo", Valores = filtro.Ramos.CriarValor() }); } List status = filtro.Status; if (status != null) { count1 = status.Count > 0; } else { count1 = false; } if (count1) { condicaos.Add(new Condicao() { Campo = "d.situacao", Valores = filtro.Status.CriarValor() }); } List tipoVendedor = filtro.TipoVendedor; if (tipoVendedor != null) { flag1 = tipoVendedor.Count > 0; } else { flag1 = false; } if (flag1) { condicaos.Add(new Condicao() { Campo = "vp.idtipovendedor", Valores = filtro.TipoVendedor.CriarValor() }); } List vendedores = filtro.Vendedores; if (vendedores != null) { count2 = vendedores.Count > 0; } else { count2 = false; } if (count2) { condicaos.Add(new Condicao() { Campo = "vp.idvendedor", Valores = filtro.Vendedores.CriarValor() }); } List estipulantes = filtro.Estipulantes; if (estipulantes != null) { flag2 = estipulantes.Count > 0; } else { flag2 = false; } if (flag2) { condicaos.Add(new Condicao() { Campo = "d.idestipulante", Valores = filtro.Estipulantes.CriarValor(), Operacao = Operacao.Or, Grupo = 3 }); condicaos.Add(new Condicao() { Campo = "d.idestipulante2", Valores = filtro.Estipulantes.CriarValor(), Operacao = Operacao.Or, Grupo = 3 }); condicaos.Add(new Condicao() { Campo = "d.idestipulante3", Valores = filtro.Estipulantes.CriarValor(), Operacao = Operacao.Or, Grupo = 3 }); condicaos.Add(new Condicao() { Campo = "d.idestipulante4", Valores = filtro.Estipulantes.CriarValor(), Operacao = Operacao.Or, Grupo = 3 }); condicaos.Add(new Condicao() { Campo = "d.idestipulante5", Valores = filtro.Estipulantes.CriarValor(), Operacao = Operacao.Or, Grupo = 3 }); } List produtos = filtro.Produtos; if (produtos != null) { count3 = produtos.Count > 0; } else { count3 = false; } if (count3) { condicaos.Add(new Condicao() { Campo = "c.idproduto", Valores = filtro.Produtos.CriarValor() }); } List negocio = filtro.Negocio; if (negocio != null) { flag3 = negocio.Count > 0; } else { flag3 = false; } if (flag3) { condicaos.Add(new Condicao() { Campo = "d.NegocioCorretora", Valores = filtro.Negocio.CriarValor(), Operacao = Operacao.Or, Grupo = 6 }); condicaos.Add(new Condicao() { Campo = "d.NegocioCorretora", Valores = null, Operacao = Operacao.Or, Grupo = 6 }); } if (filtro.IdEmpresa > (long)0) { condicaos.Add(new Condicao() { Campo = "c.idempresa", Valores = filtro.IdEmpresa.CriarValor() }); } return condicaos; } public void Delete(long id) { base.Delete(base.FindEntityById(id)); } private async Task ExisteTabelasAssinatura() { bool flag; object connection; using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) { SessionFactoryImpl sessionFactoryImpl = sessionFactory; if (sessionFactoryImpl != null) { connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandText = "SELECT OBJECT_ID('ArquivoParaAssinatura') AS existe"; flag = await sqlCommand.ExecuteScalarAsync() != DBNull.Value; } } } return flag; } public async Task> Fechamento(Filtros filtro) { List fechamentos = await this.BuscaFechamento(filtro); Filtros filtro1 = (Filtros)filtro.Clone(); DateTime inicio = filtro.Inicio; filtro1.Inicio = inicio.AddYears(-1); inicio = filtro.Fim; filtro1.Fim = inicio.AddYears(-1); List fechamentos1 = await this.BuscaFechamento(filtro1); List fechamentos2 = new List(); fechamentos1.ForEach((Fechamento a) => { Fechamento premioLiquido = fechamentos.Find((Fechamento fec) => { if (fec.Entidade != a.Entidade) { return false; } return fec.Id == a.Id; }) ?? new Fechamento() { Entidade = a.Entidade, Id = a.Id, Nome = a.Nome, PremioLiquido = decimal.Zero, PremioTotal = decimal.Zero, Fechada = decimal.Zero, Gerada = decimal.Zero, Mix = decimal.Zero, Apolice = 0, Endosso = 0, Fatura = 0, Itens = 0, Paga = decimal.Zero, Recebida = decimal.Zero }; premioLiquido.PremioLiquidoAnterior = a.PremioLiquido; premioLiquido.PremioTotalAnterior = a.PremioTotal; premioLiquido.FechadaAnterior = a.Fechada; premioLiquido.GeradaAnterior = a.Gerada; premioLiquido.MixAnterior = a.Mix; premioLiquido.ApoliceAnterior = a.Apolice; premioLiquido.EndossoAnterior = a.Endosso; premioLiquido.FaturaAnterior = a.Fatura; premioLiquido.ItensAnterior = a.Itens; premioLiquido.PagaAnterior = a.Paga; premioLiquido.RecebidaAnterior = a.Recebida; fechamentos2.Add(premioLiquido); }); fechamentos.ForEach((Fechamento a) => { if (fechamentos2.Find((Fechamento fec) => { if (fec.Entidade != a.Entidade) { return false; } return fec.Id == a.Id; }) == null) { Fechamento fechamento = new Fechamento() { Entidade = a.Entidade, Id = a.Id, Nome = a.Nome, PremioLiquidoAnterior = decimal.Zero, PremioTotalAnterior = decimal.Zero, FechadaAnterior = decimal.Zero, GeradaAnterior = decimal.Zero, MixAnterior = decimal.Zero, ApoliceAnterior = 0, EndossoAnterior = 0, FaturaAnterior = 0, ItensAnterior = 0, PagaAnterior = decimal.Zero, RecebidaAnterior = decimal.Zero, PremioLiquido = a.PremioLiquido, PremioTotal = a.PremioTotal, Fechada = a.Fechada, Gerada = a.Gerada, Mix = a.Mix, Apolice = a.Apolice, Endosso = a.Endosso, Fatura = a.Fatura, Itens = a.Itens, Paga = a.Paga, Recebida = a.Recebida }; fechamentos2.Add(fechamento); } }); List fechamentos3 = fechamentos2; return fechamentos3; } public List FindApolice(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, string campo, long idempresa = 0L, bool vendedorembranco = false, bool tipobusca = false) { List documentos; object connection; DataTable dataTable = new DataTable(); if (campo == "Proposta") { campo = (tipobusca ? string.Concat(" AND d.proposta LIKE '", pesquisa, "'") : string.Concat(" AND d.proposta LIKE '%", pesquisa, "%'")); } else if (campo == "Estipulante") { campo = (tipobusca ? string.Concat(" AND d.idestipulante IS NOT NULL AND e.nome LIKE '", pesquisa, "'") : string.Concat(" AND d.idestipulante IS NOT NULL AND e.nome LIKE '%", pesquisa, "%'")); } else if (campo == "NumeroEndosso") { campo = (tipobusca ? string.Concat(" AND d.aditamento LIKE '", pesquisa, "'") : string.Concat(" AND d.aditamento LIKE '%", pesquisa, "%'")); } else if (campo == "PedidoEndosso") { campo = (tipobusca ? string.Concat(" AND d.pedadit LIKE '", pesquisa, "'") : string.Concat(" AND d.pedadit LIKE '%", pesquisa, "%'")); } else { campo = (tipobusca ? string.Concat(" AND d.contrato LIKE '", pesquisa, "'") : string.Concat(" AND d.contrato LIKE '%", pesquisa, "%'")); } SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable1 = new DataTable(); string str = ""; string str1 = (idempresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", idempresa)); DateTime date = Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime().Date; switch (status) { case FiltroStatusDocumento.Vencidos: { str = string.Concat(string.Format(" {0} AND (d.vigencia2 IS NULL OR d.vigencia2 < '{1:yyyy-MM-dd}') ", campo, date.AddDays(-5)), "AND d.situacao NOT IN (3, 7)"); break; } case FiltroStatusDocumento.Cancelados: { str = string.Concat(" ", campo, " AND d.situacao IN (3)"); break; } case FiltroStatusDocumento.Recusados: { str = string.Concat(campo, " AND d.situacao IN (7)"); break; } case FiltroStatusDocumento.Todos: { str = string.Concat(" ", campo); break; } default: { str = string.Concat(string.Format(" {0} AND (d.vigencia2 IS NULL OR d.vigencia2 > '{1:yyyy-MM-dd}') ", campo, date.AddDays(-5)), "AND d.situacao IN (1, 2, 4)"); break; } } string str2 = "SELECT DISTINCT c.idcliente,cl.nome,cl.MalaDireta,c.idempresa,c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, d.pasta, c.AssistenciaId, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, e.nome AS estipulante FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole INNER JOIN cliente cl ON cl.idcliente = c.idcliente LEFT OUTER JOIN estipulante e ON e.idestipulante = d.idestipulante WHERE (d.excluido IS NULL OR d.excluido != 1) "; if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { Auxiliar.CriarAuxiliar(sqlCommand, false); sqlCommand.CommandText = string.Concat(str2, str1, str); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable1); } List list = ( from x in dataTable1.AsEnumerable().ToList() select x.Field("idcontrole")).ToList(); while (list.Count > 0) { List nums = list.Take(2100).ToList(); if (dataTable1.Rows.Count != 0) { string str3 = string.Concat(" d.idcontrole IN (", string.Join(",", nums), ")"); str3 = (vendedorembranco ? string.Concat(" AND ", str3) : string.Concat(" AND vp.idvendedorparcela IS NOT NULL AND ", str3)); sqlCommand.CommandText = string.Concat("SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento WHERE 1=1 ", str3); using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) { sqlDataAdapter1.SelectCommand = sqlCommand; sqlDataAdapter1.Fill(dataTable); } list = (nums.Count < 2100 ? new List() : list.Except(nums).ToList()); } else { documentos = new List(); return documentos; } } goto Label0; } } return documentos; Label0: List list1 = null; if (vendedorVinculado != null && vendedorVinculado.Count > 0) { list1 = dataTable.AsEnumerable().Where((DataRow x) => { if (!vendedorembranco) { if (x.Field("idvendedor") == null) { return false; } List vendedorUsuarios = vendedorVinculado; Func u003cu003e9_429 = DocumentoRepository.u003cu003ec.u003cu003e9__42_9; if (u003cu003e9_429 == null) { u003cu003e9_429 = (VendedorUsuario v) => v.Vendedor.Id; DocumentoRepository.u003cu003ec.u003cu003e9__42_9 = u003cu003e9_429; } return vendedorUsuarios.Select(u003cu003e9_429).Contains(x.Field("idvendedor")); } if (x.Field("idvendedor") == null) { return true; } List vendedorUsuarios1 = vendedorVinculado; Func u003cu003e9_428 = DocumentoRepository.u003cu003ec.u003cu003e9__42_8; if (u003cu003e9_428 == null) { u003cu003e9_428 = (VendedorUsuario v) => v.Vendedor.Id; DocumentoRepository.u003cu003ec.u003cu003e9__42_8 = u003cu003e9_428; } return vendedorUsuarios1.Select(u003cu003e9_428).Contains(x.Field("idvendedor")); }).Select((DataRow x) => x.Field("idcontrole")).ToList(); } if (list1 != null && list1.Count == 0) { return new List(); } List nums1 = dataTable1.AsEnumerable().Select((DataRow x) => x.Field("idcontrole")).Distinct().ToList(); List nums2 = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(nums1); return ( from x in dataTable1.AsEnumerable().Where((DataRow x) => { if (list1 == null) { return true; } return list1.Contains(x.Field("idcontrole")); }).ToList() orderby x.Field("idcontrole"), x.Field("tipo") select x).Select((DataRow x) => { Documento documento = new Documento() { Id = x.Field("iddocumento"), Controle = new Controle() { Id = x.Field("idcontrole"), IdEmpresa = (x.Field("idempresa") != null ? x.Field("idempresa") : (long)1), Cliente = new Cliente() { Id = x.Field("idcliente"), Nome = x.Field("nome"), MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) }, Seguradora = (x.Field("idciaseg") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idciaseg")) : null), Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), AssistenciaId = x.Field("AssistenciaId") }, Ordem = x.Field("ordem"), TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), AdicionalComiss = x.Field("adinacomis") == "1", Apolice = x.Field("contrato"), Endosso = x.Field("aditamento"), Comissao = x.Field("com01"), Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), PremioLiquido = x.Field("pr_liq"), PremioTotal = x.Field("pr_total"), Vigencia2 = x.Field("vigencia2") }; DateTime? nullable = x.Field("vigencia1"); documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); documento.Emissao = x.Field("emissao"); documento.Remessa = x.Field("remessa"); documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); documento.NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))); documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); documento.Tipo = x.Field("tipo"); documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(x.Field("iddocumento")); documento.Sinistro = (nums2 == null ? false : nums2.Any((long s) => s == x.Field("idcontrole"))); documento.NumeroParcelas = int.Parse(x.Field("numeroParcelas").ToString()); documento.Pasta = x.Field("Pasta"); return documento; }).ToList(); } public List FindApoliceByCustomer(long idCliente, FiltroStatusDocumento status, List vendedorVinculado, List licencas, bool endosso = false, bool acessoAgger = false, bool vendedorembranco = false) { List documentos1; object connection; long num1; SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; bool flag2 = licencas.Any((Licenca x) => { if (x.Produto != Gestor.Model.License.Produto.AssinaturaEletronica) { return false; } return x.Status != 3; }); DataTable dataTable3 = new DataTable(); DataTable dataTable4 = new DataTable(); DataTable dataTable5 = new DataTable(); DataTable dataTable6 = new DataTable(); DataTable dataTable7 = null; List nums = new List(); List condicaos = new List() { new Condicao() { Campo = "d.excluido", Valores = null, Grupo = 1, Operacao = Operacao.Or }, new Condicao() { Campo = "d.excluido", Valores = "0".CriarValor(), Grupo = 1, Operacao = Operacao.Or } }; DateTime date = Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime().Date; List condicaos1 = new List() { new Condicao() { Campo = "c.idcliente", Valores = idCliente.CriarValor() }, new Condicao() { Campo = "d.tipo", Valores = 0.CriarValor() } }; switch (status) { case FiltroStatusDocumento.Vencidos: { condicaos1.AddRange(new List() { new Condicao() { Campo = "d.situacao", Valores = new List() { 3, 7 }, Operador = Operador.Diferente }, new Condicao() { Campo = "d.vigencia2", Valores = date.AddDays(-5).CriarValor(), Operador = Operador.Menor } }); goto case FiltroStatusDocumento.Todos; } case FiltroStatusDocumento.Cancelados: { condicaos1.Add(new Condicao() { Campo = "d.situacao", Valores = 3.CriarValor() }); goto case FiltroStatusDocumento.Todos; } case FiltroStatusDocumento.Recusados: { condicaos1.Add(new Condicao() { Campo = "d.situacao", Valores = 7.CriarValor() }); goto case FiltroStatusDocumento.Todos; } case FiltroStatusDocumento.Todos: { if (!acessoAgger) { condicaos1.AddRange(condicaos); } if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { dataTable3 = sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); if (dataTable3 == null || dataTable3.Rows.Count == 0) { documentos1 = new List(); return documentos1; } else { Auxiliar.CriarAuxiliar(sqlCommand, false); nums = ( from x in dataTable3.AsEnumerable().ToList() select x.Field("idcontrole")).ToList(); List condicaos2 = new List() { new Condicao() { Campo = "c.idcontrole", Valores = nums.CriarValor() }, new Condicao() { Campo = "d.tipo", Valores = 0.CriarValor(), Operador = Operador.Diferente } }; if (!acessoAgger) { condicaos2.AddRange(condicaos); } dataTable4 = sqlCommand.Select(condicaos2.CreateParameters(0), "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); List condicaos3 = (vendedorembranco ? new List() { new Condicao() { Campo = "d.idcontrole", Valores = nums.CriarValor() } } : new List() { new Condicao() { Campo = "vp.idvendedorparcela", Valores = null, Operador = Operador.Diferente }, new Condicao() { Campo = "d.idcontrole", Valores = nums.CriarValor() } }); dataTable5 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT DISTINCT vp.IDPARCELA, vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor, p.idsubtipo FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento LEFT OUTER JOIN parcela p on p.idparcela = vp.idparcela WHERE ", ""); try { if (flag2) { List nums1 = ( from x in dataTable3.AsEnumerable().ToList() select x.Field("iddocumento")).ToList(); List nums2 = ( from x in dataTable4.AsEnumerable().ToList() select x.Field("iddocumento")).ToList(); nums1.AddRange(nums2); List condicaos4 = new List() { new Condicao() { Campo = "DocumentoId", Valores = nums1.CriarValor() }, new Condicao() { Campo = "a.excluido", Valores = null, Grupo = 2, Operacao = Operacao.Or }, new Condicao() { Campo = "a.excluido", Valores = 0.CriarValor(), Grupo = 2, Operacao = Operacao.Or } }; dataTable6 = sqlCommand.Select(condicaos4.CreateParameters(0), "SELECT DISTINCT a.idnewarquivodigital, a.descricao, ISNULL(s.Status ,0) as Status, s.assinado, s.DocumentoId, s.id, s.UsuarioId, s.Enviado FROM newarquivodigital a LEFT OUTER JOIN ArquivoParaAssinatura s on s.IndiceId = a.idnewarquivodigital WHERE ", ""); } } catch (Exception exception) { dataTable6 = null; } } } } List nums3 = null; if (vendedorVinculado != null && vendedorVinculado.Count > 0) { nums3 = dataTable5.AsEnumerable().Where((DataRow x) => { if (!vendedorembranco) { if (x.Field("idvendedor") == null) { return false; } List vendedorUsuarios = vendedorVinculado; Func u003cu003e9_1116 = DocumentoRepository.u003cu003ec.u003cu003e9__11_16; if (u003cu003e9_1116 == null) { u003cu003e9_1116 = (VendedorUsuario v) => v.Vendedor.Id; DocumentoRepository.u003cu003ec.u003cu003e9__11_16 = u003cu003e9_1116; } return vendedorUsuarios.Select(u003cu003e9_1116).Contains(x.Field("idvendedor")); } if (x.Field("idvendedor") == null) { return true; } List vendedorUsuarios1 = vendedorVinculado; Func u003cu003e9_1115 = DocumentoRepository.u003cu003ec.u003cu003e9__11_15; if (u003cu003e9_1115 == null) { u003cu003e9_1115 = (VendedorUsuario v) => v.Vendedor.Id; DocumentoRepository.u003cu003ec.u003cu003e9__11_15 = u003cu003e9_1115; } return vendedorUsuarios1.Select(u003cu003e9_1115).Contains(x.Field("idvendedor")); }).Select((DataRow x) => x.Field("idcontrole")).ToList(); } if (nums3 != null && nums3.Count == 0) { return new List(); } DataRow dataRow1 = dataTable3.AsEnumerable().FirstOrDefault(); if (dataRow1 != null) { num1 = dataRow1.Field("idempresa"); } else { num1 = (long)1; } long num2 = num1; Vendedor vendedor1 = Auxiliar.Vendedores.Find((Vendedor p) => { if (!p.Corretora) { return false; } return p.IdEmpresa == num2; }); if (endosso) { dataTable3.Merge(dataTable4); return ( from x in dataTable3.AsEnumerable().Where((DataRow x) => { if (nums3 == null) { return true; } return nums3.Contains(x.Field("idcontrole")); }).ToList() orderby x.Field("idcontrole"), x.Field("tipo") select x).Select((DataRow x) => { List list; Func func2 = null; Func func3 = null; Documento documento = new Documento() { Id = x.Field("iddocumento"), Controle = new Controle() { Id = x.Field("idcontrole"), IdEmpresa = (x.Field("idempresa") != null ? x.Field("idempresa") : (long)1), Cliente = new Cliente() { Id = idCliente, Documento = x.Field("cgccpf"), MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) }, Seguradora = (x.Field("idciaseg") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Field("idciaseg")) : null), Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Field("idramo")) : null), Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), AssistenciaId = x.Field("AssistenciaId") }, Ordem = x.Field("ordem"), TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), AdicionalComiss = x.Field("adinacomis") == "1", PremioAdicional = x.Field("pr_adic"), Proposta = x.Field("proposta"), Apolice = x.Field("contrato"), PropostaEndosso = x.Field("pedadit"), Endosso = x.Field("aditamento"), Comissao = x.Field("com01"), Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), PremioLiquido = x.Field("pr_liq"), PremioTotal = x.Field("pr_total"), Vigencia2 = x.Field("vigencia2") }; DateTime? nullable = x.Field("vigencia1"); documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); documento.Emissao = x.Field("emissao"); documento.Remessa = x.Field("remessa"); documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.Field("idestipulante")) : null); documento.NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))); documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); documento.Tipo = x.Field("tipo"); documento.VendedorPrincipal = (dataTable5.Rows.Count <= 0 || !dataTable5.AsEnumerable().Any((DataRow v1) => { if (v1.Field("idvendedor") == null || v1.Field("iddocumento") != x.Field("iddocumento")) { return false; } return v1.Field("idtipovendedor") == (long)1; }) ? vendedor1 : Auxiliar.Vendedores.Find((Vendedor v) => { EnumerableRowCollection dataRows = dataTable5.AsEnumerable(); Func u003cu003e9_26 = func2; if (u003cu003e9_26 == null) { Func func = (DataRow v1) => { if (v1.Field("iddocumento") != x.Field("iddocumento")) { return false; } return v1.Field("idtipovendedor") == (long)1; }; Func func1 = func; func2 = func; u003cu003e9_26 = func1; } return dataRows.First(u003cu003e9_26).Field("idvendedor") == v.Id; })); documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { EnumerableRowCollection dataRows = dataTable5.AsEnumerable(); Func u003cu003e9_27 = func3; if (u003cu003e9_27 == null) { Func func = (DataRow v1) => { if (v1.Field("idvendedor") == null) { return false; } return v1.Field("iddocumento") == x.Field("iddocumento"); }; Func func1 = func; func3 = func; u003cu003e9_27 = func1; } EnumerableRowCollection dataRows1 = dataRows.Where(u003cu003e9_27); Func u003cu003e9_1128 = DocumentoRepository.u003cu003ec.u003cu003e9__11_28; if (u003cu003e9_1128 == null) { u003cu003e9_1128 = (DataRow v1) => v1.Field("idvendedor"); DocumentoRepository.u003cu003ec.u003cu003e9__11_28 = u003cu003e9_1128; } return dataRows1.Select(u003cu003e9_1128).Contains(v.Id); }).ToList(); documento.NumeroParcelas = x.Field("numeroParcelas"); if (!flag2 || dataTable6 == null) { list = null; } else { EnumerableRowCollection dataRows2 = dataTable6.AsEnumerable().Where((DataRow a) => a.Field("DocumentoId") == x.Field("iddocumento")); Func u003cu003e9_1122 = DocumentoRepository.u003cu003ec.u003cu003e9__11_22; if (u003cu003e9_1122 == null) { u003cu003e9_1122 = (DataRow a) => new StatusDocumentoAssinado() { Id = a.Field("idnewarquivodigital"), Documento = a.Field("descricao"), Status = (StatusAssinatura)((a.Field("Status") != null ? a.Field("Status") : StatusAssinatura.Pendente)), Envio = (a.Field("Enviado") != null ? new DateTime?(a.Field("Enviado")) : null), Usuario = (a.Field("UsuarioId") != null ? Auxiliar.Usuarios.FirstOrDefault((Usuario u) => u.Id == a.Field("UsuarioId")) : null) }; DocumentoRepository.u003cu003ec.u003cu003e9__11_22 = u003cu003e9_1122; } list = dataRows2.Select(u003cu003e9_1122).ToList(); } documento.Assinaturas = list; documento.Pasta = x.Field("Pasta"); documento.Banco = new Banco() { Nome = x.Field("nomebanco") }; documento.Agencia = x.Field("agencia"); documento.Conta = x.Field("conta"); documento.Excluido = (x.Field("excluido") == null ? false : x.Field("excluido").ToString() == "1"); documento.FormaPagamento = new FormaPagamento?((x.Field("formapagamento") == null || !(x.Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.Field("formapagamento").ToString()))); return documento; }).ToList(); } List documentos2 = new List(); List nums4 = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(nums); ( from x in dataTable3.AsEnumerable().Where((DataRow x) => { if (nums3 == null) { return true; } return nums3.Contains(x.Field("idcontrole")); }).ToList() orderby x.Field("idcontrole") group x by x.Field("idcontrole")).ToList>().ForEach((IGrouping x) => { long? nullable1; bool count; bool flag; long? nullable2; List statusDocumentoAssinados; if (x == null || x.FirstOrDefault() == null) { return; } long num = (x.First().Field("idempresa") != null ? x.First().Field("idempresa") : (long)1); Cliente cliente = new Cliente() { Id = idCliente, Documento = x.First().Field("cgccpf"), MalaDireta = new bool?(x.First().Field("MalaDireta").GetValueOrDefault(true)) }; Seguradora seguradora = (x.First().Field("idciaseg") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.First().Field("idciaseg")) : null); Ramo ramo = (x.First().Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.First().Field("idramo")) : null); Gestor.Model.Domain.Seguros.Produto produto = (x.First().Field("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.First().Field("idproduto")) : null); EnumerableRowCollection dataRows1 = dataTable5.AsEnumerable().Where((DataRow v) => { if (v.Field("idvendedor") == null) { return false; } return v.Field("iddocumento") == x.First().Field("iddocumento"); }); DataTable dataTable = (!dataRows1.Any() ? null : dataRows1.CopyToDataTable()); DataTable dataTable1 = dataTable; count = (dataTable1 != null ? dataTable1.Rows.Count > 0 : false); List vendedors = (count ? Auxiliar.Vendedores.Where((Vendedor p) => { EnumerableRowCollection dataRows = dataTable.AsEnumerable(); Func u003cu003e9_1145 = DocumentoRepository.u003cu003ec.u003cu003e9__11_45; if (u003cu003e9_1145 == null) { u003cu003e9_1145 = (DataRow v) => v.Field("idvendedor"); DocumentoRepository.u003cu003ec.u003cu003e9__11_45 = u003cu003e9_1145; } return dataRows.Select(u003cu003e9_1145).Contains(p.Id); }).ToList() : null); DataTable dataTable2 = dataTable; flag = (dataTable2 != null ? dataTable2.Rows.Count > 0 : false); if (flag) { EnumerableRowCollection dataRows2 = dataTable.AsEnumerable(); Func u003cu003e9_1135 = DocumentoRepository.u003cu003ec.u003cu003e9__11_35; if (u003cu003e9_1135 == null) { u003cu003e9_1135 = (DataRow v) => v.Field("idsubtipo"); DocumentoRepository.u003cu003ec.u003cu003e9__11_35 = u003cu003e9_1135; } OrderedEnumerableRowCollection orderedEnumerableRowCollection = dataRows2.OrderBy(u003cu003e9_1135); Func u003cu003e9_1136 = DocumentoRepository.u003cu003ec.u003cu003e9__11_36; if (u003cu003e9_1136 == null) { u003cu003e9_1136 = (DataRow v) => v.Field("IDPARCELA"); DocumentoRepository.u003cu003ec.u003cu003e9__11_36 = u003cu003e9_1136; } List dataRows3 = orderedEnumerableRowCollection.ThenBy(u003cu003e9_1136).ToList(); Predicate u003cu003e9_1137 = DocumentoRepository.u003cu003ec.u003cu003e9__11_37; if (u003cu003e9_1137 == null) { u003cu003e9_1137 = (DataRow v) => v.Field("idtipovendedor") == (long)1; DocumentoRepository.u003cu003ec.u003cu003e9__11_37 = u003cu003e9_1137; } DataRow dataRow = dataRows3.Find(u003cu003e9_1137); if (dataRow != null) { nullable2 = new long?(dataRow.Field("idvendedor")); } else { nullable1 = null; nullable2 = nullable1; } } else { nullable1 = null; nullable2 = nullable1; } long? nullable3 = nullable2; Vendedor vendedor = (!nullable3.HasValue ? vendedor1 : Auxiliar.Vendedores.Find((Vendedor p) => { long? nullable = nullable3; long id = p.Id; return nullable.GetValueOrDefault() == id & nullable.HasValue; })); bool flag1 = (nums4 == null ? false : nums4.Any((long s) => s == x.First().Field("idcontrole"))); IEnumerable dataRows4 = from e in dataTable4.AsEnumerable().ToList() where e.Field("idcontrole") == x.Key select e; Func u003cu003e9_1141 = DocumentoRepository.u003cu003ec.u003cu003e9__11_41; if (u003cu003e9_1141 == null) { u003cu003e9_1141 = (DataRow e) => e.Field("tipo"); DocumentoRepository.u003cu003ec.u003cu003e9__11_41 = u003cu003e9_1141; } List dataRows5 = dataRows4.OrderBy(u003cu003e9_1141).ToList(); List calculos1 = null; if (dataTable7 != null) { EnumerableRowCollection dataRows6 = dataTable7.AsEnumerable().Where((DataRow c) => c.Field("IdDocumento") == x.First().Field("iddocumento")); Func u003cu003e9_1143 = DocumentoRepository.u003cu003ec.u003cu003e9__11_43; if (u003cu003e9_1143 == null) { u003cu003e9_1143 = (DataRow c) => new Calculo() { Id = c.Field("Id"), DocumentId = c.Field("IdDocumento"), DataAtualizacao = c.Field("DataAtualizacao"), Status = (StatusCalculo)c.Field("Status"), Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field("IdUsuario")) }; DocumentoRepository.u003cu003ec.u003cu003e9__11_43 = u003cu003e9_1143; } calculos1 = dataRows6.Select(u003cu003e9_1143).ToList(); if (dataRows5.Count > 0) { dataRows5.ForEach((DataRow e) => { List calculos = calculos1; EnumerableRowCollection dataRows = dataTable7.AsEnumerable().Where((DataRow c) => c.Field("IdDocumento") == e.Field("iddocumento")); Func u003cu003e9_1148 = DocumentoRepository.u003cu003ec.u003cu003e9__11_48; if (u003cu003e9_1148 == null) { u003cu003e9_1148 = (DataRow c) => new Calculo() { Id = c.Field("Id"), DocumentId = c.Field("IdDocumento"), DataAtualizacao = c.Field("DataAtualizacao"), Status = (StatusCalculo)c.Field("Status"), Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field("IdUsuario")) }; DocumentoRepository.u003cu003ec.u003cu003e9__11_48 = u003cu003e9_1148; } calculos.AddRange(dataRows.Select(u003cu003e9_1148).ToList()); }); } } Documento banco = new Documento() { Id = x.First().Field("iddocumento"), Controle = new Controle() { Id = x.Key, IdEmpresa = num, Cliente = cliente, Seguradora = seguradora, Ramo = ramo, Produto = produto, AssistenciaId = x.First().Field("AssistenciaId") }, Ordem = x.First().Field("ordem"), TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.First().Field("tiporecebimento").ToString())), AdicionalComiss = x.First().Field("adinacomis") == "1", Proposta = x.First().Field("proposta"), Apolice = x.First().Field("contrato"), Endosso = x.First().Field("aditamento"), Comissao = (x.First().Field("com01") == null ? decimal.Zero : x.First().Field("com01")), Negocio = new Negocio?((x.First().Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.First().Field("idnegocio").ToString()))), PremioLiquido = (!x.First().Field("pr_liq").HasValue ? decimal.Zero : x.First().Field("pr_liq")), PremioAdicional = (!x.First().Field("pr_adic").HasValue ? decimal.Zero : x.First().Field("pr_adic")), PremioTotal = (!x.First().Field("pr_total").HasValue ? decimal.Zero : x.First().Field("pr_total")), Vigencia2 = x.First().Field("vigencia2") }; DateTime? nullable4 = x.First().Field("vigencia1"); banco.Vigencia1 = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue); banco.Emissao = x.First().Field("emissao"); banco.Remessa = x.First().Field("remessa"); banco.Estipulante1 = (x.First().Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.First().Field("idestipulante")) : null); banco.NegocioCorretora = new NegocioCorretora?((x.First().Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.First().Field("negociocorretora").ToString()))); banco.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.First().Field("situacao").ToString()); banco.Tipo = x.First().Field("tipo"); banco.VendedorPrincipal = vendedor; banco.Sinistro = flag1; banco.TemEndosso = dataRows5.Count > 0; banco.Vendedores = vendedors; banco.Observacao = x.First().Field("Obs"); banco.NumeroParcelas = x.First().Field("numeroParcelas"); if (!flag2 || dataTable6 == null) { statusDocumentoAssinados = null; } else { EnumerableRowCollection dataRows7 = dataTable6.AsEnumerable().Where((DataRow a) => a.Field("DocumentoId") == x.First().Field("iddocumento")); Func u003cu003e9_1152 = DocumentoRepository.u003cu003ec.u003cu003e9__11_52; if (u003cu003e9_1152 == null) { u003cu003e9_1152 = (DataRow a) => new StatusDocumentoAssinado() { Id = a.Field("idnewarquivodigital"), Documento = a.Field("descricao"), Status = (StatusAssinatura)((a.Field("Status") != null ? a.Field("Status") : StatusAssinatura.Pendente)), Envio = (a.Field("Enviado") != null ? new DateTime?(a.Field("Enviado")) : null), Usuario = (a.Field("UsuarioId") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == a.Field("UsuarioId")) : null) }; DocumentoRepository.u003cu003ec.u003cu003e9__11_52 = u003cu003e9_1152; } statusDocumentoAssinados = dataRows7.Select(u003cu003e9_1152).ToList(); } banco.Assinaturas = statusDocumentoAssinados; banco.Pasta = x.First().Field("Pasta"); banco.Banco = new Banco() { Nome = x.First().Field("nomebanco") }; banco.Agencia = x.First().Field("agencia"); banco.Conta = x.First().Field("conta"); banco.Excluido = (x.First().Field("excluido") == null ? false : x.First().Field("excluido").ToString() == "1"); banco.NumeroCartao = x.First().Field("numeroCart"); banco.VencimentoCartao = x.First().Field("vencimentoCart"); banco.NomeProponente = x.First().Field("nomeProp"); banco.Calculos = calculos1; banco.FormaPagamento = new FormaPagamento?((x.First().Field("formapagamento") == null || !(x.First().Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.First().Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.First().Field("formapagamento").ToString()))); Documento documento1 = banco; List documentos = new List() { documento1 }; if (dataRows5.Count > 0) { List dataRows8 = dataRows5; Func u003cu003e9_1154 = DocumentoRepository.u003cu003ec.u003cu003e9__11_54; if (u003cu003e9_1154 == null) { u003cu003e9_1154 = (DataRow e) => e.Field("ordem"); DocumentoRepository.u003cu003ec.u003cu003e9__11_54 = u003cu003e9_1154; } documentos.AddRange(dataRows8.OrderBy(u003cu003e9_1154).Select((DataRow e) => { List list; Documento documento = new Documento() { Id = e.Field("iddocumento"), Controle = new Controle() { Id = x.Key, IdEmpresa = num, Cliente = cliente, Seguradora = seguradora, Ramo = ramo, Produto = produto, AssistenciaId = x.First().Field("AssistenciaId") }, Ordem = e.Field("ordem"), TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), e.Field("tiporecebimento").ToString())), AdicionalComiss = e.Field("adinacomis") == "1", Proposta = e.Field("proposta"), Apolice = e.Field("contrato"), PropostaEndosso = e.Field("pedadit"), Endosso = e.Field("aditamento"), Comissao = (e.Field("com01") == null ? decimal.Zero : e.Field("com01")), Negocio = new Negocio?((e.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), e.Field("idnegocio").ToString()))), PremioLiquido = e.Field("pr_liq"), PremioAdicional = e.Field("pr_adic"), PremioTotal = e.Field("pr_total"), Vigencia2 = e.Field("vigencia2") }; DateTime? nullable = e.Field("vigencia1"); documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); documento.Emissao = e.Field("emissao"); documento.Remessa = e.Field("remessa"); documento.Estipulante1 = (e.Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == e.Field("idestipulante")) : null); documento.NegocioCorretora = new NegocioCorretora?((e.Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), e.Field("negociocorretora").ToString()))); documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), e.Field("situacao").ToString()); documento.Tipo = e.Field("tipo"); documento.Sinistro = flag1; documento.NumeroParcelas = e.Field("numeroParcelas"); if (!flag2 || dataTable6 == null) { list = null; } else { EnumerableRowCollection dataRows = dataTable6.AsEnumerable().Where((DataRow a) => a.Field("DocumentoId") == e.Field("iddocumento")); Func u003cu003e9_1158 = DocumentoRepository.u003cu003ec.u003cu003e9__11_58; if (u003cu003e9_1158 == null) { u003cu003e9_1158 = (DataRow a) => new StatusDocumentoAssinado() { Id = a.Field("idnewarquivodigital"), Documento = a.Field("descricao"), Status = (StatusAssinatura)((a.Field("Status") != null ? a.Field("Status") : StatusAssinatura.Pendente)), Envio = (a.Field("Enviado") != null ? new DateTime?(a.Field("Enviado")) : null), Usuario = (a.Field("UsuarioId") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == a.Field("UsuarioId")) : null) }; DocumentoRepository.u003cu003ec.u003cu003e9__11_58 = u003cu003e9_1158; } list = dataRows.Select(u003cu003e9_1158).ToList(); } documento.Assinaturas = list; documento.Pasta = e.Field("Pasta"); documento.Banco = new Banco() { Nome = e.Field("nomebanco") }; documento.Agencia = e.Field("agencia"); documento.Conta = e.Field("conta"); documento.Excluido = (e.Field("excluido") == null ? false : e.Field("excluido").ToString() == "1"); documento.FormaPagamento = new FormaPagamento?((x.First().Field("formapagamento") == null || !(x.First().Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.First().Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.First().Field("formapagamento").ToString()))); return documento; }).ToList()); } documento1.Controle.Documentos = documentos; documentos2.Add(documento1); }); return documentos2; } default: { condicaos1.AddRange(new List() { new Condicao() { Campo = "d.situacao", Valores = new List() { 1, 2, 4 } }, new Condicao() { Campo = "d.vigencia2", Valores = null, Grupo = 2, Operacao = Operacao.Or }, new Condicao() { Campo = "d.vigencia2", Valores = date.AddDays(-5).CriarValor(), Grupo = 2, Operacao = Operacao.Or, Operador = Operador.Maior } }); goto case FiltroStatusDocumento.Todos; } } return documentos1; } public List FindByControle(long id) { List list = ( from x in base.All() where x.Controle.Id == id && !x.Excluido select x).ToList(); return ApplicationMapper.Mapper.Map, List>(list); } public Documento FindById(long id, bool itens = false, bool sinistrosPorControle = false) { DocumentoDb documentoDb = base.FindEntityById(id); Documento documento = ApplicationMapper.Mapper.Map(documentoDb); if (documento == null) { return null; } documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(id); documento.Sinistro = (sinistrosPorControle ? this.HasSinistroPorControle(documento.Controle.Id) : this.HasSinistro(documento.Id)); if (itens) { documento.ItensAtivo = (new ItemRepository(this._unitOfWork)).FindByDocumentsIds(documento.Controle.Id, StatusItem.Ativos, false); } return documento; } public Documento FindById(long id, List vendedorVinculado) { DocumentoDb documentoDb = base.FindEntityById(id); Documento documento = ApplicationMapper.Mapper.Map(documentoDb); if (documento == null) { return null; } documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(id); documento.Vendedores = (new VendedorParcelaRepository(this._unitOfWork)).FindVendedoresByDocumentId(id); documento.Sinistro = this.HasSinistro(documento.Id); if (vendedorVinculado.Count <= 0) { return documento; } if (!documento.Vendedores.Any((Vendedor y) => { List vendedorUsuarios = vendedorVinculado; Func u003cu003e9_31 = DocumentoRepository.u003cu003ec.u003cu003e9__3_1; if (u003cu003e9_31 == null) { u003cu003e9_31 = (VendedorUsuario x) => x.Vendedor.Id; DocumentoRepository.u003cu003ec.u003cu003e9__3_1 = u003cu003e9_31; } return vendedorUsuarios.Select(u003cu003e9_31).Contains(y.Id); })) { return null; } return documento; } public List FindByIds(List ids) { if (ids == null || ids.Count == 0) { return new List(); } return this.Select((new List() { new Condicao() { Campo = "d.iddocumento", Valores = ids.CriarValor() } }).CreateParameters(0)); } public List FindByLicenciamento(Filtros filtro) { List j; List documentos; object connection; List nums = null; long num; List nums1 = new List(); for (int i1 = filtro.ValorInicio; i1 <= filtro.ValorFim; i1++) { nums1.Add(i1); } string str = string.Concat("AND SUBSTRING(a.placa, len(a.placa), 1) IN ('", string.Join("','", from v in nums1 select v), "')"); string str1 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", from v in filtro.Status select v), ")")); string str2 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", from v in filtro.Negocio select v), ")")); string str3 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", from v in filtro.Seguradoras select v), ")")); string str4 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", from v in filtro.Ramos select v), ")")); string str5 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", from v in filtro.Produtos select v), ")")); string str6 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", from v in filtro.Vendedores select v), ")")); string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", from v in filtro.Estipulantes select v), ")")); string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); DataTable dataTable = new DataTable(); DataTable dataTable1 = new DataTable(); DataTable dataTable2 = new DataTable(); DataTable dataTable3 = new DataTable(); DataTable dataTable4 = new DataTable(); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { Auxiliar.CriarAuxiliar(sqlCommand, false); string str9 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao, a.placa, a.idcategoria FROM auto a INNER JOIN item i ON a.iditem = i.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (d.excluido IS NULL OR d.excluido = '0') AND d.situacao in (1,2,4) AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL AND a.placa IS NOT NULL "; string str10 = "SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf as documento, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.remessa, d.aditamento as endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.pasta, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp WHERE (d.excluido IS NULL OR d.excluido = 0) AND d.vigencia2 >= GETDATE() "; string str11 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; string str12 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; sqlCommand.CommandText = string.Concat(str9, " ", str); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable2); } if (dataTable2.Rows.Count != 0) { for (j = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("iddocumento")).Distinct().ToList(); j.Count > 0; j = nums) { List nums2 = j.Take(2000).ToList(); string str13 = string.Concat(" AND d.iddocumento IN (", string.Join(",", nums2), ")"); DataTable dataTable5 = new DataTable(); sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str8, " ", str13, " ", str1, " ", str2, " ", str3, " ", str4, " ", str5, " ", str7, " ", str6 }); using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) { sqlDataAdapter1.SelectCommand = sqlCommand; sqlDataAdapter1.Fill(dataTable5); } dataTable.Merge(dataTable5); nums = (nums2.Count < 2000 ? new List() : j.Except(nums2).ToList()); } if (dataTable.Rows.Count != 0) { if (dataTable.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null)) { string str14 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")"); DataTable dataTable6 = new DataTable(); sqlCommand.CommandText = string.Concat(new string[] { str11, " ", str14, " ", str6 }); using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) { sqlDataAdapter2.SelectCommand = sqlCommand; sqlDataAdapter2.Fill(dataTable6); } foreach (DataRow row in dataTable.Rows) { if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) { continue; } string str15 = string.Format("idcontrole = {0}", row["idcontrole"]); DataRow[] dataRowArray = dataTable6.Select(str15); if (dataRowArray.Length == 0) { continue; } row["idvendedor"] = dataRowArray[0][1]; } } j = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).Distinct().ToList(); string str16 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); sqlCommand.CommandText = string.Concat(str12, " ", str16); using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) { sqlDataAdapter3.SelectCommand = sqlCommand; sqlDataAdapter3.Fill(dataTable1); } while (j.Count > 0) { List nums3 = j.Take(2100).ToList(); string str17 = string.Concat(" AND idcliente IN (", string.Join(",", nums3), ")"); DataTable dataTable7 = new DataTable(); sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') ", str17); using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) { sqlDataAdapter4.SelectCommand = sqlCommand; sqlDataAdapter4.Fill(dataTable7); } dataTable3.Merge(dataTable7); dataTable7 = new DataTable(); sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 ", str17); using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter()) { sqlDataAdapter5.SelectCommand = sqlCommand; sqlDataAdapter5.Fill(dataTable7); } dataTable4.Merge(dataTable7); j = (nums3.Count < 2100 ? new List() : j.Except(nums3).ToList()); } goto Label0; } else { documentos = new List(); } } else { documentos = new List(); } } } return documentos; Label0: return dataTable.AsEnumerable().ToList().Select((DataRow x) => { Func func2 = null; Documento documento = new Documento() { Id = x.Field("id") }; Controle controle = new Controle() { IdEmpresa = x.Field("idempresa") }; Cliente cliente = new Cliente() { Id = x.Field("idcliente"), Nome = x.Field("cliente"), Documento = x.Field("documento"), IdEmpresa = x.Field("idempresa") }; EnumerableRowCollection dataRows1 = dataTable4.AsEnumerable().Where((DataRow t) => t.Field("idcliente") == x.Field("idcliente")); Func u003cu003e9_1525 = DocumentoRepository.u003cu003ec.u003cu003e9__15_25; if (u003cu003e9_1525 == null) { u003cu003e9_1525 = (DataRow t) => new ClienteTelefone() { Id = t.Field("idclitelefone"), Prefixo = t.Field("ddd"), Numero = t.Field("fone") }; DocumentoRepository.u003cu003ec.u003cu003e9__15_25 = u003cu003e9_1525; } cliente.Telefones = new ObservableCollection(dataRows1.Select(u003cu003e9_1525)); EnumerableRowCollection dataRows2 = dataTable3.AsEnumerable().Where((DataRow t) => t.Field("idcliente") == x.Field("idcliente")); Func u003cu003e9_1527 = DocumentoRepository.u003cu003ec.u003cu003e9__15_27; if (u003cu003e9_1527 == null) { u003cu003e9_1527 = (DataRow t) => new ClienteEmail() { Id = t.Field("idclimail"), Email = t.Field("email") }; DocumentoRepository.u003cu003ec.u003cu003e9__15_27 = u003cu003e9_1527; } cliente.Emails = new ObservableCollection(dataRows2.Select(u003cu003e9_1527)); cliente.Pasta = x.Field("pastacliente"); cliente.MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)); controle.Cliente = cliente; controle.Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null); controle.Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null); controle.Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null); controle.AssistenciaId = x.Field("AssistenciaId"); documento.Controle = controle; documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela); documento.AdicionalComiss = x.Field("adinacomiss") == "1"; documento.Apolice = x.Field("apolice"); documento.Endosso = (x.Field("tipo") == 0 ? "" : x.Field("endosso") ?? ""); documento.Comissao = x.Field("comissao"); documento.Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))); documento.PremioLiquido = x.Field("liquido"); documento.PremioTotal = x.Field("total"); documento.Vigencia2 = x.Field("vigenciafinal"); DateTime? nullable2 = x.Field("vigenciainicial"); documento.Vigencia1 = (nullable2.HasValue ? nullable2.GetValueOrDefault() : DateTime.MinValue); documento.Emissao = x.Field("emissao"); documento.Remessa = x.Field("remessa"); documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); documento.NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))); documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { List list = dataTable1.AsEnumerable().ToList(); Func u003cu003e9_28 = func2; if (u003cu003e9_28 == null) { Func func = (DataRow d) => d.Field("id") == x.Field("id"); Func func1 = func; func2 = func; u003cu003e9_28 = func1; } IEnumerable dataRows = list.Where(u003cu003e9_28); Func u003cu003e9_1529 = DocumentoRepository.u003cu003ec.u003cu003e9__15_29; if (u003cu003e9_1529 == null) { u003cu003e9_1529 = (DataRow d) => d.Field("idvendedor"); DocumentoRepository.u003cu003ec.u003cu003e9__15_29 = u003cu003e9_1529; } return dataRows.Select(u003cu003e9_1529).ToList().Contains(v.Id); }).ToList(); documento.Tipo = x.Field("tipo"); documento.DataControle = x.Field("datacontrole"); documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); documento.ItensAtivo = new List(dataTable2.AsEnumerable().ToList().Where((DataRow i) => { if (i.Field("idcontrole") == null || !long.TryParse(i.Field("idcontrole").ToString(), out num)) { return false; } return i.Field("idcontrole") == x.Field("idcontrole"); }).Select((DataRow i) => { Categoria? nullable; Categoria? nullable1; Item item = new Item() { Id = i.Field("iditem"), Descricao = i.Field("descricao"), Documento = new Documento() { Id = x.Field("id") } }; Auto auto = new Auto(); if (i.Field("idcategoria") == null) { nullable = null; nullable1 = nullable; } else if (i.Field("idcategoria").ToString() == "") { nullable = null; nullable1 = nullable; } else { nullable1 = (Categoria?)Enum.Parse(typeof(Categoria), i.Field("idcategoria").ToString()); } auto.Categoria = nullable1; auto.Placa = i.Field("placa"); item.Auto = auto; return item; }).ToList()); documento.Pasta = x.Field("Pasta"); return documento; }).ToList(); } public List FindByParcelaIds(List ids) { if (ids == null || ids.Count == 0) { return new List(); } List nums = (new ParcelaRepository(this._unitOfWork)).FindDocumentId(ids); return this.Select((new List() { new Condicao() { Campo = "d.iddocumento", Valores = nums.CriarValor() } }).CreateParameters(0)); } public List FindByPlaca(Filtros filtro) { List i; List documentos1; object connection; List nums = null; string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", from v in filtro.Status select v), ")")); string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", from v in filtro.Negocio select v), ")")); string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", from v in filtro.Seguradoras select v), ")")); string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", from v in filtro.Ramos select v), ")")); string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", from v in filtro.Produtos select v), ")")); string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", from v in filtro.Vendedores select v), ")")); string str6 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", from v in filtro.Estipulantes select v), ")")); string str7 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); DataTable dataTable = new DataTable(); DataTable dataTable1 = new DataTable(); DataTable dataTable2 = new DataTable(); DataTable dataTable3 = new DataTable(); DataTable dataTable4 = new DataTable(); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { Auxiliar.CriarAuxiliar(sqlCommand, false); object date = filtro.Inicio.Date; DateTime fim = filtro.Fim; string str8 = string.Format("SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao, a.placa, a.idcategoria FROM auto a INNER JOIN item i ON a.iditem = i.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (d.excluido IS NULL OR d.excluido = '0') {0} AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL AND d.vigencia2 >= '{1:yyyy-MM-dd}' AND d.vigencia2 <= '{2:yyyy-MM-dd}'", str, date, fim.Date); object obj = filtro.Inicio.Date; fim = filtro.Fim; string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf as documento, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.remessa, d.aditamento as endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.pasta, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp ", string.Format("WHERE (d.excluido IS NULL OR d.excluido = 0) AND d.vigencia2 >= '{0:yyyy-MM-dd}' AND d.vigencia2 <= '{1:yyyy-MM-dd}'", obj, fim.Date)); string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; sqlCommand.CommandText = str8 ?? ""; using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable2); } if (dataTable2.Rows.Count != 0) { for (i = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("iddocumento")).Distinct().ToList(); i.Count > 0; i = nums) { List nums1 = i.Take(2000).ToList(); string str12 = string.Concat(" AND d.iddocumento IN (", string.Join(",", nums1), ")"); DataTable dataTable5 = new DataTable(); sqlCommand.CommandText = string.Concat(new string[] { str9, " ", str7, " ", str12, " ", str, " ", str1, " ", str2, " ", str3, " ", str4, " ", str6, " ", str5 }); using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) { sqlDataAdapter1.SelectCommand = sqlCommand; sqlDataAdapter1.Fill(dataTable5); } dataTable.Merge(dataTable5); nums = (nums1.Count < 2000 ? new List() : i.Except(nums1).ToList()); } if (dataTable.Rows.Count != 0) { if (dataTable.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null)) { string str13 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")"); DataTable dataTable6 = new DataTable(); sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str13, " ", str5 }); using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) { sqlDataAdapter2.SelectCommand = sqlCommand; sqlDataAdapter2.Fill(dataTable6); } foreach (DataRow row in dataTable.Rows) { if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) { continue; } string str14 = string.Format("idcontrole = {0}", row["idcontrole"]); DataRow[] dataRowArray = dataTable6.Select(str14); if (dataRowArray.Length == 0) { continue; } row["idvendedor"] = dataRowArray[0][1]; } } i = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).Distinct().ToList(); string str15 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); sqlCommand.CommandText = string.Concat(str11, " ", str15); using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) { sqlDataAdapter3.SelectCommand = sqlCommand; sqlDataAdapter3.Fill(dataTable1); } while (i.Count > 0) { List nums2 = i.Take(2100).ToList(); string str16 = string.Concat(" AND idcliente IN (", string.Join(",", nums2), ")"); DataTable dataTable7 = new DataTable(); sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') ", str16); using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) { sqlDataAdapter4.SelectCommand = sqlCommand; sqlDataAdapter4.Fill(dataTable7); } dataTable3.Merge(dataTable7); dataTable7 = new DataTable(); sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 ", str16); using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter()) { sqlDataAdapter5.SelectCommand = sqlCommand; sqlDataAdapter5.Fill(dataTable7); } dataTable4.Merge(dataTable7); i = (nums2.Count < 2100 ? new List() : i.Except(nums2).ToList()); } goto Label0; } else { documentos1 = new List(); } } else { documentos1 = new List(); } } } return documentos1; Label0: List documentos2 = new List(); dataTable.AsEnumerable().ToList().ForEach((DataRow apolice) => { Func func2 = null; List documentos = documentos2; Documento documento = new Documento() { Id = apolice.Field("id") }; Controle controle = new Controle() { IdEmpresa = apolice.Field("idempresa") }; Cliente cliente = new Cliente() { Id = apolice.Field("idcliente"), Nome = apolice.Field("cliente"), Documento = apolice.Field("documento"), IdEmpresa = apolice.Field("idempresa") }; EnumerableRowCollection dataRows1 = dataTable4.AsEnumerable().Where((DataRow fone) => fone.Field("idcliente") == apolice.Field("idcliente")); Func u003cu003e9_1624 = DocumentoRepository.u003cu003ec.u003cu003e9__16_24; if (u003cu003e9_1624 == null) { u003cu003e9_1624 = (DataRow fone) => new ClienteTelefone() { Id = fone.Field("idclitelefone"), Prefixo = fone.Field("ddd"), Numero = fone.Field("fone") }; DocumentoRepository.u003cu003ec.u003cu003e9__16_24 = u003cu003e9_1624; } cliente.Telefones = new ObservableCollection(dataRows1.Select(u003cu003e9_1624)); EnumerableRowCollection dataRows2 = dataTable3.AsEnumerable().Where((DataRow mail) => mail.Field("idcliente") == apolice.Field("idcliente")); Func u003cu003e9_1626 = DocumentoRepository.u003cu003ec.u003cu003e9__16_26; if (u003cu003e9_1626 == null) { u003cu003e9_1626 = (DataRow mail) => new ClienteEmail() { Id = mail.Field("idclimail"), Email = mail.Field("email") }; DocumentoRepository.u003cu003ec.u003cu003e9__16_26 = u003cu003e9_1626; } cliente.Emails = new ObservableCollection(dataRows2.Select(u003cu003e9_1626)); cliente.Pasta = apolice.Field("pastacliente"); cliente.MalaDireta = new bool?(apolice.Field("MalaDireta").GetValueOrDefault(true)); controle.Cliente = cliente; controle.Seguradora = (apolice.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora seguradora) => seguradora.Id == apolice.Field("idseguradora")) : null); controle.Ramo = (apolice.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo ramo) => ramo.Id == apolice.Field("idramo")) : null); controle.Produto = (apolice.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto produto) => produto.Id == apolice.Field("idproduto")) : null); controle.AssistenciaId = apolice.Field("AssistenciaId"); documento.Controle = controle; documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela); documento.AdicionalComiss = apolice.Field("adinacomiss") == "1"; documento.Apolice = apolice.Field("apolice"); documento.Endosso = (apolice.Field("tipo") == 0 ? "" : apolice.Field("endosso") ?? ""); documento.Comissao = apolice.Field("comissao"); documento.Negocio = new Negocio?((apolice.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), apolice.Field("idnegocio").ToString()))); documento.PremioLiquido = apolice.Field("liquido"); documento.PremioTotal = apolice.Field("total"); documento.Vigencia2 = apolice.Field("vigenciafinal"); DateTime? nullable2 = apolice.Field("vigenciainicial"); documento.Vigencia1 = (nullable2.HasValue ? nullable2.GetValueOrDefault() : DateTime.MinValue); documento.Emissao = apolice.Field("emissao"); documento.Remessa = apolice.Field("remessa"); documento.VendedorPrincipal = (apolice.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor vendedor) => vendedor.Id == apolice.Field("idvendedor")) : null); documento.Estipulante1 = (apolice.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante estipulante) => estipulante.Id == apolice.Field("idestipulante")) : null); documento.NegocioCorretora = new NegocioCorretora?((apolice.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), apolice.Field("situacao").ToString()) != TipoSeguro.Renovacao || apolice.Field("idnegocio") == null || !(apolice.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), apolice.Field("negociocorretora").ToString()))); documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), apolice.Field("situacao").ToString()); documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor vendedor) => { List list = dataTable1.AsEnumerable().ToList(); Func u003cu003e9_27 = func2; if (u003cu003e9_27 == null) { Func func = (DataRow d) => d.Field("id") == apolice.Field("id"); Func func1 = func; func2 = func; u003cu003e9_27 = func1; } IEnumerable dataRows = list.Where(u003cu003e9_27); Func u003cu003e9_1628 = DocumentoRepository.u003cu003ec.u003cu003e9__16_28; if (u003cu003e9_1628 == null) { u003cu003e9_1628 = (DataRow d) => d.Field("idvendedor"); DocumentoRepository.u003cu003ec.u003cu003e9__16_28 = u003cu003e9_1628; } return dataRows.Select(u003cu003e9_1628).ToList().Contains(vendedor.Id); }).ToList(); documento.Tipo = apolice.Field("tipo"); documento.DataControle = apolice.Field("datacontrole"); documento.Status = (apolice.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status status) => status.Id == apolice.Field("idstatus")) : null); documento.ItensAtivo = new List(( from item in dataTable2.AsEnumerable().ToList() where item.Field("iddocumento") == apolice.Field("id") select item).Select((DataRow item) => { Categoria? nullable; Categoria? nullable1; Item item1 = new Item() { Id = item.Field("iditem"), Descricao = item.Field("descricao"), Documento = new Documento() { Id = apolice.Field("id") } }; Auto auto = new Auto(); if (item.Field("idcategoria") == null) { nullable = null; nullable1 = nullable; } else if (item.Field("idcategoria").ToString() == "") { nullable = null; nullable1 = nullable; } else { nullable1 = (Categoria?)Enum.Parse(typeof(Categoria), item.Field("idcategoria").ToString()); } auto.Categoria = nullable1; auto.Placa = item.Field("placa"); item1.Auto = auto; return item1; }).ToList()); documento.Pasta = apolice.Field("Pasta"); documentos.Add(documento); }); return documentos2; } public List FindByVigenciaFinal(Filtros filtro, List licencas, bool somarPremios) { List j; List documentos; object connection; bool count; List nums1 = null; List nums2 = null; List nums3 = null; List nums4 = null; List condicaos = this.CriaCondicaoDocumento(filtro, "CAST(d.vigencia2 AS DATE)"); condicaos.AddRange(new List() { new Condicao() { Campo = "d.excluido", Valores = null, Grupo = 1, Operacao = Operacao.Or }, new Condicao() { Campo = "d.excluido", Valores = "0".CriarValor(), Grupo = 1, Operacao = Operacao.Or } }); condicaos.Add(new Condicao() { Campo = "d.tipo", Valores = 0.CriarValor() }); DataTable dataTable = new DataTable(); DataTable dataTable1 = new DataTable(); DataTable dataTable2 = new DataTable(); DataTable dataTable3 = new DataTable(); DataTable dataTable4 = new DataTable(); DataTable dataTable5 = new DataTable(); DataTable dataTable6 = null; DataTable dataTable7 = new DataTable(); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandTimeout = 15000; string str = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf, d.idcontrole, d.iddocumento as id, d.contrato as apolice, CASE WHEN d2.aditamento <>'' THEN 'SIM' ELSE 'NÃO' END AS endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.apol_antes, d.remessa, d.emissao, d.pr_adic, d.pr_iof, d.pr_custo, d.datacontrole, d.idstatus, d.pasta, d.idbanco, cb.nomebanco, d.agencia, d.conta, cl.pasta as pastacliente, c.AssistenciaId, d.tiporecebimento FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco OUTER APPLY (SELECT TOP 1 aditamento FROM documento WHERE idcontrole = d.idcontrole AND tipo = '1') d2 ", (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 vp.idvendedor FROM vendedorparcela vp INNER JOIN parcela parc ON parc.IdParcela = vp.IdParcela WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1 ORDER BY PARC.IDSUBTIPO, CAST(parc.Parcela as int) DESC) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", from v in filtro.TipoVendedor select v), ")")), " WHERE "); string str1 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento INNER JOIN parcela p ON p.idparcela = vp.idparcela WHERE "; string str2 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE "; string str3 = "SELECT DISTINCT idcontrolesinistro, idcontrole as id, cs.iditem FROM controlesinistro cs INNER JOIN item i on i.iditem = cs.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE "; string str4 = "SELECT DISTINCT idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE "; string str5 = "SELECT DISTINCT idclimail, email, idcliente as id FROM climail WHERE "; string str6 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE "; dataTable = sqlCommand.Select(condicaos.CreateParameters(0), str, ""); if (dataTable == null || dataTable.Rows.Count == 0) { documentos = new List(); } else { Auxiliar.CriarAuxiliar(sqlCommand, false); for (List i1 = dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole")).ToList(); i1.Count > 0; i1 = nums1) { List nums5 = i1.Take(1000).ToList(); List condicaos1 = new List() { new Condicao() { Campo = "d.idcontrole", Valores = nums5.CriarValor() }, new Condicao() { Campo = "p.parcela", Operador = Operador.Diferente, Valores = "999".CriarValor() } }; List vendedores = filtro.Vendedores; if (vendedores != null) { count = vendedores.Count > 0; } else { count = false; } if (count) { condicaos1.Add(new Condicao() { Campo = "vp.idvendedor", Valores = filtro.Vendedores.CriarValor() }); } DataTable dataTable8 = sqlCommand.Select(condicaos1.CreateParameters(0), str1, ""); foreach (DataRow row in dataTable.Rows) { if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) { continue; } string str7 = string.Format("idcontrole = {0}", row["idcontrole"]); DataRow[] dataRowArray = dataTable8.Select(str7); if (dataRowArray.Length == 0) { continue; } row["idvendedor"] = dataRowArray[0][1]; } nums1 = (nums5.Count < 1000 ? new List() : i1.Except(nums5).ToList()); } for (j = dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcliente")).Distinct().ToList(); j.Count > 0; j = nums2) { List nums6 = j.Take(1000).ToList(); List condicaos2 = new List() { new Condicao() { Campo = "idcliente", Valores = nums6.CriarValor() } }; DataTable dataTable9 = sqlCommand.Select(condicaos2.CreateParameters(0), str4, ""); dataTable4.Merge(dataTable9); dataTable9 = sqlCommand.Select(condicaos2.CreateParameters(0), str5, ""); dataTable3.Merge(dataTable9); nums2 = (nums6.Count < 1000 ? new List() : j.Except(nums6).ToList()); } for (j = dataTable.AsEnumerable().Select((DataRow v) => v.Field("id")).Distinct().ToList(); j.Count > 0; j = nums3) { List nums7 = j.Take(1000).ToList(); List condicaos3 = new List() { new Condicao() { Campo = "vp.iddocumento", Valores = nums7.CriarValor() } }; DataTable dataTable10 = sqlCommand.Select(condicaos3.CreateParameters(0), str2, ""); dataTable1.Merge(dataTable10); nums3 = (nums7.Count < 1000 ? new List() : j.Except(nums7).ToList()); } for (j = dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole")).Distinct().ToList(); j.Count > 0; j = nums4) { List nums8 = j.Take(1000).ToList(); List condicaos4 = new List() { new Condicao() { Campo = "d.idcontrole", Valores = nums8.CriarValor() } }; List condicaos5 = new List(); condicaos5.AddRange(condicaos4); DataTable dataTable11 = sqlCommand.Select(condicaos5.CreateParameters(0), str3, ""); dataTable2.Merge(dataTable11); condicaos5.AddRange(new List() { new Condicao() { Campo = "idsubstituido", Valores = null }, new Condicao() { Campo = "cancelado", Valores = null, Operacao = Operacao.Or, Grupo = 1 }, new Condicao() { Campo = "cancelado", Valores = 0.CriarValor(), Operacao = Operacao.Or, Grupo = 1 } }); dataTable11 = sqlCommand.Select(condicaos5.CreateParameters(0), str6, ""); dataTable5.Merge(dataTable11); licencas.Any((Licenca x) => { if (x.Produto != Gestor.Model.License.Produto.AggilizadorCalculos && x.Produto != Gestor.Model.License.Produto.AggilizadorCalculosIndependente) { return false; } return x.Status != 3; }); if (somarPremios) { condicaos4.AddRange(new List() { new Condicao() { Campo = "d.excluido", Valores = null, Grupo = 1, Operacao = Operacao.Or }, new Condicao() { Campo = "d.excluido", Valores = "0".CriarValor(), Grupo = 1, Operacao = Operacao.Or } }); DataTable dataTable12 = sqlCommand.Select(condicaos4.CreateParameters(0), "SELECT d.iddocumento, d.idcontrole, ISNULL(d.pr_liq ,0) AS pr_liq, ISNULL(d.pr_total ,0) AS pr_total FROM documento d WHERE", ""); dataTable7.Merge(dataTable12); } nums4 = (nums8.Count < 1000 ? new List() : j.Except(nums8).ToList()); } goto Label0; } } } return documentos; Label0: List documentos1 = new List(); dataTable.AsEnumerable().ToList().ForEach((DataRow x) => { DateTime? nullable; List list; decimal num; decimal num1; DateTime? nullable1; DateTime? nullable2; EnumerableRowCollection dataRows1 = dataTable1.AsEnumerable().Where((DataRow d) => d.Field("id") == x.Field("id")); Func u003cu003e9_269 = DocumentoRepository.u003cu003ec.u003cu003e9__26_9; if (u003cu003e9_269 == null) { u003cu003e9_269 = (DataRow d) => d.Field("idvendedor"); DocumentoRepository.u003cu003ec.u003cu003e9__26_9 = u003cu003e9_269; } List nums = dataRows1.Select(u003cu003e9_269).ToList(); IEnumerable list1 = from t in dataTable4.AsEnumerable().ToList() where t.Field("id") == x.Field("idcliente") select t; Func u003cu003e9_2611 = DocumentoRepository.u003cu003ec.u003cu003e9__26_11; if (u003cu003e9_2611 == null) { u003cu003e9_2611 = (DataRow t) => new ClienteTelefone() { Prefixo = t.Field("ddd"), Numero = t.Field("fone") }; DocumentoRepository.u003cu003ec.u003cu003e9__26_11 = u003cu003e9_2611; } List clienteTelefones = list1.Select(u003cu003e9_2611).ToList(); IEnumerable list2 = from t in dataTable3.AsEnumerable().ToList() where t.Field("id") == x.Field("idcliente") select t; Func u003cu003e9_2613 = DocumentoRepository.u003cu003ec.u003cu003e9__26_13; if (u003cu003e9_2613 == null) { u003cu003e9_2613 = (DataRow t) => new ClienteEmail() { Email = t.Field("email") }; DocumentoRepository.u003cu003ec.u003cu003e9__26_13 = u003cu003e9_2613; } List clienteEmails = list2.Select(u003cu003e9_2613).ToList(); List items = ( from i in dataTable5.AsEnumerable().ToList() where i.Field("idcontrole") == x.Field("idcontrole") select i).Select((DataRow i) => { Item item = new Item() { Id = i.Field("iditem"), Descricao = i.Field("descricao") }; EnumerableRowCollection dataRows = dataTable2.AsEnumerable().Where((DataRow s) => { if (s.Field("id") != x.Field("idcontrole")) { return false; } return i.Field("iditem") == s.Field("iditem"); }); Func u003cu003e9_2624 = DocumentoRepository.u003cu003ec.u003cu003e9__26_24; if (u003cu003e9_2624 == null) { u003cu003e9_2624 = (DataRow s) => new ControleSinistro() { Id = s.Field("idcontrolesinistro") }; DocumentoRepository.u003cu003ec.u003cu003e9__26_24 = u003cu003e9_2624; } item.Sinistros = dataRows.Select(u003cu003e9_2624).ToList(); return item; }).ToList(); if (dataTable6 != null) { EnumerableRowCollection dataRows2 = dataTable6.AsEnumerable().Where((DataRow c) => c.Field("idcontrole") == x.Field("idcontrole")); Func u003cu003e9_2617 = DocumentoRepository.u003cu003ec.u003cu003e9__26_17; if (u003cu003e9_2617 == null) { u003cu003e9_2617 = (DataRow c) => new Calculo() { Id = c.Field("Id"), DocumentId = c.Field("IdDocumento"), DataAtualizacao = c.Field("DataAtualizacao"), Status = (StatusCalculo)c.Field("Status"), Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field("IdUsuario")) }; DocumentoRepository.u003cu003ec.u003cu003e9__26_17 = u003cu003e9_2617; } list = dataRows2.Select(u003cu003e9_2617).ToList(); } else { list = new List(); } List calculos = list; List list3 = dataTable7.AsEnumerable().Where((DataRow p) => p.Field("idcontrole") == x.Field("idcontrole")).ToList(); if (!somarPremios) { num = x.Field("total"); } else { List dataRows3 = list3; Func u003cu003e9_2619 = DocumentoRepository.u003cu003ec.u003cu003e9__26_19; if (u003cu003e9_2619 == null) { u003cu003e9_2619 = (DataRow p) => p.Field("pr_total"); DocumentoRepository.u003cu003ec.u003cu003e9__26_19 = u003cu003e9_2619; } num = dataRows3.Sum(u003cu003e9_2619); } decimal num2 = num; if (!somarPremios) { num1 = x.Field("liquido"); } else { List dataRows4 = list3; Func u003cu003e9_2620 = DocumentoRepository.u003cu003ec.u003cu003e9__26_20; if (u003cu003e9_2620 == null) { u003cu003e9_2620 = (DataRow p) => p.Field("pr_liq"); DocumentoRepository.u003cu003ec.u003cu003e9__26_20 = u003cu003e9_2620; } num1 = dataRows4.Sum(u003cu003e9_2620); } decimal num3 = num1; Vendedor vendedor = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.Find((Vendedor p) => p.Id == x.Field("idvendedor")) : null); NegocioCorretora negocioCorretora = (x.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString())); if (filtro.Negocio != null && filtro.Negocio.Count > 0 && !filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora)) { return; } Documento documento = new Documento() { Id = x.Field("id"), Controle = new Controle() { Id = x.Field("idcontrole"), IdEmpresa = x.Field("idempresa"), Cliente = new Cliente() { Id = x.Field("idcliente"), Nome = x.Field("cliente"), Documento = x.Field("cgccpf"), IdEmpresa = x.Field("idempresa"), Telefones = new ObservableCollection(clienteTelefones), Emails = new ObservableCollection(clienteEmails), Pasta = x.Field("pastacliente"), MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) }, Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Field("idseguradora")) : null), Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Field("idramo")) : null), Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), AssistenciaId = x.Field("AssistenciaId") }, TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), AdicionalComiss = x.Field("adinacomiss") == "1", Apolice = x.Field("apolice"), ApoliceAnterior = x.Field("apol_antes") }; if (x.Field("remessa") == null) { nullable = null; nullable1 = nullable; } else { nullable1 = new DateTime?(x.Field("remessa")); } documento.Remessa = nullable1; if (x.Field("emissao") == null) { nullable = null; nullable2 = nullable; } else { nullable2 = new DateTime?(x.Field("emissao")); } documento.Emissao = nullable2; documento.Endosso = x.Field("endosso"); documento.Comissao = x.Field("comissao"); documento.Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))); documento.PremioLiquido = num3; documento.PremioAdicional = x.Field("pr_adic"); x.Field("pr_custo"); documento.Custo = x.Field("pr_custo"); documento.Iof = x.Field("pr_iof"); documento.PremioTotal = num2; documento.Vigencia2 = x.Field("vigenciafinal"); nullable = x.Field("vigenciainicial"); documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); documento.VendedorPrincipal = vendedor; documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.Field("idestipulante")) : null); documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora); documento.Vendedores = ( from v in Auxiliar.Vendedores where nums.Contains(v.Id) select v).ToList(); documento.Sinistro = dataTable2.AsEnumerable().ToList().Any((DataRow s) => s.Field("id") == x.Field("idcontrole")); documento.Tipo = x.Field("tipo"); documento.ItensAtivo = items; documento.DataControle = x.Field("datacontrole"); documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.Find((Status p) => p.Id == x.Field("idstatus")) : null); documento.Pasta = x.Field("Pasta"); documento.Banco = new Banco() { Nome = x.Field("nomebanco") }; documento.Agencia = x.Field("agencia"); documento.Conta = x.Field("conta"); documento.Calculos = calculos; documentos1.Add(documento); }); return documentos1; } public async Task> FindEndossoByVigencia(Filtros filtro, bool buscarAssinatura = false) { decimal? nullable2; object list; bool count; decimal? porcentagemRepasse; string str = "CAST(d.vigencia1 AS DATE)"; string referencia = filtro.Referencia; if (referencia == "EMISSÃO") { str = "CAST(d.emissao AS DATE)"; } else if (referencia == "TRANSMISSÃO PROPOSTA") { str = "CAST(d.remessa AS DATE)"; } else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") { str = "CAST(d.cri_data AS DATE)"; } List vinculoVendedores = filtro.VinculoVendedores; if (vinculoVendedores != null) { IEnumerable nums = vinculoVendedores.Except(filtro.Vendedores); if (nums != null) { list = nums.ToList(); } else { list = null; } } else { list = null; } if (list == null) { list = new List(); } if (!((IEnumerable)list).Any()) { filtro.Vendedores = new List(); } List condicaos = this.CriaCondicaoDocumento(filtro, str); Condicao condicao = new Condicao() { Campo = "d.Tipo", Valores = 1.CriarValor() }; condicaos.Add(condicao); List condicaos1 = new List(); Condicao condicao1 = new Condicao() { Campo = "d.Excluido", Valores = null, Grupo = 1, Operacao = Operacao.Or }; condicaos1.Add(condicao1); Condicao condicao2 = new Condicao() { Campo = "d.Excluido", Valores = "0".CriarValor(), Grupo = 1, Operacao = Operacao.Or }; condicaos1.Add(condicao2); condicaos.AddRange(condicaos1); List documentos = await this.BuscaDocumentosPorCondicao(filtro, condicaos, buscarAssinatura); List vinculoVendedores1 = filtro.VinculoVendedores; if (vinculoVendedores1 != null) { count = vinculoVendedores1.Count > 0; } else { count = false; } if (count) { List documentos1 = new List(); foreach (Documento documento in documentos) { await this.BuscaVendedoresPorIdControle(documento.Controle.Id, documento.Controle.IdEmpresa).ForEach((VendedorParcela v) => { if (!filtro.VinculoVendedores.Contains(v.Vendedor.Id)) { documentos1.Add(documento); } }); } documentos1.ForEach((Documento d) => this.documentos.Remove(d)); } foreach (Documento vendedor in documentos) { if (vendedor.Tipo == 1 && vendedor.VendedorPrincipal == null && vendedor.Pagamentos.Count < 2) { List vendedorParcelas = await this.BuscaVendedoresPorIdControle(vendedor.Controle.Id, vendedor.Controle.IdEmpresa); vendedor.Pagamentos = vendedorParcelas; List vendedorParcelas1 = vendedorParcelas; VendedorParcela vendedorParcela = vendedorParcelas1.Find((VendedorParcela v) => v.TipoVendedor.Id == (long)1); if (vendedorParcela != null) { vendedor.VendedorPrincipal = vendedorParcela.Vendedor; } List pagamentos = vendedor.Pagamentos; IOrderedEnumerable vendedorParcelas2 = from tipo in pagamentos orderby tipo.TipoVendedor.Id select tipo; List vendedors = ( from v in vendedorParcelas2 select v.Vendedor).ToList(); vendedor.Vendedores = vendedors; Documento documento1 = vendedor; VendedorParcela vendedorParcela1 = vendedor.Pagamentos.FirstOrDefault((VendedorParcela p) => { long? nullable; long id = p.Vendedor.Id; Vendedor vendedorPrincipal = vendedor.VendedorPrincipal; if (vendedorPrincipal != null) { nullable = new long?(vendedorPrincipal.Id); } else { nullable = null; } long? nullable1 = nullable; return id == nullable1.GetValueOrDefault() & nullable1.HasValue; }); if (vendedorParcela1 != null) { porcentagemRepasse = vendedorParcela1.PorcentagemRepasse; } else { nullable2 = null; porcentagemRepasse = nullable2; } nullable2 = porcentagemRepasse; documento1.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault()); } } List documentos2 = documentos; return documentos2; } public List FindPendenciasByVigencia(Filtros filtro) { object connection; string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", from v in filtro.Status select v), ")")); string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", from v in filtro.Negocio select v), ")")); string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", from v in filtro.Seguradoras select v), ")")); string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", from v in filtro.Ramos select v), ")")); string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", from v in filtro.Produtos select v), ")")); string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", from v in filtro.Vendedores select v), ")")); string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", from v in filtro.TipoVendedor select v), ")")); string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", from v in filtro.Estipulantes select v), ")")); string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); DataTable dataTable1 = new DataTable(); DataTable dataTable2 = new DataTable(); DataTable dataTable3 = new DataTable(); DataTable dataTable4 = new DataTable(); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandTimeout = 15000; Auxiliar.CriarAuxiliar(sqlCommand, false); string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf, d.idcontrole, d.iddocumento as id, d.proposta, d.pedadit as propostaendosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento, d.datacontrole, d.idstatus, d.pasta, d.idbanco, cb.nomebanco, d.conta, d.agencia, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco ", str6, " WHERE (d.excluido IS NULL OR d.excluido = 0) AND (cl.excluido = 0 OR cl.excluido IS NULL) AND CASE \tWHEN ( d.tipo = 0 ) THEN DATALENGTH(ISNULL( d.contrato, '' )) ELSE DATALENGTH(ISNULL( d.aditamento, '' )) END < 1 "); string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; string str12 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL "; string str13 = "SELECT * FROM VinculoDocumento WHERE 1=1 "; sqlCommand.CommandText = string.Format("{0} {1} AND d.vigencia1 >= '{2:yyyy-MM-dd}' AND d.vigencia1 <= '{3:yyyy-MM-dd}' {4} {5} {6} {7} {8} {9} {10}", new object[] { str9, str8, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5 }); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable1); } if (dataTable1.Rows.Count != 0) { if (dataTable1.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null)) { string str14 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable1.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")"); DataTable dataTable5 = new DataTable(); sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str14, " ", str5 }); using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) { sqlDataAdapter1.SelectCommand = sqlCommand; sqlDataAdapter1.Fill(dataTable5); } foreach (DataRow row in dataTable1.Rows) { if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) { continue; } string str15 = string.Format("idcontrole = {0}", row["idcontrole"]); DataRow[] dataRowArray = dataTable5.Select(str15); if (dataRowArray.Length == 0) { continue; } row["idvendedor"] = dataRowArray[0][1]; } } string str16 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); sqlCommand.CommandText = string.Concat(str11, " ", str16); using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) { sqlDataAdapter2.SelectCommand = sqlCommand; sqlDataAdapter2.Fill(dataTable2); } string str17 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); sqlCommand.CommandText = string.Concat(str12, " ", str17); using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) { sqlDataAdapter3.SelectCommand = sqlCommand; sqlDataAdapter3.Fill(dataTable3); } try { string str18 = string.Concat(" AND IdDocumento IN (", string.Join(",", ( from x in dataTable1.AsEnumerable().ToList() select x.Field("id")).ToList()), ")"); sqlCommand.CommandText = string.Concat(str13, " ", str18); using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) { sqlDataAdapter4.SelectCommand = sqlCommand; sqlDataAdapter4.Fill(dataTable4); } } catch (Exception exception) { dataTable4 = null; } } else { return new List(); } } } return dataTable1.AsEnumerable().ToList().Select((DataRow x) => { VinculoDocumento vinculoDocumento; Func func2 = null; Documento documento = new Documento() { Id = x.Field("id"), Controle = new Controle() { IdEmpresa = x.Field("idempresa"), Cliente = new Cliente() { Id = x.Field("idcliente"), Nome = x.Field("cliente"), Documento = x.Field("cgccpf"), IdEmpresa = x.Field("idempresa"), Pasta = x.Field("pastacliente"), MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) }, Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), AssistenciaId = x.Field("AssistenciaId") }, TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), AdicionalComiss = x.Field("adinacomiss") == "1", Proposta = x.Field("proposta"), PropostaEndosso = x.Field("propostaendosso"), Comissao = x.Field("comissao"), Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), PremioLiquido = x.Field("liquido"), PremioTotal = x.Field("total"), Vigencia2 = x.Field("vigenciafinal") }; DateTime? nullable = x.Field("vigenciainicial"); documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { List list = dataTable2.AsEnumerable().ToList(); Func u003cu003e9_26 = func2; if (u003cu003e9_26 == null) { Func func = (DataRow d) => d.Field("id") == x.Field("id"); Func func1 = func; func2 = func; u003cu003e9_26 = func1; } IEnumerable dataRows = list.Where(u003cu003e9_26); Func u003cu003e9_3927 = DocumentoRepository.u003cu003ec.u003cu003e9__39_27; if (u003cu003e9_3927 == null) { u003cu003e9_3927 = (DataRow d) => d.Field("idvendedor"); DocumentoRepository.u003cu003ec.u003cu003e9__39_27 = u003cu003e9_3927; } return dataRows.Select(u003cu003e9_3927).ToList().Contains(v.Id); }).ToList(); documento.Tipo = x.Field("tipo"); documento.DataControle = x.Field("datacontrole"); documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); IEnumerable dataRows1 = from i in dataTable3.AsEnumerable().ToList() where i.Field("idcontrole") == x.Field("idcontrole") select i; Func u003cu003e9_3920 = DocumentoRepository.u003cu003ec.u003cu003e9__39_20; if (u003cu003e9_3920 == null) { u003cu003e9_3920 = (DataRow i) => new Item() { Id = i.Field("iditem"), Descricao = i.Field("descricao") }; DocumentoRepository.u003cu003ec.u003cu003e9__39_20 = u003cu003e9_3920; } documento.ItensAtivo = new List(dataRows1.Select(u003cu003e9_3920).ToList()); DataTable dataTable = dataTable4; if (dataTable != null) { EnumerableRowCollection dataRows2 = dataTable.AsEnumerable().Where((DataRow v) => v.Field("IdDocumento") == x.Field("id")); Func u003cu003e9_3922 = DocumentoRepository.u003cu003ec.u003cu003e9__39_22; if (u003cu003e9_3922 == null) { u003cu003e9_3922 = (DataRow v) => new VinculoDocumento() { Id = v.Field("Id"), IdDocumento = v.Field("IdDocumento"), IdPropostaDigital = v.Field("IdPropostaDigital"), IdApoliceDigital = v.Field("IdApoliceDigital") }; DocumentoRepository.u003cu003ec.u003cu003e9__39_22 = u003cu003e9_3922; } vinculoDocumento = dataRows2.Select(u003cu003e9_3922).FirstOrDefault(); } else { vinculoDocumento = null; } documento.Vinculo = vinculoDocumento; documento.Pasta = x.Field("Pasta"); documento.Banco = new Banco() { Nome = x.Field("nomebanco") }; documento.Agencia = x.Field("agencia"); documento.Conta = x.Field("conta"); return documento; }).ToList(); } public bool HasSinistro(long id) { return (new ControleSinistroRepository(this._unitOfWork)).DocumentoHasSinistro(id); } public bool HasSinistroPorControle(long controleId) { return (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(controleId); } public Documento Merge(Documento documento) { bool id; Status status = documento.Status; if (status != null) { id = status.Id == (long)0; } else { id = false; } if (id) { documento.Status = null; } if (!documento.DataCriacao.HasValue) { documento.DataCriacao = new DateTime?(Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime()); } DocumentoDb documentoDb = ApplicationMapper.Mapper.Map(documento); base.Merge(documentoDb); documento = ApplicationMapper.Mapper.Map(documentoDb); documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(documento.Id); return documento; } public void SalvarAssistencia(string id, long idcontrole) { ControleDb controleDb = this._unitOfWork.Query().FirstOrDefault((ControleDb x) => x.Id == idcontrole); if (controleDb == null) { return; } controleDb.AssistenciaId = id; this._unitOfWork.Repository().Merge(controleDb); } public Documento SaveOrUpdate(Documento documento) { bool id; Status status = documento.Status; if (status != null) { id = status.Id == (long)0; } else { id = false; } if (id) { documento.Status = null; } if (!documento.DataCriacao.HasValue) { documento.DataCriacao = new DateTime?(Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime()); } DocumentoDb documentoDb = ApplicationMapper.Mapper.Map(documento); this.SaveOrUpdate(documentoDb); documento = ApplicationMapper.Mapper.Map(documentoDb); documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(documento.Id); return documento; } private List Select(SqlQueryCondition sqlCondition) { DataTable dataTable = this._unitOfWork.Select(sqlCondition, "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); if (dataTable == null || dataTable.Rows.Count == 0) { return new List(); } this._unitOfWork.CriarAuxiliar(); List list = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcontrole")).Distinct().ToList(); List nums = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(list); return dataTable.MapDocumento(nums); } private async Task SomaComissaoPaga(int tipo, List fechamentos, Filtros filtro, List condicaoDocumento) { object connection; long num; using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) { SessionFactoryImpl sessionFactoryImpl = sessionFactory; if (sessionFactoryImpl != null) { connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { string str = "c.IdCiaSeg"; string str1 = "SUM(vp.vlrrep)"; string str2 = "FROM vendedorparcela vp INNER JOIN documento d ON vp.iddocumento = d.iddocumento INNER JOIN controle c ON c.IdControle = d.IdControle"; string str3 = "vp.DataPgt IS NOT NULL AND"; switch (tipo) { case 1: { str = "c.IdRamo"; break; } case 2: { str = "d.IdEstipulante"; break; } case 3: { str = "vp.IdVendedor"; break; } } SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0); sqlCommand.CommandTimeout = 1000; SqlCommand sqlCommand1 = sqlCommand; string[] condicao = new string[] { "SELECT ", str, " Id,", str1, " Paga ", str2, " WHERE ", str3, " ", sqlQueryCondition.Condicao, " GROUP BY ", str }; sqlCommand1.CommandText = string.Concat(condicao); sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { while (true) { if (!await sqlDataReader.ReadAsync()) { break; } bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id")); num = (flag ? (long)0 : (long)sqlDataReader["Id"]); long num1 = num; decimal item = (decimal)sqlDataReader["Paga"]; if (num1 != 0) { Fechamento fechamento = fechamentos.FirstOrDefault((Fechamento f) => { if (f.Entidade != tipo) { return false; } return f.Id == num1; }); if (fechamento != null) { Fechamento paga = fechamento; paga.Paga = paga.Paga + item; } } } } sqlDataReader = null; } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; } private async Task SomaComissaoRecebida(int tipo, List fechamentos, Filtros filtro, List condicaoDocumento) { object connection; bool flag; bool count; string str; long num; string empty; bool count1; bool flag1; using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) { SessionFactoryImpl sessionFactoryImpl = sessionFactory; if (sessionFactoryImpl != null) { connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { List vendedores = Auxiliar.Vendedores; long id = vendedores.FirstOrDefault((Vendedor v) => v.Corretora).Id; string str1 = "c.IdCiaSeg"; string str2 = "SUM(p.vlrcomiss)"; string str3 = "FROM parcela p INNER JOIN documento d ON p.iddocumento = d.iddocumento INNER JOIN controle c ON c.IdControle = d.IdControle"; string str4 = "p.DataRec IS NOT NULL AND"; switch (tipo) { case 1: { str1 = "c.IdRamo"; break; } case 2: { str1 = "d.IdEstipulante"; break; } case 3: { str1 = string.Format("CASE WHEN vp.IdVendedor IS NULL THEN {0} ELSE vp.IdVendedor END", id); break; } } bool flag2 = filtro.Vendedores.Contains(id); string str5 = ""; if (tipo == 3 && !flag2) { List tipoVendedor = filtro.TipoVendedor; if (tipoVendedor != null) { count1 = tipoVendedor.Count > 0; } else { count1 = false; } if (!count1) { List nums = filtro.Vendedores; if (nums != null) { flag1 = nums.Count > 0; } else { flag1 = false; } if (!flag1) { goto Label1; } } str5 = "LEFT JOIN vendedorparcela vp ON p.IDPARCELA = vp.IDPARCELA"; goto Label0; } Label1: string empty1 = string.Empty; flag = (filtro.TipoVendedor == null ? false : filtro.TipoVendedor.Count > 0); bool flag3 = flag; if (filtro.TipoVendedor != null && filtro.TipoVendedor.Count > 0) { if (flag3) { List tipoVendedor1 = filtro.TipoVendedor; empty = string.Join(",", from t in tipoVendedor1 select t.Value().ToString() ?? ""); } else { empty = string.Empty; } empty1 = empty; } List nums1 = filtro.TipoVendedor; if (nums1 != null) { count = nums1.Count > 0; } else { count = false; } str = (count ? string.Concat("OUTER APPLY ( SELECT TOP 1 idvendedor, idtipovendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", empty1, ")) vp") : "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp"); str5 = str; Label0: SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0); sqlCommand.CommandTimeout = 1000; SqlCommand sqlCommand1 = sqlCommand; string[] condicao = new string[] { "SELECT ", str1, " as Id,", str2, " Recebida ", str3, " ", str5, " WHERE ", str4, " ", sqlQueryCondition.Condicao, " GROUP BY ", str1 }; sqlCommand1.CommandText = string.Concat(condicao); sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { while (true) { if (!await sqlDataReader.ReadAsync()) { break; } bool flag4 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id")); num = (flag4 ? (long)0 : (long)sqlDataReader["Id"]); long num1 = num; decimal item = (decimal)sqlDataReader["Recebida"]; if (num1 != 0) { Fechamento fechamento = fechamentos.FirstOrDefault((Fechamento f) => { if (f.Entidade != tipo) { return false; } return f.Id == num1; }); if (fechamento != null) { Fechamento recebida = fechamento; recebida.Recebida = recebida.Recebida + item; } } } } sqlDataReader = null; } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; } public void TrocarCliente(Controle controle, Cliente cliente) { ControleDb controleDb = this._unitOfWork.Repository().FindEntityById(controle.Id); controleDb.Cliente = ApplicationMapper.Mapper.Map(cliente); this._unitOfWork.Repository().Merge(controleDb); } } }