using AutoMapper; using Gestor.Common.Helpers; using Gestor.Common.Validation; 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.PrevisaoPagamentoComissao; using Gestor.Model.Domain.Seguros; using NHibernate; using NHibernate.Connection; using NHibernate.Impl; using NHibernate.Util; 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 ParcelaRepository : GenericRepository, IParcelaRepository, IGenericRepository { private readonly GenericUnitOfWork _unitOfWork; public ParcelaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) { this._unitOfWork = unitOfWork; } public async Task> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) { List documentos = new List(); return await this.BuscaDocumentosPorVigenciaNew(filtro, buscaAssinaturas, painelBi); } private async Task> BuscaDocumentosPorVigenciaNew(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) { NegocioCorretora fieldValue; Predicate predicate; object connection; bool count; string str; bool flag; object vendedor; bool count1; Documento documento1; List itensAtivo; object produto; object obj; object statu; object banco; List statusDocumentoAssinados; bool flag1; StatusAssinatura statusAssinatura; NegocioCorretora negocioCorretora; bool count2; bool flag2; Predicate predicate1 = null; Predicate predicate2 = null; Predicate predicate3 = null; Predicate predicate4 = null; Predicate predicate5 = null; List documentos = new List(); string str1 = "CAST(f.vigenciai AS DATE)"; string referencia = filtro.Referencia; if (referencia == "EMISSÃO") { str1 = "CAST(f.emissao AS DATE)"; } else if (referencia == "TRANSMISSÃO PROPOSTA") { str1 = "CAST(d.remessa AS DATE)"; } else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") { str1 = "CAST(p.cri_data AS DATE)"; } List condicaos = this.CriaCondicaoDocumento(filtro, str1); List condicaos1 = new List(); Condicao condicao = new Condicao() { Campo = "d.Excluido", Valores = null, Grupo = 1, Operacao = Operacao.Or }; condicaos1.Add(condicao); Condicao condicao1 = new Condicao() { Campo = "d.Excluido", Valores = "0".CriarValor(), Grupo = 1, Operacao = Operacao.Or }; condicaos1.Add(condicao1); condicaos.AddRange(condicaos1); SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); 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; List parcelas = new List(); using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { sqlCommand.CommandTimeout = 1000; string str2 = "SELECT f.IDFATURA IdFatura, p.IDPARCELA IdParcela, d.IDDOCUMENTO IdDocumento, c.IDEMPRESA IdEmpresa, c.IDCLIENTE IdCliente, clie.CGCCPF DocumentoCliente, clie.MalaDireta MalaDireta, clie.NOME NomeCliente, clie.pasta PastaCliente, c.IDCONTROLE IdControle, cm.idclimail IdEmail, cm.email, ct.idclitelefone IdTelefone, ct.ddd Prefixo, ct.fone Numero, d.CONTRATO Apolice, d.PROPOSTA Proposta, d.PEDADIT PropostaEndosso, f.NumFatura NumeroFatura, f.Emissao EmissaoFatura, d.idnegocio Negocio, d.SITUACAO Situacao, f.VIGENCIAI VigenciaInicial, f.VIGENCIAF VigenciaFinal, p.VALOR PremioTotal, p.VALORLF PremioLiquido, p.comiss Comissao, 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.NegocioCorretora NegocioCorretora, p.datacontrole DataControleParcela, d.idstatus IdStatus, s.nome NomeStatus, p.CRI_DATA DataCriacaoParcela, d.TIPO Tipo, d.REMESSA Remessa, d.idbanco IdBanco, b.NOMEBANCO NomeBanco, d.AGENCIA Agencia, d.CONTA Conta, d.PASTA PastaDocumento, d.apoconferida ApoliceConferida, d.propassinada PropostaAssinada, vp.IDVENDEDORPARCELA IdVendedorParcela, vp.idtipovendedor IdTipoVendedor, vp.IDVENDEDOR IdVendedor, vp.VREP PorcentagemRepasse, v.NOME NomeVendedor 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 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.IDPARCELA = f.IDPARCELA LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN clitelefone ct ON ct.IDCLIENTE = c.IDCLIENTE LEFT JOIN climail cm ON cm.IDCLIENTE = c.IDCLIENTE WHERE "; sqlCommand.CommandText = string.Concat(str2, " ", sqlQueryCondition.Condicao, " ORDER BY f.IDPARCELA, 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 str3 = str; long num = sqlDataReader.GetFieldValue("IdDocumento", true, true); long fieldValue1 = sqlDataReader.GetFieldValue("IdParcela", true, true); Parcela observableCollection = parcelas.Find((Parcela p) => p.Id == fieldValue1); if (observableCollection == null) { Parcela parcela = parcelas.Find((Parcela d) => d.Documento.Id == num); if (parcela != null) { documento1 = parcela.Documento; } else { documento1 = null; } Documento zero = documento1; if (zero != null) { zero = zero.DeepCopy(); } else { long num1 = sqlDataReader.GetFieldValue("IdControle", true, true); long fieldValue2 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); Documento documento2 = documentos.Find((Documento p) => p.Controle.Id == num1); if (documento2 != null) { itensAtivo = documento2.ItensAtivo; } else { itensAtivo = null; } List items = itensAtivo; if (items == null) { items = await this.BuscaItemsPorIdControle(num1); } Documento valueOrDefault = new Documento() { Id = num }; Controle controle = new Controle() { Id = num1, IdEmpresa = fieldValue2 }; 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 observableCollection1 = new ObservableCollection(); ClienteTelefone clienteTelefone = new ClienteTelefone() { Id = sqlDataReader.GetFieldValue("IdTelefone", true, true), Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), Numero = sqlDataReader.GetFieldValue("Numero", true, true) }; observableCollection1.Add(clienteTelefone); cliente.Telefones = observableCollection1; ObservableCollection observableCollection2 = new ObservableCollection(); ClienteEmail clienteEmail = new ClienteEmail() { Id = sqlDataReader.GetFieldValue("IdEmail", true, true), Email = sqlDataReader.GetFieldValue("Email", true, true) }; observableCollection2.Add(clienteEmail); cliente.Emails = observableCollection2; controle.Cliente = cliente; Ramo ramo = new Ramo() { Id = sqlDataReader.GetFieldValue("IdRamo", true, true), Nome = sqlDataReader.GetFieldValue("NomeRamo", true, true) }; controle.Ramo = ramo; Seguradora seguradora = new Seguradora() { Id = sqlDataReader.GetFieldValue("IdCiaSeg", true, true), Nome = sqlDataReader.GetFieldValue("NomeCia", true, true), NomeSocial = sqlDataReader.GetFieldValue("NomeSocialCia", true, true) }; controle.Seguradora = seguradora; if (sqlDataReader.FieldIsNull("IdProduto")) { produto = null; } else { produto = new Produto(); ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("IdProduto", true, true); ((Produto)produto).Nome = sqlDataReader.GetFieldValue("NomeProduto", true, true); } controle.Produto = (Produto)produto; valueOrDefault.Controle = controle; if (sqlDataReader.FieldIsNull("IdEstipulante")) { obj = null; } else { obj = new Estipulante(); ((DomainBase)obj).Id = sqlDataReader.GetFieldValue("IdEstipulante", true, true); ((Estipulante)obj).Nome = sqlDataReader.GetFieldValue("NomeEstipulante", true, true); } valueOrDefault.Estipulante1 = (Estipulante)obj; valueOrDefault.Estipulantes = str3; if (sqlDataReader.FieldIsNull("IdStatus")) { statu = null; } else { statu = new Status(); ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("IdStatus", true, true); ((Status)statu).Nome = sqlDataReader.GetFieldValue("NomeStatus", true, true); } valueOrDefault.Status = (Status)statu; valueOrDefault.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura); valueOrDefault.Tipo = sqlDataReader.GetFieldValue("Tipo", true, true); valueOrDefault.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); valueOrDefault.Situacao = tipoSeguro; fieldValue3 = sqlDataReader.GetFieldValue("ApoliceConferida", true, true); valueOrDefault.ApoliceConferida = fieldValue3.GetValueOrDefault(); fieldValue3 = sqlDataReader.GetFieldValue("PropostaAssinada", true, true); valueOrDefault.PropostaAssinada = fieldValue3.GetValueOrDefault(); valueOrDefault.Proposta = sqlDataReader.GetFieldValue("Proposta", true, true); valueOrDefault.Apolice = sqlDataReader.GetFieldValue("Apolice", true, true); valueOrDefault.PropostaEndosso = sqlDataReader.GetFieldValue("PropostaEndosso", true, true); valueOrDefault.Remessa = sqlDataReader.GetFieldValue("Remessa", true, true); valueOrDefault.DataControle = sqlDataReader.GetFieldValue("DataControleParcela", true, true); valueOrDefault.DataCriacao = sqlDataReader.GetFieldValue("DataCriacaoParcela", true, true); valueOrDefault.Pasta = sqlDataReader.GetFieldValue("PastaDocumento", true, true); if (sqlDataReader.FieldIsNull("IdBanco")) { banco = null; } else { banco = new Banco(); ((Banco)banco).Id = sqlDataReader.GetFieldValue("IdBanco", true, true); ((Banco)banco).Nome = sqlDataReader.GetFieldValue("NomeBanco", true, true); } valueOrDefault.Banco = (Banco)banco; valueOrDefault.Agencia = sqlDataReader.GetFieldValue("Agencia", true, true); valueOrDefault.Conta = sqlDataReader.GetFieldValue("Conta", true, true); valueOrDefault.ItensAtivo = items; zero = valueOrDefault; if (flag4 & buscaAssinaturas) { List statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(zero.Id); string str4 = (zero.Tipo == 0 ? "PROPOSTA" : "PEDIDO DE ENDOSSO"); statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => { if (a.Documento.ToUpper() == str4 || a.Documento.ToUpper().Contains(str4)) { a.Selecionado = true; } }); List statusDocumentoAssinados2 = statusDocumentoAssinados1; StatusDocumentoAssinado statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault((StatusDocumentoAssinado a) => a.Selecionado); Documento documento3 = zero; if (statusDocumentoAssinados1 == null || statusDocumentoAssinados1.Count <= 0) { statusDocumentoAssinados = null; } else { statusDocumentoAssinados = statusDocumentoAssinados1; } documento3.Assinaturas = statusDocumentoAssinados; Documento documento4 = zero; flag1 = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status == StatusAssinatura.Assinado : false); documento4.AssinadaSiggner = flag1; Documento documento5 = zero; statusAssinatura = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status : StatusAssinatura.NaoEnviado); documento5.StatusAssinatura = statusAssinatura; } } zero.Tipo = 2; zero.AdicionalComiss = false; zero.PremioAdicional = decimal.Zero; zero.NumeroParcelas = decimal.One; zero.Endosso = string.Concat("F ", sqlDataReader.GetFieldValue("NumeroFatura", true, true)); zero.Comissao = sqlDataReader.GetFieldValue("Comissao", true, true); zero.PremioLiquido = sqlDataReader.GetFieldValue("PremioLiquido", true, true); zero.PremioTotal = sqlDataReader.GetFieldValue("PremioTotal", true, true); zero.Vigencia1 = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); zero.Vigencia2 = sqlDataReader.GetFieldValue("VigenciaFinal", true, true); zero.Emissao = sqlDataReader.GetFieldValue("EmissaoFatura", true, true); zero.DataControle = sqlDataReader.GetFieldValue("DataControleParcela", true, true); if (zero.Controle.Cliente.Telefones != null) { long num2 = sqlDataReader.GetFieldValue("IdTelefone", true, true); if (zero.Controle.Cliente.Telefones.FirstOrDefault((ClienteTelefone t) => t.Id == num2) == null) { ObservableCollection telefones = zero.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 (zero.Controle.Cliente.Emails != null) { long num3 = sqlDataReader.GetFieldValue("IdEmail", true, true); if (zero.Controle.Cliente.Emails.FirstOrDefault((ClienteEmail t) => t.Id == num3) == null) { ObservableCollection emails = zero.Controle.Cliente.Emails; ClienteEmail clienteEmail1 = new ClienteEmail() { Id = num3, Email = sqlDataReader.GetFieldValue("Email", true, true) }; emails.Add(clienteEmail1); } } Parcela parcela1 = new Parcela() { Id = fieldValue1, Documento = zero }; observableCollection = parcela1; parcelas.Add(observableCollection); zero = null; } List tipoVendedor = filtro.TipoVendedor; if (tipoVendedor != null) { flag = tipoVendedor.Count > 0; } else { flag = false; } if (!flag) { List nums = filtro.Vendedores; if (nums != null) { count1 = nums.Count > 0; } else { count1 = false; } if (!count1) { if (observableCollection.Vendedores == null) { observableCollection.Vendedores = new ObservableCollection(); } long fieldValue4 = sqlDataReader.GetFieldValue("IdTipoVendedor", true, true); long num4 = sqlDataReader.GetFieldValue("IdVendedor", true, true); if (observableCollection.Vendedores.ToList().Find((VendedorParcela vps) => { if (vps.TipoVendedor.Id != fieldValue4) { return false; } return vps.Vendedor.Id == num4; }) == null) { ObservableCollection observableCollection3 = observableCollection.Vendedores; VendedorParcela vendedorParcela1 = new VendedorParcela() { PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue("PorcentagemRepasse", true, true)), TipoVendedor = new TipoVendedor() { Id = fieldValue4 } }; Vendedor vendedor1 = new Vendedor() { Id = num4, Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true) }; vendedorParcela1.Vendedor = vendedor1; observableCollection3.Add(vendedorParcela1); } } } if (observableCollection.Documento.VendedorPrincipal == null) { Documento documento6 = observableCollection.Documento; if (sqlDataReader.FieldIsNull("IdVendedor")) { vendedor = null; } else { vendedor = new Vendedor(); ((DomainBase)vendedor).Id = sqlDataReader.GetFieldValue("IdVendedor", true, true); ((Vendedor)vendedor).Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true); } documento6.VendedorPrincipal = (Vendedor)vendedor; } str3 = null; } } } } sqlCommand = null; List tipoVendedor1 = filtro.TipoVendedor; if (tipoVendedor1 != null) { count2 = tipoVendedor1.Count > 0; } else { count2 = false; } if (!count2) { List nums1 = filtro.Vendedores; if (nums1 != null) { flag2 = nums1.Count > 0; } else { flag2 = false; } if (!flag2) { goto Label0; } } foreach (Parcela parcela2 in parcelas) { Parcela parcela3 = parcela2; List vendedorParcelas1 = await this.BuscaVendedoresPorIdParcela(parcela2.Id, parcela2.Documento.Controle.IdEmpresa, (long)1); parcela3.Vendedores = new ObservableCollection(vendedorParcelas1); parcela3 = null; } Label0: parcelas.ForEach((Parcela p) => { decimal? nullable2; decimal? porcentagemRepasse; ObservableCollection vendedores = p.Vendedores; Func u003cu003e9_1516 = ParcelaRepository.u003cu003ec.u003cu003e9__15_16; if (u003cu003e9_1516 == null) { u003cu003e9_1516 = (VendedorParcela tipo) => tipo.TipoVendedor.Id; ParcelaRepository.u003cu003ec.u003cu003e9__15_16 = u003cu003e9_1516; } IOrderedEnumerable vendedorParcelas = vendedores.OrderBy(u003cu003e9_1516); Func u003cu003e9_1517 = ParcelaRepository.u003cu003ec.u003cu003e9__15_17; if (u003cu003e9_1517 == null) { u003cu003e9_1517 = (VendedorParcela v) => v.Vendedor; ParcelaRepository.u003cu003ec.u003cu003e9__15_17 = u003cu003e9_1517; } List list = vendedorParcelas.Select(u003cu003e9_1517).ToList(); p.Documento.Vendedores = list; Documento documento = p.Documento; VendedorParcela vendedorParcela = p.Vendedores.FirstOrDefault((VendedorParcela v) => { long? nullable; long id = v.Vendedor.Id; Vendedor vendedorPrincipal = p.Documento.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()); documentos.Add(p.Documento); }); parcelas = null; } sqlConnection = null; } sessionFactory = null; List documentos1 = documentos; sqlQueryCondition = null; return documentos1; } private async Task> BuscaDocumentosPorVigenciaPrivate(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) { NegocioCorretora negocioCorretora; List.Enumerator enumerator; decimal? nullable; DateTime? nullable1; object connection; bool count; string str; bool flag; Seguradora seguradora; Ramo ramo1; Produto produto1; bool flag1; Negocio negocio; DateTime? nullable2; DateTime dateTime; DateTime? nullable3; DateTime? nullable4; Estipulante estipulante1; DateTime? nullable5; Status statu; bool flag2; List statusDocumentoAssinados; bool flag3; StatusAssinatura statusAssinatura; DateTime? nullable6; decimal? porcentagemRepasse; List list; List nums; NegocioCorretora negocioCorretora1; bool count1; Func func = null; Func func1 = null; Func func2 = null; Func func3 = null; Func func4 = null; Func func5 = null; List documentos = new List(); string str1 = "CAST(f.vigenciai AS DATE)"; string referencia = filtro.Referencia; if (referencia == "EMISSÃO") { str1 = "CAST(f.emissao AS DATE)"; } else if (referencia == "TRANSMISSÃO PROPOSTA") { str1 = "CAST(d.remessa AS DATE)"; } else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") { str1 = "CAST(p.cri_data AS DATE)"; } List condicaos = this.CriaCondicaoDocumento(filtro, str1); List condicaos1 = new List(); Condicao condicao = new Condicao() { Campo = "d.Excluido", Valores = null, Grupo = 1, Operacao = Operacao.Or }; condicaos1.Add(condicao); Condicao condicao1 = new Condicao() { Campo = "d.Excluido", Valores = "0".CriarValor(), Grupo = 1, Operacao = Operacao.Or }; condicaos1.Add(condicao1); condicaos.AddRange(condicaos1); SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); 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 = 0; Auxiliar.CriarAuxiliar(sqlCommand, false); bool flag4 = await this.ExisteTabelasAssinatura(); bool flag5 = flag4; List tipoVendedor = filtro.TipoVendedor; if (tipoVendedor != null) { count = tipoVendedor.Count > 0; } else { count = false; } if (!count) { List vendedores = filtro.Vendedores; if (vendedores != null) { count1 = vendedores.Count > 0; } else { count1 = false; } if (count1) { goto Label1; } str = ""; goto Label0; } Label1: str = "INNER JOIN vendedorparcela vp ON p.idparcela = vp.idparcela"; Label0: string str2 = string.Concat("SELECT DISTINCT c.IdEmpresa,c.IdCliente,cli.CGCCPF,cli.MalaDireta,cli.Nome,d.IdControle,p.IdParcela,d.IdDocumento,d.Contrato,f.NumFatura,f.Emissao,d.IdNegocio,d.Situacao,f.VigenciaI,f.VigenciaF,ISNULL(p.Valor, 0.00) Total,ISNULL(p.ValorLF, 0.00) Liquido,ISNULL(p.comiss, 0.00) Comissao,c.IdRamo,c.IdCiaSeg,c.IdProduto,d.IdEstipulante,d.NegocioCorretora,p.DataControle,d.IdStatus,p.Cri_Data,d.Remessa,d.IdBanco,cb.NomeBanco,d.Agencia,d.Conta,d.Pasta,d.ApoConferida,d.PropAssinada,cli.pasta PastaCliente FROM fatura f INNER JOIN parcela p ON p.IdParcela = f.IdParcela ", str, " INNER JOIN documento d ON d.IdDocumento = p.IdDocumento INNER JOIN controle c ON c.IdControle = d.IdControle INNER JOIN cliente cli ON cli.IdCliente = c.IdCliente LEFT JOIN codigobanco cb ON d.idbanco = cb.idcodigobanco WHERE "); sqlCommand.CommandText = string.Concat(str2, " ", sqlQueryCondition.Condicao); sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { while (true) { if (!await sqlDataReader.ReadAsync()) { break; } long item = (long)sqlDataReader["idparcela"]; long num = (long)sqlDataReader["iddocumento"]; long item1 = (long)sqlDataReader["idcontrole"]; long num1 = (long)sqlDataReader["idempresa"]; string str3 = "PEDIDO DE ENDOSSO"; if (!await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("negociocorretora"))) { negocioCorretora = (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), sqlDataReader["negociocorretora"].ToString()); } else { flag4 = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()) == TipoSeguro.Renovacao; if (flag4) { flag4 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio")); } negocioCorretora1 = (!flag4 || !(sqlDataReader["idnegocio"].ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); negocioCorretora = negocioCorretora1; } NegocioCorretora negocioCorretora2 = negocioCorretora; Vendedor vendedor = new Vendedor(); List vendedors = new List(); List items = new List(); List statusDocumentoAssinados1 = new List(); StatusDocumentoAssinado statusDocumentoAssinado = null; decimal valueOrDefault = new decimal(); if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora2)) { if (!painelBi) { List vendedorParcelas = await this.BuscaVendedoresPorIdParcela(item, num1, (long)1); if (filtro.Vendedores != null && filtro.Vendedores.Count > 0) { bool flag6 = true; foreach (long list1 in filtro.Vendedores.ToList()) { if (!vendedorParcelas.Any((VendedorParcela v) => v.Vendedor.Id == list1)) { continue; } flag6 = false; } if (flag6) { continue; } } List vendedorParcelas1 = vendedorParcelas; IOrderedEnumerable id = from tipo in vendedorParcelas1 orderby tipo.TipoVendedor.Id select tipo; vendedors = ( from v in id select v.Vendedor).ToList(); if (filtro.TipoVendedor != null && filtro.TipoVendedor.Count != 0) { if (filtro.TipoVendedor != null) { List tipoVendedor1 = filtro.TipoVendedor; if (tipoVendedor1.Any((long v) => v == (long)1)) { goto Label3; } } Vendedor vendedor1 = null; Filtros filtro1 = filtro; if (filtro1 != null) { List nums1 = filtro1.TipoVendedor; if (nums1 != null) { list = ( from t in nums1 orderby t select t).ToList(); } else { list = null; } } else { list = null; } enumerator = list.GetEnumerator(); try { do { if (!enumerator.MoveNext()) { break; } long current = enumerator.Current; Filtros filtro2 = filtro; if (filtro2 != null) { List vendedores1 = filtro2.Vendedores; if (vendedores1 != null) { nums = vendedores1.ToList(); } else { nums = null; } } else { nums = null; } List.Enumerator enumerator1 = nums.GetEnumerator(); try { do { if (!enumerator1.MoveNext()) { break; } long current1 = enumerator1.Current; IEnumerable vendedorParcelas2 = vendedorParcelas.Where((VendedorParcela v) => { if (v.TipoVendedor.Id != current) { return false; } return v.Vendedor.Id == current1; }); vendedor1 = ( from v in vendedorParcelas2 select v.Vendedor).FirstOrDefault(); } while (vendedor1 == null); } finally { ((IDisposable)enumerator1).Dispose(); } } while (vendedor1 == null); } finally { ((IDisposable)enumerator).Dispose(); } if ((filtro.Vendedores == null || filtro.Vendedores.Count == 0) && vendedor1 == null) { List vendedorParcelas3 = vendedorParcelas; Func func6 = func; if (func6 == null) { Func id1 = (VendedorParcela v) => v.TipoVendedor.Id == filtro.TipoVendedor.FirstOrDefault(); Func func7 = id1; func = id1; func6 = func7; } IEnumerable vendedorParcelas4 = vendedorParcelas3.Where(func6); vendedor1 = ( from v in vendedorParcelas4 select v.Vendedor).FirstOrDefault(); } Vendedor vendedor2 = vendedor1; if (vendedor2 == null) { vendedor2 = vendedors.FirstOrDefault(); } vendedor = vendedor2; goto Label2; } List vendedorParcelas5 = vendedorParcelas; IEnumerable id2 = from v in vendedorParcelas5 where v.TipoVendedor.Id == (long)1 select v; vendedor = ( from v in id2 select v.Vendedor).FirstOrDefault(); Label2: VendedorParcela vendedorParcela = vendedorParcelas.FirstOrDefault((VendedorParcela v) => v.Vendedor.Id == vendedor.Id); if (vendedorParcela != null) { porcentagemRepasse = vendedorParcela.PorcentagemRepasse; } else { nullable = null; porcentagemRepasse = nullable; } nullable = porcentagemRepasse; valueOrDefault = nullable.GetValueOrDefault(); if (flag5 & buscaAssinaturas) { statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(num); statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => { if (a.Documento.ToUpper() == str3 || a.Documento.ToUpper().Contains(str3)) { a.Selecionado = true; } }); List statusDocumentoAssinados2 = statusDocumentoAssinados1; statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault((StatusDocumentoAssinado a) => a.Selecionado); } items = await this.BuscaItemsPorIdControle(item1); } List documentos1 = documentos; Documento documento = new Documento() { Id = num }; Documento documento1 = documento; Controle controle = new Controle() { Id = item1, IdEmpresa = num1 }; Controle controle1 = controle; Cliente cliente = new Cliente() { Id = (long)sqlDataReader["idcliente"], Nome = sqlDataReader["nome"].ToString(), Documento = sqlDataReader["cgccpf"].ToString(), IdEmpresa = num1, Pasta = sqlDataReader["pastacliente"].ToString() }; Cliente cliente1 = cliente; flag4 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("maladireta")); Cliente cliente2 = cliente1; flag = (flag4 ? true : (bool)sqlDataReader["maladireta"]); cliente2.MalaDireta = new bool?(flag); controle1.Cliente = cliente; Controle controle2 = controle; bool flag7 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idciaseg")); Controle controle3 = controle2; if (flag7) { seguradora = null; } else { List seguradoras = Auxiliar.Seguradoras; Func func8 = func1; if (func8 == null) { Func id3 = (Seguradora seg) => seg.Id == (long)sqlDataReader["idciaseg"]; Func func9 = id3; func1 = id3; func8 = func9; } seguradora = seguradoras.FirstOrDefault(func8); } controle3.Seguradora = seguradora; Controle controle4 = controle; bool flag8 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idramo")); Controle controle5 = controle4; if (flag8) { ramo1 = null; } else { List ramos = Auxiliar.Ramos; Func func10 = func2; if (func10 == null) { Func id4 = (Ramo ramo) => ramo.Id == (long)sqlDataReader["idramo"]; Func func11 = id4; func2 = id4; func10 = func11; } ramo1 = ramos.FirstOrDefault(func10); } controle5.Ramo = ramo1; Controle controle6 = controle; bool flag9 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idproduto")); Controle controle7 = controle6; if (flag9) { produto1 = null; } else { List produtos = Auxiliar.Produtos; Func func12 = func3; if (func12 == null) { Func id5 = (Produto produto) => produto.Id == (long)sqlDataReader["idproduto"]; Func func13 = id5; func3 = id5; func12 = func13; } produto1 = produtos.FirstOrDefault(func12); } controle7.Produto = produto1; documento1.Controle = controle; documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura); documento.AdicionalComiss = false; documento.Apolice = sqlDataReader["contrato"].ToString(); Documento documento2 = documento; bool flag10 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("apoconferida")); Documento documento3 = documento2; flag1 = (flag10 ? false : sqlDataReader["apoconferida"].ToString() == "1"); documento3.ApoliceConferida = flag1; documento.Endosso = string.Format("F {0}", sqlDataReader["numfatura"]); documento.Comissao = (decimal)sqlDataReader["comissao"]; Documento documento4 = documento; bool flag11 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio")); Documento documento5 = documento4; negocio = (flag11 ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), sqlDataReader["idnegocio"].ToString())); documento5.Negocio = new Negocio?(negocio); documento.PremioLiquido = (decimal)sqlDataReader["liquido"]; documento.PremioTotal = (decimal)sqlDataReader["total"]; documento.NumeroParcelas = decimal.One; Documento documento6 = documento; bool flag12 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vigenciaf")); Documento documento7 = documento6; if (flag12) { nullable1 = null; nullable2 = nullable1; } else { nullable2 = new DateTime?((DateTime)sqlDataReader["vigenciaf"]); } documento7.Vigencia2 = nullable2; Documento documento8 = documento; bool flag13 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vigenciai")); Documento documento9 = documento8; dateTime = (flag13 ? DateTime.MinValue : (DateTime)sqlDataReader["vigenciai"]); documento9.Vigencia1 = dateTime; Documento documento10 = documento; bool flag14 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("emissao")); Documento documento11 = documento10; if (flag14) { nullable1 = null; nullable3 = nullable1; } else { nullable3 = new DateTime?((DateTime)sqlDataReader["emissao"]); } documento11.Emissao = nullable3; Documento documento12 = documento; bool flag15 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("remessa")); Documento documento13 = documento12; if (flag15) { nullable1 = null; nullable4 = nullable1; } else { nullable4 = new DateTime?((DateTime)sqlDataReader["remessa"]); } documento13.Remessa = nullable4; documento.PercentualRepasse = new decimal?(valueOrDefault); Documento documento14 = documento; bool flag16 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idestipulante")); Documento documento15 = documento14; if (flag16) { estipulante1 = null; } else { List estipulantes = Auxiliar.Estipulantes; Func func14 = func4; if (func14 == null) { Func id6 = (Estipulante estipulante) => estipulante.Id == (long)sqlDataReader["idestipulante"]; Func func15 = id6; func4 = id6; func14 = func15; } estipulante1 = estipulantes.FirstOrDefault(func14); } documento15.Estipulante1 = estipulante1; documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora2); documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()); documento.Tipo = 2; Documento documento16 = documento; bool flag17 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("datacontrole")); Documento documento17 = documento16; if (flag17) { nullable1 = null; nullable5 = nullable1; } else { nullable5 = new DateTime?((DateTime)sqlDataReader["datacontrole"]); } documento17.DataControle = nullable5; Documento documento18 = documento; bool flag18 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idstatus")); Documento documento19 = documento18; if (flag18) { statu = null; } else { List statusApolice = Auxiliar.StatusApolice; Func func16 = func5; if (func16 == null) { Func id7 = (Status status) => status.Id == (long)sqlDataReader["idstatus"]; Func func17 = id7; func5 = id7; func16 = func17; } statu = statusApolice.FirstOrDefault(func16); } documento19.Status = statu; documento.ItensAtivo = items; Documento documento20 = documento; bool flag19 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("propassinada")); Documento documento21 = documento20; flag2 = (flag19 ? false : sqlDataReader["propassinada"].ToString() == "1"); documento21.PropostaAssinada = flag2; documento.VendedorPrincipal = vendedor; documento.Vendedores = vendedors; Documento documento22 = documento; if (statusDocumentoAssinados1.Count == 0) { statusDocumentoAssinados = null; } else { statusDocumentoAssinados = statusDocumentoAssinados1; } documento22.Assinaturas = statusDocumentoAssinados; Documento documento23 = documento; StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado; if (statusDocumentoAssinado1 != null) { flag3 = statusDocumentoAssinado1.Status == StatusAssinatura.Assinado; } else { flag3 = false; } documento23.AssinadaSiggner = flag3; Documento documento24 = documento; StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado; if (statusDocumentoAssinado2 != null) { statusAssinatura = statusDocumentoAssinado2.Status; } else { statusAssinatura = StatusAssinatura.NaoEnviado; } documento24.StatusAssinatura = statusAssinatura; documento.Pasta = sqlDataReader["pasta"].ToString(); Documento documento25 = documento; bool flag20 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("cri_data")); Documento documento26 = documento25; if (flag20) { nullable1 = null; nullable6 = nullable1; } else { nullable6 = new DateTime?((DateTime)sqlDataReader["cri_data"]); } documento26.DataCriacao = nullable6; Documento documento27 = documento; Banco banco = new Banco() { Nome = sqlDataReader["nomebanco"].ToString() }; documento27.Banco = banco; documento.Agencia = sqlDataReader["agencia"].ToString(); documento.Conta = sqlDataReader["conta"].ToString(); documentos1.Add(documento); documentos1 = null; documento1 = null; controle1 = null; cliente1 = null; cliente = null; controle2 = null; controle4 = null; controle6 = null; controle = null; documento2 = null; documento4 = null; documento6 = null; documento8 = null; documento10 = null; documento12 = null; documento14 = null; documento16 = null; documento18 = null; documento20 = null; documento25 = null; documento = null; vendedors = null; items = null; statusDocumentoAssinados1 = null; statusDocumentoAssinado = null; } } } } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; List documentos2 = documentos; documentos = null; sqlQueryCondition = null; return documentos2; } 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 = sqlDataReader.GetFieldValue("iditem", true, true), Descricao = sqlDataReader.GetFieldValue("descricao", true, true) }; items1.Add(item); } } sqlDataReader = null; } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; List items2 = items; items = null; return items2; } private async Task> BuscaItemsPorIdControle(SqlConnection connection, long idControle) { List items = new List(); using (SqlCommand sqlCommand = connection.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; List items2 = items; items = null; return items2; } public Documento BuscarApolice(long id) { DocumentoDb documento; ParcelaDb parcelaDb = base.All().FirstOrDefault((ParcelaDb x) => x.Id == id); if (parcelaDb != null) { documento = parcelaDb.Documento; } else { documento = null; } return ApplicationMapper.Mapper.Map(documento); } 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 = "IDParcela".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 ParcelaPendente BuscarPendencia(long id) { ParcelaPendente parcelaPendente; object connection; 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()) { try { sqlCommand.CommandText = string.Format("SELECT * FROM parcelapendente WHERE idparcelapendente = {0}", id); SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); if (sqlDataReader.HasRows) { sqlDataReader.Read(); parcelaPendente = new ParcelaPendente() { Id = (long)sqlDataReader["idparcelapendente"], IdParcela = (long)sqlDataReader["idparcela"], Seguradora = (string)sqlDataReader["seguradora"], Cliente = (string)sqlDataReader["cliente"], Apolice = (string)sqlDataReader["apolice"], Parcela = (int)sqlDataReader["parcela"], Valor = decimal.Parse(sqlDataReader["valor"].ToString()), Vencimento = DateTime.Parse(sqlDataReader["vencto"].ToString()) }; } else { parcelaPendente = null; } } catch (Exception exception) { parcelaPendente = null; } } } return parcelaPendente; } 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> BuscaVendedoresPorIdParcela(long idParcela, long idEmpresa = 0L, long idSubTipo = 0L) { object connection; string str; string str1; 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()) { str = (idSubTipo > (long)0 ? " INNER JOIN parcela p ON p.idparcela = vp.idparcela " : string.Empty); string str2 = str; str1 = (idSubTipo > (long)0 ? " AND p.idsubtipo = @subtipo " : string.Empty); string str3 = string.Concat("SELECT DISTINCT vp.idvendedor,v.nome nomevendedor,vp.vrep,vp.vlrrep,vp.dataprepagto,vp.datapgt,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN vendedor v ON v.idvendedor = vp.idvendedor ", str2, " WHERE vp.idparcela = @parcela ", str1); sqlCommand.CommandTimeout = 1000; sqlCommand.CommandText = str3; sqlCommand.Parameters.Add("@parcela", SqlDbType.BigInt).Value = idParcela; sqlCommand.Parameters.Add("@subtipo", SqlDbType.BigInt).Value = idSubTipo; 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; Vendedor vendedor = new Vendedor() { Id = sqlDataReader.GetFieldValue("idvendedor", true, true), Nome = sqlDataReader.GetFieldValue("nomevendedor", true, true) }; vendedorParcela.Vendedor = vendedor; vendedorParcela.PorcentagemRepasse = sqlDataReader.GetFieldValue("vrep", true, true); vendedorParcela.ValorRepasse = sqlDataReader.GetFieldValue("vlrrep", true, true); vendedorParcela.DataPagamento = sqlDataReader.GetFieldValue("datapgt", true, true); vendedorParcela.DataPrePagamento = sqlDataReader.GetFieldValue("dataprepagto", true, true); vendedorParcelas1.Add(vendedorParcela); } if (idEmpresa > (long)0) { 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); } } } sqlDataReader = null; } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; List vendedorParcelas4 = vendedorParcelas; List list = ( from v in vendedorParcelas4 orderby v.TipoVendedor.Id select v).ToList(); vendedorParcelas = null; return list; } 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(), Grupo = 5 }); } 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(), Grupo = 5 }); } 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(), Grupo = 5 }); } 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(), Grupo = 5 }); } 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(), Grupo = 5, Operacao = Operacao.Or }); } 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(), Grupo = 5 }); } 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(), Grupo = 5 }); } 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(), Grupo = 5 }); } return condicaos; } private List CriaCondicaoFaturaPendente(Filtros filtro, string referencia) { return new List() { new Condicao() { Campo = referencia, Valores = filtro.Inicio.CriarValor(), Operador = Operador.MenorEIgual }, new Condicao() { Campo = referencia, Valores = filtro.Fim.CriarValor(), Operador = Operador.MaiorEIgual } }; } private List CriaCondicaoFaturaPendenteVigencia(Filtros filtro, string referencia, string referencia2) { 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.Fim.CriarValor(), Operador = Operador.MenorEIgual }, new Condicao() { Campo = referencia2, Valores = filtro.Inicio.CriarValor(), Grupo = 1, Operador = Operador.MaiorEIgual, Operacao = Operacao.Or }, new Condicao() { Campo = referencia2, Valores = null, Grupo = 1 } }; 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(), Grupo = 5 }); } 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(), Grupo = 5 }); } 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(), Grupo = 5 }); } 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(), Grupo = 5 }); } 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(), Grupo = 5, Operacao = Operacao.Or }); } 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(), Grupo = 5 }); } 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(), Grupo = 5 }); } 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 = 5 }); condicaos.Add(new Condicao() { Campo = "d.NegocioCorretora", Valores = null, Operacao = Operacao.Or, Grupo = 5 }); } if (filtro.IdEmpresa > (long)0) { condicaos.Add(new Condicao() { Campo = "c.idempresa", Valores = filtro.IdEmpresa.CriarValor(), Grupo = 5 }); } return condicaos; } private List CriarCondicaoFatura(Filtros filtro, string referencia) { bool count; 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 }, new Condicao() { Campo = "d.tiporecebimento", Valores = 2.CriarValor() } }; Condicao condicao = new Condicao() { Campo = referencia }; DateTime inicio = filtro.Inicio; condicao.Valores = inicio.ToString("yyyy-MM-dd").CriarValor(); condicao.Operador = Operador.MaiorEIgual; condicaos.Add(condicao); Condicao condicao1 = new Condicao() { Campo = referencia }; inicio = filtro.Fim; condicao1.Valores = inicio.ToString("yyyy-MM-dd").CriarValor(); condicao1.Operador = Operador.MenorEIgual; condicaos.Add(condicao1); condicaos.Add(new Condicao() { Campo = "p.valorr", Valores = 0.CriarValor() }); condicaos.Add(new Condicao() { Campo = "p.datarec", Valores = null }); List condicaos1 = condicaos; if (filtro.Status.Count > 0) { condicaos1.Add(new Condicao() { Campo = "situacao", Valores = filtro.Status.CriarValor() }); } if (filtro.Negocio.Count > 0) { condicaos1.Add(new Condicao() { Campo = "negociocorretora", Valores = filtro.Negocio.CriarValor() }); } if (filtro.Seguradoras.Count > 0) { condicaos1.Add(new Condicao() { Campo = "c.idciaseg", Valores = filtro.Seguradoras.CriarValor() }); } if (filtro.Ramos.Count > 0) { condicaos1.Add(new Condicao() { Campo = "c.idramo", Valores = filtro.Ramos.CriarValor() }); } if (filtro.Produtos.Count > 0) { condicaos1.Add(new Condicao() { Campo = "c.idproduto", Valores = filtro.Produtos.CriarValor() }); } if (filtro.Vendedores.Count > 0) { condicaos1.Add(new Condicao() { Campo = "vp.idvendedor", Valores = filtro.Vendedores.CriarValor(), Grupo = 2, Operacao = Operacao.Or }); condicaos1.Add(new Condicao() { Campo = "vp.idvendedor", Valores = null, Operacao = Operacao.Or, Grupo = 2 }); } if (filtro.Estipulantes.Count > 0) { condicaos1.Add(new Condicao() { Campo = "d.idestipulante", Valores = filtro.Estipulantes.CriarValor() }); } if (filtro.IdEmpresa > (long)0) { condicaos1.Add(new Condicao() { Campo = "c.idempresa", Valores = filtro.IdEmpresa.CriarValor() }); } List tipoVendedor = filtro.TipoVendedor; if (tipoVendedor != null) { count = tipoVendedor.Count > 0; } else { count = false; } if (count) { condicaos1.Add(new Condicao() { Campo = "vp.idtipovendedor", Valores = filtro.TipoVendedor.CriarValor() }); } return condicaos1; } public void Delete(long id) { List list = ( from x in this._unitOfWork.Query() where x.Parcela.Id == id select x).ToList(); if (list.Any()) { this._unitOfWork.Repository().DeleteRange(list); } ParcelaDb parcelaDb = base.FindEntityById(id); if (parcelaDb == null) { return; } base.Delete(parcelaDb); } public void DeleteRange(long id) { List list = ( from x in this._unitOfWork.Query() where x.Parcela.Documento.Id == id select x).ToList(); if (list.Any()) { this._unitOfWork.Repository().DeleteRange(list); } List parcelaDbs = ( from i in base.All() where i.Documento.Id == id && (int)i.SubTipo == 1 select i).ToList(); base.DeleteRange(parcelaDbs); } public bool ExcluirVinculoParcelaPendenteDocExcluido(Documento doc) { object connection; try { List parcelas = this.FindByDocumento(doc); if (parcelas != null && parcelas.Count > 0) { SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { parcelas.ForEach((Parcela p) => { using (SqlCommand id = sqlConnection.CreateCommand()) { id.CommandText = "UPDATE ParcelaPendente SET IdParcela = NULL WHERE IdParcela = @parcela"; id.Parameters.Add("@parcela", SqlDbType.BigInt).Value = p.Id; id.ExecuteNonQuery(); } }); } return true; } } catch { } return false; } 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> FaturaPendente(Filtros filtro) { List documentos; NegocioCorretora fieldValue; object connection; bool count; List itensAtivo; DateTime dateTime; DateTime dateTime1; DateTime dateTime2; DateTime dateTime3; object produto; string str; Vendedor vendedor; Estipulante estipulante; object statu; NegocioCorretora negocioCorretora; Func func = null; Func func1 = null; string str1 = "f.vigenciai"; string str2 = "d.vigencia1"; string str3 = "d.vigencia2"; if (filtro.Referencia == "VENCIMENTO") { str1 = "p.vencto"; } List condicaos = this.CriaCondicaoFaturaPendenteVigencia(filtro, str2, str3); List condicaos1 = this.CriaCondicaoFaturaPendente(filtro, str1); List condicaos2 = new List(); Condicao condicao = new Condicao() { Campo = "d.tiporecebimento", Valores = 2.CriarValor(), Grupo = 2 }; condicaos2.Add(condicao); List condicaos3 = condicaos2; List condicaos4 = new List(); Condicao condicao1 = new Condicao() { Campo = "d.Excluido", Valores = null, Grupo = 4, Operacao = Operacao.Or }; condicaos4.Add(condicao1); Condicao condicao2 = new Condicao() { Campo = "d.Excluido", Valores = "0".CriarValor(), Grupo = 4 }; condicaos4.Add(condicao2); List condicaos5 = condicaos4; List condicaos6 = new List(); Condicao condicao3 = new Condicao() { Campo = "d.situacao", Valores = 1.CriarValor(), Grupo = 3, Operacao = Operacao.Or }; condicaos6.Add(condicao3); Condicao condicao4 = new Condicao() { Campo = "d.situacao", Valores = 2.CriarValor(), Grupo = 3 }; condicaos6.Add(condicao4); List condicaos7 = condicaos6; condicaos.AddRange(condicaos3); condicaos.AddRange(condicaos7); condicaos.AddRange(condicaos5); SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); SqlQueryCondition sqlQueryCondition1 = condicaos1.CreateParameters(0); List documentos1 = 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; string str4 = "WITH tabfatura AS ( SELECT MAX ( f.vigenciaf ) AS vigenciaf, MAX ( f.vigenciai ) AS vigenciai, MAX ( p.idparcela ) AS idparcela, MAX ( p.vencto ) AS Vencimento, MAX (f.idfatura) as idfatura, d.iddocumento FROM documento d LEFT JOIN parcela p ON p.iddocumento = d.iddocumento LEFT JOIN fatura f ON p.idparcela = f.idparcela GROUP BY d.iddocumento ) SELECT DISTINCT d.iddocumento, d.idcontrole, IIF ( d.vigencia2 IS NULL, GETDATE(), d.vigencia2 ) AS vigenciafinalfatura, tabfatura.idparcela,tabfatura.vigenciai AS vigenciaIultimafatura, tabfatura.vigenciaf AS vigenciafultimafatura, f.numfatura,tabfatura.Vencimento, cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome AS cliente, 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, c.idramo, r.nome AS nomeramo, c.idciaseg AS idseguradora, cs.nome AS nomeseguradora, c.idproduto, pr.nome AS nomeproduto, CAST ( d.tipo AS INTEGER ) AS tipo, vp.idvendedor, d.idestipulante, d.datacontrole, d.idstatus, st.nome AS nomestatus, d.pasta, cl.pasta AS pastacliente FROM documento d INNER JOIN controle c ON c.idcontrole = d.idcontrole INNER JOIN ciaseg cs ON cs.idciaseg = c.idciaseg INNER JOIN ramo r ON r.idramo = c.idramo INNER JOIN cliente cl ON cl.idcliente = c.idcliente LEFT JOIN produto pr ON pr.idproduto = c.idproduto LEFT JOIN status st ON st.idstatus = d.idstatus LEFT JOIN parcela p ON p.iddocumento = d.iddocumento \tLEFT JOIN vendedorparcela vp ON vp.idparcela = p.idparcela LEFT JOIN tabfatura ON tabfatura.iddocumento = d.iddocumento LEFT JOIN fatura f on tabfatura.idfatura = f.idfatura WHERE"; string str5 = " AND NOT EXISTS ( SELECT 1 FROM parcela p INNER JOIN fatura f ON f.idparcela = p.idparcela WHERE p.iddocumento = d.iddocumento AND "; SqlCommand sqlCommand1 = sqlCommand; string[] strArrays = new string[] { str4, " ", sqlQueryCondition.Condicao, " ", str5, " ", sqlQueryCondition1.Condicao, " ) ORDER BY d.IDDOCUMENTO" }; sqlCommand1.CommandText = string.Concat(strArrays); foreach (SqlParameter parametro in sqlQueryCondition.Parametros) { if (sqlCommand.Parameters.Contains(parametro.ParameterName)) { continue; } sqlCommand.Parameters.Add(parametro); } foreach (SqlParameter sqlParameter in sqlQueryCondition1.Parametros) { if (sqlCommand.Parameters.Contains(sqlParameter.ParameterName)) { continue; } sqlCommand.Parameters.Add(sqlParameter); } 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 { bool flag = tipoSeguro == TipoSeguro.Renovacao; if (flag) { flag = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "idnegocio"); } negocioCorretora = (!flag || !(sqlDataReader.GetFieldValue("idnegocio", 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)) { long num = sqlDataReader.GetFieldValue("IdControle", true, true); long fieldValue1 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); Documento documento = documentos1.Find((Documento p) => p.Controle.Id == num); if (documento != null) { itensAtivo = documento.ItensAtivo; } else { itensAtivo = null; } List items = itensAtivo; if (items == null) { items = await this.BuscaItemsPorIdControle(num); } List items1 = items; DateTime? nullable = sqlDataReader.GetFieldValue("vigenciafultimafatura", true, true); dateTime = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); DateTime dateTime4 = dateTime; nullable = sqlDataReader.GetFieldValue("vigenciaIultimafatura", true, true); dateTime1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); DateTime dateTime5 = dateTime1; nullable = sqlDataReader.GetFieldValue("vigenciainicial", true, true); dateTime2 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); DateTime dateTime6 = dateTime2; nullable = sqlDataReader.GetFieldValue("vigenciafinalfatura", true, true); dateTime3 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); if (dateTime4 < dateTime3) { Documento observableCollection = new Documento() { Id = sqlDataReader.GetFieldValue("iddocumento", true, true) }; Controle controle = new Controle() { IdEmpresa = fieldValue1 }; Cliente cliente = new Cliente() { Id = sqlDataReader.GetFieldValue("idcliente", true, true), Nome = sqlDataReader.GetFieldValue("cliente", true, true), IdEmpresa = fieldValue1, Pasta = sqlDataReader.GetFieldValue("pastaCliente", true, true) }; bool? nullable1 = sqlDataReader.GetFieldValue("MalaDireta", true, true); cliente.MalaDireta = new bool?(nullable1.GetValueOrDefault(true)); controle.Cliente = cliente; Seguradora seguradora = new Seguradora() { Id = sqlDataReader.GetFieldValue("idseguradora", true, true), Nome = sqlDataReader.GetFieldValue("nomeseguradora", true, true) }; controle.Seguradora = seguradora; Ramo ramo = new Ramo() { Id = sqlDataReader.GetFieldValue("idramo", true, true), Nome = sqlDataReader.GetFieldValue("nomeramo", true, true) }; controle.Ramo = ramo; if (sqlDataReader.FieldIsNull("idproduto")) { produto = null; } else { produto = new Produto(); ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("idproduto", true, true); ((Produto)produto).Nome = sqlDataReader.GetFieldValue("nomeproduto", true, true); } controle.Produto = (Produto)produto; observableCollection.Controle = controle; observableCollection.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura); observableCollection.Apolice = sqlDataReader.GetFieldValue("apolice", true, true); observableCollection.Pasta = sqlDataReader.GetFieldValue("Pasta", true, true); str = (sqlDataReader.GetFieldValue("tipo", true, true) == 0 ? "" : string.Concat("E ", sqlDataReader.GetFieldValue("endosso", true, true))); observableCollection.Endosso = str; observableCollection.Vigencia2 = sqlDataReader.GetFieldValue("vigenciafinal", true, true); observableCollection.Vigencia1 = dateTime6; observableCollection.Emissao = sqlDataReader.GetFieldValue("emissao", true, true); observableCollection.Remessa = sqlDataReader.GetFieldValue("remessa", true, true); if (sqlDataReader.GetFieldValue("idvendedor", true, true) != null) { List vendedores = Auxiliar.Vendedores; Func func2 = func; if (func2 == null) { Func id = (Vendedor p) => p.Id == sqlDataReader.GetFieldValue("idvendedor", true, true); Func func3 = id; func = id; func2 = func3; } vendedor = vendedores.FirstOrDefault(func2); } else { vendedor = null; } observableCollection.VendedorPrincipal = vendedor; if (sqlDataReader.GetFieldValue("idestipulante", true, true) != null) { List estipulantes = Auxiliar.Estipulantes; Func func4 = func1; if (func4 == null) { Func id1 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante", true, true); Func func5 = id1; func1 = id1; func4 = func5; } estipulante = estipulantes.FirstOrDefault(func4); } else { estipulante = null; } observableCollection.Estipulante1 = estipulante; observableCollection.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); observableCollection.Situacao = tipoSeguro; List parcelas = new List(); Parcela parcela = new Parcela() { Id = sqlDataReader.GetFieldValue("idparcela", true, true), VigenciaFinal = new DateTime?(dateTime4), Fatura = sqlDataReader.GetFieldValue("numfatura", true, true), Vencimento = sqlDataReader.GetFieldValue("Vencimento", true, true), VigenciaIncial = new DateTime?(dateTime5) }; parcelas.Add(parcela); observableCollection.Parcelas = new ObservableCollection(parcelas); observableCollection.Tipo = sqlDataReader.GetFieldValue("tipo", true, true); observableCollection.DataControle = sqlDataReader.GetFieldValue("datacontrole", true, true); if (sqlDataReader.FieldIsNull("idstatus")) { statu = null; } else { statu = new Status(); ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("idstatus", true, true); ((Status)statu).Nome = sqlDataReader.GetFieldValue("nomestatus", true, true); } observableCollection.Status = (Status)statu; observableCollection.ItensAtivo = items1; documentos1.Add(observableCollection); } } } } } sqlCommand = null; } sqlConnection = null; documentos = documentos1; } documentos1 = null; return documentos; } public List FindByDocumentId(List ids) { List parcelas; object connection; SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable = new DataTable(); 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 str = string.Concat(" p.iddocumento IN (", string.Join(",", ids), ")"); sqlCommand.CommandText = string.Concat("SELECT p.iddocumento, ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss,p.obs, p.vlrcomiss, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, f.* FROM parcela p OUTER APPLY (SELECT numfatura, vigenciai, vigenciaf, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE ", str); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } if (dataTable.Rows.Count != 0) { goto Label0; } else { parcelas = new List(); } } } return parcelas; Label0: List list = dataTable.AsEnumerable().ToList(); return list.Select((DataRow x) => { Parcela parcela = new Parcela() { Id = x.Field("idparcela"), IdEmpresa = x.Field("idempresa"), Documento = new Documento() { Id = x.Field("iddocumento") }, NumeroParcela = int.Parse(x.Field("parcela").ToString()) }; DateTime? nullable = x.Field("vencto"); parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.Today); parcela.DataRecebimento = x.Field("datarec"); parcela.DataQuitacao = x.Field("dataquit"); parcela.DataControle = x.Field("datacontrole"); parcela.DataCredito = x.Field("datacred"); decimal? nullable1 = x.Field("valor"); parcela.Valor = nullable1.GetValueOrDefault(); nullable1 = x.Field("valorr"); parcela.ValorRealizado = nullable1.GetValueOrDefault(); nullable1 = x.Field("comiss"); parcela.Comissao = nullable1.GetValueOrDefault(); nullable1 = x.Field("vlrcomiss"); parcela.ValorComissao = nullable1.GetValueOrDefault(); nullable1 = x.Field("vlrcomdesc"); parcela.ValorComDesconto = nullable1.GetValueOrDefault(); parcela.Observacao = x.Field("obs"); parcela.SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field("idsubtipo").ToString()); parcela.TipoPagamento = (x.Field("idtipopagto") == null ? TipoPagamento.Nenhum : (TipoPagamento)Enum.Parse(typeof(TipoPagamento), x.Field("idtipopagto").ToString())); nullable1 = x.Field("valorlf"); parcela.ValorLiquidoFatura = nullable1.GetValueOrDefault(); parcela.Fatura = x.Field("numfatura"); parcela.VigenciaIncial = x.Field("vigenciai"); parcela.VigenciaFinal = x.Field("vigenciaf"); parcela.Emissao = x.Field("emissao"); parcela.Extrato = x.Field("extrato"); parcela.StatusPagamento = new StatusPagamento?((x.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field("StatusPagamento").ToString()))); parcela.IdParcelaPendente = x.Field("IdParcelaPendente").GetValueOrDefault(); nullable1 = x.Field("irr"); parcela.Irr = nullable1.GetValueOrDefault(); nullable1 = x.Field("iss"); parcela.Iss = nullable1.GetValueOrDefault(); nullable1 = x.Field("desconto"); parcela.Desconto = nullable1.GetValueOrDefault(); nullable1 = x.Field("outros"); parcela.Outros = nullable1.GetValueOrDefault(); return parcela; }).ToList(); } public List FindByDocumentId(long id) { List parcelas; object connection; SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable = new DataTable(); 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("SELECT ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss, p.vlrcomiss,p.obs, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, p.valorp, p.obs, p.vlrextrato, p.cri_data, p.usuariocriacao, f.* ", string.Format("FROM parcela p OUTER APPLY (SELECT idfatura, numfatura as fatura, vigenciai as vigenciainicial, vigenciaf as vigenciafinal, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE p.iddocumento = {0}", id)); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } if (dataTable.Rows.Count != 0) { Documento documento = (new DocumentoRepository(this._unitOfWork)).FindById(id, false, false); return dataTable.MapParcela(documento); } else { parcelas = new List(); } } } return parcelas; } public List FindByDocumentIds(string ids, List documentos) { object connection; DataTable dataTable = 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.CommandText = string.Concat("SELECT iddocumento, idempresa, idparcela, parcela, vencto, valor, idtipopagto, StatusPagamento, IdParcelaPendente FROM parcela WHERE iddocumento IN (", ids, ");"); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } } } documentos.ForEach((Documento x) => { List parcelas = new List(); dataTable.AsEnumerable().Where((DataRow y) => y.Field("iddocumento") == x.Id).ToList().ForEach((DataRow y) => { Parcela parcela = new Parcela() { Id = y.Field("idparcela"), IdEmpresa = (!y.Field("idempresa").HasValue ? (long)0 : y.Field("idempresa")), NumeroParcela = int.Parse(y.Field("parcela").ToString()), Vencimento = (y.Field("vencto") == null ? new DateTime() : y.Field("vencto")), Valor = y.Field("valor"), TipoPagamento = (y.Field("idtipopagto") == null ? TipoPagamento.Nenhum : (int)y.Field("idtipopagto")), StatusPagamento = new StatusPagamento?((y.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), y.Field("StatusPagamento").ToString()))), IdParcelaPendente = y.Field("IdParcelaPendente").GetValueOrDefault() }; parcelas.Add(parcela); }); x.Parcelas = new ObservableCollection(parcelas); }); return documentos; } public List FindByDocumento(Documento documento) { List parcelas; object connection; SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable = new DataTable(); 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("SELECT ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss, p.vlrcomiss,p.obs, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, p.valorp, p.obs, p.vlrextrato, p.cri_data, p.usuariocriacao, f.* ", string.Format("FROM parcela p OUTER APPLY (SELECT idfatura, numfatura as fatura, vigenciai as vigenciainicial, vigenciaf as vigenciafinal, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE p.iddocumento = {0}", documento.Id)); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } if (dataTable.Rows.Count != 0) { return dataTable.MapParcela(documento); } else { parcelas = new List(); } } } return parcelas; } public Parcela FindById(long id) { DateTime? nullable; string fatura; DateTime? vigenciaInicial; DateTime? vigenciaFinal; DateTime? emissao; ParcelaDb parcelaDb = base.FindEntityById(id); if (parcelaDb == null) { return null; } if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela || !string.IsNullOrEmpty(parcelaDb.Fatura)) { return ApplicationMapper.Mapper.Map(parcelaDb); } FaturaDb faturaDb = this._unitOfWork.Query().FirstOrDefault((FaturaDb x) => x.Parcela.Id == id); ParcelaDb parcelaDb1 = parcelaDb; if (faturaDb != null) { fatura = faturaDb.Fatura; } else { fatura = null; } parcelaDb1.Fatura = fatura; ParcelaDb parcelaDb2 = parcelaDb; if (faturaDb != null) { vigenciaInicial = faturaDb.VigenciaInicial; } else { nullable = null; vigenciaInicial = nullable; } parcelaDb2.VigenciaIncial = vigenciaInicial; ParcelaDb parcelaDb3 = parcelaDb; if (faturaDb != null) { vigenciaFinal = faturaDb.VigenciaFinal; } else { nullable = null; vigenciaFinal = nullable; } parcelaDb3.VigenciaFinal = vigenciaFinal; ParcelaDb parcelaDb4 = parcelaDb; if (faturaDb != null) { emissao = faturaDb.Emissao; } else { nullable = null; emissao = nullable; } parcelaDb4.Emissao = emissao; return ApplicationMapper.Mapper.Map(parcelaDb); } public List FindByPagamento(Filtros filtro, bool reciboPagamento, bool segundaViaReciboPagamento, bool datacontrole) { List vendedorParcelas; string str; object connection; 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), ") OR NegocioCorretora IS NULL)")); 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.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "" : string.Concat(" AND vp.idtipovendedor IN (", string.Join(",", from v in filtro.TipoVendedor select v), ")")); string str8 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", from v in filtro.Estipulantes select v), ")")); string str9 = (!reciboPagamento || segundaViaReciboPagamento ? "" : "AND vp.datapgt IS NULL "); if (segundaViaReciboPagamento) { str = "CAST(vp.datapgt AS DATE)"; } else { str = (datacontrole ? "CAST(d.datacontrole AS DATE)" : "CAST(vp.dataprepagto AS DATE)"); } string str10 = str; string str11 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); string str12 = (filtro.ParcelasEspeciais.Any((FiltroTipoParcela x) => x.Selecionado) ? string.Concat(" AND p.idsubtipo IN (", string.Join(",", from x in filtro.ParcelasEspeciais where x.Selecionado select x into v select (int)v.Tipo), ")") : ""); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable = new DataTable(); 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 str13 = "SELECT DISTINCT cl.idempresa, vp.idvendedorparcela, cl.idcliente, cl.MalaDireta, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, p.idparcela, d.iddocumento, d.N_PARC as numeroparcelas, d.datacontrole, cl.nome as cliente, d.contrato as apolice, d.aditamento as endosso, d.situacao, d.idnegocio, d.vigencia1 as vigenciainicial, d.proposta, d.vigencia2 as vigenciafinal, f.vigenciaf as vigenciaf, ISNULL(d.com01, 0) as comissao, ISNULL(p.comiss, 0.00) as comiss, p.parcela, d.tiporecebimento, ISNULL(d.pr_liq, 0.00) as liquido, ISNULL(d.pr_total, 0.00) as total, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorlf, 0.00) as liquidofatura, f.vigenciai, f.numfatura as fatura, vp.dataprepagto as recebimento, ISNULL(vp.vlrrep,0) as repasse, ISNULL(vp.vrep, 0) as percentual, p.idsubtipo, vp.datapgt, vp.idrepasse as idrepasse, rep.tipo as tiporepasse, d.cri_data, d.emissao, p.datarec, p.vlrcomdesc, d.NegocioCorretora, CASE WHEN ((Round(ISNULL( d.pr_liq, 0.00 ) * (ISNULL( d.com01, 0 ) / 100 ),2) * ( vp.vrep/ 100 )) - ROUND(vp.valortotal,2) - ROUND(cia.tolerancia,2)) > 0 THEN 'SIM' ELSE 'NÃO'END AS RecebidoPorCompleto FROM vendedorparcela vp INNER JOIN parcela p on p.idparcela = vp.idparcela INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela INNER JOIN repasse rep on rep.idrepasse = vp.idrepasse INNER JOIN ciaseg cia on cia.idciaseg = c.idciaseg WHERE (d.excluido IS NULL OR d.excluido = 0)"; sqlCommand.CommandText = string.Format("{0} {1} AND vp.idvendedor != {2} AND {3} >= '{4:yyyy-MM-dd}' AND {5} <= '{6:yyyy-MM-dd}' {7} {8} {9} {10} {11} {12} {13} {14} {15}{16}", new object[] { str13, str11, Auxiliar.Vendedores.First((Vendedor x) => x.Corretora).Id, str10, filtro.Inicio, str10, filtro.Fim, str9, str1, str2, str3, str4, str5, str8, str6, str7, str12 }); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } if (dataTable.Rows.Count != 0) { Action action = (DataRow x) => x.SetField("NegocioCorretora", (!(x.Field("situacao").ToString() == "2") || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? "0" : "1")); ( from x in dataTable.AsEnumerable().ToList() where x.Field("NegocioCorretora") == null select x).ForEach(action); if (!str2.IsNullOrEmpty()) { Func func = (DataRow p) => filtro.Negocio.Any((long filter) => filter.ToString() == p.Field("NegocioCorretora").ToString()); dataTable = dataTable.AsEnumerable().Where(func).CopyToDataTable(); } goto Label0; } else { vendedorParcelas = new List(); } } } return vendedorParcelas; Label0: List list = dataTable.AsEnumerable().ToList(); return list.Select((DataRow x) => { decimal? nullable; decimal valueOrDefault; decimal num; VendedorParcela vendedorParcela = new VendedorParcela() { Id = x.Field("idvendedorparcela"), Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")), Repasse = new Repasse() { Id = x.Field("idrepasse"), Tipo = new TipoRepasse?((TipoRepasse)Enum.Parse(typeof(TipoRepasse), x.Field("tiporepasse").ToString())) } }; Documento documento = new Documento() { Id = x.Field("iddocumento"), Controle = new Controle() { IdEmpresa = x.Field("idempresa"), Cliente = new Cliente() { Id = x.Field("idcliente"), Nome = x.Field("cliente"), IdEmpresa = x.Field("idempresa"), 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((Produto p) => p.Id == x.Field("idproduto")) : null) }, Apolice = x.Field("apolice"), Endosso = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("endosso") : string.Concat("F ", x.Field("fatura"))), Comissao = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("comissao") : x.Field("comiss")) }; if (x.Field("tiporecebimento").ToString() == "1") { nullable = x.Field("liquido"); valueOrDefault = nullable.GetValueOrDefault(); } else { nullable = x.Field("liquidofatura"); valueOrDefault = nullable.GetValueOrDefault(); } documento.PremioLiquido = valueOrDefault; if (x.Field("tiporecebimento").ToString() == "1") { nullable = x.Field("total"); num = nullable.GetValueOrDefault(); } else { nullable = x.Field("valor"); num = nullable.GetValueOrDefault(); } documento.PremioTotal = num; documento.Vigencia1 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciainicial") : (x.Field("vigenciai") != null ? x.Field("vigenciai") : new DateTime())); documento.Vigencia2 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciafinal") : x.Field("vigenciaf")); documento.Proposta = x.Field("proposta"); documento.NegocioCorretora = new NegocioCorretora?((NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("NegocioCorretora").ToString())); 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.TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())); documento.NumeroParcelas = x.Field("numeroparcelas"); documento.DataCriacao = x.Field("cri_data"); documento.DataControle = x.Field("datacontrole"); documento.Emissao = x.Field("emissao"); vendedorParcela.Documento = documento; Parcela parcela = new Parcela() { NumeroParcela = int.Parse(x.Field("parcela").ToString()), Id = x.Field("idparcela"), SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field("idsubtipo").ToString()), IdEmpresa = x.Field("idempresa"), Valor = x.Field("valor") }; nullable = x.Field("vlrcomdesc"); parcela.ValorComDesconto = nullable.GetValueOrDefault(); parcela.DataRecebimento = x.Field("datarec"); vendedorParcela.Parcela = parcela; vendedorParcela.ValorRepasse = new decimal?(x.Field("repasse")); DateTime? nullable1 = x.Field("recebimento"); vendedorParcela.DataPrePagamento = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue)); vendedorParcela.PorcentagemRepasse = new decimal?(x.Field("percentual")); vendedorParcela.DataPagamento = x.Field("datapgt"); vendedorParcela.RecebidoPorCompleto = x.Field("RecebidoPorCompleto"); return vendedorParcela; }).ToList(); } public List FindByPendente(Filtros filtro, bool pendente, bool somenteAtivos) { List parcelas; 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.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 vp2.idvendedor FROM vendedorparcela vp2 WHERE (d.tiporecebimento = 2 AND vp2.IDPARCELA = p.IDPARCELA) OR (d.tiporecebimento = 1 AND vp2.iddocumento = p.iddocumento)) 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)); string str9 = (somenteAtivos ? " AND i.idsubstituido IS NULL" : ""); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable = new DataTable(); DataTable dataTable1 = new DataTable(); DataTable dataTable2 = new DataTable(); DataTable dataTable3 = new DataTable(); DataTable dataTable4 = new DataTable(); string str10 = (pendente ? "AND p.datarec IS NULL" : ""); 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 str11 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, f.numfatura as fatura, f.vigenciai as vigenciai, f.vigenciaf as vigenciaf, p.parcela, p.datarec as recebimento, p.dataquit as quitacao, p.datacontrole as dataparcelacontrole, p.vencto as vencimento, ISNULL(p.vlrcomdesc, 0.00) as valorcomdesconto, ISNULL(p.vlrcomiss, 0) as valorcomissao, p.iddocumento, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.proposta, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorr, 0.00) as valorr, ISNULL(p.valorlf, 0.00) as valorliquidofatura, ISNULL(d.pr_total, 0.00) as total, ISNULL(d.pr_liq, 0.00) as liquido, d.pr_adic as adicional, d.adinacomis as adinacomiss, ISNULL(d.com01,0) as comissao, ISNULL(p.comiss, 0.00) as comiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento, d.N_PARC as numeroparcelas, d.datacontrole, d.idstatus, p.idsubtipo, cl.cgccpf, d.formapagamento, d.propassinada, d.pasta, cl.pasta as pastacliente FROM parcela p INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente ", (somenteAtivos ? "INNER JOIN item i on d.iddocumento = i.iddocumento " : ""), str6, " LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0)"); string str12 = "SELECT DISTINCT idparcela as id, idvendedor, vlrrep as valorrepasse, vrep as porcentagemrepasse, datapgt as datapagamento, dataprepagto as dataprepagamento FROM vendedorparcela vp WHERE 1=1 "; string str13 = "SELECT iddocumento, idparcela as id, parcela, datarec as recebimento, vencto as vencimento, vlrcomdesc as valorcomdesconto, ISNULL(vlrcomiss, 0.00) as valorcomissao, ISNULL(valor, 0.00) as valor, ISNULL(comiss, 0.00) as comiss, ISNULL(StatusPagamento, 0) AS StatusPagamento, ISNULL(IdParcelaPendente, 0) AS IdParcelaPendente FROM parcela where datarec IS NOT NULL "; string str14 = "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 str15 = "SELECT DISTINCT idcliente, idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE "; sqlCommand.CommandText = string.Format("{0} {1} {2} AND p.vencto >= '{3:yyyy-MM-dd}' AND p.vencto <= '{4:yyyy-MM-dd}' {5} {6} {7} {8} {9} {10} {11} {12}", new object[] { str11, str8, str10, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5, str9 }); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } if (dataTable.Rows.Count != 0) { string str16 = string.Concat(" AND vp.idparcela IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); sqlCommand.CommandText = string.Concat(str12, " ", str16); using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) { sqlDataAdapter1.SelectCommand = sqlCommand; sqlDataAdapter1.Fill(dataTable1); } string str17 = string.Concat(" AND iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("iddocumento"))), ")"); sqlCommand.CommandText = string.Concat(str13, " ", str17); using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) { sqlDataAdapter2.SelectCommand = sqlCommand; sqlDataAdapter2.Fill(dataTable2); } string str18 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); sqlCommand.CommandText = string.Concat(str14, " ", str18); using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) { sqlDataAdapter3.SelectCommand = sqlCommand; sqlDataAdapter3.Fill(dataTable3); } for (List i1 = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).Distinct().ToList(); i1.Count > 0; i1 = nums) { List nums1 = i1.Take(1000).ToList(); List condicaos = new List() { new Condicao() { Campo = "idcliente", Valores = nums1.CriarValor() } }; DataTable dataTable5 = sqlCommand.Select(condicaos.CreateParameters(0), str15, ""); dataTable4.Merge(dataTable5); nums = (nums1.Count < 1000 ? new List() : i1.Except(nums1).ToList()); } goto Label0; } else { parcelas = new List(); } } } return parcelas; Label0: return dataTable.AsEnumerable().ToList().Select((DataRow x) => { decimal? nullable3; decimal valueOrDefault; decimal num; Parcela observableCollection = new Parcela() { Id = x.Field("id"), IdEmpresa = x.Field("idempresa"), NumeroParcela = int.Parse(x.Field("parcela").ToString()) }; DateTime? nullable4 = x.Field("vencimento"); observableCollection.Vencimento = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue); observableCollection.Comissao = x.Field("comiss"); observableCollection.DataQuitacao = x.Field("quitacao"); observableCollection.DataControle = x.Field("dataparcelacontrole"); observableCollection.Valor = x.Field("valor"); observableCollection.SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field("idsubtipo").ToString()); observableCollection.StatusPagamento = new StatusPagamento?((x.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field("StatusPagamento").ToString()))); observableCollection.IdParcelaPendente = x.Field("IdParcelaPendente").GetValueOrDefault(); IEnumerable list = from v in dataTable1.AsEnumerable().ToList() where v.Field("id") == x.Field("id") select v; Func u003cu003e9_2614 = ParcelaRepository.u003cu003ec.u003cu003e9__26_14; if (u003cu003e9_2614 == null) { u003cu003e9_2614 = (DataRow v) => { DateTime? nullable; DateTime? nullable1; DateTime? nullable2; VendedorParcela vendedorParcela = new VendedorParcela() { Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == v.Field("idvendedor")), ValorRepasse = new decimal?((v.Field("valorrepasse") == null ? decimal.Zero : v.Field("valorrepasse"))), PorcentagemRepasse = new decimal?((v.Field("porcentagemrepasse") == null ? decimal.Zero : v.Field("porcentagemrepasse"))) }; if (v.Field("datapagamento") == null) { nullable = null; nullable1 = nullable; } else { nullable1 = v.Field("datapagamento"); } vendedorParcela.DataPagamento = nullable1; if (v.Field("dataprepagamento") == null) { nullable = null; nullable2 = nullable; } else { nullable2 = v.Field("dataprepagamento"); } vendedorParcela.DataPrePagamento = nullable2; return vendedorParcela; }; ParcelaRepository.u003cu003ec.u003cu003e9__26_14 = u003cu003e9_2614; } observableCollection.Vendedores = new ObservableCollection(list.Select(u003cu003e9_2614).ToList()); Documento documento = new Documento() { Id = x.Field("iddocumento"), 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()))) }; Controle controle = new Controle() { Id = x.Field("idcontrole"), IdEmpresa = x.Field("idempresa") }; Cliente cliente = new Cliente() { Id = x.Field("idcliente"), Nome = x.Field("cliente"), Documento = x.Field("cgccpf"), IdEmpresa = x.Field("idempresa"), Pasta = x.Field("pastacliente") }; EnumerableRowCollection dataRows = dataTable4.AsEnumerable().Where((DataRow t) => t.Field("idcliente") == x.Field("idcliente")); Func u003cu003e9_2627 = ParcelaRepository.u003cu003ec.u003cu003e9__26_27; if (u003cu003e9_2627 == null) { u003cu003e9_2627 = (DataRow t) => new ClienteTelefone() { Id = t.Field("idclitelefone"), Prefixo = t.Field("ddd"), Numero = t.Field("fone") }; ParcelaRepository.u003cu003ec.u003cu003e9__26_27 = u003cu003e9_2627; } cliente.Telefones = new ObservableCollection(dataRows.Select(u003cu003e9_2627)); 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((Produto p) => p.Id == x.Field("idproduto")) : null); documento.Controle = controle; documento.Pasta = x.Field("Pasta"); documento.NumeroParcelas = x.Field("numeroparcelas"); documento.AdicionalComiss = x.Field("adinacomiss") == "1"; documento.Apolice = x.Field("apolice"); documento.Endosso = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("endosso") : string.Concat("F ", x.Field("fatura"))); documento.Comissao = x.Field("comiss"); documento.Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))); if (x.Field("tiporecebimento").ToString() == "1") { nullable3 = x.Field("liquido"); valueOrDefault = nullable3.GetValueOrDefault(); } else { nullable3 = x.Field("valorliquidofatura"); valueOrDefault = nullable3.GetValueOrDefault(); } documento.PremioLiquido = valueOrDefault; if (x.Field("tiporecebimento").ToString() == "1") { nullable3 = x.Field("total"); num = nullable3.GetValueOrDefault(); } else { nullable3 = x.Field("valor"); num = nullable3.GetValueOrDefault(); } documento.PremioTotal = num; nullable3 = x.Field("adicional"); documento.PremioAdicional = nullable3.GetValueOrDefault(); documento.Vigencia1 = (x.Field("tiporecebimento").ToString() == "1" ? (x.Field("vigenciainicial") == null ? DateTime.MinValue : x.Field("vigenciainicial")) : (x.Field("vigenciai") != null ? x.Field("vigenciai") : (x.Field("vigenciainicial") == null ? DateTime.MinValue : x.Field("vigenciainicial")))); documento.Vigencia2 = (x.Field("tiporecebimento").ToString() == "1" ? (x.Field("vigenciafinal") == null ? new DateTime?(DateTime.MinValue) : x.Field("vigenciafinal")) : new DateTime?((x.Field("vigenciaf") != null ? x.Field("vigenciaf") : (x.Field("vigenciafinal") == null ? DateTime.MinValue : x.Field("vigenciafinal"))))); documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); documento.Proposta = x.Field("proposta"); 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.TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())); documento.PropostaAssinada = (x.Field("propassinada") == null ? false : x.Field("propassinada") == "1"); documento.Parcelas = new ObservableCollection(dataTable2.AsEnumerable().Where((DataRow p) => p.Field("iddocumento") == x.Field("iddocumento")).Select((DataRow p) => { Parcela parcela = new Parcela() { Id = p.Field("id"), NumeroParcela = int.Parse(p.Field("parcela").ToString()), DataRecebimento = p.Field("recebimento") }; DateTime? nullable = p.Field("vencimento"); parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); parcela.ValorComissao = (x.Field("valorcomissao") == null ? decimal.Zero : p.Field("valorcomissao")); parcela.ValorComDesconto = (p.Field("valorcomdesconto") == null || p.Field("valorcomdesconto") == decimal.Zero ? (x.Field("valorcomissao") == null ? decimal.Zero : p.Field("valorcomissao")) : p.Field("valorcomdesconto")); parcela.Comissao = p.Field("comiss"); parcela.Valor = p.Field("valor"); parcela.StatusPagamento = new StatusPagamento?((p.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), p.Field("StatusPagamento").ToString()))); parcela.IdParcelaPendente = p.Field("IdParcelaPendente").GetValueOrDefault(); return parcela; }).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 list1 = from i in dataTable3.AsEnumerable().ToList() where i.Field("idcontrole") == x.Field("idcontrole") select i; Func u003cu003e9_2622 = ParcelaRepository.u003cu003ec.u003cu003e9__26_22; if (u003cu003e9_2622 == null) { u003cu003e9_2622 = (DataRow i) => new Item() { Id = i.Field("iditem"), Descricao = i.Field("descricao") }; ParcelaRepository.u003cu003ec.u003cu003e9__26_22 = u003cu003e9_2622; } documento.ItensAtivo = new List(list1.Select(u003cu003e9_2622).ToList()); observableCollection.Documento = documento; return observableCollection; }).ToList(); } public async Task> FindByRecebimento(Filtros filtro) { NegocioCorretora fieldValue; bool flag; bool count; object connection; bool count1; bool flag1; List itensAtivo; decimal num; object produto; object estipulante; object statu; string str; decimal num1; decimal num2; decimal num3; DateTime dateTime; DateTime? nullable; NegocioCorretora negocioCorretora; bool count2; bool flag2; Parcela parcela; List parcelas = new List(); List condicaos = this.CriaCondicaoDocumento(filtro, "CAST(p.DATAREC AS DATE)"); List condicaos1 = new List(); Condicao condicao = new Condicao() { Campo = "d.Excluido", Valores = null, Grupo = 1, Operacao = Operacao.Or }; condicaos1.Add(condicao); Condicao condicao1 = new Condicao() { Campo = "d.Excluido", Valores = "0".CriarValor(), Grupo = 1, Operacao = Operacao.Or }; condicaos1.Add(condicao1); condicaos.AddRange(condicaos1); List vendedores = filtro.Vendedores; if (vendedores != null) { count = vendedores.Count > 0; } else { count = false; } if (count) { if (await this.VerificaVendedorPropriaCorretora(filtro.Vendedores)) { List condicaos2 = condicaos; Condicao condicao2 = new Condicao() { Campo = "vp.idvendedor", Valores = null, Grupo = 5, Operacao = Operacao.Or }; condicaos2.Add(condicao2); } } SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); 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 = 1500; string str1 = "SELECT p.IDPARCELA IdParcela,p.PARCELA NumeroParcela,p.DATAREC DataRecebimento,p.dataquit DataQuitacao,p.datacontrole DataControleParcela,p.VENCTO Vencimento,p.VLRCOMISS ValorComissao,p.IRR Irr,p.ISS Iss,p.DESCONTO Desconto,p.OUTROS Outros,p.VLRCOMDESC ValorComDesconto,p.COMISS ComissaoParcela,p.VALORR ValorRealizado,p.VALORLF PremioLiquidoFatura,p.VALOR PremioTotalFatura,p.IDSUBTIPO SubTipo,d.IDDOCUMENTO IdDocumento,c.IDCONTROLE IdControle,c.IDEMPRESA IdEmpresa,c.idcliente IdCliente,clie.NOME NomeCliente,clie.PASTA PastaCliente,clie.MalaDireta MalaDireta,r.idramo IdRamo,r.NOME NomeRamo,cia.IDCIASEG IdCiaSeg,cia.NOME NomeCia,cia.NomeSocial NomeSocial,pr.idproduto IdProduto,pr.NOME NomeProduto,e.idestipulante IdEstipulante,e.nome NomeEstipulante,s.idstatus IdStatus,s.nome NomeStatus,d.ADINACOMIS AdicionalComiss,d.contrato Apolice,d.ADITAMENTO Endosso,d.COM01 ComissaoDocumento,d.NegocioCorretora,d.idnegocio Negocio,d.PR_LIQ PremioLiquido,d.PR_TOTAL PremioTotal,d.PR_ADIC PremioAdicional,d.vigencia1 VigenciaInicial,d.vigencia2 VigenciaFinal,d.SITUACAO Situacao,d.TIPO Tipo,d.tiporecebimento TipoRecebimento,d.datacontrole DataControleDocumento,d.PASTA PastaDocumento,vp.IDVENDEDORPARCELA IdVendedorParcela,vp.VLRREP ValorRepasse,vp.VREP PorcentagemRepasse,vp.DATAPGT DataPagamento,vp.DATAPREPAGTO DataPrePagamento,vp.idtipovendedor IdTipoVendedor,vp.IDVENDEDOR IdVendedor,v.NOME NomeVendedor,f.vigenciai VigenciaInicialFatura,f.vigenciaf VigenciaFinalFatura,f.NUMFATURA Fatura FROM parcela p INNER JOIN documento d ON d.IDDOCUMENTO = p.IDDOCUMENTO 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 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.IDPARCELA = p.IDPARCELA LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN fatura f ON f.IDPARCELA = p.IDPARCELA WHERE "; sqlCommand.CommandText = string.Concat(str1, " ", sqlQueryCondition.Condicao); sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) { while (true) { if (!await sqlDataReader.ReadAsync()) { break; } if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora")) { fieldValue = sqlDataReader.GetFieldValue("NegocioCorretora", true, true); } else { flag = sqlDataReader.GetFieldValue("Situacao", true, true) == TipoSeguro.Renovacao; if (flag) { flag = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio"); } negocioCorretora = (!flag || !(sqlDataReader.GetFieldValue("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); fieldValue = negocioCorretora; } NegocioCorretora negocioCorretora1 = fieldValue; if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora1)) { long fieldValue1 = sqlDataReader.GetFieldValue("IdParcela", true, true); Parcela observableCollection = parcelas.Find((Parcela p) => p.Id == fieldValue1); if (observableCollection == null) { long fieldValue2 = sqlDataReader.GetFieldValue("IdControle", true, true); Parcela parcela1 = parcelas.Find((Parcela p) => p.Documento.Controle.Id == fieldValue2); if (parcela1 != null) { itensAtivo = parcela1.Documento.ItensAtivo; } else { itensAtivo = null; } List items = itensAtivo; if (items == null) { items = await this.BuscaItemsPorIdControle(fieldValue2); } TipoRecebimento tipoRecebimento = sqlDataReader.GetFieldValue("TipoRecebimento", true, true); decimal fieldValue3 = sqlDataReader.GetFieldValue("ValorComissao", true, true); decimal fieldValue4 = sqlDataReader.GetFieldValue("ValorComDesconto", true, true); long num4 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); parcela = new Parcela() { Id = fieldValue1, NumeroParcela = sqlDataReader.GetFieldValue("NumeroParcela", true, true), DataRecebimento = sqlDataReader.GetFieldValue("DataRecebimento", true, true), DataQuitacao = sqlDataReader.GetFieldValue("DataQuitacao", true, true), DataControle = sqlDataReader.GetFieldValue("DataControleParcela", true, true), Vencimento = sqlDataReader.GetFieldValue("Vencimento", true, true), ValorComissao = fieldValue3, Irr = sqlDataReader.GetFieldValue("Irr", true, true), Iss = sqlDataReader.GetFieldValue("Iss", true, true), Desconto = sqlDataReader.GetFieldValue("Desconto", true, true), Outros = sqlDataReader.GetFieldValue("Outros", true, true) }; Parcela parcela2 = parcela; num = (fieldValue4 == decimal.Zero ? fieldValue3 : fieldValue4); parcela2.ValorComDesconto = num; parcela.Comissao = sqlDataReader.GetFieldValue("ComissaoParcela", true, true); parcela.ValorRealizado = sqlDataReader.GetFieldValue("ValorRealizado", true, true); parcela.SubTipo = sqlDataReader.GetFieldValue("SubTipo", true, true); parcela.IdEmpresa = num4; Parcela parcela3 = parcela; Documento documento = new Documento() { Id = sqlDataReader.GetFieldValue("IdDocumento", true, true) }; Documento documento1 = documento; Controle controle = new Controle() { Id = fieldValue2, IdEmpresa = num4 }; Controle controle1 = controle; Cliente cliente = new Cliente() { Id = sqlDataReader.GetFieldValue("IdCliente", true, true), Nome = sqlDataReader.GetFieldValue("NomeCliente", true, true), Pasta = sqlDataReader.GetFieldValue("PastaCliente", true, true) }; bool? nullable1 = sqlDataReader.GetFieldValue("MalaDireta", true, true); cliente.MalaDireta = new bool?(nullable1.GetValueOrDefault(true)); 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("NomeSocial", true, true) }; controle3.Seguradora = seguradora; Controle controle4 = controle; flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdProduto"); Controle controle5 = controle4; if (flag) { produto = null; } else { produto = new Produto(); ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("IdProduto", true, true); ((Produto)produto).Nome = sqlDataReader.GetFieldValue("NomeProduto", true, true); } controle5.Produto = (Produto)produto; documento1.Controle = controle; Documento documento2 = documento; bool flag3 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdEstipulante"); Documento documento3 = documento2; if (flag3) { estipulante = null; } else { estipulante = new Estipulante(); ((DomainBase)estipulante).Id = sqlDataReader.GetFieldValue("IdEstipulante", true, true); ((Estipulante)estipulante).Nome = sqlDataReader.GetFieldValue("NomeEstipulante", true, true); } documento3.Estipulante1 = (Estipulante)estipulante; Documento documento4 = documento; bool flag4 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdStatus"); Documento documento5 = documento4; if (flag4) { statu = null; } else { statu = new Status(); ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("IdStatus", true, true); ((Status)statu).Nome = sqlDataReader.GetFieldValue("NomeStatus", true, true); } documento5.Status = (Status)statu; documento.AdicionalComiss = sqlDataReader["AdicionalComiss"].ToString() == "1"; documento.Apolice = sqlDataReader.GetFieldValue("Apolice", true, true); Documento documento6 = documento; str = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("Endosso", true, true) : string.Concat("F ", sqlDataReader.GetFieldValue("Fatura", true, true))); documento6.Endosso = str; Documento documento7 = documento; num1 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("ComissaoDocumento", true, true) : sqlDataReader.GetFieldValue("ComissaoParcela", true, true)); documento7.Comissao = num1; documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); Documento nullable2 = documento; Negocio? nullable3 = sqlDataReader.GetFieldValue("Negocio", true, true); nullable2.Negocio = new Negocio?(nullable3.GetValueOrDefault(Negocio.Proprio)); Documento documento8 = documento; num2 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("PremioLiquido", true, true) : sqlDataReader.GetFieldValue("PremioLiquidoFatura", true, true)); documento8.PremioLiquido = num2; Documento documento9 = documento; num3 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("PremioTotal", true, true) : sqlDataReader.GetFieldValue("PremioTotalFatura", true, true)); documento9.PremioTotal = num3; documento.PremioAdicional = sqlDataReader.GetFieldValue("PremioAdicional", true, true); Documento documento10 = documento; if (tipoRecebimento == TipoRecebimento.Parcela) { dateTime = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); } else { DateTime? nullable4 = sqlDataReader.GetFieldValue("VigenciaInicialFatura", true, true); dateTime = (nullable4.HasValue ? nullable4.GetValueOrDefault() : sqlDataReader.GetFieldValue("Vencimento", true, true)); } documento10.Vigencia1 = dateTime; Documento documento11 = documento; nullable = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("VigenciaFinal", true, true) : sqlDataReader.GetFieldValue("VigenciaFinalFatura", true, true)); documento11.Vigencia2 = nullable; documento.Situacao = sqlDataReader.GetFieldValue("Situacao", true, true); documento.Tipo = sqlDataReader.GetFieldValue("Tipo", true, true); documento.TipoRecebimento = new TipoRecebimento?(tipoRecebimento); documento.DataControle = sqlDataReader.GetFieldValue("DataControleDocumento", true, true); documento.Pasta = sqlDataReader.GetFieldValue("PastaDocumento", true, true); documento.ItensAtivo = items; parcela3.Documento = documento; observableCollection = parcela; parcela3 = null; documento1 = null; controle4 = null; controle = null; documento2 = null; documento4 = null; documento = null; parcela = null; if (observableCollection.Vendedores == null) { observableCollection.Vendedores = new ObservableCollection(); } parcelas.Add(observableCollection); items = null; } 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) { long fieldValue5 = sqlDataReader.GetFieldValue("IdVendedorParcela", true, true); if (fieldValue5 > (long)0) { ObservableCollection vendedores1 = observableCollection.Vendedores; VendedorParcela vendedorParcela = new VendedorParcela() { Id = fieldValue5, ValorRepasse = new decimal?(sqlDataReader.GetFieldValue("ValorRepasse", true, true)), PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue("PorcentagemRepasse", true, true)), DataPagamento = sqlDataReader.GetFieldValue("DataPagamento", true, true), DataPrePagamento = sqlDataReader.GetFieldValue("DataPrePagamento", true, true) }; TipoVendedor tipoVendedor1 = new TipoVendedor() { Id = sqlDataReader.GetFieldValue("IdTipoVendedor", true, true) }; vendedorParcela.TipoVendedor = tipoVendedor1; Vendedor vendedor = new Vendedor() { Id = sqlDataReader.GetFieldValue("IdVendedor", true, true), Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true) }; vendedorParcela.Vendedor = vendedor; vendedores1.Add(vendedorParcela); } } } } } } sqlDataReader = null; List nums1 = filtro.TipoVendedor; if (nums1 != null) { count2 = nums1.Count > 0; } else { count2 = false; } if (!count2) { List vendedores2 = filtro.Vendedores; if (vendedores2 != null) { flag2 = vendedores2.Count > 0; } else { flag2 = false; } if (!flag2) { goto Label0; } } foreach (Parcela parcela4 in parcelas) { parcela = parcela4; List vendedorParcelas = await this.BuscaVendedoresPorIdParcela(parcela4.Id, parcela4.IdEmpresa, (long)0); parcela.Vendedores = new ObservableCollection(vendedorParcelas); parcela = null; } Label0: } sqlCommand = null; } sqlConnection = null; } sessionFactory = null; List parcelas1 = parcelas; parcelas = null; condicaos = null; return parcelas1; } public List FindByVencimento(Filtros filtro) { List parcelas; 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.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)); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable = new DataTable(); DataTable dataTable1 = new DataTable(); 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 str8 = "SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, f.numfatura as fatura, f.vigenciai as vigenciai, f.vigenciaf as vigenciaf, p.parcela, p.datarec as recebimento, p.vencto as vencimento, ISNULL(p.vlrcomdesc, 0.00) as valorcomdesconto, ISNULL(p.vlrcomiss, 0.00) as valorcomissao, p.iddocumento, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorlf, 0.00) as valorliquidofatura, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, ISNULL(d.pr_total, 0.00) as total, ISNULL(d.pr_liq, 0.00) as liquido, d.pr_adic as adicional, d.adinacomis as adinacomiss, ISNULL(d.com01, 0.00) as comissao, ISNULL(p.comiss, 0.00) as comiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento FROM parcela p INNER JOIN documento d on d.iddocumento = p.iddocumento 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 LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0)"; string str9 = "SELECT DISTINCT idparcela as id, idvendedor, vlrrep as valorrepasse, vrep as porcentagemrepasse, datapgt as datapagamento, dataprepagto as dataprepagamento FROM vendedorparcela vp WHERE 1=1 "; sqlCommand.CommandText = string.Format("{0} {1} AND p.vencto >= '{2:yyyy-MM-dd}' AND p.vencto <= '{3:yyyy-MM-dd}' {4} {5} {6} {7} {8} {9} {10}", new object[] { str8, str7, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str6, str5 }); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } if (dataTable.Rows.Count != 0) { string str10 = string.Concat(" AND vp.idparcela IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); sqlCommand.CommandText = string.Concat(str9, " ", str10); using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) { sqlDataAdapter1.SelectCommand = sqlCommand; sqlDataAdapter1.Fill(dataTable1); goto Label0; } } else { parcelas = new List(); } } } return parcelas; Label0: return dataTable.AsEnumerable().ToList().Select((DataRow x) => { decimal? nullable3; decimal valueOrDefault; decimal num; Parcela parcela = new Parcela() { Id = x.Field("id"), IdEmpresa = x.Field("idempresa"), NumeroParcela = int.Parse(x.Field("parcela").ToString()), DataRecebimento = x.Field("recebimento") }; DateTime? nullable4 = x.Field("vencimento"); parcela.Vencimento = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue); parcela.ValorComDesconto = (x.Field("valorcomdesconto") == null || x.Field("valorcomdesconto") == decimal.Zero ? (x.Field("valorcomissao") == null ? decimal.Zero : x.Field("valorcomissao")) : x.Field("valorcomdesconto")); parcela.Comissao = x.Field("comiss"); parcela.Valor = x.Field("valor"); parcela.StatusPagamento = new StatusPagamento?((x.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field("StatusPagamento").ToString()))); parcela.IdParcelaPendente = x.Field("IdParcelaPendente").GetValueOrDefault(); IEnumerable list = from v in dataTable1.AsEnumerable().ToList() where v.Field("id") == x.Field("id") select v; Func u003cu003e9_2810 = ParcelaRepository.u003cu003ec.u003cu003e9__28_10; if (u003cu003e9_2810 == null) { u003cu003e9_2810 = (DataRow v) => { DateTime? nullable; DateTime? nullable1; DateTime? nullable2; VendedorParcela vendedorParcela = new VendedorParcela() { Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == v.Field("idvendedor")), ValorRepasse = new decimal?((v.Field("valorrepasse") == null ? decimal.Zero : v.Field("valorrepasse"))), PorcentagemRepasse = new decimal?((v.Field("porcentagemrepasse") == null ? decimal.Zero : v.Field("porcentagemrepasse"))) }; if (v.Field("datapagamento") == null) { nullable = null; nullable1 = nullable; } else { nullable1 = v.Field("datapagamento"); } vendedorParcela.DataPagamento = nullable1; if (v.Field("dataprepagamento") == null) { nullable = null; nullable2 = nullable; } else { nullable2 = v.Field("dataprepagamento"); } vendedorParcela.DataPrePagamento = nullable2; return vendedorParcela; }; ParcelaRepository.u003cu003ec.u003cu003e9__28_10 = u003cu003e9_2810; } parcela.Vendedores = new ObservableCollection(list.Select(u003cu003e9_2810).ToList()); Documento documento = new Documento() { Controle = new Controle() { IdEmpresa = x.Field("idempresa"), Cliente = new Cliente() { Id = x.Field("idcliente"), Nome = x.Field("cliente"), IdEmpresa = x.Field("idempresa"), 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((Produto p) => p.Id == x.Field("idproduto")) : null) }, AdicionalComiss = x.Field("adinacomiss") == "1", Apolice = x.Field("apolice"), Endosso = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("endosso") : string.Concat("F ", x.Field("fatura"))), Comissao = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("comissao") : x.Field("comiss")), Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))) }; if (x.Field("tiporecebimento").ToString() == "1") { nullable3 = x.Field("liquido"); valueOrDefault = nullable3.GetValueOrDefault(); } else { nullable3 = x.Field("valorliquidofatura"); valueOrDefault = nullable3.GetValueOrDefault(); } documento.PremioLiquido = valueOrDefault; if (x.Field("tiporecebimento").ToString() == "1") { nullable3 = x.Field("total"); num = nullable3.GetValueOrDefault(); } else { nullable3 = x.Field("valor"); num = nullable3.GetValueOrDefault(); } documento.PremioTotal = num; nullable3 = x.Field("adicional"); documento.PremioAdicional = nullable3.GetValueOrDefault(); documento.Vigencia1 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciainicial") : x.Field("vigenciai")); documento.Vigencia2 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciafinal") : x.Field("vigenciaf")); 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.Tipo = x.Field("tipo"); parcela.Documento = documento; return parcela; }).ToList(); } public List FindByVigencia(Filtros filtro) { return new List(); } public List FindDocumentId(List ids) { List nums; object connection; if (ids == null || ids.Count == 0) { return ids; } SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable = new DataTable(); if (sessionFactory != null) { connection = sessionFactory.ConnectionProvider.GetConnection(); } else { connection = null; } using (SqlConnection sqlConnection = connection as SqlConnection) { using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { string str = string.Concat(" idparcela IN (", string.Join(",", ids), ")"); sqlCommand.CommandText = string.Concat("SELECT iddocumento FROM parcela p WHERE ", str); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } if (dataTable.Rows.Count != 0) { return dataTable.AsEnumerable().Select((DataRow x) => x.Field("iddocumento")).ToList(); } else { nums = new List(); } } } return nums; } public List FindNumFatura(string numero) { List documentos; object connection; SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable = new DataTable(); DataTable dataTable1 = new DataTable(); 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 str = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, p.iddocumento, d.contrato as apolice, f.numfatura as fatura, f.emissao, d.idnegocio, d.situacao, f.vigenciai as vigenciainicial, f.vigenciaf as vigenciafinal, ISNULL(p.valor, 0.00) as total, ISNULL(p.valorlf, 0.00) as liquido, 0.00 as adicional, '0' as adinacomiss, ISNULL(p.comiss, 0.00) as comissao, c.idramo, c.idciaseg as idseguradora, c.idproduto, 2 as tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.negociocorretora, d.datacontrole, d.idstatus, p.datacontrole as dataparcelacontrole, p.cri_data, d.banco, d.agencia, d.conta, d.pasta, d.propassinada 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 INNER JOIN cliente cl on cl.idcliente = c.idcliente INNER JOIN vendedorparcela vp on vp.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0) AND NUMFATURA ='", numero, "'"); string str1 = "SELECT DISTINCT idparcela as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; sqlCommand.CommandText = str ?? ""; using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } if (dataTable.Rows.Count != 0) { string str2 = string.Concat(" AND vp.idparcela IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); sqlCommand.CommandText = string.Concat(str1, " ", str2); using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) { sqlDataAdapter1.SelectCommand = sqlCommand; sqlDataAdapter1.Fill(dataTable1); goto Label0; } } else { documentos = new List(); } } } return documentos; Label0: return dataTable.AsEnumerable().ToList().Select((DataRow x) => { Func func2 = null; Documento documento = new Documento() { Id = x.Field("iddocumento"), Controle = new Controle() { Id = x.Field("idcontrole"), IdEmpresa = x.Field("idempresa"), Cliente = new Cliente() { Nome = x.Field("cliente"), Id = x.Field("idcliente"), IdEmpresa = x.Field("idempresa"), 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((Produto p) => p.Id == x.Field("idproduto")) : null) }, Pasta = x.Field("Pasta"), TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura), AdicionalComiss = false, Apolice = x.Field("apolice"), Endosso = x.Field("fatura"), Comissao = x.Field("comissao"), 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") != (long)1 ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))), Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))) }; decimal? nullable = x.Field("liquido"); documento.PremioLiquido = nullable.GetValueOrDefault(); nullable = x.Field("total"); documento.PremioTotal = nullable.GetValueOrDefault(); DateTime? nullable1 = x.Field("vigenciainicial"); documento.Vigencia1 = (nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue); documento.Vigencia2 = x.Field("vigenciafinal"); documento.Emissao = x.Field("emissao"); 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 = dataTable1.AsEnumerable().ToList(); Func u003cu003e9_9 = func2; if (u003cu003e9_9 == null) { Func func = (DataRow d) => d.Field("id") == x.Field("id"); Func func1 = func; func2 = func; u003cu003e9_9 = func1; } IEnumerable dataRows = list.Where(u003cu003e9_9); Func u003cu003e9_2210 = ParcelaRepository.u003cu003ec.u003cu003e9__22_10; if (u003cu003e9_2210 == null) { u003cu003e9_2210 = (DataRow d) => d.Field("idvendedor"); ParcelaRepository.u003cu003ec.u003cu003e9__22_10 = u003cu003e9_2210; } return dataRows.Select(u003cu003e9_2210).ToList().Contains(v.Id); }).ToList(); documento.Tipo = x.Field("tipo"); documento.DataControle = x.Field("dataparcelacontrole"); documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); documento.DataCriacao = x.Field("cri_data"); documento.Banco = new Banco() { Nome = x.Field("banco") }; documento.Agencia = x.Field("agencia"); documento.Conta = x.Field("conta"); documento.PropostaAssinada = (x.Field("propassinada") == null ? false : x.Field("propassinada") == "1"); return documento; }).ToList(); } public bool FindParcel(long id) { bool flag; object connection; SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable = new DataTable(); 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 str = "SELECT DISTINCT c.idcliente, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.tiporecebimento, p.idparcela, pe.idparcela AS idParcelaParcelaExtrato, p.datacred FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN parcela p ON p.iddocumento = d.iddocumento INNER JOIN parcelaextrato pe ON pe.iddocumento = d.iddocumento WHERE (d.excluido IS NULL OR d.excluido = 0) "; DateTime networkTime = Funcoes.GetNetworkTime(); sqlCommand.CommandText = string.Format("{0} AND (d.vigencia2 IS NULL AND d.situacao IN (1,2) OR d.vigencia2 >= '{1:yyyy-MM-dd}') AND DATALENGTH(ISNULL( d.contrato, '' )) > 0 AND d.iddocumento in ({2}) AND pe.idparcela = p.idparcela", str, networkTime.Date, id); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } bool flag1 = false; foreach (DataRow row in dataTable.Rows) { string str1 = string.Format("{0}", row["datacred"]); flag1 = (string.Format("{0}", row["idparcela"]) != string.Format("{0}", row["idParcelaParcelaExtrato"]) ? false : !string.IsNullOrEmpty(str1)); } flag = flag1; } } return flag; } public Parcela Merge(Parcela parcela) { ParcelaDb parcelaDb = ApplicationMapper.Mapper.Map(parcela); if (parcelaDb.IdEmpresa == 0) { parcelaDb.IdEmpresa = (long)1; } base.Merge(parcelaDb); if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela) { return ApplicationMapper.Mapper.Map(parcelaDb); } FaturaDb fatura = this._unitOfWork.Query().FirstOrDefault((FaturaDb x) => x.Parcela.Id == parcelaDb.Id) ?? new FaturaDb(); fatura.Parcela = parcelaDb; fatura.Fatura = parcelaDb.Fatura; FaturaDb faturaDb = fatura; DateTime? vigenciaIncial = parcelaDb.VigenciaIncial; faturaDb.VigenciaInicial = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.VigenciaInicial); FaturaDb faturaDb1 = fatura; vigenciaIncial = parcelaDb.VigenciaFinal; faturaDb1.VigenciaFinal = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.VigenciaFinal); FaturaDb faturaDb2 = fatura; vigenciaIncial = parcelaDb.Emissao; faturaDb2.Emissao = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.Emissao); if (fatura.Id != 0) { this._unitOfWork.Repository().Merge(fatura); } else { this._unitOfWork.Repository().SaveOrUpdate(fatura); } return ApplicationMapper.Mapper.Map(parcelaDb); } public List PrevisaoPagamentoComissao(Filtros filtro) { object connection; string str2 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND d.situacao IN (", string.Join(",", from v in filtro.Status select v), ")")); string str3 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", from v in filtro.Negocio select v), ")")); string str4 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", from v in filtro.Seguradoras select v), ")")); string str5 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", from v in filtro.Ramos select v), ")")); string str6 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", from v in filtro.Produtos select v), ")")); string str7 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? " AND vp.idvendedor IS NOT NULL " : string.Concat(" AND vp.idvendedor IN (", string.Join(",", from v in filtro.Vendedores select v), ")")); string str8 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? " AND vp.idtipovendedor = 1 " : string.Concat(" AND vp.idtipovendedor IN (", string.Join(",", from v in filtro.TipoVendedor select v), ")")); string str9 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", from v in filtro.Estipulantes select v), ")")); string str10 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; DataTable dataTable = new DataTable(); 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); sqlCommand.CommandText = string.Concat("SELECT DISTINCT d.tipo, f.NUMFATURA, f.VIGENCIAI, vp.idvendedorparcela, vp.idvendedor, cl.nome AS cliente, d.situacao, d.contrato, d.VIGENCIA1, d.aditamento, c.idciaseg, c.idramo, p.parcela, ISNULL(v.desconto, 0) as desconto, p.vencto, ISNULL(vp.vlrrep, 0) as vlrliquido, ISNULL(d.pr_liq, 0) as pr_liq, ISNULL(p.VALORLF, 0) as valorlf, ISNULL(p.vlrcomiss, 0) as vlrcomiss, p.idsubtipo, d.n_parc, d.tiporecebimento FROM controle c INNER JOIN cliente cl on cl.idcliente = c.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole INNER JOIN parcela p on p.iddocumento = d.iddocumento INNER JOIN vendedorparcela vp on vp.idparcela = p.idparcela INNER JOIN vendedor v on v.idvendedor = vp.idvendedor LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela ", string.Format("WHERE (d.excluido IS NULL OR d.excluido != 1) AND v.corretora != '1' AND vp.datapgt IS NULL AND vp.vlrrep != 0 AND (d.tiporecebimento = '1' AND ISNULL(d.com01, 0.00) > 0 OR d.tiporecebimento = '2') {0} {1} {2} {3} {4} {5} {6} {7} {8} AND p.vencto >= '{9:yyyy-MM-dd}' AND p.vencto <= '{10:yyyy-MM-dd}';", new object[] { str10, str7, str2, str3, str4, str5, str6, str8, str9, filtro.Inicio, filtro.Fim })); using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) { sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataTable); } } } return dataTable.AsEnumerable().ToList().Select((DataRow x) => { string nome; string str; string nome1; string str1; PrevisaoPagamento previsaoPagamento = new PrevisaoPagamento() { Nome = x.Campo("cliente"), Apolice = (x.IsNull("tiporecebimento") ? "" : (x.Campo("tiporecebimento") == "1" ? x.Campo("contrato") : x.Campo("NUMFATURA"))), Endosso = (x.Campo("tiporecebimento") == "1" ? x.Campo("aditamento") : ""), Status = x.Campo("situacao").GetDescription(), VigenciaInicial = (x.Campo("tiporecebimento") == "1" ? x.Campo("VIGENCIA1") : x.Campo("VIGENCIAI")), TipoDocumento = (x.IsNull("tiporecebimento") ? "" : (x.Campo("tiporecebimento") == "2" ? "FATURA" : (x.Campo("tipo") == "0" ? "APÓLICE" : "ENDOSSO"))) }; Seguradora seguradora = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Campo("idciaseg")); if (seguradora != null) { nome = seguradora.Nome; } else { nome = null; } previsaoPagamento.NomeSeguradora = nome; Ramo ramo = Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Campo("idramo")); if (ramo != null) { str = ramo.Nome; } else { str = null; } previsaoPagamento.NomeRamo = str; previsaoPagamento.PremioLiquido = (x.Campo("tiporecebimento") == "1" ? x.Campo("pr_liq") : x.Campo("valorlf")); previsaoPagamento.Parcela = (x.Campo("idsubtipo") > (long)1 ? "ESPECIAL" : (x.Campo("tiporecebimento") == "1" ? string.Concat(x.Campo("parcela").PadLeft(2, '0'), " DE ", x.Campo("n_parc")) : x.Campo("parcela").PadLeft(2, '0'))); previsaoPagamento.VencimentoParcela = x.Campo("vencto"); previsaoPagamento.RepasseLiquido = x.Campo("vlrliquido") * (decimal.One - (x.Campo("desconto") > decimal.One ? x.Campo("desconto") * new decimal(1, 0, 0, false, 2) : x.Campo("desconto"))); previsaoPagamento.Repasse = x.Campo("vlrliquido"); previsaoPagamento.Vendedor = Auxiliar.Vendedores.Find((Vendedor p) => p.Id == x.Campo("idvendedor")); Seguradora seguradora1 = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Campo("idciaseg")); if (seguradora1 != null) { nome1 = seguradora1.Nome; } else { nome1 = null; } previsaoPagamento.Seguradora = nome1; Ramo ramo1 = Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Campo("idramo")); if (ramo1 != null) { str1 = ramo1.Nome; } else { str1 = null; } previsaoPagamento.Ramo = str1; return previsaoPagamento; }).ToList(); } public Parcela SaveOrUpdate(Parcela parcela) { ParcelaDb parcelaDb = ApplicationMapper.Mapper.Map(parcela); if (parcelaDb.IdEmpresa == 0) { parcelaDb.IdEmpresa = (long)1; } this.SaveOrUpdate(parcelaDb); if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela) { return ApplicationMapper.Mapper.Map(parcelaDb); } FaturaDb faturaDb = new FaturaDb() { Parcela = parcelaDb, Fatura = parcelaDb.Fatura, VigenciaInicial = parcelaDb.VigenciaIncial, VigenciaFinal = parcelaDb.VigenciaFinal, Emissao = parcelaDb.Emissao }; this._unitOfWork.Repository().SaveOrUpdate(faturaDb); return ApplicationMapper.Mapper.Map(parcelaDb); } public int[] SincronizarPendencia(DateTime date, List ids = null) { // // Current member / type: System.Int32[] Gestor.Infrastructure.Repository.Logic.ParcelaRepository::SincronizarPendencia(System.DateTime,System.Collections.Generic.List`1) // File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll // // Product version: 0.0.0.0 // Exception in: System.Int32[] SincronizarPendencia(System.DateTime,System.Collections.Generic.List) // // An item with the same key has already been added. Key: Label0 // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection>.Add(KeyValuePair`2 keyValuePair) // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 101 // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 332 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 384 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitIfStatement(IfStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 363 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitTryStatement(TryStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 483 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitTryStatement(TryStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 483 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 74 // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33 // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 23 // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 // // mailto: JustDecompilePublicFeedback@telerik.com } public bool Update(List detalhes, bool desabilitaAproximação) { // // Current member / type: System.Boolean Gestor.Infrastructure.Repository.Logic.ParcelaRepository::Update(System.Collections.Generic.List`1,System.Boolean) // File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll // // Product version: 0.0.0.0 // Exception in: System.Boolean Update(System.Collections.Generic.List,System.Boolean) // // An item with the same key has already been added. Key: Label0 // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection>.Add(KeyValuePair`2 keyValuePair) // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 101 // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 351 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 384 // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 74 // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33 // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 23 // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 // // mailto: JustDecompilePublicFeedback@telerik.com } public List UpdateRange(List parcelas) { List parcelaDbs = ApplicationMapper.Mapper.Map, List>(parcelas); parcelaDbs.ForEach((ParcelaDb x) => { if (x.IdEmpresa == 0) { x.IdEmpresa = (long)1; } }); ParcelaRepository parcelaRepository = this; parcelaDbs.ForEach(new Action(parcelaRepository.Merge)); return ApplicationMapper.Mapper.Map, List>(parcelaDbs); } private async Task VerificaVendedorPropriaCorretora(List vendedores) { bool valueOrDefault; object connection; List condicaos = new List(); Condicao condicao = new Condicao() { Campo = "IdVendedor", Valores = vendedores.CriarValor(), Grupo = 1, Operacao = Operacao.Or }; condicaos.Add(condicao); SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); 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 = string.Concat("SELECT COUNT(IdVendedor) FROM Vendedor WHERE Corretora = 1 AND ", sqlQueryCondition.Condicao); sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); int? nullable = (int?)await sqlCommand.ExecuteScalarAsync(); valueOrDefault = nullable.GetValueOrDefault() > 0; } } } return valueOrDefault; } private class VinculoParcela { public string Apolice { get; set; } public string Endosso { get; set; } public long IdDocumento { get; set; } public long IdParcela { get; set; } public int Parcela { get; set; } public Seguradora Seguradora { get; set; } public int Tipo { get; set; } public VinculoParcela() { } } } }