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