From 1f4e14b2e973ee7de337fd4866d9a5ceff5cb6d1 Mon Sep 17 00:00:00 2001 From: Lucas Faria Mendes Date: Mon, 30 Mar 2026 10:38:18 -0300 Subject: chore: location --- .../AdiantamentoRepository.cs | 168 - .../AeronauticoRepository.cs | 71 - .../AgendaEmailRepository.cs | 151 - .../AgendaRepository.cs | 86 - .../AgendaTelefoneRepository.cs | 149 - .../AtividadeRepository.cs | 92 - .../AtualizacaoRepository.cs | 44 - .../AutoRepository.cs | 607 --- .../BancoRepository.cs | 69 - .../BancosContasRepository.cs | 119 - .../CategoriaTarefaRepository.cs | 46 - .../CentroRepository.cs | 96 - .../ClienteEmailRepository.cs | 248 - .../ClienteEnderecoRepository.cs | 223 - .../ClienteRepository.cs | 3102 ------------ .../ClienteTelefoneRepository.cs | 220 - .../ClienteVinculoRepository.cs | 112 - .../CoberturaGranizoRepository.cs | 65 - .../CoberturaPadraoRepository.cs | 70 - .../CoberturaRepository.cs | 174 - .../CondicaoRepasseRepository.cs | 46 - .../ConfigExtratoImportRepository.cs | 101 - .../ConfiguracaoRepository.cs | 61 - .../ConsorcioRepository.cs | 66 - .../ControleFinanceiroRepository.cs | 73 - .../ControleRepository.cs | 68 - .../ControleSinistroRepository.cs | 161 - .../CredencialRepository.cs | 75 - .../CriticaApoliceRepository.cs | 315 -- .../DetalheExtratoRepository.cs | 99 - .../DocumentoRepository.cs | 5095 -------------------- .../EmpresaRepository.cs | 143 - .../EstipulanteRepository.cs | 93 - .../ExpedicaoRepository.cs | 55 - .../ExtratoRepository.cs | 237 - .../FabricanteRepository.cs | 65 - .../FornecedorRepository.cs | 103 - .../GranizoRepository.cs | 71 - .../ImpostoRepository.cs | 102 - .../IndiceArquivoDigitalRepository.cs | 402 -- .../ItemRepository.cs | 1450 ------ .../LancamentoRepository.cs | 345 -- .../MaisContatoRepository.cs | 158 - .../MetaSeguradoraRepository.cs | 127 - .../MetaVendedorRepository.cs | 125 - .../ModeloMalaDiretaRepository.cs | 59 - .../NotaFiscalRepository.cs | 131 - .../ParametrosRelatorioRepository.cs | 111 - .../ParametrosTotalizacaoRepository.cs | 59 - .../ParceiroRepository.cs | 108 - .../ParcelaRepository.cs | 4562 ------------------ .../PatrimonialRepository.cs | 251 - .../PerfilEmpresaRepository.cs | 64 - .../PerfilRepository.cs | 191 - .../PermissaoArquivoDigitalRepository.cs | 54 - .../PermissaoUsuarioRepository.cs | 84 - .../PlanoRepository.cs | 93 - .../PlanosRepository.cs | 101 - .../ProdutoRepository.cs | 76 - .../ProfissaoRepository.cs | 92 - .../ProspectRepository.cs | 245 - .../QualificacaoRepository.cs | 38 - .../RamoRepository.cs | 85 - .../ReciboRepository.cs | 71 - .../RegistroAcaoRepository.cs | 183 - .../RegistroLogRepository.cs | 222 - .../RepasseRepository.cs | 298 -- .../ReportRepository.cs | 1991 -------- .../RestricaoUsuarioCamposRelatoriosRepository.cs | 44 - .../RestricaoUsuarioRepository.cs | 54 - .../RiscosDiversosRepository.cs | 66 - .../SaldoRepository.cs | 136 - .../SeguradoraContatoRepository.cs | 131 - .../SeguradoraEnderecoRepository.cs | 97 - .../SeguradoraRepository.cs | 76 - .../SinistroAutoRepository.cs | 61 - .../SinistroRepository.cs | 415 -- .../SinistroVidaRepository.cs | 56 - .../SocioRepository.cs | 75 - .../StatusProspeccaoRepository.cs | 54 - .../StatusRepository.cs | 76 - .../TarefaRepository.cs | 462 -- .../TipoContaRepository.cs | 52 - .../TipoTarefaRepository.cs | 54 - .../TipoVendedorRepository.cs | 139 - .../TitularesVidaRepository.cs | 152 - .../UsuarioRepository.cs | 305 -- .../VendedorParcelaRepository.cs | 474 -- .../VendedorRepository.cs | 132 - .../VendedorTelefoneRepository.cs | 115 - .../VendedorUsuarioRepository.cs | 94 - .../VidaRepository.cs | 66 - .../VinculoDocumentoRepository.cs | 345 -- 93 files changed, 28448 deletions(-) delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DocumentoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs delete mode 100644 Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs (limited to 'Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic') diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs deleted file mode 100644 index aff2bf7..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs +++ /dev/null @@ -1,168 +0,0 @@ -using AutoMapper; -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.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class AdiantamentoRepository : GenericRepository, IAdiantamentoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public AdiantamentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List AddRange(List adiantamentos) - { - List adiantamentoDbs = ApplicationMapper.Mapper.Map, List>(adiantamentos); - base.AddRange(adiantamentoDbs); - return ApplicationMapper.Mapper.Map, List>(adiantamentoDbs); - } - - public List BuscarAdiantamentos(long id, bool concluido = false) - { - List list = ( - from x in base.All() - where x.Vendedor.Id == id && x.Pago == concluido - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find(bool ativo) - { - return this.Select((new List() - { - new Condicao() - { - Campo = "ativo", - Valores = null - }, - new Condicao() - { - Campo = "pago", - Valores = "1".CriarValor() - } - }).CreateParameters(0)); - } - - public List Find(long id) - { - return this.Select((new List() - { - new Condicao() - { - Campo = "idvendedor", - Valores = id.CriarValor() - } - }).CreateParameters(0)); - } - - public List Find(string nome) - { - return this.Select((new List() - { - new Condicao() - { - Campo = "historico", - Valores = nome.CriarValor() - } - }).CreateParameters(0)); - } - - public List FindByDate(DateTime inicio, DateTime fim, List vendedores = null, bool segundavia = false) - { - List condicaos = new List() - { - new Condicao() - { - Campo = (segundavia ? "CAST(Pagamento AS DATE)" : "CAST(data AS DATE)"), - Valores = inicio.CriarValor(), - Operador = Operador.MaiorEIgual - }, - new Condicao() - { - Campo = (segundavia ? "CAST(Pagamento AS DATE)" : "CAST(data AS DATE)"), - Valores = fim.CriarValor(), - Operador = Operador.MenorEIgual - } - }; - condicaos.AddRange((!segundavia ? new List() - { - new Condicao() - { - Campo = "pago", - Valores = null, - Operacao = Operacao.Or, - Grupo = 1 - }, - new Condicao() - { - Campo = "pago", - Valores = "1".CriarValor(), - Operacao = Operacao.Or, - Grupo = 1, - Operador = Operador.Diferente - } - } : new List() - { - new Condicao() - { - Campo = "pago", - Valores = "1".CriarValor() - } - })); - if (vendedores != null && vendedores.Count > 0) - { - condicaos.Add(new Condicao() - { - Campo = "idvendedor", - Valores = vendedores.CriarValor() - }); - } - return this.Select(condicaos.CreateParameters(0)); - } - - public Adiantamento FindById(long id) - { - AdiantamentoDb adiantamentoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(adiantamentoDb); - } - - public Adiantamento Merge(Adiantamento adiantamento) - { - AdiantamentoDb adiantamentoDb = ApplicationMapper.Mapper.Map(adiantamento); - base.Merge(adiantamentoDb); - return ApplicationMapper.Mapper.Map(adiantamentoDb); - } - - public Adiantamento SaveOrUpdate(Adiantamento adiantamento) - { - AdiantamentoDb adiantamentoDb = ApplicationMapper.Mapper.Map(adiantamento); - this.SaveOrUpdate(adiantamentoDb); - return ApplicationMapper.Mapper.Map(adiantamentoDb); - } - - private List Select(SqlQueryCondition sqlCondition) - { - return this._unitOfWork.Select(sqlCondition, "SELECT DISTINCT * FROM adiantamento WHERE", "").MapAdiantamento(); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs deleted file mode 100644 index b5b4d57..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs +++ /dev/null @@ -1,71 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class AeronauticoRepository : GenericRepository, IAeronauticoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public AeronauticoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - AeronauticoDb aeronauticoDb = base.FindEntityById(id); - if (aeronauticoDb == null) - { - return; - } - base.Delete(aeronauticoDb); - } - - public void DeleteRange(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Item.Id) - select x).ToList(); - base.DeleteRange(list); - } - - public Aeronautico Find(long id) - { - AeronauticoDb aeronauticoDb = base.All().FirstOrDefault((AeronauticoDb x) => x.Item.Id == id) ?? new AeronauticoDb(); - return ApplicationMapper.Mapper.Map(aeronauticoDb); - } - - public Aeronautico FindById(long id) - { - AeronauticoDb aeronauticoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(aeronauticoDb); - } - - public Aeronautico Merge(Aeronautico aeronautico) - { - AeronauticoDb aeronauticoDb = ApplicationMapper.Mapper.Map(aeronautico); - base.Merge(aeronauticoDb); - return ApplicationMapper.Mapper.Map(aeronauticoDb); - } - - public Aeronautico SaveOrUpdate(Aeronautico aeronautico) - { - AeronauticoDb aeronauticoDb = ApplicationMapper.Mapper.Map(aeronautico); - this.SaveOrUpdate(aeronauticoDb); - return ApplicationMapper.Mapper.Map(aeronauticoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs deleted file mode 100644 index 9131660..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs +++ /dev/null @@ -1,151 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Ferramentas; -using Gestor.Model.Domain.Generic; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class AgendaEmailRepository : GenericRepository, IAgendaEmailRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public AgendaEmailRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public void DeleteRange(long id) - { - IQueryable agendaEmailDbs = - from x in base.All() - where x.Agenda.Id == id - select x; - if (!agendaEmailDbs.Any()) - { - return; - } - base.DeleteRange(agendaEmailDbs); - } - - private List FindByAgenda(long id) - { - List list = ( - from x in base.All() - where x.Agenda.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindByAgenda(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Agenda.Id) - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindByAgendaId(long id) - { - return this.FindByAgenda(id); - } - - public AgendaEmail FindById(long id) - { - AgendaEmailDb agendaEmailDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(agendaEmailDb); - } - - public List FindEmailAgenda(string email) - { - List list = ( - from x in base.All() - where x.Email.Contains(email) - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List Inserir(List emails, Agenda agenda) - { - emails.ForEach((AgendaEmail x) => x.Agenda = agenda); - List agendaEmailDbs = ApplicationMapper.Mapper.Map, List>(emails); - base.AddRange(agendaEmailDbs); - return ApplicationMapper.Mapper.Map, List>(agendaEmailDbs); - } - - public List Inserir(List emails) - { - List agendaEmailDbs = ApplicationMapper.Mapper.Map, List>(emails); - agendaEmailDbs.ForEach((AgendaEmailDb x) => { - if (x.Id == 0) - { - this.SaveOrUpdate(x); - return; - } - base.Merge(x); - }); - return ApplicationMapper.Mapper.Map, List>(agendaEmailDbs); - } - - public AgendaEmail Merge(AgendaEmail agendaEmail) - { - AgendaEmailDb agendaEmailDb = ApplicationMapper.Mapper.Map(agendaEmail); - base.Merge(agendaEmailDb); - return ApplicationMapper.Mapper.Map(agendaEmailDb); - } - - public List Merge(List emails, Agenda agenda) - { - IQueryable agendaEmailDbs = - from x in base.All() - where x.Agenda.Id == agenda.Id - select x; - AgendaEmailRepository agendaEmailRepository = this; - ( - from x in agendaEmailDbs - select x.Id).ToList().Where((long x) => { - List agendaEmails = emails; - Func u003cu003e9_114 = AgendaEmailRepository.u003cu003ec.u003cu003e9__11_4; - if (u003cu003e9_114 == null) - { - u003cu003e9_114 = (AgendaEmail t) => t.Id; - AgendaEmailRepository.u003cu003ec.u003cu003e9__11_4 = u003cu003e9_114; - } - return !agendaEmails.Select(u003cu003e9_114).Contains(x); - }).ToList().ForEach(new Action(agendaEmailRepository.Delete)); - List agendaEmailDbs1 = ApplicationMapper.Mapper.Map, List>(emails); - agendaEmailDbs1.ForEach((AgendaEmailDb x) => { - if (x.Id != 0) - { - base.Merge(x); - return; - } - x.Agenda = ApplicationMapper.Mapper.Map(agenda); - this.SaveOrUpdate(x); - }); - return ApplicationMapper.Mapper.Map, List>(agendaEmailDbs1); - } - - public AgendaEmail SaveOrUpdate(AgendaEmail agendaEmail) - { - AgendaEmailDb agendaEmailDb = ApplicationMapper.Mapper.Map(agendaEmail); - this.SaveOrUpdate(agendaEmailDb); - return ApplicationMapper.Mapper.Map(agendaEmailDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs deleted file mode 100644 index 1ab42b8..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs +++ /dev/null @@ -1,86 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Ferramentas; -using Gestor.Model.Domain.Generic; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class AgendaRepository : GenericRepository, IAgendaRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public AgendaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - AgendaDb agendaDb = base.FindEntityById(id); - if (agendaDb == null) - { - return; - } - (new AgendaEmailRepository(this._unitOfWork)).DeleteRange(id); - (new AgendaTelefoneRepository(this._unitOfWork)).DeleteRange(id); - base.Delete(agendaDb); - } - - public List Find(string filter) - { - AgendaRepository.u003cu003ec__DisplayClass3_0 variable = null; - IQueryable agendaDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(AgendaDb), "x"); - IQueryable agendaDbs1 = agendaDbs.Where(Expression.Lambda>(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AgendaDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(AgendaRepository.u003cu003ec__DisplayClass3_0)), FieldInfo.GetFieldFromHandle(typeof(AgendaRepository.u003cu003ec__DisplayClass3_0).GetField("filter").FieldHandle)) }), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(AgendaDb), "x"); - return agendaDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Agenda)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Agenda).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AgendaDb).GetMethod("get_Nome").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); - } - - public List Find() - { - List list = base.All().ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Agenda FindById(long id) - { - AgendaDb agendaDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(agendaDb); - } - - public List FindByName(string name) - { - AgendaRepository.u003cu003ec__DisplayClass4_0 variable = null; - IQueryable agendaDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(AgendaDb), "x"); - IQueryable agendaDbs1 = agendaDbs.Where(Expression.Lambda>(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AgendaDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(AgendaRepository.u003cu003ec__DisplayClass4_0)), FieldInfo.GetFieldFromHandle(typeof(AgendaRepository.u003cu003ec__DisplayClass4_0).GetField("name").FieldHandle)) }), new ParameterExpression[] { parameterExpression })).Take(150); - parameterExpression = Expression.Parameter(typeof(AgendaDb), "x"); - return agendaDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Agenda)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Agenda).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AgendaDb).GetMethod("get_Nome").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); - } - - public Agenda Merge(Agenda agenda) - { - AgendaDb agendaDb = ApplicationMapper.Mapper.Map(agenda); - base.Merge(agendaDb); - return ApplicationMapper.Mapper.Map(agendaDb); - } - - public Agenda SaveOrUpdate(Agenda agenda) - { - AgendaDb agendaDb = ApplicationMapper.Mapper.Map(agenda); - this.SaveOrUpdate(agendaDb); - return ApplicationMapper.Mapper.Map(agendaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs deleted file mode 100644 index 9c1b0d6..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs +++ /dev/null @@ -1,149 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Ferramentas; -using Gestor.Model.Domain.Generic; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class AgendaTelefoneRepository : GenericRepository, IAgendaTelefoneRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public AgendaTelefoneRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public void DeleteRange(long id) - { - IQueryable agendaTelefoneDbs = - from x in base.All() - where x.Agenda.Id == id - select x; - if (!agendaTelefoneDbs.Any()) - { - return; - } - base.DeleteRange(agendaTelefoneDbs); - } - - public List Find(string telefone) - { - List list = ( - from x in base.All() - where x.Numero.Contains(telefone) - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - private List FindByAgenda(long id) - { - return ( - from x in base.All() - where x.Agenda.Id == id - select new AgendaTelefone() - { - Id = x.Id, - Agenda = ApplicationMapper.Mapper.Map(x.Agenda), - Prefixo = x.Prefixo, - Numero = x.Numero, - Tipo = x.Tipo, - Observacao = x.Observacao - }).ToList(); - } - - public List FindByAgendaId(long id) - { - return this.FindByAgenda(id); - } - - public AgendaTelefone FindById(long id) - { - AgendaTelefoneDb agendaTelefoneDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(agendaTelefoneDb); - } - - public List Inserir(List telefones) - { - List agendaTelefoneDbs = ApplicationMapper.Mapper.Map, List>(telefones); - agendaTelefoneDbs.ForEach((AgendaTelefoneDb x) => { - if (x.Id == 0) - { - this.SaveOrUpdate(x); - return; - } - base.Merge(x); - }); - return ApplicationMapper.Mapper.Map, List>(agendaTelefoneDbs); - } - - public List Inserir(List telefones, Agenda agenda) - { - telefones.ForEach((AgendaTelefone x) => x.Agenda = agenda); - List agendaTelefoneDbs = ApplicationMapper.Mapper.Map, List>(telefones); - base.AddRange(agendaTelefoneDbs); - return ApplicationMapper.Mapper.Map, List>(agendaTelefoneDbs); - } - - public AgendaTelefone Merge(AgendaTelefone telefone) - { - AgendaTelefoneDb agendaTelefoneDb = ApplicationMapper.Mapper.Map(telefone); - base.Merge(agendaTelefoneDb); - return ApplicationMapper.Mapper.Map(agendaTelefoneDb); - } - - public List Merge(List telefones, Agenda agenda) - { - IQueryable agendaTelefoneDbs = - from x in base.All() - where x.Agenda.Id == agenda.Id - select x; - AgendaTelefoneRepository agendaTelefoneRepository = this; - ( - from x in agendaTelefoneDbs - select x.Id).ToList().Where((long x) => { - List agendaTelefones = telefones; - Func u003cu003e9_114 = AgendaTelefoneRepository.u003cu003ec.u003cu003e9__11_4; - if (u003cu003e9_114 == null) - { - u003cu003e9_114 = (AgendaTelefone t) => t.Id; - AgendaTelefoneRepository.u003cu003ec.u003cu003e9__11_4 = u003cu003e9_114; - } - return !agendaTelefones.Select(u003cu003e9_114).Contains(x); - }).ToList().ForEach(new Action(agendaTelefoneRepository.Delete)); - List agendaTelefoneDbs1 = ApplicationMapper.Mapper.Map, List>(telefones); - agendaTelefoneDbs1.ForEach((AgendaTelefoneDb x) => { - if (x.Id != 0) - { - base.Merge(x); - return; - } - x.Agenda = ApplicationMapper.Mapper.Map(agenda); - this.SaveOrUpdate(x); - }); - return ApplicationMapper.Mapper.Map, List>(agendaTelefoneDbs1); - } - - public AgendaTelefone SaveOrUpdate(AgendaTelefone telefone) - { - AgendaTelefoneDb agendaTelefoneDb = ApplicationMapper.Mapper.Map(telefone); - this.SaveOrUpdate(agendaTelefoneDb); - return ApplicationMapper.Mapper.Map(agendaTelefoneDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs deleted file mode 100644 index d3261c6..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs +++ /dev/null @@ -1,92 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Common; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Common; -using Gestor.Model.Domain.Generic; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class AtividadeRepository : GenericRepository, IAtividadeRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public AtividadeRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List Find(string filter) - { - AtividadeRepository.u003cu003ec__DisplayClass5_0 variable = null; - IQueryable atividadeDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(AtividadeDb), "x"); - IQueryable atividadeDbs1 = atividadeDbs.Where(Expression.Lambda>(Expression.OrElse(Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AtividadeDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(AtividadeRepository.u003cu003ec__DisplayClass5_0)), FieldInfo.GetFieldFromHandle(typeof(AtividadeRepository.u003cu003ec__DisplayClass5_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AtividadeDb).GetMethod("get_Cnac").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(AtividadeRepository.u003cu003ec__DisplayClass5_0)), FieldInfo.GetFieldFromHandle(typeof(AtividadeRepository.u003cu003ec__DisplayClass5_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(AtividadeDb), "x"); - return atividadeDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Atividade)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Atividade).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AtividadeDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Atividade).GetMethod("set_Cnac", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(AtividadeDb).GetMethod("get_Cnac").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); - } - - public long FindLastId() - { - long num; - object connection; - SqlCommand sqlCommand; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - sqlCommand = sqlConnection.CreateCommand(); - } - else - { - sqlCommand = null; - } - using (SqlCommand sqlCommand1 = sqlCommand) - { - sqlCommand1.CommandText = "SELECT MAX(idatividade) as id FROM atividade"; - SqlDataReader sqlDataReader = sqlCommand1.ExecuteReader(); - sqlDataReader.Read(); - sqlDataReader["id"].ToString(); - num = (sqlDataReader["id"] == null || sqlDataReader["id"].ToString() == "" || sqlDataReader["id"].ToString() == "{}" ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); - } - } - return num; - } - - public Atividade Merge(Atividade atividade) - { - AtividadeDb atividadeDb = ApplicationMapper.Mapper.Map(atividade); - base.Merge(atividadeDb); - return ApplicationMapper.Mapper.Map(atividadeDb); - } - - public Atividade SaveOrUpdate(Atividade atividade) - { - AtividadeDb atividadeDb = ApplicationMapper.Mapper.Map(atividade); - this.SaveOrUpdate(atividadeDb); - return ApplicationMapper.Mapper.Map(atividadeDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs deleted file mode 100644 index d4702f8..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs +++ /dev/null @@ -1,44 +0,0 @@ -using Gestor.Infrastructure.Entities.Common; -using Gestor.Infrastructure.Helpers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class AtualizacaoRepository : GenericRepository, IAtualizacaoRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public AtualizacaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public long FindLastUpdate() - { - AtualizacaoDb atualizacaoDb = ( - from x in base.All() - orderby x.IdArquivo descending - select x).FirstOrDefault(); - if (atualizacaoDb != null) - { - return atualizacaoDb.IdArquivo; - } - return (long)0; - } - - public void Save(long fileId) - { - this.Add(new AtualizacaoDb() - { - IdArquivo = fileId, - DataAtualizacao = Funcoes.GetNetworkTime() - }); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs deleted file mode 100644 index 7cbb775..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs +++ /dev/null @@ -1,607 +0,0 @@ -using AutoMapper; -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.Common; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class AutoRepository : GenericRepository, IAutoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public AutoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - AutoDb autoDb = base.FindEntityById(id); - if (autoDb == null) - { - return; - } - base.Delete(autoDb); - } - - public void DeleteRange(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Item.Id) - select x).ToList(); - base.DeleteRange(list); - } - - public Auto Find(long id) - { - AutoDb autoDb = base.All().FirstOrDefault((AutoDb x) => x.Item.Id == id) ?? new AutoDb(); - return ApplicationMapper.Mapper.Map(autoDb); - } - - public List FindAuto(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, TipoPesquisa tipo, bool tipobusca = false) - { - List pesquisaAvancadas; - object connection; - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - DataTable dataTable2 = new DataTable(); - DataTable dataTable3 = new DataTable(); - DateTime date = Funcoes.GetNetworkTime().Date; - List condicaos = new List() - { - new Condicao() - { - Campo = "d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }; - switch (status) - { - case FiltroStatusDocumento.Vencidos: - { - condicaos.AddRange(new List() - { - new Condicao() - { - Campo = "d.situacao", - Valores = new List() - { - 3, - 7 - }, - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = "d.vigencia2", - Valores = date.AddDays(-5).CriarValor(), - Operador = Operador.Menor - } - }); - goto case FiltroStatusDocumento.Todos; - } - case FiltroStatusDocumento.Cancelados: - { - condicaos.Add(new Condicao() - { - Campo = "d.situacao", - Valores = 3.CriarValor() - }); - goto case FiltroStatusDocumento.Todos; - } - case FiltroStatusDocumento.Recusados: - { - condicaos.Add(new Condicao() - { - Campo = "d.situacao", - Valores = 7.CriarValor() - }); - goto case FiltroStatusDocumento.Todos; - } - case FiltroStatusDocumento.Todos: - { - 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()) - { - List condicaos1 = new List(); - if (tipo == TipoPesquisa.Chassi) - { - condicaos1.Add(new Condicao() - { - Campo = "a.chassi", - Valores = pesquisa.CriarValor(), - Operador = (tipobusca ? Operador.Igual : Operador.Like) - }); - } - else if (tipo == TipoPesquisa.Item) - { - condicaos1.Add(new Condicao() - { - Campo = "i.descricao", - Valores = pesquisa.CriarValor(), - Operador = (tipobusca ? Operador.Igual : Operador.Like) - }); - } - else if (tipo == TipoPesquisa.Placa) - { - condicaos1.Add(new Condicao() - { - Campo = "REPLACE(a.placa, '-','')", - Valores = pesquisa.Replace("-", "").Replace("?", "%").CriarValor(), - Operador = (tipobusca ? Operador.Igual : Operador.Like) - }); - } - dataTable = sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT TOP 1000 i.iditem as id FROM item i LEFT OUTER JOIN auto a on i.iditem = a.iditem WHERE ", ""); - if (dataTable.Rows.Count != 0) - { - List condicaos2 = new List() - { - new Condicao() - { - Campo = "iditem", - Valores = dataTable.AsEnumerable().Select((DataRow v) => v.Field("id")).ToList().CriarValor() - } - }; - dataTable1 = sqlCommand.Select(condicaos2.CreateParameters(0), "SELECT iddocumento as id, descricao, iditem FROM item WHERE", ""); - condicaos.Add(new Condicao() - { - Campo = "d.iddocumento", - Valores = dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id")).ToList().CriarValor() - }); - dataTable2 = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT DISTINCT cl.nome as cliente, c.idcliente, d.idcontrole, d.iddocumento, situacao, ISNULL(vigencia1, GETDATE()) AS vigencia1, vigencia2, proposta, contrato as apolice, aditamento as endosso, CAST(tipo as INTEGER) as tipo FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); - if (dataTable2.Rows.Count != 0) - { - List list = ( - from x in dataTable2.AsEnumerable().ToList() - select x.Field("idcontrole")).ToList(); - List condicaos3 = new List() - { - new Condicao() - { - Campo = "d.idcontrole", - Valores = list.CriarValor() - } - }; - dataTable3 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE ", ""); - goto Label1; - } - else - { - pesquisaAvancadas = new List(); - } - } - else - { - pesquisaAvancadas = new List(); - } - } - } - return pesquisaAvancadas; - } - default: - { - condicaos.AddRange(new List() - { - new Condicao() - { - Campo = "d.situacao", - Valores = new List() - { - 1, - 2, - 4 - } - }, - new Condicao() - { - Campo = "d.vigencia2", - Valores = null, - Grupo = 2, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.vigencia2", - Valores = date.AddDays(-5).CriarValor(), - Grupo = 2, - Operacao = Operacao.Or, - Operador = Operador.Maior - } - }); - goto case FiltroStatusDocumento.Todos; - } - } - Label1: - List nums = null; - if (vendedorVinculado != null && vendedorVinculado.Count > 0) - { - nums = dataTable3.AsEnumerable().Where((DataRow x) => { - List vendedorUsuarios = vendedorVinculado; - Func u003cu003e9_107 = AutoRepository.u003cu003ec.u003cu003e9__10_7; - if (u003cu003e9_107 == null) - { - u003cu003e9_107 = (VendedorUsuario v) => v.Vendedor.Id; - AutoRepository.u003cu003ec.u003cu003e9__10_7 = u003cu003e9_107; - } - return vendedorUsuarios.Select(u003cu003e9_107).Contains(x.Field("idvendedor")); - }).Select((DataRow x) => x.Field("idcontrole")).ToList(); - } - if (nums != null && nums.Count == 0) - { - return new List(); - } - return dataTable2.AsEnumerable().Where((DataRow x) => { - if (nums == null) - { - return true; - } - return nums.Contains(x.Field("idcontrole")); - }).Select((DataRow x) => new PesquisaAvancada() - { - IdCliente = x.Field("idcliente"), - IdDocumento = x.Field("iddocumento"), - IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), - Nome = x.Field("cliente"), - Pesquisa = (x.Field("tipo") == 0 ? string.Format("ITEM: {0} - NÚMERO DA APÓLICE: {1} - NÚMERO DA PROPOSTA: {2} - VIGÊNCIA INICIAL: {3:d} ", new object[] { dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), x.Field("apolice"), x.Field("proposta"), x.Field("vigencia1") }) : string.Format("ITEM: {0} - NÚMERO DA APÓLICE: {1} - NÚMERO DA PROPOSTA: {2} - NÚMERO DO ENDOSSO: {3} VIGÊNCIA INICIAL: {4:d}", new object[] { dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), x.Field("apolice"), x.Field("proposta"), x.Field("endosso"), x.Field("vigencia1") })) - }).ToList(); - } - - public Documento FindByChassi(string chassi, long id, DateTime vigencia1, DateTime? vigencia2, long idSeguradora) - { - DocumentoDb documento; - List tipoSeguros = new List() - { - TipoSeguro.Novo, - TipoSeguro.Renovacao, - TipoSeguro.Reabilitado - }; - DateTime dateTime3 = Convert.ToDateTime(vigencia2); - AutoDb autoDb = ( - from a in base.All() - select new AutoDb() - { - Id = a.Id, - Chassi = a.Chassi, - Item = new ItemDb() - { - Cancelado = a.Item.Cancelado, - Substituido = a.Item.Substituido, - Documento = new DocumentoDb() - { - Vigencia1 = a.Item.Documento.Vigencia1, - Vigencia2 = a.Item.Documento.Vigencia2, - Situacao = a.Item.Documento.Situacao, - Excluido = a.Item.Documento.Excluido, - Controle = new ControleDb() - { - Id = a.Item.Documento.Controle.Id, - Seguradora = new SeguradoraDb() - { - Id = a.Item.Documento.Controle.Seguradora.Id, - Nome = a.Item.Documento.Controle.Seguradora.Nome, - NomeSocial = a.Item.Documento.Controle.Seguradora.NomeSocial - }, - Cliente = new ClienteDb() - { - Id = a.Item.Documento.Controle.Cliente.Id, - Nome = a.Item.Documento.Controle.Cliente.Nome - } - } - } - } - } into x - where x.Id != id && x.Chassi == chassi && tipoSeguros.Contains(x.Item.Documento.Situacao) - select x).ToList().AsEnumerable().ToList().Where((AutoDb x) => { - DateTime dateTime = dateTime3; - DateTime dateTime4 = x.Item.Documento.Vigencia1; - if (dateTime >= dateTime4.AddDays(5)) - { - DateTime dateTime1 = dateTime3; - dateTime4 = Convert.ToDateTime(x.Item.Documento.Vigencia2); - if (dateTime1 <= dateTime4.AddDays(5)) - { - return true; - } - } - DateTime dateTime2 = vigencia1; - dateTime4 = x.Item.Documento.Vigencia1; - if (dateTime2 < dateTime4.AddDays(5)) - { - return false; - } - dateTime4 = vigencia1.AddDays(5); - DateTime? nullable1 = x.Item.Documento.Vigencia2; - if (!nullable1.HasValue) - { - return false; - } - return dateTime4 <= nullable1.GetValueOrDefault(); - }).ToList().FirstOrDefault((AutoDb x) => { - long? nullable; - if (!x.Item.Cancelado) - { - long? substituido = x.Item.Substituido; - if (!substituido.HasValue && !x.Item.Documento.Excluido) - { - long num = idSeguradora; - ControleDb controle = x.Item.Documento.Controle; - if (controle != null) - { - nullable = new long?(controle.Seguradora.Id); - } - else - { - nullable = null; - } - substituido = nullable; - return num == substituido.GetValueOrDefault() & substituido.HasValue; - } - } - return false; - }); - if (autoDb != null) - { - documento = autoDb.Item.Documento; - } - else - { - documento = null; - } - return ApplicationMapper.Mapper.Map(documento); - } - - public Auto FindById(long id) - { - AutoDb autoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(autoDb); - } - - public string FindChassi(long id) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "iditem", - Valores = id.CriarValor() - } - }; - DataTable dataTable = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT chassi FROM auto WHERE ", ""); - if (dataTable == null) - { - return null; - } - DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault(); - if (dataRow == null) - { - return null; - } - return dataRow.Field("chassi"); - } - - public List FindPlaca(string placa, FiltroStatusDocumento status, List vendedorVinculado) - { - List pesquisaAvancadas; - object connection; - string str = placa.Replace("-", ""); - string str1 = str.Insert(3, "-"); - 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.CommandText = string.Concat(new string[] { "SELECT iditem as id FROM auto WHERE placa ='", str, "' OR placa ='", str1, "'" }); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - string str2 = string.Concat(" AND iditem IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat("SELECT iddocumento as id, descricao, iditem FROM item WHERE 1=1 ", str2); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - } - sqlCommand.CommandText = string.Concat("SELECT DISTINCT cl.nome as cliente, c.idcliente, d.idcontrole, d.iddocumento, situacao, vigencia1, vigencia2, proposta, contrato as apolice, aditamento as endosso, CAST(tipo as INTEGER) as tipo FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE (d.excluido IS NULL OR d.excluido != '1') AND d.iddocumento IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) - { - sqlDataAdapter2.SelectCommand = sqlCommand; - sqlDataAdapter2.Fill(dataTable2); - } - string str3 = string.Concat(" AND d.idcontrole IN (", string.Join(",", ( - from x in dataTable2.AsEnumerable().ToList() - select x.Field("idcontrole")).ToList()), ")"); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 ", str3); - using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) - { - sqlDataAdapter3.SelectCommand = sqlCommand; - sqlDataAdapter3.Fill(dataTable3); - goto Label0; - } - } - else - { - pesquisaAvancadas = new List(); - } - } - } - return pesquisaAvancadas; - Label0: - List list = null; - if (vendedorVinculado != null && vendedorVinculado.Count > 0) - { - list = dataTable3.AsEnumerable().Where((DataRow x) => { - List vendedorUsuarios = vendedorVinculado; - Func u003cu003e9_915 = AutoRepository.u003cu003ec.u003cu003e9__9_15; - if (u003cu003e9_915 == null) - { - u003cu003e9_915 = (VendedorUsuario v) => v.Vendedor.Id; - AutoRepository.u003cu003ec.u003cu003e9__9_15 = u003cu003e9_915; - } - return vendedorUsuarios.Select(u003cu003e9_915).Contains(x.Field("idvendedor")); - }).Select((DataRow x) => x.Field("idcontrole")).ToList(); - } - if (list != null && list.Count == 0) - { - return new List(); - } - DateTime date = Funcoes.GetNetworkTime().Date; - switch (status) - { - case FiltroStatusDocumento.Vencidos: - { - return dataTable2.AsEnumerable().Where((DataRow x) => { - if ((list == null || list.Contains(x.Field("idcontrole"))) && (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) == TipoSeguro.Renovado) - { - return true; - } - return x.Field("vigencia2") < date.AddDays(-5); - }).Select((DataRow x) => new PesquisaAvancada() - { - IdCliente = x.Field("idcliente"), - IdDocumento = x.Field("iddocumento"), - IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), - Nome = x.Field("cliente"), - Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) - }).ToList(); - } - case FiltroStatusDocumento.Cancelados: - { - return dataTable2.AsEnumerable().Where((DataRow x) => { - if (list != null && !list.Contains(x.Field("idcontrole"))) - { - return false; - } - return (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) == TipoSeguro.Cancelado; - }).Select((DataRow x) => new PesquisaAvancada() - { - IdCliente = x.Field("idcliente"), - IdDocumento = x.Field("iddocumento"), - IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), - Nome = x.Field("cliente"), - Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) - }).ToList(); - } - case FiltroStatusDocumento.Recusados: - { - return dataTable2.AsEnumerable().Where((DataRow x) => { - if (list != null && !list.Contains(x.Field("idcontrole"))) - { - return false; - } - return (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) == TipoSeguro.Recusado; - }).Select((DataRow x) => new PesquisaAvancada() - { - IdCliente = x.Field("idcliente"), - IdDocumento = x.Field("iddocumento"), - IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), - Nome = x.Field("cliente"), - Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) - }).ToList(); - } - case FiltroStatusDocumento.Todos: - { - return dataTable2.AsEnumerable().Where((DataRow x) => { - if (list == null) - { - return true; - } - return list.Contains(x.Field("idcontrole")); - }).Select((DataRow x) => new PesquisaAvancada() - { - IdCliente = x.Field("idcliente"), - IdDocumento = x.Field("iddocumento"), - IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), - Nome = x.Field("cliente"), - Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) - }).ToList(); - } - default: - { - return dataTable2.AsEnumerable().Where((DataRow x) => { - if (list != null && !list.Contains(x.Field("idcontrole")) || (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Novo && (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao) - { - return false; - } - return x.Field("vigencia2") > date.AddDays(-5); - }).Select((DataRow x) => new PesquisaAvancada() - { - IdCliente = x.Field("idcliente"), - IdDocumento = x.Field("iddocumento"), - IdItem = dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("iditem"), - Nome = x.Field("cliente"), - Pesquisa = (x.Field("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First((DataRow i) => i.Field("id") == x.Field("iddocumento")).Field("descricao"), " - NÚMERO DA APÓLICE: ", x.Field("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field("endosso") })) - }).ToList(); - } - } - } - - public Auto Merge(Auto auto) - { - AutoDb autoDb = ApplicationMapper.Mapper.Map(auto); - base.Merge(autoDb); - return ApplicationMapper.Mapper.Map(autoDb); - } - - public Auto SaveOrUpdate(Auto auto) - { - AutoDb autoDb = ApplicationMapper.Mapper.Map(auto); - this.SaveOrUpdate(autoDb); - return ApplicationMapper.Mapper.Map(autoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs deleted file mode 100644 index eaba0c1..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs +++ /dev/null @@ -1,69 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Common; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Common; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class BancoRepository : GenericRepository, IBancoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public BancoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find(string filter) - { - BancoRepository.u003cu003ec__DisplayClass7_0 variable = null; - IQueryable bancoDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(BancoDb), "x"); - IQueryable bancoDbs1 = bancoDbs.Where(Expression.Lambda>(Expression.OrElse(Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(BancoDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(BancoRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(BancoRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(BancoDb).GetMethod("get_Codigo").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(int).GetMethod("ToString").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(BancoRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(BancoRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(BancoDb), "x"); - return bancoDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Banco)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Banco).GetMethod("set_Id", new Type[] { typeof(int) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(BancoDb).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Banco).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(BancoDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Banco).GetMethod("set_Codigo", new Type[] { typeof(int) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(BancoDb).GetMethod("get_Codigo").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); - } - - public Banco FindById(long id) - { - BancoDb bancoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(bancoDb); - } - - public Banco Merge(Banco banco) - { - BancoDb bancoDb = ApplicationMapper.Mapper.Map(banco); - base.Merge(bancoDb); - return ApplicationMapper.Mapper.Map(bancoDb); - } - - public Banco SaveOrUpdate(Banco banco) - { - BancoDb bancoDb = ApplicationMapper.Mapper.Map(banco); - this.SaveOrUpdate(bancoDb); - return ApplicationMapper.Mapper.Map(bancoDb); - } - - public List SelectDefault() - { - return ApplicationMapper.Mapper.Map, List>(( - from x in base.All() - orderby x.Nome - select x).ToList()); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs deleted file mode 100644 index 53fa20c..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs +++ /dev/null @@ -1,119 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Financeiro; -using Gestor.Infrastructure.Entities.Generic; -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.Domain.Financeiro; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class BancosContasRepository : GenericRepository, IBancosContasRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public BancosContasRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - List list = ( - from x in this._unitOfWork.Query() - where x.Conta.Id == id - select x).ToList(); - if (list.Any()) - { - this._unitOfWork.Repository().DeleteRange(list); - } - BancosContasDb bancosContasDb = base.FindEntityById(id); - if (bancosContasDb == null) - { - return; - } - base.Delete(bancosContasDb); - } - - public List Find(string filter) - { - return this.Select(" AND ISNULL(UPPER(descricao)) LIKE '%filter%'"); - } - - public List Find() - { - return this.Select(""); - } - - public BancosContas FindById(long id) - { - BancosContasDb bancosContasDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(bancosContasDb); - } - - public BancosContas Merge(BancosContas bancosContas) - { - BancosContasDb bancosContasDb = ApplicationMapper.Mapper.Map(bancosContas); - base.Merge(bancosContasDb); - return ApplicationMapper.Mapper.Map(bancosContasDb); - } - - public BancosContas SaveOrUpdate(BancosContas bancosContas) - { - BancosContasDb bancosContasDb = ApplicationMapper.Mapper.Map(bancosContas); - this.SaveOrUpdate(bancosContasDb); - return ApplicationMapper.Mapper.Map(bancosContasDb); - } - - private List Select(string condition) - { - List bancosContas; - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - sqlCommand.CommandText = string.Concat("SELECT * FROM conta WHERE 1=1 ", condition); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - return CustomMap.MapConta(dataTable); - } - else - { - bancosContas = new List(); - } - } - } - return bancosContas; - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs deleted file mode 100644 index e3cbdf9..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs +++ /dev/null @@ -1,46 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Ferramentas; -using System; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class CategoriaTarefaRepository : GenericRepository, ICategoriaTarefaRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public CategoriaTarefaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public CategoriaTarefa FindById(long id) - { - CategoriaTarefaDb categoriaTarefaDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(categoriaTarefaDb); - } - - public CategoriaTarefa Merge(CategoriaTarefa categoriaTarefa) - { - CategoriaTarefaDb categoriaTarefaDb = ApplicationMapper.Mapper.Map(categoriaTarefa); - base.Merge(categoriaTarefaDb); - return ApplicationMapper.Mapper.Map(categoriaTarefaDb); - } - - public CategoriaTarefa SaveOrUpdate(CategoriaTarefa categoriaTarefa) - { - CategoriaTarefaDb categoriaTarefaDb = ApplicationMapper.Mapper.Map(categoriaTarefa); - this.SaveOrUpdate(categoriaTarefaDb); - return ApplicationMapper.Mapper.Map(categoriaTarefaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs deleted file mode 100644 index c72986f..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs +++ /dev/null @@ -1,96 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Financeiro; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Financeiro; -using Gestor.Model.Domain.Generic; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class CentroRepository : GenericRepository, ICentroRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public CentroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List Find(string filter) - { - CentroRepository.u003cu003ec__DisplayClass2_0 variable = null; - IQueryable centroDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(CentroDb), "x"); - IQueryable centroDbs1 = centroDbs.Where(Expression.Lambda>(Expression.AndAlso(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CentroDb).GetMethod("get_Ativo").MethodHandle)), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CentroDb).GetMethod("get_Descricao").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(CentroRepository.u003cu003ec__DisplayClass2_0)), FieldInfo.GetFieldFromHandle(typeof(CentroRepository.u003cu003ec__DisplayClass2_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(CentroDb), "x"); - return centroDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Centro)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Centro).GetMethod("set_Descricao", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CentroDb).GetMethod("get_Descricao").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Centro).GetMethod("set_Ativo", new Type[] { typeof(bool) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CentroDb).GetMethod("get_Ativo").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Centro).GetMethod("set_IdEmpresa", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CentroDb).GetMethod("get_IdEmpresa").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); - } - - public List Find() - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT DISTINCT idcentro as id, descricao as nome, ativo FROM centro;"; - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - } - return ( - from a in dataTable.AsEnumerable().ToList() - select new Centro() - { - Id = a.Field("id"), - Descricao = a.Field("nome"), - Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") - }).ToList(); - } - - public Centro Merge(Centro centro) - { - CentroDb centroDb = ApplicationMapper.Mapper.Map(centro); - base.Merge(centroDb); - return ApplicationMapper.Mapper.Map(centroDb); - } - - public Centro SaveOrUpdate(Centro centro) - { - CentroDb centroDb = ApplicationMapper.Mapper.Map(centro); - this.SaveOrUpdate(centroDb); - return ApplicationMapper.Mapper.Map(centroDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs deleted file mode 100644 index 6d40eff..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs +++ /dev/null @@ -1,248 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ClienteEmailRepository : GenericRepository, IClienteEmailRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ClienteEmailRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List DeleteMail(long clienteId, List emails) - { - if (emails == null) - { - return null; - } - List list = ( - from x in base.All() - where x.Cliente.Id == clienteId - select x).ToList().Where((ClienteEmailDb email) => { - List clienteEmails = emails; - Func u003cu003e9_112 = ClienteEmailRepository.u003cu003ec.u003cu003e9__11_2; - if (u003cu003e9_112 == null) - { - u003cu003e9_112 = (ClienteEmail t) => t.Id; - ClienteEmailRepository.u003cu003ec.u003cu003e9__11_2 = u003cu003e9_112; - } - return !clienteEmails.Select(u003cu003e9_112).Contains(email.Id); - }).ToList(); - if (emails.Count == 0 && (list == null || list.Count == 0)) - { - return null; - } - ClienteEmailRepository clienteEmailRepository = this; - list.ForEach(new Action(clienteEmailRepository.Delete)); - return ApplicationMapper.Mapper.Map, List>(list); - } - - private List FindByCliente(long id) - { - return this.Select(string.Format(" AND cm.idcliente = {0}", id)); - } - - public List FindByCliente(List ids) - { - if (ids.Count == 0) - { - return new List(); - } - string str = string.Concat(" AND cm.idcliente IN (", string.Join(",", ids), ")"); - return this.Select(str); - } - - public List FindByClienteId(long id) - { - return this.FindByCliente(id); - } - - public ClienteEmail FindById(long id) - { - ClienteEmailDb clienteEmailDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(clienteEmailDb); - } - - public List FindEmailCliente(string email, long idempresa = 0L) - { - return this.Select((idempresa == 0 ? string.Concat(" AND cm.email LIKE '%", email, "%'") : string.Format(" AND c.idempresa = {0} AND CONTAINS(cm.email, \"%{1}%\")", idempresa, email))); - } - - public List Inserir(List emails, Cliente cliente) - { - emails.ForEach((ClienteEmail x) => { - string str; - x.Cliente = cliente; - ClienteEmail clienteEmail = x; - string observacao = x.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteEmail.Observacao = str; - }); - List clienteEmailDbs = ApplicationMapper.Mapper.Map, List>(emails); - base.AddRange(clienteEmailDbs); - return ApplicationMapper.Mapper.Map, List>(clienteEmailDbs); - } - - public List Inserir(List emails) - { - List clienteEmailDbs = ApplicationMapper.Mapper.Map, List>(emails); - clienteEmailDbs.ForEach((ClienteEmailDb x) => { - string str; - ClienteEmailDb clienteEmailDb = x; - string observacao = x.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteEmailDb.Observacao = str; - if (x.Id == 0) - { - this.SaveOrUpdate(x); - return; - } - base.Merge(x); - }); - return ApplicationMapper.Mapper.Map, List>(clienteEmailDbs); - } - - public ClienteEmail Merge(ClienteEmail clienteEmail) - { - string str; - ClienteEmailDb clienteEmailDb = ApplicationMapper.Mapper.Map(clienteEmail); - ClienteEmailDb clienteEmailDb1 = clienteEmailDb; - string observacao = clienteEmailDb.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteEmailDb1.Observacao = str; - base.Merge(clienteEmailDb); - return ApplicationMapper.Mapper.Map(clienteEmailDb); - } - - public List Merge(List emails, Cliente cliente) - { - List clienteEmailDbs = ApplicationMapper.Mapper.Map, List>(emails); - clienteEmailDbs.ForEach((ClienteEmailDb x) => { - string str; - ClienteEmailDb clienteEmailDb = x; - string observacao = x.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteEmailDb.Observacao = str; - if (x.Id != 0) - { - base.Merge(x); - return; - } - x.Cliente = ApplicationMapper.Mapper.Map(cliente); - this.SaveOrUpdate(x); - }); - return ApplicationMapper.Mapper.Map, List>(clienteEmailDbs); - } - - public ClienteEmail SaveOrUpdate(ClienteEmail clienteEmail) - { - string str; - ClienteEmailDb clienteEmailDb = ApplicationMapper.Mapper.Map(clienteEmail); - ClienteEmailDb clienteEmailDb1 = clienteEmailDb; - string observacao = clienteEmailDb.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteEmailDb1.Observacao = str; - this.SaveOrUpdate(clienteEmailDb); - return ApplicationMapper.Mapper.Map(clienteEmailDb); - } - - private List Select(string condition) - { - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT cm.idclimail AS Id, cm.idcliente as IdCliente, cm.email AS Email, cm.obs AS Observacao, cm.ordem AS Ordem, c.nome as NomeCliente FROM climail cm INNER JOIN cliente c ON c.idcliente = cm.idcliente WHERE 1=1 ", condition); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - List clienteEmails = CustomMap.MapEmail(dataTable); - int? nullable1 = new int?(0); - clienteEmails.ForEach((ClienteEmail x) => { - int? ordem = nullable1; - int? nullable = ordem; - nullable1 = (nullable.HasValue ? new int?(nullable.GetValueOrDefault() + 1) : null); - ClienteEmail clienteEmail = x; - ordem = x.Ordem; - clienteEmail.Ordem = (ordem.HasValue ? ordem : nullable1); - }); - return clienteEmails; - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs deleted file mode 100644 index 9a2ac8e..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs +++ /dev/null @@ -1,223 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ClienteEnderecoRepository : GenericRepository, IClienteEnderecoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ClienteEnderecoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List DeleteEndereco(long clienteId, List enderecos) - { - if (enderecos == null || enderecos.Count == 0) - { - return null; - } - List list = ( - from cliente in base.All() - where cliente.Cliente.Id == clienteId - select cliente).ToList().Where((ClienteEnderecoDb endereco) => { - List clienteEnderecos = enderecos; - Func u003cu003e9_102 = ClienteEnderecoRepository.u003cu003ec.u003cu003e9__10_2; - if (u003cu003e9_102 == null) - { - u003cu003e9_102 = (ClienteEndereco t) => t.Id; - ClienteEnderecoRepository.u003cu003ec.u003cu003e9__10_2 = u003cu003e9_102; - } - return !clienteEnderecos.Select(u003cu003e9_102).Contains(endereco.Id); - }).ToList(); - ClienteEnderecoRepository clienteEnderecoRepository = this; - list.ForEach(new Action(clienteEnderecoRepository.Delete)); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindByCliente(List clientes) - { - string str = string.Concat(" AND ce.idcliente in (", string.Join(",", ( - from x in clientes - select x.Id).Distinct()), ")"); - List clienteEnderecos = this.Select(str); - ( - from x in clienteEnderecos - orderby x.Ordem - select x).ToList().ForEach((ClienteEndereco x) => x.Selecionado = x.Id == clienteEnderecos.First((ClienteEndereco c) => c.Cliente.Id == x.Cliente.Id).Id); - return clienteEnderecos; - } - - public List FindByClienteId(long id) - { - return this.Select(string.Format(" AND ce.idcliente = {0}", id)); - } - - public ClienteEndereco FindById(long id) - { - ClienteEnderecoDb clienteEnderecoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(clienteEnderecoDb); - } - - public List Inserir(List endereco, Cliente cliente) - { - endereco.ForEach((ClienteEndereco x) => x.Cliente = cliente); - List clienteEnderecoDbs = ApplicationMapper.Mapper.Map, List>(endereco); - base.AddRange(clienteEnderecoDbs); - return ApplicationMapper.Mapper.Map, List>(clienteEnderecoDbs); - } - - public List Inserir(List endereco) - { - List clienteEnderecoDbs = ApplicationMapper.Mapper.Map, List>(endereco); - clienteEnderecoDbs.ForEach((ClienteEnderecoDb x) => { - string str; - ClienteEnderecoDb clienteEnderecoDb = x; - string observacao = x.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteEnderecoDb.Observacao = str; - if (x.Id == 0) - { - this.SaveOrUpdate(x); - return; - } - base.Merge(x); - }); - return ApplicationMapper.Mapper.Map, List>(clienteEnderecoDbs); - } - - public ClienteEndereco Merge(ClienteEndereco clienteEndereco) - { - string str; - ClienteEnderecoDb clienteEnderecoDb = ApplicationMapper.Mapper.Map(clienteEndereco); - ClienteEnderecoDb clienteEnderecoDb1 = clienteEnderecoDb; - string observacao = clienteEnderecoDb.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteEnderecoDb1.Observacao = str; - base.Merge(clienteEnderecoDb); - return ApplicationMapper.Mapper.Map(clienteEnderecoDb); - } - - public List Merge(List enderecos, Cliente cliente) - { - List clienteEnderecoDbs = ApplicationMapper.Mapper.Map, List>(enderecos); - clienteEnderecoDbs.ForEach((ClienteEnderecoDb x) => { - string str; - ClienteEnderecoDb clienteEnderecoDb = x; - string observacao = x.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteEnderecoDb.Observacao = str; - if (x.Id != 0) - { - base.Merge(x); - return; - } - x.Cliente = ApplicationMapper.Mapper.Map(cliente); - this.SaveOrUpdate(x); - }); - return ApplicationMapper.Mapper.Map, List>(clienteEnderecoDbs); - } - - public ClienteEndereco SaveOrUpdate(ClienteEndereco clienteEndereco) - { - string str; - ClienteEnderecoDb clienteEnderecoDb = ApplicationMapper.Mapper.Map(clienteEndereco); - ClienteEnderecoDb clienteEnderecoDb1 = clienteEnderecoDb; - string observacao = clienteEnderecoDb.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteEnderecoDb1.Observacao = str; - this.SaveOrUpdate(clienteEnderecoDb); - return ApplicationMapper.Mapper.Map(clienteEnderecoDb); - } - - private List Select(string condition) - { - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT ce.*, c.nome as NomeCliente FROM cliendereco ce INNER JOIN cliente c ON c.idcliente = ce.idcliente WHERE 1=1 ", condition); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - List clienteEnderecos = dataTable.MapEndereco(); - int? nullable1 = new int?(0); - clienteEnderecos.ForEach((ClienteEndereco x) => { - int? ordem = nullable1; - int? nullable = ordem; - nullable1 = (nullable.HasValue ? new int?(nullable.GetValueOrDefault() + 1) : null); - ClienteEndereco clienteEndereco = x; - ordem = x.Ordem; - clienteEndereco.Ordem = (ordem.HasValue ? ordem : nullable1); - }); - return clienteEnderecos; - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs deleted file mode 100644 index f07399f..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs +++ /dev/null @@ -1,3102 +0,0 @@ -using AutoMapper; -using Gestor.Common.Helpers; -using Gestor.Common.Validation; -using Gestor.Infrastructure.Entities.Ferramentas; -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.Common; -using Gestor.Model.Domain.Ferramentas; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Relatorios; -using Gestor.Model.Domain.Relatorios.Classificacao; -using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; -using Gestor.Model.Domain.Relatorios.Dashboard; -using Gestor.Model.Domain.Seguros; -using Gestor.Model.Relatorios; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using NHibernate.Util; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Diagnostics; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; -using System.Text; -using System.Text.RegularExpressions; -using System.Threading.Tasks; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ClienteRepository : GenericRepository, IClienteRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - private const string ComandoEndereco = "SELECT DISTINCT idcliend, cep, cidade, uf as estado, idcliente as id, endereco, numero, comp_end as complemento FROM cliendereco WHERE "; - - private const string ComandoTelefone = "SELECT DISTINCT idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE "; - - private const string ComandoEmail = "SELECT DISTINCT idclimail, email, idcliente as id FROM climail WHERE "; - - private const string ComandoCliente = "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE "; - - private const string ComandoClienteVinculo = "SELECT DISTINCT cl.idcliente as id, cl.idempresa, cl.nome, cl.cgccpf as documento, cl.cei, cl.rne, cl.documentoprincipal, cl.anotacoes, cl.dtnasc as nascimento, cl.idprofissao,cl.VENCHABILI as vencimento, cl.sexo, cl.RendaMensal, cl.pasta, cl.MalaDireta, cl.clidesde, cl.ESTADOCIVI FROM cliente cl inner join controle co on co.idcliente = cl.idcliente inner join documento d on d.idcontrole = co.idcontrole inner join vendedorparcela vp on vp.iddocumento = d.iddocumento inner join vendedorusuario vu on vu.idvendedor = vp.idvendedor WHERE "; - - public ClienteRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void AddCentralSegurado(long id, bool update) - { - try - { - this._unitOfWork.Session.BeginTransaction(); - this._unitOfWork.Session.CreateQuery("update ClienteDb c set c.EstaNaCentralSegurado = :update where c.Id = :updatedid").SetParameter("updatedid", id).SetParameter("update", update).ExecuteUpdate(); - this._unitOfWork.Commit(); - } - catch - { - } - } - - public async Task> BuscaClientes(bool completo, long idempresa = 0L) - { - IEnumerable clientesAtivosInativos; - DateTime? nullable; - object connection; - string str; - bool flag; - DateTime? nullable1; - string str1; - DateTime? nullable2; - string nome; - string str2; - string str3; - decimal num; - DateTime? nullable3; - ClienteRepository.u003cu003ec__DisplayClass34_0 variable; - Func func = null; - Action action2 = null; - List clientesAtivosInativos1 = new List(); - IEnumerable documentos = await this.DocumentosPeriodo(completo); - IEnumerable clienteEnderecos = await this.EnderecoClientes(); - IEnumerable clienteTelefones = await this.TelefonesClientes(); - IEnumerable clienteEmails = await this.EmailsClientes(); - Array values = Enum.GetValues(typeof(EstadoCivil)); - Regex regex = new Regex("[^\\d]"); - IEnumerable estipulanteClientes = await this.EstipulanteCliente(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, true); - SqlCommand sqlCommand1 = sqlCommand; - str = (idempresa > (long)0 ? "AND idempresa = @empresa" : ""); - sqlCommand1.CommandText = string.Concat("SELECT c.idcliente,c.nome,c.maladireta,c.dtnasc,c.sexo,c.estadocivi,c.venchabili,c.idprofissao,c.pasta,c.cgccpf,c.rendamensal, c.nomesocialrg, c.clidesde, IIF((SELECT TOP 1 idvinculo FROM clivinculo cv WHERE cv.idcliente1 = c.idcliente OR cv.idcliente2 = c.idcliente) IS NOT NULL, 'SIM', 'NÃO') Parentesco FROM cliente c WHERE (excluido IS NULL OR excluido = 0) ", str); - sqlCommand.Parameters.Add("@empresa", SqlDbType.BigInt).Value = idempresa; - sqlCommand.CommandTimeout = 1000; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - long item = (long)sqlDataReader["idcliente"]; - string str4 = sqlDataReader["nome"].ToString(); - string str5 = sqlDataReader["nomesocialrg"].ToString(); - flag = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("maladireta")) ? true : (bool)sqlDataReader["maladireta"]); - bool flag1 = flag; - if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("dtnasc"))) - { - nullable = null; - nullable1 = nullable; - } - else - { - nullable1 = new DateTime?((DateTime)sqlDataReader["dtnasc"]); - } - DateTime? nullable4 = nullable1; - str1 = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("sexo")) ? "" : sqlDataReader["sexo"].ToString()); - string str6 = str1; - Sexo sexo = Sexo.Masculino; - if (!string.IsNullOrWhiteSpace(str6) && !Enum.TryParse(str6, out sexo)) - { - str6 = ""; - } - IEnumerable id = - from d in documentos - where d.Controle.Cliente.Id == item - select d; - Gestor.Model.Relatorios.ClienteEndereco clienteEndereco = clienteEnderecos.FirstOrDefault((Gestor.Model.Relatorios.ClienteEndereco e) => e.Cliente.Id == item); - if (clienteEndereco == null) - { - clienteEndereco = new Gestor.Model.Relatorios.ClienteEndereco(); - } - Gestor.Model.Relatorios.ClienteEndereco clienteEndereco1 = clienteEndereco; - IEnumerable id1 = - from f in clienteTelefones - where f.Cliente.Id == item - select f; - IEnumerable clienteEmails1 = - from e in clienteEmails - where e.Cliente.Id == item - select e; - string str7 = ""; - string str8 = ""; - string str9 = "NÃO"; - string str10 = ""; - string description = ""; - int? nullable5 = null; - string str11 = ""; - if (nullable4.HasValue) - { - str10 = nullable4.Value.ToString("dd/MM"); - nullable5 = new int?(this.CalculaIdade(nullable4.Value)); - } - List strs = new List(); - id.ForEach((Gestor.Model.Relatorios.Documento d) => { - str9 = "SIM"; - if (completo) - { - int? ordem = d.Ordem; - if (ordem.GetValueOrDefault() > 0 & ordem.HasValue) - { - return; - } - strs.Add(d.Controle.Ramo.Nome ?? ""); - IList vendedores = d.Vendedores; - if (vendedores == null) - { - return; - } - Action u003cu003e9_10 = action2; - if (u003cu003e9_10 == null) - { - Action action = (Gestor.Model.Relatorios.Vendedor v) => { - if (!str7.Contains(v.Nome)) - { - if (str7.Length > 0) - { - str7 = string.Concat(str7, " | "); - } - str7 = string.Concat(str7, v.Nome); - } - }; - Action action1 = action; - action2 = action; - u003cu003e9_10 = action1; - } - vendedores.ForEach(u003cu003e9_10); - } - }); - List clienteTelefones1 = new List(); - id1.ForEach((Gestor.Model.Relatorios.ClienteTelefone f) => clienteTelefones1.Add(new Gestor.Model.Domain.Seguros.ClienteTelefone() - { - Prefixo = f.Prefixo, - Numero = f.Numero - })); - if (!sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("estadocivi"))) - { - foreach (object value in values) - { - if (value.GetOldValue() != sqlDataReader["estadocivi"].ToString()) - { - continue; - } - description = ((EstadoCivil)value).GetDescription(); - break; - } - } - if (completo && strs.Count > 0) - { - List strs1 = strs; - IEnumerable> groupings = - from g in strs1 - group g by g; - str8 = string.Join(" | ", - from r in groupings - select string.Format("{0}: {1}", r.Key, r.Count())); - } - IEnumerable idCliente = - from x in estipulanteClientes - where x.IdCliente == item - select x; - str11 = string.Join(" | ", - from x in idCliente - select x.NomeEstipulante); - ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); - Gestor.Model.Domain.Seguros.Cliente cliente = new Gestor.Model.Domain.Seguros.Cliente() - { - Id = item, - Nome = str4, - NomeSocialRg = str5, - MalaDireta = new bool?(flag1), - Telefones = new ObservableCollection(clienteTelefones1) - }; - clientesAtivosInativo.EntidadeCliente = cliente; - clientesAtivosInativo.Id = item; - clientesAtivosInativo.Nome = str4; - clientesAtivosInativo.Nascimento = nullable4; - clientesAtivosInativo.Aniversario = str10; - clientesAtivosInativo.Idade = nullable5; - clientesAtivosInativo.Documento = sqlDataReader["cgccpf"].ToString(); - if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("venchabili"))) - { - nullable = null; - nullable2 = nullable; - } - else - { - nullable2 = new DateTime?((DateTime)sqlDataReader["venchabili"]); - } - clientesAtivosInativo.VencimentoCnh = nullable2; - clientesAtivosInativo.Vendedor = str7; - clientesAtivosInativo.Ramo = str8; - List clienteTelefones2 = clienteTelefones1; - clientesAtivosInativo.Telefone = string.Join(" | ", - from f in clienteTelefones2 - select string.Concat(f.Prefixo, " ", f.Numero)); - IEnumerable clienteEmails2 = clienteEmails1; - clientesAtivosInativo.Email = string.Join(" | ", - from e in clienteEmails2 - select e.Email); - clientesAtivosInativo.Ativo = str9; - if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("idprofissao"))) - { - nome = ""; - } - else - { - List profissoes = Auxiliar.Profissoes; - Func func1 = func; - if (func1 == null) - { - Func id2 = (Profissao p) => p.Id == (long)this.rd["idprofissao"]; - Func func2 = id2; - func = id2; - func1 = func2; - } - Profissao profissao = profissoes.FirstOrDefault(func1); - if (profissao != null) - { - nome = profissao.Nome; - } - else - { - nome = null; - } - } - clientesAtivosInativo.Profissao = nome; - clientesAtivosInativo.Cep = clienteEndereco1.Cep; - clientesAtivosInativo.Endereco = clienteEndereco1.Endereco; - clientesAtivosInativo.Numero = clienteEndereco1.Numero; - clientesAtivosInativo.Complemento = clienteEndereco1.Complemento; - clientesAtivosInativo.Cidade = clienteEndereco1.Cidade; - clientesAtivosInativo.Estado = clienteEndereco1.Estado; - clientesAtivosInativo.Bairro = clienteEndereco1.Bairro; - clientesAtivosInativo.PastaCliente = sqlDataReader["pasta"].ToString(); - clientesAtivosInativo.RecebeEmail = (flag1 ? "SIM" : "NÃO"); - if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("cgccpf"))) - { - str2 = "FÍSICA"; - } - else - { - str2 = (regex.Replace(sqlDataReader["cgccpf"].ToString(), string.Empty).Length > 11 ? "JURÍDICA" : "FÍSICA"); - } - clientesAtivosInativo.TipoPessoa = str2; - clientesAtivosInativo.EstadoCivil = description; - str3 = (string.IsNullOrWhiteSpace(str6) ? "" : sexo.GetDescription()); - clientesAtivosInativo.Sexo = str3; - num = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("rendamensal")) ? decimal.Zero : (decimal)sqlDataReader["rendamensal"]); - clientesAtivosInativo.RendaMensal = num; - if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("clidesde"))) - { - nullable = null; - nullable3 = nullable; - } - else - { - nullable3 = new DateTime?((DateTime)sqlDataReader["clidesde"]); - } - clientesAtivosInativo.ClienteDesde = nullable3; - clientesAtivosInativo.Estipulantes = str11; - clientesAtivosInativo.Parentesco = sqlDataReader["Parentesco"].ToString(); - clientesAtivosInativos1.Add(clientesAtivosInativo); - } - } - } - sqlCommand = null; - } - else - { - clientesAtivosInativos = null; - variable = null; - clientesAtivosInativos1 = null; - documentos = null; - clienteEnderecos = null; - clienteTelefones = null; - clienteEmails = null; - values = null; - regex = null; - estipulanteClientes = null; - return clientesAtivosInativos; - } - } - sqlConnection = null; - clientesAtivosInativos = clientesAtivosInativos1; - variable = null; - clientesAtivosInativos1 = null; - documentos = null; - clienteEnderecos = null; - clienteTelefones = null; - clienteEmails = null; - values = null; - regex = null; - estipulanteClientes = null; - return clientesAtivosInativos; - } - - public async Task> BuscaClientesVinculo(bool completo, List vinculo, long idempresa = 0L) - { - IEnumerable clientesAtivosInativos; - DateTime? nullable; - object connection; - string str; - bool flag; - DateTime? nullable1; - string str1; - DateTime? nullable2; - string nome; - string str2; - string str3; - decimal num; - DateTime? nullable3; - ClienteRepository.u003cu003ec__DisplayClass43_0 variable; - Func func = null; - Action action2 = null; - List clientesAtivosInativos1 = new List(); - IEnumerable documentos = await this.DocumentosPeriodo(completo); - IEnumerable clienteEnderecos = await this.EnderecoClientes(); - IEnumerable clienteTelefones = await this.TelefonesClientes(); - IEnumerable clienteEmails = await this.EmailsClientes(); - Array values = Enum.GetValues(typeof(EstadoCivil)); - Regex regex = new Regex("[^\\d]"); - IEnumerable estipulanteClientes = await this.EstipulanteCliente(); - List vendedorUsuarios = vinculo; - List list = ( - from v in vendedorUsuarios - select v.Id).ToList(); - string[] array = ( - from id in list - select id.ToString()).ToArray(); - string str4 = string.Join(",", array); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, true); - SqlCommand sqlCommand1 = sqlCommand; - string[] strArrays = new string[] { "SELECT DISTINCT c.idcliente,c.nome,c.maladireta,c.dtnasc,c.sexo,c.estadocivi,c.venchabili,c.idprofissao,c.pasta,c.cgccpf,c.rendamensal, c.nomesocialrg, c.clidesde, \r\n IIF((SELECT TOP 1 idvinculo FROM clivinculo cv WHERE cv.idcliente1 = c.idcliente OR cv.idcliente2 = c.idcliente) IS NOT NULL, 'SIM', 'NÃO') Parentesco FROM cliente c \r\n INNER JOIN controle co on co.idcliente = c.idcliente \r\n INNER JOIN documento d on d.idcontrole = co.idcontrole \r\n INNER JOIN vendedorparcela vp on vp.IdDocumento = d.IdDocumento \r\n INNER JOIN vendedorusuario vu on vu.idvendedor = vp.idvendedor \r\n WHERE (c.excluido IS NULL OR c.excluido = 0) ", null, null, null, null }; - str = (idempresa > (long)0 ? " AND c.idempresa = @empresa" : ""); - strArrays[1] = str; - strArrays[2] = " \r\n AND vu.idvendedorusuario in ("; - strArrays[3] = str4; - strArrays[4] = ")"; - sqlCommand1.CommandText = string.Concat(strArrays); - sqlCommand.Parameters.Add("@empresa", SqlDbType.BigInt).Value = idempresa; - sqlCommand.CommandTimeout = 1000; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - long item = (long)sqlDataReader["idcliente"]; - string str5 = sqlDataReader["nome"].ToString(); - string str6 = sqlDataReader["nomesocialrg"].ToString(); - flag = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("maladireta")) ? true : (bool)sqlDataReader["maladireta"]); - bool flag1 = flag; - if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("dtnasc"))) - { - nullable = null; - nullable1 = nullable; - } - else - { - nullable1 = new DateTime?((DateTime)sqlDataReader["dtnasc"]); - } - DateTime? nullable4 = nullable1; - str1 = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("sexo")) ? "" : sqlDataReader["sexo"].ToString()); - string str7 = str1; - Sexo sexo = Sexo.Masculino; - if (!string.IsNullOrWhiteSpace(str7) && !Enum.TryParse(str7, out sexo)) - { - str7 = ""; - } - IEnumerable documentos1 = - from d in documentos - where d.Controle.Cliente.Id == item - select d; - Gestor.Model.Relatorios.ClienteEndereco clienteEndereco = clienteEnderecos.FirstOrDefault((Gestor.Model.Relatorios.ClienteEndereco e) => e.Cliente.Id == item); - if (clienteEndereco == null) - { - clienteEndereco = new Gestor.Model.Relatorios.ClienteEndereco(); - } - Gestor.Model.Relatorios.ClienteEndereco clienteEndereco1 = clienteEndereco; - IEnumerable clienteTelefones1 = - from f in clienteTelefones - where f.Cliente.Id == item - select f; - IEnumerable clienteEmails1 = - from e in clienteEmails - where e.Cliente.Id == item - select e; - string str8 = ""; - string str9 = ""; - string str10 = "NÃO"; - string str11 = ""; - string description = ""; - int? nullable5 = null; - string str12 = ""; - if (nullable4.HasValue) - { - str11 = nullable4.Value.ToString("dd/MM"); - nullable5 = new int?(this.CalculaIdade(nullable4.Value)); - } - List strs = new List(); - documentos1.ForEach((Gestor.Model.Relatorios.Documento d) => { - str10 = "SIM"; - if (completo) - { - int? ordem = d.Ordem; - if (ordem.GetValueOrDefault() > 0 & ordem.HasValue) - { - return; - } - strs.Add(d.Controle.Ramo.Nome ?? ""); - IList vendedores = d.Vendedores; - if (vendedores == null) - { - return; - } - Action u003cu003e9_12 = action2; - if (u003cu003e9_12 == null) - { - Action action = (Gestor.Model.Relatorios.Vendedor v) => { - if (!str8.Contains(v.Nome)) - { - if (str8.Length > 0) - { - str8 = string.Concat(str8, " | "); - } - str8 = string.Concat(str8, v.Nome); - } - }; - Action action1 = action; - action2 = action; - u003cu003e9_12 = action1; - } - vendedores.ForEach(u003cu003e9_12); - } - }); - List clienteTelefones2 = new List(); - clienteTelefones1.ForEach((Gestor.Model.Relatorios.ClienteTelefone f) => clienteTelefones2.Add(new Gestor.Model.Domain.Seguros.ClienteTelefone() - { - Prefixo = f.Prefixo, - Numero = f.Numero - })); - if (!sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("estadocivi"))) - { - foreach (object value in values) - { - if (value.GetOldValue() != sqlDataReader["estadocivi"].ToString()) - { - continue; - } - description = ((EstadoCivil)value).GetDescription(); - break; - } - } - if (completo && strs.Count > 0) - { - List strs1 = strs; - IEnumerable> groupings = - from g in strs1 - group g by g; - str9 = string.Join(" | ", - from r in groupings - select string.Format("{0}: {1}", r.Key, r.Count())); - } - IEnumerable idCliente = - from x in estipulanteClientes - where x.IdCliente == item - select x; - str12 = string.Join(" | ", - from x in idCliente - select x.NomeEstipulante); - ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); - Gestor.Model.Domain.Seguros.Cliente cliente = new Gestor.Model.Domain.Seguros.Cliente() - { - Id = item, - Nome = str5, - NomeSocialRg = str6, - MalaDireta = new bool?(flag1), - Telefones = new ObservableCollection(clienteTelefones2) - }; - clientesAtivosInativo.EntidadeCliente = cliente; - clientesAtivosInativo.Id = item; - clientesAtivosInativo.Nome = str5; - clientesAtivosInativo.Nascimento = nullable4; - clientesAtivosInativo.Aniversario = str11; - clientesAtivosInativo.Idade = nullable5; - clientesAtivosInativo.Documento = sqlDataReader["cgccpf"].ToString(); - if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("venchabili"))) - { - nullable = null; - nullable2 = nullable; - } - else - { - nullable2 = new DateTime?((DateTime)sqlDataReader["venchabili"]); - } - clientesAtivosInativo.VencimentoCnh = nullable2; - clientesAtivosInativo.Vendedor = str8; - clientesAtivosInativo.Ramo = str9; - List clienteTelefones3 = clienteTelefones2; - clientesAtivosInativo.Telefone = string.Join(" | ", - from f in clienteTelefones3 - select string.Concat(f.Prefixo, " ", f.Numero)); - IEnumerable clienteEmails2 = clienteEmails1; - clientesAtivosInativo.Email = string.Join(" | ", - from e in clienteEmails2 - select e.Email); - clientesAtivosInativo.Ativo = str10; - if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("idprofissao"))) - { - nome = ""; - } - else - { - List profissoes = Auxiliar.Profissoes; - Func func1 = func; - if (func1 == null) - { - Func func2 = (Profissao p) => p.Id == (long)this.rd["idprofissao"]; - Func func3 = func2; - func = func2; - func1 = func3; - } - Profissao profissao = profissoes.FirstOrDefault(func1); - if (profissao != null) - { - nome = profissao.Nome; - } - else - { - nome = null; - } - } - clientesAtivosInativo.Profissao = nome; - clientesAtivosInativo.Cep = clienteEndereco1.Cep; - clientesAtivosInativo.Endereco = clienteEndereco1.Endereco; - clientesAtivosInativo.Numero = clienteEndereco1.Numero; - clientesAtivosInativo.Complemento = clienteEndereco1.Complemento; - clientesAtivosInativo.Cidade = clienteEndereco1.Cidade; - clientesAtivosInativo.Estado = clienteEndereco1.Estado; - clientesAtivosInativo.Bairro = clienteEndereco1.Bairro; - clientesAtivosInativo.PastaCliente = sqlDataReader["pasta"].ToString(); - clientesAtivosInativo.RecebeEmail = (flag1 ? "SIM" : "NÃO"); - if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("cgccpf"))) - { - str2 = "FÍSICA"; - } - else - { - str2 = (regex.Replace(sqlDataReader["cgccpf"].ToString(), string.Empty).Length > 11 ? "JURÍDICA" : "FÍSICA"); - } - clientesAtivosInativo.TipoPessoa = str2; - clientesAtivosInativo.EstadoCivil = description; - str3 = (string.IsNullOrWhiteSpace(str7) ? "" : sexo.GetDescription()); - clientesAtivosInativo.Sexo = str3; - num = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("rendamensal")) ? decimal.Zero : (decimal)sqlDataReader["rendamensal"]); - clientesAtivosInativo.RendaMensal = num; - if (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("clidesde"))) - { - nullable = null; - nullable3 = nullable; - } - else - { - nullable3 = new DateTime?((DateTime)sqlDataReader["clidesde"]); - } - clientesAtivosInativo.ClienteDesde = nullable3; - clientesAtivosInativo.Estipulantes = str12; - clientesAtivosInativo.Parentesco = sqlDataReader["Parentesco"].ToString(); - clientesAtivosInativos1.Add(clientesAtivosInativo); - } - } - } - sqlCommand = null; - } - else - { - clientesAtivosInativos = null; - variable = null; - clientesAtivosInativos1 = null; - documentos = null; - clienteEnderecos = null; - clienteTelefones = null; - clienteEmails = null; - values = null; - regex = null; - estipulanteClientes = null; - return clientesAtivosInativos; - } - } - sqlConnection = null; - clientesAtivosInativos = clientesAtivosInativos1; - variable = null; - clientesAtivosInativos1 = null; - documentos = null; - clienteEnderecos = null; - clienteTelefones = null; - clienteEmails = null; - values = null; - regex = null; - estipulanteClientes = null; - return clientesAtivosInativos; - } - - public DateTime? BuscaNascimeto(long id) - { - DateTime? nullable; - DateTime dateTime; - object connection; - string str; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "idcliente", - Valores = id.CriarValor() - } - }; - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - object obj = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT c.dtnasc FROM cliente c WHERE", "").AsEnumerable().ToList().FirstOrDefault().Field("dtnasc"); - if (obj != null) - { - str = obj.ToString(); - } - else - { - str = null; - } - if (!DateTime.TryParse(str, out dateTime)) - { - return null; - } - else - { - nullable = new DateTime?(dateTime); - } - } - } - else - { - nullable = null; - nullable = nullable; - } - } - return nullable; - } - - public async Task> BuscaProspeccoes(Filtros filtro, long idEmpresa) - { - int? nullable; - int num; - object connection; - int? nullable1; - List prospectars = new List(); - filtro.IdEmpresa = idEmpresa; - num = (filtro.FiltrarDocumento == "AMBOS" ? -1 : (int)(!(filtro.FiltrarDocumento == "CNPJ"))); - int num1 = num; - List condicaos = new List(); - Condicao condicao = new Condicao() - { - Campo = "d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos.Add(condicao); - Condicao condicao1 = new Condicao() - { - Campo = "d.excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos.Add(condicao1); - Condicao condicao2 = new Condicao() - { - Campo = "d.situacao" - }; - List objs = new List() - { - 1, - 2, - 4 - }; - condicao2.Valores = objs; - condicaos.Add(condicao2); - List condicaos1 = condicaos; - if (filtro.IdEmpresa > (long)0) - { - Condicao condicao3 = new Condicao() - { - Campo = "cl.idempresa", - Valores = filtro.IdEmpresa.CriarValor() - }; - condicaos1.Add(condicao3); - } - string str = ""; - if (filtro.Vendedores != null && filtro.Vendedores.Count > 0) - { - str = "INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento"; - Condicao condicao4 = new Condicao() - { - Campo = "vp.idvendedor", - Valores = filtro.Vendedores.CriarValor() - }; - condicaos1.Add(condicao4); - } - string str1 = string.Concat("SELECT cl.idcliente,cl.nome,cl.cgccpf,c.idramo FROM cliente cl INNER JOIN controle c ON c.idcliente = cl.idcliente INNER JOIN documento d ON d.idcontrole = c.idcontrole ", str, " WHERE"); - string referencia = filtro.Referencia; - if (referencia == "VIGÊNCIA INICIAL") - { - Condicao condicao5 = new Condicao() - { - Campo = "CAST(d.vigencia1 AS DATE)", - Valores = filtro.Inicio.CriarValor(), - Operador = Operador.MaiorEIgual - }; - condicaos1.Add(condicao5); - Condicao condicao6 = new Condicao() - { - Campo = "CAST(d.vigencia1 AS DATE)", - Valores = filtro.Fim.CriarValor(), - Operador = Operador.MenorEIgual - }; - condicaos1.Add(condicao6); - } - else if (referencia == "VIGÊNCIA FINAL") - { - Condicao condicao7 = new Condicao() - { - Campo = "d.vigencia2", - Valores = null, - Operador = Operador.Diferente - }; - condicaos1.Add(condicao7); - Condicao condicao8 = new Condicao() - { - Campo = "CAST(d.vigencia2 AS DATE)", - Valores = filtro.Inicio.CriarValor(), - Operador = Operador.MaiorEIgual - }; - condicaos1.Add(condicao8); - Condicao condicao9 = new Condicao() - { - Campo = "CAST(d.vigencia2 AS DATE)", - Valores = filtro.Fim.CriarValor(), - Operador = Operador.MenorEIgual - }; - condicaos1.Add(condicao9); - } - else - { - Condicao condicao10 = new Condicao() - { - Campo = "CAST(p.vencto AS DATE)", - Valores = filtro.Inicio.CriarValor(), - Operador = Operador.MaiorEIgual - }; - condicaos1.Add(condicao10); - Condicao condicao11 = new Condicao() - { - Campo = "CAST(p.vencto AS DATE)", - Valores = filtro.Fim.CriarValor(), - Operador = Operador.MenorEIgual - }; - condicaos1.Add(condicao11); - str1 = string.Concat("SELECT cl.idcliente,cl.nome,cl.cgccpf,c.idramo FROM cliente cl INNER JOIN controle c ON c.idcliente = cl.idcliente INNER JOIN documento d ON d.idcontrole = c.idcontrole INNER JOIN parcela p ON p.iddocumento = d.iddocumento ", str, " WHERE CAST(d.n_parc AS INTEGER) = CAST(p.parcela AS INTEGER) AND"); - } - SqlQueryCondition sqlQueryCondition = condicaos1.CreateParameters(0); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - sqlCommand.CommandText = string.Concat(str1, " ", sqlQueryCondition.Condicao); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - List nums = new List(); - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - string str2 = sqlDataReader["cgccpf"].ToString(); - long item = (long)sqlDataReader["idcliente"]; - long item1 = (long)sqlDataReader["idramo"]; - if (filtro.Ramos.Any((long r) => r == item1)) - { - nums.Add(item); - Prospectar prospectar = prospectars.FirstOrDefault((Prospectar p) => p.Id == item); - if (prospectar != null) - { - prospectars.Remove(prospectar); - } - } - else if (!nums.Any((long i) => i == item) && !prospectars.Any((Prospectar c) => c.Id == item)) - { - if (num1 > -1) - { - string str3 = str2; - if (str3 != null) - { - string str4 = str3.Clear(); - if (str4 != null) - { - nullable1 = new int?(str4.Length); - } - else - { - nullable = null; - nullable1 = nullable; - } - } - else - { - nullable = null; - nullable1 = nullable; - } - int? nullable2 = nullable1; - if (num1 == 0) - { - nullable = nullable2; - if (nullable.GetValueOrDefault() < 12 & nullable.HasValue) - { - continue; - } - } - if (num1 == 1) - { - nullable = nullable2; - if (nullable.GetValueOrDefault() > 11 & nullable.HasValue) - { - continue; - } - } - } - if (!await this.ExisteClienteRamo(item, filtro.Ramos.FirstOrDefault())) - { - string str5 = sqlDataReader["nome"].ToString(); - List clienteTelefones = await this.BuscaTelefonesCliente(item); - List prospectars1 = prospectars; - Prospectar prospectar1 = new Prospectar(); - Gestor.Model.Domain.Seguros.Cliente cliente = new Gestor.Model.Domain.Seguros.Cliente() - { - Id = item, - Nome = str5, - Telefones = new ObservableCollection(clienteTelefones) - }; - prospectar1.EntidadeCliente = cliente; - prospectar1.Id = item; - prospectar1.Nome = str5; - prospectar1.Documento = str2; - List clienteTelefones1 = clienteTelefones; - prospectar1.Telefone = string.Join(" | ", - from t in clienteTelefones1 - select string.Concat(t.Prefixo, " ", t.Numero)); - prospectars1.Add(prospectar1); - str2 = null; - str5 = null; - } - } - } - } - sqlDataReader = null; - nums = null; - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List prospectars2 = prospectars; - List list = ( - from p in prospectars2 - orderby p.Nome - select p).ToList(); - prospectars = null; - return list; - } - - public List BuscarAniversariantes(Filtros filtro, long idempresa = 0L) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "idempresa", - Valores = idempresa.CriarValor() - } - }; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "dtnasc", - Valores = null, - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = "excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "falecido", - Valores = null, - Grupo = 2, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "falecido", - Valores = "1".CriarValor(), - Operador = Operador.Diferente, - Grupo = 2, - Operacao = Operacao.Or - } - }; - if (idempresa > (long)0) - { - condicaos1.AddRange(condicaos); - } - string str = (filtro.Inicio.Month != 12 || filtro.Fim.Month != 1 ? string.Format("{0} FORMAT(dtnasc,'MMdd') BETWEEN {1:Mdd} AND {2:Mdd} AND", "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", filtro.Inicio, filtro.Fim) : string.Format("{0} 1 = (FLOOR(DATEDIFF(dd,DTNASC,'{1:yyyy-MM-dd}') / 365.25)) - (FLOOR(DATEDIFF(dd,DTNASC,'{2:yyyy-MM-dd}') / 365.25)) AND", "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", filtro.Fim, filtro.Inicio)); - return this.Select(condicaos1.CreateParameters(0), str, true); - } - - public List BuscarAniversariantesVinculo(Filtros filtro, List vinculo, long idempresa = 0L) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "cl.idempresa", - Valores = idempresa.CriarValor() - } - }; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "cl.dtnasc", - Valores = null, - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = "cl.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "cl.excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "cl.falecido", - Valores = null, - Grupo = 2, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "cl.falecido", - Valores = "1".CriarValor(), - Operador = Operador.Diferente, - Grupo = 2, - Operacao = Operacao.Or - } - }; - if (idempresa > (long)0) - { - condicaos1.AddRange(condicaos); - } - string[] array = ( - from id in ( - from v in vinculo - select v.Id).ToList() - select id.ToString()).ToArray(); - string str = string.Join(",", array); - string str1 = (filtro.Inicio.Month != 12 || filtro.Fim.Month != 1 ? string.Format("{0} vu.idvendedorusuario in ({1}) AND FORMAT(cl.dtnasc,'MMdd') BETWEEN {2:Mdd} AND {3:Mdd} AND", new object[] { "SELECT DISTINCT cl.idcliente as id, cl.idempresa, cl.nome, cl.cgccpf as documento, cl.cei, cl.rne, cl.documentoprincipal, cl.anotacoes, cl.dtnasc as nascimento, cl.idprofissao,cl.VENCHABILI as vencimento, cl.sexo, cl.RendaMensal, cl.pasta, cl.MalaDireta, cl.clidesde, cl.ESTADOCIVI FROM cliente cl inner join controle co on co.idcliente = cl.idcliente inner join documento d on d.idcontrole = co.idcontrole inner join vendedorparcela vp on vp.iddocumento = d.iddocumento inner join vendedorusuario vu on vu.idvendedor = vp.idvendedor WHERE ", str, filtro.Inicio, filtro.Fim }) : string.Format("{0} 1 = (FLOOR(DATEDIFF(dd,cl.DTNASC,'{1:yyyy-MM-dd}') / 365.25)) - (FLOOR(DATEDIFF(dd,cl.DTNASC,'{2:yyyy-MM-dd}') / 365.25)) AND", "SELECT DISTINCT cl.idcliente as id, cl.idempresa, cl.nome, cl.cgccpf as documento, cl.cei, cl.rne, cl.documentoprincipal, cl.anotacoes, cl.dtnasc as nascimento, cl.idprofissao,cl.VENCHABILI as vencimento, cl.sexo, cl.RendaMensal, cl.pasta, cl.MalaDireta, cl.clidesde, cl.ESTADOCIVI FROM cliente cl inner join controle co on co.idcliente = cl.idcliente inner join documento d on d.idcontrole = co.idcontrole inner join vendedorparcela vp on vp.iddocumento = d.iddocumento inner join vendedorusuario vu on vu.idvendedor = vp.idvendedor WHERE ", filtro.Fim, filtro.Inicio)); - return this.Select(condicaos1.CreateParameters(0), str1, true); - } - - public async Task> BuscarClassificacoes(long idEmpresa) - { - List classificacaos; - Func, bool> func; - object connection; - string str; - Func, bool> func1 = null; - Func, bool> func2 = null; - Func, bool> func3 = null; - List classificacaos1 = new List(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "WITH classificatorio ( CodigoCliente, NomeCliente, AtivoInativo, SomaPremioLiq, MediaComissao, Resultado ) AS (\r\nSELECT\r\n\tcl.idcliente AS CodigoCliente,\r\n\tcl.Nome AS NomeCliente,\r\n\t IIF(MAX(d.vigencia2) >= GETDATE(), 1, 0) AS AtivoInativo,\r\n\tSUM (d.pr_liq) AS SomaPremioLiq,\r\n\tSUM (d.com01) / (COUNT(d.com01)) AS MediaComissao,\r\n\tSUM ((d.pr_liq + (IIF(d.adinacomis = 1, d.pr_adic, 0))) * (d.com01 * 0.01)) AS Resultado\r\nFROM\r\n\tcliente cl\r\n\tLEFT JOIN controle c ON c.idcliente = cl.idcliente\r\n\tLEFT JOIN documento d ON d.idcontrole = c.idcontrole AND d.excluido != 1 \tAND d.SITUACAO not in (3,7) WHERE CL.EXCLUIDO != 1 \r\nGROUP BY\r\n\tcl.IdCliente,\r\n\tcl.nome \r\n\t) SELECT CodigoCliente,NomeCliente,\r\n\tAtivoInativo,\r\nCASE\r\n\tWHEN SomaPremioLiq >= iif(quali.liquido3 is null, 500, quali.liquido3) THEN\r\n\t3\r\n\tWHEN SomaPremioLiq >= iif(quali.liquido2 is null, 500, quali.liquido2) THEN\r\n\t2 \r\n\tWHEN SomaPremioLiq >= iif(quali.liquido1 is null, 500, quali.liquido1) THEN\r\n\t1 \r\n\tELSE 0 \r\nEND QualiPremioLiquido,\r\nCASE\r\n\tWHEN MediaComissao >= iif(quali.comissao3 is null, 20, quali.comissao3) THEN\r\n\t3\r\n\tWHEN MediaComissao >= iif(quali.comissao2 is null, 15, quali.comissao2) THEN\r\n\t2 \r\n\tWHEN MediaComissao >= iif(quali.comissao1 is null, 10, quali.comissao1) THEN\r\n\t1 \r\n\tELSE 0 \r\nEND QualiComissao,\r\nCASE\r\n\tWHEN Resultado >= iif(quali.resultado3 is null, 300, quali.resultado3) THEN\r\n\t3\r\n\tWHEN Resultado >= iif(quali.resultado2 is null, 200, quali.resultado2) THEN\r\n\t2 \r\n\tWHEN Resultado >= iif(quali.resultado1 is null, 100, quali.resultado1) THEN\r\n\t1 \r\n\tELSE 0 \r\nEND QualiResultado\r\nFROM\r\nclassificatorio OUTER APPLY (SELECT top 1 * FROM qualificacao) AS quali;"; - sqlCommand.CommandTimeout = 1000; - List> tuples = new List>() - { - new Tuple("0", "SEM CLASSIFICAÇÃO"), - new Tuple("1", "BRONZE"), - new Tuple("2", "PRATA"), - new Tuple("3", "OURO") - }; - List> tuples1 = tuples; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List> tuples2 = tuples1; - Func, bool> func4 = func1; - if (func4 == null) - { - Func, bool> func5 = (Tuple x) => x.Item1.Equals(sqlDataReader["QualiPremioLiquido"].ToString() ?? "0"); - func = func5; - func1 = func5; - func4 = func; - } - Tuple tuple = tuples2.FirstOrDefault>(func4); - List> tuples3 = tuples1; - Func, bool> func6 = func2; - if (func6 == null) - { - Func, bool> func7 = (Tuple x) => x.Item1.Equals(sqlDataReader["QualiResultado"].ToString() ?? "0"); - func = func7; - func2 = func7; - func6 = func; - } - Tuple tuple1 = tuples3.FirstOrDefault>(func6); - List> tuples4 = tuples1; - Func, bool> func8 = func3; - if (func8 == null) - { - Func, bool> func9 = (Tuple x) => x.Item1.Equals(sqlDataReader["QualiComissao"].ToString() ?? "0"); - func = func9; - func3 = func9; - func8 = func; - } - Tuple tuple2 = tuples4.FirstOrDefault>(func8); - string item2 = tuples1.FirstOrDefault>((Tuple x) => x.Item1.Equals(((int)Math.Round((double.Parse(tuple.Item1) + double.Parse(tuple1.Item1) + double.Parse(tuple2.Item1)) / 3)).ToString())).Item2; - str = (sqlDataReader["AtivoInativo"].ToString().Equals("1") ? "SIM" : "NÃO"); - string str1 = str; - List classificacaos2 = classificacaos1; - Classificacao classificacao = new Classificacao(); - Gestor.Model.Domain.Seguros.Cliente cliente = new Gestor.Model.Domain.Seguros.Cliente() - { - Id = long.Parse(sqlDataReader["codigocliente"].ToString()) - }; - classificacao.EntidadeCliente = cliente; - classificacao.Nome = sqlDataReader["NomeCliente"].ToString(); - classificacao.Premioliquido = tuple.Item2; - classificacao.Resultado = tuple1.Item2; - classificacao.Comissao = tuple2.Item2; - classificacao.Geral = item2; - classificacao.Ativo = str1; - classificacaos2.Add(classificacao); - } - } - tuples1 = null; - } - sqlCommand = null; - } - else - { - classificacaos = null; - classificacaos1 = null; - return classificacaos; - } - } - sqlConnection = null; - classificacaos = classificacaos1; - classificacaos1 = null; - return classificacaos; - } - - public string BuscarLogAntigo(long id, string conn) - { - object connection; - string str = ""; - List condicaos = new List() - { - new Condicao() - { - Campo = "id", - Valores = id.CriarValor() - }, - new Condicao() - { - Campo = "idname", - Valores = "idcliente".CriarValor() - } - }; - this._unitOfWork.CriarAuxiliar(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - string str1 = "oldbacklog"; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog"; - SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); - sqlDataReader.Read(); - string str2 = sqlDataReader["bdname"].ToString(); - str1 = sqlDataReader["tabela"].ToString(); - sqlDataReader.Close(); - if (sqlConnection.Database != str2) - { - conn = conn.Replace(sqlConnection.Database, str2); - } - } - } - DataTable dataTable = new DataTable(); - using (SqlConnection sqlConnection1 = new SqlConnection(conn)) - { - sqlConnection1.Open(); - using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand()) - { - sqlCommand1.CommandTimeout = 15000; - dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), ""); - } - } - if (dataTable == null || dataTable.Rows.Count == 0) - { - return ""; - } - if (dataTable != null) - { - dataTable.AsEnumerable().OrderBy((DataRow x) => x.Field("idbacklog")).ToList().ForEach((DataRow x) => { - str = string.Concat(new string[] { str, "
(", x.Field("data").ToString(), ") ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("idusuario")).Nome, "
" }); - str = string.Concat(str, "", x.Field("historico").ToString().Replace(Environment.NewLine, "
"), ""); - }); - } - return str; - } - - public List BuscarOrigem(long id) - { - List list = ( - from x in this._unitOfWork.Query() - where x.Cliente.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List BuscarVencimentoCnh(Filtros filtro, long idempresa = 0L) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "idempresa", - Valores = idempresa.CriarValor() - } - }; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "venchabili", - Valores = null, - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = "venchabili", - Valores = filtro.Inicio.CriarValor(), - Operador = Operador.MaiorEIgual - }, - new Condicao() - { - Campo = "venchabili", - Valores = filtro.Fim.CriarValor(), - Operador = Operador.MenorEIgual - }, - new Condicao() - { - Campo = "excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }; - if (idempresa > (long)0) - { - condicaos1.AddRange(condicaos); - } - return this.Select(condicaos1.CreateParameters(0), "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", true); - } - - private async Task> BuscaTelefonesCliente(long idCliente) - { - object connection; - List clienteTelefones = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - sqlCommand.CommandText = "SELECT ddd,fone FROM clitelefone WHERE idcliente = @cliente"; - sqlCommand.Parameters.Add("@cliente", SqlDbType.BigInt).Value = idCliente; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List clienteTelefones1 = clienteTelefones; - Gestor.Model.Domain.Seguros.ClienteTelefone clienteTelefone = new Gestor.Model.Domain.Seguros.ClienteTelefone() - { - Prefixo = sqlDataReader["ddd"].ToString(), - Numero = sqlDataReader["fone"].ToString() - }; - clienteTelefones1.Add(clienteTelefone); - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List clienteTelefones2 = clienteTelefones; - clienteTelefones = null; - return clienteTelefones2; - } - - private int CalculaIdade(DateTime nascimento) - { - int year = DateTime.Now.Year - nascimento.Year; - if (DateTime.Now.DayOfYear < nascimento.DayOfYear) - { - year--; - } - return year; - } - - private List CriarFiltro(string filter) - { - return new List() - { - new Condicao() - { - Campo = "UPPER(NOME) COLLATE Latin1_General_CI_AI", - Valores = filter.CriarValor(), - Operacao = Operacao.Or, - Operador = Operador.Like, - Grupo = 2 - }, - new Condicao() - { - Campo = "UPPER(CGCCPF)", - Valores = filter.CriarValor(), - Operacao = Operacao.Or, - Operador = Operador.Like, - Grupo = 2 - }, - new Condicao() - { - Campo = "UPPER(CEI)", - Valores = filter.CriarValor(), - Operacao = Operacao.Or, - Operador = Operador.Like, - Grupo = 2 - }, - new Condicao() - { - Campo = "UPPER(RNE)", - Valores = filter.CriarValor(), - Operacao = Operacao.Or, - Operador = Operador.Like, - Grupo = 2 - }, - new Condicao() - { - Campo = "UPPER(CAEPF)", - Valores = filter.CriarValor(), - Operacao = Operacao.Or, - Operador = Operador.Like, - Grupo = 2 - }, - new Condicao() - { - Campo = "UPPER(nomesocialRg) COLLATE Latin1_General_CI_AI", - Valores = filter.CriarValor(), - Operacao = Operacao.Or, - Operador = Operador.Like, - Grupo = 2 - } - }; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public void DeleteOrigem(long id) - { - OrigemClienteDb origemClienteDb = this._unitOfWork.Repository().FindEntityById(id); - if (origemClienteDb == null) - { - return; - } - this._unitOfWork.Repository().Delete(origemClienteDb); - } - - private async Task> DocumentosPeriodo(bool completo) - { - IEnumerable documentos; - object connection; - Func func = null; - List documentos1 = new List(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - if (!completo) - { - sqlCommand.CommandText = "SELECT DISTINCT d.iddocumento,d.idcontrole,c.idcliente FROM documento d INNER JOIN controle c ON c.idcontrole = d.idcontrole WHERE c.idcliente IS NOT NULL AND (d.excluido IS NULL OR d.excluido = 0) AND (d.vigencia2 IS NULL OR d.vigencia2 > @vigenciafinal) AND d.situacao IN (1,2,4) ORDER BY d.iddocumento"; - } - else - { - sqlCommand.CommandText = "SELECT DISTINCT d.iddocumento,d.idcontrole,c.idcliente,c.idramo,r.nome nomeramo,vp.idvendedor,v.nome nomevendedor, d.ordem FROM documento d INNER JOIN controle c ON c.idcontrole = d.idcontrole INNER JOIN ramo r ON r.idramo = c.idramo LEFT JOIN vendedorparcela vp ON d.iddocumento = vp.iddocumento LEFT JOIN vendedor v ON vp.idvendedor = v.idvendedor WHERE c.idcliente IS NOT NULL AND (d.excluido IS NULL OR d.excluido = 0) AND (d.vigencia2 IS NULL OR d.vigencia2 > @vigenciafinal) AND d.situacao IN (1,2,4) ORDER BY d.iddocumento"; - } - SqlParameter sqlParameter = sqlCommand.Parameters.Add("@vigenciafinal", SqlDbType.DateTime); - sqlParameter.Value = DateTime.Now.AddDays(-5); - sqlCommand.CommandTimeout = 1000; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - long id = (long)0; - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - Gestor.Model.Relatorios.Documento documento = new Gestor.Model.Relatorios.Documento(); - bool flag = true; - if (id == (long)sqlDataReader["iddocumento"]) - { - documento = documentos1.Last(); - flag = false; - } - if (!flag) - { - bool flag1 = completo; - if (flag1) - { - flag1 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idvendedor")); - } - if (flag1) - { - IList vendedores = documento.Vendedores; - Func func1 = func; - if (func1 == null) - { - Func id1 = (Gestor.Model.Relatorios.Vendedor v) => v.Id == (long)sqlDataReader["idvendedor"]; - Func func2 = id1; - func = id1; - func1 = func2; - } - if (vendedores.Where(func1).Count() == 0) - { - IList vendedors = documento.Vendedores; - Gestor.Model.Relatorios.Vendedor vendedor = new Gestor.Model.Relatorios.Vendedor() - { - Id = (long)sqlDataReader["idvendedor"], - Nome = sqlDataReader["nomevendedor"].ToString() - }; - vendedors.Add(vendedor); - } - } - } - else - { - documento.Id = (long)sqlDataReader["iddocumento"]; - Gestor.Model.Relatorios.Documento documento1 = documento; - Gestor.Model.Relatorios.Controle controle = new Gestor.Model.Relatorios.Controle() - { - Id = (long)sqlDataReader["idcontrole"] - }; - Gestor.Model.Relatorios.Cliente cliente = new Gestor.Model.Relatorios.Cliente() - { - Id = (long)sqlDataReader["idcliente"] - }; - controle.Cliente = cliente; - documento1.Controle = controle; - if (completo) - { - documento.Ordem = (int?)sqlDataReader["ordem"]; - Gestor.Model.Relatorios.Controle controle1 = documento.Controle; - Gestor.Model.Relatorios.Ramo ramo = new Gestor.Model.Relatorios.Ramo() - { - Id = (long)sqlDataReader["idramo"], - Nome = sqlDataReader["nomeramo"].ToString() - }; - controle1.Ramo = ramo; - if (!await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idvendedor"))) - { - Gestor.Model.Relatorios.Documento documento2 = documento; - List vendedors1 = new List(); - Gestor.Model.Relatorios.Vendedor vendedor1 = new Gestor.Model.Relatorios.Vendedor() - { - Id = (long)sqlDataReader["idvendedor"], - Nome = sqlDataReader["nomevendedor"].ToString() - }; - vendedors1.Add(vendedor1); - documento2.Vendedores = vendedors1; - } - } - } - id = documento.Id; - if (flag) - { - documentos1.Add(documento); - } - documento = null; - } - } - } - sqlCommand = null; - } - else - { - documentos = null; - documentos1 = null; - return documentos; - } - } - sqlConnection = null; - documentos = documentos1; - documentos1 = null; - return documentos; - } - - private async Task> EmailsClientes() - { - IEnumerable clienteEmails; - object connection; - List clienteEmails1 = new List(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT idcliente,email FROM climail ORDER BY idcliente,ordem"; - sqlCommand.CommandTimeout = 1000; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List clienteEmails2 = clienteEmails1; - Gestor.Model.Relatorios.ClienteEmail clienteEmail = new Gestor.Model.Relatorios.ClienteEmail(); - Gestor.Model.Relatorios.Cliente cliente = new Gestor.Model.Relatorios.Cliente() - { - Id = (long)sqlDataReader["idcliente"] - }; - clienteEmail.Cliente = cliente; - clienteEmail.Email = sqlDataReader["email"].ToString(); - clienteEmails2.Add(clienteEmail); - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - else - { - clienteEmails = null; - clienteEmails1 = null; - return clienteEmails; - } - } - sqlConnection = null; - clienteEmails = clienteEmails1; - clienteEmails1 = null; - return clienteEmails; - } - - private async Task> EnderecoClientes() - { - IEnumerable clienteEnderecos; - object connection; - int num; - List clienteEnderecos1 = new List(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT DISTINCT idcliend, idcliente,ordem,endereco,numero,comp_end,cidade,uf,cep,bairro FROM cliendereco ORDER BY idcliente, ordem, idcliend"; - sqlCommand.CommandTimeout = 1000; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List clienteEnderecos2 = clienteEnderecos1; - Gestor.Model.Relatorios.ClienteEndereco clienteEndereco = new Gestor.Model.Relatorios.ClienteEndereco() - { - IdCliEnd = (long)sqlDataReader["idcliend"] - }; - Gestor.Model.Relatorios.Cliente cliente = new Gestor.Model.Relatorios.Cliente() - { - Id = (long)sqlDataReader["idcliente"] - }; - clienteEndereco.Cliente = cliente; - clienteEndereco.Endereco = sqlDataReader["endereco"].ToString(); - clienteEndereco.Numero = sqlDataReader["numero"].ToString(); - clienteEndereco.Complemento = sqlDataReader["comp_end"].ToString(); - clienteEndereco.Cidade = sqlDataReader["cidade"].ToString(); - clienteEndereco.Estado = sqlDataReader["uf"].ToString(); - clienteEndereco.Cep = sqlDataReader["cep"].ToString(); - clienteEndereco.Bairro = sqlDataReader["bairro"].ToString(); - num = (sqlDataReader.IsDBNull(sqlDataReader.GetOrdinal("ordem")) ? 0 : (int)sqlDataReader["ordem"]); - clienteEndereco.Ordem = num; - clienteEnderecos2.Add(clienteEndereco); - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - else - { - clienteEnderecos = null; - clienteEnderecos1 = null; - return clienteEnderecos; - } - } - sqlConnection = null; - clienteEnderecos = clienteEnderecos1; - clienteEnderecos1 = null; - return clienteEnderecos; - } - - private async Task> EstipulanteCliente() - { - IEnumerable estipulanteClientes; - object connection; - List estipulanteClientes1 = new List(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT DISTINCT c.idcliente, e.idestipulante, e.nome FROM documento d INNER JOIN estipulante e on e.idestipulante = d.idestipulante INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE d.idestipulante IS NOT NULL AND (d.vigencia2 > GETDATE() OR d.vigencia2 IS NULL)"; - sqlCommand.CommandTimeout = 1000; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List estipulanteClientes2 = estipulanteClientes1; - EstipulanteCliente estipulanteCliente = new EstipulanteCliente() - { - IdEstiputante = (long)sqlDataReader["idestipulante"], - IdCliente = (long)sqlDataReader["idcliente"], - NomeEstipulante = sqlDataReader["nome"].ToString() - }; - estipulanteClientes2.Add(estipulanteCliente); - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - else - { - estipulanteClientes = null; - estipulanteClientes1 = null; - return estipulanteClientes; - } - } - sqlConnection = null; - estipulanteClientes = estipulanteClientes1; - estipulanteClientes1 = null; - return estipulanteClientes; - } - - private async Task ExisteClienteRamo(long idCliente, long idRamo) - { - 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 COUNT(c.idcontrole) contador FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole WHERE d.situacao IN (1,2,4) AND (d.vigencia2 > DATEADD(day, -5, GETDATE()) OR d.vigencia2 IS NULL) AND c.idcliente = @cliente AND c.idramo = @ramo"; - sqlCommand.Parameters.Add("@cliente", SqlDbType.BigInt).Value = idCliente; - sqlCommand.Parameters.Add("@ramo", SqlDbType.BigInt).Value = idRamo; - flag = (int)await sqlCommand.ExecuteScalarAsync() > 0; - } - } - } - return flag; - } - - public List Find(string filter, long idempresa = 0L, bool acessoAgger = false, bool assintatura = false) - { - List clientes; - object connection; - DataTable dataTable = new DataTable(); - List nums = new List(); - 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) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }; - List condicaos1 = this.CriarFiltro(filter); - List condicaos2 = new List() - { - new Condicao() - { - Campo = "idempresa", - Valores = idempresa.CriarValor() - } - }; - if (!acessoAgger) - { - condicaos1.AddRange(condicaos); - } - if (idempresa > (long)0) - { - condicaos1.AddRange(condicaos2); - } - dataTable = sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT TOP 200 IDEMPRESA, IDCLIENTE, NOME COLLATE Latin1_General_CI_AI AS NOME, CGCCPF, CEI, RNE, ISNULL(DOCUMENTOPRINCIPAL, 0) AS DOCUMENTOPRINCIPAL, CAEPF, EXCLUIDO, MalaDireta, nomesocialRg COLLATE Latin1_General_CI_AI as nomesocialRg FROM cliente WHERE", ""); - if (dataTable.Rows.Count > 0) - { - List condicaos3 = new List() - { - new Condicao() - { - Campo = "c.idcliente", - Valores = dataTable.AsEnumerable().Select((DataRow x) => x.Field("IDCLIENTE")).ToList().CriarValor() - } - }; - List condicaos4 = new List() - { - new Condicao() - { - Campo = "d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.tipo", - Valores = 0.CriarValor() - }, - new Condicao() - { - Campo = "d.vigencia2", - Valores = null, - Grupo = 2, - Operacao = Operacao.Or - } - }; - Condicao condicao = new Condicao() - { - Campo = "d.vigencia2" - }; - DateTime date = Funcoes.GetNetworkTime().Date; - condicao.Valores = date.AddDays(-5).CriarValor(); - condicao.Grupo = 2; - condicao.Operacao = Operacao.Or; - condicao.Operador = Operador.Maior; - condicaos4.Add(condicao); - condicaos4.Add(new Condicao() - { - Campo = "d.situacao", - Valores = new List() - { - 1, - 2, - 4 - } - }); - List condicaos5 = condicaos4; - condicaos5.AddRange(condicaos3); - DataTable dataTable2 = sqlCommand.Select(condicaos5.CreateParameters(0), "SELECT DISTINCT c.idcliente FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE", ""); - nums = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).ToList(); - if (assintatura) - { - dataTable1 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT * FROM ResponsavelAssinatura c WHERE ", ""); - } - } - goto Label0; - } - } - else - { - clientes = new List(); - } - } - return clientes; - List list = dataTable1.AsEnumerable().Select((DataRow x) => new ResponsavelAssinatura() - { - Id = x.Field("Id"), - IdCliente = x.Field("IdCliente"), - NomeResponsavel = x.Field("NomeResponsavel").RemoverAcentos(), - DocumentoResponsavel = x.Field("DocumentoResponsavel"), - EmailResponsavel = x.Field("EmailResponsavel") - }).ToList(); - return ( - from x in dataTable.AsEnumerable().ToList() - select new Gestor.Model.Domain.Seguros.Cliente() - { - Id = x.Field("IDCLIENTE"), - IdEmpresa = x.Field("IDEMPRESA"), - Nome = x.Field("NOME").RemoverAcentos(), - Documento = x.Field("CGCCPF"), - Cei = x.Field("CEI"), - Rne = x.Field("RNE"), - Caepf = x.Field("CAEPF"), - DocumentoPrincipal = new TipoDocumento?((TipoDocumento)Enum.Parse(typeof(TipoDocumento), x.Field("DOCUMENTOPRINCIPAL").ToString())), - Status = (nums.Any((long d) => d == x.Field("IDCLIENTE")) ? "ATIVO" : "INATIVO"), - ResponsavelAssinatura = list.Find((ResponsavelAssinatura r) => r.IdCliente == x.Field("IDCLIENTE")), - Excluido = (x.Field("EXCLUIDO") == null ? false : x.Field("EXCLUIDO").ToString() == "1"), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)), - NomeSocialRg = x.Field("nomesocialRg") - }).ToList(); - } - - public List FindAllClientes(bool completo, long idempresa = 0L) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "idempresa", - Valores = idempresa.CriarValor() - } - }; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }; - if (idempresa > (long)0) - { - condicaos1.AddRange(condicaos); - } - return this.Select(condicaos1.CreateParameters(0), "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", completo); - } - - public Gestor.Model.Domain.Seguros.Cliente FindById(long id) - { - ClienteDb clienteDb = base.FindEntityById(id); - ResponsavelAssinaturaDb responsavelAssinaturaDb = this._unitOfWork.Query().FirstOrDefault((ResponsavelAssinaturaDb x) => x.IdCliente == id); - ResponsavelAssinatura responsavelAssinatura = ApplicationMapper.Mapper.Map(responsavelAssinaturaDb); - Gestor.Model.Domain.Seguros.Cliente cliente = ApplicationMapper.Mapper.Map(clienteDb); - cliente.ResponsavelAssinatura = responsavelAssinatura; - return cliente; - } - - public List FindByName(string filter, long idEmpresa = 0L, bool acessoAgger = false, bool assintatura = false, bool somenteNome = false) - { - return this.Find(filter, idEmpresa, acessoAgger, assintatura); - } - - public List FindByNameOld(string filter, long idempresa = 0L, bool acessoAgger = false, bool assintatura = false, bool somenteNome = false) - { - List clientes; - object connection; - DataTable dataTable = new DataTable(); - List nums = new List(); - 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) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "UPPER(NOME) COLLATE Latin1_General_CI_AI", - Valores = filter.CriarValor(), - Operador = (somenteNome ? Operador.ComecaCom : Operador.Like) - } - }; - List condicaos2 = new List() - { - new Condicao() - { - Campo = "idempresa", - Valores = idempresa.CriarValor() - } - }; - if (!acessoAgger) - { - condicaos1.AddRange(condicaos); - } - if (idempresa > (long)0) - { - condicaos1.AddRange(condicaos2); - } - dataTable = sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT TOP 200 IDEMPRESA, IDCLIENTE, NOME COLLATE Latin1_General_CI_AI AS NOME, CGCCPF, CEI, RNE, ISNULL(DOCUMENTOPRINCIPAL, 0) AS DOCUMENTOPRINCIPAL, CAEPF, EXCLUIDO, MalaDireta, nomesocialRg COLLATE Latin1_General_CI_AI as nomesocialRg FROM cliente WHERE", ""); - if (dataTable.Rows.Count > 0) - { - List condicaos3 = new List() - { - new Condicao() - { - Campo = "c.idcliente", - Valores = dataTable.AsEnumerable().Select((DataRow x) => x.Field("IDCLIENTE")).ToList().CriarValor() - } - }; - List condicaos4 = new List() - { - new Condicao() - { - Campo = "d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.tipo", - Valores = 0.CriarValor() - }, - new Condicao() - { - Campo = "d.vigencia2", - Valores = null, - Grupo = 2, - Operacao = Operacao.Or - } - }; - Condicao condicao = new Condicao() - { - Campo = "d.vigencia2" - }; - DateTime date = Funcoes.GetNetworkTime().Date; - condicao.Valores = date.AddDays(-5).CriarValor(); - condicao.Grupo = 2; - condicao.Operacao = Operacao.Or; - condicao.Operador = Operador.Maior; - condicaos4.Add(condicao); - condicaos4.Add(new Condicao() - { - Campo = "d.situacao", - Valores = new List() - { - 1, - 2, - 4 - } - }); - List condicaos5 = condicaos4; - condicaos5.AddRange(condicaos3); - DataTable dataTable2 = sqlCommand.Select(condicaos5.CreateParameters(0), "SELECT DISTINCT c.idcliente FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE", ""); - nums = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).ToList(); - if (assintatura) - { - dataTable1 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT * FROM ResponsavelAssinatura c WHERE ", ""); - } - } - goto Label0; - } - } - else - { - clientes = new List(); - } - } - return clientes; - List list = dataTable1.AsEnumerable().Select((DataRow x) => new ResponsavelAssinatura() - { - Id = x.Field("Id"), - IdCliente = x.Field("IdCliente"), - NomeResponsavel = x.Field("NomeResponsavel").RemoverAcentos(), - DocumentoResponsavel = x.Field("DocumentoResponsavel"), - EmailResponsavel = x.Field("EmailResponsavel") - }).ToList(); - return ( - from x in dataTable.AsEnumerable().ToList() - select new Gestor.Model.Domain.Seguros.Cliente() - { - Id = x.Field("IDCLIENTE"), - IdEmpresa = x.Field("IDEMPRESA"), - Nome = x.Field("NOME").RemoverAcentos(), - Documento = x.Field("CGCCPF"), - Cei = x.Field("CEI"), - Rne = x.Field("RNE"), - Caepf = x.Field("CAEPF"), - DocumentoPrincipal = new TipoDocumento?((TipoDocumento)Enum.Parse(typeof(TipoDocumento), x.Field("DOCUMENTOPRINCIPAL").ToString())), - Status = (nums.Any((long d) => d == x.Field("IDCLIENTE")) ? "ATIVO" : "INATIVO"), - ResponsavelAssinatura = list.Find((ResponsavelAssinatura r) => r.IdCliente == x.Field("IDCLIENTE")), - Excluido = (x.Field("EXCLUIDO") == null ? false : x.Field("EXCLUIDO").ToString() == "1"), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)), - NomeSocialRg = x.Field("nomesocialRg") ?? "" - }).ToList(); - } - - public List FindClienteDocumento(string documento) - { - List clientes; - object connection; - List clientes1 = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT c.IDEMPRESA, c.IDCLIENTE, c.NOME COLLATE Latin1_General_CI_AI AS NOME FROM cliente c WHERE (UPPER(c.CGCCPF) = @documento OR UPPER(c.CEI) = @documento OR UPPER(c.RNE) = @documento OR UPPER(c.CAEPF) = @documento) AND c.EXCLUIDO = '0'"; - sqlCommand.Parameters.Add("@documento", SqlDbType.VarChar).Value = documento; - using (SqlDataReader sqlDataReader = sqlCommand.ExecuteReader()) - { - while (sqlDataReader.Read()) - { - clientes1.Add(new Gestor.Model.Domain.Seguros.Cliente() - { - Id = sqlDataReader.GetFieldValue("idcliente", true, true), - IdEmpresa = sqlDataReader.GetFieldValue("idempresa", true, true), - Nome = sqlDataReader.GetFieldValue("nome", true, true), - Documento = documento - }); - } - return clientes1; - } - } - } - else - { - clientes = clientes1; - } - } - } - return clientes; - } - - public List FindClienteVinculo(string filter, List vinculos, long idempresa = 0L, bool acessoAgger = false, bool assinatura = false, TipoFiltroCliente tipoFiltroCliente = 2) - { - List clientes; - object connection; - List clientes1 = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand item = sqlConnection.CreateCommand()) - { - StringBuilder stringBuilder = new StringBuilder("SELECT TOP 25 c.IDEMPRESA, c.IDCLIENTE, c.NOME COLLATE Latin1_General_CI_AI AS NOME, c.NOMESOCIALRG COLLATE Latin1_General_CI_AI AS NOMESOCIAL, c.CGCCPF, c.CEI, c.RNE, ISNULL(c.DOCUMENTOPRINCIPAL, 0) AS DOCUMENTOPRINCIPAL, c.CAEPF, c.EXCLUIDO, c.MalaDireta, (CASE WHEN (SELECT COUNT(d.IDDOCUMENTO) FROM DOCUMENTO d INNER JOIN CONTROLE ctrl ON d.IDCONTROLE = ctrl.IDCONTROLE WHERE ctrl.IDCLIENTE = c.IDCLIENTE AND (d.EXCLUIDO IS NULL OR d.EXCLUIDO = '0') AND (d.VIGENCIA2 IS NULL OR d.VIGENCIA2 >= GETDATE() - 5) AND d.TIPO = 0 AND d.SITUACAO NOT IN(3,7)) > 0 THEN 0 ELSE 1 END) AS ATIVO FROM CLIENTE c WHERE "); - if (idempresa > (long)0) - { - stringBuilder.Append(" (c.IDEMPRESA = @empresa) AND "); - item.Parameters.Add("@empresa", SqlDbType.BigInt).Value = idempresa; - } - if (!acessoAgger) - { - stringBuilder.Append(" (c.excluido IS NULL OR c.excluido = @excluido) AND "); - item.Parameters.Add("@excluido", SqlDbType.VarChar, 1).Value = "0"; - } - stringBuilder.Append((tipoFiltroCliente != TipoFiltroCliente.NomeDocumentos ? " (UPPER(c.NOME) COLLATE Latin1_General_CI_AI LIKE @filtro OR UPPER(c.NOMESOCIALRG) COLLATE Latin1_General_CI_AI LIKE @filtro) " : " (UPPER(c.NOME) COLLATE Latin1_General_CI_AI LIKE @filtro OR UPPER(c.NOMESOCIALRG) COLLATE Latin1_General_CI_AI LIKE @filtro OR UPPER(c.CGCCPF) LIKE @filtro OR UPPER(c.CEI) LIKE @filtro OR UPPER(c.RNE) LIKE @filtro OR UPPER(c.CAEPF) LIKE @filtro) ")); - item.Parameters.Add("@filtro", SqlDbType.VarChar, 150).Value = string.Concat((tipoFiltroCliente == TipoFiltroCliente.Nome ? "" : "%"), filter, "%"); - if (vinculos != null && vinculos.Count > 0) - { - stringBuilder.Append("AND ((SELECT COUNT(vp.IDVENDEDOR) FROM vendedorparcela vp INNER JOIN DOCUMENTO d ON vp.IDDOCUMENTO = d.IDDOCUMENTO INNER JOIN CONTROLE ctrl ON d.IDCONTROLE = ctrl.IDCONTROLE WHERE ctrl.IDCLIENTE = c.IDCLIENTE AND (d.EXCLUIDO IS NULL OR d.EXCLUIDO = '0') AND vp.IDVENDEDOR IN ("); - StringBuilder stringBuilder1 = new StringBuilder(); - for (int i = 0; i < vinculos.Count; i++) - { - if (i > 0) - { - stringBuilder1.Append(","); - } - string str = string.Format("@p{0}", i); - stringBuilder1.Append(str); - item.Parameters.Add(str, SqlDbType.BigInt).Value = vinculos[i]; - } - stringBuilder1.Append(")"); - stringBuilder.Append(stringBuilder1); - stringBuilder.Append(") > 0 OR ((SELECT COUNT(vp.IDVENDEDOR) FROM vendedorparcela vp INNER JOIN DOCUMENTO d ON vp.IDDOCUMENTO = d.IDDOCUMENTO INNER JOIN CONTROLE ctrl ON d.IDCONTROLE = ctrl.IDCONTROLE WHERE ctrl.IDCLIENTE = c.IDCLIENTE AND (d.EXCLUIDO IS NULL OR d.EXCLUIDO = '0') AND vp.IDVENDEDOR IN ("); - stringBuilder.Append(stringBuilder1); - stringBuilder.Append(") = 0 AND (SELECT COUNT(d.IDDOCUMENTO) FROM DOCUMENTO d INNER JOIN CONTROLE ctrl ON d.IDCONTROLE = ctrl.IDCONTROLE WHERE ctrl.IDCLIENTE = c.IDCLIENTE AND (d.EXCLUIDO IS NULL OR d.EXCLUIDO = '0')) = 0))"); - } - item.CommandText = stringBuilder.ToString(); - using (SqlDataReader sqlDataReader = item.ExecuteReader()) - { - while (sqlDataReader.Read()) - { - clientes1.Add(new Gestor.Model.Domain.Seguros.Cliente() - { - Id = sqlDataReader.GetFieldValue("idcliente", true, true), - IdEmpresa = sqlDataReader.GetFieldValue("idempresa", true, true), - Nome = sqlDataReader.GetFieldValue("nome", true, true), - Documento = sqlDataReader.GetFieldValue("cgccpf", true, true), - Cei = sqlDataReader.GetFieldValue("cei", true, true), - Rne = sqlDataReader.GetFieldValue("rne", true, true), - Caepf = sqlDataReader.GetFieldValue("caepf", true, true), - DocumentoPrincipal = new TipoDocumento?(sqlDataReader.GetFieldValue("documentoprincipal", true, true)), - Status = (sqlDataReader.GetFieldValue("ativo", true, true) == 0 ? "ATIVO" : "INATIVO"), - Excluido = sqlDataReader.GetFieldValue("excluido", true, true) == 1, - NomeSocialRg = sqlDataReader.GetFieldValue("nomesocial", true, true) - }); - } - return clientes1; - } - } - } - else - { - clientes = clientes1; - } - } - } - return clientes; - } - - public List FindObsCliente(string obsCliente, long idempresa = 0L) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "idempresa", - Valores = idempresa.CriarValor() - } - }; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "anotacoes", - Valores = obsCliente.CriarValor(), - Operador = Operador.Like - }, - new Condicao() - { - Campo = "excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }; - if (idempresa > (long)0) - { - condicaos1.AddRange(condicaos); - } - return this._unitOfWork.Select(condicaos1.CreateParameters(0), "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", "").MapCliente(); - } - - public List FindPastaCliente(string pastaCliente, bool busca = false, long idempresa = 0L) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "idempresa", - Valores = idempresa.CriarValor() - } - }; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "pasta", - Valores = pastaCliente.CriarValor(), - Operador = (busca ? Operador.Igual : Operador.Like) - }, - new Condicao() - { - Campo = "excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }; - if (idempresa > (long)0) - { - condicaos1.AddRange(condicaos); - } - return this._unitOfWork.Select(condicaos1.CreateParameters(0), "SELECT idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta, clidesde, ESTADOCIVI FROM cliente WHERE ", "").MapCliente(); - } - - public List FindVinculo(string filter, long id) - { - List condicaos = this.CriarFiltro(filter); - condicaos.AddRange(new List() - { - new Condicao() - { - Campo = "excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "idcliente", - Valores = id.CriarValor(), - Operador = Operador.Diferente - } - }); - DataTable dataTable = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT TOP 200 idcliente as id, idempresa, nome, cgccpf as documento, cei, rne, documentoprincipal, anotacoes, dtnasc as nascimento, idprofissao, VENCHABILI as vencimento, sexo, RendaMensal, pasta, MalaDireta FROM cliente WHERE", ""); - if (dataTable != null && dataTable.Rows.Count == 0) - { - return new List(); - } - return dataTable.MapCliente(); - } - - public Gestor.Model.Domain.Seguros.Cliente Merge(Gestor.Model.Domain.Seguros.Cliente cliente) - { - ResponsavelAssinatura responsavelAssinatura; - ClienteDb clienteDb = ApplicationMapper.Mapper.Map(cliente); - if (cliente.ResponsavelAssinatura == null || string.IsNullOrEmpty(cliente.ResponsavelAssinatura.NomeResponsavel)) - { - responsavelAssinatura = null; - } - else - { - responsavelAssinatura = cliente.ResponsavelAssinatura; - } - ResponsavelAssinatura responsavelAssinatura1 = responsavelAssinatura; - if (responsavelAssinatura1 != null) - { - ResponsavelAssinaturaDb responsavelAssinaturaDb = ApplicationMapper.Mapper.Map(responsavelAssinatura1); - if (responsavelAssinaturaDb.Id != 0) - { - this._unitOfWork.Repository().Merge(responsavelAssinaturaDb); - } - else - { - this._unitOfWork.Repository().SaveOrUpdate(responsavelAssinaturaDb); - } - responsavelAssinatura1 = ApplicationMapper.Mapper.Map(responsavelAssinaturaDb); - } - base.Merge(clienteDb); - Gestor.Model.Domain.Seguros.Cliente cliente1 = ApplicationMapper.Mapper.Map(clienteDb); - cliente1.ResponsavelAssinatura = responsavelAssinatura1; - return cliente1; - } - - public OrigemCliente Merge(OrigemCliente origem) - { - OrigemClienteDb origemClienteDb = ApplicationMapper.Mapper.Map(origem); - this._unitOfWork.Repository().Merge(origemClienteDb); - return ApplicationMapper.Mapper.Map(origemClienteDb); - } - - public Gestor.Model.Domain.Seguros.Cliente SaveOrUpdate(Gestor.Model.Domain.Seguros.Cliente cliente) - { - ResponsavelAssinatura responsavelAssinatura; - ClienteDb clienteDb = ApplicationMapper.Mapper.Map(cliente); - this.SaveOrUpdate(clienteDb); - if (cliente.ResponsavelAssinatura == null || string.IsNullOrEmpty(cliente.ResponsavelAssinatura.NomeResponsavel)) - { - responsavelAssinatura = null; - } - else - { - responsavelAssinatura = cliente.ResponsavelAssinatura; - } - ResponsavelAssinatura id = responsavelAssinatura; - if (id != null) - { - id.IdCliente = clienteDb.Id; - ResponsavelAssinaturaDb responsavelAssinaturaDb = ApplicationMapper.Mapper.Map(id); - this._unitOfWork.Repository().SaveOrUpdate(responsavelAssinaturaDb); - id = ApplicationMapper.Mapper.Map(responsavelAssinaturaDb); - } - Gestor.Model.Domain.Seguros.Cliente cliente1 = ApplicationMapper.Mapper.Map(clienteDb); - cliente1.ResponsavelAssinatura = id; - return cliente1; - } - - public OrigemCliente SaveOrUpdate(OrigemCliente origem) - { - OrigemClienteDb origemClienteDb = ApplicationMapper.Mapper.Map(origem); - this._unitOfWork.Repository().SaveOrUpdate(origemClienteDb); - return ApplicationMapper.Mapper.Map(origemClienteDb); - } - - private List Select(SqlQueryCondition condition, string command, bool completo) - { - List clientesAtivosInativos; - object connection; - List nums3 = null; - List nums4 = null; - DataTable dataTable1 = new DataTable(); - DataTable dataTable2 = new DataTable(); - DataTable dataTable3 = new DataTable(); - DataTable dataTable4 = new DataTable(); - DataTable dataTable5 = new DataTable(); - DataTable dataTable6 = new DataTable(); - DataTable dataTable7 = new DataTable(); - DataTable dataTable8 = 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) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - if (completo) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - } - dataTable1 = sqlCommand.Select(condition, command, ""); - if (dataTable1 == null || dataTable1.Rows.Count != 0) - { - for (List i = dataTable1.AsEnumerable().Select((DataRow x) => x.Field("id")).ToList(); i.Count > 0; i = nums3) - { - List nums5 = i.Take(2000).ToList(); - List condicaos = new List() - { - new Condicao() - { - Campo = "idcliente", - Valores = nums5.CriarValor() - } - }; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.vigencia2", - Valores = null, - Grupo = 2, - Operacao = Operacao.Or - } - }; - Condicao condicao = new Condicao() - { - Campo = "d.vigencia2" - }; - DateTime date = Funcoes.GetNetworkTime().Date; - condicao.Valores = date.AddDays(-5).CriarValor(); - condicao.Grupo = 2; - condicao.Operacao = Operacao.Or; - condicao.Operador = Operador.Maior; - condicaos1.Add(condicao); - condicaos1.Add(new Condicao() - { - Campo = "d.situacao", - Valores = new List() - { - 1, - 2, - 4 - } - }); - List condicaos2 = condicaos1; - condicaos2.AddRange(condicaos); - DataTable dataTable9 = sqlCommand.Select(condicaos2.CreateParameters(0), "SELECT DISTINCT c.idcliente, r.idramo, r.nome AS ramo, d.iddocumento as id, d.idcontrole FROM documento d INNER JOIN controle c ON c.idcontrole = d.idcontrole INNER JOIN ramo r ON r.idramo = c.idramo WHERE", ""); - List nums6 = dataTable9.AsEnumerable().Select((DataRow x) => x.Field("id")).ToList(); - List nums7 = dataTable9.AsEnumerable().Select((DataRow x) => x.Field("id")).ToList(); - dataTable2.Merge(dataTable9); - List condicaos3 = new List() - { - new Condicao() - { - Campo = "ORDEM", - Valores = "1".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "PADRAO", - Valores = "1".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }; - condicaos3.AddRange(condicaos); - dataTable9 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT DISTINCT idcliend, cep, cidade, uf as estado, idcliente as id, endereco, numero, comp_end as complemento FROM cliendereco WHERE ", ""); - dataTable3.Merge(dataTable9); - dataTable9 = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT DISTINCT idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE ", ""); - dataTable5.Merge(dataTable9); - dataTable9 = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT DISTINCT idclimail, email, idcliente as id FROM climail WHERE ", ""); - dataTable4.Merge(dataTable9); - if (completo) - { - for (List j = nums5; j.Count > 0; j = nums4) - { - List nums8 = j.Take(1000).ToList(); - List condicaos4 = new List() - { - new Condicao() - { - Campo = "idcliente1", - Valores = nums8.CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "idcliente2", - Valores = nums8.CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }; - dataTable9 = sqlCommand.Select(condicaos4.CreateParameters(0), "SELECT * FROM clivinculo c WHERE", ""); - dataTable7.Merge(dataTable9); - nums4 = (nums8.Count < 1000 ? new List() : j.Except(nums8).ToList()); - } - while (nums6.Count > 0) - { - List nums9 = nums6.Take(2000).ToList(); - List condicaos5 = new List() - { - new Condicao() - { - Campo = "vp.iddocumento", - Valores = nums9.CriarValor() - } - }; - dataTable9 = sqlCommand.Select(condicaos5.CreateParameters(0), "SELECT DISTINCT vp.idvendedor, vp.iddocumento FROM vendedorparcela vp WHERE", ""); - dataTable6.Merge(dataTable9); - nums6 = (nums9.Count < 2000 ? new List() : nums6.Except(nums9).ToList()); - } - while (nums7.Count > 0) - { - List nums10 = nums7.Take(2000).ToList(); - List condicaos6 = new List() - { - new Condicao() - { - Campo = "iddocumento", - Valores = nums10.CriarValor() - } - }; - dataTable9 = sqlCommand.Select(condicaos6.CreateParameters(0), "select IDDOCUMENTO, case when(idestipulante is null ) then 0 else idestipulante end as idestipulante from documento where", ""); - dataTable8.Merge(dataTable9); - nums7 = (nums10.Count < 2000 ? new List() : nums6.Except(nums10).ToList()); - } - } - nums3 = (nums5.Count < 2000 ? new List() : i.Except(nums5).ToList()); - } - goto Label0; - } - else - { - clientesAtivosInativos = new List(); - } - } - } - else - { - clientesAtivosInativos = new List(); - } - } - return clientesAtivosInativos; - Label0: - Regex regex = new Regex("[^\\d]"); - DateTime networkTime = Funcoes.GetNetworkTime(); - Array values = Enum.GetValues(typeof(EstadoCivil)); - List clientesAtivosInativos1 = new List(); - dataTable1.AsEnumerable().ToList().ForEach((DataRow x) => { - DateTime? nullable; - DateTime dateTime; - List list; - List nums; - DateTime? nullable1; - string str; - DateTime? nullable2; - string nome; - int year; - int? nullable3; - DateTime? nullable4; - List dataRows = dataTable2.AsEnumerable().Where((DataRow y) => y.Field("idcliente") == x.Field("id")).ToList(); - List dataRows1 = dataRows; - Func u003cu003e9_325 = ClienteRepository.u003cu003ec.u003cu003e9__32_5; - if (u003cu003e9_325 == null) - { - u003cu003e9_325 = (DataRow d) => d.Field("id"); - ClienteRepository.u003cu003ec.u003cu003e9__32_5 = u003cu003e9_325; - } - List list1 = dataRows1.Select(u003cu003e9_325).ToList(); - DataRow dataRow = dataTable3.AsEnumerable().FirstOrDefault((DataRow t) => t.Field("id") == x.Field("id")); - EnumerableRowCollection dataRows2 = dataTable4.AsEnumerable().Where((DataRow t) => t.Field("id") == x.Field("id")); - Func u003cu003e9_328 = ClienteRepository.u003cu003ec.u003cu003e9__32_8; - if (u003cu003e9_328 == null) - { - u003cu003e9_328 = (DataRow t) => t.Field("email"); - ClienteRepository.u003cu003ec.u003cu003e9__32_8 = u003cu003e9_328; - } - EnumerableRowCollection strs = dataRows2.Select(u003cu003e9_328); - if (list1.Count > 0) - { - EnumerableRowCollection dataRows3 = dataTable6.AsEnumerable().Where((DataRow y) => list1.Contains(y.Field("iddocumento"))); - Func u003cu003e9_3210 = ClienteRepository.u003cu003ec.u003cu003e9__32_10; - if (u003cu003e9_3210 == null) - { - u003cu003e9_3210 = (DataRow y) => y.Field("idvendedor"); - ClienteRepository.u003cu003ec.u003cu003e9__32_10 = u003cu003e9_3210; - } - list = dataRows3.Select(u003cu003e9_3210).Distinct().ToList(); - } - else - { - list = null; - } - List nums1 = list; - EnumerableRowCollection dataRows4 = dataTable5.AsEnumerable().Where((DataRow t) => t.Field("id") == x.Field("id")); - Func u003cu003e9_3212 = ClienteRepository.u003cu003ec.u003cu003e9__32_12; - if (u003cu003e9_3212 == null) - { - u003cu003e9_3212 = (DataRow t) => new Gestor.Model.Domain.Seguros.ClienteTelefone() - { - Prefixo = t.Field("ddd"), - Numero = t.Field("fone") - }; - ClienteRepository.u003cu003ec.u003cu003e9__32_12 = u003cu003e9_3212; - } - List clienteTelefones = dataRows4.Select(u003cu003e9_3212).ToList(); - List clienteTelefones1 = clienteTelefones; - Func u003cu003e9_3213 = ClienteRepository.u003cu003ec.u003cu003e9__32_13; - if (u003cu003e9_3213 == null) - { - u003cu003e9_3213 = (Gestor.Model.Domain.Seguros.ClienteTelefone t) => string.Concat(t.Prefixo, " ", t.Numero); - ClienteRepository.u003cu003ec.u003cu003e9__32_13 = u003cu003e9_3213; - } - IEnumerable strs1 = clienteTelefones1.Select(u003cu003e9_3213); - List dataRows5 = dataRows; - Func u003cu003e9_3214 = ClienteRepository.u003cu003ec.u003cu003e9__32_14; - if (u003cu003e9_3214 == null) - { - u003cu003e9_3214 = (DataRow y) => y.Field("ramo"); - ClienteRepository.u003cu003ec.u003cu003e9__32_14 = u003cu003e9_3214; - } - IEnumerable strs2 = dataRows5.Select(u003cu003e9_3214); - Func u003cu003e9_3215 = ClienteRepository.u003cu003ec.u003cu003e9__32_15; - if (u003cu003e9_3215 == null) - { - u003cu003e9_3215 = (string r) => r; - ClienteRepository.u003cu003ec.u003cu003e9__32_15 = u003cu003e9_3215; - } - List list2 = strs2.OrderBy(u003cu003e9_3215).Distinct().ToList(); - DataRow dataRow1 = dataTable7.AsEnumerable().FirstOrDefault((DataRow v) => v.Field("idcliente1") == x.Field("id")) ?? dataTable7.AsEnumerable().FirstOrDefault((DataRow v) => v.Field("idcliente2") == x.Field("id")); - if (list1.Count > 0) - { - DataTable dataTable = dataTable8; - if (dataTable != null) - { - EnumerableRowCollection dataRows6 = dataTable.AsEnumerable().Where((DataRow y) => list1.Contains(y.Field("iddocumento"))); - Func u003cu003e9_3219 = ClienteRepository.u003cu003ec.u003cu003e9__32_19; - if (u003cu003e9_3219 == null) - { - u003cu003e9_3219 = (DataRow y) => y.Field("idestipulante"); - ClienteRepository.u003cu003ec.u003cu003e9__32_19 = u003cu003e9_3219; - } - nums = dataRows6.Select(u003cu003e9_3219).Distinct().ToList(); - } - else - { - nums = null; - } - } - else - { - nums = null; - } - List nums2 = nums; - List vendedors = (nums1 == null || nums1.Count <= 0 ? new List() : ( - from v in Auxiliar.Vendedores - where nums1.Contains(v.Id) - select v).ToList()); - List estipulantes = (nums2 == null || nums2.Count <= 0 ? new List() : ( - from e in Auxiliar.Estipulantes - where nums2.Contains(e.Id) - select e).ToList()); - string description = ""; - foreach (object obj in values) - { - if (obj.GetOldValue() != x.Field("EstadoCivi")) - { - continue; - } - description = ((EstadoCivil)obj).GetDescription(); - } - ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos() - { - EntidadeCliente = new Gestor.Model.Domain.Seguros.Cliente() - { - Id = x.Field("id"), - Nome = x.Field("nome"), - Telefones = new ObservableCollection(clienteTelefones), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) - }, - Id = x.Field("id"), - Nome = x.Field("nome") - }; - if (x.Field("nascimento") == null) - { - nullable = null; - nullable1 = nullable; - } - else - { - nullable1 = new DateTime?(DateTime.Parse(x.Field("nascimento").ToString())); - } - clientesAtivosInativo.Nascimento = nullable1; - if (x.Field("nascimento") == null) - { - str = ""; - } - else - { - dateTime = x.Field("nascimento"); - str = dateTime.ToString("dd/MM"); - } - clientesAtivosInativo.Aniversario = str; - clientesAtivosInativo.Documento = x.Field("documento"); - if (x.Field("vencimento") == null) - { - nullable = null; - nullable2 = nullable; - } - else - { - nullable2 = x.Field("vencimento"); - } - clientesAtivosInativo.VencimentoCnh = nullable2; - clientesAtivosInativo.Ramo = string.Join(" | ", list2); - clientesAtivosInativo.Ativo = (list2.Any() ? "SIM" : "NÃO"); - if (x.Field("idprofissao") != null) - { - Profissao profissao = Auxiliar.Profissoes.FirstOrDefault((Profissao p) => p.Id == long.Parse(x.Field("idprofissao").ToString())); - if (profissao != null) - { - nome = profissao.Nome; - } - else - { - nome = null; - } - } - else - { - nome = ""; - } - clientesAtivosInativo.Profissao = nome; - clientesAtivosInativo.Telefone = string.Join(" | ", strs1); - clientesAtivosInativo.Cep = (dataRow != null ? dataRow.Field("cep") : null); - clientesAtivosInativo.Endereco = (dataRow != null ? dataRow.Field("endereco") : null); - clientesAtivosInativo.Numero = (dataRow != null ? dataRow.Field("numero") : null); - clientesAtivosInativo.Complemento = (dataRow != null ? dataRow.Field("complemento") : null); - clientesAtivosInativo.Cidade = (dataRow != null ? dataRow.Field("cidade") : null); - clientesAtivosInativo.PastaCliente = x.Field("pasta"); - clientesAtivosInativo.Estado = (dataRow != null ? dataRow.Field("estado") : null); - clientesAtivosInativo.Email = string.Join(" | ", strs); - clientesAtivosInativo.RecebeEmail = (x.Field("maladireta").GetValueOrDefault() ? "SIM" : "NÃO"); - List vendedors1 = vendedors; - Func u003cu003e9_3223 = ClienteRepository.u003cu003ec.u003cu003e9__32_23; - if (u003cu003e9_3223 == null) - { - u003cu003e9_3223 = (Gestor.Model.Domain.Seguros.Vendedor v) => v.Nome; - ClienteRepository.u003cu003ec.u003cu003e9__32_23 = u003cu003e9_3223; - } - clientesAtivosInativo.Vendedor = string.Join(" | ", vendedors1.Select(u003cu003e9_3223)); - clientesAtivosInativo.TipoPessoa = (string.IsNullOrEmpty(x.Field("documento")) ? "FÍSICA" : (regex.Replace(x.Field("documento"), "").Length > 11 ? "JURÍDICA" : "FÍSICA")); - clientesAtivosInativo.Sexo = (x.Field("sexo") == null || !(x.Field("sexo").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("sexo").ToString()) ? "" : ((Sexo)Enum.Parse(typeof(Sexo), x.Field("sexo").ToString())).GetDescription()); - clientesAtivosInativo.RendaMensal = (x.Field("RendaMensal") == null ? decimal.Zero : x.Field("RendaMensal")); - clientesAtivosInativo.Parentesco = (dataRow1 == null ? "NÃO" : "SIM"); - if (x.Field("nascimento") != null) - { - DateTime dateTime1 = DateTime.Parse(x.Field("nascimento").ToString()); - int num = networkTime.Year; - dateTime = DateTime.Parse(x.Field("nascimento").ToString()); - if (dateTime1 > networkTime.AddYears(-(num - dateTime.Year))) - { - int year1 = networkTime.Year; - dateTime = DateTime.Parse(x.Field("nascimento").ToString()); - year = year1 - dateTime.Year - 1; - } - else - { - int num1 = networkTime.Year; - dateTime = DateTime.Parse(x.Field("nascimento").ToString()); - year = num1 - dateTime.Year; - } - nullable3 = new int?(year); - } - else - { - nullable3 = null; - } - clientesAtivosInativo.Idade = nullable3; - nullable = x.Field("clidesde"); - if (!nullable.HasValue) - { - nullable = null; - nullable4 = nullable; - } - else - { - nullable4 = x.Field("clidesde"); - } - clientesAtivosInativo.ClienteDesde = nullable4; - clientesAtivosInativo.EstadoCivil = description; - List estipulantes1 = estipulantes; - Func u003cu003e9_3224 = ClienteRepository.u003cu003ec.u003cu003e9__32_24; - if (u003cu003e9_3224 == null) - { - u003cu003e9_3224 = (Estipulante v) => v.Nome; - ClienteRepository.u003cu003ec.u003cu003e9__32_24 = u003cu003e9_3224; - } - clientesAtivosInativo.Estipulantes = string.Join(" | ", estipulantes1.Select(u003cu003e9_3224)); - clientesAtivosInativos1.Add(clientesAtivosInativo); - }); - return clientesAtivosInativos1; - } - - public List Sincronize(List origens, long id) - { - if (origens == null) - { - return null; - } - IEnumerable origemClienteDbs = ( - from x in this._unitOfWork.Query() - where x.Cliente.Id == id - select x).ToList().Where((OrigemClienteDb x) => { - List origemClientes = origens; - Func u003cu003e9_304 = ClienteRepository.u003cu003ec.u003cu003e9__30_4; - if (u003cu003e9_304 == null) - { - u003cu003e9_304 = (OrigemCliente i) => i.Id; - ClienteRepository.u003cu003ec.u003cu003e9__30_4 = u003cu003e9_304; - } - return !origemClientes.Select(u003cu003e9_304).Contains(x.Id); - }); - if (origemClienteDbs != null) - { - origemClienteDbs.ForEach((OrigemClienteDb x) => this._unitOfWork.Repository().Delete(x)); - } - else - { - } - origens.ForEach((OrigemCliente x) => x = (x.Id > (long)0 ? this.Merge(x) : this.SaveOrUpdate(x))); - return origens; - } - - private async Task> TelefonesClientes() - { - IEnumerable clienteTelefones; - object connection; - List clienteTelefones1 = new List(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT idcliente,ddd,fone FROM clitelefone ORDER BY idcliente,ordem"; - sqlCommand.CommandTimeout = 1000; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List clienteTelefones2 = clienteTelefones1; - Gestor.Model.Relatorios.ClienteTelefone clienteTelefone = new Gestor.Model.Relatorios.ClienteTelefone(); - Gestor.Model.Relatorios.Cliente cliente = new Gestor.Model.Relatorios.Cliente() - { - Id = (long)sqlDataReader["idcliente"] - }; - clienteTelefone.Cliente = cliente; - clienteTelefone.Prefixo = sqlDataReader["ddd"].ToString(); - clienteTelefone.Numero = sqlDataReader["fone"].ToString(); - clienteTelefones2.Add(clienteTelefone); - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - else - { - clienteTelefones = null; - clienteTelefones1 = null; - return clienteTelefones; - } - } - sqlConnection = null; - clienteTelefones = clienteTelefones1; - clienteTelefones1 = null; - return clienteTelefones; - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs deleted file mode 100644 index 1a5fb3c..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs +++ /dev/null @@ -1,220 +0,0 @@ -using AutoMapper; -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.Generic; -using Gestor.Model.Domain.Seguros; -using Gestor.Model.Helper; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ClienteTelefoneRepository : GenericRepository, IClienteTelefoneRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ClienteTelefoneRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List DeleteFone(long clienteId, List telefones) - { - if (telefones == null || telefones.Count == 0) - { - return null; - } - List list = ( - from cliente in base.All() - where cliente.Cliente.Id == clienteId - select cliente).ToList().Where((ClienteTelefoneDb fone) => { - List clienteTelefones = telefones; - Func u003cu003e9_103 = ClienteTelefoneRepository.u003cu003ec.u003cu003e9__10_3; - if (u003cu003e9_103 == null) - { - u003cu003e9_103 = (ClienteTelefone t) => t.Id; - ClienteTelefoneRepository.u003cu003ec.u003cu003e9__10_3 = u003cu003e9_103; - } - return !clienteTelefones.Select(u003cu003e9_103).Contains(fone.Id); - }).ToList(); - list.ForEach((ClienteTelefoneDb fonesExcluido) => base.Delete(fonesExcluido)); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List Find(string telefone, long idempresa = 0L) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "REPLACE(ISNULL(ct.fone, ''), '-','')", - Valores = telefone.Clear().CriarValor(), - Operador = Operador.Like - } - }; - if (idempresa > (long)0) - { - condicaos.Add(new Condicao() - { - Campo = "c.idempresa", - Valores = idempresa.CriarValor() - }); - } - return this.Select(condicaos.CreateParameters(0)); - } - - private List FindByCliente(long id) - { - return this.Select((new List() - { - new Condicao() - { - Campo = "ct.idcliente", - Valores = id.CriarValor() - } - }).CreateParameters(0)); - } - - public List FindByClienteId(long id) - { - return this.FindByCliente(id); - } - - public ClienteTelefone FindById(long id) - { - ClienteTelefoneDb clienteTelefoneDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(clienteTelefoneDb); - } - - public List Inserir(List telefones) - { - List clienteTelefoneDbs = ApplicationMapper.Mapper.Map, List>(telefones); - clienteTelefoneDbs.ForEach((ClienteTelefoneDb x) => { - string str; - ClienteTelefoneDb clienteTelefoneDb = x; - string observacao = x.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteTelefoneDb.Observacao = str; - if (x.Id == 0) - { - this.SaveOrUpdate(x); - return; - } - base.Merge(x); - }); - return ApplicationMapper.Mapper.Map, List>(clienteTelefoneDbs); - } - - public List Inserir(List telefones, Cliente cliente) - { - telefones.ForEach((ClienteTelefone x) => { - string str; - x.Cliente = cliente; - ClienteTelefone clienteTelefone = x; - string observacao = x.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteTelefone.Observacao = str; - }); - List clienteTelefoneDbs = ApplicationMapper.Mapper.Map, List>(telefones); - base.AddRange(clienteTelefoneDbs); - return ApplicationMapper.Mapper.Map, List>(clienteTelefoneDbs); - } - - public ClienteTelefone Merge(ClienteTelefone telefone) - { - ClienteTelefoneDb clienteTelefoneDb = ApplicationMapper.Mapper.Map(telefone); - clienteTelefoneDb.Observacao = clienteTelefoneDb.Observacao.Trim(); - base.Merge(clienteTelefoneDb); - return ApplicationMapper.Mapper.Map(clienteTelefoneDb); - } - - public List Merge(List telefones, Cliente cliente) - { - List clienteTelefoneDbs = ApplicationMapper.Mapper.Map, List>(telefones); - clienteTelefoneDbs.ForEach((ClienteTelefoneDb x) => { - string str; - ClienteTelefoneDb clienteTelefoneDb = x; - string observacao = x.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteTelefoneDb.Observacao = str; - if (x.Id != 0) - { - base.Merge(x); - return; - } - x.Cliente = ApplicationMapper.Mapper.Map(cliente); - this.SaveOrUpdate(x); - }); - return ApplicationMapper.Mapper.Map, List>(clienteTelefoneDbs); - } - - public ClienteTelefone SaveOrUpdate(ClienteTelefone telefone) - { - string str; - ClienteTelefoneDb clienteTelefoneDb = ApplicationMapper.Mapper.Map(telefone); - ClienteTelefoneDb clienteTelefoneDb1 = clienteTelefoneDb; - string observacao = clienteTelefoneDb.Observacao; - if (observacao != null) - { - str = observacao.Trim(); - } - else - { - str = null; - } - clienteTelefoneDb1.Observacao = str; - this.SaveOrUpdate(clienteTelefoneDb); - return ApplicationMapper.Mapper.Map(clienteTelefoneDb); - } - - private List Select(SqlQueryCondition condition) - { - List clienteTelefones = CustomMap.MapTelefone(this._unitOfWork.Select(condition, "SELECT ct.idclitelefone AS Id, ct.idcliente as IdCliente, ct.ddd AS Prefixo, ct.fone AS Numero, ISNULL(ct.tipo , 0) AS Tipo, ct.obs AS Observacao, ct.ordem AS Ordem, c.nome as NomeCliente FROM clitelefone ct INNER JOIN cliente c ON c.idcliente = ct.idcliente WHERE ", "")); - int? nullable1 = new int?(0); - clienteTelefones.ForEach((ClienteTelefone x) => { - int? ordem = nullable1; - int? nullable = ordem; - nullable1 = (nullable.HasValue ? new int?(nullable.GetValueOrDefault() + 1) : null); - ClienteTelefone clienteTelefone = x; - ordem = x.Ordem; - clienteTelefone.Ordem = (ordem.HasValue ? ordem : nullable1); - }); - return clienteTelefones; - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs deleted file mode 100644 index 460e860..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs +++ /dev/null @@ -1,112 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ClienteVinculoRepository : GenericRepository, IClienteVinculoRepository, IGenericRepository - { - public ClienteVinculoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List DeleteVinculo(long clienteId, List vinculos) - { - if (vinculos == null) - { - return null; - } - List list = ( - from x in base.All() - where x.Cliente1.Id == clienteId || x.Cliente2.Id == clienteId - select x).ToList().Where((ClienteVinculoDb vinculo) => { - List clienteVinculos = vinculos; - Func u003cu003e9_32 = ClienteVinculoRepository.u003cu003ec.u003cu003e9__3_2; - if (u003cu003e9_32 == null) - { - u003cu003e9_32 = (ClienteVinculo t) => t.Id; - ClienteVinculoRepository.u003cu003ec.u003cu003e9__3_2 = u003cu003e9_32; - } - return !clienteVinculos.Select(u003cu003e9_32).Contains(vinculo.Id); - }).ToList(); - ClienteVinculoRepository clienteVinculoRepository = this; - list.ForEach(new Action(clienteVinculoRepository.Delete)); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindByCliente(long id) - { - List list = ( - from x in base.All() - where x.Cliente1.Id == id || x.Cliente2.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public ClienteVinculo FindById(long id) - { - ClienteVinculoDb clienteVinculoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(clienteVinculoDb); - } - - public List Inserir(List vinculos, Cliente cliente) - { - foreach (ClienteVinculo vinculo in vinculos) - { - if (vinculo.Cliente1.Id == cliente.Id || vinculo.Cliente1.Id == 0) - { - vinculo.Cliente1 = cliente; - } - else - { - if (vinculo.Cliente2.Id != cliente.Id && vinculo.Cliente2.Id != 0) - { - continue; - } - vinculo.Cliente2 = cliente; - } - } - List clienteVinculoDbs = ApplicationMapper.Mapper.Map, List>(vinculos); - base.AddRange(clienteVinculoDbs); - return ApplicationMapper.Mapper.Map, List>(clienteVinculoDbs); - } - - public List Merge(List vinculos, Cliente cliente) - { - List clienteVinculoDbs = ApplicationMapper.Mapper.Map, List>(vinculos); - clienteVinculoDbs.ForEach((ClienteVinculoDb x) => { - if (x.Id != 0) - { - base.Merge(x); - return; - } - x.Cliente1 = ApplicationMapper.Mapper.Map(cliente); - this.SaveOrUpdate(x); - }); - return ApplicationMapper.Mapper.Map, List>(clienteVinculoDbs); - } - - public ClienteVinculo SaveOrUpdate(ClienteVinculo clienteVinculo) - { - ClienteVinculoDb clienteVinculoDb = ApplicationMapper.Mapper.Map(clienteVinculo); - this.SaveOrUpdate(clienteVinculoDb); - return ApplicationMapper.Mapper.Map(clienteVinculoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs deleted file mode 100644 index f4abfdf..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs +++ /dev/null @@ -1,65 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class CoberturaGranizoRepository : GenericRepository, ICoberturaGranizoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public CoberturaGranizoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - CoberturaGranizoDb coberturaGranizoDb = base.FindEntityById(id); - if (coberturaGranizoDb == null) - { - return; - } - base.Delete(coberturaGranizoDb); - } - - public List Find(long id) - { - List list = ( - from x in base.All() - where x.Granizo.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public CoberturaGranizo FindById(long id) - { - CoberturaGranizoDb coberturaGranizoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(coberturaGranizoDb); - } - - public CoberturaGranizo Merge(CoberturaGranizo cobertura) - { - CoberturaGranizoDb coberturaGranizoDb = ApplicationMapper.Mapper.Map(cobertura); - base.Merge(coberturaGranizoDb); - return ApplicationMapper.Mapper.Map(coberturaGranizoDb); - } - - public CoberturaGranizo SaveOrUpdate(CoberturaGranizo cobertura) - { - CoberturaGranizoDb coberturaGranizoDb = ApplicationMapper.Mapper.Map(cobertura); - this.SaveOrUpdate(coberturaGranizoDb); - return ApplicationMapper.Mapper.Map(coberturaGranizoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs deleted file mode 100644 index e9f916d..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs +++ /dev/null @@ -1,70 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class CoberturaPadraoRepository : GenericRepository, ICoberturaPadraoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public CoberturaPadraoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - CoberturaPadraoDb coberturaPadraoDb = base.FindEntityById(id); - if (coberturaPadraoDb == null) - { - return; - } - base.Delete(coberturaPadraoDb); - } - - public List Find() - { - List list = base.All().ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public CoberturaPadrao FindById(long id) - { - CoberturaPadraoDb coberturaPadraoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(coberturaPadraoDb); - } - - public List FindByRamoId(long id) - { - List list = ( - from x in base.All() - where x.IdRamo == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public CoberturaPadrao Merge(CoberturaPadrao coberturaPadrao) - { - CoberturaPadraoDb coberturaPadraoDb = ApplicationMapper.Mapper.Map(coberturaPadrao); - base.Merge(coberturaPadraoDb); - return ApplicationMapper.Mapper.Map(coberturaPadraoDb); - } - - public CoberturaPadrao SaveOrUpdate(CoberturaPadrao coberturaPadrao) - { - CoberturaPadraoDb coberturaPadraoDb = ApplicationMapper.Mapper.Map(coberturaPadrao); - this.SaveOrUpdate(coberturaPadraoDb); - return ApplicationMapper.Mapper.Map(coberturaPadraoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs deleted file mode 100644 index f50d4ee..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs +++ /dev/null @@ -1,174 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class CoberturaRepository : GenericRepository, ICoberturaRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public CoberturaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List AddRange(List coberturas) - { - List coberturaDbs = ApplicationMapper.Mapper.Map, List>(coberturas); - base.AddRange(coberturaDbs); - return ApplicationMapper.Mapper.Map, List>(coberturaDbs); - } - - public void Delete(long id) - { - CoberturaDb coberturaDb = base.FindEntityById(id); - if (coberturaDb == null) - { - return; - } - base.Delete(coberturaDb); - } - - public void DeletebyItem(long id) - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Format("DELETE FROM cobertura WHERE iditem = {0}", id); - sqlCommand.ExecuteNonQuery(); - } - } - } - - public void DeleteRange(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Item.Id) - select x).ToList(); - if (list.Count == 0) - { - return; - } - base.DeleteRange(list); - } - - public Cobertura FindById(long id) - { - CoberturaDb coberturaDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(coberturaDb); - } - - public List FindByItemId(long id) - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT * FROM coberturapadrao;"; - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - sqlCommand.CommandText = string.Format("SELECT * FROM cobertura WHERE iditem = {0}", id); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - } - } - } - List list = ( - from x in dataTable.AsEnumerable().ToList() - select new CoberturaPadrao() - { - Id = x.Field("idcoberturapadrao"), - IdRamo = (x.Field("idramo") != null ? x.Field("idramo") : (long)0), - Descricao = x.Field("descricao") - }).ToList(); - return dataTable1.AsEnumerable().ToList().Select((DataRow x) => { - Cobertura cobertura = new Cobertura() - { - Id = x.Field("idcobertura"), - CoberturaPadrao = (x.Field("idcoberturapadrao") == null ? null : list.FirstOrDefault((CoberturaPadrao c) => c.Id == x.Field("idcoberturapadrao"))), - Item = new Item() - { - Id = x.Field("iditem") - } - }; - decimal? nullable = x.Field("franquia"); - cobertura.Franquia = nullable.GetValueOrDefault(); - nullable = x.Field("premio"); - cobertura.Premio = nullable.GetValueOrDefault(); - nullable = x.Field("lmi"); - cobertura.Lmi = nullable.GetValueOrDefault(); - cobertura.Observacao = x.Field("observacao"); - return cobertura; - }).ToList(); - } - - public Cobertura Merge(Cobertura cobertura) - { - CoberturaDb coberturaDb = ApplicationMapper.Mapper.Map(cobertura); - base.Merge(coberturaDb); - return ApplicationMapper.Mapper.Map(coberturaDb); - } - - public List MergeRange(List coberturas) - { - List coberturaDbs = ApplicationMapper.Mapper.Map, List>(coberturas); - CoberturaRepository coberturaRepository = this; - coberturaDbs.ForEach(new Action(coberturaRepository.Merge)); - return ApplicationMapper.Mapper.Map, List>(coberturaDbs); - } - - public Cobertura SaveOrUpdate(Cobertura cobertura) - { - CoberturaDb coberturaDb = ApplicationMapper.Mapper.Map(cobertura); - this.SaveOrUpdate(coberturaDb); - return ApplicationMapper.Mapper.Map(coberturaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs deleted file mode 100644 index d06bfaf..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs +++ /dev/null @@ -1,46 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class CondicaoRepasseRepository : GenericRepository, ICondicaoRepasseRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public CondicaoRepasseRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public CondicaoRepasse FindById(long id) - { - CondicaoRepasseDb condicaoRepasseDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(condicaoRepasseDb); - } - - public CondicaoRepasse Merge(CondicaoRepasse condicaoRepasse) - { - CondicaoRepasseDb condicaoRepasseDb = ApplicationMapper.Mapper.Map(condicaoRepasse); - base.Merge(condicaoRepasseDb); - return ApplicationMapper.Mapper.Map(condicaoRepasseDb); - } - - public CondicaoRepasse SaveOrUpdate(CondicaoRepasse condicaoRepasse) - { - CondicaoRepasseDb condicaoRepasseDb = ApplicationMapper.Mapper.Map(condicaoRepasse); - this.SaveOrUpdate(condicaoRepasseDb); - return ApplicationMapper.Mapper.Map(condicaoRepasseDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs deleted file mode 100644 index 2410399..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs +++ /dev/null @@ -1,101 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ConfigExtratoImportRepository : GenericRepository, IConfigExtratoImportRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ConfigExtratoImportRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find(bool ativo) - { - return ( - from x in this._unitOfWork.Session.CreateQuery("from ConfigExtratoImportDb \r\n where ativo IS NULL OR ativo != '1'").List() - select new ConfigExtratoImport() - { - Id = x.Id, - IdSeguradora = x.IdSeguradora, - Codigo = x.Codigo, - Descricao = x.Descricao, - Ativo = x.Ativo - }).ToList(); - } - - public List Find() - { - return ( - from x in this._unitOfWork.Session.CreateQuery("from ConfigExtratoImportDb").List() - select new ConfigExtratoImport() - { - Id = x.Id, - IdSeguradora = x.IdSeguradora, - Codigo = x.Codigo, - Descricao = x.Descricao, - Ativo = x.Ativo - }).ToList(); - } - - public ConfigExtratoImport FindById(long id) - { - ConfigExtratoImportDb configExtratoImportDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(configExtratoImportDb); - } - - public List FindBySeguradora(long id) - { - return ( - from x in this._unitOfWork.Session.CreateQuery(string.Format("from ConfigExtratoImportDb where IdSeguradora = {0}", id)).List() - select new ConfigExtratoImport() - { - Id = x.Id, - IdSeguradora = x.IdSeguradora, - Codigo = x.Codigo, - Descricao = x.Descricao, - Ativo = x.Ativo - }).ToList(); - } - - public Gestor.Model.Domain.Seguros.ConfigExtratoImport Merge(Gestor.Model.Domain.Seguros.ConfigExtratoImport ConfigExtratoImport) - { - ConfigExtratoImportDb configExtratoImportDb = ApplicationMapper.Mapper.Map(ConfigExtratoImport); - base.Merge(configExtratoImportDb); - return ApplicationMapper.Mapper.Map(configExtratoImportDb); - } - - public List MergeRange(List configExtratoImport) - { - List configExtratoImportDbs = ApplicationMapper.Mapper.Map, List>(configExtratoImport); - ConfigExtratoImportRepository configExtratoImportRepository = this; - configExtratoImportDbs.ForEach(new Action(configExtratoImportRepository.Merge)); - return ApplicationMapper.Mapper.Map, List>(configExtratoImportDbs); - } - - public Gestor.Model.Domain.Seguros.ConfigExtratoImport SaveOrUpdate(Gestor.Model.Domain.Seguros.ConfigExtratoImport ConfigExtratoImport) - { - ConfigExtratoImportDb configExtratoImportDb = ApplicationMapper.Mapper.Map(ConfigExtratoImport); - this.SaveOrUpdate(configExtratoImportDb); - return ApplicationMapper.Mapper.Map(configExtratoImportDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs deleted file mode 100644 index 5d6f539..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs +++ /dev/null @@ -1,61 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Configuracoes; -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.Configuracoes; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ConfiguracaoRepository : GenericRepository, IConfiguracaoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ConfiguracaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List BuscarConfiguracoes() - { - return ApplicationMapper.Mapper.Map, List>(base.All().ToList()); - } - - public void Delete(long id) - { - ConfiguracaoSistemaDb configuracaoSistemaDb = base.FindEntityById(id); - if (configuracaoSistemaDb == null) - { - return; - } - base.Delete(configuracaoSistemaDb); - } - - public ConfiguracaoSistema Find(Configuracao configuracao) - { - ConfiguracaoSistemaDb configuracaoSistemaDb = base.All().FirstOrDefault((ConfiguracaoSistemaDb x) => (int)x.Configuracao == (int)configuracao); - return ApplicationMapper.Mapper.Map(configuracaoSistemaDb); - } - - public ConfiguracaoSistema Merge(ConfiguracaoSistema configuracao) - { - ConfiguracaoSistemaDb configuracaoSistemaDb = ApplicationMapper.Mapper.Map(configuracao); - base.Merge(configuracaoSistemaDb); - return ApplicationMapper.Mapper.Map(configuracaoSistemaDb); - } - - public ConfiguracaoSistema SaveOrUpdate(ConfiguracaoSistema configuracao) - { - ConfiguracaoSistemaDb configuracaoSistemaDb = ApplicationMapper.Mapper.Map(configuracao); - this.SaveOrUpdate(configuracaoSistemaDb); - return ApplicationMapper.Mapper.Map(configuracaoSistemaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs deleted file mode 100644 index c909e73..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs +++ /dev/null @@ -1,66 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ConsorcioRepository : GenericRepository, IConsorcioRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ConsorcioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public void DeleteRange(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Item.Id) - select x).ToList(); - base.DeleteRange(list); - } - - public Consorcio Find(long id) - { - ConsorcioDb consorcioDb = base.All().FirstOrDefault((ConsorcioDb x) => x.Item.Id == id) ?? new ConsorcioDb(); - return ApplicationMapper.Mapper.Map(consorcioDb); - } - - public Consorcio FindById(long id) - { - ConsorcioDb consorcioDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(consorcioDb); - } - - public Consorcio Merge(Consorcio consorcio) - { - ConsorcioDb consorcioDb = ApplicationMapper.Mapper.Map(consorcio); - base.Merge(consorcioDb); - return ApplicationMapper.Mapper.Map(consorcioDb); - } - - public Consorcio SaveOrUpdate(Consorcio consorcio) - { - ConsorcioDb consorcioDb = ApplicationMapper.Mapper.Map(consorcio); - this.SaveOrUpdate(consorcioDb); - return ApplicationMapper.Mapper.Map(consorcioDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs deleted file mode 100644 index 15ac6ff..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs +++ /dev/null @@ -1,73 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Financeiro; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Financeiro; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ControleFinanceiroRepository : GenericRepository, IControleFinanceiroRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ControleFinanceiroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - ControleFinanceiroDb controleFinanceiroDb = base.FindEntityById(id); - if (controleFinanceiroDb == null) - { - return; - } - IQueryable lancamentoDbs = - from x in this._unitOfWork.Query() - where x.Controle.Id == id - select x; - if (lancamentoDbs.Any()) - { - this._unitOfWork.Repository().DeleteRange(lancamentoDbs); - } - base.Delete(controleFinanceiroDb); - } - - public List FindByFornecedor(long id) - { - List list = ( - from x in base.All() - where x.Fornecedor.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public ControleFinanceiro FindById(long id) - { - ControleFinanceiroDb controleFinanceiroDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(controleFinanceiroDb); - } - - public ControleFinanceiro Merge(ControleFinanceiro controle) - { - ControleFinanceiroDb controleFinanceiroDb = ApplicationMapper.Mapper.Map(controle); - base.Merge(controleFinanceiroDb); - return ApplicationMapper.Mapper.Map(controleFinanceiroDb); - } - - public ControleFinanceiro SaveOrUpdate(ControleFinanceiro controle) - { - ControleFinanceiroDb controleFinanceiroDb = ApplicationMapper.Mapper.Map(controle); - this.SaveOrUpdate(controleFinanceiroDb); - return ApplicationMapper.Mapper.Map(controleFinanceiroDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs deleted file mode 100644 index 6f06aaf..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs +++ /dev/null @@ -1,68 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ControleRepository : GenericRepository, IControleRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ControleRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public IEnumerable FindByCustomerId(long id) - { - return - from c in ( - from c in base.All() - where c.Cliente.Id == id - select c).ToList() - select c.Id; - } - - public Controle FindById(long id) - { - ControleDb controleDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(controleDb); - } - - public Controle Merge(Controle controle) - { - ControleDb controleDb = ApplicationMapper.Mapper.Map(controle); - base.Merge(controleDb); - return ApplicationMapper.Mapper.Map(controleDb); - } - - public Controle SaveOrUpdate(Controle controle) - { - ControleDb controleDb = ApplicationMapper.Mapper.Map(controle); - this.SaveOrUpdate(controleDb); - return ApplicationMapper.Mapper.Map(controleDb); - } - - public IEnumerable SelectDocumentIds(long id) - { - return - from x in base.All().First((ControleDb c) => c.Id == id).Documentos - select x.Id; - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs deleted file mode 100644 index 5d23145..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs +++ /dev/null @@ -1,161 +0,0 @@ -using AutoMapper; -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.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ControleSinistroRepository : GenericRepository, IControleSinistroRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ControleSinistroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - ControleSinistroDb controleSinistroDb = base.FindEntityById(id); - if (controleSinistroDb == null) - { - return; - } - base.Delete(controleSinistroDb); - } - - public void DeleteByItem(long id) - { - object connection; - List list = ( - from s in this._unitOfWork.Query() - where s.ControleSinistro.Item.Id == id - select s).ToList(); - 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("DELETE FROM controlesinistro WHERE iditem = {0}", id); - sqlCommand.ExecuteNonQuery(); - list.ForEach((SinistroDb x) => { - sqlCommand.CommandText = string.Format("DELETE FROM sinistro WHERE idsinistro = {0}", x.Id); - sqlCommand.ExecuteNonQuery(); - sqlCommand.CommandText = string.Format("DELETE FROM sinistroauto WHERE idsinistro = {0}", x.Id); - sqlCommand.ExecuteNonQuery(); - sqlCommand.CommandText = string.Format("DELETE FROM sinistrovida WHERE idsinistro = {0}", x.Id); - sqlCommand.ExecuteNonQuery(); - }); - } - } - } - - public void DeleteRange(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Item.Id) - select x).ToList(); - if (list == null || list.Count == 0) - { - return; - } - base.DeleteRange(list); - } - - public bool DocumentoHasSinistro(long id) - { - return base.All().Any((ControleSinistroDb x) => x.Item.Documento.Id == id); - } - - public ControleSinistro FindById(long id) - { - ControleSinistroDb controleSinistroDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(controleSinistroDb); - } - - public List FindByIdItem(long id) - { - List list = ( - from c in base.All() - where c.Item.Id == id - select c into x - select new ControleSinistro() - { - Id = x.Id, - DataSinistro = x.DataSinistro, - Item = ApplicationMapper.Mapper.Map(x.Item) - }).ToList(); - list.ForEach((ControleSinistro x) => x.Sinistros = (new SinistroRepository(this._unitOfWork)).FindByControleId(x.Id)); - return list; - } - - public List HasSinistro(List ids) - { - List nums = new List(); - while (ids.Count > 0) - { - List list = ids.Take(1000).ToList(); - List condicaos = new List() - { - new Condicao() - { - Campo = "d.idcontrole", - Valores = list.CriarValor() - } - }; - DataTable dataTable = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT DISTINCT d.idcontrole as id FROM controlesinistro c CROSS APPLY (select idcontrole FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE i.iditem = c.iditem) d WHERE ", ""); - if (dataTable != null && dataTable.Rows.Count > 0) - { - nums.AddRange(dataTable.AsEnumerable().Select((DataRow x) => x.Field("id")).ToList()); - } - ids = (list.Count < 1000 ? new List() : ids.Except(list).ToList()); - } - return nums; - } - - public bool HasSinistro(long id) - { - return base.All().Any((ControleSinistroDb x) => x.Item.Documento.Controle.Id == id); - } - - public ControleSinistro Merge(ControleSinistro controleSinistro) - { - ControleSinistroDb controleSinistroDb = ApplicationMapper.Mapper.Map(controleSinistro); - base.Merge(controleSinistroDb); - return ApplicationMapper.Mapper.Map(controleSinistroDb); - } - - public ControleSinistro SaveOrUpdate(ControleSinistro controleSinistro) - { - ControleSinistroDb controleSinistroDb = ApplicationMapper.Mapper.Map(controleSinistro); - this.SaveOrUpdate(controleSinistroDb); - return ApplicationMapper.Mapper.Map(controleSinistroDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs deleted file mode 100644 index 0e7d668..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs +++ /dev/null @@ -1,75 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Ferramentas; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class CredencialRepository : GenericRepository, ICredencialRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public CredencialRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - CredencialDb credencialDb = base.FindEntityById(id); - if (credencialDb == null) - { - return; - } - credencialDb.Excluido = true; - base.Merge(credencialDb); - } - - public List Find(long idEmpresa) - { - List list = ( - from x in base.All() - where x.IdEmpresa == idEmpresa && !x.Excluido - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List Find(string filter, long idEmpresa) - { - CredencialRepository.u003cu003ec__DisplayClass7_0 variable = null; - IQueryable credencialDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(CredencialDb), "x"); - List list = credencialDbs.Where(Expression.Lambda>(Expression.AndAlso(Expression.Equal(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CredencialDb).GetMethod("get_Excluido").MethodHandle)), Expression.Constant(false, typeof(bool))), Expression.OrElse(Expression.OrElse(Expression.AndAlso(Expression.Equal(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CredencialDb).GetMethod("get_IdEmpresa").MethodHandle)), Expression.Field(Expression.Constant(variable, typeof(CredencialRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(CredencialRepository.u003cu003ec__DisplayClass7_0).GetField("idEmpresa").FieldHandle))), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CredencialDb).GetMethod("get_Descricao").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(CredencialRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(CredencialRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) })), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CredencialDb).GetMethod("get_Email").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(CredencialRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(CredencialRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) })), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(CredencialDb).GetMethod("get_Dominio").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(CredencialRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(CredencialRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) }))), new ParameterExpression[] { parameterExpression })).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Credencial FindById(long id) - { - CredencialDb credencialDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(credencialDb); - } - - public Credencial Merge(Credencial credencial) - { - CredencialDb credencialDb = ApplicationMapper.Mapper.Map(credencial); - base.Merge(credencialDb); - return ApplicationMapper.Mapper.Map(credencialDb); - } - - public Credencial SaveOrUpdate(Credencial credencial) - { - CredencialDb credencialDb = ApplicationMapper.Mapper.Map(credencial); - this.SaveOrUpdate(credencialDb); - return ApplicationMapper.Mapper.Map(credencialDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs deleted file mode 100644 index 3e57d4d..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs +++ /dev/null @@ -1,315 +0,0 @@ -using AutoMapper; -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.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class CriticaApoliceRepository : GenericRepository, ICriticaApoliceRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - private const string _commandoCritica = "SELECT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE"; - - private const string _commandoCriticaVinculo = "SELECT DISTINCT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN vendedorparcela vp on vp.iddocumento = d.iddocumento WHERE"; - - public CriticaApoliceRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List BuscarUsuarioCritica(DateTime inicio, DateTime fim, bool criticado = false, long idempresa = 0L) - { - List usuarios; - object connection; - string str = (criticado ? " AND i.critica = '1'" : " AND i.critica = '0'"); - string str1 = (idempresa == 0 ? "" : string.Format(" AND u.idempresa = {0}", idempresa)); - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliarUsuario(sqlCommand); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT i.idusuario FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN usuario u on u.idusuario = i.idusuario ", string.Format("WHERE CAST(i.dataimportacao AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(i.dataimportacao AS DATE) <= '{1:yyyy-MM-dd}' AND (d.excluido IS NULL OR d.excluido != '1') {2} {3}", new object[] { inicio, fim, str1, str })); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - goto Label0; - } - else - { - usuarios = new List(); - } - } - } - return usuarios; - List list = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idusuario")).ToList(); - return ( - from x in Auxiliar.Usuarios - where list.Contains(x.Id) - select x).ToList(); - } - - public void Delete(long id) - { - CriticaApoliceDb criticaApoliceDb = base.All().FirstOrDefault((CriticaApoliceDb x) => x.Id == id); - if (criticaApoliceDb == null) - { - return; - } - base.Delete(criticaApoliceDb); - } - - public List Find(long usuario, DateTime inicio, DateTime fim, long vendedorCorretoraId, bool criticado = false, long idempresa = 0L, List vinculos = null, bool vendedorEmBranco = false, bool vinculoVendedorCritica = false) - { - Condicao condicao = new Condicao() - { - Campo = "i.idusuario", - Valores = usuario.CriarValor() - }; - Condicao condicao1 = new Condicao() - { - Campo = "i.critica", - Valores = (criticado ? "1".CriarValor() : "0".CriarValor()) - }; - Condicao condicao2 = new Condicao() - { - Campo = "c.idempresa", - Valores = idempresa.CriarValor() - }; - List condicaos = new List() - { - new Condicao() - { - Campo = "CAST(i.dataimportacao AS DATE)", - Valores = inicio.CriarValor(), - Operador = Operador.MaiorEIgual - }, - new Condicao() - { - Campo = "CAST(i.dataimportacao AS DATE)", - Valores = fim.CriarValor(), - Operador = Operador.MenorEIgual - }, - new Condicao() - { - Campo = " d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = " d.excluido", - Valores = "1".CriarValor(), - Grupo = 1, - Operador = Operador.Diferente, - Operacao = Operacao.Or - } - }; - string str = (vinculos == null || vinculos.Count <= 0 ? "SELECT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE" : "SELECT DISTINCT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN vendedorparcela vp on vp.iddocumento = d.iddocumento WHERE"); - if (vinculos != null && vinculos.Count > 0) - { - if (vendedorEmBranco) - { - condicaos.Add(new Condicao() - { - Campo = "vp.idvendedor", - Valores = null, - Operacao = Operacao.Or, - Grupo = 3 - }); - } - condicaos.Add(new Condicao() - { - Campo = "vp.idvendedor", - Valores = (vinculoVendedorCritica & vendedorEmBranco ? vendedorCorretoraId.CriarValor() : ( - from x in vinculos - select x.Vendedor.Id).ToList().CriarValor()), - Grupo = 3 - }); - } - if (usuario > (long)0) - { - condicaos.Add(condicao); - } - if (idempresa > (long)0) - { - condicaos.Add(condicao2); - } - condicaos.Add(condicao1); - return this.Select(condicaos.CreateParameters(0), str); - } - - public List Find(DateTime inicio, DateTime fim, long idempresa = 0L) - { - Condicao condicao = new Condicao() - { - Campo = "c.idempresa", - Valores = idempresa.CriarValor() - }; - List condicaos = new List() - { - new Condicao() - { - Campo = "CAST(i.dataimportacao AS DATE)", - Valores = inicio.CriarValor(), - Operador = Operador.MaiorEIgual - }, - new Condicao() - { - Campo = "CAST(i.dataimportacao AS DATE)", - Valores = fim.CriarValor(), - Operador = Operador.MenorEIgual - }, - new Condicao() - { - Campo = " d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = " d.excluido", - Valores = "1".CriarValor(), - Grupo = 1, - Operador = Operador.Diferente, - Operacao = Operacao.Or - } - }; - if (idempresa > (long)0) - { - condicaos.Add(condicao); - } - return this.Select(condicaos.CreateParameters(0), "SELECT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE"); - } - - public List Find(long id) - { - List list = this._unitOfWork.Session.CreateQuery(string.Format("from CriticaApoliceDb WHERE iddocumento = {0} AND (Critica IS NULL OR Critica != '1')", id)).List().ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public CriticaApolice FindByApolice(long id) - { - CriticaApoliceDb criticaApoliceDb = base.All().FirstOrDefault((CriticaApoliceDb x) => x.Documento.Id == id); - return ApplicationMapper.Mapper.Map(criticaApoliceDb); - } - - public CriticaApolice FindById(long id) - { - CriticaApoliceDb criticaApoliceDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(criticaApoliceDb); - } - - public List FindDuo(long id, DateTime vigencia) - { - return this.Select((new List() - { - new Condicao() - { - Campo = " c.idcliente", - Valores = id.CriarValor() - }, - new Condicao() - { - Campo = " CAST(d.vigencia1 AS DATE)", - Valores = vigencia.CriarValor(), - Operador = Operador.Igual - }, - new Condicao() - { - Campo = " i.critica", - Valores = 1.CriarValor(), - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = " d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = " d.excluido", - Valores = "1".CriarValor(), - Grupo = 1, - Operador = Operador.Diferente, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = " c.idramo", - Valores = 5.CriarValor(), - Grupo = 2, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = " c.idramo", - Valores = 1.CriarValor(), - Grupo = 2, - Operacao = Operacao.Or - } - }).CreateParameters(0), "SELECT i.idimportacao as id, i.iddocumento, i.idusuario, i.critica, i.dataimportacao, i.tipo, d.contrato as apolice, d.proposta, c.idcontrole, c.idciaseg, c.idramo, cl.idcliente, cl.nome as cliente, cl.documentoprincipal, cl.cgccpf as documento, cl.rne, cl.cei, d.vigencia1, d.vigencia2, i.critica, i.idusuariocritica, i.datacritica FROM importacao i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE"); - } - - public List FindImport(long id) - { - List list = this._unitOfWork.Session.CreateQuery(string.Format("from CriticaApoliceDb WHERE iddocumento = {0}", id)).List().ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public CriticaApolice Merge(CriticaApolice documento) - { - CriticaApoliceDb criticaApoliceDb = ApplicationMapper.Mapper.Map(documento); - base.Merge(criticaApoliceDb); - return ApplicationMapper.Mapper.Map(criticaApoliceDb); - } - - public CriticaApolice SaveOrUpdate(CriticaApolice documento) - { - CriticaApoliceDb criticaApoliceDb = ApplicationMapper.Mapper.Map(documento); - this.SaveOrUpdate(criticaApoliceDb); - return ApplicationMapper.Mapper.Map(criticaApoliceDb); - } - - private List Select(SqlQueryCondition condition, string command) - { - return this._unitOfWork.Select(condition, command, "").MapImportacao(); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs deleted file mode 100644 index 54af174..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs +++ /dev/null @@ -1,99 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -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.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class DetalheExtratoRepository : GenericRepository, IDetalheExtratoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public DetalheExtratoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public bool Completo(long id) - { - List statusParcelas = new List() - { - StatusParcela.BaixadaCritica, - StatusParcela.Baixada, - StatusParcela.BaixadaDiferencaPercentual, - StatusParcela.BaixadaAnteriormente, - StatusParcela.BaixadaManualmente, - StatusParcela.DesconsideradaUsuario, - StatusParcela.DesconsideradaSistema - }; - return ( - from x in base.All() - where x.Extrato.Id == id - select x).All((DetalheExtratoDb x) => statusParcelas.Contains(x.Status.Value)); - } - - public void Delete(long id) - { - DetalheExtratoDb detalheExtratoDb = base.FindEntityById(id); - if (detalheExtratoDb == null) - { - return; - } - base.Delete(detalheExtratoDb); - } - - public List Find(long id) - { - List list = ( - from x in base.All() - where x.Extrato.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public DetalheExtrato FindById(long id) - { - DetalheExtratoDb detalheExtratoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(detalheExtratoDb); - } - - public List FindByLongId(long? id) - { - List list = ( - from x in base.All() - where (long?)x.Extrato.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public DetalheExtrato FindByParcelaId(long id) - { - DetalheExtratoDb detalheExtratoDb = base.All().FirstOrDefault((DetalheExtratoDb x) => x.Parcela == (long?)id); - return ApplicationMapper.Mapper.Map(detalheExtratoDb); - } - - public DetalheExtrato Merge(DetalheExtrato parcela) - { - DetalheExtratoDb detalheExtratoDb = ApplicationMapper.Mapper.Map(parcela); - base.Merge(detalheExtratoDb); - return ApplicationMapper.Mapper.Map(detalheExtratoDb); - } - - public DetalheExtrato SaveOrUpdate(DetalheExtrato parcela) - { - DetalheExtratoDb detalheExtratoDb = ApplicationMapper.Mapper.Map(parcela); - this.SaveOrUpdate(detalheExtratoDb); - return ApplicationMapper.Mapper.Map(detalheExtratoDb); - } - } -} \ No newline at end of file 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, IDocumentoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - private const string _commandoDocumento = "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE "; - - private const string _comandoVendedores = "SELECT DISTINCT vp.IDPARCELA, vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor, p.idsubtipo FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento LEFT OUTER JOIN parcela p on p.idparcela = vp.idparcela WHERE "; - - private const string _comandoArquivo = "SELECT DISTINCT a.idnewarquivodigital, a.descricao, ISNULL(s.Status ,0) as Status, s.assinado, s.DocumentoId, s.id, s.UsuarioId, s.Enviado FROM newarquivodigital a LEFT OUTER JOIN ArquivoParaAssinatura s on s.IndiceId = a.idnewarquivodigital WHERE "; - - private const string ComandoEndereco = "SELECT DISTINCT idcliend, cep, cidade, uf as estado, idcliente FROM cliendereco WHERE (ORDEM = '1' OR PADRAO = '1') "; - - private const string ComandoTelefone = "SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 "; - - private const string ComandoEmail = "SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') "; - - public DocumentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public bool AtualizarNumero(long id, string numero, string endosso, int tipoDocumento) - { - DocumentoDb documentoDb = base.FindEntityById(id); - if (documentoDb == null) - { - return false; - } - if (!documentoDb.Emissao.HasValue) - { - return true; - } - if (tipoDocumento == 0) - { - documentoDb.Apolice = numero; - } - else if (tipoDocumento == 1) - { - documentoDb.Apolice = numero; - documentoDb.Endosso = endosso; - } - base.Merge(documentoDb); - return true; - } - - public List Auditoria(Filtros filtro) - { - List documentos; - object connection; - string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", - from v in filtro.Status - select v), ")")); - string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", - from v in filtro.Negocio - select v), ")")); - string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", - from v in filtro.Seguradoras - select v), ")")); - string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", - from v in filtro.Ramos - select v), ")")); - string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", - from v in filtro.Produtos - select v), ")")); - string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", - from v in filtro.Vendedores - select v), ")")); - string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", - from v in filtro.TipoVendedor - select v), ")")); - string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", - from v in filtro.Estipulantes - select v), ")")); - string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - DataTable dataTable2 = new DataTable(); - DataTable dataTable3 = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.datacontrole, d.idstatus, d.pasta, d.n_parc, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente ", str6, " WHERE (d.excluido IS NULL OR d.excluido = 0) "); - string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; - string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; - string str12 = "SELECT DISTINCT vp.idparcela, vp.iddocumento as id, ISNULL(vp.vlrcomiss, 0) as recebida, vp.idsubtipo, vp.datarec as recebimento FROM parcela vp WHERE 1=1 "; - string str13 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL "; - sqlCommand.CommandText = string.Format("{0} {1} AND d.vigencia1 >= '{2:yyyy-MM-dd}' AND d.vigencia1 <= '{3:yyyy-MM-dd}' AND d.tiporecebimento = 1 {4} {5} {6} {7} {8} {9} {10}", new object[] { str9, str8, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5 }); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - string str14 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat(str12, (filtro.ParcelasEspeciais.Any((FiltroTipoParcela x) => x.Selecionado) ? string.Concat(" AND vp.idsubtipo IN (1,", string.Join(",", - from x in filtro.ParcelasEspeciais - where x.Selecionado - select x into v - select (int)v.Tipo), ")") : " AND vp.idsubtipo = 1 "), str14); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - } - string str15 = (dataTable.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null) ? string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")") : ""); - DataTable dataTable4 = new DataTable(); - sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str15, " ", str5 }); - using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) - { - sqlDataAdapter2.SelectCommand = sqlCommand; - sqlDataAdapter2.Fill(dataTable4); - } - List dataRows3 = new List(); - foreach (DataRow row in dataTable.Rows) - { - string str16 = string.Format("id = {0}", row["id"]); - DataRow[] dataRowArray = dataTable1.Select(str16); - decimal num = Math.Round(((row.Field("liquido") + (row.Field("adinacomiss") == "1" ? row.Field("liquido") : decimal.Zero)) * row.Field("comissao")) * new decimal(1, 0, 0, false, 2), 2); - decimal num1 = ((IEnumerable)dataRowArray).Sum((DataRow x) => x.Field("recebida")); - decimal? tolerancia = Auxiliar.Seguradoras.First((Seguradora p) => p.Id == row.Field("idseguradora")).Tolerancia; - if ((num - num1) > tolerancia.GetValueOrDefault()) - { - if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) - { - continue; - } - string str17 = string.Format("idcontrole = {0}", row["idcontrole"]); - DataRow[] dataRowArray1 = dataTable4.Select(str17); - if (dataRowArray1.Length == 0) - { - continue; - } - row["idvendedor"] = dataRowArray1[0][1]; - } - else - { - dataRows3.Add(row); - } - } - dataRows3.ForEach((DataRow x) => dataTable.Rows.Remove(x)); - if (dataTable.Rows.Count != 0) - { - str14 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat(str11, " ", str14); - using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) - { - sqlDataAdapter3.SelectCommand = sqlCommand; - sqlDataAdapter3.Fill(dataTable2); - } - string str18 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); - sqlCommand.CommandText = string.Concat(str13, " ", str18); - using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) - { - sqlDataAdapter4.SelectCommand = sqlCommand; - sqlDataAdapter4.Fill(dataTable3); - goto Label0; - } - } - else - { - documentos = new List(); - } - } - else - { - documentos = new List(); - } - } - } - return documentos; - Label0: - return dataTable.AsEnumerable().ToList().Select((DataRow x) => { - Func func2 = null; - Documento documento = new Documento() - { - Id = x.Field("id"), - Controle = new Controle() - { - IdEmpresa = x.Field("idempresa"), - Cliente = new Cliente() - { - Id = x.Field("idcliente"), - Nome = x.Field("cliente"), - IdEmpresa = x.Field("idempresa"), - Pasta = x.Field("pastacliente"), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) - }, - Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), - Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), - Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), - AssistenciaId = x.Field("AssistenciaId") - }, - TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela), - AdicionalComiss = x.Field("adinacomiss") == "1", - Apolice = x.Field("apolice"), - Endosso = x.Field("endosso"), - Comissao = x.Field("comissao"), - Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), - PremioLiquido = x.Field("liquido"), - PremioTotal = x.Field("total"), - PremioAdicional = x.Field("adicional"), - Vigencia2 = x.Field("vigenciafinal") - }; - DateTime? nullable = x.Field("vigenciainicial"); - documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); - documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); - documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { - List list = dataTable2.AsEnumerable().ToList(); - Func u003cu003e9_32 = func2; - if (u003cu003e9_32 == null) - { - Func func = (DataRow d) => d.Field("id") == x.Field("id"); - Func func1 = func; - func2 = func; - u003cu003e9_32 = func1; - } - IEnumerable dataRows = list.Where(u003cu003e9_32); - Func u003cu003e9_4033 = DocumentoRepository.u003cu003ec.u003cu003e9__40_33; - if (u003cu003e9_4033 == null) - { - u003cu003e9_4033 = (DataRow d) => d.Field("idvendedor"); - DocumentoRepository.u003cu003ec.u003cu003e9__40_33 = u003cu003e9_4033; - } - return dataRows.Select(u003cu003e9_4033).ToList().Contains(v.Id); - }).ToList(); - documento.Tipo = x.Field("tipo"); - IEnumerable dataRows1 = - from p in dataTable1.AsEnumerable().ToList() - where p.Field("id") == x.Field("id") - select p; - Func u003cu003e9_4025 = DocumentoRepository.u003cu003ec.u003cu003e9__40_25; - if (u003cu003e9_4025 == null) - { - u003cu003e9_4025 = (DataRow p) => new Parcela() - { - Id = p.Field("idparcela"), - ValorComissao = p.Field("recebida"), - DataRecebimento = p.Field("recebimento"), - SubTipo = (p.Field("idsubtipo") == null ? SubTipo.ParcelaNormal : (SubTipo)Enum.Parse(typeof(SubTipo), p.Field("idsubtipo").ToString())) - }; - DocumentoRepository.u003cu003ec.u003cu003e9__40_25 = u003cu003e9_4025; - } - documento.Parcelas = new ObservableCollection(dataRows1.Select(u003cu003e9_4025).ToList()); - documento.DataControle = x.Field("datacontrole"); - documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); - IEnumerable dataRows2 = - from i in dataTable3.AsEnumerable().ToList() - where i.Field("idcontrole") == x.Field("idcontrole") - select i; - Func u003cu003e9_4028 = DocumentoRepository.u003cu003ec.u003cu003e9__40_28; - if (u003cu003e9_4028 == null) - { - u003cu003e9_4028 = (DataRow i) => new Item() - { - Id = i.Field("iditem"), - Descricao = i.Field("descricao") - }; - DocumentoRepository.u003cu003ec.u003cu003e9__40_28 = u003cu003e9_4028; - } - documento.ItensAtivo = new List(dataRows2.Select(u003cu003e9_4028).ToList()); - documento.Pasta = x.Field("Pasta"); - documento.NumeroParcelas = (x.Field("n_parc") != null ? decimal.Parse(x.Field("n_parc").ToString()) : decimal.Zero); - return documento; - }).ToList(); - } - - private async Task> BuscaDocumentosPorCondicao(Filtros filtro, List condicao, bool buscaAssinaturas) - { - NegocioCorretora fieldValue; - Predicate predicate; - bool flag; - object connection; - bool count; - string str; - object vendedor; - bool count1; - bool flag1; - List itensAtivo; - object produto; - object obj; - object statu; - object banco; - List statusDocumentoAssinados; - bool flag2; - StatusAssinatura statusAssinatura; - NegocioCorretora negocioCorretora; - bool count2; - bool count3; - Documento vendedorParcelas; - Documento fieldValue1; - Predicate predicate1 = null; - Predicate predicate2 = null; - Predicate predicate3 = null; - Predicate predicate4 = null; - Predicate predicate5 = null; - List documentos = new List(); - SqlQueryCondition sqlQueryCondition = condicao.CreateParameters(0); - Vendedor vendedor1 = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { - if (v.IdEmpresa != (filtro.IdEmpresa == 0 ? (long)1 : filtro.IdEmpresa)) - { - return false; - } - return v.Corretora; - }); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - bool flag3 = await this.ExisteTabelasAssinatura(); - bool flag4 = flag3; - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - string str1 = "SELECT d.IDDOCUMENTO IdDocumento,c.IDCONTROLE IdControle,c.IDEMPRESA IdEmpresa,c.IDCLIENTE IdCliente,clie.NOME NomeCliente,clie.CGCCPF DocumentoCliente,clie.PASTA PastaCliente,clie.MalaDireta MalaDireta,cm.idclimail IdEmail,cm.email,ct.idclitelefone IdTelefone,ct.ddd Prefixo,ct.fone Numero,c.IDRAMO IdRamo,r.NOME NomeRamo,c.IDCIASEG IdCiaSeg,cia.NOME NomeCia,cia.NomeSocial NomeSocialCia,c.IDPRODUTO IdProduto,pr.NOME NomeProduto,d.idestipulante IdEstipulante, d.idestipulante2 IdEstipulante2, d.idestipulante3 IdEstipulante3, d.idestipulante4 IdEstipulante4, d.idestipulante5 IdEstipulante5, e.nome NomeEstipulante,d.idstatus IdStatus,s.NOME NomeStatus,vp.idtipovendedor IdTipoVendedor,vp.VREP PorcentagemRepasse,vp.idvendedor IdVendedor,v.NOME NomeVendedor,tv.DESCRICAO DescricaoTipovendedor,d.PROPOSTA Proposta,d.CONTRATO Apolice,d.apoconferida ApoliceConferida,d.PEDADIT PropostaEndosso,d.ADITAMENTO Endosso,d.ADINACOMIS AdicionalComissao,d.COM01 Comissao,d.idnegocio Negocio,d.NegocioCorretora NegocioCorretora,d.tiporecebimento TipoRecebimento,d.TIPO Tipo,d.PR_LIQ PremioLiquido,d.PR_TOTAL PremioTotal,d.PR_ADIC PremioAdicional,d.N_PARC NumeroParcelas,d.VIGENCIA1 VigenciaInicial,d.VIGENCIA2 VigenciaFinal,d.EMISSAO Emissao,d.REMESSA Remessa,d.SITUACAO Situacao,d.datacontrole DataControleDocumento,d.propassinada PropostaAssinada,d.PASTA PastaDocumento,d.CRI_DATA DataCriacao,d.idbanco IdBanco,b.NOMEBANCO NomeBanco,d.AGENCIA Agencia,d.conta Conta FROM documento d INNER JOIN controle c ON c.IDCONTROLE = d.IDCONTROLE INNER JOIN cliente clie ON clie.IDCLIENTE = c.IDCLIENTE INNER JOIN ramo r ON r.IDRAMO = c.IDRAMO INNER JOIN ciaseg cia ON cia.IDCIASEG = c.IDCIASEG LEFT JOIN codigobanco b ON b.IDCODIGOBANCO = d.IDBANCO LEFT JOIN produto pr ON pr.IDPRODUTO = c.IDPRODUTO LEFT JOIN estipulante e ON e.idestipulante = d.idestipulante LEFT JOIN status s ON s.idstatus = d.idstatus LEFT JOIN vendedorparcela vp ON vp.IDDOCUMENTO = d.IDDOCUMENTO LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN tipovendedor tv on tv.idtipovendedor = vp.idtipovendedor LEFT JOIN clitelefone ct ON ct.IDCLIENTE = c.IDCLIENTE LEFT JOIN parcela p ON p.idparcela = vp.idparcela LEFT JOIN climail cm ON cm.IDCLIENTE = c.IDCLIENTE WHERE "; - sqlCommand.CommandText = string.Concat(str1, " ", sqlQueryCondition.Condicao, " ORDER BY d.IDDOCUMENTO,d.IDCONTROLE,vp.idtipovendedor,vp.IDVENDEDOR"); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - TipoSeguro tipoSeguro = sqlDataReader.GetFieldValue("Situacao", true, true); - if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora")) - { - fieldValue = sqlDataReader.GetFieldValue("NegocioCorretora", true, true); - } - else - { - flag3 = tipoSeguro == TipoSeguro.Renovacao; - if (flag3) - { - flag3 = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio"); - } - negocioCorretora = (!flag3 || !(sqlDataReader.GetFieldValue("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); - fieldValue = negocioCorretora; - } - NegocioCorretora negocioCorretora1 = fieldValue; - List negocio = filtro.Negocio; - if (negocio != null) - { - count = negocio.Count > 0; - } - else - { - count = false; - } - if (!count || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora1)) - { - List estipulantes = new List(); - sqlDataReader.GetFieldValue("idestipulante", true, true); - if (sqlDataReader.GetFieldValue("idestipulante", true, true) != 0) - { - List estipulantes1 = estipulantes; - Estipulante nome = new Estipulante(); - List estipulantes2 = Auxiliar.Estipulantes; - Predicate predicate6 = predicate1; - if (predicate6 == null) - { - Predicate predicate7 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante", true, true); - predicate = predicate7; - predicate1 = predicate7; - predicate6 = predicate; - } - nome.Nome = estipulantes2.Find(predicate6).Nome; - estipulantes1.Add(nome); - } - sqlDataReader.GetFieldValue("idestipulante2", true, true); - if (sqlDataReader.GetFieldValue("idestipulante2", true, true) != 0) - { - List estipulantes3 = estipulantes; - Estipulante nome1 = new Estipulante(); - List estipulantes4 = Auxiliar.Estipulantes; - Predicate predicate8 = predicate2; - if (predicate8 == null) - { - Predicate predicate9 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante2", true, true); - predicate = predicate9; - predicate2 = predicate9; - predicate8 = predicate; - } - nome1.Nome = estipulantes4.Find(predicate8).Nome; - estipulantes3.Add(nome1); - } - sqlDataReader.GetFieldValue("idestipulante3", true, true); - if (sqlDataReader.GetFieldValue("idestipulante3", true, true) != 0) - { - List estipulantes5 = estipulantes; - Estipulante estipulante1 = new Estipulante(); - List estipulantes6 = Auxiliar.Estipulantes; - Predicate predicate10 = predicate3; - if (predicate10 == null) - { - Predicate predicate11 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante3", true, true); - predicate = predicate11; - predicate3 = predicate11; - predicate10 = predicate; - } - estipulante1.Nome = estipulantes6.Find(predicate10).Nome; - estipulantes5.Add(estipulante1); - } - sqlDataReader.GetFieldValue("idestipulante4", true, true); - if (sqlDataReader.GetFieldValue("idestipulante4", true, true) != 0) - { - List estipulantes7 = estipulantes; - Estipulante nome2 = new Estipulante(); - List estipulantes8 = Auxiliar.Estipulantes; - Predicate predicate12 = predicate4; - if (predicate12 == null) - { - Predicate predicate13 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante4", true, true); - predicate = predicate13; - predicate4 = predicate13; - predicate12 = predicate; - } - nome2.Nome = estipulantes8.Find(predicate12).Nome; - estipulantes7.Add(nome2); - } - sqlDataReader.GetFieldValue("idestipulante5", true, true); - if (sqlDataReader.GetFieldValue("idestipulante5", true, true) != 0) - { - List estipulantes9 = estipulantes; - Estipulante estipulante2 = new Estipulante(); - List estipulantes10 = Auxiliar.Estipulantes; - Predicate predicate14 = predicate5; - if (predicate14 == null) - { - Predicate predicate15 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante5", true, true); - predicate = predicate15; - predicate5 = predicate15; - predicate14 = predicate; - } - estipulante2.Nome = estipulantes10.Find(predicate14).Nome; - estipulantes9.Add(estipulante2); - } - if (estipulantes.Count > 0) - { - List estipulantes11 = estipulantes; - str = string.Join(" | ", - from estipulante in estipulantes11 - select estipulante.Nome); - } - else - { - str = ""; - } - string str2 = str; - long num = sqlDataReader.GetFieldValue("IdDocumento", true, true); - vendedorParcelas = documentos.Find((Documento d) => d.Id == num); - if (vendedorParcelas == null) - { - long num1 = sqlDataReader.GetFieldValue("IdControle", true, true); - long fieldValue2 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); - Documento documento1 = documentos.Find((Documento p) => p.Controle.Id == num1); - if (documento1 != null) - { - itensAtivo = documento1.ItensAtivo; - } - else - { - itensAtivo = null; - } - List items = itensAtivo; - if (items == null) - { - items = await this.BuscaItemsPorIdControle(num1); - } - List items1 = items; - fieldValue1 = new Documento() - { - Id = num - }; - Documento documento2 = fieldValue1; - Controle controle = new Controle() - { - Id = num1, - IdEmpresa = fieldValue2 - }; - Controle controle1 = controle; - Cliente cliente = new Cliente() - { - Id = sqlDataReader.GetFieldValue("IdCliente", true, true), - Nome = sqlDataReader.GetFieldValue("NomeCliente", true, true), - Documento = sqlDataReader.GetFieldValue("DocumentoCliente", true, true), - Pasta = sqlDataReader.GetFieldValue("PastaCliente", true, true) - }; - bool? fieldValue3 = sqlDataReader.GetFieldValue("MalaDireta", true, true); - cliente.MalaDireta = new bool?(fieldValue3.GetValueOrDefault(true)); - ObservableCollection observableCollection = new ObservableCollection(); - ClienteTelefone clienteTelefone = new ClienteTelefone() - { - Id = sqlDataReader.GetFieldValue("IdTelefone", true, true), - Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), - Numero = sqlDataReader.GetFieldValue("Numero", true, true) - }; - observableCollection.Add(clienteTelefone); - cliente.Telefones = observableCollection; - ObservableCollection observableCollection1 = new ObservableCollection(); - ClienteEmail clienteEmail = new ClienteEmail() - { - Id = sqlDataReader.GetFieldValue("IdEMail", true, true), - Email = sqlDataReader.GetFieldValue("Email", true, true) - }; - observableCollection1.Add(clienteEmail); - cliente.Emails = observableCollection1; - controle1.Cliente = cliente; - Controle controle2 = controle; - Ramo ramo = new Ramo() - { - Id = sqlDataReader.GetFieldValue("IdRamo", true, true), - Nome = sqlDataReader.GetFieldValue("NomeRamo", true, true) - }; - controle2.Ramo = ramo; - Controle controle3 = controle; - Seguradora seguradora = new Seguradora() - { - Id = sqlDataReader.GetFieldValue("IdCiaSeg", true, true), - Nome = sqlDataReader.GetFieldValue("NomeCia", true, true), - NomeSocial = sqlDataReader.GetFieldValue("NomeSocialCia", true, true) - }; - controle3.Seguradora = seguradora; - Controle controle4 = controle; - flag3 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdProduto"); - Controle controle5 = controle4; - if (flag3) - { - produto = null; - } - else - { - produto = new Gestor.Model.Domain.Seguros.Produto(); - ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("IdProduto", true, true); - ((Gestor.Model.Domain.Seguros.Produto)produto).Nome = sqlDataReader.GetFieldValue("NomeProduto", true, true); - } - controle5.Produto = (Gestor.Model.Domain.Seguros.Produto)produto; - documento2.Controle = controle; - Documento documento3 = fieldValue1; - bool flag5 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdEstipulante"); - Documento documento4 = documento3; - if (flag5) - { - obj = null; - } - else - { - obj = new Estipulante(); - ((DomainBase)obj).Id = sqlDataReader.GetFieldValue("IdEstipulante", true, true); - ((Estipulante)obj).Nome = sqlDataReader.GetFieldValue("NomeEstipulante", true, true); - } - documento4.Estipulante1 = (Estipulante)obj; - fieldValue1.Estipulantes = str2; - Documento documento5 = fieldValue1; - bool flag6 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdStatus"); - Documento documento6 = documento5; - if (flag6) - { - statu = null; - } - else - { - statu = new Status(); - ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("IdStatus", true, true); - ((Status)statu).Nome = sqlDataReader.GetFieldValue("NomeStatus", true, true); - } - documento6.Status = (Status)statu; - fieldValue1.TipoRecebimento = new TipoRecebimento?(sqlDataReader.GetFieldValue("TipoRecebimento", true, true)); - fieldValue1.Tipo = sqlDataReader.GetFieldValue("Tipo", true, true); - fieldValue1.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); - fieldValue1.Situacao = tipoSeguro; - Documento valueOrDefault = fieldValue1; - fieldValue3 = sqlDataReader.GetFieldValue("ApoliceConferida", true, true); - valueOrDefault.ApoliceConferida = fieldValue3.GetValueOrDefault(); - Documento valueOrDefault1 = fieldValue1; - fieldValue3 = sqlDataReader.GetFieldValue("PropostaAssinada", true, true); - valueOrDefault1.PropostaAssinada = fieldValue3.GetValueOrDefault(); - fieldValue1.Proposta = sqlDataReader.GetFieldValue("Proposta", true, true); - fieldValue1.Apolice = sqlDataReader.GetFieldValue("Apolice", true, true); - fieldValue1.PropostaEndosso = sqlDataReader.GetFieldValue("PropostaEndosso", true, true); - fieldValue1.Endosso = sqlDataReader.GetFieldValue("Endosso", true, true); - fieldValue1.Comissao = sqlDataReader.GetFieldValue("Comissao", true, true); - fieldValue1.PremioLiquido = sqlDataReader.GetFieldValue("PremioLiquido", true, true); - Documento valueOrDefault2 = fieldValue1; - fieldValue3 = sqlDataReader.GetFieldValue("AdicionalComissao", true, true); - valueOrDefault2.AdicionalComiss = fieldValue3.GetValueOrDefault(); - fieldValue1.PremioAdicional = sqlDataReader.GetFieldValue("PremioAdicional", true, true); - fieldValue1.PremioTotal = sqlDataReader.GetFieldValue("PremioTotal", true, true); - fieldValue1.NumeroParcelas = sqlDataReader.GetFieldValue("NumeroParcelas", true, true); - fieldValue1.Vigencia1 = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); - fieldValue1.Vigencia2 = sqlDataReader.GetFieldValue("VigenciaFinal", true, true); - fieldValue1.Emissao = sqlDataReader.GetFieldValue("Emissao", true, true); - fieldValue1.Remessa = sqlDataReader.GetFieldValue("Remessa", true, true); - fieldValue1.DataControle = sqlDataReader.GetFieldValue("DataControleDocumento", true, true); - fieldValue1.DataCriacao = sqlDataReader.GetFieldValue("DataCriacao", true, true); - fieldValue1.Pasta = sqlDataReader.GetFieldValue("PastaDocumento", true, true); - Documento documento7 = fieldValue1; - flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdBanco"); - Documento documento8 = documento7; - if (flag) - { - banco = null; - } - else - { - banco = new Banco(); - ((Banco)banco).Id = sqlDataReader.GetFieldValue("IdBanco", true, true); - ((Banco)banco).Nome = sqlDataReader.GetFieldValue("NomeBanco", true, true); - } - documento8.Banco = (Banco)banco; - fieldValue1.Agencia = sqlDataReader.GetFieldValue("Agencia", true, true); - fieldValue1.Conta = sqlDataReader.GetFieldValue("Conta", true, true); - fieldValue1.ItensAtivo = items1; - vendedorParcelas = fieldValue1; - documento2 = null; - controle4 = null; - controle = null; - documento3 = null; - documento5 = null; - documento7 = null; - fieldValue1 = null; - if (flag4 & buscaAssinaturas) - { - List statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(vendedorParcelas.Id); - string str3 = (vendedorParcelas.Tipo == 0 ? "PROPOSTA" : "PEDIDO DE ENDOSSO"); - statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => { - if (a.Documento.ToUpper() == str3 || a.Documento.ToUpper().Contains(str3)) - { - a.Selecionado = true; - } - }); - List statusDocumentoAssinados2 = statusDocumentoAssinados1; - StatusDocumentoAssinado statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault((StatusDocumentoAssinado a) => a.Selecionado); - Documento documento9 = vendedorParcelas; - if (statusDocumentoAssinados1 == null || statusDocumentoAssinados1.Count <= 0) - { - statusDocumentoAssinados = null; - } - else - { - statusDocumentoAssinados = statusDocumentoAssinados1; - } - documento9.Assinaturas = statusDocumentoAssinados; - Documento documento10 = vendedorParcelas; - flag2 = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status == StatusAssinatura.Assinado : false); - documento10.AssinadaSiggner = flag2; - Documento documento11 = vendedorParcelas; - statusAssinatura = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status : StatusAssinatura.NaoEnviado); - documento11.StatusAssinatura = statusAssinatura; - } - documentos.Add(vendedorParcelas); - items1 = null; - } - if (vendedorParcelas.VendedorPrincipal == null || vendedorParcelas.VendedorPrincipal.Id == vendedor1.Id) - { - fieldValue1 = vendedorParcelas; - flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdVendedor"); - Documento documento12 = fieldValue1; - if (flag) - { - vendedor = null; - } - else - { - vendedor = new Vendedor(); - ((DomainBase)vendedor).Id = sqlDataReader.GetFieldValue("IdVendedor", true, true); - ((Vendedor)vendedor).Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true); - } - documento12.VendedorPrincipal = (Vendedor)vendedor; - fieldValue1 = null; - } - if (vendedorParcelas.Controle.Cliente.Telefones != null) - { - long num2 = sqlDataReader.GetFieldValue("IdTelefone", true, true); - if (vendedorParcelas.Controle.Cliente.Telefones.FirstOrDefault((ClienteTelefone t) => t.Id == num2) == null) - { - ObservableCollection telefones = vendedorParcelas.Controle.Cliente.Telefones; - ClienteTelefone clienteTelefone1 = new ClienteTelefone() - { - Id = num2, - Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), - Numero = sqlDataReader.GetFieldValue("Numero", true, true) - }; - telefones.Add(clienteTelefone1); - } - } - if (vendedorParcelas.Controle.Cliente.Emails != null) - { - long num3 = sqlDataReader.GetFieldValue("IdEmail", true, true); - if (vendedorParcelas.Controle.Cliente.Emails.FirstOrDefault((ClienteEmail t) => t.Id == num3) == null) - { - ObservableCollection emails = vendedorParcelas.Controle.Cliente.Emails; - ClienteEmail clienteEmail1 = new ClienteEmail() - { - Id = num3, - Email = sqlDataReader.GetFieldValue("Email", true, true) - }; - emails.Add(clienteEmail1); - } - } - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - count1 = tipoVendedor.Count > 0; - } - else - { - count1 = false; - } - if (!count1) - { - List vendedores = filtro.Vendedores; - if (vendedores != null) - { - flag1 = vendedores.Count > 0; - } - else - { - flag1 = false; - } - if (!flag1) - { - if (vendedorParcelas.Pagamentos == null) - { - vendedorParcelas.Pagamentos = new List(); - } - long fieldValue4 = sqlDataReader.GetFieldValue("IdTipoVendedor", true, true); - long num4 = sqlDataReader.GetFieldValue("IdVendedor", true, true); - if (vendedorParcelas.Pagamentos.Find((VendedorParcela vps) => { - if (vps.TipoVendedor.Id != fieldValue4) - { - return false; - } - return vps.Vendedor.Id == num4; - }) == null) - { - List pagamentos = vendedorParcelas.Pagamentos; - VendedorParcela vendedorParcela1 = new VendedorParcela() - { - PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue("PorcentagemRepasse", true, true)) - }; - TipoVendedor tipoVendedor1 = new TipoVendedor() - { - Id = fieldValue4, - Descricao = sqlDataReader.GetFieldValue("DescricaoTipovendedor", true, true) - }; - vendedorParcela1.TipoVendedor = tipoVendedor1; - Vendedor vendedor2 = new Vendedor() - { - Id = num4, - Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true) - }; - vendedorParcela1.Vendedor = vendedor2; - pagamentos.Add(vendedorParcela1); - } - } - } - str2 = null; - vendedorParcelas = null; - } - } - } - } - sqlCommand = null; - List nums = filtro.TipoVendedor; - if (nums != null) - { - count2 = nums.Count > 0; - } - else - { - count2 = false; - } - if (!count2) - { - List vendedores1 = filtro.Vendedores; - if (vendedores1 != null) - { - count3 = vendedores1.Count > 0; - } - else - { - count3 = false; - } - if (!count3) - { - goto Label0; - } - } - foreach (Documento documento13 in documentos) - { - vendedorParcelas = documento13; - List vendedorParcelas1 = await this.BuscaVendedoresPorIdDocumento(documento13.Id, documento13.Controle.IdEmpresa); - vendedorParcelas.Pagamentos = vendedorParcelas1; - vendedorParcelas = null; - } - Label0: - List documentos1 = documentos; - documentos1.ForEach((Documento d) => { - decimal? nullable2; - decimal? porcentagemRepasse; - d.Vendedores = ( - from tipo in d.Pagamentos - orderby tipo.TipoVendedor.Id - select tipo into v - select v.Vendedor).ToList(); - Documento documento = d; - VendedorParcela vendedorParcela = d.Pagamentos.FirstOrDefault((VendedorParcela p) => { - long? nullable; - long id = p.Vendedor.Id; - Vendedor vendedorPrincipal = d.VendedorPrincipal; - nullable = (vendedorPrincipal != null ? new long?(vendedorPrincipal.Id) : null); - long? nullable1 = nullable; - return id == nullable1.GetValueOrDefault() & nullable1.HasValue; - }); - if (vendedorParcela != null) - { - porcentagemRepasse = vendedorParcela.PorcentagemRepasse; - } - else - { - nullable2 = null; - porcentagemRepasse = nullable2; - } - nullable2 = porcentagemRepasse; - documento.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault()); - }); - } - sqlConnection = null; - } - sessionFactory = null; - List documentos2 = documentos; - documentos = null; - sqlQueryCondition = null; - vendedor1 = null; - return documentos2; - } - - public async Task> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) - { - string str = "CAST(d.vigencia1 AS DATE)"; - string referencia = filtro.Referencia; - if (referencia == "EMISSÃO") - { - str = "CAST(d.emissao AS DATE)"; - } - else if (referencia == "TRANSMISSÃO PROPOSTA") - { - str = "CAST(d.remessa AS DATE)"; - } - else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") - { - str = "CAST(d.cri_data AS DATE)"; - } - List condicaos = this.CriaCondicaoDocumento(filtro, str); - Condicao condicao = new Condicao() - { - Campo = "d.TipoRecebimento", - Valores = 1.CriarValor() - }; - condicaos.Add(condicao); - List condicaos1 = new List(); - Condicao condicao1 = new Condicao() - { - Campo = "d.Excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos1.Add(condicao1); - Condicao condicao2 = new Condicao() - { - Campo = "d.Excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos1.Add(condicao2); - condicaos.AddRange(condicaos1); - return await this.BuscaDocumentosPorCondicao(filtro, condicaos, buscaAssinaturas); - } - - private async Task> BuscaFechamento(Filtros filtro) - { - NegocioCorretora negocioCorretora; - bool count; - object connection; - long num; - long num1; - decimal num2; - decimal num3; - decimal num4; - decimal num5; - NegocioCorretora negocioCorretora1; - bool flag; - List fechamentos = new List(); - string str2 = "CAST(d.vigencia1 AS DATE)"; - string str3 = "CAST(f.vigenciai AS DATE)"; - if (filtro.Referencia == "EMISSÃO") - { - str2 = "CAST(d.emissao AS DATE)"; - str3 = "CAST(f.emissao AS DATE)"; - } - List condicaos = this.CriaCondicaoDocumento(filtro, str2); - List condicaos1 = this.CriaCondicaoDocumento(filtro, str3); - List condicaos2 = this.CriaCondicaoDocumento(filtro, "CAST(d.vigencia1 AS DATE)"); - Condicao condicao = new Condicao() - { - Campo = "d.TipoRecebimento", - Valores = 1.CriarValor() - }; - condicaos.Add(condicao); - List condicaos3 = new List(); - Condicao condicao1 = new Condicao() - { - Campo = "d.Excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos3.Add(condicao1); - Condicao condicao2 = new Condicao() - { - Campo = "d.Excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos3.Add(condicao2); - List condicaos4 = condicaos3; - condicaos.AddRange(condicaos4); - condicaos1.AddRange(condicaos4); - condicaos2.AddRange(condicaos4); - string str4 = ""; - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - count = tipoVendedor.Count > 0; - } - else - { - count = false; - } - if (!count) - { - List vendedores = filtro.Vendedores; - if (vendedores != null) - { - flag = vendedores.Count > 0; - } - else - { - flag = false; - } - if (flag) - { - goto Label1; - } - str4 = "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp"; - goto Label0; - } - Label1: - str4 = "INNER JOIN vendedorparcela vp ON d.iddocumento = vp.iddocumento"; - Label0: - SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); - SqlQueryCondition sqlQueryCondition1 = condicaos1.CreateParameters(sqlQueryCondition.Parametros.Count); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str5 = string.Concat("SELECT DISTINCT c.IdEmpresa, d.IdControle, d.IdDocumento Id, d.Pr_Total Total, d.Pr_liq Liquido, d.Pr_Adic Adicional, ISNULL(d.com01, 0.00) Comissao, ISNULL(d.adinacomis, '0') AdinaComis, c.IdRamo, c.IdCiaSeg, c.IdProduto, CAST(d.Tipo AS INTEGER) Tipo, d.IdEstipulante, d.IdNegocio, d.Situacao, d.NegocioCorretora, vp.IdVendedor FROM documento d INNER JOIN controle c ON c.IdControle = d.IdControle ", str4, " WHERE "); - string str6 = string.Concat("SELECT DISTINCT c.IdEmpresa, d.IdControle, p.IdParcela Id, p.Valor Total, p.ValorLF Liquido, 0 Adicional, p.Comiss Comissao, '0' AdinaComis, c.IdRamo, c.IdCiaSeg, c.IdProduto, 2 Tipo, d.IdEstipulante, d.IdNegocio, d.Situacao, d.NegocioCorretora, vp.IdVendedor FROM fatura f INNER JOIN parcela p ON p.idparcela = f.idparcela INNER JOIN documento d ON d.iddocumento = p.iddocumento INNER JOIN controle c ON c.idcontrole = d.idcontrole ", str4, " WHERE "); - sqlCommand.CommandTimeout = 1000; - SqlCommand sqlCommand1 = sqlCommand; - string[] strArrays = new string[] { str5, " ", sqlQueryCondition.Condicao, " UNION ", str6, " ", sqlQueryCondition1.Condicao }; - sqlCommand1.CommandText = string.Concat(strArrays); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - sqlCommand.Parameters.AddRange(sqlQueryCondition1.Parametros.ToArray()); - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - List fechamentos1 = new List(); - decimal num6 = new decimal(); - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdCiaSeg")); - if (!flag1) - { - flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdRamo")); - } - if (!flag1) - { - long item = (long)sqlDataReader["IdEmpresa"]; - long item1 = (long)sqlDataReader["IdCiaSeg"]; - long item2 = (long)sqlDataReader["IdRamo"]; - flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdEstipulante")); - num = (flag1 ? (long)0 : (long)sqlDataReader["IdEstipulante"]); - long num7 = num; - flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdVendedor")); - num1 = (flag1 ? (long)0 : (long)sqlDataReader["IdVendedor"]); - long id = num1; - flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Total")); - num2 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Total"]); - decimal num8 = num2; - flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Liquido")); - num3 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Liquido"]); - decimal num9 = num3; - flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Adicional")); - num4 = (flag1 || sqlDataReader["AdinaComis"].ToString() == "0" ? decimal.Zero : (decimal)sqlDataReader["Adicional"]); - decimal num10 = num4; - flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Comissao")); - num5 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Comissao"]); - decimal num11 = num5; - int item3 = (int)sqlDataReader["Tipo"]; - if (!await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("negociocorretora"))) - { - negocioCorretora = (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), sqlDataReader["negociocorretora"].ToString()); - } - else - { - flag1 = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()) == TipoSeguro.Renovacao; - if (flag1) - { - flag1 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio")); - } - negocioCorretora1 = (!flag1 || !(sqlDataReader["idnegocio"].ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); - negocioCorretora = negocioCorretora1; - } - NegocioCorretora negocioCorretora2 = negocioCorretora; - if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora2)) - { - if (id == 0) - { - id = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { - if (v.IdEmpresa != item) - { - return false; - } - return v.Corretora; - }).Id; - } - decimal num12 = (num9 + num10) * num11 * new decimal(1, 0, 0, false, 2); - num6 += num8; - for (int i = 0; i < 4; i++) - { - long num13 = (long)0; - switch (i) - { - case 0: - { - num13 = item1; - break; - } - case 1: - { - num13 = item2; - break; - } - case 2: - { - num13 = num7; - break; - } - case 3: - { - num13 = id; - break; - } - } - if (num13 != 0) - { - Fechamento fechamento4 = fechamentos1.FirstOrDefault((Fechamento a) => { - if (a.Entidade != i) - { - return false; - } - return a.Id == num13; - }); - if (fechamento4 == null) - { - fechamento4 = new Fechamento(); - } - Fechamento fechamento5 = fechamento4; - Fechamento premioTotal = fechamento5; - premioTotal.PremioTotal = premioTotal.PremioTotal + num8; - Fechamento premioLiquido = fechamento5; - premioLiquido.PremioLiquido = premioLiquido.PremioLiquido + num9; - Fechamento fechamento6 = fechamento5; - fechamento6.Fechada = fechamento6.Fechada + num11; - Fechamento gerada = fechamento5; - gerada.Gerada = gerada.Gerada + num12; - switch (item3) - { - case 0: - { - Fechamento apolice = fechamento5; - apolice.Apolice = apolice.Apolice + 1; - break; - } - case 1: - { - Fechamento endosso = fechamento5; - endosso.Endosso = endosso.Endosso + 1; - break; - } - case 2: - { - Fechamento fatura = fechamento5; - fatura.Fatura = fatura.Fatura + 1; - break; - } - } - if (fechamento5.Id == 0) - { - fechamento5.Entidade = i; - fechamento5.Id = num13; - fechamentos1.Add(fechamento5); - } - } - } - } - } - } - fechamentos1.ForEach((Fechamento f) => { - string nome; - string str; - string nome1; - string str1; - switch (f.Entidade) - { - case 0: - { - Fechamento fechamento = f; - Seguradora seguradora = Auxiliar.Seguradoras.Find((Seguradora s) => s.Id == f.Id); - if (seguradora != null) - { - nome = seguradora.Nome; - } - else - { - nome = null; - } - fechamento.Nome = nome; - break; - } - case 1: - { - Fechamento fechamento1 = f; - Ramo ramo = Auxiliar.Ramos.Find((Ramo r) => r.Id == f.Id); - if (ramo != null) - { - str = ramo.Nome; - } - else - { - str = null; - } - fechamento1.Nome = str; - break; - } - case 2: - { - Fechamento fechamento2 = f; - Estipulante estipulante = Auxiliar.Estipulantes.Find((Estipulante e) => e.Id == f.Id); - if (estipulante != null) - { - nome1 = estipulante.Nome; - } - else - { - nome1 = null; - } - fechamento2.Nome = nome1; - break; - } - case 3: - { - Fechamento fechamento3 = f; - Vendedor vendedor = Auxiliar.Vendedores.Find((Vendedor v) => v.Id == f.Id); - if (vendedor != null) - { - str1 = vendedor.Nome; - } - else - { - str1 = null; - } - fechamento3.Nome = str1; - break; - } - } - Fechamento fechada = f; - fechada.Fechada = fechada.Fechada / f.Apolice + f.Fatura + f.Endosso; - f.Mix = (f.PremioTotal * new decimal(100)) / num6; - }); - List fechamentos2 = fechamentos1; - foreach (IGrouping nums in - from g in fechamentos2 - group g by g.Entidade) - { - await this.ContaRegistros(nums.Key, fechamentos1, filtro, condicaos2); - await this.SomaComissaoPaga(nums.Key, fechamentos1, filtro, condicaos2); - await this.SomaComissaoRecebida(nums.Key, fechamentos1, filtro, condicaos2); - } - fechamentos.AddRange(fechamentos1); - fechamentos1 = null; - } - sqlDataReader = null; - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List fechamentos3 = fechamentos; - fechamentos = null; - condicaos2 = null; - return fechamentos3; - } - - private async Task> BuscaItemsPorIdControle(long idControle) - { - object connection; - List items = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)"; - sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List items1 = items; - Item item = new Item() - { - Id = (long)sqlDataReader["iditem"], - Descricao = sqlDataReader["descricao"].ToString() - }; - items1.Add(item); - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List items2 = items; - items = null; - return items2; - } - - public List BuscarDocumentoPorEstipulante(long id) - { - List list = ( - from x in base.All() - where x.Estipulante1.Id == id || x.Estipulante2.Id == id || x.Estipulante3.Id == id || x.Estipulante4.Id == id || x.Estipulante5.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List BuscarDocumentoPorStatus(long id) - { - List list = ( - from x in base.All() - where x.Status.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public string BuscarLogAntigo(long id, string conn) - { - object connection; - string str = ""; - List condicaos = new List() - { - new Condicao() - { - Campo = "id", - Valores = id.CriarValor() - }, - new Condicao() - { - Campo = "idname", - Valores = "iddocumento".CriarValor() - } - }; - this._unitOfWork.CriarAuxiliar(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - string str1 = "oldbacklog"; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog"; - SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); - sqlDataReader.Read(); - string str2 = sqlDataReader["bdname"].ToString(); - str1 = sqlDataReader["tabela"].ToString(); - sqlDataReader.Close(); - if (sqlConnection.Database != str2) - { - conn = conn.Replace(sqlConnection.Database, str2); - } - } - } - DataTable dataTable = new DataTable(); - using (SqlConnection sqlConnection1 = new SqlConnection(conn)) - { - sqlConnection1.Open(); - using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand()) - { - sqlCommand1.CommandTimeout = 15000; - dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), ""); - } - } - if (dataTable == null || dataTable.Rows.Count == 0) - { - return ""; - } - if (dataTable != null) - { - dataTable.AsEnumerable().OrderBy((DataRow x) => x.Field("idbacklog")).ToList().ForEach((DataRow x) => { - str = string.Concat(new string[] { str, "
(", x.Field("data").ToString(), ") ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("idusuario")).Nome, "
" }); - str = string.Concat(str, "", x.Field("historico").ToString().Replace(Environment.NewLine, "
"), ""); - }); - } - return str; - } - - public List BuscarPlanilhaCompletaProspeccao(List ids) - { - object connection; - List nums = null; - if (ids == null || ids.Count == 0) - { - return new List(); - } - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - for (List i = ids; i.Count > 0; i = nums) - { - List list = i.Take(2100).ToList(); - string str1 = string.Concat(" AND va.idvenctoaleatorio IN (", string.Join(",", list), ")"); - DataTable dataTable2 = new DataTable(); - string str2 = string.Concat("SELECT DISTINCT * FROM venctoaleatorio va LEFT OUTER JOIN tarefa ta on va.idtarefa = ta.id WHERE 1=1 ", str1, ";"); - sqlCommand.CommandText = str2 ?? ""; - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable2); - } - dataTable.Merge(dataTable2); - nums = (list.Count < 2100 ? new List() : i.Except(list).ToList()); - } - } - } - if (dataTable.Rows.Count == 0) - { - return new List(); - } - List planilhaCompletas = new List(); - dataTable.AsEnumerable().ToList().ForEach((DataRow x) => { - DateTime? nullable; - string str; - DateTime? nullable1; - DateTime? nullable2; - PlanilhaCompleta planilhaCompletum = new PlanilhaCompleta() - { - NumeroApolice = "PROSPECÇÃO", - Status = (x.Field("situacao") == null || !(x.Field("situacao").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("situacao").ToString()) ? null : (StatusProspeccao)Enum.Parse(typeof(StatusProspeccao), x.Field("situacao").ToString()).GetDescription()) - }; - DateTime? nullable3 = x.Field("finalcontrato"); - if (nullable3.HasValue) - { - nullable = x.Field("finalcontrato"); - } - else - { - nullable3 = null; - nullable = nullable3; - } - planilhaCompletum.VigenciaFinal = nullable; - DataRow dataRow = dataTable1.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")); - if (dataRow != null) - { - str = dataRow.Field("nome"); - } - else - { - str = null; - } - planilhaCompletum.Estipulante = str; - planilhaCompletum.Vendedor = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")).Nome : null); - planilhaCompletum.NomeCliente = x.Field("nome"); - nullable3 = x.Field("dtnascimento"); - if (nullable3.HasValue) - { - nullable1 = x.Field("dtnascimento"); - } - else - { - nullable3 = null; - nullable1 = nullable3; - } - planilhaCompletum.NascimentoCliente = nullable1; - planilhaCompletum.DocumentoCliente = x.Field("cpfcnpj"); - planilhaCompletum.Prefixo1 = x.Field("ddd"); - planilhaCompletum.Telefone1 = x.Field("fone"); - planilhaCompletum.Prefixo2 = x.Field("ddd2"); - planilhaCompletum.Telefone2 = x.Field("fone2"); - planilhaCompletum.Email1 = x.Field("email"); - planilhaCompletum.DescricaoItem = x.Field("item"); - planilhaCompletum.ObsProspeccao = x.Field("obs"); - planilhaCompletum.TipoProspeccao = x.Field("tipoprospeccao"); - planilhaCompletum.TituloTarefa = x.Field("titulo"); - planilhaCompletum.DescricaoTarefa = x.Field("descricao"); - nullable3 = x.Field("agendamento"); - if (nullable3.HasValue) - { - nullable2 = x.Field("agendamento"); - } - else - { - nullable3 = null; - nullable2 = nullable3; - } - planilhaCompletum.AgendamentoTarefa = nullable2; - planilhaCompletas.Add(planilhaCompletum); - }); - return planilhaCompletas; - } - - private async Task> BuscaStatusAssinadosPorIdDocumento(long idDocumento) - { - object connection; - DateTime? nullable; - Usuario usuario1; - Func func = null; - List statusDocumentoAssinados = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - sqlCommand.CommandText = "SELECT a.idnewarquivodigital,a.descricao,ISNULL(s.Status ,3) status,s.assinado,a.iddocumento,s.id,s.usuarioid,s.enviado FROM newarquivodigital a LEFT JOIN ArquivoParaAssinatura s ON a.idnewarquivodigital = s.indiceid WHERE a.iddocumento = @documento AND (a.excluido = 0 OR a.excluido IS NULL)"; - sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List statusDocumentoAssinados1 = statusDocumentoAssinados; - StatusDocumentoAssinado statusDocumentoAssinado = new StatusDocumentoAssinado() - { - Id = (long)sqlDataReader["idnewarquivodigital"], - Documento = sqlDataReader["descricao"].ToString(), - Status = (StatusAssinatura)((int)sqlDataReader["status"]) - }; - StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado; - bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("enviado")); - StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado1; - if (flag) - { - nullable = null; - } - else - { - nullable = new DateTime?((DateTime)sqlDataReader["enviado"]); - } - statusDocumentoAssinado2.Envio = nullable; - StatusDocumentoAssinado statusDocumentoAssinado3 = statusDocumentoAssinado; - bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("usuarioid")); - StatusDocumentoAssinado statusDocumentoAssinado4 = statusDocumentoAssinado3; - if (flag1) - { - usuario1 = null; - } - else - { - List usuarios = Auxiliar.Usuarios; - Func func1 = func; - if (func1 == null) - { - Func id = (Usuario usuario) => usuario.Id == (long)sqlDataReader["usuarioid"]; - Func func2 = id; - func = id; - func1 = func2; - } - usuario1 = usuarios.FirstOrDefault(func1); - } - statusDocumentoAssinado4.Usuario = usuario1; - statusDocumentoAssinados1.Add(statusDocumentoAssinado); - statusDocumentoAssinados1 = null; - statusDocumentoAssinado1 = null; - statusDocumentoAssinado3 = null; - statusDocumentoAssinado = null; - } - } - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List statusDocumentoAssinados2 = statusDocumentoAssinados; - statusDocumentoAssinados = null; - return statusDocumentoAssinados2; - } - - private async Task> BuscaVendedoresPorIdControle(long idControle, long idEmpresa) - { - object connection; - Func func = null; - List vendedorParcelas = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - sqlCommand.CommandText = "SELECT DISTINCT vp.idvendedor,vp.vrep,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN parcela p ON vp.idparcela = p.idparcela INNER JOIN documento d ON d.iddocumento = vp.iddocumento WHERE d.idcontrole = @controle AND p.idsubtipo = 1"; - sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List vendedorParcelas1 = vendedorParcelas; - VendedorParcela vendedorParcela = new VendedorParcela(); - TipoVendedor tipoVendedor = new TipoVendedor() - { - Id = sqlDataReader.GetFieldValue("idtipovendedor", true, true) - }; - vendedorParcela.TipoVendedor = tipoVendedor; - List vendedores = Auxiliar.Vendedores; - Func func1 = func; - if (func1 == null) - { - Func id = (Vendedor vendedor) => vendedor.Id == sqlDataReader.GetFieldValue("idvendedor", true, true); - Func func2 = id; - func = id; - func1 = func2; - } - vendedorParcela.Vendedor = vendedores.FirstOrDefault(func1); - vendedorParcela.PorcentagemRepasse = sqlDataReader.GetFieldValue("vrep", true, true); - vendedorParcelas1.Add(vendedorParcela); - } - List vendedorParcelas2 = vendedorParcelas; - if (!vendedorParcelas2.Any((VendedorParcela v) => v.TipoVendedor.Id == (long)1)) - { - List vendedorParcelas3 = vendedorParcelas; - VendedorParcela vendedorParcela1 = new VendedorParcela() - { - TipoVendedor = new TipoVendedor() - { - Id = (long)1 - }, - Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { - if (v.IdEmpresa != idEmpresa) - { - return false; - } - return v.Corretora; - }), - PorcentagemRepasse = new decimal?(new decimal()) - }; - vendedorParcelas3.Add(vendedorParcela1); - } - } - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List vendedorParcelas4 = vendedorParcelas; - vendedorParcelas = null; - return vendedorParcelas4; - } - - private async Task> BuscaVendedoresPorIdDocumento(long idDocumento, long idEmpresa) - { - object connection; - decimal? nullable; - Func func = null; - List vendedorParcelas = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - sqlCommand.CommandText = "SELECT DISTINCT vp.idvendedor,vp.vrep,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN parcela p ON vp.idparcela = p.idparcela WHERE vp.iddocumento = @documento AND p.idsubtipo = 1"; - sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List vendedorParcelas1 = vendedorParcelas; - VendedorParcela vendedorParcela = new VendedorParcela(); - VendedorParcela vendedorParcela1 = vendedorParcela; - TipoVendedor tipoVendedor = new TipoVendedor() - { - Id = (long)sqlDataReader["idtipovendedor"] - }; - vendedorParcela1.TipoVendedor = tipoVendedor; - VendedorParcela vendedorParcela2 = vendedorParcela; - List vendedores = Auxiliar.Vendedores; - Func func1 = func; - if (func1 == null) - { - Func id = (Vendedor vendedor) => vendedor.Id == (long)sqlDataReader["idvendedor"]; - Func func2 = id; - func = id; - func1 = func2; - } - vendedorParcela2.Vendedor = vendedores.FirstOrDefault(func1); - VendedorParcela vendedorParcela3 = vendedorParcela; - bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vrep")); - VendedorParcela vendedorParcela4 = vendedorParcela3; - if (flag) - { - nullable = null; - } - else - { - nullable = new decimal?((decimal)sqlDataReader["vrep"]); - } - vendedorParcela4.PorcentagemRepasse = nullable; - vendedorParcelas1.Add(vendedorParcela); - vendedorParcelas1 = null; - vendedorParcela3 = null; - vendedorParcela = null; - } - List vendedorParcelas2 = vendedorParcelas; - if (!vendedorParcelas2.Any((VendedorParcela v) => v.TipoVendedor.Id == (long)1)) - { - List vendedorParcelas3 = vendedorParcelas; - VendedorParcela vendedorParcela5 = new VendedorParcela() - { - TipoVendedor = new TipoVendedor() - { - Id = (long)1 - }, - Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { - if (v.IdEmpresa != idEmpresa) - { - return false; - } - return v.Corretora; - }), - PorcentagemRepasse = new decimal?(new decimal()) - }; - vendedorParcelas3.Add(vendedorParcela5); - } - } - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List vendedorParcelas4 = vendedorParcelas; - vendedorParcelas = null; - return vendedorParcelas4; - } - - private async Task ContaRegistros(int tipo, List fechamentos, Filtros filtro, List condicaoDocumento) - { - object connection; - long num; - bool count; - bool flag; - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - string str = "c.IdCiaSeg"; - string str1 = "COUNT(d.IdDocumento)"; - string str2 = "FROM item i INNER JOIN documento d ON d.IdDocumento = i.IdDocumento INNER JOIN controle c ON c.IdControle = d.IdControle"; - string str3 = "i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0) AND"; - switch (tipo) - { - case 1: - { - str = "c.IdRamo"; - break; - } - case 2: - { - str = "d.IdEstipulante"; - break; - } - case 3: - { - str = "vp.IdVendedor"; - break; - } - } - string str4 = ""; - if (tipo != 3) - { - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - count = tipoVendedor.Count > 0; - } - else - { - count = false; - } - if (!count) - { - List vendedores = filtro.Vendedores; - if (vendedores != null) - { - flag = vendedores.Count > 0; - } - else - { - flag = false; - } - if (!flag) - { - goto Label0; - } - } - } - str1 = "COUNT(DISTINCT d.IdDocumento)"; - str4 = "INNER JOIN vendedorparcela vp ON d.iddocumento = vp.iddocumento"; - Label0: - SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0); - sqlCommand.CommandTimeout = 1000; - SqlCommand sqlCommand1 = sqlCommand; - string[] condicao = new string[] { "SELECT ", str, " Id,", str1, " Contador ", str2, " ", str4, " WHERE ", str3, " ", sqlQueryCondition.Condicao, " GROUP BY ", str }; - sqlCommand1.CommandText = string.Concat(condicao); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id")); - num = (flag1 ? (long)0 : (long)sqlDataReader["Id"]); - long num1 = num; - int item = (int)sqlDataReader["Contador"]; - if (num1 != 0) - { - Fechamento fechamento = fechamentos.FirstOrDefault((Fechamento f) => { - if (f.Entidade != tipo) - { - return false; - } - return f.Id == num1; - }); - if (fechamento != null) - { - Fechamento itens = fechamento; - itens.Itens = itens.Itens + item; - } - } - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - } - - public int Cotacoes(Filtros filtro) - { - int num; - object connection; - string str = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND u.idempresa = {0}", filtro.IdEmpresa)); - try - { - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Format("SELECT COUNT(r.id) as quantidade from ResultadoCalculo r INNER JOIN usuario u ON u.idusuario = r.IdUsuario where CAST(DataAtualizacao AS DATE) >= '{0:yyyy-MM-dd}' and CAST(DataAtualizacao AS DATE) <= '{1:yyyy-MM-dd}' AND DataExclusao IS NULL AND Calculado = 1 {2};", filtro.Inicio, filtro.Fim, str); - SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); - sqlDataReader.Read(); - num = (sqlDataReader.HasRows ? int.Parse(sqlDataReader["quantidade"].ToString()) : 0); - } - } - } - catch (Exception exception) - { - num = 0; - } - return num; - } - - private List CriaCondicaoDocumento(Filtros filtro, string referencia) - { - bool count; - bool flag; - bool count1; - bool flag1; - bool count2; - bool flag2; - bool count3; - bool flag3; - List condicaos = new List() - { - new Condicao() - { - Campo = referencia, - Valores = filtro.Inicio.CriarValor(), - Operador = Operador.MaiorEIgual - }, - new Condicao() - { - Campo = referencia, - Valores = filtro.Fim.CriarValor(), - Operador = Operador.MenorEIgual - } - }; - List seguradoras = filtro.Seguradoras; - if (seguradoras != null) - { - count = seguradoras.Count > 0; - } - else - { - count = false; - } - if (count) - { - condicaos.Add(new Condicao() - { - Campo = "c.idciaseg", - Valores = filtro.Seguradoras.CriarValor() - }); - } - List ramos = filtro.Ramos; - if (ramos != null) - { - flag = ramos.Count > 0; - } - else - { - flag = false; - } - if (flag) - { - condicaos.Add(new Condicao() - { - Campo = "c.idramo", - Valores = filtro.Ramos.CriarValor() - }); - } - List status = filtro.Status; - if (status != null) - { - count1 = status.Count > 0; - } - else - { - count1 = false; - } - if (count1) - { - condicaos.Add(new Condicao() - { - Campo = "d.situacao", - Valores = filtro.Status.CriarValor() - }); - } - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - flag1 = tipoVendedor.Count > 0; - } - else - { - flag1 = false; - } - if (flag1) - { - condicaos.Add(new Condicao() - { - Campo = "vp.idtipovendedor", - Valores = filtro.TipoVendedor.CriarValor() - }); - } - List vendedores = filtro.Vendedores; - if (vendedores != null) - { - count2 = vendedores.Count > 0; - } - else - { - count2 = false; - } - if (count2) - { - condicaos.Add(new Condicao() - { - Campo = "vp.idvendedor", - Valores = filtro.Vendedores.CriarValor() - }); - } - List estipulantes = filtro.Estipulantes; - if (estipulantes != null) - { - flag2 = estipulantes.Count > 0; - } - else - { - flag2 = false; - } - if (flag2) - { - condicaos.Add(new Condicao() - { - Campo = "d.idestipulante", - Valores = filtro.Estipulantes.CriarValor(), - Operacao = Operacao.Or, - Grupo = 3 - }); - condicaos.Add(new Condicao() - { - Campo = "d.idestipulante2", - Valores = filtro.Estipulantes.CriarValor(), - Operacao = Operacao.Or, - Grupo = 3 - }); - condicaos.Add(new Condicao() - { - Campo = "d.idestipulante3", - Valores = filtro.Estipulantes.CriarValor(), - Operacao = Operacao.Or, - Grupo = 3 - }); - condicaos.Add(new Condicao() - { - Campo = "d.idestipulante4", - Valores = filtro.Estipulantes.CriarValor(), - Operacao = Operacao.Or, - Grupo = 3 - }); - condicaos.Add(new Condicao() - { - Campo = "d.idestipulante5", - Valores = filtro.Estipulantes.CriarValor(), - Operacao = Operacao.Or, - Grupo = 3 - }); - } - List produtos = filtro.Produtos; - if (produtos != null) - { - count3 = produtos.Count > 0; - } - else - { - count3 = false; - } - if (count3) - { - condicaos.Add(new Condicao() - { - Campo = "c.idproduto", - Valores = filtro.Produtos.CriarValor() - }); - } - List negocio = filtro.Negocio; - if (negocio != null) - { - flag3 = negocio.Count > 0; - } - else - { - flag3 = false; - } - if (flag3) - { - condicaos.Add(new Condicao() - { - Campo = "d.NegocioCorretora", - Valores = filtro.Negocio.CriarValor(), - Operacao = Operacao.Or, - Grupo = 6 - }); - condicaos.Add(new Condicao() - { - Campo = "d.NegocioCorretora", - Valores = null, - Operacao = Operacao.Or, - Grupo = 6 - }); - } - if (filtro.IdEmpresa > (long)0) - { - condicaos.Add(new Condicao() - { - Campo = "c.idempresa", - Valores = filtro.IdEmpresa.CriarValor() - }); - } - return condicaos; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - private async Task ExisteTabelasAssinatura() - { - bool flag; - object connection; - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT OBJECT_ID('ArquivoParaAssinatura') AS existe"; - flag = await sqlCommand.ExecuteScalarAsync() != DBNull.Value; - } - } - } - return flag; - } - - public async Task> Fechamento(Filtros filtro) - { - List fechamentos = await this.BuscaFechamento(filtro); - Filtros filtro1 = (Filtros)filtro.Clone(); - DateTime inicio = filtro.Inicio; - filtro1.Inicio = inicio.AddYears(-1); - inicio = filtro.Fim; - filtro1.Fim = inicio.AddYears(-1); - List fechamentos1 = await this.BuscaFechamento(filtro1); - List fechamentos2 = new List(); - fechamentos1.ForEach((Fechamento a) => { - Fechamento premioLiquido = fechamentos.Find((Fechamento fec) => { - if (fec.Entidade != a.Entidade) - { - return false; - } - return fec.Id == a.Id; - }) ?? new Fechamento() - { - Entidade = a.Entidade, - Id = a.Id, - Nome = a.Nome, - PremioLiquido = decimal.Zero, - PremioTotal = decimal.Zero, - Fechada = decimal.Zero, - Gerada = decimal.Zero, - Mix = decimal.Zero, - Apolice = 0, - Endosso = 0, - Fatura = 0, - Itens = 0, - Paga = decimal.Zero, - Recebida = decimal.Zero - }; - premioLiquido.PremioLiquidoAnterior = a.PremioLiquido; - premioLiquido.PremioTotalAnterior = a.PremioTotal; - premioLiquido.FechadaAnterior = a.Fechada; - premioLiquido.GeradaAnterior = a.Gerada; - premioLiquido.MixAnterior = a.Mix; - premioLiquido.ApoliceAnterior = a.Apolice; - premioLiquido.EndossoAnterior = a.Endosso; - premioLiquido.FaturaAnterior = a.Fatura; - premioLiquido.ItensAnterior = a.Itens; - premioLiquido.PagaAnterior = a.Paga; - premioLiquido.RecebidaAnterior = a.Recebida; - fechamentos2.Add(premioLiquido); - }); - fechamentos.ForEach((Fechamento a) => { - if (fechamentos2.Find((Fechamento fec) => { - if (fec.Entidade != a.Entidade) - { - return false; - } - return fec.Id == a.Id; - }) == null) - { - Fechamento fechamento = new Fechamento() - { - Entidade = a.Entidade, - Id = a.Id, - Nome = a.Nome, - PremioLiquidoAnterior = decimal.Zero, - PremioTotalAnterior = decimal.Zero, - FechadaAnterior = decimal.Zero, - GeradaAnterior = decimal.Zero, - MixAnterior = decimal.Zero, - ApoliceAnterior = 0, - EndossoAnterior = 0, - FaturaAnterior = 0, - ItensAnterior = 0, - PagaAnterior = decimal.Zero, - RecebidaAnterior = decimal.Zero, - PremioLiquido = a.PremioLiquido, - PremioTotal = a.PremioTotal, - Fechada = a.Fechada, - Gerada = a.Gerada, - Mix = a.Mix, - Apolice = a.Apolice, - Endosso = a.Endosso, - Fatura = a.Fatura, - Itens = a.Itens, - Paga = a.Paga, - Recebida = a.Recebida - }; - fechamentos2.Add(fechamento); - } - }); - List fechamentos3 = fechamentos2; - return fechamentos3; - } - - public List FindApolice(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, string campo, long idempresa = 0L, bool vendedorembranco = false, bool tipobusca = false) - { - List documentos; - object connection; - DataTable dataTable = new DataTable(); - if (campo == "Proposta") - { - campo = (tipobusca ? string.Concat(" AND d.proposta LIKE '", pesquisa, "'") : string.Concat(" AND d.proposta LIKE '%", pesquisa, "%'")); - } - else if (campo == "Estipulante") - { - campo = (tipobusca ? string.Concat(" AND d.idestipulante IS NOT NULL AND e.nome LIKE '", pesquisa, "'") : string.Concat(" AND d.idestipulante IS NOT NULL AND e.nome LIKE '%", pesquisa, "%'")); - } - else if (campo == "NumeroEndosso") - { - campo = (tipobusca ? string.Concat(" AND d.aditamento LIKE '", pesquisa, "'") : string.Concat(" AND d.aditamento LIKE '%", pesquisa, "%'")); - } - else if (campo == "PedidoEndosso") - { - campo = (tipobusca ? string.Concat(" AND d.pedadit LIKE '", pesquisa, "'") : string.Concat(" AND d.pedadit LIKE '%", pesquisa, "%'")); - } - else - { - campo = (tipobusca ? string.Concat(" AND d.contrato LIKE '", pesquisa, "'") : string.Concat(" AND d.contrato LIKE '%", pesquisa, "%'")); - } - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable1 = new DataTable(); - string str = ""; - string str1 = (idempresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", idempresa)); - DateTime date = Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime().Date; - switch (status) - { - case FiltroStatusDocumento.Vencidos: - { - str = string.Concat(string.Format(" {0} AND (d.vigencia2 IS NULL OR d.vigencia2 < '{1:yyyy-MM-dd}') ", campo, date.AddDays(-5)), "AND d.situacao NOT IN (3, 7)"); - break; - } - case FiltroStatusDocumento.Cancelados: - { - str = string.Concat(" ", campo, " AND d.situacao IN (3)"); - break; - } - case FiltroStatusDocumento.Recusados: - { - str = string.Concat(campo, " AND d.situacao IN (7)"); - break; - } - case FiltroStatusDocumento.Todos: - { - str = string.Concat(" ", campo); - break; - } - default: - { - str = string.Concat(string.Format(" {0} AND (d.vigencia2 IS NULL OR d.vigencia2 > '{1:yyyy-MM-dd}') ", campo, date.AddDays(-5)), "AND d.situacao IN (1, 2, 4)"); - break; - } - } - string str2 = "SELECT DISTINCT c.idcliente,cl.nome,cl.MalaDireta,c.idempresa,c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, d.pasta, c.AssistenciaId, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, e.nome AS estipulante FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole INNER JOIN cliente cl ON cl.idcliente = c.idcliente LEFT OUTER JOIN estipulante e ON e.idestipulante = d.idestipulante WHERE (d.excluido IS NULL OR d.excluido != 1) "; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - sqlCommand.CommandText = string.Concat(str2, str1, str); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable1); - } - List list = ( - from x in dataTable1.AsEnumerable().ToList() - select x.Field("idcontrole")).ToList(); - while (list.Count > 0) - { - List nums = list.Take(2100).ToList(); - if (dataTable1.Rows.Count != 0) - { - string str3 = string.Concat(" d.idcontrole IN (", string.Join(",", nums), ")"); - str3 = (vendedorembranco ? string.Concat(" AND ", str3) : string.Concat(" AND vp.idvendedorparcela IS NOT NULL AND ", str3)); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento WHERE 1=1 ", str3); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable); - } - list = (nums.Count < 2100 ? new List() : list.Except(nums).ToList()); - } - else - { - documentos = new List(); - return documentos; - } - } - goto Label0; - } - } - return documentos; - Label0: - List list1 = null; - if (vendedorVinculado != null && vendedorVinculado.Count > 0) - { - list1 = dataTable.AsEnumerable().Where((DataRow x) => { - if (!vendedorembranco) - { - if (x.Field("idvendedor") == null) - { - return false; - } - List vendedorUsuarios = vendedorVinculado; - Func u003cu003e9_429 = DocumentoRepository.u003cu003ec.u003cu003e9__42_9; - if (u003cu003e9_429 == null) - { - u003cu003e9_429 = (VendedorUsuario v) => v.Vendedor.Id; - DocumentoRepository.u003cu003ec.u003cu003e9__42_9 = u003cu003e9_429; - } - return vendedorUsuarios.Select(u003cu003e9_429).Contains(x.Field("idvendedor")); - } - if (x.Field("idvendedor") == null) - { - return true; - } - List vendedorUsuarios1 = vendedorVinculado; - Func u003cu003e9_428 = DocumentoRepository.u003cu003ec.u003cu003e9__42_8; - if (u003cu003e9_428 == null) - { - u003cu003e9_428 = (VendedorUsuario v) => v.Vendedor.Id; - DocumentoRepository.u003cu003ec.u003cu003e9__42_8 = u003cu003e9_428; - } - return vendedorUsuarios1.Select(u003cu003e9_428).Contains(x.Field("idvendedor")); - }).Select((DataRow x) => x.Field("idcontrole")).ToList(); - } - if (list1 != null && list1.Count == 0) - { - return new List(); - } - List nums1 = dataTable1.AsEnumerable().Select((DataRow x) => x.Field("idcontrole")).Distinct().ToList(); - List nums2 = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(nums1); - return ( - from x in dataTable1.AsEnumerable().Where((DataRow x) => { - if (list1 == null) - { - return true; - } - return list1.Contains(x.Field("idcontrole")); - }).ToList() - orderby x.Field("idcontrole"), x.Field("tipo") - select x).Select((DataRow x) => { - Documento documento = new Documento() - { - Id = x.Field("iddocumento"), - Controle = new Controle() - { - Id = x.Field("idcontrole"), - IdEmpresa = (x.Field("idempresa") != null ? x.Field("idempresa") : (long)1), - Cliente = new Cliente() - { - Id = x.Field("idcliente"), - Nome = x.Field("nome"), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) - }, - Seguradora = (x.Field("idciaseg") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idciaseg")) : null), - Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), - Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), - AssistenciaId = x.Field("AssistenciaId") - }, - Ordem = x.Field("ordem"), - TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), - AdicionalComiss = x.Field("adinacomis") == "1", - Apolice = x.Field("contrato"), - Endosso = x.Field("aditamento"), - Comissao = x.Field("com01"), - Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), - PremioLiquido = x.Field("pr_liq"), - PremioTotal = x.Field("pr_total"), - Vigencia2 = x.Field("vigencia2") - }; - DateTime? nullable = x.Field("vigencia1"); - documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - documento.Emissao = x.Field("emissao"); - documento.Remessa = x.Field("remessa"); - documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); - documento.NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); - documento.Tipo = x.Field("tipo"); - documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(x.Field("iddocumento")); - documento.Sinistro = (nums2 == null ? false : nums2.Any((long s) => s == x.Field("idcontrole"))); - documento.NumeroParcelas = int.Parse(x.Field("numeroParcelas").ToString()); - documento.Pasta = x.Field("Pasta"); - return documento; - }).ToList(); - } - - public List FindApoliceByCustomer(long idCliente, FiltroStatusDocumento status, List vendedorVinculado, List licencas, bool endosso = false, bool acessoAgger = false, bool vendedorembranco = false) - { - List documentos1; - object connection; - long num1; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - bool flag2 = licencas.Any((Licenca x) => { - if (x.Produto != Gestor.Model.License.Produto.AssinaturaEletronica) - { - return false; - } - return x.Status != 3; - }); - DataTable dataTable3 = new DataTable(); - DataTable dataTable4 = new DataTable(); - DataTable dataTable5 = new DataTable(); - DataTable dataTable6 = new DataTable(); - DataTable dataTable7 = null; - List nums = new List(); - List condicaos = new List() - { - new Condicao() - { - Campo = "d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }; - DateTime date = Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime().Date; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "c.idcliente", - Valores = idCliente.CriarValor() - }, - new Condicao() - { - Campo = "d.tipo", - Valores = 0.CriarValor() - } - }; - switch (status) - { - case FiltroStatusDocumento.Vencidos: - { - condicaos1.AddRange(new List() - { - new Condicao() - { - Campo = "d.situacao", - Valores = new List() - { - 3, - 7 - }, - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = "d.vigencia2", - Valores = date.AddDays(-5).CriarValor(), - Operador = Operador.Menor - } - }); - goto case FiltroStatusDocumento.Todos; - } - case FiltroStatusDocumento.Cancelados: - { - condicaos1.Add(new Condicao() - { - Campo = "d.situacao", - Valores = 3.CriarValor() - }); - goto case FiltroStatusDocumento.Todos; - } - case FiltroStatusDocumento.Recusados: - { - condicaos1.Add(new Condicao() - { - Campo = "d.situacao", - Valores = 7.CriarValor() - }); - goto case FiltroStatusDocumento.Todos; - } - case FiltroStatusDocumento.Todos: - { - if (!acessoAgger) - { - condicaos1.AddRange(condicaos); - } - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - dataTable3 = sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); - if (dataTable3 == null || dataTable3.Rows.Count == 0) - { - documentos1 = new List(); - return documentos1; - } - else - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - nums = ( - from x in dataTable3.AsEnumerable().ToList() - select x.Field("idcontrole")).ToList(); - List condicaos2 = new List() - { - new Condicao() - { - Campo = "c.idcontrole", - Valores = nums.CriarValor() - }, - new Condicao() - { - Campo = "d.tipo", - Valores = 0.CriarValor(), - Operador = Operador.Diferente - } - }; - if (!acessoAgger) - { - condicaos2.AddRange(condicaos); - } - dataTable4 = sqlCommand.Select(condicaos2.CreateParameters(0), "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); - List condicaos3 = (vendedorembranco ? new List() - { - new Condicao() - { - Campo = "d.idcontrole", - Valores = nums.CriarValor() - } - } : new List() - { - new Condicao() - { - Campo = "vp.idvendedorparcela", - Valores = null, - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = "d.idcontrole", - Valores = nums.CriarValor() - } - }); - dataTable5 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT DISTINCT vp.IDPARCELA, vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor, p.idsubtipo FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento LEFT OUTER JOIN parcela p on p.idparcela = vp.idparcela WHERE ", ""); - try - { - if (flag2) - { - List nums1 = ( - from x in dataTable3.AsEnumerable().ToList() - select x.Field("iddocumento")).ToList(); - List nums2 = ( - from x in dataTable4.AsEnumerable().ToList() - select x.Field("iddocumento")).ToList(); - nums1.AddRange(nums2); - List condicaos4 = new List() - { - new Condicao() - { - Campo = "DocumentoId", - Valores = nums1.CriarValor() - }, - new Condicao() - { - Campo = "a.excluido", - Valores = null, - Grupo = 2, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "a.excluido", - Valores = 0.CriarValor(), - Grupo = 2, - Operacao = Operacao.Or - } - }; - dataTable6 = sqlCommand.Select(condicaos4.CreateParameters(0), "SELECT DISTINCT a.idnewarquivodigital, a.descricao, ISNULL(s.Status ,0) as Status, s.assinado, s.DocumentoId, s.id, s.UsuarioId, s.Enviado FROM newarquivodigital a LEFT OUTER JOIN ArquivoParaAssinatura s on s.IndiceId = a.idnewarquivodigital WHERE ", ""); - } - } - catch (Exception exception) - { - dataTable6 = null; - } - } - } - } - List nums3 = null; - if (vendedorVinculado != null && vendedorVinculado.Count > 0) - { - nums3 = dataTable5.AsEnumerable().Where((DataRow x) => { - if (!vendedorembranco) - { - if (x.Field("idvendedor") == null) - { - return false; - } - List vendedorUsuarios = vendedorVinculado; - Func u003cu003e9_1116 = DocumentoRepository.u003cu003ec.u003cu003e9__11_16; - if (u003cu003e9_1116 == null) - { - u003cu003e9_1116 = (VendedorUsuario v) => v.Vendedor.Id; - DocumentoRepository.u003cu003ec.u003cu003e9__11_16 = u003cu003e9_1116; - } - return vendedorUsuarios.Select(u003cu003e9_1116).Contains(x.Field("idvendedor")); - } - if (x.Field("idvendedor") == null) - { - return true; - } - List vendedorUsuarios1 = vendedorVinculado; - Func u003cu003e9_1115 = DocumentoRepository.u003cu003ec.u003cu003e9__11_15; - if (u003cu003e9_1115 == null) - { - u003cu003e9_1115 = (VendedorUsuario v) => v.Vendedor.Id; - DocumentoRepository.u003cu003ec.u003cu003e9__11_15 = u003cu003e9_1115; - } - return vendedorUsuarios1.Select(u003cu003e9_1115).Contains(x.Field("idvendedor")); - }).Select((DataRow x) => x.Field("idcontrole")).ToList(); - } - if (nums3 != null && nums3.Count == 0) - { - return new List(); - } - DataRow dataRow1 = dataTable3.AsEnumerable().FirstOrDefault(); - if (dataRow1 != null) - { - num1 = dataRow1.Field("idempresa"); - } - else - { - num1 = (long)1; - } - long num2 = num1; - Vendedor vendedor1 = Auxiliar.Vendedores.Find((Vendedor p) => { - if (!p.Corretora) - { - return false; - } - return p.IdEmpresa == num2; - }); - if (endosso) - { - dataTable3.Merge(dataTable4); - return ( - from x in dataTable3.AsEnumerable().Where((DataRow x) => { - if (nums3 == null) - { - return true; - } - return nums3.Contains(x.Field("idcontrole")); - }).ToList() - orderby x.Field("idcontrole"), x.Field("tipo") - select x).Select((DataRow x) => { - List list; - Func func2 = null; - Func func3 = null; - Documento documento = new Documento() - { - Id = x.Field("iddocumento"), - Controle = new Controle() - { - Id = x.Field("idcontrole"), - IdEmpresa = (x.Field("idempresa") != null ? x.Field("idempresa") : (long)1), - Cliente = new Cliente() - { - Id = idCliente, - Documento = x.Field("cgccpf"), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) - }, - Seguradora = (x.Field("idciaseg") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Field("idciaseg")) : null), - Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Field("idramo")) : null), - Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), - AssistenciaId = x.Field("AssistenciaId") - }, - Ordem = x.Field("ordem"), - TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), - AdicionalComiss = x.Field("adinacomis") == "1", - PremioAdicional = x.Field("pr_adic"), - Proposta = x.Field("proposta"), - Apolice = x.Field("contrato"), - PropostaEndosso = x.Field("pedadit"), - Endosso = x.Field("aditamento"), - Comissao = x.Field("com01"), - Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), - PremioLiquido = x.Field("pr_liq"), - PremioTotal = x.Field("pr_total"), - Vigencia2 = x.Field("vigencia2") - }; - DateTime? nullable = x.Field("vigencia1"); - documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - documento.Emissao = x.Field("emissao"); - documento.Remessa = x.Field("remessa"); - documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.Field("idestipulante")) : null); - documento.NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); - documento.Tipo = x.Field("tipo"); - documento.VendedorPrincipal = (dataTable5.Rows.Count <= 0 || !dataTable5.AsEnumerable().Any((DataRow v1) => { - if (v1.Field("idvendedor") == null || v1.Field("iddocumento") != x.Field("iddocumento")) - { - return false; - } - return v1.Field("idtipovendedor") == (long)1; - }) ? vendedor1 : Auxiliar.Vendedores.Find((Vendedor v) => { - EnumerableRowCollection dataRows = dataTable5.AsEnumerable(); - Func u003cu003e9_26 = func2; - if (u003cu003e9_26 == null) - { - Func func = (DataRow v1) => { - if (v1.Field("iddocumento") != x.Field("iddocumento")) - { - return false; - } - return v1.Field("idtipovendedor") == (long)1; - }; - Func func1 = func; - func2 = func; - u003cu003e9_26 = func1; - } - return dataRows.First(u003cu003e9_26).Field("idvendedor") == v.Id; - })); - documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { - EnumerableRowCollection dataRows = dataTable5.AsEnumerable(); - Func u003cu003e9_27 = func3; - if (u003cu003e9_27 == null) - { - Func func = (DataRow v1) => { - if (v1.Field("idvendedor") == null) - { - return false; - } - return v1.Field("iddocumento") == x.Field("iddocumento"); - }; - Func func1 = func; - func3 = func; - u003cu003e9_27 = func1; - } - EnumerableRowCollection dataRows1 = dataRows.Where(u003cu003e9_27); - Func u003cu003e9_1128 = DocumentoRepository.u003cu003ec.u003cu003e9__11_28; - if (u003cu003e9_1128 == null) - { - u003cu003e9_1128 = (DataRow v1) => v1.Field("idvendedor"); - DocumentoRepository.u003cu003ec.u003cu003e9__11_28 = u003cu003e9_1128; - } - return dataRows1.Select(u003cu003e9_1128).Contains(v.Id); - }).ToList(); - documento.NumeroParcelas = x.Field("numeroParcelas"); - if (!flag2 || dataTable6 == null) - { - list = null; - } - else - { - EnumerableRowCollection dataRows2 = dataTable6.AsEnumerable().Where((DataRow a) => a.Field("DocumentoId") == x.Field("iddocumento")); - Func u003cu003e9_1122 = DocumentoRepository.u003cu003ec.u003cu003e9__11_22; - if (u003cu003e9_1122 == null) - { - u003cu003e9_1122 = (DataRow a) => new StatusDocumentoAssinado() - { - Id = a.Field("idnewarquivodigital"), - Documento = a.Field("descricao"), - Status = (StatusAssinatura)((a.Field("Status") != null ? a.Field("Status") : StatusAssinatura.Pendente)), - Envio = (a.Field("Enviado") != null ? new DateTime?(a.Field("Enviado")) : null), - Usuario = (a.Field("UsuarioId") != null ? Auxiliar.Usuarios.FirstOrDefault((Usuario u) => u.Id == a.Field("UsuarioId")) : null) - }; - DocumentoRepository.u003cu003ec.u003cu003e9__11_22 = u003cu003e9_1122; - } - list = dataRows2.Select(u003cu003e9_1122).ToList(); - } - documento.Assinaturas = list; - documento.Pasta = x.Field("Pasta"); - documento.Banco = new Banco() - { - Nome = x.Field("nomebanco") - }; - documento.Agencia = x.Field("agencia"); - documento.Conta = x.Field("conta"); - documento.Excluido = (x.Field("excluido") == null ? false : x.Field("excluido").ToString() == "1"); - documento.FormaPagamento = new FormaPagamento?((x.Field("formapagamento") == null || !(x.Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.Field("formapagamento").ToString()))); - return documento; - }).ToList(); - } - List documentos2 = new List(); - List nums4 = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(nums); - ( - from x in dataTable3.AsEnumerable().Where((DataRow x) => { - if (nums3 == null) - { - return true; - } - return nums3.Contains(x.Field("idcontrole")); - }).ToList() - orderby x.Field("idcontrole") - group x by x.Field("idcontrole")).ToList>().ForEach((IGrouping x) => { - long? nullable1; - bool count; - bool flag; - long? nullable2; - List statusDocumentoAssinados; - if (x == null || x.FirstOrDefault() == null) - { - return; - } - long num = (x.First().Field("idempresa") != null ? x.First().Field("idempresa") : (long)1); - Cliente cliente = new Cliente() - { - Id = idCliente, - Documento = x.First().Field("cgccpf"), - MalaDireta = new bool?(x.First().Field("MalaDireta").GetValueOrDefault(true)) - }; - Seguradora seguradora = (x.First().Field("idciaseg") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.First().Field("idciaseg")) : null); - Ramo ramo = (x.First().Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.First().Field("idramo")) : null); - Gestor.Model.Domain.Seguros.Produto produto = (x.First().Field("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.First().Field("idproduto")) : null); - EnumerableRowCollection dataRows1 = dataTable5.AsEnumerable().Where((DataRow v) => { - if (v.Field("idvendedor") == null) - { - return false; - } - return v.Field("iddocumento") == x.First().Field("iddocumento"); - }); - DataTable dataTable = (!dataRows1.Any() ? null : dataRows1.CopyToDataTable()); - DataTable dataTable1 = dataTable; - count = (dataTable1 != null ? dataTable1.Rows.Count > 0 : false); - List vendedors = (count ? Auxiliar.Vendedores.Where((Vendedor p) => { - EnumerableRowCollection dataRows = dataTable.AsEnumerable(); - Func u003cu003e9_1145 = DocumentoRepository.u003cu003ec.u003cu003e9__11_45; - if (u003cu003e9_1145 == null) - { - u003cu003e9_1145 = (DataRow v) => v.Field("idvendedor"); - DocumentoRepository.u003cu003ec.u003cu003e9__11_45 = u003cu003e9_1145; - } - return dataRows.Select(u003cu003e9_1145).Contains(p.Id); - }).ToList() : null); - DataTable dataTable2 = dataTable; - flag = (dataTable2 != null ? dataTable2.Rows.Count > 0 : false); - if (flag) - { - EnumerableRowCollection dataRows2 = dataTable.AsEnumerable(); - Func u003cu003e9_1135 = DocumentoRepository.u003cu003ec.u003cu003e9__11_35; - if (u003cu003e9_1135 == null) - { - u003cu003e9_1135 = (DataRow v) => v.Field("idsubtipo"); - DocumentoRepository.u003cu003ec.u003cu003e9__11_35 = u003cu003e9_1135; - } - OrderedEnumerableRowCollection orderedEnumerableRowCollection = dataRows2.OrderBy(u003cu003e9_1135); - Func u003cu003e9_1136 = DocumentoRepository.u003cu003ec.u003cu003e9__11_36; - if (u003cu003e9_1136 == null) - { - u003cu003e9_1136 = (DataRow v) => v.Field("IDPARCELA"); - DocumentoRepository.u003cu003ec.u003cu003e9__11_36 = u003cu003e9_1136; - } - List dataRows3 = orderedEnumerableRowCollection.ThenBy(u003cu003e9_1136).ToList(); - Predicate u003cu003e9_1137 = DocumentoRepository.u003cu003ec.u003cu003e9__11_37; - if (u003cu003e9_1137 == null) - { - u003cu003e9_1137 = (DataRow v) => v.Field("idtipovendedor") == (long)1; - DocumentoRepository.u003cu003ec.u003cu003e9__11_37 = u003cu003e9_1137; - } - DataRow dataRow = dataRows3.Find(u003cu003e9_1137); - if (dataRow != null) - { - nullable2 = new long?(dataRow.Field("idvendedor")); - } - else - { - nullable1 = null; - nullable2 = nullable1; - } - } - else - { - nullable1 = null; - nullable2 = nullable1; - } - long? nullable3 = nullable2; - Vendedor vendedor = (!nullable3.HasValue ? vendedor1 : Auxiliar.Vendedores.Find((Vendedor p) => { - long? nullable = nullable3; - long id = p.Id; - return nullable.GetValueOrDefault() == id & nullable.HasValue; - })); - bool flag1 = (nums4 == null ? false : nums4.Any((long s) => s == x.First().Field("idcontrole"))); - IEnumerable dataRows4 = - from e in dataTable4.AsEnumerable().ToList() - where e.Field("idcontrole") == x.Key - select e; - Func u003cu003e9_1141 = DocumentoRepository.u003cu003ec.u003cu003e9__11_41; - if (u003cu003e9_1141 == null) - { - u003cu003e9_1141 = (DataRow e) => e.Field("tipo"); - DocumentoRepository.u003cu003ec.u003cu003e9__11_41 = u003cu003e9_1141; - } - List dataRows5 = dataRows4.OrderBy(u003cu003e9_1141).ToList(); - List calculos1 = null; - if (dataTable7 != null) - { - EnumerableRowCollection dataRows6 = dataTable7.AsEnumerable().Where((DataRow c) => c.Field("IdDocumento") == x.First().Field("iddocumento")); - Func u003cu003e9_1143 = DocumentoRepository.u003cu003ec.u003cu003e9__11_43; - if (u003cu003e9_1143 == null) - { - u003cu003e9_1143 = (DataRow c) => new Calculo() - { - Id = c.Field("Id"), - DocumentId = c.Field("IdDocumento"), - DataAtualizacao = c.Field("DataAtualizacao"), - Status = (StatusCalculo)c.Field("Status"), - Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field("IdUsuario")) - }; - DocumentoRepository.u003cu003ec.u003cu003e9__11_43 = u003cu003e9_1143; - } - calculos1 = dataRows6.Select(u003cu003e9_1143).ToList(); - if (dataRows5.Count > 0) - { - dataRows5.ForEach((DataRow e) => { - List calculos = calculos1; - EnumerableRowCollection dataRows = dataTable7.AsEnumerable().Where((DataRow c) => c.Field("IdDocumento") == e.Field("iddocumento")); - Func u003cu003e9_1148 = DocumentoRepository.u003cu003ec.u003cu003e9__11_48; - if (u003cu003e9_1148 == null) - { - u003cu003e9_1148 = (DataRow c) => new Calculo() - { - Id = c.Field("Id"), - DocumentId = c.Field("IdDocumento"), - DataAtualizacao = c.Field("DataAtualizacao"), - Status = (StatusCalculo)c.Field("Status"), - Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field("IdUsuario")) - }; - DocumentoRepository.u003cu003ec.u003cu003e9__11_48 = u003cu003e9_1148; - } - calculos.AddRange(dataRows.Select(u003cu003e9_1148).ToList()); - }); - } - } - Documento banco = new Documento() - { - Id = x.First().Field("iddocumento"), - Controle = new Controle() - { - Id = x.Key, - IdEmpresa = num, - Cliente = cliente, - Seguradora = seguradora, - Ramo = ramo, - Produto = produto, - AssistenciaId = x.First().Field("AssistenciaId") - }, - Ordem = x.First().Field("ordem"), - TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.First().Field("tiporecebimento").ToString())), - AdicionalComiss = x.First().Field("adinacomis") == "1", - Proposta = x.First().Field("proposta"), - Apolice = x.First().Field("contrato"), - Endosso = x.First().Field("aditamento"), - Comissao = (x.First().Field("com01") == null ? decimal.Zero : x.First().Field("com01")), - Negocio = new Negocio?((x.First().Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.First().Field("idnegocio").ToString()))), - PremioLiquido = (!x.First().Field("pr_liq").HasValue ? decimal.Zero : x.First().Field("pr_liq")), - PremioAdicional = (!x.First().Field("pr_adic").HasValue ? decimal.Zero : x.First().Field("pr_adic")), - PremioTotal = (!x.First().Field("pr_total").HasValue ? decimal.Zero : x.First().Field("pr_total")), - Vigencia2 = x.First().Field("vigencia2") - }; - DateTime? nullable4 = x.First().Field("vigencia1"); - banco.Vigencia1 = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue); - banco.Emissao = x.First().Field("emissao"); - banco.Remessa = x.First().Field("remessa"); - banco.Estipulante1 = (x.First().Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.First().Field("idestipulante")) : null); - banco.NegocioCorretora = new NegocioCorretora?((x.First().Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.First().Field("negociocorretora").ToString()))); - banco.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.First().Field("situacao").ToString()); - banco.Tipo = x.First().Field("tipo"); - banco.VendedorPrincipal = vendedor; - banco.Sinistro = flag1; - banco.TemEndosso = dataRows5.Count > 0; - banco.Vendedores = vendedors; - banco.Observacao = x.First().Field("Obs"); - banco.NumeroParcelas = x.First().Field("numeroParcelas"); - if (!flag2 || dataTable6 == null) - { - statusDocumentoAssinados = null; - } - else - { - EnumerableRowCollection dataRows7 = dataTable6.AsEnumerable().Where((DataRow a) => a.Field("DocumentoId") == x.First().Field("iddocumento")); - Func u003cu003e9_1152 = DocumentoRepository.u003cu003ec.u003cu003e9__11_52; - if (u003cu003e9_1152 == null) - { - u003cu003e9_1152 = (DataRow a) => new StatusDocumentoAssinado() - { - Id = a.Field("idnewarquivodigital"), - Documento = a.Field("descricao"), - Status = (StatusAssinatura)((a.Field("Status") != null ? a.Field("Status") : StatusAssinatura.Pendente)), - Envio = (a.Field("Enviado") != null ? new DateTime?(a.Field("Enviado")) : null), - Usuario = (a.Field("UsuarioId") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == a.Field("UsuarioId")) : null) - }; - DocumentoRepository.u003cu003ec.u003cu003e9__11_52 = u003cu003e9_1152; - } - statusDocumentoAssinados = dataRows7.Select(u003cu003e9_1152).ToList(); - } - banco.Assinaturas = statusDocumentoAssinados; - banco.Pasta = x.First().Field("Pasta"); - banco.Banco = new Banco() - { - Nome = x.First().Field("nomebanco") - }; - banco.Agencia = x.First().Field("agencia"); - banco.Conta = x.First().Field("conta"); - banco.Excluido = (x.First().Field("excluido") == null ? false : x.First().Field("excluido").ToString() == "1"); - banco.NumeroCartao = x.First().Field("numeroCart"); - banco.VencimentoCartao = x.First().Field("vencimentoCart"); - banco.NomeProponente = x.First().Field("nomeProp"); - banco.Calculos = calculos1; - banco.FormaPagamento = new FormaPagamento?((x.First().Field("formapagamento") == null || !(x.First().Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.First().Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.First().Field("formapagamento").ToString()))); - Documento documento1 = banco; - List documentos = new List() - { - documento1 - }; - if (dataRows5.Count > 0) - { - List dataRows8 = dataRows5; - Func u003cu003e9_1154 = DocumentoRepository.u003cu003ec.u003cu003e9__11_54; - if (u003cu003e9_1154 == null) - { - u003cu003e9_1154 = (DataRow e) => e.Field("ordem"); - DocumentoRepository.u003cu003ec.u003cu003e9__11_54 = u003cu003e9_1154; - } - documentos.AddRange(dataRows8.OrderBy(u003cu003e9_1154).Select((DataRow e) => { - List list; - Documento documento = new Documento() - { - Id = e.Field("iddocumento"), - Controle = new Controle() - { - Id = x.Key, - IdEmpresa = num, - Cliente = cliente, - Seguradora = seguradora, - Ramo = ramo, - Produto = produto, - AssistenciaId = x.First().Field("AssistenciaId") - }, - Ordem = e.Field("ordem"), - TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), e.Field("tiporecebimento").ToString())), - AdicionalComiss = e.Field("adinacomis") == "1", - Proposta = e.Field("proposta"), - Apolice = e.Field("contrato"), - PropostaEndosso = e.Field("pedadit"), - Endosso = e.Field("aditamento"), - Comissao = (e.Field("com01") == null ? decimal.Zero : e.Field("com01")), - Negocio = new Negocio?((e.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), e.Field("idnegocio").ToString()))), - PremioLiquido = e.Field("pr_liq"), - PremioAdicional = e.Field("pr_adic"), - PremioTotal = e.Field("pr_total"), - Vigencia2 = e.Field("vigencia2") - }; - DateTime? nullable = e.Field("vigencia1"); - documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - documento.Emissao = e.Field("emissao"); - documento.Remessa = e.Field("remessa"); - documento.Estipulante1 = (e.Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == e.Field("idestipulante")) : null); - documento.NegocioCorretora = new NegocioCorretora?((e.Field("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), e.Field("negociocorretora").ToString()))); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), e.Field("situacao").ToString()); - documento.Tipo = e.Field("tipo"); - documento.Sinistro = flag1; - documento.NumeroParcelas = e.Field("numeroParcelas"); - if (!flag2 || dataTable6 == null) - { - list = null; - } - else - { - EnumerableRowCollection dataRows = dataTable6.AsEnumerable().Where((DataRow a) => a.Field("DocumentoId") == e.Field("iddocumento")); - Func u003cu003e9_1158 = DocumentoRepository.u003cu003ec.u003cu003e9__11_58; - if (u003cu003e9_1158 == null) - { - u003cu003e9_1158 = (DataRow a) => new StatusDocumentoAssinado() - { - Id = a.Field("idnewarquivodigital"), - Documento = a.Field("descricao"), - Status = (StatusAssinatura)((a.Field("Status") != null ? a.Field("Status") : StatusAssinatura.Pendente)), - Envio = (a.Field("Enviado") != null ? new DateTime?(a.Field("Enviado")) : null), - Usuario = (a.Field("UsuarioId") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == a.Field("UsuarioId")) : null) - }; - DocumentoRepository.u003cu003ec.u003cu003e9__11_58 = u003cu003e9_1158; - } - list = dataRows.Select(u003cu003e9_1158).ToList(); - } - documento.Assinaturas = list; - documento.Pasta = e.Field("Pasta"); - documento.Banco = new Banco() - { - Nome = e.Field("nomebanco") - }; - documento.Agencia = e.Field("agencia"); - documento.Conta = e.Field("conta"); - documento.Excluido = (e.Field("excluido") == null ? false : e.Field("excluido").ToString() == "1"); - documento.FormaPagamento = new FormaPagamento?((x.First().Field("formapagamento") == null || !(x.First().Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.First().Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.First().Field("formapagamento").ToString()))); - return documento; - }).ToList()); - } - documento1.Controle.Documentos = documentos; - documentos2.Add(documento1); - }); - return documentos2; - } - default: - { - condicaos1.AddRange(new List() - { - new Condicao() - { - Campo = "d.situacao", - Valores = new List() - { - 1, - 2, - 4 - } - }, - new Condicao() - { - Campo = "d.vigencia2", - Valores = null, - Grupo = 2, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.vigencia2", - Valores = date.AddDays(-5).CriarValor(), - Grupo = 2, - Operacao = Operacao.Or, - Operador = Operador.Maior - } - }); - goto case FiltroStatusDocumento.Todos; - } - } - return documentos1; - } - - public List FindByControle(long id) - { - List list = ( - from x in base.All() - where x.Controle.Id == id && !x.Excluido - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Documento FindById(long id, bool itens = false, bool sinistrosPorControle = false) - { - DocumentoDb documentoDb = base.FindEntityById(id); - Documento documento = ApplicationMapper.Mapper.Map(documentoDb); - if (documento == null) - { - return null; - } - documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(id); - documento.Sinistro = (sinistrosPorControle ? this.HasSinistroPorControle(documento.Controle.Id) : this.HasSinistro(documento.Id)); - if (itens) - { - documento.ItensAtivo = (new ItemRepository(this._unitOfWork)).FindByDocumentsIds(documento.Controle.Id, StatusItem.Ativos, false); - } - return documento; - } - - public Documento FindById(long id, List vendedorVinculado) - { - DocumentoDb documentoDb = base.FindEntityById(id); - Documento documento = ApplicationMapper.Mapper.Map(documentoDb); - if (documento == null) - { - return null; - } - documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(id); - documento.Vendedores = (new VendedorParcelaRepository(this._unitOfWork)).FindVendedoresByDocumentId(id); - documento.Sinistro = this.HasSinistro(documento.Id); - if (vendedorVinculado.Count <= 0) - { - return documento; - } - if (!documento.Vendedores.Any((Vendedor y) => { - List vendedorUsuarios = vendedorVinculado; - Func u003cu003e9_31 = DocumentoRepository.u003cu003ec.u003cu003e9__3_1; - if (u003cu003e9_31 == null) - { - u003cu003e9_31 = (VendedorUsuario x) => x.Vendedor.Id; - DocumentoRepository.u003cu003ec.u003cu003e9__3_1 = u003cu003e9_31; - } - return vendedorUsuarios.Select(u003cu003e9_31).Contains(y.Id); - })) - { - return null; - } - return documento; - } - - public List FindByIds(List ids) - { - if (ids == null || ids.Count == 0) - { - return new List(); - } - return this.Select((new List() - { - new Condicao() - { - Campo = "d.iddocumento", - Valores = ids.CriarValor() - } - }).CreateParameters(0)); - } - - public List FindByLicenciamento(Filtros filtro) - { - List j; - List documentos; - object connection; - List nums = null; - long num; - List nums1 = new List(); - for (int i1 = filtro.ValorInicio; i1 <= filtro.ValorFim; i1++) - { - nums1.Add(i1); - } - string str = string.Concat("AND SUBSTRING(a.placa, len(a.placa), 1) IN ('", string.Join("','", - from v in nums1 - select v), "')"); - string str1 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", - from v in filtro.Status - select v), ")")); - string str2 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", - from v in filtro.Negocio - select v), ")")); - string str3 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", - from v in filtro.Seguradoras - select v), ")")); - string str4 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", - from v in filtro.Ramos - select v), ")")); - string str5 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", - from v in filtro.Produtos - select v), ")")); - string str6 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", - from v in filtro.Vendedores - select v), ")")); - string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", - from v in filtro.Estipulantes - select v), ")")); - string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - DataTable dataTable2 = new DataTable(); - DataTable dataTable3 = new DataTable(); - DataTable dataTable4 = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str9 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao, a.placa, a.idcategoria FROM auto a INNER JOIN item i ON a.iditem = i.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (d.excluido IS NULL OR d.excluido = '0') AND d.situacao in (1,2,4) AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL AND a.placa IS NOT NULL "; - string str10 = "SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf as documento, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.remessa, d.aditamento as endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.pasta, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp WHERE (d.excluido IS NULL OR d.excluido = 0) AND d.vigencia2 >= GETDATE() "; - string str11 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; - string str12 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; - sqlCommand.CommandText = string.Concat(str9, " ", str); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable2); - } - if (dataTable2.Rows.Count != 0) - { - for (j = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("iddocumento")).Distinct().ToList(); j.Count > 0; j = nums) - { - List nums2 = j.Take(2000).ToList(); - string str13 = string.Concat(" AND d.iddocumento IN (", string.Join(",", nums2), ")"); - DataTable dataTable5 = new DataTable(); - sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str8, " ", str13, " ", str1, " ", str2, " ", str3, " ", str4, " ", str5, " ", str7, " ", str6 }); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable5); - } - dataTable.Merge(dataTable5); - nums = (nums2.Count < 2000 ? new List() : j.Except(nums2).ToList()); - } - if (dataTable.Rows.Count != 0) - { - if (dataTable.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null)) - { - string str14 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")"); - DataTable dataTable6 = new DataTable(); - sqlCommand.CommandText = string.Concat(new string[] { str11, " ", str14, " ", str6 }); - using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) - { - sqlDataAdapter2.SelectCommand = sqlCommand; - sqlDataAdapter2.Fill(dataTable6); - } - foreach (DataRow row in dataTable.Rows) - { - if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) - { - continue; - } - string str15 = string.Format("idcontrole = {0}", row["idcontrole"]); - DataRow[] dataRowArray = dataTable6.Select(str15); - if (dataRowArray.Length == 0) - { - continue; - } - row["idvendedor"] = dataRowArray[0][1]; - } - } - j = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).Distinct().ToList(); - string str16 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat(str12, " ", str16); - using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) - { - sqlDataAdapter3.SelectCommand = sqlCommand; - sqlDataAdapter3.Fill(dataTable1); - } - while (j.Count > 0) - { - List nums3 = j.Take(2100).ToList(); - string str17 = string.Concat(" AND idcliente IN (", string.Join(",", nums3), ")"); - DataTable dataTable7 = new DataTable(); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') ", str17); - using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) - { - sqlDataAdapter4.SelectCommand = sqlCommand; - sqlDataAdapter4.Fill(dataTable7); - } - dataTable3.Merge(dataTable7); - dataTable7 = new DataTable(); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 ", str17); - using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter()) - { - sqlDataAdapter5.SelectCommand = sqlCommand; - sqlDataAdapter5.Fill(dataTable7); - } - dataTable4.Merge(dataTable7); - j = (nums3.Count < 2100 ? new List() : j.Except(nums3).ToList()); - } - goto Label0; - } - else - { - documentos = new List(); - } - } - else - { - documentos = new List(); - } - } - } - return documentos; - Label0: - return dataTable.AsEnumerable().ToList().Select((DataRow x) => { - Func func2 = null; - Documento documento = new Documento() - { - Id = x.Field("id") - }; - Controle controle = new Controle() - { - IdEmpresa = x.Field("idempresa") - }; - Cliente cliente = new Cliente() - { - Id = x.Field("idcliente"), - Nome = x.Field("cliente"), - Documento = x.Field("documento"), - IdEmpresa = x.Field("idempresa") - }; - EnumerableRowCollection dataRows1 = dataTable4.AsEnumerable().Where((DataRow t) => t.Field("idcliente") == x.Field("idcliente")); - Func u003cu003e9_1525 = DocumentoRepository.u003cu003ec.u003cu003e9__15_25; - if (u003cu003e9_1525 == null) - { - u003cu003e9_1525 = (DataRow t) => new ClienteTelefone() - { - Id = t.Field("idclitelefone"), - Prefixo = t.Field("ddd"), - Numero = t.Field("fone") - }; - DocumentoRepository.u003cu003ec.u003cu003e9__15_25 = u003cu003e9_1525; - } - cliente.Telefones = new ObservableCollection(dataRows1.Select(u003cu003e9_1525)); - EnumerableRowCollection dataRows2 = dataTable3.AsEnumerable().Where((DataRow t) => t.Field("idcliente") == x.Field("idcliente")); - Func u003cu003e9_1527 = DocumentoRepository.u003cu003ec.u003cu003e9__15_27; - if (u003cu003e9_1527 == null) - { - u003cu003e9_1527 = (DataRow t) => new ClienteEmail() - { - Id = t.Field("idclimail"), - Email = t.Field("email") - }; - DocumentoRepository.u003cu003ec.u003cu003e9__15_27 = u003cu003e9_1527; - } - cliente.Emails = new ObservableCollection(dataRows2.Select(u003cu003e9_1527)); - cliente.Pasta = x.Field("pastacliente"); - cliente.MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)); - controle.Cliente = cliente; - controle.Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null); - controle.Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null); - controle.Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null); - controle.AssistenciaId = x.Field("AssistenciaId"); - documento.Controle = controle; - documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela); - documento.AdicionalComiss = x.Field("adinacomiss") == "1"; - documento.Apolice = x.Field("apolice"); - documento.Endosso = (x.Field("tipo") == 0 ? "" : x.Field("endosso") ?? ""); - documento.Comissao = x.Field("comissao"); - documento.Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))); - documento.PremioLiquido = x.Field("liquido"); - documento.PremioTotal = x.Field("total"); - documento.Vigencia2 = x.Field("vigenciafinal"); - DateTime? nullable2 = x.Field("vigenciainicial"); - documento.Vigencia1 = (nullable2.HasValue ? nullable2.GetValueOrDefault() : DateTime.MinValue); - documento.Emissao = x.Field("emissao"); - documento.Remessa = x.Field("remessa"); - documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); - documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); - documento.NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); - documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { - List list = dataTable1.AsEnumerable().ToList(); - Func u003cu003e9_28 = func2; - if (u003cu003e9_28 == null) - { - Func func = (DataRow d) => d.Field("id") == x.Field("id"); - Func func1 = func; - func2 = func; - u003cu003e9_28 = func1; - } - IEnumerable dataRows = list.Where(u003cu003e9_28); - Func u003cu003e9_1529 = DocumentoRepository.u003cu003ec.u003cu003e9__15_29; - if (u003cu003e9_1529 == null) - { - u003cu003e9_1529 = (DataRow d) => d.Field("idvendedor"); - DocumentoRepository.u003cu003ec.u003cu003e9__15_29 = u003cu003e9_1529; - } - return dataRows.Select(u003cu003e9_1529).ToList().Contains(v.Id); - }).ToList(); - documento.Tipo = x.Field("tipo"); - documento.DataControle = x.Field("datacontrole"); - documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); - documento.ItensAtivo = new List(dataTable2.AsEnumerable().ToList().Where((DataRow i) => { - if (i.Field("idcontrole") == null || !long.TryParse(i.Field("idcontrole").ToString(), out num)) - { - return false; - } - return i.Field("idcontrole") == x.Field("idcontrole"); - }).Select((DataRow i) => { - Categoria? nullable; - Categoria? nullable1; - Item item = new Item() - { - Id = i.Field("iditem"), - Descricao = i.Field("descricao"), - Documento = new Documento() - { - Id = x.Field("id") - } - }; - Auto auto = new Auto(); - if (i.Field("idcategoria") == null) - { - nullable = null; - nullable1 = nullable; - } - else if (i.Field("idcategoria").ToString() == "") - { - nullable = null; - nullable1 = nullable; - } - else - { - nullable1 = (Categoria?)Enum.Parse(typeof(Categoria), i.Field("idcategoria").ToString()); - } - auto.Categoria = nullable1; - auto.Placa = i.Field("placa"); - item.Auto = auto; - return item; - }).ToList()); - documento.Pasta = x.Field("Pasta"); - return documento; - }).ToList(); - } - - public List FindByParcelaIds(List ids) - { - if (ids == null || ids.Count == 0) - { - return new List(); - } - List nums = (new ParcelaRepository(this._unitOfWork)).FindDocumentId(ids); - return this.Select((new List() - { - new Condicao() - { - Campo = "d.iddocumento", - Valores = nums.CriarValor() - } - }).CreateParameters(0)); - } - - public List FindByPlaca(Filtros filtro) - { - List i; - List documentos1; - object connection; - List nums = null; - string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", - from v in filtro.Status - select v), ")")); - string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", - from v in filtro.Negocio - select v), ")")); - string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", - from v in filtro.Seguradoras - select v), ")")); - string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", - from v in filtro.Ramos - select v), ")")); - string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", - from v in filtro.Produtos - select v), ")")); - string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", - from v in filtro.Vendedores - select v), ")")); - string str6 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", - from v in filtro.Estipulantes - select v), ")")); - string str7 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - DataTable dataTable2 = new DataTable(); - DataTable dataTable3 = new DataTable(); - DataTable dataTable4 = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - object date = filtro.Inicio.Date; - DateTime fim = filtro.Fim; - string str8 = string.Format("SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao, a.placa, a.idcategoria FROM auto a INNER JOIN item i ON a.iditem = i.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (d.excluido IS NULL OR d.excluido = '0') {0} AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL AND d.vigencia2 >= '{1:yyyy-MM-dd}' AND d.vigencia2 <= '{2:yyyy-MM-dd}'", str, date, fim.Date); - object obj = filtro.Inicio.Date; - fim = filtro.Fim; - string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf as documento, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.remessa, d.aditamento as endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.pasta, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp ", string.Format("WHERE (d.excluido IS NULL OR d.excluido = 0) AND d.vigencia2 >= '{0:yyyy-MM-dd}' AND d.vigencia2 <= '{1:yyyy-MM-dd}'", obj, fim.Date)); - string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; - string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; - sqlCommand.CommandText = str8 ?? ""; - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable2); - } - if (dataTable2.Rows.Count != 0) - { - for (i = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("iddocumento")).Distinct().ToList(); i.Count > 0; i = nums) - { - List nums1 = i.Take(2000).ToList(); - string str12 = string.Concat(" AND d.iddocumento IN (", string.Join(",", nums1), ")"); - DataTable dataTable5 = new DataTable(); - sqlCommand.CommandText = string.Concat(new string[] { str9, " ", str7, " ", str12, " ", str, " ", str1, " ", str2, " ", str3, " ", str4, " ", str6, " ", str5 }); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable5); - } - dataTable.Merge(dataTable5); - nums = (nums1.Count < 2000 ? new List() : i.Except(nums1).ToList()); - } - if (dataTable.Rows.Count != 0) - { - if (dataTable.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null)) - { - string str13 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")"); - DataTable dataTable6 = new DataTable(); - sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str13, " ", str5 }); - using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) - { - sqlDataAdapter2.SelectCommand = sqlCommand; - sqlDataAdapter2.Fill(dataTable6); - } - foreach (DataRow row in dataTable.Rows) - { - if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) - { - continue; - } - string str14 = string.Format("idcontrole = {0}", row["idcontrole"]); - DataRow[] dataRowArray = dataTable6.Select(str14); - if (dataRowArray.Length == 0) - { - continue; - } - row["idvendedor"] = dataRowArray[0][1]; - } - } - i = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).Distinct().ToList(); - string str15 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat(str11, " ", str15); - using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) - { - sqlDataAdapter3.SelectCommand = sqlCommand; - sqlDataAdapter3.Fill(dataTable1); - } - while (i.Count > 0) - { - List nums2 = i.Take(2100).ToList(); - string str16 = string.Concat(" AND idcliente IN (", string.Join(",", nums2), ")"); - DataTable dataTable7 = new DataTable(); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') ", str16); - using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) - { - sqlDataAdapter4.SelectCommand = sqlCommand; - sqlDataAdapter4.Fill(dataTable7); - } - dataTable3.Merge(dataTable7); - dataTable7 = new DataTable(); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 ", str16); - using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter()) - { - sqlDataAdapter5.SelectCommand = sqlCommand; - sqlDataAdapter5.Fill(dataTable7); - } - dataTable4.Merge(dataTable7); - i = (nums2.Count < 2100 ? new List() : i.Except(nums2).ToList()); - } - goto Label0; - } - else - { - documentos1 = new List(); - } - } - else - { - documentos1 = new List(); - } - } - } - return documentos1; - Label0: - List documentos2 = new List(); - dataTable.AsEnumerable().ToList().ForEach((DataRow apolice) => { - Func func2 = null; - List documentos = documentos2; - Documento documento = new Documento() - { - Id = apolice.Field("id") - }; - Controle controle = new Controle() - { - IdEmpresa = apolice.Field("idempresa") - }; - Cliente cliente = new Cliente() - { - Id = apolice.Field("idcliente"), - Nome = apolice.Field("cliente"), - Documento = apolice.Field("documento"), - IdEmpresa = apolice.Field("idempresa") - }; - EnumerableRowCollection dataRows1 = dataTable4.AsEnumerable().Where((DataRow fone) => fone.Field("idcliente") == apolice.Field("idcliente")); - Func u003cu003e9_1624 = DocumentoRepository.u003cu003ec.u003cu003e9__16_24; - if (u003cu003e9_1624 == null) - { - u003cu003e9_1624 = (DataRow fone) => new ClienteTelefone() - { - Id = fone.Field("idclitelefone"), - Prefixo = fone.Field("ddd"), - Numero = fone.Field("fone") - }; - DocumentoRepository.u003cu003ec.u003cu003e9__16_24 = u003cu003e9_1624; - } - cliente.Telefones = new ObservableCollection(dataRows1.Select(u003cu003e9_1624)); - EnumerableRowCollection dataRows2 = dataTable3.AsEnumerable().Where((DataRow mail) => mail.Field("idcliente") == apolice.Field("idcliente")); - Func u003cu003e9_1626 = DocumentoRepository.u003cu003ec.u003cu003e9__16_26; - if (u003cu003e9_1626 == null) - { - u003cu003e9_1626 = (DataRow mail) => new ClienteEmail() - { - Id = mail.Field("idclimail"), - Email = mail.Field("email") - }; - DocumentoRepository.u003cu003ec.u003cu003e9__16_26 = u003cu003e9_1626; - } - cliente.Emails = new ObservableCollection(dataRows2.Select(u003cu003e9_1626)); - cliente.Pasta = apolice.Field("pastacliente"); - cliente.MalaDireta = new bool?(apolice.Field("MalaDireta").GetValueOrDefault(true)); - controle.Cliente = cliente; - controle.Seguradora = (apolice.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora seguradora) => seguradora.Id == apolice.Field("idseguradora")) : null); - controle.Ramo = (apolice.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo ramo) => ramo.Id == apolice.Field("idramo")) : null); - controle.Produto = (apolice.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto produto) => produto.Id == apolice.Field("idproduto")) : null); - controle.AssistenciaId = apolice.Field("AssistenciaId"); - documento.Controle = controle; - documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela); - documento.AdicionalComiss = apolice.Field("adinacomiss") == "1"; - documento.Apolice = apolice.Field("apolice"); - documento.Endosso = (apolice.Field("tipo") == 0 ? "" : apolice.Field("endosso") ?? ""); - documento.Comissao = apolice.Field("comissao"); - documento.Negocio = new Negocio?((apolice.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), apolice.Field("idnegocio").ToString()))); - documento.PremioLiquido = apolice.Field("liquido"); - documento.PremioTotal = apolice.Field("total"); - documento.Vigencia2 = apolice.Field("vigenciafinal"); - DateTime? nullable2 = apolice.Field("vigenciainicial"); - documento.Vigencia1 = (nullable2.HasValue ? nullable2.GetValueOrDefault() : DateTime.MinValue); - documento.Emissao = apolice.Field("emissao"); - documento.Remessa = apolice.Field("remessa"); - documento.VendedorPrincipal = (apolice.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor vendedor) => vendedor.Id == apolice.Field("idvendedor")) : null); - documento.Estipulante1 = (apolice.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante estipulante) => estipulante.Id == apolice.Field("idestipulante")) : null); - documento.NegocioCorretora = new NegocioCorretora?((apolice.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), apolice.Field("situacao").ToString()) != TipoSeguro.Renovacao || apolice.Field("idnegocio") == null || !(apolice.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), apolice.Field("negociocorretora").ToString()))); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), apolice.Field("situacao").ToString()); - documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor vendedor) => { - List list = dataTable1.AsEnumerable().ToList(); - Func u003cu003e9_27 = func2; - if (u003cu003e9_27 == null) - { - Func func = (DataRow d) => d.Field("id") == apolice.Field("id"); - Func func1 = func; - func2 = func; - u003cu003e9_27 = func1; - } - IEnumerable dataRows = list.Where(u003cu003e9_27); - Func u003cu003e9_1628 = DocumentoRepository.u003cu003ec.u003cu003e9__16_28; - if (u003cu003e9_1628 == null) - { - u003cu003e9_1628 = (DataRow d) => d.Field("idvendedor"); - DocumentoRepository.u003cu003ec.u003cu003e9__16_28 = u003cu003e9_1628; - } - return dataRows.Select(u003cu003e9_1628).ToList().Contains(vendedor.Id); - }).ToList(); - documento.Tipo = apolice.Field("tipo"); - documento.DataControle = apolice.Field("datacontrole"); - documento.Status = (apolice.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status status) => status.Id == apolice.Field("idstatus")) : null); - documento.ItensAtivo = new List(( - from item in dataTable2.AsEnumerable().ToList() - where item.Field("iddocumento") == apolice.Field("id") - select item).Select((DataRow item) => { - Categoria? nullable; - Categoria? nullable1; - Item item1 = new Item() - { - Id = item.Field("iditem"), - Descricao = item.Field("descricao"), - Documento = new Documento() - { - Id = apolice.Field("id") - } - }; - Auto auto = new Auto(); - if (item.Field("idcategoria") == null) - { - nullable = null; - nullable1 = nullable; - } - else if (item.Field("idcategoria").ToString() == "") - { - nullable = null; - nullable1 = nullable; - } - else - { - nullable1 = (Categoria?)Enum.Parse(typeof(Categoria), item.Field("idcategoria").ToString()); - } - auto.Categoria = nullable1; - auto.Placa = item.Field("placa"); - item1.Auto = auto; - return item1; - }).ToList()); - documento.Pasta = apolice.Field("Pasta"); - documentos.Add(documento); - }); - return documentos2; - } - - public List FindByVigenciaFinal(Filtros filtro, List licencas, bool somarPremios) - { - List j; - List documentos; - object connection; - bool count; - List nums1 = null; - List nums2 = null; - List nums3 = null; - List nums4 = null; - List condicaos = this.CriaCondicaoDocumento(filtro, "CAST(d.vigencia2 AS DATE)"); - condicaos.AddRange(new List() - { - new Condicao() - { - Campo = "d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }); - condicaos.Add(new Condicao() - { - Campo = "d.tipo", - Valores = 0.CriarValor() - }); - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - DataTable dataTable2 = new DataTable(); - DataTable dataTable3 = new DataTable(); - DataTable dataTable4 = new DataTable(); - DataTable dataTable5 = new DataTable(); - DataTable dataTable6 = null; - DataTable dataTable7 = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - string str = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf, d.idcontrole, d.iddocumento as id, d.contrato as apolice, CASE WHEN d2.aditamento <>'' THEN 'SIM' ELSE 'NÃO' END AS endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.apol_antes, d.remessa, d.emissao, d.pr_adic, d.pr_iof, d.pr_custo, d.datacontrole, d.idstatus, d.pasta, d.idbanco, cb.nomebanco, d.agencia, d.conta, cl.pasta as pastacliente, c.AssistenciaId, d.tiporecebimento FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco OUTER APPLY (SELECT TOP 1 aditamento FROM documento WHERE idcontrole = d.idcontrole AND tipo = '1') d2 ", (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 vp.idvendedor FROM vendedorparcela vp INNER JOIN parcela parc ON parc.IdParcela = vp.IdParcela WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1 ORDER BY PARC.IDSUBTIPO, CAST(parc.Parcela as int) DESC) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", - from v in filtro.TipoVendedor - select v), ")")), " WHERE "); - string str1 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento INNER JOIN parcela p ON p.idparcela = vp.idparcela WHERE "; - string str2 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE "; - string str3 = "SELECT DISTINCT idcontrolesinistro, idcontrole as id, cs.iditem FROM controlesinistro cs INNER JOIN item i on i.iditem = cs.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE "; - string str4 = "SELECT DISTINCT idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE "; - string str5 = "SELECT DISTINCT idclimail, email, idcliente as id FROM climail WHERE "; - string str6 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE "; - dataTable = sqlCommand.Select(condicaos.CreateParameters(0), str, ""); - if (dataTable == null || dataTable.Rows.Count == 0) - { - documentos = new List(); - } - else - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - for (List i1 = dataTable.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole")).ToList(); i1.Count > 0; i1 = nums1) - { - List nums5 = i1.Take(1000).ToList(); - List condicaos1 = new List() - { - new Condicao() - { - Campo = "d.idcontrole", - Valores = nums5.CriarValor() - }, - new Condicao() - { - Campo = "p.parcela", - Operador = Operador.Diferente, - Valores = "999".CriarValor() - } - }; - List vendedores = filtro.Vendedores; - if (vendedores != null) - { - count = vendedores.Count > 0; - } - else - { - count = false; - } - if (count) - { - condicaos1.Add(new Condicao() - { - Campo = "vp.idvendedor", - Valores = filtro.Vendedores.CriarValor() - }); - } - DataTable dataTable8 = sqlCommand.Select(condicaos1.CreateParameters(0), str1, ""); - foreach (DataRow row in dataTable.Rows) - { - if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) - { - continue; - } - string str7 = string.Format("idcontrole = {0}", row["idcontrole"]); - DataRow[] dataRowArray = dataTable8.Select(str7); - if (dataRowArray.Length == 0) - { - continue; - } - row["idvendedor"] = dataRowArray[0][1]; - } - nums1 = (nums5.Count < 1000 ? new List() : i1.Except(nums5).ToList()); - } - for (j = dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcliente")).Distinct().ToList(); j.Count > 0; j = nums2) - { - List nums6 = j.Take(1000).ToList(); - List condicaos2 = new List() - { - new Condicao() - { - Campo = "idcliente", - Valores = nums6.CriarValor() - } - }; - DataTable dataTable9 = sqlCommand.Select(condicaos2.CreateParameters(0), str4, ""); - dataTable4.Merge(dataTable9); - dataTable9 = sqlCommand.Select(condicaos2.CreateParameters(0), str5, ""); - dataTable3.Merge(dataTable9); - nums2 = (nums6.Count < 1000 ? new List() : j.Except(nums6).ToList()); - } - for (j = dataTable.AsEnumerable().Select((DataRow v) => v.Field("id")).Distinct().ToList(); j.Count > 0; j = nums3) - { - List nums7 = j.Take(1000).ToList(); - List condicaos3 = new List() - { - new Condicao() - { - Campo = "vp.iddocumento", - Valores = nums7.CriarValor() - } - }; - DataTable dataTable10 = sqlCommand.Select(condicaos3.CreateParameters(0), str2, ""); - dataTable1.Merge(dataTable10); - nums3 = (nums7.Count < 1000 ? new List() : j.Except(nums7).ToList()); - } - for (j = dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole")).Distinct().ToList(); j.Count > 0; j = nums4) - { - List nums8 = j.Take(1000).ToList(); - List condicaos4 = new List() - { - new Condicao() - { - Campo = "d.idcontrole", - Valores = nums8.CriarValor() - } - }; - List condicaos5 = new List(); - condicaos5.AddRange(condicaos4); - DataTable dataTable11 = sqlCommand.Select(condicaos5.CreateParameters(0), str3, ""); - dataTable2.Merge(dataTable11); - condicaos5.AddRange(new List() - { - new Condicao() - { - Campo = "idsubstituido", - Valores = null - }, - new Condicao() - { - Campo = "cancelado", - Valores = null, - Operacao = Operacao.Or, - Grupo = 1 - }, - new Condicao() - { - Campo = "cancelado", - Valores = 0.CriarValor(), - Operacao = Operacao.Or, - Grupo = 1 - } - }); - dataTable11 = sqlCommand.Select(condicaos5.CreateParameters(0), str6, ""); - dataTable5.Merge(dataTable11); - licencas.Any((Licenca x) => { - if (x.Produto != Gestor.Model.License.Produto.AggilizadorCalculos && x.Produto != Gestor.Model.License.Produto.AggilizadorCalculosIndependente) - { - return false; - } - return x.Status != 3; - }); - if (somarPremios) - { - condicaos4.AddRange(new List() - { - new Condicao() - { - Campo = "d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - } - }); - DataTable dataTable12 = sqlCommand.Select(condicaos4.CreateParameters(0), "SELECT d.iddocumento, d.idcontrole, ISNULL(d.pr_liq ,0) AS pr_liq, ISNULL(d.pr_total ,0) AS pr_total FROM documento d WHERE", ""); - dataTable7.Merge(dataTable12); - } - nums4 = (nums8.Count < 1000 ? new List() : j.Except(nums8).ToList()); - } - goto Label0; - } - } - } - return documentos; - Label0: - List documentos1 = new List(); - dataTable.AsEnumerable().ToList().ForEach((DataRow x) => { - DateTime? nullable; - List list; - decimal num; - decimal num1; - DateTime? nullable1; - DateTime? nullable2; - EnumerableRowCollection dataRows1 = dataTable1.AsEnumerable().Where((DataRow d) => d.Field("id") == x.Field("id")); - Func u003cu003e9_269 = DocumentoRepository.u003cu003ec.u003cu003e9__26_9; - if (u003cu003e9_269 == null) - { - u003cu003e9_269 = (DataRow d) => d.Field("idvendedor"); - DocumentoRepository.u003cu003ec.u003cu003e9__26_9 = u003cu003e9_269; - } - List nums = dataRows1.Select(u003cu003e9_269).ToList(); - IEnumerable list1 = - from t in dataTable4.AsEnumerable().ToList() - where t.Field("id") == x.Field("idcliente") - select t; - Func u003cu003e9_2611 = DocumentoRepository.u003cu003ec.u003cu003e9__26_11; - if (u003cu003e9_2611 == null) - { - u003cu003e9_2611 = (DataRow t) => new ClienteTelefone() - { - Prefixo = t.Field("ddd"), - Numero = t.Field("fone") - }; - DocumentoRepository.u003cu003ec.u003cu003e9__26_11 = u003cu003e9_2611; - } - List clienteTelefones = list1.Select(u003cu003e9_2611).ToList(); - IEnumerable list2 = - from t in dataTable3.AsEnumerable().ToList() - where t.Field("id") == x.Field("idcliente") - select t; - Func u003cu003e9_2613 = DocumentoRepository.u003cu003ec.u003cu003e9__26_13; - if (u003cu003e9_2613 == null) - { - u003cu003e9_2613 = (DataRow t) => new ClienteEmail() - { - Email = t.Field("email") - }; - DocumentoRepository.u003cu003ec.u003cu003e9__26_13 = u003cu003e9_2613; - } - List clienteEmails = list2.Select(u003cu003e9_2613).ToList(); - List items = ( - from i in dataTable5.AsEnumerable().ToList() - where i.Field("idcontrole") == x.Field("idcontrole") - select i).Select((DataRow i) => { - Item item = new Item() - { - Id = i.Field("iditem"), - Descricao = i.Field("descricao") - }; - EnumerableRowCollection dataRows = dataTable2.AsEnumerable().Where((DataRow s) => { - if (s.Field("id") != x.Field("idcontrole")) - { - return false; - } - return i.Field("iditem") == s.Field("iditem"); - }); - Func u003cu003e9_2624 = DocumentoRepository.u003cu003ec.u003cu003e9__26_24; - if (u003cu003e9_2624 == null) - { - u003cu003e9_2624 = (DataRow s) => new ControleSinistro() - { - Id = s.Field("idcontrolesinistro") - }; - DocumentoRepository.u003cu003ec.u003cu003e9__26_24 = u003cu003e9_2624; - } - item.Sinistros = dataRows.Select(u003cu003e9_2624).ToList(); - return item; - }).ToList(); - if (dataTable6 != null) - { - EnumerableRowCollection dataRows2 = dataTable6.AsEnumerable().Where((DataRow c) => c.Field("idcontrole") == x.Field("idcontrole")); - Func u003cu003e9_2617 = DocumentoRepository.u003cu003ec.u003cu003e9__26_17; - if (u003cu003e9_2617 == null) - { - u003cu003e9_2617 = (DataRow c) => new Calculo() - { - Id = c.Field("Id"), - DocumentId = c.Field("IdDocumento"), - DataAtualizacao = c.Field("DataAtualizacao"), - Status = (StatusCalculo)c.Field("Status"), - Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field("IdUsuario")) - }; - DocumentoRepository.u003cu003ec.u003cu003e9__26_17 = u003cu003e9_2617; - } - list = dataRows2.Select(u003cu003e9_2617).ToList(); - } - else - { - list = new List(); - } - List calculos = list; - List list3 = dataTable7.AsEnumerable().Where((DataRow p) => p.Field("idcontrole") == x.Field("idcontrole")).ToList(); - if (!somarPremios) - { - num = x.Field("total"); - } - else - { - List dataRows3 = list3; - Func u003cu003e9_2619 = DocumentoRepository.u003cu003ec.u003cu003e9__26_19; - if (u003cu003e9_2619 == null) - { - u003cu003e9_2619 = (DataRow p) => p.Field("pr_total"); - DocumentoRepository.u003cu003ec.u003cu003e9__26_19 = u003cu003e9_2619; - } - num = dataRows3.Sum(u003cu003e9_2619); - } - decimal num2 = num; - if (!somarPremios) - { - num1 = x.Field("liquido"); - } - else - { - List dataRows4 = list3; - Func u003cu003e9_2620 = DocumentoRepository.u003cu003ec.u003cu003e9__26_20; - if (u003cu003e9_2620 == null) - { - u003cu003e9_2620 = (DataRow p) => p.Field("pr_liq"); - DocumentoRepository.u003cu003ec.u003cu003e9__26_20 = u003cu003e9_2620; - } - num1 = dataRows4.Sum(u003cu003e9_2620); - } - decimal num3 = num1; - Vendedor vendedor = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.Find((Vendedor p) => p.Id == x.Field("idvendedor")) : null); - NegocioCorretora negocioCorretora = (x.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString())); - if (filtro.Negocio != null && filtro.Negocio.Count > 0 && !filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora)) - { - return; - } - Documento documento = new Documento() - { - Id = x.Field("id"), - Controle = new Controle() - { - Id = x.Field("idcontrole"), - IdEmpresa = x.Field("idempresa"), - Cliente = new Cliente() - { - Id = x.Field("idcliente"), - Nome = x.Field("cliente"), - Documento = x.Field("cgccpf"), - IdEmpresa = x.Field("idempresa"), - Telefones = new ObservableCollection(clienteTelefones), - Emails = new ObservableCollection(clienteEmails), - Pasta = x.Field("pastacliente"), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) - }, - Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Field("idseguradora")) : null), - Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Field("idramo")) : null), - Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), - AssistenciaId = x.Field("AssistenciaId") - }, - TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), - AdicionalComiss = x.Field("adinacomiss") == "1", - Apolice = x.Field("apolice"), - ApoliceAnterior = x.Field("apol_antes") - }; - if (x.Field("remessa") == null) - { - nullable = null; - nullable1 = nullable; - } - else - { - nullable1 = new DateTime?(x.Field("remessa")); - } - documento.Remessa = nullable1; - if (x.Field("emissao") == null) - { - nullable = null; - nullable2 = nullable; - } - else - { - nullable2 = new DateTime?(x.Field("emissao")); - } - documento.Emissao = nullable2; - documento.Endosso = x.Field("endosso"); - documento.Comissao = x.Field("comissao"); - documento.Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))); - documento.PremioLiquido = num3; - documento.PremioAdicional = x.Field("pr_adic"); - x.Field("pr_custo"); - documento.Custo = x.Field("pr_custo"); - documento.Iof = x.Field("pr_iof"); - documento.PremioTotal = num2; - documento.Vigencia2 = x.Field("vigenciafinal"); - nullable = x.Field("vigenciainicial"); - documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - documento.VendedorPrincipal = vendedor; - documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.Field("idestipulante")) : null); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); - documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora); - documento.Vendedores = ( - from v in Auxiliar.Vendedores - where nums.Contains(v.Id) - select v).ToList(); - documento.Sinistro = dataTable2.AsEnumerable().ToList().Any((DataRow s) => s.Field("id") == x.Field("idcontrole")); - documento.Tipo = x.Field("tipo"); - documento.ItensAtivo = items; - documento.DataControle = x.Field("datacontrole"); - documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.Find((Status p) => p.Id == x.Field("idstatus")) : null); - documento.Pasta = x.Field("Pasta"); - documento.Banco = new Banco() - { - Nome = x.Field("nomebanco") - }; - documento.Agencia = x.Field("agencia"); - documento.Conta = x.Field("conta"); - documento.Calculos = calculos; - documentos1.Add(documento); - }); - return documentos1; - } - - public async Task> FindEndossoByVigencia(Filtros filtro, bool buscarAssinatura = false) - { - decimal? nullable2; - object list; - bool count; - decimal? porcentagemRepasse; - string str = "CAST(d.vigencia1 AS DATE)"; - string referencia = filtro.Referencia; - if (referencia == "EMISSÃO") - { - str = "CAST(d.emissao AS DATE)"; - } - else if (referencia == "TRANSMISSÃO PROPOSTA") - { - str = "CAST(d.remessa AS DATE)"; - } - else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") - { - str = "CAST(d.cri_data AS DATE)"; - } - List vinculoVendedores = filtro.VinculoVendedores; - if (vinculoVendedores != null) - { - IEnumerable nums = vinculoVendedores.Except(filtro.Vendedores); - if (nums != null) - { - list = nums.ToList(); - } - else - { - list = null; - } - } - else - { - list = null; - } - if (list == null) - { - list = new List(); - } - if (!((IEnumerable)list).Any()) - { - filtro.Vendedores = new List(); - } - List condicaos = this.CriaCondicaoDocumento(filtro, str); - Condicao condicao = new Condicao() - { - Campo = "d.Tipo", - Valores = 1.CriarValor() - }; - condicaos.Add(condicao); - List condicaos1 = new List(); - Condicao condicao1 = new Condicao() - { - Campo = "d.Excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos1.Add(condicao1); - Condicao condicao2 = new Condicao() - { - Campo = "d.Excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos1.Add(condicao2); - condicaos.AddRange(condicaos1); - List documentos = await this.BuscaDocumentosPorCondicao(filtro, condicaos, buscarAssinatura); - List vinculoVendedores1 = filtro.VinculoVendedores; - if (vinculoVendedores1 != null) - { - count = vinculoVendedores1.Count > 0; - } - else - { - count = false; - } - if (count) - { - List documentos1 = new List(); - foreach (Documento documento in documentos) - { - await this.BuscaVendedoresPorIdControle(documento.Controle.Id, documento.Controle.IdEmpresa).ForEach((VendedorParcela v) => { - if (!filtro.VinculoVendedores.Contains(v.Vendedor.Id)) - { - documentos1.Add(documento); - } - }); - } - documentos1.ForEach((Documento d) => this.documentos.Remove(d)); - } - foreach (Documento vendedor in documentos) - { - if (vendedor.Tipo == 1 && vendedor.VendedorPrincipal == null && vendedor.Pagamentos.Count < 2) - { - List vendedorParcelas = await this.BuscaVendedoresPorIdControle(vendedor.Controle.Id, vendedor.Controle.IdEmpresa); - vendedor.Pagamentos = vendedorParcelas; - List vendedorParcelas1 = vendedorParcelas; - VendedorParcela vendedorParcela = vendedorParcelas1.Find((VendedorParcela v) => v.TipoVendedor.Id == (long)1); - if (vendedorParcela != null) - { - vendedor.VendedorPrincipal = vendedorParcela.Vendedor; - } - List pagamentos = vendedor.Pagamentos; - IOrderedEnumerable vendedorParcelas2 = - from tipo in pagamentos - orderby tipo.TipoVendedor.Id - select tipo; - List vendedors = ( - from v in vendedorParcelas2 - select v.Vendedor).ToList(); - vendedor.Vendedores = vendedors; - Documento documento1 = vendedor; - VendedorParcela vendedorParcela1 = vendedor.Pagamentos.FirstOrDefault((VendedorParcela p) => { - long? nullable; - long id = p.Vendedor.Id; - Vendedor vendedorPrincipal = vendedor.VendedorPrincipal; - if (vendedorPrincipal != null) - { - nullable = new long?(vendedorPrincipal.Id); - } - else - { - nullable = null; - } - long? nullable1 = nullable; - return id == nullable1.GetValueOrDefault() & nullable1.HasValue; - }); - if (vendedorParcela1 != null) - { - porcentagemRepasse = vendedorParcela1.PorcentagemRepasse; - } - else - { - nullable2 = null; - porcentagemRepasse = nullable2; - } - nullable2 = porcentagemRepasse; - documento1.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault()); - } - } - List documentos2 = documentos; - return documentos2; - } - - public List FindPendenciasByVigencia(Filtros filtro) - { - object connection; - string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", - from v in filtro.Status - select v), ")")); - string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", - from v in filtro.Negocio - select v), ")")); - string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", - from v in filtro.Seguradoras - select v), ")")); - string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", - from v in filtro.Ramos - select v), ")")); - string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", - from v in filtro.Produtos - select v), ")")); - string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", - from v in filtro.Vendedores - select v), ")")); - string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", - from v in filtro.TipoVendedor - select v), ")")); - string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", - from v in filtro.Estipulantes - select v), ")")); - string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); - DataTable dataTable1 = new DataTable(); - DataTable dataTable2 = new DataTable(); - DataTable dataTable3 = new DataTable(); - DataTable dataTable4 = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf, d.idcontrole, d.iddocumento as id, d.proposta, d.pedadit as propostaendosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento, d.datacontrole, d.idstatus, d.pasta, d.idbanco, cb.nomebanco, d.conta, d.agencia, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco ", str6, " WHERE (d.excluido IS NULL OR d.excluido = 0) AND (cl.excluido = 0 OR cl.excluido IS NULL) AND CASE \tWHEN ( d.tipo = 0 ) THEN DATALENGTH(ISNULL( d.contrato, '' )) ELSE DATALENGTH(ISNULL( d.aditamento, '' )) END < 1 "); - string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 "; - string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; - string str12 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL "; - string str13 = "SELECT * FROM VinculoDocumento WHERE 1=1 "; - sqlCommand.CommandText = string.Format("{0} {1} AND d.vigencia1 >= '{2:yyyy-MM-dd}' AND d.vigencia1 <= '{3:yyyy-MM-dd}' {4} {5} {6} {7} {8} {9} {10}", new object[] { str9, str8, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5 }); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable1); - } - if (dataTable1.Rows.Count != 0) - { - if (dataTable1.AsEnumerable().Any((DataRow x) => x.Field("idvendedor") == null)) - { - string str14 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable1.AsEnumerable().Where((DataRow x) => x.Field("idvendedor") == null).Select((DataRow v) => v.Field("idcontrole"))), ")"); - DataTable dataTable5 = new DataTable(); - sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str14, " ", str5 }); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable5); - } - foreach (DataRow row in dataTable1.Rows) - { - if (!string.IsNullOrEmpty(row["idvendedor"].ToString())) - { - continue; - } - string str15 = string.Format("idcontrole = {0}", row["idcontrole"]); - DataRow[] dataRowArray = dataTable5.Select(str15); - if (dataRowArray.Length == 0) - { - continue; - } - row["idvendedor"] = dataRowArray[0][1]; - } - } - string str16 = string.Concat(" AND vp.iddocumento IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat(str11, " ", str16); - using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) - { - sqlDataAdapter2.SelectCommand = sqlCommand; - sqlDataAdapter2.Fill(dataTable2); - } - string str17 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); - sqlCommand.CommandText = string.Concat(str12, " ", str17); - using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) - { - sqlDataAdapter3.SelectCommand = sqlCommand; - sqlDataAdapter3.Fill(dataTable3); - } - try - { - string str18 = string.Concat(" AND IdDocumento IN (", string.Join(",", ( - from x in dataTable1.AsEnumerable().ToList() - select x.Field("id")).ToList()), ")"); - sqlCommand.CommandText = string.Concat(str13, " ", str18); - using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) - { - sqlDataAdapter4.SelectCommand = sqlCommand; - sqlDataAdapter4.Fill(dataTable4); - } - } - catch (Exception exception) - { - dataTable4 = null; - } - } - else - { - return new List(); - } - } - } - return dataTable1.AsEnumerable().ToList().Select((DataRow x) => { - VinculoDocumento vinculoDocumento; - Func func2 = null; - Documento documento = new Documento() - { - Id = x.Field("id"), - Controle = new Controle() - { - IdEmpresa = x.Field("idempresa"), - Cliente = new Cliente() - { - Id = x.Field("idcliente"), - Nome = x.Field("cliente"), - Documento = x.Field("cgccpf"), - IdEmpresa = x.Field("idempresa"), - Pasta = x.Field("pastacliente"), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) - }, - Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), - Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), - Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field("idproduto")) : null), - AssistenciaId = x.Field("AssistenciaId") - }, - TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())), - AdicionalComiss = x.Field("adinacomiss") == "1", - Proposta = x.Field("proposta"), - PropostaEndosso = x.Field("propostaendosso"), - Comissao = x.Field("comissao"), - Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))), - PremioLiquido = x.Field("liquido"), - PremioTotal = x.Field("total"), - Vigencia2 = x.Field("vigenciafinal") - }; - DateTime? nullable = x.Field("vigenciainicial"); - documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); - documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); - documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { - List list = dataTable2.AsEnumerable().ToList(); - Func u003cu003e9_26 = func2; - if (u003cu003e9_26 == null) - { - Func func = (DataRow d) => d.Field("id") == x.Field("id"); - Func func1 = func; - func2 = func; - u003cu003e9_26 = func1; - } - IEnumerable dataRows = list.Where(u003cu003e9_26); - Func u003cu003e9_3927 = DocumentoRepository.u003cu003ec.u003cu003e9__39_27; - if (u003cu003e9_3927 == null) - { - u003cu003e9_3927 = (DataRow d) => d.Field("idvendedor"); - DocumentoRepository.u003cu003ec.u003cu003e9__39_27 = u003cu003e9_3927; - } - return dataRows.Select(u003cu003e9_3927).ToList().Contains(v.Id); - }).ToList(); - documento.Tipo = x.Field("tipo"); - documento.DataControle = x.Field("datacontrole"); - documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); - IEnumerable dataRows1 = - from i in dataTable3.AsEnumerable().ToList() - where i.Field("idcontrole") == x.Field("idcontrole") - select i; - Func u003cu003e9_3920 = DocumentoRepository.u003cu003ec.u003cu003e9__39_20; - if (u003cu003e9_3920 == null) - { - u003cu003e9_3920 = (DataRow i) => new Item() - { - Id = i.Field("iditem"), - Descricao = i.Field("descricao") - }; - DocumentoRepository.u003cu003ec.u003cu003e9__39_20 = u003cu003e9_3920; - } - documento.ItensAtivo = new List(dataRows1.Select(u003cu003e9_3920).ToList()); - DataTable dataTable = dataTable4; - if (dataTable != null) - { - EnumerableRowCollection dataRows2 = dataTable.AsEnumerable().Where((DataRow v) => v.Field("IdDocumento") == x.Field("id")); - Func u003cu003e9_3922 = DocumentoRepository.u003cu003ec.u003cu003e9__39_22; - if (u003cu003e9_3922 == null) - { - u003cu003e9_3922 = (DataRow v) => new VinculoDocumento() - { - Id = v.Field("Id"), - IdDocumento = v.Field("IdDocumento"), - IdPropostaDigital = v.Field("IdPropostaDigital"), - IdApoliceDigital = v.Field("IdApoliceDigital") - }; - DocumentoRepository.u003cu003ec.u003cu003e9__39_22 = u003cu003e9_3922; - } - vinculoDocumento = dataRows2.Select(u003cu003e9_3922).FirstOrDefault(); - } - else - { - vinculoDocumento = null; - } - documento.Vinculo = vinculoDocumento; - documento.Pasta = x.Field("Pasta"); - documento.Banco = new Banco() - { - Nome = x.Field("nomebanco") - }; - documento.Agencia = x.Field("agencia"); - documento.Conta = x.Field("conta"); - return documento; - }).ToList(); - } - - public bool HasSinistro(long id) - { - return (new ControleSinistroRepository(this._unitOfWork)).DocumentoHasSinistro(id); - } - - public bool HasSinistroPorControle(long controleId) - { - return (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(controleId); - } - - public Documento Merge(Documento documento) - { - bool id; - Status status = documento.Status; - if (status != null) - { - id = status.Id == (long)0; - } - else - { - id = false; - } - if (id) - { - documento.Status = null; - } - if (!documento.DataCriacao.HasValue) - { - documento.DataCriacao = new DateTime?(Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime()); - } - DocumentoDb documentoDb = ApplicationMapper.Mapper.Map(documento); - base.Merge(documentoDb); - documento = ApplicationMapper.Mapper.Map(documentoDb); - documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(documento.Id); - return documento; - } - - public void SalvarAssistencia(string id, long idcontrole) - { - ControleDb controleDb = this._unitOfWork.Query().FirstOrDefault((ControleDb x) => x.Id == idcontrole); - if (controleDb == null) - { - return; - } - controleDb.AssistenciaId = id; - this._unitOfWork.Repository().Merge(controleDb); - } - - public Documento SaveOrUpdate(Documento documento) - { - bool id; - Status status = documento.Status; - if (status != null) - { - id = status.Id == (long)0; - } - else - { - id = false; - } - if (id) - { - documento.Status = null; - } - if (!documento.DataCriacao.HasValue) - { - documento.DataCriacao = new DateTime?(Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime()); - } - DocumentoDb documentoDb = ApplicationMapper.Mapper.Map(documento); - this.SaveOrUpdate(documentoDb); - documento = ApplicationMapper.Mapper.Map(documentoDb); - documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(documento.Id); - return documento; - } - - private List Select(SqlQueryCondition sqlCondition) - { - DataTable dataTable = this._unitOfWork.Select(sqlCondition, "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); - if (dataTable == null || dataTable.Rows.Count == 0) - { - return new List(); - } - this._unitOfWork.CriarAuxiliar(); - List list = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcontrole")).Distinct().ToList(); - List nums = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(list); - return dataTable.MapDocumento(nums); - } - - private async Task SomaComissaoPaga(int tipo, List fechamentos, Filtros filtro, List condicaoDocumento) - { - object connection; - long num; - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - string str = "c.IdCiaSeg"; - string str1 = "SUM(vp.vlrrep)"; - string str2 = "FROM vendedorparcela vp INNER JOIN documento d ON vp.iddocumento = d.iddocumento INNER JOIN controle c ON c.IdControle = d.IdControle"; - string str3 = "vp.DataPgt IS NOT NULL AND"; - switch (tipo) - { - case 1: - { - str = "c.IdRamo"; - break; - } - case 2: - { - str = "d.IdEstipulante"; - break; - } - case 3: - { - str = "vp.IdVendedor"; - break; - } - } - SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0); - sqlCommand.CommandTimeout = 1000; - SqlCommand sqlCommand1 = sqlCommand; - string[] condicao = new string[] { "SELECT ", str, " Id,", str1, " Paga ", str2, " WHERE ", str3, " ", sqlQueryCondition.Condicao, " GROUP BY ", str }; - sqlCommand1.CommandText = string.Concat(condicao); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id")); - num = (flag ? (long)0 : (long)sqlDataReader["Id"]); - long num1 = num; - decimal item = (decimal)sqlDataReader["Paga"]; - if (num1 != 0) - { - Fechamento fechamento = fechamentos.FirstOrDefault((Fechamento f) => { - if (f.Entidade != tipo) - { - return false; - } - return f.Id == num1; - }); - if (fechamento != null) - { - Fechamento paga = fechamento; - paga.Paga = paga.Paga + item; - } - } - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - } - - private async Task SomaComissaoRecebida(int tipo, List fechamentos, Filtros filtro, List condicaoDocumento) - { - object connection; - bool flag; - bool count; - string str; - long num; - string empty; - bool count1; - bool flag1; - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - List vendedores = Auxiliar.Vendedores; - long id = vendedores.FirstOrDefault((Vendedor v) => v.Corretora).Id; - string str1 = "c.IdCiaSeg"; - string str2 = "SUM(p.vlrcomiss)"; - string str3 = "FROM parcela p INNER JOIN documento d ON p.iddocumento = d.iddocumento INNER JOIN controle c ON c.IdControle = d.IdControle"; - string str4 = "p.DataRec IS NOT NULL AND"; - switch (tipo) - { - case 1: - { - str1 = "c.IdRamo"; - break; - } - case 2: - { - str1 = "d.IdEstipulante"; - break; - } - case 3: - { - str1 = string.Format("CASE WHEN vp.IdVendedor IS NULL THEN {0} ELSE vp.IdVendedor END", id); - break; - } - } - bool flag2 = filtro.Vendedores.Contains(id); - string str5 = ""; - if (tipo == 3 && !flag2) - { - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - count1 = tipoVendedor.Count > 0; - } - else - { - count1 = false; - } - if (!count1) - { - List nums = filtro.Vendedores; - if (nums != null) - { - flag1 = nums.Count > 0; - } - else - { - flag1 = false; - } - if (!flag1) - { - goto Label1; - } - } - str5 = "LEFT JOIN vendedorparcela vp ON p.IDPARCELA = vp.IDPARCELA"; - goto Label0; - } - Label1: - string empty1 = string.Empty; - flag = (filtro.TipoVendedor == null ? false : filtro.TipoVendedor.Count > 0); - bool flag3 = flag; - if (filtro.TipoVendedor != null && filtro.TipoVendedor.Count > 0) - { - if (flag3) - { - List tipoVendedor1 = filtro.TipoVendedor; - empty = string.Join(",", - from t in tipoVendedor1 - select t.Value().ToString() ?? ""); - } - else - { - empty = string.Empty; - } - empty1 = empty; - } - List nums1 = filtro.TipoVendedor; - if (nums1 != null) - { - count = nums1.Count > 0; - } - else - { - count = false; - } - str = (count ? string.Concat("OUTER APPLY ( SELECT TOP 1 idvendedor, idtipovendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", empty1, ")) vp") : "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp"); - str5 = str; - Label0: - SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0); - sqlCommand.CommandTimeout = 1000; - SqlCommand sqlCommand1 = sqlCommand; - string[] condicao = new string[] { "SELECT ", str1, " as Id,", str2, " Recebida ", str3, " ", str5, " WHERE ", str4, " ", sqlQueryCondition.Condicao, " GROUP BY ", str1 }; - sqlCommand1.CommandText = string.Concat(condicao); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - bool flag4 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id")); - num = (flag4 ? (long)0 : (long)sqlDataReader["Id"]); - long num1 = num; - decimal item = (decimal)sqlDataReader["Recebida"]; - if (num1 != 0) - { - Fechamento fechamento = fechamentos.FirstOrDefault((Fechamento f) => { - if (f.Entidade != tipo) - { - return false; - } - return f.Id == num1; - }); - if (fechamento != null) - { - Fechamento recebida = fechamento; - recebida.Recebida = recebida.Recebida + item; - } - } - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - } - - public void TrocarCliente(Controle controle, Cliente cliente) - { - ControleDb controleDb = this._unitOfWork.Repository().FindEntityById(controle.Id); - controleDb.Cliente = ApplicationMapper.Mapper.Map(cliente); - this._unitOfWork.Repository().Merge(controleDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs deleted file mode 100644 index 4d51e87..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs +++ /dev/null @@ -1,143 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Common; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Common; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class EmpresaRepository : GenericRepository, IEmpresaRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public EmpresaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public string BuscarSenhaAdm(long idempresa = 1L) - { - EmpresaDb empresaDb = base.All().FirstOrDefault((EmpresaDb x) => x.Id == idempresa); - if (empresaDb != null) - { - return empresaDb.SenhaAdmin; - } - return null; - } - - public double ConsultaEspacoBancoInGb() - { - double num; - object connection; - using (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 = "EXEC sp_spaceused @oneresultset = '1'"; - SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); - if (!sqlDataReader.HasRows) - { - return 0; - } - else - { - sqlDataReader.Read(); - double num1 = double.Parse(sqlDataReader["reserved"].ToString().Replace("KB", string.Empty).Trim()); - double num2 = double.Parse(sqlDataReader["unallocated space"].ToString().Replace("MB", string.Empty).Replace(".", ",").Trim()); - num = (num1 / 1024 + num2) / 1024; - } - } - } - } - return num; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find(long idempresa = 0L) - { - return ( - from x in (idempresa == 0 ? base.All() : - from x in base.All() - where x.Id == idempresa - select x) - select new Empresa() - { - Id = x.Id, - Nome = x.Nome, - Documento = x.Documento, - Serial = x.Serial - }).ToList(); - } - - public List FindAsCliente(string filter) - { - EmpresaRepository.u003cu003ec__DisplayClass9_0 variable = null; - IQueryable empresaDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(EmpresaDb), "x"); - IQueryable empresaDbs1 = empresaDbs.Where(Expression.Lambda>(Expression.OrElse(Expression.OrElse(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EmpresaDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0)), FieldInfo.GetFieldFromHandle(typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EmpresaDb).GetMethod("get_Documento").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0)), FieldInfo.GetFieldFromHandle(typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0).GetField("filter").FieldHandle)) })), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EmpresaDb).GetMethod("get_Serial").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0)), FieldInfo.GetFieldFromHandle(typeof(EmpresaRepository.u003cu003ec__DisplayClass9_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(EmpresaDb), "x"); - return empresaDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Cliente)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Cliente).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EmpresaDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Cliente).GetMethod("set_Documento", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EmpresaDb).GetMethod("get_Documento").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); - } - - public Empresa FindByDocumento(string documento) - { - EmpresaDb empresaDb = base.All().FirstOrDefault((EmpresaDb e) => e.Documento.Replace(",", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty).Replace("/", string.Empty).Equals(documento)) ?? base.All().First(); - return ApplicationMapper.Mapper.Map(empresaDb); - } - - public Empresa FindById(long id) - { - EmpresaDb empresaDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(empresaDb); - } - - public Empresa FindBySerial(string serial) - { - EmpresaDb empresaDb = base.All().FirstOrDefault((EmpresaDb e) => e.Serial.Equals(serial)) ?? base.All().First(); - return ApplicationMapper.Mapper.Map(empresaDb); - } - - public Empresa Merge(Empresa empresa) - { - EmpresaDb empresaDb = ApplicationMapper.Mapper.Map(empresa); - base.Merge(empresaDb); - return ApplicationMapper.Mapper.Map(empresaDb); - } - - public Empresa SaveOrUpdate(Empresa empresa) - { - EmpresaDb empresaDb = ApplicationMapper.Mapper.Map(empresa); - this.SaveOrUpdate(empresaDb); - return ApplicationMapper.Mapper.Map(empresaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs deleted file mode 100644 index b0ab6cd..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs +++ /dev/null @@ -1,93 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class EstipulanteRepository : GenericRepository, IEstipulanteRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public EstipulanteRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find(string value, long idempresa = 0L) - { - string str = (idempresa == 0 ? string.Format(" AND idempresa = {0}", idempresa) : ""); - string str1 = string.Concat(new string[] { " AND (UPPER(ISNULL(nome, '')) LIKE '%", value.ToUpper(), "%' OR UPPER(ISNULL(cpfcnpj, '')) LIKE '%", value.ToUpper(), "%') " }); - return this.Select(string.Concat(str, str1)); - } - - public List Find() - { - return this.Select(""); - } - - public Estipulante FindById(long id) - { - EstipulanteDb estipulanteDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(estipulanteDb); - } - - public Estipulante Merge(Estipulante estipulante) - { - EstipulanteDb estipulanteDb = ApplicationMapper.Mapper.Map(estipulante); - base.Merge(estipulanteDb); - return ApplicationMapper.Mapper.Map(estipulanteDb); - } - - public Estipulante SaveOrUpdate(Estipulante estipulante) - { - EstipulanteDb estipulanteDb = ApplicationMapper.Mapper.Map(estipulante); - this.SaveOrUpdate(estipulanteDb); - return ApplicationMapper.Mapper.Map(estipulanteDb); - } - - private List Select(string condition) - { - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT DISTINCT * FROM estipulante WHERE 1=1 ", condition, ";"); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return dataTable.MapEstipulante(); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs deleted file mode 100644 index e568567..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs +++ /dev/null @@ -1,55 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ExpedicaoRepository : GenericRepository, IExpedicaoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ExpedicaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List FindByIdDocumento(long IdDocumento) - { - List list = ( - from x in base.All() - where x.Apolice.Id == IdDocumento - orderby x.DataEnvio descending - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Expedicao Merge(Expedicao expedicao) - { - ExpedicaoDb expedicaoDb = ApplicationMapper.Mapper.Map(expedicao); - base.Merge(expedicaoDb); - return ApplicationMapper.Mapper.Map(expedicaoDb); - } - - public Expedicao SaveOrUpdate(Expedicao expedicao) - { - ExpedicaoDb expedicaoDb = ApplicationMapper.Mapper.Map(expedicao); - this.SaveOrUpdate(expedicaoDb); - return ApplicationMapper.Mapper.Map(expedicaoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs deleted file mode 100644 index ff4afc6..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs +++ /dev/null @@ -1,237 +0,0 @@ -using AutoMapper; -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.Relatorios; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ExtratoRepository : GenericRepository, IExtratoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ExtratoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - List list = ( - from x in this._unitOfWork.Query() - where x.Extrato.Id == id - select x).ToList(); - if (list.Count > 0) - { - this._unitOfWork.Repository().DeleteRange(list); - } - ExtratoDb extratoDb = base.FindEntityById(id); - if (extratoDb == null) - { - return; - } - base.Delete(extratoDb); - } - - public List FindByData(Filtros filtro) - { - string str = "CAST(datacriacao AS DATE)"; - string referencia = filtro.Referencia; - if (referencia == "DATA DO EXTRATO") - { - str = "CAST(data AS DATE)"; - } - else if (referencia == "DATA DO CRÉDITO") - { - str = "CAST(DataCredito AS DATE)"; - } - List condicaos = new List() - { - new Condicao() - { - Campo = str, - Valores = filtro.Inicio.CriarValor(), - Operador = Operador.MaiorEIgual - }, - new Condicao() - { - Campo = str, - Valores = filtro.Fim.CriarValor(), - Operador = Operador.MenorEIgual - }, - new Condicao() - { - Campo = "idstatusextrato", - Valores = null, - Operador = Operador.Diferente, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "idstatusextrato", - Valores = "1".CriarValor(), - Operador = Operador.Diferente, - Grupo = 1, - Operacao = Operacao.Or - } - }; - return CustomMap.MapExtrato(this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM EXTRATO WHERE ", ""), null); - } - - public List FindByEmpresa(long id) - { - List list = ( - from x in base.All() - where x.IdEmpresa == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Extrato FindById(long id) - { - ExtratoDb extratoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(extratoDb); - } - - public List FindBySeguradora(long id, long idusuario, long empresa, DateTime inicio, DateTime fim, StatusExtrato? status = null) - { - List extratos; - object connection; - 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); - string str = ""; - if (empresa > (long)1) - { - str = string.Format("idempresa = {0} AND", empresa); - } - string str1 = string.Format("SELECT * FROM EXTRATO WHERE {0} data >= '{1:yyyy-MM-dd}' AND data <= '{2:yyyy-MM-dd}'", str, inicio, fim); - if (id > (long)0) - { - str1 = string.Concat(str1, string.Format(" AND idciaseg = {0}", id)); - } - if (idusuario > (long)0) - { - str1 = string.Concat(str1, string.Format(" AND usuariocriacao = {0}", idusuario)); - } - if (status.HasValue) - { - StatusExtrato valueOrDefault = status.GetValueOrDefault(); - if (valueOrDefault == StatusExtrato.Pendente) - { - str1 = string.Concat(str1, " AND (idstatusextrato IS NULL OR idstatusextrato = 1)"); - } - else if (valueOrDefault == StatusExtrato.Baixado) - { - str1 = string.Concat(str1, " AND idstatusextrato IS NOT NULL AND idstatusextrato != 1"); - } - } - sqlCommand.CommandText = str1; - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - string str2 = string.Concat(" AND idextrato IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("idextrato"))), ")"); - List nums = new List() - { - 13, - 1, - 10, - 5, - 12, - 6, - 8, - 21 - }; - sqlCommand.CommandText = string.Concat("SELECT idextrato, idparcelaextrato FROM parcelaextrato WHERE idstatusparcela NOT IN (", string.Join(",", - from v in nums - select v), ") ", str2); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - return CustomMap.MapExtrato(dataTable, dataTable1); - } - } - else - { - extratos = new List(); - } - } - } - return extratos; - } - - public List FindByStatus(StatusExtrato status) - { - List list = ( - from x in base.All() - where (int)x.Status == (int)status - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindSeguradoras(StatusExtrato status) - { - return ( - from x in ( - from x in base.All() - where (int)x.Status == (int)status - select x.Seguradora).ToList() - group x by x.Id into x - select new Seguradora() - { - Id = x.Key, - Nome = x.First().Nome - }).ToList(); - } - - public Extrato Merge(Extrato extrato) - { - ExtratoDb extratoDb = ApplicationMapper.Mapper.Map(extrato); - base.Merge(extratoDb); - return ApplicationMapper.Mapper.Map(extratoDb); - } - - public Extrato SaveOrUpdate(Extrato extrato) - { - ExtratoDb extratoDb = ApplicationMapper.Mapper.Map(extrato); - this.SaveOrUpdate(extratoDb); - return ApplicationMapper.Mapper.Map(extratoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs deleted file mode 100644 index 609964c..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs +++ /dev/null @@ -1,65 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - internal class FabricanteRepository : GenericRepository, IFabricanteRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public FabricanteRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find(string filter) - { - FabricanteRepository.u003cu003ec__DisplayClass7_0 variable = null; - IQueryable fabricanteDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(FabricanteDb), "x"); - List list = fabricanteDbs.Where(Expression.Lambda>(Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(FabricanteDb).GetMethod("get_Descricao").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(FabricanteRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(FabricanteRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) }), new ParameterExpression[] { parameterExpression })).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Fabricante FindById(long id) - { - FabricanteDb fabricanteDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(fabricanteDb); - } - - public Fabricante Merge(Fabricante fabricante) - { - FabricanteDb fabricanteDb = ApplicationMapper.Mapper.Map(fabricante); - base.Merge(fabricanteDb); - return ApplicationMapper.Mapper.Map(fabricanteDb); - } - - public Fabricante SaveOrUpdate(Fabricante fabricante) - { - FabricanteDb fabricanteDb = ApplicationMapper.Mapper.Map(fabricante); - this.SaveOrUpdate(fabricanteDb); - return ApplicationMapper.Mapper.Map(fabricanteDb); - } - - public List Select() - { - return ApplicationMapper.Mapper.Map, List>(base.All().ToList()); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs deleted file mode 100644 index 98ce65b..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs +++ /dev/null @@ -1,103 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Financeiro; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Financeiro; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class FornecedorRepository : GenericRepository, IFornecedorRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public FornecedorRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - FornecedorDb fornecedorDb = base.FindEntityById(id); - if (fornecedorDb == null) - { - return; - } - base.Delete(fornecedorDb); - } - - public List Find(string filter, bool ativo = false) - { - List fornecedors; - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - string str = string.Concat(new string[] { "(UPPER(nome) COLLATE Latin1_General_CI_AI LIKE '%", filter, "%' OR UPPER(cpfcnpj) LIKE '%", filter, "%' OR UPPER(fone1) LIKE '%", filter, "%' OR UPPER(fone2) LIKE '%", filter, "%' OR UPPER(email) LIKE '%", filter, "%')" }); - sqlCommand.CommandText = string.Concat("SELECT top 200 * FROM fornecedor WHERE ", str, " ", (ativo ? "AND Ativo = 1" : string.Empty)); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - return CustomMap.MapFornecedor(dataTable); - } - else - { - fornecedors = new List(); - } - } - } - return fornecedors; - } - - public List Find() - { - List list = this._unitOfWork.Session.CreateQuery("from FornecedorDb").List().ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Fornecedor FindById(long id) - { - FornecedorDb fornecedorDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(fornecedorDb); - } - - public Fornecedor Merge(Fornecedor fornecedor) - { - FornecedorDb fornecedorDb = ApplicationMapper.Mapper.Map(fornecedor); - base.Merge(fornecedorDb); - return ApplicationMapper.Mapper.Map(fornecedorDb); - } - - public Fornecedor SaveOrUpdate(Fornecedor fornecedor) - { - FornecedorDb fornecedorDb = ApplicationMapper.Mapper.Map(fornecedor); - this.SaveOrUpdate(fornecedorDb); - return ApplicationMapper.Mapper.Map(fornecedorDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs deleted file mode 100644 index ad6cdb6..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs +++ /dev/null @@ -1,71 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class GranizoRepository : GenericRepository, IGranizoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public GranizoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - GranizoDb granizoDb = base.FindEntityById(id); - if (granizoDb == null) - { - return; - } - base.Delete(granizoDb); - } - - public void DeleteRange(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Item.Id) - select x).ToList(); - base.DeleteRange(list); - } - - public Granizo Find(long id) - { - GranizoDb granizoDb = base.All().FirstOrDefault((GranizoDb x) => x.Item.Id == id) ?? new GranizoDb(); - return ApplicationMapper.Mapper.Map(granizoDb); - } - - public Granizo FindById(long id) - { - GranizoDb granizoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(granizoDb); - } - - public Granizo Merge(Granizo granizo) - { - GranizoDb granizoDb = ApplicationMapper.Mapper.Map(granizo); - base.Merge(granizoDb); - return ApplicationMapper.Mapper.Map(granizoDb); - } - - public Granizo SaveOrUpdate(Granizo granizo) - { - GranizoDb granizoDb = ApplicationMapper.Mapper.Map(granizo); - this.SaveOrUpdate(granizoDb); - return ApplicationMapper.Mapper.Map(granizoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs deleted file mode 100644 index 004432a..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs +++ /dev/null @@ -1,102 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -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.Domain.Ferramentas; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ImpostoRepository : GenericRepository, IImpostoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ImpostoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List DefaultSelect(bool? ativo) - { - string str; - if (!ativo.HasValue) - { - str = ""; - } - else - { - str = (ativo.Value ? " AND Ativo = 1" : " AND Ativo = 0"); - } - return this.Select(str); - } - - public Imposto FindById(long id) - { - ImpostoDb impostoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(impostoDb); - } - - public List FindByRamo(long id) - { - return this.Select(string.Format(" AND idramo = {0}", id)); - } - - public List FindBySeguradora(long id) - { - return this.Select(string.Format(" AND idciaseg = {0}", id)); - } - - public Imposto Merge(Imposto imposto) - { - ImpostoDb impostoDb = ApplicationMapper.Mapper.Map(imposto); - base.Merge(impostoDb); - return ApplicationMapper.Mapper.Map(impostoDb); - } - - public Imposto SaveOrUpdate(Imposto imposto) - { - ImpostoDb impostoDb = ApplicationMapper.Mapper.Map(imposto); - this.SaveOrUpdate(impostoDb); - return ApplicationMapper.Mapper.Map(impostoDb); - } - - private List Select(string condition) - { - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - sqlCommand.CommandText = string.Concat("SELECT * FROM Imposto WHERE 1=1 ", condition); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return CustomMap.MapImposto(dataTable); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs deleted file mode 100644 index 5d50ddf..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs +++ /dev/null @@ -1,402 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Common; -using Gestor.Infrastructure.Entities.Generic; -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.Common; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class IndiceArquivoDigitalRepository : GenericRepository, IIndiceArquivoDigitalRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public IndiceArquivoDigitalRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public ControleArquivoDigital BuscarBanco() - { - ControleArquivoDigitalDb controleArquivoDigitalDb = ( - from x in this._unitOfWork.Query() - orderby x.Id descending - select x).First(); - return ApplicationMapper.Mapper.Map(controleArquivoDigitalDb); - } - - public List BuscarBancos() - { - List list = ( - from x in this._unitOfWork.Query() - orderby x.Id descending - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public ControleArquivoDigital ConsultarBanco(string banco) - { - ControleArquivoDigitalDb controleArquivoDigitalDb = this._unitOfWork.Query().First((ControleArquivoDigitalDb x) => x.Catalogo == banco); - return ApplicationMapper.Mapper.Map(controleArquivoDigitalDb); - } - - public void Delete(long id) - { - IndiceArquivoDigitalDb indiceArquivoDigitalDb = base.FindEntityById(id); - if (indiceArquivoDigitalDb == null) - { - return; - } - base.Delete(indiceArquivoDigitalDb); - } - - public List Find(TipoArquivoDigital tipo, long id, long usuario, bool buscarAssinaturas = false) - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - string str1 = ""; - switch (tipo) - { - case TipoArquivoDigital.Todos: - { - str1 = "idcliente = @id "; - break; - } - case TipoArquivoDigital.Cliente: - { - str1 = "idcliente = @id AND ISNULL(iddocumento, 0) = 0 AND ISNULL(iditem, 0) = 0 AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idparcela, 0) = 0 AND ISNULL(idsinistro, 0) = 0 "; - break; - } - case TipoArquivoDigital.Apolice: - { - str1 = "iddocumento = @id AND ISNULL(iditem, 0) = 0 AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idparcela, 0) = 0 AND ISNULL(idsinistro, 0) = 0 "; - break; - } - case TipoArquivoDigital.Parcela: - { - str1 = "idparcela = @id AND ISNULL(iditem, 0) = 0 AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idsinistro, 0) = 0 "; - break; - } - case TipoArquivoDigital.Item: - { - str1 = "iditem = @id AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idparcela, 0) = 0 AND ISNULL(idsinistro, 0) = 0 "; - break; - } - case TipoArquivoDigital.Sinistro: - { - str1 = "idsinistro = @id AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idparcela, 0) = 0 "; - break; - } - case TipoArquivoDigital.Vendedor: - { - str1 = "idvendedor = @id "; - break; - } - case TipoArquivoDigital.Extrato: - { - str1 = "idextrato = @id "; - break; - } - case TipoArquivoDigital.Seguradora: - { - str1 = "idciaseg = @id "; - break; - } - case TipoArquivoDigital.Lancamento: - { - str1 = "idlancamen = @id "; - break; - } - case TipoArquivoDigital.Fornecedor: - { - str1 = "idfornecedor = @id AND ISNULL(idlancamen, 0) = 0 "; - break; - } - case TipoArquivoDigital.Prospeccao: - { - str1 = "idvenctoaleatorio = @id "; - break; - } - case TipoArquivoDigital.Usuario: - { - str1 = "idusuarioarquivo = @id "; - break; - } - case TipoArquivoDigital.Empresa: - { - str1 = "idempresa = @id AND ISNULL(idcliente, 0) = 0 AND ISNULL(iddocumento, 0) = 0 AND ISNULL(iditem, 0) = 0 AND ISNULL(idvenctoaleatorio, 0) = 0 AND ISNULL(idparcela, 0) = 0 AND ISNULL(idsinistro, 0) = 0 AND ISNULL(idlancamen, 0) = 0 AND ISNULL(idfornecedor, 0) = 0 AND ISNULL(idextrato, 0) = 0 AND ISNULL(idciaseg, 0) = 0 AND ISNULL(idvendedor, 0) = 0 AND ISNULL(idusuarioarquivo, 0) = 0 AND ISNULL(idtarefa, 0) = 0 AND ISNULL(idsocio, 0) = 0 "; - break; - } - case TipoArquivoDigital.Socio: - { - str1 = "idsocio = @id "; - break; - } - case TipoArquivoDigital.Tarefa: - { - str1 = "IdTarefa = @id "; - break; - } - case TipoArquivoDigital.NotaFiscal: - { - str1 = "IdNotaFiscal = @id "; - break; - } - case TipoArquivoDigital.Estipulante: - { - str1 = "IdEstipulante = @id "; - break; - } - } - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT * FROM newarquivodigital WHERE ", (usuario == 0 ? "" : "(excluido IS NULL OR excluido != '1') AND"), " ", str1); - sqlCommand.Parameters.AddWithValue("@id", id); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - try - { - if (buscarAssinaturas) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "IndiceId", - Valores = ( - from x in dataTable.AsEnumerable().ToList() - select x.Field("idnewarquivodigital")).ToList().CriarValor() - }, - new Condicao() - { - Campo = "excluido", - Valores = null, - Grupo = 2, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "excluido", - Valores = "1".CriarValor(), - Operador = Operador.Diferente, - Grupo = 2, - Operacao = Operacao.Or - } - }; - dataTable1 = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT assinado, IndiceId, UrlAssinatura FROM ArquivoParaAssinatura WHERE ", ""); - } - } - catch (Exception exception) - { - dataTable1 = null; - } - } - else - { - return new List(); - } - } - } - return dataTable.AsEnumerable().ToList().Select((DataRow x) => { - string str; - IndiceArquivoDigital indiceArquivoDigital = new IndiceArquivoDigital() - { - Id = x.Field("idnewarquivodigital"), - IdArquivoDigital = x.Field("idarquivodigital"), - Bd = x.Field("banco"), - Descricao = x.Field("descricao"), - Extensao = x.Field("extension") - }; - long? nullable = x.Field("idcliente"); - indiceArquivoDigital.IdCliente = nullable.GetValueOrDefault(); - nullable = x.Field("iddocumento"); - indiceArquivoDigital.IdDocumento = nullable.GetValueOrDefault(); - nullable = x.Field("iditem"); - indiceArquivoDigital.IdItem = nullable.GetValueOrDefault(); - nullable = x.Field("idparcela"); - indiceArquivoDigital.IdParcela = nullable.GetValueOrDefault(); - nullable = x.Field("idsinistro"); - indiceArquivoDigital.IdSinistro = nullable.GetValueOrDefault(); - nullable = x.Field("idciaseg"); - indiceArquivoDigital.IdSeguradora = nullable.GetValueOrDefault(); - nullable = x.Field("idvendedor"); - indiceArquivoDigital.IdVendedor = nullable.GetValueOrDefault(); - nullable = x.Field("idextrato"); - indiceArquivoDigital.IdExtrato = nullable.GetValueOrDefault(); - nullable = x.Field("idempresa"); - indiceArquivoDigital.IdEmpresa = nullable.GetValueOrDefault(); - nullable = x.Field("idlancamen"); - indiceArquivoDigital.IdLancamento = nullable.GetValueOrDefault(); - nullable = x.Field("idfornecedor"); - indiceArquivoDigital.IdFornecedor = nullable.GetValueOrDefault(); - nullable = x.Field("idvenctoaleatorio"); - indiceArquivoDigital.IdProspeccao = nullable.GetValueOrDefault(); - nullable = x.Field("idsocio"); - indiceArquivoDigital.IdSocio = nullable.GetValueOrDefault(); - indiceArquivoDigital.Excluido = (x.Field("excluido") == null ? true : x.Field("excluido").ToString() != "1"); - nullable = x.Field("idusuarioarquivo"); - indiceArquivoDigital.IdUsuario = nullable.GetValueOrDefault(); - nullable = x.Field("IdTarefa"); - indiceArquivoDigital.IdTarefa = nullable.GetValueOrDefault(); - nullable = x.Field("IdNotaFiscal"); - indiceArquivoDigital.IdNotaFiscal = nullable.GetValueOrDefault(); - nullable = x.Field("IdEstipulante"); - indiceArquivoDigital.IdEstipulante = nullable.GetValueOrDefault(); - nullable = x.Field("usuariocriacao"); - indiceArquivoDigital.UsuarioCriacao = nullable.GetValueOrDefault(); - nullable = x.Field("usuarioalteracao"); - indiceArquivoDigital.UsuarioAtualizacao = nullable.GetValueOrDefault(); - DateTime? nullable1 = x.Field("datacriacao"); - indiceArquivoDigital.DataCriacao = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue)); - nullable1 = x.Field("dataalteracao"); - indiceArquivoDigital.DataAtualizacao = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue)); - indiceArquivoDigital.Assinado = (!buscarAssinaturas || dataTable1 == null ? false : dataTable1.AsEnumerable().ToList().Any((DataRow a) => { - if (a.Field("IndiceId") != x.Field("idnewarquivodigital")) - { - return false; - } - return a.Field("assinado"); - })); - indiceArquivoDigital.EnviadoAssinatura = (!buscarAssinaturas || dataTable1 == null ? false : dataTable1.AsEnumerable().ToList().Any((DataRow a) => a.Field("IndiceId") == x.Field("idnewarquivodigital"))); - if (!buscarAssinaturas || dataTable1 == null) - { - str = ""; - } - else - { - DataRow dataRow = dataTable1.AsEnumerable().ToList().FirstOrDefault((DataRow a) => a.Field("IndiceId") == x.Field("idnewarquivodigital")); - if (dataRow != null) - { - str = dataRow.Field("UrlAssinatura"); - } - else - { - str = null; - } - } - indiceArquivoDigital.UrlAssinatura = str; - indiceArquivoDigital.AzureGuid = x.Field("AzureGuid"); - indiceArquivoDigital.AzureStorage = x.Field("AzureStorage"); - return indiceArquivoDigital; - }).ToList(); - } - - public List Find(string condicao) - { - List list; - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - try - { - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT * FROM AssinaturaRecebida WHERE tipo = 'MANIFEST' ", condicao, " "); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - list = ( - from x in dataTable.AsEnumerable().ToList() - select new ArquivoDigital() - { - Id = x.Field("Id"), - Arquivo = x.Field("Bytes"), - Descricao = x.Field("Nome"), - Extensao = x.Field("Mime"), - DataCriacao = x.Field("DataCriacao"), - AzureGuid = x.Field("AzureGuid") - }).ToList(); - } - catch (Exception exception) - { - list = new List(); - } - return list; - } - - public ArquivoDigital FindAssinatura(long id) - { - string str = string.Format(" AND IndiceId = {0}", id); - return this.Find(str).FirstOrDefault(); - } - - public List FindAssinatura(List id) - { - string str = string.Concat(" AND IndiceId IN (", string.Join(",", id), ")"); - return this.Find(str); - } - - public IndiceArquivoDigital FindById(long id) - { - IndiceArquivoDigitalDb indiceArquivoDigitalDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(indiceArquivoDigitalDb); - } - - public IndiceArquivoDigital Merge(IndiceArquivoDigital indice) - { - IndiceArquivoDigitalDb indiceArquivoDigitalDb = ApplicationMapper.Mapper.Map(indice); - base.Merge(indiceArquivoDigitalDb); - return ApplicationMapper.Mapper.Map(indiceArquivoDigitalDb); - } - - public IndiceArquivoDigital SaveOrUpdate(IndiceArquivoDigital indice) - { - IndiceArquivoDigitalDb indiceArquivoDigitalDb = ApplicationMapper.Mapper.Map(indice); - this.SaveOrUpdate(indiceArquivoDigitalDb); - return ApplicationMapper.Mapper.Map(indiceArquivoDigitalDb); - } - - public ControleArquivoDigital SaveOrUpdate(ControleArquivoDigital catalogo) - { - ControleArquivoDigitalDb controleArquivoDigitalDb = ApplicationMapper.Mapper.Map(catalogo); - this._unitOfWork.Repository().SaveOrUpdate(controleArquivoDigitalDb); - return ApplicationMapper.Mapper.Map(controleArquivoDigitalDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs deleted file mode 100644 index 0d8590f..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs +++ /dev/null @@ -1,1450 +0,0 @@ -using AutoMapper; -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.Common; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using NHibernate.Util; -using System; -using System.Collections; -using System.Collections.Generic; -using System.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 ItemRepository : GenericRepository, IItemRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ItemRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public async Task> BuscaItensPorObs(string pesquisa, FiltroStatusDocumento status, List vendedorVinculado, TipoPesquisa tipo, bool tipobusca = false) - { - List pesquisaAvancadas; - object connection; - object obj; - DateTime dateTime; - List pesquisaAvancadas1 = new List(); - DateTime date = Funcoes.GetNetworkTime().Date; - List condicaos = new List(); - Condicao condicao = new Condicao() - { - Campo = "d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos.Add(condicao); - Condicao condicao1 = new Condicao() - { - Campo = "d.excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos.Add(condicao1); - List condicaos1 = condicaos; - if (vendedorVinculado.Count > 0) - { - Condicao condicao2 = new Condicao() - { - Campo = "vp.IdVendedor", - Valores = vendedorVinculado.CriarValor() - }; - condicaos1.Add(condicao2); - } - switch (status) - { - case FiltroStatusDocumento.Vencidos: - { - List condicaos2 = new List(); - Condicao condicao3 = new Condicao() - { - Campo = "d.situacao", - Valores = new List() - { - 3, - 7 - }, - Operador = Operador.Diferente - }; - condicaos2.Add(condicao3); - Condicao condicao4 = new Condicao() - { - Campo = "d.vigencia2", - Valores = date.AddDays(-5).CriarValor(), - Operador = Operador.Menor - }; - condicaos2.Add(condicao4); - condicaos1.AddRange(condicaos2); - goto Label0; - } - case FiltroStatusDocumento.Cancelados: - { - Condicao condicao5 = new Condicao() - { - Campo = "d.situacao", - Valores = 3.CriarValor() - }; - condicaos1.Add(condicao5); - goto Label0; - } - case FiltroStatusDocumento.Recusados: - { - Condicao condicao6 = new Condicao() - { - Campo = "d.situacao", - Valores = 7.CriarValor() - }; - condicaos1.Add(condicao6); - goto Label0; - } - case FiltroStatusDocumento.Todos: - { - 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 condicaos3 = condicaos1; - Condicao condicao7 = new Condicao() - { - Campo = "a.obs", - Valores = pesquisa.CriarValor(), - Grupo = 3, - Operacao = Operacao.Or, - Operador = (tipobusca ? Operador.Igual : Operador.Like) - }; - condicaos3.Add(condicao7); - List condicaos4 = condicaos1; - Condicao condicao8 = new Condicao() - { - Campo = "r.obs", - Valores = pesquisa.CriarValor(), - Grupo = 3, - Operacao = Operacao.Or, - Operador = (tipobusca ? Operador.Igual : Operador.Like) - }; - condicaos4.Add(condicao8); - List condicaos5 = condicaos1; - Condicao condicao9 = new Condicao() - { - Campo = "aero.obs", - Valores = pesquisa.CriarValor(), - Grupo = 3, - Operacao = Operacao.Or, - Operador = (tipobusca ? Operador.Igual : Operador.Like) - }; - condicaos5.Add(condicao9); - List condicaos6 = condicaos1; - Condicao condicao10 = new Condicao() - { - Campo = "g.obs", - Valores = pesquisa.CriarValor(), - Grupo = 3, - Operacao = Operacao.Or, - Operador = (tipobusca ? Operador.Igual : Operador.Like) - }; - condicaos6.Add(condicao10); - List condicaos7 = condicaos1; - Condicao condicao11 = new Condicao() - { - Campo = "v.obs", - Valores = pesquisa.CriarValor(), - Grupo = 3, - Operacao = Operacao.Or, - Operador = (tipobusca ? Operador.Igual : Operador.Like) - }; - condicaos7.Add(condicao11); - List condicaos8 = condicaos1; - Condicao condicao12 = new Condicao() - { - Campo = "rd.obs", - Valores = pesquisa.CriarValor(), - Grupo = 3, - Operacao = Operacao.Or, - Operador = (tipobusca ? Operador.Igual : Operador.Like) - }; - condicaos8.Add(condicao12); - List condicaos9 = condicaos1; - Condicao condicao13 = new Condicao() - { - Campo = "re.bens", - Valores = pesquisa.CriarValor(), - Grupo = 3, - Operacao = Operacao.Or, - Operador = (tipobusca ? Operador.Igual : Operador.Like) - }; - condicaos9.Add(condicao13); - SqlQueryCondition sqlQueryCondition = condicaos1.CreateParameters(0); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT TOP 1000 c.IdControle,d.IdDocumento,d.Proposta,d.Contrato Apolice,d.Aditamento Endosso,d.Vigencia1 VigenciaInicial,c.IdCliente,d.Tipo Tipo,i.IdItem,i.Descricao,cli.Nome,vp.IdVendedor FROM documento d INNER JOIN controle c ON d.IdControle = c.idControle INNER JOIN cliente cli ON cli.IdCliente = c.IdCliente INNER JOIN item i ON d.IdDocumento = i.IdDocumento LEFT JOIN auto a ON i.IdItem = a.IdItem LEFT JOIN resempco r ON i.IdItem = r.IdItem LEFT JOIN aeronautico aero ON i.IdItem = aero.IdItem LEFT JOIN granizo g ON i.IdItem = g.IdItem LEFT JOIN vida v ON i.IdItem = v.IdItem LEFT JOIN riscosdiversos rd ON i.IdItem = rd.IdItem LEFT JOIN vendedorparcela vp ON d.IdDocumento = vp.IdDocumento LEFT JOIN resempco re ON i.IdItem = re.IdItem WHERE ", sqlQueryCondition.Condicao); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - object[] fieldValue = new object[] { sqlDataReader.GetFieldValue("Descricao", true, true), sqlDataReader.GetFieldValue("Apolice", true, true), null, null, null }; - obj = (sqlDataReader.GetFieldValue("Tipo", true, true) == 0 ? "" : string.Concat(" - ENDOSSO: ", sqlDataReader.GetFieldValue("Endosso", true, true))); - fieldValue[2] = obj; - fieldValue[3] = sqlDataReader.GetFieldValue("Proposta", true, true); - DateTime? nullable = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); - dateTime = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.Now); - fieldValue[4] = dateTime; - string str = string.Format("ITEM: {0} - APÓLICE: {1}{2} - PROPOSTA: {3} - VIGÊNCIA INICIAL: {4:d}", fieldValue); - PesquisaAvancada pesquisaAvancada = new PesquisaAvancada() - { - IdCliente = sqlDataReader.GetFieldValue("IdCliente", true, true), - IdDocumento = sqlDataReader.GetFieldValue("IdDocumento", true, true), - IdItem = sqlDataReader.GetFieldValue("IdItem", true, true), - Nome = sqlDataReader.GetFieldValue("Nome", true, true).ToUpper(), - Pesquisa = str.ToUpper() - }; - pesquisaAvancadas1.Add(pesquisaAvancada); - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - pesquisaAvancadas = pesquisaAvancadas1; - break; - } - default: - { - List condicaos10 = new List(); - Condicao condicao14 = new Condicao() - { - Campo = "d.situacao" - }; - List objs = new List() - { - 1, - 2, - 4 - }; - condicao14.Valores = objs; - condicaos10.Add(condicao14); - Condicao condicao15 = new Condicao() - { - Campo = "d.vigencia2", - Valores = null, - Grupo = 2, - Operacao = Operacao.Or - }; - condicaos10.Add(condicao15); - Condicao condicao16 = new Condicao() - { - Campo = "d.vigencia2", - Valores = date.AddDays(-5).CriarValor(), - Grupo = 2, - Operacao = Operacao.Or, - Operador = Operador.Maior - }; - condicaos10.Add(condicao16); - condicaos1.AddRange(condicaos10); - goto Label0; - } - } - pesquisaAvancadas1 = null; - return pesquisaAvancadas; - } - - public Cliente BuscarCliente(long id) - { - return this.FindById(id).Documento.Controle.Cliente; - } - - public int ChecarQuantidade(long idDocumento) - { - return base.All().Count((ItemDb x) => x.Documento.Id == idDocumento); - } - - public void Delete(long id) - { - ItemDb itemDb = base.FindEntityById(id); - if (itemDb == null) - { - return; - } - base.Delete(itemDb); - } - - public void DeleteRange(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Id) - select x).ToList(); - base.DeleteRange(list); - } - - public List FindByDocumentsIds(long id, StatusItem status = 0, bool sinistroCompleto = false) - { - List condicaos; - DataTable dataTable1; - int length; - Item granizo; - long? nullable; - long? nullable1; - long? nullable2; - string str; - string str1; - string str2; - string str3; - string str4; - string str5; - string str6; - string str7; - object fabricante; - string str8; - string str9; - string str10; - string str11; - string str12; - string str13; - string str14; - string str15; - string str16; - int? nullable3; - TabelaReferencia tabelaReferencium; - string str17; - string str18; - Cor cor; - string str19; - string str20; - Action action = null; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "d.idcontrole", - Valores = id.CriarValor() - } - }; - switch (status) - { - case StatusItem.Ativos: - { - condicaos1.AddRange(new List() - { - new Condicao() - { - Campo = "idsubstituido", - Valores = null - }, - new Condicao() - { - Campo = "cancelado", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "cancelado", - Valores = "1".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or, - Operador = Operador.Diferente - } - }); - break; - } - case StatusItem.Inativos: - { - condicaos1.AddRange(new List() - { - new Condicao() - { - Campo = "idsubstituido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or, - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = "cancelado", - Valores = "1".CriarValor(), - Grupo = 1 - } - }); - break; - } - case StatusItem.Documento: - { - condicaos1 = new List() - { - new Condicao() - { - Campo = "d.iddocumento", - Valores = id.CriarValor() - } - }; - break; - } - } - DataTable dataTable2 = this._unitOfWork.Select(condicaos1.CreateParameters(0), "SELECT i.iditem, c.idramo, i.iddocumento, i.descricao, i.sinistrado, i.status, i.statusinc, i.idsubstituido, i.iddocumentocancelado, i.ordem FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE ", "ORDER BY i.ordem"); - if (dataTable2.Rows.Count == 0) - { - return new List(); - } - string str21 = dataTable2.AsEnumerable().First().Field("idramo").ToString(); - List list = dataTable2.AsEnumerable().Select((DataRow x) => x.Field("iditem")).ToList(); - DataTable dataTable3 = new DataTable(); - DataTable dataTable4 = new DataTable(); - DataTable dataTable5 = new DataTable(); - DataTable dataTable6 = new DataTable(); - DataTable dataTable7 = new DataTable(); - DataTable dataTable8 = new DataTable(); - DataTable dataTable9 = new DataTable(); - DataTable dataTable10 = new DataTable(); - DataTable dataTable11 = new DataTable(); - DataTable dataTable12 = new DataTable(); - while (list.Count > 0) - { - List nums = list.Take(1500).ToList(); - condicaos = new List() - { - new Condicao() - { - Campo = "iditem", - Valores = nums.CriarValor() - } - }; - dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT idcobertura, iditem, observacao, franquia, premio, lmi FROM cobertura WHERE ", ""); - dataTable12.Merge(dataTable1); - if (str21 != null) - { - length = str21.Length; - if (length == 1) - { - switch (str21[0]) - { - case '1': - case '2': - case '3': - { - goto Label1; - } - case '4': - case '8': - { - break; - } - case '5': - { - dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT a.*, f.descricao AS fabricante FROM auto a LEFT OUTER JOIN fabricante f ON f.idfabricante = a.IDFABRICANTE WHERE ", ""); - dataTable3.Merge(dataTable1); - goto Label0; - } - default: - { - goto Label0; - } - } - } - else if (length == 2) - { - switch (str21[1]) - { - case '0': - { - if (str21 == "10") - { - goto Label0; - } - if (str21 == "20") - { - dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT iditem, obs FROM granizo WHERE ", ""); - dataTable11.Merge(dataTable1); - goto Label0; - } - else - { - goto Label0; - } - } - case '1': - { - if (str21 == "31" || str21 == "41") - { - break; - } - goto Label0; - } - case '3': - { - if (str21 == "23" || str21 == "33") - { - break; - } - if (str21 == "13") - { - dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT iditem, obs FROM aeronautico WHERE ", ""); - dataTable10.Merge(dataTable1); - goto Label0; - } - else - { - if (str21 == "53") - { - goto Label0; - } - goto Label0; - } - } - case '5': - { - if (str21 == "15") - { - goto Label1; - } - goto Label0; - } - case '6': - { - if (str21 == "16" || str21 == "26") - { - break; - } - goto Label0; - } - case '7': - { - if (str21 == "17") - { - break; - } - goto Label0; - } - case '8': - { - if (str21 == "18") - { - goto Label1; - } - if (str21 == "28") - { - break; - } - goto Label0; - } - case '9': - { - if (str21 == "19" || str21 == "39" || str21 == "59") - { - break; - } - goto Label0; - } - default: - { - goto Label0; - } - } - } - else - { - goto Label0; - } - dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT iditem, obs FROM riscosdiversos WHERE ", ""); - dataTable9.Merge(dataTable1); - } - Label0: - dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM controlesinistro WHERE ", ""); - dataTable5.Merge(dataTable1); - if (dataTable1.Rows.Count > 0) - { - List condicaos2 = new List() - { - new Condicao() - { - Campo = "idcontrolesinistro", - Valores = dataTable5.AsEnumerable().Select((DataRow x) => x.Field("idcontrolesinistro")).ToList().CriarValor() - } - }; - dataTable1 = this._unitOfWork.Select(condicaos2.CreateParameters(0), "SELECT * FROM sinistro WHERE ", ""); - dataTable6.Merge(dataTable1); - List condicaos3 = new List() - { - new Condicao() - { - Campo = "idsinistro", - Valores = dataTable6.AsEnumerable().Select((DataRow x) => x.Field("idsinistro")).ToList().CriarValor() - } - }; - dataTable1 = this._unitOfWork.Select(condicaos3.CreateParameters(0), "SELECT * FROM sinistrovida WHERE ", ""); - dataTable8.Merge(dataTable1); - dataTable1 = this._unitOfWork.Select(condicaos3.CreateParameters(0), "SELECT * FROM sinistroauto WHERE ", ""); - dataTable7.Merge(dataTable1); - } - list = (nums.Count < 1500 ? new List() : list.Except(nums).ToList()); - } - List items = new List(); - Label4: - foreach (DataRow row in dataTable2.Rows) - { - Item item = new Item() - { - Id = long.Parse(row["iditem"].ToString()), - Documento = new Documento() - { - Id = long.Parse(row["iddocumento"].ToString()) - }, - Sinistrado = row["sinistrado"].ToString() == "1", - Descricao = row["descricao"].ToString(), - Status = row["status"].ToString(), - Ordem = new int?(int.Parse(row["ordem"].ToString())), - StatusInclusao = row["statusinc"].ToString() - }; - if (string.IsNullOrEmpty(row["iddocumentocancelado"].ToString())) - { - nullable = null; - nullable1 = nullable; - } - else - { - nullable1 = new long?(long.Parse(row["iddocumentocancelado"].ToString())); - } - item.IdDocumentoCancelado = nullable1; - if (string.IsNullOrEmpty(row["idsubstituido"].ToString())) - { - nullable = null; - nullable2 = nullable; - } - else - { - nullable2 = new long?(long.Parse(row["idsubstituido"].ToString())); - } - item.Substituido = nullable2; - item.Coberturas = ( - from x in dataTable12.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList() - select new Cobertura() - { - Id = x.Field("idcobertura"), - Observacao = x.Field("observacao"), - Franquia = (x.Field("franquia") == null ? decimal.Zero : x.Field("franquia")), - Lmi = (x.Field("lmi") == null ? decimal.Zero : x.Field("lmi")), - Premio = (x.Field("premio") == null ? decimal.Zero : x.Field("premio")) - }).ToList(); - granizo = item; - string str22 = row["idramo"].ToString(); - if (str22 != null) - { - length = str22.Length; - if (length == 1) - { - switch (str22[0]) - { - case '1': - case '2': - case '3': - { - goto Label3; - } - case '4': - case '8': - { - break; - } - case '5': - { - if (dataTable3.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList().Count == 0) - { - continue; - } - DataRow dataRow4 = dataTable3.AsEnumerable().FirstOrDefault((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())); - Item item1 = granizo; - Auto auto = new Auto(); - if (dataRow4 != null) - { - str7 = dataRow4["IDFABRICANTE"].ToString(); - } - else - { - str7 = null; - } - if (string.IsNullOrEmpty(str7)) - { - fabricante = null; - } - else - { - fabricante = new Fabricante(); - if (dataRow4 != null) - { - str19 = dataRow4["IDFABRICANTE"].ToString(); - } - else - { - str19 = null; - } - ((Fabricante)fabricante).Id = int.Parse(str19); - if (dataRow4 != null) - { - str20 = dataRow4["fabricante"].ToString(); - } - else - { - str20 = null; - } - ((Fabricante)fabricante).Descricao = str20; - } - auto.Fabricante = (Fabricante)fabricante; - if (dataRow4 != null) - { - str8 = dataRow4["modelo"].ToString(); - } - else - { - str8 = null; - } - auto.Modelo = str8; - if (dataRow4 != null) - { - str9 = dataRow4["anofab"].ToString(); - } - else - { - str9 = null; - } - auto.AnoFabricacao = str9; - if (dataRow4 != null) - { - str10 = dataRow4["anomod"].ToString(); - } - else - { - str10 = null; - } - auto.AnoModelo = str10; - if (dataRow4 != null) - { - str11 = dataRow4["placa"].ToString(); - } - else - { - str11 = null; - } - auto.Placa = str11; - if (dataRow4 != null) - { - str12 = dataRow4["chassi"].ToString(); - } - else - { - str12 = null; - } - auto.Chassi = str12; - if (dataRow4 != null) - { - str13 = dataRow4["ci"].ToString(); - } - else - { - str13 = null; - } - auto.Ci = str13; - if (dataRow4 != null) - { - str14 = dataRow4["renavam"].ToString(); - } - else - { - str14 = null; - } - auto.Renavam = str14; - if (dataRow4 != null) - { - str15 = dataRow4["CEPpernoite"].ToString(); - } - else - { - str15 = null; - } - auto.CepPernoite = str15; - if (dataRow4 != null) - { - str16 = dataRow4["financiado"].ToString(); - } - else - { - str16 = null; - } - auto.Financiado = new bool?(str16 == "1"); - auto.TipoCobertura = (!string.IsNullOrEmpty(dataRow4["idtipocobertura"].ToString()) ? new TipoCobertura?((TipoCobertura)int.Parse(dataRow4["idtipocobertura"].ToString())) : new TipoCobertura?(0)); - if (string.IsNullOrEmpty(dataRow4["bonus"].ToString())) - { - nullable3 = null; - } - else - { - nullable3 = new int?(int.Parse(dataRow4["bonus"].ToString())); - } - auto.Bonus = nullable3; - auto.RegiaoCirculacao = dataRow4["regiaocirculacao"].ToString(); - if (!string.IsNullOrEmpty(dataRow4["idtabelareferencia"].ToString())) - { - tabelaReferencium = (TabelaReferencia)int.Parse(dataRow4["idtabelareferencia"].ToString()); - } - else - { - tabelaReferencium = TabelaReferencia.Molicar; - } - auto.TabelaReferencia = new TabelaReferencia?(tabelaReferencium); - auto.PorcentagemReferencia = (string.IsNullOrEmpty(dataRow4["porcentagemreferencia"].ToString()) ? decimal.Zero : decimal.Parse(dataRow4["porcentagemreferencia"].ToString())); - auto.Fipe = dataRow4["CODFIPE"].ToString(); - if (dataRow4 != null) - { - str17 = dataRow4["idcor"].ToString(); - } - else - { - str17 = null; - } - if (!string.IsNullOrEmpty(str17)) - { - if (dataRow4 != null) - { - str18 = dataRow4["idcor"].ToString(); - } - else - { - str18 = null; - } - cor = (Cor)int.Parse(str18); - } - else - { - cor = Cor.OutrosNull; - } - auto.Cor = new Cor?(cor); - item1.Auto = auto; - goto Label2; - } - default: - { - goto Label2; - } - } - } - else if (length == 2) - { - switch (str22[1]) - { - case '0': - { - if (str22 == "10") - { - goto Label2; - } - if (str22 == "20") - { - if (dataTable11.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList().Count <= 0) - { - goto Label2; - } - granizo.Granizo = new Granizo() - { - Observacao = dataTable11.AsEnumerable().FirstOrDefault((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString()))["obs"].ToString() - }; - goto Label2; - } - else - { - goto Label2; - } - } - case '1': - { - if (str22 == "31" || str22 == "41") - { - break; - } - goto Label2; - } - case '3': - { - if (str22 == "53") - { - goto Label2; - } - if (str22 == "23" || str22 == "33") - { - break; - } - if (str22 == "13") - { - if (dataTable10.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList().Count <= 0) - { - goto Label2; - } - granizo.Aeronautico = new Aeronautico() - { - Observacao = dataTable10.AsEnumerable().FirstOrDefault((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString()))["obs"].ToString() - }; - goto Label2; - } - else - { - goto Label2; - } - } - case '5': - { - if (str22 == "15") - { - goto Label3; - } - goto Label2; - } - case '6': - { - if (str22 == "16" || str22 == "26") - { - break; - } - goto Label2; - } - case '7': - { - if (str22 == "17") - { - break; - } - goto Label2; - } - case '8': - { - if (str22 == "18") - { - goto Label3; - } - if (str22 == "28") - { - break; - } - goto Label2; - } - case '9': - { - if (str22 == "19" || str22 == "39" || str22 == "59") - { - break; - } - goto Label2; - } - default: - { - goto Label2; - } - } - } - else - { - goto Label2; - } - if (dataTable9.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList().Count > 0) - { - granizo.RiscosDiversos = new RiscosDiversos() - { - Observacao = dataTable9.AsEnumerable().FirstOrDefault((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString()))["obs"].ToString() - }; - } - } - Label2: - List sinistros = new List(); - granizo.Sinistros = new List(); - foreach (DataRow row1 in dataTable5.Rows) - { - if (row1["iditem"].ToString() != row["iditem"].ToString()) - { - continue; - } - long num = long.Parse(row1["idcontrolesinistro"].ToString()); - EnumerableRowCollection dataRows = dataTable6.AsEnumerable().Where((DataRow x) => x.Field("idcontrolesinistro") == num); - Action action1 = action; - if (action1 == null) - { - Action action2 = (DataRow x) => { - DataRow dataRow; - DataRow dataRow1; - object sinistroVida; - object sinistroAuto; - DataTable cSu0024u003cu003e8_locals1 = dataTable8; - if (cSu0024u003cu003e8_locals1 != null) - { - dataRow = cSu0024u003cu003e8_locals1.AsEnumerable().FirstOrDefault((DataRow s) => s.Field("idsinistro") == x.Field("idsinistro")); - } - else - { - dataRow = null; - } - DataRow dataRow2 = dataRow; - DataTable dataTable = dataTable7; - if (dataTable != null) - { - dataRow1 = dataTable.AsEnumerable().FirstOrDefault((DataRow s) => s.Field("idsinistro") == x.Field("idsinistro")); - } - else - { - dataRow1 = null; - } - DataRow dataRow3 = dataRow1; - if (dataRow2 == null) - { - sinistroVida = null; - } - else - { - sinistroVida = new SinistroVida(); - ((DomainBase)sinistroVida).Id = dataRow2.Field("idsinistrovida"); - ((SinistroVida)sinistroVida).Beneficiario = dataRow2.Field("beneficiario"); - } - SinistroVida sinistroVida1 = (SinistroVida)sinistroVida; - if (dataRow3 == null) - { - sinistroAuto = null; - } - else - { - sinistroAuto = new SinistroAuto(); - ((DomainBase)sinistroAuto).Id = dataRow3.Field("idsinistroauto"); - } - SinistroAuto sinistroAuto1 = (SinistroAuto)sinistroAuto; - sinistros.Add(new Sinistro() - { - Id = x.Field("idsinistro"), - Numero = x.Field("numsinistro"), - DataReclamacao = x.Field("datareclamacao"), - StatusSinistro = (x.Field("idstatussinistro") != null ? new StatusSinistro?((StatusSinistro)int.Parse(x.Field("idstatussinistro").ToString())) : null), - DataLiquidacao = x.Field("dataliquidacao"), - ItemSinistrado = x.Field("itemsinistrado"), - Motivo = x.Field("motivo"), - Valor = x.Field("valor").GetValueOrDefault(), - SinistroVida = sinistroVida1, - SinistroAuto = sinistroAuto1 - }); - }; - Action action3 = action2; - action = action2; - action1 = action3; - } - dataRows.ForEach(action1); - granizo.Sinistros.Add(new ControleSinistro() - { - Id = num, - DataSinistro = row1.Field("datasinistro"), - Item = new Item() - { - Id = long.Parse(row["iditem"].ToString()) - }, - Sinistros = sinistros - }); - } - items.Add(granizo); - } - return items; - Label1: - dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM resempco WHERE ", ""); - dataTable4.Merge(dataTable1); - goto Label0; - Label3: - if (dataTable4.AsEnumerable().Where((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())).ToList().Count == 0) - { - goto Label4; - } - DataRow dataRow5 = dataTable4.AsEnumerable().FirstOrDefault((DataRow x) => x.Field("iditem") == long.Parse(this.i["iditem"].ToString())); - Item item2 = granizo; - Patrimonial patrimonial = new Patrimonial(); - if (dataRow5 != null) - { - str = dataRow5["endereco"].ToString(); - } - else - { - str = null; - } - patrimonial.Endereco = str; - if (dataRow5 != null) - { - str1 = dataRow5["numero"].ToString(); - } - else - { - str1 = null; - } - patrimonial.Numero = str1; - if (dataRow5 != null) - { - str2 = dataRow5["complemento"].ToString(); - } - else - { - str2 = null; - } - patrimonial.Complemento = str2; - if (dataRow5 != null) - { - str3 = dataRow5["bairro"].ToString(); - } - else - { - str3 = null; - } - patrimonial.Bairro = str3; - if (dataRow5 != null) - { - str4 = dataRow5["cidade"].ToString(); - } - else - { - str4 = null; - } - patrimonial.Cidade = str4; - if (dataRow5 != null) - { - str5 = dataRow5["uf"].ToString(); - } - else - { - str5 = null; - } - patrimonial.Estado = str5; - if (dataRow5 != null) - { - str6 = dataRow5["cep"].ToString(); - } - else - { - str6 = null; - } - patrimonial.Cep = str6; - item2.Patrimonial = patrimonial; - goto Label2; - } - - public Item FindById(long id) - { - ItemDb itemDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(itemDb); - } - - public List FindByIds(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Id) - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindItens(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Id) - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindItens(long id, StatusItem status) - { - List items; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - string str = ""; - switch (status) - { - case StatusItem.Ativos: - { - str = string.Format("AND d.idcontrole = {0} AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL", id); - break; - } - case StatusItem.Inativos: - { - str = string.Format("AND d.idcontrole = {0} AND (cancelado IS NOT NULL AND cancelado = '1' OR idsubstituido IS NOT NULL)", id); - break; - } - case StatusItem.Documento: - { - str = string.Format("AND d.iddocumento = {0}", id); - break; - } - case StatusItem.Controle: - { - str = string.Format("AND d.idcontrole = {0}", id); - break; - } - } - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT i.* FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE 1=1 ", str); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - string str1 = string.Concat(" AND iditem IN (", string.Join(",", ( - from x in dataTable.AsEnumerable().ToList() - select x.Field("iditem")).ToList()), ")"); - sqlCommand.CommandText = string.Concat("SELECT iditem, idcontrolesinistro, datasinistro FROM controlesinistro WHERE 1=1 ", str1); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - return dataTable.AsEnumerable().ToList().Select((DataRow x) => { - Item item = new Item() - { - Id = x.Field("iditem"), - Descricao = x.Field("descricao"), - Ordem = x.Field("ordem"), - Sinistrado = (x.Field("sinistrado") == null ? false : x.Field("sinistrado") == "1"), - Cancelado = (x.Field("cancelado") == null ? false : x.Field("cancelado") == "1"), - Substituicao = x.Field("idsubstituicao"), - Substituido = x.Field("idsubstituido"), - Status = x.Field("status"), - StatusInclusao = x.Field("statusinc") - }; - IEnumerable list = - from s in dataTable1.AsEnumerable().ToList() - where s.Field("iditem") == x.Field("iditem") - select s; - Func u003cu003e9_104 = ItemRepository.u003cu003ec.u003cu003e9__10_4; - if (u003cu003e9_104 == null) - { - u003cu003e9_104 = (DataRow s) => { - ControleSinistro controleSinistro = new ControleSinistro() - { - Id = s.Field("idcontrolesinistro") - }; - DateTime? nullable = s.Field("datasinistro"); - controleSinistro.DataSinistro = new DateTime?((nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue)); - return controleSinistro; - }; - ItemRepository.u003cu003ec.u003cu003e9__10_4 = u003cu003e9_104; - } - item.Sinistros = list.Select(u003cu003e9_104).ToList(); - return item; - }).OrderBy((Item x) => x.Ordem).ToList(); - } - } - else - { - items = new List(); - } - } - } - return items; - } - - public List FindItens(List documento) - { - List items; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT * FROM item WHERE iddocumento IN (", string.Join(",", - from x in documento - select x.Id), ")"); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - return ( - from x in dataTable.AsEnumerable().ToList() - select new Item() - { - Id = x.Field("iditem"), - Descricao = x.Field("descricao"), - Ordem = x.Field("ordem"), - Documento = new Documento() - { - Id = x.Field("iddocumento") - } - } into x - orderby x.Ordem - select x).ToList(); - } - else - { - items = new List(); - } - } - } - return items; - } - - public List FindItens(long id) - { - List list = ( - from x in base.All() - where x.Documento.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public int FindNextItem(long id) - { - int? nullable; - int? nullable1; - int? ordem; - int? nullable2; - List items = this.FindItens(id, StatusItem.Ativos); - if (items != null) - { - Item item = items.LastOrDefault(); - if (item != null) - { - ordem = item.Ordem; - } - else - { - nullable1 = null; - ordem = nullable1; - } - nullable = ordem; - if (nullable.HasValue) - { - nullable2 = new int?(nullable.GetValueOrDefault() + 1); - } - else - { - nullable1 = null; - nullable2 = nullable1; - } - } - else - { - nullable = null; - nullable2 = nullable; - } - nullable = nullable2; - return nullable.GetValueOrDefault(1); - } - - public Item Merge(Item item) - { - bool count; - List list; - ItemDb itemDb = ApplicationMapper.Mapper.Map(item); - IList coberturaDbs = itemDb.Coberturas; - if (coberturaDbs != null) - { - count = coberturaDbs.Count == 0; - } - else - { - count = false; - } - bool flag = count; - List list1 = ( - from x in this._unitOfWork.Query() - where x.Item.Id == itemDb.Id - select x).ToList(); - if (list1 != null) - { - list = list1.Where((CoberturaDb x) => { - IList coberturas = itemDb.Coberturas; - Func u003cu003e9_42 = ItemRepository.u003cu003ec.u003cu003e9__4_2; - if (u003cu003e9_42 == null) - { - u003cu003e9_42 = (CoberturaDb c) => c.Id; - ItemRepository.u003cu003ec.u003cu003e9__4_2 = u003cu003e9_42; - } - return !coberturas.Select(u003cu003e9_42).ToList().Contains(x.Id); - }).ToList(); - } - else - { - list = null; - } - List coberturaDbs1 = list; - itemDb.Coberturas = list1; - base.Merge(itemDb); - if (coberturaDbs1 != null && coberturaDbs1.Count > 0) - { - this._unitOfWork.Repository().DeleteRange(coberturaDbs1); - } - if (flag) - { - this._unitOfWork.Repository().DeleteRange(itemDb.Coberturas); - } - itemDb.Coberturas = null; - return ApplicationMapper.Mapper.Map(itemDb); - } - - public Item SaveOrUpdate(Item item) - { - ItemDb itemDb = ApplicationMapper.Mapper.Map(item); - this.SaveOrUpdate(itemDb); - return ApplicationMapper.Mapper.Map(itemDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs deleted file mode 100644 index 82f67fc..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs +++ /dev/null @@ -1,345 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Financeiro; -using Gestor.Infrastructure.Entities.Generic; -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.Financeiro; -using Gestor.Model.Domain.Financeiro.Relatorios; -using Gestor.Model.Domain.Generic; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class LancamentoRepository : GenericRepository, ILancamentoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public LancamentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List AddRange(List lancamento) - { - List lancamentoDbs = ApplicationMapper.Mapper.Map, List>(lancamento); - base.AddRange(lancamentoDbs); - return ApplicationMapper.Mapper.Map, List>(lancamentoDbs); - } - - public bool BancosContasUtilizado(long id) - { - return base.All().Any((LancamentoDb x) => x.Conta.Id == id); - } - - public void Delete(long id) - { - LancamentoDb lancamentoDb = base.FindEntityById(id); - if (lancamentoDb == null) - { - return; - } - base.Delete(lancamentoDb); - } - - public List Fechamento(FiltroFinanceiro filtro) - { - string str = (filtro.Centro == null || filtro.Centro.Count == 0 ? "" : string.Concat(" AND c.idcentro IN (", string.Join(",", filtro.Centro), ")")); - string str1 = (filtro.Plano == null || filtro.Plano.Count == 0 ? "" : string.Concat(" AND cp.idcplano IN (", string.Join(",", filtro.Plano), ")")); - string str2 = (filtro.Planos == null || filtro.Planos.Count == 0 ? "" : string.Concat(" AND c.idcplanos IN (", string.Join(",", filtro.Planos), ")")); - string str3 = (filtro.Conta == null || filtro.Conta.Count == 0 ? "" : string.Concat(" AND l.idconta IN (", string.Join(",", filtro.Conta), ")")); - return this.Select(string.Format(" AND {0} >= '{1:yyyy-MM-dd}' AND {2} <= '{3:yyyy-MM-dd}' {4} {5} {6} {7}", new object[] { filtro.Referencia, filtro.Inicio, filtro.Referencia, filtro.Fim, str, str1, str2, str3 })); - } - - public Saldo FecharSaldo(Saldo saldo) - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - decimal num = new decimal(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Format("SELECT sinal, vlrbaixa FROM lancamen WHERE idconta = {0} AND dtbaixa IS NOT NULL AND dtbaixa >= '{1:yyyy-MM-dd}' AND dtbaixa < '{2:yyyy-MM-dd}' ", saldo.Conta.Id, saldo.DataInicio, saldo.DataFinal); - DataTable dataTable = new DataTable(); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - num = (dataTable.Rows.Count == 0 ? decimal.Zero : dataTable.AsEnumerable().ToList().Sum((DataRow x) => { - decimal? nullable; - decimal? nullable1; - if (x.Field("sinal") == "0") - { - nullable = x.Field("vlrbaixa"); - return nullable.GetValueOrDefault(); - } - decimal? nullable2 = x.Field("vlrbaixa"); - if (nullable2.HasValue) - { - nullable1 = new decimal?(-nullable2.GetValueOrDefault()); - } - else - { - nullable = null; - nullable1 = nullable; - } - nullable = nullable1; - return nullable.GetValueOrDefault(); - })); - } - } - } - saldo.ValorFinal = new decimal?(saldo.ValorInicio + num); - return saldo; - } - - public List Find(DateTime inicio, DateTime fim, StatusLancamento status) - { - if (status == StatusLancamento.Baixados) - { - return this.Select(string.Format(" AND CAST(l.dtpre AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtpre AS DATE) <= '{1:yyyy-MM-dd}' AND l.dtbaixa IS NOT NULL", inicio, fim)); - } - if (status != StatusLancamento.Todos) - { - return this.Select(string.Format(" AND CAST(l.dtpre AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtpre AS DATE) <= '{1:yyyy-MM-dd}' AND l.dtbaixa IS NULL", inicio, fim)); - } - return this.Select(string.Format(" AND CAST(l.dtpre AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtpre AS DATE) <= '{1:yyyy-MM-dd}'", inicio, fim)); - } - - public List FindByBaixa(DateTime inicio, DateTime fim) - { - return this.Select(string.Format(" AND CAST(l.dtbaixa AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtbaixa AS DATE) <= '{1:yyyy-MM-dd}'", inicio, fim)); - } - - public List FindByCodigoBanco(List codigos) - { - List strs = codigos; - List lancamentos = new List(); - while (strs.Count > 0) - { - List list = strs.Take(2100).ToList(); - string str = string.Concat(" AND l.CodigoBanco IN ('", string.Join(",", list), "')"); - lancamentos.AddRange(this.Select(str)); - strs = (list.Count < 2100 ? new List() : strs.Except(list).ToList()); - } - return lancamentos; - } - - public List FindByConta(DateTime inicio, DateTime fim, long id) - { - return this.Select(string.Format(" AND l.idconta = {0} AND CAST(l.dtbaixa AS DATE) >= '{1:yyyy-MM-dd}' AND CAST(l.dtbaixa AS DATE) <= '{2:yyyy-MM-dd}'", id, inicio, fim)).Select((Lancamento x) => { - decimal? valorPago; - string nome; - decimal zero; - ExtratoConta extratoContum = new ExtratoConta() - { - IdLancamento = x.Id - }; - DateTime? baixa = x.Baixa; - extratoContum.Baixa = new DateTime?((baixa.HasValue ? baixa.GetValueOrDefault() : DateTime.MinValue)); - ControleFinanceiro controle = x.Controle; - if (controle != null) - { - Fornecedor fornecedor = controle.Fornecedor; - if (fornecedor != null) - { - nome = fornecedor.Nome; - } - else - { - nome = null; - } - } - else - { - nome = null; - } - extratoContum.Fornecedor = nome; - extratoContum.Historico = x.Historico; - extratoContum.TipoPagamento = new TipoPagamento?(x.TipoPagamento); - if (!x.ValorPago.HasValue) - { - zero = decimal.Zero; - } - else if (x.Sinal == Sinal.Credito) - { - valorPago = x.ValorPago; - zero = Math.Abs(valorPago.Value); - } - else - { - valorPago = x.ValorPago; - zero = -Math.Abs(valorPago.Value); - } - extratoContum.Valor = new decimal?(zero); - extratoContum.Sinal = x.Sinal; - return extratoContum; - }).ToList(); - } - - public List FindByControle(long id, StatusLancamento status) - { - if (status == StatusLancamento.Baixados) - { - return this.Select(string.Format(" AND l.idcfinan = {0} AND l.dtbaixa IS NOT NULL", id)); - } - if (status != StatusLancamento.Todos) - { - return this.Select(string.Format(" AND l.idcfinan = {0} AND l.dtbaixa IS NULL", id)); - } - return this.Select(string.Format(" AND l.idcfinan = {0}", id)); - } - - public Lancamento FindByControle(long id, int parcela) - { - return this.Select(string.Format(" AND l.idcfinan = {0} AND l.parcela = {1}", id, parcela)).FirstOrDefault(); - } - - public List FindByFornecedor(long id, StatusLancamento status) - { - if (status == StatusLancamento.Baixados) - { - return this.Select(string.Format(" AND c.idfornecedor = {0} AND l.dtbaixa IS NOT NULL", id)); - } - if (status != StatusLancamento.Todos) - { - return this.Select(string.Format(" AND c.idfornecedor = {0} AND l.dtbaixa IS NULL", id)); - } - return this.Select(string.Format(" AND c.idfornecedor = {0}", id)); - } - - public List FindByFornecedor(long id, DateTime date, Sinal sinal) - { - return this.Select(string.Format(" AND c.idfornecedor = {0} AND l.dtpre >= '{1:yyyy-MM-dd}' AND l.dtpre <= '{2:yyyy-MM-dd}' AND l.sinal = {3}", new object[] { id, date, date.AddMonths(1), (int)sinal })); - } - - public Lancamento FindById(long id) - { - LancamentoDb lancamentoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(lancamentoDb); - } - - public List FindByLancamento(DateTime inicio, DateTime fim, StatusLancamento status) - { - if (status == StatusLancamento.Baixados) - { - return this.Select(string.Format(" AND CAST(l.datacriacao AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.datacriacao AS DATE) <= '{1:yyyy-MM-dd}' AND l.dtbaixa IS NOT NULL", inicio, fim)); - } - if (status != StatusLancamento.Todos) - { - return this.Select(string.Format(" AND CAST(l.datacriacao AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.datacriacao AS DATE) <= '{1:yyyy-MM-dd}' AND l.dtbaixa IS NULL", inicio, fim)); - } - return this.Select(string.Format(" AND CAST(l.datacriacao AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.datacriacao AS DATE) <= '{1:yyyy-MM-dd}'", inicio, fim)); - } - - public List FindByPagamento(DateTime inicio, DateTime fim) - { - return this.Select(string.Format(" AND CAST(l.dtpagto AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtpagto AS DATE) <= '{1:yyyy-MM-dd}'", inicio, fim)); - } - - public List FindLancamentosByConta(DateTime inicio, DateTime fim, long id) - { - return this.Select(string.Format(" AND CAST(l.dtpre AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.dtpre AS DATE) <= '{1:yyyy-MM-dd}' AND l.idconta = {2}", inicio, fim, id)); - } - - public List FindPersonalizado(DateTime inicio, DateTime fim, StatusLancamento status, FiltroLancamentoData filtrodata) - { - string referencia = this.GetReferencia(filtrodata); - if (status == StatusLancamento.Baixados) - { - return this.Select(string.Format(" AND {0} >= '{1:yyyy-MM-dd}' AND {2} <= '{3:yyyy-MM-dd}' AND l.dtbaixa IS NOT NULL", new object[] { referencia, inicio, referencia, fim })); - } - if (status != StatusLancamento.Todos) - { - return this.Select(string.Format(" AND {0} >= '{1:yyyy-MM-dd}' AND {2} <= '{3:yyyy-MM-dd}' AND l.dtbaixa IS NULL", new object[] { referencia, inicio, referencia, fim })); - } - return this.Select(string.Format(" AND {0} >= '{1:yyyy-MM-dd}' AND {2} <= '{3:yyyy-MM-dd}'", new object[] { referencia, inicio, referencia, fim })); - } - - private string GetReferencia(FiltroLancamentoData filtro) - { - if (filtro == FiltroLancamentoData.Baixa) - { - return "CAST(l.dtbaixa AS DATE)"; - } - if (filtro != FiltroLancamentoData.Pagamento) - { - return "CAST(l.dtpre AS DATE)"; - } - return "CAST(l.dtpagto AS DATE)"; - } - - public bool HasByFornecedor(long id) - { - return base.All().Any((LancamentoDb x) => x.Controle.Fornecedor.Id == id); - } - - public Lancamento Merge(Lancamento lancamento) - { - LancamentoDb lancamentoDb = ApplicationMapper.Mapper.Map(lancamento); - base.Merge(lancamentoDb); - return ApplicationMapper.Mapper.Map(lancamentoDb); - } - - public Lancamento SaveOrUpdate(Lancamento lancamento) - { - LancamentoDb lancamentoDb = ApplicationMapper.Mapper.Map(lancamento); - this.SaveOrUpdate(lancamentoDb); - return ApplicationMapper.Mapper.Map(lancamentoDb); - } - - private List Select(string condition) - { - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - AuxiliarFinanceiro.Criar(sqlCommand); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT c.idfornecedor, f.nome, f.Ativo, c.idfornecedor, c.idcplanos, c.idcentro, c.historico as historicocfinan, c.parcela as parcelas, cp.idcplano, l.* FROM lancamen l INNER JOIN cfinan c on c.idcfinan = l.idcfinan LEFT OUTER JOIN cplanos cp on c.idcplanos = cp.idcplanos LEFT OUTER JOIN fornecedor f on f.idfornecedor = c.idfornecedor WHERE 1=1 ", condition); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return CustomMap.MapLancamento(dataTable); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs deleted file mode 100644 index 3dccaa4..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs +++ /dev/null @@ -1,158 +0,0 @@ -using AutoMapper; -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.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class MaisContatoRepository : GenericRepository, IMaisContatoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public MaisContatoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List DeleteContato(long clienteId, List contatos) - { - if (contatos == null) - { - return null; - } - List list = ( - from cliente in base.All() - where cliente.Cliente.Id == clienteId - select cliente).ToList().Where((MaisContatoDb contato) => { - List maisContatos = contatos; - Func u003cu003e9_83 = MaisContatoRepository.u003cu003ec.u003cu003e9__8_3; - if (u003cu003e9_83 == null) - { - u003cu003e9_83 = (MaisContato t) => t.Id; - MaisContatoRepository.u003cu003ec.u003cu003e9__8_3 = u003cu003e9_83; - } - if (maisContatos.Select(u003cu003e9_83).Contains(contato.Id)) - { - return false; - } - return !contato.Excluido; - }).ToList(); - if (contatos.Count == 0 && (list == null || list.Count == 0)) - { - return null; - } - list.ForEach((MaisContatoDb contato) => { - contato.Excluido = true; - base.Merge(contato); - }); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindByCustomerId(long id) - { - ClienteDb clienteDb = this._unitOfWork.Query().FirstOrDefault((ClienteDb x) => x.Id == id); - if (clienteDb == null) - { - return new List(); - } - Cliente cliente = ApplicationMapper.Mapper.Map(clienteDb); - List condicaos = new List() - { - new Condicao() - { - Campo = "idcliente", - Valores = id.CriarValor() - }, - new Condicao() - { - Campo = "excluido", - Valores = null, - Operacao = Operacao.Or, - Grupo = 1 - }, - new Condicao() - { - Campo = "excluido", - Valores = "0".CriarValor(), - Operacao = Operacao.Or, - Grupo = 1 - } - }; - return this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM clicontato WHERE", "").MapMaisContatos(cliente); - } - - public MaisContato FindById(long id) - { - MaisContatoDb maisContatoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(maisContatoDb); - } - - public List Inserir(List contatos, Cliente cliente) - { - contatos.ForEach((MaisContato x) => x.Cliente = cliente); - List maisContatoDbs = ApplicationMapper.Mapper.Map, List>(contatos); - base.AddRange(maisContatoDbs); - return ApplicationMapper.Mapper.Map, List>(maisContatoDbs); - } - - public List Inserir(List contatos) - { - List maisContatoDbs = ApplicationMapper.Mapper.Map, List>(contatos); - maisContatoDbs.ForEach((MaisContatoDb x) => { - if (x.Id == 0) - { - this.SaveOrUpdate(x); - return; - } - base.Merge(x); - }); - return ApplicationMapper.Mapper.Map, List>(maisContatoDbs); - } - - public MaisContato Merge(MaisContato maisContato) - { - MaisContatoDb maisContatoDb = ApplicationMapper.Mapper.Map(maisContato); - base.Merge(maisContatoDb); - return ApplicationMapper.Mapper.Map(maisContatoDb); - } - - public List Merge(List contatos, Cliente cliente) - { - List maisContatoDbs = ApplicationMapper.Mapper.Map, List>(contatos); - maisContatoDbs.ForEach((MaisContatoDb x) => { - if (x.Id != 0) - { - base.Merge(x); - return; - } - x.Cliente = ApplicationMapper.Mapper.Map(cliente); - this.SaveOrUpdate(x); - }); - return ApplicationMapper.Mapper.Map, List>(maisContatoDbs); - } - - public MaisContato SaveOrUpdate(MaisContato maisContato) - { - MaisContatoDb maisContatoDb = ApplicationMapper.Mapper.Map(maisContato); - this.SaveOrUpdate(maisContatoDb); - return ApplicationMapper.Mapper.Map(maisContatoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs deleted file mode 100644 index 639e281..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs +++ /dev/null @@ -1,127 +0,0 @@ -using AutoMapper; -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.Generic; -using Gestor.Model.Domain.Relatorios; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class MetaSeguradoraRepository : GenericRepository, IMetaSeguradoraRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public MetaSeguradoraRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find(long id) - { - return ( - from x in this._unitOfWork.Session.CreateQuery(string.Format("from MetaSeguradoraDb WHERE idciaseg = {0}", id)).List() - select new MetaSeguradora() - { - Id = x.Id, - Mes = x.Mes, - Ano = x.Ano, - Valor = x.Valor - }).ToList(); - } - - public MetaSeguradora FindById(long id) - { - MetaSeguradoraDb metaSeguradoraDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(metaSeguradoraDb); - } - - public List FindByMeta(Filtros filtro) - { - List metaSeguradoras; - object connection; - string str = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND idciaseg IN (", string.Join(",", - from v in filtro.Seguradoras - select v), ")")); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - object month = filtro.Fim.Month; - DateTime fim = filtro.Fim; - sqlCommand.CommandText = string.Format("SELECT IdMeta, IdCiaSeg, Mes, Ano, Valor\r\n FROM Meta\r\n WHERE (IdCiaSeg IS NOT NULL OR IdCiaSeg != '') AND Mes = {0} AND Ano = {1} {2};", month, fim.Year, str); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - return ( - from x in dataTable.AsEnumerable().ToList() - select new MetaSeguradora() - { - Id = x.Field("IdMeta"), - Mes = (Mes)x.Field("Mes"), - Ano = long.Parse(x.Field("Ano").ToString()), - Valor = x.Field("Valor"), - Seguradora = Auxiliar.Seguradoras.FirstOrDefault((Seguradora s) => s.Id == x.Field("IdCiaseg")) - }).ToList(); - } - else - { - metaSeguradoras = new List(); - } - } - } - return metaSeguradoras; - } - - public MetaSeguradora Merge(MetaSeguradora metaSeguradora) - { - MetaSeguradoraDb idAggilizador = ApplicationMapper.Mapper.Map(metaSeguradora); - idAggilizador.IdAggilizador = idAggilizador.Seguradora.IdAggilizador; - base.Merge(idAggilizador); - return ApplicationMapper.Mapper.Map(idAggilizador); - } - - public MetaSeguradora SaveOrUpdate(MetaSeguradora metaSeguradora) - { - MetaSeguradoraDb idAggilizador = ApplicationMapper.Mapper.Map(metaSeguradora); - idAggilizador.IdAggilizador = idAggilizador.Seguradora.IdAggilizador; - this.SaveOrUpdate(idAggilizador); - return ApplicationMapper.Mapper.Map(idAggilizador); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs deleted file mode 100644 index 04be6b1..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs +++ /dev/null @@ -1,125 +0,0 @@ -using AutoMapper; -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.Generic; -using Gestor.Model.Domain.Relatorios; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class MetaVendedorRepository : GenericRepository, IMetaVendedorRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public MetaVendedorRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find(long id) - { - return ( - from x in this._unitOfWork.Session.CreateQuery(string.Format("from MetaVendedorDb WHERE idvendedor = {0}", id)).List() - select new MetaVendedor() - { - Id = x.Id, - Mes = x.Mes, - Ano = x.Ano, - Valor = x.Valor - }).ToList(); - } - - public MetaVendedor FindById(long id) - { - MetaVendedorDb metaVendedorDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(metaVendedorDb); - } - - public List FindByMeta(Filtros filtro) - { - List metaVendedors; - object connection; - string str = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND idvendedor IN (", string.Join(",", - from v in filtro.Vendedores - select v), ")")); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - object month = filtro.Fim.Month; - DateTime fim = filtro.Fim; - sqlCommand.CommandText = string.Format("SELECT IdMetaVendedor, IdVendedor, Mes, Ano, Valor\r\n FROM MetaVendedor\r\n WHERE Mes = {0} AND Ano = {1} {2};", month, fim.Year, str); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - return ( - from x in dataTable.AsEnumerable().ToList() - select new MetaVendedor() - { - Id = x.Field("IdMetaVendedor"), - Mes = (Mes)x.Field("Mes"), - Ano = long.Parse(x.Field("Ano").ToString()), - Valor = x.Field("Valor"), - Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => v.Id == x.Field("idvendedor")) - }).ToList(); - } - else - { - metaVendedors = new List(); - } - } - } - return metaVendedors; - } - - public MetaVendedor Merge(MetaVendedor metaVendedor) - { - MetaVendedorDb metaVendedorDb = ApplicationMapper.Mapper.Map(metaVendedor); - base.Merge(metaVendedorDb); - return ApplicationMapper.Mapper.Map(metaVendedorDb); - } - - public MetaVendedor SaveOrUpdate(MetaVendedor metaVendedor) - { - MetaVendedorDb metaVendedorDb = ApplicationMapper.Mapper.Map(metaVendedor); - this.SaveOrUpdate(metaVendedorDb); - return ApplicationMapper.Mapper.Map(metaVendedorDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs deleted file mode 100644 index 799cb19..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Common; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.MalaDireta; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ModeloMalaDiretaRepository : GenericRepository, IModeloMalaDiretaRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ModeloMalaDiretaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - ModeloMalaDiretaDb modeloMalaDiretaDb = base.FindEntityById(id); - if (modeloMalaDiretaDb == null) - { - return; - } - base.Delete(modeloMalaDiretaDb); - } - - public List Find() - { - List list = base.All().ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public ModeloMalaDireta FindById(long id) - { - ModeloMalaDiretaDb modeloMalaDiretaDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(modeloMalaDiretaDb); - } - - public ModeloMalaDireta Merge(ModeloMalaDireta modelo) - { - ModeloMalaDiretaDb modeloMalaDiretaDb = ApplicationMapper.Mapper.Map(modelo); - base.Merge(modeloMalaDiretaDb); - return ApplicationMapper.Mapper.Map(modeloMalaDiretaDb); - } - - public ModeloMalaDireta SaveOrUpdate(ModeloMalaDireta modelo) - { - ModeloMalaDiretaDb modeloMalaDiretaDb = ApplicationMapper.Mapper.Map(modelo); - this.SaveOrUpdate(modeloMalaDiretaDb); - return ApplicationMapper.Mapper.Map(modeloMalaDiretaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs deleted file mode 100644 index f35835a..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs +++ /dev/null @@ -1,131 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -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.Domain.Ferramentas; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Relatorios; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class NotaFiscalRepository : GenericRepository, INotaFiscalRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public NotaFiscalRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - NotaFiscalDb notaFiscalDb = base.FindEntityById(id); - if (notaFiscalDb == null) - { - return; - } - base.Delete(notaFiscalDb); - } - - public List FindAll() - { - return this.Select(""); - } - - public List FindByDatas(Filtros filtro) - { - string str = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND IdSeguradora IN (", string.Join(",", - from v in filtro.Seguradoras - select v), ")")); - return this.Select(string.Format(" AND Data >= '{0:yyyy-MM-dd}' AND Data <= '{1:yyyy-MM-dd}' {2}", filtro.Inicio, filtro.Fim, str)); - } - - public bool FindByExtrato(long id) - { - return base.All().FirstOrDefault((NotaFiscalDb x) => x.IdExtrato == (long?)id) != null; - } - - public NotaFiscal Merge(NotaFiscal notaFiscal) - { - NotaFiscalDb notaFiscalDb = ApplicationMapper.Mapper.Map(notaFiscal); - base.Merge(notaFiscalDb); - return ApplicationMapper.Mapper.Map(notaFiscalDb); - } - - public NotaFiscal SaveOrUpdate(NotaFiscal notaFiscal) - { - NotaFiscalDb notaFiscalDb = ApplicationMapper.Mapper.Map(notaFiscal); - this.SaveOrUpdate(notaFiscalDb); - return ApplicationMapper.Mapper.Map(notaFiscalDb); - } - - private List Select(string condition) - { - List notaFiscals; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - Auxiliar.CriarAuxiliar(sqlCommand, false); - sqlCommand.CommandText = string.Concat("SELECT * FROM NotaFiscal WHERE 1=1 ", condition, ";"); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - return ( - from x in dataTable.AsEnumerable().ToList() - select new NotaFiscal() - { - Id = x.Field("Id"), - ValorLiquido = x.Field("ValorLiquido"), - Obs = x.Field("obs"), - IdExtrato = x.Field("IdExtrato"), - Iss = x.Field("Iss"), - ValorBruto = x.Field("ValorBruto"), - Data = x.Field("Data"), - Seguradora = Auxiliar.Seguradoras.FirstOrDefault((Seguradora v) => v.Id == x.Field("IdSeguradora")), - Estipulante = (!x.Field("IdEstipulante").HasValue ? null : Auxiliar.Estipulantes.FirstOrDefault((Estipulante e) => e.Id == x.Field("IdEstipulante"))), - Extrato = x.Field("Extrato"), - Ir = (x.Field("Ir") != null ? x.Field("Ir") : decimal.Zero) - }).ToList(); - } - else - { - notaFiscals = new List(); - } - } - } - return notaFiscals; - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs deleted file mode 100644 index d547f22..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs +++ /dev/null @@ -1,111 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Relatorios; -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.Relatorios; -using System; -using System.Collections.Generic; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ParametrosRelatorioRepository : GenericRepository, IParametrosRelatorioRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ParametrosRelatorioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - ParametrosRelatorioDb parametrosRelatorioDb = base.FindEntityById(id); - if (parametrosRelatorioDb == null) - { - return; - } - base.Delete(parametrosRelatorioDb); - } - - public List Find(long id, Relatorio relatorio) - { - List parametrosRelatorios = this.Select(new List() - { - new Condicao() - { - Campo = "IdUsuario", - Valores = id.CriarValor() - }, - new Condicao() - { - Campo = "Relatorio", - Valores = relatorio.CriarValor() - }, - new Condicao() - { - Campo = "Header", - Valores = null, - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = "Header", - Valores = "".CriarValor(), - Operador = Operador.Diferente - } - }); - if (parametrosRelatorios.Count == 0) - { - parametrosRelatorios = this.Select(new List() - { - new Condicao() - { - Campo = "IdUsuario", - Valores = 0.CriarValor() - }, - new Condicao() - { - Campo = "Relatorio", - Valores = relatorio.CriarValor() - }, - new Condicao() - { - Campo = "Header", - Valores = null, - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = "Header", - Valores = "".CriarValor(), - Operador = Operador.Diferente - } - }); - } - return parametrosRelatorios; - } - - public ParametrosRelatorio Merge(ParametrosRelatorio parametrosRelatorio) - { - ParametrosRelatorioDb parametrosRelatorioDb = ApplicationMapper.Mapper.Map(parametrosRelatorio); - base.Merge(parametrosRelatorioDb); - return ApplicationMapper.Mapper.Map(parametrosRelatorioDb); - } - - public ParametrosRelatorio SaveOrUpdate(ParametrosRelatorio parametrosRelatorio) - { - ParametrosRelatorioDb parametrosRelatorioDb = ApplicationMapper.Mapper.Map(parametrosRelatorio); - this.SaveOrUpdate(parametrosRelatorioDb); - return ApplicationMapper.Mapper.Map(parametrosRelatorioDb); - } - - public List Select(List condicao) - { - return this._unitOfWork.Select(condicao.CreateParameters(0), "SELECT * FROM CamposRelatorios WHERE ", "").MapCamposRelatorio(); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs deleted file mode 100644 index 19ce696..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs +++ /dev/null @@ -1,59 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Relatorios; -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.Relatorios; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ParametrosTotalizacaoRepository : GenericRepository, IParametrosTotalizacaoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ParametrosTotalizacaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - ParametrosTotalizacaoDb parametrosTotalizacaoDb = base.FindEntityById(id); - if (parametrosTotalizacaoDb == null) - { - return; - } - base.Delete(parametrosTotalizacaoDb); - } - - public List Find(long id, Relatorio relatorio) - { - List list = ( - from x in base.All() - where x.IdUsuario == id && (int)x.Relatorio == (int)relatorio && x.Header != "AGRUPAMENTO" - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public ParametrosTotalizacao Merge(ParametrosTotalizacao parametrosTotalizacao) - { - ParametrosTotalizacaoDb parametrosTotalizacaoDb = ApplicationMapper.Mapper.Map(parametrosTotalizacao); - base.Merge(parametrosTotalizacaoDb); - return ApplicationMapper.Mapper.Map(parametrosTotalizacaoDb); - } - - public ParametrosTotalizacao SaveOrUpdate(ParametrosTotalizacao parametrosTotalizacao) - { - ParametrosTotalizacaoDb parametrosTotalizacaoDb = ApplicationMapper.Mapper.Map(parametrosTotalizacao); - this.SaveOrUpdate(parametrosTotalizacaoDb); - return ApplicationMapper.Mapper.Map(parametrosTotalizacaoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs deleted file mode 100644 index 476ec1a..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs +++ /dev/null @@ -1,108 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ParceiroRepository : GenericRepository, IParceiroRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ParceiroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find() - { - List list = base.All().ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List Find(string filter) - { - ParceiroRepository.u003cu003ec__DisplayClass7_0 variable = null; - IQueryable parceiroDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(ParceiroDb), "x"); - IQueryable parceiroDbs1 = parceiroDbs.Where(Expression.Lambda>(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ParceiroDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(ParceiroRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(ParceiroRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) }), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(ParceiroDb), "x"); - return parceiroDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Parceiro)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Parceiro).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ParceiroDb).GetMethod("get_Nome").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); - } - - public Parceiro FindById(long id) - { - ParceiroDb parceiroDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(parceiroDb); - } - - public long FindLastId() - { - long num; - object connection; - SqlCommand sqlCommand; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - sqlCommand = sqlConnection.CreateCommand(); - } - else - { - sqlCommand = null; - } - using (SqlCommand sqlCommand1 = sqlCommand) - { - sqlCommand1.CommandText = "SELECT MAX(IDPARCEIRO) as id FROM parceiro"; - SqlDataReader sqlDataReader = sqlCommand1.ExecuteReader(); - sqlDataReader.Read(); - num = (sqlDataReader["id"] == null ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); - } - } - return num; - } - - public Parceiro Merge(Parceiro parceiro) - { - ParceiroDb parceiroDb = ApplicationMapper.Mapper.Map(parceiro); - base.Merge(parceiroDb); - return ApplicationMapper.Mapper.Map(parceiroDb); - } - - public Parceiro SaveOrUpdate(Parceiro parceiro) - { - ParceiroDb parceiroDb = ApplicationMapper.Mapper.Map(parceiro); - this.SaveOrUpdate(parceiroDb); - return ApplicationMapper.Mapper.Map(parceiroDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs deleted file mode 100644 index f6e2cdf..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs +++ /dev/null @@ -1,4562 +0,0 @@ -using AutoMapper; -using Gestor.Common.Helpers; -using Gestor.Common.Validation; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Helpers; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Common; -using Gestor.Model.Domain.Aggilizador; -using Gestor.Model.Domain.Common; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Relatorios; -using Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using NHibernate.Util; -using System; -using System.Collections; -using System.Collections.Generic; -using System.Collections.ObjectModel; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Diagnostics; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; -using System.Threading.Tasks; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ParcelaRepository : GenericRepository, IParcelaRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ParcelaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public async Task> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) - { - List documentos = new List(); - return await this.BuscaDocumentosPorVigenciaNew(filtro, buscaAssinaturas, painelBi); - } - - private async Task> BuscaDocumentosPorVigenciaNew(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) - { - NegocioCorretora fieldValue; - Predicate predicate; - object connection; - bool count; - string str; - bool flag; - object vendedor; - bool count1; - Documento documento1; - List itensAtivo; - object produto; - object obj; - object statu; - object banco; - List statusDocumentoAssinados; - bool flag1; - StatusAssinatura statusAssinatura; - NegocioCorretora negocioCorretora; - bool count2; - bool flag2; - Predicate predicate1 = null; - Predicate predicate2 = null; - Predicate predicate3 = null; - Predicate predicate4 = null; - Predicate predicate5 = null; - List documentos = new List(); - string str1 = "CAST(f.vigenciai AS DATE)"; - string referencia = filtro.Referencia; - if (referencia == "EMISSÃO") - { - str1 = "CAST(f.emissao AS DATE)"; - } - else if (referencia == "TRANSMISSÃO PROPOSTA") - { - str1 = "CAST(d.remessa AS DATE)"; - } - else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") - { - str1 = "CAST(p.cri_data AS DATE)"; - } - List condicaos = this.CriaCondicaoDocumento(filtro, str1); - List condicaos1 = new List(); - Condicao condicao = new Condicao() - { - Campo = "d.Excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos1.Add(condicao); - Condicao condicao1 = new Condicao() - { - Campo = "d.Excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos1.Add(condicao1); - condicaos.AddRange(condicaos1); - SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - bool flag3 = await this.ExisteTabelasAssinatura(); - bool flag4 = flag3; - List parcelas = new List(); - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - string str2 = "SELECT f.IDFATURA IdFatura, p.IDPARCELA IdParcela, d.IDDOCUMENTO IdDocumento, c.IDEMPRESA IdEmpresa, c.IDCLIENTE IdCliente, clie.CGCCPF DocumentoCliente, clie.MalaDireta MalaDireta, clie.NOME NomeCliente, clie.pasta PastaCliente, c.IDCONTROLE IdControle, cm.idclimail IdEmail, cm.email, ct.idclitelefone IdTelefone, ct.ddd Prefixo, ct.fone Numero, d.CONTRATO Apolice, d.PROPOSTA Proposta, d.PEDADIT PropostaEndosso, f.NumFatura NumeroFatura, f.Emissao EmissaoFatura, d.idnegocio Negocio, d.SITUACAO Situacao, f.VIGENCIAI VigenciaInicial, f.VIGENCIAF VigenciaFinal, p.VALOR PremioTotal, p.VALORLF PremioLiquido, p.comiss Comissao, c.IDRAMO IdRamo, r.NOME NomeRamo, c.IDCIASEG IdCiaSeg, cia.NOME NomeCia, cia.NomeSocial NomeSocialCia, c.IDPRODUTO IdProduto, pr.NOME NomeProduto, d.idestipulante IdEstipulante,d.idestipulante2 IdEstipulante2,d.idestipulante3 IdEstipulante3,d.idestipulante4 IdEstipulante4,d.idestipulante5 IdEstipulante5, e.nome NomeEstipulante, d.NegocioCorretora NegocioCorretora, p.datacontrole DataControleParcela, d.idstatus IdStatus, s.nome NomeStatus, p.CRI_DATA DataCriacaoParcela, d.TIPO Tipo, d.REMESSA Remessa, d.idbanco IdBanco, b.NOMEBANCO NomeBanco, d.AGENCIA Agencia, d.CONTA Conta, d.PASTA PastaDocumento, d.apoconferida ApoliceConferida, d.propassinada PropostaAssinada, vp.IDVENDEDORPARCELA IdVendedorParcela, vp.idtipovendedor IdTipoVendedor, vp.IDVENDEDOR IdVendedor, vp.VREP PorcentagemRepasse, v.NOME NomeVendedor FROM fatura f INNER JOIN parcela p ON p.IDPARCELA = f.IDPARCELA INNER JOIN documento d ON d.IDDOCUMENTO = p.IDDOCUMENTO INNER JOIN controle c ON c.IDCONTROLE = d.IDCONTROLE INNER JOIN cliente clie ON clie.IDCLIENTE = c.IDCLIENTE INNER JOIN ramo r ON r.IDRAMO = c.IDRAMO INNER JOIN ciaseg cia ON cia.IDCIASEG = c.IDCIASEG LEFT JOIN codigobanco b ON b.IDCODIGOBANCO = d.IDBANCO LEFT JOIN produto pr ON pr.IDPRODUTO = c.IDPRODUTO LEFT JOIN estipulante e ON e.idestipulante = d.idestipulante LEFT JOIN status s ON s.idstatus = d.idstatus LEFT JOIN vendedorparcela vp ON vp.IDPARCELA = f.IDPARCELA LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN clitelefone ct ON ct.IDCLIENTE = c.IDCLIENTE LEFT JOIN climail cm ON cm.IDCLIENTE = c.IDCLIENTE WHERE "; - sqlCommand.CommandText = string.Concat(str2, " ", sqlQueryCondition.Condicao, " ORDER BY f.IDPARCELA, d.IDDOCUMENTO, d.IDCONTROLE, vp.idtipovendedor, vp.IDVENDEDOR"); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - TipoSeguro tipoSeguro = sqlDataReader.GetFieldValue("Situacao", true, true); - if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora")) - { - fieldValue = sqlDataReader.GetFieldValue("NegocioCorretora", true, true); - } - else - { - flag3 = tipoSeguro == TipoSeguro.Renovacao; - if (flag3) - { - flag3 = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio"); - } - negocioCorretora = (!flag3 || !(sqlDataReader.GetFieldValue("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); - fieldValue = negocioCorretora; - } - NegocioCorretora negocioCorretora1 = fieldValue; - List negocio = filtro.Negocio; - if (negocio != null) - { - count = negocio.Count > 0; - } - else - { - count = false; - } - if (!count || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora1)) - { - List estipulantes = new List(); - sqlDataReader.GetFieldValue("idestipulante", true, true); - if (sqlDataReader.GetFieldValue("idestipulante", true, true) != 0) - { - List estipulantes1 = estipulantes; - Estipulante nome = new Estipulante(); - List estipulantes2 = Auxiliar.Estipulantes; - Predicate predicate6 = predicate1; - if (predicate6 == null) - { - Predicate predicate7 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante", true, true); - predicate = predicate7; - predicate1 = predicate7; - predicate6 = predicate; - } - nome.Nome = estipulantes2.Find(predicate6).Nome; - estipulantes1.Add(nome); - } - sqlDataReader.GetFieldValue("idestipulante2", true, true); - if (sqlDataReader.GetFieldValue("idestipulante2", true, true) != 0) - { - List estipulantes3 = estipulantes; - Estipulante nome1 = new Estipulante(); - List estipulantes4 = Auxiliar.Estipulantes; - Predicate predicate8 = predicate2; - if (predicate8 == null) - { - Predicate predicate9 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante2", true, true); - predicate = predicate9; - predicate2 = predicate9; - predicate8 = predicate; - } - nome1.Nome = estipulantes4.Find(predicate8).Nome; - estipulantes3.Add(nome1); - } - sqlDataReader.GetFieldValue("idestipulante3", true, true); - if (sqlDataReader.GetFieldValue("idestipulante3", true, true) != 0) - { - List estipulantes5 = estipulantes; - Estipulante estipulante1 = new Estipulante(); - List estipulantes6 = Auxiliar.Estipulantes; - Predicate predicate10 = predicate3; - if (predicate10 == null) - { - Predicate predicate11 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante3", true, true); - predicate = predicate11; - predicate3 = predicate11; - predicate10 = predicate; - } - estipulante1.Nome = estipulantes6.Find(predicate10).Nome; - estipulantes5.Add(estipulante1); - } - sqlDataReader.GetFieldValue("idestipulante4", true, true); - if (sqlDataReader.GetFieldValue("idestipulante4", true, true) != 0) - { - List estipulantes7 = estipulantes; - Estipulante nome2 = new Estipulante(); - List estipulantes8 = Auxiliar.Estipulantes; - Predicate predicate12 = predicate4; - if (predicate12 == null) - { - Predicate predicate13 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante4", true, true); - predicate = predicate13; - predicate4 = predicate13; - predicate12 = predicate; - } - nome2.Nome = estipulantes8.Find(predicate12).Nome; - estipulantes7.Add(nome2); - } - sqlDataReader.GetFieldValue("idestipulante5", true, true); - if (sqlDataReader.GetFieldValue("idestipulante5", true, true) != 0) - { - List estipulantes9 = estipulantes; - Estipulante estipulante2 = new Estipulante(); - List estipulantes10 = Auxiliar.Estipulantes; - Predicate predicate14 = predicate5; - if (predicate14 == null) - { - Predicate predicate15 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante5", true, true); - predicate = predicate15; - predicate5 = predicate15; - predicate14 = predicate; - } - estipulante2.Nome = estipulantes10.Find(predicate14).Nome; - estipulantes9.Add(estipulante2); - } - if (estipulantes.Count > 0) - { - List estipulantes11 = estipulantes; - str = string.Join(" | ", - from estipulante in estipulantes11 - select estipulante.Nome); - } - else - { - str = ""; - } - string str3 = str; - long num = sqlDataReader.GetFieldValue("IdDocumento", true, true); - long fieldValue1 = sqlDataReader.GetFieldValue("IdParcela", true, true); - Parcela observableCollection = parcelas.Find((Parcela p) => p.Id == fieldValue1); - if (observableCollection == null) - { - Parcela parcela = parcelas.Find((Parcela d) => d.Documento.Id == num); - if (parcela != null) - { - documento1 = parcela.Documento; - } - else - { - documento1 = null; - } - Documento zero = documento1; - if (zero != null) - { - zero = zero.DeepCopy(); - } - else - { - long num1 = sqlDataReader.GetFieldValue("IdControle", true, true); - long fieldValue2 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); - Documento documento2 = documentos.Find((Documento p) => p.Controle.Id == num1); - if (documento2 != null) - { - itensAtivo = documento2.ItensAtivo; - } - else - { - itensAtivo = null; - } - List items = itensAtivo; - if (items == null) - { - items = await this.BuscaItemsPorIdControle(num1); - } - Documento valueOrDefault = new Documento() - { - Id = num - }; - Controle controle = new Controle() - { - Id = num1, - IdEmpresa = fieldValue2 - }; - Cliente cliente = new Cliente() - { - Id = sqlDataReader.GetFieldValue("IdCliente", true, true), - Nome = sqlDataReader.GetFieldValue("NomeCliente", true, true), - Documento = sqlDataReader.GetFieldValue("DocumentoCliente", true, true), - Pasta = sqlDataReader.GetFieldValue("PastaCliente", true, true) - }; - bool? fieldValue3 = sqlDataReader.GetFieldValue("MalaDireta", true, true); - cliente.MalaDireta = new bool?(fieldValue3.GetValueOrDefault(true)); - ObservableCollection observableCollection1 = new ObservableCollection(); - ClienteTelefone clienteTelefone = new ClienteTelefone() - { - Id = sqlDataReader.GetFieldValue("IdTelefone", true, true), - Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), - Numero = sqlDataReader.GetFieldValue("Numero", true, true) - }; - observableCollection1.Add(clienteTelefone); - cliente.Telefones = observableCollection1; - ObservableCollection observableCollection2 = new ObservableCollection(); - ClienteEmail clienteEmail = new ClienteEmail() - { - Id = sqlDataReader.GetFieldValue("IdEmail", true, true), - Email = sqlDataReader.GetFieldValue("Email", true, true) - }; - observableCollection2.Add(clienteEmail); - cliente.Emails = observableCollection2; - controle.Cliente = cliente; - Ramo ramo = new Ramo() - { - Id = sqlDataReader.GetFieldValue("IdRamo", true, true), - Nome = sqlDataReader.GetFieldValue("NomeRamo", true, true) - }; - controle.Ramo = ramo; - Seguradora seguradora = new Seguradora() - { - Id = sqlDataReader.GetFieldValue("IdCiaSeg", true, true), - Nome = sqlDataReader.GetFieldValue("NomeCia", true, true), - NomeSocial = sqlDataReader.GetFieldValue("NomeSocialCia", true, true) - }; - controle.Seguradora = seguradora; - if (sqlDataReader.FieldIsNull("IdProduto")) - { - produto = null; - } - else - { - produto = new Produto(); - ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("IdProduto", true, true); - ((Produto)produto).Nome = sqlDataReader.GetFieldValue("NomeProduto", true, true); - } - controle.Produto = (Produto)produto; - valueOrDefault.Controle = controle; - if (sqlDataReader.FieldIsNull("IdEstipulante")) - { - obj = null; - } - else - { - obj = new Estipulante(); - ((DomainBase)obj).Id = sqlDataReader.GetFieldValue("IdEstipulante", true, true); - ((Estipulante)obj).Nome = sqlDataReader.GetFieldValue("NomeEstipulante", true, true); - } - valueOrDefault.Estipulante1 = (Estipulante)obj; - valueOrDefault.Estipulantes = str3; - if (sqlDataReader.FieldIsNull("IdStatus")) - { - statu = null; - } - else - { - statu = new Status(); - ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("IdStatus", true, true); - ((Status)statu).Nome = sqlDataReader.GetFieldValue("NomeStatus", true, true); - } - valueOrDefault.Status = (Status)statu; - valueOrDefault.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura); - valueOrDefault.Tipo = sqlDataReader.GetFieldValue("Tipo", true, true); - valueOrDefault.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); - valueOrDefault.Situacao = tipoSeguro; - fieldValue3 = sqlDataReader.GetFieldValue("ApoliceConferida", true, true); - valueOrDefault.ApoliceConferida = fieldValue3.GetValueOrDefault(); - fieldValue3 = sqlDataReader.GetFieldValue("PropostaAssinada", true, true); - valueOrDefault.PropostaAssinada = fieldValue3.GetValueOrDefault(); - valueOrDefault.Proposta = sqlDataReader.GetFieldValue("Proposta", true, true); - valueOrDefault.Apolice = sqlDataReader.GetFieldValue("Apolice", true, true); - valueOrDefault.PropostaEndosso = sqlDataReader.GetFieldValue("PropostaEndosso", true, true); - valueOrDefault.Remessa = sqlDataReader.GetFieldValue("Remessa", true, true); - valueOrDefault.DataControle = sqlDataReader.GetFieldValue("DataControleParcela", true, true); - valueOrDefault.DataCriacao = sqlDataReader.GetFieldValue("DataCriacaoParcela", true, true); - valueOrDefault.Pasta = sqlDataReader.GetFieldValue("PastaDocumento", true, true); - if (sqlDataReader.FieldIsNull("IdBanco")) - { - banco = null; - } - else - { - banco = new Banco(); - ((Banco)banco).Id = sqlDataReader.GetFieldValue("IdBanco", true, true); - ((Banco)banco).Nome = sqlDataReader.GetFieldValue("NomeBanco", true, true); - } - valueOrDefault.Banco = (Banco)banco; - valueOrDefault.Agencia = sqlDataReader.GetFieldValue("Agencia", true, true); - valueOrDefault.Conta = sqlDataReader.GetFieldValue("Conta", true, true); - valueOrDefault.ItensAtivo = items; - zero = valueOrDefault; - if (flag4 & buscaAssinaturas) - { - List statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(zero.Id); - string str4 = (zero.Tipo == 0 ? "PROPOSTA" : "PEDIDO DE ENDOSSO"); - statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => { - if (a.Documento.ToUpper() == str4 || a.Documento.ToUpper().Contains(str4)) - { - a.Selecionado = true; - } - }); - List statusDocumentoAssinados2 = statusDocumentoAssinados1; - StatusDocumentoAssinado statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault((StatusDocumentoAssinado a) => a.Selecionado); - Documento documento3 = zero; - if (statusDocumentoAssinados1 == null || statusDocumentoAssinados1.Count <= 0) - { - statusDocumentoAssinados = null; - } - else - { - statusDocumentoAssinados = statusDocumentoAssinados1; - } - documento3.Assinaturas = statusDocumentoAssinados; - Documento documento4 = zero; - flag1 = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status == StatusAssinatura.Assinado : false); - documento4.AssinadaSiggner = flag1; - Documento documento5 = zero; - statusAssinatura = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status : StatusAssinatura.NaoEnviado); - documento5.StatusAssinatura = statusAssinatura; - } - } - zero.Tipo = 2; - zero.AdicionalComiss = false; - zero.PremioAdicional = decimal.Zero; - zero.NumeroParcelas = decimal.One; - zero.Endosso = string.Concat("F ", sqlDataReader.GetFieldValue("NumeroFatura", true, true)); - zero.Comissao = sqlDataReader.GetFieldValue("Comissao", true, true); - zero.PremioLiquido = sqlDataReader.GetFieldValue("PremioLiquido", true, true); - zero.PremioTotal = sqlDataReader.GetFieldValue("PremioTotal", true, true); - zero.Vigencia1 = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); - zero.Vigencia2 = sqlDataReader.GetFieldValue("VigenciaFinal", true, true); - zero.Emissao = sqlDataReader.GetFieldValue("EmissaoFatura", true, true); - zero.DataControle = sqlDataReader.GetFieldValue("DataControleParcela", true, true); - if (zero.Controle.Cliente.Telefones != null) - { - long num2 = sqlDataReader.GetFieldValue("IdTelefone", true, true); - if (zero.Controle.Cliente.Telefones.FirstOrDefault((ClienteTelefone t) => t.Id == num2) == null) - { - ObservableCollection telefones = zero.Controle.Cliente.Telefones; - ClienteTelefone clienteTelefone1 = new ClienteTelefone() - { - Id = num2, - Prefixo = sqlDataReader.GetFieldValue("Prefixo", true, true), - Numero = sqlDataReader.GetFieldValue("Numero", true, true) - }; - telefones.Add(clienteTelefone1); - } - } - if (zero.Controle.Cliente.Emails != null) - { - long num3 = sqlDataReader.GetFieldValue("IdEmail", true, true); - if (zero.Controle.Cliente.Emails.FirstOrDefault((ClienteEmail t) => t.Id == num3) == null) - { - ObservableCollection emails = zero.Controle.Cliente.Emails; - ClienteEmail clienteEmail1 = new ClienteEmail() - { - Id = num3, - Email = sqlDataReader.GetFieldValue("Email", true, true) - }; - emails.Add(clienteEmail1); - } - } - Parcela parcela1 = new Parcela() - { - Id = fieldValue1, - Documento = zero - }; - observableCollection = parcela1; - parcelas.Add(observableCollection); - zero = null; - } - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - flag = tipoVendedor.Count > 0; - } - else - { - flag = false; - } - if (!flag) - { - List nums = filtro.Vendedores; - if (nums != null) - { - count1 = nums.Count > 0; - } - else - { - count1 = false; - } - if (!count1) - { - if (observableCollection.Vendedores == null) - { - observableCollection.Vendedores = new ObservableCollection(); - } - long fieldValue4 = sqlDataReader.GetFieldValue("IdTipoVendedor", true, true); - long num4 = sqlDataReader.GetFieldValue("IdVendedor", true, true); - if (observableCollection.Vendedores.ToList().Find((VendedorParcela vps) => { - if (vps.TipoVendedor.Id != fieldValue4) - { - return false; - } - return vps.Vendedor.Id == num4; - }) == null) - { - ObservableCollection observableCollection3 = observableCollection.Vendedores; - VendedorParcela vendedorParcela1 = new VendedorParcela() - { - PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue("PorcentagemRepasse", true, true)), - TipoVendedor = new TipoVendedor() - { - Id = fieldValue4 - } - }; - Vendedor vendedor1 = new Vendedor() - { - Id = num4, - Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true) - }; - vendedorParcela1.Vendedor = vendedor1; - observableCollection3.Add(vendedorParcela1); - } - } - } - if (observableCollection.Documento.VendedorPrincipal == null) - { - Documento documento6 = observableCollection.Documento; - if (sqlDataReader.FieldIsNull("IdVendedor")) - { - vendedor = null; - } - else - { - vendedor = new Vendedor(); - ((DomainBase)vendedor).Id = sqlDataReader.GetFieldValue("IdVendedor", true, true); - ((Vendedor)vendedor).Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true); - } - documento6.VendedorPrincipal = (Vendedor)vendedor; - } - str3 = null; - } - } - } - } - sqlCommand = null; - List tipoVendedor1 = filtro.TipoVendedor; - if (tipoVendedor1 != null) - { - count2 = tipoVendedor1.Count > 0; - } - else - { - count2 = false; - } - if (!count2) - { - List nums1 = filtro.Vendedores; - if (nums1 != null) - { - flag2 = nums1.Count > 0; - } - else - { - flag2 = false; - } - if (!flag2) - { - goto Label0; - } - } - foreach (Parcela parcela2 in parcelas) - { - Parcela parcela3 = parcela2; - List vendedorParcelas1 = await this.BuscaVendedoresPorIdParcela(parcela2.Id, parcela2.Documento.Controle.IdEmpresa, (long)1); - parcela3.Vendedores = new ObservableCollection(vendedorParcelas1); - parcela3 = null; - } - Label0: - parcelas.ForEach((Parcela p) => { - decimal? nullable2; - decimal? porcentagemRepasse; - ObservableCollection vendedores = p.Vendedores; - Func u003cu003e9_1516 = ParcelaRepository.u003cu003ec.u003cu003e9__15_16; - if (u003cu003e9_1516 == null) - { - u003cu003e9_1516 = (VendedorParcela tipo) => tipo.TipoVendedor.Id; - ParcelaRepository.u003cu003ec.u003cu003e9__15_16 = u003cu003e9_1516; - } - IOrderedEnumerable vendedorParcelas = vendedores.OrderBy(u003cu003e9_1516); - Func u003cu003e9_1517 = ParcelaRepository.u003cu003ec.u003cu003e9__15_17; - if (u003cu003e9_1517 == null) - { - u003cu003e9_1517 = (VendedorParcela v) => v.Vendedor; - ParcelaRepository.u003cu003ec.u003cu003e9__15_17 = u003cu003e9_1517; - } - List list = vendedorParcelas.Select(u003cu003e9_1517).ToList(); - p.Documento.Vendedores = list; - Documento documento = p.Documento; - VendedorParcela vendedorParcela = p.Vendedores.FirstOrDefault((VendedorParcela v) => { - long? nullable; - long id = v.Vendedor.Id; - Vendedor vendedorPrincipal = p.Documento.VendedorPrincipal; - nullable = (vendedorPrincipal != null ? new long?(vendedorPrincipal.Id) : null); - long? nullable1 = nullable; - return id == nullable1.GetValueOrDefault() & nullable1.HasValue; - }); - if (vendedorParcela != null) - { - porcentagemRepasse = vendedorParcela.PorcentagemRepasse; - } - else - { - nullable2 = null; - porcentagemRepasse = nullable2; - } - nullable2 = porcentagemRepasse; - documento.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault()); - documentos.Add(p.Documento); - }); - parcelas = null; - } - sqlConnection = null; - } - sessionFactory = null; - List documentos1 = documentos; - sqlQueryCondition = null; - return documentos1; - } - - private async Task> BuscaDocumentosPorVigenciaPrivate(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false) - { - NegocioCorretora negocioCorretora; - List.Enumerator enumerator; - decimal? nullable; - DateTime? nullable1; - object connection; - bool count; - string str; - bool flag; - Seguradora seguradora; - Ramo ramo1; - Produto produto1; - bool flag1; - Negocio negocio; - DateTime? nullable2; - DateTime dateTime; - DateTime? nullable3; - DateTime? nullable4; - Estipulante estipulante1; - DateTime? nullable5; - Status statu; - bool flag2; - List statusDocumentoAssinados; - bool flag3; - StatusAssinatura statusAssinatura; - DateTime? nullable6; - decimal? porcentagemRepasse; - List list; - List nums; - NegocioCorretora negocioCorretora1; - bool count1; - Func func = null; - Func func1 = null; - Func func2 = null; - Func func3 = null; - Func func4 = null; - Func func5 = null; - List documentos = new List(); - string str1 = "CAST(f.vigenciai AS DATE)"; - string referencia = filtro.Referencia; - if (referencia == "EMISSÃO") - { - str1 = "CAST(f.emissao AS DATE)"; - } - else if (referencia == "TRANSMISSÃO PROPOSTA") - { - str1 = "CAST(d.remessa AS DATE)"; - } - else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO") - { - str1 = "CAST(p.cri_data AS DATE)"; - } - List condicaos = this.CriaCondicaoDocumento(filtro, str1); - List condicaos1 = new List(); - Condicao condicao = new Condicao() - { - Campo = "d.Excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos1.Add(condicao); - Condicao condicao1 = new Condicao() - { - Campo = "d.Excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos1.Add(condicao1); - condicaos.AddRange(condicaos1); - SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 0; - Auxiliar.CriarAuxiliar(sqlCommand, false); - bool flag4 = await this.ExisteTabelasAssinatura(); - bool flag5 = flag4; - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - count = tipoVendedor.Count > 0; - } - else - { - count = false; - } - if (!count) - { - List vendedores = filtro.Vendedores; - if (vendedores != null) - { - count1 = vendedores.Count > 0; - } - else - { - count1 = false; - } - if (count1) - { - goto Label1; - } - str = ""; - goto Label0; - } - Label1: - str = "INNER JOIN vendedorparcela vp ON p.idparcela = vp.idparcela"; - Label0: - string str2 = string.Concat("SELECT DISTINCT c.IdEmpresa,c.IdCliente,cli.CGCCPF,cli.MalaDireta,cli.Nome,d.IdControle,p.IdParcela,d.IdDocumento,d.Contrato,f.NumFatura,f.Emissao,d.IdNegocio,d.Situacao,f.VigenciaI,f.VigenciaF,ISNULL(p.Valor, 0.00) Total,ISNULL(p.ValorLF, 0.00) Liquido,ISNULL(p.comiss, 0.00) Comissao,c.IdRamo,c.IdCiaSeg,c.IdProduto,d.IdEstipulante,d.NegocioCorretora,p.DataControle,d.IdStatus,p.Cri_Data,d.Remessa,d.IdBanco,cb.NomeBanco,d.Agencia,d.Conta,d.Pasta,d.ApoConferida,d.PropAssinada,cli.pasta PastaCliente FROM fatura f INNER JOIN parcela p ON p.IdParcela = f.IdParcela ", str, " INNER JOIN documento d ON d.IdDocumento = p.IdDocumento INNER JOIN controle c ON c.IdControle = d.IdControle INNER JOIN cliente cli ON cli.IdCliente = c.IdCliente LEFT JOIN codigobanco cb ON d.idbanco = cb.idcodigobanco WHERE "); - sqlCommand.CommandText = string.Concat(str2, " ", sqlQueryCondition.Condicao); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - long item = (long)sqlDataReader["idparcela"]; - long num = (long)sqlDataReader["iddocumento"]; - long item1 = (long)sqlDataReader["idcontrole"]; - long num1 = (long)sqlDataReader["idempresa"]; - string str3 = "PEDIDO DE ENDOSSO"; - if (!await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("negociocorretora"))) - { - negocioCorretora = (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), sqlDataReader["negociocorretora"].ToString()); - } - else - { - flag4 = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()) == TipoSeguro.Renovacao; - if (flag4) - { - flag4 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio")); - } - negocioCorretora1 = (!flag4 || !(sqlDataReader["idnegocio"].ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); - negocioCorretora = negocioCorretora1; - } - NegocioCorretora negocioCorretora2 = negocioCorretora; - Vendedor vendedor = new Vendedor(); - List vendedors = new List(); - List items = new List(); - List statusDocumentoAssinados1 = new List(); - StatusDocumentoAssinado statusDocumentoAssinado = null; - decimal valueOrDefault = new decimal(); - if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora2)) - { - if (!painelBi) - { - List vendedorParcelas = await this.BuscaVendedoresPorIdParcela(item, num1, (long)1); - if (filtro.Vendedores != null && filtro.Vendedores.Count > 0) - { - bool flag6 = true; - foreach (long list1 in filtro.Vendedores.ToList()) - { - if (!vendedorParcelas.Any((VendedorParcela v) => v.Vendedor.Id == list1)) - { - continue; - } - flag6 = false; - } - if (flag6) - { - continue; - } - } - List vendedorParcelas1 = vendedorParcelas; - IOrderedEnumerable id = - from tipo in vendedorParcelas1 - orderby tipo.TipoVendedor.Id - select tipo; - vendedors = ( - from v in id - select v.Vendedor).ToList(); - if (filtro.TipoVendedor != null && filtro.TipoVendedor.Count != 0) - { - if (filtro.TipoVendedor != null) - { - List tipoVendedor1 = filtro.TipoVendedor; - if (tipoVendedor1.Any((long v) => v == (long)1)) - { - goto Label3; - } - } - Vendedor vendedor1 = null; - Filtros filtro1 = filtro; - if (filtro1 != null) - { - List nums1 = filtro1.TipoVendedor; - if (nums1 != null) - { - list = ( - from t in nums1 - orderby t - select t).ToList(); - } - else - { - list = null; - } - } - else - { - list = null; - } - enumerator = list.GetEnumerator(); - try - { - do - { - if (!enumerator.MoveNext()) - { - break; - } - long current = enumerator.Current; - Filtros filtro2 = filtro; - if (filtro2 != null) - { - List vendedores1 = filtro2.Vendedores; - if (vendedores1 != null) - { - nums = vendedores1.ToList(); - } - else - { - nums = null; - } - } - else - { - nums = null; - } - List.Enumerator enumerator1 = nums.GetEnumerator(); - try - { - do - { - if (!enumerator1.MoveNext()) - { - break; - } - long current1 = enumerator1.Current; - IEnumerable vendedorParcelas2 = vendedorParcelas.Where((VendedorParcela v) => { - if (v.TipoVendedor.Id != current) - { - return false; - } - return v.Vendedor.Id == current1; - }); - vendedor1 = ( - from v in vendedorParcelas2 - select v.Vendedor).FirstOrDefault(); - } - while (vendedor1 == null); - } - finally - { - ((IDisposable)enumerator1).Dispose(); - } - } - while (vendedor1 == null); - } - finally - { - ((IDisposable)enumerator).Dispose(); - } - if ((filtro.Vendedores == null || filtro.Vendedores.Count == 0) && vendedor1 == null) - { - List vendedorParcelas3 = vendedorParcelas; - Func func6 = func; - if (func6 == null) - { - Func id1 = (VendedorParcela v) => v.TipoVendedor.Id == filtro.TipoVendedor.FirstOrDefault(); - Func func7 = id1; - func = id1; - func6 = func7; - } - IEnumerable vendedorParcelas4 = vendedorParcelas3.Where(func6); - vendedor1 = ( - from v in vendedorParcelas4 - select v.Vendedor).FirstOrDefault(); - } - Vendedor vendedor2 = vendedor1; - if (vendedor2 == null) - { - vendedor2 = vendedors.FirstOrDefault(); - } - vendedor = vendedor2; - goto Label2; - } - List vendedorParcelas5 = vendedorParcelas; - IEnumerable id2 = - from v in vendedorParcelas5 - where v.TipoVendedor.Id == (long)1 - select v; - vendedor = ( - from v in id2 - select v.Vendedor).FirstOrDefault(); - Label2: - VendedorParcela vendedorParcela = vendedorParcelas.FirstOrDefault((VendedorParcela v) => v.Vendedor.Id == vendedor.Id); - if (vendedorParcela != null) - { - porcentagemRepasse = vendedorParcela.PorcentagemRepasse; - } - else - { - nullable = null; - porcentagemRepasse = nullable; - } - nullable = porcentagemRepasse; - valueOrDefault = nullable.GetValueOrDefault(); - if (flag5 & buscaAssinaturas) - { - statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(num); - statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => { - if (a.Documento.ToUpper() == str3 || a.Documento.ToUpper().Contains(str3)) - { - a.Selecionado = true; - } - }); - List statusDocumentoAssinados2 = statusDocumentoAssinados1; - statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault((StatusDocumentoAssinado a) => a.Selecionado); - } - items = await this.BuscaItemsPorIdControle(item1); - } - List documentos1 = documentos; - Documento documento = new Documento() - { - Id = num - }; - Documento documento1 = documento; - Controle controle = new Controle() - { - Id = item1, - IdEmpresa = num1 - }; - Controle controle1 = controle; - Cliente cliente = new Cliente() - { - Id = (long)sqlDataReader["idcliente"], - Nome = sqlDataReader["nome"].ToString(), - Documento = sqlDataReader["cgccpf"].ToString(), - IdEmpresa = num1, - Pasta = sqlDataReader["pastacliente"].ToString() - }; - Cliente cliente1 = cliente; - flag4 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("maladireta")); - Cliente cliente2 = cliente1; - flag = (flag4 ? true : (bool)sqlDataReader["maladireta"]); - cliente2.MalaDireta = new bool?(flag); - controle1.Cliente = cliente; - Controle controle2 = controle; - bool flag7 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idciaseg")); - Controle controle3 = controle2; - if (flag7) - { - seguradora = null; - } - else - { - List seguradoras = Auxiliar.Seguradoras; - Func func8 = func1; - if (func8 == null) - { - Func id3 = (Seguradora seg) => seg.Id == (long)sqlDataReader["idciaseg"]; - Func func9 = id3; - func1 = id3; - func8 = func9; - } - seguradora = seguradoras.FirstOrDefault(func8); - } - controle3.Seguradora = seguradora; - Controle controle4 = controle; - bool flag8 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idramo")); - Controle controle5 = controle4; - if (flag8) - { - ramo1 = null; - } - else - { - List ramos = Auxiliar.Ramos; - Func func10 = func2; - if (func10 == null) - { - Func id4 = (Ramo ramo) => ramo.Id == (long)sqlDataReader["idramo"]; - Func func11 = id4; - func2 = id4; - func10 = func11; - } - ramo1 = ramos.FirstOrDefault(func10); - } - controle5.Ramo = ramo1; - Controle controle6 = controle; - bool flag9 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idproduto")); - Controle controle7 = controle6; - if (flag9) - { - produto1 = null; - } - else - { - List produtos = Auxiliar.Produtos; - Func func12 = func3; - if (func12 == null) - { - Func id5 = (Produto produto) => produto.Id == (long)sqlDataReader["idproduto"]; - Func func13 = id5; - func3 = id5; - func12 = func13; - } - produto1 = produtos.FirstOrDefault(func12); - } - controle7.Produto = produto1; - documento1.Controle = controle; - documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura); - documento.AdicionalComiss = false; - documento.Apolice = sqlDataReader["contrato"].ToString(); - Documento documento2 = documento; - bool flag10 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("apoconferida")); - Documento documento3 = documento2; - flag1 = (flag10 ? false : sqlDataReader["apoconferida"].ToString() == "1"); - documento3.ApoliceConferida = flag1; - documento.Endosso = string.Format("F {0}", sqlDataReader["numfatura"]); - documento.Comissao = (decimal)sqlDataReader["comissao"]; - Documento documento4 = documento; - bool flag11 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio")); - Documento documento5 = documento4; - negocio = (flag11 ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), sqlDataReader["idnegocio"].ToString())); - documento5.Negocio = new Negocio?(negocio); - documento.PremioLiquido = (decimal)sqlDataReader["liquido"]; - documento.PremioTotal = (decimal)sqlDataReader["total"]; - documento.NumeroParcelas = decimal.One; - Documento documento6 = documento; - bool flag12 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vigenciaf")); - Documento documento7 = documento6; - if (flag12) - { - nullable1 = null; - nullable2 = nullable1; - } - else - { - nullable2 = new DateTime?((DateTime)sqlDataReader["vigenciaf"]); - } - documento7.Vigencia2 = nullable2; - Documento documento8 = documento; - bool flag13 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vigenciai")); - Documento documento9 = documento8; - dateTime = (flag13 ? DateTime.MinValue : (DateTime)sqlDataReader["vigenciai"]); - documento9.Vigencia1 = dateTime; - Documento documento10 = documento; - bool flag14 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("emissao")); - Documento documento11 = documento10; - if (flag14) - { - nullable1 = null; - nullable3 = nullable1; - } - else - { - nullable3 = new DateTime?((DateTime)sqlDataReader["emissao"]); - } - documento11.Emissao = nullable3; - Documento documento12 = documento; - bool flag15 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("remessa")); - Documento documento13 = documento12; - if (flag15) - { - nullable1 = null; - nullable4 = nullable1; - } - else - { - nullable4 = new DateTime?((DateTime)sqlDataReader["remessa"]); - } - documento13.Remessa = nullable4; - documento.PercentualRepasse = new decimal?(valueOrDefault); - Documento documento14 = documento; - bool flag16 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idestipulante")); - Documento documento15 = documento14; - if (flag16) - { - estipulante1 = null; - } - else - { - List estipulantes = Auxiliar.Estipulantes; - Func func14 = func4; - if (func14 == null) - { - Func id6 = (Estipulante estipulante) => estipulante.Id == (long)sqlDataReader["idestipulante"]; - Func func15 = id6; - func4 = id6; - func14 = func15; - } - estipulante1 = estipulantes.FirstOrDefault(func14); - } - documento15.Estipulante1 = estipulante1; - documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora2); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()); - documento.Tipo = 2; - Documento documento16 = documento; - bool flag17 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("datacontrole")); - Documento documento17 = documento16; - if (flag17) - { - nullable1 = null; - nullable5 = nullable1; - } - else - { - nullable5 = new DateTime?((DateTime)sqlDataReader["datacontrole"]); - } - documento17.DataControle = nullable5; - Documento documento18 = documento; - bool flag18 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idstatus")); - Documento documento19 = documento18; - if (flag18) - { - statu = null; - } - else - { - List statusApolice = Auxiliar.StatusApolice; - Func func16 = func5; - if (func16 == null) - { - Func id7 = (Status status) => status.Id == (long)sqlDataReader["idstatus"]; - Func func17 = id7; - func5 = id7; - func16 = func17; - } - statu = statusApolice.FirstOrDefault(func16); - } - documento19.Status = statu; - documento.ItensAtivo = items; - Documento documento20 = documento; - bool flag19 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("propassinada")); - Documento documento21 = documento20; - flag2 = (flag19 ? false : sqlDataReader["propassinada"].ToString() == "1"); - documento21.PropostaAssinada = flag2; - documento.VendedorPrincipal = vendedor; - documento.Vendedores = vendedors; - Documento documento22 = documento; - if (statusDocumentoAssinados1.Count == 0) - { - statusDocumentoAssinados = null; - } - else - { - statusDocumentoAssinados = statusDocumentoAssinados1; - } - documento22.Assinaturas = statusDocumentoAssinados; - Documento documento23 = documento; - StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado; - if (statusDocumentoAssinado1 != null) - { - flag3 = statusDocumentoAssinado1.Status == StatusAssinatura.Assinado; - } - else - { - flag3 = false; - } - documento23.AssinadaSiggner = flag3; - Documento documento24 = documento; - StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado; - if (statusDocumentoAssinado2 != null) - { - statusAssinatura = statusDocumentoAssinado2.Status; - } - else - { - statusAssinatura = StatusAssinatura.NaoEnviado; - } - documento24.StatusAssinatura = statusAssinatura; - documento.Pasta = sqlDataReader["pasta"].ToString(); - Documento documento25 = documento; - bool flag20 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("cri_data")); - Documento documento26 = documento25; - if (flag20) - { - nullable1 = null; - nullable6 = nullable1; - } - else - { - nullable6 = new DateTime?((DateTime)sqlDataReader["cri_data"]); - } - documento26.DataCriacao = nullable6; - Documento documento27 = documento; - Banco banco = new Banco() - { - Nome = sqlDataReader["nomebanco"].ToString() - }; - documento27.Banco = banco; - documento.Agencia = sqlDataReader["agencia"].ToString(); - documento.Conta = sqlDataReader["conta"].ToString(); - documentos1.Add(documento); - documentos1 = null; - documento1 = null; - controle1 = null; - cliente1 = null; - cliente = null; - controle2 = null; - controle4 = null; - controle6 = null; - controle = null; - documento2 = null; - documento4 = null; - documento6 = null; - documento8 = null; - documento10 = null; - documento12 = null; - documento14 = null; - documento16 = null; - documento18 = null; - documento20 = null; - documento25 = null; - documento = null; - vendedors = null; - items = null; - statusDocumentoAssinados1 = null; - statusDocumentoAssinado = null; - } - } - } - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List documentos2 = documentos; - documentos = null; - sqlQueryCondition = null; - return documentos2; - } - - private async Task> BuscaItemsPorIdControle(long idControle) - { - object connection; - List items = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)"; - sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List items1 = items; - Item item = new Item() - { - Id = sqlDataReader.GetFieldValue("iditem", true, true), - Descricao = sqlDataReader.GetFieldValue("descricao", true, true) - }; - items1.Add(item); - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List items2 = items; - items = null; - return items2; - } - - private async Task> BuscaItemsPorIdControle(SqlConnection connection, long idControle) - { - List items = new List(); - using (SqlCommand sqlCommand = connection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)"; - sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List items1 = items; - Item item = new Item() - { - Id = (long)sqlDataReader["iditem"], - Descricao = sqlDataReader["descricao"].ToString() - }; - items1.Add(item); - } - } - sqlDataReader = null; - } - sqlCommand = null; - List items2 = items; - items = null; - return items2; - } - - public Documento BuscarApolice(long id) - { - DocumentoDb documento; - ParcelaDb parcelaDb = base.All().FirstOrDefault((ParcelaDb x) => x.Id == id); - if (parcelaDb != null) - { - documento = parcelaDb.Documento; - } - else - { - documento = null; - } - return ApplicationMapper.Mapper.Map(documento); - } - - public string BuscarLogAntigo(long id, string conn) - { - object connection; - string str = ""; - List condicaos = new List() - { - new Condicao() - { - Campo = "id", - Valores = id.CriarValor() - }, - new Condicao() - { - Campo = "idname", - Valores = "IDParcela".CriarValor() - } - }; - this._unitOfWork.CriarAuxiliar(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - string str1 = "oldbacklog"; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog"; - SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); - sqlDataReader.Read(); - string str2 = sqlDataReader["bdname"].ToString(); - str1 = sqlDataReader["tabela"].ToString(); - sqlDataReader.Close(); - if (sqlConnection.Database != str2) - { - conn = conn.Replace(sqlConnection.Database, str2); - } - } - } - DataTable dataTable = new DataTable(); - using (SqlConnection sqlConnection1 = new SqlConnection(conn)) - { - sqlConnection1.Open(); - using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand()) - { - sqlCommand1.CommandTimeout = 15000; - dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), ""); - } - } - if (dataTable == null || dataTable.Rows.Count == 0) - { - return ""; - } - if (dataTable != null) - { - dataTable.AsEnumerable().OrderBy((DataRow x) => x.Field("idbacklog")).ToList().ForEach((DataRow x) => { - str = string.Concat(new string[] { str, "
(", x.Field("data").ToString(), ") ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field("idusuario")).Nome, "
" }); - str = string.Concat(str, "", x.Field("historico").ToString().Replace(Environment.NewLine, "
"), ""); - }); - } - return str; - } - - public ParcelaPendente BuscarPendencia(long id) - { - ParcelaPendente parcelaPendente; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - try - { - sqlCommand.CommandText = string.Format("SELECT * FROM parcelapendente WHERE idparcelapendente = {0}", id); - SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); - if (sqlDataReader.HasRows) - { - sqlDataReader.Read(); - parcelaPendente = new ParcelaPendente() - { - Id = (long)sqlDataReader["idparcelapendente"], - IdParcela = (long)sqlDataReader["idparcela"], - Seguradora = (string)sqlDataReader["seguradora"], - Cliente = (string)sqlDataReader["cliente"], - Apolice = (string)sqlDataReader["apolice"], - Parcela = (int)sqlDataReader["parcela"], - Valor = decimal.Parse(sqlDataReader["valor"].ToString()), - Vencimento = DateTime.Parse(sqlDataReader["vencto"].ToString()) - }; - } - else - { - parcelaPendente = null; - } - } - catch (Exception exception) - { - parcelaPendente = null; - } - } - } - return parcelaPendente; - } - - private async Task> BuscaStatusAssinadosPorIdDocumento(long idDocumento) - { - object connection; - DateTime? nullable; - Usuario usuario1; - Func func = null; - List statusDocumentoAssinados = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - sqlCommand.CommandText = "SELECT a.idnewarquivodigital,a.descricao,ISNULL(s.Status ,3) status,s.assinado,a.iddocumento,s.id,s.usuarioid,s.enviado FROM newarquivodigital a LEFT JOIN ArquivoParaAssinatura s ON a.idnewarquivodigital = s.indiceid WHERE a.iddocumento = @documento AND (a.excluido = 0 OR a.excluido IS NULL)"; - sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List statusDocumentoAssinados1 = statusDocumentoAssinados; - StatusDocumentoAssinado statusDocumentoAssinado = new StatusDocumentoAssinado() - { - Id = (long)sqlDataReader["idnewarquivodigital"], - Documento = sqlDataReader["descricao"].ToString(), - Status = (StatusAssinatura)((int)sqlDataReader["status"]) - }; - StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado; - bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("enviado")); - StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado1; - if (flag) - { - nullable = null; - } - else - { - nullable = new DateTime?((DateTime)sqlDataReader["enviado"]); - } - statusDocumentoAssinado2.Envio = nullable; - StatusDocumentoAssinado statusDocumentoAssinado3 = statusDocumentoAssinado; - bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("usuarioid")); - StatusDocumentoAssinado statusDocumentoAssinado4 = statusDocumentoAssinado3; - if (flag1) - { - usuario1 = null; - } - else - { - List usuarios = Auxiliar.Usuarios; - Func func1 = func; - if (func1 == null) - { - Func id = (Usuario usuario) => usuario.Id == (long)sqlDataReader["usuarioid"]; - Func func2 = id; - func = id; - func1 = func2; - } - usuario1 = usuarios.FirstOrDefault(func1); - } - statusDocumentoAssinado4.Usuario = usuario1; - statusDocumentoAssinados1.Add(statusDocumentoAssinado); - statusDocumentoAssinados1 = null; - statusDocumentoAssinado1 = null; - statusDocumentoAssinado3 = null; - statusDocumentoAssinado = null; - } - } - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List statusDocumentoAssinados2 = statusDocumentoAssinados; - statusDocumentoAssinados = null; - return statusDocumentoAssinados2; - } - - private async Task> BuscaVendedoresPorIdParcela(long idParcela, long idEmpresa = 0L, long idSubTipo = 0L) - { - object connection; - string str; - string str1; - List vendedorParcelas = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - str = (idSubTipo > (long)0 ? " INNER JOIN parcela p ON p.idparcela = vp.idparcela " : string.Empty); - string str2 = str; - str1 = (idSubTipo > (long)0 ? " AND p.idsubtipo = @subtipo " : string.Empty); - string str3 = string.Concat("SELECT DISTINCT vp.idvendedor,v.nome nomevendedor,vp.vrep,vp.vlrrep,vp.dataprepagto,vp.datapgt,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN vendedor v ON v.idvendedor = vp.idvendedor ", str2, " WHERE vp.idparcela = @parcela ", str1); - sqlCommand.CommandTimeout = 1000; - sqlCommand.CommandText = str3; - sqlCommand.Parameters.Add("@parcela", SqlDbType.BigInt).Value = idParcela; - sqlCommand.Parameters.Add("@subtipo", SqlDbType.BigInt).Value = idSubTipo; - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - List vendedorParcelas1 = vendedorParcelas; - VendedorParcela vendedorParcela = new VendedorParcela(); - TipoVendedor tipoVendedor = new TipoVendedor() - { - Id = sqlDataReader.GetFieldValue("idtipovendedor", true, true) - }; - vendedorParcela.TipoVendedor = tipoVendedor; - Vendedor vendedor = new Vendedor() - { - Id = sqlDataReader.GetFieldValue("idvendedor", true, true), - Nome = sqlDataReader.GetFieldValue("nomevendedor", true, true) - }; - vendedorParcela.Vendedor = vendedor; - vendedorParcela.PorcentagemRepasse = sqlDataReader.GetFieldValue("vrep", true, true); - vendedorParcela.ValorRepasse = sqlDataReader.GetFieldValue("vlrrep", true, true); - vendedorParcela.DataPagamento = sqlDataReader.GetFieldValue("datapgt", true, true); - vendedorParcela.DataPrePagamento = sqlDataReader.GetFieldValue("dataprepagto", true, true); - vendedorParcelas1.Add(vendedorParcela); - } - if (idEmpresa > (long)0) - { - List vendedorParcelas2 = vendedorParcelas; - if (!vendedorParcelas2.Any((VendedorParcela v) => v.TipoVendedor.Id == (long)1)) - { - List vendedorParcelas3 = vendedorParcelas; - VendedorParcela vendedorParcela1 = new VendedorParcela() - { - TipoVendedor = new TipoVendedor() - { - Id = (long)1 - }, - Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor v) => { - if (v.IdEmpresa != idEmpresa) - { - return false; - } - return v.Corretora; - }), - PorcentagemRepasse = new decimal?(new decimal()) - }; - vendedorParcelas3.Add(vendedorParcela1); - } - } - } - sqlDataReader = null; - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List vendedorParcelas4 = vendedorParcelas; - List list = ( - from v in vendedorParcelas4 - orderby v.TipoVendedor.Id - select v).ToList(); - vendedorParcelas = null; - return list; - } - - private List CriaCondicaoDocumento(Filtros filtro, string referencia) - { - bool count; - bool flag; - bool count1; - bool flag1; - bool count2; - bool flag2; - bool count3; - bool flag3; - List condicaos = new List() - { - new Condicao() - { - Campo = referencia, - Valores = filtro.Inicio.CriarValor(), - Operador = Operador.MaiorEIgual - }, - new Condicao() - { - Campo = referencia, - Valores = filtro.Fim.CriarValor(), - Operador = Operador.MenorEIgual - } - }; - List seguradoras = filtro.Seguradoras; - if (seguradoras != null) - { - count = seguradoras.Count > 0; - } - else - { - count = false; - } - if (count) - { - condicaos.Add(new Condicao() - { - Campo = "c.idciaseg", - Valores = filtro.Seguradoras.CriarValor(), - Grupo = 5 - }); - } - List ramos = filtro.Ramos; - if (ramos != null) - { - flag = ramos.Count > 0; - } - else - { - flag = false; - } - if (flag) - { - condicaos.Add(new Condicao() - { - Campo = "c.idramo", - Valores = filtro.Ramos.CriarValor(), - Grupo = 5 - }); - } - List status = filtro.Status; - if (status != null) - { - count1 = status.Count > 0; - } - else - { - count1 = false; - } - if (count1) - { - condicaos.Add(new Condicao() - { - Campo = "d.situacao", - Valores = filtro.Status.CriarValor(), - Grupo = 5 - }); - } - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - flag1 = tipoVendedor.Count > 0; - } - else - { - flag1 = false; - } - if (flag1) - { - condicaos.Add(new Condicao() - { - Campo = "vp.idtipovendedor", - Valores = filtro.TipoVendedor.CriarValor(), - Grupo = 5 - }); - } - List vendedores = filtro.Vendedores; - if (vendedores != null) - { - count2 = vendedores.Count > 0; - } - else - { - count2 = false; - } - if (count2) - { - condicaos.Add(new Condicao() - { - Campo = "vp.idvendedor", - Valores = filtro.Vendedores.CriarValor(), - Grupo = 5, - Operacao = Operacao.Or - }); - } - List estipulantes = filtro.Estipulantes; - if (estipulantes != null) - { - flag2 = estipulantes.Count > 0; - } - else - { - flag2 = false; - } - if (flag2) - { - condicaos.Add(new Condicao() - { - Campo = "d.idestipulante", - Valores = filtro.Estipulantes.CriarValor(), - Grupo = 5 - }); - } - List produtos = filtro.Produtos; - if (produtos != null) - { - count3 = produtos.Count > 0; - } - else - { - count3 = false; - } - if (count3) - { - condicaos.Add(new Condicao() - { - Campo = "c.idproduto", - Valores = filtro.Produtos.CriarValor(), - Grupo = 5 - }); - } - List negocio = filtro.Negocio; - if (negocio != null) - { - flag3 = negocio.Count > 0; - } - else - { - flag3 = false; - } - if (flag3) - { - condicaos.Add(new Condicao() - { - Campo = "d.NegocioCorretora", - Valores = filtro.Negocio.CriarValor(), - Operacao = Operacao.Or, - Grupo = 6 - }); - condicaos.Add(new Condicao() - { - Campo = "d.NegocioCorretora", - Valores = null, - Operacao = Operacao.Or, - Grupo = 6 - }); - } - if (filtro.IdEmpresa > (long)0) - { - condicaos.Add(new Condicao() - { - Campo = "c.idempresa", - Valores = filtro.IdEmpresa.CriarValor(), - Grupo = 5 - }); - } - return condicaos; - } - - private List CriaCondicaoFaturaPendente(Filtros filtro, string referencia) - { - return new List() - { - new Condicao() - { - Campo = referencia, - Valores = filtro.Inicio.CriarValor(), - Operador = Operador.MenorEIgual - }, - new Condicao() - { - Campo = referencia, - Valores = filtro.Fim.CriarValor(), - Operador = Operador.MaiorEIgual - } - }; - } - - private List CriaCondicaoFaturaPendenteVigencia(Filtros filtro, string referencia, string referencia2) - { - bool count; - bool flag; - bool count1; - bool flag1; - bool count2; - bool flag2; - bool count3; - bool flag3; - List condicaos = new List() - { - new Condicao() - { - Campo = referencia, - Valores = filtro.Fim.CriarValor(), - Operador = Operador.MenorEIgual - }, - new Condicao() - { - Campo = referencia2, - Valores = filtro.Inicio.CriarValor(), - Grupo = 1, - Operador = Operador.MaiorEIgual, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = referencia2, - Valores = null, - Grupo = 1 - } - }; - List seguradoras = filtro.Seguradoras; - if (seguradoras != null) - { - count = seguradoras.Count > 0; - } - else - { - count = false; - } - if (count) - { - condicaos.Add(new Condicao() - { - Campo = "c.idciaseg", - Valores = filtro.Seguradoras.CriarValor(), - Grupo = 5 - }); - } - List ramos = filtro.Ramos; - if (ramos != null) - { - flag = ramos.Count > 0; - } - else - { - flag = false; - } - if (flag) - { - condicaos.Add(new Condicao() - { - Campo = "c.idramo", - Valores = filtro.Ramos.CriarValor(), - Grupo = 5 - }); - } - List status = filtro.Status; - if (status != null) - { - count1 = status.Count > 0; - } - else - { - count1 = false; - } - if (count1) - { - condicaos.Add(new Condicao() - { - Campo = "d.situacao", - Valores = filtro.Status.CriarValor(), - Grupo = 5 - }); - } - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - flag1 = tipoVendedor.Count > 0; - } - else - { - flag1 = false; - } - if (flag1) - { - condicaos.Add(new Condicao() - { - Campo = "vp.idtipovendedor", - Valores = filtro.TipoVendedor.CriarValor(), - Grupo = 5 - }); - } - List vendedores = filtro.Vendedores; - if (vendedores != null) - { - count2 = vendedores.Count > 0; - } - else - { - count2 = false; - } - if (count2) - { - condicaos.Add(new Condicao() - { - Campo = "vp.idvendedor", - Valores = filtro.Vendedores.CriarValor(), - Grupo = 5, - Operacao = Operacao.Or - }); - } - List estipulantes = filtro.Estipulantes; - if (estipulantes != null) - { - flag2 = estipulantes.Count > 0; - } - else - { - flag2 = false; - } - if (flag2) - { - condicaos.Add(new Condicao() - { - Campo = "d.idestipulante", - Valores = filtro.Estipulantes.CriarValor(), - Grupo = 5 - }); - } - List produtos = filtro.Produtos; - if (produtos != null) - { - count3 = produtos.Count > 0; - } - else - { - count3 = false; - } - if (count3) - { - condicaos.Add(new Condicao() - { - Campo = "c.idproduto", - Valores = filtro.Produtos.CriarValor(), - Grupo = 5 - }); - } - List negocio = filtro.Negocio; - if (negocio != null) - { - flag3 = negocio.Count > 0; - } - else - { - flag3 = false; - } - if (flag3) - { - condicaos.Add(new Condicao() - { - Campo = "d.NegocioCorretora", - Valores = filtro.Negocio.CriarValor(), - Operacao = Operacao.Or, - Grupo = 5 - }); - condicaos.Add(new Condicao() - { - Campo = "d.NegocioCorretora", - Valores = null, - Operacao = Operacao.Or, - Grupo = 5 - }); - } - if (filtro.IdEmpresa > (long)0) - { - condicaos.Add(new Condicao() - { - Campo = "c.idempresa", - Valores = filtro.IdEmpresa.CriarValor(), - Grupo = 5 - }); - } - return condicaos; - } - - private List CriarCondicaoFatura(Filtros filtro, string referencia) - { - bool count; - List condicaos = new List() - { - new Condicao() - { - Campo = "d.Excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.Excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }, - new Condicao() - { - Campo = "d.tiporecebimento", - Valores = 2.CriarValor() - } - }; - Condicao condicao = new Condicao() - { - Campo = referencia - }; - DateTime inicio = filtro.Inicio; - condicao.Valores = inicio.ToString("yyyy-MM-dd").CriarValor(); - condicao.Operador = Operador.MaiorEIgual; - condicaos.Add(condicao); - Condicao condicao1 = new Condicao() - { - Campo = referencia - }; - inicio = filtro.Fim; - condicao1.Valores = inicio.ToString("yyyy-MM-dd").CriarValor(); - condicao1.Operador = Operador.MenorEIgual; - condicaos.Add(condicao1); - condicaos.Add(new Condicao() - { - Campo = "p.valorr", - Valores = 0.CriarValor() - }); - condicaos.Add(new Condicao() - { - Campo = "p.datarec", - Valores = null - }); - List condicaos1 = condicaos; - if (filtro.Status.Count > 0) - { - condicaos1.Add(new Condicao() - { - Campo = "situacao", - Valores = filtro.Status.CriarValor() - }); - } - if (filtro.Negocio.Count > 0) - { - condicaos1.Add(new Condicao() - { - Campo = "negociocorretora", - Valores = filtro.Negocio.CriarValor() - }); - } - if (filtro.Seguradoras.Count > 0) - { - condicaos1.Add(new Condicao() - { - Campo = "c.idciaseg", - Valores = filtro.Seguradoras.CriarValor() - }); - } - if (filtro.Ramos.Count > 0) - { - condicaos1.Add(new Condicao() - { - Campo = "c.idramo", - Valores = filtro.Ramos.CriarValor() - }); - } - if (filtro.Produtos.Count > 0) - { - condicaos1.Add(new Condicao() - { - Campo = "c.idproduto", - Valores = filtro.Produtos.CriarValor() - }); - } - if (filtro.Vendedores.Count > 0) - { - condicaos1.Add(new Condicao() - { - Campo = "vp.idvendedor", - Valores = filtro.Vendedores.CriarValor(), - Grupo = 2, - Operacao = Operacao.Or - }); - condicaos1.Add(new Condicao() - { - Campo = "vp.idvendedor", - Valores = null, - Operacao = Operacao.Or, - Grupo = 2 - }); - } - if (filtro.Estipulantes.Count > 0) - { - condicaos1.Add(new Condicao() - { - Campo = "d.idestipulante", - Valores = filtro.Estipulantes.CriarValor() - }); - } - if (filtro.IdEmpresa > (long)0) - { - condicaos1.Add(new Condicao() - { - Campo = "c.idempresa", - Valores = filtro.IdEmpresa.CriarValor() - }); - } - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - count = tipoVendedor.Count > 0; - } - else - { - count = false; - } - if (count) - { - condicaos1.Add(new Condicao() - { - Campo = "vp.idtipovendedor", - Valores = filtro.TipoVendedor.CriarValor() - }); - } - return condicaos1; - } - - public void Delete(long id) - { - List list = ( - from x in this._unitOfWork.Query() - where x.Parcela.Id == id - select x).ToList(); - if (list.Any()) - { - this._unitOfWork.Repository().DeleteRange(list); - } - ParcelaDb parcelaDb = base.FindEntityById(id); - if (parcelaDb == null) - { - return; - } - base.Delete(parcelaDb); - } - - public void DeleteRange(long id) - { - List list = ( - from x in this._unitOfWork.Query() - where x.Parcela.Documento.Id == id - select x).ToList(); - if (list.Any()) - { - this._unitOfWork.Repository().DeleteRange(list); - } - List parcelaDbs = ( - from i in base.All() - where i.Documento.Id == id && (int)i.SubTipo == 1 - select i).ToList(); - base.DeleteRange(parcelaDbs); - } - - public bool ExcluirVinculoParcelaPendenteDocExcluido(Documento doc) - { - object connection; - try - { - List parcelas = this.FindByDocumento(doc); - if (parcelas != null && parcelas.Count > 0) - { - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - parcelas.ForEach((Parcela p) => { - using (SqlCommand id = sqlConnection.CreateCommand()) - { - id.CommandText = "UPDATE ParcelaPendente SET IdParcela = NULL WHERE IdParcela = @parcela"; - id.Parameters.Add("@parcela", SqlDbType.BigInt).Value = p.Id; - id.ExecuteNonQuery(); - } - }); - } - return true; - } - } - catch - { - } - return false; - } - - private async Task ExisteTabelasAssinatura() - { - bool flag; - object connection; - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT OBJECT_ID('ArquivoParaAssinatura') AS existe"; - flag = await sqlCommand.ExecuteScalarAsync() != DBNull.Value; - } - } - } - return flag; - } - - public async Task> FaturaPendente(Filtros filtro) - { - List documentos; - NegocioCorretora fieldValue; - object connection; - bool count; - List itensAtivo; - DateTime dateTime; - DateTime dateTime1; - DateTime dateTime2; - DateTime dateTime3; - object produto; - string str; - Vendedor vendedor; - Estipulante estipulante; - object statu; - NegocioCorretora negocioCorretora; - Func func = null; - Func func1 = null; - string str1 = "f.vigenciai"; - string str2 = "d.vigencia1"; - string str3 = "d.vigencia2"; - if (filtro.Referencia == "VENCIMENTO") - { - str1 = "p.vencto"; - } - List condicaos = this.CriaCondicaoFaturaPendenteVigencia(filtro, str2, str3); - List condicaos1 = this.CriaCondicaoFaturaPendente(filtro, str1); - List condicaos2 = new List(); - Condicao condicao = new Condicao() - { - Campo = "d.tiporecebimento", - Valores = 2.CriarValor(), - Grupo = 2 - }; - condicaos2.Add(condicao); - List condicaos3 = condicaos2; - List condicaos4 = new List(); - Condicao condicao1 = new Condicao() - { - Campo = "d.Excluido", - Valores = null, - Grupo = 4, - Operacao = Operacao.Or - }; - condicaos4.Add(condicao1); - Condicao condicao2 = new Condicao() - { - Campo = "d.Excluido", - Valores = "0".CriarValor(), - Grupo = 4 - }; - condicaos4.Add(condicao2); - List condicaos5 = condicaos4; - List condicaos6 = new List(); - Condicao condicao3 = new Condicao() - { - Campo = "d.situacao", - Valores = 1.CriarValor(), - Grupo = 3, - Operacao = Operacao.Or - }; - condicaos6.Add(condicao3); - Condicao condicao4 = new Condicao() - { - Campo = "d.situacao", - Valores = 2.CriarValor(), - Grupo = 3 - }; - condicaos6.Add(condicao4); - List condicaos7 = condicaos6; - condicaos.AddRange(condicaos3); - condicaos.AddRange(condicaos7); - condicaos.AddRange(condicaos5); - SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); - SqlQueryCondition sqlQueryCondition1 = condicaos1.CreateParameters(0); - List documentos1 = new List(); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1000; - string str4 = "WITH tabfatura AS ( SELECT MAX ( f.vigenciaf ) AS vigenciaf, MAX ( f.vigenciai ) AS vigenciai, MAX ( p.idparcela ) AS idparcela, MAX ( p.vencto ) AS Vencimento, MAX (f.idfatura) as idfatura, d.iddocumento FROM documento d LEFT JOIN parcela p ON p.iddocumento = d.iddocumento LEFT JOIN fatura f ON p.idparcela = f.idparcela GROUP BY d.iddocumento ) SELECT DISTINCT d.iddocumento, d.idcontrole, IIF ( d.vigencia2 IS NULL, GETDATE(), d.vigencia2 ) AS vigenciafinalfatura, tabfatura.idparcela,tabfatura.vigenciai AS vigenciaIultimafatura, tabfatura.vigenciaf AS vigenciafultimafatura, f.numfatura,tabfatura.Vencimento, cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome AS cliente, d.contrato AS apolice, d.emissao, d.remessa, d.aditamento AS endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 AS vigenciainicial, d.vigencia2 AS vigenciafinal, c.idramo, r.nome AS nomeramo, c.idciaseg AS idseguradora, cs.nome AS nomeseguradora, c.idproduto, pr.nome AS nomeproduto, CAST ( d.tipo AS INTEGER ) AS tipo, vp.idvendedor, d.idestipulante, d.datacontrole, d.idstatus, st.nome AS nomestatus, d.pasta, cl.pasta AS pastacliente FROM documento d INNER JOIN controle c ON c.idcontrole = d.idcontrole INNER JOIN ciaseg cs ON cs.idciaseg = c.idciaseg INNER JOIN ramo r ON r.idramo = c.idramo INNER JOIN cliente cl ON cl.idcliente = c.idcliente LEFT JOIN produto pr ON pr.idproduto = c.idproduto LEFT JOIN status st ON st.idstatus = d.idstatus LEFT JOIN parcela p ON p.iddocumento = d.iddocumento \tLEFT JOIN vendedorparcela vp ON vp.idparcela = p.idparcela LEFT JOIN tabfatura ON tabfatura.iddocumento = d.iddocumento LEFT JOIN fatura f on tabfatura.idfatura = f.idfatura WHERE"; - string str5 = " AND NOT EXISTS ( SELECT 1 FROM parcela p INNER JOIN fatura f ON f.idparcela = p.idparcela WHERE p.iddocumento = d.iddocumento AND "; - SqlCommand sqlCommand1 = sqlCommand; - string[] strArrays = new string[] { str4, " ", sqlQueryCondition.Condicao, " ", str5, " ", sqlQueryCondition1.Condicao, " ) ORDER BY d.IDDOCUMENTO" }; - sqlCommand1.CommandText = string.Concat(strArrays); - foreach (SqlParameter parametro in sqlQueryCondition.Parametros) - { - if (sqlCommand.Parameters.Contains(parametro.ParameterName)) - { - continue; - } - sqlCommand.Parameters.Add(parametro); - } - foreach (SqlParameter sqlParameter in sqlQueryCondition1.Parametros) - { - if (sqlCommand.Parameters.Contains(sqlParameter.ParameterName)) - { - continue; - } - sqlCommand.Parameters.Add(sqlParameter); - } - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - TipoSeguro tipoSeguro = sqlDataReader.GetFieldValue("situacao", true, true); - if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "negociocorretora")) - { - fieldValue = sqlDataReader.GetFieldValue("negociocorretora", true, true); - } - else - { - bool flag = tipoSeguro == TipoSeguro.Renovacao; - if (flag) - { - flag = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "idnegocio"); - } - negocioCorretora = (!flag || !(sqlDataReader.GetFieldValue("idnegocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); - fieldValue = negocioCorretora; - } - NegocioCorretora negocioCorretora1 = fieldValue; - List negocio = filtro.Negocio; - if (negocio != null) - { - count = negocio.Count > 0; - } - else - { - count = false; - } - if (!count || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora1)) - { - long num = sqlDataReader.GetFieldValue("IdControle", true, true); - long fieldValue1 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); - Documento documento = documentos1.Find((Documento p) => p.Controle.Id == num); - if (documento != null) - { - itensAtivo = documento.ItensAtivo; - } - else - { - itensAtivo = null; - } - List items = itensAtivo; - if (items == null) - { - items = await this.BuscaItemsPorIdControle(num); - } - List items1 = items; - DateTime? nullable = sqlDataReader.GetFieldValue("vigenciafultimafatura", true, true); - dateTime = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - DateTime dateTime4 = dateTime; - nullable = sqlDataReader.GetFieldValue("vigenciaIultimafatura", true, true); - dateTime1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - DateTime dateTime5 = dateTime1; - nullable = sqlDataReader.GetFieldValue("vigenciainicial", true, true); - dateTime2 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - DateTime dateTime6 = dateTime2; - nullable = sqlDataReader.GetFieldValue("vigenciafinalfatura", true, true); - dateTime3 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - if (dateTime4 < dateTime3) - { - Documento observableCollection = new Documento() - { - Id = sqlDataReader.GetFieldValue("iddocumento", true, true) - }; - Controle controle = new Controle() - { - IdEmpresa = fieldValue1 - }; - Cliente cliente = new Cliente() - { - Id = sqlDataReader.GetFieldValue("idcliente", true, true), - Nome = sqlDataReader.GetFieldValue("cliente", true, true), - IdEmpresa = fieldValue1, - Pasta = sqlDataReader.GetFieldValue("pastaCliente", true, true) - }; - bool? nullable1 = sqlDataReader.GetFieldValue("MalaDireta", true, true); - cliente.MalaDireta = new bool?(nullable1.GetValueOrDefault(true)); - controle.Cliente = cliente; - Seguradora seguradora = new Seguradora() - { - Id = sqlDataReader.GetFieldValue("idseguradora", true, true), - Nome = sqlDataReader.GetFieldValue("nomeseguradora", true, true) - }; - controle.Seguradora = seguradora; - Ramo ramo = new Ramo() - { - Id = sqlDataReader.GetFieldValue("idramo", true, true), - Nome = sqlDataReader.GetFieldValue("nomeramo", true, true) - }; - controle.Ramo = ramo; - if (sqlDataReader.FieldIsNull("idproduto")) - { - produto = null; - } - else - { - produto = new Produto(); - ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("idproduto", true, true); - ((Produto)produto).Nome = sqlDataReader.GetFieldValue("nomeproduto", true, true); - } - controle.Produto = (Produto)produto; - observableCollection.Controle = controle; - observableCollection.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura); - observableCollection.Apolice = sqlDataReader.GetFieldValue("apolice", true, true); - observableCollection.Pasta = sqlDataReader.GetFieldValue("Pasta", true, true); - str = (sqlDataReader.GetFieldValue("tipo", true, true) == 0 ? "" : string.Concat("E ", sqlDataReader.GetFieldValue("endosso", true, true))); - observableCollection.Endosso = str; - observableCollection.Vigencia2 = sqlDataReader.GetFieldValue("vigenciafinal", true, true); - observableCollection.Vigencia1 = dateTime6; - observableCollection.Emissao = sqlDataReader.GetFieldValue("emissao", true, true); - observableCollection.Remessa = sqlDataReader.GetFieldValue("remessa", true, true); - if (sqlDataReader.GetFieldValue("idvendedor", true, true) != null) - { - List vendedores = Auxiliar.Vendedores; - Func func2 = func; - if (func2 == null) - { - Func id = (Vendedor p) => p.Id == sqlDataReader.GetFieldValue("idvendedor", true, true); - Func func3 = id; - func = id; - func2 = func3; - } - vendedor = vendedores.FirstOrDefault(func2); - } - else - { - vendedor = null; - } - observableCollection.VendedorPrincipal = vendedor; - if (sqlDataReader.GetFieldValue("idestipulante", true, true) != null) - { - List estipulantes = Auxiliar.Estipulantes; - Func func4 = func1; - if (func4 == null) - { - Func id1 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue("idestipulante", true, true); - Func func5 = id1; - func1 = id1; - func4 = func5; - } - estipulante = estipulantes.FirstOrDefault(func4); - } - else - { - estipulante = null; - } - observableCollection.Estipulante1 = estipulante; - observableCollection.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); - observableCollection.Situacao = tipoSeguro; - List parcelas = new List(); - Parcela parcela = new Parcela() - { - Id = sqlDataReader.GetFieldValue("idparcela", true, true), - VigenciaFinal = new DateTime?(dateTime4), - Fatura = sqlDataReader.GetFieldValue("numfatura", true, true), - Vencimento = sqlDataReader.GetFieldValue("Vencimento", true, true), - VigenciaIncial = new DateTime?(dateTime5) - }; - parcelas.Add(parcela); - observableCollection.Parcelas = new ObservableCollection(parcelas); - observableCollection.Tipo = sqlDataReader.GetFieldValue("tipo", true, true); - observableCollection.DataControle = sqlDataReader.GetFieldValue("datacontrole", true, true); - if (sqlDataReader.FieldIsNull("idstatus")) - { - statu = null; - } - else - { - statu = new Status(); - ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("idstatus", true, true); - ((Status)statu).Nome = sqlDataReader.GetFieldValue("nomestatus", true, true); - } - observableCollection.Status = (Status)statu; - observableCollection.ItensAtivo = items1; - documentos1.Add(observableCollection); - } - } - } - } - } - sqlCommand = null; - } - sqlConnection = null; - documentos = documentos1; - } - documentos1 = null; - return documentos; - } - - public List FindByDocumentId(List ids) - { - List parcelas; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str = string.Concat(" p.iddocumento IN (", string.Join(",", ids), ")"); - sqlCommand.CommandText = string.Concat("SELECT p.iddocumento, ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss,p.obs, p.vlrcomiss, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, f.* FROM parcela p OUTER APPLY (SELECT numfatura, vigenciai, vigenciaf, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE ", str); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - goto Label0; - } - else - { - parcelas = new List(); - } - } - } - return parcelas; - Label0: - List list = dataTable.AsEnumerable().ToList(); - return list.Select((DataRow x) => { - Parcela parcela = new Parcela() - { - Id = x.Field("idparcela"), - IdEmpresa = x.Field("idempresa"), - Documento = new Documento() - { - Id = x.Field("iddocumento") - }, - NumeroParcela = int.Parse(x.Field("parcela").ToString()) - }; - DateTime? nullable = x.Field("vencto"); - parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.Today); - parcela.DataRecebimento = x.Field("datarec"); - parcela.DataQuitacao = x.Field("dataquit"); - parcela.DataControle = x.Field("datacontrole"); - parcela.DataCredito = x.Field("datacred"); - decimal? nullable1 = x.Field("valor"); - parcela.Valor = nullable1.GetValueOrDefault(); - nullable1 = x.Field("valorr"); - parcela.ValorRealizado = nullable1.GetValueOrDefault(); - nullable1 = x.Field("comiss"); - parcela.Comissao = nullable1.GetValueOrDefault(); - nullable1 = x.Field("vlrcomiss"); - parcela.ValorComissao = nullable1.GetValueOrDefault(); - nullable1 = x.Field("vlrcomdesc"); - parcela.ValorComDesconto = nullable1.GetValueOrDefault(); - parcela.Observacao = x.Field("obs"); - parcela.SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field("idsubtipo").ToString()); - parcela.TipoPagamento = (x.Field("idtipopagto") == null ? TipoPagamento.Nenhum : (TipoPagamento)Enum.Parse(typeof(TipoPagamento), x.Field("idtipopagto").ToString())); - nullable1 = x.Field("valorlf"); - parcela.ValorLiquidoFatura = nullable1.GetValueOrDefault(); - parcela.Fatura = x.Field("numfatura"); - parcela.VigenciaIncial = x.Field("vigenciai"); - parcela.VigenciaFinal = x.Field("vigenciaf"); - parcela.Emissao = x.Field("emissao"); - parcela.Extrato = x.Field("extrato"); - parcela.StatusPagamento = new StatusPagamento?((x.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field("StatusPagamento").ToString()))); - parcela.IdParcelaPendente = x.Field("IdParcelaPendente").GetValueOrDefault(); - nullable1 = x.Field("irr"); - parcela.Irr = nullable1.GetValueOrDefault(); - nullable1 = x.Field("iss"); - parcela.Iss = nullable1.GetValueOrDefault(); - nullable1 = x.Field("desconto"); - parcela.Desconto = nullable1.GetValueOrDefault(); - nullable1 = x.Field("outros"); - parcela.Outros = nullable1.GetValueOrDefault(); - return parcela; - }).ToList(); - } - - public List FindByDocumentId(long id) - { - List parcelas; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - sqlCommand.CommandText = string.Concat("SELECT ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss, p.vlrcomiss,p.obs, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, p.valorp, p.obs, p.vlrextrato, p.cri_data, p.usuariocriacao, f.* ", string.Format("FROM parcela p OUTER APPLY (SELECT idfatura, numfatura as fatura, vigenciai as vigenciainicial, vigenciaf as vigenciafinal, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE p.iddocumento = {0}", id)); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - Documento documento = (new DocumentoRepository(this._unitOfWork)).FindById(id, false, false); - return dataTable.MapParcela(documento); - } - else - { - parcelas = new List(); - } - } - } - return parcelas; - } - - public List FindByDocumentIds(string ids, List documentos) - { - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT iddocumento, idempresa, idparcela, parcela, vencto, valor, idtipopagto, StatusPagamento, IdParcelaPendente FROM parcela WHERE iddocumento IN (", ids, ");"); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - documentos.ForEach((Documento x) => { - List parcelas = new List(); - dataTable.AsEnumerable().Where((DataRow y) => y.Field("iddocumento") == x.Id).ToList().ForEach((DataRow y) => { - Parcela parcela = new Parcela() - { - Id = y.Field("idparcela"), - IdEmpresa = (!y.Field("idempresa").HasValue ? (long)0 : y.Field("idempresa")), - NumeroParcela = int.Parse(y.Field("parcela").ToString()), - Vencimento = (y.Field("vencto") == null ? new DateTime() : y.Field("vencto")), - Valor = y.Field("valor"), - TipoPagamento = (y.Field("idtipopagto") == null ? TipoPagamento.Nenhum : (int)y.Field("idtipopagto")), - StatusPagamento = new StatusPagamento?((y.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), y.Field("StatusPagamento").ToString()))), - IdParcelaPendente = y.Field("IdParcelaPendente").GetValueOrDefault() - }; - parcelas.Add(parcela); - }); - x.Parcelas = new ObservableCollection(parcelas); - }); - return documentos; - } - - public List FindByDocumento(Documento documento) - { - List parcelas; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - sqlCommand.CommandText = string.Concat("SELECT ISNULL(p.idempresa, 1) AS idempresa, p.idparcela, p.parcela, p.vencto, p.datarec, p.dataquit, p.datacontrole, p.datacred, p.valor, p.valorr, p.comiss, p.vlrcomiss,p.obs, p.vlrcomdesc, p.idsubtipo, p.idtipopagto, p.valorlf, p.extrato, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, p.irr, p.iss, p.outros, p.desconto, p.valorp, p.obs, p.vlrextrato, p.cri_data, p.usuariocriacao, f.* ", string.Format("FROM parcela p OUTER APPLY (SELECT idfatura, numfatura as fatura, vigenciai as vigenciainicial, vigenciaf as vigenciafinal, emissao FROM fatura WHERE idparcela = p.idparcela) f WHERE p.iddocumento = {0}", documento.Id)); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - return dataTable.MapParcela(documento); - } - else - { - parcelas = new List(); - } - } - } - return parcelas; - } - - public Parcela FindById(long id) - { - DateTime? nullable; - string fatura; - DateTime? vigenciaInicial; - DateTime? vigenciaFinal; - DateTime? emissao; - ParcelaDb parcelaDb = base.FindEntityById(id); - if (parcelaDb == null) - { - return null; - } - if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela || !string.IsNullOrEmpty(parcelaDb.Fatura)) - { - return ApplicationMapper.Mapper.Map(parcelaDb); - } - FaturaDb faturaDb = this._unitOfWork.Query().FirstOrDefault((FaturaDb x) => x.Parcela.Id == id); - ParcelaDb parcelaDb1 = parcelaDb; - if (faturaDb != null) - { - fatura = faturaDb.Fatura; - } - else - { - fatura = null; - } - parcelaDb1.Fatura = fatura; - ParcelaDb parcelaDb2 = parcelaDb; - if (faturaDb != null) - { - vigenciaInicial = faturaDb.VigenciaInicial; - } - else - { - nullable = null; - vigenciaInicial = nullable; - } - parcelaDb2.VigenciaIncial = vigenciaInicial; - ParcelaDb parcelaDb3 = parcelaDb; - if (faturaDb != null) - { - vigenciaFinal = faturaDb.VigenciaFinal; - } - else - { - nullable = null; - vigenciaFinal = nullable; - } - parcelaDb3.VigenciaFinal = vigenciaFinal; - ParcelaDb parcelaDb4 = parcelaDb; - if (faturaDb != null) - { - emissao = faturaDb.Emissao; - } - else - { - nullable = null; - emissao = nullable; - } - parcelaDb4.Emissao = emissao; - return ApplicationMapper.Mapper.Map(parcelaDb); - } - - public List FindByPagamento(Filtros filtro, bool reciboPagamento, bool segundaViaReciboPagamento, bool datacontrole) - { - List vendedorParcelas; - string str; - object connection; - string str1 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", - from v in filtro.Status - select v), ")")); - string str2 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND (NegocioCorretora IN (", string.Join(",", - from v in filtro.Negocio - select v), ") OR NegocioCorretora IS NULL)")); - string str3 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", - from v in filtro.Seguradoras - select v), ")")); - string str4 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", - from v in filtro.Ramos - select v), ")")); - string str5 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", - from v in filtro.Produtos - select v), ")")); - string str6 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", - from v in filtro.Vendedores - select v), ")")); - string str7 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "" : string.Concat(" AND vp.idtipovendedor IN (", string.Join(",", - from v in filtro.TipoVendedor - select v), ")")); - string str8 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", - from v in filtro.Estipulantes - select v), ")")); - string str9 = (!reciboPagamento || segundaViaReciboPagamento ? "" : "AND vp.datapgt IS NULL "); - if (segundaViaReciboPagamento) - { - str = "CAST(vp.datapgt AS DATE)"; - } - else - { - str = (datacontrole ? "CAST(d.datacontrole AS DATE)" : "CAST(vp.dataprepagto AS DATE)"); - } - string str10 = str; - string str11 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); - string str12 = (filtro.ParcelasEspeciais.Any((FiltroTipoParcela x) => x.Selecionado) ? string.Concat(" AND p.idsubtipo IN (", string.Join(",", - from x in filtro.ParcelasEspeciais - where x.Selecionado - select x into v - select (int)v.Tipo), ")") : ""); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str13 = "SELECT DISTINCT cl.idempresa, vp.idvendedorparcela, cl.idcliente, cl.MalaDireta, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, p.idparcela, d.iddocumento, d.N_PARC as numeroparcelas, d.datacontrole, cl.nome as cliente, d.contrato as apolice, d.aditamento as endosso, d.situacao, d.idnegocio, d.vigencia1 as vigenciainicial, d.proposta, d.vigencia2 as vigenciafinal, f.vigenciaf as vigenciaf, ISNULL(d.com01, 0) as comissao, ISNULL(p.comiss, 0.00) as comiss, p.parcela, d.tiporecebimento, ISNULL(d.pr_liq, 0.00) as liquido, ISNULL(d.pr_total, 0.00) as total, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorlf, 0.00) as liquidofatura, f.vigenciai, f.numfatura as fatura, vp.dataprepagto as recebimento, ISNULL(vp.vlrrep,0) as repasse, ISNULL(vp.vrep, 0) as percentual, p.idsubtipo, vp.datapgt, vp.idrepasse as idrepasse, rep.tipo as tiporepasse, d.cri_data, d.emissao, p.datarec, p.vlrcomdesc, d.NegocioCorretora, CASE WHEN ((Round(ISNULL( d.pr_liq, 0.00 ) * (ISNULL( d.com01, 0 ) / 100 ),2) * ( vp.vrep/ 100 )) - ROUND(vp.valortotal,2) - ROUND(cia.tolerancia,2)) > 0 THEN 'SIM' ELSE 'NÃO'END AS RecebidoPorCompleto FROM vendedorparcela vp INNER JOIN parcela p on p.idparcela = vp.idparcela INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela INNER JOIN repasse rep on rep.idrepasse = vp.idrepasse INNER JOIN ciaseg cia on cia.idciaseg = c.idciaseg WHERE (d.excluido IS NULL OR d.excluido = 0)"; - sqlCommand.CommandText = string.Format("{0} {1} AND vp.idvendedor != {2} AND {3} >= '{4:yyyy-MM-dd}' AND {5} <= '{6:yyyy-MM-dd}' {7} {8} {9} {10} {11} {12} {13} {14} {15}{16}", new object[] { str13, str11, Auxiliar.Vendedores.First((Vendedor x) => x.Corretora).Id, str10, filtro.Inicio, str10, filtro.Fim, str9, str1, str2, str3, str4, str5, str8, str6, str7, str12 }); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - Action action = (DataRow x) => x.SetField("NegocioCorretora", (!(x.Field("situacao").ToString() == "2") || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? "0" : "1")); - ( - from x in dataTable.AsEnumerable().ToList() - where x.Field("NegocioCorretora") == null - select x).ForEach(action); - if (!str2.IsNullOrEmpty()) - { - Func func = (DataRow p) => filtro.Negocio.Any((long filter) => filter.ToString() == p.Field("NegocioCorretora").ToString()); - dataTable = dataTable.AsEnumerable().Where(func).CopyToDataTable(); - } - goto Label0; - } - else - { - vendedorParcelas = new List(); - } - } - } - return vendedorParcelas; - Label0: - List list = dataTable.AsEnumerable().ToList(); - return list.Select((DataRow x) => { - decimal? nullable; - decimal valueOrDefault; - decimal num; - VendedorParcela vendedorParcela = new VendedorParcela() - { - Id = x.Field("idvendedorparcela"), - Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")), - Repasse = new Repasse() - { - Id = x.Field("idrepasse"), - Tipo = new TipoRepasse?((TipoRepasse)Enum.Parse(typeof(TipoRepasse), x.Field("tiporepasse").ToString())) - } - }; - Documento documento = new Documento() - { - Id = x.Field("iddocumento"), - Controle = new Controle() - { - IdEmpresa = x.Field("idempresa"), - Cliente = new Cliente() - { - Id = x.Field("idcliente"), - Nome = x.Field("cliente"), - IdEmpresa = x.Field("idempresa"), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) - }, - Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), - Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), - Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Produto p) => p.Id == x.Field("idproduto")) : null) - }, - Apolice = x.Field("apolice"), - Endosso = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("endosso") : string.Concat("F ", x.Field("fatura"))), - Comissao = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("comissao") : x.Field("comiss")) - }; - if (x.Field("tiporecebimento").ToString() == "1") - { - nullable = x.Field("liquido"); - valueOrDefault = nullable.GetValueOrDefault(); - } - else - { - nullable = x.Field("liquidofatura"); - valueOrDefault = nullable.GetValueOrDefault(); - } - documento.PremioLiquido = valueOrDefault; - if (x.Field("tiporecebimento").ToString() == "1") - { - nullable = x.Field("total"); - num = nullable.GetValueOrDefault(); - } - else - { - nullable = x.Field("valor"); - num = nullable.GetValueOrDefault(); - } - documento.PremioTotal = num; - documento.Vigencia1 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciainicial") : (x.Field("vigenciai") != null ? x.Field("vigenciai") : new DateTime())); - documento.Vigencia2 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciafinal") : x.Field("vigenciaf")); - documento.Proposta = x.Field("proposta"); - documento.NegocioCorretora = new NegocioCorretora?((NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("NegocioCorretora").ToString())); - documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); - documento.TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())); - documento.NumeroParcelas = x.Field("numeroparcelas"); - documento.DataCriacao = x.Field("cri_data"); - documento.DataControle = x.Field("datacontrole"); - documento.Emissao = x.Field("emissao"); - vendedorParcela.Documento = documento; - Parcela parcela = new Parcela() - { - NumeroParcela = int.Parse(x.Field("parcela").ToString()), - Id = x.Field("idparcela"), - SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field("idsubtipo").ToString()), - IdEmpresa = x.Field("idempresa"), - Valor = x.Field("valor") - }; - nullable = x.Field("vlrcomdesc"); - parcela.ValorComDesconto = nullable.GetValueOrDefault(); - parcela.DataRecebimento = x.Field("datarec"); - vendedorParcela.Parcela = parcela; - vendedorParcela.ValorRepasse = new decimal?(x.Field("repasse")); - DateTime? nullable1 = x.Field("recebimento"); - vendedorParcela.DataPrePagamento = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue)); - vendedorParcela.PorcentagemRepasse = new decimal?(x.Field("percentual")); - vendedorParcela.DataPagamento = x.Field("datapgt"); - vendedorParcela.RecebidoPorCompleto = x.Field("RecebidoPorCompleto"); - return vendedorParcela; - }).ToList(); - } - - public List FindByPendente(Filtros filtro, bool pendente, bool somenteAtivos) - { - List parcelas; - object connection; - List nums = null; - string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", - from v in filtro.Status - select v), ")")); - string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", - from v in filtro.Negocio - select v), ")")); - string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", - from v in filtro.Seguradoras - select v), ")")); - string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", - from v in filtro.Ramos - select v), ")")); - string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", - from v in filtro.Produtos - select v), ")")); - string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", - from v in filtro.Vendedores - select v), ")")); - string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 vp2.idvendedor FROM vendedorparcela vp2 WHERE (d.tiporecebimento = 2 AND vp2.IDPARCELA = p.IDPARCELA) OR (d.tiporecebimento = 1 AND vp2.iddocumento = p.iddocumento)) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join(",", - from v in filtro.TipoVendedor - select v), ")")); - string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", - from v in filtro.Estipulantes - select v), ")")); - string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); - string str9 = (somenteAtivos ? " AND i.idsubstituido IS NULL" : ""); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - DataTable dataTable2 = new DataTable(); - DataTable dataTable3 = new DataTable(); - DataTable dataTable4 = new DataTable(); - string str10 = (pendente ? "AND p.datarec IS NULL" : ""); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str11 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, f.numfatura as fatura, f.vigenciai as vigenciai, f.vigenciaf as vigenciaf, p.parcela, p.datarec as recebimento, p.dataquit as quitacao, p.datacontrole as dataparcelacontrole, p.vencto as vencimento, ISNULL(p.vlrcomdesc, 0.00) as valorcomdesconto, ISNULL(p.vlrcomiss, 0) as valorcomissao, p.iddocumento, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.proposta, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorr, 0.00) as valorr, ISNULL(p.valorlf, 0.00) as valorliquidofatura, ISNULL(d.pr_total, 0.00) as total, ISNULL(d.pr_liq, 0.00) as liquido, d.pr_adic as adicional, d.adinacomis as adinacomiss, ISNULL(d.com01,0) as comissao, ISNULL(p.comiss, 0.00) as comiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento, d.N_PARC as numeroparcelas, d.datacontrole, d.idstatus, p.idsubtipo, cl.cgccpf, d.formapagamento, d.propassinada, d.pasta, cl.pasta as pastacliente FROM parcela p INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente ", (somenteAtivos ? "INNER JOIN item i on d.iddocumento = i.iddocumento " : ""), str6, " LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0)"); - string str12 = "SELECT DISTINCT idparcela as id, idvendedor, vlrrep as valorrepasse, vrep as porcentagemrepasse, datapgt as datapagamento, dataprepagto as dataprepagamento FROM vendedorparcela vp WHERE 1=1 "; - string str13 = "SELECT iddocumento, idparcela as id, parcela, datarec as recebimento, vencto as vencimento, vlrcomdesc as valorcomdesconto, ISNULL(vlrcomiss, 0.00) as valorcomissao, ISNULL(valor, 0.00) as valor, ISNULL(comiss, 0.00) as comiss, ISNULL(StatusPagamento, 0) AS StatusPagamento, ISNULL(IdParcelaPendente, 0) AS IdParcelaPendente FROM parcela where datarec IS NOT NULL "; - string str14 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL "; - string str15 = "SELECT DISTINCT idcliente, idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE "; - sqlCommand.CommandText = string.Format("{0} {1} {2} AND p.vencto >= '{3:yyyy-MM-dd}' AND p.vencto <= '{4:yyyy-MM-dd}' {5} {6} {7} {8} {9} {10} {11} {12}", new object[] { str11, str8, str10, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5, str9 }); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - string str16 = string.Concat(" AND vp.idparcela IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat(str12, " ", str16); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - } - string str17 = string.Concat(" AND iddocumento IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("iddocumento"))), ")"); - sqlCommand.CommandText = string.Concat(str13, " ", str17); - using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) - { - sqlDataAdapter2.SelectCommand = sqlCommand; - sqlDataAdapter2.Fill(dataTable2); - } - string str18 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); - sqlCommand.CommandText = string.Concat(str14, " ", str18); - using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) - { - sqlDataAdapter3.SelectCommand = sqlCommand; - sqlDataAdapter3.Fill(dataTable3); - } - for (List i1 = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idcliente")).Distinct().ToList(); i1.Count > 0; i1 = nums) - { - List nums1 = i1.Take(1000).ToList(); - List condicaos = new List() - { - new Condicao() - { - Campo = "idcliente", - Valores = nums1.CriarValor() - } - }; - DataTable dataTable5 = sqlCommand.Select(condicaos.CreateParameters(0), str15, ""); - dataTable4.Merge(dataTable5); - nums = (nums1.Count < 1000 ? new List() : i1.Except(nums1).ToList()); - } - goto Label0; - } - else - { - parcelas = new List(); - } - } - } - return parcelas; - Label0: - return dataTable.AsEnumerable().ToList().Select((DataRow x) => { - decimal? nullable3; - decimal valueOrDefault; - decimal num; - Parcela observableCollection = new Parcela() - { - Id = x.Field("id"), - IdEmpresa = x.Field("idempresa"), - NumeroParcela = int.Parse(x.Field("parcela").ToString()) - }; - DateTime? nullable4 = x.Field("vencimento"); - observableCollection.Vencimento = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue); - observableCollection.Comissao = x.Field("comiss"); - observableCollection.DataQuitacao = x.Field("quitacao"); - observableCollection.DataControle = x.Field("dataparcelacontrole"); - observableCollection.Valor = x.Field("valor"); - observableCollection.SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field("idsubtipo").ToString()); - observableCollection.StatusPagamento = new StatusPagamento?((x.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field("StatusPagamento").ToString()))); - observableCollection.IdParcelaPendente = x.Field("IdParcelaPendente").GetValueOrDefault(); - IEnumerable list = - from v in dataTable1.AsEnumerable().ToList() - where v.Field("id") == x.Field("id") - select v; - Func u003cu003e9_2614 = ParcelaRepository.u003cu003ec.u003cu003e9__26_14; - if (u003cu003e9_2614 == null) - { - u003cu003e9_2614 = (DataRow v) => { - DateTime? nullable; - DateTime? nullable1; - DateTime? nullable2; - VendedorParcela vendedorParcela = new VendedorParcela() - { - Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == v.Field("idvendedor")), - ValorRepasse = new decimal?((v.Field("valorrepasse") == null ? decimal.Zero : v.Field("valorrepasse"))), - PorcentagemRepasse = new decimal?((v.Field("porcentagemrepasse") == null ? decimal.Zero : v.Field("porcentagemrepasse"))) - }; - if (v.Field("datapagamento") == null) - { - nullable = null; - nullable1 = nullable; - } - else - { - nullable1 = v.Field("datapagamento"); - } - vendedorParcela.DataPagamento = nullable1; - if (v.Field("dataprepagamento") == null) - { - nullable = null; - nullable2 = nullable; - } - else - { - nullable2 = v.Field("dataprepagamento"); - } - vendedorParcela.DataPrePagamento = nullable2; - return vendedorParcela; - }; - ParcelaRepository.u003cu003ec.u003cu003e9__26_14 = u003cu003e9_2614; - } - observableCollection.Vendedores = new ObservableCollection(list.Select(u003cu003e9_2614).ToList()); - Documento documento = new Documento() - { - Id = x.Field("iddocumento"), - FormaPagamento = new FormaPagamento?((x.Field("formapagamento") == null || !(x.Field("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.Field("formapagamento").ToString()))) - }; - Controle controle = new Controle() - { - Id = x.Field("idcontrole"), - IdEmpresa = x.Field("idempresa") - }; - Cliente cliente = new Cliente() - { - Id = x.Field("idcliente"), - Nome = x.Field("cliente"), - Documento = x.Field("cgccpf"), - IdEmpresa = x.Field("idempresa"), - Pasta = x.Field("pastacliente") - }; - EnumerableRowCollection dataRows = dataTable4.AsEnumerable().Where((DataRow t) => t.Field("idcliente") == x.Field("idcliente")); - Func u003cu003e9_2627 = ParcelaRepository.u003cu003ec.u003cu003e9__26_27; - if (u003cu003e9_2627 == null) - { - u003cu003e9_2627 = (DataRow t) => new ClienteTelefone() - { - Id = t.Field("idclitelefone"), - Prefixo = t.Field("ddd"), - Numero = t.Field("fone") - }; - ParcelaRepository.u003cu003ec.u003cu003e9__26_27 = u003cu003e9_2627; - } - cliente.Telefones = new ObservableCollection(dataRows.Select(u003cu003e9_2627)); - cliente.MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)); - controle.Cliente = cliente; - controle.Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null); - controle.Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null); - controle.Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Produto p) => p.Id == x.Field("idproduto")) : null); - documento.Controle = controle; - documento.Pasta = x.Field("Pasta"); - documento.NumeroParcelas = x.Field("numeroparcelas"); - documento.AdicionalComiss = x.Field("adinacomiss") == "1"; - documento.Apolice = x.Field("apolice"); - documento.Endosso = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("endosso") : string.Concat("F ", x.Field("fatura"))); - documento.Comissao = x.Field("comiss"); - documento.Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))); - if (x.Field("tiporecebimento").ToString() == "1") - { - nullable3 = x.Field("liquido"); - valueOrDefault = nullable3.GetValueOrDefault(); - } - else - { - nullable3 = x.Field("valorliquidofatura"); - valueOrDefault = nullable3.GetValueOrDefault(); - } - documento.PremioLiquido = valueOrDefault; - if (x.Field("tiporecebimento").ToString() == "1") - { - nullable3 = x.Field("total"); - num = nullable3.GetValueOrDefault(); - } - else - { - nullable3 = x.Field("valor"); - num = nullable3.GetValueOrDefault(); - } - documento.PremioTotal = num; - nullable3 = x.Field("adicional"); - documento.PremioAdicional = nullable3.GetValueOrDefault(); - documento.Vigencia1 = (x.Field("tiporecebimento").ToString() == "1" ? (x.Field("vigenciainicial") == null ? DateTime.MinValue : x.Field("vigenciainicial")) : (x.Field("vigenciai") != null ? x.Field("vigenciai") : (x.Field("vigenciainicial") == null ? DateTime.MinValue : x.Field("vigenciainicial")))); - documento.Vigencia2 = (x.Field("tiporecebimento").ToString() == "1" ? (x.Field("vigenciafinal") == null ? new DateTime?(DateTime.MinValue) : x.Field("vigenciafinal")) : new DateTime?((x.Field("vigenciaf") != null ? x.Field("vigenciaf") : (x.Field("vigenciafinal") == null ? DateTime.MinValue : x.Field("vigenciafinal"))))); - documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); - documento.Proposta = x.Field("proposta"); - documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); - documento.TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field("tiporecebimento").ToString())); - documento.PropostaAssinada = (x.Field("propassinada") == null ? false : x.Field("propassinada") == "1"); - documento.Parcelas = new ObservableCollection(dataTable2.AsEnumerable().Where((DataRow p) => p.Field("iddocumento") == x.Field("iddocumento")).Select((DataRow p) => { - Parcela parcela = new Parcela() - { - Id = p.Field("id"), - NumeroParcela = int.Parse(p.Field("parcela").ToString()), - DataRecebimento = p.Field("recebimento") - }; - DateTime? nullable = p.Field("vencimento"); - parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue); - parcela.ValorComissao = (x.Field("valorcomissao") == null ? decimal.Zero : p.Field("valorcomissao")); - parcela.ValorComDesconto = (p.Field("valorcomdesconto") == null || p.Field("valorcomdesconto") == decimal.Zero ? (x.Field("valorcomissao") == null ? decimal.Zero : p.Field("valorcomissao")) : p.Field("valorcomdesconto")); - parcela.Comissao = p.Field("comiss"); - parcela.Valor = p.Field("valor"); - parcela.StatusPagamento = new StatusPagamento?((p.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), p.Field("StatusPagamento").ToString()))); - parcela.IdParcelaPendente = p.Field("IdParcelaPendente").GetValueOrDefault(); - return parcela; - }).ToList()); - documento.Tipo = x.Field("tipo"); - documento.DataControle = x.Field("datacontrole"); - documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); - IEnumerable list1 = - from i in dataTable3.AsEnumerable().ToList() - where i.Field("idcontrole") == x.Field("idcontrole") - select i; - Func u003cu003e9_2622 = ParcelaRepository.u003cu003ec.u003cu003e9__26_22; - if (u003cu003e9_2622 == null) - { - u003cu003e9_2622 = (DataRow i) => new Item() - { - Id = i.Field("iditem"), - Descricao = i.Field("descricao") - }; - ParcelaRepository.u003cu003ec.u003cu003e9__26_22 = u003cu003e9_2622; - } - documento.ItensAtivo = new List(list1.Select(u003cu003e9_2622).ToList()); - observableCollection.Documento = documento; - return observableCollection; - }).ToList(); - } - - public async Task> FindByRecebimento(Filtros filtro) - { - NegocioCorretora fieldValue; - bool flag; - bool count; - object connection; - bool count1; - bool flag1; - List itensAtivo; - decimal num; - object produto; - object estipulante; - object statu; - string str; - decimal num1; - decimal num2; - decimal num3; - DateTime dateTime; - DateTime? nullable; - NegocioCorretora negocioCorretora; - bool count2; - bool flag2; - Parcela parcela; - List parcelas = new List(); - List condicaos = this.CriaCondicaoDocumento(filtro, "CAST(p.DATAREC AS DATE)"); - List condicaos1 = new List(); - Condicao condicao = new Condicao() - { - Campo = "d.Excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos1.Add(condicao); - Condicao condicao1 = new Condicao() - { - Campo = "d.Excluido", - Valores = "0".CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos1.Add(condicao1); - condicaos.AddRange(condicaos1); - List vendedores = filtro.Vendedores; - if (vendedores != null) - { - count = vendedores.Count > 0; - } - else - { - count = false; - } - if (count) - { - if (await this.VerificaVendedorPropriaCorretora(filtro.Vendedores)) - { - List condicaos2 = condicaos; - Condicao condicao2 = new Condicao() - { - Campo = "vp.idvendedor", - Valores = null, - Grupo = 5, - Operacao = Operacao.Or - }; - condicaos2.Add(condicao2); - } - } - SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 1500; - string str1 = "SELECT p.IDPARCELA IdParcela,p.PARCELA NumeroParcela,p.DATAREC DataRecebimento,p.dataquit DataQuitacao,p.datacontrole DataControleParcela,p.VENCTO Vencimento,p.VLRCOMISS ValorComissao,p.IRR Irr,p.ISS Iss,p.DESCONTO Desconto,p.OUTROS Outros,p.VLRCOMDESC ValorComDesconto,p.COMISS ComissaoParcela,p.VALORR ValorRealizado,p.VALORLF PremioLiquidoFatura,p.VALOR PremioTotalFatura,p.IDSUBTIPO SubTipo,d.IDDOCUMENTO IdDocumento,c.IDCONTROLE IdControle,c.IDEMPRESA IdEmpresa,c.idcliente IdCliente,clie.NOME NomeCliente,clie.PASTA PastaCliente,clie.MalaDireta MalaDireta,r.idramo IdRamo,r.NOME NomeRamo,cia.IDCIASEG IdCiaSeg,cia.NOME NomeCia,cia.NomeSocial NomeSocial,pr.idproduto IdProduto,pr.NOME NomeProduto,e.idestipulante IdEstipulante,e.nome NomeEstipulante,s.idstatus IdStatus,s.nome NomeStatus,d.ADINACOMIS AdicionalComiss,d.contrato Apolice,d.ADITAMENTO Endosso,d.COM01 ComissaoDocumento,d.NegocioCorretora,d.idnegocio Negocio,d.PR_LIQ PremioLiquido,d.PR_TOTAL PremioTotal,d.PR_ADIC PremioAdicional,d.vigencia1 VigenciaInicial,d.vigencia2 VigenciaFinal,d.SITUACAO Situacao,d.TIPO Tipo,d.tiporecebimento TipoRecebimento,d.datacontrole DataControleDocumento,d.PASTA PastaDocumento,vp.IDVENDEDORPARCELA IdVendedorParcela,vp.VLRREP ValorRepasse,vp.VREP PorcentagemRepasse,vp.DATAPGT DataPagamento,vp.DATAPREPAGTO DataPrePagamento,vp.idtipovendedor IdTipoVendedor,vp.IDVENDEDOR IdVendedor,v.NOME NomeVendedor,f.vigenciai VigenciaInicialFatura,f.vigenciaf VigenciaFinalFatura,f.NUMFATURA Fatura FROM parcela p INNER JOIN documento d ON d.IDDOCUMENTO = p.IDDOCUMENTO INNER JOIN controle c ON c.IDCONTROLE = d.IDCONTROLE INNER JOIN cliente clie ON clie.IDCLIENTE = c.IDCLIENTE INNER JOIN ramo r ON r.IDRAMO = c.IDRAMO INNER JOIN ciaseg cia ON cia.IDCIASEG = c.IDCIASEG LEFT JOIN produto pr ON pr.IDPRODUTO = c.IDPRODUTO LEFT JOIN estipulante e ON e.idestipulante = d.idestipulante LEFT JOIN status s ON s.idstatus = d.idstatus LEFT JOIN vendedorparcela vp ON vp.IDPARCELA = p.IDPARCELA LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN fatura f ON f.IDPARCELA = p.IDPARCELA WHERE "; - sqlCommand.CommandText = string.Concat(str1, " ", sqlQueryCondition.Condicao); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync()) - { - while (true) - { - if (!await sqlDataReader.ReadAsync()) - { - break; - } - if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora")) - { - fieldValue = sqlDataReader.GetFieldValue("NegocioCorretora", true, true); - } - else - { - flag = sqlDataReader.GetFieldValue("Situacao", true, true) == TipoSeguro.Renovacao; - if (flag) - { - flag = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio"); - } - negocioCorretora = (!flag || !(sqlDataReader.GetFieldValue("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio); - fieldValue = negocioCorretora; - } - NegocioCorretora negocioCorretora1 = fieldValue; - if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any((long n) => (int)n == (int)negocioCorretora1)) - { - long fieldValue1 = sqlDataReader.GetFieldValue("IdParcela", true, true); - Parcela observableCollection = parcelas.Find((Parcela p) => p.Id == fieldValue1); - if (observableCollection == null) - { - long fieldValue2 = sqlDataReader.GetFieldValue("IdControle", true, true); - Parcela parcela1 = parcelas.Find((Parcela p) => p.Documento.Controle.Id == fieldValue2); - if (parcela1 != null) - { - itensAtivo = parcela1.Documento.ItensAtivo; - } - else - { - itensAtivo = null; - } - List items = itensAtivo; - if (items == null) - { - items = await this.BuscaItemsPorIdControle(fieldValue2); - } - TipoRecebimento tipoRecebimento = sqlDataReader.GetFieldValue("TipoRecebimento", true, true); - decimal fieldValue3 = sqlDataReader.GetFieldValue("ValorComissao", true, true); - decimal fieldValue4 = sqlDataReader.GetFieldValue("ValorComDesconto", true, true); - long num4 = sqlDataReader.GetFieldValue("IdEmpresa", true, true); - parcela = new Parcela() - { - Id = fieldValue1, - NumeroParcela = sqlDataReader.GetFieldValue("NumeroParcela", true, true), - DataRecebimento = sqlDataReader.GetFieldValue("DataRecebimento", true, true), - DataQuitacao = sqlDataReader.GetFieldValue("DataQuitacao", true, true), - DataControle = sqlDataReader.GetFieldValue("DataControleParcela", true, true), - Vencimento = sqlDataReader.GetFieldValue("Vencimento", true, true), - ValorComissao = fieldValue3, - Irr = sqlDataReader.GetFieldValue("Irr", true, true), - Iss = sqlDataReader.GetFieldValue("Iss", true, true), - Desconto = sqlDataReader.GetFieldValue("Desconto", true, true), - Outros = sqlDataReader.GetFieldValue("Outros", true, true) - }; - Parcela parcela2 = parcela; - num = (fieldValue4 == decimal.Zero ? fieldValue3 : fieldValue4); - parcela2.ValorComDesconto = num; - parcela.Comissao = sqlDataReader.GetFieldValue("ComissaoParcela", true, true); - parcela.ValorRealizado = sqlDataReader.GetFieldValue("ValorRealizado", true, true); - parcela.SubTipo = sqlDataReader.GetFieldValue("SubTipo", true, true); - parcela.IdEmpresa = num4; - Parcela parcela3 = parcela; - Documento documento = new Documento() - { - Id = sqlDataReader.GetFieldValue("IdDocumento", true, true) - }; - Documento documento1 = documento; - Controle controle = new Controle() - { - Id = fieldValue2, - IdEmpresa = num4 - }; - Controle controle1 = controle; - Cliente cliente = new Cliente() - { - Id = sqlDataReader.GetFieldValue("IdCliente", true, true), - Nome = sqlDataReader.GetFieldValue("NomeCliente", true, true), - Pasta = sqlDataReader.GetFieldValue("PastaCliente", true, true) - }; - bool? nullable1 = sqlDataReader.GetFieldValue("MalaDireta", true, true); - cliente.MalaDireta = new bool?(nullable1.GetValueOrDefault(true)); - controle1.Cliente = cliente; - Controle controle2 = controle; - Ramo ramo = new Ramo() - { - Id = sqlDataReader.GetFieldValue("IdRamo", true, true), - Nome = sqlDataReader.GetFieldValue("NomeRamo", true, true) - }; - controle2.Ramo = ramo; - Controle controle3 = controle; - Seguradora seguradora = new Seguradora() - { - Id = sqlDataReader.GetFieldValue("IdCiaSeg", true, true), - Nome = sqlDataReader.GetFieldValue("NomeCia", true, true), - NomeSocial = sqlDataReader.GetFieldValue("NomeSocial", true, true) - }; - controle3.Seguradora = seguradora; - Controle controle4 = controle; - flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdProduto"); - Controle controle5 = controle4; - if (flag) - { - produto = null; - } - else - { - produto = new Produto(); - ((DomainBase)produto).Id = sqlDataReader.GetFieldValue("IdProduto", true, true); - ((Produto)produto).Nome = sqlDataReader.GetFieldValue("NomeProduto", true, true); - } - controle5.Produto = (Produto)produto; - documento1.Controle = controle; - Documento documento2 = documento; - bool flag3 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdEstipulante"); - Documento documento3 = documento2; - if (flag3) - { - estipulante = null; - } - else - { - estipulante = new Estipulante(); - ((DomainBase)estipulante).Id = sqlDataReader.GetFieldValue("IdEstipulante", true, true); - ((Estipulante)estipulante).Nome = sqlDataReader.GetFieldValue("NomeEstipulante", true, true); - } - documento3.Estipulante1 = (Estipulante)estipulante; - Documento documento4 = documento; - bool flag4 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdStatus"); - Documento documento5 = documento4; - if (flag4) - { - statu = null; - } - else - { - statu = new Status(); - ((DomainBase)statu).Id = sqlDataReader.GetFieldValue("IdStatus", true, true); - ((Status)statu).Nome = sqlDataReader.GetFieldValue("NomeStatus", true, true); - } - documento5.Status = (Status)statu; - documento.AdicionalComiss = sqlDataReader["AdicionalComiss"].ToString() == "1"; - documento.Apolice = sqlDataReader.GetFieldValue("Apolice", true, true); - Documento documento6 = documento; - str = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("Endosso", true, true) : string.Concat("F ", sqlDataReader.GetFieldValue("Fatura", true, true))); - documento6.Endosso = str; - Documento documento7 = documento; - num1 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("ComissaoDocumento", true, true) : sqlDataReader.GetFieldValue("ComissaoParcela", true, true)); - documento7.Comissao = num1; - documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora1); - Documento nullable2 = documento; - Negocio? nullable3 = sqlDataReader.GetFieldValue("Negocio", true, true); - nullable2.Negocio = new Negocio?(nullable3.GetValueOrDefault(Negocio.Proprio)); - Documento documento8 = documento; - num2 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("PremioLiquido", true, true) : sqlDataReader.GetFieldValue("PremioLiquidoFatura", true, true)); - documento8.PremioLiquido = num2; - Documento documento9 = documento; - num3 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("PremioTotal", true, true) : sqlDataReader.GetFieldValue("PremioTotalFatura", true, true)); - documento9.PremioTotal = num3; - documento.PremioAdicional = sqlDataReader.GetFieldValue("PremioAdicional", true, true); - Documento documento10 = documento; - if (tipoRecebimento == TipoRecebimento.Parcela) - { - dateTime = sqlDataReader.GetFieldValue("VigenciaInicial", true, true); - } - else - { - DateTime? nullable4 = sqlDataReader.GetFieldValue("VigenciaInicialFatura", true, true); - dateTime = (nullable4.HasValue ? nullable4.GetValueOrDefault() : sqlDataReader.GetFieldValue("Vencimento", true, true)); - } - documento10.Vigencia1 = dateTime; - Documento documento11 = documento; - nullable = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue("VigenciaFinal", true, true) : sqlDataReader.GetFieldValue("VigenciaFinalFatura", true, true)); - documento11.Vigencia2 = nullable; - documento.Situacao = sqlDataReader.GetFieldValue("Situacao", true, true); - documento.Tipo = sqlDataReader.GetFieldValue("Tipo", true, true); - documento.TipoRecebimento = new TipoRecebimento?(tipoRecebimento); - documento.DataControle = sqlDataReader.GetFieldValue("DataControleDocumento", true, true); - documento.Pasta = sqlDataReader.GetFieldValue("PastaDocumento", true, true); - documento.ItensAtivo = items; - parcela3.Documento = documento; - observableCollection = parcela; - parcela3 = null; - documento1 = null; - controle4 = null; - controle = null; - documento2 = null; - documento4 = null; - documento = null; - parcela = null; - if (observableCollection.Vendedores == null) - { - observableCollection.Vendedores = new ObservableCollection(); - } - parcelas.Add(observableCollection); - items = null; - } - List tipoVendedor = filtro.TipoVendedor; - if (tipoVendedor != null) - { - count1 = tipoVendedor.Count > 0; - } - else - { - count1 = false; - } - if (!count1) - { - List nums = filtro.Vendedores; - if (nums != null) - { - flag1 = nums.Count > 0; - } - else - { - flag1 = false; - } - if (!flag1) - { - long fieldValue5 = sqlDataReader.GetFieldValue("IdVendedorParcela", true, true); - if (fieldValue5 > (long)0) - { - ObservableCollection vendedores1 = observableCollection.Vendedores; - VendedorParcela vendedorParcela = new VendedorParcela() - { - Id = fieldValue5, - ValorRepasse = new decimal?(sqlDataReader.GetFieldValue("ValorRepasse", true, true)), - PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue("PorcentagemRepasse", true, true)), - DataPagamento = sqlDataReader.GetFieldValue("DataPagamento", true, true), - DataPrePagamento = sqlDataReader.GetFieldValue("DataPrePagamento", true, true) - }; - TipoVendedor tipoVendedor1 = new TipoVendedor() - { - Id = sqlDataReader.GetFieldValue("IdTipoVendedor", true, true) - }; - vendedorParcela.TipoVendedor = tipoVendedor1; - Vendedor vendedor = new Vendedor() - { - Id = sqlDataReader.GetFieldValue("IdVendedor", true, true), - Nome = sqlDataReader.GetFieldValue("NomeVendedor", true, true) - }; - vendedorParcela.Vendedor = vendedor; - vendedores1.Add(vendedorParcela); - } - } - } - } - } - } - sqlDataReader = null; - List nums1 = filtro.TipoVendedor; - if (nums1 != null) - { - count2 = nums1.Count > 0; - } - else - { - count2 = false; - } - if (!count2) - { - List vendedores2 = filtro.Vendedores; - if (vendedores2 != null) - { - flag2 = vendedores2.Count > 0; - } - else - { - flag2 = false; - } - if (!flag2) - { - goto Label0; - } - } - foreach (Parcela parcela4 in parcelas) - { - parcela = parcela4; - List vendedorParcelas = await this.BuscaVendedoresPorIdParcela(parcela4.Id, parcela4.IdEmpresa, (long)0); - parcela.Vendedores = new ObservableCollection(vendedorParcelas); - parcela = null; - } - Label0: - } - sqlCommand = null; - } - sqlConnection = null; - } - sessionFactory = null; - List parcelas1 = parcelas; - parcelas = null; - condicaos = null; - return parcelas1; - } - - public List FindByVencimento(Filtros filtro) - { - List parcelas; - object connection; - string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join(",", - from v in filtro.Status - select v), ")")); - string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", - from v in filtro.Negocio - select v), ")")); - string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", - from v in filtro.Seguradoras - select v), ")")); - string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", - from v in filtro.Ramos - select v), ")")); - string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", - from v in filtro.Produtos - select v), ")")); - string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join(",", - from v in filtro.Vendedores - select v), ")")); - string str6 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", - from v in filtro.Estipulantes - select v), ")")); - string str7 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str8 = "SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, f.numfatura as fatura, f.vigenciai as vigenciai, f.vigenciaf as vigenciaf, p.parcela, p.datarec as recebimento, p.vencto as vencimento, ISNULL(p.vlrcomdesc, 0.00) as valorcomdesconto, ISNULL(p.vlrcomiss, 0.00) as valorcomissao, p.iddocumento, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, ISNULL(p.valor, 0.00) as valor, ISNULL(p.valorlf, 0.00) as valorliquidofatura, ISNULL(p.StatusPagamento, 0) AS StatusPagamento, ISNULL(p.IdParcelaPendente, 0) AS IdParcelaPendente, ISNULL(d.pr_total, 0.00) as total, ISNULL(d.pr_liq, 0.00) as liquido, d.pr_adic as adicional, d.adinacomis as adinacomiss, ISNULL(d.com01, 0.00) as comissao, ISNULL(p.comiss, 0.00) as comiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento FROM parcela p INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0)"; - string str9 = "SELECT DISTINCT idparcela as id, idvendedor, vlrrep as valorrepasse, vrep as porcentagemrepasse, datapgt as datapagamento, dataprepagto as dataprepagamento FROM vendedorparcela vp WHERE 1=1 "; - sqlCommand.CommandText = string.Format("{0} {1} AND p.vencto >= '{2:yyyy-MM-dd}' AND p.vencto <= '{3:yyyy-MM-dd}' {4} {5} {6} {7} {8} {9} {10}", new object[] { str8, str7, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str6, str5 }); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - string str10 = string.Concat(" AND vp.idparcela IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat(str9, " ", str10); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - goto Label0; - } - } - else - { - parcelas = new List(); - } - } - } - return parcelas; - Label0: - return dataTable.AsEnumerable().ToList().Select((DataRow x) => { - decimal? nullable3; - decimal valueOrDefault; - decimal num; - Parcela parcela = new Parcela() - { - Id = x.Field("id"), - IdEmpresa = x.Field("idempresa"), - NumeroParcela = int.Parse(x.Field("parcela").ToString()), - DataRecebimento = x.Field("recebimento") - }; - DateTime? nullable4 = x.Field("vencimento"); - parcela.Vencimento = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue); - parcela.ValorComDesconto = (x.Field("valorcomdesconto") == null || x.Field("valorcomdesconto") == decimal.Zero ? (x.Field("valorcomissao") == null ? decimal.Zero : x.Field("valorcomissao")) : x.Field("valorcomdesconto")); - parcela.Comissao = x.Field("comiss"); - parcela.Valor = x.Field("valor"); - parcela.StatusPagamento = new StatusPagamento?((x.Field("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field("StatusPagamento").ToString()))); - parcela.IdParcelaPendente = x.Field("IdParcelaPendente").GetValueOrDefault(); - IEnumerable list = - from v in dataTable1.AsEnumerable().ToList() - where v.Field("id") == x.Field("id") - select v; - Func u003cu003e9_2810 = ParcelaRepository.u003cu003ec.u003cu003e9__28_10; - if (u003cu003e9_2810 == null) - { - u003cu003e9_2810 = (DataRow v) => { - DateTime? nullable; - DateTime? nullable1; - DateTime? nullable2; - VendedorParcela vendedorParcela = new VendedorParcela() - { - Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == v.Field("idvendedor")), - ValorRepasse = new decimal?((v.Field("valorrepasse") == null ? decimal.Zero : v.Field("valorrepasse"))), - PorcentagemRepasse = new decimal?((v.Field("porcentagemrepasse") == null ? decimal.Zero : v.Field("porcentagemrepasse"))) - }; - if (v.Field("datapagamento") == null) - { - nullable = null; - nullable1 = nullable; - } - else - { - nullable1 = v.Field("datapagamento"); - } - vendedorParcela.DataPagamento = nullable1; - if (v.Field("dataprepagamento") == null) - { - nullable = null; - nullable2 = nullable; - } - else - { - nullable2 = v.Field("dataprepagamento"); - } - vendedorParcela.DataPrePagamento = nullable2; - return vendedorParcela; - }; - ParcelaRepository.u003cu003ec.u003cu003e9__28_10 = u003cu003e9_2810; - } - parcela.Vendedores = new ObservableCollection(list.Select(u003cu003e9_2810).ToList()); - Documento documento = new Documento() - { - Controle = new Controle() - { - IdEmpresa = x.Field("idempresa"), - Cliente = new Cliente() - { - Id = x.Field("idcliente"), - Nome = x.Field("cliente"), - IdEmpresa = x.Field("idempresa"), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) - }, - Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), - Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), - Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Produto p) => p.Id == x.Field("idproduto")) : null) - }, - AdicionalComiss = x.Field("adinacomiss") == "1", - Apolice = x.Field("apolice"), - Endosso = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("endosso") : string.Concat("F ", x.Field("fatura"))), - Comissao = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("comissao") : x.Field("comiss")), - Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))) - }; - if (x.Field("tiporecebimento").ToString() == "1") - { - nullable3 = x.Field("liquido"); - valueOrDefault = nullable3.GetValueOrDefault(); - } - else - { - nullable3 = x.Field("valorliquidofatura"); - valueOrDefault = nullable3.GetValueOrDefault(); - } - documento.PremioLiquido = valueOrDefault; - if (x.Field("tiporecebimento").ToString() == "1") - { - nullable3 = x.Field("total"); - num = nullable3.GetValueOrDefault(); - } - else - { - nullable3 = x.Field("valor"); - num = nullable3.GetValueOrDefault(); - } - documento.PremioTotal = num; - nullable3 = x.Field("adicional"); - documento.PremioAdicional = nullable3.GetValueOrDefault(); - documento.Vigencia1 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciainicial") : x.Field("vigenciai")); - documento.Vigencia2 = (x.Field("tiporecebimento").ToString() == "1" ? x.Field("vigenciafinal") : x.Field("vigenciaf")); - documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); - documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); - documento.Tipo = x.Field("tipo"); - parcela.Documento = documento; - return parcela; - }).ToList(); - } - - public List FindByVigencia(Filtros filtro) - { - return new List(); - } - - public List FindDocumentId(List ids) - { - List nums; - object connection; - if (ids == null || ids.Count == 0) - { - return ids; - } - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - string str = string.Concat(" idparcela IN (", string.Join(",", ids), ")"); - sqlCommand.CommandText = string.Concat("SELECT iddocumento FROM parcela p WHERE ", str); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - return dataTable.AsEnumerable().Select((DataRow x) => x.Field("iddocumento")).ToList(); - } - else - { - nums = new List(); - } - } - } - return nums; - } - - public List FindNumFatura(string numero) - { - List documentos; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, p.idparcela as id, p.iddocumento, d.contrato as apolice, f.numfatura as fatura, f.emissao, d.idnegocio, d.situacao, f.vigenciai as vigenciainicial, f.vigenciaf as vigenciafinal, ISNULL(p.valor, 0.00) as total, ISNULL(p.valorlf, 0.00) as liquido, 0.00 as adicional, '0' as adinacomiss, ISNULL(p.comiss, 0.00) as comissao, c.idramo, c.idciaseg as idseguradora, c.idproduto, 2 as tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.negociocorretora, d.datacontrole, d.idstatus, p.datacontrole as dataparcelacontrole, p.cri_data, d.banco, d.agencia, d.conta, d.pasta, d.propassinada FROM fatura f INNER JOIN parcela p on p.idparcela = f.idparcela INNER JOIN documento d on d.iddocumento = p.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente INNER JOIN vendedorparcela vp on vp.idparcela = p.idparcela WHERE (d.excluido IS NULL OR d.excluido = 0) AND NUMFATURA ='", numero, "'"); - string str1 = "SELECT DISTINCT idparcela as id, idvendedor FROM vendedorparcela vp WHERE 1=1 "; - sqlCommand.CommandText = str ?? ""; - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - string str2 = string.Concat(" AND vp.idparcela IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat(str1, " ", str2); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - goto Label0; - } - } - else - { - documentos = new List(); - } - } - } - return documentos; - Label0: - return dataTable.AsEnumerable().ToList().Select((DataRow x) => { - Func func2 = null; - Documento documento = new Documento() - { - Id = x.Field("iddocumento"), - Controle = new Controle() - { - Id = x.Field("idcontrole"), - IdEmpresa = x.Field("idempresa"), - Cliente = new Cliente() - { - Nome = x.Field("cliente"), - Id = x.Field("idcliente"), - IdEmpresa = x.Field("idempresa"), - MalaDireta = new bool?(x.Field("MalaDireta").GetValueOrDefault(true)) - }, - Seguradora = (x.Field("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault((Seguradora p) => p.Id == x.Field("idseguradora")) : null), - Ramo = (x.Field("idramo") != null ? Auxiliar.Ramos.FirstOrDefault((Ramo p) => p.Id == x.Field("idramo")) : null), - Produto = (x.Field("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault((Produto p) => p.Id == x.Field("idproduto")) : null) - }, - Pasta = x.Field("Pasta"), - TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura), - AdicionalComiss = false, - Apolice = x.Field("apolice"), - Endosso = x.Field("fatura"), - Comissao = x.Field("comissao"), - NegocioCorretora = new NegocioCorretora?((x.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao || x.Field("idnegocio") == null || x.Field("idnegocio") != (long)1 ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString()))), - Negocio = new Negocio?((x.Field("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field("idnegocio").ToString()))) - }; - decimal? nullable = x.Field("liquido"); - documento.PremioLiquido = nullable.GetValueOrDefault(); - nullable = x.Field("total"); - documento.PremioTotal = nullable.GetValueOrDefault(); - DateTime? nullable1 = x.Field("vigenciainicial"); - documento.Vigencia1 = (nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue); - documento.Vigencia2 = x.Field("vigenciafinal"); - documento.Emissao = x.Field("emissao"); - documento.VendedorPrincipal = (x.Field("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault((Vendedor p) => p.Id == x.Field("idvendedor")) : null); - documento.Estipulante1 = (x.Field("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault((Estipulante p) => p.Id == x.Field("idestipulante")) : null); - documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()); - documento.Vendedores = Auxiliar.Vendedores.Where((Vendedor v) => { - List list = dataTable1.AsEnumerable().ToList(); - Func u003cu003e9_9 = func2; - if (u003cu003e9_9 == null) - { - Func func = (DataRow d) => d.Field("id") == x.Field("id"); - Func func1 = func; - func2 = func; - u003cu003e9_9 = func1; - } - IEnumerable dataRows = list.Where(u003cu003e9_9); - Func u003cu003e9_2210 = ParcelaRepository.u003cu003ec.u003cu003e9__22_10; - if (u003cu003e9_2210 == null) - { - u003cu003e9_2210 = (DataRow d) => d.Field("idvendedor"); - ParcelaRepository.u003cu003ec.u003cu003e9__22_10 = u003cu003e9_2210; - } - return dataRows.Select(u003cu003e9_2210).ToList().Contains(v.Id); - }).ToList(); - documento.Tipo = x.Field("tipo"); - documento.DataControle = x.Field("dataparcelacontrole"); - documento.Status = (x.Field("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault((Status p) => p.Id == x.Field("idstatus")) : null); - documento.DataCriacao = x.Field("cri_data"); - documento.Banco = new Banco() - { - Nome = x.Field("banco") - }; - documento.Agencia = x.Field("agencia"); - documento.Conta = x.Field("conta"); - documento.PropostaAssinada = (x.Field("propassinada") == null ? false : x.Field("propassinada") == "1"); - return documento; - }).ToList(); - } - - public bool FindParcel(long id) - { - bool flag; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str = "SELECT DISTINCT c.idcliente, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.tiporecebimento, p.idparcela, pe.idparcela AS idParcelaParcelaExtrato, p.datacred FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN parcela p ON p.iddocumento = d.iddocumento INNER JOIN parcelaextrato pe ON pe.iddocumento = d.iddocumento WHERE (d.excluido IS NULL OR d.excluido = 0) "; - DateTime networkTime = Funcoes.GetNetworkTime(); - sqlCommand.CommandText = string.Format("{0} AND (d.vigencia2 IS NULL AND d.situacao IN (1,2) OR d.vigencia2 >= '{1:yyyy-MM-dd}') AND DATALENGTH(ISNULL( d.contrato, '' )) > 0 AND d.iddocumento in ({2}) AND pe.idparcela = p.idparcela", str, networkTime.Date, id); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - bool flag1 = false; - foreach (DataRow row in dataTable.Rows) - { - string str1 = string.Format("{0}", row["datacred"]); - flag1 = (string.Format("{0}", row["idparcela"]) != string.Format("{0}", row["idParcelaParcelaExtrato"]) ? false : !string.IsNullOrEmpty(str1)); - } - flag = flag1; - } - } - return flag; - } - - public Parcela Merge(Parcela parcela) - { - ParcelaDb parcelaDb = ApplicationMapper.Mapper.Map(parcela); - if (parcelaDb.IdEmpresa == 0) - { - parcelaDb.IdEmpresa = (long)1; - } - base.Merge(parcelaDb); - if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela) - { - return ApplicationMapper.Mapper.Map(parcelaDb); - } - FaturaDb fatura = this._unitOfWork.Query().FirstOrDefault((FaturaDb x) => x.Parcela.Id == parcelaDb.Id) ?? new FaturaDb(); - fatura.Parcela = parcelaDb; - fatura.Fatura = parcelaDb.Fatura; - FaturaDb faturaDb = fatura; - DateTime? vigenciaIncial = parcelaDb.VigenciaIncial; - faturaDb.VigenciaInicial = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.VigenciaInicial); - FaturaDb faturaDb1 = fatura; - vigenciaIncial = parcelaDb.VigenciaFinal; - faturaDb1.VigenciaFinal = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.VigenciaFinal); - FaturaDb faturaDb2 = fatura; - vigenciaIncial = parcelaDb.Emissao; - faturaDb2.Emissao = (vigenciaIncial.HasValue ? vigenciaIncial : fatura.Emissao); - if (fatura.Id != 0) - { - this._unitOfWork.Repository().Merge(fatura); - } - else - { - this._unitOfWork.Repository().SaveOrUpdate(fatura); - } - return ApplicationMapper.Mapper.Map(parcelaDb); - } - - public List PrevisaoPagamentoComissao(Filtros filtro) - { - object connection; - string str2 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND d.situacao IN (", string.Join(",", - from v in filtro.Status - select v), ")")); - string str3 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join(",", - from v in filtro.Negocio - select v), ")")); - string str4 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join(",", - from v in filtro.Seguradoras - select v), ")")); - string str5 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join(",", - from v in filtro.Ramos - select v), ")")); - string str6 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join(",", - from v in filtro.Produtos - select v), ")")); - string str7 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? " AND vp.idvendedor IS NOT NULL " : string.Concat(" AND vp.idvendedor IN (", string.Join(",", - from v in filtro.Vendedores - select v), ")")); - string str8 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? " AND vp.idtipovendedor = 1 " : string.Concat(" AND vp.idtipovendedor IN (", string.Join(",", - from v in filtro.TipoVendedor - select v), ")")); - string str9 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join(",", - from v in filtro.Estipulantes - select v), ")")); - string str10 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa)); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - Auxiliar.CriarAuxiliar(sqlCommand, false); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT d.tipo, f.NUMFATURA, f.VIGENCIAI, vp.idvendedorparcela, vp.idvendedor, cl.nome AS cliente, d.situacao, d.contrato, d.VIGENCIA1, d.aditamento, c.idciaseg, c.idramo, p.parcela, ISNULL(v.desconto, 0) as desconto, p.vencto, ISNULL(vp.vlrrep, 0) as vlrliquido, ISNULL(d.pr_liq, 0) as pr_liq, ISNULL(p.VALORLF, 0) as valorlf, ISNULL(p.vlrcomiss, 0) as vlrcomiss, p.idsubtipo, d.n_parc, d.tiporecebimento FROM controle c INNER JOIN cliente cl on cl.idcliente = c.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole INNER JOIN parcela p on p.iddocumento = d.iddocumento INNER JOIN vendedorparcela vp on vp.idparcela = p.idparcela INNER JOIN vendedor v on v.idvendedor = vp.idvendedor LEFT OUTER JOIN fatura f on f.idparcela = p.idparcela ", string.Format("WHERE (d.excluido IS NULL OR d.excluido != 1) AND v.corretora != '1' AND vp.datapgt IS NULL AND vp.vlrrep != 0 AND (d.tiporecebimento = '1' AND ISNULL(d.com01, 0.00) > 0 OR d.tiporecebimento = '2') {0} {1} {2} {3} {4} {5} {6} {7} {8} AND p.vencto >= '{9:yyyy-MM-dd}' AND p.vencto <= '{10:yyyy-MM-dd}';", new object[] { str10, str7, str2, str3, str4, str5, str6, str8, str9, filtro.Inicio, filtro.Fim })); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return dataTable.AsEnumerable().ToList().Select((DataRow x) => { - string nome; - string str; - string nome1; - string str1; - PrevisaoPagamento previsaoPagamento = new PrevisaoPagamento() - { - Nome = x.Campo("cliente"), - Apolice = (x.IsNull("tiporecebimento") ? "" : (x.Campo("tiporecebimento") == "1" ? x.Campo("contrato") : x.Campo("NUMFATURA"))), - Endosso = (x.Campo("tiporecebimento") == "1" ? x.Campo("aditamento") : ""), - Status = x.Campo("situacao").GetDescription(), - VigenciaInicial = (x.Campo("tiporecebimento") == "1" ? x.Campo("VIGENCIA1") : x.Campo("VIGENCIAI")), - TipoDocumento = (x.IsNull("tiporecebimento") ? "" : (x.Campo("tiporecebimento") == "2" ? "FATURA" : (x.Campo("tipo") == "0" ? "APÓLICE" : "ENDOSSO"))) - }; - Seguradora seguradora = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Campo("idciaseg")); - if (seguradora != null) - { - nome = seguradora.Nome; - } - else - { - nome = null; - } - previsaoPagamento.NomeSeguradora = nome; - Ramo ramo = Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Campo("idramo")); - if (ramo != null) - { - str = ramo.Nome; - } - else - { - str = null; - } - previsaoPagamento.NomeRamo = str; - previsaoPagamento.PremioLiquido = (x.Campo("tiporecebimento") == "1" ? x.Campo("pr_liq") : x.Campo("valorlf")); - previsaoPagamento.Parcela = (x.Campo("idsubtipo") > (long)1 ? "ESPECIAL" : (x.Campo("tiporecebimento") == "1" ? string.Concat(x.Campo("parcela").PadLeft(2, '0'), " DE ", x.Campo("n_parc")) : x.Campo("parcela").PadLeft(2, '0'))); - previsaoPagamento.VencimentoParcela = x.Campo("vencto"); - previsaoPagamento.RepasseLiquido = x.Campo("vlrliquido") * (decimal.One - (x.Campo("desconto") > decimal.One ? x.Campo("desconto") * new decimal(1, 0, 0, false, 2) : x.Campo("desconto"))); - previsaoPagamento.Repasse = x.Campo("vlrliquido"); - previsaoPagamento.Vendedor = Auxiliar.Vendedores.Find((Vendedor p) => p.Id == x.Campo("idvendedor")); - Seguradora seguradora1 = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Campo("idciaseg")); - if (seguradora1 != null) - { - nome1 = seguradora1.Nome; - } - else - { - nome1 = null; - } - previsaoPagamento.Seguradora = nome1; - Ramo ramo1 = Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Campo("idramo")); - if (ramo1 != null) - { - str1 = ramo1.Nome; - } - else - { - str1 = null; - } - previsaoPagamento.Ramo = str1; - return previsaoPagamento; - }).ToList(); - } - - public Parcela SaveOrUpdate(Parcela parcela) - { - ParcelaDb parcelaDb = ApplicationMapper.Mapper.Map(parcela); - if (parcelaDb.IdEmpresa == 0) - { - parcelaDb.IdEmpresa = (long)1; - } - this.SaveOrUpdate(parcelaDb); - if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela) - { - return ApplicationMapper.Mapper.Map(parcelaDb); - } - FaturaDb faturaDb = new FaturaDb() - { - Parcela = parcelaDb, - Fatura = parcelaDb.Fatura, - VigenciaInicial = parcelaDb.VigenciaIncial, - VigenciaFinal = parcelaDb.VigenciaFinal, - Emissao = parcelaDb.Emissao - }; - this._unitOfWork.Repository().SaveOrUpdate(faturaDb); - return ApplicationMapper.Mapper.Map(parcelaDb); - } - - public int[] SincronizarPendencia(DateTime date, List ids = null) - { - // - // Current member / type: System.Int32[] Gestor.Infrastructure.Repository.Logic.ParcelaRepository::SincronizarPendencia(System.DateTime,System.Collections.Generic.List`1) - // File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll - // - // Product version: 0.0.0.0 - // Exception in: System.Int32[] SincronizarPendencia(System.DateTime,System.Collections.Generic.List) - // - // An item with the same key has already been added. Key: Label0 - // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) - // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection>.Add(KeyValuePair`2 keyValuePair) - // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 101 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 332 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 384 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitIfStatement(IfStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 363 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitTryStatement(TryStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 483 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 338 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitTryStatement(TryStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 483 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 74 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 23 - // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 - // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 - // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 - // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 - // - // mailto: JustDecompilePublicFeedback@telerik.com - - } - - public bool Update(List detalhes, bool desabilitaAproximação) - { - // - // Current member / type: System.Boolean Gestor.Infrastructure.Repository.Logic.ParcelaRepository::Update(System.Collections.Generic.List`1,System.Boolean) - // File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll - // - // Product version: 0.0.0.0 - // Exception in: System.Boolean Update(System.Collections.Generic.List,System.Boolean) - // - // An item with the same key has already been added. Key: Label0 - // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) - // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection>.Add(KeyValuePair`2 keyValuePair) - // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 101 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 351 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 384 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 74 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 33 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 23 - // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 - // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 - // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 - // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 133 - // - // mailto: JustDecompilePublicFeedback@telerik.com - - } - - public List UpdateRange(List parcelas) - { - List parcelaDbs = ApplicationMapper.Mapper.Map, List>(parcelas); - parcelaDbs.ForEach((ParcelaDb x) => { - if (x.IdEmpresa == 0) - { - x.IdEmpresa = (long)1; - } - }); - ParcelaRepository parcelaRepository = this; - parcelaDbs.ForEach(new Action(parcelaRepository.Merge)); - return ApplicationMapper.Mapper.Map, List>(parcelaDbs); - } - - private async Task VerificaVendedorPropriaCorretora(List vendedores) - { - bool valueOrDefault; - object connection; - List condicaos = new List(); - Condicao condicao = new Condicao() - { - Campo = "IdVendedor", - Valores = vendedores.CriarValor(), - Grupo = 1, - Operacao = Operacao.Or - }; - condicaos.Add(condicao); - SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0); - using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl) - { - SessionFactoryImpl sessionFactoryImpl = sessionFactory; - if (sessionFactoryImpl != null) - { - connection = sessionFactoryImpl.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT COUNT(IdVendedor) FROM Vendedor WHERE Corretora = 1 AND ", sqlQueryCondition.Condicao); - sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray()); - int? nullable = (int?)await sqlCommand.ExecuteScalarAsync(); - valueOrDefault = nullable.GetValueOrDefault() > 0; - } - } - } - return valueOrDefault; - } - - private class VinculoParcela - { - public string Apolice - { - get; - set; - } - - public string Endosso - { - get; - set; - } - - public long IdDocumento - { - get; - set; - } - - public long IdParcela - { - get; - set; - } - - public int Parcela - { - get; - set; - } - - public Seguradora Seguradora - { - get; - set; - } - - public int Tipo - { - get; - set; - } - - public VinculoParcela() - { - } - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs deleted file mode 100644 index f3b92f0..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs +++ /dev/null @@ -1,251 +0,0 @@ -using AutoMapper; -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.Common; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class PatrimonialRepository : GenericRepository, IPatrimonialRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public PatrimonialRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public void DeleteRange(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Item.Id) - select x).ToList(); - base.DeleteRange(list); - } - - public Patrimonial Find(long id) - { - PatrimonialDb patrimonialDb = base.All().FirstOrDefault((PatrimonialDb x) => x.Item.Id == id) ?? new PatrimonialDb(); - return ApplicationMapper.Mapper.Map(patrimonialDb); - } - - public Patrimonial FindById(long id) - { - PatrimonialDb patrimonialDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(patrimonialDb); - } - - public List FindImobiliaria(string imobiliaria, FiltroStatusDocumento status, List vendedorVinculado) - { - List pesquisaAvancadas; - object connection; - 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.CommandText = string.Concat("SELECT iditem as id FROM resempco WHERE imobiliaria LIKE '%", imobiliaria, "%'"); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - string str = string.Concat(" AND iditem IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat("SELECT iddocumento as id, descricao, iditem FROM item WHERE 1=1 ", str); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - } - sqlCommand.CommandText = string.Concat("SELECT DISTINCT cl.nome as cliente, c.idcliente, d.idcontrole, d.iddocumento, situacao, vigencia1, vigencia2, proposta, contrato as apolice, aditamento as endosso, CAST(tipo as INTEGER) as tipo FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE d.iddocumento IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) - { - sqlDataAdapter2.SelectCommand = sqlCommand; - sqlDataAdapter2.Fill(dataTable2); - } - string str1 = string.Concat(" AND d.idcontrole IN (", string.Join(",", ( - from x in dataTable2.AsEnumerable().ToList() - select x.Field("idcontrole")).ToList()), ")"); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 ", str1); - using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) - { - sqlDataAdapter3.SelectCommand = sqlCommand; - sqlDataAdapter3.Fill(dataTable3); - List list = null; - if (vendedorVinculado != null && vendedorVinculado.Count > 0) - { - list = dataTable3.AsEnumerable().Where((DataRow x) => { - List vendedorUsuarios = vendedorVinculado; - Func u003cu003e9_85 = PatrimonialRepository.u003cu003ec.u003cu003e9__8_5; - if (u003cu003e9_85 == null) - { - u003cu003e9_85 = (VendedorUsuario v) => v.Vendedor.Id; - PatrimonialRepository.u003cu003ec.u003cu003e9__8_5 = u003cu003e9_85; - } - return vendedorUsuarios.Select(u003cu003e9_85).Contains(x.Field("idvendedor")); - }).Select((DataRow x) => x.Field("idcontrole")).ToList(); - } - if (list != null && list.Count == 0) - { - return new List(); - } - return Auxiliar.PesquisaAvancada(status, dataTable2, dataTable1, list); - } - } - else - { - pesquisaAvancadas = new List(); - } - } - } - return pesquisaAvancadas; - } - - public List Findlocatario(string imobiliaria, FiltroStatusDocumento status, List vendedorVinculado) - { - List pesquisaAvancadas; - object connection; - bool count; - 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.CommandText = string.Concat(new string[] { "SELECT DISTINCT rec.iditem AS id FROM resempco rec INNER JOIN item i ON i.iditem = rec.iditem INNER JOIN documento d ON i.IDDOCUMENTO = d.IDDOCUMENTO WHERE (rec.locatario LIKE '%", imobiliaria, "%' OR rec.locatario2 LIKE '%", imobiliaria, "%' OR rec.locatario3 LIKE '%", imobiliaria, "%') AND d.excluido != 1;" }); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - string str = string.Concat(" AND iditem IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - sqlCommand.CommandText = string.Concat("SELECT iddocumento as id, descricao, iditem FROM item WHERE 1=1 ", str); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - } - sqlCommand.CommandText = string.Concat("SELECT DISTINCT cl.nome as cliente, c.idcliente, d.idcontrole, d.iddocumento, situacao, vigencia1, vigencia2, proposta, contrato as apolice, aditamento as endosso, CAST(tipo as INTEGER) as tipo FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE d.iddocumento IN (", string.Join(",", dataTable1.AsEnumerable().Select((DataRow v) => v.Field("id"))), ")"); - using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) - { - sqlDataAdapter2.SelectCommand = sqlCommand; - sqlDataAdapter2.Fill(dataTable2); - } - string str1 = string.Concat(" AND d.idcontrole IN (", string.Join(",", ( - from x in dataTable2.AsEnumerable().ToList() - select x.Field("idcontrole")).ToList()), ")"); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 ", str1); - using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) - { - sqlDataAdapter3.SelectCommand = sqlCommand; - sqlDataAdapter3.Fill(dataTable3); - goto Label0; - } - } - else - { - pesquisaAvancadas = new List(); - } - } - } - return pesquisaAvancadas; - Label0: - List list = null; - if (vendedorVinculado != null && vendedorVinculado.Count > 0) - { - list = dataTable3.AsEnumerable().Where((DataRow x) => { - List vendedorUsuarios = vendedorVinculado; - Func u003cu003e9_97 = PatrimonialRepository.u003cu003ec.u003cu003e9__9_7; - if (u003cu003e9_97 == null) - { - u003cu003e9_97 = (VendedorUsuario v) => v.Vendedor.Id; - PatrimonialRepository.u003cu003ec.u003cu003e9__9_7 = u003cu003e9_97; - } - return vendedorUsuarios.Select(u003cu003e9_97).Contains(x.Field("idvendedor")); - }).Select((DataRow x) => x.Field("idcontrole")).ToList(); - } - if (vendedorVinculado != null) - { - List vendedorUsuarios1 = vendedorVinculado; - if (vendedorUsuarios1 != null) - { - count = vendedorUsuarios1.Count == 0; - } - else - { - count = false; - } - if (count) - { - list = dataTable2.AsEnumerable().Where((DataRow x) => x.Field("idcontrole").HasValue).Select((DataRow x) => x.Field("idcontrole")).ToList(); - } - } - return Auxiliar.PesquisaAvancada(status, dataTable2, dataTable1, list); - } - - public Patrimonial Merge(Patrimonial patrimonial) - { - PatrimonialDb patrimonialDb = ApplicationMapper.Mapper.Map(patrimonial); - base.Merge(patrimonialDb); - return ApplicationMapper.Mapper.Map(patrimonialDb); - } - - public Patrimonial SaveOrUpdate(Patrimonial patrimonial) - { - PatrimonialDb patrimonialDb = ApplicationMapper.Mapper.Map(patrimonial); - this.SaveOrUpdate(patrimonialDb); - return ApplicationMapper.Mapper.Map(patrimonialDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs deleted file mode 100644 index b32c539..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs +++ /dev/null @@ -1,64 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class PerfilEmpresaRepository : GenericRepository, IPerfilEmpresaRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public PerfilEmpresaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - PerfilEmpresaDb perfilEmpresaDb = base.FindEntityById(id); - if (perfilEmpresaDb == null) - { - return; - } - base.Delete(perfilEmpresaDb); - } - - public PerfilEmpresa Find(long id) - { - PerfilEmpresaDb perfilEmpresaDb = base.All().FirstOrDefault((PerfilEmpresaDb x) => x.Id == id); - return ApplicationMapper.Mapper.Map(perfilEmpresaDb); - } - - public PerfilEmpresa FindByControleId(long id) - { - PerfilEmpresaDb perfilEmpresaDb = ( - from x in base.All() - where x.Controle.Id == id - select x).FirstOrDefault(); - return ApplicationMapper.Mapper.Map(perfilEmpresaDb); - } - - public PerfilEmpresa Merge(PerfilEmpresa perfil) - { - PerfilEmpresaDb perfilEmpresaDb = ApplicationMapper.Mapper.Map(perfil); - base.Merge(perfilEmpresaDb); - return ApplicationMapper.Mapper.Map(perfilEmpresaDb); - } - - public PerfilEmpresa SaveOrUpdate(PerfilEmpresa perfilEmpresa) - { - PerfilEmpresaDb perfilEmpresaDb = ApplicationMapper.Mapper.Map(perfilEmpresa); - this.SaveOrUpdate(perfilEmpresaDb); - return ApplicationMapper.Mapper.Map(perfilEmpresaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs deleted file mode 100644 index 67375a5..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs +++ /dev/null @@ -1,191 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -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.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class PerfilRepository : GenericRepository, IPerfilRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public PerfilRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - PerfilDb perfilDb = base.FindEntityById(id); - if (perfilDb == null) - { - return; - } - base.Delete(perfilDb); - } - - public Perfil Find(long id) - { - PerfilDb perfilDb = base.All().FirstOrDefault((PerfilDb x) => x.Id == id); - return ApplicationMapper.Mapper.Map(perfilDb); - } - - public List FindByControleId(long id) - { - List list = ( - from x in base.All() - where x.Controle.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindByControleIds(string ids) - { - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT * FROM perfil WHERE idcontrole IN (", ids, ");"); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - if (dataTable.Rows.Count == 0) - { - return new List(); - } - return dataTable.AsEnumerable().Select((DataRow p) => { - GaragemTrabalhoEstudo? nullable; - bool? nullable1; - GaragemTrabalhoEstudo? nullable2; - GaragemTrabalhoEstudo? nullable3; - bool? nullable4; - bool? nullable5; - bool? nullable6; - Perfil perfil = new Perfil() - { - Cliente = new Cliente() - { - Id = long.Parse(p["idcliente"].ToString()) - }, - Controle = new Controle() - { - Id = long.Parse(p["idcontrole"].ToString()) - }, - Nome = p["nomecompleto"].ToString(), - Cpf = p["cpf"].ToString(), - Nascimento = (string.IsNullOrEmpty(p["datanascimento"].ToString()) ? null : new DateTime?(DateTime.Parse(p["datanascimento"].ToString()))), - EstadoCivil = (string.IsNullOrEmpty(p["estadocivil"].ToString()) ? null : new EstadoCivil?((EstadoCivil)int.Parse(p["estadocivil"].ToString()))), - Sexo = (string.IsNullOrEmpty(p["sexo"].ToString()) ? null : new Sexo?((Sexo)int.Parse(p["sexo"].ToString()))), - Relacao = (string.IsNullOrEmpty(p["relacao"].ToString()) ? null : new Relacao?((Relacao)int.Parse(p["relacao"].ToString()))), - Habilitacao = p["numerohabilitacao"].ToString(), - TempoHabilitacao = (string.IsNullOrEmpty(p["tempohabilitacao"].ToString()) ? null : new TempoHabilitacao?((TempoHabilitacao)int.Parse(p["tempohabilitacao"].ToString()))), - VeiculoResidencia = (string.IsNullOrEmpty(p["veiculosresidencia"].ToString()) ? null : new int?(int.Parse(p["veiculosresidencia"].ToString()))), - GaragemResidencia = (string.IsNullOrEmpty(p["garagemresidencia"].ToString()) ? null : new GaragemResidencia?((GaragemResidencia)int.Parse(p["garagemresidencia"].ToString()))) - }; - if (string.IsNullOrEmpty(p["garagemtrabalho"].ToString())) - { - nullable = null; - nullable2 = nullable; - } - else - { - nullable2 = new GaragemTrabalhoEstudo?((GaragemTrabalhoEstudo)int.Parse(p["garagemtrabalho"].ToString())); - } - perfil.GaragemTrabalho = nullable2; - if (string.IsNullOrEmpty(p["garagemestudo"].ToString())) - { - nullable = null; - nullable3 = nullable; - } - else - { - nullable3 = new GaragemTrabalhoEstudo?((GaragemTrabalhoEstudo)int.Parse(p["garagemestudo"].ToString())); - } - perfil.GaragemEstudo = nullable3; - perfil.TipoResidencia = (string.IsNullOrEmpty(p["tiporesidencia"].ToString()) ? null : new TipoResidencia?((TipoResidencia)int.Parse(p["tiporesidencia"].ToString()))); - perfil.KmMensal = p["quilometragemmensal"].ToString(); - perfil.DistanciaResidenciaTrabalho = (string.IsNullOrEmpty(p["distanciaresidenciatrabalho"].ToString()) ? null : new DistanciaTrabalho?((DistanciaTrabalho)int.Parse(p["distanciaresidenciatrabalho"].ToString()))); - if (string.IsNullOrEmpty(p["usoprofissional"].ToString())) - { - nullable1 = null; - nullable4 = nullable1; - } - else - { - nullable4 = new bool?(p["usoprofissional"].ToString() == "1"); - } - perfil.UsoProfissional = nullable4; - perfil.UsoDependentes = (string.IsNullOrEmpty(p["usodependentes"].ToString()) ? null : new UsoDependetes?((UsoDependetes)int.Parse(p["usodependentes"].ToString()))); - perfil.Ocupacao = (string.IsNullOrEmpty(p["ocupacao"].ToString()) ? null : new Ocupacao?((Ocupacao)int.Parse(p["ocupacao"].ToString()))); - if (string.IsNullOrEmpty(p["segurovida"].ToString())) - { - nullable1 = null; - nullable5 = nullable1; - } - else - { - nullable5 = new bool?(p["segurovida"].ToString() == "1"); - } - perfil.SeguroVida = nullable5; - perfil.EstenderCobertura = (bool?)p["EstenderCobertura"]; - if (string.IsNullOrEmpty(p["isencao"].ToString())) - { - nullable1 = null; - nullable6 = nullable1; - } - else - { - nullable6 = new bool?(p["isencao"].ToString() == "1"); - } - perfil.Isencao = nullable6; - perfil.AntiFurto = (string.IsNullOrEmpty(p["antifurto"].ToString()) ? null : new Antifurto?((Antifurto)int.Parse(p["antifurto"].ToString()))); - return perfil; - }).ToList(); - } - - public Perfil Merge(Perfil perfil) - { - PerfilDb perfilDb = ApplicationMapper.Mapper.Map(perfil); - base.Merge(perfilDb); - return ApplicationMapper.Mapper.Map(perfilDb); - } - - public Perfil SaveOrUpdate(Perfil perfil) - { - PerfilDb perfilDb = ApplicationMapper.Mapper.Map(perfil); - this.SaveOrUpdate(perfilDb); - return ApplicationMapper.Mapper.Map(perfilDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs deleted file mode 100644 index 50201a9..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs +++ /dev/null @@ -1,54 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -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.Seguros; -using NHibernate; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class PermissaoArquivoDigitalRepository : GenericRepository, IPermissaoArquivoDigitalRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public PermissaoArquivoDigitalRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public PermissaoArquivoDigital FindByPermissao(long id, TipoArquivoDigital tela) - { - PermissaoArquivoDigitalDb permissaoArquivoDigitalDb = base.All().FirstOrDefault((PermissaoArquivoDigitalDb x) => x.Usuario.Id == id && (int)x.Tela == (int)tela); - return ApplicationMapper.Mapper.Map(permissaoArquivoDigitalDb); - } - - public List FindByUsuario(long id) - { - List list = this._unitOfWork.Session.CreateQuery(string.Format("from PermissaoArquivoDigitalDb WHERE IdUsuario = {0}", id)).List().ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public PermissaoArquivoDigital Merge(PermissaoArquivoDigital permissao) - { - PermissaoArquivoDigitalDb permissaoArquivoDigitalDb = ApplicationMapper.Mapper.Map(permissao); - base.Merge(permissaoArquivoDigitalDb); - return ApplicationMapper.Mapper.Map(permissaoArquivoDigitalDb); - } - - public PermissaoArquivoDigital SaveOrUpdate(PermissaoArquivoDigital permissao) - { - PermissaoArquivoDigitalDb permissaoArquivoDigitalDb = ApplicationMapper.Mapper.Map(permissao); - this.SaveOrUpdate(permissaoArquivoDigitalDb); - return ApplicationMapper.Mapper.Map(permissaoArquivoDigitalDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs deleted file mode 100644 index e0e226c..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs +++ /dev/null @@ -1,84 +0,0 @@ -using AutoMapper; -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.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class PermissaoUsuarioRepository : GenericRepository, IPermissaoUsuarioRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public PermissaoUsuarioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public PermissaoUsuario FindByPermissao(long id, TipoTela tela) - { - return this.Select(string.Format(" AND IdUsuario = {0} AND Tela = {1}", id, (int)tela)).FirstOrDefault(); - } - - public List FindByUsuario(long id) - { - return this.Select(string.Format(" AND IdUsuario = {0}", id)); - } - - public PermissaoUsuario Merge(PermissaoUsuario permissao) - { - PermissaoUsuarioDb permissaoUsuarioDb = ApplicationMapper.Mapper.Map(permissao); - base.Merge(permissaoUsuarioDb); - return ApplicationMapper.Mapper.Map(permissaoUsuarioDb); - } - - public PermissaoUsuario SaveOrUpdate(PermissaoUsuario permissao) - { - PermissaoUsuarioDb permissaoUsuarioDb = ApplicationMapper.Mapper.Map(permissao); - this.SaveOrUpdate(permissaoUsuarioDb); - return ApplicationMapper.Mapper.Map(permissaoUsuarioDb); - } - - private List Select(string condition) - { - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliarUsuario(sqlCommand); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT * FROM PermissaoUsuario WHERE 1=1 ", condition, ";"); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return dataTable.MapPermissao(); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs deleted file mode 100644 index 47044d1..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs +++ /dev/null @@ -1,93 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Financeiro; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Financeiro; -using Gestor.Model.Domain.Generic; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class PlanoRepository : GenericRepository, IPlanoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public PlanoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List Find(string filter) - { - PlanoRepository.u003cu003ec__DisplayClass2_0 variable = null; - IQueryable planoDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(PlanoDb), "x"); - IQueryable planoDbs1 = planoDbs.Where(Expression.Lambda>(Expression.AndAlso(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(PlanoDb).GetMethod("get_Ativo").MethodHandle)), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(PlanoDb).GetMethod("get_Descricao").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(PlanoRepository.u003cu003ec__DisplayClass2_0)), FieldInfo.GetFieldFromHandle(typeof(PlanoRepository.u003cu003ec__DisplayClass2_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(PlanoDb), "x"); - return planoDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Plano)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Plano).GetMethod("set_Descricao", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(PlanoDb).GetMethod("get_Descricao").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Plano).GetMethod("set_Ativo", new Type[] { typeof(bool) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(PlanoDb).GetMethod("get_Ativo").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); - } - - public List Find() - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT DISTINCT idcplano as id, descricao as nome, ativo FROM cplano;"; - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return ( - from a in dataTable.AsEnumerable().ToList() - select new Plano() - { - Id = a.Field("id"), - Descricao = a.Field("nome"), - Ativo = (a.Field("ativo") == null ? true : a.Field("ativo").ToString() == "1") - }).ToList(); - } - - public Plano Merge(Plano plano) - { - PlanoDb planoDb = ApplicationMapper.Mapper.Map(plano); - base.Merge(planoDb); - return ApplicationMapper.Mapper.Map(planoDb); - } - - public Plano SaveOrUpdate(Plano plano) - { - PlanoDb planoDb = ApplicationMapper.Mapper.Map(plano); - this.SaveOrUpdate(planoDb); - return ApplicationMapper.Mapper.Map(planoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs deleted file mode 100644 index d76619d..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs +++ /dev/null @@ -1,101 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Financeiro; -using Gestor.Infrastructure.Entities.Generic; -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.Domain.Financeiro; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class PlanosRepository : GenericRepository, IPlanosRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public PlanosRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List Find(string description) - { - PlanosRepository.u003cu003ec__DisplayClass3_0 variable = null; - IQueryable planosDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(PlanosDb), "x"); - List list = planosDbs.Where(Expression.Lambda>(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(PlanosDb).GetMethod("get_Descricao").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(PlanosRepository.u003cu003ec__DisplayClass3_0)), FieldInfo.GetFieldFromHandle(typeof(PlanosRepository.u003cu003ec__DisplayClass3_0).GetField("description").FieldHandle)) }), new ParameterExpression[] { parameterExpression })).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List Find() - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - AuxiliarFinanceiro.Criar(sqlCommand); - sqlCommand.CommandText = "SELECT DISTINCT cs.idcplanos as id, cs.descricao as nome, cs.ativo, cs.idcplano, cs.idtipoconta, cs.ctipo, cp.descricao FROM cplanos cs INNER JOIN cplano cp ON cs.idcplano = cp.idcplano;"; - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return CustomMap.MapPlanos(dataTable); - } - - public Planos FindById(long id) - { - PlanosDb planosDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(planosDb); - } - - public List FindByPlanoId(long id) - { - List list = ( - from x in base.All() - where x.Plano.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Planos Merge(Planos planos) - { - PlanosDb planosDb = ApplicationMapper.Mapper.Map(planos); - base.Merge(planosDb); - return ApplicationMapper.Mapper.Map(planosDb); - } - - public Planos SaveOrUpdate(Planos planos) - { - PlanosDb planosDb = ApplicationMapper.Mapper.Map(planos); - this.SaveOrUpdate(planosDb); - return ApplicationMapper.Mapper.Map(planosDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs deleted file mode 100644 index 472ec21..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs +++ /dev/null @@ -1,76 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ProdutoRepository : GenericRepository, IProdutoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ProdutoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find(string value) - { - ProdutoRepository.u003cu003ec__DisplayClass6_0 variable = null; - IQueryable produtoDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(ProdutoDb), "x"); - IQueryable produtoDbs1 = produtoDbs.Where(Expression.Lambda>(Expression.OrElse(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProdutoDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(ProdutoRepository.u003cu003ec__DisplayClass6_0)), FieldInfo.GetFieldFromHandle(typeof(ProdutoRepository.u003cu003ec__DisplayClass6_0).GetField("value").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProdutoDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(ProdutoRepository.u003cu003ec__DisplayClass6_0)), FieldInfo.GetFieldFromHandle(typeof(ProdutoRepository.u003cu003ec__DisplayClass6_0).GetField("value").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(ProdutoDb), "x"); - return produtoDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Produto)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Produto).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProdutoDb).GetMethod("get_Nome").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); - } - - public List Find() - { - return ( - from x in this._unitOfWork.Session.CreateQuery("from ProdutoDb").List() - select new Produto() - { - Id = x.Id, - Nome = x.Nome, - Ativo = x.Ativo - }).ToList(); - } - - public Produto FindById(long id) - { - ProdutoDb produtoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(produtoDb); - } - - public Produto Merge(Produto produto) - { - ProdutoDb produtoDb = ApplicationMapper.Mapper.Map(produto); - base.Merge(produtoDb); - return ApplicationMapper.Mapper.Map(produtoDb); - } - - public Produto SaveOrUpdate(Produto produto) - { - ProdutoDb produtoDb = ApplicationMapper.Mapper.Map(produto); - this.SaveOrUpdate(produtoDb); - return ApplicationMapper.Mapper.Map(produtoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs deleted file mode 100644 index f251e6e..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs +++ /dev/null @@ -1,92 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Common; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Common; -using Gestor.Model.Domain.Generic; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ProfissaoRepository : GenericRepository, IProfissaoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ProfissaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List Find(string filter) - { - ProfissaoRepository.u003cu003ec__DisplayClass5_0 variable = null; - IQueryable profissaoDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(ProfissaoDb), "x"); - IQueryable profissaoDbs1 = profissaoDbs.Where(Expression.Lambda>(Expression.OrElse(Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProfissaoDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(ProfissaoRepository.u003cu003ec__DisplayClass5_0)), FieldInfo.GetFieldFromHandle(typeof(ProfissaoRepository.u003cu003ec__DisplayClass5_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProfissaoDb).GetMethod("get_Codigo").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(ProfissaoRepository.u003cu003ec__DisplayClass5_0)), FieldInfo.GetFieldFromHandle(typeof(ProfissaoRepository.u003cu003ec__DisplayClass5_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(ProfissaoDb), "x"); - return profissaoDbs1.Select(Expression.Lambda>(Expression.MemberInit(Expression.New(typeof(Profissao)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Profissao).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProfissaoDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Profissao).GetMethod("set_Codigo", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(ProfissaoDb).GetMethod("get_Codigo").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList(); - } - - public long FindLastId() - { - long num; - object connection; - SqlCommand sqlCommand; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - sqlCommand = sqlConnection.CreateCommand(); - } - else - { - sqlCommand = null; - } - using (SqlCommand sqlCommand1 = sqlCommand) - { - sqlCommand1.CommandText = "SELECT MAX(idprofissao) as id FROM profissao"; - SqlDataReader sqlDataReader = sqlCommand1.ExecuteReader(); - sqlDataReader.Read(); - object item = sqlDataReader["id"]; - num = (sqlDataReader["id"] == null || sqlDataReader["id"].ToString() == "" || sqlDataReader["id"].ToString() == "{}" ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); - } - } - return num; - } - - public Profissao Merge(Profissao profissao) - { - ProfissaoDb profissaoDb = ApplicationMapper.Mapper.Map(profissao); - base.Merge(profissaoDb); - return ApplicationMapper.Mapper.Map(profissaoDb); - } - - public Profissao SaveOrUpdate(Profissao profissao) - { - ProfissaoDb profissaoDb = ApplicationMapper.Mapper.Map(profissao); - this.SaveOrUpdate(profissaoDb); - return ApplicationMapper.Mapper.Map(profissaoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs deleted file mode 100644 index 8b4909c..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs +++ /dev/null @@ -1,245 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -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.Relatorios; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ProspectRepository : GenericRepository, IProspectRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ProspectRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - ProspeccaoDb prospeccaoDb = base.FindEntityById(id); - if (prospeccaoDb == null) - { - return; - } - base.Delete(prospeccaoDb); - } - - public List Find(long idempresa, long id, DateTime inicio, DateTime fim, StatusProspeccao? status) - { - VendedorDb vendedorDb = this._unitOfWork.Query().First((VendedorDb x) => x.Corretora); - List prospeccaoDbs = new List(); - if (status.HasValue) - { - if (idempresa == 0 && id == 0) - { - prospeccaoDbs = ( - from x in base.All() - where (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) && (int?)x.Status == (int?)status - select x).ToList(); - } - if (idempresa == 0 && id > (long)0) - { - prospeccaoDbs = ( - from x in base.All() - where x.Vendedor.Id == id && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) && (int?)x.Status == (int?)status - select x).ToList(); - } - if (idempresa > (long)0 && id == 0) - { - prospeccaoDbs = ( - from x in base.All() - where x.IdEmpresa == idempresa && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) && (int?)x.Status == (int?)status - select x).ToList(); - } - if (idempresa > (long)0 && id > (long)0) - { - prospeccaoDbs = ( - from x in base.All() - where x.IdEmpresa == idempresa && x.Vendedor.Id == id && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) && (int?)x.Status == (int?)status - select x).ToList(); - } - } - else - { - if (idempresa == 0 && id == 0) - { - prospeccaoDbs = ( - from x in base.All() - where (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) - select x).ToList(); - } - if (idempresa == 0 && id > (long)0) - { - prospeccaoDbs = ( - from x in base.All() - where x.Vendedor.Id == id && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) - select x).ToList(); - } - if (idempresa > (long)0 && id == 0) - { - prospeccaoDbs = ( - from x in base.All() - where x.IdEmpresa == idempresa && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) - select x).ToList(); - } - if (idempresa > (long)0 && id > (long)0) - { - prospeccaoDbs = ( - from x in base.All() - where x.IdEmpresa == idempresa && x.Vendedor.Id == id && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) - select x).ToList(); - } - } - foreach (ProspeccaoDb prospeccaoDb in prospeccaoDbs) - { - if (prospeccaoDb.Vendedor == null || prospeccaoDb.Vendedor.Id == 0) - { - prospeccaoDb.Vendedor = vendedorDb; - } - bool? renovacao = prospeccaoDb.Renovacao; - prospeccaoDb.Renovacao = new bool?(renovacao.GetValueOrDefault(true)); - } - return ApplicationMapper.Mapper.Map, List>(prospeccaoDbs); - } - - public List Find(Filtros filtro) - { - List prospeccaoDbs; - VendedorDb vendedorDb = this._unitOfWork.Query().First((VendedorDb x) => x.Corretora); - List statusProspeccaos = new List() - { - StatusProspeccao.Agendado, - StatusProspeccao.EmAndamento, - StatusProspeccao.NaoTrabalhado, - StatusProspeccao.Perdido, - StatusProspeccao.Ganho - }; - if (filtro.Status != null && filtro.Status.Count > 0) - { - statusProspeccaos.RemoveAll((StatusProspeccao x) => true); - if (filtro.Status.Contains((long)1) || filtro.Status.Contains((long)2)) - { - statusProspeccaos.Add(StatusProspeccao.Agendado); - statusProspeccaos.Add(StatusProspeccao.NaoTrabalhado); - statusProspeccaos.Add(StatusProspeccao.EmAndamento); - } - if (filtro.Status.Contains((long)6)) - { - statusProspeccaos.Add(StatusProspeccao.Perdido); - } - if (filtro.Status.Contains((long)5)) - { - statusProspeccaos.Add(StatusProspeccao.Ganho); - } - } - prospeccaoDbs = (filtro.Vendedores == null || filtro.Vendedores.Count <= 0 ? ( - from x in base.All() - where (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)filtro.Inicio) && (x.VigenciaFinal <= (DateTime?)filtro.Fim) && statusProspeccaos.Contains(x.Status.Value) - select x).ToList() : ( - from x in base.All() - where filtro.Vendedores.Contains(x.Vendedor.Id) && (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)filtro.Inicio) && (x.VigenciaFinal <= (DateTime?)filtro.Fim) && statusProspeccaos.Contains(x.Status.Value) - select x).ToList()); - foreach (ProspeccaoDb nullable in prospeccaoDbs) - { - if (nullable.Vendedor == null || nullable.Vendedor.Id == 0) - { - nullable.Vendedor = vendedorDb; - } - bool? renovacao = nullable.Renovacao; - nullable.Renovacao = new bool?(renovacao.GetValueOrDefault(true)); - } - prospeccaoDbs = (filtro.IdEmpresa == 0 ? prospeccaoDbs : ( - from x in prospeccaoDbs - where x.IdEmpresa == filtro.IdEmpresa - select x).ToList()); - return ApplicationMapper.Mapper.Map, List>(prospeccaoDbs); - } - - public List FindByData(DateTime inicio, DateTime fim) - { - List list = ( - from x in base.All() - where (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim) - select x).ToList(); - list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true))); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Prospeccao FindById(long id) - { - ProspeccaoDb nullable = base.FindEntityById(id); - if (nullable != null) - { - bool? renovacao = nullable.Renovacao; - nullable.Renovacao = new bool?(renovacao.GetValueOrDefault(true)); - } - return ApplicationMapper.Mapper.Map(nullable); - } - - public List FindByStatus(StatusProspeccao status) - { - List list = ( - from x in base.All() - where (int?)x.Status == (int?)status - select x).ToList(); - list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true))); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindByStatusPersonalizado(long statusId) - { - List list = ( - from x in base.All() - where x.StatusPersonalizado.Id == statusId - select x).ToList(); - list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true))); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Prospeccao FindByTarefa(long id) - { - ProspeccaoDb nullable = base.All().FirstOrDefault((ProspeccaoDb x) => x.Tarefa.Id == id); - if (nullable != null) - { - bool? renovacao = nullable.Renovacao; - nullable.Renovacao = new bool?(renovacao.GetValueOrDefault(true)); - } - return ApplicationMapper.Mapper.Map(nullable); - } - - public List FindByVendedor(long id) - { - List list = ( - from x in base.All() - where x.Vendedor.Id == id - select x).ToList(); - list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true))); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Prospeccao Merge(Prospeccao prospeccao) - { - ProspeccaoDb prospeccaoDb = ApplicationMapper.Mapper.Map(prospeccao); - base.Merge(prospeccaoDb); - return ApplicationMapper.Mapper.Map(prospeccaoDb); - } - - public Prospeccao SaveOrUpdate(Prospeccao prospeccao) - { - ProspeccaoDb prospeccaoDb = ApplicationMapper.Mapper.Map(prospeccao); - this.SaveOrUpdate(prospeccaoDb); - return ApplicationMapper.Mapper.Map(prospeccaoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs deleted file mode 100644 index e8c621b..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs +++ /dev/null @@ -1,38 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class QualificacaoRepository : GenericRepository, IQualificacaoRepository, IGenericRepository - { - public QualificacaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - } - - public Qualificacao FindById(long id) - { - QualificacaoDb qualificacaoDb = base.FindEntityById(id) ?? new QualificacaoDb(); - return ApplicationMapper.Mapper.Map(qualificacaoDb); - } - - public Qualificacao Merge(Qualificacao qualificacao) - { - QualificacaoDb qualificacaoDb = ApplicationMapper.Mapper.Map(qualificacao); - base.Merge(qualificacaoDb); - return ApplicationMapper.Mapper.Map(qualificacaoDb); - } - - public Qualificacao SaveOrUpdate(Qualificacao qualificacao) - { - QualificacaoDb qualificacaoDb = ApplicationMapper.Mapper.Map(qualificacao); - this.SaveOrUpdate(qualificacaoDb); - return ApplicationMapper.Mapper.Map(qualificacaoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs deleted file mode 100644 index 563c6bf..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs +++ /dev/null @@ -1,85 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class RamoRepository : GenericRepository, IRamoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public RamoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List Find(bool ativo) - { - return ( - from x in this._unitOfWork.Session.CreateQuery("from RamoDb \r\n where ativo IS NULL OR ativo != '1'").List() - select new Ramo() - { - Id = x.Id, - Nome = x.Nome, - Iof = x.Iof, - Ativo = x.Ativo - }).ToList(); - } - - public List Find() - { - return ( - from x in this._unitOfWork.Session.CreateQuery("from RamoDb").List() - select new Ramo() - { - Id = x.Id, - Nome = x.Nome, - Iof = x.Iof, - Ativo = x.Ativo - }).ToList(); - } - - public Ramo FindById(long id) - { - RamoDb ramoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(ramoDb); - } - - public Ramo Merge(Ramo ramo) - { - RamoDb ramoDb = ApplicationMapper.Mapper.Map(ramo); - base.Merge(ramoDb); - return ApplicationMapper.Mapper.Map(ramoDb); - } - - public List MergeRange(List ramos) - { - List ramoDbs = ApplicationMapper.Mapper.Map, List>(ramos); - RamoRepository ramoRepository = this; - ramoDbs.ForEach(new Action(ramoRepository.Merge)); - return ApplicationMapper.Mapper.Map, List>(ramoDbs); - } - - public Ramo SaveOrUpdate(Ramo ramo) - { - RamoDb ramoDb = ApplicationMapper.Mapper.Map(ramo); - this.SaveOrUpdate(ramoDb); - return ApplicationMapper.Mapper.Map(ramoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs deleted file mode 100644 index cff93a5..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs +++ /dev/null @@ -1,71 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Ferramentas; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ReciboRepository : GenericRepository, IReciboRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ReciboRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List BuscarRecibos() - { - List list = base.All().ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public void Delete(long id) - { - ReciboDb reciboDb = base.FindEntityById(id); - if (reciboDb == null) - { - return; - } - base.Delete(reciboDb); - } - - public void DeleteRange(List ids) - { - List list = ( - from x in base.All() - where ids.Contains(x.Id) - select x).ToList(); - base.DeleteRange(list); - } - - public Recibo FindById(long id) - { - ReciboDb reciboDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(reciboDb); - } - - public Recibo Merge(Recibo recibo) - { - ReciboDb reciboDb = ApplicationMapper.Mapper.Map(recibo); - base.Merge(reciboDb); - return ApplicationMapper.Mapper.Map(reciboDb); - } - - public Recibo SaveOrUpdate(Recibo recibo) - { - ReciboDb reciboDb = ApplicationMapper.Mapper.Map(recibo); - this.SaveOrUpdate(reciboDb); - return ApplicationMapper.Mapper.Map(reciboDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs deleted file mode 100644 index 158bcb9..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs +++ /dev/null @@ -1,183 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Common; -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.Common; -using Gestor.Model.Domain.Relatorios; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class RegistroAcaoRepository : GenericRepository, IRegistroAcaoRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public RegistroAcaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - RegistroAcaoDb registroAcaoDb = base.FindEntityById(id); - if (registroAcaoDb == null) - { - return; - } - base.Delete(registroAcaoDb); - } - - public List Find(Filtros filtros) - { - return this.Select(filtros); - } - - public List FindByEntityId(long id, TipoTela tela) - { - List list = ( - from x in base.All() - where x.EntidadeId == id && (int?)x.Tela == (int?)tela - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public RegistroAcao FindById(long id) - { - RegistroAcaoDb registroAcaoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(registroAcaoDb); - } - - public List FindOld(Filtros filtros, string connection) - { - return this.SelectOld(filtros, connection); - } - - public RegistroAcao SaveOrUpdate(RegistroAcao log) - { - RegistroAcaoDb registroAcaoDb = ApplicationMapper.Mapper.Map(log); - this.SaveOrUpdate(registroAcaoDb); - return ApplicationMapper.Mapper.Map(registroAcaoDb); - } - - private List Select(Filtros filtros) - { - List registroAcaos; - object connection; - DataTable dataTable = new DataTable(); - string str = (filtros.Usuarios == null || filtros.Usuarios.Count == 0 ? "" : string.Concat(" AND IdUsuario IN (", string.Join(",", - from v in filtros.Usuarios - select v), ")")); - string str1 = (filtros.Telas == null || filtros.Telas.Count == 0 ? "" : string.Concat(" AND Tela IN (", string.Join(",", - from v in filtros.Telas - select v), ")")); - string str2 = (filtros.Relatorios == null || filtros.Relatorios.Count == 0 ? "" : string.Concat(" AND Relatorio IN (", string.Join(",", - from v in filtros.Relatorios - select v), ")")); - string str3 = (filtros.Inicio == DateTime.MinValue ? "" : string.Format(" AND CAST(DataHora AS DATE) >= '{0:yyyy-MM-dd}'", filtros.Inicio)); - string str4 = (filtros.Fim == DateTime.MinValue ? "" : string.Format(" AND CAST(DataHora AS DATE) <= '{0:yyyy-MM-dd}'", filtros.Fim)); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat(new string[] { "SELECT * FROM RegistroAcao WHERE 1=1 ", str3, str4, str, str1, str2 }); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - return CustomMap.MapLogAcao(dataTable); - } - else - { - registroAcaos = new List(); - } - } - } - return registroAcaos; - } - - private List SelectOld(Filtros filtros, string conn) - { - List registroAcaos; - object connection; - try - { - DataTable dataTable = new DataTable(); - string str = (filtros.Usuarios == null || filtros.Usuarios.Count == 0 ? "" : string.Concat(" AND IDUSUARIO IN (", string.Join(",", - from v in filtros.Usuarios - select v), ")")); - string str1 = (filtros.Inicio == DateTime.MinValue ? "" : string.Format(" AND CAST(DATA AS DATE) >= '{0:yyyy-MM-dd}'", filtros.Inicio)); - string str2 = (filtros.Fim == DateTime.MinValue ? "" : string.Format(" AND CAST(DATA AS DATE) <= '{0:yyyy-MM-dd}'", filtros.Fim)); - 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 = "SELECT TOP 1 * FROM controlelog"; - SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); - sqlDataReader.Read(); - string str3 = sqlDataReader["bdname"].ToString(); - sqlDataReader["tabela"].ToString(); - sqlDataReader.Close(); - if (sqlConnection.Database != str3) - { - conn = conn.Replace(sqlConnection.Database, str3); - } - } - } - using (SqlConnection sqlConnection1 = new SqlConnection(conn)) - { - sqlConnection1.Open(); - using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand()) - { - sqlCommand1.CommandTimeout = 15000; - sqlCommand1.CommandText = string.Concat("SELECT IDACTION, ID, FORM, IDUSUARIO, DATA, ACAO, historico, maquina FROM actionlog WHERE 1=1 ", str1, str2, str); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand1; - sqlDataAdapter.Fill(dataTable); - } - } - } - registroAcaos = (dataTable.Rows.Count != 0 ? CustomMap.MapOldLogAcao(dataTable) : new List()); - } - catch (Exception exception) - { - registroAcaos = new List(); - } - return registroAcaos; - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs deleted file mode 100644 index a57c17e..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs +++ /dev/null @@ -1,222 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Common; -using Gestor.Infrastructure.Entities.Ferramentas; -using Gestor.Infrastructure.Entities.Generic; -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.Common; -using Gestor.Model.Domain.Ferramentas; -using Gestor.Model.Domain.Relatorios; -using Gestor.Model.Domain.Relatorios.LogsEnvio; -using Gestor.Model.Validation; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class RegistroLogRepository : GenericRepository, IRegistroLogRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public RegistroLogRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void AddRange(List registrosLog) - { - base.AddRange(ApplicationMapper.Mapper.Map, List>(registrosLog)); - } - - public List BuscaLogParcelas(List entidadeId) - { - return this.Select((new List() - { - new Condicao() - { - Campo = "Tela", - Valores = 5.CriarValor() - }, - new Condicao() - { - Campo = "EntidadeId", - Valores = entidadeId.CriarValor() - } - }).CreateParameters(0)); - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List FindByCredential(long id) - { - List list = ( - from x in this._unitOfWork.Query() - where x.Credencial.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindByEntity(TipoTela tela, long id) - { - List list = ( - from x in this._unitOfWork.Query() - where x.EntityId == id && (int)x.Tela == (int)tela - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindByEntityId(TipoTela tela, long entidadeId) - { - List condicaos = new List() - { - new Condicao() - { - Campo = "Tela", - Valores = tela.CriarValor() - } - }; - Condicao condicao = new Condicao() - { - Campo = "EntidadeId", - Valores = entidadeId.CriarValor() - }; - if (tela != TipoTela.Configuracoes) - { - condicaos.Add(condicao); - } - return this.Select(condicaos.CreateParameters(0)); - } - - public RegistroLog FindById(long id) - { - RegistroLogDb registroLogDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map(registroLogDb); - } - - public List FindByIdSingle(long id) - { - List list = ( - from x in this._unitOfWork.Query() - where x.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List FindByUser(TipoTela tela, long idUsuario) - { - return this.Select((new List() - { - new Condicao() - { - Campo = "IdUsuario", - Valores = idUsuario.CriarValor() - }, - new Condicao() - { - Campo = "Tela", - Valores = 0.CriarValor(), - Operacao = Operacao.Or, - Grupo = 1 - }, - new Condicao() - { - Campo = "Tela", - Valores = tela.CriarValor(), - Operacao = Operacao.Or, - Grupo = 1 - } - }).CreateParameters(0)); - } - - public List FindByUsuario(long id) - { - List list = ( - from x in this._unitOfWork.Query() - where x.Usuario.Id == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public List LogsEnvio(Filtros filtro) - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - Auxiliar.CriarAuxiliar(sqlCommand, false); - sqlCommand.CommandText = string.Concat("SELECT e.email as emailenvio, u.nome as usuarionome, l.id as id, l.tela as tela, l.data as data, l.destinatarios as destinatarios, l.assunto as assunto, l.cco as cco, l.versao as versao, l.nomemaquina as nomemaquina, l.usuariomaquina as usuariomaquina, l.ip as ip FROM LogEmail l INNER JOIN enviosmtp e on e.idenviosmtp = l.Credencial_id INNER JOIN usuario u on u.idusuario = l.Usuario_id ", string.Format("AND CAST(l.data AS DATE) >= '{0:yyyy-MM-dd}' AND CAST(l.data as DATE) <= '{1:yyyy-MM-dd}'", filtro.Inicio, filtro.Fim)); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - } - return dataTable.AsEnumerable().Select((DataRow x) => new LogsEnvio() - { - Id = x.Campo("id"), - Tela = x.Campo("tela").GetDescription(), - Assunto = x.Campo("assunto"), - Destinatarios = x.Campo("destinatarios").Replace(";", ";\n"), - Data = x.Campo("data"), - Ip = x.Campo("ip"), - Versao = x.Campo("versao"), - Cco = x.Campo("cco").Replace(";", ";\n"), - Maquina = x.Campo("nomemaquina"), - UsuarioMaquina = x.Campo("usuariomaquina"), - UsuarioAgger = x.Campo("usuarionome"), - Remetente = x.Campo("emailenvio") - }).ToList(); - } - - public RegistroLog SaveOrUpdate(RegistroLog registroLog) - { - RegistroLogDb registroLogDb = ApplicationMapper.Mapper.Map(registroLog); - this.SaveOrUpdate(registroLogDb); - return ApplicationMapper.Mapper.Map(registroLogDb); - } - - public LogEmail SaveOrUpdate(LogEmail log) - { - LogEmailDb logEmailDb = ApplicationMapper.Mapper.Map(log); - this._unitOfWork.Repository().SaveOrUpdate(logEmailDb); - return ApplicationMapper.Mapper.Map(logEmailDb); - } - - private List Select(SqlQueryCondition sqlCondition) - { - return this._unitOfWork.Select(sqlCondition, "SELECT DISTINCT * FROM RegistroLog WHERE", "").MapRegistroLog(); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs deleted file mode 100644 index 861ac85..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs +++ /dev/null @@ -1,298 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -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.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class RepasseRepository : GenericRepository, IRepasseRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public RepasseRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List DefaultSelect(long idempresa = 0L) - { - List repasses; - object connection; - List nums = null; - Func func1 = null; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarVendedor(sqlCommand, true); - Auxiliar.LoadTipoVendedor(sqlCommand); - List condicaos = new List() - { - new Condicao() - { - Campo = "idempresa", - Valores = idempresa.CriarValor() - } - }; - string str = "SELECT * FROM repasse WHERE "; - string str1 = "SELECT * FROM VinculoRepasse WHERE "; - List condicaos1 = new List() - { - new Condicao() - { - Campo = "1", - Valores = "1".CriarValor() - } - }; - if (idempresa > (long)0) - { - condicaos1.AddRange(condicaos); - } - dataTable = sqlCommand.Select(condicaos1.CreateParameters(0), str, ""); - if (dataTable.Rows.Count != 0) - { - for (List i = dataTable.AsEnumerable().Select((DataRow x) => x.Field("idrepasse")).Distinct().ToList(); i.Count > 0; i = nums) - { - List nums1 = i.Take(2000).ToList(); - List condicaos2 = new List() - { - new Condicao() - { - Campo = "IdRepasse", - Valores = nums1.CriarValor() - } - }; - DataTable dataTable2 = sqlCommand.Select(condicaos2.CreateParameters(0), str1, ""); - dataTable1.Merge(dataTable2); - nums = (nums1.Count < 2000 ? new List() : i.Except(nums1).ToList()); - } - List repasses1 = dataTable.AsEnumerable().Select((DataRow x) => { - long? nullable1; - long? nullable2; - Repasse repasse = new Repasse() - { - Id = x.Field("idrepasse"), - Ativo = (x.Field("ativo") == null ? true : x.Field("ativo").ToString() != "0"), - Base = (x.Field("base") == null ? null : new BaseRepasse?((BaseRepasse)Enum.Parse(typeof(BaseRepasse), x.Field("base").ToString()))), - Forma = (x.Field("forma") == null ? null : new FormaRepasse?((FormaRepasse)Enum.Parse(typeof(FormaRepasse), x.Field("forma").ToString()))), - Incidencia = (x.Field("incidencia") == null ? null : new TipoIncidencia?((TipoIncidencia)Enum.Parse(typeof(TipoIncidencia), x.Field("incidencia").ToString()))), - Tipo = (x.Field("tipo") == null ? null : new TipoRepasse?((TipoRepasse)Enum.Parse(typeof(TipoRepasse), x.Field("tipo").ToString()))) - }; - decimal? nullable3 = x.Field("vlrnovo"); - repasse.ValorNovo = nullable3.GetValueOrDefault(); - nullable3 = x.Field("vlrrenovacao"); - repasse.ValorRenovacao = nullable3.GetValueOrDefault(); - repasse.Vendedor = Auxiliar.Vendedores.FirstOrDefault((Vendedor z) => z.Id == x.Field("idvendedor")); - repasse.Ramo = (x.Field("idramo") == null ? null : Auxiliar.Ramos.FirstOrDefault((Ramo z) => { - long id = z.Id; - long? nullable = x.Field("idramo"); - return id == nullable.GetValueOrDefault() & nullable.HasValue; - })); - if (x.Field("idciaseg") == null) - { - nullable1 = null; - nullable2 = nullable1; - } - else - { - Seguradora seguradora = Auxiliar.Seguradoras.FirstOrDefault((Seguradora z) => { - long id = z.Id; - long? nullable = x.Field("idciaseg"); - return id == nullable.GetValueOrDefault() & nullable.HasValue; - }); - if (seguradora != null) - { - nullable2 = new long?(seguradora.Id); - } - else - { - nullable1 = null; - nullable2 = nullable1; - } - } - repasse.Seguradora = nullable2; - return repasse; - }).ToList(); - List repasses2 = ( - from x in repasses1 - where x.Ativo - select x).ToList(); - repasses2.ForEach((Repasse x) => { - Repasse list = x; - EnumerableRowCollection dataRows = dataTable1.AsEnumerable().Where((DataRow r) => r.Field("IdRepasse") == x.Id); - Func u003cu003e9_8 = func1; - if (u003cu003e9_8 == null) - { - Func vinculoRepasse = (DataRow v) => new VinculoRepasse() - { - Id = v.Field("Id"), - IdRepasse = v.Field("IdRepasse"), - RepasseVinculo = repasses1.Find((Repasse z) => z.Id == v.Field("RepasseVinculo_id")), - TipoVendedor = Auxiliar.TipoVendedores.Find((TipoVendedor z) => z.Id == v.Field("TipoVendedor_id")), - TipoVendedorVinculo = Auxiliar.TipoVendedores.Find((TipoVendedor z) => z.Id == v.Field("TipoVendedorVinculo_id")) - }; - Func func = vinculoRepasse; - func1 = vinculoRepasse; - u003cu003e9_8 = func; - } - list.Vinculo = dataRows.Select(u003cu003e9_8).ToList(); - }); - repasses = repasses2; - } - else - { - repasses = new List(); - } - } - } - return repasses; - } - - public void Delete(long id) - { - RepasseDb repasseDb = base.FindEntityById(id); - if (repasseDb == null) - { - return; - } - base.Delete(repasseDb); - } - - public void DeleteVinculo(long id) - { - VinculoRepasseDb vinculoRepasseDb = this._unitOfWork.Repository().FindEntityById(id); - if (vinculoRepasseDb == null) - { - return; - } - this._unitOfWork.Repository().Delete(vinculoRepasseDb); - } - - public Repasse FindById(long id) - { - List vinculoRepasses; - RepasseDb repasseDb = base.FindEntityById(id); - List vinculoRepasses1 = this.FindByRepasse(id); - Repasse repasse = ApplicationMapper.Mapper.Map(repasseDb); - if (vinculoRepasses1 == null || vinculoRepasses1.Count <= 0) - { - vinculoRepasses = null; - } - else - { - vinculoRepasses = vinculoRepasses1; - } - repasse.Vinculo = vinculoRepasses; - return repasse; - } - - public List FindByIdRepasse(long id) - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarVendedor(sqlCommand, false); - sqlCommand.CommandText = string.Format("SELECT idvendedorparcela FROM vendedorparcela WHERE idrepasse = {0}", id); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return dataTable.AsEnumerable().Select((DataRow x) => new VendedorParcela() - { - Id = x.Field("idvendedorparcela") - }).ToList(); - } - - public List FindByIdVendedor(long id) - { - List list = this._unitOfWork.Session.CreateQuery(string.Format("from RepasseDb \r\n where IdVendedor = {0}", id)).List().ToList(); - List repasses = ApplicationMapper.Mapper.Map, List>(list); - repasses.ForEach((Repasse x) => { - List vinculoRepasses = this.FindByRepasse(x.Id); - x.Vinculo = (vinculoRepasses == null || vinculoRepasses.Count <= 0 ? null : vinculoRepasses); - }); - return repasses; - } - - public List FindByRepasse(long id) - { - List list = ( - from x in this._unitOfWork.Query() - where x.IdRepasse == id - select x).ToList(); - return ApplicationMapper.Mapper.Map, List>(list); - } - - public Repasse Merge(Repasse repasse) - { - RepasseDb repasseDb = ApplicationMapper.Mapper.Map(repasse); - base.Merge(repasseDb); - return ApplicationMapper.Mapper.Map(repasseDb); - } - - public VinculoRepasse Merge(VinculoRepasse vinculo) - { - VinculoRepasseDb vinculoRepasseDb = ApplicationMapper.Mapper.Map(vinculo); - this._unitOfWork.Repository().Merge(vinculoRepasseDb); - return ApplicationMapper.Mapper.Map(vinculoRepasseDb); - } - - public Repasse SaveOrUpdate(Repasse repasse) - { - RepasseDb repasseDb = ApplicationMapper.Mapper.Map(repasse); - this.SaveOrUpdate(repasseDb); - return ApplicationMapper.Mapper.Map(repasseDb); - } - - public VinculoRepasse SaveOrUpdate(VinculoRepasse vinculo) - { - VinculoRepasseDb vinculoRepasseDb = ApplicationMapper.Mapper.Map(vinculo); - this._unitOfWork.Repository().SaveOrUpdate(vinculoRepasseDb); - return ApplicationMapper.Mapper.Map(vinculoRepasseDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs deleted file mode 100644 index 990e3a2..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs +++ /dev/null @@ -1,1991 +0,0 @@ -using Gestor.Common.Helpers; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Helpers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Common; -using Gestor.Model.Domain.Common; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Relatorios; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Runtime.CompilerServices; -using System.Text.RegularExpressions; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class ReportRepository : GenericRepository, IReportRepository, IGenericRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public ReportRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List PlanilhaCompleta(List ids, bool configFranquia, bool configSomaPremio) - { - object connection; - List nums = null; - List nums1 = null; - if (ids == null || ids.Count == 0) - { - return new List(); - } - 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 = new DataTable(); - DataTable dataTable7 = new DataTable(); - DataTable dataTable8 = new DataTable(); - DataTable dataTable9 = new DataTable(); - DataTable dataTable10 = new DataTable(); - DataTable dataTable11 = new DataTable(); - DataTable dataTable12 = new DataTable(); - DataTable dataTable13 = new DataTable(); - DataTable dataTable14 = new DataTable(); - DataTable dataTable15 = new DataTable(); - DataTable dataTable16 = new DataTable(); - DataTable dataTable17 = new DataTable(); - DataTable dataTable18 = new DataTable(); - DataTable dataTable19 = new DataTable(); - DataTable dataTable20 = 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 i1 = ids; i1.Count > 0; i1 = nums1) - { - List nums2 = i1.Take(2100).ToList(); - string str9 = string.Concat(" AND d.iddocumento IN (", string.Join(",", nums2), ")"); - DataTable table = new DataTable(); - string str10 = string.Concat("SELECT DISTINCT *, r.nome AS nomeRamo, cs.nome AS nomeCiaseg, ven.nome AS nomeVendedor, cl.idcodigobanco AS cliBanco, cl.agencia AS cliAgencia, cl.Conta AS cliConta, d.adinacomis as adinacomis, prod.nome as nomeProduto, c.idciasegant as idciasegant FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente INNER JOIN ramo r on r.idramo = c.idramo INNER JOIN ciaseg cs on cs.idciaseg = c.idciaseg OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp LEFT OUTER JOIN vendedor ven on ven.idvendedor = vp.idvendedor LEFT OUTER JOIN produto prod on prod.idproduto = c.idproduto WHERE 1=1 ", str9, " AND d.tiporecebimento = 1;"); - sqlCommand.CommandText = str10 ?? ""; - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlCommand.CommandTimeout = 3000; - sqlDataAdapter.Fill(table); - } - dataTable.Merge(table); - table = new DataTable(); - string str11 = string.Concat("SELECT d.idcontrole, d.pedadit, d.aditamento, d.ordem, pr_liq, pr_adic, pr_custo, pr_iof, pr_total FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole WHERE 1=1 AND c.idcontrole IN (SELECT d.idcontrole FROM documento d WHERE 1=1 ", str9, ")AND d.tiporecebimento = 1 AND d.ordem != 0 ORDER BY d.ordem"); - sqlCommand.CommandText = str11 ?? ""; - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(table); - } - dataTable16.Merge(table); - table = new DataTable(); - string str12 = string.Concat("SELECT d.iddocumento, ce.endereco, ce.numero, ce.uf, ce.bairro, ce.cep, ce.cidade, ce.ordem FROM cliendereco ce INNER JOIN cliente cl on cl.idcliente = ce.idcliente INNER JOIN controle c on c.idcliente = cl.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole WHERE 1=1 ", str9, ";"); - sqlCommand.CommandText = str12 ?? ""; - using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter()) - { - sqlDataAdapter2.SelectCommand = sqlCommand; - sqlDataAdapter2.Fill(table); - } - DataView defaultView = table.DefaultView; - defaultView.Sort = "ordem"; - table = defaultView.ToTable(); - dataTable4.Merge(table); - table = new DataTable(); - string str13 = string.Concat("SELECT d.iddocumento, email, cm.ordem FROM climail cm INNER JOIN cliente cl on cl.idcliente = cm.idcliente INNER JOIN controle c on c.idcliente = cl.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole WHERE 1=1 ", str9, " ;"); - sqlCommand.CommandText = str13 ?? ""; - using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter()) - { - sqlDataAdapter3.SelectCommand = sqlCommand; - sqlDataAdapter3.Fill(table); - } - DataView dataViews = table.DefaultView; - dataViews.Sort = "ordem"; - table = dataViews.ToTable(); - dataTable3.Merge(table); - table = new DataTable(); - string str14 = string.Concat("SELECT d.iddocumento, ddd, fone, ct.ordem FROM clitelefone ct INNER JOIN cliente cl on cl.idcliente = ct.idcliente INNER JOIN controle c on c.idcliente = cl.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole WHERE 1=1 ", str9, ";"); - sqlCommand.CommandText = str14 ?? ""; - using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter()) - { - sqlDataAdapter4.SelectCommand = sqlCommand; - sqlDataAdapter4.Fill(table); - } - DataView defaultView1 = table.DefaultView; - defaultView1.Sort = "ordem"; - table = defaultView1.ToTable(); - dataTable2.Merge(table); - table = new DataTable(); - string str15 = string.Concat("SELECT d.iddocumento, nome AS nomeEstipulante, CASE WHEN es.idestipulante = d.idestipulante THEN '1'WHEN es.idestipulante = d.idestipulante2 THEN '2'WHEN es.idestipulante = d.idestipulante3 THEN '3'WHEN es.idestipulante = d.idestipulante4 THEN '4'WHEN es.idestipulante = d.idestipulante5 THEN '5'ELSE 'N/A'END AS 'index'FROM estipulante es INNER JOIN documento d on es.idestipulante IN (d.idestipulante, d.idestipulante2, d.idestipulante3, d.idestipulante4, d.idestipulante5) WHERE 1=1 ", str9, ";"); - sqlCommand.CommandText = str15 ?? ""; - using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter()) - { - sqlDataAdapter5.SelectCommand = sqlCommand; - sqlDataAdapter5.Fill(table); - } - dataTable1.Merge(table); - table = new DataTable(); - string str16 = string.Concat("SELECT d.iddocumento, * FROM cliContato cc INNER JOIN cliente cl on cl.idcliente = cc.idcliente INNER JOIN controle c on c.idcliente = cl.idcliente INNER JOIN documento d on d.idcontrole = c.idcontrole WHERE 1=1 ", str9, ";"); - sqlCommand.CommandText = str16 ?? ""; - using (SqlDataAdapter sqlDataAdapter6 = new SqlDataAdapter()) - { - sqlDataAdapter6.SelectCommand = sqlCommand; - sqlDataAdapter6.Fill(table); - } - dataTable5.Merge(table); - table = new DataTable(); - string str17 = string.Concat("SELECT DISTINCT idcontrolesinistro, idcontrole as id FROM controlesinistro cs INNER JOIN item i on i.iditem = cs.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE 1=1 ", str9); - sqlCommand.CommandText = str17 ?? ""; - using (SqlDataAdapter sqlDataAdapter7 = new SqlDataAdapter()) - { - sqlDataAdapter7.SelectCommand = sqlCommand; - sqlDataAdapter7.Fill(table); - } - dataTable7.Merge(table); - table = new DataTable(); - string str18 = string.Concat(" AND d.idcontrole IN (", string.Join(",", dataTable.AsEnumerable().Select((DataRow v) => v.Field("idcontrole"))), ")"); - sqlCommand.CommandText = string.Concat("SELECT it.iditem, d.iddocumento, it.descricao, it.sinistrado, it.obs, it.status, d.idcontrole FROM item it INNER JOIN documento d on d.iddocumento = it.iddocumento WHERE 1=1 AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL ", " ", str18); - using (SqlDataAdapter sqlDataAdapter8 = new SqlDataAdapter()) - { - sqlDataAdapter8.SelectCommand = sqlCommand; - sqlDataAdapter8.Fill(table); - } - dataTable6.Merge(table); - for (List j = table.AsEnumerable().Select((DataRow i) => i.Field("iditem")).ToList(); j.Count > 0; j = nums) - { - List nums3 = j.Take(2000).ToList(); - SqlQueryCondition sqlQueryCondition = (new List() - { - new Condicao() - { - Campo = "iditem", - Valores = nums3.CriarValor() - } - }).CreateParameters(0); - table = sqlCommand.Select(sqlQueryCondition, "SELECT iditem, a.codfipe, a.modelo, a.idcategoria, a.idtabelareferencia, a.idcombustivel, a.chassi, a.placa, a.anofab, a.anomod, a.renavam, a.capacidade, a.portas, a.idcor, a.obs, a.regiaocirculacao, a.bonus, a.porcentagemreferencia, a.valordeterminado, a.ci, a.ceppernoite, a.financiado, a.zerokm, a.isencao, a.pcd, a.correcao, a.idfabricante, fab.descricao as fabricante FROM auto a LEFT JOIN fabricante fab on fab.idfabricante = a.idfabricante WHERE ", ""); - dataTable9.Merge(table); - table = sqlCommand.Select(sqlQueryCondition, "SELECT iditem, res.endereco as enderecoitem, res.numero as numeroitem, res.bens, res.cidade as cidadeitem, res.uf as ufitem, res.bairro as bairroitem, res.cep as cepitem, res.complemento as complementoitem, res.tiporesidencia, res.obs as obsresidencia, res.imobiliaria, res.contato as contatoresidencia, res.idfonetipo as fonetipoloc, res.ddd as dddloc, res.fone as foneloc, res.locatario, res.cpflocatario1, res.ddd2 as ddd2loc, res.fone2 as fone2loc, res.locatario2, res.cpflocatario2, res.dddlocatario2, res.fonelocatario2, res.locatario3, res.cpflocatario3, res.dddlocatario3, res.fonelocatario3 FROM resempco res WHERE ", ""); - dataTable10.Merge(table); - table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM granizo g WHERE ", ""); - dataTable11.Merge(table); - table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM aeronautico a WHERE ", ""); - dataTable12.Merge(table); - table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM riscosdiversos r WHERE ", ""); - dataTable13.Merge(table); - table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM vida v WHERE ", ""); - dataTable14.Merge(table); - table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM controlesinistro cs INNER JOIN sinistro s on s.idcontrolesinistro = cs.idcontrolesinistro WHERE ", ""); - dataTable8.Merge(table); - table = sqlCommand.Select(sqlQueryCondition, "SELECT * FROM consorcio WHERE", ""); - dataTable20.Merge(table); - nums = (nums3.Count < 2000 ? new List() : j.Except(nums3).ToList()); - } - table = new DataTable(); - string str19 = string.Concat(" select cli.* from clivinculo cli inner join controle con on cli.idcliente1 = con.idcliente inner join documento d on d.idcontrole = con.idcontrole inner join cliente cliente on cliente.IDCLIENTE = cli.idcliente1 WHERE 1=1 ", str9, ";"); - sqlCommand.CommandText = str19 ?? ""; - using (SqlDataAdapter sqlDataAdapter9 = new SqlDataAdapter()) - { - sqlDataAdapter9.SelectCommand = sqlCommand; - sqlDataAdapter9.Fill(table); - } - dataTable15.Merge(table); - table = new DataTable(); - string str20 = string.Concat("SELECT franquia, d.iddocumento FROM cobertura c INNER JOIN item i ON i.iditem = c.iditem INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE 1=1 AND franquia IS NOT NULL AND franquia != 0 ", str9, " ;"); - if (configFranquia) - { - str20 = string.Concat("SELECT SUM(franquia) AS franquia, d.iddocumento FROM cobertura c INNER JOIN item i ON i.iditem = c.iditem INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE 1=1 ", str9, " GROUP BY d.iddocumento;"); - } - sqlCommand.CommandText = str20 ?? ""; - using (SqlDataAdapter sqlDataAdapter10 = new SqlDataAdapter()) - { - sqlDataAdapter10.SelectCommand = sqlCommand; - sqlDataAdapter10.Fill(table); - } - dataTable17.Merge(table); - table = new DataTable(); - string str21 = string.Concat("SELECT idcoberturapadrao, franquia, lmi, observacao, premio, c.iditem FROM cobertura c INNER JOIN item i ON i.iditem = c.iditem INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE 1=1 ", str9, " AND idcoberturapadrao IN (2, 3, 17, 7, 5);"); - sqlCommand.CommandText = str21 ?? ""; - using (SqlDataAdapter sqlDataAdapter11 = new SqlDataAdapter()) - { - sqlDataAdapter11.SelectCommand = sqlCommand; - sqlDataAdapter11.Fill(table); - } - dataTable18.Merge(table); - table = new DataTable(); - string str22 = string.Concat("SELECT DISTINCT p.nomecompleto, p.cpf, p.datanascimento, p.sexo, p.estadocivil, p.ceppernoite, p.cepcirculacao, c.idcontrole, d.iddocumento FROM perfil p INNER JOIN controle c on c.idcontrole = p.idcontrole INNER JOIN documento d on d.idcontrole = c.idcontrole WHERE 1=1 ", str9); - sqlCommand.CommandText = str22 ?? ""; - using (SqlDataAdapter sqlDataAdapter12 = new SqlDataAdapter()) - { - sqlDataAdapter12.SelectCommand = sqlCommand; - sqlDataAdapter12.Fill(table); - } - dataTable19.Merge(table); - nums1 = (nums2.Count < 2100 ? new List() : i1.Except(nums2).ToList()); - } - } - } - if (dataTable.Rows.Count == 0) - { - return new List(); - } - List planilhaCompletas = new List(); - dataTable.AsEnumerable().ToList().ForEach((DataRow x) => { - decimal? nullable; - decimal? nullable1; - decimal? nullable2; - decimal? nullable3; - decimal? nullable4; - decimal? nullable5; - decimal? nullable6; - decimal? nullable7; - decimal num; - DateTime? nullable8; - long? nullable9; - string nome; - decimal? nullable10; - decimal? nullable11; - decimal? nullable12; - decimal? nullable13; - decimal? nullable14; - decimal? nullable15; - string str; - DateTime? nullable16; - DateTime? nullable17; - DateTime? nullable18; - DateTime? nullable19; - decimal? nullable20; - decimal? nullable21; - decimal? nullable22; - int? nullable23; - decimal? nullable24; - object empty; - object obj; - object empty1; - object obj1; - object empty2; - DateTime? nullable25; - string nome1; - DateTime? nullable26; - DateTime? nullable27; - DateTime? nullable28; - DateTime? nullable29; - DateTime? nullable30; - DateTime? nullable31; - DateTime? nullable32; - DateTime? nullable33; - string description; - string description1; - string str1; - decimal? nullable34; - decimal? nullable35; - string description2; - string str2; - DateTime? nullable36; - DateTime? nullable37; - decimal? nullable38; - decimal? nullable39; - int? nullable40; - int? nullable41; - int? nullable42; - long? nullable43; - DateTime? nullable44; - decimal? nullable45; - decimal? nullable46; - int? nullable47; - int? nullable48; - decimal? nullable49; - decimal? nullable50; - DateTime? nullable51; - DateTime? nullable52; - DateTime? nullable53; - decimal? nullable54; - decimal? nullable55; - decimal? nullable56; - decimal? nullable57; - decimal? nullable58; - decimal? nullable59; - decimal? nullable60; - decimal? nullable61; - decimal? nullable62; - decimal? nullable63; - decimal? nullable64; - decimal? nullable65; - decimal? nullable66; - decimal? nullable67; - decimal? nullable68; - decimal? nullable69; - decimal? nullable70; - decimal? nullable71; - try - { - DataRow dataRow = dataTable16.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("idcontrole") == x.Field("idcontrole")); - List list = dataTable2.AsEnumerable().Where((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")).Take(3).ToList(); - List dataRows = dataTable3.AsEnumerable().Where((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")).Take(2).ToList(); - DataRow dataRow1 = dataTable4.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")); - DataRow dataRow2 = dataTable5.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")); - List list1 = dataTable6.AsEnumerable().Where((DataRow e) => e.Field("idcontrole") == x.Field("idcontrole")).ToList(); - bool count = list1.Count != 1; - DataRow dataRow3 = (count ? null : dataTable9.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); - DataRow dataRow4 = (count ? null : dataTable10.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); - DataRow dataRow5 = (count ? null : dataTable11.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); - DataRow dataRow6 = (count ? null : dataTable12.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); - DataRow dataRow7 = (count ? null : dataTable13.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); - DataRow dataRow8 = (count ? null : dataTable14.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); - DataRow dataRow9 = (count ? null : dataTable8.AsEnumerable().FirstOrDefault((DataRow e) => e.Field("iditem") == list1.First().Field("iditem"))); - NegocioCorretora negocioCorretora = (x.Field("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString()) != TipoSeguro.Renovacao || x.Field("idnegocio") == null || !(x.Field("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field("negociocorretora").ToString())); - EnumerableRowCollection dataRows1 = dataTable1.AsEnumerable().Where((DataRow e) => e.Field("iddocumento") == x.Field("iddocumento")); - string str3 = (x.Field("situacao") == null || !(x.Field("situacao").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("situacao").ToString()) ? null : ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field("situacao").ToString())).GetDescription()); - string str4 = (x.Field("sexo") == null || !(x.Field("sexo").ToString() != "") || string.IsNullOrWhiteSpace(x.Field("sexo").ToString()) ? "" : ((Sexo)Enum.Parse(typeof(Sexo), x.Field("sexo").ToString())).GetDescription()); - object obj2 = x.Field("clibanco"); - List banco = Auxiliar.Banco; - List bancos = banco; - Predicate u003cu003e9_217 = ReportRepository.u003cu003ec.u003cu003e9__2_17; - if (u003cu003e9_217 == null) - { - u003cu003e9_217 = (Banco y) => y == null; - ReportRepository.u003cu003ec.u003cu003e9__2_17 = u003cu003e9_217; - } - bancos.RemoveAll(u003cu003e9_217); - if (obj2 == null || string.IsNullOrWhiteSpace(obj2.ToString())) - { - nome = ""; - } - else - { - Banco banco1 = banco.FirstOrDefault((Banco b) => b.Id == int.Parse(obj2.ToString())); - if (banco1 != null) - { - nome = banco1.Nome; - } - else - { - nome = null; - } - } - string str5 = nome; - string str6 = ""; - if (dataRow9 != null && dataRow9.Field("observacao") != null) - { - str6 = (new Regex(".*<\\/title>")).Replace((dataRow9 != null ? dataRow9.Field<string>("observacao") : null), "").Trim(); - str6 = (new Regex("(<[^>]*>)|(p\\s?{[^}]*})|(\\r)|(\\n)")).Replace(str6, "").Trim(); - } - if (dataRow3 == null || dataRow3.Field<object>("bonus") == null) - { - nullable5 = null; - nullable10 = nullable5; - } - else - { - nullable10 = new decimal?(decimal.Parse(dataRow3.Field<object>("bonus").ToString())); - } - decimal? nullable72 = nullable10; - DataRow dataRow10 = dataTable15.AsEnumerable().FirstOrDefault<DataRow>((DataRow v) => v.Field<long>("idcliente1") == x.Field<long>("idcliente")) ?? dataTable15.AsEnumerable().FirstOrDefault<DataRow>((DataRow v) => v.Field<long>("idcliente2") == x.Field<long>("idcliente")); - DataRow dataRow11 = dataTable17.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iddocumento") == x.Field<long>("iddocumento")); - EnumerableRowCollection<DataRow> dataRows2 = dataTable18.AsEnumerable().Where<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")); - Cobertura cobertura = new Cobertura(); - if (list1.Count > 0) - { - EnumerableRowCollection<DataRow> dataRows3 = dataRows2; - Func<DataRow, bool> u003cu003e9_223 = ReportRepository.u003cu003ec.u003cu003e9__2_23; - if (u003cu003e9_223 == null) - { - u003cu003e9_223 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)3; - ReportRepository.u003cu003ec.u003cu003e9__2_23 = u003cu003e9_223; - } - if (dataRows3.Where<DataRow>(u003cu003e9_223).AsEnumerable<DataRow>().ToList<DataRow>().Count > 0) - { - Cobertura valueOrDefault = new Cobertura(); - EnumerableRowCollection<DataRow> dataRows4 = dataRows2; - Func<DataRow, bool> u003cu003e9_234 = ReportRepository.u003cu003ec.u003cu003e9__2_34; - if (u003cu003e9_234 == null) - { - u003cu003e9_234 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)3; - ReportRepository.u003cu003ec.u003cu003e9__2_34 = u003cu003e9_234; - } - nullable5 = dataRows4.FirstOrDefault<DataRow>(u003cu003e9_234).Field<decimal?>("franquia"); - valueOrDefault.Franquia = nullable5.GetValueOrDefault(); - EnumerableRowCollection<DataRow> dataRows5 = dataRows2; - Func<DataRow, bool> u003cu003e9_235 = ReportRepository.u003cu003ec.u003cu003e9__2_35; - if (u003cu003e9_235 == null) - { - u003cu003e9_235 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)3; - ReportRepository.u003cu003ec.u003cu003e9__2_35 = u003cu003e9_235; - } - nullable5 = dataRows5.FirstOrDefault<DataRow>(u003cu003e9_235).Field<decimal?>("premio"); - valueOrDefault.Premio = nullable5.GetValueOrDefault(); - EnumerableRowCollection<DataRow> dataRows6 = dataRows2; - Func<DataRow, bool> u003cu003e9_236 = ReportRepository.u003cu003ec.u003cu003e9__2_36; - if (u003cu003e9_236 == null) - { - u003cu003e9_236 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)3; - ReportRepository.u003cu003ec.u003cu003e9__2_36 = u003cu003e9_236; - } - nullable5 = dataRows6.FirstOrDefault<DataRow>(u003cu003e9_236).Field<decimal?>("lmi"); - valueOrDefault.Lmi = nullable5.GetValueOrDefault(); - cobertura = valueOrDefault; - } - } - Cobertura cobertura1 = new Cobertura(); - if (list1.Count > 0) - { - EnumerableRowCollection<DataRow> dataRows7 = dataRows2; - Func<DataRow, bool> u003cu003e9_224 = ReportRepository.u003cu003ec.u003cu003e9__2_24; - if (u003cu003e9_224 == null) - { - u003cu003e9_224 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)2; - ReportRepository.u003cu003ec.u003cu003e9__2_24 = u003cu003e9_224; - } - if (dataRows7.Where<DataRow>(u003cu003e9_224).AsEnumerable<DataRow>().ToList<DataRow>().Count > 0) - { - Cobertura valueOrDefault1 = new Cobertura(); - EnumerableRowCollection<DataRow> dataRows8 = dataRows2; - Func<DataRow, bool> u003cu003e9_237 = ReportRepository.u003cu003ec.u003cu003e9__2_37; - if (u003cu003e9_237 == null) - { - u003cu003e9_237 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)2; - ReportRepository.u003cu003ec.u003cu003e9__2_37 = u003cu003e9_237; - } - nullable5 = dataRows8.FirstOrDefault<DataRow>(u003cu003e9_237).Field<decimal?>("franquia"); - valueOrDefault1.Franquia = nullable5.GetValueOrDefault(); - EnumerableRowCollection<DataRow> dataRows9 = dataRows2; - Func<DataRow, bool> u003cu003e9_238 = ReportRepository.u003cu003ec.u003cu003e9__2_38; - if (u003cu003e9_238 == null) - { - u003cu003e9_238 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)2; - ReportRepository.u003cu003ec.u003cu003e9__2_38 = u003cu003e9_238; - } - nullable5 = dataRows9.FirstOrDefault<DataRow>(u003cu003e9_238).Field<decimal?>("premio"); - valueOrDefault1.Premio = nullable5.GetValueOrDefault(); - EnumerableRowCollection<DataRow> dataRows10 = dataRows2; - Func<DataRow, bool> u003cu003e9_239 = ReportRepository.u003cu003ec.u003cu003e9__2_39; - if (u003cu003e9_239 == null) - { - u003cu003e9_239 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)2; - ReportRepository.u003cu003ec.u003cu003e9__2_39 = u003cu003e9_239; - } - nullable5 = dataRows10.FirstOrDefault<DataRow>(u003cu003e9_239).Field<decimal?>("lmi"); - valueOrDefault1.Lmi = nullable5.GetValueOrDefault(); - cobertura1 = valueOrDefault1; - } - } - Cobertura cobertura2 = new Cobertura(); - if (list1.Count > 0) - { - EnumerableRowCollection<DataRow> dataRows11 = dataRows2; - Func<DataRow, bool> u003cu003e9_225 = ReportRepository.u003cu003ec.u003cu003e9__2_25; - if (u003cu003e9_225 == null) - { - u003cu003e9_225 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)17; - ReportRepository.u003cu003ec.u003cu003e9__2_25 = u003cu003e9_225; - } - if (dataRows11.Where<DataRow>(u003cu003e9_225).AsEnumerable<DataRow>().ToList<DataRow>().Count > 0) - { - Cobertura valueOrDefault2 = new Cobertura(); - EnumerableRowCollection<DataRow> dataRows12 = dataRows2; - Func<DataRow, bool> u003cu003e9_240 = ReportRepository.u003cu003ec.u003cu003e9__2_40; - if (u003cu003e9_240 == null) - { - u003cu003e9_240 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)17; - ReportRepository.u003cu003ec.u003cu003e9__2_40 = u003cu003e9_240; - } - nullable5 = dataRows12.FirstOrDefault<DataRow>(u003cu003e9_240).Field<decimal?>("franquia"); - valueOrDefault2.Franquia = nullable5.GetValueOrDefault(); - EnumerableRowCollection<DataRow> dataRows13 = dataRows2; - Func<DataRow, bool> u003cu003e9_241 = ReportRepository.u003cu003ec.u003cu003e9__2_41; - if (u003cu003e9_241 == null) - { - u003cu003e9_241 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)17; - ReportRepository.u003cu003ec.u003cu003e9__2_41 = u003cu003e9_241; - } - nullable5 = dataRows13.FirstOrDefault<DataRow>(u003cu003e9_241).Field<decimal?>("premio"); - valueOrDefault2.Premio = nullable5.GetValueOrDefault(); - EnumerableRowCollection<DataRow> dataRows14 = dataRows2; - Func<DataRow, bool> u003cu003e9_242 = ReportRepository.u003cu003ec.u003cu003e9__2_42; - if (u003cu003e9_242 == null) - { - u003cu003e9_242 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)17; - ReportRepository.u003cu003ec.u003cu003e9__2_42 = u003cu003e9_242; - } - nullable5 = dataRows14.FirstOrDefault<DataRow>(u003cu003e9_242).Field<decimal?>("lmi"); - valueOrDefault2.Lmi = nullable5.GetValueOrDefault(); - cobertura2 = valueOrDefault2; - } - } - Cobertura cobertura3 = new Cobertura(); - if (list1.Count > 0) - { - EnumerableRowCollection<DataRow> dataRows15 = dataRows2; - Func<DataRow, bool> u003cu003e9_226 = ReportRepository.u003cu003ec.u003cu003e9__2_26; - if (u003cu003e9_226 == null) - { - u003cu003e9_226 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)5; - ReportRepository.u003cu003ec.u003cu003e9__2_26 = u003cu003e9_226; - } - if (dataRows15.Where<DataRow>(u003cu003e9_226).AsEnumerable<DataRow>().ToList<DataRow>().Count > 0) - { - Cobertura valueOrDefault3 = new Cobertura(); - EnumerableRowCollection<DataRow> dataRows16 = dataRows2; - Func<DataRow, bool> u003cu003e9_243 = ReportRepository.u003cu003ec.u003cu003e9__2_43; - if (u003cu003e9_243 == null) - { - u003cu003e9_243 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)5; - ReportRepository.u003cu003ec.u003cu003e9__2_43 = u003cu003e9_243; - } - nullable5 = dataRows16.FirstOrDefault<DataRow>(u003cu003e9_243).Field<decimal?>("franquia"); - valueOrDefault3.Franquia = nullable5.GetValueOrDefault(); - EnumerableRowCollection<DataRow> dataRows17 = dataRows2; - Func<DataRow, bool> u003cu003e9_244 = ReportRepository.u003cu003ec.u003cu003e9__2_44; - if (u003cu003e9_244 == null) - { - u003cu003e9_244 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)5; - ReportRepository.u003cu003ec.u003cu003e9__2_44 = u003cu003e9_244; - } - nullable5 = dataRows17.FirstOrDefault<DataRow>(u003cu003e9_244).Field<decimal?>("premio"); - valueOrDefault3.Premio = nullable5.GetValueOrDefault(); - EnumerableRowCollection<DataRow> dataRows18 = dataRows2; - Func<DataRow, bool> u003cu003e9_245 = ReportRepository.u003cu003ec.u003cu003e9__2_45; - if (u003cu003e9_245 == null) - { - u003cu003e9_245 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)5; - ReportRepository.u003cu003ec.u003cu003e9__2_45 = u003cu003e9_245; - } - nullable5 = dataRows18.FirstOrDefault<DataRow>(u003cu003e9_245).Field<decimal?>("lmi"); - valueOrDefault3.Lmi = nullable5.GetValueOrDefault(); - cobertura3 = valueOrDefault3; - } - } - Cobertura cobertura4 = new Cobertura(); - if (list1.Count > 0) - { - EnumerableRowCollection<DataRow> dataRows19 = dataRows2; - Func<DataRow, bool> u003cu003e9_227 = ReportRepository.u003cu003ec.u003cu003e9__2_27; - if (u003cu003e9_227 == null) - { - u003cu003e9_227 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)7; - ReportRepository.u003cu003ec.u003cu003e9__2_27 = u003cu003e9_227; - } - if (dataRows19.Where<DataRow>(u003cu003e9_227).AsEnumerable<DataRow>().ToList<DataRow>().Count > 0) - { - Cobertura valueOrDefault4 = new Cobertura(); - EnumerableRowCollection<DataRow> dataRows20 = dataRows2; - Func<DataRow, bool> u003cu003e9_246 = ReportRepository.u003cu003ec.u003cu003e9__2_46; - if (u003cu003e9_246 == null) - { - u003cu003e9_246 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)7; - ReportRepository.u003cu003ec.u003cu003e9__2_46 = u003cu003e9_246; - } - valueOrDefault4.Observacao = dataRows20.FirstOrDefault<DataRow>(u003cu003e9_246).Field<string>("observacao") ?? ""; - EnumerableRowCollection<DataRow> dataRows21 = dataRows2; - Func<DataRow, bool> u003cu003e9_247 = ReportRepository.u003cu003ec.u003cu003e9__2_47; - if (u003cu003e9_247 == null) - { - u003cu003e9_247 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)7; - ReportRepository.u003cu003ec.u003cu003e9__2_47 = u003cu003e9_247; - } - nullable5 = dataRows21.FirstOrDefault<DataRow>(u003cu003e9_247).Field<decimal?>("franquia"); - valueOrDefault4.Franquia = nullable5.GetValueOrDefault(); - EnumerableRowCollection<DataRow> dataRows22 = dataRows2; - Func<DataRow, bool> u003cu003e9_248 = ReportRepository.u003cu003ec.u003cu003e9__2_48; - if (u003cu003e9_248 == null) - { - u003cu003e9_248 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)7; - ReportRepository.u003cu003ec.u003cu003e9__2_48 = u003cu003e9_248; - } - nullable5 = dataRows22.FirstOrDefault<DataRow>(u003cu003e9_248).Field<decimal?>("premio"); - valueOrDefault4.Premio = nullable5.GetValueOrDefault(); - EnumerableRowCollection<DataRow> dataRows23 = dataRows2; - Func<DataRow, bool> u003cu003e9_249 = ReportRepository.u003cu003ec.u003cu003e9__2_49; - if (u003cu003e9_249 == null) - { - u003cu003e9_249 = (DataRow v) => v.Field<long>("idcoberturapadrao") == (long)7; - ReportRepository.u003cu003ec.u003cu003e9__2_49 = u003cu003e9_249; - } - nullable5 = dataRows23.FirstOrDefault<DataRow>(u003cu003e9_249).Field<decimal?>("lmi"); - valueOrDefault4.Lmi = nullable5.GetValueOrDefault(); - cobertura4 = valueOrDefault4; - } - } - IEnumerable<DataRow> list2 = - from e in dataTable16.AsEnumerable().ToList<DataRow>() - where e.Field<long>("idcontrole") == x.Field<long>("idcontrole") - select e; - if (!configSomaPremio) - { - nullable6 = x.Field<decimal?>("pr_liq"); - if (nullable6.HasValue) - { - nullable11 = x.Field<decimal?>("pr_liq"); - } - else - { - nullable6 = null; - nullable11 = nullable6; - } - nullable = nullable11; - nullable6 = x.Field<decimal?>("pr_adic"); - if (nullable6.HasValue) - { - nullable12 = x.Field<decimal?>("pr_adic"); - } - else - { - nullable6 = null; - nullable12 = nullable6; - } - nullable1 = nullable12; - nullable6 = x.Field<decimal?>("pr_custo"); - if (nullable6.HasValue) - { - nullable13 = x.Field<decimal?>("pr_custo"); - } - else - { - nullable6 = null; - nullable13 = nullable6; - } - nullable2 = nullable13; - nullable6 = x.Field<decimal?>("pr_iof"); - if (nullable6.HasValue) - { - nullable14 = x.Field<decimal?>("pr_iof"); - } - else - { - nullable6 = null; - nullable14 = nullable6; - } - nullable3 = nullable14; - nullable6 = x.Field<decimal?>("pr_total"); - if (nullable6.HasValue) - { - nullable15 = x.Field<decimal?>("pr_total"); - } - else - { - nullable6 = null; - nullable15 = nullable6; - } - nullable4 = nullable15; - } - else - { - IEnumerable<DataRow> dataRows24 = list2; - Func<DataRow, bool> u003cu003e9_250 = ReportRepository.u003cu003ec.u003cu003e9__2_50; - if (u003cu003e9_250 == null) - { - u003cu003e9_250 = (DataRow z) => z.Field<decimal?>("pr_liq").HasValue; - ReportRepository.u003cu003ec.u003cu003e9__2_50 = u003cu003e9_250; - } - IEnumerable<DataRow> dataRows25 = dataRows24.Where<DataRow>(u003cu003e9_250); - if (dataRows25 != null) - { - Func<DataRow, decimal?> u003cu003e9_251 = ReportRepository.u003cu003ec.u003cu003e9__2_51; - if (u003cu003e9_251 == null) - { - u003cu003e9_251 = (DataRow y) => y.Field<decimal?>("pr_liq"); - ReportRepository.u003cu003ec.u003cu003e9__2_51 = u003cu003e9_251; - } - nullable62 = dataRows25.Sum<DataRow>(u003cu003e9_251); - } - else - { - nullable7 = null; - nullable62 = nullable7; - } - nullable5 = nullable62; - nullable6 = x.Field<decimal?>("pr_liq"); - if (nullable5.HasValue & nullable6.HasValue) - { - nullable63 = new decimal?(nullable5.GetValueOrDefault() + nullable6.GetValueOrDefault()); - } - else - { - nullable7 = null; - nullable63 = nullable7; - } - nullable = nullable63; - IEnumerable<DataRow> dataRows26 = list2; - Func<DataRow, bool> u003cu003e9_252 = ReportRepository.u003cu003ec.u003cu003e9__2_52; - if (u003cu003e9_252 == null) - { - u003cu003e9_252 = (DataRow z) => z.Field<decimal?>("pr_adic").HasValue; - ReportRepository.u003cu003ec.u003cu003e9__2_52 = u003cu003e9_252; - } - IEnumerable<DataRow> dataRows27 = dataRows26.Where<DataRow>(u003cu003e9_252); - if (dataRows27 != null) - { - Func<DataRow, decimal?> u003cu003e9_253 = ReportRepository.u003cu003ec.u003cu003e9__2_53; - if (u003cu003e9_253 == null) - { - u003cu003e9_253 = (DataRow y) => y.Field<decimal?>("pr_adic"); - ReportRepository.u003cu003ec.u003cu003e9__2_53 = u003cu003e9_253; - } - nullable64 = dataRows27.Sum<DataRow>(u003cu003e9_253); - } - else - { - nullable7 = null; - nullable64 = nullable7; - } - nullable6 = nullable64; - nullable5 = x.Field<decimal?>("pr_adic"); - if (nullable6.HasValue & nullable5.HasValue) - { - nullable65 = new decimal?(nullable6.GetValueOrDefault() + nullable5.GetValueOrDefault()); - } - else - { - nullable7 = null; - nullable65 = nullable7; - } - nullable1 = nullable65; - IEnumerable<DataRow> dataRows28 = list2; - Func<DataRow, bool> u003cu003e9_254 = ReportRepository.u003cu003ec.u003cu003e9__2_54; - if (u003cu003e9_254 == null) - { - u003cu003e9_254 = (DataRow z) => z.Field<decimal?>("pr_custo").HasValue; - ReportRepository.u003cu003ec.u003cu003e9__2_54 = u003cu003e9_254; - } - IEnumerable<DataRow> dataRows29 = dataRows28.Where<DataRow>(u003cu003e9_254); - if (dataRows29 != null) - { - Func<DataRow, decimal?> u003cu003e9_255 = ReportRepository.u003cu003ec.u003cu003e9__2_55; - if (u003cu003e9_255 == null) - { - u003cu003e9_255 = (DataRow y) => y.Field<decimal?>("pr_custo"); - ReportRepository.u003cu003ec.u003cu003e9__2_55 = u003cu003e9_255; - } - nullable66 = dataRows29.Sum<DataRow>(u003cu003e9_255); - } - else - { - nullable7 = null; - nullable66 = nullable7; - } - nullable5 = nullable66; - nullable6 = x.Field<decimal?>("pr_custo"); - if (nullable5.HasValue & nullable6.HasValue) - { - nullable67 = new decimal?(nullable5.GetValueOrDefault() + nullable6.GetValueOrDefault()); - } - else - { - nullable7 = null; - nullable67 = nullable7; - } - nullable2 = nullable67; - IEnumerable<DataRow> dataRows30 = list2; - Func<DataRow, bool> u003cu003e9_256 = ReportRepository.u003cu003ec.u003cu003e9__2_56; - if (u003cu003e9_256 == null) - { - u003cu003e9_256 = (DataRow z) => z.Field<decimal?>("pr_iof").HasValue; - ReportRepository.u003cu003ec.u003cu003e9__2_56 = u003cu003e9_256; - } - IEnumerable<DataRow> dataRows31 = dataRows30.Where<DataRow>(u003cu003e9_256); - if (dataRows31 != null) - { - Func<DataRow, decimal?> u003cu003e9_257 = ReportRepository.u003cu003ec.u003cu003e9__2_57; - if (u003cu003e9_257 == null) - { - u003cu003e9_257 = (DataRow y) => y.Field<decimal?>("pr_iof"); - ReportRepository.u003cu003ec.u003cu003e9__2_57 = u003cu003e9_257; - } - nullable68 = dataRows31.Sum<DataRow>(u003cu003e9_257); - } - else - { - nullable7 = null; - nullable68 = nullable7; - } - nullable6 = nullable68; - nullable5 = x.Field<decimal?>("pr_iof"); - if (nullable6.HasValue & nullable5.HasValue) - { - nullable69 = new decimal?(nullable6.GetValueOrDefault() + nullable5.GetValueOrDefault()); - } - else - { - nullable7 = null; - nullable69 = nullable7; - } - nullable3 = nullable69; - IEnumerable<DataRow> dataRows32 = list2; - Func<DataRow, bool> u003cu003e9_258 = ReportRepository.u003cu003ec.u003cu003e9__2_58; - if (u003cu003e9_258 == null) - { - u003cu003e9_258 = (DataRow z) => z.Field<decimal?>("pr_total").HasValue; - ReportRepository.u003cu003ec.u003cu003e9__2_58 = u003cu003e9_258; - } - IEnumerable<DataRow> dataRows33 = dataRows32.Where<DataRow>(u003cu003e9_258); - if (dataRows33 != null) - { - Func<DataRow, decimal?> u003cu003e9_259 = ReportRepository.u003cu003ec.u003cu003e9__2_59; - if (u003cu003e9_259 == null) - { - u003cu003e9_259 = (DataRow y) => y.Field<decimal?>("pr_total"); - ReportRepository.u003cu003ec.u003cu003e9__2_59 = u003cu003e9_259; - } - nullable70 = dataRows33.Sum<DataRow>(u003cu003e9_259); - } - else - { - nullable7 = null; - nullable70 = nullable7; - } - nullable5 = nullable70; - nullable6 = x.Field<decimal?>("pr_total"); - if (nullable5.HasValue & nullable6.HasValue) - { - nullable71 = new decimal?(nullable5.GetValueOrDefault() + nullable6.GetValueOrDefault()); - } - else - { - nullable7 = null; - nullable71 = nullable7; - } - nullable4 = nullable71; - } - int num1 = dataTable16.AsEnumerable().Count<DataRow>((DataRow e) => e.Field<long>("idcontrole") == x.Field<long>("idcontrole")); - int num2 = dataTable7.AsEnumerable().Count<DataRow>((DataRow s) => s.Field<long>("id") == x.Field<long>("idcontrole")); - DataRow dataRow12 = dataTable19.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iddocumento") == x.Field<long>("iddocumento")); - string str7 = ((dataRow12 != null ? dataRow12.Field<object>("sexo") == null : true) ? "" : (dataRow12.Field<object>("sexo").ToString() == "2" ? Sexo.Feminino.GetDescription<Sexo>() : (dataRow12.Field<object>("sexo").ToString() == "1" ? Sexo.Masculino.GetDescription<Sexo>() : ""))); - if (x.Field<object>("idciasegant") == null) - { - str = ""; - } - else - { - Seguradora seguradora = Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora ciaseg) => ciaseg.Id == x.Field<long>("idciasegant")); - if (seguradora != null) - { - str = seguradora.Nome; - } - else - { - str = null; - } - } - string str8 = str; - DataRow dataRow13 = dataTable20.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")); - PlanilhaCompleta planilhaCompletum = new PlanilhaCompleta() - { - NumeroProposta = x.Field<string>("proposta"), - NumeroApolice = x.Field<string>("contrato"), - NumeroPedidoEndosso = (!string.IsNullOrEmpty(x.Field<string>("pedadit")) || dataRow == null ? x.Field<string>("pedadit") : dataRow.Field<string>("pedadit")), - NumeroEndosso = (!string.IsNullOrEmpty(x.Field<string>("aditamento")) || dataRow == null ? x.Field<string>("aditamento") : dataRow.Field<string>("aditamento")), - Status = str3, - TipoRecebimento = TipoRecebimento.Parcela.GetDescription<TipoRecebimento>() - }; - DateTime? nullable73 = x.Field<DateTime?>("emissao"); - if (nullable73.HasValue) - { - nullable16 = x.Field<DateTime?>("emissao"); - } - else - { - nullable73 = null; - nullable16 = nullable73; - } - planilhaCompletum.Emissao = nullable16; - nullable73 = x.Field<DateTime?>("vigencia1"); - if (nullable73.HasValue) - { - nullable17 = x.Field<DateTime?>("vigencia1"); - } - else - { - nullable73 = null; - nullable17 = nullable73; - } - planilhaCompletum.VigenciaInicial = nullable17; - nullable73 = x.Field<DateTime?>("vigencia2"); - if (nullable73.HasValue) - { - nullable18 = x.Field<DateTime?>("vigencia2"); - } - else - { - nullable73 = null; - nullable18 = nullable73; - } - planilhaCompletum.VigenciaFinal = nullable18; - nullable73 = x.Field<DateTime?>("remessa"); - if (nullable73.HasValue) - { - nullable19 = x.Field<DateTime?>("remessa"); - } - else - { - nullable73 = null; - nullable19 = nullable73; - } - planilhaCompletum.Remessa = nullable19; - nullable6 = x.Field<decimal?>("com01"); - if (nullable6.HasValue) - { - nullable20 = x.Field<decimal?>("com01"); - } - else - { - nullable6 = null; - nullable20 = nullable6; - } - planilhaCompletum.Comissao = nullable20; - planilhaCompletum.AdicionalComiss = x.Field<string>("adinacomis") == "1"; - nullable7 = nullable; - if (x.Field<string>("adinacomis") == "1") - { - nullable21 = nullable1; - } - else - { - num = new decimal(); - nullable21 = new decimal?(num); - } - decimal? nullable74 = nullable21; - nullable6 = (nullable7.HasValue & nullable74.HasValue ? new decimal?(nullable7.GetValueOrDefault() + nullable74.GetValueOrDefault()) : null); - nullable5 = x.Field<decimal?>("com01"); - if (nullable6.HasValue & nullable5.HasValue) - { - nullable22 = new decimal?((nullable6.GetValueOrDefault() * nullable5.GetValueOrDefault()) * new decimal(1, 0, 0, false, 2)); - } - else - { - nullable74 = null; - nullable22 = nullable74; - } - planilhaCompletum.ComissaoGerada = nullable22; - planilhaCompletum.PremioLiquido = new decimal?(nullable.GetValueOrDefault()); - planilhaCompletum.PremioAdicional = new decimal?(nullable1.GetValueOrDefault()); - planilhaCompletum.PremioCusto = new decimal?(nullable2.GetValueOrDefault()); - num = new decimal(); - planilhaCompletum.LiquidoFatura = new decimal?(num); - num = new decimal(); - planilhaCompletum.TotalFatura = new decimal?(num); - planilhaCompletum.Iof = new decimal?(nullable3.GetValueOrDefault()); - planilhaCompletum.PremioTotal = nullable4; - int? nullable75 = x.Field<int?>("n_parc"); - if (nullable75.HasValue) - { - nullable23 = x.Field<int?>("n_parc"); - } - else - { - nullable75 = null; - nullable23 = nullable75; - } - planilhaCompletum.NumParcelas = nullable23; - nullable75 = x.Field<int?>("n_parc"); - if (!nullable75.HasValue || x.Field<int>("n_parc") <= 0) - { - num = new decimal(); - nullable24 = new decimal?(num); - } - else - { - nullable5 = x.Field<decimal?>("pr_total"); - num = x.Field<int>("n_parc"); - if (nullable5.HasValue) - { - nullable24 = new decimal?(nullable5.GetValueOrDefault() / num); - } - else - { - nullable6 = null; - nullable24 = nullable6; - } - } - planilhaCompletum.ValorParcela = nullable24; - planilhaCompletum.FormaPagamento = (x.Field<object>("formapagamento") == null || !(x.Field<object>("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.Field<object>("formapagamento").ToString()) ? null : ((FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.Field<object>("formapagamento").ToString())).GetDescription<FormaPagamento>()); - planilhaCompletum.Negocio = negocioCorretora.GetDescription<NegocioCorretora>(); - if (dataRows1 != null) - { - EnumerableRowCollection<DataRow> dataRows34 = dataRows1; - Func<DataRow, bool> u003cu003e9_260 = ReportRepository.u003cu003ec.u003cu003e9__2_60; - if (u003cu003e9_260 == null) - { - u003cu003e9_260 = (DataRow e) => e.Field<string>("index").Equals("1"); - ReportRepository.u003cu003ec.u003cu003e9__2_60 = u003cu003e9_260; - } - DataRow dataRow14 = dataRows34.FirstOrDefault<DataRow>(u003cu003e9_260); - if (dataRow14 != null) - { - empty = dataRow14.Field<string>("nomeEstipulante"); - } - else - { - empty = null; - } - } - else - { - empty = null; - } - if (empty == null) - { - empty = string.Empty; - } - planilhaCompletum.Estipulante = (string)empty; - if (dataRows1 != null) - { - EnumerableRowCollection<DataRow> dataRows35 = dataRows1; - Func<DataRow, bool> u003cu003e9_261 = ReportRepository.u003cu003ec.u003cu003e9__2_61; - if (u003cu003e9_261 == null) - { - u003cu003e9_261 = (DataRow e) => e.Field<string>("index").Equals("2"); - ReportRepository.u003cu003ec.u003cu003e9__2_61 = u003cu003e9_261; - } - DataRow dataRow15 = dataRows35.FirstOrDefault<DataRow>(u003cu003e9_261); - if (dataRow15 != null) - { - obj = dataRow15.Field<string>("nomeEstipulante"); - } - else - { - obj = null; - } - } - else - { - obj = null; - } - if (obj == null) - { - obj = string.Empty; - } - planilhaCompletum.Estipulante2 = (string)obj; - if (dataRows1 != null) - { - EnumerableRowCollection<DataRow> dataRows36 = dataRows1; - Func<DataRow, bool> u003cu003e9_262 = ReportRepository.u003cu003ec.u003cu003e9__2_62; - if (u003cu003e9_262 == null) - { - u003cu003e9_262 = (DataRow e) => e.Field<string>("index").Equals("3"); - ReportRepository.u003cu003ec.u003cu003e9__2_62 = u003cu003e9_262; - } - DataRow dataRow16 = dataRows36.FirstOrDefault<DataRow>(u003cu003e9_262); - if (dataRow16 != null) - { - empty1 = dataRow16.Field<string>("nomeEstipulante"); - } - else - { - empty1 = null; - } - } - else - { - empty1 = null; - } - if (empty1 == null) - { - empty1 = string.Empty; - } - planilhaCompletum.Estipulante3 = (string)empty1; - if (dataRows1 != null) - { - EnumerableRowCollection<DataRow> dataRows37 = dataRows1; - Func<DataRow, bool> u003cu003e9_263 = ReportRepository.u003cu003ec.u003cu003e9__2_63; - if (u003cu003e9_263 == null) - { - u003cu003e9_263 = (DataRow e) => e.Field<string>("index").Equals("4"); - ReportRepository.u003cu003ec.u003cu003e9__2_63 = u003cu003e9_263; - } - DataRow dataRow17 = dataRows37.FirstOrDefault<DataRow>(u003cu003e9_263); - if (dataRow17 != null) - { - obj1 = dataRow17.Field<string>("nomeEstipulante"); - } - else - { - obj1 = null; - } - } - else - { - obj1 = null; - } - if (obj1 == null) - { - obj1 = string.Empty; - } - planilhaCompletum.Estipulante4 = (string)obj1; - if (dataRows1 != null) - { - EnumerableRowCollection<DataRow> dataRows38 = dataRows1; - Func<DataRow, bool> u003cu003e9_264 = ReportRepository.u003cu003ec.u003cu003e9__2_64; - if (u003cu003e9_264 == null) - { - u003cu003e9_264 = (DataRow e) => e.Field<string>("index").Equals("5"); - ReportRepository.u003cu003ec.u003cu003e9__2_64 = u003cu003e9_264; - } - DataRow dataRow18 = dataRows38.FirstOrDefault<DataRow>(u003cu003e9_264); - if (dataRow18 != null) - { - empty2 = dataRow18.Field<string>("nomeEstipulante"); - } - else - { - empty2 = null; - } - } - else - { - empty2 = null; - } - if (empty2 == null) - { - empty2 = string.Empty; - } - planilhaCompletum.Estipulante5 = (string)empty2; - planilhaCompletum.Vendedor = x.Field<string>("nomeVendedor"); - planilhaCompletum.Produto = x.Field<string>("nomeProduto"); - nullable73 = x.Field<DateTime?>("datacontrole"); - if (nullable73.HasValue) - { - nullable25 = x.Field<DateTime?>("datacontrole"); - } - else - { - nullable73 = null; - nullable25 = nullable73; - } - planilhaCompletum.DataControle = nullable25; - planilhaCompletum.Seguradora = x.Field<string>("nomeCiaseg"); - planilhaCompletum.Ramo = x.Field<string>("nomeRamo"); - planilhaCompletum.SeguradoraAnterior = str8 ?? ""; - planilhaCompletum.IdDocumento = x.Field<long>("iddocumento"); - planilhaCompletum.ObservacaoDocumento = (x.Field<string>("obs") == null || x.Field<string>("obs").Length <= 30000 ? x.Field<string>("obs") : x.Field<string>("obs").Substring(0, 30000)); - planilhaCompletum.NomeCliente = x.Field<string>("nome"); - if (x.Field<object>("idprofissao") != null) - { - Profissao profissao = Auxiliar.Profissoes.FirstOrDefault<Profissao>((Profissao p) => p.Id == long.Parse(x.Field<object>("idprofissao").ToString())); - if (profissao != null) - { - nome1 = profissao.Nome; - } - else - { - nome1 = null; - } - } - else - { - nome1 = ""; - } - planilhaCompletum.ProfissaoCliente = nome1; - nullable73 = x.Field<DateTime?>("dtnasc"); - if (nullable73.HasValue) - { - nullable26 = x.Field<DateTime?>("dtnasc"); - } - else - { - nullable73 = null; - nullable26 = nullable73; - } - planilhaCompletum.NascimentoCliente = nullable26; - planilhaCompletum.SexoCliente = str4; - planilhaCompletum.EstadoCivilCliente = x.Field<string>("estadocivi"); - planilhaCompletum.DocumentoCliente = x.Field<string>("cgccpf"); - planilhaCompletum.IdentidadeCliente = x.Field<string>("rg"); - planilhaCompletum.EmissorCliente = x.Field<string>("emissor"); - planilhaCompletum.EstadoEmissorCliente = x.Field<string>("rguf"); - nullable73 = x.Field<DateTime?>("rgexpedica"); - if (nullable73.HasValue) - { - nullable27 = x.Field<DateTime?>("rgexpedica"); - } - else - { - nullable73 = null; - nullable27 = nullable73; - } - planilhaCompletum.ExpedicaoCliente = nullable27; - planilhaCompletum.HabilitacaoCliente = x.Field<string>("numehabili"); - nullable73 = x.Field<DateTime?>("primehabil"); - if (nullable73.HasValue) - { - nullable28 = x.Field<DateTime?>("primehabil"); - } - else - { - nullable73 = null; - nullable28 = nullable73; - } - planilhaCompletum.PrimeiraHabilitacaoCliente = nullable28; - nullable73 = x.Field<DateTime?>("venchabili"); - if (nullable73.HasValue) - { - nullable29 = x.Field<DateTime?>("venchabili"); - } - else - { - nullable73 = null; - nullable29 = nullable73; - } - planilhaCompletum.VencimentoHabilitacaoCliente = nullable29; - planilhaCompletum.CategoriaHabilitacaoCliente = x.Field<string>("cathabili"); - nullable73 = x.Field<DateTime?>("clidesde"); - if (nullable73.HasValue) - { - nullable30 = x.Field<DateTime?>("clidesde"); - } - else - { - nullable73 = null; - nullable30 = nullable73; - } - planilhaCompletum.ClienteDesde = nullable30; - planilhaCompletum.PastaCliente = x.Field<string>("pasta"); - planilhaCompletum.CeiCliente = x.Field<string>("cei"); - planilhaCompletum.RneCliente = x.Field<string>("rne"); - planilhaCompletum.FalecidoCliente = (!x.Field<bool?>("falecido").HasValue || !x.Field<bool?>("falecido").GetValueOrDefault() ? "NÃO" : "SIM"); - planilhaCompletum.ObservacaoCliente = (x.Field<string>("anotacoes") == null || x.Field<string>("anotacoes").Length <= 30000 ? x.Field<string>("anotacoes") : x.Field<string>("anotacoes").Substring(0, 30000)); - planilhaCompletum.Prefixo1 = (list == null || list.Count <= 0 ? "" : list[0].Field<string>("ddd")); - planilhaCompletum.Telefone1 = (list == null || list.Count <= 0 ? "" : list[0].Field<string>("fone")); - planilhaCompletum.Prefixo2 = (list == null || list.Count <= 1 ? "" : list[1].Field<string>("ddd")); - planilhaCompletum.Telefone2 = (list == null || list.Count <= 1 ? "" : list[1].Field<string>("fone")); - planilhaCompletum.Prefixo3 = (list == null || list.Count <= 2 ? "" : list[2].Field<string>("ddd")); - planilhaCompletum.Telefone3 = (list == null || list.Count <= 2 ? "" : list[2].Field<string>("fone")); - planilhaCompletum.Email1 = (dataRows == null || dataRows.Count <= 0 ? "" : dataRows[0].Field<string>("email")); - planilhaCompletum.Email2 = (dataRows == null || dataRows.Count <= 1 ? "" : dataRows[1].Field<string>("email")); - planilhaCompletum.Endereco = (dataRow1 != null ? dataRow1.Field<string>("endereco") : null); - planilhaCompletum.Numero = (dataRow1 != null ? dataRow1.Field<string>("numero") : null); - planilhaCompletum.Bairro = (dataRow1 != null ? dataRow1.Field<string>("bairro") : null); - planilhaCompletum.Cidade = (dataRow1 != null ? dataRow1.Field<string>("cidade") : null); - planilhaCompletum.Estado = (dataRow1 != null ? dataRow1.Field<string>("uf") : null); - planilhaCompletum.Cep = (dataRow1 != null ? dataRow1.Field<string>("cep") : null); - planilhaCompletum.BancoCliente = str5; - planilhaCompletum.AgenciaCliente = x.Field<string>("cliAgencia"); - planilhaCompletum.ContaCliente = x.Field<string>("cliConta"); - planilhaCompletum.NomeContato = (dataRow2 != null ? dataRow2.Field<string>("nome") : null); - if (dataRow2 != null) - { - nullable73 = dataRow2.Field<DateTime?>("dtnasc"); - if (!nullable73.HasValue) - { - goto Label1; - } - if (dataRow2 != null) - { - nullable31 = dataRow2.Field<DateTime?>("dtnasc"); - goto Label0; - } - else - { - nullable73 = null; - nullable31 = nullable73; - goto Label0; - } - } - Label1: - nullable73 = null; - nullable31 = nullable73; - Label0: - planilhaCompletum.NascimentoContato = nullable31; - planilhaCompletum.DocumentoContato = (dataRow2 != null ? dataRow2.Field<string>("cgccpf") : null); - planilhaCompletum.IdentidadeContato = (dataRow2 != null ? dataRow2.Field<string>("rg") : null); - if (dataRow2 != null) - { - nullable73 = dataRow2.Field<DateTime?>("rgexpedicao"); - if (!nullable73.HasValue) - { - goto Label3; - } - if (dataRow2 != null) - { - nullable32 = dataRow2.Field<DateTime?>("rgexpedicao"); - goto Label2; - } - else - { - nullable73 = null; - nullable32 = nullable73; - goto Label2; - } - } - Label3: - nullable73 = null; - nullable32 = nullable73; - Label2: - planilhaCompletum.ExpedicaoContato = nullable32; - planilhaCompletum.PrefixoContato = (dataRow2 != null ? dataRow2.Field<string>("ddd") : null); - planilhaCompletum.TelefoneContato = (dataRow2 != null ? dataRow2.Field<string>("fone") : null); - planilhaCompletum.EmailContato = (dataRow2 != null ? dataRow2.Field<string>("email") : null); - planilhaCompletum.HabilitacaoContato = (dataRow2 != null ? dataRow2.Field<string>("cnh") : null); - if (dataRow2 != null) - { - nullable73 = dataRow2.Field<DateTime?>("prihabilitacao"); - if (!nullable73.HasValue) - { - goto Label5; - } - if (dataRow2 != null) - { - nullable33 = dataRow2.Field<DateTime?>("prihabilitacao"); - goto Label4; - } - else - { - nullable73 = null; - nullable33 = nullable73; - goto Label4; - } - } - Label5: - nullable73 = null; - nullable33 = nullable73; - Label4: - planilhaCompletum.PrimeiraHabilitacaoContato = nullable33; - planilhaCompletum.BancoContato = (dataRow2 != null ? dataRow2.Field<string>("banco") : null); - planilhaCompletum.AgenciaContato = (dataRow2 != null ? dataRow2.Field<string>("agencia") : null); - planilhaCompletum.ContaContato = (dataRow2 != null ? dataRow2.Field<string>("conta") : null); - planilhaCompletum.DocumentoSinistrado = (num2 > 0 ? "SIM" : "NÃO"); - planilhaCompletum.Frota = (list1.Count == 0 ? "" : (list1.Count > 1 ? "ESTE DOCUMENTO SE TRATA DE UMA FROTA" : "")); - planilhaCompletum.DescricaoItem = (list1.Count == 0 ? "" : (list1.Count > 1 ? "ESTE DOCUMENTO SE TRATA DE UMA FROTA" : list1.First<DataRow>().Field<string>("descricao"))); - planilhaCompletum.StatusItem = (list1.Count == 0 || list1.Count > 1 ? "" : list1.First<DataRow>().Field<string>("status")); - planilhaCompletum.CodFipe = (string)((dataRow3 != null ? dataRow3.Field<string>("codfipe") : null) ?? ""); - if (dataRow3 != null && dataRow3.Field<object>("idcombustivel") != null) - { - if (string.IsNullOrWhiteSpace((dataRow3 != null ? dataRow3.Field<object>("idcombustivel").ToString() : null))) - { - goto Label7; - } - description = ((Combustivel)Enum.Parse(typeof(Combustivel), dataRow3.Field<object>("idcombustivel").ToString())).GetDescription<Combustivel>(); - goto Label6; - } - Label7: - description = ""; - Label6: - planilhaCompletum.Combustivel = description; - planilhaCompletum.Modelo = (string)((dataRow3 != null ? dataRow3.Field<string>("modelo") : null) ?? ""); - planilhaCompletum.Fabricante = (string)((dataRow3 != null ? dataRow3.Field<string>("fabricante") : null) ?? ""); - if (dataRow3 != null && dataRow3.Field<object>("idcategoria") != null) - { - if (string.IsNullOrWhiteSpace((dataRow3 != null ? dataRow3.Field<object>("idcategoria").ToString() : null))) - { - goto Label9; - } - description1 = ((Categoria)Enum.Parse(typeof(Categoria), dataRow3.Field<object>("idcategoria").ToString())).GetDescription<Categoria>(); - goto Label8; - } - Label9: - description1 = ""; - Label8: - planilhaCompletum.Categoria = description1; - planilhaCompletum.Chassi = (string)((dataRow3 != null ? dataRow3.Field<string>("chassi") : null) ?? ""); - planilhaCompletum.Placa = (string)((dataRow3 != null ? dataRow3.Field<string>("placa") : null) ?? ""); - planilhaCompletum.AnoFab = (string)((dataRow3 != null ? dataRow3.Field<string>("anofab") : null) ?? ""); - planilhaCompletum.AnoMod = (string)((dataRow3 != null ? dataRow3.Field<string>("anomod") : null) ?? ""); - planilhaCompletum.Renavam = (string)((dataRow3 != null ? dataRow3.Field<string>("renavam") : null) ?? ""); - planilhaCompletum.Capacidade = (string)((dataRow3 != null ? dataRow3.Field<string>("capacidade") : null) ?? ""); - planilhaCompletum.Portas = (string)((dataRow3 != null ? dataRow3.Field<string>("portas") : null) ?? ""); - planilhaCompletum.ObsAuto = (string)((dataRow3 != null ? dataRow3.Field<string>("obs") : null) ?? ""); - planilhaCompletum.ObsVida = (string)((dataRow8 != null ? dataRow8.Field<string>("obs") : null) ?? ""); - planilhaCompletum.RegCirc = (string)((dataRow3 != null ? dataRow3.Field<string>("regiaocirculacao") : null) ?? ""); - if (dataRow3 != null && dataRow3.Field<object>("idtabelareferencia") != null) - { - if (string.IsNullOrWhiteSpace((dataRow3 != null ? dataRow3.Field<object>("idtabelareferencia").ToString() : null))) - { - goto Label11; - } - str1 = ((TabelaReferencia)Enum.Parse(typeof(TabelaReferencia), dataRow3.Field<object>("idtabelareferencia").ToString())).GetDescription<TabelaReferencia>(); - goto Label10; - } - Label11: - str1 = ""; - Label10: - planilhaCompletum.TabelaRef = str1; - if (dataRow3 != null) - { - nullable34 = dataRow3.Field<decimal?>("porcentagemreferencia"); - } - else - { - nullable5 = null; - nullable34 = nullable5; - } - planilhaCompletum.PorcRef = nullable34; - if (dataRow3 != null) - { - nullable35 = dataRow3.Field<decimal?>("valordeterminado"); - } - else - { - nullable5 = null; - nullable35 = nullable5; - } - planilhaCompletum.ValorDeterminado = nullable35; - planilhaCompletum.Ci = (string)((dataRow3 != null ? dataRow3.Field<string>("ci") : null) ?? ""); - planilhaCompletum.CepPernoite = (string)((dataRow3 != null ? dataRow3.Field<string>("ceppernoite") : null) ?? ""); - planilhaCompletum.Financiado = (dataRow3 == null ? "" : (dataRow3.Field<string>("financiado") == "1" ? "SIM" : "NÃO")); - planilhaCompletum.ZeroKm = (dataRow3 == null ? "" : (dataRow3.Field<string>("zerokm") == "1" ? "SIM" : "NÃO")); - planilhaCompletum.Pcd = (dataRow3 == null ? "" : (dataRow3.Field<object>("pcd") == null || !(dataRow3.Field<object>("pcd").ToString() == "1") ? "NÃO" : "SIM")); - if (dataRow3 != null && dataRow3.Field<object>("idcor") != null) - { - if (string.IsNullOrWhiteSpace((dataRow3 != null ? dataRow3.Field<object>("idcor").ToString() : null))) - { - goto Label13; - } - description2 = ((Cor)Enum.Parse(typeof(Cor), dataRow3.Field<object>("idcor").ToString())).GetDescription<Cor>(); - goto Label12; - } - Label13: - description2 = ""; - Label12: - planilhaCompletum.Cor = description2; - if (dataRow3 != null && dataRow3.Field<object>("correcao") != null) - { - if (string.IsNullOrWhiteSpace((dataRow3 != null ? dataRow3.Field<object>("correcao").ToString() : null))) - { - goto Label15; - } - str2 = ((Correcao)Enum.Parse(typeof(Correcao), dataRow3.Field<object>("correcao").ToString())).GetDescription<Correcao>(); - goto Label14; - } - Label15: - str2 = ""; - Label14: - planilhaCompletum.Correcao = str2; - planilhaCompletum.Bonus = nullable72; - planilhaCompletum.CpfPerfil = (string)((dataRow12 != null ? dataRow12.Field<string>("cpf") : null) ?? ""); - planilhaCompletum.NomePerfil = (string)((dataRow12 != null ? dataRow12.Field<string>("nomecompleto") : null) ?? ""); - if (dataRow12 != null) - { - nullable36 = dataRow12.Field<DateTime?>("datanascimento"); - } - else - { - nullable8 = null; - nullable36 = nullable8; - } - nullable73 = nullable36; - if (nullable73.HasValue) - { - nullable37 = nullable73; - } - else - { - nullable8 = null; - nullable37 = nullable8; - } - planilhaCompletum.NascimentoPerfil = nullable37; - planilhaCompletum.SexoPerfil = str7 ?? ""; - planilhaCompletum.EstadoCivilPerfil = (string)((dataRow12 != null ? dataRow12.Field<string>("estadocivil") : null) ?? ""); - planilhaCompletum.CEPCirculacaoPerfil = (string)((dataRow12 != null ? dataRow12.Field<string>("cepcirculacao") : null) ?? ""); - planilhaCompletum.CEPPernoitePerfil = (string)((dataRow12 != null ? dataRow12.Field<string>("ceppernoite") : null) ?? ""); - planilhaCompletum.DanosMateriasPremios = new decimal?((cobertura1 != null ? cobertura1.Premio : decimal.Zero)); - planilhaCompletum.DanosMateriasFranquia = new decimal?((cobertura1 != null ? cobertura1.Franquia : decimal.Zero)); - planilhaCompletum.DanosMateriasLmi = new decimal?((cobertura1 != null ? cobertura1.Lmi : decimal.Zero)); - planilhaCompletum.DanosCorporaisPremios = new decimal?((cobertura != null ? cobertura.Premio : decimal.Zero)); - planilhaCompletum.DanosCorporaisFranquia = new decimal?((cobertura != null ? cobertura.Franquia : decimal.Zero)); - planilhaCompletum.DanosCorporaisLmi = new decimal?((cobertura != null ? cobertura.Lmi : decimal.Zero)); - planilhaCompletum.DanosMoraisPremios = new decimal?((cobertura2 != null ? cobertura2.Premio : decimal.Zero)); - planilhaCompletum.DanosMoraisFranquia = new decimal?((cobertura2 != null ? cobertura2.Franquia : decimal.Zero)); - planilhaCompletum.DanosMoraisLmi = new decimal?((cobertura2 != null ? cobertura2.Lmi : decimal.Zero)); - planilhaCompletum.AppPremios = new decimal?((cobertura3 != null ? cobertura3.Premio : decimal.Zero)); - planilhaCompletum.AppFranquia = new decimal?((cobertura3 != null ? cobertura3.Franquia : decimal.Zero)); - planilhaCompletum.AppLmi = new decimal?((cobertura3 != null ? cobertura3.Lmi : decimal.Zero)); - planilhaCompletum.CarroReservaPremios = new decimal?((cobertura4 != null ? cobertura4.Premio : decimal.Zero)); - planilhaCompletum.CarroReservaFranquia = new decimal?((cobertura4 != null ? cobertura4.Franquia : decimal.Zero)); - planilhaCompletum.CarroReservaLmi = new decimal?((cobertura4 != null ? cobertura4.Lmi : decimal.Zero)); - planilhaCompletum.CarroReservaObs = (cobertura4 != null ? cobertura4.Observacao : ""); - planilhaCompletum.EnderecoItem = (dataRow4 != null ? dataRow4.Field<string>("enderecoitem") : (dataRow5 != null ? dataRow5.Field<string>("endereco") : null)); - planilhaCompletum.NumeroItem = (dataRow4 != null ? dataRow4.Field<string>("numeroitem") : (dataRow5 != null ? dataRow5.Field<string>("numero") : null)); - planilhaCompletum.ComplementoItem = (dataRow4 != null ? dataRow4.Field<string>("complementoitem") : (dataRow5 != null ? dataRow5.Field<string>("complemento") : null)); - planilhaCompletum.BairroItem = (dataRow4 != null ? dataRow4.Field<string>("bairroitem") : (dataRow5 != null ? dataRow5.Field<string>("bairro") : null)); - planilhaCompletum.CidadeItem = (dataRow4 != null ? dataRow4.Field<string>("cidadeitem") : (dataRow5 != null ? dataRow5.Field<string>("cidade") : null)); - planilhaCompletum.UfItem = (dataRow4 != null ? dataRow4.Field<string>("ufitem") : (dataRow5 != null ? dataRow5.Field<string>("uf") : null)); - planilhaCompletum.CepItem = (dataRow4 != null ? dataRow4.Field<string>("cepitem") : (dataRow5 != null ? dataRow5.Field<string>("cep") : null)); - planilhaCompletum.ObsPatrimonial = (dataRow4 != null ? dataRow4.Field<string>("obsresidencia") : null); - planilhaCompletum.ObsGranizo = (dataRow5 != null ? dataRow5.Field<string>("obs") : null); - planilhaCompletum.CulturaGranizo = (dataRow5 != null ? dataRow5.Field<string>("cultura") : null); - planilhaCompletum.SitioGranizo = (dataRow5 != null ? dataRow5.Field<string>("sitio") : null); - if (dataRow5 != null) - { - nullable38 = dataRow5.Field<decimal?>("subfed"); - } - else - { - nullable5 = null; - nullable38 = nullable5; - } - planilhaCompletum.SubFedGranizo = nullable38; - if (dataRow5 != null) - { - nullable39 = dataRow5.Field<decimal?>("subest"); - } - else - { - nullable5 = null; - nullable39 = nullable5; - } - planilhaCompletum.SubEstGranizo = nullable39; - planilhaCompletum.ImobiliariaPatrimonial = (dataRow4 != null ? dataRow4.Field<string>("imobiliaria") : null); - planilhaCompletum.ContatoPatrimonial = (dataRow4 != null ? dataRow4.Field<string>("contatoresidencia") : null); - planilhaCompletum.Locatario = (dataRow4 != null ? dataRow4.Field<string>("locatario") : null); - planilhaCompletum.DocumentoLocatario = (dataRow4 != null ? dataRow4.Field<string>("cpflocatario1") : null); - planilhaCompletum.DddLocatario = (dataRow4 != null ? dataRow4.Field<string>("dddloc") : null); - planilhaCompletum.TelefoneLocatario = (dataRow4 != null ? dataRow4.Field<string>("foneloc") : null); - planilhaCompletum.Ddd2Locatario = (dataRow4 != null ? dataRow4.Field<string>("ddd2loc") : null); - planilhaCompletum.Telefone2Locatario = (dataRow4 != null ? dataRow4.Field<string>("fone2loc") : null); - planilhaCompletum.Locatario2 = (dataRow4 != null ? dataRow4.Field<string>("locatario2") : null); - planilhaCompletum.DocumentoLocatario2 = (dataRow4 != null ? dataRow4.Field<string>("cpflocatario2") : null); - planilhaCompletum.DddLocatario2 = (dataRow4 != null ? dataRow4.Field<string>("dddlocatario2") : null); - planilhaCompletum.TelefoneLocatario2 = (dataRow4 != null ? dataRow4.Field<string>("fonelocatario2") : null); - planilhaCompletum.Locatario3 = (dataRow4 != null ? dataRow4.Field<string>("locatario3") : null); - planilhaCompletum.DocumentoLocatario3 = (dataRow4 != null ? dataRow4.Field<string>("cpflocatario3") : null); - planilhaCompletum.DddLocatario3 = (dataRow4 != null ? dataRow4.Field<string>("dddlocatario3") : null); - planilhaCompletum.TelefoneLocatario3 = (dataRow4 != null ? dataRow4.Field<string>("fonelocatario3") : null); - planilhaCompletum.BensPatrimonial = (dataRow4 != null ? dataRow4.Field<string>("bens") : null); - planilhaCompletum.FabricanteAero = (dataRow6 != null ? dataRow6.Field<string>("fabricante") : null); - planilhaCompletum.ModeloAero = (dataRow6 != null ? dataRow6.Field<string>("modelo") : null); - planilhaCompletum.SerieAero = (dataRow6 != null ? dataRow6.Field<string>("serieregistro") : null); - planilhaCompletum.NomeAero = (dataRow6 != null ? dataRow6.Field<string>("nomeprefixo") : null); - if (dataRow6 != null) - { - nullable40 = dataRow6.Field<int?>("anofab"); - } - else - { - nullable75 = null; - nullable40 = nullable75; - } - planilhaCompletum.AnoFabAero = nullable40; - if (dataRow6 != null) - { - nullable41 = dataRow6.Field<int?>("tripulantes"); - } - else - { - nullable75 = null; - nullable41 = nullable75; - } - planilhaCompletum.TripulantesAero = nullable41; - if (dataRow6 != null) - { - nullable42 = dataRow6.Field<int?>("passageiros"); - } - else - { - nullable75 = null; - nullable42 = nullable75; - } - nullable75 = nullable42; - planilhaCompletum.PassageirosAero = new int?(nullable75.GetValueOrDefault()); - if (dataRow6 != null) - { - nullable43 = dataRow6.Field<long?>("peso"); - } - else - { - nullable9 = null; - nullable43 = nullable9; - } - nullable9 = nullable43; - planilhaCompletum.PesoAero = new decimal?(nullable9.GetValueOrDefault()); - planilhaCompletum.MarinaAero = (dataRow6 != null ? dataRow6.Field<string>("marinaaero") : null); - planilhaCompletum.CertificadoAero = (dataRow6 != null ? dataRow6.Field<string>("certificado") : null); - if (dataRow6 != null) - { - nullable44 = dataRow6.Field<DateTime?>("vistoria"); - } - else - { - nullable73 = null; - nullable44 = nullable73; - } - planilhaCompletum.VistoriaAero = nullable44; - planilhaCompletum.CascoAero = (dataRow6 != null ? dataRow6.Field<string>("casco") : null); - planilhaCompletum.NavegacaoAero = (dataRow6 != null ? dataRow6.Field<string>("navegacao") : null); - planilhaCompletum.ObsAero = (dataRow6 != null ? dataRow6.Field<string>("obs") : null); - planilhaCompletum.ObsRiscos = (dataRow7 != null ? dataRow7.Field<string>("obs") : null); - if (dataRow7 != null) - { - nullable45 = dataRow7.Field<decimal?>("subfed"); - } - else - { - nullable5 = null; - nullable45 = nullable5; - } - planilhaCompletum.SubFedRiscos = nullable45; - if (dataRow7 != null) - { - nullable46 = dataRow7.Field<decimal?>("subest"); - } - else - { - nullable5 = null; - nullable46 = nullable5; - } - planilhaCompletum.SubEstRiscos = nullable46; - planilhaCompletum.PlanoVida = (dataRow8 != null ? dataRow8.Field<string>("plano") : null); - if (dataRow8 != null) - { - nullable47 = dataRow8.Field<int?>("socios"); - } - else - { - nullable75 = null; - nullable47 = nullable75; - } - planilhaCompletum.SociosVida = nullable47; - if (dataRow8 != null) - { - nullable48 = dataRow8.Field<int?>("funcionarios"); - } - else - { - nullable75 = null; - nullable48 = nullable75; - } - planilhaCompletum.FuncionariosVida = nullable48; - if (dataRow8 != null) - { - nullable49 = dataRow8.Field<decimal?>("capitalsocio"); - } - else - { - nullable5 = null; - nullable49 = nullable5; - } - planilhaCompletum.CapitalSociosVida = nullable49; - if (dataRow8 != null) - { - nullable50 = dataRow8.Field<decimal?>("capitalfunc"); - } - else - { - nullable5 = null; - nullable50 = nullable5; - } - planilhaCompletum.CapitalFuncionariosVida = nullable50; - planilhaCompletum.ObsItem = (list1.Count != 1 ? "" : list1.First<DataRow>().Field<string>("obs")); - planilhaCompletum.DescricaoSinistro = (dataRow9 != null ? dataRow9.Field<string>("descricao") : null); - planilhaCompletum.NumeroSinistro = (dataRow9 != null ? dataRow9.Field<string>("numsinistro") : null); - if (dataRow9 != null) - { - nullable73 = dataRow9.Field<DateTime?>("datareclamacao"); - if (!nullable73.HasValue) - { - goto Label17; - } - if (dataRow9 != null) - { - nullable51 = dataRow9.Field<DateTime?>("datareclamacao"); - goto Label16; - } - else - { - nullable73 = null; - nullable51 = nullable73; - goto Label16; - } - } - Label17: - nullable73 = null; - nullable51 = nullable73; - Label16: - planilhaCompletum.DataReclamacao = nullable51; - if (dataRow9 != null) - { - nullable73 = dataRow9.Field<DateTime?>("datasinistro"); - if (!nullable73.HasValue) - { - goto Label19; - } - if (dataRow9 != null) - { - nullable52 = dataRow9.Field<DateTime?>("datasinistro"); - goto Label18; - } - else - { - nullable73 = null; - nullable52 = nullable73; - goto Label18; - } - } - Label19: - nullable73 = null; - nullable52 = nullable73; - Label18: - planilhaCompletum.DataSinistro = nullable52; - if (dataRow9 != null) - { - nullable73 = dataRow9.Field<DateTime?>("dataliquidacao"); - if (!nullable73.HasValue) - { - goto Label21; - } - if (dataRow9 != null) - { - nullable53 = dataRow9.Field<DateTime?>("dataliquidacao"); - goto Label20; - } - else - { - nullable73 = null; - nullable53 = nullable73; - goto Label20; - } - } - Label21: - nullable73 = null; - nullable53 = nullable73; - Label20: - planilhaCompletum.DataLiquidacao = nullable53; - planilhaCompletum.ObsSinistro = (str6.Length > 30000 ? str6.Substring(0, 30000) : str6); - planilhaCompletum.MotivoSinistro = (dataRow9 != null ? dataRow9.Field<string>("motivo") : null); - if (dataRow9 != null) - { - nullable5 = dataRow9.Field<decimal?>("valor"); - if (!nullable5.HasValue) - { - goto Label23; - } - if (dataRow9 != null) - { - nullable54 = dataRow9.Field<decimal?>("valor"); - goto Label22; - } - else - { - nullable5 = null; - nullable54 = nullable5; - goto Label22; - } - } - Label23: - nullable5 = null; - nullable54 = nullable5; - Label22: - planilhaCompletum.ValorSinistro = nullable54; - if (dataRow9 != null) - { - nullable5 = dataRow9.Field<decimal?>("vlrfranquia"); - if (!nullable5.HasValue) - { - goto Label25; - } - if (dataRow9 != null) - { - nullable55 = dataRow9.Field<decimal?>("vlrfranquia"); - goto Label24; - } - else - { - nullable5 = null; - nullable55 = nullable5; - goto Label24; - } - } - Label25: - nullable5 = null; - nullable55 = nullable5; - Label24: - planilhaCompletum.ValorFranquiaSinistro = nullable55; - if (dataRow9 != null) - { - nullable5 = dataRow9.Field<decimal?>("vlrorcado"); - if (!nullable5.HasValue) - { - goto Label27; - } - if (dataRow9 != null) - { - nullable56 = dataRow9.Field<decimal?>("vlrorcado"); - goto Label26; - } - else - { - nullable5 = null; - nullable56 = nullable5; - goto Label26; - } - } - Label27: - nullable5 = null; - nullable56 = nullable5; - Label26: - planilhaCompletum.ValorOrcado = nullable56; - if (dataRow9 != null) - { - nullable5 = dataRow9.Field<decimal?>("vlrliberado"); - if (!nullable5.HasValue) - { - goto Label29; - } - if (dataRow9 != null) - { - nullable57 = dataRow9.Field<decimal?>("vlrliberado"); - goto Label28; - } - else - { - nullable5 = null; - nullable57 = nullable5; - goto Label28; - } - } - Label29: - nullable5 = null; - nullable57 = nullable5; - Label28: - planilhaCompletum.ValorLiberado = nullable57; - if (dataRow9 != null) - { - nullable5 = dataRow9.Field<decimal?>("vlrpago"); - if (!nullable5.HasValue) - { - goto Label31; - } - if (dataRow9 != null) - { - nullable58 = dataRow9.Field<decimal?>("vlrpago"); - goto Label30; - } - else - { - nullable5 = null; - nullable58 = nullable5; - goto Label30; - } - } - Label31: - nullable5 = null; - nullable58 = nullable5; - Label30: - planilhaCompletum.ValorPago = nullable58; - if (dataRow9 != null) - { - nullable5 = dataRow9.Field<decimal?>("vlrsalvado"); - if (!nullable5.HasValue) - { - goto Label33; - } - if (dataRow9 != null) - { - nullable59 = dataRow9.Field<decimal?>("vlrsalvado"); - goto Label32; - } - else - { - nullable5 = null; - nullable59 = nullable5; - goto Label32; - } - } - Label33: - nullable5 = null; - nullable59 = nullable5; - Label32: - planilhaCompletum.ValorSalvo = nullable59; - planilhaCompletum.Parentesco = (dataRow10 != null ? ((ParentescoVinculo?)Enum.Parse(typeof(ParentescoVinculo), dataRow10.Field<object>("parentesco").ToString())).GetDescription<ParentescoVinculo?>() : ""); - if (dataRow11 != null) - { - nullable5 = dataRow11.Field<decimal?>("franquia"); - if (!nullable5.HasValue) - { - goto Label35; - } - if (dataRow11 != null) - { - nullable60 = dataRow11.Field<decimal?>("franquia"); - goto Label34; - } - else - { - nullable5 = null; - nullable60 = nullable5; - goto Label34; - } - } - Label35: - nullable5 = null; - nullable60 = nullable5; - Label34: - planilhaCompletum.ValorFranquiaApolice = nullable60; - planilhaCompletum.QtdeEndosso = num1; - planilhaCompletum.QtdeSinistro = num2; - planilhaCompletum.BensConsorcio = (dataRow13 != null ? dataRow13.Field<string>("bensconsorcio") : null); - planilhaCompletum.Grupo = (dataRow13 != null ? dataRow13.Field<string>("grupo") : null); - planilhaCompletum.Cota = (dataRow13 != null ? dataRow13.Field<string>("cota") : null); - if (dataRow13 != null) - { - nullable61 = dataRow13.Field<decimal?>("valorCredito"); - } - else - { - nullable5 = null; - nullable61 = nullable5; - } - planilhaCompletum.ValorCredito = nullable61; - planilhaCompletum.AreaRiscos = (dataRow7 != null ? dataRow7.Field<string>("area") : null); - planilhaCompletum.AreaGranizo = (dataRow5 != null ? dataRow5.Field<string>("area") : null); - planilhaCompletas.Add(planilhaCompletum); - } - catch (Exception exception) - { - } - }); - return planilhaCompletas; - } - - public List<PlanilhaCompleta> PlanilhaCompletaFatura(List<long> ids, Relatorio relatorio, DateTime inicio, DateTime fim, bool configFranquia, bool configSomaPremio) - { - // - // Current member / type: System.Collections.Generic.List`1<Gestor.Model.Domain.Relatorios.PlanilhaCompleta> Gestor.Infrastructure.Repository.Logic.ReportRepository::PlanilhaCompletaFatura(System.Collections.Generic.List`1<System.Int64>,Gestor.Model.Common.Relatorio,System.DateTime,System.DateTime,System.Boolean,System.Boolean) - // File path: C:\AggerSeguros\Lib\Gestor.Infrastructure.dll - // - // Product version: 0.0.0.0 - // Exception in: System.Collections.Generic.List<Gestor.Model.Domain.Relatorios.PlanilhaCompleta> PlanilhaCompletaFatura(System.Collections.Generic.List<System.Int64>,Gestor.Model.Common.Relatorio,System.DateTime,System.DateTime,System.Boolean,System.Boolean) - // - // An item with the same key has already been added. Key: Label0 - // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) - // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>.Add(KeyValuePair`2 keyValuePair) - // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 99 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 332 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 290 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ExpressionCollection node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 322 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 499 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitExpressionStatement(ExpressionStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 383 - // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.Match(BlockStatement theBlock, Int32 index) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 114 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.VisitBlockStatement(BlockStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 30 - // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 21 - // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.RunInternal(MethodBody body, BlockStatement block, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 100 - // at Telerik.JustDecompiler.Decompiler.DecompilationPipeline.Run(MethodBody body, ILanguage language) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\DecompilationPipeline.cs:line 72 - // at Telerik.JustDecompiler.Decompiler.Extensions.RunPipeline(DecompilationPipeline pipeline, ILanguage language, MethodBody body, DecompilationContext& context) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 95 - // at Telerik.JustDecompiler.Decompiler.Extensions.Decompile(MethodBody body, ILanguage language, DecompilationContext& context, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 61 - // at Telerik.JustDecompiler.Decompiler.WriterContextServices.BaseWriterContextService.DecompileMethod(ILanguage language, MethodDefinition method, TypeSpecificContext typeContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\WriterContextServices\BaseWriterContextService.cs:line 118 - // - // mailto: JustDecompilePublicFeedback@telerik.com - - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs deleted file mode 100644 index 12ab574..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs +++ /dev/null @@ -1,44 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using System; -using System.Collections.Generic; -using System.Linq; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class RestricaoUsuarioCamposRelatoriosRepository : GenericRepository<RestricaoUsuarioCamposRelatoriosDb>, IRestricaoUsuarioCamposRelatoriosRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public RestricaoUsuarioCamposRelatoriosRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List<RestricaoUsuarioCamposRelatorios> FindByUsuario(long id) - { - List<RestricaoUsuarioCamposRelatoriosDb> list = this._unitOfWork.Session.CreateQuery(string.Format("from RestricaoUsuarioCamposRelatoriosDb WHERE Usuario = {0}", id)).List<RestricaoUsuarioCamposRelatoriosDb>().ToList<RestricaoUsuarioCamposRelatoriosDb>(); - return ApplicationMapper.Mapper.Map<List<RestricaoUsuarioCamposRelatoriosDb>, List<RestricaoUsuarioCamposRelatorios>>(list); - } - - public RestricaoUsuarioCamposRelatorios Merge(RestricaoUsuarioCamposRelatorios restricao) - { - RestricaoUsuarioCamposRelatoriosDb restricaoUsuarioCamposRelatoriosDb = ApplicationMapper.Mapper.Map<RestricaoUsuarioCamposRelatorios, RestricaoUsuarioCamposRelatoriosDb>(restricao); - base.Merge(restricaoUsuarioCamposRelatoriosDb); - return ApplicationMapper.Mapper.Map<RestricaoUsuarioCamposRelatoriosDb, RestricaoUsuarioCamposRelatorios>(restricaoUsuarioCamposRelatoriosDb); - } - - public RestricaoUsuarioCamposRelatorios SaveOrUpdate(RestricaoUsuarioCamposRelatorios restricao) - { - RestricaoUsuarioCamposRelatoriosDb restricaoUsuarioCamposRelatoriosDb = ApplicationMapper.Mapper.Map<RestricaoUsuarioCamposRelatorios, RestricaoUsuarioCamposRelatoriosDb>(restricao); - this.SaveOrUpdate(restricaoUsuarioCamposRelatoriosDb); - return ApplicationMapper.Mapper.Map<RestricaoUsuarioCamposRelatoriosDb, RestricaoUsuarioCamposRelatorios>(restricaoUsuarioCamposRelatoriosDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs deleted file mode 100644 index 3d1fbcc..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs +++ /dev/null @@ -1,54 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -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.Seguros; -using NHibernate; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class RestricaoUsuarioRepository : GenericRepository<RestricaoUsuarioDb>, IRestricaoUsuarioRepository - { - private readonly GenericUnitOfWork _unitOfWork; - - public RestricaoUsuarioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List<RestricaoUsuario> FindByUsuario(long id) - { - List<RestricaoUsuarioDb> list = this._unitOfWork.Session.CreateQuery(string.Format("from RestricaoUsuarioDb WHERE IdUsuario = {0}", id)).List<RestricaoUsuarioDb>().ToList<RestricaoUsuarioDb>(); - return ApplicationMapper.Mapper.Map<List<RestricaoUsuarioDb>, List<RestricaoUsuario>>(list); - } - - public RestricaoUsuario FindRestricao(long id, TipoRestricao restricao) - { - RestricaoUsuarioDb restricaoUsuarioDb = base.All().FirstOrDefault<RestricaoUsuarioDb>((RestricaoUsuarioDb x) => x.Usuario.Id == id && (int)x.Tipo == (int)restricao); - return ApplicationMapper.Mapper.Map<RestricaoUsuarioDb, RestricaoUsuario>(restricaoUsuarioDb); - } - - public RestricaoUsuario Merge(RestricaoUsuario restricao) - { - RestricaoUsuarioDb restricaoUsuarioDb = ApplicationMapper.Mapper.Map<RestricaoUsuario, RestricaoUsuarioDb>(restricao); - base.Merge(restricaoUsuarioDb); - return ApplicationMapper.Mapper.Map<RestricaoUsuarioDb, RestricaoUsuario>(restricaoUsuarioDb); - } - - public RestricaoUsuario SaveOrUpdate(RestricaoUsuario restricao) - { - RestricaoUsuarioDb restricaoUsuarioDb = ApplicationMapper.Mapper.Map<RestricaoUsuario, RestricaoUsuarioDb>(restricao); - this.SaveOrUpdate(restricaoUsuarioDb); - return ApplicationMapper.Mapper.Map<RestricaoUsuarioDb, RestricaoUsuario>(restricaoUsuarioDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs deleted file mode 100644 index 6353540..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs +++ /dev/null @@ -1,66 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class RiscosDiversosRepository : GenericRepository<RiscosDiversosDb>, IRiscosDiversosRepository, IGenericRepository<RiscosDiversosDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public RiscosDiversosRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public void DeleteRange(List<long> ids) - { - List<RiscosDiversosDb> list = ( - from x in base.All() - where ids.Contains(x.Item.Id) - select x).ToList<RiscosDiversosDb>(); - base.DeleteRange(list); - } - - public RiscosDiversos Find(long id) - { - RiscosDiversosDb riscosDiversosDb = base.All().FirstOrDefault<RiscosDiversosDb>((RiscosDiversosDb x) => x.Item.Id == id) ?? new RiscosDiversosDb(); - return ApplicationMapper.Mapper.Map<RiscosDiversosDb, RiscosDiversos>(riscosDiversosDb); - } - - public RiscosDiversos FindById(long id) - { - RiscosDiversosDb riscosDiversosDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<RiscosDiversosDb, RiscosDiversos>(riscosDiversosDb); - } - - public RiscosDiversos Merge(RiscosDiversos risco) - { - RiscosDiversosDb riscosDiversosDb = ApplicationMapper.Mapper.Map<RiscosDiversos, RiscosDiversosDb>(risco); - base.Merge(riscosDiversosDb); - return ApplicationMapper.Mapper.Map<RiscosDiversosDb, RiscosDiversos>(riscosDiversosDb); - } - - public RiscosDiversos SaveOrUpdate(RiscosDiversos risco) - { - RiscosDiversosDb riscosDiversosDb = ApplicationMapper.Mapper.Map<RiscosDiversos, RiscosDiversosDb>(risco); - this.SaveOrUpdate(riscosDiversosDb); - return ApplicationMapper.Mapper.Map<RiscosDiversosDb, RiscosDiversos>(riscosDiversosDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs deleted file mode 100644 index 5249fcf..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs +++ /dev/null @@ -1,136 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Financeiro; -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.Domain.Financeiro; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class SaldoRepository : GenericRepository<SaldoDb>, ISaldoRepository, IGenericRepository<SaldoDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public SaldoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public Saldo BuscarAberto(long id) - { - string str = string.Format(" AND idconta = {0} AND dtfim IS NULL", id); - return this.Select(str).FirstOrDefault<Saldo>(); - } - - public List<Saldo> BuscarPorConta(long id) - { - return this.Select(string.Format(" AND idconta = {0}", id)); - } - - public Saldo BuscarPorData(DateTime inicio, long id) - { - string str = string.Format(" AND idconta = {0}", id); - return ( - from x in this.Select(str) - orderby x.DataInicio descending - select x).FirstOrDefault<Saldo>((Saldo x) => { - DateTime? dataInicio = x.DataInicio; - DateTime dateTime = inicio; - if (!dataInicio.HasValue) - { - return false; - } - return dataInicio.GetValueOrDefault() <= dateTime; - }); - } - - public Saldo BuscarPorMenorData(long id) - { - string str = string.Format(" AND idconta = {0}", id); - return ( - from x in this.Select(str) - orderby x.DataInicio - select x).FirstOrDefault<Saldo>(); - } - - public void Delete(long id) - { - SaldoDb saldoDb = base.FindEntityById(id); - if (saldoDb == null) - { - return; - } - base.Delete(saldoDb); - } - - public Saldo FindById(long id) - { - SaldoDb saldoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<SaldoDb, Saldo>(saldoDb); - } - - public Saldo Merge(Saldo saldo) - { - SaldoDb saldoDb = ApplicationMapper.Mapper.Map<Saldo, SaldoDb>(saldo); - base.Merge(saldoDb); - return ApplicationMapper.Mapper.Map<SaldoDb, Saldo>(saldoDb); - } - - public Saldo SaveOrUpdate(Saldo saldo) - { - SaldoDb saldoDb = ApplicationMapper.Mapper.Map<Saldo, SaldoDb>(saldo); - this.SaveOrUpdate(saldoDb); - return ApplicationMapper.Mapper.Map<SaldoDb, Saldo>(saldoDb); - } - - private List<Saldo> Select(string condition) - { - List<Saldo> saldos; - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - AuxiliarFinanceiro.Criar(sqlCommand); - sqlCommand.CommandText = string.Concat("SELECT * FROM saldo WHERE 1=1 ", condition); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - if (dataTable.Rows.Count != 0) - { - return CustomMap.MapSaldo(dataTable); - } - else - { - saldos = new List<Saldo>(); - } - } - } - return saldos; - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs deleted file mode 100644 index 19ee09a..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs +++ /dev/null @@ -1,131 +0,0 @@ -using AutoMapper; -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.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class SeguradoraContatoRepository : GenericRepository<SeguradoraContatoDb>, ISeguradoraContatoRepository, IGenericRepository<SeguradoraContatoDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public SeguradoraContatoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - SeguradoraContatoDb seguradoraContatoDb = base.FindEntityById(id); - if (seguradoraContatoDb == null) - { - return; - } - base.Delete(seguradoraContatoDb); - } - - public List<SeguradoraContato> FindAssistencia(long empresa, long id) - { - List<Condicao> condicaos = new List<Condicao>() - { - new Condicao() - { - Campo = "idempresa", - Valores = empresa.CriarValor<long>() - }, - new Condicao() - { - Campo = "idciaseg", - Valores = id.CriarValor<long>() - }, - new Condicao() - { - Campo = "TipoContato", - Valores = 1.CriarValor<int>() - } - }; - return this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT TOP 4 * FROM ciacontato WHERE ", "").MapSeguradoraContato(); - } - - public SeguradoraContato FindById(long id) - { - SeguradoraContatoDb seguradoraContatoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<SeguradoraContatoDb, SeguradoraContato>(seguradoraContatoDb); - } - - public List<SeguradoraContato> FindBySeguradora(long empresa, long id) - { - List<Condicao> condicaos = new List<Condicao>() - { - new Condicao() - { - Campo = "idempresa", - Valores = empresa.CriarValor<long>() - }, - new Condicao() - { - Campo = "idciaseg", - Valores = id.CriarValor<long>() - } - }; - return this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM ciacontato WHERE ", "").MapSeguradoraContato(); - } - - public SeguradoraContato Merge(SeguradoraContato contato) - { - SeguradoraContatoDb seguradoraContatoDb = ApplicationMapper.Mapper.Map<SeguradoraContato, SeguradoraContatoDb>(contato); - base.Merge(seguradoraContatoDb); - return ApplicationMapper.Mapper.Map<SeguradoraContatoDb, SeguradoraContato>(seguradoraContatoDb); - } - - public List<SeguradoraContato> Merge(List<SeguradoraContato> contatos, Seguradora seguradora, long empresa) - { - IQueryable<SeguradoraContatoDb> seguradoraContatoDbs = - from x in base.All() - where x.Seguradora.Id == seguradora.Id && x.Empresa.Id == empresa - select x; - SeguradoraContatoRepository seguradoraContatoRepository = this; - ( - from x in seguradoraContatoDbs - select x.Id).ToList<long>().Where<long>((long x) => { - List<SeguradoraContato> seguradoraContatos = contatos; - Func<SeguradoraContato, long> u003cu003e9_64 = SeguradoraContatoRepository.u003cu003ec.u003cu003e9__6_4; - if (u003cu003e9_64 == null) - { - u003cu003e9_64 = (SeguradoraContato t) => t.Id; - SeguradoraContatoRepository.u003cu003ec.u003cu003e9__6_4 = u003cu003e9_64; - } - return !seguradoraContatos.Select<SeguradoraContato, long>(u003cu003e9_64).Contains<long>(x); - }).ToList<long>().ForEach(new Action<long>(seguradoraContatoRepository.Delete)); - List<SeguradoraContatoDb> seguradoraContatoDbs1 = ApplicationMapper.Mapper.Map<List<SeguradoraContato>, List<SeguradoraContatoDb>>(contatos); - seguradoraContatoDbs1.ForEach((SeguradoraContatoDb x) => { - if (x.Id == 0) - { - this.SaveOrUpdate(x); - return; - } - base.Merge(x); - }); - return ApplicationMapper.Mapper.Map<List<SeguradoraContatoDb>, List<SeguradoraContato>>(seguradoraContatoDbs1); - } - - public SeguradoraContato SaveOrUpdate(SeguradoraContato contato) - { - SeguradoraContatoDb seguradoraContatoDb = ApplicationMapper.Mapper.Map<SeguradoraContato, SeguradoraContatoDb>(contato); - this.SaveOrUpdate(seguradoraContatoDb); - return ApplicationMapper.Mapper.Map<SeguradoraContatoDb, SeguradoraContato>(seguradoraContatoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs deleted file mode 100644 index a88001e..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs +++ /dev/null @@ -1,97 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class SeguradoraEnderecoRepository : GenericRepository<SeguradoraEnderecoDb>, ISeguradoraEnderecoRepository, IGenericRepository<SeguradoraEnderecoDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public SeguradoraEnderecoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - SeguradoraEnderecoDb seguradoraEnderecoDb = base.FindEntityById(id); - if (seguradoraEnderecoDb == null) - { - return; - } - base.Delete(seguradoraEnderecoDb); - } - - public SeguradoraEndereco FindById(long id) - { - SeguradoraEnderecoDb seguradoraEnderecoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<SeguradoraEnderecoDb, SeguradoraEndereco>(seguradoraEnderecoDb); - } - - public List<SeguradoraEndereco> FindBySeguradora(long empresa, long id) - { - List<SeguradoraEnderecoDb> list = ( - from x in base.All() - where x.Empresa.Id == empresa && x.Seguradora.Id == id - select x).ToList<SeguradoraEnderecoDb>(); - return ApplicationMapper.Mapper.Map<List<SeguradoraEnderecoDb>, List<SeguradoraEndereco>>(list); - } - - public SeguradoraEndereco Merge(SeguradoraEndereco endereco) - { - SeguradoraEnderecoDb seguradoraEnderecoDb = ApplicationMapper.Mapper.Map<SeguradoraEndereco, SeguradoraEnderecoDb>(endereco); - base.Merge(seguradoraEnderecoDb); - return ApplicationMapper.Mapper.Map<SeguradoraEnderecoDb, SeguradoraEndereco>(seguradoraEnderecoDb); - } - - public List<SeguradoraEndereco> Merge(List<SeguradoraEndereco> enderecos, Seguradora seguradora, long empresa) - { - IQueryable<SeguradoraEnderecoDb> seguradoraEnderecoDbs = - from x in base.All() - where x.Seguradora.Id == seguradora.Id && x.Empresa.Id == empresa - select x; - SeguradoraEnderecoRepository seguradoraEnderecoRepository = this; - ( - from x in seguradoraEnderecoDbs - select x.Id).ToList<long>().Where<long>((long x) => { - List<SeguradoraEndereco> seguradoraEnderecos = enderecos; - Func<SeguradoraEndereco, long> u003cu003e9_64 = SeguradoraEnderecoRepository.u003cu003ec.u003cu003e9__6_4; - if (u003cu003e9_64 == null) - { - u003cu003e9_64 = (SeguradoraEndereco t) => t.Id; - SeguradoraEnderecoRepository.u003cu003ec.u003cu003e9__6_4 = u003cu003e9_64; - } - return !seguradoraEnderecos.Select<SeguradoraEndereco, long>(u003cu003e9_64).Contains<long>(x); - }).ToList<long>().ForEach(new Action<long>(seguradoraEnderecoRepository.Delete)); - List<SeguradoraEnderecoDb> seguradoraEnderecoDbs1 = ApplicationMapper.Mapper.Map<List<SeguradoraEndereco>, List<SeguradoraEnderecoDb>>(enderecos); - seguradoraEnderecoDbs1.ForEach((SeguradoraEnderecoDb x) => { - if (x.Id == 0) - { - this.SaveOrUpdate(x); - return; - } - base.Merge(x); - }); - return ApplicationMapper.Mapper.Map<List<SeguradoraEnderecoDb>, List<SeguradoraEndereco>>(seguradoraEnderecoDbs1); - } - - public SeguradoraEndereco SaveOrUpdate(SeguradoraEndereco endereco) - { - SeguradoraEnderecoDb seguradoraEnderecoDb = ApplicationMapper.Mapper.Map<SeguradoraEndereco, SeguradoraEnderecoDb>(endereco); - this.SaveOrUpdate(seguradoraEnderecoDb); - return ApplicationMapper.Mapper.Map<SeguradoraEnderecoDb, SeguradoraEndereco>(seguradoraEnderecoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs deleted file mode 100644 index 328fa86..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs +++ /dev/null @@ -1,76 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class SeguradoraRepository : GenericRepository<SeguradoraDb>, ISeguradoraRepository, IGenericRepository<SeguradoraDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public SeguradoraRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List<Seguradora> Find(string filter) - { - SeguradoraRepository.u003cu003ec__DisplayClass3_0 variable = null; - IQueryable<SeguradoraDb> seguradoraDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(SeguradoraDb), "x"); - IQueryable<SeguradoraDb> seguradoraDbs1 = seguradoraDbs.Where<SeguradoraDb>(Expression.Lambda<Func<SeguradoraDb, bool>>(Expression.OrElse(Expression.OrElse(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0)), FieldInfo.GetFieldFromHandle(typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Documento").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0)), FieldInfo.GetFieldFromHandle(typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0).GetField("filter").FieldHandle)) })), Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Susep").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0)), FieldInfo.GetFieldFromHandle(typeof(SeguradoraRepository.u003cu003ec__DisplayClass3_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(SeguradoraDb), "x"); - return seguradoraDbs1.Select<SeguradoraDb, Seguradora>(Expression.Lambda<Func<SeguradoraDb, Seguradora>>(Expression.MemberInit(Expression.New(typeof(Seguradora)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Seguradora).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Seguradora).GetMethod("set_Documento", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Documento").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Seguradora).GetMethod("set_Susep", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(SeguradoraDb).GetMethod("get_Susep").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList<Seguradora>(); - } - - public List<Seguradora> Find(bool ativo) - { - List<SeguradoraDb> list = this._unitOfWork.Session.CreateQuery("from SeguradoraDb where ativo IS NULL OR ativo = '1'").List<SeguradoraDb>().ToList<SeguradoraDb>(); - return ApplicationMapper.Mapper.Map<List<SeguradoraDb>, List<Seguradora>>(list); - } - - public List<Seguradora> Find() - { - List<SeguradoraDb> list = base.All().ToList<SeguradoraDb>(); - return ApplicationMapper.Mapper.Map<List<SeguradoraDb>, List<Seguradora>>(list); - } - - public Seguradora FindById(long id) - { - SeguradoraDb seguradoraDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<SeguradoraDb, Seguradora>(seguradoraDb); - } - - public Seguradora Merge(Seguradora seguradora) - { - SeguradoraDb seguradoraDb = ApplicationMapper.Mapper.Map<Seguradora, SeguradoraDb>(seguradora); - base.Merge(seguradoraDb); - return ApplicationMapper.Mapper.Map<SeguradoraDb, Seguradora>(seguradoraDb); - } - - public Seguradora SaveOrUpdate(Seguradora seguradora) - { - SeguradoraDb seguradoraDb = ApplicationMapper.Mapper.Map<Seguradora, SeguradoraDb>(seguradora); - this.SaveOrUpdate(seguradoraDb); - return ApplicationMapper.Mapper.Map<SeguradoraDb, Seguradora>(seguradoraDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs deleted file mode 100644 index f4ad079..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs +++ /dev/null @@ -1,61 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class SinistroAutoRepository : GenericRepository<SinistroAutoDb>, ISinistroAutoRepository, IGenericRepository<SinistroAutoDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public SinistroAutoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public SinistroAuto FindById(long id) - { - SinistroAutoDb sinistroAutoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<SinistroAutoDb, SinistroAuto>(sinistroAutoDb); - } - - public SinistroAuto FindBySinistroId(long id) - { - SinistroAutoDb sinistroAutoDb = base.All().FirstOrDefault<SinistroAutoDb>((SinistroAutoDb x) => x.Sinistro.Id == id); - return ApplicationMapper.Mapper.Map<SinistroAutoDb, SinistroAuto>(sinistroAutoDb); - } - - public SinistroAuto Merge(SinistroAuto sinistroAuto) - { - SinistroAutoDb sinistroAutoDb = ApplicationMapper.Mapper.Map<SinistroAuto, SinistroAutoDb>(sinistroAuto); - base.Merge(sinistroAutoDb); - return ApplicationMapper.Mapper.Map<SinistroAutoDb, SinistroAuto>(sinistroAutoDb); - } - - public bool ParceiroUtilizado(long id) - { - return base.All().Any<SinistroAutoDb>((SinistroAutoDb x) => x.ParceiroFunilaria.Id == id || x.ParceiroMecanica.Id == id); - } - - public SinistroAuto SaveOrUpdate(SinistroAuto sinistroAuto) - { - SinistroAutoDb sinistroAutoDb = ApplicationMapper.Mapper.Map<SinistroAuto, SinistroAutoDb>(sinistroAuto); - this.SaveOrUpdate(sinistroAutoDb); - return ApplicationMapper.Mapper.Map<SinistroAutoDb, SinistroAuto>(sinistroAutoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs deleted file mode 100644 index ba62ba0..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs +++ /dev/null @@ -1,415 +0,0 @@ -using AutoMapper; -using Gestor.Common.Validation; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Helpers; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Common; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Relatorios; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using NHibernate.Util; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class SinistroRepository : GenericRepository<SinistroDb>, ISinistroRepository, IGenericRepository<SinistroDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public SinistroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List<Sinistro> Find(string numero) - { - List<SinistroDb> list = ( - from x in base.All() - where x.Numero.Normalized().Contains(numero.Normalized()) && numero.Normalized().Contains(x.Numero.Normalized()) - select x).ToList<SinistroDb>(); - return ApplicationMapper.Mapper.Map<List<SinistroDb>, List<Sinistro>>(list); - } - - public List<Sinistro> FindByControleId(long id) - { - List<SinistroDb> list = ( - from x in base.All() - where x.ControleSinistro.Id == id - select x).ToList<SinistroDb>(); - List<Sinistro> sinistros = ApplicationMapper.Mapper.Map<List<SinistroDb>, List<Sinistro>>(list); - sinistros.ForEach((Sinistro x) => { - x.SinistroAuto = (new SinistroAutoRepository(this._unitOfWork)).FindBySinistroId(x.Id); - x.SinistroVida = (new SinistroVidaRepository(this._unitOfWork)).FindBySinistroId(x.Id); - }); - return sinistros; - } - - public List<Sinistro> FindByData(Filtros filtro, bool pendentes = false) - { - object connection; - string str = "CAST(cs.datasinistro AS DATE)"; - string referencia = filtro.Referencia; - if (referencia == "DATA LIQUIDAÇÃO") - { - str = "CAST(s.dataliquidacao AS DATE)"; - } - else if (referencia == "DATA RECLAMAÇÃO") - { - str = "CAST(s.datareclamacao AS DATE)"; - } - List<Condicao> condicaos2 = filtro.CriarCondicao(str); - List<Condicao> list = ( - from x in condicaos2 - where x.Campo == str - select x).ToList<Condicao>(); - if (pendentes) - { - list.Add(new Condicao() - { - Campo = "CAST(s.dataliquidacao AS DATE)", - Valores = null - }); - } - string str1 = (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), ")")); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - DataTable dataTable1 = new DataTable(); - DataTable dataTable2 = new DataTable(); - DataTable dataTable3 = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - string str2 = "SELECT DISTINCT cs.iditem as id, cs.idcontrolesinistro, s.idsinistro, cs.datasinistro as data, s.numsinistro as numero, s.datareclamacao as reclamacao, s.itemsinistrado as item, s.motivo, s.tiposinistro, s.valor as valor, s.vlrorcado as valororcado, s.vlrliberado as valorliberado, s.vlrpago as valorpago, s.vlrfranquia as valorfranquia, s.vlrsalvado as valorsalvado, s.dataliquidacao as liquidacao, s.idstatussinistro, s.StatusPersonalizado, s.auxiliar, s.usuariocriacao, s.usuarioalteracao, s.datacriacao, s.dataalteracao FROM sinistro s INNER JOIN controlesinistro cs on cs.idcontrolesinistro = s.idcontrolesinistro WHERE "; - dataTable = sqlCommand.Select(list.CreateParameters(0), str2, ""); - if (dataTable.Rows.Count != 0) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - List<Condicao> list1 = condicaos2.Where<Condicao>((Condicao x) => { - if (x.Campo == this.referencia) - { - return false; - } - return x.Campo != "CAST(s.dataliquidacao AS DATE)"; - }).ToList<Condicao>(); - list1.Add(new Condicao() - { - Campo = "d.excluido", - Valores = null, - Grupo = 1, - Operacao = Operacao.Or - }); - list1.Add(new Condicao() - { - Campo = "d.excluido", - Valores = "0".CriarValor<string>(), - Grupo = 1, - Operacao = Operacao.Or - }); - string str3 = string.Concat("SELECT i.iditem as id, cl.nome as cliente, cl.MalaDireta, cl.idcliente, c.idcontrole, c.idempresa, i.iddocumento, d.contrato as apolice, d.aditamento as endosso, d.vigencia1, d.vigencia2, c.idramo, c.idciaseg as idseguradora, c.idproduto, vp.idvendedor, d.idestipulante, d.datacontrole, d.idstatus, d.pasta, cl.pasta as pastacliente, cl.cgccpf as cpfcnpj FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente ", str1, " WHERE "); - dataTable.AsEnumerable().ForEach<DataRow>((DataRow sinistro) => { - List<Condicao> condicaos = new List<Condicao>() - { - new Condicao() - { - Campo = "i.iditem", - Valores = sinistro.Field<long>("id").CriarValor<long>() - } - }; - condicaos.AddRange(list1); - List<Condicao> condicaos1 = new List<Condicao>() - { - new Condicao() - { - Campo = "idsinistro", - Valores = sinistro.Field<long>("idsinistro").CriarValor<long>() - } - }; - dataTable1.Merge(sqlCommand.Select(condicaos.CreateParameters(0), str3, "")); - dataTable2.Merge(sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT * FROM sinistroauto WHERE", "")); - dataTable3.Merge(sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT * FROM sinistrovida WHERE", "")); - }); - } - else - { - return new List<Sinistro>(); - } - } - } - } - List<long> nums = dataTable1.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("id")).ToList<long>(); - List<Sinistro> sinistros = new List<Sinistro>(); - dataTable.AsEnumerable().Where<DataRow>((DataRow x) => nums.Contains(x.Field<long>("id"))).ForEach<DataRow>((DataRow x) => { - TipoPerda? nullable; - object sinistroAuto; - object sinistroVida; - TipoPerda? nullable1; - Parceiro parceiro; - Parceiro parceiro1; - TipoPerda? nullable2; - DataRow dataRow = dataTable1.Select(string.Format("id = {0}", x.Field<long>("id"))).FirstOrDefault<DataRow>(); - if (dataRow == null) - { - return; - } - DataRow dataRow1 = dataTable2.AsEnumerable().ToList<DataRow>().FirstOrDefault<DataRow>((DataRow a) => a.Field<long>("idsinistro") == x.Field<long>("idsinistro")); - if (dataRow1 == null) - { - sinistroAuto = null; - } - else - { - sinistroAuto = new SinistroAuto(); - ((DomainBase)sinistroAuto).Id = dataRow1.Field<long>("idsinistroauto"); - parceiro = (dataRow1.Field<object>("idparceirofunilaria") == null ? null : Auxiliar.Parceiros.Find((Parceiro a) => a.Id == dataRow1.Field<long>("idparceirofunilaria"))); - ((SinistroAuto)sinistroAuto).ParceiroFunilaria = parceiro; - parceiro1 = (dataRow1.Field<object>("idparceiromecanica") == null ? null : Auxiliar.Parceiros.Find((Parceiro a) => a.Id == dataRow1.Field<long>("idparceiromecanica"))); - ((SinistroAuto)sinistroAuto).ParceiroMecanica = parceiro1; - if (dataRow1.Field<object>("idtipoperda") == null) - { - nullable = null; - nullable2 = nullable; - } - else - { - nullable2 = new TipoPerda?((TipoPerda)int.Parse(dataRow1.Field<object>("idtipoperda").ToString())); - } - ((SinistroAuto)sinistroAuto).TipoPerda = nullable2; - ((SinistroAuto)sinistroAuto).Email = dataRow1.Field<string>("email"); - ((SinistroAuto)sinistroAuto).Telefone = string.Concat(dataRow1.Field<string>("ddd"), " ", dataRow1.Field<string>("telefone")); - } - SinistroAuto sinistroAuto1 = (SinistroAuto)sinistroAuto; - DataRow dataRow2 = dataTable3.AsEnumerable().ToList<DataRow>().FirstOrDefault<DataRow>((DataRow a) => a.Field<long>("idsinistro") == x.Field<long>("idsinistro")); - if (dataRow2 == null) - { - sinistroVida = null; - } - else - { - sinistroVida = new SinistroVida(); - ((DomainBase)sinistroVida).Id = dataRow2.Field<long>("idsinistrovida"); - if (dataRow2.Field<object>("tipoperda") == null) - { - nullable = null; - nullable1 = nullable; - } - else - { - nullable1 = new TipoPerda?((TipoPerda)int.Parse(dataRow2.Field<object>("tipoperda").ToString())); - } - ((SinistroVida)sinistroVida).TipoPerda = nullable1; - ((SinistroVida)sinistroVida).Beneficiario = dataRow2.Field<string>("beneficiario"); - } - SinistroVida sinistroVida1 = (SinistroVida)sinistroVida; - Sinistro sinistro1 = new Sinistro() - { - Id = x.Field<long>("idsinistro"), - Numero = x.Field<string>("numero"), - ItemSinistrado = x.Field<string>("item"), - Motivo = x.Field<string>("motivo"), - TipoSinistro = new TipoSinistro?((TipoSinistro)Enum.Parse(typeof(TipoSinistro), x.Field<object>("tiposinistro").ToString())), - DataReclamacao = new DateTime?((x.Field<object>("reclamacao") != null ? x.Field<DateTime>("reclamacao") : (x.Field<object>("data") != null ? x.Field<DateTime>("data") : DateTime.MinValue))), - Valor = (x.Field<object>("valor") == null ? decimal.Zero : x.Field<decimal>("valor")), - ValorOrcado = (x.Field<object>("valororcado") == null ? decimal.Zero : x.Field<decimal>("valororcado")), - ValorLiberado = (x.Field<object>("valorliberado") == null ? decimal.Zero : x.Field<decimal>("valorliberado")), - ValorSalvado = new decimal?((x.Field<object>("valorsalvado") == null ? decimal.Zero : x.Field<decimal>("valorsalvado"))), - ValorFranquia = (x.Field<object>("valorfranquia") == null ? decimal.Zero : x.Field<decimal>("valorfranquia")), - ValorPago = (x.Field<object>("valorpago") == null ? decimal.Zero : x.Field<decimal>("valorpago")), - DataLiquidacao = x.Field<DateTime?>("liquidacao"), - StatusSinistro = new StatusSinistro?((StatusSinistro)((x.Field<object>("idstatussinistro") == null ? 0 : (StatusSinistro)x.Field<object>("idstatussinistro")))), - SinistroAuto = sinistroAuto1, - SinistroVida = sinistroVida1, - StatusPersonalizado = x.Field<string>("StatusPersonalizado"), - Auxiliar = x.Field<string>("auxiliar"), - IdUsuarioCriacao = (x.Field<object>("usuariocriacao") == null ? (long)0 : x.Field<long>("usuariocriacao")), - DataCriacao = x.Field<DateTime?>("datacriacao"), - IdUsuarioAlteracao = (x.Field<object>("usuarioalteracao") == null ? (long)0 : x.Field<long>("usuarioalteracao")), - DataAlteracao = x.Field<DateTime?>("dataalteracao") - }; - ControleSinistro controleSinistro = new ControleSinistro() - { - Id = x.Field<long>("idcontrolesinistro"), - DataSinistro = new DateTime?((x.Field<object>("data") != null ? x.Field<DateTime>("data") : DateTime.MinValue)) - }; - Item item = new Item() - { - Id = x.Field<long>("id") - }; - Documento documento = new Documento() - { - Id = dataRow.Field<long>("iddocumento"), - Controle = new Controle() - { - Id = dataRow.Field<long>("idcontrole"), - IdEmpresa = dataRow.Field<long>("idempresa"), - Cliente = new Cliente() - { - Id = dataRow.Field<long>("idcliente"), - Nome = dataRow.Field<string>("cliente"), - Pasta = dataRow.Field<string>("pastacliente"), - Documento = dataRow.Field<string>("cpfcnpj"), - MalaDireta = new bool?(dataRow.Field<bool?>("MalaDireta").GetValueOrDefault(true)) - }, - Seguradora = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == dataRow.Field<long>("idseguradora")), - Ramo = Auxiliar.Ramos.Find((Ramo p) => p.Id == dataRow.Field<long>("idramo")), - Produto = (dataRow.Field<object>("idproduto") != null ? Auxiliar.Produtos.Find((Produto p) => p.Id == dataRow.Field<long>("idproduto")) : null) - }, - Apolice = dataRow.Field<string>("apolice"), - Endosso = dataRow.Field<string>("endosso"), - VendedorPrincipal = (dataRow.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.Find((Vendedor p) => p.Id == dataRow.Field<long>("idvendedor")) : null), - Estipulante1 = (dataRow.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == dataRow.Field<long>("idestipulante")) : null), - DataControle = dataRow.Field<DateTime?>("datacontrole"), - Status = (dataRow.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.Find((Status p) => p.Id == dataRow.Field<long>("idstatus")) : null) - }; - DateTime? nullable3 = dataRow.Field<DateTime?>("vigencia1"); - documento.Vigencia1 = (nullable3.HasValue ? nullable3.GetValueOrDefault() : DateTime.MinValue); - documento.Vigencia2 = dataRow.Field<DateTime?>("vigencia2"); - documento.Pasta = dataRow.Field<string>("Pasta"); - item.Documento = documento; - controleSinistro.Item = item; - sinistro1.ControleSinistro = controleSinistro; - sinistros.Add(sinistro1); - }); - return sinistros; - } - - public Sinistro FindById(long id) - { - SinistroDb sinistroDb = base.FindEntityById(id); - if (sinistroDb == null) - { - return null; - } - Sinistro sinistro = ApplicationMapper.Mapper.Map<SinistroDb, Sinistro>(sinistroDb); - sinistro.SinistroAuto = (new SinistroAutoRepository(this._unitOfWork)).FindBySinistroId(sinistro.Id); - sinistro.SinistroVida = (new SinistroVidaRepository(this._unitOfWork)).FindBySinistroId(sinistro.Id); - return sinistro; - } - - public List<Sinistro> FindByItemId(long id) - { - IEnumerable<long> nums = - from cs in (new ControleSinistroRepository(this._unitOfWork)).FindByIdItem(id) - select cs.Id; - return ( - from s in base.All().ToList<SinistroDb>() - where nums.Contains<long>(s.ControleSinistro.Id) - select new Sinistro() - { - Id = s.Id, - Descricao = (string.IsNullOrEmpty(s.Descricao) ? "" : s.Descricao), - DataReclamacao = s.DataReclamacao, - Observacao = (string.IsNullOrEmpty(s.Observacao) ? "" : s.Observacao), - Valor = s.Valor, - ValorPago = s.ValorPago, - Numero = s.Numero, - ControleSinistro = new ControleSinistro() - { - DataSinistro = s.ControleSinistro.DataSinistro - }, - ItemSinistrado = s.ItemSinistrado, - SinistroAuto = (new SinistroAutoRepository(this._unitOfWork)).FindBySinistroId(s.Id), - SinistroVida = (new SinistroVidaRepository(this._unitOfWork)).FindBySinistroId(s.Id) - }).ToList<Sinistro>(); - } - - public List<Sinistro> FindNumeroSinistro(string numero) - { - return this.Select((new List<Condicao>() - { - new Condicao() - { - Campo = "s.numsinistro", - Valores = null, - Operador = Operador.Diferente - }, - new Condicao() - { - Campo = "s.numsinistro", - Valores = numero.CriarValor<string>() - } - }).CreateParameters(0)); - } - - public Sinistro Merge(Sinistro sinistro) - { - SinistroDb sinistroDb = ApplicationMapper.Mapper.Map<Sinistro, SinistroDb>(sinistro); - base.Merge(sinistroDb); - return ApplicationMapper.Mapper.Map<SinistroDb, Sinistro>(sinistroDb); - } - - public Sinistro SaveOrUpdate(Sinistro sinistro) - { - SinistroDb sinistroDb = ApplicationMapper.Mapper.Map<Sinistro, SinistroDb>(sinistro); - this.SaveOrUpdate(sinistroDb); - return ApplicationMapper.Mapper.Map<SinistroDb, Sinistro>(sinistroDb); - } - - private List<Sinistro> Select(SqlQueryCondition condition) - { - DataTable dataTable = this._unitOfWork.Select(condition, "SELECT * FROM sinistro s INNER JOIN controlesinistro cs on cs.idcontrolesinistro = s.idcontrolesinistro WHERE ", ""); - if (dataTable != null && dataTable.Rows.Count == 0) - { - return new List<Sinistro>(); - } - List<long> list = ( - from x in dataTable.AsEnumerable().ToList<DataRow>() - select x.Field<long>("iditem")).ToList<long>(); - List<Condicao> condicaos = new List<Condicao>() - { - new Condicao() - { - Campo = "i.iditem", - Valores = list.CriarValor<long>() - }, - 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 dataTable1 = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT i.iditem, d.iddocumento, ISNULL(d.contrato, '') as apolice, c.idcontrole, cl.idcliente, cl.nome FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", ""); - return dataTable.MapSinistro(dataTable1); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs deleted file mode 100644 index 8f22151..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs +++ /dev/null @@ -1,56 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class SinistroVidaRepository : GenericRepository<SinistroVidaDb>, ISinistroVidaRepository, IGenericRepository<SinistroVidaDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public SinistroVidaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public SinistroVida FindById(long id) - { - SinistroVidaDb sinistroVidaDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<SinistroVidaDb, SinistroVida>(sinistroVidaDb); - } - - public SinistroVida FindBySinistroId(long id) - { - SinistroVidaDb sinistroVidaDb = base.All().FirstOrDefault<SinistroVidaDb>((SinistroVidaDb x) => x.Sinistro.Id == id); - return ApplicationMapper.Mapper.Map<SinistroVidaDb, SinistroVida>(sinistroVidaDb); - } - - public SinistroVida Merge(SinistroVida sinistroVida) - { - SinistroVidaDb sinistroVidaDb = ApplicationMapper.Mapper.Map<SinistroVida, SinistroVidaDb>(sinistroVida); - base.Merge(sinistroVidaDb); - return ApplicationMapper.Mapper.Map<SinistroVidaDb, SinistroVida>(sinistroVidaDb); - } - - public SinistroVida SaveOrUpdate(SinistroVida sinistroVida) - { - SinistroVidaDb sinistroVidaDb = ApplicationMapper.Mapper.Map<SinistroVida, SinistroVidaDb>(sinistroVida); - this.SaveOrUpdate(sinistroVidaDb); - return ApplicationMapper.Mapper.Map<SinistroVidaDb, SinistroVida>(sinistroVidaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs deleted file mode 100644 index 0bacb70..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs +++ /dev/null @@ -1,75 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Common; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Common; -using NHibernate; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class SocioRepository : GenericRepository<SocioDb>, ISocioRepository, IGenericRepository<SocioDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public SocioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List<Socio> Find() - { - return ( - from x in base.All() - select new Socio() - { - Id = x.Id, - Nome = x.Nome, - Email = x.Email, - Prefixo = x.Prefixo, - Telefone = x.Telefone - }).ToList<Socio>(); - } - - public List<Socio> FindByEmpresa(long id) - { - List<SocioDb> list = ( - from x in this._unitOfWork.Session.CreateQuery("FROM SocioDb WHERE (excluido IS NULL OR excluido != '1')").List<SocioDb>() - where x.IdEmpresa == id - select x).ToList<SocioDb>(); - return ApplicationMapper.Mapper.Map<List<SocioDb>, List<Socio>>(list); - } - - public Socio FindById(long id) - { - SocioDb socioDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<SocioDb, Socio>(socioDb); - } - - public Socio Merge(Socio socio) - { - SocioDb socioDb = ApplicationMapper.Mapper.Map<Socio, SocioDb>(socio); - base.Merge(socioDb); - return ApplicationMapper.Mapper.Map<SocioDb, Socio>(socioDb); - } - - public Socio SaveOrUpdate(Socio socio) - { - SocioDb socioDb = ApplicationMapper.Mapper.Map<Socio, SocioDb>(socio); - this.SaveOrUpdate(socioDb); - return ApplicationMapper.Mapper.Map<SocioDb, Socio>(socioDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs deleted file mode 100644 index 9e9cac0..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs +++ /dev/null @@ -1,54 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Ferramentas; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class StatusProspeccaoRepository : GenericRepository<StatusDeProspeccaoDb>, IStatusProspeccaoRepository, IGenericRepository<StatusDeProspeccaoDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public StatusProspeccaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List<StatusDeProspeccao> FindAll() - { - return ( - from x in base.All() - select new StatusDeProspeccao() - { - Id = x.Id, - Nome = x.Nome, - Descricao = x.Descricao, - Ativo = x.Ativo, - Excluido = x.Excluido - }).ToList<StatusDeProspeccao>(); - } - - public StatusDeProspeccao Merge(StatusDeProspeccao statusProspeccao) - { - StatusDeProspeccaoDb statusDeProspeccaoDb = ApplicationMapper.Mapper.Map<StatusDeProspeccao, StatusDeProspeccaoDb>(statusProspeccao); - base.Merge(statusDeProspeccaoDb); - return ApplicationMapper.Mapper.Map<StatusDeProspeccaoDb, StatusDeProspeccao>(statusDeProspeccaoDb); - } - - public StatusDeProspeccao SaveOrUpdate(StatusDeProspeccao statusProspeccao) - { - StatusDeProspeccaoDb statusDeProspeccaoDb = ApplicationMapper.Mapper.Map<StatusDeProspeccao, StatusDeProspeccaoDb>(statusProspeccao); - this.SaveOrUpdate(statusDeProspeccaoDb); - return ApplicationMapper.Mapper.Map<StatusDeProspeccaoDb, StatusDeProspeccao>(statusDeProspeccaoDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs deleted file mode 100644 index 0eac8b3..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs +++ /dev/null @@ -1,76 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class StatusRepository : GenericRepository<StatusDb>, IStatusRepository, IGenericRepository<StatusDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public StatusRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List<Status> Find(string value) - { - StatusRepository.u003cu003ec__DisplayClass6_0 variable = null; - IQueryable<StatusDb> statusDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(StatusDb), "x"); - IQueryable<StatusDb> statusDbs1 = statusDbs.Where<StatusDb>(Expression.Lambda<Func<StatusDb, bool>>(Expression.OrElse(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(StatusDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(StatusRepository.u003cu003ec__DisplayClass6_0)), FieldInfo.GetFieldFromHandle(typeof(StatusRepository.u003cu003ec__DisplayClass6_0).GetField("value").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(StatusDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(StatusRepository.u003cu003ec__DisplayClass6_0)), FieldInfo.GetFieldFromHandle(typeof(StatusRepository.u003cu003ec__DisplayClass6_0).GetField("value").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); - parameterExpression = Expression.Parameter(typeof(StatusDb), "x"); - return statusDbs1.Select<StatusDb, Status>(Expression.Lambda<Func<StatusDb, Status>>(Expression.MemberInit(Expression.New(typeof(Status)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Status).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(StatusDb).GetMethod("get_Nome").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList<Status>(); - } - - public List<Status> Find() - { - return ( - from x in this._unitOfWork.Session.CreateQuery("from StatusDb").List<StatusDb>() - select new Status() - { - Id = x.Id, - Nome = x.Nome, - Ativo = x.Ativo - }).ToList<Status>(); - } - - public Status FindById(long id) - { - StatusDb statusDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<StatusDb, Status>(statusDb); - } - - public Status Merge(Status status) - { - StatusDb statusDb = ApplicationMapper.Mapper.Map<Status, StatusDb>(status); - base.Merge(statusDb); - return ApplicationMapper.Mapper.Map<StatusDb, Status>(statusDb); - } - - public Status SaveOrUpdate(Status status) - { - StatusDb statusDb = ApplicationMapper.Mapper.Map<Status, StatusDb>(status); - this.SaveOrUpdate(statusDb); - return ApplicationMapper.Mapper.Map<StatusDb, Status>(statusDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs deleted file mode 100644 index bfcdd72..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs +++ /dev/null @@ -1,462 +0,0 @@ -using AutoMapper; -using Gestor.Common.Validation; -using Gestor.Infrastructure.Entities.Ferramentas; -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.Ferramentas; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Relatorios.Tarefa; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class TarefaRepository : GenericRepository<TarefaDb>, ITarefaRepository, IGenericRepository<TarefaDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public TarefaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public Gestor.Model.Domain.Ferramentas.Tarefa Atualizar(Gestor.Model.Domain.Ferramentas.Tarefa tarefa) - { - List<ResponsavelTarefa> list; - Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = tarefa; - List<ResponsavelTarefa> responsaveis = tarefa1.Responsaveis; - if (responsaveis != null) - { - list = ( - from x in responsaveis - where x.Usuario.Id != tarefa1.Usuario.Id - select x).ToList<ResponsavelTarefa>(); - } - else - { - list = null; - } - List<ResponsavelTarefa> responsavelTarefas = list; - TarefaDb tarefaDb = ApplicationMapper.Mapper.Map<Gestor.Model.Domain.Ferramentas.Tarefa, TarefaDb>(tarefa1); - List<ResponsavelTarefaDb> responsavelTarefaDbs = ( - from x in this._unitOfWork.Query<ResponsavelTarefaDb>() - where x.IdTarefa == tarefa1.Id - select x).ToList<ResponsavelTarefaDb>(); - this._unitOfWork.Repository<ResponsavelTarefaDb>().DeleteRange(responsavelTarefaDbs); - base.Merge(tarefaDb); - tarefa1 = ApplicationMapper.Mapper.Map<TarefaDb, Gestor.Model.Domain.Ferramentas.Tarefa>(tarefaDb); - if (responsavelTarefas != null) - { - responsavelTarefas.ForEach((ResponsavelTarefa x) => { - x.Id = (long)0; - x.IdTarefa = tarefa1.Id; - x = this.Save(x); - }); - } - tarefa1.Responsaveis = responsavelTarefas; - return tarefa1; - } - - public Trilha Atualizar(Trilha trilha) - { - TrilhaDb trilhaDb = ApplicationMapper.Mapper.Map<Trilha, TrilhaDb>(trilha); - this._unitOfWork.Repository<TrilhaDb>().Merge(trilhaDb); - return ApplicationMapper.Mapper.Map<TrilhaDb, Trilha>(trilhaDb); - } - - public Fase Atualizar(Fase fase) - { - FaseDb faseDb = ApplicationMapper.Mapper.Map<Fase, FaseDb>(fase); - this._unitOfWork.Repository<FaseDb>().Merge(faseDb); - return ApplicationMapper.Mapper.Map<FaseDb, Fase>(faseDb); - } - - public List<Fase> BuscarFases(long id) - { - List<FaseDb> list = ( - from x in this._unitOfWork.Query<FaseDb>() - where x.Trilha.Id == id - select x).ToList<FaseDb>(); - return ApplicationMapper.Mapper.Map<List<FaseDb>, List<Fase>>(list); - } - - public Gestor.Model.Domain.Ferramentas.Tarefa BuscarTarefa(long id) - { - TarefaDb tarefaDb = base.FindEntityById(id); - List<ResponsavelTarefaDb> list = ( - from x in this._unitOfWork.Query<ResponsavelTarefaDb>() - where x.IdTarefa == id - select x).ToList<ResponsavelTarefaDb>(); - Gestor.Model.Domain.Ferramentas.Tarefa tarefa = ApplicationMapper.Mapper.Map<TarefaDb, Gestor.Model.Domain.Ferramentas.Tarefa>(tarefaDb); - tarefa.Responsaveis = ApplicationMapper.Mapper.Map<List<ResponsavelTarefaDb>, List<ResponsavelTarefa>>(list); - return tarefa; - } - - public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefa(TipoTarefa entidade, long id, bool? concluido = false) - { - string str; - if (!concluido.HasValue) - { - str = ""; - } - else - { - str = (concluido.GetValueOrDefault() ? " AND t.Conclusao IS NOT NULL" : " AND t.Conclusao IS NULL"); - } - string str1 = str; - return this.Select(string.Format(" AND t.Entidade = {0} AND t.IdEntidade = {1} {2}", (int)entidade, id, str1)); - } - - public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaConcluidaPorUsuario(long id, TipoTarefa tipo) - { - return this.Select(string.Format(" AND t.Entidade = {0} AND t.Conclusao IS NOT NULL AND (t.IdUsuario = {1} OR r.Usuario_id = {2})", (int)tipo, id, id)); - } - - public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorCliente(long id) - { - return this.Select(string.Format(" AND t.Entidade != 1 AND t.IdCliente = {0}", id)); - } - - public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorData(DateTime data, long idUsuario, bool? concluido = false) - { - string str; - if (!concluido.HasValue) - { - str = ""; - } - else - { - str = (concluido.GetValueOrDefault() ? "AND t.Conclusao IS NOT NULL" : " AND t.Conclusao IS NULL"); - } - string str1 = str; - return this.Select(string.Format(" AND t.Entidade != 1 AND CAST(t.Agendamento AS DATE) == '{0:yyyy-MM-dd}' {1} AND (t.IdUsuario = {2} OR r.Usuario_id = {3})", new object[] { data, str1, idUsuario, idUsuario })); - } - - public List<Gestor.Model.Domain.Relatorios.Tarefa.Tarefa> BuscarTarefaPorFiltro(DateTime inicio, DateTime fim) - { - return ( - from x in this.Select(string.Format(" AND t.Entidade != 1 AND CAST(t.agendamento AS DATE) BETWEEN '{0:yyyy-MM-dd}' AND '{1:yyyy-MM-dd}'", inicio, fim)) - select new Gestor.Model.Domain.Relatorios.Tarefa.Tarefa() - { - Id = x.Id, - IdCliente = x.IdCliente, - Cliente = x.Cliente, - Agendamento = x.Agendamento, - Conclusao = x.Conclusao, - Referencia = x.Referencia, - Titulo = x.Titulo, - Usuario = (x.Usuario != null ? x.Usuario.Nome : ""), - IdEntidade = x.IdEntidade, - Entidade = x.Entidade, - TipoTarefa = (x.TipoDeTarefa != null ? x.TipoDeTarefa.Nome : ""), - Status = x.Status.GetDescription() - }).ToList<Gestor.Model.Domain.Relatorios.Tarefa.Tarefa>(); - } - - public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorTrilha(long id) - { - return this.Select(string.Format(" AND t.IdTrilha = {0}", id)); - } - - public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorUsuario(long id, bool? concluido = false) - { - string str; - if (!concluido.HasValue) - { - str = ""; - } - else - { - str = (concluido.GetValueOrDefault() ? " AND t.Conclusao IS NOT NULL" : " AND t.Conclusao IS NULL"); - } - string str1 = str; - return this.Select(string.Format(" AND {0} AND (t.IdUsuario = {1} OR r.Usuario_id = {2})", str1, id, id)); - } - - public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorUsuario(long id, DateTime inicio, DateTime fim, bool? concluido) - { - string str; - fim = fim.AddDays(1); - if (!concluido.HasValue) - { - str = ""; - } - else - { - str = (concluido.GetValueOrDefault() ? " AND t.Conclusao IS NOT NULL" : " AND t.Conclusao IS NULL"); - } - string str1 = str; - string str2 = (id == 0 ? "" : string.Format(" AND (t.IdUsuario = {0} OR r.Usuario_id = {1})", id, id)); - return this.Select(string.Format(" AND t.Entidade != 1 AND t.Agendamento >= '{0:yyyy-MM-dd}' AND t.Agendamento <= '{1:yyyy-MM-dd}' {2} {3}", new object[] { inicio, fim, str1, str2 })); - } - - public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefaPorUsuario(long id, TipoTarefa tipo) - { - return this.Select(string.Format(" AND t.Entidade = {0} AND t.Conclusao IS NULL AND (t.IdUsuario = {1} OR r.Usuario_id = {2})", (int)tipo, id, id)); - } - - public List<Gestor.Model.Domain.Ferramentas.Tarefa> BuscarTarefasPorTipo(long id) - { - return this.Select(string.Format(" AND t.IdTipoTarefa = {0}", id)); - } - - public Trilha BuscarTrilha(long id) - { - TrilhaDb trilhaDb = this._unitOfWork.Query<TrilhaDb>().FirstOrDefault<TrilhaDb>((TrilhaDb x) => x.Id == id); - return ApplicationMapper.Mapper.Map<TrilhaDb, Trilha>(trilhaDb); - } - - public List<Trilha> BuscarTrilhas(bool ativo = true) - { - List<TrilhaDb> list = ( - from x in this._unitOfWork.Query<TrilhaDb>() - where x.Ativo == ativo - select x).ToList<TrilhaDb>(); - return ApplicationMapper.Mapper.Map<List<TrilhaDb>, List<Trilha>>(list); - } - - public List<Trilha> BuscarTrilhas(string titulo, bool ativo = true) - { - List<TrilhaDb> list = this._unitOfWork.Query<TrilhaDb>().ToList<TrilhaDb>().Where<TrilhaDb>((TrilhaDb x) => { - if (x.Ativo != ativo) - { - return false; - } - return x.Titulo.Normalized() == titulo.Normalized(); - }).ToList<TrilhaDb>(); - return ApplicationMapper.Mapper.Map<List<TrilhaDb>, List<Trilha>>(list); - } - - public int[] ContarTarefas(long id) - { - int[] numArray = new int[] { this.Count(string.Format(" AND t.Entidade = 1 AND t.Conclusao IS NULL AND (t.IdUsuario = {0} OR r.Usuario_id = {1})", id, id)), 0 }; - DateTime date = Funcoes.GetNetworkTime().Date; - numArray[1] = this.Count(string.Format(" AND t.Entidade != 1 AND t.Conclusao IS NULL AND t.Agendamento < '{0:yyyy-MM-dd}' AND (t.IdUsuario = {1} OR r.Usuario_id = {2})", date.AddDays(1), id, id)); - return numArray; - } - - private int Count(string condition) - { - int num; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Concat("SELECT Count(DISTINCT t.Id) as quantidade FROM Tarefa t LEFT OUTER JOIN ResponsavelTarefa r on r.IdTarefa = t.id WHERE 1=1 ", condition); - SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); - sqlDataReader.Read(); - num = int.Parse(sqlDataReader["quantidade"].ToString()); - } - } - return num; - } - - public void Excluir(long id) - { - TarefaDb tarefaDb = base.FindEntityById(id); - if (tarefaDb == null) - { - return; - } - List<ResponsavelTarefaDb> list = ( - from x in this._unitOfWork.Query<ResponsavelTarefaDb>() - where x.IdTarefa == id - select x).ToList<ResponsavelTarefaDb>(); - this._unitOfWork.Repository<ResponsavelTarefaDb>().DeleteRange(list); - ( - from x in this._unitOfWork.Query<ProspeccaoDb>() - where x.Tarefa.Id == tarefaDb.Id - select x).ToList<ProspeccaoDb>().ForEach((ProspeccaoDb x) => { - x.Tarefa = null; - this._unitOfWork.Repository<ProspeccaoDb>().Merge(x); - }); - base.Delete(tarefaDb); - } - - public void ExcluirFase(long id) - { - FaseDb faseDb = this._unitOfWork.Query<FaseDb>().FirstOrDefault<FaseDb>((FaseDb x) => x.Id == id); - if (faseDb == null) - { - return; - } - this._unitOfWork.Repository<FaseDb>().Delete(faseDb); - } - - public void ExcluirTrilha(long id) - { - TrilhaDb trilhaDb = this._unitOfWork.Query<TrilhaDb>().FirstOrDefault<TrilhaDb>((TrilhaDb x) => x.Id == id); - if (trilhaDb == null) - { - return; - } - this._unitOfWork.Repository<TrilhaDb>().Delete(trilhaDb); - } - - public Gestor.Model.Domain.Ferramentas.Tarefa Salvar(Gestor.Model.Domain.Ferramentas.Tarefa tarefa) - { - List<ResponsavelTarefa> list; - Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = tarefa; - List<ResponsavelTarefa> responsaveis = tarefa1.Responsaveis; - if (responsaveis != null) - { - list = ( - from x in responsaveis - where x.Usuario.Id != tarefa1.Usuario.Id - select x).ToList<ResponsavelTarefa>(); - } - else - { - list = null; - } - List<ResponsavelTarefa> responsavelTarefas = list; - TarefaDb tarefaDb = ApplicationMapper.Mapper.Map<Gestor.Model.Domain.Ferramentas.Tarefa, TarefaDb>(tarefa1); - this.SaveOrUpdate(tarefaDb); - tarefa1 = ApplicationMapper.Mapper.Map<TarefaDb, Gestor.Model.Domain.Ferramentas.Tarefa>(tarefaDb); - if (responsavelTarefas != null) - { - responsavelTarefas.ForEach((ResponsavelTarefa x) => { - x.IdTarefa = tarefa1.Id; - x = this.Save(x); - }); - } - tarefa1.Responsaveis = responsavelTarefas; - return tarefa1; - } - - public List<Gestor.Model.Domain.Ferramentas.Tarefa> Salvar(List<Gestor.Model.Domain.Ferramentas.Tarefa> tarefas) - { - tarefas.ForEach((Gestor.Model.Domain.Ferramentas.Tarefa x) => x = this.Salvar(x)); - return tarefas; - } - - public Trilha Salvar(Trilha trilha) - { - TrilhaDb trilhaDb = ApplicationMapper.Mapper.Map<Trilha, TrilhaDb>(trilha); - this._unitOfWork.Repository<TrilhaDb>().SaveOrUpdate(trilhaDb); - return ApplicationMapper.Mapper.Map<TrilhaDb, Trilha>(trilhaDb); - } - - public Fase Salvar(Fase fase) - { - FaseDb faseDb = ApplicationMapper.Mapper.Map<Fase, FaseDb>(fase); - this._unitOfWork.Repository<FaseDb>().SaveOrUpdate(faseDb); - return ApplicationMapper.Mapper.Map<FaseDb, Fase>(faseDb); - } - - public List<Fase> Salvar(List<Fase> fases) - { - List<FaseDb> faseDbs = new List<FaseDb>(); - List<Fase> list = ( - from x in fases - where x.Id == (long)0 - select x).ToList<Fase>(); - List<Fase> list1 = fases.Except<Fase>(list).ToList<Fase>(); - if (list.Count > 0) - { - faseDbs = ApplicationMapper.Mapper.Map<List<Fase>, List<FaseDb>>(list); - this._unitOfWork.Repository<FaseDb>().AddRange(faseDbs); - } - if (list1 != null) - { - list1.ForEach((Fase x) => { - FaseDb faseDb = ApplicationMapper.Mapper.Map<Fase, FaseDb>(x); - this._unitOfWork.Repository<FaseDb>().SaveOrUpdate(faseDb); - faseDbs.Add(faseDb); - }); - } - else - { - } - return ApplicationMapper.Mapper.Map<List<FaseDb>, List<Fase>>(faseDbs); - } - - public ResponsavelTarefa Save(ResponsavelTarefa responsavel) - { - ResponsavelTarefaDb responsavelTarefaDb = ApplicationMapper.Mapper.Map<ResponsavelTarefa, ResponsavelTarefaDb>(responsavel); - this._unitOfWork.Repository<ResponsavelTarefaDb>().SaveOrUpdate(responsavelTarefaDb); - return ApplicationMapper.Mapper.Map<ResponsavelTarefaDb, ResponsavelTarefa>(responsavelTarefaDb); - } - - private List<Gestor.Model.Domain.Ferramentas.Tarefa> Select(string condition) - { - object connection; - List<long> nums = null; - 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()) - { - sqlCommand.CommandTimeout = 15000; - Auxiliar.LoadTipoTarefa(sqlCommand); - Auxiliar.CriarAuxiliar(sqlCommand, false); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT t.* FROM Tarefa t LEFT OUTER JOIN ResponsavelTarefa r on r.IdTarefa = t.id WHERE 1=1 ", condition); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - for (List<long> i = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("Id")).ToList<long>(); i.Count > 0; i = nums) - { - List<long> list = i.Take<long>(2100).ToList<long>(); - string str = string.Concat(" AND IdTarefa IN (", string.Join<long>(",", list), ")"); - DataTable dataTable2 = new DataTable(); - sqlCommand.CommandText = string.Concat("SELECT * FROM ResponsavelTarefa WHERE 1=1 ", str); - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable2); - } - dataTable1.Merge(dataTable2); - nums = (list.Count < 2100 ? new List<long>() : i.Except<long>(list).ToList<long>()); - } - } - } - return CustomMap.MapTarefa(dataTable, dataTable1); - } - - public List<long> Validar(List<long> ids, long trilha) - { - return ( - from x in base.All() - where ids.Contains(x.IdEntidade) && x.Trilha != null && x.Trilha.Id == trilha - select x.Id).ToList<long>(); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs deleted file mode 100644 index 4f5a3cf..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs +++ /dev/null @@ -1,52 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Financeiro; -using NHibernate; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class TipoContaRepository : GenericRepository<TipoContaDb>, ITipoContaRepository, IGenericRepository<TipoContaDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public TipoContaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List<TipoConta> Find() - { - return ( - from x in this._unitOfWork.Session.CreateQuery("from TipoContaDb").List<TipoContaDb>() - select new TipoConta() - { - Descricao = x.Descricao, - Ativo = x.Ativo, - Id = x.Id - }).ToList<TipoConta>(); - } - - public TipoConta Merge(TipoConta tipoConta) - { - TipoContaDb tipoContaDb = ApplicationMapper.Mapper.Map<TipoConta, TipoContaDb>(tipoConta); - base.Merge(tipoContaDb); - return ApplicationMapper.Mapper.Map<TipoContaDb, TipoConta>(tipoContaDb); - } - - public TipoConta SaveOrUpdate(TipoConta tipoConta) - { - TipoContaDb tipoContaDb = ApplicationMapper.Mapper.Map<TipoConta, TipoContaDb>(tipoConta); - this.SaveOrUpdate(tipoContaDb); - return ApplicationMapper.Mapper.Map<TipoContaDb, TipoConta>(tipoContaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs deleted file mode 100644 index df36a20..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs +++ /dev/null @@ -1,54 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Ferramentas; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Ferramentas; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class TipoTarefaRepository : GenericRepository<TipoDeTarefaDb>, ITipoTarefaRepository, IGenericRepository<TipoDeTarefaDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public TipoTarefaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List<TipoDeTarefa> FindAll() - { - return ( - from x in base.All() - select new TipoDeTarefa() - { - Id = x.Id, - Nome = x.Nome, - Descricao = x.Descricao, - Ativo = x.Ativo, - Excluido = x.Excluido - }).ToList<TipoDeTarefa>(); - } - - public TipoDeTarefa Merge(TipoDeTarefa tipoTarefa) - { - TipoDeTarefaDb tipoDeTarefaDb = ApplicationMapper.Mapper.Map<TipoDeTarefa, TipoDeTarefaDb>(tipoTarefa); - base.Merge(tipoDeTarefaDb); - return ApplicationMapper.Mapper.Map<TipoDeTarefaDb, TipoDeTarefa>(tipoDeTarefaDb); - } - - public TipoDeTarefa SaveOrUpdate(TipoDeTarefa tipoTarefa) - { - TipoDeTarefaDb tipoDeTarefaDb = ApplicationMapper.Mapper.Map<TipoDeTarefa, TipoDeTarefaDb>(tipoTarefa); - this.SaveOrUpdate(tipoDeTarefaDb); - return ApplicationMapper.Mapper.Map<TipoDeTarefaDb, TipoDeTarefa>(tipoDeTarefaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs deleted file mode 100644 index 30382b0..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs +++ /dev/null @@ -1,139 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class TipoVendedorRepository : GenericRepository<TipoVendedorDb>, ITipoVendedorRepository, IGenericRepository<TipoVendedorDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public TipoVendedorRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List<TipoVendedor> DefaultSelect() - { - List<TipoVendedorDb> list = base.All().ToList<TipoVendedorDb>(); - return ApplicationMapper.Mapper.Map<List<TipoVendedorDb>, List<TipoVendedor>>(list); - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List<TipoVendedor> Find(bool ativo) - { - return ( - from x in base.All() - where x.Ativo == (bool?)ativo - select new TipoVendedor() - { - Id = x.Id, - Descricao = x.Descricao, - Ativo = x.Ativo - }).ToList<TipoVendedor>(); - } - - public List<TipoVendedor> Find() - { - return ( - from x in this._unitOfWork.Session.CreateQuery("from TipoVendedorDb").List<TipoVendedorDb>() - select new TipoVendedor() - { - Id = x.Id, - Descricao = x.Descricao, - Ativo = x.Ativo - }).ToList<TipoVendedor>(); - } - - public TipoVendedor FindById(long id) - { - TipoVendedorDb tipoVendedorDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<TipoVendedorDb, TipoVendedor>(tipoVendedorDb); - } - - public long FindLastId() - { - long num; - object connection; - SqlCommand sqlCommand; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - sqlCommand = sqlConnection.CreateCommand(); - } - else - { - sqlCommand = null; - } - using (SqlCommand sqlCommand1 = sqlCommand) - { - sqlCommand1.CommandText = "SELECT MAX(idtipovendedor) as id FROM tipovendedor"; - SqlDataReader sqlDataReader = sqlCommand1.ExecuteReader(); - sqlDataReader.Read(); - num = (sqlDataReader["id"] == null ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); - } - } - return num; - } - - public TipoVendedor Merge(TipoVendedor tipoVendedor) - { - TipoVendedorDb tipoVendedorDb = ApplicationMapper.Mapper.Map<TipoVendedor, TipoVendedorDb>(tipoVendedor); - base.Merge(tipoVendedorDb); - return ApplicationMapper.Mapper.Map<TipoVendedorDb, TipoVendedor>(tipoVendedorDb); - } - - public List<TipoVendedor> MergeRange(List<TipoVendedor> tiposVendedor) - { - List<TipoVendedor> tipoVendedors = new List<TipoVendedor>(); - tiposVendedor.ForEach((TipoVendedor x) => { - TipoVendedorDb tipoVendedorDb = ApplicationMapper.Mapper.Map<TipoVendedor, TipoVendedorDb>(x); - if (!x.Inserido.HasValue || x.Inserido.Value) - { - base.Merge(tipoVendedorDb); - } - else - { - this.SaveOrUpdate(tipoVendedorDb); - } - tipoVendedors.Add(ApplicationMapper.Mapper.Map<TipoVendedorDb, TipoVendedor>(tipoVendedorDb)); - }); - return tipoVendedors; - } - - public TipoVendedor SaveOrUpdate(TipoVendedor tipoVendedor) - { - TipoVendedorDb tipoVendedorDb = ApplicationMapper.Mapper.Map<TipoVendedor, TipoVendedorDb>(tipoVendedor); - this.SaveOrUpdate(tipoVendedorDb); - return ApplicationMapper.Mapper.Map<TipoVendedorDb, TipoVendedor>(tipoVendedorDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs deleted file mode 100644 index 4a0f512..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs +++ /dev/null @@ -1,152 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -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.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class TitularesVidaRepository : GenericRepository<TitularesVidaDb>, ITitularesVidaRepository, IGenericRepository<TitularesVidaDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public TitularesVidaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public void DeleteRange(List<long> ids) - { - for (int i = 0; i < ids.Count; i += 200) - { - IEnumerable<long> nums = ids.Skip<long>(i).Take<long>(200); - List<TitularesVidaDb> list = ( - from x in base.All() - where nums.Contains<long>(x.Id) - select x).ToList<TitularesVidaDb>(); - base.DeleteRange(list); - } - } - - public List<TitularesVida> Find(long id) - { - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = string.Format("SELECT * FROM TitularesVida WHERE IdItem = {0}", id); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - } - return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, TitularesVida>((DataRow x) => { - DateTime? nullable; - DateTime? nullable1; - DateTime? nullable2; - DateTime? nullable3; - TitularesVida titularesVida = new TitularesVida() - { - Id = x.Field<long>("Id"), - Codigo = (x.Field<object>("Codigo") != null ? x.Field<object>("Codigo").ToString() : null) - }; - if (x.Field<object>("Inicio") != null) - { - nullable1 = new DateTime?(DateTime.Parse(x.Field<object>("Inicio").ToString())); - } - else - { - nullable = null; - nullable1 = nullable; - } - titularesVida.Inicio = nullable1; - if (x.Field<object>("Fim") != null) - { - nullable2 = new DateTime?(DateTime.Parse(x.Field<object>("Fim").ToString())); - } - else - { - nullable = null; - nullable2 = nullable; - } - titularesVida.Fim = nullable2; - titularesVida.Fatura = (x.Field<object>("Fatura") != null ? x.Field<object>("Fatura").ToString() : null); - titularesVida.Nome = (x.Field<object>("Nome") != null ? x.Field<object>("Nome").ToString() : null); - titularesVida.Observacao = (x.Field<object>("Observacao") != null ? x.Field<object>("Observacao").ToString() : null); - if (x.Field<object>("Nascimento") != null) - { - nullable3 = new DateTime?(DateTime.Parse(x.Field<object>("Nascimento").ToString())); - } - else - { - nullable = null; - nullable3 = nullable; - } - titularesVida.Nascimento = nullable3; - titularesVida.Cpf = (x.Field<object>("Cpf") != null ? x.Field<object>("Cpf").ToString() : null); - titularesVida.Matricula = (x.Field<object>("Matricula") != null ? x.Field<object>("Matricula").ToString() : null); - titularesVida.Premio = new decimal?((x.Field<object>("Premio") != null ? x.Field<decimal>("Premio") : decimal.Zero)); - titularesVida.Capital = new decimal?((x.Field<object>("Capital") != null ? x.Field<decimal>("Capital") : decimal.Zero)); - titularesVida.Tipo = (x.Field<object>("Tipo") != null ? (TipoTitular?)Enum.Parse(typeof(TipoTitular), x.Field<object>("Tipo").ToString()) : null); - titularesVida.Dependente = (x.Field<object>("Dependente_id") != null ? this.FindById(x.Field<long>("Dependente_id")) : null); - return titularesVida; - }).ToList<TitularesVida>(); - } - - public TitularesVida FindById(long id) - { - TitularesVidaDb titularesVidaDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<TitularesVidaDb, TitularesVida>(titularesVidaDb); - } - - public TitularesVida Merge(TitularesVida vida) - { - TitularesVidaDb titularesVidaDb = ApplicationMapper.Mapper.Map<TitularesVida, TitularesVidaDb>(vida); - base.Merge(titularesVidaDb); - return ApplicationMapper.Mapper.Map<TitularesVidaDb, TitularesVida>(titularesVidaDb); - } - - public TitularesVida SaveOrUpdate(TitularesVida vida) - { - TitularesVidaDb titularesVidaDb = ApplicationMapper.Mapper.Map<TitularesVida, TitularesVidaDb>(vida); - this.SaveOrUpdate(titularesVidaDb); - return ApplicationMapper.Mapper.Map<TitularesVidaDb, TitularesVida>(titularesVidaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs deleted file mode 100644 index f1f9993..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs +++ /dev/null @@ -1,305 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.API; -using Gestor.Model.Common; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Reflection; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class UsuarioRepository : GenericRepository<UsuarioDb>, IUsuarioRepository, IGenericRepository<UsuarioDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public UsuarioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public Usuario AddUsuarioFromSso(UserSso userSso) - { - return this.SaveOrUpdate(new Usuario() - { - SsoId = userSso.Id, - IdEmpresa = userSso.IdEmpresa, - Nome = userSso.Name, - Login = userSso.Username, - Senha = userSso.Password, - Administrador = false, - Excluido = userSso.IsDeleted, - PermissaoAggilizador = new long?((long)1) - }); - } - - public void Delete(long id) - { - UsuarioDb nullable = base.FindEntityById(id); - if (nullable.Login.IndexOf("_REM", StringComparison.InvariantCultureIgnoreCase) == -1) - { - UsuarioDb usuarioDb = nullable; - usuarioDb.Login = string.Concat(usuarioDb.Login, "_REM"); - } - nullable.Excluido = new bool?(true); - base.Merge(nullable); - } - - public List<Usuario> Find(string filter, long idempresa = 0L) - { - UsuarioRepository.u003cu003ec__DisplayClass11_0 variable = null; - ParameterExpression parameterExpression; - bool? nullable; - IQueryable<UsuarioDb> usuarioDbs; - if (idempresa == 0) - { - IQueryable<UsuarioDb> usuarioDbs1 = base.All(); - parameterExpression = Expression.Parameter(typeof(UsuarioDb), "x"); - nullable = null; - usuarioDbs = usuarioDbs1.Where<UsuarioDb>(Expression.Lambda<Func<UsuarioDb, bool>>(Expression.OrElse(Expression.AndAlso(Expression.AndAlso(Expression.NotEqual(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Excluido").MethodHandle)), Expression.Constant(nullable, typeof(bool?))), Expression.Equal(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Excluido").MethodHandle)), Expression.Convert(Expression.Constant(false, typeof(bool)), typeof(bool?)))), Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0).GetField("filter").FieldHandle)) })), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Documento").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0).GetField("filter").FieldHandle)) })), new ParameterExpression[] { parameterExpression })); - } - else - { - IQueryable<UsuarioDb> usuarioDbs2 = base.All(); - parameterExpression = Expression.Parameter(typeof(UsuarioDb), "x"); - nullable = null; - usuarioDbs = usuarioDbs2.Where<UsuarioDb>(Expression.Lambda<Func<UsuarioDb, bool>>(Expression.AndAlso(Expression.AndAlso(Expression.AndAlso(Expression.NotEqual(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Excluido").MethodHandle)), Expression.Constant(nullable, typeof(bool?))), Expression.Equal(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Excluido").MethodHandle)), Expression.Convert(Expression.Constant(false, typeof(bool)), typeof(bool?)))), Expression.Equal(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_IdEmpresa").MethodHandle)), Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0).GetField("idempresa").FieldHandle)))), Expression.OrElse(Expression.Call(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Nome").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0).GetField("filter").FieldHandle)) }), Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Documento").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Trim").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Contains", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass11_0).GetField("filter").FieldHandle)) }))), new ParameterExpression[] { parameterExpression })); - } - parameterExpression = Expression.Parameter(typeof(UsuarioDb), "x"); - return usuarioDbs.Select<UsuarioDb, Usuario>(Expression.Lambda<Func<UsuarioDb, Usuario>>(Expression.MemberInit(Expression.New(typeof(Usuario)), new MemberBinding[] { Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_IdEmpresa", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_IdEmpresa").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(DomainBase).GetMethod("set_Id", new Type[] { typeof(long) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(EntityBase).GetMethod("get_Id").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_Nome", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Nome").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_Documento", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Documento").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_Excluido", new Type[] { typeof(bool) }).MethodHandle), Expression.Coalesce(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Excluido").MethodHandle)), Expression.Constant(false, typeof(bool)))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_PermissaoAggilizador", new Type[] { typeof(long?) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_PermissaoAggilizador").MethodHandle))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_Administrador", new Type[] { typeof(bool) }).MethodHandle), Expression.Coalesce(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Administrador").MethodHandle)), Expression.Constant(false, typeof(bool)))), Expression.Bind((MethodInfo)MethodBase.GetMethodFromHandle(typeof(Usuario).GetMethod("set_Visita", new Type[] { typeof(string) }).MethodHandle), Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Visita").MethodHandle))) }), new ParameterExpression[] { parameterExpression })).ToList<Usuario>(); - } - - public List<Usuario> Find(long idempresa = 0L) - { - List<Usuario> usuarios; - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - string str = (idempresa == 0 ? "SELECT * FROM usuario" : "SELECT * FROM usuario WHERE idempresa = @idempresa"); - try - { - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = str; - sqlCommand.Parameters.AddWithValue("@idempresa", idempresa); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - else - { - usuarios = null; - return usuarios; - } - } - usuarios = CustomMap.MapUsuario(dataTable); - } - catch (Exception exception) - { - usuarios = null; - } - return usuarios; - } - - public Usuario FindById(long id) - { - UsuarioDb usuarioDb = base.FindEntityById(id); - if (usuarioDb == null) - { - return null; - } - return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); - } - - public List<Usuario> FindByLoginInteiro(string filter) - { - return ( - from x in ( - from x in base.All() - where x.Excluido != null && x.Excluido == (bool?)false && x.Login.Equals(filter) - select x).ToList<UsuarioDb>() - select new Usuario() - { - IdEmpresa = x.IdEmpresa, - Id = x.Id, - Nome = x.Nome, - Documento = x.Documento, - Excluido = x.Excluido.GetValueOrDefault(), - PermissaoAggilizador = x.PermissaoAggilizador, - Administrador = x.Administrador.GetValueOrDefault(), - Visita = x.Visita - } into x - where !x.Excluido - select x).ToList<Usuario>(); - } - - private Usuario FindBySso(string ssoId) - { - UsuarioDb usuarioDb = base.All().FirstOrDefault<UsuarioDb>((UsuarioDb u) => u.SsoId == ssoId); - if (usuarioDb == null) - { - return null; - } - return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); - } - - public bool FindDocUsedByDocumento(string filter, long id, long idempresa) - { - return base.All().Any<UsuarioDb>((UsuarioDb u) => u.IdEmpresa == idempresa && u.Excluido != null && u.Excluido == (bool?)false && u.Id != id && u.Documento != null && u.Documento.Replace(".", string.Empty).Replace("-", string.Empty).Replace("/", string.Empty).Equals(filter)); - } - - public Usuario FindFromSso(UserSso userSso) - { - UsuarioRepository.u003cu003ec__DisplayClass4_0 variable = null; - if (userSso.IsDeleted) - { - return null; - } - IQueryable<UsuarioDb> usuarioDbs = base.All(); - ParameterExpression parameterExpression = Expression.Parameter(typeof(UsuarioDb), "u"); - UsuarioDb usuarioDb = usuarioDbs.FirstOrDefault<UsuarioDb>(Expression.Lambda<Func<UsuarioDb, bool>>(Expression.Call(Expression.Call(Expression.Property(parameterExpression, (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UsuarioDb).GetMethod("get_Login").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("Equals", new Type[] { typeof(string) }).MethodHandle), new Expression[] { Expression.Call(Expression.Property(Expression.Field(Expression.Constant(variable, typeof(UsuarioRepository.u003cu003ec__DisplayClass4_0)), FieldInfo.GetFieldFromHandle(typeof(UsuarioRepository.u003cu003ec__DisplayClass4_0).GetField("userSso").FieldHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(UserSso).GetMethod("get_Username").MethodHandle)), (MethodInfo)MethodBase.GetMethodFromHandle(typeof(string).GetMethod("ToUpper").MethodHandle), Array.Empty<Expression>()) }), new ParameterExpression[] { parameterExpression })); - if (usuarioDb == null) - { - return null; - } - return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); - } - - public Usuario FindUsuario(string login) - { - UsuarioDb usuarioDb = ( - from x in base.All() - where x.Excluido != null && x.Excluido == (bool?)false - select x).FirstOrDefault<UsuarioDb>((UsuarioDb x) => x.Login == login); - return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); - } - - public Usuario Merge(Usuario usuario) - { - UsuarioDb usuarioDb = ApplicationMapper.Mapper.Map<Usuario, UsuarioDb>(usuario); - base.Merge(usuarioDb); - return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); - } - - public List<PermissaoAggilizador> PermissaoAggilizador() - { - List<PermissaoAggilizador> list; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - try - { - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT * FROM Permissao where IdPermissao != 4"; - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - } - list = ( - from x in dataTable.AsEnumerable().ToList<DataRow>() - select new PermissaoAggilizador() - { - Id = x.Field<long>("IdPermissao"), - Descricao = x.Field<string>("Nome").ToUpper() - }).ToList<PermissaoAggilizador>(); - } - catch (Exception exception) - { - list = new List<PermissaoAggilizador>() - { - new PermissaoAggilizador() - { - Id = (long)1, - Descricao = "ADMINISTRADOR" - }, - new PermissaoAggilizador() - { - Id = (long)2, - Descricao = "NORMAL" - }, - new PermissaoAggilizador() - { - Id = (long)3, - Descricao = "LIMITADO" - } - }; - } - return list; - } - - public Usuario SaveOrUpdate(Usuario usuario) - { - UsuarioDb usuarioDb = ApplicationMapper.Mapper.Map<Usuario, UsuarioDb>(usuario); - this.SaveOrUpdate(usuarioDb); - return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); - } - - public Usuario SsoId(AuthSso sso) - { - if (sso.Code != 200) - { - return null; - } - return this.FindBySso(sso.Data.User.Id); - } - - public Usuario ValidateLogin(string login, string password) - { - UsuarioDb usuarioDb = this._unitOfWork.Session.CreateQuery("FROM UsuarioDb WHERE (removido IS NULL OR removido != '1') AND (inativo = '0' OR inativo IS NULL)").List<UsuarioDb>().FirstOrDefault<UsuarioDb>((UsuarioDb u) => { - if (!string.Equals(u.Login.Trim(), login.Trim(), StringComparison.CurrentCultureIgnoreCase)) - { - return false; - } - return u.Senha == password; - }); - return ApplicationMapper.Mapper.Map<UsuarioDb, Usuario>(usuarioDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs deleted file mode 100644 index e765212..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs +++ /dev/null @@ -1,474 +0,0 @@ -using AutoMapper; -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.Ferramentas; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Relatorios; -using Gestor.Model.Domain.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class VendedorParcelaRepository : GenericRepository<VendedorParcelaDb>, IVendedorParcelaRepository, IGenericRepository<VendedorParcelaDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public VendedorParcelaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List<VendedorParcela> AddRange(List<VendedorParcela> repasses) - { - List<VendedorParcelaDb> vendedorParcelaDbs = ApplicationMapper.Mapper.Map<List<VendedorParcela>, List<VendedorParcelaDb>>(repasses); - base.AddRange(vendedorParcelaDbs); - return ApplicationMapper.Mapper.Map<List<VendedorParcelaDb>, List<VendedorParcela>>(vendedorParcelaDbs); - } - - public Vendedor BuscarVendedorPorControle(long id) - { - Vendedor vendedor; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarVendedor(sqlCommand, false); - sqlCommand.CommandText = string.Format("SELECT TOP 1 idvendedor as id FROM vendedorparcela vp INNER JOIN parcela p on p.idparcela = vp.idparcela INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE vp.idtipovendedor = 1 AND p.idsubtipo = 1 AND d.idcontrole = {0};", id); - SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); - if (sqlDataReader.HasRows) - { - sqlDataReader.Read(); - long num = (sqlDataReader["id"] == null ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); - sqlDataReader.Close(); - return Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor x) => { - if (x == null) - { - return false; - } - return x.Id == num; - }); - } - else - { - vendedor = null; - } - } - } - return vendedor; - } - - public bool Delete(long id) - { - VendedorParcelaDb vendedorParcelaDb = base.FindEntityById(id); - if (vendedorParcelaDb == null) - { - return true; - } - base.Delete(vendedorParcelaDb); - return true; - } - - public void DeleteRange(long id) - { - List<VendedorParcelaDb> list = ( - from vp in base.All() - where vp.Documento.Id == id && (int)vp.Parcela.SubTipo == 1 - select vp).ToList<VendedorParcelaDb>(); - if (list.Count == 0) - { - return; - } - VendedorParcelaRepository vendedorParcelaRepository = this; - list.ForEach(new Action<VendedorParcelaDb>(vendedorParcelaRepository.Delete)); - } - - public void DeleteRange(List<VendedorParcela> repasses) - { - List<long> list = ( - from y in repasses - select y.Id).ToList<long>(); - List<VendedorParcelaDb> vendedorParcelaDbs = ( - from x in base.All() - where list.Contains(x.Id) - select x).ToList<VendedorParcelaDb>(); - if (vendedorParcelaDbs.Count == 0) - { - return; - } - VendedorParcelaRepository vendedorParcelaRepository = this; - vendedorParcelaDbs.ForEach(new Action<VendedorParcelaDb>(vendedorParcelaRepository.Delete)); - } - - public List<ManutencaoPagamentos> FindByDate(Filtros filtro) - { - List<ManutencaoPagamentos> manutencaoPagamentos; - object connection; - DataTable dataTable = new DataTable(); - string str = (filtro.Referencia == "DATA PAGAMENTO" ? "CAST(vp.datapgt AS DATE)" : "CAST(vp.dataprepagto AS DATE)"); - List<Condicao> condicaos = new List<Condicao>() - { - new Condicao() - { - Campo = "vp.datapgt", - Valores = null, - Operador = Operador.Diferente, - Operacao = Operacao.And - }, - new Condicao() - { - Campo = str, - Valores = filtro.Inicio.CriarValor<DateTime>(), - Operador = Operador.MaiorEIgual - }, - new Condicao() - { - Campo = str, - Valores = filtro.Fim.CriarValor<DateTime>(), - Operador = Operador.MenorEIgual - } - }; - if (filtro.Vendedores != null && filtro.Vendedores.Any<long>()) - { - condicaos.Add(new Condicao() - { - Campo = "vp.idvendedor", - Valores = filtro.Vendedores.CriarValor<long>() - }); - } - if (filtro.IdEmpresa > (long)0) - { - condicaos.Add(new Condicao() - { - Campo = "c.idempresa", - Valores = filtro.IdEmpresa.CriarValor<long>() - }); - } - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - string str1 = "SELECT p.idparcela, vp.idvendedorparcela as idvendedorparcela, vp.iddocumento as iddocumento, c.idciaseg as idseguradora, cl.nome as nomecliente, c.idramo, d.contrato as apolice, d.aditamento as endosso, v.nome as nomevendedor, p.parcela as numeroparcela, p.valor as valor, p.datarec as datarecebimento, vp.datapgt as datapagamento, vp.dataprepagto as dataprepagamento, p.idsubtipo, c.idempresa, vp.vlrrep, c.idproduto FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN vendedor v on v.idvendedor = vp.idvendedor INNER JOIN parcela p on p.idparcela = vp.idparcela INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE "; - dataTable = sqlCommand.Select(condicaos.CreateParameters(0), str1, ""); - return dataTable.MapManutencao(); - } - } - else - { - manutencaoPagamentos = null; - } - } - return manutencaoPagamentos; - } - - public List<VendedorParcela> FindByDocumentId(long documentId) - { - return this.Select(string.Format(" AND vp.iddocumento = {0}", documentId)); - } - - public VendedorParcela FindById(long id) - { - VendedorParcelaDb vendedorParcelaDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<VendedorParcelaDb, VendedorParcela>(vendedorParcelaDb); - } - - public Vendedor FindByMainDocumentId(long id) - { - Vendedor vendedor; - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarVendedor(sqlCommand, false); - sqlCommand.CommandText = string.Format("SELECT TOP 1 idvendedor as id FROM vendedorparcela vp INNER JOIN parcela p on p.idparcela = vp.idparcela WHERE vp.idtipovendedor = 1 AND p.idsubtipo = 1 AND vp.iddocumento = {0};", id); - SqlDataReader sqlDataReader = sqlCommand.ExecuteReader(); - if (sqlDataReader.HasRows) - { - sqlDataReader.Read(); - long num = (sqlDataReader["id"] == null ? (long)0 : long.Parse(sqlDataReader["id"].ToString())); - sqlDataReader.Close(); - return Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor x) => { - if (x == null) - { - return false; - } - return x.Id == num; - }); - } - else - { - vendedor = null; - } - } - } - return vendedor; - } - - public List<VendedorParcela> FindByParcela(long id) - { - return this.Select(string.Format(" AND vp.idparcela = {0}", id)); - } - - public List<Vendedor> FindVendedoresByDocumentId(long documentId) - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarVendedor(sqlCommand, false); - sqlCommand.CommandText = string.Format("SELECT DISTINCT idvendedor as id FROM vendedorparcela WHERE iddocumento = {0}", documentId); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return Auxiliar.Vendedores.Where<Vendedor>((Vendedor x) => { - List<DataRow> list = dataTable.AsEnumerable().ToList<DataRow>(); - Func<DataRow, long> u003cu003e9_181 = VendedorParcelaRepository.u003cu003ec.u003cu003e9__18_1; - if (u003cu003e9_181 == null) - { - u003cu003e9_181 = (DataRow v) => v.Field<long>("id"); - VendedorParcelaRepository.u003cu003ec.u003cu003e9__18_1 = u003cu003e9_181; - } - return list.Select<DataRow, long>(u003cu003e9_181).Contains<long>(x.Id); - }).ToList<Vendedor>(); - } - - public List<Vendedor> FindVinculoByIdCliente(long idcliente) - { - object connection; - SqlCommand sqlCommand; - List<long> list; - List<Condicao> condicaos = new List<Condicao>(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - condicaos.Add(new Condicao() - { - Campo = "cl.idcliente", - Valores = idcliente.CriarValor<long>() - }); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - sqlCommand = sqlConnection.CreateCommand(); - } - else - { - sqlCommand = null; - } - using (SqlCommand sqlCommand1 = sqlCommand) - { - Auxiliar.CriarAuxiliar(sqlCommand1, false); - string str = "SELECT DISTINCT vp.idvendedor idvendedor FROM vendedorparcela vp LEFT JOIN documento d ON vp.iddocumento = d.iddocumento LEFT JOIN controle c ON c.idcontrole = d.idcontrole LEFT JOIN cliente cl on cl.idcliente = c.idcliente WHERE"; - DataTable dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), str, ""); - list = dataTable.AsEnumerable().Select<DataRow, long>((DataRow column) => column.Field<long>("idvendedor")).ToList<long>(); - } - } - return ( - from v in Auxiliar.Vendedores - where list.Contains(v.Id) - select v).ToList<Vendedor>(); - } - - public bool GerarPagamento(List<long> ids, DateTime data) - { - bool flag; - object connection; - 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) - { - if (sqlConnection != null) - { - SqlTransaction sqlTransaction = sqlConnection.BeginTransaction(); - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandTimeout = 15000; - sqlCommand.Transaction = sqlTransaction; - List<long> nums = ids; - while (nums.Count > 0) - { - List<long> list = nums.Take<long>(1000).ToList<long>(); - List<Condicao> condicaos = new List<Condicao>() - { - new Condicao() - { - Campo = "idvendedorparcela", - Valores = list.CriarValor<long>() - }, - new Condicao() - { - Campo = "datapgt", - Valores = null - } - }; - List<SqlParameter> sqlParameters = new List<SqlParameter>() - { - new SqlParameter() - { - ParameterName = "@datapgt", - SqlDbType = Funcoes.GetDbType(typeof(DateTime)), - Value = data - } - }; - if (sqlCommand.Update(condicaos.CreateParameters(0), "UPDATE vendedorparcela SET datapgt = @datapgt WHERE ", sqlParameters)) - { - nums = (list.Count < 1000 ? new List<long>() : nums.Except<long>(list).ToList<long>()); - } - else - { - flag = false; - return flag; - } - } - sqlTransaction.Commit(); - sqlCommand.Dispose(); - } - } - else - { - flag = false; - return flag; - } - } - return true; - } - catch (Exception exception) - { - flag = false; - } - return flag; - } - - public VendedorParcela Merge(VendedorParcela vendedorParcela) - { - VendedorParcelaDb vendedorParcelaDb = ApplicationMapper.Mapper.Map<VendedorParcela, VendedorParcelaDb>(vendedorParcela); - base.Merge(vendedorParcelaDb); - return ApplicationMapper.Mapper.Map<VendedorParcelaDb, VendedorParcela>(vendedorParcelaDb); - } - - public VendedorParcela SaveOrUpdate(VendedorParcela vendedorParcela) - { - VendedorParcelaDb vendedorParcelaDb = ApplicationMapper.Mapper.Map<VendedorParcela, VendedorParcelaDb>(vendedorParcela); - this.SaveOrUpdate(vendedorParcelaDb); - return ApplicationMapper.Mapper.Map<VendedorParcelaDb, VendedorParcela>(vendedorParcelaDb); - } - - public List<VendedorParcela> Select(string condition) - { - object connection; - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - DataTable dataTable = new DataTable(); - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarVendedor(sqlCommand, true); - sqlCommand.CommandText = string.Concat("SELECT DISTINCT * FROM vendedorparcela vp INNER JOIN parcela p on p.idparcela = vp.idparcela WHERE 1=1 ", condition); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return CustomMap.MapVendedorParcela(dataTable); - } - - public bool TemPagamentoParcela(long id) - { - return base.All().Any<VendedorParcelaDb>((VendedorParcelaDb x) => x.Parcela.Id == id && (x.DataPagamento != null) && (int?)x.Repasse.Forma == (int?)FormaRepasse.Recebimento); - } - - public bool TipoVendedorUtilizado(long id) - { - return base.All().Any<VendedorParcelaDb>((VendedorParcelaDb x) => x.TipoVendedor.Id == id); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs deleted file mode 100644 index 04a6532..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs +++ /dev/null @@ -1,132 +0,0 @@ -using AutoMapper; -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.Seguros; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class VendedorRepository : GenericRepository<VendedorDb>, IVendedorRepository, IGenericRepository<VendedorDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - private const string comandoVendedor = "SELECT idvendedor, nome, corretora, tipoincidenciadesconto, desconto, ativo, idempresa, idcodigobanco, agencia, conta, cpfcnpj, idtipoconta, cpfcnpjtitular, titularconta, obs FROM vendedor WHERE"; - - public VendedorRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public List<Vendedor> Find(bool ativo, long idempresa = 0L) - { - List<Condicao> condicaos = new List<Condicao>() - { - new Condicao() - { - Campo = "idempresa", - Valores = idempresa.CriarValor<long>() - } - }; - List<Condicao> condicaos1 = new List<Condicao>() - { - new Condicao() - { - Campo = "ISNULL(ativo, '1')", - Valores = (ativo ? "1".CriarValor<string>() : "0".CriarValor<string>()) - } - }; - if (idempresa > (long)0) - { - condicaos1.AddRange(condicaos); - } - return this._unitOfWork.Select(condicaos1.CreateParameters(0), "SELECT idvendedor, nome, corretora, tipoincidenciadesconto, desconto, ativo, idempresa, idcodigobanco, agencia, conta, cpfcnpj, idtipoconta, cpfcnpjtitular, titularconta, obs FROM vendedor WHERE", "").MapVendedor(); - } - - public List<Vendedor> Find(long idempresa = 0L) - { - return this.Select((idempresa == 0 ? "" : string.Format(" AND idempresa = {0}", idempresa))); - } - - public List<Vendedor> Find(string nome, long idempresa = 0L) - { - string str = (idempresa == 0 ? "" : string.Format(" AND idempresa = {0}", idempresa)); - string str1 = string.Concat(" AND UPPER(ISNULL(nome, '')) LIKE '%", nome.ToUpper(), "%'"); - return this.Select(string.Concat(str, str1)); - } - - public Vendedor FindById(long id) - { - VendedorDb vendedorDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<VendedorDb, Vendedor>(vendedorDb); - } - - public Vendedor FindCorretora() - { - VendedorDb vendedorDb = base.All().FirstOrDefault<VendedorDb>((VendedorDb x) => x.Corretora); - return ApplicationMapper.Mapper.Map<VendedorDb, Vendedor>(vendedorDb); - } - - public Vendedor Merge(Vendedor vendedor) - { - VendedorDb vendedorDb = ApplicationMapper.Mapper.Map<Vendedor, VendedorDb>(vendedor); - base.Merge(vendedorDb); - return ApplicationMapper.Mapper.Map<VendedorDb, Vendedor>(vendedorDb); - } - - public Vendedor SaveOrUpdate(Vendedor vendedor) - { - VendedorDb vendedorDb = ApplicationMapper.Mapper.Map<Vendedor, VendedorDb>(vendedor); - this.SaveOrUpdate(vendedorDb); - return ApplicationMapper.Mapper.Map<VendedorDb, Vendedor>(vendedorDb); - } - - public List<Vendedor> Select(string condition) - { - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - Auxiliar.CriarAuxiliar(sqlCommand, false); - sqlCommand.CommandText = string.Concat("SELECT idvendedor, nome, corretora, tipoincidenciadesconto, desconto, ativo, idempresa, idcodigobanco, agencia, conta, cpfcnpj, idtipoconta, cpfcnpjtitular, titularconta, obs FROM vendedor WHERE 1=1 ", condition, " "); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - } - } - return dataTable.MapVendedor(); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs deleted file mode 100644 index 2f4d3c1..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs +++ /dev/null @@ -1,115 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class VendedorTelefoneRepository : GenericRepository<VendedorTelefoneDb>, IVendedorTelefoneRepository, IGenericRepository<VendedorTelefoneDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public VendedorTelefoneRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public VendedorTelefone FindById(long id) - { - VendedorTelefoneDb vendedorTelefoneDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<VendedorTelefoneDb, VendedorTelefone>(vendedorTelefoneDb); - } - - public List<VendedorTelefone> FindByVendedorId(long id) - { - List<VendedorTelefoneDb> list = ( - from x in base.All() - where x.Vendedor.Id == id - select x).ToList<VendedorTelefoneDb>(); - return ApplicationMapper.Mapper.Map<List<VendedorTelefoneDb>, List<VendedorTelefone>>(list); - } - - public List<VendedorTelefone> Inserir(List<VendedorTelefone> telefones) - { - List<VendedorTelefoneDb> vendedorTelefoneDbs = ApplicationMapper.Mapper.Map<List<VendedorTelefone>, List<VendedorTelefoneDb>>(telefones); - vendedorTelefoneDbs.ForEach((VendedorTelefoneDb x) => { - if (x.Id == 0) - { - this.SaveOrUpdate(x); - return; - } - base.Merge(x); - }); - return ApplicationMapper.Mapper.Map<List<VendedorTelefoneDb>, List<VendedorTelefone>>(vendedorTelefoneDbs); - } - - public List<VendedorTelefone> Inserir(List<VendedorTelefone> telefones, Vendedor vendedor) - { - telefones.ForEach((VendedorTelefone x) => x.Vendedor = vendedor); - List<VendedorTelefoneDb> vendedorTelefoneDbs = ApplicationMapper.Mapper.Map<List<VendedorTelefone>, List<VendedorTelefoneDb>>(telefones); - base.AddRange(vendedorTelefoneDbs); - return ApplicationMapper.Mapper.Map<List<VendedorTelefoneDb>, List<VendedorTelefone>>(vendedorTelefoneDbs); - } - - public VendedorTelefone Merge(VendedorTelefone telefone) - { - VendedorTelefoneDb vendedorTelefoneDb = ApplicationMapper.Mapper.Map<VendedorTelefone, VendedorTelefoneDb>(telefone); - base.Merge(vendedorTelefoneDb); - return ApplicationMapper.Mapper.Map<VendedorTelefoneDb, VendedorTelefone>(vendedorTelefoneDb); - } - - public List<VendedorTelefone> Merge(List<VendedorTelefone> telefones, Vendedor vendedor) - { - IQueryable<VendedorTelefoneDb> vendedorTelefoneDbs = - from x in base.All() - where x.Vendedor.Id == vendedor.Id - select x; - VendedorTelefoneRepository vendedorTelefoneRepository = this; - ( - from x in vendedorTelefoneDbs - select x.Id).ToList<long>().Where<long>((long x) => { - List<VendedorTelefone> vendedorTelefones = telefones; - Func<VendedorTelefone, long> u003cu003e9_94 = VendedorTelefoneRepository.u003cu003ec.u003cu003e9__9_4; - if (u003cu003e9_94 == null) - { - u003cu003e9_94 = (VendedorTelefone t) => t.Id; - VendedorTelefoneRepository.u003cu003ec.u003cu003e9__9_4 = u003cu003e9_94; - } - return !vendedorTelefones.Select<VendedorTelefone, long>(u003cu003e9_94).Contains<long>(x); - }).ToList<long>().ForEach(new Action<long>(vendedorTelefoneRepository.Delete)); - List<VendedorTelefoneDb> vendedorTelefoneDbs1 = ApplicationMapper.Mapper.Map<List<VendedorTelefone>, List<VendedorTelefoneDb>>(telefones); - vendedorTelefoneDbs1.ForEach((VendedorTelefoneDb x) => { - if (x.Id != 0) - { - base.Merge(x); - return; - } - x.Vendedor = ApplicationMapper.Mapper.Map<Vendedor, VendedorDb>(vendedor); - this.SaveOrUpdate(x); - }); - return ApplicationMapper.Mapper.Map<List<VendedorTelefoneDb>, List<VendedorTelefone>>(vendedorTelefoneDbs1); - } - - public VendedorTelefone SaveOrUpdate(VendedorTelefone telefone) - { - VendedorTelefoneDb vendedorTelefoneDb = ApplicationMapper.Mapper.Map<VendedorTelefone, VendedorTelefoneDb>(telefone); - this.SaveOrUpdate(vendedorTelefoneDb); - return ApplicationMapper.Mapper.Map<VendedorTelefoneDb, VendedorTelefone>(vendedorTelefoneDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs deleted file mode 100644 index 49c552f..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs +++ /dev/null @@ -1,94 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class VendedorUsuarioRepository : GenericRepository<VendedorUsuarioDb>, IVendedorUsuarioRepository, IGenericRepository<VendedorUsuarioDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public VendedorUsuarioRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public bool Exist(long id) - { - return base.All().Any<VendedorUsuarioDb>((VendedorUsuarioDb v) => v.Vendedor.Id == id); - } - - public bool ExistVinculoUsuario(long idUsuario) - { - return base.All().Any<VendedorUsuarioDb>((VendedorUsuarioDb v) => v.Usuario.Id == idUsuario); - } - - public VendedorUsuario FindById(long id) - { - VendedorUsuarioDb vendedorUsuarioDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<VendedorUsuarioDb, VendedorUsuario>(vendedorUsuarioDb); - } - - public IList<Vendedor> FindByUsuario(long idUsuario) - { - List<VendedorUsuarioDb> list = ( - from x in base.All() - where x.Usuario.Id == idUsuario - select x).ToList<VendedorUsuarioDb>(); - List<Vendedor> vendedors = new List<Vendedor>(); - list.ForEach((VendedorUsuarioDb vu) => vendedors.Add((new VendedorRepository(this._unitOfWork)).FindById(vu.Vendedor.Id))); - return vendedors; - } - - public List<VendedorUsuario> FindByVinculo(long idUsuario) - { - return ( - from x in base.All() - where x.Usuario.Id == idUsuario - select x into u - select new VendedorUsuario() - { - Id = u.Id, - Usuario = new Usuario() - { - Id = u.Usuario.Id, - Nome = u.Usuario.Nome - }, - Vendedor = new Vendedor() - { - Id = u.Vendedor.Id, - Nome = u.Vendedor.Nome - } - }).ToList<VendedorUsuario>(); - } - - public VendedorUsuario Merge(VendedorUsuario vendedorUsuario) - { - VendedorUsuarioDb vendedorUsuarioDb = ApplicationMapper.Mapper.Map<VendedorUsuario, VendedorUsuarioDb>(vendedorUsuario); - base.Merge(vendedorUsuarioDb); - return ApplicationMapper.Mapper.Map<VendedorUsuarioDb, VendedorUsuario>(vendedorUsuarioDb); - } - - public VendedorUsuario SaveOrUpdate(VendedorUsuario vendedorUsuario) - { - VendedorUsuarioDb vendedorUsuarioDb = ApplicationMapper.Mapper.Map<VendedorUsuario, VendedorUsuarioDb>(vendedorUsuario); - this.SaveOrUpdate(vendedorUsuarioDb); - return ApplicationMapper.Mapper.Map<VendedorUsuarioDb, VendedorUsuario>(vendedorUsuarioDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs deleted file mode 100644 index d5507ae..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs +++ /dev/null @@ -1,66 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Generic; -using Gestor.Infrastructure.Entities.Seguros; -using Gestor.Infrastructure.Mappers; -using Gestor.Infrastructure.Repository.Generic; -using Gestor.Infrastructure.Repository.Interface; -using Gestor.Infrastructure.UnitOfWork.Generic; -using Gestor.Model.Domain.Seguros; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class VidaRepository : GenericRepository<VidaDb>, IVidaRepository, IGenericRepository<VidaDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public VidaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public void Delete(long id) - { - base.Delete(base.FindEntityById(id)); - } - - public void DeleteRange(List<long> ids) - { - List<VidaDb> list = ( - from x in base.All() - where ids.Contains(x.Item.Id) - select x).ToList<VidaDb>(); - base.DeleteRange(list); - } - - public Vida Find(long id) - { - VidaDb vidaDb = base.All().FirstOrDefault<VidaDb>((VidaDb x) => x.Item.Id == id) ?? new VidaDb(); - return ApplicationMapper.Mapper.Map<VidaDb, Vida>(vidaDb); - } - - public Vida FindById(long id) - { - VidaDb vidaDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<VidaDb, Vida>(vidaDb); - } - - public Vida Merge(Vida vida) - { - VidaDb vidaDb = ApplicationMapper.Mapper.Map<Vida, VidaDb>(vida); - base.Merge(vidaDb); - return ApplicationMapper.Mapper.Map<VidaDb, Vida>(vidaDb); - } - - public Vida SaveOrUpdate(Vida vida) - { - VidaDb vidaDb = ApplicationMapper.Mapper.Map<Vida, VidaDb>(vida); - this.SaveOrUpdate(vidaDb); - return ApplicationMapper.Mapper.Map<VidaDb, Vida>(vidaDb); - } - } -} \ No newline at end of file diff --git a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs b/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs deleted file mode 100644 index 4ad03aa..0000000 --- a/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs +++ /dev/null @@ -1,345 +0,0 @@ -using AutoMapper; -using Gestor.Infrastructure.Entities.Aggilizador; -using Gestor.Infrastructure.Entities.Generic; -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.Relatorios; -using Gestor.Model.Helper; -using NHibernate; -using NHibernate.Connection; -using NHibernate.Impl; -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using System.Data.SqlClient; -using System.Linq; -using System.Runtime.CompilerServices; - -namespace Gestor.Infrastructure.Repository.Logic -{ - public class VinculoDocumentoRepository : GenericRepository<VinculoDocumentoDb>, IVinculoDocumentoRepository, IGenericRepository<VinculoDocumentoDb> - { - private readonly GenericUnitOfWork _unitOfWork; - - public VinculoDocumentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session) - { - this._unitOfWork = unitOfWork; - } - - public List<ArquivoVinculo> BuscarArquivos(List<long> ids, TipoArquivoVinculo type) - { - string str; - str = (type == TipoArquivoVinculo.Proposta ? "IdPropostaDigital" : "IdApoliceDigital"); - return this.Select(string.Concat(new string[] { " AND ", str, " IN (", string.Join<long>(",", ids), ")" }), type); - } - - public void Delete(long id) - { - VinculoDocumentoDb vinculoDocumentoDb = base.FindEntityById(id); - if (vinculoDocumentoDb == null) - { - return; - } - base.Delete(vinculoDocumentoDb); - } - - public VinculoDocumento FindById(long id) - { - VinculoDocumentoDb vinculoDocumentoDb = base.FindEntityById(id); - return ApplicationMapper.Mapper.Map<VinculoDocumentoDb, VinculoDocumento>(vinculoDocumentoDb); - } - - public VinculoDocumento Merge(VinculoDocumento vinculo) - { - VinculoDocumentoDb vinculoDocumentoDb = ApplicationMapper.Mapper.Map<VinculoDocumento, VinculoDocumentoDb>(vinculo); - base.Merge(vinculoDocumentoDb); - return ApplicationMapper.Mapper.Map<VinculoDocumentoDb, VinculoDocumento>(vinculoDocumentoDb); - } - - public VinculoDocumento SaveOrUpdate(VinculoDocumento vinculo) - { - VinculoDocumentoDb vinculoDocumentoDb = ApplicationMapper.Mapper.Map<VinculoDocumento, VinculoDocumentoDb>(vinculo); - this.SaveOrUpdate(vinculoDocumentoDb); - return ApplicationMapper.Mapper.Map<VinculoDocumentoDb, VinculoDocumento>(vinculoDocumentoDb); - } - - public void SaveVinculo(VinculoDocumentoDb vinculoDb) - { - if (vinculoDb.Id == 0) - { - this.SaveOrUpdate(vinculoDb); - return; - } - base.Merge(vinculoDb); - } - - private List<ArquivoVinculo> Select(string condition, TipoArquivoVinculo type) - { - string str; - string str1; - object connection; - DataTable dataTable = new DataTable(); - SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl; - if (sessionFactory != null) - { - connection = sessionFactory.ConnectionProvider.GetConnection(); - } - else - { - connection = null; - } - using (SqlConnection sqlConnection = connection as SqlConnection) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - if (type == TipoArquivoVinculo.Proposta) - { - str = "IdArquivoProposta as Id, Conteudo as Arquivo, IdPropostaDigital as IdVinculo, Chave, Ano, Storage"; - str1 = "ArquivoProposta"; - } - else - { - str = "IdArquivoApolice as Id, Conteudo as Arquivo, IdApoliceDigital as IdVinculo, Chave, Ano, Storage"; - str1 = "ArquivoApolice"; - } - sqlCommand.CommandText = string.Concat(new string[] { "SELECT ", str, " FROM ", str1, " WHERE 1=1 ", condition }); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - sqlCommand.Parameters.Clear(); - } - } - } - return CustomMap.MapArquivoVinculo(dataTable); - } - - public int Sincronize(DateTime inicio, List<DadosVinculo> dados) - { - int num1; - object connection; - int num2; - int num3 = 0; - int num4 = 0; - try - { - 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) - { - if (sqlConnection != null) - { - using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) - { - sqlCommand.CommandText = "SELECT * FROM PropostaDigital p INNER JOIN ClienteDigital c on c.idcliente = p.idcliente WHERE Data >= @Data"; - sqlCommand.Parameters.AddWithValue("@Data", inicio.AddMonths(-2)); - using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter()) - { - sqlDataAdapter.SelectCommand = sqlCommand; - sqlDataAdapter.Fill(dataTable); - } - sqlCommand.CommandText = "SELECT * FROM ApoliceDigital p INNER JOIN ClienteDigital c on c.idcliente = p.idcliente WHERE DataEmissao >= @Data"; - using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter()) - { - sqlDataAdapter1.SelectCommand = sqlCommand; - sqlDataAdapter1.Fill(dataTable1); - } - sqlCommand.Parameters.Clear(); - } - } - } - dataTable = dataTable.AsEnumerable().Where<DataRow>((DataRow x) => !string.IsNullOrWhiteSpace(x.Field<string>("Numero"))).CopyToDataTable<DataRow>(); - dados.ForEach((DadosVinculo x) => { - num3++; - if (x.IdSeguradora != (long)1) - { - x.Proposta = x.Proposta.Clear(); - } - x.Documento = x.Documento.Clear(); - x.Vinculo = x.Vinculo ?? new VinculoDocumento() - { - IdDocumento = x.Id - }; - if (!string.IsNullOrWhiteSpace(x.Proposta) && string.IsNullOrWhiteSpace(x.Endosso)) - { - DataRow dataRow = (x.Vinculo.IdPropostaDigital > (long)0 ? dataTable.AsEnumerable().FirstOrDefault<DataRow>((DataRow p) => p.Field<long>("IdProposta") == x.Vinculo.IdPropostaDigital) : dataTable.AsEnumerable().FirstOrDefault<DataRow>((DataRow p) => { - if (x.IdSeguradora == (long)1 && !p.IsNull("Identificacao")) - { - return p.Field<string>("Identificacao").Equals(x.Proposta); - } - if (!p.Field<string>("Numero").Equals(x.Proposta)) - { - return false; - } - return p.Field<int>("Seguradora").Equals((int)x.IdSeguradora); - })); - if (dataRow != null) - { - x.Vinculo.IdPropostaDigital = dataRow.Field<long>("IdProposta"); - DataRow dataRow1 = dataTable1.AsEnumerable().FirstOrDefault<DataRow>((DataRow y) => { - if (!y.Field<long?>("IdProposta").HasValue) - { - return false; - } - return y.Field<long>("IdProposta") == x.Vinculo.IdPropostaDigital; - }); - x.Vinculo.IdApoliceDigital = (dataRow1 != null ? dataRow1.Field<long>("IdApolice") : (long)0); - this.SaveVinculo(ApplicationMapper.Mapper.Map<VinculoDocumento, VinculoDocumentoDb>(x.Vinculo)); - num4++; - return; - } - EnumerableRowCollection<DataRow> dataRows = dataTable.AsEnumerable().Where<DataRow>((DataRow p) => { - if (!string.IsNullOrEmpty(p.Field<string>("Documento")) && !p.Field<string>("Documento").Equals(x.Documento) || !p.Field<int>("Seguradora").Equals((int)x.IdSeguradora)) - { - return false; - } - if (x.Proposta.Contains(p.Field<string>("Numero"))) - { - return true; - } - return p.Field<string>("Numero").Contains(x.Proposta); - }); - Func<DataRow, long> u003cu003e9_38 = VinculoDocumentoRepository.u003cu003ec.u003cu003e9__3_8; - if (u003cu003e9_38 == null) - { - u003cu003e9_38 = (DataRow y) => y.Field<long>("idProposta"); - VinculoDocumentoRepository.u003cu003ec.u003cu003e9__3_8 = u003cu003e9_38; - } - List<long> list = dataRows.Select<DataRow, long>(u003cu003e9_38).ToList<long>(); - if (list.Count != 0) - { - DataRow dataRow2 = dataTable1.AsEnumerable().Where<DataRow>((DataRow y) => { - if (!y.Field<long?>("IdProposta").HasValue) - { - return false; - } - return list.Contains(y.Field<long>("IdProposta")); - }).FirstOrDefault<DataRow>((DataRow y) => { - if (y.Field<string>("Endosso") != null && (!int.TryParse(y.Field<string>("Endosso"), out num2) || num2 != 0)) - { - return false; - } - DateTime? nullable = y.Field<DateTime?>("VigenciaInicial"); - DateTime vigenciaInicial = x.VigenciaInicial; - if ((nullable.HasValue ? nullable.GetValueOrDefault() != vigenciaInicial : true)) - { - nullable = y.Field<DateTime?>("VigenciaFinal"); - DateTime? vigenciafinal = x.Vigenciafinal; - if ((nullable.HasValue == vigenciafinal.HasValue ? (nullable.HasValue ? nullable.GetValueOrDefault() != vigenciafinal.GetValueOrDefault() : false) : true)) - { - vigenciafinal = y.Field<DateTime?>("DataEmissao"); - if (!vigenciafinal.HasValue) - { - return false; - } - vigenciaInicial = y.Field<DateTime>("DataEmissao"); - return vigenciaInicial.AddMonths(1) >= x.VigenciaInicial; - } - } - return true; - }); - if (dataRow2 != null) - { - dataRow = dataTable.AsEnumerable().First<DataRow>((DataRow p) => p.Field<long>("IdProposta") == dataRow2.Field<long>("IdProposta")); - x.Vinculo.IdPropostaDigital = dataRow.Field<long>("IdProposta"); - x.Vinculo.IdApoliceDigital = dataRow2.Field<long>("IdApolice"); - this.SaveVinculo(ApplicationMapper.Mapper.Map<VinculoDocumento, VinculoDocumentoDb>(x.Vinculo)); - num4++; - return; - } - } - } - num2 = 0; - DataRow dataRow3 = dataTable1.AsEnumerable().Where<DataRow>((DataRow p) => { - if (p.Field<string>("Documento") == null || !p.Field<string>("Documento").Equals(x.Documento)) - { - return false; - } - return p.Field<int>("Seguradora").Equals((int)x.IdSeguradora); - }).ToList<DataRow>().FirstOrDefault<DataRow>((DataRow y) => { - DateTime vigenciaInicial; - DateTime? vigenciafinal; - if (!string.IsNullOrWhiteSpace(x.Endosso)) - { - if (y.Field<string>("Endosso") == null || !int.TryParse(y.Field<string>("Endosso"), out num2) || num2 <= 0) - { - return false; - } - vigenciafinal = y.Field<DateTime?>("VigenciaInicial"); - vigenciaInicial = x.VigenciaInicial; - if (!vigenciafinal.HasValue) - { - return false; - } - return vigenciafinal.GetValueOrDefault() == vigenciaInicial; - } - if (y.Field<string>("Endosso") == null) - { - return true; - } - if (!int.TryParse(y.Field<string>("Endosso"), out num2) || num2 != 0) - { - return false; - } - DateTime? nullable = y.Field<DateTime?>("VigenciaInicial"); - vigenciaInicial = x.VigenciaInicial; - if ((nullable.HasValue ? nullable.GetValueOrDefault() != vigenciaInicial : true)) - { - nullable = y.Field<DateTime?>("VigenciaFinal"); - vigenciafinal = x.Vigenciafinal; - if ((nullable.HasValue == vigenciafinal.HasValue ? (nullable.HasValue ? nullable.GetValueOrDefault() != vigenciafinal.GetValueOrDefault() : false) : true)) - { - vigenciafinal = y.Field<DateTime?>("DataEmissao"); - if (!vigenciafinal.HasValue) - { - return false; - } - vigenciaInicial = y.Field<DateTime>("DataEmissao"); - return vigenciaInicial.AddMonths(1) >= x.VigenciaInicial; - } - } - return true; - }); - if (dataRow3 == null) - { - return; - } - DataRow dataRow4 = dataTable.AsEnumerable().FirstOrDefault<DataRow>((DataRow p) => { - if (!dataRow3.Field<long?>("IdProposta").HasValue) - { - return false; - } - return p.Field<long>("IdProposta") == dataRow3.Field<long>("IdProposta"); - }); - x.Vinculo.IdPropostaDigital = (dataRow4 != null ? dataRow4.Field<long>("IdProposta") : (long)0); - x.Vinculo.IdApoliceDigital = dataRow3.Field<long>("IdApolice"); - this.SaveVinculo(ApplicationMapper.Mapper.Map<VinculoDocumento, VinculoDocumentoDb>(x.Vinculo)); - num4++; - }); - num1 = num4; - } - catch (Exception exception) - { - num1 = num4; - } - return num1; - } - } -} \ No newline at end of file -- cgit v1.2.3