summaryrefslogtreecommitdiff
path: root/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic
diff options
context:
space:
mode:
Diffstat (limited to 'Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic')
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs168
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs71
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs151
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs86
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs149
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs92
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs44
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs607
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs69
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs119
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs46
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs96
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs248
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs223
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs3102
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs220
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs112
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs65
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs70
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs174
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs46
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs101
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs61
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs66
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs73
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs68
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs161
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs75
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs315
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs99
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DocumentoRepository.cs5095
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs143
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs93
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs55
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs237
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs65
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs103
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs71
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs102
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs402
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs1450
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs345
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs158
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs127
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs125
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs59
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs131
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs111
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs59
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs108
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs4562
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs251
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs64
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs191
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs54
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs84
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs93
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs101
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs76
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs92
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs245
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs38
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs85
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs71
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs183
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs222
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs298
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs1991
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs44
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs54
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs66
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs136
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs131
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs97
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs76
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs61
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs415
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs56
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs75
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs54
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs76
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs462
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs52
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs54
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs139
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs152
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs305
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs474
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs132
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs115
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs94
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs66
-rw-r--r--Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs345
93 files changed, 28448 insertions, 0 deletions
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs
new file mode 100644
index 0000000..aff2bf7
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AdiantamentoRepository.cs
@@ -0,0 +1,168 @@
+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<AdiantamentoDb>, IAdiantamentoRepository, IGenericRepository<AdiantamentoDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public AdiantamentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Adiantamento> AddRange(List<Adiantamento> adiantamentos)
+ {
+ List<AdiantamentoDb> adiantamentoDbs = ApplicationMapper.Mapper.Map<List<Adiantamento>, List<AdiantamentoDb>>(adiantamentos);
+ base.AddRange(adiantamentoDbs);
+ return ApplicationMapper.Mapper.Map<List<AdiantamentoDb>, List<Adiantamento>>(adiantamentoDbs);
+ }
+
+ public List<Adiantamento> BuscarAdiantamentos(long id, bool concluido = false)
+ {
+ List<AdiantamentoDb> list = (
+ from x in base.All()
+ where x.Vendedor.Id == id && x.Pago == concluido
+ select x).ToList<AdiantamentoDb>();
+ return ApplicationMapper.Mapper.Map<List<AdiantamentoDb>, List<Adiantamento>>(list);
+ }
+
+ public void Delete(long id)
+ {
+ base.Delete(base.FindEntityById(id));
+ }
+
+ public List<Adiantamento> Find(bool ativo)
+ {
+ return this.Select((new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "ativo",
+ Valores = null
+ },
+ new Condicao()
+ {
+ Campo = "pago",
+ Valores = "1".CriarValor<string>()
+ }
+ }).CreateParameters(0));
+ }
+
+ public List<Adiantamento> Find(long id)
+ {
+ return this.Select((new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idvendedor",
+ Valores = id.CriarValor<long>()
+ }
+ }).CreateParameters(0));
+ }
+
+ public List<Adiantamento> Find(string nome)
+ {
+ return this.Select((new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "historico",
+ Valores = nome.CriarValor<string>()
+ }
+ }).CreateParameters(0));
+ }
+
+ public List<Adiantamento> FindByDate(DateTime inicio, DateTime fim, List<long> vendedores = null, bool segundavia = false)
+ {
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = (segundavia ? "CAST(Pagamento AS DATE)" : "CAST(data AS DATE)"),
+ Valores = inicio.CriarValor<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ },
+ new Condicao()
+ {
+ Campo = (segundavia ? "CAST(Pagamento AS DATE)" : "CAST(data AS DATE)"),
+ Valores = fim.CriarValor<DateTime>(),
+ Operador = Operador.MenorEIgual
+ }
+ };
+ condicaos.AddRange((!segundavia ? new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "pago",
+ Valores = null,
+ Operacao = Operacao.Or,
+ Grupo = 1
+ },
+ new Condicao()
+ {
+ Campo = "pago",
+ Valores = "1".CriarValor<string>(),
+ Operacao = Operacao.Or,
+ Grupo = 1,
+ Operador = Operador.Diferente
+ }
+ } : new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "pago",
+ Valores = "1".CriarValor<string>()
+ }
+ }));
+ if (vendedores != null && vendedores.Count > 0)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "idvendedor",
+ Valores = vendedores.CriarValor<long>()
+ });
+ }
+ return this.Select(condicaos.CreateParameters(0));
+ }
+
+ public Adiantamento FindById(long id)
+ {
+ AdiantamentoDb adiantamentoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<AdiantamentoDb, Adiantamento>(adiantamentoDb);
+ }
+
+ public Adiantamento Merge(Adiantamento adiantamento)
+ {
+ AdiantamentoDb adiantamentoDb = ApplicationMapper.Mapper.Map<Adiantamento, AdiantamentoDb>(adiantamento);
+ base.Merge(adiantamentoDb);
+ return ApplicationMapper.Mapper.Map<AdiantamentoDb, Adiantamento>(adiantamentoDb);
+ }
+
+ public Adiantamento SaveOrUpdate(Adiantamento adiantamento)
+ {
+ AdiantamentoDb adiantamentoDb = ApplicationMapper.Mapper.Map<Adiantamento, AdiantamentoDb>(adiantamento);
+ this.SaveOrUpdate(adiantamentoDb);
+ return ApplicationMapper.Mapper.Map<AdiantamentoDb, Adiantamento>(adiantamentoDb);
+ }
+
+ private List<Adiantamento> Select(SqlQueryCondition sqlCondition)
+ {
+ return this._unitOfWork.Select(sqlCondition, "SELECT DISTINCT * FROM adiantamento WHERE", "").MapAdiantamento();
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs
new file mode 100644
index 0000000..b5b4d57
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AeronauticoRepository.cs
@@ -0,0 +1,71 @@
+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<AeronauticoDb>, IAeronauticoRepository, IGenericRepository<AeronauticoDb>
+ {
+ 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<long> ids)
+ {
+ List<AeronauticoDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Item.Id)
+ select x).ToList<AeronauticoDb>();
+ base.DeleteRange(list);
+ }
+
+ public Aeronautico Find(long id)
+ {
+ AeronauticoDb aeronauticoDb = base.All().FirstOrDefault<AeronauticoDb>((AeronauticoDb x) => x.Item.Id == id) ?? new AeronauticoDb();
+ return ApplicationMapper.Mapper.Map<AeronauticoDb, Aeronautico>(aeronauticoDb);
+ }
+
+ public Aeronautico FindById(long id)
+ {
+ AeronauticoDb aeronauticoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<AeronauticoDb, Aeronautico>(aeronauticoDb);
+ }
+
+ public Aeronautico Merge(Aeronautico aeronautico)
+ {
+ AeronauticoDb aeronauticoDb = ApplicationMapper.Mapper.Map<Aeronautico, AeronauticoDb>(aeronautico);
+ base.Merge(aeronauticoDb);
+ return ApplicationMapper.Mapper.Map<AeronauticoDb, Aeronautico>(aeronauticoDb);
+ }
+
+ public Aeronautico SaveOrUpdate(Aeronautico aeronautico)
+ {
+ AeronauticoDb aeronauticoDb = ApplicationMapper.Mapper.Map<Aeronautico, AeronauticoDb>(aeronautico);
+ this.SaveOrUpdate(aeronauticoDb);
+ return ApplicationMapper.Mapper.Map<AeronauticoDb, Aeronautico>(aeronauticoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs
new file mode 100644
index 0000000..9131660
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaEmailRepository.cs
@@ -0,0 +1,151 @@
+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<AgendaEmailDb>, IAgendaEmailRepository, IGenericRepository<AgendaEmailDb>
+ {
+ 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<AgendaEmailDb> agendaEmailDbs =
+ from x in base.All()
+ where x.Agenda.Id == id
+ select x;
+ if (!agendaEmailDbs.Any<AgendaEmailDb>())
+ {
+ return;
+ }
+ base.DeleteRange(agendaEmailDbs);
+ }
+
+ private List<AgendaEmail> FindByAgenda(long id)
+ {
+ List<AgendaEmailDb> list = (
+ from x in base.All()
+ where x.Agenda.Id == id
+ select x).ToList<AgendaEmailDb>();
+ return ApplicationMapper.Mapper.Map<List<AgendaEmailDb>, List<AgendaEmail>>(list);
+ }
+
+ public List<AgendaEmail> FindByAgenda(List<long> ids)
+ {
+ List<AgendaEmailDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Agenda.Id)
+ select x).ToList<AgendaEmailDb>();
+ return ApplicationMapper.Mapper.Map<List<AgendaEmailDb>, List<AgendaEmail>>(list);
+ }
+
+ public List<AgendaEmail> FindByAgendaId(long id)
+ {
+ return this.FindByAgenda(id);
+ }
+
+ public AgendaEmail FindById(long id)
+ {
+ AgendaEmailDb agendaEmailDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<AgendaEmailDb, AgendaEmail>(agendaEmailDb);
+ }
+
+ public List<AgendaEmail> FindEmailAgenda(string email)
+ {
+ List<AgendaEmailDb> list = (
+ from x in base.All()
+ where x.Email.Contains(email)
+ select x).ToList<AgendaEmailDb>();
+ return ApplicationMapper.Mapper.Map<List<AgendaEmailDb>, List<AgendaEmail>>(list);
+ }
+
+ public List<AgendaEmail> Inserir(List<AgendaEmail> emails, Agenda agenda)
+ {
+ emails.ForEach((AgendaEmail x) => x.Agenda = agenda);
+ List<AgendaEmailDb> agendaEmailDbs = ApplicationMapper.Mapper.Map<List<AgendaEmail>, List<AgendaEmailDb>>(emails);
+ base.AddRange(agendaEmailDbs);
+ return ApplicationMapper.Mapper.Map<List<AgendaEmailDb>, List<AgendaEmail>>(agendaEmailDbs);
+ }
+
+ public List<AgendaEmail> Inserir(List<AgendaEmail> emails)
+ {
+ List<AgendaEmailDb> agendaEmailDbs = ApplicationMapper.Mapper.Map<List<AgendaEmail>, List<AgendaEmailDb>>(emails);
+ agendaEmailDbs.ForEach((AgendaEmailDb x) => {
+ if (x.Id == 0)
+ {
+ this.SaveOrUpdate(x);
+ return;
+ }
+ base.Merge(x);
+ });
+ return ApplicationMapper.Mapper.Map<List<AgendaEmailDb>, List<AgendaEmail>>(agendaEmailDbs);
+ }
+
+ public AgendaEmail Merge(AgendaEmail agendaEmail)
+ {
+ AgendaEmailDb agendaEmailDb = ApplicationMapper.Mapper.Map<AgendaEmail, AgendaEmailDb>(agendaEmail);
+ base.Merge(agendaEmailDb);
+ return ApplicationMapper.Mapper.Map<AgendaEmailDb, AgendaEmail>(agendaEmailDb);
+ }
+
+ public List<AgendaEmail> Merge(List<AgendaEmail> emails, Agenda agenda)
+ {
+ IQueryable<AgendaEmailDb> 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<long>().Where<long>((long x) => {
+ List<AgendaEmail> agendaEmails = emails;
+ Func<AgendaEmail, long> 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<AgendaEmail, long>(u003cu003e9_114).Contains<long>(x);
+ }).ToList<long>().ForEach(new Action<long>(agendaEmailRepository.Delete));
+ List<AgendaEmailDb> agendaEmailDbs1 = ApplicationMapper.Mapper.Map<List<AgendaEmail>, List<AgendaEmailDb>>(emails);
+ agendaEmailDbs1.ForEach((AgendaEmailDb x) => {
+ if (x.Id != 0)
+ {
+ base.Merge(x);
+ return;
+ }
+ x.Agenda = ApplicationMapper.Mapper.Map<Agenda, AgendaDb>(agenda);
+ this.SaveOrUpdate(x);
+ });
+ return ApplicationMapper.Mapper.Map<List<AgendaEmailDb>, List<AgendaEmail>>(agendaEmailDbs1);
+ }
+
+ public AgendaEmail SaveOrUpdate(AgendaEmail agendaEmail)
+ {
+ AgendaEmailDb agendaEmailDb = ApplicationMapper.Mapper.Map<AgendaEmail, AgendaEmailDb>(agendaEmail);
+ this.SaveOrUpdate(agendaEmailDb);
+ return ApplicationMapper.Mapper.Map<AgendaEmailDb, AgendaEmail>(agendaEmailDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs
new file mode 100644
index 0000000..1ab42b8
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaRepository.cs
@@ -0,0 +1,86 @@
+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<AgendaDb>, IAgendaRepository, IGenericRepository<AgendaDb>
+ {
+ 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<Agenda> Find(string filter)
+ {
+ AgendaRepository.u003cu003ec__DisplayClass3_0 variable = null;
+ IQueryable<AgendaDb> agendaDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(AgendaDb), "x");
+ IQueryable<AgendaDb> agendaDbs1 = agendaDbs.Where<AgendaDb>(Expression.Lambda<Func<AgendaDb, bool>>(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<Expression>()), (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<AgendaDb, Agenda>(Expression.Lambda<Func<AgendaDb, Agenda>>(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<Agenda>();
+ }
+
+ public List<Agenda> Find()
+ {
+ List<AgendaDb> list = base.All().ToList<AgendaDb>();
+ return ApplicationMapper.Mapper.Map<List<AgendaDb>, List<Agenda>>(list);
+ }
+
+ public Agenda FindById(long id)
+ {
+ AgendaDb agendaDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<AgendaDb, Agenda>(agendaDb);
+ }
+
+ public List<Agenda> FindByName(string name)
+ {
+ AgendaRepository.u003cu003ec__DisplayClass4_0 variable = null;
+ IQueryable<AgendaDb> agendaDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(AgendaDb), "x");
+ IQueryable<AgendaDb> agendaDbs1 = agendaDbs.Where<AgendaDb>(Expression.Lambda<Func<AgendaDb, bool>>(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<Expression>()), (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<AgendaDb>(150);
+ parameterExpression = Expression.Parameter(typeof(AgendaDb), "x");
+ return agendaDbs1.Select<AgendaDb, Agenda>(Expression.Lambda<Func<AgendaDb, Agenda>>(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<Agenda>();
+ }
+
+ public Agenda Merge(Agenda agenda)
+ {
+ AgendaDb agendaDb = ApplicationMapper.Mapper.Map<Agenda, AgendaDb>(agenda);
+ base.Merge(agendaDb);
+ return ApplicationMapper.Mapper.Map<AgendaDb, Agenda>(agendaDb);
+ }
+
+ public Agenda SaveOrUpdate(Agenda agenda)
+ {
+ AgendaDb agendaDb = ApplicationMapper.Mapper.Map<Agenda, AgendaDb>(agenda);
+ this.SaveOrUpdate(agendaDb);
+ return ApplicationMapper.Mapper.Map<AgendaDb, Agenda>(agendaDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs
new file mode 100644
index 0000000..9c1b0d6
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AgendaTelefoneRepository.cs
@@ -0,0 +1,149 @@
+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<AgendaTelefoneDb>, IAgendaTelefoneRepository, IGenericRepository<AgendaTelefoneDb>
+ {
+ 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<AgendaTelefoneDb> agendaTelefoneDbs =
+ from x in base.All()
+ where x.Agenda.Id == id
+ select x;
+ if (!agendaTelefoneDbs.Any<AgendaTelefoneDb>())
+ {
+ return;
+ }
+ base.DeleteRange(agendaTelefoneDbs);
+ }
+
+ public List<AgendaTelefone> Find(string telefone)
+ {
+ List<AgendaTelefoneDb> list = (
+ from x in base.All()
+ where x.Numero.Contains(telefone)
+ select x).ToList<AgendaTelefoneDb>();
+ return ApplicationMapper.Mapper.Map<List<AgendaTelefoneDb>, List<AgendaTelefone>>(list);
+ }
+
+ private List<AgendaTelefone> FindByAgenda(long id)
+ {
+ return (
+ from x in base.All()
+ where x.Agenda.Id == id
+ select new AgendaTelefone()
+ {
+ Id = x.Id,
+ Agenda = ApplicationMapper.Mapper.Map<AgendaDb, Agenda>(x.Agenda),
+ Prefixo = x.Prefixo,
+ Numero = x.Numero,
+ Tipo = x.Tipo,
+ Observacao = x.Observacao
+ }).ToList<AgendaTelefone>();
+ }
+
+ public List<AgendaTelefone> FindByAgendaId(long id)
+ {
+ return this.FindByAgenda(id);
+ }
+
+ public AgendaTelefone FindById(long id)
+ {
+ AgendaTelefoneDb agendaTelefoneDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<AgendaTelefoneDb, AgendaTelefone>(agendaTelefoneDb);
+ }
+
+ public List<AgendaTelefone> Inserir(List<AgendaTelefone> telefones)
+ {
+ List<AgendaTelefoneDb> agendaTelefoneDbs = ApplicationMapper.Mapper.Map<List<AgendaTelefone>, List<AgendaTelefoneDb>>(telefones);
+ agendaTelefoneDbs.ForEach((AgendaTelefoneDb x) => {
+ if (x.Id == 0)
+ {
+ this.SaveOrUpdate(x);
+ return;
+ }
+ base.Merge(x);
+ });
+ return ApplicationMapper.Mapper.Map<List<AgendaTelefoneDb>, List<AgendaTelefone>>(agendaTelefoneDbs);
+ }
+
+ public List<AgendaTelefone> Inserir(List<AgendaTelefone> telefones, Agenda agenda)
+ {
+ telefones.ForEach((AgendaTelefone x) => x.Agenda = agenda);
+ List<AgendaTelefoneDb> agendaTelefoneDbs = ApplicationMapper.Mapper.Map<List<AgendaTelefone>, List<AgendaTelefoneDb>>(telefones);
+ base.AddRange(agendaTelefoneDbs);
+ return ApplicationMapper.Mapper.Map<List<AgendaTelefoneDb>, List<AgendaTelefone>>(agendaTelefoneDbs);
+ }
+
+ public AgendaTelefone Merge(AgendaTelefone telefone)
+ {
+ AgendaTelefoneDb agendaTelefoneDb = ApplicationMapper.Mapper.Map<AgendaTelefone, AgendaTelefoneDb>(telefone);
+ base.Merge(agendaTelefoneDb);
+ return ApplicationMapper.Mapper.Map<AgendaTelefoneDb, AgendaTelefone>(agendaTelefoneDb);
+ }
+
+ public List<AgendaTelefone> Merge(List<AgendaTelefone> telefones, Agenda agenda)
+ {
+ IQueryable<AgendaTelefoneDb> 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<long>().Where<long>((long x) => {
+ List<AgendaTelefone> agendaTelefones = telefones;
+ Func<AgendaTelefone, long> 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<AgendaTelefone, long>(u003cu003e9_114).Contains<long>(x);
+ }).ToList<long>().ForEach(new Action<long>(agendaTelefoneRepository.Delete));
+ List<AgendaTelefoneDb> agendaTelefoneDbs1 = ApplicationMapper.Mapper.Map<List<AgendaTelefone>, List<AgendaTelefoneDb>>(telefones);
+ agendaTelefoneDbs1.ForEach((AgendaTelefoneDb x) => {
+ if (x.Id != 0)
+ {
+ base.Merge(x);
+ return;
+ }
+ x.Agenda = ApplicationMapper.Mapper.Map<Agenda, AgendaDb>(agenda);
+ this.SaveOrUpdate(x);
+ });
+ return ApplicationMapper.Mapper.Map<List<AgendaTelefoneDb>, List<AgendaTelefone>>(agendaTelefoneDbs1);
+ }
+
+ public AgendaTelefone SaveOrUpdate(AgendaTelefone telefone)
+ {
+ AgendaTelefoneDb agendaTelefoneDb = ApplicationMapper.Mapper.Map<AgendaTelefone, AgendaTelefoneDb>(telefone);
+ this.SaveOrUpdate(agendaTelefoneDb);
+ return ApplicationMapper.Mapper.Map<AgendaTelefoneDb, AgendaTelefone>(agendaTelefoneDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs
new file mode 100644
index 0000000..d3261c6
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtividadeRepository.cs
@@ -0,0 +1,92 @@
+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<AtividadeDb>, IAtividadeRepository, IGenericRepository<AtividadeDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public AtividadeRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Atividade> Find(string filter)
+ {
+ AtividadeRepository.u003cu003ec__DisplayClass5_0 variable = null;
+ IQueryable<AtividadeDb> atividadeDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(AtividadeDb), "x");
+ IQueryable<AtividadeDb> atividadeDbs1 = atividadeDbs.Where<AtividadeDb>(Expression.Lambda<Func<AtividadeDb, bool>>(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<Expression>()), (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(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<Expression>()), (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(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<AtividadeDb, Atividade>(Expression.Lambda<Func<AtividadeDb, Atividade>>(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<Atividade>();
+ }
+
+ 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, AtividadeDb>(atividade);
+ base.Merge(atividadeDb);
+ return ApplicationMapper.Mapper.Map<AtividadeDb, Atividade>(atividadeDb);
+ }
+
+ public Atividade SaveOrUpdate(Atividade atividade)
+ {
+ AtividadeDb atividadeDb = ApplicationMapper.Mapper.Map<Atividade, AtividadeDb>(atividade);
+ this.SaveOrUpdate(atividadeDb);
+ return ApplicationMapper.Mapper.Map<AtividadeDb, Atividade>(atividadeDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs
new file mode 100644
index 0000000..d4702f8
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AtualizacaoRepository.cs
@@ -0,0 +1,44 @@
+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<AtualizacaoDb>, 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<AtualizacaoDb>();
+ 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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs
new file mode 100644
index 0000000..7cbb775
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/AutoRepository.cs
@@ -0,0 +1,607 @@
+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<AutoDb>, IAutoRepository, IGenericRepository<AutoDb>
+ {
+ 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<long> ids)
+ {
+ List<AutoDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Item.Id)
+ select x).ToList<AutoDb>();
+ base.DeleteRange(list);
+ }
+
+ public Auto Find(long id)
+ {
+ AutoDb autoDb = base.All().FirstOrDefault<AutoDb>((AutoDb x) => x.Item.Id == id) ?? new AutoDb();
+ return ApplicationMapper.Mapper.Map<AutoDb, Auto>(autoDb);
+ }
+
+ public List<PesquisaAvancada> FindAuto(string pesquisa, FiltroStatusDocumento status, List<VendedorUsuario> vendedorVinculado, TipoPesquisa tipo, bool tipobusca = false)
+ {
+ List<PesquisaAvancada> 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<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ }
+ };
+ switch (status)
+ {
+ case FiltroStatusDocumento.Vencidos:
+ {
+ condicaos.AddRange(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = new List<object>()
+ {
+ 3,
+ 7
+ },
+ Operador = Operador.Diferente
+ },
+ new Condicao()
+ {
+ Campo = "d.vigencia2",
+ Valores = date.AddDays(-5).CriarValor<DateTime>(),
+ Operador = Operador.Menor
+ }
+ });
+ goto case FiltroStatusDocumento.Todos;
+ }
+ case FiltroStatusDocumento.Cancelados:
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = 3.CriarValor<int>()
+ });
+ goto case FiltroStatusDocumento.Todos;
+ }
+ case FiltroStatusDocumento.Recusados:
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = 7.CriarValor<int>()
+ });
+ 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<Condicao> condicaos1 = new List<Condicao>();
+ if (tipo == TipoPesquisa.Chassi)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "a.chassi",
+ Valores = pesquisa.CriarValor<string>(),
+ Operador = (tipobusca ? Operador.Igual : Operador.Like)
+ });
+ }
+ else if (tipo == TipoPesquisa.Item)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "i.descricao",
+ Valores = pesquisa.CriarValor<string>(),
+ Operador = (tipobusca ? Operador.Igual : Operador.Like)
+ });
+ }
+ else if (tipo == TipoPesquisa.Placa)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "REPLACE(a.placa, '-','')",
+ Valores = pesquisa.Replace("-", "").Replace("?", "%").CriarValor<string>(),
+ 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<Condicao> condicaos2 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "iditem",
+ Valores = dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id")).ToList<long>().CriarValor<long>()
+ }
+ };
+ 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, long>((DataRow v) => v.Field<long>("id")).ToList<long>().CriarValor<long>()
+ });
+ 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<long> list = (
+ from x in dataTable2.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("idcontrole")).ToList<long>();
+ List<Condicao> condicaos3 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.idcontrole",
+ Valores = list.CriarValor<long>()
+ }
+ };
+ 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<PesquisaAvancada>();
+ }
+ }
+ else
+ {
+ pesquisaAvancadas = new List<PesquisaAvancada>();
+ }
+ }
+ }
+ return pesquisaAvancadas;
+ }
+ default:
+ {
+ condicaos.AddRange(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = new List<object>()
+ {
+ 1,
+ 2,
+ 4
+ }
+ },
+ new Condicao()
+ {
+ Campo = "d.vigencia2",
+ Valores = null,
+ Grupo = 2,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.vigencia2",
+ Valores = date.AddDays(-5).CriarValor<DateTime>(),
+ Grupo = 2,
+ Operacao = Operacao.Or,
+ Operador = Operador.Maior
+ }
+ });
+ goto case FiltroStatusDocumento.Todos;
+ }
+ }
+ Label1:
+ List<long> nums = null;
+ if (vendedorVinculado != null && vendedorVinculado.Count > 0)
+ {
+ nums = dataTable3.AsEnumerable().Where<DataRow>((DataRow x) => {
+ List<VendedorUsuario> vendedorUsuarios = vendedorVinculado;
+ Func<VendedorUsuario, long> 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<VendedorUsuario, long>(u003cu003e9_107).Contains<long>(x.Field<long>("idvendedor"));
+ }).Select<DataRow, long>((DataRow x) => x.Field<long>("idcontrole")).ToList<long>();
+ }
+ if (nums != null && nums.Count == 0)
+ {
+ return new List<PesquisaAvancada>();
+ }
+ return dataTable2.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if (nums == null)
+ {
+ return true;
+ }
+ return nums.Contains(x.Field<long>("idcontrole"));
+ }).Select<DataRow, PesquisaAvancada>((DataRow x) => new PesquisaAvancada()
+ {
+ IdCliente = x.Field<long>("idcliente"),
+ IdDocumento = x.Field<long>("iddocumento"),
+ IdItem = dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<long>("iditem"),
+ Nome = x.Field<string>("cliente"),
+ Pesquisa = (x.Field<int>("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>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), x.Field<string>("apolice"), x.Field<string>("proposta"), x.Field<DateTime>("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>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), x.Field<string>("apolice"), x.Field<string>("proposta"), x.Field<string>("endosso"), x.Field<DateTime>("vigencia1") }))
+ }).ToList<PesquisaAvancada>();
+ }
+
+ public Documento FindByChassi(string chassi, long id, DateTime vigencia1, DateTime? vigencia2, long idSeguradora)
+ {
+ DocumentoDb documento;
+ List<TipoSeguro> tipoSeguros = new List<TipoSeguro>()
+ {
+ 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<AutoDb>().AsEnumerable<AutoDb>().ToList<AutoDb>().Where<AutoDb>((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<AutoDb>().FirstOrDefault<AutoDb>((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<DocumentoDb, Documento>(documento);
+ }
+
+ public Auto FindById(long id)
+ {
+ AutoDb autoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<AutoDb, Auto>(autoDb);
+ }
+
+ public string FindChassi(long id)
+ {
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "iditem",
+ Valores = id.CriarValor<long>()
+ }
+ };
+ DataTable dataTable = this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT chassi FROM auto WHERE ", "");
+ if (dataTable == null)
+ {
+ return null;
+ }
+ DataRow dataRow = dataTable.AsEnumerable().FirstOrDefault<DataRow>();
+ if (dataRow == null)
+ {
+ return null;
+ }
+ return dataRow.Field<string>("chassi");
+ }
+
+ public List<PesquisaAvancada> FindPlaca(string placa, FiltroStatusDocumento status, List<VendedorUsuario> vendedorVinculado)
+ {
+ List<PesquisaAvancada> 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<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("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<long>(",", dataTable1.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
+ using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter())
+ {
+ sqlDataAdapter2.SelectCommand = sqlCommand;
+ sqlDataAdapter2.Fill(dataTable2);
+ }
+ string str3 = string.Concat(" AND d.idcontrole IN (", string.Join<long>(",", (
+ from x in dataTable2.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("idcontrole")).ToList<long>()), ")");
+ 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<PesquisaAvancada>();
+ }
+ }
+ }
+ return pesquisaAvancadas;
+ Label0:
+ List<long> list = null;
+ if (vendedorVinculado != null && vendedorVinculado.Count > 0)
+ {
+ list = dataTable3.AsEnumerable().Where<DataRow>((DataRow x) => {
+ List<VendedorUsuario> vendedorUsuarios = vendedorVinculado;
+ Func<VendedorUsuario, long> 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<VendedorUsuario, long>(u003cu003e9_915).Contains<long>(x.Field<long>("idvendedor"));
+ }).Select<DataRow, long>((DataRow x) => x.Field<long>("idcontrole")).ToList<long>();
+ }
+ if (list != null && list.Count == 0)
+ {
+ return new List<PesquisaAvancada>();
+ }
+ DateTime date = Funcoes.GetNetworkTime().Date;
+ switch (status)
+ {
+ case FiltroStatusDocumento.Vencidos:
+ {
+ return dataTable2.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if ((list == null || list.Contains(x.Field<long>("idcontrole"))) && (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString()) == TipoSeguro.Renovado)
+ {
+ return true;
+ }
+ return x.Field<DateTime>("vigencia2") < date.AddDays(-5);
+ }).Select<DataRow, PesquisaAvancada>((DataRow x) => new PesquisaAvancada()
+ {
+ IdCliente = x.Field<long>("idcliente"),
+ IdDocumento = x.Field<long>("iddocumento"),
+ IdItem = dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<long>("iditem"),
+ Nome = x.Field<string>("cliente"),
+ Pesquisa = (x.Field<int>("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), " - NÚMERO DA APÓLICE: ", x.Field<string>("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field<string>("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), " - NÚMERO DA APÓLICE: ", x.Field<string>("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field<string>("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field<string>("endosso") }))
+ }).ToList<PesquisaAvancada>();
+ }
+ case FiltroStatusDocumento.Cancelados:
+ {
+ return dataTable2.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if (list != null && !list.Contains(x.Field<long>("idcontrole")))
+ {
+ return false;
+ }
+ return (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString()) == TipoSeguro.Cancelado;
+ }).Select<DataRow, PesquisaAvancada>((DataRow x) => new PesquisaAvancada()
+ {
+ IdCliente = x.Field<long>("idcliente"),
+ IdDocumento = x.Field<long>("iddocumento"),
+ IdItem = dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<long>("iditem"),
+ Nome = x.Field<string>("cliente"),
+ Pesquisa = (x.Field<int>("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), " - NÚMERO DA APÓLICE: ", x.Field<string>("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field<string>("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), " - NÚMERO DA APÓLICE: ", x.Field<string>("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field<string>("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field<string>("endosso") }))
+ }).ToList<PesquisaAvancada>();
+ }
+ case FiltroStatusDocumento.Recusados:
+ {
+ return dataTable2.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if (list != null && !list.Contains(x.Field<long>("idcontrole")))
+ {
+ return false;
+ }
+ return (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString()) == TipoSeguro.Recusado;
+ }).Select<DataRow, PesquisaAvancada>((DataRow x) => new PesquisaAvancada()
+ {
+ IdCliente = x.Field<long>("idcliente"),
+ IdDocumento = x.Field<long>("iddocumento"),
+ IdItem = dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<long>("iditem"),
+ Nome = x.Field<string>("cliente"),
+ Pesquisa = (x.Field<int>("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), " - NÚMERO DA APÓLICE: ", x.Field<string>("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field<string>("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), " - NÚMERO DA APÓLICE: ", x.Field<string>("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field<string>("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field<string>("endosso") }))
+ }).ToList<PesquisaAvancada>();
+ }
+ case FiltroStatusDocumento.Todos:
+ {
+ return dataTable2.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if (list == null)
+ {
+ return true;
+ }
+ return list.Contains(x.Field<long>("idcontrole"));
+ }).Select<DataRow, PesquisaAvancada>((DataRow x) => new PesquisaAvancada()
+ {
+ IdCliente = x.Field<long>("idcliente"),
+ IdDocumento = x.Field<long>("iddocumento"),
+ IdItem = dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<long>("iditem"),
+ Nome = x.Field<string>("cliente"),
+ Pesquisa = (x.Field<int>("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), " - NÚMERO DA APÓLICE: ", x.Field<string>("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field<string>("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), " - NÚMERO DA APÓLICE: ", x.Field<string>("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field<string>("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field<string>("endosso") }))
+ }).ToList<PesquisaAvancada>();
+ }
+ default:
+ {
+ return dataTable2.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if (list != null && !list.Contains(x.Field<long>("idcontrole")) || (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString()) != TipoSeguro.Novo && (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString()) != TipoSeguro.Renovacao)
+ {
+ return false;
+ }
+ return x.Field<DateTime>("vigencia2") > date.AddDays(-5);
+ }).Select<DataRow, PesquisaAvancada>((DataRow x) => new PesquisaAvancada()
+ {
+ IdCliente = x.Field<long>("idcliente"),
+ IdDocumento = x.Field<long>("iddocumento"),
+ IdItem = dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<long>("iditem"),
+ Nome = x.Field<string>("cliente"),
+ Pesquisa = (x.Field<int>("tipo") == 0 ? string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), " - NÚMERO DA APÓLICE: ", x.Field<string>("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field<string>("proposta") }) : string.Concat(new string[] { "ITEM: ", dataTable1.AsEnumerable().First<DataRow>((DataRow i) => i.Field<long>("id") == x.Field<long>("iddocumento")).Field<string>("descricao"), " - NÚMERO DA APÓLICE: ", x.Field<string>("apolice"), " - NÚMERO DA PROPOSTA: ", x.Field<string>("proposta"), " - NÚMERO DO ENDOSSO: ", x.Field<string>("endosso") }))
+ }).ToList<PesquisaAvancada>();
+ }
+ }
+ }
+
+ public Auto Merge(Auto auto)
+ {
+ AutoDb autoDb = ApplicationMapper.Mapper.Map<Auto, AutoDb>(auto);
+ base.Merge(autoDb);
+ return ApplicationMapper.Mapper.Map<AutoDb, Auto>(autoDb);
+ }
+
+ public Auto SaveOrUpdate(Auto auto)
+ {
+ AutoDb autoDb = ApplicationMapper.Mapper.Map<Auto, AutoDb>(auto);
+ this.SaveOrUpdate(autoDb);
+ return ApplicationMapper.Mapper.Map<AutoDb, Auto>(autoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs
new file mode 100644
index 0000000..eaba0c1
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancoRepository.cs
@@ -0,0 +1,69 @@
+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<BancoDb>, IBancoRepository, IGenericRepository<BancoDb>
+ {
+ 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<Banco> Find(string filter)
+ {
+ BancoRepository.u003cu003ec__DisplayClass7_0 variable = null;
+ IQueryable<BancoDb> bancoDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(BancoDb), "x");
+ IQueryable<BancoDb> bancoDbs1 = bancoDbs.Where<BancoDb>(Expression.Lambda<Func<BancoDb, bool>>(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<Expression>()), (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(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<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(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<BancoDb, Banco>(Expression.Lambda<Func<BancoDb, Banco>>(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<Banco>();
+ }
+
+ public Banco FindById(long id)
+ {
+ BancoDb bancoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<BancoDb, Banco>(bancoDb);
+ }
+
+ public Banco Merge(Banco banco)
+ {
+ BancoDb bancoDb = ApplicationMapper.Mapper.Map<Banco, BancoDb>(banco);
+ base.Merge(bancoDb);
+ return ApplicationMapper.Mapper.Map<BancoDb, Banco>(bancoDb);
+ }
+
+ public Banco SaveOrUpdate(Banco banco)
+ {
+ BancoDb bancoDb = ApplicationMapper.Mapper.Map<Banco, BancoDb>(banco);
+ this.SaveOrUpdate(bancoDb);
+ return ApplicationMapper.Mapper.Map<BancoDb, Banco>(bancoDb);
+ }
+
+ public List<Banco> SelectDefault()
+ {
+ return ApplicationMapper.Mapper.Map<List<BancoDb>, List<Banco>>((
+ from x in base.All()
+ orderby x.Nome
+ select x).ToList<BancoDb>());
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs
new file mode 100644
index 0000000..53fa20c
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/BancosContasRepository.cs
@@ -0,0 +1,119 @@
+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<BancosContasDb>, IBancosContasRepository, IGenericRepository<BancosContasDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public BancosContasRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public void Delete(long id)
+ {
+ List<SaldoDb> list = (
+ from x in this._unitOfWork.Query<SaldoDb>()
+ where x.Conta.Id == id
+ select x).ToList<SaldoDb>();
+ if (list.Any<SaldoDb>())
+ {
+ this._unitOfWork.Repository<SaldoDb>().DeleteRange(list);
+ }
+ BancosContasDb bancosContasDb = base.FindEntityById(id);
+ if (bancosContasDb == null)
+ {
+ return;
+ }
+ base.Delete(bancosContasDb);
+ }
+
+ public List<BancosContas> Find(string filter)
+ {
+ return this.Select(" AND ISNULL(UPPER(descricao)) LIKE '%filter%'");
+ }
+
+ public List<BancosContas> Find()
+ {
+ return this.Select("");
+ }
+
+ public BancosContas FindById(long id)
+ {
+ BancosContasDb bancosContasDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<BancosContasDb, BancosContas>(bancosContasDb);
+ }
+
+ public BancosContas Merge(BancosContas bancosContas)
+ {
+ BancosContasDb bancosContasDb = ApplicationMapper.Mapper.Map<BancosContas, BancosContasDb>(bancosContas);
+ base.Merge(bancosContasDb);
+ return ApplicationMapper.Mapper.Map<BancosContasDb, BancosContas>(bancosContasDb);
+ }
+
+ public BancosContas SaveOrUpdate(BancosContas bancosContas)
+ {
+ BancosContasDb bancosContasDb = ApplicationMapper.Mapper.Map<BancosContas, BancosContasDb>(bancosContas);
+ this.SaveOrUpdate(bancosContasDb);
+ return ApplicationMapper.Mapper.Map<BancosContasDb, BancosContas>(bancosContasDb);
+ }
+
+ private List<BancosContas> Select(string condition)
+ {
+ List<BancosContas> 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<BancosContas>();
+ }
+ }
+ }
+ return bancosContas;
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs
new file mode 100644
index 0000000..e3cbdf9
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CategoriaTarefaRepository.cs
@@ -0,0 +1,46 @@
+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<CategoriaTarefaDb>, ICategoriaTarefaRepository, IGenericRepository<CategoriaTarefaDb>
+ {
+ 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, CategoriaTarefa>(categoriaTarefaDb);
+ }
+
+ public CategoriaTarefa Merge(CategoriaTarefa categoriaTarefa)
+ {
+ CategoriaTarefaDb categoriaTarefaDb = ApplicationMapper.Mapper.Map<CategoriaTarefa, CategoriaTarefaDb>(categoriaTarefa);
+ base.Merge(categoriaTarefaDb);
+ return ApplicationMapper.Mapper.Map<CategoriaTarefaDb, CategoriaTarefa>(categoriaTarefaDb);
+ }
+
+ public CategoriaTarefa SaveOrUpdate(CategoriaTarefa categoriaTarefa)
+ {
+ CategoriaTarefaDb categoriaTarefaDb = ApplicationMapper.Mapper.Map<CategoriaTarefa, CategoriaTarefaDb>(categoriaTarefa);
+ this.SaveOrUpdate(categoriaTarefaDb);
+ return ApplicationMapper.Mapper.Map<CategoriaTarefaDb, CategoriaTarefa>(categoriaTarefaDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs
new file mode 100644
index 0000000..c72986f
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CentroRepository.cs
@@ -0,0 +1,96 @@
+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<CentroDb>, ICentroRepository, IGenericRepository<CentroDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public CentroRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Centro> Find(string filter)
+ {
+ CentroRepository.u003cu003ec__DisplayClass2_0 variable = null;
+ IQueryable<CentroDb> centroDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(CentroDb), "x");
+ IQueryable<CentroDb> centroDbs1 = centroDbs.Where<CentroDb>(Expression.Lambda<Func<CentroDb, bool>>(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<Expression>()), (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<CentroDb, Centro>(Expression.Lambda<Func<CentroDb, Centro>>(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<Centro>();
+ }
+
+ public List<Centro> 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<DataRow>()
+ select new Centro()
+ {
+ Id = a.Field<long>("id"),
+ Descricao = a.Field<string>("nome"),
+ Ativo = (a.Field<object>("ativo") == null ? true : a.Field<object>("ativo").ToString() == "1")
+ }).ToList<Centro>();
+ }
+
+ public Centro Merge(Centro centro)
+ {
+ CentroDb centroDb = ApplicationMapper.Mapper.Map<Centro, CentroDb>(centro);
+ base.Merge(centroDb);
+ return ApplicationMapper.Mapper.Map<CentroDb, Centro>(centroDb);
+ }
+
+ public Centro SaveOrUpdate(Centro centro)
+ {
+ CentroDb centroDb = ApplicationMapper.Mapper.Map<Centro, CentroDb>(centro);
+ this.SaveOrUpdate(centroDb);
+ return ApplicationMapper.Mapper.Map<CentroDb, Centro>(centroDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs
new file mode 100644
index 0000000..6d40eff
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEmailRepository.cs
@@ -0,0 +1,248 @@
+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<ClienteEmailDb>, IClienteEmailRepository, IGenericRepository<ClienteEmailDb>
+ {
+ 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<ClienteEmail> DeleteMail(long clienteId, List<ClienteEmail> emails)
+ {
+ if (emails == null)
+ {
+ return null;
+ }
+ List<ClienteEmailDb> list = (
+ from x in base.All()
+ where x.Cliente.Id == clienteId
+ select x).ToList<ClienteEmailDb>().Where<ClienteEmailDb>((ClienteEmailDb email) => {
+ List<ClienteEmail> clienteEmails = emails;
+ Func<ClienteEmail, long> 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<ClienteEmail, long>(u003cu003e9_112).Contains<long>(email.Id);
+ }).ToList<ClienteEmailDb>();
+ if (emails.Count == 0 && (list == null || list.Count == 0))
+ {
+ return null;
+ }
+ ClienteEmailRepository clienteEmailRepository = this;
+ list.ForEach(new Action<ClienteEmailDb>(clienteEmailRepository.Delete));
+ return ApplicationMapper.Mapper.Map<List<ClienteEmailDb>, List<ClienteEmail>>(list);
+ }
+
+ private List<ClienteEmail> FindByCliente(long id)
+ {
+ return this.Select(string.Format(" AND cm.idcliente = {0}", id));
+ }
+
+ public List<ClienteEmail> FindByCliente(List<long> ids)
+ {
+ if (ids.Count == 0)
+ {
+ return new List<ClienteEmail>();
+ }
+ string str = string.Concat(" AND cm.idcliente IN (", string.Join<long>(",", ids), ")");
+ return this.Select(str);
+ }
+
+ public List<ClienteEmail> FindByClienteId(long id)
+ {
+ return this.FindByCliente(id);
+ }
+
+ public ClienteEmail FindById(long id)
+ {
+ ClienteEmailDb clienteEmailDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ClienteEmailDb, ClienteEmail>(clienteEmailDb);
+ }
+
+ public List<ClienteEmail> 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<ClienteEmail> Inserir(List<ClienteEmail> 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<ClienteEmailDb> clienteEmailDbs = ApplicationMapper.Mapper.Map<List<ClienteEmail>, List<ClienteEmailDb>>(emails);
+ base.AddRange(clienteEmailDbs);
+ return ApplicationMapper.Mapper.Map<List<ClienteEmailDb>, List<ClienteEmail>>(clienteEmailDbs);
+ }
+
+ public List<ClienteEmail> Inserir(List<ClienteEmail> emails)
+ {
+ List<ClienteEmailDb> clienteEmailDbs = ApplicationMapper.Mapper.Map<List<ClienteEmail>, List<ClienteEmailDb>>(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<ClienteEmailDb>, List<ClienteEmail>>(clienteEmailDbs);
+ }
+
+ public ClienteEmail Merge(ClienteEmail clienteEmail)
+ {
+ string str;
+ ClienteEmailDb clienteEmailDb = ApplicationMapper.Mapper.Map<ClienteEmail, ClienteEmailDb>(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, ClienteEmail>(clienteEmailDb);
+ }
+
+ public List<ClienteEmail> Merge(List<ClienteEmail> emails, Cliente cliente)
+ {
+ List<ClienteEmailDb> clienteEmailDbs = ApplicationMapper.Mapper.Map<List<ClienteEmail>, List<ClienteEmailDb>>(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, ClienteDb>(cliente);
+ this.SaveOrUpdate(x);
+ });
+ return ApplicationMapper.Mapper.Map<List<ClienteEmailDb>, List<ClienteEmail>>(clienteEmailDbs);
+ }
+
+ public ClienteEmail SaveOrUpdate(ClienteEmail clienteEmail)
+ {
+ string str;
+ ClienteEmailDb clienteEmailDb = ApplicationMapper.Mapper.Map<ClienteEmail, ClienteEmailDb>(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, ClienteEmail>(clienteEmailDb);
+ }
+
+ private List<ClienteEmail> 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<ClienteEmail> 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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs
new file mode 100644
index 0000000..9a2ac8e
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteEnderecoRepository.cs
@@ -0,0 +1,223 @@
+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<ClienteEnderecoDb>, IClienteEnderecoRepository, IGenericRepository<ClienteEnderecoDb>
+ {
+ 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<ClienteEndereco> DeleteEndereco(long clienteId, List<ClienteEndereco> enderecos)
+ {
+ if (enderecos == null || enderecos.Count == 0)
+ {
+ return null;
+ }
+ List<ClienteEnderecoDb> list = (
+ from cliente in base.All()
+ where cliente.Cliente.Id == clienteId
+ select cliente).ToList<ClienteEnderecoDb>().Where<ClienteEnderecoDb>((ClienteEnderecoDb endereco) => {
+ List<ClienteEndereco> clienteEnderecos = enderecos;
+ Func<ClienteEndereco, long> 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<ClienteEndereco, long>(u003cu003e9_102).Contains<long>(endereco.Id);
+ }).ToList<ClienteEnderecoDb>();
+ ClienteEnderecoRepository clienteEnderecoRepository = this;
+ list.ForEach(new Action<ClienteEnderecoDb>(clienteEnderecoRepository.Delete));
+ return ApplicationMapper.Mapper.Map<List<ClienteEnderecoDb>, List<ClienteEndereco>>(list);
+ }
+
+ public List<ClienteEndereco> FindByCliente(List<Cliente> clientes)
+ {
+ string str = string.Concat(" AND ce.idcliente in (", string.Join<long>(",", (
+ from x in clientes
+ select x.Id).Distinct<long>()), ")");
+ List<ClienteEndereco> clienteEnderecos = this.Select(str);
+ (
+ from x in clienteEnderecos
+ orderby x.Ordem
+ select x).ToList<ClienteEndereco>().ForEach((ClienteEndereco x) => x.Selecionado = x.Id == clienteEnderecos.First<ClienteEndereco>((ClienteEndereco c) => c.Cliente.Id == x.Cliente.Id).Id);
+ return clienteEnderecos;
+ }
+
+ public List<ClienteEndereco> 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, ClienteEndereco>(clienteEnderecoDb);
+ }
+
+ public List<ClienteEndereco> Inserir(List<ClienteEndereco> endereco, Cliente cliente)
+ {
+ endereco.ForEach((ClienteEndereco x) => x.Cliente = cliente);
+ List<ClienteEnderecoDb> clienteEnderecoDbs = ApplicationMapper.Mapper.Map<List<ClienteEndereco>, List<ClienteEnderecoDb>>(endereco);
+ base.AddRange(clienteEnderecoDbs);
+ return ApplicationMapper.Mapper.Map<List<ClienteEnderecoDb>, List<ClienteEndereco>>(clienteEnderecoDbs);
+ }
+
+ public List<ClienteEndereco> Inserir(List<ClienteEndereco> endereco)
+ {
+ List<ClienteEnderecoDb> clienteEnderecoDbs = ApplicationMapper.Mapper.Map<List<ClienteEndereco>, List<ClienteEnderecoDb>>(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<ClienteEnderecoDb>, List<ClienteEndereco>>(clienteEnderecoDbs);
+ }
+
+ public ClienteEndereco Merge(ClienteEndereco clienteEndereco)
+ {
+ string str;
+ ClienteEnderecoDb clienteEnderecoDb = ApplicationMapper.Mapper.Map<ClienteEndereco, ClienteEnderecoDb>(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, ClienteEndereco>(clienteEnderecoDb);
+ }
+
+ public List<ClienteEndereco> Merge(List<ClienteEndereco> enderecos, Cliente cliente)
+ {
+ List<ClienteEnderecoDb> clienteEnderecoDbs = ApplicationMapper.Mapper.Map<List<ClienteEndereco>, List<ClienteEnderecoDb>>(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, ClienteDb>(cliente);
+ this.SaveOrUpdate(x);
+ });
+ return ApplicationMapper.Mapper.Map<List<ClienteEnderecoDb>, List<ClienteEndereco>>(clienteEnderecoDbs);
+ }
+
+ public ClienteEndereco SaveOrUpdate(ClienteEndereco clienteEndereco)
+ {
+ string str;
+ ClienteEnderecoDb clienteEnderecoDb = ApplicationMapper.Mapper.Map<ClienteEndereco, ClienteEnderecoDb>(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, ClienteEndereco>(clienteEnderecoDb);
+ }
+
+ private List<ClienteEndereco> 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<ClienteEndereco> 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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs
new file mode 100644
index 0000000..f07399f
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteRepository.cs
@@ -0,0 +1,3102 @@
+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<ClienteDb>, IClienteRepository, IGenericRepository<ClienteDb>
+ {
+ 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<long>("updatedid", id).SetParameter<bool>("update", update).ExecuteUpdate();
+ this._unitOfWork.Commit();
+ }
+ catch
+ {
+ }
+ }
+
+ public async Task<IEnumerable<ClientesAtivosInativos>> BuscaClientes(bool completo, long idempresa = 0L)
+ {
+ IEnumerable<ClientesAtivosInativos> 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<Profissao, bool> func = null;
+ Action<Gestor.Model.Relatorios.Vendedor> action2 = null;
+ List<ClientesAtivosInativos> clientesAtivosInativos1 = new List<ClientesAtivosInativos>();
+ IEnumerable<Gestor.Model.Relatorios.Documento> documentos = await this.DocumentosPeriodo(completo);
+ IEnumerable<Gestor.Model.Relatorios.ClienteEndereco> clienteEnderecos = await this.EnderecoClientes();
+ IEnumerable<Gestor.Model.Relatorios.ClienteTelefone> clienteTelefones = await this.TelefonesClientes();
+ IEnumerable<Gestor.Model.Relatorios.ClienteEmail> clienteEmails = await this.EmailsClientes();
+ Array values = Enum.GetValues(typeof(EstadoCivil));
+ Regex regex = new Regex("[^\\d]");
+ IEnumerable<EstipulanteCliente> 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<Sexo>(str6, out sexo))
+ {
+ str6 = "";
+ }
+ IEnumerable<Gestor.Model.Relatorios.Documento> id =
+ from d in documentos
+ where d.Controle.Cliente.Id == item
+ select d;
+ Gestor.Model.Relatorios.ClienteEndereco clienteEndereco = clienteEnderecos.FirstOrDefault<Gestor.Model.Relatorios.ClienteEndereco>((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<Gestor.Model.Relatorios.ClienteTelefone> id1 =
+ from f in clienteTelefones
+ where f.Cliente.Id == item
+ select f;
+ IEnumerable<Gestor.Model.Relatorios.ClienteEmail> 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<string> strs = new List<string>();
+ id.ForEach<Gestor.Model.Relatorios.Documento>((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<Gestor.Model.Relatorios.Vendedor> vendedores = d.Vendedores;
+ if (vendedores == null)
+ {
+ return;
+ }
+ Action<Gestor.Model.Relatorios.Vendedor> u003cu003e9_10 = action2;
+ if (u003cu003e9_10 == null)
+ {
+ Action<Gestor.Model.Relatorios.Vendedor> 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<Gestor.Model.Relatorios.Vendedor> action1 = action;
+ action2 = action;
+ u003cu003e9_10 = action1;
+ }
+ vendedores.ForEach<Gestor.Model.Relatorios.Vendedor>(u003cu003e9_10);
+ }
+ });
+ List<Gestor.Model.Domain.Seguros.ClienteTelefone> clienteTelefones1 = new List<Gestor.Model.Domain.Seguros.ClienteTelefone>();
+ id1.ForEach<Gestor.Model.Relatorios.ClienteTelefone>((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<object>() != sqlDataReader["estadocivi"].ToString())
+ {
+ continue;
+ }
+ description = ((EstadoCivil)value).GetDescription<EstadoCivil>();
+ break;
+ }
+ }
+ if (completo && strs.Count > 0)
+ {
+ List<string> strs1 = strs;
+ IEnumerable<IGrouping<string, string>> 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<string>()));
+ }
+ IEnumerable<EstipulanteCliente> 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<Gestor.Model.Domain.Seguros.ClienteTelefone>(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<Gestor.Model.Domain.Seguros.ClienteTelefone> clienteTelefones2 = clienteTelefones1;
+ clientesAtivosInativo.Telefone = string.Join(" | ",
+ from f in clienteTelefones2
+ select string.Concat(f.Prefixo, " ", f.Numero));
+ IEnumerable<Gestor.Model.Relatorios.ClienteEmail> 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<Profissao> profissoes = Auxiliar.Profissoes;
+ Func<Profissao, bool> func1 = func;
+ if (func1 == null)
+ {
+ Func<Profissao, bool> id2 = (Profissao p) => p.Id == (long)this.rd["idprofissao"];
+ Func<Profissao, bool> func2 = id2;
+ func = id2;
+ func1 = func2;
+ }
+ Profissao profissao = profissoes.FirstOrDefault<Profissao>(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<Sexo>());
+ 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<IEnumerable<ClientesAtivosInativos>> BuscaClientesVinculo(bool completo, List<VendedorUsuario> vinculo, long idempresa = 0L)
+ {
+ IEnumerable<ClientesAtivosInativos> 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<Profissao, bool> func = null;
+ Action<Gestor.Model.Relatorios.Vendedor> action2 = null;
+ List<ClientesAtivosInativos> clientesAtivosInativos1 = new List<ClientesAtivosInativos>();
+ IEnumerable<Gestor.Model.Relatorios.Documento> documentos = await this.DocumentosPeriodo(completo);
+ IEnumerable<Gestor.Model.Relatorios.ClienteEndereco> clienteEnderecos = await this.EnderecoClientes();
+ IEnumerable<Gestor.Model.Relatorios.ClienteTelefone> clienteTelefones = await this.TelefonesClientes();
+ IEnumerable<Gestor.Model.Relatorios.ClienteEmail> clienteEmails = await this.EmailsClientes();
+ Array values = Enum.GetValues(typeof(EstadoCivil));
+ Regex regex = new Regex("[^\\d]");
+ IEnumerable<EstipulanteCliente> estipulanteClientes = await this.EstipulanteCliente();
+ List<VendedorUsuario> vendedorUsuarios = vinculo;
+ List<long> list = (
+ from v in vendedorUsuarios
+ select v.Id).ToList<long>();
+ string[] array = (
+ from id in list
+ select id.ToString()).ToArray<string>();
+ 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<Sexo>(str7, out sexo))
+ {
+ str7 = "";
+ }
+ IEnumerable<Gestor.Model.Relatorios.Documento> documentos1 =
+ from d in documentos
+ where d.Controle.Cliente.Id == item
+ select d;
+ Gestor.Model.Relatorios.ClienteEndereco clienteEndereco = clienteEnderecos.FirstOrDefault<Gestor.Model.Relatorios.ClienteEndereco>((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<Gestor.Model.Relatorios.ClienteTelefone> clienteTelefones1 =
+ from f in clienteTelefones
+ where f.Cliente.Id == item
+ select f;
+ IEnumerable<Gestor.Model.Relatorios.ClienteEmail> 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<string> strs = new List<string>();
+ documentos1.ForEach<Gestor.Model.Relatorios.Documento>((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<Gestor.Model.Relatorios.Vendedor> vendedores = d.Vendedores;
+ if (vendedores == null)
+ {
+ return;
+ }
+ Action<Gestor.Model.Relatorios.Vendedor> u003cu003e9_12 = action2;
+ if (u003cu003e9_12 == null)
+ {
+ Action<Gestor.Model.Relatorios.Vendedor> 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<Gestor.Model.Relatorios.Vendedor> action1 = action;
+ action2 = action;
+ u003cu003e9_12 = action1;
+ }
+ vendedores.ForEach<Gestor.Model.Relatorios.Vendedor>(u003cu003e9_12);
+ }
+ });
+ List<Gestor.Model.Domain.Seguros.ClienteTelefone> clienteTelefones2 = new List<Gestor.Model.Domain.Seguros.ClienteTelefone>();
+ clienteTelefones1.ForEach<Gestor.Model.Relatorios.ClienteTelefone>((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<object>() != sqlDataReader["estadocivi"].ToString())
+ {
+ continue;
+ }
+ description = ((EstadoCivil)value).GetDescription<EstadoCivil>();
+ break;
+ }
+ }
+ if (completo && strs.Count > 0)
+ {
+ List<string> strs1 = strs;
+ IEnumerable<IGrouping<string, string>> 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<string>()));
+ }
+ IEnumerable<EstipulanteCliente> 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<Gestor.Model.Domain.Seguros.ClienteTelefone>(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<Gestor.Model.Domain.Seguros.ClienteTelefone> clienteTelefones3 = clienteTelefones2;
+ clientesAtivosInativo.Telefone = string.Join(" | ",
+ from f in clienteTelefones3
+ select string.Concat(f.Prefixo, " ", f.Numero));
+ IEnumerable<Gestor.Model.Relatorios.ClienteEmail> 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<Profissao> profissoes = Auxiliar.Profissoes;
+ Func<Profissao, bool> func1 = func;
+ if (func1 == null)
+ {
+ Func<Profissao, bool> func2 = (Profissao p) => p.Id == (long)this.rd["idprofissao"];
+ Func<Profissao, bool> func3 = func2;
+ func = func2;
+ func1 = func3;
+ }
+ Profissao profissao = profissoes.FirstOrDefault<Profissao>(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<Sexo>());
+ 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<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idcliente",
+ Valores = id.CriarValor<long>()
+ }
+ };
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 15000;
+ object obj = sqlCommand.Select(condicaos.CreateParameters(0), "SELECT c.dtnasc FROM cliente c WHERE", "").AsEnumerable().ToList<DataRow>().FirstOrDefault<DataRow>().Field<object>("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<List<Prospectar>> BuscaProspeccoes(Filtros filtro, long idEmpresa)
+ {
+ int? nullable;
+ int num;
+ object connection;
+ int? nullable1;
+ List<Prospectar> prospectars = new List<Prospectar>();
+ filtro.IdEmpresa = idEmpresa;
+ num = (filtro.FiltrarDocumento == "AMBOS" ? -1 : (int)(!(filtro.FiltrarDocumento == "CNPJ")));
+ int num1 = num;
+ List<Condicao> condicaos = new List<Condicao>();
+ 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<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ };
+ condicaos.Add(condicao1);
+ Condicao condicao2 = new Condicao()
+ {
+ Campo = "d.situacao"
+ };
+ List<object> objs = new List<object>()
+ {
+ 1,
+ 2,
+ 4
+ };
+ condicao2.Valores = objs;
+ condicaos.Add(condicao2);
+ List<Condicao> condicaos1 = condicaos;
+ if (filtro.IdEmpresa > (long)0)
+ {
+ Condicao condicao3 = new Condicao()
+ {
+ Campo = "cl.idempresa",
+ Valores = filtro.IdEmpresa.CriarValor<long>()
+ };
+ 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<long>()
+ };
+ 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<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ };
+ condicaos1.Add(condicao5);
+ Condicao condicao6 = new Condicao()
+ {
+ Campo = "CAST(d.vigencia1 AS DATE)",
+ Valores = filtro.Fim.CriarValor<DateTime>(),
+ 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<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ };
+ condicaos1.Add(condicao8);
+ Condicao condicao9 = new Condicao()
+ {
+ Campo = "CAST(d.vigencia2 AS DATE)",
+ Valores = filtro.Fim.CriarValor<DateTime>(),
+ Operador = Operador.MenorEIgual
+ };
+ condicaos1.Add(condicao9);
+ }
+ else
+ {
+ Condicao condicao10 = new Condicao()
+ {
+ Campo = "CAST(p.vencto AS DATE)",
+ Valores = filtro.Inicio.CriarValor<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ };
+ condicaos1.Add(condicao10);
+ Condicao condicao11 = new Condicao()
+ {
+ Campo = "CAST(p.vencto AS DATE)",
+ Valores = filtro.Fim.CriarValor<DateTime>(),
+ 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<long> nums = new List<long>();
+ 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>((long r) => r == item1))
+ {
+ nums.Add(item);
+ Prospectar prospectar = prospectars.FirstOrDefault<Prospectar>((Prospectar p) => p.Id == item);
+ if (prospectar != null)
+ {
+ prospectars.Remove(prospectar);
+ }
+ }
+ else if (!nums.Any<long>((long i) => i == item) && !prospectars.Any<Prospectar>((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<long>()))
+ {
+ string str5 = sqlDataReader["nome"].ToString();
+ List<Gestor.Model.Domain.Seguros.ClienteTelefone> clienteTelefones = await this.BuscaTelefonesCliente(item);
+ List<Prospectar> 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<Gestor.Model.Domain.Seguros.ClienteTelefone>(clienteTelefones)
+ };
+ prospectar1.EntidadeCliente = cliente;
+ prospectar1.Id = item;
+ prospectar1.Nome = str5;
+ prospectar1.Documento = str2;
+ List<Gestor.Model.Domain.Seguros.ClienteTelefone> 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<Prospectar> prospectars2 = prospectars;
+ List<Prospectar> list = (
+ from p in prospectars2
+ orderby p.Nome
+ select p).ToList<Prospectar>();
+ prospectars = null;
+ return list;
+ }
+
+ public List<ClientesAtivosInativos> BuscarAniversariantes(Filtros filtro, 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 = "dtnasc",
+ Valores = null,
+ Operador = Operador.Diferente
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "falecido",
+ Valores = null,
+ Grupo = 2,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "falecido",
+ Valores = "1".CriarValor<string>(),
+ 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<ClientesAtivosInativos> BuscarAniversariantesVinculo(Filtros filtro, List<VendedorUsuario> vinculo, long idempresa = 0L)
+ {
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "cl.idempresa",
+ Valores = idempresa.CriarValor<long>()
+ }
+ };
+ List<Condicao> condicaos1 = new List<Condicao>()
+ {
+ 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<string>(),
+ 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<string>(),
+ 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<long>()
+ select id.ToString()).ToArray<string>();
+ 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<List<Classificacao>> BuscarClassificacoes(long idEmpresa)
+ {
+ List<Classificacao> classificacaos;
+ Func<Tuple<string, string>, bool> func;
+ object connection;
+ string str;
+ Func<Tuple<string, string>, bool> func1 = null;
+ Func<Tuple<string, string>, bool> func2 = null;
+ Func<Tuple<string, string>, bool> func3 = null;
+ List<Classificacao> classificacaos1 = new List<Classificacao>();
+ 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<Tuple<string, string>> tuples = new List<Tuple<string, string>>()
+ {
+ new Tuple<string, string>("0", "SEM CLASSIFICAÇÃO"),
+ new Tuple<string, string>("1", "BRONZE"),
+ new Tuple<string, string>("2", "PRATA"),
+ new Tuple<string, string>("3", "OURO")
+ };
+ List<Tuple<string, string>> tuples1 = tuples;
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ List<Tuple<string, string>> tuples2 = tuples1;
+ Func<Tuple<string, string>, bool> func4 = func1;
+ if (func4 == null)
+ {
+ Func<Tuple<string, string>, bool> func5 = (Tuple<string, string> x) => x.Item1.Equals(sqlDataReader["QualiPremioLiquido"].ToString() ?? "0");
+ func = func5;
+ func1 = func5;
+ func4 = func;
+ }
+ Tuple<string, string> tuple = tuples2.FirstOrDefault<Tuple<string, string>>(func4);
+ List<Tuple<string, string>> tuples3 = tuples1;
+ Func<Tuple<string, string>, bool> func6 = func2;
+ if (func6 == null)
+ {
+ Func<Tuple<string, string>, bool> func7 = (Tuple<string, string> x) => x.Item1.Equals(sqlDataReader["QualiResultado"].ToString() ?? "0");
+ func = func7;
+ func2 = func7;
+ func6 = func;
+ }
+ Tuple<string, string> tuple1 = tuples3.FirstOrDefault<Tuple<string, string>>(func6);
+ List<Tuple<string, string>> tuples4 = tuples1;
+ Func<Tuple<string, string>, bool> func8 = func3;
+ if (func8 == null)
+ {
+ Func<Tuple<string, string>, bool> func9 = (Tuple<string, string> x) => x.Item1.Equals(sqlDataReader["QualiComissao"].ToString() ?? "0");
+ func = func9;
+ func3 = func9;
+ func8 = func;
+ }
+ Tuple<string, string> tuple2 = tuples4.FirstOrDefault<Tuple<string, string>>(func8);
+ string item2 = tuples1.FirstOrDefault<Tuple<string, string>>((Tuple<string, string> 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<Classificacao> 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<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "id",
+ Valores = id.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "idname",
+ Valores = "idcliente".CriarValor<string>()
+ }
+ };
+ this._unitOfWork.CriarAuxiliar();
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ string str1 = "oldbacklog";
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog";
+ SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
+ sqlDataReader.Read();
+ string str2 = sqlDataReader["bdname"].ToString();
+ str1 = sqlDataReader["tabela"].ToString();
+ sqlDataReader.Close();
+ if (sqlConnection.Database != str2)
+ {
+ conn = conn.Replace(sqlConnection.Database, str2);
+ }
+ }
+ }
+ DataTable dataTable = new DataTable();
+ using (SqlConnection sqlConnection1 = new SqlConnection(conn))
+ {
+ sqlConnection1.Open();
+ using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand())
+ {
+ sqlCommand1.CommandTimeout = 15000;
+ dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), "");
+ }
+ }
+ if (dataTable == null || dataTable.Rows.Count == 0)
+ {
+ return "";
+ }
+ if (dataTable != null)
+ {
+ dataTable.AsEnumerable().OrderBy<DataRow, long>((DataRow x) => x.Field<long>("idbacklog")).ToList<DataRow>().ForEach((DataRow x) => {
+ str = string.Concat(new string[] { str, "<br><FONT face=verdana color=#FF0000 size=2><strong>(", x.Field<object>("data").ToString(), ")</font><FONT face=verdana size=2 color=#000000> ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field<long>("idusuario")).Nome, "</strong></font><br>" });
+ str = string.Concat(str, "<FONT face=verdana color=#000000 size=1>", x.Field<object>("historico").ToString().Replace(Environment.NewLine, "<br>"), "</font>");
+ });
+ }
+ return str;
+ }
+
+ public List<OrigemCliente> BuscarOrigem(long id)
+ {
+ List<OrigemClienteDb> list = (
+ from x in this._unitOfWork.Query<OrigemClienteDb>()
+ where x.Cliente.Id == id
+ select x).ToList<OrigemClienteDb>();
+ return ApplicationMapper.Mapper.Map<List<OrigemClienteDb>, List<OrigemCliente>>(list);
+ }
+
+ public List<ClientesAtivosInativos> BuscarVencimentoCnh(Filtros filtro, 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 = "venchabili",
+ Valores = null,
+ Operador = Operador.Diferente
+ },
+ new Condicao()
+ {
+ Campo = "venchabili",
+ Valores = filtro.Inicio.CriarValor<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ },
+ new Condicao()
+ {
+ Campo = "venchabili",
+ Valores = filtro.Fim.CriarValor<DateTime>(),
+ Operador = Operador.MenorEIgual
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = "0".CriarValor<string>(),
+ 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<List<Gestor.Model.Domain.Seguros.ClienteTelefone>> BuscaTelefonesCliente(long idCliente)
+ {
+ object connection;
+ List<Gestor.Model.Domain.Seguros.ClienteTelefone> clienteTelefones = new List<Gestor.Model.Domain.Seguros.ClienteTelefone>();
+ 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<Gestor.Model.Domain.Seguros.ClienteTelefone> 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<Gestor.Model.Domain.Seguros.ClienteTelefone> 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<Condicao> CriarFiltro(string filter)
+ {
+ return new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "UPPER(NOME) COLLATE Latin1_General_CI_AI",
+ Valores = filter.CriarValor<string>(),
+ Operacao = Operacao.Or,
+ Operador = Operador.Like,
+ Grupo = 2
+ },
+ new Condicao()
+ {
+ Campo = "UPPER(CGCCPF)",
+ Valores = filter.CriarValor<string>(),
+ Operacao = Operacao.Or,
+ Operador = Operador.Like,
+ Grupo = 2
+ },
+ new Condicao()
+ {
+ Campo = "UPPER(CEI)",
+ Valores = filter.CriarValor<string>(),
+ Operacao = Operacao.Or,
+ Operador = Operador.Like,
+ Grupo = 2
+ },
+ new Condicao()
+ {
+ Campo = "UPPER(RNE)",
+ Valores = filter.CriarValor<string>(),
+ Operacao = Operacao.Or,
+ Operador = Operador.Like,
+ Grupo = 2
+ },
+ new Condicao()
+ {
+ Campo = "UPPER(CAEPF)",
+ Valores = filter.CriarValor<string>(),
+ Operacao = Operacao.Or,
+ Operador = Operador.Like,
+ Grupo = 2
+ },
+ new Condicao()
+ {
+ Campo = "UPPER(nomesocialRg) COLLATE Latin1_General_CI_AI",
+ Valores = filter.CriarValor<string>(),
+ 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<OrigemClienteDb>().FindEntityById(id);
+ if (origemClienteDb == null)
+ {
+ return;
+ }
+ this._unitOfWork.Repository<OrigemClienteDb>().Delete(origemClienteDb);
+ }
+
+ private async Task<IEnumerable<Gestor.Model.Relatorios.Documento>> DocumentosPeriodo(bool completo)
+ {
+ IEnumerable<Gestor.Model.Relatorios.Documento> documentos;
+ object connection;
+ Func<Gestor.Model.Relatorios.Vendedor, bool> func = null;
+ List<Gestor.Model.Relatorios.Documento> documentos1 = new List<Gestor.Model.Relatorios.Documento>();
+ 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<Gestor.Model.Relatorios.Documento>();
+ flag = false;
+ }
+ if (!flag)
+ {
+ bool flag1 = completo;
+ if (flag1)
+ {
+ flag1 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idvendedor"));
+ }
+ if (flag1)
+ {
+ IList<Gestor.Model.Relatorios.Vendedor> vendedores = documento.Vendedores;
+ Func<Gestor.Model.Relatorios.Vendedor, bool> func1 = func;
+ if (func1 == null)
+ {
+ Func<Gestor.Model.Relatorios.Vendedor, bool> id1 = (Gestor.Model.Relatorios.Vendedor v) => v.Id == (long)sqlDataReader["idvendedor"];
+ Func<Gestor.Model.Relatorios.Vendedor, bool> func2 = id1;
+ func = id1;
+ func1 = func2;
+ }
+ if (vendedores.Where<Gestor.Model.Relatorios.Vendedor>(func1).Count<Gestor.Model.Relatorios.Vendedor>() == 0)
+ {
+ IList<Gestor.Model.Relatorios.Vendedor> 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<Gestor.Model.Relatorios.Vendedor> vendedors1 = new List<Gestor.Model.Relatorios.Vendedor>();
+ 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<IEnumerable<Gestor.Model.Relatorios.ClienteEmail>> EmailsClientes()
+ {
+ IEnumerable<Gestor.Model.Relatorios.ClienteEmail> clienteEmails;
+ object connection;
+ List<Gestor.Model.Relatorios.ClienteEmail> clienteEmails1 = new List<Gestor.Model.Relatorios.ClienteEmail>();
+ 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<Gestor.Model.Relatorios.ClienteEmail> 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<IEnumerable<Gestor.Model.Relatorios.ClienteEndereco>> EnderecoClientes()
+ {
+ IEnumerable<Gestor.Model.Relatorios.ClienteEndereco> clienteEnderecos;
+ object connection;
+ int num;
+ List<Gestor.Model.Relatorios.ClienteEndereco> clienteEnderecos1 = new List<Gestor.Model.Relatorios.ClienteEndereco>();
+ 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<Gestor.Model.Relatorios.ClienteEndereco> 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<IEnumerable<EstipulanteCliente>> EstipulanteCliente()
+ {
+ IEnumerable<EstipulanteCliente> estipulanteClientes;
+ object connection;
+ List<EstipulanteCliente> estipulanteClientes1 = new List<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())
+ {
+ 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<EstipulanteCliente> 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<bool> 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<Gestor.Model.Domain.Seguros.Cliente> Find(string filter, long idempresa = 0L, bool acessoAgger = false, bool assintatura = false)
+ {
+ List<Gestor.Model.Domain.Seguros.Cliente> clientes;
+ object connection;
+ DataTable dataTable = new DataTable();
+ List<long> nums = new List<long>();
+ 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<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ }
+ };
+ List<Condicao> condicaos1 = this.CriarFiltro(filter);
+ List<Condicao> condicaos2 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idempresa",
+ Valores = idempresa.CriarValor<long>()
+ }
+ };
+ 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<Condicao> condicaos3 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "c.idcliente",
+ Valores = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("IDCLIENTE")).ToList<long>().CriarValor<long>()
+ }
+ };
+ List<Condicao> condicaos4 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.tipo",
+ Valores = 0.CriarValor<int>()
+ },
+ 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<DateTime>();
+ condicao.Grupo = 2;
+ condicao.Operacao = Operacao.Or;
+ condicao.Operador = Operador.Maior;
+ condicaos4.Add(condicao);
+ condicaos4.Add(new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = new List<object>()
+ {
+ 1,
+ 2,
+ 4
+ }
+ });
+ List<Condicao> 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, long>((DataRow x) => x.Field<long>("idcliente")).ToList<long>();
+ if (assintatura)
+ {
+ dataTable1 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT * FROM ResponsavelAssinatura c WHERE ", "");
+ }
+ }
+ goto Label0;
+ }
+ }
+ else
+ {
+ clientes = new List<Gestor.Model.Domain.Seguros.Cliente>();
+ }
+ }
+ return clientes;
+ List<ResponsavelAssinatura> list = dataTable1.AsEnumerable().Select<DataRow, ResponsavelAssinatura>((DataRow x) => new ResponsavelAssinatura()
+ {
+ Id = x.Field<long>("Id"),
+ IdCliente = x.Field<long>("IdCliente"),
+ NomeResponsavel = x.Field<string>("NomeResponsavel").RemoverAcentos(),
+ DocumentoResponsavel = x.Field<string>("DocumentoResponsavel"),
+ EmailResponsavel = x.Field<string>("EmailResponsavel")
+ }).ToList<ResponsavelAssinatura>();
+ return (
+ from x in dataTable.AsEnumerable().ToList<DataRow>()
+ select new Gestor.Model.Domain.Seguros.Cliente()
+ {
+ Id = x.Field<long>("IDCLIENTE"),
+ IdEmpresa = x.Field<long>("IDEMPRESA"),
+ Nome = x.Field<string>("NOME").RemoverAcentos(),
+ Documento = x.Field<string>("CGCCPF"),
+ Cei = x.Field<string>("CEI"),
+ Rne = x.Field<string>("RNE"),
+ Caepf = x.Field<string>("CAEPF"),
+ DocumentoPrincipal = new TipoDocumento?((TipoDocumento)Enum.Parse(typeof(TipoDocumento), x.Field<int>("DOCUMENTOPRINCIPAL").ToString())),
+ Status = (nums.Any<long>((long d) => d == x.Field<long>("IDCLIENTE")) ? "ATIVO" : "INATIVO"),
+ ResponsavelAssinatura = list.Find((ResponsavelAssinatura r) => r.IdCliente == x.Field<long>("IDCLIENTE")),
+ Excluido = (x.Field<object>("EXCLUIDO") == null ? false : x.Field<object>("EXCLUIDO").ToString() == "1"),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true)),
+ NomeSocialRg = x.Field<string>("nomesocialRg")
+ }).ToList<Gestor.Model.Domain.Seguros.Cliente>();
+ }
+
+ public List<ClientesAtivosInativos> FindAllClientes(bool completo, 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 = "excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = "0".CriarValor<string>(),
+ 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<ResponsavelAssinaturaDb>().FirstOrDefault<ResponsavelAssinaturaDb>((ResponsavelAssinaturaDb x) => x.IdCliente == id);
+ ResponsavelAssinatura responsavelAssinatura = ApplicationMapper.Mapper.Map<ResponsavelAssinaturaDb, ResponsavelAssinatura>(responsavelAssinaturaDb);
+ Gestor.Model.Domain.Seguros.Cliente cliente = ApplicationMapper.Mapper.Map<ClienteDb, Gestor.Model.Domain.Seguros.Cliente>(clienteDb);
+ cliente.ResponsavelAssinatura = responsavelAssinatura;
+ return cliente;
+ }
+
+ public List<Gestor.Model.Domain.Seguros.Cliente> FindByName(string filter, long idEmpresa = 0L, bool acessoAgger = false, bool assintatura = false, bool somenteNome = false)
+ {
+ return this.Find(filter, idEmpresa, acessoAgger, assintatura);
+ }
+
+ public List<Gestor.Model.Domain.Seguros.Cliente> FindByNameOld(string filter, long idempresa = 0L, bool acessoAgger = false, bool assintatura = false, bool somenteNome = false)
+ {
+ List<Gestor.Model.Domain.Seguros.Cliente> clientes;
+ object connection;
+ DataTable dataTable = new DataTable();
+ List<long> nums = new List<long>();
+ 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<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ }
+ };
+ List<Condicao> condicaos1 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "UPPER(NOME) COLLATE Latin1_General_CI_AI",
+ Valores = filter.CriarValor<string>(),
+ Operador = (somenteNome ? Operador.ComecaCom : Operador.Like)
+ }
+ };
+ List<Condicao> condicaos2 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idempresa",
+ Valores = idempresa.CriarValor<long>()
+ }
+ };
+ 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<Condicao> condicaos3 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "c.idcliente",
+ Valores = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("IDCLIENTE")).ToList<long>().CriarValor<long>()
+ }
+ };
+ List<Condicao> condicaos4 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.tipo",
+ Valores = 0.CriarValor<int>()
+ },
+ 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<DateTime>();
+ condicao.Grupo = 2;
+ condicao.Operacao = Operacao.Or;
+ condicao.Operador = Operador.Maior;
+ condicaos4.Add(condicao);
+ condicaos4.Add(new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = new List<object>()
+ {
+ 1,
+ 2,
+ 4
+ }
+ });
+ List<Condicao> 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, long>((DataRow x) => x.Field<long>("idcliente")).ToList<long>();
+ if (assintatura)
+ {
+ dataTable1 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT * FROM ResponsavelAssinatura c WHERE ", "");
+ }
+ }
+ goto Label0;
+ }
+ }
+ else
+ {
+ clientes = new List<Gestor.Model.Domain.Seguros.Cliente>();
+ }
+ }
+ return clientes;
+ List<ResponsavelAssinatura> list = dataTable1.AsEnumerable().Select<DataRow, ResponsavelAssinatura>((DataRow x) => new ResponsavelAssinatura()
+ {
+ Id = x.Field<long>("Id"),
+ IdCliente = x.Field<long>("IdCliente"),
+ NomeResponsavel = x.Field<string>("NomeResponsavel").RemoverAcentos(),
+ DocumentoResponsavel = x.Field<string>("DocumentoResponsavel"),
+ EmailResponsavel = x.Field<string>("EmailResponsavel")
+ }).ToList<ResponsavelAssinatura>();
+ return (
+ from x in dataTable.AsEnumerable().ToList<DataRow>()
+ select new Gestor.Model.Domain.Seguros.Cliente()
+ {
+ Id = x.Field<long>("IDCLIENTE"),
+ IdEmpresa = x.Field<long>("IDEMPRESA"),
+ Nome = x.Field<string>("NOME").RemoverAcentos(),
+ Documento = x.Field<string>("CGCCPF"),
+ Cei = x.Field<string>("CEI"),
+ Rne = x.Field<string>("RNE"),
+ Caepf = x.Field<string>("CAEPF"),
+ DocumentoPrincipal = new TipoDocumento?((TipoDocumento)Enum.Parse(typeof(TipoDocumento), x.Field<int>("DOCUMENTOPRINCIPAL").ToString())),
+ Status = (nums.Any<long>((long d) => d == x.Field<long>("IDCLIENTE")) ? "ATIVO" : "INATIVO"),
+ ResponsavelAssinatura = list.Find((ResponsavelAssinatura r) => r.IdCliente == x.Field<long>("IDCLIENTE")),
+ Excluido = (x.Field<object>("EXCLUIDO") == null ? false : x.Field<object>("EXCLUIDO").ToString() == "1"),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true)),
+ NomeSocialRg = x.Field<string>("nomesocialRg") ?? ""
+ }).ToList<Gestor.Model.Domain.Seguros.Cliente>();
+ }
+
+ public List<Gestor.Model.Domain.Seguros.Cliente> FindClienteDocumento(string documento)
+ {
+ List<Gestor.Model.Domain.Seguros.Cliente> clientes;
+ object connection;
+ List<Gestor.Model.Domain.Seguros.Cliente> clientes1 = new List<Gestor.Model.Domain.Seguros.Cliente>();
+ 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<long>("idcliente", true, true),
+ IdEmpresa = sqlDataReader.GetFieldValue<long>("idempresa", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("nome", true, true),
+ Documento = documento
+ });
+ }
+ return clientes1;
+ }
+ }
+ }
+ else
+ {
+ clientes = clientes1;
+ }
+ }
+ }
+ return clientes;
+ }
+
+ public List<Gestor.Model.Domain.Seguros.Cliente> FindClienteVinculo(string filter, List<long> vinculos, long idempresa = 0L, bool acessoAgger = false, bool assinatura = false, TipoFiltroCliente tipoFiltroCliente = 2)
+ {
+ List<Gestor.Model.Domain.Seguros.Cliente> clientes;
+ object connection;
+ List<Gestor.Model.Domain.Seguros.Cliente> clientes1 = new List<Gestor.Model.Domain.Seguros.Cliente>();
+ 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<long>("idcliente", true, true),
+ IdEmpresa = sqlDataReader.GetFieldValue<long>("idempresa", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("nome", true, true),
+ Documento = sqlDataReader.GetFieldValue<string>("cgccpf", true, true),
+ Cei = sqlDataReader.GetFieldValue<string>("cei", true, true),
+ Rne = sqlDataReader.GetFieldValue<string>("rne", true, true),
+ Caepf = sqlDataReader.GetFieldValue<string>("caepf", true, true),
+ DocumentoPrincipal = new TipoDocumento?(sqlDataReader.GetFieldValue<TipoDocumento>("documentoprincipal", true, true)),
+ Status = (sqlDataReader.GetFieldValue<int>("ativo", true, true) == 0 ? "ATIVO" : "INATIVO"),
+ Excluido = sqlDataReader.GetFieldValue<int>("excluido", true, true) == 1,
+ NomeSocialRg = sqlDataReader.GetFieldValue<string>("nomesocial", true, true)
+ });
+ }
+ return clientes1;
+ }
+ }
+ }
+ else
+ {
+ clientes = clientes1;
+ }
+ }
+ }
+ return clientes;
+ }
+
+ public List<Gestor.Model.Domain.Seguros.Cliente> FindObsCliente(string obsCliente, 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 = "anotacoes",
+ Valores = obsCliente.CriarValor<string>(),
+ Operador = Operador.Like
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = "0".CriarValor<string>(),
+ 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<Gestor.Model.Domain.Seguros.Cliente> FindPastaCliente(string pastaCliente, bool busca = false, 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 = "pasta",
+ Valores = pastaCliente.CriarValor<string>(),
+ Operador = (busca ? Operador.Igual : Operador.Like)
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = "0".CriarValor<string>(),
+ 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<Gestor.Model.Domain.Seguros.Cliente> FindVinculo(string filter, long id)
+ {
+ List<Condicao> condicaos = this.CriarFiltro(filter);
+ condicaos.AddRange(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "idcliente",
+ Valores = id.CriarValor<long>(),
+ 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<Gestor.Model.Domain.Seguros.Cliente>();
+ }
+ return dataTable.MapCliente();
+ }
+
+ public Gestor.Model.Domain.Seguros.Cliente Merge(Gestor.Model.Domain.Seguros.Cliente cliente)
+ {
+ ResponsavelAssinatura responsavelAssinatura;
+ ClienteDb clienteDb = ApplicationMapper.Mapper.Map<Gestor.Model.Domain.Seguros.Cliente, ClienteDb>(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<ResponsavelAssinatura, ResponsavelAssinaturaDb>(responsavelAssinatura1);
+ if (responsavelAssinaturaDb.Id != 0)
+ {
+ this._unitOfWork.Repository<ResponsavelAssinaturaDb>().Merge(responsavelAssinaturaDb);
+ }
+ else
+ {
+ this._unitOfWork.Repository<ResponsavelAssinaturaDb>().SaveOrUpdate(responsavelAssinaturaDb);
+ }
+ responsavelAssinatura1 = ApplicationMapper.Mapper.Map<ResponsavelAssinaturaDb, ResponsavelAssinatura>(responsavelAssinaturaDb);
+ }
+ base.Merge(clienteDb);
+ Gestor.Model.Domain.Seguros.Cliente cliente1 = ApplicationMapper.Mapper.Map<ClienteDb, Gestor.Model.Domain.Seguros.Cliente>(clienteDb);
+ cliente1.ResponsavelAssinatura = responsavelAssinatura1;
+ return cliente1;
+ }
+
+ public OrigemCliente Merge(OrigemCliente origem)
+ {
+ OrigemClienteDb origemClienteDb = ApplicationMapper.Mapper.Map<OrigemCliente, OrigemClienteDb>(origem);
+ this._unitOfWork.Repository<OrigemClienteDb>().Merge(origemClienteDb);
+ return ApplicationMapper.Mapper.Map<OrigemClienteDb, OrigemCliente>(origemClienteDb);
+ }
+
+ public Gestor.Model.Domain.Seguros.Cliente SaveOrUpdate(Gestor.Model.Domain.Seguros.Cliente cliente)
+ {
+ ResponsavelAssinatura responsavelAssinatura;
+ ClienteDb clienteDb = ApplicationMapper.Mapper.Map<Gestor.Model.Domain.Seguros.Cliente, ClienteDb>(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<ResponsavelAssinatura, ResponsavelAssinaturaDb>(id);
+ this._unitOfWork.Repository<ResponsavelAssinaturaDb>().SaveOrUpdate(responsavelAssinaturaDb);
+ id = ApplicationMapper.Mapper.Map<ResponsavelAssinaturaDb, ResponsavelAssinatura>(responsavelAssinaturaDb);
+ }
+ Gestor.Model.Domain.Seguros.Cliente cliente1 = ApplicationMapper.Mapper.Map<ClienteDb, Gestor.Model.Domain.Seguros.Cliente>(clienteDb);
+ cliente1.ResponsavelAssinatura = id;
+ return cliente1;
+ }
+
+ public OrigemCliente SaveOrUpdate(OrigemCliente origem)
+ {
+ OrigemClienteDb origemClienteDb = ApplicationMapper.Mapper.Map<OrigemCliente, OrigemClienteDb>(origem);
+ this._unitOfWork.Repository<OrigemClienteDb>().SaveOrUpdate(origemClienteDb);
+ return ApplicationMapper.Mapper.Map<OrigemClienteDb, OrigemCliente>(origemClienteDb);
+ }
+
+ private List<ClientesAtivosInativos> Select(SqlQueryCondition condition, string command, bool completo)
+ {
+ List<ClientesAtivosInativos> clientesAtivosInativos;
+ object connection;
+ List<long> nums3 = null;
+ List<long> 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<long> i = dataTable1.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("id")).ToList<long>(); i.Count > 0; i = nums3)
+ {
+ List<long> nums5 = i.Take<long>(2000).ToList<long>();
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idcliente",
+ Valores = nums5.CriarValor<long>()
+ }
+ };
+ List<Condicao> condicaos1 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ 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<DateTime>();
+ condicao.Grupo = 2;
+ condicao.Operacao = Operacao.Or;
+ condicao.Operador = Operador.Maior;
+ condicaos1.Add(condicao);
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = new List<object>()
+ {
+ 1,
+ 2,
+ 4
+ }
+ });
+ List<Condicao> 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<long> nums6 = dataTable9.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("id")).ToList<long>();
+ List<long> nums7 = dataTable9.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("id")).ToList<long>();
+ dataTable2.Merge(dataTable9);
+ List<Condicao> condicaos3 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "ORDEM",
+ Valores = "1".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "PADRAO",
+ Valores = "1".CriarValor<string>(),
+ 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<long> j = nums5; j.Count > 0; j = nums4)
+ {
+ List<long> nums8 = j.Take<long>(1000).ToList<long>();
+ List<Condicao> condicaos4 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idcliente1",
+ Valores = nums8.CriarValor<long>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "idcliente2",
+ Valores = nums8.CriarValor<long>(),
+ 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<long>() : j.Except<long>(nums8).ToList<long>());
+ }
+ while (nums6.Count > 0)
+ {
+ List<long> nums9 = nums6.Take<long>(2000).ToList<long>();
+ List<Condicao> condicaos5 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "vp.iddocumento",
+ Valores = nums9.CriarValor<long>()
+ }
+ };
+ 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<long>() : nums6.Except<long>(nums9).ToList<long>());
+ }
+ while (nums7.Count > 0)
+ {
+ List<long> nums10 = nums7.Take<long>(2000).ToList<long>();
+ List<Condicao> condicaos6 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "iddocumento",
+ Valores = nums10.CriarValor<long>()
+ }
+ };
+ 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<long>() : nums6.Except<long>(nums10).ToList<long>());
+ }
+ }
+ nums3 = (nums5.Count < 2000 ? new List<long>() : i.Except<long>(nums5).ToList<long>());
+ }
+ goto Label0;
+ }
+ else
+ {
+ clientesAtivosInativos = new List<ClientesAtivosInativos>();
+ }
+ }
+ }
+ else
+ {
+ clientesAtivosInativos = new List<ClientesAtivosInativos>();
+ }
+ }
+ return clientesAtivosInativos;
+ Label0:
+ Regex regex = new Regex("[^\\d]");
+ DateTime networkTime = Funcoes.GetNetworkTime();
+ Array values = Enum.GetValues(typeof(EstadoCivil));
+ List<ClientesAtivosInativos> clientesAtivosInativos1 = new List<ClientesAtivosInativos>();
+ dataTable1.AsEnumerable().ToList<DataRow>().ForEach((DataRow x) => {
+ DateTime? nullable;
+ DateTime dateTime;
+ List<long> list;
+ List<long> nums;
+ DateTime? nullable1;
+ string str;
+ DateTime? nullable2;
+ string nome;
+ int year;
+ int? nullable3;
+ DateTime? nullable4;
+ List<DataRow> dataRows = dataTable2.AsEnumerable().Where<DataRow>((DataRow y) => y.Field<long>("idcliente") == x.Field<long>("id")).ToList<DataRow>();
+ List<DataRow> dataRows1 = dataRows;
+ Func<DataRow, long> u003cu003e9_325 = ClienteRepository.u003cu003ec.u003cu003e9__32_5;
+ if (u003cu003e9_325 == null)
+ {
+ u003cu003e9_325 = (DataRow d) => d.Field<long>("id");
+ ClienteRepository.u003cu003ec.u003cu003e9__32_5 = u003cu003e9_325;
+ }
+ List<long> list1 = dataRows1.Select<DataRow, long>(u003cu003e9_325).ToList<long>();
+ DataRow dataRow = dataTable3.AsEnumerable().FirstOrDefault<DataRow>((DataRow t) => t.Field<long>("id") == x.Field<long>("id"));
+ EnumerableRowCollection<DataRow> dataRows2 = dataTable4.AsEnumerable().Where<DataRow>((DataRow t) => t.Field<long>("id") == x.Field<long>("id"));
+ Func<DataRow, string> u003cu003e9_328 = ClienteRepository.u003cu003ec.u003cu003e9__32_8;
+ if (u003cu003e9_328 == null)
+ {
+ u003cu003e9_328 = (DataRow t) => t.Field<string>("email");
+ ClienteRepository.u003cu003ec.u003cu003e9__32_8 = u003cu003e9_328;
+ }
+ EnumerableRowCollection<string> strs = dataRows2.Select<DataRow, string>(u003cu003e9_328);
+ if (list1.Count > 0)
+ {
+ EnumerableRowCollection<DataRow> dataRows3 = dataTable6.AsEnumerable().Where<DataRow>((DataRow y) => list1.Contains(y.Field<long>("iddocumento")));
+ Func<DataRow, long> u003cu003e9_3210 = ClienteRepository.u003cu003ec.u003cu003e9__32_10;
+ if (u003cu003e9_3210 == null)
+ {
+ u003cu003e9_3210 = (DataRow y) => y.Field<long>("idvendedor");
+ ClienteRepository.u003cu003ec.u003cu003e9__32_10 = u003cu003e9_3210;
+ }
+ list = dataRows3.Select<DataRow, long>(u003cu003e9_3210).Distinct<long>().ToList<long>();
+ }
+ else
+ {
+ list = null;
+ }
+ List<long> nums1 = list;
+ EnumerableRowCollection<DataRow> dataRows4 = dataTable5.AsEnumerable().Where<DataRow>((DataRow t) => t.Field<long>("id") == x.Field<long>("id"));
+ Func<DataRow, Gestor.Model.Domain.Seguros.ClienteTelefone> u003cu003e9_3212 = ClienteRepository.u003cu003ec.u003cu003e9__32_12;
+ if (u003cu003e9_3212 == null)
+ {
+ u003cu003e9_3212 = (DataRow t) => new Gestor.Model.Domain.Seguros.ClienteTelefone()
+ {
+ Prefixo = t.Field<string>("ddd"),
+ Numero = t.Field<string>("fone")
+ };
+ ClienteRepository.u003cu003ec.u003cu003e9__32_12 = u003cu003e9_3212;
+ }
+ List<Gestor.Model.Domain.Seguros.ClienteTelefone> clienteTelefones = dataRows4.Select<DataRow, Gestor.Model.Domain.Seguros.ClienteTelefone>(u003cu003e9_3212).ToList<Gestor.Model.Domain.Seguros.ClienteTelefone>();
+ List<Gestor.Model.Domain.Seguros.ClienteTelefone> clienteTelefones1 = clienteTelefones;
+ Func<Gestor.Model.Domain.Seguros.ClienteTelefone, string> 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<string> strs1 = clienteTelefones1.Select<Gestor.Model.Domain.Seguros.ClienteTelefone, string>(u003cu003e9_3213);
+ List<DataRow> dataRows5 = dataRows;
+ Func<DataRow, string> u003cu003e9_3214 = ClienteRepository.u003cu003ec.u003cu003e9__32_14;
+ if (u003cu003e9_3214 == null)
+ {
+ u003cu003e9_3214 = (DataRow y) => y.Field<string>("ramo");
+ ClienteRepository.u003cu003ec.u003cu003e9__32_14 = u003cu003e9_3214;
+ }
+ IEnumerable<string> strs2 = dataRows5.Select<DataRow, string>(u003cu003e9_3214);
+ Func<string, string> u003cu003e9_3215 = ClienteRepository.u003cu003ec.u003cu003e9__32_15;
+ if (u003cu003e9_3215 == null)
+ {
+ u003cu003e9_3215 = (string r) => r;
+ ClienteRepository.u003cu003ec.u003cu003e9__32_15 = u003cu003e9_3215;
+ }
+ List<string> list2 = strs2.OrderBy<string, string>(u003cu003e9_3215).Distinct<string>().ToList<string>();
+ DataRow dataRow1 = dataTable7.AsEnumerable().FirstOrDefault<DataRow>((DataRow v) => v.Field<long>("idcliente1") == x.Field<long>("id")) ?? dataTable7.AsEnumerable().FirstOrDefault<DataRow>((DataRow v) => v.Field<long>("idcliente2") == x.Field<long>("id"));
+ if (list1.Count > 0)
+ {
+ DataTable dataTable = dataTable8;
+ if (dataTable != null)
+ {
+ EnumerableRowCollection<DataRow> dataRows6 = dataTable.AsEnumerable().Where<DataRow>((DataRow y) => list1.Contains(y.Field<long>("iddocumento")));
+ Func<DataRow, long> u003cu003e9_3219 = ClienteRepository.u003cu003ec.u003cu003e9__32_19;
+ if (u003cu003e9_3219 == null)
+ {
+ u003cu003e9_3219 = (DataRow y) => y.Field<long>("idestipulante");
+ ClienteRepository.u003cu003ec.u003cu003e9__32_19 = u003cu003e9_3219;
+ }
+ nums = dataRows6.Select<DataRow, long>(u003cu003e9_3219).Distinct<long>().ToList<long>();
+ }
+ else
+ {
+ nums = null;
+ }
+ }
+ else
+ {
+ nums = null;
+ }
+ List<long> nums2 = nums;
+ List<Gestor.Model.Domain.Seguros.Vendedor> vendedors = (nums1 == null || nums1.Count <= 0 ? new List<Gestor.Model.Domain.Seguros.Vendedor>() : (
+ from v in Auxiliar.Vendedores
+ where nums1.Contains(v.Id)
+ select v).ToList<Gestor.Model.Domain.Seguros.Vendedor>());
+ List<Estipulante> estipulantes = (nums2 == null || nums2.Count <= 0 ? new List<Estipulante>() : (
+ from e in Auxiliar.Estipulantes
+ where nums2.Contains(e.Id)
+ select e).ToList<Estipulante>());
+ string description = "";
+ foreach (object obj in values)
+ {
+ if (obj.GetOldValue<object>() != x.Field<string>("EstadoCivi"))
+ {
+ continue;
+ }
+ description = ((EstadoCivil)obj).GetDescription<EstadoCivil>();
+ }
+ ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos()
+ {
+ EntidadeCliente = new Gestor.Model.Domain.Seguros.Cliente()
+ {
+ Id = x.Field<long>("id"),
+ Nome = x.Field<string>("nome"),
+ Telefones = new ObservableCollection<Gestor.Model.Domain.Seguros.ClienteTelefone>(clienteTelefones),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
+ },
+ Id = x.Field<long>("id"),
+ Nome = x.Field<string>("nome")
+ };
+ if (x.Field<object>("nascimento") == null)
+ {
+ nullable = null;
+ nullable1 = nullable;
+ }
+ else
+ {
+ nullable1 = new DateTime?(DateTime.Parse(x.Field<object>("nascimento").ToString()));
+ }
+ clientesAtivosInativo.Nascimento = nullable1;
+ if (x.Field<object>("nascimento") == null)
+ {
+ str = "";
+ }
+ else
+ {
+ dateTime = x.Field<DateTime>("nascimento");
+ str = dateTime.ToString("dd/MM");
+ }
+ clientesAtivosInativo.Aniversario = str;
+ clientesAtivosInativo.Documento = x.Field<string>("documento");
+ if (x.Field<object>("vencimento") == null)
+ {
+ nullable = null;
+ nullable2 = nullable;
+ }
+ else
+ {
+ nullable2 = x.Field<DateTime?>("vencimento");
+ }
+ clientesAtivosInativo.VencimentoCnh = nullable2;
+ clientesAtivosInativo.Ramo = string.Join(" | ", list2);
+ clientesAtivosInativo.Ativo = (list2.Any<string>() ? "SIM" : "NÃO");
+ 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)
+ {
+ nome = profissao.Nome;
+ }
+ else
+ {
+ nome = null;
+ }
+ }
+ else
+ {
+ nome = "";
+ }
+ clientesAtivosInativo.Profissao = nome;
+ clientesAtivosInativo.Telefone = string.Join(" | ", strs1);
+ clientesAtivosInativo.Cep = (dataRow != null ? dataRow.Field<string>("cep") : null);
+ clientesAtivosInativo.Endereco = (dataRow != null ? dataRow.Field<string>("endereco") : null);
+ clientesAtivosInativo.Numero = (dataRow != null ? dataRow.Field<string>("numero") : null);
+ clientesAtivosInativo.Complemento = (dataRow != null ? dataRow.Field<string>("complemento") : null);
+ clientesAtivosInativo.Cidade = (dataRow != null ? dataRow.Field<string>("cidade") : null);
+ clientesAtivosInativo.PastaCliente = x.Field<string>("pasta");
+ clientesAtivosInativo.Estado = (dataRow != null ? dataRow.Field<string>("estado") : null);
+ clientesAtivosInativo.Email = string.Join(" | ", strs);
+ clientesAtivosInativo.RecebeEmail = (x.Field<bool?>("maladireta").GetValueOrDefault() ? "SIM" : "NÃO");
+ List<Gestor.Model.Domain.Seguros.Vendedor> vendedors1 = vendedors;
+ Func<Gestor.Model.Domain.Seguros.Vendedor, string> 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<Gestor.Model.Domain.Seguros.Vendedor, string>(u003cu003e9_3223));
+ clientesAtivosInativo.TipoPessoa = (string.IsNullOrEmpty(x.Field<string>("documento")) ? "FÍSICA" : (regex.Replace(x.Field<string>("documento"), "").Length > 11 ? "JURÍDICA" : "FÍSICA"));
+ clientesAtivosInativo.Sexo = (x.Field<object>("sexo") == null || !(x.Field<object>("sexo").ToString() != "") || string.IsNullOrWhiteSpace(x.Field<object>("sexo").ToString()) ? "" : ((Sexo)Enum.Parse(typeof(Sexo), x.Field<object>("sexo").ToString())).GetDescription<Sexo>());
+ clientesAtivosInativo.RendaMensal = (x.Field<object>("RendaMensal") == null ? decimal.Zero : x.Field<decimal>("RendaMensal"));
+ clientesAtivosInativo.Parentesco = (dataRow1 == null ? "NÃO" : "SIM");
+ if (x.Field<object>("nascimento") != null)
+ {
+ DateTime dateTime1 = DateTime.Parse(x.Field<object>("nascimento").ToString());
+ int num = networkTime.Year;
+ dateTime = DateTime.Parse(x.Field<object>("nascimento").ToString());
+ if (dateTime1 > networkTime.AddYears(-(num - dateTime.Year)))
+ {
+ int year1 = networkTime.Year;
+ dateTime = DateTime.Parse(x.Field<object>("nascimento").ToString());
+ year = year1 - dateTime.Year - 1;
+ }
+ else
+ {
+ int num1 = networkTime.Year;
+ dateTime = DateTime.Parse(x.Field<object>("nascimento").ToString());
+ year = num1 - dateTime.Year;
+ }
+ nullable3 = new int?(year);
+ }
+ else
+ {
+ nullable3 = null;
+ }
+ clientesAtivosInativo.Idade = nullable3;
+ nullable = x.Field<DateTime?>("clidesde");
+ if (!nullable.HasValue)
+ {
+ nullable = null;
+ nullable4 = nullable;
+ }
+ else
+ {
+ nullable4 = x.Field<DateTime?>("clidesde");
+ }
+ clientesAtivosInativo.ClienteDesde = nullable4;
+ clientesAtivosInativo.EstadoCivil = description;
+ List<Estipulante> estipulantes1 = estipulantes;
+ Func<Estipulante, string> 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<Estipulante, string>(u003cu003e9_3224));
+ clientesAtivosInativos1.Add(clientesAtivosInativo);
+ });
+ return clientesAtivosInativos1;
+ }
+
+ public List<OrigemCliente> Sincronize(List<OrigemCliente> origens, long id)
+ {
+ if (origens == null)
+ {
+ return null;
+ }
+ IEnumerable<OrigemClienteDb> origemClienteDbs = (
+ from x in this._unitOfWork.Query<OrigemClienteDb>()
+ where x.Cliente.Id == id
+ select x).ToList<OrigemClienteDb>().Where<OrigemClienteDb>((OrigemClienteDb x) => {
+ List<OrigemCliente> origemClientes = origens;
+ Func<OrigemCliente, long> 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<OrigemCliente, long>(u003cu003e9_304).Contains<long>(x.Id);
+ });
+ if (origemClienteDbs != null)
+ {
+ origemClienteDbs.ForEach<OrigemClienteDb>((OrigemClienteDb x) => this._unitOfWork.Repository<OrigemClienteDb>().Delete(x));
+ }
+ else
+ {
+ }
+ origens.ForEach((OrigemCliente x) => x = (x.Id > (long)0 ? this.Merge(x) : this.SaveOrUpdate(x)));
+ return origens;
+ }
+
+ private async Task<IEnumerable<Gestor.Model.Relatorios.ClienteTelefone>> TelefonesClientes()
+ {
+ IEnumerable<Gestor.Model.Relatorios.ClienteTelefone> clienteTelefones;
+ object connection;
+ List<Gestor.Model.Relatorios.ClienteTelefone> clienteTelefones1 = new List<Gestor.Model.Relatorios.ClienteTelefone>();
+ 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<Gestor.Model.Relatorios.ClienteTelefone> 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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs
new file mode 100644
index 0000000..1a5fb3c
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteTelefoneRepository.cs
@@ -0,0 +1,220 @@
+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<ClienteTelefoneDb>, IClienteTelefoneRepository, IGenericRepository<ClienteTelefoneDb>
+ {
+ 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<ClienteTelefone> DeleteFone(long clienteId, List<ClienteTelefone> telefones)
+ {
+ if (telefones == null || telefones.Count == 0)
+ {
+ return null;
+ }
+ List<ClienteTelefoneDb> list = (
+ from cliente in base.All()
+ where cliente.Cliente.Id == clienteId
+ select cliente).ToList<ClienteTelefoneDb>().Where<ClienteTelefoneDb>((ClienteTelefoneDb fone) => {
+ List<ClienteTelefone> clienteTelefones = telefones;
+ Func<ClienteTelefone, long> 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<ClienteTelefone, long>(u003cu003e9_103).Contains<long>(fone.Id);
+ }).ToList<ClienteTelefoneDb>();
+ list.ForEach((ClienteTelefoneDb fonesExcluido) => base.Delete(fonesExcluido));
+ return ApplicationMapper.Mapper.Map<List<ClienteTelefoneDb>, List<ClienteTelefone>>(list);
+ }
+
+ public List<ClienteTelefone> Find(string telefone, long idempresa = 0L)
+ {
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "REPLACE(ISNULL(ct.fone, ''), '-','')",
+ Valores = telefone.Clear().CriarValor<string>(),
+ Operador = Operador.Like
+ }
+ };
+ if (idempresa > (long)0)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idempresa",
+ Valores = idempresa.CriarValor<long>()
+ });
+ }
+ return this.Select(condicaos.CreateParameters(0));
+ }
+
+ private List<ClienteTelefone> FindByCliente(long id)
+ {
+ return this.Select((new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "ct.idcliente",
+ Valores = id.CriarValor<long>()
+ }
+ }).CreateParameters(0));
+ }
+
+ public List<ClienteTelefone> FindByClienteId(long id)
+ {
+ return this.FindByCliente(id);
+ }
+
+ public ClienteTelefone FindById(long id)
+ {
+ ClienteTelefoneDb clienteTelefoneDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ClienteTelefoneDb, ClienteTelefone>(clienteTelefoneDb);
+ }
+
+ public List<ClienteTelefone> Inserir(List<ClienteTelefone> telefones)
+ {
+ List<ClienteTelefoneDb> clienteTelefoneDbs = ApplicationMapper.Mapper.Map<List<ClienteTelefone>, List<ClienteTelefoneDb>>(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<ClienteTelefoneDb>, List<ClienteTelefone>>(clienteTelefoneDbs);
+ }
+
+ public List<ClienteTelefone> Inserir(List<ClienteTelefone> 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<ClienteTelefoneDb> clienteTelefoneDbs = ApplicationMapper.Mapper.Map<List<ClienteTelefone>, List<ClienteTelefoneDb>>(telefones);
+ base.AddRange(clienteTelefoneDbs);
+ return ApplicationMapper.Mapper.Map<List<ClienteTelefoneDb>, List<ClienteTelefone>>(clienteTelefoneDbs);
+ }
+
+ public ClienteTelefone Merge(ClienteTelefone telefone)
+ {
+ ClienteTelefoneDb clienteTelefoneDb = ApplicationMapper.Mapper.Map<ClienteTelefone, ClienteTelefoneDb>(telefone);
+ clienteTelefoneDb.Observacao = clienteTelefoneDb.Observacao.Trim();
+ base.Merge(clienteTelefoneDb);
+ return ApplicationMapper.Mapper.Map<ClienteTelefoneDb, ClienteTelefone>(clienteTelefoneDb);
+ }
+
+ public List<ClienteTelefone> Merge(List<ClienteTelefone> telefones, Cliente cliente)
+ {
+ List<ClienteTelefoneDb> clienteTelefoneDbs = ApplicationMapper.Mapper.Map<List<ClienteTelefone>, List<ClienteTelefoneDb>>(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, ClienteDb>(cliente);
+ this.SaveOrUpdate(x);
+ });
+ return ApplicationMapper.Mapper.Map<List<ClienteTelefoneDb>, List<ClienteTelefone>>(clienteTelefoneDbs);
+ }
+
+ public ClienteTelefone SaveOrUpdate(ClienteTelefone telefone)
+ {
+ string str;
+ ClienteTelefoneDb clienteTelefoneDb = ApplicationMapper.Mapper.Map<ClienteTelefone, ClienteTelefoneDb>(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, ClienteTelefone>(clienteTelefoneDb);
+ }
+
+ private List<ClienteTelefone> Select(SqlQueryCondition condition)
+ {
+ List<ClienteTelefone> 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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs
new file mode 100644
index 0000000..460e860
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ClienteVinculoRepository.cs
@@ -0,0 +1,112 @@
+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<ClienteVinculoDb>, IClienteVinculoRepository, IGenericRepository<ClienteVinculoDb>
+ {
+ public ClienteVinculoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ }
+
+ public void Delete(long id)
+ {
+ base.Delete(base.FindEntityById(id));
+ }
+
+ public List<ClienteVinculo> DeleteVinculo(long clienteId, List<ClienteVinculo> vinculos)
+ {
+ if (vinculos == null)
+ {
+ return null;
+ }
+ List<ClienteVinculoDb> list = (
+ from x in base.All()
+ where x.Cliente1.Id == clienteId || x.Cliente2.Id == clienteId
+ select x).ToList<ClienteVinculoDb>().Where<ClienteVinculoDb>((ClienteVinculoDb vinculo) => {
+ List<ClienteVinculo> clienteVinculos = vinculos;
+ Func<ClienteVinculo, long> 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<ClienteVinculo, long>(u003cu003e9_32).Contains<long>(vinculo.Id);
+ }).ToList<ClienteVinculoDb>();
+ ClienteVinculoRepository clienteVinculoRepository = this;
+ list.ForEach(new Action<ClienteVinculoDb>(clienteVinculoRepository.Delete));
+ return ApplicationMapper.Mapper.Map<List<ClienteVinculoDb>, List<ClienteVinculo>>(list);
+ }
+
+ public List<ClienteVinculo> FindByCliente(long id)
+ {
+ List<ClienteVinculoDb> list = (
+ from x in base.All()
+ where x.Cliente1.Id == id || x.Cliente2.Id == id
+ select x).ToList<ClienteVinculoDb>();
+ return ApplicationMapper.Mapper.Map<List<ClienteVinculoDb>, List<ClienteVinculo>>(list);
+ }
+
+ public ClienteVinculo FindById(long id)
+ {
+ ClienteVinculoDb clienteVinculoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ClienteVinculoDb, ClienteVinculo>(clienteVinculoDb);
+ }
+
+ public List<ClienteVinculo> Inserir(List<ClienteVinculo> 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<ClienteVinculoDb> clienteVinculoDbs = ApplicationMapper.Mapper.Map<List<ClienteVinculo>, List<ClienteVinculoDb>>(vinculos);
+ base.AddRange(clienteVinculoDbs);
+ return ApplicationMapper.Mapper.Map<List<ClienteVinculoDb>, List<ClienteVinculo>>(clienteVinculoDbs);
+ }
+
+ public List<ClienteVinculo> Merge(List<ClienteVinculo> vinculos, Cliente cliente)
+ {
+ List<ClienteVinculoDb> clienteVinculoDbs = ApplicationMapper.Mapper.Map<List<ClienteVinculo>, List<ClienteVinculoDb>>(vinculos);
+ clienteVinculoDbs.ForEach((ClienteVinculoDb x) => {
+ if (x.Id != 0)
+ {
+ base.Merge(x);
+ return;
+ }
+ x.Cliente1 = ApplicationMapper.Mapper.Map<Cliente, ClienteDb>(cliente);
+ this.SaveOrUpdate(x);
+ });
+ return ApplicationMapper.Mapper.Map<List<ClienteVinculoDb>, List<ClienteVinculo>>(clienteVinculoDbs);
+ }
+
+ public ClienteVinculo SaveOrUpdate(ClienteVinculo clienteVinculo)
+ {
+ ClienteVinculoDb clienteVinculoDb = ApplicationMapper.Mapper.Map<ClienteVinculo, ClienteVinculoDb>(clienteVinculo);
+ this.SaveOrUpdate(clienteVinculoDb);
+ return ApplicationMapper.Mapper.Map<ClienteVinculoDb, ClienteVinculo>(clienteVinculoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs
new file mode 100644
index 0000000..f4abfdf
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaGranizoRepository.cs
@@ -0,0 +1,65 @@
+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<CoberturaGranizoDb>, ICoberturaGranizoRepository, IGenericRepository<CoberturaGranizoDb>
+ {
+ 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<CoberturaGranizo> Find(long id)
+ {
+ List<CoberturaGranizoDb> list = (
+ from x in base.All()
+ where x.Granizo.Id == id
+ select x).ToList<CoberturaGranizoDb>();
+ return ApplicationMapper.Mapper.Map<List<CoberturaGranizoDb>, List<CoberturaGranizo>>(list);
+ }
+
+ public CoberturaGranizo FindById(long id)
+ {
+ CoberturaGranizoDb coberturaGranizoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<CoberturaGranizoDb, CoberturaGranizo>(coberturaGranizoDb);
+ }
+
+ public CoberturaGranizo Merge(CoberturaGranizo cobertura)
+ {
+ CoberturaGranizoDb coberturaGranizoDb = ApplicationMapper.Mapper.Map<CoberturaGranizo, CoberturaGranizoDb>(cobertura);
+ base.Merge(coberturaGranizoDb);
+ return ApplicationMapper.Mapper.Map<CoberturaGranizoDb, CoberturaGranizo>(coberturaGranizoDb);
+ }
+
+ public CoberturaGranizo SaveOrUpdate(CoberturaGranizo cobertura)
+ {
+ CoberturaGranizoDb coberturaGranizoDb = ApplicationMapper.Mapper.Map<CoberturaGranizo, CoberturaGranizoDb>(cobertura);
+ this.SaveOrUpdate(coberturaGranizoDb);
+ return ApplicationMapper.Mapper.Map<CoberturaGranizoDb, CoberturaGranizo>(coberturaGranizoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs
new file mode 100644
index 0000000..e9f916d
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaPadraoRepository.cs
@@ -0,0 +1,70 @@
+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<CoberturaPadraoDb>, ICoberturaPadraoRepository, IGenericRepository<CoberturaPadraoDb>
+ {
+ 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<CoberturaPadrao> Find()
+ {
+ List<CoberturaPadraoDb> list = base.All().ToList<CoberturaPadraoDb>();
+ return ApplicationMapper.Mapper.Map<List<CoberturaPadraoDb>, List<CoberturaPadrao>>(list);
+ }
+
+ public CoberturaPadrao FindById(long id)
+ {
+ CoberturaPadraoDb coberturaPadraoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<CoberturaPadraoDb, CoberturaPadrao>(coberturaPadraoDb);
+ }
+
+ public List<CoberturaPadrao> FindByRamoId(long id)
+ {
+ List<CoberturaPadraoDb> list = (
+ from x in base.All()
+ where x.IdRamo == id
+ select x).ToList<CoberturaPadraoDb>();
+ return ApplicationMapper.Mapper.Map<List<CoberturaPadraoDb>, List<CoberturaPadrao>>(list);
+ }
+
+ public CoberturaPadrao Merge(CoberturaPadrao coberturaPadrao)
+ {
+ CoberturaPadraoDb coberturaPadraoDb = ApplicationMapper.Mapper.Map<CoberturaPadrao, CoberturaPadraoDb>(coberturaPadrao);
+ base.Merge(coberturaPadraoDb);
+ return ApplicationMapper.Mapper.Map<CoberturaPadraoDb, CoberturaPadrao>(coberturaPadraoDb);
+ }
+
+ public CoberturaPadrao SaveOrUpdate(CoberturaPadrao coberturaPadrao)
+ {
+ CoberturaPadraoDb coberturaPadraoDb = ApplicationMapper.Mapper.Map<CoberturaPadrao, CoberturaPadraoDb>(coberturaPadrao);
+ this.SaveOrUpdate(coberturaPadraoDb);
+ return ApplicationMapper.Mapper.Map<CoberturaPadraoDb, CoberturaPadrao>(coberturaPadraoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs
new file mode 100644
index 0000000..f50d4ee
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CoberturaRepository.cs
@@ -0,0 +1,174 @@
+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<CoberturaDb>, ICoberturaRepository, IGenericRepository<CoberturaDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public CoberturaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Cobertura> AddRange(List<Cobertura> coberturas)
+ {
+ List<CoberturaDb> coberturaDbs = ApplicationMapper.Mapper.Map<List<Cobertura>, List<CoberturaDb>>(coberturas);
+ base.AddRange(coberturaDbs);
+ return ApplicationMapper.Mapper.Map<List<CoberturaDb>, List<Cobertura>>(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<long> ids)
+ {
+ List<CoberturaDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Item.Id)
+ select x).ToList<CoberturaDb>();
+ if (list.Count == 0)
+ {
+ return;
+ }
+ base.DeleteRange(list);
+ }
+
+ public Cobertura FindById(long id)
+ {
+ CoberturaDb coberturaDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<CoberturaDb, Cobertura>(coberturaDb);
+ }
+
+ public List<Cobertura> 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<CoberturaPadrao> list = (
+ from x in dataTable.AsEnumerable().ToList<DataRow>()
+ select new CoberturaPadrao()
+ {
+ Id = x.Field<long>("idcoberturapadrao"),
+ IdRamo = (x.Field<object>("idramo") != null ? x.Field<long>("idramo") : (long)0),
+ Descricao = x.Field<string>("descricao")
+ }).ToList<CoberturaPadrao>();
+ return dataTable1.AsEnumerable().ToList<DataRow>().Select<DataRow, Cobertura>((DataRow x) => {
+ Cobertura cobertura = new Cobertura()
+ {
+ Id = x.Field<long>("idcobertura"),
+ CoberturaPadrao = (x.Field<object>("idcoberturapadrao") == null ? null : list.FirstOrDefault<CoberturaPadrao>((CoberturaPadrao c) => c.Id == x.Field<long>("idcoberturapadrao"))),
+ Item = new Item()
+ {
+ Id = x.Field<long>("iditem")
+ }
+ };
+ decimal? nullable = x.Field<decimal?>("franquia");
+ cobertura.Franquia = nullable.GetValueOrDefault();
+ nullable = x.Field<decimal?>("premio");
+ cobertura.Premio = nullable.GetValueOrDefault();
+ nullable = x.Field<decimal?>("lmi");
+ cobertura.Lmi = nullable.GetValueOrDefault();
+ cobertura.Observacao = x.Field<string>("observacao");
+ return cobertura;
+ }).ToList<Cobertura>();
+ }
+
+ public Cobertura Merge(Cobertura cobertura)
+ {
+ CoberturaDb coberturaDb = ApplicationMapper.Mapper.Map<Cobertura, CoberturaDb>(cobertura);
+ base.Merge(coberturaDb);
+ return ApplicationMapper.Mapper.Map<CoberturaDb, Cobertura>(coberturaDb);
+ }
+
+ public List<Cobertura> MergeRange(List<Cobertura> coberturas)
+ {
+ List<CoberturaDb> coberturaDbs = ApplicationMapper.Mapper.Map<List<Cobertura>, List<CoberturaDb>>(coberturas);
+ CoberturaRepository coberturaRepository = this;
+ coberturaDbs.ForEach(new Action<CoberturaDb>(coberturaRepository.Merge));
+ return ApplicationMapper.Mapper.Map<List<CoberturaDb>, List<Cobertura>>(coberturaDbs);
+ }
+
+ public Cobertura SaveOrUpdate(Cobertura cobertura)
+ {
+ CoberturaDb coberturaDb = ApplicationMapper.Mapper.Map<Cobertura, CoberturaDb>(cobertura);
+ this.SaveOrUpdate(coberturaDb);
+ return ApplicationMapper.Mapper.Map<CoberturaDb, Cobertura>(coberturaDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs
new file mode 100644
index 0000000..d06bfaf
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CondicaoRepasseRepository.cs
@@ -0,0 +1,46 @@
+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<CondicaoRepasseDb>, ICondicaoRepasseRepository, IGenericRepository<CondicaoRepasseDb>
+ {
+ 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, CondicaoRepasse>(condicaoRepasseDb);
+ }
+
+ public CondicaoRepasse Merge(CondicaoRepasse condicaoRepasse)
+ {
+ CondicaoRepasseDb condicaoRepasseDb = ApplicationMapper.Mapper.Map<CondicaoRepasse, CondicaoRepasseDb>(condicaoRepasse);
+ base.Merge(condicaoRepasseDb);
+ return ApplicationMapper.Mapper.Map<CondicaoRepasseDb, CondicaoRepasse>(condicaoRepasseDb);
+ }
+
+ public CondicaoRepasse SaveOrUpdate(CondicaoRepasse condicaoRepasse)
+ {
+ CondicaoRepasseDb condicaoRepasseDb = ApplicationMapper.Mapper.Map<CondicaoRepasse, CondicaoRepasseDb>(condicaoRepasse);
+ this.SaveOrUpdate(condicaoRepasseDb);
+ return ApplicationMapper.Mapper.Map<CondicaoRepasseDb, CondicaoRepasse>(condicaoRepasseDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs
new file mode 100644
index 0000000..2410399
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfigExtratoImportRepository.cs
@@ -0,0 +1,101 @@
+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<ConfigExtratoImportDb>, IConfigExtratoImportRepository, IGenericRepository<ConfigExtratoImportDb>
+ {
+ 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<ConfigExtratoImport> Find(bool ativo)
+ {
+ return (
+ from x in this._unitOfWork.Session.CreateQuery("from ConfigExtratoImportDb \r\n where ativo IS NULL OR ativo != '1'").List<ConfigExtratoImportDb>()
+ select new ConfigExtratoImport()
+ {
+ Id = x.Id,
+ IdSeguradora = x.IdSeguradora,
+ Codigo = x.Codigo,
+ Descricao = x.Descricao,
+ Ativo = x.Ativo
+ }).ToList<ConfigExtratoImport>();
+ }
+
+ public List<ConfigExtratoImport> Find()
+ {
+ return (
+ from x in this._unitOfWork.Session.CreateQuery("from ConfigExtratoImportDb").List<ConfigExtratoImportDb>()
+ select new ConfigExtratoImport()
+ {
+ Id = x.Id,
+ IdSeguradora = x.IdSeguradora,
+ Codigo = x.Codigo,
+ Descricao = x.Descricao,
+ Ativo = x.Ativo
+ }).ToList<ConfigExtratoImport>();
+ }
+
+ public ConfigExtratoImport FindById(long id)
+ {
+ ConfigExtratoImportDb configExtratoImportDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ConfigExtratoImportDb, ConfigExtratoImport>(configExtratoImportDb);
+ }
+
+ public List<ConfigExtratoImport> FindBySeguradora(long id)
+ {
+ return (
+ from x in this._unitOfWork.Session.CreateQuery(string.Format("from ConfigExtratoImportDb where IdSeguradora = {0}", id)).List<ConfigExtratoImportDb>()
+ select new ConfigExtratoImport()
+ {
+ Id = x.Id,
+ IdSeguradora = x.IdSeguradora,
+ Codigo = x.Codigo,
+ Descricao = x.Descricao,
+ Ativo = x.Ativo
+ }).ToList<ConfigExtratoImport>();
+ }
+
+ public Gestor.Model.Domain.Seguros.ConfigExtratoImport Merge(Gestor.Model.Domain.Seguros.ConfigExtratoImport ConfigExtratoImport)
+ {
+ ConfigExtratoImportDb configExtratoImportDb = ApplicationMapper.Mapper.Map<Gestor.Model.Domain.Seguros.ConfigExtratoImport, ConfigExtratoImportDb>(ConfigExtratoImport);
+ base.Merge(configExtratoImportDb);
+ return ApplicationMapper.Mapper.Map<ConfigExtratoImportDb, Gestor.Model.Domain.Seguros.ConfigExtratoImport>(configExtratoImportDb);
+ }
+
+ public List<ConfigExtratoImport> MergeRange(List<ConfigExtratoImport> configExtratoImport)
+ {
+ List<ConfigExtratoImportDb> configExtratoImportDbs = ApplicationMapper.Mapper.Map<List<ConfigExtratoImport>, List<ConfigExtratoImportDb>>(configExtratoImport);
+ ConfigExtratoImportRepository configExtratoImportRepository = this;
+ configExtratoImportDbs.ForEach(new Action<ConfigExtratoImportDb>(configExtratoImportRepository.Merge));
+ return ApplicationMapper.Mapper.Map<List<ConfigExtratoImportDb>, List<ConfigExtratoImport>>(configExtratoImportDbs);
+ }
+
+ public Gestor.Model.Domain.Seguros.ConfigExtratoImport SaveOrUpdate(Gestor.Model.Domain.Seguros.ConfigExtratoImport ConfigExtratoImport)
+ {
+ ConfigExtratoImportDb configExtratoImportDb = ApplicationMapper.Mapper.Map<Gestor.Model.Domain.Seguros.ConfigExtratoImport, ConfigExtratoImportDb>(ConfigExtratoImport);
+ this.SaveOrUpdate(configExtratoImportDb);
+ return ApplicationMapper.Mapper.Map<ConfigExtratoImportDb, Gestor.Model.Domain.Seguros.ConfigExtratoImport>(configExtratoImportDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs
new file mode 100644
index 0000000..5d6f539
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConfiguracaoRepository.cs
@@ -0,0 +1,61 @@
+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<ConfiguracaoSistemaDb>, IConfiguracaoRepository, IGenericRepository<ConfiguracaoSistemaDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public ConfiguracaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<ConfiguracaoSistema> BuscarConfiguracoes()
+ {
+ return ApplicationMapper.Mapper.Map<List<ConfiguracaoSistemaDb>, List<ConfiguracaoSistema>>(base.All().ToList<ConfiguracaoSistemaDb>());
+ }
+
+ 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>((ConfiguracaoSistemaDb x) => (int)x.Configuracao == (int)configuracao);
+ return ApplicationMapper.Mapper.Map<ConfiguracaoSistemaDb, ConfiguracaoSistema>(configuracaoSistemaDb);
+ }
+
+ public ConfiguracaoSistema Merge(ConfiguracaoSistema configuracao)
+ {
+ ConfiguracaoSistemaDb configuracaoSistemaDb = ApplicationMapper.Mapper.Map<ConfiguracaoSistema, ConfiguracaoSistemaDb>(configuracao);
+ base.Merge(configuracaoSistemaDb);
+ return ApplicationMapper.Mapper.Map<ConfiguracaoSistemaDb, ConfiguracaoSistema>(configuracaoSistemaDb);
+ }
+
+ public ConfiguracaoSistema SaveOrUpdate(ConfiguracaoSistema configuracao)
+ {
+ ConfiguracaoSistemaDb configuracaoSistemaDb = ApplicationMapper.Mapper.Map<ConfiguracaoSistema, ConfiguracaoSistemaDb>(configuracao);
+ this.SaveOrUpdate(configuracaoSistemaDb);
+ return ApplicationMapper.Mapper.Map<ConfiguracaoSistemaDb, ConfiguracaoSistema>(configuracaoSistemaDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs
new file mode 100644
index 0000000..c909e73
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ConsorcioRepository.cs
@@ -0,0 +1,66 @@
+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<ConsorcioDb>, IConsorcioRepository, IGenericRepository<ConsorcioDb>
+ {
+ 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<long> ids)
+ {
+ List<ConsorcioDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Item.Id)
+ select x).ToList<ConsorcioDb>();
+ base.DeleteRange(list);
+ }
+
+ public Consorcio Find(long id)
+ {
+ ConsorcioDb consorcioDb = base.All().FirstOrDefault<ConsorcioDb>((ConsorcioDb x) => x.Item.Id == id) ?? new ConsorcioDb();
+ return ApplicationMapper.Mapper.Map<ConsorcioDb, Consorcio>(consorcioDb);
+ }
+
+ public Consorcio FindById(long id)
+ {
+ ConsorcioDb consorcioDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ConsorcioDb, Consorcio>(consorcioDb);
+ }
+
+ public Consorcio Merge(Consorcio consorcio)
+ {
+ ConsorcioDb consorcioDb = ApplicationMapper.Mapper.Map<Consorcio, ConsorcioDb>(consorcio);
+ base.Merge(consorcioDb);
+ return ApplicationMapper.Mapper.Map<ConsorcioDb, Consorcio>(consorcioDb);
+ }
+
+ public Consorcio SaveOrUpdate(Consorcio consorcio)
+ {
+ ConsorcioDb consorcioDb = ApplicationMapper.Mapper.Map<Consorcio, ConsorcioDb>(consorcio);
+ this.SaveOrUpdate(consorcioDb);
+ return ApplicationMapper.Mapper.Map<ConsorcioDb, Consorcio>(consorcioDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs
new file mode 100644
index 0000000..15ac6ff
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleFinanceiroRepository.cs
@@ -0,0 +1,73 @@
+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<ControleFinanceiroDb>, IControleFinanceiroRepository, IGenericRepository<ControleFinanceiroDb>
+ {
+ 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<LancamentoDb> lancamentoDbs =
+ from x in this._unitOfWork.Query<LancamentoDb>()
+ where x.Controle.Id == id
+ select x;
+ if (lancamentoDbs.Any<LancamentoDb>())
+ {
+ this._unitOfWork.Repository<LancamentoDb>().DeleteRange(lancamentoDbs);
+ }
+ base.Delete(controleFinanceiroDb);
+ }
+
+ public List<ControleFinanceiro> FindByFornecedor(long id)
+ {
+ List<ControleFinanceiroDb> list = (
+ from x in base.All()
+ where x.Fornecedor.Id == id
+ select x).ToList<ControleFinanceiroDb>();
+ return ApplicationMapper.Mapper.Map<List<ControleFinanceiroDb>, List<ControleFinanceiro>>(list);
+ }
+
+ public ControleFinanceiro FindById(long id)
+ {
+ ControleFinanceiroDb controleFinanceiroDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ControleFinanceiroDb, ControleFinanceiro>(controleFinanceiroDb);
+ }
+
+ public ControleFinanceiro Merge(ControleFinanceiro controle)
+ {
+ ControleFinanceiroDb controleFinanceiroDb = ApplicationMapper.Mapper.Map<ControleFinanceiro, ControleFinanceiroDb>(controle);
+ base.Merge(controleFinanceiroDb);
+ return ApplicationMapper.Mapper.Map<ControleFinanceiroDb, ControleFinanceiro>(controleFinanceiroDb);
+ }
+
+ public ControleFinanceiro SaveOrUpdate(ControleFinanceiro controle)
+ {
+ ControleFinanceiroDb controleFinanceiroDb = ApplicationMapper.Mapper.Map<ControleFinanceiro, ControleFinanceiroDb>(controle);
+ this.SaveOrUpdate(controleFinanceiroDb);
+ return ApplicationMapper.Mapper.Map<ControleFinanceiroDb, ControleFinanceiro>(controleFinanceiroDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs
new file mode 100644
index 0000000..6f06aaf
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleRepository.cs
@@ -0,0 +1,68 @@
+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<ControleDb>, IControleRepository, IGenericRepository<ControleDb>
+ {
+ 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<long> FindByCustomerId(long id)
+ {
+ return
+ from c in (
+ from c in base.All()
+ where c.Cliente.Id == id
+ select c).ToList<ControleDb>()
+ select c.Id;
+ }
+
+ public Controle FindById(long id)
+ {
+ ControleDb controleDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ControleDb, Controle>(controleDb);
+ }
+
+ public Controle Merge(Controle controle)
+ {
+ ControleDb controleDb = ApplicationMapper.Mapper.Map<Controle, ControleDb>(controle);
+ base.Merge(controleDb);
+ return ApplicationMapper.Mapper.Map<ControleDb, Controle>(controleDb);
+ }
+
+ public Controle SaveOrUpdate(Controle controle)
+ {
+ ControleDb controleDb = ApplicationMapper.Mapper.Map<Controle, ControleDb>(controle);
+ this.SaveOrUpdate(controleDb);
+ return ApplicationMapper.Mapper.Map<ControleDb, Controle>(controleDb);
+ }
+
+ public IEnumerable<long> SelectDocumentIds(long id)
+ {
+ return
+ from x in base.All().First<ControleDb>((ControleDb c) => c.Id == id).Documentos
+ select x.Id;
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs
new file mode 100644
index 0000000..5d23145
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ControleSinistroRepository.cs
@@ -0,0 +1,161 @@
+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<ControleSinistroDb>, IControleSinistroRepository, IGenericRepository<ControleSinistroDb>
+ {
+ 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<SinistroDb> list = (
+ from s in this._unitOfWork.Query<SinistroDb>()
+ where s.ControleSinistro.Item.Id == id
+ select s).ToList<SinistroDb>();
+ 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<long> ids)
+ {
+ List<ControleSinistroDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Item.Id)
+ select x).ToList<ControleSinistroDb>();
+ if (list == null || list.Count == 0)
+ {
+ return;
+ }
+ base.DeleteRange(list);
+ }
+
+ public bool DocumentoHasSinistro(long id)
+ {
+ return base.All().Any<ControleSinistroDb>((ControleSinistroDb x) => x.Item.Documento.Id == id);
+ }
+
+ public ControleSinistro FindById(long id)
+ {
+ ControleSinistroDb controleSinistroDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ControleSinistroDb, ControleSinistro>(controleSinistroDb);
+ }
+
+ public List<ControleSinistro> FindByIdItem(long id)
+ {
+ List<ControleSinistro> 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<ItemDb, Item>(x.Item)
+ }).ToList<ControleSinistro>();
+ list.ForEach((ControleSinistro x) => x.Sinistros = (new SinistroRepository(this._unitOfWork)).FindByControleId(x.Id));
+ return list;
+ }
+
+ public List<long> HasSinistro(List<long> ids)
+ {
+ List<long> nums = new List<long>();
+ while (ids.Count > 0)
+ {
+ List<long> list = ids.Take<long>(1000).ToList<long>();
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.idcontrole",
+ Valores = list.CriarValor<long>()
+ }
+ };
+ 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, long>((DataRow x) => x.Field<long>("id")).ToList<long>());
+ }
+ ids = (list.Count < 1000 ? new List<long>() : ids.Except<long>(list).ToList<long>());
+ }
+ return nums;
+ }
+
+ public bool HasSinistro(long id)
+ {
+ return base.All().Any<ControleSinistroDb>((ControleSinistroDb x) => x.Item.Documento.Controle.Id == id);
+ }
+
+ public ControleSinistro Merge(ControleSinistro controleSinistro)
+ {
+ ControleSinistroDb controleSinistroDb = ApplicationMapper.Mapper.Map<ControleSinistro, ControleSinistroDb>(controleSinistro);
+ base.Merge(controleSinistroDb);
+ return ApplicationMapper.Mapper.Map<ControleSinistroDb, ControleSinistro>(controleSinistroDb);
+ }
+
+ public ControleSinistro SaveOrUpdate(ControleSinistro controleSinistro)
+ {
+ ControleSinistroDb controleSinistroDb = ApplicationMapper.Mapper.Map<ControleSinistro, ControleSinistroDb>(controleSinistro);
+ this.SaveOrUpdate(controleSinistroDb);
+ return ApplicationMapper.Mapper.Map<ControleSinistroDb, ControleSinistro>(controleSinistroDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs
new file mode 100644
index 0000000..0e7d668
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CredencialRepository.cs
@@ -0,0 +1,75 @@
+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<CredencialDb>, ICredencialRepository, IGenericRepository<CredencialDb>
+ {
+ 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<Credencial> Find(long idEmpresa)
+ {
+ List<CredencialDb> list = (
+ from x in base.All()
+ where x.IdEmpresa == idEmpresa && !x.Excluido
+ select x).ToList<CredencialDb>();
+ return ApplicationMapper.Mapper.Map<List<CredencialDb>, List<Credencial>>(list);
+ }
+
+ public List<Credencial> Find(string filter, long idEmpresa)
+ {
+ CredencialRepository.u003cu003ec__DisplayClass7_0 variable = null;
+ IQueryable<CredencialDb> credencialDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(CredencialDb), "x");
+ List<CredencialDb> list = credencialDbs.Where<CredencialDb>(Expression.Lambda<Func<CredencialDb, bool>>(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<Expression>()), (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<CredencialDb>();
+ return ApplicationMapper.Mapper.Map<List<CredencialDb>, List<Credencial>>(list);
+ }
+
+ public Credencial FindById(long id)
+ {
+ CredencialDb credencialDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<CredencialDb, Credencial>(credencialDb);
+ }
+
+ public Credencial Merge(Credencial credencial)
+ {
+ CredencialDb credencialDb = ApplicationMapper.Mapper.Map<Credencial, CredencialDb>(credencial);
+ base.Merge(credencialDb);
+ return ApplicationMapper.Mapper.Map<CredencialDb, Credencial>(credencialDb);
+ }
+
+ public Credencial SaveOrUpdate(Credencial credencial)
+ {
+ CredencialDb credencialDb = ApplicationMapper.Mapper.Map<Credencial, CredencialDb>(credencial);
+ this.SaveOrUpdate(credencialDb);
+ return ApplicationMapper.Mapper.Map<CredencialDb, Credencial>(credencialDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs
new file mode 100644
index 0000000..3e57d4d
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/CriticaApoliceRepository.cs
@@ -0,0 +1,315 @@
+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<CriticaApoliceDb>, ICriticaApoliceRepository, IGenericRepository<CriticaApoliceDb>
+ {
+ 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<Usuario> BuscarUsuarioCritica(DateTime inicio, DateTime fim, bool criticado = false, long idempresa = 0L)
+ {
+ List<Usuario> 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<Usuario>();
+ }
+ }
+ }
+ return usuarios;
+ List<long> list = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("idusuario")).ToList<long>();
+ return (
+ from x in Auxiliar.Usuarios
+ where list.Contains(x.Id)
+ select x).ToList<Usuario>();
+ }
+
+ public void Delete(long id)
+ {
+ CriticaApoliceDb criticaApoliceDb = base.All().FirstOrDefault<CriticaApoliceDb>((CriticaApoliceDb x) => x.Id == id);
+ if (criticaApoliceDb == null)
+ {
+ return;
+ }
+ base.Delete(criticaApoliceDb);
+ }
+
+ public List<CriticaApolice> Find(long usuario, DateTime inicio, DateTime fim, long vendedorCorretoraId, bool criticado = false, long idempresa = 0L, List<VendedorUsuario> vinculos = null, bool vendedorEmBranco = false, bool vinculoVendedorCritica = false)
+ {
+ Condicao condicao = new Condicao()
+ {
+ Campo = "i.idusuario",
+ Valores = usuario.CriarValor<long>()
+ };
+ Condicao condicao1 = new Condicao()
+ {
+ Campo = "i.critica",
+ Valores = (criticado ? "1".CriarValor<string>() : "0".CriarValor<string>())
+ };
+ Condicao condicao2 = new Condicao()
+ {
+ Campo = "c.idempresa",
+ Valores = idempresa.CriarValor<long>()
+ };
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "CAST(i.dataimportacao AS DATE)",
+ Valores = inicio.CriarValor<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ },
+ new Condicao()
+ {
+ Campo = "CAST(i.dataimportacao AS DATE)",
+ Valores = fim.CriarValor<DateTime>(),
+ Operador = Operador.MenorEIgual
+ },
+ new Condicao()
+ {
+ Campo = " d.excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = " d.excluido",
+ Valores = "1".CriarValor<string>(),
+ 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<long>() : (
+ from x in vinculos
+ select x.Vendedor.Id).ToList<long>().CriarValor<long>()),
+ 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<CriticaApolice> Find(DateTime inicio, DateTime fim, long idempresa = 0L)
+ {
+ Condicao condicao = new Condicao()
+ {
+ Campo = "c.idempresa",
+ Valores = idempresa.CriarValor<long>()
+ };
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "CAST(i.dataimportacao AS DATE)",
+ Valores = inicio.CriarValor<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ },
+ new Condicao()
+ {
+ Campo = "CAST(i.dataimportacao AS DATE)",
+ Valores = fim.CriarValor<DateTime>(),
+ Operador = Operador.MenorEIgual
+ },
+ new Condicao()
+ {
+ Campo = " d.excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = " d.excluido",
+ Valores = "1".CriarValor<string>(),
+ 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<CriticaApolice> Find(long id)
+ {
+ List<CriticaApoliceDb> list = this._unitOfWork.Session.CreateQuery(string.Format("from CriticaApoliceDb WHERE iddocumento = {0} AND (Critica IS NULL OR Critica != '1')", id)).List<CriticaApoliceDb>().ToList<CriticaApoliceDb>();
+ return ApplicationMapper.Mapper.Map<List<CriticaApoliceDb>, List<CriticaApolice>>(list);
+ }
+
+ public CriticaApolice FindByApolice(long id)
+ {
+ CriticaApoliceDb criticaApoliceDb = base.All().FirstOrDefault<CriticaApoliceDb>((CriticaApoliceDb x) => x.Documento.Id == id);
+ return ApplicationMapper.Mapper.Map<CriticaApoliceDb, CriticaApolice>(criticaApoliceDb);
+ }
+
+ public CriticaApolice FindById(long id)
+ {
+ CriticaApoliceDb criticaApoliceDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<CriticaApoliceDb, CriticaApolice>(criticaApoliceDb);
+ }
+
+ public List<CriticaApolice> FindDuo(long id, DateTime vigencia)
+ {
+ return this.Select((new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = " c.idcliente",
+ Valores = id.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = " CAST(d.vigencia1 AS DATE)",
+ Valores = vigencia.CriarValor<DateTime>(),
+ Operador = Operador.Igual
+ },
+ new Condicao()
+ {
+ Campo = " i.critica",
+ Valores = 1.CriarValor<int>(),
+ Operador = Operador.Diferente
+ },
+ new Condicao()
+ {
+ Campo = " d.excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = " d.excluido",
+ Valores = "1".CriarValor<string>(),
+ Grupo = 1,
+ Operador = Operador.Diferente,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = " c.idramo",
+ Valores = 5.CriarValor<int>(),
+ Grupo = 2,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = " c.idramo",
+ Valores = 1.CriarValor<int>(),
+ 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<CriticaApolice> FindImport(long id)
+ {
+ List<CriticaApoliceDb> list = this._unitOfWork.Session.CreateQuery(string.Format("from CriticaApoliceDb WHERE iddocumento = {0}", id)).List<CriticaApoliceDb>().ToList<CriticaApoliceDb>();
+ return ApplicationMapper.Mapper.Map<List<CriticaApoliceDb>, List<CriticaApolice>>(list);
+ }
+
+ public CriticaApolice Merge(CriticaApolice documento)
+ {
+ CriticaApoliceDb criticaApoliceDb = ApplicationMapper.Mapper.Map<CriticaApolice, CriticaApoliceDb>(documento);
+ base.Merge(criticaApoliceDb);
+ return ApplicationMapper.Mapper.Map<CriticaApoliceDb, CriticaApolice>(criticaApoliceDb);
+ }
+
+ public CriticaApolice SaveOrUpdate(CriticaApolice documento)
+ {
+ CriticaApoliceDb criticaApoliceDb = ApplicationMapper.Mapper.Map<CriticaApolice, CriticaApoliceDb>(documento);
+ this.SaveOrUpdate(criticaApoliceDb);
+ return ApplicationMapper.Mapper.Map<CriticaApoliceDb, CriticaApolice>(criticaApoliceDb);
+ }
+
+ private List<CriticaApolice> Select(SqlQueryCondition condition, string command)
+ {
+ return this._unitOfWork.Select(condition, command, "").MapImportacao();
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs
new file mode 100644
index 0000000..54af174
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DetalheExtratoRepository.cs
@@ -0,0 +1,99 @@
+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<DetalheExtratoDb>, IDetalheExtratoRepository, IGenericRepository<DetalheExtratoDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public DetalheExtratoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public bool Completo(long id)
+ {
+ List<StatusParcela> statusParcelas = new List<StatusParcela>()
+ {
+ 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>((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<DetalheExtrato> Find(long id)
+ {
+ List<DetalheExtratoDb> list = (
+ from x in base.All()
+ where x.Extrato.Id == id
+ select x).ToList<DetalheExtratoDb>();
+ return ApplicationMapper.Mapper.Map<List<DetalheExtratoDb>, List<DetalheExtrato>>(list);
+ }
+
+ public DetalheExtrato FindById(long id)
+ {
+ DetalheExtratoDb detalheExtratoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<DetalheExtratoDb, DetalheExtrato>(detalheExtratoDb);
+ }
+
+ public List<DetalheExtrato> FindByLongId(long? id)
+ {
+ List<DetalheExtratoDb> list = (
+ from x in base.All()
+ where (long?)x.Extrato.Id == id
+ select x).ToList<DetalheExtratoDb>();
+ return ApplicationMapper.Mapper.Map<List<DetalheExtratoDb>, List<DetalheExtrato>>(list);
+ }
+
+ public DetalheExtrato FindByParcelaId(long id)
+ {
+ DetalheExtratoDb detalheExtratoDb = base.All().FirstOrDefault<DetalheExtratoDb>((DetalheExtratoDb x) => x.Parcela == (long?)id);
+ return ApplicationMapper.Mapper.Map<DetalheExtratoDb, DetalheExtrato>(detalheExtratoDb);
+ }
+
+ public DetalheExtrato Merge(DetalheExtrato parcela)
+ {
+ DetalheExtratoDb detalheExtratoDb = ApplicationMapper.Mapper.Map<DetalheExtrato, DetalheExtratoDb>(parcela);
+ base.Merge(detalheExtratoDb);
+ return ApplicationMapper.Mapper.Map<DetalheExtratoDb, DetalheExtrato>(detalheExtratoDb);
+ }
+
+ public DetalheExtrato SaveOrUpdate(DetalheExtrato parcela)
+ {
+ DetalheExtratoDb detalheExtratoDb = ApplicationMapper.Mapper.Map<DetalheExtrato, DetalheExtratoDb>(parcela);
+ this.SaveOrUpdate(detalheExtratoDb);
+ return ApplicationMapper.Mapper.Map<DetalheExtratoDb, DetalheExtrato>(detalheExtratoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DocumentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DocumentoRepository.cs
new file mode 100644
index 0000000..7414c45
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/DocumentoRepository.cs
@@ -0,0 +1,5095 @@
+using AutoMapper;
+using Gestor.Common.Helpers;
+using Gestor.Infrastructure.Entities.Generic;
+using Gestor.Infrastructure.Entities.Seguros;
+using Gestor.Infrastructure.Helpers;
+using Gestor.Infrastructure.Mappers;
+using Gestor.Infrastructure.Repository.Generic;
+using Gestor.Infrastructure.Repository.Interface;
+using Gestor.Infrastructure.UnitOfWork.Generic;
+using Gestor.Model.Common;
+using Gestor.Model.Domain.Aggilizador;
+using Gestor.Model.Domain.Common;
+using Gestor.Model.Domain.Generic;
+using Gestor.Model.Domain.Relatorios;
+using Gestor.Model.Domain.Relatorios.Fechamento;
+using Gestor.Model.Domain.Seguros;
+using Gestor.Model.License;
+using Gestor.Model.Validation;
+using NHibernate;
+using NHibernate.Connection;
+using NHibernate.Impl;
+using System;
+using System.Collections;
+using System.Collections.Generic;
+using System.Collections.ObjectModel;
+using System.Data;
+using System.Data.Common;
+using System.Data.SqlClient;
+using System.Diagnostics;
+using System.Linq;
+using System.Linq.Expressions;
+using System.Runtime.CompilerServices;
+using System.Threading.Tasks;
+
+namespace Gestor.Infrastructure.Repository.Logic
+{
+ public class DocumentoRepository : GenericRepository<DocumentoDb>, IDocumentoRepository, IGenericRepository<DocumentoDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ private const string _commandoDocumento = "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ";
+
+ private const string _comandoVendedores = "SELECT DISTINCT vp.IDPARCELA, vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor, p.idsubtipo FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento LEFT OUTER JOIN parcela p on p.idparcela = vp.idparcela WHERE ";
+
+ private const string _comandoArquivo = "SELECT DISTINCT a.idnewarquivodigital, a.descricao, ISNULL(s.Status ,0) as Status, s.assinado, s.DocumentoId, s.id, s.UsuarioId, s.Enviado FROM newarquivodigital a LEFT OUTER JOIN ArquivoParaAssinatura s on s.IndiceId = a.idnewarquivodigital WHERE ";
+
+ private const string ComandoEndereco = "SELECT DISTINCT idcliend, cep, cidade, uf as estado, idcliente FROM cliendereco WHERE (ORDEM = '1' OR PADRAO = '1') ";
+
+ private const string ComandoTelefone = "SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 ";
+
+ private const string ComandoEmail = "SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') ";
+
+ public DocumentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public bool AtualizarNumero(long id, string numero, string endosso, int tipoDocumento)
+ {
+ DocumentoDb documentoDb = base.FindEntityById(id);
+ if (documentoDb == null)
+ {
+ return false;
+ }
+ if (!documentoDb.Emissao.HasValue)
+ {
+ return true;
+ }
+ if (tipoDocumento == 0)
+ {
+ documentoDb.Apolice = numero;
+ }
+ else if (tipoDocumento == 1)
+ {
+ documentoDb.Apolice = numero;
+ documentoDb.Endosso = endosso;
+ }
+ base.Merge(documentoDb);
+ return true;
+ }
+
+ public List<Documento> Auditoria(Filtros filtro)
+ {
+ List<Documento> documentos;
+ object connection;
+ string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join<long>(",",
+ from v in filtro.Status
+ select v), ")"));
+ string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join<long>(",",
+ from v in filtro.Negocio
+ select v), ")"));
+ string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",",
+ from v in filtro.Seguradoras
+ select v), ")"));
+ string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",",
+ from v in filtro.Ramos
+ select v), ")"));
+ string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",",
+ from v in filtro.Produtos
+ select v), ")"));
+ string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",",
+ from v in filtro.Vendedores
+ select v), ")"));
+ string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join<long>(",",
+ from v in filtro.TipoVendedor
+ select v), ")"));
+ string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",",
+ from v in filtro.Estipulantes
+ select v), ")"));
+ string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa));
+ DataTable dataTable = new DataTable();
+ DataTable dataTable1 = new DataTable();
+ DataTable dataTable2 = new DataTable();
+ DataTable dataTable3 = new DataTable();
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 15000;
+ Auxiliar.CriarAuxiliar(sqlCommand, false);
+ string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.aditamento as endosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.datacontrole, d.idstatus, d.pasta, d.n_parc, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente ", str6, " WHERE (d.excluido IS NULL OR d.excluido = 0) ");
+ string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 ";
+ string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 ";
+ string str12 = "SELECT DISTINCT vp.idparcela, vp.iddocumento as id, ISNULL(vp.vlrcomiss, 0) as recebida, vp.idsubtipo, vp.datarec as recebimento FROM parcela vp WHERE 1=1 ";
+ string str13 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL ";
+ sqlCommand.CommandText = string.Format("{0} {1} AND d.vigencia1 >= '{2:yyyy-MM-dd}' AND d.vigencia1 <= '{3:yyyy-MM-dd}' AND d.tiporecebimento = 1 {4} {5} {6} {7} {8} {9} {10}", new object[] { str9, str8, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5 });
+ using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
+ {
+ sqlDataAdapter.SelectCommand = sqlCommand;
+ sqlDataAdapter.Fill(dataTable);
+ }
+ if (dataTable.Rows.Count != 0)
+ {
+ string str14 = string.Concat(" AND vp.iddocumento IN (", string.Join<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
+ sqlCommand.CommandText = string.Concat(str12, (filtro.ParcelasEspeciais.Any<FiltroTipoParcela>((FiltroTipoParcela x) => x.Selecionado) ? string.Concat(" AND vp.idsubtipo IN (1,", string.Join<int>(",",
+ from x in filtro.ParcelasEspeciais
+ where x.Selecionado
+ select x into v
+ select (int)v.Tipo), ")") : " AND vp.idsubtipo = 1 "), str14);
+ using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter())
+ {
+ sqlDataAdapter1.SelectCommand = sqlCommand;
+ sqlDataAdapter1.Fill(dataTable1);
+ }
+ string str15 = (dataTable.AsEnumerable().Any<DataRow>((DataRow x) => x.Field<object>("idvendedor") == null) ? string.Concat(" AND d.idcontrole IN (", string.Join<long>(",", dataTable.AsEnumerable().Where<DataRow>((DataRow x) => x.Field<object>("idvendedor") == null).Select<DataRow, long>((DataRow v) => v.Field<long>("idcontrole"))), ")") : "");
+ DataTable dataTable4 = new DataTable();
+ sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str15, " ", str5 });
+ using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter())
+ {
+ sqlDataAdapter2.SelectCommand = sqlCommand;
+ sqlDataAdapter2.Fill(dataTable4);
+ }
+ List<DataRow> dataRows3 = new List<DataRow>();
+ foreach (DataRow row in dataTable.Rows)
+ {
+ string str16 = string.Format("id = {0}", row["id"]);
+ DataRow[] dataRowArray = dataTable1.Select(str16);
+ decimal num = Math.Round(((row.Field<decimal>("liquido") + (row.Field<string>("adinacomiss") == "1" ? row.Field<decimal>("liquido") : decimal.Zero)) * row.Field<decimal>("comissao")) * new decimal(1, 0, 0, false, 2), 2);
+ decimal num1 = ((IEnumerable<DataRow>)dataRowArray).Sum<DataRow>((DataRow x) => x.Field<decimal>("recebida"));
+ decimal? tolerancia = Auxiliar.Seguradoras.First<Seguradora>((Seguradora p) => p.Id == row.Field<long>("idseguradora")).Tolerancia;
+ if ((num - num1) > tolerancia.GetValueOrDefault())
+ {
+ if (!string.IsNullOrEmpty(row["idvendedor"].ToString()))
+ {
+ continue;
+ }
+ string str17 = string.Format("idcontrole = {0}", row["idcontrole"]);
+ DataRow[] dataRowArray1 = dataTable4.Select(str17);
+ if (dataRowArray1.Length == 0)
+ {
+ continue;
+ }
+ row["idvendedor"] = dataRowArray1[0][1];
+ }
+ else
+ {
+ dataRows3.Add(row);
+ }
+ }
+ dataRows3.ForEach((DataRow x) => dataTable.Rows.Remove(x));
+ if (dataTable.Rows.Count != 0)
+ {
+ str14 = string.Concat(" AND vp.iddocumento IN (", string.Join<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
+ sqlCommand.CommandText = string.Concat(str11, " ", str14);
+ using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter())
+ {
+ sqlDataAdapter3.SelectCommand = sqlCommand;
+ sqlDataAdapter3.Fill(dataTable2);
+ }
+ string str18 = string.Concat(" AND d.idcontrole IN (", string.Join<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("idcontrole"))), ")");
+ sqlCommand.CommandText = string.Concat(str13, " ", str18);
+ using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter())
+ {
+ sqlDataAdapter4.SelectCommand = sqlCommand;
+ sqlDataAdapter4.Fill(dataTable3);
+ goto Label0;
+ }
+ }
+ else
+ {
+ documentos = new List<Documento>();
+ }
+ }
+ else
+ {
+ documentos = new List<Documento>();
+ }
+ }
+ }
+ return documentos;
+ Label0:
+ return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, Documento>((DataRow x) => {
+ Func<DataRow, bool> func2 = null;
+ Documento documento = new Documento()
+ {
+ Id = x.Field<long>("id"),
+ Controle = new Controle()
+ {
+ IdEmpresa = x.Field<long>("idempresa"),
+ Cliente = new Cliente()
+ {
+ Id = x.Field<long>("idcliente"),
+ Nome = x.Field<string>("cliente"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ Pasta = x.Field<string>("pastacliente"),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
+ },
+ Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null),
+ Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
+ Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Gestor.Model.Domain.Seguros.Produto>((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field<long>("idproduto")) : null),
+ AssistenciaId = x.Field<string>("AssistenciaId")
+ },
+ TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela),
+ AdicionalComiss = x.Field<string>("adinacomiss") == "1",
+ Apolice = x.Field<string>("apolice"),
+ Endosso = x.Field<string>("endosso"),
+ Comissao = x.Field<decimal>("comissao"),
+ Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString()))),
+ PremioLiquido = x.Field<decimal>("liquido"),
+ PremioTotal = x.Field<decimal>("total"),
+ PremioAdicional = x.Field<decimal>("adicional"),
+ Vigencia2 = x.Field<DateTime?>("vigenciafinal")
+ };
+ DateTime? nullable = x.Field<DateTime?>("vigenciainicial");
+ documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ documento.VendedorPrincipal = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")) : null);
+ documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
+ documento.Vendedores = Auxiliar.Vendedores.Where<Vendedor>((Vendedor v) => {
+ List<DataRow> list = dataTable2.AsEnumerable().ToList<DataRow>();
+ Func<DataRow, bool> u003cu003e9_32 = func2;
+ if (u003cu003e9_32 == null)
+ {
+ Func<DataRow, bool> func = (DataRow d) => d.Field<long>("id") == x.Field<long>("id");
+ Func<DataRow, bool> func1 = func;
+ func2 = func;
+ u003cu003e9_32 = func1;
+ }
+ IEnumerable<DataRow> dataRows = list.Where<DataRow>(u003cu003e9_32);
+ Func<DataRow, long> u003cu003e9_4033 = DocumentoRepository.u003cu003ec.u003cu003e9__40_33;
+ if (u003cu003e9_4033 == null)
+ {
+ u003cu003e9_4033 = (DataRow d) => d.Field<long>("idvendedor");
+ DocumentoRepository.u003cu003ec.u003cu003e9__40_33 = u003cu003e9_4033;
+ }
+ return dataRows.Select<DataRow, long>(u003cu003e9_4033).ToList<long>().Contains(v.Id);
+ }).ToList<Vendedor>();
+ documento.Tipo = x.Field<int>("tipo");
+ IEnumerable<DataRow> dataRows1 =
+ from p in dataTable1.AsEnumerable().ToList<DataRow>()
+ where p.Field<long>("id") == x.Field<long>("id")
+ select p;
+ Func<DataRow, Parcela> u003cu003e9_4025 = DocumentoRepository.u003cu003ec.u003cu003e9__40_25;
+ if (u003cu003e9_4025 == null)
+ {
+ u003cu003e9_4025 = (DataRow p) => new Parcela()
+ {
+ Id = p.Field<long>("idparcela"),
+ ValorComissao = p.Field<decimal>("recebida"),
+ DataRecebimento = p.Field<DateTime?>("recebimento"),
+ SubTipo = (p.Field<object>("idsubtipo") == null ? SubTipo.ParcelaNormal : (SubTipo)Enum.Parse(typeof(SubTipo), p.Field<object>("idsubtipo").ToString()))
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__40_25 = u003cu003e9_4025;
+ }
+ documento.Parcelas = new ObservableCollection<Parcela>(dataRows1.Select<DataRow, Parcela>(u003cu003e9_4025).ToList<Parcela>());
+ documento.DataControle = x.Field<DateTime?>("datacontrole");
+ documento.Status = (x.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault<Status>((Status p) => p.Id == x.Field<long>("idstatus")) : null);
+ IEnumerable<DataRow> dataRows2 =
+ from i in dataTable3.AsEnumerable().ToList<DataRow>()
+ where i.Field<long>("idcontrole") == x.Field<long>("idcontrole")
+ select i;
+ Func<DataRow, Item> u003cu003e9_4028 = DocumentoRepository.u003cu003ec.u003cu003e9__40_28;
+ if (u003cu003e9_4028 == null)
+ {
+ u003cu003e9_4028 = (DataRow i) => new Item()
+ {
+ Id = i.Field<long>("iditem"),
+ Descricao = i.Field<string>("descricao")
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__40_28 = u003cu003e9_4028;
+ }
+ documento.ItensAtivo = new List<Item>(dataRows2.Select<DataRow, Item>(u003cu003e9_4028).ToList<Item>());
+ documento.Pasta = x.Field<string>("Pasta");
+ documento.NumeroParcelas = (x.Field<object>("n_parc") != null ? decimal.Parse(x.Field<object>("n_parc").ToString()) : decimal.Zero);
+ return documento;
+ }).ToList<Documento>();
+ }
+
+ private async Task<List<Documento>> BuscaDocumentosPorCondicao(Filtros filtro, List<Condicao> condicao, bool buscaAssinaturas)
+ {
+ NegocioCorretora fieldValue;
+ Predicate<Estipulante> predicate;
+ bool flag;
+ object connection;
+ bool count;
+ string str;
+ object vendedor;
+ bool count1;
+ bool flag1;
+ List<Item> itensAtivo;
+ object produto;
+ object obj;
+ object statu;
+ object banco;
+ List<StatusDocumentoAssinado> statusDocumentoAssinados;
+ bool flag2;
+ StatusAssinatura statusAssinatura;
+ NegocioCorretora negocioCorretora;
+ bool count2;
+ bool count3;
+ Documento vendedorParcelas;
+ Documento fieldValue1;
+ Predicate<Estipulante> predicate1 = null;
+ Predicate<Estipulante> predicate2 = null;
+ Predicate<Estipulante> predicate3 = null;
+ Predicate<Estipulante> predicate4 = null;
+ Predicate<Estipulante> predicate5 = null;
+ List<Documento> documentos = new List<Documento>();
+ SqlQueryCondition sqlQueryCondition = condicao.CreateParameters(0);
+ Vendedor vendedor1 = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor v) => {
+ if (v.IdEmpresa != (filtro.IdEmpresa == 0 ? (long)1 : filtro.IdEmpresa))
+ {
+ return false;
+ }
+ return v.Corretora;
+ });
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ bool flag3 = await this.ExisteTabelasAssinatura();
+ bool flag4 = flag3;
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 1000;
+ string str1 = "SELECT d.IDDOCUMENTO IdDocumento,c.IDCONTROLE IdControle,c.IDEMPRESA IdEmpresa,c.IDCLIENTE IdCliente,clie.NOME NomeCliente,clie.CGCCPF DocumentoCliente,clie.PASTA PastaCliente,clie.MalaDireta MalaDireta,cm.idclimail IdEmail,cm.email,ct.idclitelefone IdTelefone,ct.ddd Prefixo,ct.fone Numero,c.IDRAMO IdRamo,r.NOME NomeRamo,c.IDCIASEG IdCiaSeg,cia.NOME NomeCia,cia.NomeSocial NomeSocialCia,c.IDPRODUTO IdProduto,pr.NOME NomeProduto,d.idestipulante IdEstipulante, d.idestipulante2 IdEstipulante2, d.idestipulante3 IdEstipulante3, d.idestipulante4 IdEstipulante4, d.idestipulante5 IdEstipulante5, e.nome NomeEstipulante,d.idstatus IdStatus,s.NOME NomeStatus,vp.idtipovendedor IdTipoVendedor,vp.VREP PorcentagemRepasse,vp.idvendedor IdVendedor,v.NOME NomeVendedor,tv.DESCRICAO DescricaoTipovendedor,d.PROPOSTA Proposta,d.CONTRATO Apolice,d.apoconferida ApoliceConferida,d.PEDADIT PropostaEndosso,d.ADITAMENTO Endosso,d.ADINACOMIS AdicionalComissao,d.COM01 Comissao,d.idnegocio Negocio,d.NegocioCorretora NegocioCorretora,d.tiporecebimento TipoRecebimento,d.TIPO Tipo,d.PR_LIQ PremioLiquido,d.PR_TOTAL PremioTotal,d.PR_ADIC PremioAdicional,d.N_PARC NumeroParcelas,d.VIGENCIA1 VigenciaInicial,d.VIGENCIA2 VigenciaFinal,d.EMISSAO Emissao,d.REMESSA Remessa,d.SITUACAO Situacao,d.datacontrole DataControleDocumento,d.propassinada PropostaAssinada,d.PASTA PastaDocumento,d.CRI_DATA DataCriacao,d.idbanco IdBanco,b.NOMEBANCO NomeBanco,d.AGENCIA Agencia,d.conta Conta FROM documento d INNER JOIN controle c ON c.IDCONTROLE = d.IDCONTROLE INNER JOIN cliente clie ON clie.IDCLIENTE = c.IDCLIENTE INNER JOIN ramo r ON r.IDRAMO = c.IDRAMO INNER JOIN ciaseg cia ON cia.IDCIASEG = c.IDCIASEG LEFT JOIN codigobanco b ON b.IDCODIGOBANCO = d.IDBANCO LEFT JOIN produto pr ON pr.IDPRODUTO = c.IDPRODUTO LEFT JOIN estipulante e ON e.idestipulante = d.idestipulante LEFT JOIN status s ON s.idstatus = d.idstatus LEFT JOIN vendedorparcela vp ON vp.IDDOCUMENTO = d.IDDOCUMENTO LEFT JOIN vendedor v ON v.IDVENDEDOR = vp.IDVENDEDOR LEFT JOIN tipovendedor tv on tv.idtipovendedor = vp.idtipovendedor LEFT JOIN clitelefone ct ON ct.IDCLIENTE = c.IDCLIENTE LEFT JOIN parcela p ON p.idparcela = vp.idparcela LEFT JOIN climail cm ON cm.IDCLIENTE = c.IDCLIENTE WHERE ";
+ sqlCommand.CommandText = string.Concat(str1, " ", sqlQueryCondition.Condicao, " ORDER BY d.IDDOCUMENTO,d.IDCONTROLE,vp.idtipovendedor,vp.IDVENDEDOR");
+ sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray());
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ TipoSeguro tipoSeguro = sqlDataReader.GetFieldValue<TipoSeguro>("Situacao", true, true);
+ if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora"))
+ {
+ fieldValue = sqlDataReader.GetFieldValue<NegocioCorretora>("NegocioCorretora", true, true);
+ }
+ else
+ {
+ flag3 = tipoSeguro == TipoSeguro.Renovacao;
+ if (flag3)
+ {
+ flag3 = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio");
+ }
+ negocioCorretora = (!flag3 || !(sqlDataReader.GetFieldValue<string>("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio);
+ fieldValue = negocioCorretora;
+ }
+ NegocioCorretora negocioCorretora1 = fieldValue;
+ List<long> negocio = filtro.Negocio;
+ if (negocio != null)
+ {
+ count = negocio.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (!count || filtro.Negocio.Any<long>((long n) => (int)n == (int)negocioCorretora1))
+ {
+ List<Estipulante> estipulantes = new List<Estipulante>();
+ sqlDataReader.GetFieldValue<long>("idestipulante", true, true);
+ if (sqlDataReader.GetFieldValue<long>("idestipulante", true, true) != 0)
+ {
+ List<Estipulante> estipulantes1 = estipulantes;
+ Estipulante nome = new Estipulante();
+ List<Estipulante> estipulantes2 = Auxiliar.Estipulantes;
+ Predicate<Estipulante> predicate6 = predicate1;
+ if (predicate6 == null)
+ {
+ Predicate<Estipulante> predicate7 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante", true, true);
+ predicate = predicate7;
+ predicate1 = predicate7;
+ predicate6 = predicate;
+ }
+ nome.Nome = estipulantes2.Find(predicate6).Nome;
+ estipulantes1.Add(nome);
+ }
+ sqlDataReader.GetFieldValue<long>("idestipulante2", true, true);
+ if (sqlDataReader.GetFieldValue<long>("idestipulante2", true, true) != 0)
+ {
+ List<Estipulante> estipulantes3 = estipulantes;
+ Estipulante nome1 = new Estipulante();
+ List<Estipulante> estipulantes4 = Auxiliar.Estipulantes;
+ Predicate<Estipulante> predicate8 = predicate2;
+ if (predicate8 == null)
+ {
+ Predicate<Estipulante> predicate9 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante2", true, true);
+ predicate = predicate9;
+ predicate2 = predicate9;
+ predicate8 = predicate;
+ }
+ nome1.Nome = estipulantes4.Find(predicate8).Nome;
+ estipulantes3.Add(nome1);
+ }
+ sqlDataReader.GetFieldValue<long>("idestipulante3", true, true);
+ if (sqlDataReader.GetFieldValue<long>("idestipulante3", true, true) != 0)
+ {
+ List<Estipulante> estipulantes5 = estipulantes;
+ Estipulante estipulante1 = new Estipulante();
+ List<Estipulante> estipulantes6 = Auxiliar.Estipulantes;
+ Predicate<Estipulante> predicate10 = predicate3;
+ if (predicate10 == null)
+ {
+ Predicate<Estipulante> predicate11 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante3", true, true);
+ predicate = predicate11;
+ predicate3 = predicate11;
+ predicate10 = predicate;
+ }
+ estipulante1.Nome = estipulantes6.Find(predicate10).Nome;
+ estipulantes5.Add(estipulante1);
+ }
+ sqlDataReader.GetFieldValue<long>("idestipulante4", true, true);
+ if (sqlDataReader.GetFieldValue<long>("idestipulante4", true, true) != 0)
+ {
+ List<Estipulante> estipulantes7 = estipulantes;
+ Estipulante nome2 = new Estipulante();
+ List<Estipulante> estipulantes8 = Auxiliar.Estipulantes;
+ Predicate<Estipulante> predicate12 = predicate4;
+ if (predicate12 == null)
+ {
+ Predicate<Estipulante> predicate13 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante4", true, true);
+ predicate = predicate13;
+ predicate4 = predicate13;
+ predicate12 = predicate;
+ }
+ nome2.Nome = estipulantes8.Find(predicate12).Nome;
+ estipulantes7.Add(nome2);
+ }
+ sqlDataReader.GetFieldValue<long>("idestipulante5", true, true);
+ if (sqlDataReader.GetFieldValue<long>("idestipulante5", true, true) != 0)
+ {
+ List<Estipulante> estipulantes9 = estipulantes;
+ Estipulante estipulante2 = new Estipulante();
+ List<Estipulante> estipulantes10 = Auxiliar.Estipulantes;
+ Predicate<Estipulante> predicate14 = predicate5;
+ if (predicate14 == null)
+ {
+ Predicate<Estipulante> predicate15 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante5", true, true);
+ predicate = predicate15;
+ predicate5 = predicate15;
+ predicate14 = predicate;
+ }
+ estipulante2.Nome = estipulantes10.Find(predicate14).Nome;
+ estipulantes9.Add(estipulante2);
+ }
+ if (estipulantes.Count > 0)
+ {
+ List<Estipulante> estipulantes11 = estipulantes;
+ str = string.Join(" | ",
+ from estipulante in estipulantes11
+ select estipulante.Nome);
+ }
+ else
+ {
+ str = "";
+ }
+ string str2 = str;
+ long num = sqlDataReader.GetFieldValue<long>("IdDocumento", true, true);
+ vendedorParcelas = documentos.Find((Documento d) => d.Id == num);
+ if (vendedorParcelas == null)
+ {
+ long num1 = sqlDataReader.GetFieldValue<long>("IdControle", true, true);
+ long fieldValue2 = sqlDataReader.GetFieldValue<long>("IdEmpresa", true, true);
+ Documento documento1 = documentos.Find((Documento p) => p.Controle.Id == num1);
+ if (documento1 != null)
+ {
+ itensAtivo = documento1.ItensAtivo;
+ }
+ else
+ {
+ itensAtivo = null;
+ }
+ List<Item> items = itensAtivo;
+ if (items == null)
+ {
+ items = await this.BuscaItemsPorIdControle(num1);
+ }
+ List<Item> items1 = items;
+ fieldValue1 = new Documento()
+ {
+ Id = num
+ };
+ Documento documento2 = fieldValue1;
+ Controle controle = new Controle()
+ {
+ Id = num1,
+ IdEmpresa = fieldValue2
+ };
+ Controle controle1 = controle;
+ Cliente cliente = new Cliente()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdCliente", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("NomeCliente", true, true),
+ Documento = sqlDataReader.GetFieldValue<string>("DocumentoCliente", true, true),
+ Pasta = sqlDataReader.GetFieldValue<string>("PastaCliente", true, true)
+ };
+ bool? fieldValue3 = sqlDataReader.GetFieldValue<bool?>("MalaDireta", true, true);
+ cliente.MalaDireta = new bool?(fieldValue3.GetValueOrDefault(true));
+ ObservableCollection<ClienteTelefone> observableCollection = new ObservableCollection<ClienteTelefone>();
+ ClienteTelefone clienteTelefone = new ClienteTelefone()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdTelefone", true, true),
+ Prefixo = sqlDataReader.GetFieldValue<string>("Prefixo", true, true),
+ Numero = sqlDataReader.GetFieldValue<string>("Numero", true, true)
+ };
+ observableCollection.Add(clienteTelefone);
+ cliente.Telefones = observableCollection;
+ ObservableCollection<ClienteEmail> observableCollection1 = new ObservableCollection<ClienteEmail>();
+ ClienteEmail clienteEmail = new ClienteEmail()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdEMail", true, true),
+ Email = sqlDataReader.GetFieldValue<string>("Email", true, true)
+ };
+ observableCollection1.Add(clienteEmail);
+ cliente.Emails = observableCollection1;
+ controle1.Cliente = cliente;
+ Controle controle2 = controle;
+ Ramo ramo = new Ramo()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdRamo", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("NomeRamo", true, true)
+ };
+ controle2.Ramo = ramo;
+ Controle controle3 = controle;
+ Seguradora seguradora = new Seguradora()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdCiaSeg", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("NomeCia", true, true),
+ NomeSocial = sqlDataReader.GetFieldValue<string>("NomeSocialCia", true, true)
+ };
+ controle3.Seguradora = seguradora;
+ Controle controle4 = controle;
+ flag3 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdProduto");
+ Controle controle5 = controle4;
+ if (flag3)
+ {
+ produto = null;
+ }
+ else
+ {
+ produto = new Gestor.Model.Domain.Seguros.Produto();
+ ((DomainBase)produto).Id = sqlDataReader.GetFieldValue<long>("IdProduto", true, true);
+ ((Gestor.Model.Domain.Seguros.Produto)produto).Nome = sqlDataReader.GetFieldValue<string>("NomeProduto", true, true);
+ }
+ controle5.Produto = (Gestor.Model.Domain.Seguros.Produto)produto;
+ documento2.Controle = controle;
+ Documento documento3 = fieldValue1;
+ bool flag5 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdEstipulante");
+ Documento documento4 = documento3;
+ if (flag5)
+ {
+ obj = null;
+ }
+ else
+ {
+ obj = new Estipulante();
+ ((DomainBase)obj).Id = sqlDataReader.GetFieldValue<long>("IdEstipulante", true, true);
+ ((Estipulante)obj).Nome = sqlDataReader.GetFieldValue<string>("NomeEstipulante", true, true);
+ }
+ documento4.Estipulante1 = (Estipulante)obj;
+ fieldValue1.Estipulantes = str2;
+ Documento documento5 = fieldValue1;
+ bool flag6 = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdStatus");
+ Documento documento6 = documento5;
+ if (flag6)
+ {
+ statu = null;
+ }
+ else
+ {
+ statu = new Status();
+ ((DomainBase)statu).Id = sqlDataReader.GetFieldValue<long>("IdStatus", true, true);
+ ((Status)statu).Nome = sqlDataReader.GetFieldValue<string>("NomeStatus", true, true);
+ }
+ documento6.Status = (Status)statu;
+ fieldValue1.TipoRecebimento = new TipoRecebimento?(sqlDataReader.GetFieldValue<TipoRecebimento>("TipoRecebimento", true, true));
+ fieldValue1.Tipo = sqlDataReader.GetFieldValue<int>("Tipo", true, true);
+ fieldValue1.NegocioCorretora = new NegocioCorretora?(negocioCorretora1);
+ fieldValue1.Situacao = tipoSeguro;
+ Documento valueOrDefault = fieldValue1;
+ fieldValue3 = sqlDataReader.GetFieldValue<bool?>("ApoliceConferida", true, true);
+ valueOrDefault.ApoliceConferida = fieldValue3.GetValueOrDefault();
+ Documento valueOrDefault1 = fieldValue1;
+ fieldValue3 = sqlDataReader.GetFieldValue<bool?>("PropostaAssinada", true, true);
+ valueOrDefault1.PropostaAssinada = fieldValue3.GetValueOrDefault();
+ fieldValue1.Proposta = sqlDataReader.GetFieldValue<string>("Proposta", true, true);
+ fieldValue1.Apolice = sqlDataReader.GetFieldValue<string>("Apolice", true, true);
+ fieldValue1.PropostaEndosso = sqlDataReader.GetFieldValue<string>("PropostaEndosso", true, true);
+ fieldValue1.Endosso = sqlDataReader.GetFieldValue<string>("Endosso", true, true);
+ fieldValue1.Comissao = sqlDataReader.GetFieldValue<decimal>("Comissao", true, true);
+ fieldValue1.PremioLiquido = sqlDataReader.GetFieldValue<decimal>("PremioLiquido", true, true);
+ Documento valueOrDefault2 = fieldValue1;
+ fieldValue3 = sqlDataReader.GetFieldValue<bool?>("AdicionalComissao", true, true);
+ valueOrDefault2.AdicionalComiss = fieldValue3.GetValueOrDefault();
+ fieldValue1.PremioAdicional = sqlDataReader.GetFieldValue<decimal>("PremioAdicional", true, true);
+ fieldValue1.PremioTotal = sqlDataReader.GetFieldValue<decimal>("PremioTotal", true, true);
+ fieldValue1.NumeroParcelas = sqlDataReader.GetFieldValue<int>("NumeroParcelas", true, true);
+ fieldValue1.Vigencia1 = sqlDataReader.GetFieldValue<DateTime>("VigenciaInicial", true, true);
+ fieldValue1.Vigencia2 = sqlDataReader.GetFieldValue<DateTime?>("VigenciaFinal", true, true);
+ fieldValue1.Emissao = sqlDataReader.GetFieldValue<DateTime?>("Emissao", true, true);
+ fieldValue1.Remessa = sqlDataReader.GetFieldValue<DateTime?>("Remessa", true, true);
+ fieldValue1.DataControle = sqlDataReader.GetFieldValue<DateTime?>("DataControleDocumento", true, true);
+ fieldValue1.DataCriacao = sqlDataReader.GetFieldValue<DateTime?>("DataCriacao", true, true);
+ fieldValue1.Pasta = sqlDataReader.GetFieldValue<string>("PastaDocumento", true, true);
+ Documento documento7 = fieldValue1;
+ flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdBanco");
+ Documento documento8 = documento7;
+ if (flag)
+ {
+ banco = null;
+ }
+ else
+ {
+ banco = new Banco();
+ ((Banco)banco).Id = sqlDataReader.GetFieldValue<int>("IdBanco", true, true);
+ ((Banco)banco).Nome = sqlDataReader.GetFieldValue<string>("NomeBanco", true, true);
+ }
+ documento8.Banco = (Banco)banco;
+ fieldValue1.Agencia = sqlDataReader.GetFieldValue<string>("Agencia", true, true);
+ fieldValue1.Conta = sqlDataReader.GetFieldValue<string>("Conta", true, true);
+ fieldValue1.ItensAtivo = items1;
+ vendedorParcelas = fieldValue1;
+ documento2 = null;
+ controle4 = null;
+ controle = null;
+ documento3 = null;
+ documento5 = null;
+ documento7 = null;
+ fieldValue1 = null;
+ if (flag4 & buscaAssinaturas)
+ {
+ List<StatusDocumentoAssinado> statusDocumentoAssinados1 = await this.BuscaStatusAssinadosPorIdDocumento(vendedorParcelas.Id);
+ string str3 = (vendedorParcelas.Tipo == 0 ? "PROPOSTA" : "PEDIDO DE ENDOSSO");
+ statusDocumentoAssinados1.ForEach((StatusDocumentoAssinado a) => {
+ if (a.Documento.ToUpper() == str3 || a.Documento.ToUpper().Contains(str3))
+ {
+ a.Selecionado = true;
+ }
+ });
+ List<StatusDocumentoAssinado> statusDocumentoAssinados2 = statusDocumentoAssinados1;
+ StatusDocumentoAssinado statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault<StatusDocumentoAssinado>((StatusDocumentoAssinado a) => a.Selecionado);
+ Documento documento9 = vendedorParcelas;
+ if (statusDocumentoAssinados1 == null || statusDocumentoAssinados1.Count <= 0)
+ {
+ statusDocumentoAssinados = null;
+ }
+ else
+ {
+ statusDocumentoAssinados = statusDocumentoAssinados1;
+ }
+ documento9.Assinaturas = statusDocumentoAssinados;
+ Documento documento10 = vendedorParcelas;
+ flag2 = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status == StatusAssinatura.Assinado : false);
+ documento10.AssinadaSiggner = flag2;
+ Documento documento11 = vendedorParcelas;
+ statusAssinatura = (statusDocumentoAssinado != null ? statusDocumentoAssinado.Status : StatusAssinatura.NaoEnviado);
+ documento11.StatusAssinatura = statusAssinatura;
+ }
+ documentos.Add(vendedorParcelas);
+ items1 = null;
+ }
+ if (vendedorParcelas.VendedorPrincipal == null || vendedorParcelas.VendedorPrincipal.Id == vendedor1.Id)
+ {
+ fieldValue1 = vendedorParcelas;
+ flag = await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "IdVendedor");
+ Documento documento12 = fieldValue1;
+ if (flag)
+ {
+ vendedor = null;
+ }
+ else
+ {
+ vendedor = new Vendedor();
+ ((DomainBase)vendedor).Id = sqlDataReader.GetFieldValue<long>("IdVendedor", true, true);
+ ((Vendedor)vendedor).Nome = sqlDataReader.GetFieldValue<string>("NomeVendedor", true, true);
+ }
+ documento12.VendedorPrincipal = (Vendedor)vendedor;
+ fieldValue1 = null;
+ }
+ if (vendedorParcelas.Controle.Cliente.Telefones != null)
+ {
+ long num2 = sqlDataReader.GetFieldValue<long>("IdTelefone", true, true);
+ if (vendedorParcelas.Controle.Cliente.Telefones.FirstOrDefault<ClienteTelefone>((ClienteTelefone t) => t.Id == num2) == null)
+ {
+ ObservableCollection<ClienteTelefone> telefones = vendedorParcelas.Controle.Cliente.Telefones;
+ ClienteTelefone clienteTelefone1 = new ClienteTelefone()
+ {
+ Id = num2,
+ Prefixo = sqlDataReader.GetFieldValue<string>("Prefixo", true, true),
+ Numero = sqlDataReader.GetFieldValue<string>("Numero", true, true)
+ };
+ telefones.Add(clienteTelefone1);
+ }
+ }
+ if (vendedorParcelas.Controle.Cliente.Emails != null)
+ {
+ long num3 = sqlDataReader.GetFieldValue<long>("IdEmail", true, true);
+ if (vendedorParcelas.Controle.Cliente.Emails.FirstOrDefault<ClienteEmail>((ClienteEmail t) => t.Id == num3) == null)
+ {
+ ObservableCollection<ClienteEmail> emails = vendedorParcelas.Controle.Cliente.Emails;
+ ClienteEmail clienteEmail1 = new ClienteEmail()
+ {
+ Id = num3,
+ Email = sqlDataReader.GetFieldValue<string>("Email", true, true)
+ };
+ emails.Add(clienteEmail1);
+ }
+ }
+ List<long> tipoVendedor = filtro.TipoVendedor;
+ if (tipoVendedor != null)
+ {
+ count1 = tipoVendedor.Count > 0;
+ }
+ else
+ {
+ count1 = false;
+ }
+ if (!count1)
+ {
+ List<long> vendedores = filtro.Vendedores;
+ if (vendedores != null)
+ {
+ flag1 = vendedores.Count > 0;
+ }
+ else
+ {
+ flag1 = false;
+ }
+ if (!flag1)
+ {
+ if (vendedorParcelas.Pagamentos == null)
+ {
+ vendedorParcelas.Pagamentos = new List<VendedorParcela>();
+ }
+ long fieldValue4 = sqlDataReader.GetFieldValue<long>("IdTipoVendedor", true, true);
+ long num4 = sqlDataReader.GetFieldValue<long>("IdVendedor", true, true);
+ if (vendedorParcelas.Pagamentos.Find((VendedorParcela vps) => {
+ if (vps.TipoVendedor.Id != fieldValue4)
+ {
+ return false;
+ }
+ return vps.Vendedor.Id == num4;
+ }) == null)
+ {
+ List<VendedorParcela> pagamentos = vendedorParcelas.Pagamentos;
+ VendedorParcela vendedorParcela1 = new VendedorParcela()
+ {
+ PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue<decimal>("PorcentagemRepasse", true, true))
+ };
+ TipoVendedor tipoVendedor1 = new TipoVendedor()
+ {
+ Id = fieldValue4,
+ Descricao = sqlDataReader.GetFieldValue<string>("DescricaoTipovendedor", true, true)
+ };
+ vendedorParcela1.TipoVendedor = tipoVendedor1;
+ Vendedor vendedor2 = new Vendedor()
+ {
+ Id = num4,
+ Nome = sqlDataReader.GetFieldValue<string>("NomeVendedor", true, true)
+ };
+ vendedorParcela1.Vendedor = vendedor2;
+ pagamentos.Add(vendedorParcela1);
+ }
+ }
+ }
+ str2 = null;
+ vendedorParcelas = null;
+ }
+ }
+ }
+ }
+ sqlCommand = null;
+ List<long> nums = filtro.TipoVendedor;
+ if (nums != null)
+ {
+ count2 = nums.Count > 0;
+ }
+ else
+ {
+ count2 = false;
+ }
+ if (!count2)
+ {
+ List<long> vendedores1 = filtro.Vendedores;
+ if (vendedores1 != null)
+ {
+ count3 = vendedores1.Count > 0;
+ }
+ else
+ {
+ count3 = false;
+ }
+ if (!count3)
+ {
+ goto Label0;
+ }
+ }
+ foreach (Documento documento13 in documentos)
+ {
+ vendedorParcelas = documento13;
+ List<VendedorParcela> vendedorParcelas1 = await this.BuscaVendedoresPorIdDocumento(documento13.Id, documento13.Controle.IdEmpresa);
+ vendedorParcelas.Pagamentos = vendedorParcelas1;
+ vendedorParcelas = null;
+ }
+ Label0:
+ List<Documento> documentos1 = documentos;
+ documentos1.ForEach((Documento d) => {
+ decimal? nullable2;
+ decimal? porcentagemRepasse;
+ d.Vendedores = (
+ from tipo in d.Pagamentos
+ orderby tipo.TipoVendedor.Id
+ select tipo into v
+ select v.Vendedor).ToList<Vendedor>();
+ Documento documento = d;
+ VendedorParcela vendedorParcela = d.Pagamentos.FirstOrDefault<VendedorParcela>((VendedorParcela p) => {
+ long? nullable;
+ long id = p.Vendedor.Id;
+ Vendedor vendedorPrincipal = d.VendedorPrincipal;
+ nullable = (vendedorPrincipal != null ? new long?(vendedorPrincipal.Id) : null);
+ long? nullable1 = nullable;
+ return id == nullable1.GetValueOrDefault() & nullable1.HasValue;
+ });
+ if (vendedorParcela != null)
+ {
+ porcentagemRepasse = vendedorParcela.PorcentagemRepasse;
+ }
+ else
+ {
+ nullable2 = null;
+ porcentagemRepasse = nullable2;
+ }
+ nullable2 = porcentagemRepasse;
+ documento.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault());
+ });
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ List<Documento> documentos2 = documentos;
+ documentos = null;
+ sqlQueryCondition = null;
+ vendedor1 = null;
+ return documentos2;
+ }
+
+ public async Task<List<Documento>> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false)
+ {
+ string str = "CAST(d.vigencia1 AS DATE)";
+ string referencia = filtro.Referencia;
+ if (referencia == "EMISSÃO")
+ {
+ str = "CAST(d.emissao AS DATE)";
+ }
+ else if (referencia == "TRANSMISSÃO PROPOSTA")
+ {
+ str = "CAST(d.remessa AS DATE)";
+ }
+ else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO")
+ {
+ str = "CAST(d.cri_data AS DATE)";
+ }
+ List<Condicao> condicaos = this.CriaCondicaoDocumento(filtro, str);
+ Condicao condicao = new Condicao()
+ {
+ Campo = "d.TipoRecebimento",
+ Valores = 1.CriarValor<int>()
+ };
+ condicaos.Add(condicao);
+ List<Condicao> condicaos1 = new List<Condicao>();
+ Condicao condicao1 = new Condicao()
+ {
+ Campo = "d.Excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ };
+ condicaos1.Add(condicao1);
+ Condicao condicao2 = new Condicao()
+ {
+ Campo = "d.Excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ };
+ condicaos1.Add(condicao2);
+ condicaos.AddRange(condicaos1);
+ return await this.BuscaDocumentosPorCondicao(filtro, condicaos, buscaAssinaturas);
+ }
+
+ private async Task<List<Fechamento>> BuscaFechamento(Filtros filtro)
+ {
+ NegocioCorretora negocioCorretora;
+ bool count;
+ object connection;
+ long num;
+ long num1;
+ decimal num2;
+ decimal num3;
+ decimal num4;
+ decimal num5;
+ NegocioCorretora negocioCorretora1;
+ bool flag;
+ List<Fechamento> fechamentos = new List<Fechamento>();
+ string str2 = "CAST(d.vigencia1 AS DATE)";
+ string str3 = "CAST(f.vigenciai AS DATE)";
+ if (filtro.Referencia == "EMISSÃO")
+ {
+ str2 = "CAST(d.emissao AS DATE)";
+ str3 = "CAST(f.emissao AS DATE)";
+ }
+ List<Condicao> condicaos = this.CriaCondicaoDocumento(filtro, str2);
+ List<Condicao> condicaos1 = this.CriaCondicaoDocumento(filtro, str3);
+ List<Condicao> condicaos2 = this.CriaCondicaoDocumento(filtro, "CAST(d.vigencia1 AS DATE)");
+ Condicao condicao = new Condicao()
+ {
+ Campo = "d.TipoRecebimento",
+ Valores = 1.CriarValor<int>()
+ };
+ condicaos.Add(condicao);
+ List<Condicao> condicaos3 = new List<Condicao>();
+ Condicao condicao1 = new Condicao()
+ {
+ Campo = "d.Excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ };
+ condicaos3.Add(condicao1);
+ Condicao condicao2 = new Condicao()
+ {
+ Campo = "d.Excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ };
+ condicaos3.Add(condicao2);
+ List<Condicao> condicaos4 = condicaos3;
+ condicaos.AddRange(condicaos4);
+ condicaos1.AddRange(condicaos4);
+ condicaos2.AddRange(condicaos4);
+ string str4 = "";
+ List<long> tipoVendedor = filtro.TipoVendedor;
+ if (tipoVendedor != null)
+ {
+ count = tipoVendedor.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (!count)
+ {
+ List<long> vendedores = filtro.Vendedores;
+ if (vendedores != null)
+ {
+ flag = vendedores.Count > 0;
+ }
+ else
+ {
+ flag = false;
+ }
+ if (flag)
+ {
+ goto Label1;
+ }
+ str4 = "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp";
+ goto Label0;
+ }
+ Label1:
+ str4 = "INNER JOIN vendedorparcela vp ON d.iddocumento = vp.iddocumento";
+ Label0:
+ SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0);
+ SqlQueryCondition sqlQueryCondition1 = condicaos1.CreateParameters(sqlQueryCondition.Parametros.Count);
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ Auxiliar.CriarAuxiliar(sqlCommand, false);
+ string str5 = string.Concat("SELECT DISTINCT c.IdEmpresa, d.IdControle, d.IdDocumento Id, d.Pr_Total Total, d.Pr_liq Liquido, d.Pr_Adic Adicional, ISNULL(d.com01, 0.00) Comissao, ISNULL(d.adinacomis, '0') AdinaComis, c.IdRamo, c.IdCiaSeg, c.IdProduto, CAST(d.Tipo AS INTEGER) Tipo, d.IdEstipulante, d.IdNegocio, d.Situacao, d.NegocioCorretora, vp.IdVendedor FROM documento d INNER JOIN controle c ON c.IdControle = d.IdControle ", str4, " WHERE ");
+ string str6 = string.Concat("SELECT DISTINCT c.IdEmpresa, d.IdControle, p.IdParcela Id, p.Valor Total, p.ValorLF Liquido, 0 Adicional, p.Comiss Comissao, '0' AdinaComis, c.IdRamo, c.IdCiaSeg, c.IdProduto, 2 Tipo, d.IdEstipulante, d.IdNegocio, d.Situacao, d.NegocioCorretora, vp.IdVendedor FROM fatura f INNER JOIN parcela p ON p.idparcela = f.idparcela INNER JOIN documento d ON d.iddocumento = p.iddocumento INNER JOIN controle c ON c.idcontrole = d.idcontrole ", str4, " WHERE ");
+ sqlCommand.CommandTimeout = 1000;
+ SqlCommand sqlCommand1 = sqlCommand;
+ string[] strArrays = new string[] { str5, " ", sqlQueryCondition.Condicao, " UNION ", str6, " ", sqlQueryCondition1.Condicao };
+ sqlCommand1.CommandText = string.Concat(strArrays);
+ sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray());
+ sqlCommand.Parameters.AddRange(sqlQueryCondition1.Parametros.ToArray());
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ List<Fechamento> fechamentos1 = new List<Fechamento>();
+ decimal num6 = new decimal();
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdCiaSeg"));
+ if (!flag1)
+ {
+ flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdRamo"));
+ }
+ if (!flag1)
+ {
+ long item = (long)sqlDataReader["IdEmpresa"];
+ long item1 = (long)sqlDataReader["IdCiaSeg"];
+ long item2 = (long)sqlDataReader["IdRamo"];
+ flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdEstipulante"));
+ num = (flag1 ? (long)0 : (long)sqlDataReader["IdEstipulante"]);
+ long num7 = num;
+ flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("IdVendedor"));
+ num1 = (flag1 ? (long)0 : (long)sqlDataReader["IdVendedor"]);
+ long id = num1;
+ flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Total"));
+ num2 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Total"]);
+ decimal num8 = num2;
+ flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Liquido"));
+ num3 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Liquido"]);
+ decimal num9 = num3;
+ flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Adicional"));
+ num4 = (flag1 || sqlDataReader["AdinaComis"].ToString() == "0" ? decimal.Zero : (decimal)sqlDataReader["Adicional"]);
+ decimal num10 = num4;
+ flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Comissao"));
+ num5 = (flag1 ? decimal.Zero : (decimal)sqlDataReader["Comissao"]);
+ decimal num11 = num5;
+ int item3 = (int)sqlDataReader["Tipo"];
+ if (!await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("negociocorretora")))
+ {
+ negocioCorretora = (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), sqlDataReader["negociocorretora"].ToString());
+ }
+ else
+ {
+ flag1 = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), sqlDataReader["situacao"].ToString()) == TipoSeguro.Renovacao;
+ if (flag1)
+ {
+ flag1 = !await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idnegocio"));
+ }
+ negocioCorretora1 = (!flag1 || !(sqlDataReader["idnegocio"].ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio);
+ negocioCorretora = negocioCorretora1;
+ }
+ NegocioCorretora negocioCorretora2 = negocioCorretora;
+ if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any<long>((long n) => (int)n == (int)negocioCorretora2))
+ {
+ if (id == 0)
+ {
+ id = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor v) => {
+ if (v.IdEmpresa != item)
+ {
+ return false;
+ }
+ return v.Corretora;
+ }).Id;
+ }
+ decimal num12 = (num9 + num10) * num11 * new decimal(1, 0, 0, false, 2);
+ num6 += num8;
+ for (int i = 0; i < 4; i++)
+ {
+ long num13 = (long)0;
+ switch (i)
+ {
+ case 0:
+ {
+ num13 = item1;
+ break;
+ }
+ case 1:
+ {
+ num13 = item2;
+ break;
+ }
+ case 2:
+ {
+ num13 = num7;
+ break;
+ }
+ case 3:
+ {
+ num13 = id;
+ break;
+ }
+ }
+ if (num13 != 0)
+ {
+ Fechamento fechamento4 = fechamentos1.FirstOrDefault<Fechamento>((Fechamento a) => {
+ if (a.Entidade != i)
+ {
+ return false;
+ }
+ return a.Id == num13;
+ });
+ if (fechamento4 == null)
+ {
+ fechamento4 = new Fechamento();
+ }
+ Fechamento fechamento5 = fechamento4;
+ Fechamento premioTotal = fechamento5;
+ premioTotal.PremioTotal = premioTotal.PremioTotal + num8;
+ Fechamento premioLiquido = fechamento5;
+ premioLiquido.PremioLiquido = premioLiquido.PremioLiquido + num9;
+ Fechamento fechamento6 = fechamento5;
+ fechamento6.Fechada = fechamento6.Fechada + num11;
+ Fechamento gerada = fechamento5;
+ gerada.Gerada = gerada.Gerada + num12;
+ switch (item3)
+ {
+ case 0:
+ {
+ Fechamento apolice = fechamento5;
+ apolice.Apolice = apolice.Apolice + 1;
+ break;
+ }
+ case 1:
+ {
+ Fechamento endosso = fechamento5;
+ endosso.Endosso = endosso.Endosso + 1;
+ break;
+ }
+ case 2:
+ {
+ Fechamento fatura = fechamento5;
+ fatura.Fatura = fatura.Fatura + 1;
+ break;
+ }
+ }
+ if (fechamento5.Id == 0)
+ {
+ fechamento5.Entidade = i;
+ fechamento5.Id = num13;
+ fechamentos1.Add(fechamento5);
+ }
+ }
+ }
+ }
+ }
+ }
+ fechamentos1.ForEach((Fechamento f) => {
+ string nome;
+ string str;
+ string nome1;
+ string str1;
+ switch (f.Entidade)
+ {
+ case 0:
+ {
+ Fechamento fechamento = f;
+ Seguradora seguradora = Auxiliar.Seguradoras.Find((Seguradora s) => s.Id == f.Id);
+ if (seguradora != null)
+ {
+ nome = seguradora.Nome;
+ }
+ else
+ {
+ nome = null;
+ }
+ fechamento.Nome = nome;
+ break;
+ }
+ case 1:
+ {
+ Fechamento fechamento1 = f;
+ Ramo ramo = Auxiliar.Ramos.Find((Ramo r) => r.Id == f.Id);
+ if (ramo != null)
+ {
+ str = ramo.Nome;
+ }
+ else
+ {
+ str = null;
+ }
+ fechamento1.Nome = str;
+ break;
+ }
+ case 2:
+ {
+ Fechamento fechamento2 = f;
+ Estipulante estipulante = Auxiliar.Estipulantes.Find((Estipulante e) => e.Id == f.Id);
+ if (estipulante != null)
+ {
+ nome1 = estipulante.Nome;
+ }
+ else
+ {
+ nome1 = null;
+ }
+ fechamento2.Nome = nome1;
+ break;
+ }
+ case 3:
+ {
+ Fechamento fechamento3 = f;
+ Vendedor vendedor = Auxiliar.Vendedores.Find((Vendedor v) => v.Id == f.Id);
+ if (vendedor != null)
+ {
+ str1 = vendedor.Nome;
+ }
+ else
+ {
+ str1 = null;
+ }
+ fechamento3.Nome = str1;
+ break;
+ }
+ }
+ Fechamento fechada = f;
+ fechada.Fechada = fechada.Fechada / f.Apolice + f.Fatura + f.Endosso;
+ f.Mix = (f.PremioTotal * new decimal(100)) / num6;
+ });
+ List<Fechamento> fechamentos2 = fechamentos1;
+ foreach (IGrouping<int, Fechamento> nums in
+ from g in fechamentos2
+ group g by g.Entidade)
+ {
+ await this.ContaRegistros(nums.Key, fechamentos1, filtro, condicaos2);
+ await this.SomaComissaoPaga(nums.Key, fechamentos1, filtro, condicaos2);
+ await this.SomaComissaoRecebida(nums.Key, fechamentos1, filtro, condicaos2);
+ }
+ fechamentos.AddRange(fechamentos1);
+ fechamentos1 = null;
+ }
+ sqlDataReader = null;
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ List<Fechamento> fechamentos3 = fechamentos;
+ fechamentos = null;
+ condicaos2 = null;
+ return fechamentos3;
+ }
+
+ private async Task<List<Item>> BuscaItemsPorIdControle(long idControle)
+ {
+ object connection;
+ List<Item> items = new List<Item>();
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 1000;
+ sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)";
+ sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle;
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ List<Item> items1 = items;
+ Item item = new Item()
+ {
+ Id = (long)sqlDataReader["iditem"],
+ Descricao = sqlDataReader["descricao"].ToString()
+ };
+ items1.Add(item);
+ }
+ }
+ sqlDataReader = null;
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ List<Item> items2 = items;
+ items = null;
+ return items2;
+ }
+
+ public List<Documento> BuscarDocumentoPorEstipulante(long id)
+ {
+ List<DocumentoDb> list = (
+ from x in base.All()
+ where x.Estipulante1.Id == id || x.Estipulante2.Id == id || x.Estipulante3.Id == id || x.Estipulante4.Id == id || x.Estipulante5.Id == id
+ select x).ToList<DocumentoDb>();
+ return ApplicationMapper.Mapper.Map<List<DocumentoDb>, List<Documento>>(list);
+ }
+
+ public List<Documento> BuscarDocumentoPorStatus(long id)
+ {
+ List<DocumentoDb> list = (
+ from x in base.All()
+ where x.Status.Id == id
+ select x).ToList<DocumentoDb>();
+ return ApplicationMapper.Mapper.Map<List<DocumentoDb>, List<Documento>>(list);
+ }
+
+ public string BuscarLogAntigo(long id, string conn)
+ {
+ object connection;
+ string str = "";
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "id",
+ Valores = id.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "idname",
+ Valores = "iddocumento".CriarValor<string>()
+ }
+ };
+ this._unitOfWork.CriarAuxiliar();
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ string str1 = "oldbacklog";
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog";
+ SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
+ sqlDataReader.Read();
+ string str2 = sqlDataReader["bdname"].ToString();
+ str1 = sqlDataReader["tabela"].ToString();
+ sqlDataReader.Close();
+ if (sqlConnection.Database != str2)
+ {
+ conn = conn.Replace(sqlConnection.Database, str2);
+ }
+ }
+ }
+ DataTable dataTable = new DataTable();
+ using (SqlConnection sqlConnection1 = new SqlConnection(conn))
+ {
+ sqlConnection1.Open();
+ using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand())
+ {
+ sqlCommand1.CommandTimeout = 15000;
+ dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), "");
+ }
+ }
+ if (dataTable == null || dataTable.Rows.Count == 0)
+ {
+ return "";
+ }
+ if (dataTable != null)
+ {
+ dataTable.AsEnumerable().OrderBy<DataRow, long>((DataRow x) => x.Field<long>("idbacklog")).ToList<DataRow>().ForEach((DataRow x) => {
+ str = string.Concat(new string[] { str, "<br><FONT face=verdana color=#FF0000 size=2><strong>(", x.Field<object>("data").ToString(), ")</font><FONT face=verdana size=2 color=#000000> ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field<long>("idusuario")).Nome, "</strong></font><br>" });
+ str = string.Concat(str, "<FONT face=verdana color=#000000 size=1>", x.Field<object>("historico").ToString().Replace(Environment.NewLine, "<br>"), "</font>");
+ });
+ }
+ return str;
+ }
+
+ public List<PlanilhaCompleta> BuscarPlanilhaCompletaProspeccao(List<long> ids)
+ {
+ object connection;
+ List<long> nums = null;
+ if (ids == null || ids.Count == 0)
+ {
+ return new List<PlanilhaCompleta>();
+ }
+ DataTable dataTable = new DataTable();
+ DataTable dataTable1 = new DataTable();
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ Auxiliar.CriarAuxiliar(sqlCommand, false);
+ for (List<long> i = ids; i.Count > 0; i = nums)
+ {
+ List<long> list = i.Take<long>(2100).ToList<long>();
+ string str1 = string.Concat(" AND va.idvenctoaleatorio IN (", string.Join<long>(",", list), ")");
+ DataTable dataTable2 = new DataTable();
+ string str2 = string.Concat("SELECT DISTINCT * FROM venctoaleatorio va LEFT OUTER JOIN tarefa ta on va.idtarefa = ta.id WHERE 1=1 ", str1, ";");
+ sqlCommand.CommandText = str2 ?? "";
+ using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
+ {
+ sqlDataAdapter.SelectCommand = sqlCommand;
+ sqlDataAdapter.Fill(dataTable2);
+ }
+ dataTable.Merge(dataTable2);
+ nums = (list.Count < 2100 ? new List<long>() : i.Except<long>(list).ToList<long>());
+ }
+ }
+ }
+ if (dataTable.Rows.Count == 0)
+ {
+ return new List<PlanilhaCompleta>();
+ }
+ List<PlanilhaCompleta> planilhaCompletas = new List<PlanilhaCompleta>();
+ dataTable.AsEnumerable().ToList<DataRow>().ForEach((DataRow x) => {
+ DateTime? nullable;
+ string str;
+ DateTime? nullable1;
+ DateTime? nullable2;
+ PlanilhaCompleta planilhaCompletum = new PlanilhaCompleta()
+ {
+ NumeroApolice = "PROSPECÇÃO",
+ Status = (x.Field<object>("situacao") == null || !(x.Field<object>("situacao").ToString() != "") || string.IsNullOrWhiteSpace(x.Field<object>("situacao").ToString()) ? null : (StatusProspeccao)Enum.Parse(typeof(StatusProspeccao), x.Field<object>("situacao").ToString()).GetDescription())
+ };
+ DateTime? nullable3 = x.Field<DateTime?>("finalcontrato");
+ if (nullable3.HasValue)
+ {
+ nullable = x.Field<DateTime?>("finalcontrato");
+ }
+ else
+ {
+ nullable3 = null;
+ nullable = nullable3;
+ }
+ planilhaCompletum.VigenciaFinal = nullable;
+ DataRow dataRow = dataTable1.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iddocumento") == x.Field<long>("iddocumento"));
+ if (dataRow != null)
+ {
+ str = dataRow.Field<string>("nome");
+ }
+ else
+ {
+ str = null;
+ }
+ planilhaCompletum.Estipulante = str;
+ planilhaCompletum.Vendedor = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")).Nome : null);
+ planilhaCompletum.NomeCliente = x.Field<string>("nome");
+ nullable3 = x.Field<DateTime?>("dtnascimento");
+ if (nullable3.HasValue)
+ {
+ nullable1 = x.Field<DateTime?>("dtnascimento");
+ }
+ else
+ {
+ nullable3 = null;
+ nullable1 = nullable3;
+ }
+ planilhaCompletum.NascimentoCliente = nullable1;
+ planilhaCompletum.DocumentoCliente = x.Field<string>("cpfcnpj");
+ planilhaCompletum.Prefixo1 = x.Field<string>("ddd");
+ planilhaCompletum.Telefone1 = x.Field<string>("fone");
+ planilhaCompletum.Prefixo2 = x.Field<string>("ddd2");
+ planilhaCompletum.Telefone2 = x.Field<string>("fone2");
+ planilhaCompletum.Email1 = x.Field<string>("email");
+ planilhaCompletum.DescricaoItem = x.Field<string>("item");
+ planilhaCompletum.ObsProspeccao = x.Field<string>("obs");
+ planilhaCompletum.TipoProspeccao = x.Field<string>("tipoprospeccao");
+ planilhaCompletum.TituloTarefa = x.Field<string>("titulo");
+ planilhaCompletum.DescricaoTarefa = x.Field<string>("descricao");
+ nullable3 = x.Field<DateTime?>("agendamento");
+ if (nullable3.HasValue)
+ {
+ nullable2 = x.Field<DateTime?>("agendamento");
+ }
+ else
+ {
+ nullable3 = null;
+ nullable2 = nullable3;
+ }
+ planilhaCompletum.AgendamentoTarefa = nullable2;
+ planilhaCompletas.Add(planilhaCompletum);
+ });
+ return planilhaCompletas;
+ }
+
+ private async Task<List<StatusDocumentoAssinado>> BuscaStatusAssinadosPorIdDocumento(long idDocumento)
+ {
+ object connection;
+ DateTime? nullable;
+ Usuario usuario1;
+ Func<Usuario, bool> func = null;
+ List<StatusDocumentoAssinado> statusDocumentoAssinados = new List<StatusDocumentoAssinado>();
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 1000;
+ sqlCommand.CommandText = "SELECT a.idnewarquivodigital,a.descricao,ISNULL(s.Status ,3) status,s.assinado,a.iddocumento,s.id,s.usuarioid,s.enviado FROM newarquivodigital a LEFT JOIN ArquivoParaAssinatura s ON a.idnewarquivodigital = s.indiceid WHERE a.iddocumento = @documento AND (a.excluido = 0 OR a.excluido IS NULL)";
+ sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento;
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ List<StatusDocumentoAssinado> statusDocumentoAssinados1 = statusDocumentoAssinados;
+ StatusDocumentoAssinado statusDocumentoAssinado = new StatusDocumentoAssinado()
+ {
+ Id = (long)sqlDataReader["idnewarquivodigital"],
+ Documento = sqlDataReader["descricao"].ToString(),
+ Status = (StatusAssinatura)((int)sqlDataReader["status"])
+ };
+ StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado;
+ bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("enviado"));
+ StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado1;
+ if (flag)
+ {
+ nullable = null;
+ }
+ else
+ {
+ nullable = new DateTime?((DateTime)sqlDataReader["enviado"]);
+ }
+ statusDocumentoAssinado2.Envio = nullable;
+ StatusDocumentoAssinado statusDocumentoAssinado3 = statusDocumentoAssinado;
+ bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("usuarioid"));
+ StatusDocumentoAssinado statusDocumentoAssinado4 = statusDocumentoAssinado3;
+ if (flag1)
+ {
+ usuario1 = null;
+ }
+ else
+ {
+ List<Usuario> usuarios = Auxiliar.Usuarios;
+ Func<Usuario, bool> func1 = func;
+ if (func1 == null)
+ {
+ Func<Usuario, bool> id = (Usuario usuario) => usuario.Id == (long)sqlDataReader["usuarioid"];
+ Func<Usuario, bool> func2 = id;
+ func = id;
+ func1 = func2;
+ }
+ usuario1 = usuarios.FirstOrDefault<Usuario>(func1);
+ }
+ statusDocumentoAssinado4.Usuario = usuario1;
+ statusDocumentoAssinados1.Add(statusDocumentoAssinado);
+ statusDocumentoAssinados1 = null;
+ statusDocumentoAssinado1 = null;
+ statusDocumentoAssinado3 = null;
+ statusDocumentoAssinado = null;
+ }
+ }
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ List<StatusDocumentoAssinado> statusDocumentoAssinados2 = statusDocumentoAssinados;
+ statusDocumentoAssinados = null;
+ return statusDocumentoAssinados2;
+ }
+
+ private async Task<List<VendedorParcela>> BuscaVendedoresPorIdControle(long idControle, long idEmpresa)
+ {
+ object connection;
+ Func<Vendedor, bool> func = null;
+ List<VendedorParcela> vendedorParcelas = new List<VendedorParcela>();
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 1000;
+ sqlCommand.CommandText = "SELECT DISTINCT vp.idvendedor,vp.vrep,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN parcela p ON vp.idparcela = p.idparcela INNER JOIN documento d ON d.iddocumento = vp.iddocumento WHERE d.idcontrole = @controle AND p.idsubtipo = 1";
+ sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle;
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ List<VendedorParcela> vendedorParcelas1 = vendedorParcelas;
+ VendedorParcela vendedorParcela = new VendedorParcela();
+ TipoVendedor tipoVendedor = new TipoVendedor()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("idtipovendedor", true, true)
+ };
+ vendedorParcela.TipoVendedor = tipoVendedor;
+ List<Vendedor> vendedores = Auxiliar.Vendedores;
+ Func<Vendedor, bool> func1 = func;
+ if (func1 == null)
+ {
+ Func<Vendedor, bool> id = (Vendedor vendedor) => vendedor.Id == sqlDataReader.GetFieldValue<long>("idvendedor", true, true);
+ Func<Vendedor, bool> func2 = id;
+ func = id;
+ func1 = func2;
+ }
+ vendedorParcela.Vendedor = vendedores.FirstOrDefault<Vendedor>(func1);
+ vendedorParcela.PorcentagemRepasse = sqlDataReader.GetFieldValue<decimal?>("vrep", true, true);
+ vendedorParcelas1.Add(vendedorParcela);
+ }
+ List<VendedorParcela> vendedorParcelas2 = vendedorParcelas;
+ if (!vendedorParcelas2.Any<VendedorParcela>((VendedorParcela v) => v.TipoVendedor.Id == (long)1))
+ {
+ List<VendedorParcela> vendedorParcelas3 = vendedorParcelas;
+ VendedorParcela vendedorParcela1 = new VendedorParcela()
+ {
+ TipoVendedor = new TipoVendedor()
+ {
+ Id = (long)1
+ },
+ Vendedor = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor v) => {
+ if (v.IdEmpresa != idEmpresa)
+ {
+ return false;
+ }
+ return v.Corretora;
+ }),
+ PorcentagemRepasse = new decimal?(new decimal())
+ };
+ vendedorParcelas3.Add(vendedorParcela1);
+ }
+ }
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ List<VendedorParcela> vendedorParcelas4 = vendedorParcelas;
+ vendedorParcelas = null;
+ return vendedorParcelas4;
+ }
+
+ private async Task<List<VendedorParcela>> BuscaVendedoresPorIdDocumento(long idDocumento, long idEmpresa)
+ {
+ object connection;
+ decimal? nullable;
+ Func<Vendedor, bool> func = null;
+ List<VendedorParcela> vendedorParcelas = new List<VendedorParcela>();
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 1000;
+ sqlCommand.CommandText = "SELECT DISTINCT vp.idvendedor,vp.vrep,vp.idtipovendedor FROM vendedorparcela vp INNER JOIN parcela p ON vp.idparcela = p.idparcela WHERE vp.iddocumento = @documento AND p.idsubtipo = 1";
+ sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento;
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ List<VendedorParcela> vendedorParcelas1 = vendedorParcelas;
+ VendedorParcela vendedorParcela = new VendedorParcela();
+ VendedorParcela vendedorParcela1 = vendedorParcela;
+ TipoVendedor tipoVendedor = new TipoVendedor()
+ {
+ Id = (long)sqlDataReader["idtipovendedor"]
+ };
+ vendedorParcela1.TipoVendedor = tipoVendedor;
+ VendedorParcela vendedorParcela2 = vendedorParcela;
+ List<Vendedor> vendedores = Auxiliar.Vendedores;
+ Func<Vendedor, bool> func1 = func;
+ if (func1 == null)
+ {
+ Func<Vendedor, bool> id = (Vendedor vendedor) => vendedor.Id == (long)sqlDataReader["idvendedor"];
+ Func<Vendedor, bool> func2 = id;
+ func = id;
+ func1 = func2;
+ }
+ vendedorParcela2.Vendedor = vendedores.FirstOrDefault<Vendedor>(func1);
+ VendedorParcela vendedorParcela3 = vendedorParcela;
+ bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("vrep"));
+ VendedorParcela vendedorParcela4 = vendedorParcela3;
+ if (flag)
+ {
+ nullable = null;
+ }
+ else
+ {
+ nullable = new decimal?((decimal)sqlDataReader["vrep"]);
+ }
+ vendedorParcela4.PorcentagemRepasse = nullable;
+ vendedorParcelas1.Add(vendedorParcela);
+ vendedorParcelas1 = null;
+ vendedorParcela3 = null;
+ vendedorParcela = null;
+ }
+ List<VendedorParcela> vendedorParcelas2 = vendedorParcelas;
+ if (!vendedorParcelas2.Any<VendedorParcela>((VendedorParcela v) => v.TipoVendedor.Id == (long)1))
+ {
+ List<VendedorParcela> vendedorParcelas3 = vendedorParcelas;
+ VendedorParcela vendedorParcela5 = new VendedorParcela()
+ {
+ TipoVendedor = new TipoVendedor()
+ {
+ Id = (long)1
+ },
+ Vendedor = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor v) => {
+ if (v.IdEmpresa != idEmpresa)
+ {
+ return false;
+ }
+ return v.Corretora;
+ }),
+ PorcentagemRepasse = new decimal?(new decimal())
+ };
+ vendedorParcelas3.Add(vendedorParcela5);
+ }
+ }
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ List<VendedorParcela> vendedorParcelas4 = vendedorParcelas;
+ vendedorParcelas = null;
+ return vendedorParcelas4;
+ }
+
+ private async Task ContaRegistros(int tipo, List<Fechamento> fechamentos, Filtros filtro, List<Condicao> condicaoDocumento)
+ {
+ object connection;
+ long num;
+ bool count;
+ bool flag;
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ string str = "c.IdCiaSeg";
+ string str1 = "COUNT(d.IdDocumento)";
+ string str2 = "FROM item i INNER JOIN documento d ON d.IdDocumento = i.IdDocumento INNER JOIN controle c ON c.IdControle = d.IdControle";
+ string str3 = "i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0) AND";
+ switch (tipo)
+ {
+ case 1:
+ {
+ str = "c.IdRamo";
+ break;
+ }
+ case 2:
+ {
+ str = "d.IdEstipulante";
+ break;
+ }
+ case 3:
+ {
+ str = "vp.IdVendedor";
+ break;
+ }
+ }
+ string str4 = "";
+ if (tipo != 3)
+ {
+ List<long> tipoVendedor = filtro.TipoVendedor;
+ if (tipoVendedor != null)
+ {
+ count = tipoVendedor.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (!count)
+ {
+ List<long> vendedores = filtro.Vendedores;
+ if (vendedores != null)
+ {
+ flag = vendedores.Count > 0;
+ }
+ else
+ {
+ flag = false;
+ }
+ if (!flag)
+ {
+ goto Label0;
+ }
+ }
+ }
+ str1 = "COUNT(DISTINCT d.IdDocumento)";
+ str4 = "INNER JOIN vendedorparcela vp ON d.iddocumento = vp.iddocumento";
+ Label0:
+ SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0);
+ sqlCommand.CommandTimeout = 1000;
+ SqlCommand sqlCommand1 = sqlCommand;
+ string[] condicao = new string[] { "SELECT ", str, " Id,", str1, " Contador ", str2, " ", str4, " WHERE ", str3, " ", sqlQueryCondition.Condicao, " GROUP BY ", str };
+ sqlCommand1.CommandText = string.Concat(condicao);
+ sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray());
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id"));
+ num = (flag1 ? (long)0 : (long)sqlDataReader["Id"]);
+ long num1 = num;
+ int item = (int)sqlDataReader["Contador"];
+ if (num1 != 0)
+ {
+ Fechamento fechamento = fechamentos.FirstOrDefault<Fechamento>((Fechamento f) => {
+ if (f.Entidade != tipo)
+ {
+ return false;
+ }
+ return f.Id == num1;
+ });
+ if (fechamento != null)
+ {
+ Fechamento itens = fechamento;
+ itens.Itens = itens.Itens + item;
+ }
+ }
+ }
+ }
+ sqlDataReader = null;
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ }
+
+ public int Cotacoes(Filtros filtro)
+ {
+ int num;
+ object connection;
+ string str = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND u.idempresa = {0}", filtro.IdEmpresa));
+ try
+ {
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandText = string.Format("SELECT COUNT(r.id) as quantidade from ResultadoCalculo r INNER JOIN usuario u ON u.idusuario = r.IdUsuario where CAST(DataAtualizacao AS DATE) >= '{0:yyyy-MM-dd}' and CAST(DataAtualizacao AS DATE) <= '{1:yyyy-MM-dd}' AND DataExclusao IS NULL AND Calculado = 1 {2};", filtro.Inicio, filtro.Fim, str);
+ SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
+ sqlDataReader.Read();
+ num = (sqlDataReader.HasRows ? int.Parse(sqlDataReader["quantidade"].ToString()) : 0);
+ }
+ }
+ }
+ catch (Exception exception)
+ {
+ num = 0;
+ }
+ return num;
+ }
+
+ private List<Condicao> CriaCondicaoDocumento(Filtros filtro, string referencia)
+ {
+ bool count;
+ bool flag;
+ bool count1;
+ bool flag1;
+ bool count2;
+ bool flag2;
+ bool count3;
+ bool flag3;
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = referencia,
+ Valores = filtro.Inicio.CriarValor<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ },
+ new Condicao()
+ {
+ Campo = referencia,
+ Valores = filtro.Fim.CriarValor<DateTime>(),
+ Operador = Operador.MenorEIgual
+ }
+ };
+ List<long> seguradoras = filtro.Seguradoras;
+ if (seguradoras != null)
+ {
+ count = seguradoras.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (count)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idciaseg",
+ Valores = filtro.Seguradoras.CriarValor<long>()
+ });
+ }
+ List<long> ramos = filtro.Ramos;
+ if (ramos != null)
+ {
+ flag = ramos.Count > 0;
+ }
+ else
+ {
+ flag = false;
+ }
+ if (flag)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idramo",
+ Valores = filtro.Ramos.CriarValor<long>()
+ });
+ }
+ List<long> status = filtro.Status;
+ if (status != null)
+ {
+ count1 = status.Count > 0;
+ }
+ else
+ {
+ count1 = false;
+ }
+ if (count1)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = filtro.Status.CriarValor<long>()
+ });
+ }
+ List<long> tipoVendedor = filtro.TipoVendedor;
+ if (tipoVendedor != null)
+ {
+ flag1 = tipoVendedor.Count > 0;
+ }
+ else
+ {
+ flag1 = false;
+ }
+ if (flag1)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "vp.idtipovendedor",
+ Valores = filtro.TipoVendedor.CriarValor<long>()
+ });
+ }
+ List<long> vendedores = filtro.Vendedores;
+ if (vendedores != null)
+ {
+ count2 = vendedores.Count > 0;
+ }
+ else
+ {
+ count2 = false;
+ }
+ if (count2)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "vp.idvendedor",
+ Valores = filtro.Vendedores.CriarValor<long>()
+ });
+ }
+ List<long> estipulantes = filtro.Estipulantes;
+ if (estipulantes != null)
+ {
+ flag2 = estipulantes.Count > 0;
+ }
+ else
+ {
+ flag2 = false;
+ }
+ if (flag2)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.idestipulante",
+ Valores = filtro.Estipulantes.CriarValor<long>(),
+ Operacao = Operacao.Or,
+ Grupo = 3
+ });
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.idestipulante2",
+ Valores = filtro.Estipulantes.CriarValor<long>(),
+ Operacao = Operacao.Or,
+ Grupo = 3
+ });
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.idestipulante3",
+ Valores = filtro.Estipulantes.CriarValor<long>(),
+ Operacao = Operacao.Or,
+ Grupo = 3
+ });
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.idestipulante4",
+ Valores = filtro.Estipulantes.CriarValor<long>(),
+ Operacao = Operacao.Or,
+ Grupo = 3
+ });
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.idestipulante5",
+ Valores = filtro.Estipulantes.CriarValor<long>(),
+ Operacao = Operacao.Or,
+ Grupo = 3
+ });
+ }
+ List<long> produtos = filtro.Produtos;
+ if (produtos != null)
+ {
+ count3 = produtos.Count > 0;
+ }
+ else
+ {
+ count3 = false;
+ }
+ if (count3)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idproduto",
+ Valores = filtro.Produtos.CriarValor<long>()
+ });
+ }
+ List<long> negocio = filtro.Negocio;
+ if (negocio != null)
+ {
+ flag3 = negocio.Count > 0;
+ }
+ else
+ {
+ flag3 = false;
+ }
+ if (flag3)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.NegocioCorretora",
+ Valores = filtro.Negocio.CriarValor<long>(),
+ Operacao = Operacao.Or,
+ Grupo = 6
+ });
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.NegocioCorretora",
+ Valores = null,
+ Operacao = Operacao.Or,
+ Grupo = 6
+ });
+ }
+ if (filtro.IdEmpresa > (long)0)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idempresa",
+ Valores = filtro.IdEmpresa.CriarValor<long>()
+ });
+ }
+ return condicaos;
+ }
+
+ public void Delete(long id)
+ {
+ base.Delete(base.FindEntityById(id));
+ }
+
+ private async Task<bool> ExisteTabelasAssinatura()
+ {
+ bool flag;
+ object connection;
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandText = "SELECT OBJECT_ID('ArquivoParaAssinatura') AS existe";
+ flag = await sqlCommand.ExecuteScalarAsync() != DBNull.Value;
+ }
+ }
+ }
+ return flag;
+ }
+
+ public async Task<List<Fechamento>> Fechamento(Filtros filtro)
+ {
+ List<Fechamento> fechamentos = await this.BuscaFechamento(filtro);
+ Filtros filtro1 = (Filtros)filtro.Clone();
+ DateTime inicio = filtro.Inicio;
+ filtro1.Inicio = inicio.AddYears(-1);
+ inicio = filtro.Fim;
+ filtro1.Fim = inicio.AddYears(-1);
+ List<Fechamento> fechamentos1 = await this.BuscaFechamento(filtro1);
+ List<Fechamento> fechamentos2 = new List<Fechamento>();
+ fechamentos1.ForEach((Fechamento a) => {
+ Fechamento premioLiquido = fechamentos.Find((Fechamento fec) => {
+ if (fec.Entidade != a.Entidade)
+ {
+ return false;
+ }
+ return fec.Id == a.Id;
+ }) ?? new Fechamento()
+ {
+ Entidade = a.Entidade,
+ Id = a.Id,
+ Nome = a.Nome,
+ PremioLiquido = decimal.Zero,
+ PremioTotal = decimal.Zero,
+ Fechada = decimal.Zero,
+ Gerada = decimal.Zero,
+ Mix = decimal.Zero,
+ Apolice = 0,
+ Endosso = 0,
+ Fatura = 0,
+ Itens = 0,
+ Paga = decimal.Zero,
+ Recebida = decimal.Zero
+ };
+ premioLiquido.PremioLiquidoAnterior = a.PremioLiquido;
+ premioLiquido.PremioTotalAnterior = a.PremioTotal;
+ premioLiquido.FechadaAnterior = a.Fechada;
+ premioLiquido.GeradaAnterior = a.Gerada;
+ premioLiquido.MixAnterior = a.Mix;
+ premioLiquido.ApoliceAnterior = a.Apolice;
+ premioLiquido.EndossoAnterior = a.Endosso;
+ premioLiquido.FaturaAnterior = a.Fatura;
+ premioLiquido.ItensAnterior = a.Itens;
+ premioLiquido.PagaAnterior = a.Paga;
+ premioLiquido.RecebidaAnterior = a.Recebida;
+ fechamentos2.Add(premioLiquido);
+ });
+ fechamentos.ForEach((Fechamento a) => {
+ if (fechamentos2.Find((Fechamento fec) => {
+ if (fec.Entidade != a.Entidade)
+ {
+ return false;
+ }
+ return fec.Id == a.Id;
+ }) == null)
+ {
+ Fechamento fechamento = new Fechamento()
+ {
+ Entidade = a.Entidade,
+ Id = a.Id,
+ Nome = a.Nome,
+ PremioLiquidoAnterior = decimal.Zero,
+ PremioTotalAnterior = decimal.Zero,
+ FechadaAnterior = decimal.Zero,
+ GeradaAnterior = decimal.Zero,
+ MixAnterior = decimal.Zero,
+ ApoliceAnterior = 0,
+ EndossoAnterior = 0,
+ FaturaAnterior = 0,
+ ItensAnterior = 0,
+ PagaAnterior = decimal.Zero,
+ RecebidaAnterior = decimal.Zero,
+ PremioLiquido = a.PremioLiquido,
+ PremioTotal = a.PremioTotal,
+ Fechada = a.Fechada,
+ Gerada = a.Gerada,
+ Mix = a.Mix,
+ Apolice = a.Apolice,
+ Endosso = a.Endosso,
+ Fatura = a.Fatura,
+ Itens = a.Itens,
+ Paga = a.Paga,
+ Recebida = a.Recebida
+ };
+ fechamentos2.Add(fechamento);
+ }
+ });
+ List<Fechamento> fechamentos3 = fechamentos2;
+ return fechamentos3;
+ }
+
+ public List<Documento> FindApolice(string pesquisa, FiltroStatusDocumento status, List<VendedorUsuario> vendedorVinculado, string campo, long idempresa = 0L, bool vendedorembranco = false, bool tipobusca = false)
+ {
+ List<Documento> documentos;
+ object connection;
+ DataTable dataTable = new DataTable();
+ if (campo == "Proposta")
+ {
+ campo = (tipobusca ? string.Concat(" AND d.proposta LIKE '", pesquisa, "'") : string.Concat(" AND d.proposta LIKE '%", pesquisa, "%'"));
+ }
+ else if (campo == "Estipulante")
+ {
+ campo = (tipobusca ? string.Concat(" AND d.idestipulante IS NOT NULL AND e.nome LIKE '", pesquisa, "'") : string.Concat(" AND d.idestipulante IS NOT NULL AND e.nome LIKE '%", pesquisa, "%'"));
+ }
+ else if (campo == "NumeroEndosso")
+ {
+ campo = (tipobusca ? string.Concat(" AND d.aditamento LIKE '", pesquisa, "'") : string.Concat(" AND d.aditamento LIKE '%", pesquisa, "%'"));
+ }
+ else if (campo == "PedidoEndosso")
+ {
+ campo = (tipobusca ? string.Concat(" AND d.pedadit LIKE '", pesquisa, "'") : string.Concat(" AND d.pedadit LIKE '%", pesquisa, "%'"));
+ }
+ else
+ {
+ campo = (tipobusca ? string.Concat(" AND d.contrato LIKE '", pesquisa, "'") : string.Concat(" AND d.contrato LIKE '%", pesquisa, "%'"));
+ }
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ DataTable dataTable1 = new DataTable();
+ string str = "";
+ string str1 = (idempresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", idempresa));
+ DateTime date = Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime().Date;
+ switch (status)
+ {
+ case FiltroStatusDocumento.Vencidos:
+ {
+ str = string.Concat(string.Format(" {0} AND (d.vigencia2 IS NULL OR d.vigencia2 < '{1:yyyy-MM-dd}') ", campo, date.AddDays(-5)), "AND d.situacao NOT IN (3, 7)");
+ break;
+ }
+ case FiltroStatusDocumento.Cancelados:
+ {
+ str = string.Concat(" ", campo, " AND d.situacao IN (3)");
+ break;
+ }
+ case FiltroStatusDocumento.Recusados:
+ {
+ str = string.Concat(campo, " AND d.situacao IN (7)");
+ break;
+ }
+ case FiltroStatusDocumento.Todos:
+ {
+ str = string.Concat(" ", campo);
+ break;
+ }
+ default:
+ {
+ str = string.Concat(string.Format(" {0} AND (d.vigencia2 IS NULL OR d.vigencia2 > '{1:yyyy-MM-dd}') ", campo, date.AddDays(-5)), "AND d.situacao IN (1, 2, 4)");
+ break;
+ }
+ }
+ string str2 = "SELECT DISTINCT c.idcliente,cl.nome,cl.MalaDireta,c.idempresa,c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, d.pasta, c.AssistenciaId, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, e.nome AS estipulante FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole INNER JOIN cliente cl ON cl.idcliente = c.idcliente LEFT OUTER JOIN estipulante e ON e.idestipulante = d.idestipulante WHERE (d.excluido IS NULL OR d.excluido != 1) ";
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ Auxiliar.CriarAuxiliar(sqlCommand, false);
+ sqlCommand.CommandText = string.Concat(str2, str1, str);
+ using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
+ {
+ sqlDataAdapter.SelectCommand = sqlCommand;
+ sqlDataAdapter.Fill(dataTable1);
+ }
+ List<long> list = (
+ from x in dataTable1.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("idcontrole")).ToList<long>();
+ while (list.Count > 0)
+ {
+ List<long> nums = list.Take<long>(2100).ToList<long>();
+ if (dataTable1.Rows.Count != 0)
+ {
+ string str3 = string.Concat(" d.idcontrole IN (", string.Join<long>(",", nums), ")");
+ str3 = (vendedorembranco ? string.Concat(" AND ", str3) : string.Concat(" AND vp.idvendedorparcela IS NOT NULL AND ", str3));
+ sqlCommand.CommandText = string.Concat("SELECT DISTINCT vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento WHERE 1=1 ", str3);
+ using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter())
+ {
+ sqlDataAdapter1.SelectCommand = sqlCommand;
+ sqlDataAdapter1.Fill(dataTable);
+ }
+ list = (nums.Count < 2100 ? new List<long>() : list.Except<long>(nums).ToList<long>());
+ }
+ else
+ {
+ documentos = new List<Documento>();
+ return documentos;
+ }
+ }
+ goto Label0;
+ }
+ }
+ return documentos;
+ Label0:
+ List<long> list1 = null;
+ if (vendedorVinculado != null && vendedorVinculado.Count > 0)
+ {
+ list1 = dataTable.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if (!vendedorembranco)
+ {
+ if (x.Field<object>("idvendedor") == null)
+ {
+ return false;
+ }
+ List<VendedorUsuario> vendedorUsuarios = vendedorVinculado;
+ Func<VendedorUsuario, long> u003cu003e9_429 = DocumentoRepository.u003cu003ec.u003cu003e9__42_9;
+ if (u003cu003e9_429 == null)
+ {
+ u003cu003e9_429 = (VendedorUsuario v) => v.Vendedor.Id;
+ DocumentoRepository.u003cu003ec.u003cu003e9__42_9 = u003cu003e9_429;
+ }
+ return vendedorUsuarios.Select<VendedorUsuario, long>(u003cu003e9_429).Contains<long>(x.Field<long>("idvendedor"));
+ }
+ if (x.Field<object>("idvendedor") == null)
+ {
+ return true;
+ }
+ List<VendedorUsuario> vendedorUsuarios1 = vendedorVinculado;
+ Func<VendedorUsuario, long> u003cu003e9_428 = DocumentoRepository.u003cu003ec.u003cu003e9__42_8;
+ if (u003cu003e9_428 == null)
+ {
+ u003cu003e9_428 = (VendedorUsuario v) => v.Vendedor.Id;
+ DocumentoRepository.u003cu003ec.u003cu003e9__42_8 = u003cu003e9_428;
+ }
+ return vendedorUsuarios1.Select<VendedorUsuario, long>(u003cu003e9_428).Contains<long>(x.Field<long>("idvendedor"));
+ }).Select<DataRow, long>((DataRow x) => x.Field<long>("idcontrole")).ToList<long>();
+ }
+ if (list1 != null && list1.Count == 0)
+ {
+ return new List<Documento>();
+ }
+ List<long> nums1 = dataTable1.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("idcontrole")).Distinct<long>().ToList<long>();
+ List<long> nums2 = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(nums1);
+ return (
+ from x in dataTable1.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if (list1 == null)
+ {
+ return true;
+ }
+ return list1.Contains(x.Field<long>("idcontrole"));
+ }).ToList<DataRow>()
+ orderby x.Field<long>("idcontrole"), x.Field<int>("tipo")
+ select x).Select<DataRow, Documento>((DataRow x) => {
+ Documento documento = new Documento()
+ {
+ Id = x.Field<long>("iddocumento"),
+ Controle = new Controle()
+ {
+ Id = x.Field<long>("idcontrole"),
+ IdEmpresa = (x.Field<object>("idempresa") != null ? x.Field<long>("idempresa") : (long)1),
+ Cliente = new Cliente()
+ {
+ Id = x.Field<long>("idcliente"),
+ Nome = x.Field<string>("nome"),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
+ },
+ Seguradora = (x.Field<object>("idciaseg") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idciaseg")) : null),
+ Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
+ Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Gestor.Model.Domain.Seguros.Produto>((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field<long>("idproduto")) : null),
+ AssistenciaId = x.Field<string>("AssistenciaId")
+ },
+ Ordem = x.Field<int>("ordem"),
+ TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field<object>("tiporecebimento").ToString())),
+ AdicionalComiss = x.Field<string>("adinacomis") == "1",
+ Apolice = x.Field<string>("contrato"),
+ Endosso = x.Field<string>("aditamento"),
+ Comissao = x.Field<decimal>("com01"),
+ Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString()))),
+ PremioLiquido = x.Field<decimal>("pr_liq"),
+ PremioTotal = x.Field<decimal>("pr_total"),
+ Vigencia2 = x.Field<DateTime?>("vigencia2")
+ };
+ DateTime? nullable = x.Field<DateTime?>("vigencia1");
+ documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ documento.Emissao = x.Field<DateTime?>("emissao");
+ documento.Remessa = x.Field<DateTime?>("remessa");
+ documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
+ documento.NegocioCorretora = new NegocioCorretora?((x.Field<object>("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field<object>("negociocorretora").ToString())));
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
+ documento.Tipo = x.Field<int>("tipo");
+ documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(x.Field<long>("iddocumento"));
+ documento.Sinistro = (nums2 == null ? false : nums2.Any<long>((long s) => s == x.Field<long>("idcontrole")));
+ documento.NumeroParcelas = int.Parse(x.Field<object>("numeroParcelas").ToString());
+ documento.Pasta = x.Field<string>("Pasta");
+ return documento;
+ }).ToList<Documento>();
+ }
+
+ public List<Documento> FindApoliceByCustomer(long idCliente, FiltroStatusDocumento status, List<VendedorUsuario> vendedorVinculado, List<Licenca> licencas, bool endosso = false, bool acessoAgger = false, bool vendedorembranco = false)
+ {
+ List<Documento> documentos1;
+ object connection;
+ long num1;
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ bool flag2 = licencas.Any<Licenca>((Licenca x) => {
+ if (x.Produto != Gestor.Model.License.Produto.AssinaturaEletronica)
+ {
+ return false;
+ }
+ return x.Status != 3;
+ });
+ DataTable dataTable3 = new DataTable();
+ DataTable dataTable4 = new DataTable();
+ DataTable dataTable5 = new DataTable();
+ DataTable dataTable6 = new DataTable();
+ DataTable dataTable7 = null;
+ List<long> nums = new List<long>();
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ }
+ };
+ DateTime date = Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime().Date;
+ List<Condicao> condicaos1 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "c.idcliente",
+ Valores = idCliente.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "d.tipo",
+ Valores = 0.CriarValor<int>()
+ }
+ };
+ switch (status)
+ {
+ case FiltroStatusDocumento.Vencidos:
+ {
+ condicaos1.AddRange(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = new List<object>()
+ {
+ 3,
+ 7
+ },
+ Operador = Operador.Diferente
+ },
+ new Condicao()
+ {
+ Campo = "d.vigencia2",
+ Valores = date.AddDays(-5).CriarValor<DateTime>(),
+ Operador = Operador.Menor
+ }
+ });
+ goto case FiltroStatusDocumento.Todos;
+ }
+ case FiltroStatusDocumento.Cancelados:
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = 3.CriarValor<int>()
+ });
+ goto case FiltroStatusDocumento.Todos;
+ }
+ case FiltroStatusDocumento.Recusados:
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = 7.CriarValor<int>()
+ });
+ goto case FiltroStatusDocumento.Todos;
+ }
+ case FiltroStatusDocumento.Todos:
+ {
+ if (!acessoAgger)
+ {
+ condicaos1.AddRange(condicaos);
+ }
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ dataTable3 = sqlCommand.Select(condicaos1.CreateParameters(0), "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", "");
+ if (dataTable3 == null || dataTable3.Rows.Count == 0)
+ {
+ documentos1 = new List<Documento>();
+ return documentos1;
+ }
+ else
+ {
+ Auxiliar.CriarAuxiliar(sqlCommand, false);
+ nums = (
+ from x in dataTable3.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("idcontrole")).ToList<long>();
+ List<Condicao> condicaos2 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "c.idcontrole",
+ Valores = nums.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "d.tipo",
+ Valores = 0.CriarValor<int>(),
+ Operador = Operador.Diferente
+ }
+ };
+ if (!acessoAgger)
+ {
+ condicaos2.AddRange(condicaos);
+ }
+ dataTable4 = sqlCommand.Select(condicaos2.CreateParameters(0), "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", "");
+ List<Condicao> condicaos3 = (vendedorembranco ? new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.idcontrole",
+ Valores = nums.CriarValor<long>()
+ }
+ } : new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "vp.idvendedorparcela",
+ Valores = null,
+ Operador = Operador.Diferente
+ },
+ new Condicao()
+ {
+ Campo = "d.idcontrole",
+ Valores = nums.CriarValor<long>()
+ }
+ });
+ dataTable5 = sqlCommand.Select(condicaos3.CreateParameters(0), "SELECT DISTINCT vp.IDPARCELA, vp.idvendedor, d.iddocumento, d.idcontrole, vp.idtipovendedor, p.idsubtipo FROM documento d LEFT OUTER JOIN vendedorparcela vp on d.iddocumento = vp.iddocumento LEFT OUTER JOIN parcela p on p.idparcela = vp.idparcela WHERE ", "");
+ try
+ {
+ if (flag2)
+ {
+ List<long> nums1 = (
+ from x in dataTable3.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("iddocumento")).ToList<long>();
+ List<long> nums2 = (
+ from x in dataTable4.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("iddocumento")).ToList<long>();
+ nums1.AddRange(nums2);
+ List<Condicao> condicaos4 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "DocumentoId",
+ Valores = nums1.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "a.excluido",
+ Valores = null,
+ Grupo = 2,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "a.excluido",
+ Valores = 0.CriarValor<int>(),
+ Grupo = 2,
+ Operacao = Operacao.Or
+ }
+ };
+ dataTable6 = sqlCommand.Select(condicaos4.CreateParameters(0), "SELECT DISTINCT a.idnewarquivodigital, a.descricao, ISNULL(s.Status ,0) as Status, s.assinado, s.DocumentoId, s.id, s.UsuarioId, s.Enviado FROM newarquivodigital a LEFT OUTER JOIN ArquivoParaAssinatura s on s.IndiceId = a.idnewarquivodigital WHERE ", "");
+ }
+ }
+ catch (Exception exception)
+ {
+ dataTable6 = null;
+ }
+ }
+ }
+ }
+ List<long> nums3 = null;
+ if (vendedorVinculado != null && vendedorVinculado.Count > 0)
+ {
+ nums3 = dataTable5.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if (!vendedorembranco)
+ {
+ if (x.Field<object>("idvendedor") == null)
+ {
+ return false;
+ }
+ List<VendedorUsuario> vendedorUsuarios = vendedorVinculado;
+ Func<VendedorUsuario, long> u003cu003e9_1116 = DocumentoRepository.u003cu003ec.u003cu003e9__11_16;
+ if (u003cu003e9_1116 == null)
+ {
+ u003cu003e9_1116 = (VendedorUsuario v) => v.Vendedor.Id;
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_16 = u003cu003e9_1116;
+ }
+ return vendedorUsuarios.Select<VendedorUsuario, long>(u003cu003e9_1116).Contains<long>(x.Field<long>("idvendedor"));
+ }
+ if (x.Field<object>("idvendedor") == null)
+ {
+ return true;
+ }
+ List<VendedorUsuario> vendedorUsuarios1 = vendedorVinculado;
+ Func<VendedorUsuario, long> u003cu003e9_1115 = DocumentoRepository.u003cu003ec.u003cu003e9__11_15;
+ if (u003cu003e9_1115 == null)
+ {
+ u003cu003e9_1115 = (VendedorUsuario v) => v.Vendedor.Id;
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_15 = u003cu003e9_1115;
+ }
+ return vendedorUsuarios1.Select<VendedorUsuario, long>(u003cu003e9_1115).Contains<long>(x.Field<long>("idvendedor"));
+ }).Select<DataRow, long>((DataRow x) => x.Field<long>("idcontrole")).ToList<long>();
+ }
+ if (nums3 != null && nums3.Count == 0)
+ {
+ return new List<Documento>();
+ }
+ DataRow dataRow1 = dataTable3.AsEnumerable().FirstOrDefault<DataRow>();
+ if (dataRow1 != null)
+ {
+ num1 = dataRow1.Field<long>("idempresa");
+ }
+ else
+ {
+ num1 = (long)1;
+ }
+ long num2 = num1;
+ Vendedor vendedor1 = Auxiliar.Vendedores.Find((Vendedor p) => {
+ if (!p.Corretora)
+ {
+ return false;
+ }
+ return p.IdEmpresa == num2;
+ });
+ if (endosso)
+ {
+ dataTable3.Merge(dataTable4);
+ return (
+ from x in dataTable3.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if (nums3 == null)
+ {
+ return true;
+ }
+ return nums3.Contains(x.Field<long>("idcontrole"));
+ }).ToList<DataRow>()
+ orderby x.Field<long>("idcontrole"), x.Field<int>("tipo")
+ select x).Select<DataRow, Documento>((DataRow x) => {
+ List<StatusDocumentoAssinado> list;
+ Func<DataRow, bool> func2 = null;
+ Func<DataRow, bool> func3 = null;
+ Documento documento = new Documento()
+ {
+ Id = x.Field<long>("iddocumento"),
+ Controle = new Controle()
+ {
+ Id = x.Field<long>("idcontrole"),
+ IdEmpresa = (x.Field<object>("idempresa") != null ? x.Field<long>("idempresa") : (long)1),
+ Cliente = new Cliente()
+ {
+ Id = idCliente,
+ Documento = x.Field<string>("cgccpf"),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
+ },
+ Seguradora = (x.Field<object>("idciaseg") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Field<long>("idciaseg")) : null),
+ Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
+ Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field<long>("idproduto")) : null),
+ AssistenciaId = x.Field<string>("AssistenciaId")
+ },
+ Ordem = x.Field<int>("ordem"),
+ TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field<object>("tiporecebimento").ToString())),
+ AdicionalComiss = x.Field<string>("adinacomis") == "1",
+ PremioAdicional = x.Field<decimal>("pr_adic"),
+ Proposta = x.Field<string>("proposta"),
+ Apolice = x.Field<string>("contrato"),
+ PropostaEndosso = x.Field<string>("pedadit"),
+ Endosso = x.Field<string>("aditamento"),
+ Comissao = x.Field<decimal>("com01"),
+ Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString()))),
+ PremioLiquido = x.Field<decimal>("pr_liq"),
+ PremioTotal = x.Field<decimal>("pr_total"),
+ Vigencia2 = x.Field<DateTime?>("vigencia2")
+ };
+ DateTime? nullable = x.Field<DateTime?>("vigencia1");
+ documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ documento.Emissao = x.Field<DateTime?>("emissao");
+ documento.Remessa = x.Field<DateTime?>("remessa");
+ documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
+ documento.NegocioCorretora = new NegocioCorretora?((x.Field<object>("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field<object>("negociocorretora").ToString())));
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
+ documento.Tipo = x.Field<int>("tipo");
+ documento.VendedorPrincipal = (dataTable5.Rows.Count <= 0 || !dataTable5.AsEnumerable().Any<DataRow>((DataRow v1) => {
+ if (v1.Field<object>("idvendedor") == null || v1.Field<long>("iddocumento") != x.Field<long>("iddocumento"))
+ {
+ return false;
+ }
+ return v1.Field<long>("idtipovendedor") == (long)1;
+ }) ? vendedor1 : Auxiliar.Vendedores.Find((Vendedor v) => {
+ EnumerableRowCollection<DataRow> dataRows = dataTable5.AsEnumerable();
+ Func<DataRow, bool> u003cu003e9_26 = func2;
+ if (u003cu003e9_26 == null)
+ {
+ Func<DataRow, bool> func = (DataRow v1) => {
+ if (v1.Field<long>("iddocumento") != x.Field<long>("iddocumento"))
+ {
+ return false;
+ }
+ return v1.Field<long>("idtipovendedor") == (long)1;
+ };
+ Func<DataRow, bool> func1 = func;
+ func2 = func;
+ u003cu003e9_26 = func1;
+ }
+ return dataRows.First<DataRow>(u003cu003e9_26).Field<long>("idvendedor") == v.Id;
+ }));
+ documento.Vendedores = Auxiliar.Vendedores.Where<Vendedor>((Vendedor v) => {
+ EnumerableRowCollection<DataRow> dataRows = dataTable5.AsEnumerable();
+ Func<DataRow, bool> u003cu003e9_27 = func3;
+ if (u003cu003e9_27 == null)
+ {
+ Func<DataRow, bool> func = (DataRow v1) => {
+ if (v1.Field<object>("idvendedor") == null)
+ {
+ return false;
+ }
+ return v1.Field<long>("iddocumento") == x.Field<long>("iddocumento");
+ };
+ Func<DataRow, bool> func1 = func;
+ func3 = func;
+ u003cu003e9_27 = func1;
+ }
+ EnumerableRowCollection<DataRow> dataRows1 = dataRows.Where<DataRow>(u003cu003e9_27);
+ Func<DataRow, long> u003cu003e9_1128 = DocumentoRepository.u003cu003ec.u003cu003e9__11_28;
+ if (u003cu003e9_1128 == null)
+ {
+ u003cu003e9_1128 = (DataRow v1) => v1.Field<long>("idvendedor");
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_28 = u003cu003e9_1128;
+ }
+ return dataRows1.Select<DataRow, long>(u003cu003e9_1128).Contains<long>(v.Id);
+ }).ToList<Vendedor>();
+ documento.NumeroParcelas = x.Field<int>("numeroParcelas");
+ if (!flag2 || dataTable6 == null)
+ {
+ list = null;
+ }
+ else
+ {
+ EnumerableRowCollection<DataRow> dataRows2 = dataTable6.AsEnumerable().Where<DataRow>((DataRow a) => a.Field<long>("DocumentoId") == x.Field<long>("iddocumento"));
+ Func<DataRow, StatusDocumentoAssinado> u003cu003e9_1122 = DocumentoRepository.u003cu003ec.u003cu003e9__11_22;
+ if (u003cu003e9_1122 == null)
+ {
+ u003cu003e9_1122 = (DataRow a) => new StatusDocumentoAssinado()
+ {
+ Id = a.Field<long>("idnewarquivodigital"),
+ Documento = a.Field<string>("descricao"),
+ Status = (StatusAssinatura)((a.Field<object>("Status") != null ? a.Field<int>("Status") : StatusAssinatura.Pendente)),
+ Envio = (a.Field<object>("Enviado") != null ? new DateTime?(a.Field<DateTime>("Enviado")) : null),
+ Usuario = (a.Field<object>("UsuarioId") != null ? Auxiliar.Usuarios.FirstOrDefault<Usuario>((Usuario u) => u.Id == a.Field<long>("UsuarioId")) : null)
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_22 = u003cu003e9_1122;
+ }
+ list = dataRows2.Select<DataRow, StatusDocumentoAssinado>(u003cu003e9_1122).ToList<StatusDocumentoAssinado>();
+ }
+ documento.Assinaturas = list;
+ documento.Pasta = x.Field<string>("Pasta");
+ documento.Banco = new Banco()
+ {
+ Nome = x.Field<string>("nomebanco")
+ };
+ documento.Agencia = x.Field<string>("agencia");
+ documento.Conta = x.Field<string>("conta");
+ documento.Excluido = (x.Field<object>("excluido") == null ? false : x.Field<object>("excluido").ToString() == "1");
+ documento.FormaPagamento = new FormaPagamento?((x.Field<object>("formapagamento") == null || !(x.Field<object>("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.Field<object>("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.Field<object>("formapagamento").ToString())));
+ return documento;
+ }).ToList<Documento>();
+ }
+ List<Documento> documentos2 = new List<Documento>();
+ List<long> nums4 = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(nums);
+ (
+ from x in dataTable3.AsEnumerable().Where<DataRow>((DataRow x) => {
+ if (nums3 == null)
+ {
+ return true;
+ }
+ return nums3.Contains(x.Field<long>("idcontrole"));
+ }).ToList<DataRow>()
+ orderby x.Field<long>("idcontrole")
+ group x by x.Field<long>("idcontrole")).ToList<IGrouping<long, DataRow>>().ForEach((IGrouping<long, DataRow> x) => {
+ long? nullable1;
+ bool count;
+ bool flag;
+ long? nullable2;
+ List<StatusDocumentoAssinado> statusDocumentoAssinados;
+ if (x == null || x.FirstOrDefault<DataRow>() == null)
+ {
+ return;
+ }
+ long num = (x.First<DataRow>().Field<object>("idempresa") != null ? x.First<DataRow>().Field<long>("idempresa") : (long)1);
+ Cliente cliente = new Cliente()
+ {
+ Id = idCliente,
+ Documento = x.First<DataRow>().Field<string>("cgccpf"),
+ MalaDireta = new bool?(x.First<DataRow>().Field<bool?>("MalaDireta").GetValueOrDefault(true))
+ };
+ Seguradora seguradora = (x.First<DataRow>().Field<object>("idciaseg") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.First<DataRow>().Field<long>("idciaseg")) : null);
+ Ramo ramo = (x.First<DataRow>().Field<object>("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.First<DataRow>().Field<long>("idramo")) : null);
+ Gestor.Model.Domain.Seguros.Produto produto = (x.First<DataRow>().Field<object>("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.First<DataRow>().Field<long>("idproduto")) : null);
+ EnumerableRowCollection<DataRow> dataRows1 = dataTable5.AsEnumerable().Where<DataRow>((DataRow v) => {
+ if (v.Field<object>("idvendedor") == null)
+ {
+ return false;
+ }
+ return v.Field<long>("iddocumento") == x.First<DataRow>().Field<long>("iddocumento");
+ });
+ DataTable dataTable = (!dataRows1.Any<DataRow>() ? null : dataRows1.CopyToDataTable<DataRow>());
+ DataTable dataTable1 = dataTable;
+ count = (dataTable1 != null ? dataTable1.Rows.Count > 0 : false);
+ List<Vendedor> vendedors = (count ? Auxiliar.Vendedores.Where<Vendedor>((Vendedor p) => {
+ EnumerableRowCollection<DataRow> dataRows = dataTable.AsEnumerable();
+ Func<DataRow, long> u003cu003e9_1145 = DocumentoRepository.u003cu003ec.u003cu003e9__11_45;
+ if (u003cu003e9_1145 == null)
+ {
+ u003cu003e9_1145 = (DataRow v) => v.Field<long>("idvendedor");
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_45 = u003cu003e9_1145;
+ }
+ return dataRows.Select<DataRow, long>(u003cu003e9_1145).Contains<long>(p.Id);
+ }).ToList<Vendedor>() : null);
+ DataTable dataTable2 = dataTable;
+ flag = (dataTable2 != null ? dataTable2.Rows.Count > 0 : false);
+ if (flag)
+ {
+ EnumerableRowCollection<DataRow> dataRows2 = dataTable.AsEnumerable();
+ Func<DataRow, object> u003cu003e9_1135 = DocumentoRepository.u003cu003ec.u003cu003e9__11_35;
+ if (u003cu003e9_1135 == null)
+ {
+ u003cu003e9_1135 = (DataRow v) => v.Field<object>("idsubtipo");
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_35 = u003cu003e9_1135;
+ }
+ OrderedEnumerableRowCollection<DataRow> orderedEnumerableRowCollection = dataRows2.OrderBy<DataRow, object>(u003cu003e9_1135);
+ Func<DataRow, object> u003cu003e9_1136 = DocumentoRepository.u003cu003ec.u003cu003e9__11_36;
+ if (u003cu003e9_1136 == null)
+ {
+ u003cu003e9_1136 = (DataRow v) => v.Field<object>("IDPARCELA");
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_36 = u003cu003e9_1136;
+ }
+ List<DataRow> dataRows3 = orderedEnumerableRowCollection.ThenBy<DataRow, object>(u003cu003e9_1136).ToList<DataRow>();
+ Predicate<DataRow> u003cu003e9_1137 = DocumentoRepository.u003cu003ec.u003cu003e9__11_37;
+ if (u003cu003e9_1137 == null)
+ {
+ u003cu003e9_1137 = (DataRow v) => v.Field<long>("idtipovendedor") == (long)1;
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_37 = u003cu003e9_1137;
+ }
+ DataRow dataRow = dataRows3.Find(u003cu003e9_1137);
+ if (dataRow != null)
+ {
+ nullable2 = new long?(dataRow.Field<long>("idvendedor"));
+ }
+ else
+ {
+ nullable1 = null;
+ nullable2 = nullable1;
+ }
+ }
+ else
+ {
+ nullable1 = null;
+ nullable2 = nullable1;
+ }
+ long? nullable3 = nullable2;
+ Vendedor vendedor = (!nullable3.HasValue ? vendedor1 : Auxiliar.Vendedores.Find((Vendedor p) => {
+ long? nullable = nullable3;
+ long id = p.Id;
+ return nullable.GetValueOrDefault() == id & nullable.HasValue;
+ }));
+ bool flag1 = (nums4 == null ? false : nums4.Any<long>((long s) => s == x.First<DataRow>().Field<long>("idcontrole")));
+ IEnumerable<DataRow> dataRows4 =
+ from e in dataTable4.AsEnumerable().ToList<DataRow>()
+ where e.Field<long>("idcontrole") == x.Key
+ select e;
+ Func<DataRow, int> u003cu003e9_1141 = DocumentoRepository.u003cu003ec.u003cu003e9__11_41;
+ if (u003cu003e9_1141 == null)
+ {
+ u003cu003e9_1141 = (DataRow e) => e.Field<int>("tipo");
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_41 = u003cu003e9_1141;
+ }
+ List<DataRow> dataRows5 = dataRows4.OrderBy<DataRow, int>(u003cu003e9_1141).ToList<DataRow>();
+ List<Calculo> calculos1 = null;
+ if (dataTable7 != null)
+ {
+ EnumerableRowCollection<DataRow> dataRows6 = dataTable7.AsEnumerable().Where<DataRow>((DataRow c) => c.Field<long>("IdDocumento") == x.First<DataRow>().Field<long>("iddocumento"));
+ Func<DataRow, Calculo> u003cu003e9_1143 = DocumentoRepository.u003cu003ec.u003cu003e9__11_43;
+ if (u003cu003e9_1143 == null)
+ {
+ u003cu003e9_1143 = (DataRow c) => new Calculo()
+ {
+ Id = c.Field<long>("Id"),
+ DocumentId = c.Field<long>("IdDocumento"),
+ DataAtualizacao = c.Field<DateTime>("DataAtualizacao"),
+ Status = (StatusCalculo)c.Field<int>("Status"),
+ Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field<long>("IdUsuario"))
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_43 = u003cu003e9_1143;
+ }
+ calculos1 = dataRows6.Select<DataRow, Calculo>(u003cu003e9_1143).ToList<Calculo>();
+ if (dataRows5.Count > 0)
+ {
+ dataRows5.ForEach((DataRow e) => {
+ List<Calculo> calculos = calculos1;
+ EnumerableRowCollection<DataRow> dataRows = dataTable7.AsEnumerable().Where<DataRow>((DataRow c) => c.Field<long>("IdDocumento") == e.Field<long>("iddocumento"));
+ Func<DataRow, Calculo> u003cu003e9_1148 = DocumentoRepository.u003cu003ec.u003cu003e9__11_48;
+ if (u003cu003e9_1148 == null)
+ {
+ u003cu003e9_1148 = (DataRow c) => new Calculo()
+ {
+ Id = c.Field<long>("Id"),
+ DocumentId = c.Field<long>("IdDocumento"),
+ DataAtualizacao = c.Field<DateTime>("DataAtualizacao"),
+ Status = (StatusCalculo)c.Field<int>("Status"),
+ Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field<long>("IdUsuario"))
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_48 = u003cu003e9_1148;
+ }
+ calculos.AddRange(dataRows.Select<DataRow, Calculo>(u003cu003e9_1148).ToList<Calculo>());
+ });
+ }
+ }
+ Documento banco = new Documento()
+ {
+ Id = x.First<DataRow>().Field<long>("iddocumento"),
+ Controle = new Controle()
+ {
+ Id = x.Key,
+ IdEmpresa = num,
+ Cliente = cliente,
+ Seguradora = seguradora,
+ Ramo = ramo,
+ Produto = produto,
+ AssistenciaId = x.First<DataRow>().Field<string>("AssistenciaId")
+ },
+ Ordem = x.First<DataRow>().Field<int>("ordem"),
+ TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.First<DataRow>().Field<object>("tiporecebimento").ToString())),
+ AdicionalComiss = x.First<DataRow>().Field<string>("adinacomis") == "1",
+ Proposta = x.First<DataRow>().Field<string>("proposta"),
+ Apolice = x.First<DataRow>().Field<string>("contrato"),
+ Endosso = x.First<DataRow>().Field<string>("aditamento"),
+ Comissao = (x.First<DataRow>().Field<object>("com01") == null ? decimal.Zero : x.First<DataRow>().Field<decimal>("com01")),
+ Negocio = new Negocio?((x.First<DataRow>().Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.First<DataRow>().Field<object>("idnegocio").ToString()))),
+ PremioLiquido = (!x.First<DataRow>().Field<decimal?>("pr_liq").HasValue ? decimal.Zero : x.First<DataRow>().Field<decimal>("pr_liq")),
+ PremioAdicional = (!x.First<DataRow>().Field<decimal?>("pr_adic").HasValue ? decimal.Zero : x.First<DataRow>().Field<decimal>("pr_adic")),
+ PremioTotal = (!x.First<DataRow>().Field<decimal?>("pr_total").HasValue ? decimal.Zero : x.First<DataRow>().Field<decimal>("pr_total")),
+ Vigencia2 = x.First<DataRow>().Field<DateTime?>("vigencia2")
+ };
+ DateTime? nullable4 = x.First<DataRow>().Field<DateTime?>("vigencia1");
+ banco.Vigencia1 = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue);
+ banco.Emissao = x.First<DataRow>().Field<DateTime?>("emissao");
+ banco.Remessa = x.First<DataRow>().Field<DateTime?>("remessa");
+ banco.Estipulante1 = (x.First<DataRow>().Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.First<DataRow>().Field<long>("idestipulante")) : null);
+ banco.NegocioCorretora = new NegocioCorretora?((x.First<DataRow>().Field<object>("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.First<DataRow>().Field<object>("negociocorretora").ToString())));
+ banco.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.First<DataRow>().Field<object>("situacao").ToString());
+ banco.Tipo = x.First<DataRow>().Field<int>("tipo");
+ banco.VendedorPrincipal = vendedor;
+ banco.Sinistro = flag1;
+ banco.TemEndosso = dataRows5.Count > 0;
+ banco.Vendedores = vendedors;
+ banco.Observacao = x.First<DataRow>().Field<string>("Obs");
+ banco.NumeroParcelas = x.First<DataRow>().Field<int>("numeroParcelas");
+ if (!flag2 || dataTable6 == null)
+ {
+ statusDocumentoAssinados = null;
+ }
+ else
+ {
+ EnumerableRowCollection<DataRow> dataRows7 = dataTable6.AsEnumerable().Where<DataRow>((DataRow a) => a.Field<long>("DocumentoId") == x.First<DataRow>().Field<long>("iddocumento"));
+ Func<DataRow, StatusDocumentoAssinado> u003cu003e9_1152 = DocumentoRepository.u003cu003ec.u003cu003e9__11_52;
+ if (u003cu003e9_1152 == null)
+ {
+ u003cu003e9_1152 = (DataRow a) => new StatusDocumentoAssinado()
+ {
+ Id = a.Field<long>("idnewarquivodigital"),
+ Documento = a.Field<string>("descricao"),
+ Status = (StatusAssinatura)((a.Field<object>("Status") != null ? a.Field<int>("Status") : StatusAssinatura.Pendente)),
+ Envio = (a.Field<object>("Enviado") != null ? new DateTime?(a.Field<DateTime>("Enviado")) : null),
+ Usuario = (a.Field<object>("UsuarioId") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == a.Field<long>("UsuarioId")) : null)
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_52 = u003cu003e9_1152;
+ }
+ statusDocumentoAssinados = dataRows7.Select<DataRow, StatusDocumentoAssinado>(u003cu003e9_1152).ToList<StatusDocumentoAssinado>();
+ }
+ banco.Assinaturas = statusDocumentoAssinados;
+ banco.Pasta = x.First<DataRow>().Field<string>("Pasta");
+ banco.Banco = new Banco()
+ {
+ Nome = x.First<DataRow>().Field<string>("nomebanco")
+ };
+ banco.Agencia = x.First<DataRow>().Field<string>("agencia");
+ banco.Conta = x.First<DataRow>().Field<string>("conta");
+ banco.Excluido = (x.First<DataRow>().Field<object>("excluido") == null ? false : x.First<DataRow>().Field<object>("excluido").ToString() == "1");
+ banco.NumeroCartao = x.First<DataRow>().Field<string>("numeroCart");
+ banco.VencimentoCartao = x.First<DataRow>().Field<string>("vencimentoCart");
+ banco.NomeProponente = x.First<DataRow>().Field<string>("nomeProp");
+ banco.Calculos = calculos1;
+ banco.FormaPagamento = new FormaPagamento?((x.First<DataRow>().Field<object>("formapagamento") == null || !(x.First<DataRow>().Field<object>("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.First<DataRow>().Field<object>("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.First<DataRow>().Field<object>("formapagamento").ToString())));
+ Documento documento1 = banco;
+ List<Documento> documentos = new List<Documento>()
+ {
+ documento1
+ };
+ if (dataRows5.Count > 0)
+ {
+ List<DataRow> dataRows8 = dataRows5;
+ Func<DataRow, int> u003cu003e9_1154 = DocumentoRepository.u003cu003ec.u003cu003e9__11_54;
+ if (u003cu003e9_1154 == null)
+ {
+ u003cu003e9_1154 = (DataRow e) => e.Field<int>("ordem");
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_54 = u003cu003e9_1154;
+ }
+ documentos.AddRange(dataRows8.OrderBy<DataRow, int>(u003cu003e9_1154).Select<DataRow, Documento>((DataRow e) => {
+ List<StatusDocumentoAssinado> list;
+ Documento documento = new Documento()
+ {
+ Id = e.Field<long>("iddocumento"),
+ Controle = new Controle()
+ {
+ Id = x.Key,
+ IdEmpresa = num,
+ Cliente = cliente,
+ Seguradora = seguradora,
+ Ramo = ramo,
+ Produto = produto,
+ AssistenciaId = x.First<DataRow>().Field<string>("AssistenciaId")
+ },
+ Ordem = e.Field<int>("ordem"),
+ TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), e.Field<object>("tiporecebimento").ToString())),
+ AdicionalComiss = e.Field<string>("adinacomis") == "1",
+ Proposta = e.Field<string>("proposta"),
+ Apolice = e.Field<string>("contrato"),
+ PropostaEndosso = e.Field<string>("pedadit"),
+ Endosso = e.Field<string>("aditamento"),
+ Comissao = (e.Field<object>("com01") == null ? decimal.Zero : e.Field<decimal>("com01")),
+ Negocio = new Negocio?((e.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), e.Field<object>("idnegocio").ToString()))),
+ PremioLiquido = e.Field<decimal>("pr_liq"),
+ PremioAdicional = e.Field<decimal>("pr_adic"),
+ PremioTotal = e.Field<decimal>("pr_total"),
+ Vigencia2 = e.Field<DateTime?>("vigencia2")
+ };
+ DateTime? nullable = e.Field<DateTime?>("vigencia1");
+ documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ documento.Emissao = e.Field<DateTime?>("emissao");
+ documento.Remessa = e.Field<DateTime?>("remessa");
+ documento.Estipulante1 = (e.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == e.Field<long>("idestipulante")) : null);
+ documento.NegocioCorretora = new NegocioCorretora?((e.Field<object>("negociocorretora") == null ? NegocioCorretora.Proprio : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), e.Field<object>("negociocorretora").ToString())));
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), e.Field<object>("situacao").ToString());
+ documento.Tipo = e.Field<int>("tipo");
+ documento.Sinistro = flag1;
+ documento.NumeroParcelas = e.Field<int>("numeroParcelas");
+ if (!flag2 || dataTable6 == null)
+ {
+ list = null;
+ }
+ else
+ {
+ EnumerableRowCollection<DataRow> dataRows = dataTable6.AsEnumerable().Where<DataRow>((DataRow a) => a.Field<long>("DocumentoId") == e.Field<long>("iddocumento"));
+ Func<DataRow, StatusDocumentoAssinado> u003cu003e9_1158 = DocumentoRepository.u003cu003ec.u003cu003e9__11_58;
+ if (u003cu003e9_1158 == null)
+ {
+ u003cu003e9_1158 = (DataRow a) => new StatusDocumentoAssinado()
+ {
+ Id = a.Field<long>("idnewarquivodigital"),
+ Documento = a.Field<string>("descricao"),
+ Status = (StatusAssinatura)((a.Field<object>("Status") != null ? a.Field<int>("Status") : StatusAssinatura.Pendente)),
+ Envio = (a.Field<object>("Enviado") != null ? new DateTime?(a.Field<DateTime>("Enviado")) : null),
+ Usuario = (a.Field<object>("UsuarioId") != null ? Auxiliar.Usuarios.Find((Usuario u) => u.Id == a.Field<long>("UsuarioId")) : null)
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__11_58 = u003cu003e9_1158;
+ }
+ list = dataRows.Select<DataRow, StatusDocumentoAssinado>(u003cu003e9_1158).ToList<StatusDocumentoAssinado>();
+ }
+ documento.Assinaturas = list;
+ documento.Pasta = e.Field<string>("Pasta");
+ documento.Banco = new Banco()
+ {
+ Nome = e.Field<string>("nomebanco")
+ };
+ documento.Agencia = e.Field<string>("agencia");
+ documento.Conta = e.Field<string>("conta");
+ documento.Excluido = (e.Field<object>("excluido") == null ? false : e.Field<object>("excluido").ToString() == "1");
+ documento.FormaPagamento = new FormaPagamento?((x.First<DataRow>().Field<object>("formapagamento") == null || !(x.First<DataRow>().Field<object>("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.First<DataRow>().Field<object>("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.First<DataRow>().Field<object>("formapagamento").ToString())));
+ return documento;
+ }).ToList<Documento>());
+ }
+ documento1.Controle.Documentos = documentos;
+ documentos2.Add(documento1);
+ });
+ return documentos2;
+ }
+ default:
+ {
+ condicaos1.AddRange(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = new List<object>()
+ {
+ 1,
+ 2,
+ 4
+ }
+ },
+ new Condicao()
+ {
+ Campo = "d.vigencia2",
+ Valores = null,
+ Grupo = 2,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.vigencia2",
+ Valores = date.AddDays(-5).CriarValor<DateTime>(),
+ Grupo = 2,
+ Operacao = Operacao.Or,
+ Operador = Operador.Maior
+ }
+ });
+ goto case FiltroStatusDocumento.Todos;
+ }
+ }
+ return documentos1;
+ }
+
+ public List<Documento> FindByControle(long id)
+ {
+ List<DocumentoDb> list = (
+ from x in base.All()
+ where x.Controle.Id == id && !x.Excluido
+ select x).ToList<DocumentoDb>();
+ return ApplicationMapper.Mapper.Map<List<DocumentoDb>, List<Documento>>(list);
+ }
+
+ public Documento FindById(long id, bool itens = false, bool sinistrosPorControle = false)
+ {
+ DocumentoDb documentoDb = base.FindEntityById(id);
+ Documento documento = ApplicationMapper.Mapper.Map<DocumentoDb, Documento>(documentoDb);
+ if (documento == null)
+ {
+ return null;
+ }
+ documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(id);
+ documento.Sinistro = (sinistrosPorControle ? this.HasSinistroPorControle(documento.Controle.Id) : this.HasSinistro(documento.Id));
+ if (itens)
+ {
+ documento.ItensAtivo = (new ItemRepository(this._unitOfWork)).FindByDocumentsIds(documento.Controle.Id, StatusItem.Ativos, false);
+ }
+ return documento;
+ }
+
+ public Documento FindById(long id, List<VendedorUsuario> vendedorVinculado)
+ {
+ DocumentoDb documentoDb = base.FindEntityById(id);
+ Documento documento = ApplicationMapper.Mapper.Map<DocumentoDb, Documento>(documentoDb);
+ if (documento == null)
+ {
+ return null;
+ }
+ documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(id);
+ documento.Vendedores = (new VendedorParcelaRepository(this._unitOfWork)).FindVendedoresByDocumentId(id);
+ documento.Sinistro = this.HasSinistro(documento.Id);
+ if (vendedorVinculado.Count <= 0)
+ {
+ return documento;
+ }
+ if (!documento.Vendedores.Any<Vendedor>((Vendedor y) => {
+ List<VendedorUsuario> vendedorUsuarios = vendedorVinculado;
+ Func<VendedorUsuario, long> u003cu003e9_31 = DocumentoRepository.u003cu003ec.u003cu003e9__3_1;
+ if (u003cu003e9_31 == null)
+ {
+ u003cu003e9_31 = (VendedorUsuario x) => x.Vendedor.Id;
+ DocumentoRepository.u003cu003ec.u003cu003e9__3_1 = u003cu003e9_31;
+ }
+ return vendedorUsuarios.Select<VendedorUsuario, long>(u003cu003e9_31).Contains<long>(y.Id);
+ }))
+ {
+ return null;
+ }
+ return documento;
+ }
+
+ public List<Documento> FindByIds(List<long> ids)
+ {
+ if (ids == null || ids.Count == 0)
+ {
+ return new List<Documento>();
+ }
+ return this.Select((new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.iddocumento",
+ Valores = ids.CriarValor<long>()
+ }
+ }).CreateParameters(0));
+ }
+
+ public List<Documento> FindByLicenciamento(Filtros filtro)
+ {
+ List<long> j;
+ List<Documento> documentos;
+ object connection;
+ List<long> nums = null;
+ long num;
+ List<int> nums1 = new List<int>();
+ for (int i1 = filtro.ValorInicio; i1 <= filtro.ValorFim; i1++)
+ {
+ nums1.Add(i1);
+ }
+ string str = string.Concat("AND SUBSTRING(a.placa, len(a.placa), 1) IN ('", string.Join<int>("','",
+ from v in nums1
+ select v), "')");
+ string str1 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join<long>(",",
+ from v in filtro.Status
+ select v), ")"));
+ string str2 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join<long>(",",
+ from v in filtro.Negocio
+ select v), ")"));
+ string str3 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",",
+ from v in filtro.Seguradoras
+ select v), ")"));
+ string str4 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",",
+ from v in filtro.Ramos
+ select v), ")"));
+ string str5 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",",
+ from v in filtro.Produtos
+ select v), ")"));
+ string str6 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",",
+ from v in filtro.Vendedores
+ select v), ")"));
+ string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",",
+ from v in filtro.Estipulantes
+ select v), ")"));
+ string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa));
+ DataTable dataTable = new DataTable();
+ DataTable dataTable1 = new DataTable();
+ DataTable dataTable2 = new DataTable();
+ DataTable dataTable3 = new DataTable();
+ DataTable dataTable4 = new DataTable();
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ Auxiliar.CriarAuxiliar(sqlCommand, false);
+ string str9 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao, a.placa, a.idcategoria FROM auto a INNER JOIN item i ON a.iditem = i.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (d.excluido IS NULL OR d.excluido = '0') AND d.situacao in (1,2,4) AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL AND a.placa IS NOT NULL ";
+ string str10 = "SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf as documento, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.remessa, d.aditamento as endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.pasta, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp WHERE (d.excluido IS NULL OR d.excluido = 0) AND d.vigencia2 >= GETDATE() ";
+ string str11 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 ";
+ string str12 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 ";
+ sqlCommand.CommandText = string.Concat(str9, " ", str);
+ using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
+ {
+ sqlDataAdapter.SelectCommand = sqlCommand;
+ sqlDataAdapter.Fill(dataTable2);
+ }
+ if (dataTable2.Rows.Count != 0)
+ {
+ for (j = dataTable2.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("iddocumento")).Distinct<long>().ToList<long>(); j.Count > 0; j = nums)
+ {
+ List<long> nums2 = j.Take<long>(2000).ToList<long>();
+ string str13 = string.Concat(" AND d.iddocumento IN (", string.Join<long>(",", nums2), ")");
+ DataTable dataTable5 = new DataTable();
+ sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str8, " ", str13, " ", str1, " ", str2, " ", str3, " ", str4, " ", str5, " ", str7, " ", str6 });
+ using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter())
+ {
+ sqlDataAdapter1.SelectCommand = sqlCommand;
+ sqlDataAdapter1.Fill(dataTable5);
+ }
+ dataTable.Merge(dataTable5);
+ nums = (nums2.Count < 2000 ? new List<long>() : j.Except<long>(nums2).ToList<long>());
+ }
+ if (dataTable.Rows.Count != 0)
+ {
+ if (dataTable.AsEnumerable().Any<DataRow>((DataRow x) => x.Field<object>("idvendedor") == null))
+ {
+ string str14 = string.Concat(" AND d.idcontrole IN (", string.Join<long>(",", dataTable.AsEnumerable().Where<DataRow>((DataRow x) => x.Field<object>("idvendedor") == null).Select<DataRow, long>((DataRow v) => v.Field<long>("idcontrole"))), ")");
+ DataTable dataTable6 = new DataTable();
+ sqlCommand.CommandText = string.Concat(new string[] { str11, " ", str14, " ", str6 });
+ using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter())
+ {
+ sqlDataAdapter2.SelectCommand = sqlCommand;
+ sqlDataAdapter2.Fill(dataTable6);
+ }
+ foreach (DataRow row in dataTable.Rows)
+ {
+ if (!string.IsNullOrEmpty(row["idvendedor"].ToString()))
+ {
+ continue;
+ }
+ string str15 = string.Format("idcontrole = {0}", row["idcontrole"]);
+ DataRow[] dataRowArray = dataTable6.Select(str15);
+ if (dataRowArray.Length == 0)
+ {
+ continue;
+ }
+ row["idvendedor"] = dataRowArray[0][1];
+ }
+ }
+ j = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("idcliente")).Distinct<long>().ToList<long>();
+ string str16 = string.Concat(" AND vp.iddocumento IN (", string.Join<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
+ sqlCommand.CommandText = string.Concat(str12, " ", str16);
+ using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter())
+ {
+ sqlDataAdapter3.SelectCommand = sqlCommand;
+ sqlDataAdapter3.Fill(dataTable1);
+ }
+ while (j.Count > 0)
+ {
+ List<long> nums3 = j.Take<long>(2100).ToList<long>();
+ string str17 = string.Concat(" AND idcliente IN (", string.Join<long>(",", nums3), ")");
+ DataTable dataTable7 = new DataTable();
+ sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') ", str17);
+ using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter())
+ {
+ sqlDataAdapter4.SelectCommand = sqlCommand;
+ sqlDataAdapter4.Fill(dataTable7);
+ }
+ dataTable3.Merge(dataTable7);
+ dataTable7 = new DataTable();
+ sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 ", str17);
+ using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter())
+ {
+ sqlDataAdapter5.SelectCommand = sqlCommand;
+ sqlDataAdapter5.Fill(dataTable7);
+ }
+ dataTable4.Merge(dataTable7);
+ j = (nums3.Count < 2100 ? new List<long>() : j.Except<long>(nums3).ToList<long>());
+ }
+ goto Label0;
+ }
+ else
+ {
+ documentos = new List<Documento>();
+ }
+ }
+ else
+ {
+ documentos = new List<Documento>();
+ }
+ }
+ }
+ return documentos;
+ Label0:
+ return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, Documento>((DataRow x) => {
+ Func<DataRow, bool> func2 = null;
+ Documento documento = new Documento()
+ {
+ Id = x.Field<long>("id")
+ };
+ Controle controle = new Controle()
+ {
+ IdEmpresa = x.Field<long>("idempresa")
+ };
+ Cliente cliente = new Cliente()
+ {
+ Id = x.Field<long>("idcliente"),
+ Nome = x.Field<string>("cliente"),
+ Documento = x.Field<string>("documento"),
+ IdEmpresa = x.Field<long>("idempresa")
+ };
+ EnumerableRowCollection<DataRow> dataRows1 = dataTable4.AsEnumerable().Where<DataRow>((DataRow t) => t.Field<long>("idcliente") == x.Field<long>("idcliente"));
+ Func<DataRow, ClienteTelefone> u003cu003e9_1525 = DocumentoRepository.u003cu003ec.u003cu003e9__15_25;
+ if (u003cu003e9_1525 == null)
+ {
+ u003cu003e9_1525 = (DataRow t) => new ClienteTelefone()
+ {
+ Id = t.Field<long>("idclitelefone"),
+ Prefixo = t.Field<string>("ddd"),
+ Numero = t.Field<string>("fone")
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__15_25 = u003cu003e9_1525;
+ }
+ cliente.Telefones = new ObservableCollection<ClienteTelefone>(dataRows1.Select<DataRow, ClienteTelefone>(u003cu003e9_1525));
+ EnumerableRowCollection<DataRow> dataRows2 = dataTable3.AsEnumerable().Where<DataRow>((DataRow t) => t.Field<long>("idcliente") == x.Field<long>("idcliente"));
+ Func<DataRow, ClienteEmail> u003cu003e9_1527 = DocumentoRepository.u003cu003ec.u003cu003e9__15_27;
+ if (u003cu003e9_1527 == null)
+ {
+ u003cu003e9_1527 = (DataRow t) => new ClienteEmail()
+ {
+ Id = t.Field<long>("idclimail"),
+ Email = t.Field<string>("email")
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__15_27 = u003cu003e9_1527;
+ }
+ cliente.Emails = new ObservableCollection<ClienteEmail>(dataRows2.Select<DataRow, ClienteEmail>(u003cu003e9_1527));
+ cliente.Pasta = x.Field<string>("pastacliente");
+ cliente.MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true));
+ controle.Cliente = cliente;
+ controle.Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null);
+ controle.Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null);
+ controle.Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Gestor.Model.Domain.Seguros.Produto>((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field<long>("idproduto")) : null);
+ controle.AssistenciaId = x.Field<string>("AssistenciaId");
+ documento.Controle = controle;
+ documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela);
+ documento.AdicionalComiss = x.Field<string>("adinacomiss") == "1";
+ documento.Apolice = x.Field<string>("apolice");
+ documento.Endosso = (x.Field<int>("tipo") == 0 ? "" : x.Field<string>("endosso") ?? "");
+ documento.Comissao = x.Field<decimal>("comissao");
+ documento.Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString())));
+ documento.PremioLiquido = x.Field<decimal>("liquido");
+ documento.PremioTotal = x.Field<decimal>("total");
+ documento.Vigencia2 = x.Field<DateTime?>("vigenciafinal");
+ DateTime? nullable2 = x.Field<DateTime?>("vigenciainicial");
+ documento.Vigencia1 = (nullable2.HasValue ? nullable2.GetValueOrDefault() : DateTime.MinValue);
+ documento.Emissao = x.Field<DateTime?>("emissao");
+ documento.Remessa = x.Field<DateTime?>("remessa");
+ documento.VendedorPrincipal = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")) : null);
+ documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
+ documento.NegocioCorretora = new NegocioCorretora?((x.Field<object>("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString()) != TipoSeguro.Renovacao || x.Field<object>("idnegocio") == null || !(x.Field<object>("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field<object>("negociocorretora").ToString())));
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
+ documento.Vendedores = Auxiliar.Vendedores.Where<Vendedor>((Vendedor v) => {
+ List<DataRow> list = dataTable1.AsEnumerable().ToList<DataRow>();
+ Func<DataRow, bool> u003cu003e9_28 = func2;
+ if (u003cu003e9_28 == null)
+ {
+ Func<DataRow, bool> func = (DataRow d) => d.Field<long>("id") == x.Field<long>("id");
+ Func<DataRow, bool> func1 = func;
+ func2 = func;
+ u003cu003e9_28 = func1;
+ }
+ IEnumerable<DataRow> dataRows = list.Where<DataRow>(u003cu003e9_28);
+ Func<DataRow, long> u003cu003e9_1529 = DocumentoRepository.u003cu003ec.u003cu003e9__15_29;
+ if (u003cu003e9_1529 == null)
+ {
+ u003cu003e9_1529 = (DataRow d) => d.Field<long>("idvendedor");
+ DocumentoRepository.u003cu003ec.u003cu003e9__15_29 = u003cu003e9_1529;
+ }
+ return dataRows.Select<DataRow, long>(u003cu003e9_1529).ToList<long>().Contains(v.Id);
+ }).ToList<Vendedor>();
+ documento.Tipo = x.Field<int>("tipo");
+ documento.DataControle = x.Field<DateTime?>("datacontrole");
+ documento.Status = (x.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault<Status>((Status p) => p.Id == x.Field<long>("idstatus")) : null);
+ documento.ItensAtivo = new List<Item>(dataTable2.AsEnumerable().ToList<DataRow>().Where<DataRow>((DataRow i) => {
+ if (i.Field<object>("idcontrole") == null || !long.TryParse(i.Field<object>("idcontrole").ToString(), out num))
+ {
+ return false;
+ }
+ return i.Field<long>("idcontrole") == x.Field<long>("idcontrole");
+ }).Select<DataRow, Item>((DataRow i) => {
+ Categoria? nullable;
+ Categoria? nullable1;
+ Item item = new Item()
+ {
+ Id = i.Field<long>("iditem"),
+ Descricao = i.Field<string>("descricao"),
+ Documento = new Documento()
+ {
+ Id = x.Field<long>("id")
+ }
+ };
+ Auto auto = new Auto();
+ if (i.Field<object>("idcategoria") == null)
+ {
+ nullable = null;
+ nullable1 = nullable;
+ }
+ else if (i.Field<object>("idcategoria").ToString() == "")
+ {
+ nullable = null;
+ nullable1 = nullable;
+ }
+ else
+ {
+ nullable1 = (Categoria?)Enum.Parse(typeof(Categoria), i.Field<object>("idcategoria").ToString());
+ }
+ auto.Categoria = nullable1;
+ auto.Placa = i.Field<string>("placa");
+ item.Auto = auto;
+ return item;
+ }).ToList<Item>());
+ documento.Pasta = x.Field<string>("Pasta");
+ return documento;
+ }).ToList<Documento>();
+ }
+
+ public List<Documento> FindByParcelaIds(List<long> ids)
+ {
+ if (ids == null || ids.Count == 0)
+ {
+ return new List<Documento>();
+ }
+ List<long> nums = (new ParcelaRepository(this._unitOfWork)).FindDocumentId(ids);
+ return this.Select((new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.iddocumento",
+ Valores = nums.CriarValor<long>()
+ }
+ }).CreateParameters(0));
+ }
+
+ public List<Documento> FindByPlaca(Filtros filtro)
+ {
+ List<long> i;
+ List<Documento> documentos1;
+ object connection;
+ List<long> nums = null;
+ string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join<long>(",",
+ from v in filtro.Status
+ select v), ")"));
+ string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join<long>(",",
+ from v in filtro.Negocio
+ select v), ")"));
+ string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",",
+ from v in filtro.Seguradoras
+ select v), ")"));
+ string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",",
+ from v in filtro.Ramos
+ select v), ")"));
+ string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",",
+ from v in filtro.Produtos
+ select v), ")"));
+ string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",",
+ from v in filtro.Vendedores
+ select v), ")"));
+ string str6 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",",
+ from v in filtro.Estipulantes
+ select v), ")"));
+ string str7 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa));
+ DataTable dataTable = new DataTable();
+ DataTable dataTable1 = new DataTable();
+ DataTable dataTable2 = new DataTable();
+ DataTable dataTable3 = new DataTable();
+ DataTable dataTable4 = new DataTable();
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ Auxiliar.CriarAuxiliar(sqlCommand, false);
+ object date = filtro.Inicio.Date;
+ DateTime fim = filtro.Fim;
+ string str8 = string.Format("SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao, a.placa, a.idcategoria FROM auto a INNER JOIN item i ON a.iditem = i.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (d.excluido IS NULL OR d.excluido = '0') {0} AND (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL AND d.vigencia2 >= '{1:yyyy-MM-dd}' AND d.vigencia2 <= '{2:yyyy-MM-dd}'", str, date, fim.Date);
+ object obj = filtro.Inicio.Date;
+ fim = filtro.Fim;
+ string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf as documento, d.idcontrole, d.iddocumento as id, d.contrato as apolice, d.emissao, d.remessa, d.aditamento as endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.idnegocio, d.datacontrole, d.idstatus, d.pasta, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp ", string.Format("WHERE (d.excluido IS NULL OR d.excluido = 0) AND d.vigencia2 >= '{0:yyyy-MM-dd}' AND d.vigencia2 <= '{1:yyyy-MM-dd}'", obj, fim.Date));
+ string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 ";
+ string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 ";
+ sqlCommand.CommandText = str8 ?? "";
+ using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
+ {
+ sqlDataAdapter.SelectCommand = sqlCommand;
+ sqlDataAdapter.Fill(dataTable2);
+ }
+ if (dataTable2.Rows.Count != 0)
+ {
+ for (i = dataTable2.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("iddocumento")).Distinct<long>().ToList<long>(); i.Count > 0; i = nums)
+ {
+ List<long> nums1 = i.Take<long>(2000).ToList<long>();
+ string str12 = string.Concat(" AND d.iddocumento IN (", string.Join<long>(",", nums1), ")");
+ DataTable dataTable5 = new DataTable();
+ sqlCommand.CommandText = string.Concat(new string[] { str9, " ", str7, " ", str12, " ", str, " ", str1, " ", str2, " ", str3, " ", str4, " ", str6, " ", str5 });
+ using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter())
+ {
+ sqlDataAdapter1.SelectCommand = sqlCommand;
+ sqlDataAdapter1.Fill(dataTable5);
+ }
+ dataTable.Merge(dataTable5);
+ nums = (nums1.Count < 2000 ? new List<long>() : i.Except<long>(nums1).ToList<long>());
+ }
+ if (dataTable.Rows.Count != 0)
+ {
+ if (dataTable.AsEnumerable().Any<DataRow>((DataRow x) => x.Field<object>("idvendedor") == null))
+ {
+ string str13 = string.Concat(" AND d.idcontrole IN (", string.Join<long>(",", dataTable.AsEnumerable().Where<DataRow>((DataRow x) => x.Field<object>("idvendedor") == null).Select<DataRow, long>((DataRow v) => v.Field<long>("idcontrole"))), ")");
+ DataTable dataTable6 = new DataTable();
+ sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str13, " ", str5 });
+ using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter())
+ {
+ sqlDataAdapter2.SelectCommand = sqlCommand;
+ sqlDataAdapter2.Fill(dataTable6);
+ }
+ foreach (DataRow row in dataTable.Rows)
+ {
+ if (!string.IsNullOrEmpty(row["idvendedor"].ToString()))
+ {
+ continue;
+ }
+ string str14 = string.Format("idcontrole = {0}", row["idcontrole"]);
+ DataRow[] dataRowArray = dataTable6.Select(str14);
+ if (dataRowArray.Length == 0)
+ {
+ continue;
+ }
+ row["idvendedor"] = dataRowArray[0][1];
+ }
+ }
+ i = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("idcliente")).Distinct<long>().ToList<long>();
+ string str15 = string.Concat(" AND vp.iddocumento IN (", string.Join<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
+ sqlCommand.CommandText = string.Concat(str11, " ", str15);
+ using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter())
+ {
+ sqlDataAdapter3.SelectCommand = sqlCommand;
+ sqlDataAdapter3.Fill(dataTable1);
+ }
+ while (i.Count > 0)
+ {
+ List<long> nums2 = i.Take<long>(2100).ToList<long>();
+ string str16 = string.Concat(" AND idcliente IN (", string.Join<long>(",", nums2), ")");
+ DataTable dataTable7 = new DataTable();
+ sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclimail, email, idcliente FROM climail WHERE (ORDEM = '1' OR PADRAO = '1') ", str16);
+ using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter())
+ {
+ sqlDataAdapter4.SelectCommand = sqlCommand;
+ sqlDataAdapter4.Fill(dataTable7);
+ }
+ dataTable3.Merge(dataTable7);
+ dataTable7 = new DataTable();
+ sqlCommand.CommandText = string.Concat("SELECT DISTINCT idclitelefone, ddd, fone, idcliente FROM clitelefone WHERE 1=1 ", str16);
+ using (SqlDataAdapter sqlDataAdapter5 = new SqlDataAdapter())
+ {
+ sqlDataAdapter5.SelectCommand = sqlCommand;
+ sqlDataAdapter5.Fill(dataTable7);
+ }
+ dataTable4.Merge(dataTable7);
+ i = (nums2.Count < 2100 ? new List<long>() : i.Except<long>(nums2).ToList<long>());
+ }
+ goto Label0;
+ }
+ else
+ {
+ documentos1 = new List<Documento>();
+ }
+ }
+ else
+ {
+ documentos1 = new List<Documento>();
+ }
+ }
+ }
+ return documentos1;
+ Label0:
+ List<Documento> documentos2 = new List<Documento>();
+ dataTable.AsEnumerable().ToList<DataRow>().ForEach((DataRow apolice) => {
+ Func<DataRow, bool> func2 = null;
+ List<Documento> documentos = documentos2;
+ Documento documento = new Documento()
+ {
+ Id = apolice.Field<long>("id")
+ };
+ Controle controle = new Controle()
+ {
+ IdEmpresa = apolice.Field<long>("idempresa")
+ };
+ Cliente cliente = new Cliente()
+ {
+ Id = apolice.Field<long>("idcliente"),
+ Nome = apolice.Field<string>("cliente"),
+ Documento = apolice.Field<string>("documento"),
+ IdEmpresa = apolice.Field<long>("idempresa")
+ };
+ EnumerableRowCollection<DataRow> dataRows1 = dataTable4.AsEnumerable().Where<DataRow>((DataRow fone) => fone.Field<long>("idcliente") == apolice.Field<long>("idcliente"));
+ Func<DataRow, ClienteTelefone> u003cu003e9_1624 = DocumentoRepository.u003cu003ec.u003cu003e9__16_24;
+ if (u003cu003e9_1624 == null)
+ {
+ u003cu003e9_1624 = (DataRow fone) => new ClienteTelefone()
+ {
+ Id = fone.Field<long>("idclitelefone"),
+ Prefixo = fone.Field<string>("ddd"),
+ Numero = fone.Field<string>("fone")
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__16_24 = u003cu003e9_1624;
+ }
+ cliente.Telefones = new ObservableCollection<ClienteTelefone>(dataRows1.Select<DataRow, ClienteTelefone>(u003cu003e9_1624));
+ EnumerableRowCollection<DataRow> dataRows2 = dataTable3.AsEnumerable().Where<DataRow>((DataRow mail) => mail.Field<long>("idcliente") == apolice.Field<long>("idcliente"));
+ Func<DataRow, ClienteEmail> u003cu003e9_1626 = DocumentoRepository.u003cu003ec.u003cu003e9__16_26;
+ if (u003cu003e9_1626 == null)
+ {
+ u003cu003e9_1626 = (DataRow mail) => new ClienteEmail()
+ {
+ Id = mail.Field<long>("idclimail"),
+ Email = mail.Field<string>("email")
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__16_26 = u003cu003e9_1626;
+ }
+ cliente.Emails = new ObservableCollection<ClienteEmail>(dataRows2.Select<DataRow, ClienteEmail>(u003cu003e9_1626));
+ cliente.Pasta = apolice.Field<string>("pastacliente");
+ cliente.MalaDireta = new bool?(apolice.Field<bool?>("MalaDireta").GetValueOrDefault(true));
+ controle.Cliente = cliente;
+ controle.Seguradora = (apolice.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora seguradora) => seguradora.Id == apolice.Field<long>("idseguradora")) : null);
+ controle.Ramo = (apolice.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo ramo) => ramo.Id == apolice.Field<long>("idramo")) : null);
+ controle.Produto = (apolice.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Gestor.Model.Domain.Seguros.Produto>((Gestor.Model.Domain.Seguros.Produto produto) => produto.Id == apolice.Field<long>("idproduto")) : null);
+ controle.AssistenciaId = apolice.Field<string>("AssistenciaId");
+ documento.Controle = controle;
+ documento.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Parcela);
+ documento.AdicionalComiss = apolice.Field<string>("adinacomiss") == "1";
+ documento.Apolice = apolice.Field<string>("apolice");
+ documento.Endosso = (apolice.Field<int>("tipo") == 0 ? "" : apolice.Field<string>("endosso") ?? "");
+ documento.Comissao = apolice.Field<decimal>("comissao");
+ documento.Negocio = new Negocio?((apolice.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), apolice.Field<object>("idnegocio").ToString())));
+ documento.PremioLiquido = apolice.Field<decimal>("liquido");
+ documento.PremioTotal = apolice.Field<decimal>("total");
+ documento.Vigencia2 = apolice.Field<DateTime?>("vigenciafinal");
+ DateTime? nullable2 = apolice.Field<DateTime?>("vigenciainicial");
+ documento.Vigencia1 = (nullable2.HasValue ? nullable2.GetValueOrDefault() : DateTime.MinValue);
+ documento.Emissao = apolice.Field<DateTime?>("emissao");
+ documento.Remessa = apolice.Field<DateTime?>("remessa");
+ documento.VendedorPrincipal = (apolice.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor vendedor) => vendedor.Id == apolice.Field<long>("idvendedor")) : null);
+ documento.Estipulante1 = (apolice.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante estipulante) => estipulante.Id == apolice.Field<long>("idestipulante")) : null);
+ documento.NegocioCorretora = new NegocioCorretora?((apolice.Field<object>("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), apolice.Field<object>("situacao").ToString()) != TipoSeguro.Renovacao || apolice.Field<object>("idnegocio") == null || !(apolice.Field<object>("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), apolice.Field<object>("negociocorretora").ToString())));
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), apolice.Field<object>("situacao").ToString());
+ documento.Vendedores = Auxiliar.Vendedores.Where<Vendedor>((Vendedor vendedor) => {
+ List<DataRow> list = dataTable1.AsEnumerable().ToList<DataRow>();
+ Func<DataRow, bool> u003cu003e9_27 = func2;
+ if (u003cu003e9_27 == null)
+ {
+ Func<DataRow, bool> func = (DataRow d) => d.Field<long>("id") == apolice.Field<long>("id");
+ Func<DataRow, bool> func1 = func;
+ func2 = func;
+ u003cu003e9_27 = func1;
+ }
+ IEnumerable<DataRow> dataRows = list.Where<DataRow>(u003cu003e9_27);
+ Func<DataRow, long> u003cu003e9_1628 = DocumentoRepository.u003cu003ec.u003cu003e9__16_28;
+ if (u003cu003e9_1628 == null)
+ {
+ u003cu003e9_1628 = (DataRow d) => d.Field<long>("idvendedor");
+ DocumentoRepository.u003cu003ec.u003cu003e9__16_28 = u003cu003e9_1628;
+ }
+ return dataRows.Select<DataRow, long>(u003cu003e9_1628).ToList<long>().Contains(vendedor.Id);
+ }).ToList<Vendedor>();
+ documento.Tipo = apolice.Field<int>("tipo");
+ documento.DataControle = apolice.Field<DateTime?>("datacontrole");
+ documento.Status = (apolice.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault<Status>((Status status) => status.Id == apolice.Field<long>("idstatus")) : null);
+ documento.ItensAtivo = new List<Item>((
+ from item in dataTable2.AsEnumerable().ToList<DataRow>()
+ where item.Field<long>("iddocumento") == apolice.Field<long>("id")
+ select item).Select<DataRow, Item>((DataRow item) => {
+ Categoria? nullable;
+ Categoria? nullable1;
+ Item item1 = new Item()
+ {
+ Id = item.Field<long>("iditem"),
+ Descricao = item.Field<string>("descricao"),
+ Documento = new Documento()
+ {
+ Id = apolice.Field<long>("id")
+ }
+ };
+ Auto auto = new Auto();
+ if (item.Field<object>("idcategoria") == null)
+ {
+ nullable = null;
+ nullable1 = nullable;
+ }
+ else if (item.Field<object>("idcategoria").ToString() == "")
+ {
+ nullable = null;
+ nullable1 = nullable;
+ }
+ else
+ {
+ nullable1 = (Categoria?)Enum.Parse(typeof(Categoria), item.Field<object>("idcategoria").ToString());
+ }
+ auto.Categoria = nullable1;
+ auto.Placa = item.Field<string>("placa");
+ item1.Auto = auto;
+ return item1;
+ }).ToList<Item>());
+ documento.Pasta = apolice.Field<string>("Pasta");
+ documentos.Add(documento);
+ });
+ return documentos2;
+ }
+
+ public List<Documento> FindByVigenciaFinal(Filtros filtro, List<Licenca> licencas, bool somarPremios)
+ {
+ List<long> j;
+ List<Documento> documentos;
+ object connection;
+ bool count;
+ List<long> nums1 = null;
+ List<long> nums2 = null;
+ List<long> nums3 = null;
+ List<long> nums4 = null;
+ List<Condicao> condicaos = this.CriaCondicaoDocumento(filtro, "CAST(d.vigencia2 AS DATE)");
+ condicaos.AddRange(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ }
+ });
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.tipo",
+ Valores = 0.CriarValor<int>()
+ });
+ DataTable dataTable = new DataTable();
+ DataTable dataTable1 = new DataTable();
+ DataTable dataTable2 = new DataTable();
+ DataTable dataTable3 = new DataTable();
+ DataTable dataTable4 = new DataTable();
+ DataTable dataTable5 = new DataTable();
+ DataTable dataTable6 = null;
+ DataTable dataTable7 = new DataTable();
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 15000;
+ string str = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf, d.idcontrole, d.iddocumento as id, d.contrato as apolice, CASE WHEN d2.aditamento <>'' THEN 'SIM' ELSE 'NÃO' END AS endosso, d.idnegocio, d.situacao, d.negociocorretora, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.apol_antes, d.remessa, d.emissao, d.pr_adic, d.pr_iof, d.pr_custo, d.datacontrole, d.idstatus, d.pasta, d.idbanco, cb.nomebanco, d.agencia, d.conta, cl.pasta as pastacliente, c.AssistenciaId, d.tiporecebimento FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco OUTER APPLY (SELECT TOP 1 aditamento FROM documento WHERE idcontrole = d.idcontrole AND tipo = '1') d2 ", (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 vp.idvendedor FROM vendedorparcela vp INNER JOIN parcela parc ON parc.IdParcela = vp.IdParcela WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1 ORDER BY PARC.IDSUBTIPO, CAST(parc.Parcela as int) DESC) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join<long>(",",
+ from v in filtro.TipoVendedor
+ select v), ")")), " WHERE ");
+ string str1 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento INNER JOIN parcela p ON p.idparcela = vp.idparcela WHERE ";
+ string str2 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE ";
+ string str3 = "SELECT DISTINCT idcontrolesinistro, idcontrole as id, cs.iditem FROM controlesinistro cs INNER JOIN item i on i.iditem = cs.iditem INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE ";
+ string str4 = "SELECT DISTINCT idclitelefone, ddd, fone, idcliente as id FROM clitelefone WHERE ";
+ string str5 = "SELECT DISTINCT idclimail, email, idcliente as id FROM climail WHERE ";
+ string str6 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE ";
+ dataTable = sqlCommand.Select(condicaos.CreateParameters(0), str, "");
+ if (dataTable == null || dataTable.Rows.Count == 0)
+ {
+ documentos = new List<Documento>();
+ }
+ else
+ {
+ Auxiliar.CriarAuxiliar(sqlCommand, false);
+ for (List<long> i1 = dataTable.AsEnumerable().Where<DataRow>((DataRow x) => x.Field<object>("idvendedor") == null).Select<DataRow, long>((DataRow v) => v.Field<long>("idcontrole")).ToList<long>(); i1.Count > 0; i1 = nums1)
+ {
+ List<long> nums5 = i1.Take<long>(1000).ToList<long>();
+ List<Condicao> condicaos1 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.idcontrole",
+ Valores = nums5.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "p.parcela",
+ Operador = Operador.Diferente,
+ Valores = "999".CriarValor<string>()
+ }
+ };
+ List<long> vendedores = filtro.Vendedores;
+ if (vendedores != null)
+ {
+ count = vendedores.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (count)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "vp.idvendedor",
+ Valores = filtro.Vendedores.CriarValor<long>()
+ });
+ }
+ DataTable dataTable8 = sqlCommand.Select(condicaos1.CreateParameters(0), str1, "");
+ foreach (DataRow row in dataTable.Rows)
+ {
+ if (!string.IsNullOrEmpty(row["idvendedor"].ToString()))
+ {
+ continue;
+ }
+ string str7 = string.Format("idcontrole = {0}", row["idcontrole"]);
+ DataRow[] dataRowArray = dataTable8.Select(str7);
+ if (dataRowArray.Length == 0)
+ {
+ continue;
+ }
+ row["idvendedor"] = dataRowArray[0][1];
+ }
+ nums1 = (nums5.Count < 1000 ? new List<long>() : i1.Except<long>(nums5).ToList<long>());
+ }
+ for (j = dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("idcliente")).Distinct<long>().ToList<long>(); j.Count > 0; j = nums2)
+ {
+ List<long> nums6 = j.Take<long>(1000).ToList<long>();
+ List<Condicao> condicaos2 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idcliente",
+ Valores = nums6.CriarValor<long>()
+ }
+ };
+ DataTable dataTable9 = sqlCommand.Select(condicaos2.CreateParameters(0), str4, "");
+ dataTable4.Merge(dataTable9);
+ dataTable9 = sqlCommand.Select(condicaos2.CreateParameters(0), str5, "");
+ dataTable3.Merge(dataTable9);
+ nums2 = (nums6.Count < 1000 ? new List<long>() : j.Except<long>(nums6).ToList<long>());
+ }
+ for (j = dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id")).Distinct<long>().ToList<long>(); j.Count > 0; j = nums3)
+ {
+ List<long> nums7 = j.Take<long>(1000).ToList<long>();
+ List<Condicao> condicaos3 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "vp.iddocumento",
+ Valores = nums7.CriarValor<long>()
+ }
+ };
+ DataTable dataTable10 = sqlCommand.Select(condicaos3.CreateParameters(0), str2, "");
+ dataTable1.Merge(dataTable10);
+ nums3 = (nums7.Count < 1000 ? new List<long>() : j.Except<long>(nums7).ToList<long>());
+ }
+ for (j = dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("idcontrole")).Distinct<long>().ToList<long>(); j.Count > 0; j = nums4)
+ {
+ List<long> nums8 = j.Take<long>(1000).ToList<long>();
+ List<Condicao> condicaos4 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.idcontrole",
+ Valores = nums8.CriarValor<long>()
+ }
+ };
+ List<Condicao> condicaos5 = new List<Condicao>();
+ condicaos5.AddRange(condicaos4);
+ DataTable dataTable11 = sqlCommand.Select(condicaos5.CreateParameters(0), str3, "");
+ dataTable2.Merge(dataTable11);
+ condicaos5.AddRange(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idsubstituido",
+ Valores = null
+ },
+ new Condicao()
+ {
+ Campo = "cancelado",
+ Valores = null,
+ Operacao = Operacao.Or,
+ Grupo = 1
+ },
+ new Condicao()
+ {
+ Campo = "cancelado",
+ Valores = 0.CriarValor<int>(),
+ Operacao = Operacao.Or,
+ Grupo = 1
+ }
+ });
+ dataTable11 = sqlCommand.Select(condicaos5.CreateParameters(0), str6, "");
+ dataTable5.Merge(dataTable11);
+ licencas.Any<Licenca>((Licenca x) => {
+ if (x.Produto != Gestor.Model.License.Produto.AggilizadorCalculos && x.Produto != Gestor.Model.License.Produto.AggilizadorCalculosIndependente)
+ {
+ return false;
+ }
+ return x.Status != 3;
+ });
+ if (somarPremios)
+ {
+ condicaos4.AddRange(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ }
+ });
+ DataTable dataTable12 = sqlCommand.Select(condicaos4.CreateParameters(0), "SELECT d.iddocumento, d.idcontrole, ISNULL(d.pr_liq ,0) AS pr_liq, ISNULL(d.pr_total ,0) AS pr_total FROM documento d WHERE", "");
+ dataTable7.Merge(dataTable12);
+ }
+ nums4 = (nums8.Count < 1000 ? new List<long>() : j.Except<long>(nums8).ToList<long>());
+ }
+ goto Label0;
+ }
+ }
+ }
+ return documentos;
+ Label0:
+ List<Documento> documentos1 = new List<Documento>();
+ dataTable.AsEnumerable().ToList<DataRow>().ForEach((DataRow x) => {
+ DateTime? nullable;
+ List<Calculo> list;
+ decimal num;
+ decimal num1;
+ DateTime? nullable1;
+ DateTime? nullable2;
+ EnumerableRowCollection<DataRow> dataRows1 = dataTable1.AsEnumerable().Where<DataRow>((DataRow d) => d.Field<long>("id") == x.Field<long>("id"));
+ Func<DataRow, long> u003cu003e9_269 = DocumentoRepository.u003cu003ec.u003cu003e9__26_9;
+ if (u003cu003e9_269 == null)
+ {
+ u003cu003e9_269 = (DataRow d) => d.Field<long>("idvendedor");
+ DocumentoRepository.u003cu003ec.u003cu003e9__26_9 = u003cu003e9_269;
+ }
+ List<long> nums = dataRows1.Select<DataRow, long>(u003cu003e9_269).ToList<long>();
+ IEnumerable<DataRow> list1 =
+ from t in dataTable4.AsEnumerable().ToList<DataRow>()
+ where t.Field<long>("id") == x.Field<long>("idcliente")
+ select t;
+ Func<DataRow, ClienteTelefone> u003cu003e9_2611 = DocumentoRepository.u003cu003ec.u003cu003e9__26_11;
+ if (u003cu003e9_2611 == null)
+ {
+ u003cu003e9_2611 = (DataRow t) => new ClienteTelefone()
+ {
+ Prefixo = t.Field<string>("ddd"),
+ Numero = t.Field<string>("fone")
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__26_11 = u003cu003e9_2611;
+ }
+ List<ClienteTelefone> clienteTelefones = list1.Select<DataRow, ClienteTelefone>(u003cu003e9_2611).ToList<ClienteTelefone>();
+ IEnumerable<DataRow> list2 =
+ from t in dataTable3.AsEnumerable().ToList<DataRow>()
+ where t.Field<long>("id") == x.Field<long>("idcliente")
+ select t;
+ Func<DataRow, ClienteEmail> u003cu003e9_2613 = DocumentoRepository.u003cu003ec.u003cu003e9__26_13;
+ if (u003cu003e9_2613 == null)
+ {
+ u003cu003e9_2613 = (DataRow t) => new ClienteEmail()
+ {
+ Email = t.Field<string>("email")
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__26_13 = u003cu003e9_2613;
+ }
+ List<ClienteEmail> clienteEmails = list2.Select<DataRow, ClienteEmail>(u003cu003e9_2613).ToList<ClienteEmail>();
+ List<Item> items = (
+ from i in dataTable5.AsEnumerable().ToList<DataRow>()
+ where i.Field<long>("idcontrole") == x.Field<long>("idcontrole")
+ select i).Select<DataRow, Item>((DataRow i) => {
+ Item item = new Item()
+ {
+ Id = i.Field<long>("iditem"),
+ Descricao = i.Field<string>("descricao")
+ };
+ EnumerableRowCollection<DataRow> dataRows = dataTable2.AsEnumerable().Where<DataRow>((DataRow s) => {
+ if (s.Field<long>("id") != x.Field<long>("idcontrole"))
+ {
+ return false;
+ }
+ return i.Field<long>("iditem") == s.Field<long>("iditem");
+ });
+ Func<DataRow, ControleSinistro> u003cu003e9_2624 = DocumentoRepository.u003cu003ec.u003cu003e9__26_24;
+ if (u003cu003e9_2624 == null)
+ {
+ u003cu003e9_2624 = (DataRow s) => new ControleSinistro()
+ {
+ Id = s.Field<long>("idcontrolesinistro")
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__26_24 = u003cu003e9_2624;
+ }
+ item.Sinistros = dataRows.Select<DataRow, ControleSinistro>(u003cu003e9_2624).ToList<ControleSinistro>();
+ return item;
+ }).ToList<Item>();
+ if (dataTable6 != null)
+ {
+ EnumerableRowCollection<DataRow> dataRows2 = dataTable6.AsEnumerable().Where<DataRow>((DataRow c) => c.Field<long>("idcontrole") == x.Field<long>("idcontrole"));
+ Func<DataRow, Calculo> u003cu003e9_2617 = DocumentoRepository.u003cu003ec.u003cu003e9__26_17;
+ if (u003cu003e9_2617 == null)
+ {
+ u003cu003e9_2617 = (DataRow c) => new Calculo()
+ {
+ Id = c.Field<long>("Id"),
+ DocumentId = c.Field<long>("IdDocumento"),
+ DataAtualizacao = c.Field<DateTime>("DataAtualizacao"),
+ Status = (StatusCalculo)c.Field<int>("Status"),
+ Usuario = Auxiliar.Usuarios.Find((Usuario u) => u.Id == c.Field<long>("IdUsuario"))
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__26_17 = u003cu003e9_2617;
+ }
+ list = dataRows2.Select<DataRow, Calculo>(u003cu003e9_2617).ToList<Calculo>();
+ }
+ else
+ {
+ list = new List<Calculo>();
+ }
+ List<Calculo> calculos = list;
+ List<DataRow> list3 = dataTable7.AsEnumerable().Where<DataRow>((DataRow p) => p.Field<long>("idcontrole") == x.Field<long>("idcontrole")).ToList<DataRow>();
+ if (!somarPremios)
+ {
+ num = x.Field<decimal>("total");
+ }
+ else
+ {
+ List<DataRow> dataRows3 = list3;
+ Func<DataRow, decimal> u003cu003e9_2619 = DocumentoRepository.u003cu003ec.u003cu003e9__26_19;
+ if (u003cu003e9_2619 == null)
+ {
+ u003cu003e9_2619 = (DataRow p) => p.Field<decimal>("pr_total");
+ DocumentoRepository.u003cu003ec.u003cu003e9__26_19 = u003cu003e9_2619;
+ }
+ num = dataRows3.Sum<DataRow>(u003cu003e9_2619);
+ }
+ decimal num2 = num;
+ if (!somarPremios)
+ {
+ num1 = x.Field<decimal>("liquido");
+ }
+ else
+ {
+ List<DataRow> dataRows4 = list3;
+ Func<DataRow, decimal> u003cu003e9_2620 = DocumentoRepository.u003cu003ec.u003cu003e9__26_20;
+ if (u003cu003e9_2620 == null)
+ {
+ u003cu003e9_2620 = (DataRow p) => p.Field<decimal>("pr_liq");
+ DocumentoRepository.u003cu003ec.u003cu003e9__26_20 = u003cu003e9_2620;
+ }
+ num1 = dataRows4.Sum<DataRow>(u003cu003e9_2620);
+ }
+ decimal num3 = num1;
+ Vendedor vendedor = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.Find((Vendedor p) => p.Id == x.Field<long>("idvendedor")) : null);
+ NegocioCorretora negocioCorretora = (x.Field<object>("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString()) != TipoSeguro.Renovacao || x.Field<object>("idnegocio") == null || !(x.Field<object>("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field<object>("negociocorretora").ToString()));
+ if (filtro.Negocio != null && filtro.Negocio.Count > 0 && !filtro.Negocio.Any<long>((long n) => (int)n == (int)negocioCorretora))
+ {
+ return;
+ }
+ Documento documento = new Documento()
+ {
+ Id = x.Field<long>("id"),
+ Controle = new Controle()
+ {
+ Id = x.Field<long>("idcontrole"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ Cliente = new Cliente()
+ {
+ Id = x.Field<long>("idcliente"),
+ Nome = x.Field<string>("cliente"),
+ Documento = x.Field<string>("cgccpf"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ Telefones = new ObservableCollection<ClienteTelefone>(clienteTelefones),
+ Emails = new ObservableCollection<ClienteEmail>(clienteEmails),
+ Pasta = x.Field<string>("pastacliente"),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
+ },
+ Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null),
+ Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
+ Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.Find((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field<long>("idproduto")) : null),
+ AssistenciaId = x.Field<string>("AssistenciaId")
+ },
+ TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field<object>("tiporecebimento").ToString())),
+ AdicionalComiss = x.Field<string>("adinacomiss") == "1",
+ Apolice = x.Field<string>("apolice"),
+ ApoliceAnterior = x.Field<string>("apol_antes")
+ };
+ if (x.Field<object>("remessa") == null)
+ {
+ nullable = null;
+ nullable1 = nullable;
+ }
+ else
+ {
+ nullable1 = new DateTime?(x.Field<DateTime>("remessa"));
+ }
+ documento.Remessa = nullable1;
+ if (x.Field<object>("emissao") == null)
+ {
+ nullable = null;
+ nullable2 = nullable;
+ }
+ else
+ {
+ nullable2 = new DateTime?(x.Field<DateTime>("emissao"));
+ }
+ documento.Emissao = nullable2;
+ documento.Endosso = x.Field<string>("endosso");
+ documento.Comissao = x.Field<decimal>("comissao");
+ documento.Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString())));
+ documento.PremioLiquido = num3;
+ documento.PremioAdicional = x.Field<decimal>("pr_adic");
+ x.Field<decimal>("pr_custo");
+ documento.Custo = x.Field<decimal>("pr_custo");
+ documento.Iof = x.Field<decimal>("pr_iof");
+ documento.PremioTotal = num2;
+ documento.Vigencia2 = x.Field<DateTime?>("vigenciafinal");
+ nullable = x.Field<DateTime?>("vigenciainicial");
+ documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ documento.VendedorPrincipal = vendedor;
+ documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.Find((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
+ documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora);
+ documento.Vendedores = (
+ from v in Auxiliar.Vendedores
+ where nums.Contains(v.Id)
+ select v).ToList<Vendedor>();
+ documento.Sinistro = dataTable2.AsEnumerable().ToList<DataRow>().Any<DataRow>((DataRow s) => s.Field<long>("id") == x.Field<long>("idcontrole"));
+ documento.Tipo = x.Field<int>("tipo");
+ documento.ItensAtivo = items;
+ documento.DataControle = x.Field<DateTime?>("datacontrole");
+ documento.Status = (x.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.Find((Status p) => p.Id == x.Field<long>("idstatus")) : null);
+ documento.Pasta = x.Field<string>("Pasta");
+ documento.Banco = new Banco()
+ {
+ Nome = x.Field<string>("nomebanco")
+ };
+ documento.Agencia = x.Field<string>("agencia");
+ documento.Conta = x.Field<string>("conta");
+ documento.Calculos = calculos;
+ documentos1.Add(documento);
+ });
+ return documentos1;
+ }
+
+ public async Task<List<Documento>> FindEndossoByVigencia(Filtros filtro, bool buscarAssinatura = false)
+ {
+ decimal? nullable2;
+ object list;
+ bool count;
+ decimal? porcentagemRepasse;
+ string str = "CAST(d.vigencia1 AS DATE)";
+ string referencia = filtro.Referencia;
+ if (referencia == "EMISSÃO")
+ {
+ str = "CAST(d.emissao AS DATE)";
+ }
+ else if (referencia == "TRANSMISSÃO PROPOSTA")
+ {
+ str = "CAST(d.remessa AS DATE)";
+ }
+ else if (referencia == "DATA CRIAÇÃO" || referencia == "DATA DE CADASTRO")
+ {
+ str = "CAST(d.cri_data AS DATE)";
+ }
+ List<long> vinculoVendedores = filtro.VinculoVendedores;
+ if (vinculoVendedores != null)
+ {
+ IEnumerable<long> nums = vinculoVendedores.Except<long>(filtro.Vendedores);
+ if (nums != null)
+ {
+ list = nums.ToList<long>();
+ }
+ else
+ {
+ list = null;
+ }
+ }
+ else
+ {
+ list = null;
+ }
+ if (list == null)
+ {
+ list = new List<long>();
+ }
+ if (!((IEnumerable<long>)list).Any<long>())
+ {
+ filtro.Vendedores = new List<long>();
+ }
+ List<Condicao> condicaos = this.CriaCondicaoDocumento(filtro, str);
+ Condicao condicao = new Condicao()
+ {
+ Campo = "d.Tipo",
+ Valores = 1.CriarValor<int>()
+ };
+ condicaos.Add(condicao);
+ List<Condicao> condicaos1 = new List<Condicao>();
+ Condicao condicao1 = new Condicao()
+ {
+ Campo = "d.Excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ };
+ condicaos1.Add(condicao1);
+ Condicao condicao2 = new Condicao()
+ {
+ Campo = "d.Excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ };
+ condicaos1.Add(condicao2);
+ condicaos.AddRange(condicaos1);
+ List<Documento> documentos = await this.BuscaDocumentosPorCondicao(filtro, condicaos, buscarAssinatura);
+ List<long> vinculoVendedores1 = filtro.VinculoVendedores;
+ if (vinculoVendedores1 != null)
+ {
+ count = vinculoVendedores1.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (count)
+ {
+ List<Documento> documentos1 = new List<Documento>();
+ foreach (Documento documento in documentos)
+ {
+ await this.BuscaVendedoresPorIdControle(documento.Controle.Id, documento.Controle.IdEmpresa).ForEach((VendedorParcela v) => {
+ if (!filtro.VinculoVendedores.Contains(v.Vendedor.Id))
+ {
+ documentos1.Add(documento);
+ }
+ });
+ }
+ documentos1.ForEach((Documento d) => this.documentos.Remove(d));
+ }
+ foreach (Documento vendedor in documentos)
+ {
+ if (vendedor.Tipo == 1 && vendedor.VendedorPrincipal == null && vendedor.Pagamentos.Count < 2)
+ {
+ List<VendedorParcela> vendedorParcelas = await this.BuscaVendedoresPorIdControle(vendedor.Controle.Id, vendedor.Controle.IdEmpresa);
+ vendedor.Pagamentos = vendedorParcelas;
+ List<VendedorParcela> vendedorParcelas1 = vendedorParcelas;
+ VendedorParcela vendedorParcela = vendedorParcelas1.Find((VendedorParcela v) => v.TipoVendedor.Id == (long)1);
+ if (vendedorParcela != null)
+ {
+ vendedor.VendedorPrincipal = vendedorParcela.Vendedor;
+ }
+ List<VendedorParcela> pagamentos = vendedor.Pagamentos;
+ IOrderedEnumerable<VendedorParcela> vendedorParcelas2 =
+ from tipo in pagamentos
+ orderby tipo.TipoVendedor.Id
+ select tipo;
+ List<Vendedor> vendedors = (
+ from v in vendedorParcelas2
+ select v.Vendedor).ToList<Vendedor>();
+ vendedor.Vendedores = vendedors;
+ Documento documento1 = vendedor;
+ VendedorParcela vendedorParcela1 = vendedor.Pagamentos.FirstOrDefault<VendedorParcela>((VendedorParcela p) => {
+ long? nullable;
+ long id = p.Vendedor.Id;
+ Vendedor vendedorPrincipal = vendedor.VendedorPrincipal;
+ if (vendedorPrincipal != null)
+ {
+ nullable = new long?(vendedorPrincipal.Id);
+ }
+ else
+ {
+ nullable = null;
+ }
+ long? nullable1 = nullable;
+ return id == nullable1.GetValueOrDefault() & nullable1.HasValue;
+ });
+ if (vendedorParcela1 != null)
+ {
+ porcentagemRepasse = vendedorParcela1.PorcentagemRepasse;
+ }
+ else
+ {
+ nullable2 = null;
+ porcentagemRepasse = nullable2;
+ }
+ nullable2 = porcentagemRepasse;
+ documento1.PercentualRepasse = new decimal?(nullable2.GetValueOrDefault());
+ }
+ }
+ List<Documento> documentos2 = documentos;
+ return documentos2;
+ }
+
+ public List<Documento> FindPendenciasByVigencia(Filtros filtro)
+ {
+ object connection;
+ string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join<long>(",",
+ from v in filtro.Status
+ select v), ")"));
+ string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join<long>(",",
+ from v in filtro.Negocio
+ select v), ")"));
+ string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",",
+ from v in filtro.Seguradoras
+ select v), ")"));
+ string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",",
+ from v in filtro.Ramos
+ select v), ")"));
+ string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",",
+ from v in filtro.Produtos
+ select v), ")"));
+ string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",",
+ from v in filtro.Vendedores
+ select v), ")"));
+ string str6 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp" : string.Concat("INNER JOIN vendedorparcela vp ON vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", string.Join<long>(",",
+ from v in filtro.TipoVendedor
+ select v), ")"));
+ string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",",
+ from v in filtro.Estipulantes
+ select v), ")"));
+ string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa));
+ DataTable dataTable1 = new DataTable();
+ DataTable dataTable2 = new DataTable();
+ DataTable dataTable3 = new DataTable();
+ DataTable dataTable4 = new DataTable();
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 15000;
+ Auxiliar.CriarAuxiliar(sqlCommand, false);
+ string str9 = string.Concat("SELECT DISTINCT cl.idempresa, cl.idcliente, cl.MalaDireta, cl.nome as cliente, cl.cgccpf, d.idcontrole, d.iddocumento as id, d.proposta, d.pedadit as propostaendosso, d.idnegocio, d.situacao, d.vigencia1 as vigenciainicial, d.vigencia2 as vigenciafinal, d.pr_total as total, d.pr_liq as liquido, d.pr_adic as adicional, ISNULL(d.com01, 0.00) as comissao, ISNULL(d.adinacomis, '0') as adinacomiss, c.idramo, c.idciaseg as idseguradora, c.idproduto, CAST(d.tipo AS INTEGER) AS tipo, vp.idvendedor, d.idestipulante, d.tiporecebimento, d.datacontrole, d.idstatus, d.pasta, d.idbanco, cb.nomebanco, d.conta, d.agencia, cl.pasta as pastacliente, c.AssistenciaId FROM documento d INNER JOIN controle c on c.idcontrole = d.idcontrole INNER JOIN cliente cl on cl.idcliente = c.idcliente LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco ", str6, " WHERE (d.excluido IS NULL OR d.excluido = 0) AND (cl.excluido = 0 OR cl.excluido IS NULL) AND CASE \tWHEN ( d.tipo = 0 ) THEN DATALENGTH(ISNULL( d.contrato, '' )) ELSE DATALENGTH(ISNULL( d.aditamento, '' )) END < 1 ");
+ string str10 = "SELECT DISTINCT d.idcontrole, idvendedor FROM vendedorparcela vp INNER JOIN documento d on d.iddocumento = vp.iddocumento WHERE 1=1 ";
+ string str11 = "SELECT DISTINCT iddocumento as id, idvendedor FROM vendedorparcela vp WHERE 1=1 ";
+ string str12 = "SELECT i.iditem, d.iddocumento, d.idcontrole, i.descricao FROM item i INNER JOIN documento d on d.iddocumento = i.iddocumento WHERE (cancelado IS NULL OR cancelado != '1') AND idsubstituido IS NULL ";
+ string str13 = "SELECT * FROM VinculoDocumento WHERE 1=1 ";
+ sqlCommand.CommandText = string.Format("{0} {1} AND d.vigencia1 >= '{2:yyyy-MM-dd}' AND d.vigencia1 <= '{3:yyyy-MM-dd}' {4} {5} {6} {7} {8} {9} {10}", new object[] { str9, str8, filtro.Inicio, filtro.Fim, str, str1, str2, str3, str4, str7, str5 });
+ using (SqlDataAdapter sqlDataAdapter = new SqlDataAdapter())
+ {
+ sqlDataAdapter.SelectCommand = sqlCommand;
+ sqlDataAdapter.Fill(dataTable1);
+ }
+ if (dataTable1.Rows.Count != 0)
+ {
+ if (dataTable1.AsEnumerable().Any<DataRow>((DataRow x) => x.Field<object>("idvendedor") == null))
+ {
+ string str14 = string.Concat(" AND d.idcontrole IN (", string.Join<long>(",", dataTable1.AsEnumerable().Where<DataRow>((DataRow x) => x.Field<object>("idvendedor") == null).Select<DataRow, long>((DataRow v) => v.Field<long>("idcontrole"))), ")");
+ DataTable dataTable5 = new DataTable();
+ sqlCommand.CommandText = string.Concat(new string[] { str10, " ", str14, " ", str5 });
+ using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter())
+ {
+ sqlDataAdapter1.SelectCommand = sqlCommand;
+ sqlDataAdapter1.Fill(dataTable5);
+ }
+ foreach (DataRow row in dataTable1.Rows)
+ {
+ if (!string.IsNullOrEmpty(row["idvendedor"].ToString()))
+ {
+ continue;
+ }
+ string str15 = string.Format("idcontrole = {0}", row["idcontrole"]);
+ DataRow[] dataRowArray = dataTable5.Select(str15);
+ if (dataRowArray.Length == 0)
+ {
+ continue;
+ }
+ row["idvendedor"] = dataRowArray[0][1];
+ }
+ }
+ string str16 = string.Concat(" AND vp.iddocumento IN (", string.Join<long>(",", dataTable1.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
+ sqlCommand.CommandText = string.Concat(str11, " ", str16);
+ using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter())
+ {
+ sqlDataAdapter2.SelectCommand = sqlCommand;
+ sqlDataAdapter2.Fill(dataTable2);
+ }
+ string str17 = string.Concat(" AND d.idcontrole IN (", string.Join<long>(",", dataTable1.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("idcontrole"))), ")");
+ sqlCommand.CommandText = string.Concat(str12, " ", str17);
+ using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter())
+ {
+ sqlDataAdapter3.SelectCommand = sqlCommand;
+ sqlDataAdapter3.Fill(dataTable3);
+ }
+ try
+ {
+ string str18 = string.Concat(" AND IdDocumento IN (", string.Join<long>(",", (
+ from x in dataTable1.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("id")).ToList<long>()), ")");
+ sqlCommand.CommandText = string.Concat(str13, " ", str18);
+ using (SqlDataAdapter sqlDataAdapter4 = new SqlDataAdapter())
+ {
+ sqlDataAdapter4.SelectCommand = sqlCommand;
+ sqlDataAdapter4.Fill(dataTable4);
+ }
+ }
+ catch (Exception exception)
+ {
+ dataTable4 = null;
+ }
+ }
+ else
+ {
+ return new List<Documento>();
+ }
+ }
+ }
+ return dataTable1.AsEnumerable().ToList<DataRow>().Select<DataRow, Documento>((DataRow x) => {
+ VinculoDocumento vinculoDocumento;
+ Func<DataRow, bool> func2 = null;
+ Documento documento = new Documento()
+ {
+ Id = x.Field<long>("id"),
+ Controle = new Controle()
+ {
+ IdEmpresa = x.Field<long>("idempresa"),
+ Cliente = new Cliente()
+ {
+ Id = x.Field<long>("idcliente"),
+ Nome = x.Field<string>("cliente"),
+ Documento = x.Field<string>("cgccpf"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ Pasta = x.Field<string>("pastacliente"),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
+ },
+ Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null),
+ Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
+ Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Gestor.Model.Domain.Seguros.Produto>((Gestor.Model.Domain.Seguros.Produto p) => p.Id == x.Field<long>("idproduto")) : null),
+ AssistenciaId = x.Field<string>("AssistenciaId")
+ },
+ TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field<object>("tiporecebimento").ToString())),
+ AdicionalComiss = x.Field<string>("adinacomiss") == "1",
+ Proposta = x.Field<string>("proposta"),
+ PropostaEndosso = x.Field<string>("propostaendosso"),
+ Comissao = x.Field<decimal>("comissao"),
+ Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString()))),
+ PremioLiquido = x.Field<decimal>("liquido"),
+ PremioTotal = x.Field<decimal>("total"),
+ Vigencia2 = x.Field<DateTime?>("vigenciafinal")
+ };
+ DateTime? nullable = x.Field<DateTime?>("vigenciainicial");
+ documento.Vigencia1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ documento.VendedorPrincipal = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")) : null);
+ documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
+ documento.Vendedores = Auxiliar.Vendedores.Where<Vendedor>((Vendedor v) => {
+ List<DataRow> list = dataTable2.AsEnumerable().ToList<DataRow>();
+ Func<DataRow, bool> u003cu003e9_26 = func2;
+ if (u003cu003e9_26 == null)
+ {
+ Func<DataRow, bool> func = (DataRow d) => d.Field<long>("id") == x.Field<long>("id");
+ Func<DataRow, bool> func1 = func;
+ func2 = func;
+ u003cu003e9_26 = func1;
+ }
+ IEnumerable<DataRow> dataRows = list.Where<DataRow>(u003cu003e9_26);
+ Func<DataRow, long> u003cu003e9_3927 = DocumentoRepository.u003cu003ec.u003cu003e9__39_27;
+ if (u003cu003e9_3927 == null)
+ {
+ u003cu003e9_3927 = (DataRow d) => d.Field<long>("idvendedor");
+ DocumentoRepository.u003cu003ec.u003cu003e9__39_27 = u003cu003e9_3927;
+ }
+ return dataRows.Select<DataRow, long>(u003cu003e9_3927).ToList<long>().Contains(v.Id);
+ }).ToList<Vendedor>();
+ documento.Tipo = x.Field<int>("tipo");
+ documento.DataControle = x.Field<DateTime?>("datacontrole");
+ documento.Status = (x.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault<Status>((Status p) => p.Id == x.Field<long>("idstatus")) : null);
+ IEnumerable<DataRow> dataRows1 =
+ from i in dataTable3.AsEnumerable().ToList<DataRow>()
+ where i.Field<long>("idcontrole") == x.Field<long>("idcontrole")
+ select i;
+ Func<DataRow, Item> u003cu003e9_3920 = DocumentoRepository.u003cu003ec.u003cu003e9__39_20;
+ if (u003cu003e9_3920 == null)
+ {
+ u003cu003e9_3920 = (DataRow i) => new Item()
+ {
+ Id = i.Field<long>("iditem"),
+ Descricao = i.Field<string>("descricao")
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__39_20 = u003cu003e9_3920;
+ }
+ documento.ItensAtivo = new List<Item>(dataRows1.Select<DataRow, Item>(u003cu003e9_3920).ToList<Item>());
+ DataTable dataTable = dataTable4;
+ if (dataTable != null)
+ {
+ EnumerableRowCollection<DataRow> dataRows2 = dataTable.AsEnumerable().Where<DataRow>((DataRow v) => v.Field<long>("IdDocumento") == x.Field<long>("id"));
+ Func<DataRow, VinculoDocumento> u003cu003e9_3922 = DocumentoRepository.u003cu003ec.u003cu003e9__39_22;
+ if (u003cu003e9_3922 == null)
+ {
+ u003cu003e9_3922 = (DataRow v) => new VinculoDocumento()
+ {
+ Id = v.Field<long>("Id"),
+ IdDocumento = v.Field<long>("IdDocumento"),
+ IdPropostaDigital = v.Field<long>("IdPropostaDigital"),
+ IdApoliceDigital = v.Field<long>("IdApoliceDigital")
+ };
+ DocumentoRepository.u003cu003ec.u003cu003e9__39_22 = u003cu003e9_3922;
+ }
+ vinculoDocumento = dataRows2.Select<DataRow, VinculoDocumento>(u003cu003e9_3922).FirstOrDefault<VinculoDocumento>();
+ }
+ else
+ {
+ vinculoDocumento = null;
+ }
+ documento.Vinculo = vinculoDocumento;
+ documento.Pasta = x.Field<string>("Pasta");
+ documento.Banco = new Banco()
+ {
+ Nome = x.Field<string>("nomebanco")
+ };
+ documento.Agencia = x.Field<string>("agencia");
+ documento.Conta = x.Field<string>("conta");
+ return documento;
+ }).ToList<Documento>();
+ }
+
+ public bool HasSinistro(long id)
+ {
+ return (new ControleSinistroRepository(this._unitOfWork)).DocumentoHasSinistro(id);
+ }
+
+ public bool HasSinistroPorControle(long controleId)
+ {
+ return (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(controleId);
+ }
+
+ public Documento Merge(Documento documento)
+ {
+ bool id;
+ Status status = documento.Status;
+ if (status != null)
+ {
+ id = status.Id == (long)0;
+ }
+ else
+ {
+ id = false;
+ }
+ if (id)
+ {
+ documento.Status = null;
+ }
+ if (!documento.DataCriacao.HasValue)
+ {
+ documento.DataCriacao = new DateTime?(Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime());
+ }
+ DocumentoDb documentoDb = ApplicationMapper.Mapper.Map<Documento, DocumentoDb>(documento);
+ base.Merge(documentoDb);
+ documento = ApplicationMapper.Mapper.Map<DocumentoDb, Documento>(documentoDb);
+ documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(documento.Id);
+ return documento;
+ }
+
+ public void SalvarAssistencia(string id, long idcontrole)
+ {
+ ControleDb controleDb = this._unitOfWork.Query<ControleDb>().FirstOrDefault<ControleDb>((ControleDb x) => x.Id == idcontrole);
+ if (controleDb == null)
+ {
+ return;
+ }
+ controleDb.AssistenciaId = id;
+ this._unitOfWork.Repository<ControleDb>().Merge(controleDb);
+ }
+
+ public Documento SaveOrUpdate(Documento documento)
+ {
+ bool id;
+ Status status = documento.Status;
+ if (status != null)
+ {
+ id = status.Id == (long)0;
+ }
+ else
+ {
+ id = false;
+ }
+ if (id)
+ {
+ documento.Status = null;
+ }
+ if (!documento.DataCriacao.HasValue)
+ {
+ documento.DataCriacao = new DateTime?(Gestor.Infrastructure.Helpers.Funcoes.GetNetworkTime());
+ }
+ DocumentoDb documentoDb = ApplicationMapper.Mapper.Map<Documento, DocumentoDb>(documento);
+ this.SaveOrUpdate(documentoDb);
+ documento = ApplicationMapper.Mapper.Map<DocumentoDb, Documento>(documentoDb);
+ documento.VendedorPrincipal = (new VendedorParcelaRepository(this._unitOfWork)).FindByMainDocumentId(documento.Id);
+ return documento;
+ }
+
+ private List<Documento> Select(SqlQueryCondition sqlCondition)
+ {
+ DataTable dataTable = this._unitOfWork.Select(sqlCondition, "SELECT DISTINCT c.idcliente, cl.MalaDireta, cl.cgccpf, c.idempresa, c.idcontrole, c.idciaseg, c.idramo, c.idproduto, d.iddocumento, d.adinacomis, d.pr_adic, d.proposta, d.pedadit, d.contrato, d.aditamento, d.com01, d.idnegocio, d.pr_liq, d.pr_total, d.vigencia1, d.vigencia2, d.emissao, d.remessa, d.idestipulante, d.negociocorretora, d.situacao, d.tiporecebimento, CAST(d.tipo AS INTEGER) AS tipo, CAST(d.ordem AS INTEGER) AS ordem, d.n_parc AS numeroParcelas, d.pasta, d.banco, cb.nomebanco, d.agencia, d.conta, d.excluido, c.AssistenciaId, d.numeroCart, d.vencimentoCart, d.nomeProp, d.formapagamento, d.Obs FROM controle c INNER JOIN documento d ON d.idcontrole = c.idcontrole LEFT OUTER JOIN codigobanco cb on cb.idcodigobanco = d.idbanco INNER JOIN cliente cl on cl.idcliente = c.idcliente WHERE ", "");
+ if (dataTable == null || dataTable.Rows.Count == 0)
+ {
+ return new List<Documento>();
+ }
+ this._unitOfWork.CriarAuxiliar();
+ List<long> list = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("idcontrole")).Distinct<long>().ToList<long>();
+ List<long> nums = (new ControleSinistroRepository(this._unitOfWork)).HasSinistro(list);
+ return dataTable.MapDocumento(nums);
+ }
+
+ private async Task SomaComissaoPaga(int tipo, List<Fechamento> fechamentos, Filtros filtro, List<Condicao> condicaoDocumento)
+ {
+ object connection;
+ long num;
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ string str = "c.IdCiaSeg";
+ string str1 = "SUM(vp.vlrrep)";
+ string str2 = "FROM vendedorparcela vp INNER JOIN documento d ON vp.iddocumento = d.iddocumento INNER JOIN controle c ON c.IdControle = d.IdControle";
+ string str3 = "vp.DataPgt IS NOT NULL AND";
+ switch (tipo)
+ {
+ case 1:
+ {
+ str = "c.IdRamo";
+ break;
+ }
+ case 2:
+ {
+ str = "d.IdEstipulante";
+ break;
+ }
+ case 3:
+ {
+ str = "vp.IdVendedor";
+ break;
+ }
+ }
+ SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0);
+ sqlCommand.CommandTimeout = 1000;
+ SqlCommand sqlCommand1 = sqlCommand;
+ string[] condicao = new string[] { "SELECT ", str, " Id,", str1, " Paga ", str2, " WHERE ", str3, " ", sqlQueryCondition.Condicao, " GROUP BY ", str };
+ sqlCommand1.CommandText = string.Concat(condicao);
+ sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray());
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id"));
+ num = (flag ? (long)0 : (long)sqlDataReader["Id"]);
+ long num1 = num;
+ decimal item = (decimal)sqlDataReader["Paga"];
+ if (num1 != 0)
+ {
+ Fechamento fechamento = fechamentos.FirstOrDefault<Fechamento>((Fechamento f) => {
+ if (f.Entidade != tipo)
+ {
+ return false;
+ }
+ return f.Id == num1;
+ });
+ if (fechamento != null)
+ {
+ Fechamento paga = fechamento;
+ paga.Paga = paga.Paga + item;
+ }
+ }
+ }
+ }
+ sqlDataReader = null;
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ }
+
+ private async Task SomaComissaoRecebida(int tipo, List<Fechamento> fechamentos, Filtros filtro, List<Condicao> condicaoDocumento)
+ {
+ object connection;
+ bool flag;
+ bool count;
+ string str;
+ long num;
+ string empty;
+ bool count1;
+ bool flag1;
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ List<Vendedor> vendedores = Auxiliar.Vendedores;
+ long id = vendedores.FirstOrDefault<Vendedor>((Vendedor v) => v.Corretora).Id;
+ string str1 = "c.IdCiaSeg";
+ string str2 = "SUM(p.vlrcomiss)";
+ string str3 = "FROM parcela p INNER JOIN documento d ON p.iddocumento = d.iddocumento INNER JOIN controle c ON c.IdControle = d.IdControle";
+ string str4 = "p.DataRec IS NOT NULL AND";
+ switch (tipo)
+ {
+ case 1:
+ {
+ str1 = "c.IdRamo";
+ break;
+ }
+ case 2:
+ {
+ str1 = "d.IdEstipulante";
+ break;
+ }
+ case 3:
+ {
+ str1 = string.Format("CASE WHEN vp.IdVendedor IS NULL THEN {0} ELSE vp.IdVendedor END", id);
+ break;
+ }
+ }
+ bool flag2 = filtro.Vendedores.Contains(id);
+ string str5 = "";
+ if (tipo == 3 && !flag2)
+ {
+ List<long> tipoVendedor = filtro.TipoVendedor;
+ if (tipoVendedor != null)
+ {
+ count1 = tipoVendedor.Count > 0;
+ }
+ else
+ {
+ count1 = false;
+ }
+ if (!count1)
+ {
+ List<long> nums = filtro.Vendedores;
+ if (nums != null)
+ {
+ flag1 = nums.Count > 0;
+ }
+ else
+ {
+ flag1 = false;
+ }
+ if (!flag1)
+ {
+ goto Label1;
+ }
+ }
+ str5 = "LEFT JOIN vendedorparcela vp ON p.IDPARCELA = vp.IDPARCELA";
+ goto Label0;
+ }
+ Label1:
+ string empty1 = string.Empty;
+ flag = (filtro.TipoVendedor == null ? false : filtro.TipoVendedor.Count > 0);
+ bool flag3 = flag;
+ if (filtro.TipoVendedor != null && filtro.TipoVendedor.Count > 0)
+ {
+ if (flag3)
+ {
+ List<long> tipoVendedor1 = filtro.TipoVendedor;
+ empty = string.Join(",",
+ from t in tipoVendedor1
+ select t.Value<long>().ToString() ?? "");
+ }
+ else
+ {
+ empty = string.Empty;
+ }
+ empty1 = empty;
+ }
+ List<long> nums1 = filtro.TipoVendedor;
+ if (nums1 != null)
+ {
+ count = nums1.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ str = (count ? string.Concat("OUTER APPLY ( SELECT TOP 1 idvendedor, idtipovendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor IN (", empty1, ")) vp") : "OUTER APPLY (SELECT TOP 1 idvendedor FROM vendedorparcela vp WHERE vp.iddocumento = d.iddocumento AND vp.idtipovendedor = 1) vp");
+ str5 = str;
+ Label0:
+ SqlQueryCondition sqlQueryCondition = condicaoDocumento.CreateParameters(0);
+ sqlCommand.CommandTimeout = 1000;
+ SqlCommand sqlCommand1 = sqlCommand;
+ string[] condicao = new string[] { "SELECT ", str1, " as Id,", str2, " Recebida ", str3, " ", str5, " WHERE ", str4, " ", sqlQueryCondition.Condicao, " GROUP BY ", str1 };
+ sqlCommand1.CommandText = string.Concat(condicao);
+ sqlCommand.Parameters.AddRange(sqlQueryCondition.Parametros.ToArray());
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ bool flag4 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("Id"));
+ num = (flag4 ? (long)0 : (long)sqlDataReader["Id"]);
+ long num1 = num;
+ decimal item = (decimal)sqlDataReader["Recebida"];
+ if (num1 != 0)
+ {
+ Fechamento fechamento = fechamentos.FirstOrDefault<Fechamento>((Fechamento f) => {
+ if (f.Entidade != tipo)
+ {
+ return false;
+ }
+ return f.Id == num1;
+ });
+ if (fechamento != null)
+ {
+ Fechamento recebida = fechamento;
+ recebida.Recebida = recebida.Recebida + item;
+ }
+ }
+ }
+ }
+ sqlDataReader = null;
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ }
+
+ public void TrocarCliente(Controle controle, Cliente cliente)
+ {
+ ControleDb controleDb = this._unitOfWork.Repository<ControleDb>().FindEntityById(controle.Id);
+ controleDb.Cliente = ApplicationMapper.Mapper.Map<Cliente, ClienteDb>(cliente);
+ this._unitOfWork.Repository<ControleDb>().Merge(controleDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs
new file mode 100644
index 0000000..4d51e87
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EmpresaRepository.cs
@@ -0,0 +1,143 @@
+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<EmpresaDb>, IEmpresaRepository, IGenericRepository<EmpresaDb>
+ {
+ 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>((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<Empresa> 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<Empresa>();
+ }
+
+ public List<Cliente> FindAsCliente(string filter)
+ {
+ EmpresaRepository.u003cu003ec__DisplayClass9_0 variable = null;
+ IQueryable<EmpresaDb> empresaDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(EmpresaDb), "x");
+ IQueryable<EmpresaDb> empresaDbs1 = empresaDbs.Where<EmpresaDb>(Expression.Lambda<Func<EmpresaDb, bool>>(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<Expression>()), (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<EmpresaDb, Cliente>(Expression.Lambda<Func<EmpresaDb, Cliente>>(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<Cliente>();
+ }
+
+ public Empresa FindByDocumento(string documento)
+ {
+ EmpresaDb empresaDb = base.All().FirstOrDefault<EmpresaDb>((EmpresaDb e) => e.Documento.Replace(",", string.Empty).Replace(".", string.Empty).Replace("-", string.Empty).Replace("/", string.Empty).Equals(documento)) ?? base.All().First<EmpresaDb>();
+ return ApplicationMapper.Mapper.Map<EmpresaDb, Empresa>(empresaDb);
+ }
+
+ public Empresa FindById(long id)
+ {
+ EmpresaDb empresaDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<EmpresaDb, Empresa>(empresaDb);
+ }
+
+ public Empresa FindBySerial(string serial)
+ {
+ EmpresaDb empresaDb = base.All().FirstOrDefault<EmpresaDb>((EmpresaDb e) => e.Serial.Equals(serial)) ?? base.All().First<EmpresaDb>();
+ return ApplicationMapper.Mapper.Map<EmpresaDb, Empresa>(empresaDb);
+ }
+
+ public Empresa Merge(Empresa empresa)
+ {
+ EmpresaDb empresaDb = ApplicationMapper.Mapper.Map<Empresa, EmpresaDb>(empresa);
+ base.Merge(empresaDb);
+ return ApplicationMapper.Mapper.Map<EmpresaDb, Empresa>(empresaDb);
+ }
+
+ public Empresa SaveOrUpdate(Empresa empresa)
+ {
+ EmpresaDb empresaDb = ApplicationMapper.Mapper.Map<Empresa, EmpresaDb>(empresa);
+ this.SaveOrUpdate(empresaDb);
+ return ApplicationMapper.Mapper.Map<EmpresaDb, Empresa>(empresaDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs
new file mode 100644
index 0000000..b0ab6cd
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/EstipulanteRepository.cs
@@ -0,0 +1,93 @@
+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<EstipulanteDb>, IEstipulanteRepository, IGenericRepository<EstipulanteDb>
+ {
+ 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<Estipulante> 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<Estipulante> Find()
+ {
+ return this.Select("");
+ }
+
+ public Estipulante FindById(long id)
+ {
+ EstipulanteDb estipulanteDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<EstipulanteDb, Estipulante>(estipulanteDb);
+ }
+
+ public Estipulante Merge(Estipulante estipulante)
+ {
+ EstipulanteDb estipulanteDb = ApplicationMapper.Mapper.Map<Estipulante, EstipulanteDb>(estipulante);
+ base.Merge(estipulanteDb);
+ return ApplicationMapper.Mapper.Map<EstipulanteDb, Estipulante>(estipulanteDb);
+ }
+
+ public Estipulante SaveOrUpdate(Estipulante estipulante)
+ {
+ EstipulanteDb estipulanteDb = ApplicationMapper.Mapper.Map<Estipulante, EstipulanteDb>(estipulante);
+ this.SaveOrUpdate(estipulanteDb);
+ return ApplicationMapper.Mapper.Map<EstipulanteDb, Estipulante>(estipulanteDb);
+ }
+
+ private List<Estipulante> 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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs
new file mode 100644
index 0000000..e568567
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExpedicaoRepository.cs
@@ -0,0 +1,55 @@
+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<ExpedicaoDb>, IExpedicaoRepository, IGenericRepository<ExpedicaoDb>
+ {
+ 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<Expedicao> FindByIdDocumento(long IdDocumento)
+ {
+ List<ExpedicaoDb> list = (
+ from x in base.All()
+ where x.Apolice.Id == IdDocumento
+ orderby x.DataEnvio descending
+ select x).ToList<ExpedicaoDb>();
+ return ApplicationMapper.Mapper.Map<List<ExpedicaoDb>, List<Expedicao>>(list);
+ }
+
+ public Expedicao Merge(Expedicao expedicao)
+ {
+ ExpedicaoDb expedicaoDb = ApplicationMapper.Mapper.Map<Expedicao, ExpedicaoDb>(expedicao);
+ base.Merge(expedicaoDb);
+ return ApplicationMapper.Mapper.Map<ExpedicaoDb, Expedicao>(expedicaoDb);
+ }
+
+ public Expedicao SaveOrUpdate(Expedicao expedicao)
+ {
+ ExpedicaoDb expedicaoDb = ApplicationMapper.Mapper.Map<Expedicao, ExpedicaoDb>(expedicao);
+ this.SaveOrUpdate(expedicaoDb);
+ return ApplicationMapper.Mapper.Map<ExpedicaoDb, Expedicao>(expedicaoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs
new file mode 100644
index 0000000..ff4afc6
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ExtratoRepository.cs
@@ -0,0 +1,237 @@
+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<ExtratoDb>, IExtratoRepository, IGenericRepository<ExtratoDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public ExtratoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public void Delete(long id)
+ {
+ List<DetalheExtratoDb> list = (
+ from x in this._unitOfWork.Query<DetalheExtratoDb>()
+ where x.Extrato.Id == id
+ select x).ToList<DetalheExtratoDb>();
+ if (list.Count > 0)
+ {
+ this._unitOfWork.Repository<DetalheExtratoDb>().DeleteRange(list);
+ }
+ ExtratoDb extratoDb = base.FindEntityById(id);
+ if (extratoDb == null)
+ {
+ return;
+ }
+ base.Delete(extratoDb);
+ }
+
+ public List<Extrato> 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<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = str,
+ Valores = filtro.Inicio.CriarValor<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ },
+ new Condicao()
+ {
+ Campo = str,
+ Valores = filtro.Fim.CriarValor<DateTime>(),
+ Operador = Operador.MenorEIgual
+ },
+ new Condicao()
+ {
+ Campo = "idstatusextrato",
+ Valores = null,
+ Operador = Operador.Diferente,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "idstatusextrato",
+ Valores = "1".CriarValor<string>(),
+ Operador = Operador.Diferente,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ }
+ };
+ return CustomMap.MapExtrato(this._unitOfWork.Select(condicaos.CreateParameters(0), "SELECT * FROM EXTRATO WHERE ", ""), null);
+ }
+
+ public List<Extrato> FindByEmpresa(long id)
+ {
+ List<ExtratoDb> list = (
+ from x in base.All()
+ where x.IdEmpresa == id
+ select x).ToList<ExtratoDb>();
+ return ApplicationMapper.Mapper.Map<List<ExtratoDb>, List<Extrato>>(list);
+ }
+
+ public Extrato FindById(long id)
+ {
+ ExtratoDb extratoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ExtratoDb, Extrato>(extratoDb);
+ }
+
+ public List<Extrato> FindBySeguradora(long id, long idusuario, long empresa, DateTime inicio, DateTime fim, StatusExtrato? status = null)
+ {
+ List<Extrato> 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<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("idextrato"))), ")");
+ List<int> nums = new List<int>()
+ {
+ 13,
+ 1,
+ 10,
+ 5,
+ 12,
+ 6,
+ 8,
+ 21
+ };
+ sqlCommand.CommandText = string.Concat("SELECT idextrato, idparcelaextrato FROM parcelaextrato WHERE idstatusparcela NOT IN (", string.Join<int>(",",
+ 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<Extrato>();
+ }
+ }
+ }
+ return extratos;
+ }
+
+ public List<Extrato> FindByStatus(StatusExtrato status)
+ {
+ List<ExtratoDb> list = (
+ from x in base.All()
+ where (int)x.Status == (int)status
+ select x).ToList<ExtratoDb>();
+ return ApplicationMapper.Mapper.Map<List<ExtratoDb>, List<Extrato>>(list);
+ }
+
+ public List<Seguradora> FindSeguradoras(StatusExtrato status)
+ {
+ return (
+ from x in (
+ from x in base.All()
+ where (int)x.Status == (int)status
+ select x.Seguradora).ToList<SeguradoraDb>()
+ group x by x.Id into x
+ select new Seguradora()
+ {
+ Id = x.Key,
+ Nome = x.First<SeguradoraDb>().Nome
+ }).ToList<Seguradora>();
+ }
+
+ public Extrato Merge(Extrato extrato)
+ {
+ ExtratoDb extratoDb = ApplicationMapper.Mapper.Map<Extrato, ExtratoDb>(extrato);
+ base.Merge(extratoDb);
+ return ApplicationMapper.Mapper.Map<ExtratoDb, Extrato>(extratoDb);
+ }
+
+ public Extrato SaveOrUpdate(Extrato extrato)
+ {
+ ExtratoDb extratoDb = ApplicationMapper.Mapper.Map<Extrato, ExtratoDb>(extrato);
+ this.SaveOrUpdate(extratoDb);
+ return ApplicationMapper.Mapper.Map<ExtratoDb, Extrato>(extratoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs
new file mode 100644
index 0000000..609964c
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FabricanteRepository.cs
@@ -0,0 +1,65 @@
+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<FabricanteDb>, IFabricanteRepository, IGenericRepository<FabricanteDb>
+ {
+ 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<Fabricante> Find(string filter)
+ {
+ FabricanteRepository.u003cu003ec__DisplayClass7_0 variable = null;
+ IQueryable<FabricanteDb> fabricanteDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(FabricanteDb), "x");
+ List<FabricanteDb> list = fabricanteDbs.Where<FabricanteDb>(Expression.Lambda<Func<FabricanteDb, bool>>(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<Expression>()), (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(FabricanteRepository.u003cu003ec__DisplayClass7_0)), FieldInfo.GetFieldFromHandle(typeof(FabricanteRepository.u003cu003ec__DisplayClass7_0).GetField("filter").FieldHandle)) }), new ParameterExpression[] { parameterExpression })).ToList<FabricanteDb>();
+ return ApplicationMapper.Mapper.Map<List<FabricanteDb>, List<Fabricante>>(list);
+ }
+
+ public Fabricante FindById(long id)
+ {
+ FabricanteDb fabricanteDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<FabricanteDb, Fabricante>(fabricanteDb);
+ }
+
+ public Fabricante Merge(Fabricante fabricante)
+ {
+ FabricanteDb fabricanteDb = ApplicationMapper.Mapper.Map<Fabricante, FabricanteDb>(fabricante);
+ base.Merge(fabricanteDb);
+ return ApplicationMapper.Mapper.Map<FabricanteDb, Fabricante>(fabricanteDb);
+ }
+
+ public Fabricante SaveOrUpdate(Fabricante fabricante)
+ {
+ FabricanteDb fabricanteDb = ApplicationMapper.Mapper.Map<Fabricante, FabricanteDb>(fabricante);
+ this.SaveOrUpdate(fabricanteDb);
+ return ApplicationMapper.Mapper.Map<FabricanteDb, Fabricante>(fabricanteDb);
+ }
+
+ public List<Fabricante> Select()
+ {
+ return ApplicationMapper.Mapper.Map<List<FabricanteDb>, List<Fabricante>>(base.All().ToList<FabricanteDb>());
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs
new file mode 100644
index 0000000..98ce65b
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/FornecedorRepository.cs
@@ -0,0 +1,103 @@
+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<FornecedorDb>, IFornecedorRepository, IGenericRepository<FornecedorDb>
+ {
+ 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<Fornecedor> Find(string filter, bool ativo = false)
+ {
+ List<Fornecedor> 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<Fornecedor>();
+ }
+ }
+ }
+ return fornecedors;
+ }
+
+ public List<Fornecedor> Find()
+ {
+ List<FornecedorDb> list = this._unitOfWork.Session.CreateQuery("from FornecedorDb").List<FornecedorDb>().ToList<FornecedorDb>();
+ return ApplicationMapper.Mapper.Map<List<FornecedorDb>, List<Fornecedor>>(list);
+ }
+
+ public Fornecedor FindById(long id)
+ {
+ FornecedorDb fornecedorDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<FornecedorDb, Fornecedor>(fornecedorDb);
+ }
+
+ public Fornecedor Merge(Fornecedor fornecedor)
+ {
+ FornecedorDb fornecedorDb = ApplicationMapper.Mapper.Map<Fornecedor, FornecedorDb>(fornecedor);
+ base.Merge(fornecedorDb);
+ return ApplicationMapper.Mapper.Map<FornecedorDb, Fornecedor>(fornecedorDb);
+ }
+
+ public Fornecedor SaveOrUpdate(Fornecedor fornecedor)
+ {
+ FornecedorDb fornecedorDb = ApplicationMapper.Mapper.Map<Fornecedor, FornecedorDb>(fornecedor);
+ this.SaveOrUpdate(fornecedorDb);
+ return ApplicationMapper.Mapper.Map<FornecedorDb, Fornecedor>(fornecedorDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs
new file mode 100644
index 0000000..ad6cdb6
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/GranizoRepository.cs
@@ -0,0 +1,71 @@
+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<GranizoDb>, IGranizoRepository, IGenericRepository<GranizoDb>
+ {
+ 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<long> ids)
+ {
+ List<GranizoDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Item.Id)
+ select x).ToList<GranizoDb>();
+ base.DeleteRange(list);
+ }
+
+ public Granizo Find(long id)
+ {
+ GranizoDb granizoDb = base.All().FirstOrDefault<GranizoDb>((GranizoDb x) => x.Item.Id == id) ?? new GranizoDb();
+ return ApplicationMapper.Mapper.Map<GranizoDb, Granizo>(granizoDb);
+ }
+
+ public Granizo FindById(long id)
+ {
+ GranizoDb granizoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<GranizoDb, Granizo>(granizoDb);
+ }
+
+ public Granizo Merge(Granizo granizo)
+ {
+ GranizoDb granizoDb = ApplicationMapper.Mapper.Map<Granizo, GranizoDb>(granizo);
+ base.Merge(granizoDb);
+ return ApplicationMapper.Mapper.Map<GranizoDb, Granizo>(granizoDb);
+ }
+
+ public Granizo SaveOrUpdate(Granizo granizo)
+ {
+ GranizoDb granizoDb = ApplicationMapper.Mapper.Map<Granizo, GranizoDb>(granizo);
+ this.SaveOrUpdate(granizoDb);
+ return ApplicationMapper.Mapper.Map<GranizoDb, Granizo>(granizoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs
new file mode 100644
index 0000000..004432a
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ImpostoRepository.cs
@@ -0,0 +1,102 @@
+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<ImpostoDb>, IImpostoRepository, IGenericRepository<ImpostoDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public ImpostoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Imposto> 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, Imposto>(impostoDb);
+ }
+
+ public List<Imposto> FindByRamo(long id)
+ {
+ return this.Select(string.Format(" AND idramo = {0}", id));
+ }
+
+ public List<Imposto> FindBySeguradora(long id)
+ {
+ return this.Select(string.Format(" AND idciaseg = {0}", id));
+ }
+
+ public Imposto Merge(Imposto imposto)
+ {
+ ImpostoDb impostoDb = ApplicationMapper.Mapper.Map<Imposto, ImpostoDb>(imposto);
+ base.Merge(impostoDb);
+ return ApplicationMapper.Mapper.Map<ImpostoDb, Imposto>(impostoDb);
+ }
+
+ public Imposto SaveOrUpdate(Imposto imposto)
+ {
+ ImpostoDb impostoDb = ApplicationMapper.Mapper.Map<Imposto, ImpostoDb>(imposto);
+ this.SaveOrUpdate(impostoDb);
+ return ApplicationMapper.Mapper.Map<ImpostoDb, Imposto>(impostoDb);
+ }
+
+ private List<Imposto> 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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs
new file mode 100644
index 0000000..5d50ddf
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/IndiceArquivoDigitalRepository.cs
@@ -0,0 +1,402 @@
+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<IndiceArquivoDigitalDb>, IIndiceArquivoDigitalRepository, IGenericRepository<IndiceArquivoDigitalDb>
+ {
+ 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<ControleArquivoDigitalDb>()
+ orderby x.Id descending
+ select x).First<ControleArquivoDigitalDb>();
+ return ApplicationMapper.Mapper.Map<ControleArquivoDigitalDb, ControleArquivoDigital>(controleArquivoDigitalDb);
+ }
+
+ public List<ControleArquivoDigital> BuscarBancos()
+ {
+ List<ControleArquivoDigitalDb> list = (
+ from x in this._unitOfWork.Query<ControleArquivoDigitalDb>()
+ orderby x.Id descending
+ select x).ToList<ControleArquivoDigitalDb>();
+ return ApplicationMapper.Mapper.Map<List<ControleArquivoDigitalDb>, List<ControleArquivoDigital>>(list);
+ }
+
+ public ControleArquivoDigital ConsultarBanco(string banco)
+ {
+ ControleArquivoDigitalDb controleArquivoDigitalDb = this._unitOfWork.Query<ControleArquivoDigitalDb>().First<ControleArquivoDigitalDb>((ControleArquivoDigitalDb x) => x.Catalogo == banco);
+ return ApplicationMapper.Mapper.Map<ControleArquivoDigitalDb, ControleArquivoDigital>(controleArquivoDigitalDb);
+ }
+
+ public void Delete(long id)
+ {
+ IndiceArquivoDigitalDb indiceArquivoDigitalDb = base.FindEntityById(id);
+ if (indiceArquivoDigitalDb == null)
+ {
+ return;
+ }
+ base.Delete(indiceArquivoDigitalDb);
+ }
+
+ public List<IndiceArquivoDigital> 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<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "IndiceId",
+ Valores = (
+ from x in dataTable.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("idnewarquivodigital")).ToList<long>().CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = null,
+ Grupo = 2,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = "1".CriarValor<string>(),
+ 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<IndiceArquivoDigital>();
+ }
+ }
+ }
+ return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, IndiceArquivoDigital>((DataRow x) => {
+ string str;
+ IndiceArquivoDigital indiceArquivoDigital = new IndiceArquivoDigital()
+ {
+ Id = x.Field<long>("idnewarquivodigital"),
+ IdArquivoDigital = x.Field<long>("idarquivodigital"),
+ Bd = x.Field<string>("banco"),
+ Descricao = x.Field<string>("descricao"),
+ Extensao = x.Field<string>("extension")
+ };
+ long? nullable = x.Field<long?>("idcliente");
+ indiceArquivoDigital.IdCliente = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("iddocumento");
+ indiceArquivoDigital.IdDocumento = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("iditem");
+ indiceArquivoDigital.IdItem = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("idparcela");
+ indiceArquivoDigital.IdParcela = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("idsinistro");
+ indiceArquivoDigital.IdSinistro = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("idciaseg");
+ indiceArquivoDigital.IdSeguradora = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("idvendedor");
+ indiceArquivoDigital.IdVendedor = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("idextrato");
+ indiceArquivoDigital.IdExtrato = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("idempresa");
+ indiceArquivoDigital.IdEmpresa = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("idlancamen");
+ indiceArquivoDigital.IdLancamento = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("idfornecedor");
+ indiceArquivoDigital.IdFornecedor = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("idvenctoaleatorio");
+ indiceArquivoDigital.IdProspeccao = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("idsocio");
+ indiceArquivoDigital.IdSocio = nullable.GetValueOrDefault();
+ indiceArquivoDigital.Excluido = (x.Field<object>("excluido") == null ? true : x.Field<object>("excluido").ToString() != "1");
+ nullable = x.Field<long?>("idusuarioarquivo");
+ indiceArquivoDigital.IdUsuario = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("IdTarefa");
+ indiceArquivoDigital.IdTarefa = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("IdNotaFiscal");
+ indiceArquivoDigital.IdNotaFiscal = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("IdEstipulante");
+ indiceArquivoDigital.IdEstipulante = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("usuariocriacao");
+ indiceArquivoDigital.UsuarioCriacao = nullable.GetValueOrDefault();
+ nullable = x.Field<long?>("usuarioalteracao");
+ indiceArquivoDigital.UsuarioAtualizacao = nullable.GetValueOrDefault();
+ DateTime? nullable1 = x.Field<DateTime?>("datacriacao");
+ indiceArquivoDigital.DataCriacao = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue));
+ nullable1 = x.Field<DateTime?>("dataalteracao");
+ indiceArquivoDigital.DataAtualizacao = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue));
+ indiceArquivoDigital.Assinado = (!buscarAssinaturas || dataTable1 == null ? false : dataTable1.AsEnumerable().ToList<DataRow>().Any<DataRow>((DataRow a) => {
+ if (a.Field<long>("IndiceId") != x.Field<long>("idnewarquivodigital"))
+ {
+ return false;
+ }
+ return a.Field<bool>("assinado");
+ }));
+ indiceArquivoDigital.EnviadoAssinatura = (!buscarAssinaturas || dataTable1 == null ? false : dataTable1.AsEnumerable().ToList<DataRow>().Any<DataRow>((DataRow a) => a.Field<long>("IndiceId") == x.Field<long>("idnewarquivodigital")));
+ if (!buscarAssinaturas || dataTable1 == null)
+ {
+ str = "";
+ }
+ else
+ {
+ DataRow dataRow = dataTable1.AsEnumerable().ToList<DataRow>().FirstOrDefault<DataRow>((DataRow a) => a.Field<long>("IndiceId") == x.Field<long>("idnewarquivodigital"));
+ if (dataRow != null)
+ {
+ str = dataRow.Field<string>("UrlAssinatura");
+ }
+ else
+ {
+ str = null;
+ }
+ }
+ indiceArquivoDigital.UrlAssinatura = str;
+ indiceArquivoDigital.AzureGuid = x.Field<Guid?>("AzureGuid");
+ indiceArquivoDigital.AzureStorage = x.Field<string>("AzureStorage");
+ return indiceArquivoDigital;
+ }).ToList<IndiceArquivoDigital>();
+ }
+
+ public List<ArquivoDigital> Find(string condicao)
+ {
+ List<ArquivoDigital> 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<DataRow>()
+ select new ArquivoDigital()
+ {
+ Id = x.Field<long>("Id"),
+ Arquivo = x.Field<byte[]>("Bytes"),
+ Descricao = x.Field<string>("Nome"),
+ Extensao = x.Field<string>("Mime"),
+ DataCriacao = x.Field<DateTime?>("DataCriacao"),
+ AzureGuid = x.Field<Guid?>("AzureGuid")
+ }).ToList<ArquivoDigital>();
+ }
+ catch (Exception exception)
+ {
+ list = new List<ArquivoDigital>();
+ }
+ return list;
+ }
+
+ public ArquivoDigital FindAssinatura(long id)
+ {
+ string str = string.Format(" AND IndiceId = {0}", id);
+ return this.Find(str).FirstOrDefault<ArquivoDigital>();
+ }
+
+ public List<ArquivoDigital> FindAssinatura(List<long> id)
+ {
+ string str = string.Concat(" AND IndiceId IN (", string.Join<long>(",", id), ")");
+ return this.Find(str);
+ }
+
+ public IndiceArquivoDigital FindById(long id)
+ {
+ IndiceArquivoDigitalDb indiceArquivoDigitalDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<IndiceArquivoDigitalDb, IndiceArquivoDigital>(indiceArquivoDigitalDb);
+ }
+
+ public IndiceArquivoDigital Merge(IndiceArquivoDigital indice)
+ {
+ IndiceArquivoDigitalDb indiceArquivoDigitalDb = ApplicationMapper.Mapper.Map<IndiceArquivoDigital, IndiceArquivoDigitalDb>(indice);
+ base.Merge(indiceArquivoDigitalDb);
+ return ApplicationMapper.Mapper.Map<IndiceArquivoDigitalDb, IndiceArquivoDigital>(indiceArquivoDigitalDb);
+ }
+
+ public IndiceArquivoDigital SaveOrUpdate(IndiceArquivoDigital indice)
+ {
+ IndiceArquivoDigitalDb indiceArquivoDigitalDb = ApplicationMapper.Mapper.Map<IndiceArquivoDigital, IndiceArquivoDigitalDb>(indice);
+ this.SaveOrUpdate(indiceArquivoDigitalDb);
+ return ApplicationMapper.Mapper.Map<IndiceArquivoDigitalDb, IndiceArquivoDigital>(indiceArquivoDigitalDb);
+ }
+
+ public ControleArquivoDigital SaveOrUpdate(ControleArquivoDigital catalogo)
+ {
+ ControleArquivoDigitalDb controleArquivoDigitalDb = ApplicationMapper.Mapper.Map<ControleArquivoDigital, ControleArquivoDigitalDb>(catalogo);
+ this._unitOfWork.Repository<ControleArquivoDigitalDb>().SaveOrUpdate(controleArquivoDigitalDb);
+ return ApplicationMapper.Mapper.Map<ControleArquivoDigitalDb, ControleArquivoDigital>(controleArquivoDigitalDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs
new file mode 100644
index 0000000..0d8590f
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ItemRepository.cs
@@ -0,0 +1,1450 @@
+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<ItemDb>, IItemRepository, IGenericRepository<ItemDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public ItemRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public async Task<List<PesquisaAvancada>> BuscaItensPorObs(string pesquisa, FiltroStatusDocumento status, List<VendedorUsuario> vendedorVinculado, TipoPesquisa tipo, bool tipobusca = false)
+ {
+ List<PesquisaAvancada> pesquisaAvancadas;
+ object connection;
+ object obj;
+ DateTime dateTime;
+ List<PesquisaAvancada> pesquisaAvancadas1 = new List<PesquisaAvancada>();
+ DateTime date = Funcoes.GetNetworkTime().Date;
+ List<Condicao> condicaos = new List<Condicao>();
+ 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<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ };
+ condicaos.Add(condicao1);
+ List<Condicao> condicaos1 = condicaos;
+ if (vendedorVinculado.Count > 0)
+ {
+ Condicao condicao2 = new Condicao()
+ {
+ Campo = "vp.IdVendedor",
+ Valores = vendedorVinculado.CriarValor<VendedorUsuario>()
+ };
+ condicaos1.Add(condicao2);
+ }
+ switch (status)
+ {
+ case FiltroStatusDocumento.Vencidos:
+ {
+ List<Condicao> condicaos2 = new List<Condicao>();
+ Condicao condicao3 = new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = new List<object>()
+ {
+ 3,
+ 7
+ },
+ Operador = Operador.Diferente
+ };
+ condicaos2.Add(condicao3);
+ Condicao condicao4 = new Condicao()
+ {
+ Campo = "d.vigencia2",
+ Valores = date.AddDays(-5).CriarValor<DateTime>(),
+ Operador = Operador.Menor
+ };
+ condicaos2.Add(condicao4);
+ condicaos1.AddRange(condicaos2);
+ goto Label0;
+ }
+ case FiltroStatusDocumento.Cancelados:
+ {
+ Condicao condicao5 = new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = 3.CriarValor<int>()
+ };
+ condicaos1.Add(condicao5);
+ goto Label0;
+ }
+ case FiltroStatusDocumento.Recusados:
+ {
+ Condicao condicao6 = new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = 7.CriarValor<int>()
+ };
+ 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<Condicao> condicaos3 = condicaos1;
+ Condicao condicao7 = new Condicao()
+ {
+ Campo = "a.obs",
+ Valores = pesquisa.CriarValor<string>(),
+ Grupo = 3,
+ Operacao = Operacao.Or,
+ Operador = (tipobusca ? Operador.Igual : Operador.Like)
+ };
+ condicaos3.Add(condicao7);
+ List<Condicao> condicaos4 = condicaos1;
+ Condicao condicao8 = new Condicao()
+ {
+ Campo = "r.obs",
+ Valores = pesquisa.CriarValor<string>(),
+ Grupo = 3,
+ Operacao = Operacao.Or,
+ Operador = (tipobusca ? Operador.Igual : Operador.Like)
+ };
+ condicaos4.Add(condicao8);
+ List<Condicao> condicaos5 = condicaos1;
+ Condicao condicao9 = new Condicao()
+ {
+ Campo = "aero.obs",
+ Valores = pesquisa.CriarValor<string>(),
+ Grupo = 3,
+ Operacao = Operacao.Or,
+ Operador = (tipobusca ? Operador.Igual : Operador.Like)
+ };
+ condicaos5.Add(condicao9);
+ List<Condicao> condicaos6 = condicaos1;
+ Condicao condicao10 = new Condicao()
+ {
+ Campo = "g.obs",
+ Valores = pesquisa.CriarValor<string>(),
+ Grupo = 3,
+ Operacao = Operacao.Or,
+ Operador = (tipobusca ? Operador.Igual : Operador.Like)
+ };
+ condicaos6.Add(condicao10);
+ List<Condicao> condicaos7 = condicaos1;
+ Condicao condicao11 = new Condicao()
+ {
+ Campo = "v.obs",
+ Valores = pesquisa.CriarValor<string>(),
+ Grupo = 3,
+ Operacao = Operacao.Or,
+ Operador = (tipobusca ? Operador.Igual : Operador.Like)
+ };
+ condicaos7.Add(condicao11);
+ List<Condicao> condicaos8 = condicaos1;
+ Condicao condicao12 = new Condicao()
+ {
+ Campo = "rd.obs",
+ Valores = pesquisa.CriarValor<string>(),
+ Grupo = 3,
+ Operacao = Operacao.Or,
+ Operador = (tipobusca ? Operador.Igual : Operador.Like)
+ };
+ condicaos8.Add(condicao12);
+ List<Condicao> condicaos9 = condicaos1;
+ Condicao condicao13 = new Condicao()
+ {
+ Campo = "re.bens",
+ Valores = pesquisa.CriarValor<string>(),
+ 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<string>("Descricao", true, true), sqlDataReader.GetFieldValue<string>("Apolice", true, true), null, null, null };
+ obj = (sqlDataReader.GetFieldValue<int>("Tipo", true, true) == 0 ? "" : string.Concat(" - ENDOSSO: ", sqlDataReader.GetFieldValue<string>("Endosso", true, true)));
+ fieldValue[2] = obj;
+ fieldValue[3] = sqlDataReader.GetFieldValue<string>("Proposta", true, true);
+ DateTime? nullable = sqlDataReader.GetFieldValue<DateTime?>("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<long>("IdCliente", true, true),
+ IdDocumento = sqlDataReader.GetFieldValue<long>("IdDocumento", true, true),
+ IdItem = sqlDataReader.GetFieldValue<long>("IdItem", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("Nome", true, true).ToUpper(),
+ Pesquisa = str.ToUpper()
+ };
+ pesquisaAvancadas1.Add(pesquisaAvancada);
+ }
+ }
+ sqlDataReader = null;
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ pesquisaAvancadas = pesquisaAvancadas1;
+ break;
+ }
+ default:
+ {
+ List<Condicao> condicaos10 = new List<Condicao>();
+ Condicao condicao14 = new Condicao()
+ {
+ Campo = "d.situacao"
+ };
+ List<object> objs = new List<object>()
+ {
+ 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<DateTime>(),
+ 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>((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<long> ids)
+ {
+ List<ItemDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Id)
+ select x).ToList<ItemDb>();
+ base.DeleteRange(list);
+ }
+
+ public List<Item> FindByDocumentsIds(long id, StatusItem status = 0, bool sinistroCompleto = false)
+ {
+ List<Condicao> 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<DataRow> action = null;
+ List<Condicao> condicaos1 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.idcontrole",
+ Valores = id.CriarValor<long>()
+ }
+ };
+ switch (status)
+ {
+ case StatusItem.Ativos:
+ {
+ condicaos1.AddRange(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idsubstituido",
+ Valores = null
+ },
+ new Condicao()
+ {
+ Campo = "cancelado",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "cancelado",
+ Valores = "1".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or,
+ Operador = Operador.Diferente
+ }
+ });
+ break;
+ }
+ case StatusItem.Inativos:
+ {
+ condicaos1.AddRange(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idsubstituido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or,
+ Operador = Operador.Diferente
+ },
+ new Condicao()
+ {
+ Campo = "cancelado",
+ Valores = "1".CriarValor<string>(),
+ Grupo = 1
+ }
+ });
+ break;
+ }
+ case StatusItem.Documento:
+ {
+ condicaos1 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.iddocumento",
+ Valores = id.CriarValor<long>()
+ }
+ };
+ 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<Item>();
+ }
+ string str21 = dataTable2.AsEnumerable().First<DataRow>().Field<object>("idramo").ToString();
+ List<long> list = dataTable2.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("iditem")).ToList<long>();
+ 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<long> nums = list.Take<long>(1500).ToList<long>();
+ condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "iditem",
+ Valores = nums.CriarValor<long>()
+ }
+ };
+ 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<Condicao> condicaos2 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idcontrolesinistro",
+ Valores = dataTable5.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("idcontrolesinistro")).ToList<long>().CriarValor<long>()
+ }
+ };
+ dataTable1 = this._unitOfWork.Select(condicaos2.CreateParameters(0), "SELECT * FROM sinistro WHERE ", "");
+ dataTable6.Merge(dataTable1);
+ List<Condicao> condicaos3 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idsinistro",
+ Valores = dataTable6.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("idsinistro")).ToList<long>().CriarValor<long>()
+ }
+ };
+ 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<long>() : list.Except<long>(nums).ToList<long>());
+ }
+ List<Item> items = new List<Item>();
+ 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>((DataRow x) => x.Field<long>("iditem") == long.Parse(this.i["iditem"].ToString())).ToList<DataRow>()
+ select new Cobertura()
+ {
+ Id = x.Field<long>("idcobertura"),
+ Observacao = x.Field<string>("observacao"),
+ Franquia = (x.Field<object>("franquia") == null ? decimal.Zero : x.Field<decimal>("franquia")),
+ Lmi = (x.Field<object>("lmi") == null ? decimal.Zero : x.Field<decimal>("lmi")),
+ Premio = (x.Field<object>("premio") == null ? decimal.Zero : x.Field<decimal>("premio"))
+ }).ToList<Cobertura>();
+ 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>((DataRow x) => x.Field<long>("iditem") == long.Parse(this.i["iditem"].ToString())).ToList<DataRow>().Count == 0)
+ {
+ continue;
+ }
+ DataRow dataRow4 = dataTable3.AsEnumerable().FirstOrDefault<DataRow>((DataRow x) => x.Field<long>("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>((DataRow x) => x.Field<long>("iditem") == long.Parse(this.i["iditem"].ToString())).ToList<DataRow>().Count <= 0)
+ {
+ goto Label2;
+ }
+ granizo.Granizo = new Granizo()
+ {
+ Observacao = dataTable11.AsEnumerable().FirstOrDefault<DataRow>((DataRow x) => x.Field<long>("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>((DataRow x) => x.Field<long>("iditem") == long.Parse(this.i["iditem"].ToString())).ToList<DataRow>().Count <= 0)
+ {
+ goto Label2;
+ }
+ granizo.Aeronautico = new Aeronautico()
+ {
+ Observacao = dataTable10.AsEnumerable().FirstOrDefault<DataRow>((DataRow x) => x.Field<long>("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>((DataRow x) => x.Field<long>("iditem") == long.Parse(this.i["iditem"].ToString())).ToList<DataRow>().Count > 0)
+ {
+ granizo.RiscosDiversos = new RiscosDiversos()
+ {
+ Observacao = dataTable9.AsEnumerable().FirstOrDefault<DataRow>((DataRow x) => x.Field<long>("iditem") == long.Parse(this.i["iditem"].ToString()))["obs"].ToString()
+ };
+ }
+ }
+ Label2:
+ List<Sinistro> sinistros = new List<Sinistro>();
+ granizo.Sinistros = new List<ControleSinistro>();
+ foreach (DataRow row1 in dataTable5.Rows)
+ {
+ if (row1["iditem"].ToString() != row["iditem"].ToString())
+ {
+ continue;
+ }
+ long num = long.Parse(row1["idcontrolesinistro"].ToString());
+ EnumerableRowCollection<DataRow> dataRows = dataTable6.AsEnumerable().Where<DataRow>((DataRow x) => x.Field<long>("idcontrolesinistro") == num);
+ Action<DataRow> action1 = action;
+ if (action1 == null)
+ {
+ Action<DataRow> 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>((DataRow s) => s.Field<long>("idsinistro") == x.Field<long>("idsinistro"));
+ }
+ else
+ {
+ dataRow = null;
+ }
+ DataRow dataRow2 = dataRow;
+ DataTable dataTable = dataTable7;
+ if (dataTable != null)
+ {
+ dataRow1 = dataTable.AsEnumerable().FirstOrDefault<DataRow>((DataRow s) => s.Field<long>("idsinistro") == x.Field<long>("idsinistro"));
+ }
+ else
+ {
+ dataRow1 = null;
+ }
+ DataRow dataRow3 = dataRow1;
+ if (dataRow2 == null)
+ {
+ sinistroVida = null;
+ }
+ else
+ {
+ sinistroVida = new SinistroVida();
+ ((DomainBase)sinistroVida).Id = dataRow2.Field<long>("idsinistrovida");
+ ((SinistroVida)sinistroVida).Beneficiario = dataRow2.Field<string>("beneficiario");
+ }
+ SinistroVida sinistroVida1 = (SinistroVida)sinistroVida;
+ if (dataRow3 == null)
+ {
+ sinistroAuto = null;
+ }
+ else
+ {
+ sinistroAuto = new SinistroAuto();
+ ((DomainBase)sinistroAuto).Id = dataRow3.Field<long>("idsinistroauto");
+ }
+ SinistroAuto sinistroAuto1 = (SinistroAuto)sinistroAuto;
+ sinistros.Add(new Sinistro()
+ {
+ Id = x.Field<long>("idsinistro"),
+ Numero = x.Field<string>("numsinistro"),
+ DataReclamacao = x.Field<DateTime?>("datareclamacao"),
+ StatusSinistro = (x.Field<object>("idstatussinistro") != null ? new StatusSinistro?((StatusSinistro)int.Parse(x.Field<object>("idstatussinistro").ToString())) : null),
+ DataLiquidacao = x.Field<DateTime?>("dataliquidacao"),
+ ItemSinistrado = x.Field<string>("itemsinistrado"),
+ Motivo = x.Field<string>("motivo"),
+ Valor = x.Field<decimal?>("valor").GetValueOrDefault(),
+ SinistroVida = sinistroVida1,
+ SinistroAuto = sinistroAuto1
+ });
+ };
+ Action<DataRow> action3 = action2;
+ action = action2;
+ action1 = action3;
+ }
+ dataRows.ForEach<DataRow>(action1);
+ granizo.Sinistros.Add(new ControleSinistro()
+ {
+ Id = num,
+ DataSinistro = row1.Field<DateTime?>("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>((DataRow x) => x.Field<long>("iditem") == long.Parse(this.i["iditem"].ToString())).ToList<DataRow>().Count == 0)
+ {
+ goto Label4;
+ }
+ DataRow dataRow5 = dataTable4.AsEnumerable().FirstOrDefault<DataRow>((DataRow x) => x.Field<long>("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, Item>(itemDb);
+ }
+
+ public List<Item> FindByIds(List<long> ids)
+ {
+ List<ItemDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Id)
+ select x).ToList<ItemDb>();
+ return ApplicationMapper.Mapper.Map<List<ItemDb>, List<Item>>(list);
+ }
+
+ public List<Item> FindItens(List<long> ids)
+ {
+ List<ItemDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Id)
+ select x).ToList<ItemDb>();
+ return ApplicationMapper.Mapper.Map<List<ItemDb>, List<Item>>(list);
+ }
+
+ public List<Item> FindItens(long id, StatusItem status)
+ {
+ List<Item> 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<long>(",", (
+ from x in dataTable.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("iditem")).ToList<long>()), ")");
+ 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<DataRow>().Select<DataRow, Item>((DataRow x) => {
+ Item item = new Item()
+ {
+ Id = x.Field<long>("iditem"),
+ Descricao = x.Field<string>("descricao"),
+ Ordem = x.Field<int?>("ordem"),
+ Sinistrado = (x.Field<object>("sinistrado") == null ? false : x.Field<string>("sinistrado") == "1"),
+ Cancelado = (x.Field<object>("cancelado") == null ? false : x.Field<string>("cancelado") == "1"),
+ Substituicao = x.Field<long?>("idsubstituicao"),
+ Substituido = x.Field<long?>("idsubstituido"),
+ Status = x.Field<string>("status"),
+ StatusInclusao = x.Field<string>("statusinc")
+ };
+ IEnumerable<DataRow> list =
+ from s in dataTable1.AsEnumerable().ToList<DataRow>()
+ where s.Field<long>("iditem") == x.Field<long>("iditem")
+ select s;
+ Func<DataRow, ControleSinistro> u003cu003e9_104 = ItemRepository.u003cu003ec.u003cu003e9__10_4;
+ if (u003cu003e9_104 == null)
+ {
+ u003cu003e9_104 = (DataRow s) => {
+ ControleSinistro controleSinistro = new ControleSinistro()
+ {
+ Id = s.Field<long>("idcontrolesinistro")
+ };
+ DateTime? nullable = s.Field<DateTime?>("datasinistro");
+ controleSinistro.DataSinistro = new DateTime?((nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue));
+ return controleSinistro;
+ };
+ ItemRepository.u003cu003ec.u003cu003e9__10_4 = u003cu003e9_104;
+ }
+ item.Sinistros = list.Select<DataRow, ControleSinistro>(u003cu003e9_104).ToList<ControleSinistro>();
+ return item;
+ }).OrderBy<Item, int?>((Item x) => x.Ordem).ToList<Item>();
+ }
+ }
+ else
+ {
+ items = new List<Item>();
+ }
+ }
+ }
+ return items;
+ }
+
+ public List<Item> FindItens(List<Documento> documento)
+ {
+ List<Item> 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<long>(",",
+ 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<DataRow>()
+ select new Item()
+ {
+ Id = x.Field<long>("iditem"),
+ Descricao = x.Field<string>("descricao"),
+ Ordem = x.Field<int?>("ordem"),
+ Documento = new Documento()
+ {
+ Id = x.Field<long>("iddocumento")
+ }
+ } into x
+ orderby x.Ordem
+ select x).ToList<Item>();
+ }
+ else
+ {
+ items = new List<Item>();
+ }
+ }
+ }
+ return items;
+ }
+
+ public List<Item> FindItens(long id)
+ {
+ List<ItemDb> list = (
+ from x in base.All()
+ where x.Documento.Id == id
+ select x).ToList<ItemDb>();
+ return ApplicationMapper.Mapper.Map<List<ItemDb>, List<Item>>(list);
+ }
+
+ public int FindNextItem(long id)
+ {
+ int? nullable;
+ int? nullable1;
+ int? ordem;
+ int? nullable2;
+ List<Item> items = this.FindItens(id, StatusItem.Ativos);
+ if (items != null)
+ {
+ Item item = items.LastOrDefault<Item>();
+ 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<CoberturaDb> list;
+ ItemDb itemDb = ApplicationMapper.Mapper.Map<Item, ItemDb>(item);
+ IList<CoberturaDb> coberturaDbs = itemDb.Coberturas;
+ if (coberturaDbs != null)
+ {
+ count = coberturaDbs.Count == 0;
+ }
+ else
+ {
+ count = false;
+ }
+ bool flag = count;
+ List<CoberturaDb> list1 = (
+ from x in this._unitOfWork.Query<CoberturaDb>()
+ where x.Item.Id == itemDb.Id
+ select x).ToList<CoberturaDb>();
+ if (list1 != null)
+ {
+ list = list1.Where<CoberturaDb>((CoberturaDb x) => {
+ IList<CoberturaDb> coberturas = itemDb.Coberturas;
+ Func<CoberturaDb, long> 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<CoberturaDb, long>(u003cu003e9_42).ToList<long>().Contains(x.Id);
+ }).ToList<CoberturaDb>();
+ }
+ else
+ {
+ list = null;
+ }
+ List<CoberturaDb> coberturaDbs1 = list;
+ itemDb.Coberturas = list1;
+ base.Merge(itemDb);
+ if (coberturaDbs1 != null && coberturaDbs1.Count > 0)
+ {
+ this._unitOfWork.Repository<CoberturaDb>().DeleteRange(coberturaDbs1);
+ }
+ if (flag)
+ {
+ this._unitOfWork.Repository<CoberturaDb>().DeleteRange(itemDb.Coberturas);
+ }
+ itemDb.Coberturas = null;
+ return ApplicationMapper.Mapper.Map<ItemDb, Item>(itemDb);
+ }
+
+ public Item SaveOrUpdate(Item item)
+ {
+ ItemDb itemDb = ApplicationMapper.Mapper.Map<Item, ItemDb>(item);
+ this.SaveOrUpdate(itemDb);
+ return ApplicationMapper.Mapper.Map<ItemDb, Item>(itemDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs
new file mode 100644
index 0000000..82f67fc
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/LancamentoRepository.cs
@@ -0,0 +1,345 @@
+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<LancamentoDb>, ILancamentoRepository, IGenericRepository<LancamentoDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public LancamentoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Lancamento> AddRange(List<Lancamento> lancamento)
+ {
+ List<LancamentoDb> lancamentoDbs = ApplicationMapper.Mapper.Map<List<Lancamento>, List<LancamentoDb>>(lancamento);
+ base.AddRange(lancamentoDbs);
+ return ApplicationMapper.Mapper.Map<List<LancamentoDb>, List<Lancamento>>(lancamentoDbs);
+ }
+
+ public bool BancosContasUtilizado(long id)
+ {
+ return base.All().Any<LancamentoDb>((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<Lancamento> Fechamento(FiltroFinanceiro filtro)
+ {
+ string str = (filtro.Centro == null || filtro.Centro.Count == 0 ? "" : string.Concat(" AND c.idcentro IN (", string.Join<long>(",", filtro.Centro), ")"));
+ string str1 = (filtro.Plano == null || filtro.Plano.Count == 0 ? "" : string.Concat(" AND cp.idcplano IN (", string.Join<long>(",", filtro.Plano), ")"));
+ string str2 = (filtro.Planos == null || filtro.Planos.Count == 0 ? "" : string.Concat(" AND c.idcplanos IN (", string.Join<long>(",", filtro.Planos), ")"));
+ string str3 = (filtro.Conta == null || filtro.Conta.Count == 0 ? "" : string.Concat(" AND l.idconta IN (", string.Join<long>(",", 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<DataRow>().Sum<DataRow>((DataRow x) => {
+ decimal? nullable;
+ decimal? nullable1;
+ if (x.Field<string>("sinal") == "0")
+ {
+ nullable = x.Field<decimal?>("vlrbaixa");
+ return nullable.GetValueOrDefault();
+ }
+ decimal? nullable2 = x.Field<decimal?>("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<Lancamento> 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<Lancamento> 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<Lancamento> FindByCodigoBanco(List<string> codigos)
+ {
+ List<string> strs = codigos;
+ List<Lancamento> lancamentos = new List<Lancamento>();
+ while (strs.Count > 0)
+ {
+ List<string> list = strs.Take<string>(2100).ToList<string>();
+ string str = string.Concat(" AND l.CodigoBanco IN ('", string.Join(",", list), "')");
+ lancamentos.AddRange(this.Select(str));
+ strs = (list.Count < 2100 ? new List<string>() : strs.Except<string>(list).ToList<string>());
+ }
+ return lancamentos;
+ }
+
+ public List<ExtratoConta> 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, ExtratoConta>((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<ExtratoConta>();
+ }
+
+ public List<Lancamento> 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<Lancamento>();
+ }
+
+ public List<Lancamento> 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<Lancamento> 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, Lancamento>(lancamentoDb);
+ }
+
+ public List<Lancamento> 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<Lancamento> 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<Lancamento> 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<Lancamento> 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>((LancamentoDb x) => x.Controle.Fornecedor.Id == id);
+ }
+
+ public Lancamento Merge(Lancamento lancamento)
+ {
+ LancamentoDb lancamentoDb = ApplicationMapper.Mapper.Map<Lancamento, LancamentoDb>(lancamento);
+ base.Merge(lancamentoDb);
+ return ApplicationMapper.Mapper.Map<LancamentoDb, Lancamento>(lancamentoDb);
+ }
+
+ public Lancamento SaveOrUpdate(Lancamento lancamento)
+ {
+ LancamentoDb lancamentoDb = ApplicationMapper.Mapper.Map<Lancamento, LancamentoDb>(lancamento);
+ this.SaveOrUpdate(lancamentoDb);
+ return ApplicationMapper.Mapper.Map<LancamentoDb, Lancamento>(lancamentoDb);
+ }
+
+ private List<Lancamento> 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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs
new file mode 100644
index 0000000..3dccaa4
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MaisContatoRepository.cs
@@ -0,0 +1,158 @@
+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<MaisContatoDb>, IMaisContatoRepository, IGenericRepository<MaisContatoDb>
+ {
+ 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<MaisContato> DeleteContato(long clienteId, List<MaisContato> contatos)
+ {
+ if (contatos == null)
+ {
+ return null;
+ }
+ List<MaisContatoDb> list = (
+ from cliente in base.All()
+ where cliente.Cliente.Id == clienteId
+ select cliente).ToList<MaisContatoDb>().Where<MaisContatoDb>((MaisContatoDb contato) => {
+ List<MaisContato> maisContatos = contatos;
+ Func<MaisContato, long> 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<MaisContato, long>(u003cu003e9_83).Contains<long>(contato.Id))
+ {
+ return false;
+ }
+ return !contato.Excluido;
+ }).ToList<MaisContatoDb>();
+ 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<MaisContatoDb>, List<MaisContato>>(list);
+ }
+
+ public List<MaisContato> FindByCustomerId(long id)
+ {
+ ClienteDb clienteDb = this._unitOfWork.Query<ClienteDb>().FirstOrDefault<ClienteDb>((ClienteDb x) => x.Id == id);
+ if (clienteDb == null)
+ {
+ return new List<MaisContato>();
+ }
+ Cliente cliente = ApplicationMapper.Mapper.Map<ClienteDb, Cliente>(clienteDb);
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idcliente",
+ Valores = id.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = null,
+ Operacao = Operacao.Or,
+ Grupo = 1
+ },
+ new Condicao()
+ {
+ Campo = "excluido",
+ Valores = "0".CriarValor<string>(),
+ 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, MaisContato>(maisContatoDb);
+ }
+
+ public List<MaisContato> Inserir(List<MaisContato> contatos, Cliente cliente)
+ {
+ contatos.ForEach((MaisContato x) => x.Cliente = cliente);
+ List<MaisContatoDb> maisContatoDbs = ApplicationMapper.Mapper.Map<List<MaisContato>, List<MaisContatoDb>>(contatos);
+ base.AddRange(maisContatoDbs);
+ return ApplicationMapper.Mapper.Map<List<MaisContatoDb>, List<MaisContato>>(maisContatoDbs);
+ }
+
+ public List<MaisContato> Inserir(List<MaisContato> contatos)
+ {
+ List<MaisContatoDb> maisContatoDbs = ApplicationMapper.Mapper.Map<List<MaisContato>, List<MaisContatoDb>>(contatos);
+ maisContatoDbs.ForEach((MaisContatoDb x) => {
+ if (x.Id == 0)
+ {
+ this.SaveOrUpdate(x);
+ return;
+ }
+ base.Merge(x);
+ });
+ return ApplicationMapper.Mapper.Map<List<MaisContatoDb>, List<MaisContato>>(maisContatoDbs);
+ }
+
+ public MaisContato Merge(MaisContato maisContato)
+ {
+ MaisContatoDb maisContatoDb = ApplicationMapper.Mapper.Map<MaisContato, MaisContatoDb>(maisContato);
+ base.Merge(maisContatoDb);
+ return ApplicationMapper.Mapper.Map<MaisContatoDb, MaisContato>(maisContatoDb);
+ }
+
+ public List<MaisContato> Merge(List<MaisContato> contatos, Cliente cliente)
+ {
+ List<MaisContatoDb> maisContatoDbs = ApplicationMapper.Mapper.Map<List<MaisContato>, List<MaisContatoDb>>(contatos);
+ maisContatoDbs.ForEach((MaisContatoDb x) => {
+ if (x.Id != 0)
+ {
+ base.Merge(x);
+ return;
+ }
+ x.Cliente = ApplicationMapper.Mapper.Map<Cliente, ClienteDb>(cliente);
+ this.SaveOrUpdate(x);
+ });
+ return ApplicationMapper.Mapper.Map<List<MaisContatoDb>, List<MaisContato>>(maisContatoDbs);
+ }
+
+ public MaisContato SaveOrUpdate(MaisContato maisContato)
+ {
+ MaisContatoDb maisContatoDb = ApplicationMapper.Mapper.Map<MaisContato, MaisContatoDb>(maisContato);
+ this.SaveOrUpdate(maisContatoDb);
+ return ApplicationMapper.Mapper.Map<MaisContatoDb, MaisContato>(maisContatoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs
new file mode 100644
index 0000000..639e281
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaSeguradoraRepository.cs
@@ -0,0 +1,127 @@
+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<MetaSeguradoraDb>, IMetaSeguradoraRepository, IGenericRepository<MetaSeguradoraDb>
+ {
+ 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<MetaSeguradora> Find(long id)
+ {
+ return (
+ from x in this._unitOfWork.Session.CreateQuery(string.Format("from MetaSeguradoraDb WHERE idciaseg = {0}", id)).List<MetaSeguradoraDb>()
+ select new MetaSeguradora()
+ {
+ Id = x.Id,
+ Mes = x.Mes,
+ Ano = x.Ano,
+ Valor = x.Valor
+ }).ToList<MetaSeguradora>();
+ }
+
+ public MetaSeguradora FindById(long id)
+ {
+ MetaSeguradoraDb metaSeguradoraDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<MetaSeguradoraDb, MetaSeguradora>(metaSeguradoraDb);
+ }
+
+ public List<MetaSeguradora> FindByMeta(Filtros filtro)
+ {
+ List<MetaSeguradora> metaSeguradoras;
+ object connection;
+ string str = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND idciaseg IN (", string.Join<long>(",",
+ 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<DataRow>()
+ select new MetaSeguradora()
+ {
+ Id = x.Field<long>("IdMeta"),
+ Mes = (Mes)x.Field<int>("Mes"),
+ Ano = long.Parse(x.Field<object>("Ano").ToString()),
+ Valor = x.Field<decimal>("Valor"),
+ Seguradora = Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora s) => s.Id == x.Field<long>("IdCiaseg"))
+ }).ToList<MetaSeguradora>();
+ }
+ else
+ {
+ metaSeguradoras = new List<MetaSeguradora>();
+ }
+ }
+ }
+ return metaSeguradoras;
+ }
+
+ public MetaSeguradora Merge(MetaSeguradora metaSeguradora)
+ {
+ MetaSeguradoraDb idAggilizador = ApplicationMapper.Mapper.Map<MetaSeguradora, MetaSeguradoraDb>(metaSeguradora);
+ idAggilizador.IdAggilizador = idAggilizador.Seguradora.IdAggilizador;
+ base.Merge(idAggilizador);
+ return ApplicationMapper.Mapper.Map<MetaSeguradoraDb, MetaSeguradora>(idAggilizador);
+ }
+
+ public MetaSeguradora SaveOrUpdate(MetaSeguradora metaSeguradora)
+ {
+ MetaSeguradoraDb idAggilizador = ApplicationMapper.Mapper.Map<MetaSeguradora, MetaSeguradoraDb>(metaSeguradora);
+ idAggilizador.IdAggilizador = idAggilizador.Seguradora.IdAggilizador;
+ this.SaveOrUpdate(idAggilizador);
+ return ApplicationMapper.Mapper.Map<MetaSeguradoraDb, MetaSeguradora>(idAggilizador);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs
new file mode 100644
index 0000000..04be6b1
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/MetaVendedorRepository.cs
@@ -0,0 +1,125 @@
+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<MetaVendedorDb>, IMetaVendedorRepository, IGenericRepository<MetaVendedorDb>
+ {
+ 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<MetaVendedor> Find(long id)
+ {
+ return (
+ from x in this._unitOfWork.Session.CreateQuery(string.Format("from MetaVendedorDb WHERE idvendedor = {0}", id)).List<MetaVendedorDb>()
+ select new MetaVendedor()
+ {
+ Id = x.Id,
+ Mes = x.Mes,
+ Ano = x.Ano,
+ Valor = x.Valor
+ }).ToList<MetaVendedor>();
+ }
+
+ public MetaVendedor FindById(long id)
+ {
+ MetaVendedorDb metaVendedorDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<MetaVendedorDb, MetaVendedor>(metaVendedorDb);
+ }
+
+ public List<MetaVendedor> FindByMeta(Filtros filtro)
+ {
+ List<MetaVendedor> metaVendedors;
+ object connection;
+ string str = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND idvendedor IN (", string.Join<long>(",",
+ 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<DataRow>()
+ select new MetaVendedor()
+ {
+ Id = x.Field<long>("IdMetaVendedor"),
+ Mes = (Mes)x.Field<int>("Mes"),
+ Ano = long.Parse(x.Field<object>("Ano").ToString()),
+ Valor = x.Field<decimal>("Valor"),
+ Vendedor = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor v) => v.Id == x.Field<long>("idvendedor"))
+ }).ToList<MetaVendedor>();
+ }
+ else
+ {
+ metaVendedors = new List<MetaVendedor>();
+ }
+ }
+ }
+ return metaVendedors;
+ }
+
+ public MetaVendedor Merge(MetaVendedor metaVendedor)
+ {
+ MetaVendedorDb metaVendedorDb = ApplicationMapper.Mapper.Map<MetaVendedor, MetaVendedorDb>(metaVendedor);
+ base.Merge(metaVendedorDb);
+ return ApplicationMapper.Mapper.Map<MetaVendedorDb, MetaVendedor>(metaVendedorDb);
+ }
+
+ public MetaVendedor SaveOrUpdate(MetaVendedor metaVendedor)
+ {
+ MetaVendedorDb metaVendedorDb = ApplicationMapper.Mapper.Map<MetaVendedor, MetaVendedorDb>(metaVendedor);
+ this.SaveOrUpdate(metaVendedorDb);
+ return ApplicationMapper.Mapper.Map<MetaVendedorDb, MetaVendedor>(metaVendedorDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs
new file mode 100644
index 0000000..799cb19
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ModeloMalaDiretaRepository.cs
@@ -0,0 +1,59 @@
+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<ModeloMalaDiretaDb>, IModeloMalaDiretaRepository, IGenericRepository<ModeloMalaDiretaDb>
+ {
+ 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<ModeloMalaDireta> Find()
+ {
+ List<ModeloMalaDiretaDb> list = base.All().ToList<ModeloMalaDiretaDb>();
+ return ApplicationMapper.Mapper.Map<List<ModeloMalaDiretaDb>, List<ModeloMalaDireta>>(list);
+ }
+
+ public ModeloMalaDireta FindById(long id)
+ {
+ ModeloMalaDiretaDb modeloMalaDiretaDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ModeloMalaDiretaDb, ModeloMalaDireta>(modeloMalaDiretaDb);
+ }
+
+ public ModeloMalaDireta Merge(ModeloMalaDireta modelo)
+ {
+ ModeloMalaDiretaDb modeloMalaDiretaDb = ApplicationMapper.Mapper.Map<ModeloMalaDireta, ModeloMalaDiretaDb>(modelo);
+ base.Merge(modeloMalaDiretaDb);
+ return ApplicationMapper.Mapper.Map<ModeloMalaDiretaDb, ModeloMalaDireta>(modeloMalaDiretaDb);
+ }
+
+ public ModeloMalaDireta SaveOrUpdate(ModeloMalaDireta modelo)
+ {
+ ModeloMalaDiretaDb modeloMalaDiretaDb = ApplicationMapper.Mapper.Map<ModeloMalaDireta, ModeloMalaDiretaDb>(modelo);
+ this.SaveOrUpdate(modeloMalaDiretaDb);
+ return ApplicationMapper.Mapper.Map<ModeloMalaDiretaDb, ModeloMalaDireta>(modeloMalaDiretaDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs
new file mode 100644
index 0000000..f35835a
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/NotaFiscalRepository.cs
@@ -0,0 +1,131 @@
+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<NotaFiscalDb>, INotaFiscalRepository, IGenericRepository<NotaFiscalDb>
+ {
+ 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<NotaFiscal> FindAll()
+ {
+ return this.Select("");
+ }
+
+ public List<NotaFiscal> FindByDatas(Filtros filtro)
+ {
+ string str = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND IdSeguradora IN (", string.Join<long>(",",
+ 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>((NotaFiscalDb x) => x.IdExtrato == (long?)id) != null;
+ }
+
+ public NotaFiscal Merge(NotaFiscal notaFiscal)
+ {
+ NotaFiscalDb notaFiscalDb = ApplicationMapper.Mapper.Map<NotaFiscal, NotaFiscalDb>(notaFiscal);
+ base.Merge(notaFiscalDb);
+ return ApplicationMapper.Mapper.Map<NotaFiscalDb, NotaFiscal>(notaFiscalDb);
+ }
+
+ public NotaFiscal SaveOrUpdate(NotaFiscal notaFiscal)
+ {
+ NotaFiscalDb notaFiscalDb = ApplicationMapper.Mapper.Map<NotaFiscal, NotaFiscalDb>(notaFiscal);
+ this.SaveOrUpdate(notaFiscalDb);
+ return ApplicationMapper.Mapper.Map<NotaFiscalDb, NotaFiscal>(notaFiscalDb);
+ }
+
+ private List<NotaFiscal> Select(string condition)
+ {
+ List<NotaFiscal> 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<DataRow>()
+ select new NotaFiscal()
+ {
+ Id = x.Field<long>("Id"),
+ ValorLiquido = x.Field<decimal>("ValorLiquido"),
+ Obs = x.Field<string>("obs"),
+ IdExtrato = x.Field<long?>("IdExtrato"),
+ Iss = x.Field<decimal>("Iss"),
+ ValorBruto = x.Field<decimal>("ValorBruto"),
+ Data = x.Field<DateTime?>("Data"),
+ Seguradora = Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora v) => v.Id == x.Field<long>("IdSeguradora")),
+ Estipulante = (!x.Field<long?>("IdEstipulante").HasValue ? null : Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante e) => e.Id == x.Field<long>("IdEstipulante"))),
+ Extrato = x.Field<string>("Extrato"),
+ Ir = (x.Field<object>("Ir") != null ? x.Field<decimal>("Ir") : decimal.Zero)
+ }).ToList<NotaFiscal>();
+ }
+ else
+ {
+ notaFiscals = new List<NotaFiscal>();
+ }
+ }
+ }
+ return notaFiscals;
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs
new file mode 100644
index 0000000..d547f22
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosRelatorioRepository.cs
@@ -0,0 +1,111 @@
+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<ParametrosRelatorioDb>, IParametrosRelatorioRepository, IGenericRepository<ParametrosRelatorioDb>
+ {
+ 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<ParametrosRelatorio> Find(long id, Relatorio relatorio)
+ {
+ List<ParametrosRelatorio> parametrosRelatorios = this.Select(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "IdUsuario",
+ Valores = id.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "Relatorio",
+ Valores = relatorio.CriarValor<int>()
+ },
+ new Condicao()
+ {
+ Campo = "Header",
+ Valores = null,
+ Operador = Operador.Diferente
+ },
+ new Condicao()
+ {
+ Campo = "Header",
+ Valores = "".CriarValor<string>(),
+ Operador = Operador.Diferente
+ }
+ });
+ if (parametrosRelatorios.Count == 0)
+ {
+ parametrosRelatorios = this.Select(new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "IdUsuario",
+ Valores = 0.CriarValor<int>()
+ },
+ new Condicao()
+ {
+ Campo = "Relatorio",
+ Valores = relatorio.CriarValor<int>()
+ },
+ new Condicao()
+ {
+ Campo = "Header",
+ Valores = null,
+ Operador = Operador.Diferente
+ },
+ new Condicao()
+ {
+ Campo = "Header",
+ Valores = "".CriarValor<string>(),
+ Operador = Operador.Diferente
+ }
+ });
+ }
+ return parametrosRelatorios;
+ }
+
+ public ParametrosRelatorio Merge(ParametrosRelatorio parametrosRelatorio)
+ {
+ ParametrosRelatorioDb parametrosRelatorioDb = ApplicationMapper.Mapper.Map<ParametrosRelatorio, ParametrosRelatorioDb>(parametrosRelatorio);
+ base.Merge(parametrosRelatorioDb);
+ return ApplicationMapper.Mapper.Map<ParametrosRelatorioDb, ParametrosRelatorio>(parametrosRelatorioDb);
+ }
+
+ public ParametrosRelatorio SaveOrUpdate(ParametrosRelatorio parametrosRelatorio)
+ {
+ ParametrosRelatorioDb parametrosRelatorioDb = ApplicationMapper.Mapper.Map<ParametrosRelatorio, ParametrosRelatorioDb>(parametrosRelatorio);
+ this.SaveOrUpdate(parametrosRelatorioDb);
+ return ApplicationMapper.Mapper.Map<ParametrosRelatorioDb, ParametrosRelatorio>(parametrosRelatorioDb);
+ }
+
+ public List<ParametrosRelatorio> Select(List<Condicao> condicao)
+ {
+ return this._unitOfWork.Select(condicao.CreateParameters(0), "SELECT * FROM CamposRelatorios WHERE ", "").MapCamposRelatorio();
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs
new file mode 100644
index 0000000..19ce696
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParametrosTotalizacaoRepository.cs
@@ -0,0 +1,59 @@
+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<ParametrosTotalizacaoDb>, IParametrosTotalizacaoRepository, IGenericRepository<ParametrosTotalizacaoDb>
+ {
+ 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<ParametrosTotalizacao> Find(long id, Relatorio relatorio)
+ {
+ List<ParametrosTotalizacaoDb> list = (
+ from x in base.All()
+ where x.IdUsuario == id && (int)x.Relatorio == (int)relatorio && x.Header != "AGRUPAMENTO"
+ select x).ToList<ParametrosTotalizacaoDb>();
+ return ApplicationMapper.Mapper.Map<List<ParametrosTotalizacaoDb>, List<ParametrosTotalizacao>>(list);
+ }
+
+ public ParametrosTotalizacao Merge(ParametrosTotalizacao parametrosTotalizacao)
+ {
+ ParametrosTotalizacaoDb parametrosTotalizacaoDb = ApplicationMapper.Mapper.Map<ParametrosTotalizacao, ParametrosTotalizacaoDb>(parametrosTotalizacao);
+ base.Merge(parametrosTotalizacaoDb);
+ return ApplicationMapper.Mapper.Map<ParametrosTotalizacaoDb, ParametrosTotalizacao>(parametrosTotalizacaoDb);
+ }
+
+ public ParametrosTotalizacao SaveOrUpdate(ParametrosTotalizacao parametrosTotalizacao)
+ {
+ ParametrosTotalizacaoDb parametrosTotalizacaoDb = ApplicationMapper.Mapper.Map<ParametrosTotalizacao, ParametrosTotalizacaoDb>(parametrosTotalizacao);
+ this.SaveOrUpdate(parametrosTotalizacaoDb);
+ return ApplicationMapper.Mapper.Map<ParametrosTotalizacaoDb, ParametrosTotalizacao>(parametrosTotalizacaoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs
new file mode 100644
index 0000000..476ec1a
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParceiroRepository.cs
@@ -0,0 +1,108 @@
+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<ParceiroDb>, IParceiroRepository, IGenericRepository<ParceiroDb>
+ {
+ 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<Parceiro> Find()
+ {
+ List<ParceiroDb> list = base.All().ToList<ParceiroDb>();
+ return ApplicationMapper.Mapper.Map<List<ParceiroDb>, List<Parceiro>>(list);
+ }
+
+ public List<Parceiro> Find(string filter)
+ {
+ ParceiroRepository.u003cu003ec__DisplayClass7_0 variable = null;
+ IQueryable<ParceiroDb> parceiroDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(ParceiroDb), "x");
+ IQueryable<ParceiroDb> parceiroDbs1 = parceiroDbs.Where<ParceiroDb>(Expression.Lambda<Func<ParceiroDb, bool>>(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<Expression>()), (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<ParceiroDb, Parceiro>(Expression.Lambda<Func<ParceiroDb, Parceiro>>(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<Parceiro>();
+ }
+
+ public Parceiro FindById(long id)
+ {
+ ParceiroDb parceiroDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ParceiroDb, Parceiro>(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, ParceiroDb>(parceiro);
+ base.Merge(parceiroDb);
+ return ApplicationMapper.Mapper.Map<ParceiroDb, Parceiro>(parceiroDb);
+ }
+
+ public Parceiro SaveOrUpdate(Parceiro parceiro)
+ {
+ ParceiroDb parceiroDb = ApplicationMapper.Mapper.Map<Parceiro, ParceiroDb>(parceiro);
+ this.SaveOrUpdate(parceiroDb);
+ return ApplicationMapper.Mapper.Map<ParceiroDb, Parceiro>(parceiroDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs
new file mode 100644
index 0000000..f6e2cdf
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ParcelaRepository.cs
@@ -0,0 +1,4562 @@
+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<ParcelaDb>, IParcelaRepository, IGenericRepository<ParcelaDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public ParcelaRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public async Task<List<Documento>> BuscaDocumentosPorVigencia(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false)
+ {
+ List<Documento> documentos = new List<Documento>();
+ return await this.BuscaDocumentosPorVigenciaNew(filtro, buscaAssinaturas, painelBi);
+ }
+
+ private async Task<List<Documento>> BuscaDocumentosPorVigenciaNew(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false)
+ {
+ NegocioCorretora fieldValue;
+ Predicate<Estipulante> predicate;
+ object connection;
+ bool count;
+ string str;
+ bool flag;
+ object vendedor;
+ bool count1;
+ Documento documento1;
+ List<Item> itensAtivo;
+ object produto;
+ object obj;
+ object statu;
+ object banco;
+ List<StatusDocumentoAssinado> statusDocumentoAssinados;
+ bool flag1;
+ StatusAssinatura statusAssinatura;
+ NegocioCorretora negocioCorretora;
+ bool count2;
+ bool flag2;
+ Predicate<Estipulante> predicate1 = null;
+ Predicate<Estipulante> predicate2 = null;
+ Predicate<Estipulante> predicate3 = null;
+ Predicate<Estipulante> predicate4 = null;
+ Predicate<Estipulante> predicate5 = null;
+ List<Documento> documentos = new List<Documento>();
+ 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<Condicao> condicaos = this.CriaCondicaoDocumento(filtro, str1);
+ List<Condicao> condicaos1 = new List<Condicao>();
+ 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<string>(),
+ 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<Parcela> parcelas = new List<Parcela>();
+ 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<TipoSeguro>("Situacao", true, true);
+ if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "NegocioCorretora"))
+ {
+ fieldValue = sqlDataReader.GetFieldValue<NegocioCorretora>("NegocioCorretora", true, true);
+ }
+ else
+ {
+ flag3 = tipoSeguro == TipoSeguro.Renovacao;
+ if (flag3)
+ {
+ flag3 = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio");
+ }
+ negocioCorretora = (!flag3 || !(sqlDataReader.GetFieldValue<string>("Negocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio);
+ fieldValue = negocioCorretora;
+ }
+ NegocioCorretora negocioCorretora1 = fieldValue;
+ List<long> negocio = filtro.Negocio;
+ if (negocio != null)
+ {
+ count = negocio.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (!count || filtro.Negocio.Any<long>((long n) => (int)n == (int)negocioCorretora1))
+ {
+ List<Estipulante> estipulantes = new List<Estipulante>();
+ sqlDataReader.GetFieldValue<long>("idestipulante", true, true);
+ if (sqlDataReader.GetFieldValue<long>("idestipulante", true, true) != 0)
+ {
+ List<Estipulante> estipulantes1 = estipulantes;
+ Estipulante nome = new Estipulante();
+ List<Estipulante> estipulantes2 = Auxiliar.Estipulantes;
+ Predicate<Estipulante> predicate6 = predicate1;
+ if (predicate6 == null)
+ {
+ Predicate<Estipulante> predicate7 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante", true, true);
+ predicate = predicate7;
+ predicate1 = predicate7;
+ predicate6 = predicate;
+ }
+ nome.Nome = estipulantes2.Find(predicate6).Nome;
+ estipulantes1.Add(nome);
+ }
+ sqlDataReader.GetFieldValue<long>("idestipulante2", true, true);
+ if (sqlDataReader.GetFieldValue<long>("idestipulante2", true, true) != 0)
+ {
+ List<Estipulante> estipulantes3 = estipulantes;
+ Estipulante nome1 = new Estipulante();
+ List<Estipulante> estipulantes4 = Auxiliar.Estipulantes;
+ Predicate<Estipulante> predicate8 = predicate2;
+ if (predicate8 == null)
+ {
+ Predicate<Estipulante> predicate9 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante2", true, true);
+ predicate = predicate9;
+ predicate2 = predicate9;
+ predicate8 = predicate;
+ }
+ nome1.Nome = estipulantes4.Find(predicate8).Nome;
+ estipulantes3.Add(nome1);
+ }
+ sqlDataReader.GetFieldValue<long>("idestipulante3", true, true);
+ if (sqlDataReader.GetFieldValue<long>("idestipulante3", true, true) != 0)
+ {
+ List<Estipulante> estipulantes5 = estipulantes;
+ Estipulante estipulante1 = new Estipulante();
+ List<Estipulante> estipulantes6 = Auxiliar.Estipulantes;
+ Predicate<Estipulante> predicate10 = predicate3;
+ if (predicate10 == null)
+ {
+ Predicate<Estipulante> predicate11 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante3", true, true);
+ predicate = predicate11;
+ predicate3 = predicate11;
+ predicate10 = predicate;
+ }
+ estipulante1.Nome = estipulantes6.Find(predicate10).Nome;
+ estipulantes5.Add(estipulante1);
+ }
+ sqlDataReader.GetFieldValue<long>("idestipulante4", true, true);
+ if (sqlDataReader.GetFieldValue<long>("idestipulante4", true, true) != 0)
+ {
+ List<Estipulante> estipulantes7 = estipulantes;
+ Estipulante nome2 = new Estipulante();
+ List<Estipulante> estipulantes8 = Auxiliar.Estipulantes;
+ Predicate<Estipulante> predicate12 = predicate4;
+ if (predicate12 == null)
+ {
+ Predicate<Estipulante> predicate13 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante4", true, true);
+ predicate = predicate13;
+ predicate4 = predicate13;
+ predicate12 = predicate;
+ }
+ nome2.Nome = estipulantes8.Find(predicate12).Nome;
+ estipulantes7.Add(nome2);
+ }
+ sqlDataReader.GetFieldValue<long>("idestipulante5", true, true);
+ if (sqlDataReader.GetFieldValue<long>("idestipulante5", true, true) != 0)
+ {
+ List<Estipulante> estipulantes9 = estipulantes;
+ Estipulante estipulante2 = new Estipulante();
+ List<Estipulante> estipulantes10 = Auxiliar.Estipulantes;
+ Predicate<Estipulante> predicate14 = predicate5;
+ if (predicate14 == null)
+ {
+ Predicate<Estipulante> predicate15 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante5", true, true);
+ predicate = predicate15;
+ predicate5 = predicate15;
+ predicate14 = predicate;
+ }
+ estipulante2.Nome = estipulantes10.Find(predicate14).Nome;
+ estipulantes9.Add(estipulante2);
+ }
+ if (estipulantes.Count > 0)
+ {
+ List<Estipulante> estipulantes11 = estipulantes;
+ str = string.Join(" | ",
+ from estipulante in estipulantes11
+ select estipulante.Nome);
+ }
+ else
+ {
+ str = "";
+ }
+ string str3 = str;
+ long num = sqlDataReader.GetFieldValue<long>("IdDocumento", true, true);
+ long fieldValue1 = sqlDataReader.GetFieldValue<long>("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<long>("IdControle", true, true);
+ long fieldValue2 = sqlDataReader.GetFieldValue<long>("IdEmpresa", true, true);
+ Documento documento2 = documentos.Find((Documento p) => p.Controle.Id == num1);
+ if (documento2 != null)
+ {
+ itensAtivo = documento2.ItensAtivo;
+ }
+ else
+ {
+ itensAtivo = null;
+ }
+ List<Item> 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<long>("IdCliente", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("NomeCliente", true, true),
+ Documento = sqlDataReader.GetFieldValue<string>("DocumentoCliente", true, true),
+ Pasta = sqlDataReader.GetFieldValue<string>("PastaCliente", true, true)
+ };
+ bool? fieldValue3 = sqlDataReader.GetFieldValue<bool?>("MalaDireta", true, true);
+ cliente.MalaDireta = new bool?(fieldValue3.GetValueOrDefault(true));
+ ObservableCollection<ClienteTelefone> observableCollection1 = new ObservableCollection<ClienteTelefone>();
+ ClienteTelefone clienteTelefone = new ClienteTelefone()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdTelefone", true, true),
+ Prefixo = sqlDataReader.GetFieldValue<string>("Prefixo", true, true),
+ Numero = sqlDataReader.GetFieldValue<string>("Numero", true, true)
+ };
+ observableCollection1.Add(clienteTelefone);
+ cliente.Telefones = observableCollection1;
+ ObservableCollection<ClienteEmail> observableCollection2 = new ObservableCollection<ClienteEmail>();
+ ClienteEmail clienteEmail = new ClienteEmail()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdEmail", true, true),
+ Email = sqlDataReader.GetFieldValue<string>("Email", true, true)
+ };
+ observableCollection2.Add(clienteEmail);
+ cliente.Emails = observableCollection2;
+ controle.Cliente = cliente;
+ Ramo ramo = new Ramo()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdRamo", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("NomeRamo", true, true)
+ };
+ controle.Ramo = ramo;
+ Seguradora seguradora = new Seguradora()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdCiaSeg", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("NomeCia", true, true),
+ NomeSocial = sqlDataReader.GetFieldValue<string>("NomeSocialCia", true, true)
+ };
+ controle.Seguradora = seguradora;
+ if (sqlDataReader.FieldIsNull("IdProduto"))
+ {
+ produto = null;
+ }
+ else
+ {
+ produto = new Produto();
+ ((DomainBase)produto).Id = sqlDataReader.GetFieldValue<long>("IdProduto", true, true);
+ ((Produto)produto).Nome = sqlDataReader.GetFieldValue<string>("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<long>("IdEstipulante", true, true);
+ ((Estipulante)obj).Nome = sqlDataReader.GetFieldValue<string>("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<long>("IdStatus", true, true);
+ ((Status)statu).Nome = sqlDataReader.GetFieldValue<string>("NomeStatus", true, true);
+ }
+ valueOrDefault.Status = (Status)statu;
+ valueOrDefault.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura);
+ valueOrDefault.Tipo = sqlDataReader.GetFieldValue<int>("Tipo", true, true);
+ valueOrDefault.NegocioCorretora = new NegocioCorretora?(negocioCorretora1);
+ valueOrDefault.Situacao = tipoSeguro;
+ fieldValue3 = sqlDataReader.GetFieldValue<bool?>("ApoliceConferida", true, true);
+ valueOrDefault.ApoliceConferida = fieldValue3.GetValueOrDefault();
+ fieldValue3 = sqlDataReader.GetFieldValue<bool?>("PropostaAssinada", true, true);
+ valueOrDefault.PropostaAssinada = fieldValue3.GetValueOrDefault();
+ valueOrDefault.Proposta = sqlDataReader.GetFieldValue<string>("Proposta", true, true);
+ valueOrDefault.Apolice = sqlDataReader.GetFieldValue<string>("Apolice", true, true);
+ valueOrDefault.PropostaEndosso = sqlDataReader.GetFieldValue<string>("PropostaEndosso", true, true);
+ valueOrDefault.Remessa = sqlDataReader.GetFieldValue<DateTime?>("Remessa", true, true);
+ valueOrDefault.DataControle = sqlDataReader.GetFieldValue<DateTime?>("DataControleParcela", true, true);
+ valueOrDefault.DataCriacao = sqlDataReader.GetFieldValue<DateTime?>("DataCriacaoParcela", true, true);
+ valueOrDefault.Pasta = sqlDataReader.GetFieldValue<string>("PastaDocumento", true, true);
+ if (sqlDataReader.FieldIsNull("IdBanco"))
+ {
+ banco = null;
+ }
+ else
+ {
+ banco = new Banco();
+ ((Banco)banco).Id = sqlDataReader.GetFieldValue<int>("IdBanco", true, true);
+ ((Banco)banco).Nome = sqlDataReader.GetFieldValue<string>("NomeBanco", true, true);
+ }
+ valueOrDefault.Banco = (Banco)banco;
+ valueOrDefault.Agencia = sqlDataReader.GetFieldValue<string>("Agencia", true, true);
+ valueOrDefault.Conta = sqlDataReader.GetFieldValue<string>("Conta", true, true);
+ valueOrDefault.ItensAtivo = items;
+ zero = valueOrDefault;
+ if (flag4 & buscaAssinaturas)
+ {
+ List<StatusDocumentoAssinado> 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<StatusDocumentoAssinado> statusDocumentoAssinados2 = statusDocumentoAssinados1;
+ StatusDocumentoAssinado statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault<StatusDocumentoAssinado>((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<string>("NumeroFatura", true, true));
+ zero.Comissao = sqlDataReader.GetFieldValue<decimal>("Comissao", true, true);
+ zero.PremioLiquido = sqlDataReader.GetFieldValue<decimal>("PremioLiquido", true, true);
+ zero.PremioTotal = sqlDataReader.GetFieldValue<decimal>("PremioTotal", true, true);
+ zero.Vigencia1 = sqlDataReader.GetFieldValue<DateTime>("VigenciaInicial", true, true);
+ zero.Vigencia2 = sqlDataReader.GetFieldValue<DateTime?>("VigenciaFinal", true, true);
+ zero.Emissao = sqlDataReader.GetFieldValue<DateTime?>("EmissaoFatura", true, true);
+ zero.DataControle = sqlDataReader.GetFieldValue<DateTime?>("DataControleParcela", true, true);
+ if (zero.Controle.Cliente.Telefones != null)
+ {
+ long num2 = sqlDataReader.GetFieldValue<long>("IdTelefone", true, true);
+ if (zero.Controle.Cliente.Telefones.FirstOrDefault<ClienteTelefone>((ClienteTelefone t) => t.Id == num2) == null)
+ {
+ ObservableCollection<ClienteTelefone> telefones = zero.Controle.Cliente.Telefones;
+ ClienteTelefone clienteTelefone1 = new ClienteTelefone()
+ {
+ Id = num2,
+ Prefixo = sqlDataReader.GetFieldValue<string>("Prefixo", true, true),
+ Numero = sqlDataReader.GetFieldValue<string>("Numero", true, true)
+ };
+ telefones.Add(clienteTelefone1);
+ }
+ }
+ if (zero.Controle.Cliente.Emails != null)
+ {
+ long num3 = sqlDataReader.GetFieldValue<long>("IdEmail", true, true);
+ if (zero.Controle.Cliente.Emails.FirstOrDefault<ClienteEmail>((ClienteEmail t) => t.Id == num3) == null)
+ {
+ ObservableCollection<ClienteEmail> emails = zero.Controle.Cliente.Emails;
+ ClienteEmail clienteEmail1 = new ClienteEmail()
+ {
+ Id = num3,
+ Email = sqlDataReader.GetFieldValue<string>("Email", true, true)
+ };
+ emails.Add(clienteEmail1);
+ }
+ }
+ Parcela parcela1 = new Parcela()
+ {
+ Id = fieldValue1,
+ Documento = zero
+ };
+ observableCollection = parcela1;
+ parcelas.Add(observableCollection);
+ zero = null;
+ }
+ List<long> tipoVendedor = filtro.TipoVendedor;
+ if (tipoVendedor != null)
+ {
+ flag = tipoVendedor.Count > 0;
+ }
+ else
+ {
+ flag = false;
+ }
+ if (!flag)
+ {
+ List<long> nums = filtro.Vendedores;
+ if (nums != null)
+ {
+ count1 = nums.Count > 0;
+ }
+ else
+ {
+ count1 = false;
+ }
+ if (!count1)
+ {
+ if (observableCollection.Vendedores == null)
+ {
+ observableCollection.Vendedores = new ObservableCollection<VendedorParcela>();
+ }
+ long fieldValue4 = sqlDataReader.GetFieldValue<long>("IdTipoVendedor", true, true);
+ long num4 = sqlDataReader.GetFieldValue<long>("IdVendedor", true, true);
+ if (observableCollection.Vendedores.ToList<VendedorParcela>().Find((VendedorParcela vps) => {
+ if (vps.TipoVendedor.Id != fieldValue4)
+ {
+ return false;
+ }
+ return vps.Vendedor.Id == num4;
+ }) == null)
+ {
+ ObservableCollection<VendedorParcela> observableCollection3 = observableCollection.Vendedores;
+ VendedorParcela vendedorParcela1 = new VendedorParcela()
+ {
+ PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue<decimal>("PorcentagemRepasse", true, true)),
+ TipoVendedor = new TipoVendedor()
+ {
+ Id = fieldValue4
+ }
+ };
+ Vendedor vendedor1 = new Vendedor()
+ {
+ Id = num4,
+ Nome = sqlDataReader.GetFieldValue<string>("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<long>("IdVendedor", true, true);
+ ((Vendedor)vendedor).Nome = sqlDataReader.GetFieldValue<string>("NomeVendedor", true, true);
+ }
+ documento6.VendedorPrincipal = (Vendedor)vendedor;
+ }
+ str3 = null;
+ }
+ }
+ }
+ }
+ sqlCommand = null;
+ List<long> tipoVendedor1 = filtro.TipoVendedor;
+ if (tipoVendedor1 != null)
+ {
+ count2 = tipoVendedor1.Count > 0;
+ }
+ else
+ {
+ count2 = false;
+ }
+ if (!count2)
+ {
+ List<long> 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<VendedorParcela> vendedorParcelas1 = await this.BuscaVendedoresPorIdParcela(parcela2.Id, parcela2.Documento.Controle.IdEmpresa, (long)1);
+ parcela3.Vendedores = new ObservableCollection<VendedorParcela>(vendedorParcelas1);
+ parcela3 = null;
+ }
+ Label0:
+ parcelas.ForEach((Parcela p) => {
+ decimal? nullable2;
+ decimal? porcentagemRepasse;
+ ObservableCollection<VendedorParcela> vendedores = p.Vendedores;
+ Func<VendedorParcela, long> 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<VendedorParcela> vendedorParcelas = vendedores.OrderBy<VendedorParcela, long>(u003cu003e9_1516);
+ Func<VendedorParcela, Vendedor> 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<Vendedor> list = vendedorParcelas.Select<VendedorParcela, Vendedor>(u003cu003e9_1517).ToList<Vendedor>();
+ p.Documento.Vendedores = list;
+ Documento documento = p.Documento;
+ VendedorParcela vendedorParcela = p.Vendedores.FirstOrDefault<VendedorParcela>((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<Documento> documentos1 = documentos;
+ sqlQueryCondition = null;
+ return documentos1;
+ }
+
+ private async Task<List<Documento>> BuscaDocumentosPorVigenciaPrivate(Filtros filtro, bool buscaAssinaturas = false, bool painelBi = false)
+ {
+ NegocioCorretora negocioCorretora;
+ List<long>.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<StatusDocumentoAssinado> statusDocumentoAssinados;
+ bool flag3;
+ StatusAssinatura statusAssinatura;
+ DateTime? nullable6;
+ decimal? porcentagemRepasse;
+ List<long> list;
+ List<long> nums;
+ NegocioCorretora negocioCorretora1;
+ bool count1;
+ Func<VendedorParcela, bool> func = null;
+ Func<Seguradora, bool> func1 = null;
+ Func<Ramo, bool> func2 = null;
+ Func<Produto, bool> func3 = null;
+ Func<Estipulante, bool> func4 = null;
+ Func<Status, bool> func5 = null;
+ List<Documento> documentos = new List<Documento>();
+ 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<Condicao> condicaos = this.CriaCondicaoDocumento(filtro, str1);
+ List<Condicao> condicaos1 = new List<Condicao>();
+ 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<string>(),
+ 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<long> tipoVendedor = filtro.TipoVendedor;
+ if (tipoVendedor != null)
+ {
+ count = tipoVendedor.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (!count)
+ {
+ List<long> 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<Vendedor> vendedors = new List<Vendedor>();
+ List<Item> items = new List<Item>();
+ List<StatusDocumentoAssinado> statusDocumentoAssinados1 = new List<StatusDocumentoAssinado>();
+ StatusDocumentoAssinado statusDocumentoAssinado = null;
+ decimal valueOrDefault = new decimal();
+ if (filtro.Negocio == null || filtro.Negocio.Count <= 0 || filtro.Negocio.Any<long>((long n) => (int)n == (int)negocioCorretora2))
+ {
+ if (!painelBi)
+ {
+ List<VendedorParcela> 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<long>())
+ {
+ if (!vendedorParcelas.Any<VendedorParcela>((VendedorParcela v) => v.Vendedor.Id == list1))
+ {
+ continue;
+ }
+ flag6 = false;
+ }
+ if (flag6)
+ {
+ continue;
+ }
+ }
+ List<VendedorParcela> vendedorParcelas1 = vendedorParcelas;
+ IOrderedEnumerable<VendedorParcela> id =
+ from tipo in vendedorParcelas1
+ orderby tipo.TipoVendedor.Id
+ select tipo;
+ vendedors = (
+ from v in id
+ select v.Vendedor).ToList<Vendedor>();
+ if (filtro.TipoVendedor != null && filtro.TipoVendedor.Count != 0)
+ {
+ if (filtro.TipoVendedor != null)
+ {
+ List<long> tipoVendedor1 = filtro.TipoVendedor;
+ if (tipoVendedor1.Any<long>((long v) => v == (long)1))
+ {
+ goto Label3;
+ }
+ }
+ Vendedor vendedor1 = null;
+ Filtros filtro1 = filtro;
+ if (filtro1 != null)
+ {
+ List<long> nums1 = filtro1.TipoVendedor;
+ if (nums1 != null)
+ {
+ list = (
+ from t in nums1
+ orderby t
+ select t).ToList<long>();
+ }
+ 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<long> vendedores1 = filtro2.Vendedores;
+ if (vendedores1 != null)
+ {
+ nums = vendedores1.ToList<long>();
+ }
+ else
+ {
+ nums = null;
+ }
+ }
+ else
+ {
+ nums = null;
+ }
+ List<long>.Enumerator enumerator1 = nums.GetEnumerator();
+ try
+ {
+ do
+ {
+ if (!enumerator1.MoveNext())
+ {
+ break;
+ }
+ long current1 = enumerator1.Current;
+ IEnumerable<VendedorParcela> vendedorParcelas2 = vendedorParcelas.Where<VendedorParcela>((VendedorParcela v) => {
+ if (v.TipoVendedor.Id != current)
+ {
+ return false;
+ }
+ return v.Vendedor.Id == current1;
+ });
+ vendedor1 = (
+ from v in vendedorParcelas2
+ select v.Vendedor).FirstOrDefault<Vendedor>();
+ }
+ 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<VendedorParcela> vendedorParcelas3 = vendedorParcelas;
+ Func<VendedorParcela, bool> func6 = func;
+ if (func6 == null)
+ {
+ Func<VendedorParcela, bool> id1 = (VendedorParcela v) => v.TipoVendedor.Id == filtro.TipoVendedor.FirstOrDefault<long>();
+ Func<VendedorParcela, bool> func7 = id1;
+ func = id1;
+ func6 = func7;
+ }
+ IEnumerable<VendedorParcela> vendedorParcelas4 = vendedorParcelas3.Where<VendedorParcela>(func6);
+ vendedor1 = (
+ from v in vendedorParcelas4
+ select v.Vendedor).FirstOrDefault<Vendedor>();
+ }
+ Vendedor vendedor2 = vendedor1;
+ if (vendedor2 == null)
+ {
+ vendedor2 = vendedors.FirstOrDefault<Vendedor>();
+ }
+ vendedor = vendedor2;
+ goto Label2;
+ }
+ List<VendedorParcela> vendedorParcelas5 = vendedorParcelas;
+ IEnumerable<VendedorParcela> id2 =
+ from v in vendedorParcelas5
+ where v.TipoVendedor.Id == (long)1
+ select v;
+ vendedor = (
+ from v in id2
+ select v.Vendedor).FirstOrDefault<Vendedor>();
+ Label2:
+ VendedorParcela vendedorParcela = vendedorParcelas.FirstOrDefault<VendedorParcela>((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<StatusDocumentoAssinado> statusDocumentoAssinados2 = statusDocumentoAssinados1;
+ statusDocumentoAssinado = statusDocumentoAssinados2.FirstOrDefault<StatusDocumentoAssinado>((StatusDocumentoAssinado a) => a.Selecionado);
+ }
+ items = await this.BuscaItemsPorIdControle(item1);
+ }
+ List<Documento> 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<Seguradora> seguradoras = Auxiliar.Seguradoras;
+ Func<Seguradora, bool> func8 = func1;
+ if (func8 == null)
+ {
+ Func<Seguradora, bool> id3 = (Seguradora seg) => seg.Id == (long)sqlDataReader["idciaseg"];
+ Func<Seguradora, bool> func9 = id3;
+ func1 = id3;
+ func8 = func9;
+ }
+ seguradora = seguradoras.FirstOrDefault<Seguradora>(func8);
+ }
+ controle3.Seguradora = seguradora;
+ Controle controle4 = controle;
+ bool flag8 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idramo"));
+ Controle controle5 = controle4;
+ if (flag8)
+ {
+ ramo1 = null;
+ }
+ else
+ {
+ List<Ramo> ramos = Auxiliar.Ramos;
+ Func<Ramo, bool> func10 = func2;
+ if (func10 == null)
+ {
+ Func<Ramo, bool> id4 = (Ramo ramo) => ramo.Id == (long)sqlDataReader["idramo"];
+ Func<Ramo, bool> func11 = id4;
+ func2 = id4;
+ func10 = func11;
+ }
+ ramo1 = ramos.FirstOrDefault<Ramo>(func10);
+ }
+ controle5.Ramo = ramo1;
+ Controle controle6 = controle;
+ bool flag9 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("idproduto"));
+ Controle controle7 = controle6;
+ if (flag9)
+ {
+ produto1 = null;
+ }
+ else
+ {
+ List<Produto> produtos = Auxiliar.Produtos;
+ Func<Produto, bool> func12 = func3;
+ if (func12 == null)
+ {
+ Func<Produto, bool> id5 = (Produto produto) => produto.Id == (long)sqlDataReader["idproduto"];
+ Func<Produto, bool> func13 = id5;
+ func3 = id5;
+ func12 = func13;
+ }
+ produto1 = produtos.FirstOrDefault<Produto>(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<Estipulante> estipulantes = Auxiliar.Estipulantes;
+ Func<Estipulante, bool> func14 = func4;
+ if (func14 == null)
+ {
+ Func<Estipulante, bool> id6 = (Estipulante estipulante) => estipulante.Id == (long)sqlDataReader["idestipulante"];
+ Func<Estipulante, bool> func15 = id6;
+ func4 = id6;
+ func14 = func15;
+ }
+ estipulante1 = estipulantes.FirstOrDefault<Estipulante>(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<Status> statusApolice = Auxiliar.StatusApolice;
+ Func<Status, bool> func16 = func5;
+ if (func16 == null)
+ {
+ Func<Status, bool> id7 = (Status status) => status.Id == (long)sqlDataReader["idstatus"];
+ Func<Status, bool> func17 = id7;
+ func5 = id7;
+ func16 = func17;
+ }
+ statu = statusApolice.FirstOrDefault<Status>(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<Documento> documentos2 = documentos;
+ documentos = null;
+ sqlQueryCondition = null;
+ return documentos2;
+ }
+
+ private async Task<List<Item>> BuscaItemsPorIdControle(long idControle)
+ {
+ object connection;
+ List<Item> items = new List<Item>();
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 1000;
+ sqlCommand.CommandText = "SELECT i.iditem,i.descricao FROM item i INNER JOIN documento d ON d.iddocumento = i.iddocumento WHERE d.idcontrole = @controle AND i.idsubstituido IS NULL AND (i.cancelado IS NULL OR i.cancelado = 0)";
+ sqlCommand.Parameters.Add("@controle", SqlDbType.BigInt).Value = idControle;
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ List<Item> items1 = items;
+ Item item = new Item()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("iditem", true, true),
+ Descricao = sqlDataReader.GetFieldValue<string>("descricao", true, true)
+ };
+ items1.Add(item);
+ }
+ }
+ sqlDataReader = null;
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ List<Item> items2 = items;
+ items = null;
+ return items2;
+ }
+
+ private async Task<List<Item>> BuscaItemsPorIdControle(SqlConnection connection, long idControle)
+ {
+ List<Item> items = new List<Item>();
+ 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<Item> items1 = items;
+ Item item = new Item()
+ {
+ Id = (long)sqlDataReader["iditem"],
+ Descricao = sqlDataReader["descricao"].ToString()
+ };
+ items1.Add(item);
+ }
+ }
+ sqlDataReader = null;
+ }
+ sqlCommand = null;
+ List<Item> items2 = items;
+ items = null;
+ return items2;
+ }
+
+ public Documento BuscarApolice(long id)
+ {
+ DocumentoDb documento;
+ ParcelaDb parcelaDb = base.All().FirstOrDefault<ParcelaDb>((ParcelaDb x) => x.Id == id);
+ if (parcelaDb != null)
+ {
+ documento = parcelaDb.Documento;
+ }
+ else
+ {
+ documento = null;
+ }
+ return ApplicationMapper.Mapper.Map<DocumentoDb, Documento>(documento);
+ }
+
+ public string BuscarLogAntigo(long id, string conn)
+ {
+ object connection;
+ string str = "";
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "id",
+ Valores = id.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "idname",
+ Valores = "IDParcela".CriarValor<string>()
+ }
+ };
+ this._unitOfWork.CriarAuxiliar();
+ SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl;
+ string str1 = "oldbacklog";
+ if (sessionFactory != null)
+ {
+ connection = sessionFactory.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandText = "SELECT TOP 1 * FROM controlelog";
+ SqlDataReader sqlDataReader = sqlCommand.ExecuteReader();
+ sqlDataReader.Read();
+ string str2 = sqlDataReader["bdname"].ToString();
+ str1 = sqlDataReader["tabela"].ToString();
+ sqlDataReader.Close();
+ if (sqlConnection.Database != str2)
+ {
+ conn = conn.Replace(sqlConnection.Database, str2);
+ }
+ }
+ }
+ DataTable dataTable = new DataTable();
+ using (SqlConnection sqlConnection1 = new SqlConnection(conn))
+ {
+ sqlConnection1.Open();
+ using (SqlCommand sqlCommand1 = sqlConnection1.CreateCommand())
+ {
+ sqlCommand1.CommandTimeout = 15000;
+ dataTable = sqlCommand1.Select(condicaos.CreateParameters(0), string.Concat("SELECT b.* FROM ", str1, " b WHERE"), "");
+ }
+ }
+ if (dataTable == null || dataTable.Rows.Count == 0)
+ {
+ return "";
+ }
+ if (dataTable != null)
+ {
+ dataTable.AsEnumerable().OrderBy<DataRow, long>((DataRow x) => x.Field<long>("idbacklog")).ToList<DataRow>().ForEach((DataRow x) => {
+ str = string.Concat(new string[] { str, "<br><FONT face=verdana color=#FF0000 size=2><strong>(", x.Field<object>("data").ToString(), ")</font><FONT face=verdana size=2 color=#000000> ", Auxiliar.Usuarios.Find((Usuario u) => u.Id == x.Field<long>("idusuario")).Nome, "</strong></font><br>" });
+ str = string.Concat(str, "<FONT face=verdana color=#000000 size=1>", x.Field<object>("historico").ToString().Replace(Environment.NewLine, "<br>"), "</font>");
+ });
+ }
+ return str;
+ }
+
+ public 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<List<StatusDocumentoAssinado>> BuscaStatusAssinadosPorIdDocumento(long idDocumento)
+ {
+ object connection;
+ DateTime? nullable;
+ Usuario usuario1;
+ Func<Usuario, bool> func = null;
+ List<StatusDocumentoAssinado> statusDocumentoAssinados = new List<StatusDocumentoAssinado>();
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandTimeout = 1000;
+ sqlCommand.CommandText = "SELECT a.idnewarquivodigital,a.descricao,ISNULL(s.Status ,3) status,s.assinado,a.iddocumento,s.id,s.usuarioid,s.enviado FROM newarquivodigital a LEFT JOIN ArquivoParaAssinatura s ON a.idnewarquivodigital = s.indiceid WHERE a.iddocumento = @documento AND (a.excluido = 0 OR a.excluido IS NULL)";
+ sqlCommand.Parameters.Add("@documento", SqlDbType.BigInt).Value = idDocumento;
+ using (SqlDataReader sqlDataReader = await sqlCommand.ExecuteReaderAsync())
+ {
+ while (true)
+ {
+ if (!await sqlDataReader.ReadAsync())
+ {
+ break;
+ }
+ List<StatusDocumentoAssinado> statusDocumentoAssinados1 = statusDocumentoAssinados;
+ StatusDocumentoAssinado statusDocumentoAssinado = new StatusDocumentoAssinado()
+ {
+ Id = (long)sqlDataReader["idnewarquivodigital"],
+ Documento = sqlDataReader["descricao"].ToString(),
+ Status = (StatusAssinatura)((int)sqlDataReader["status"])
+ };
+ StatusDocumentoAssinado statusDocumentoAssinado1 = statusDocumentoAssinado;
+ bool flag = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("enviado"));
+ StatusDocumentoAssinado statusDocumentoAssinado2 = statusDocumentoAssinado1;
+ if (flag)
+ {
+ nullable = null;
+ }
+ else
+ {
+ nullable = new DateTime?((DateTime)sqlDataReader["enviado"]);
+ }
+ statusDocumentoAssinado2.Envio = nullable;
+ StatusDocumentoAssinado statusDocumentoAssinado3 = statusDocumentoAssinado;
+ bool flag1 = await sqlDataReader.IsDBNullAsync(sqlDataReader.GetOrdinal("usuarioid"));
+ StatusDocumentoAssinado statusDocumentoAssinado4 = statusDocumentoAssinado3;
+ if (flag1)
+ {
+ usuario1 = null;
+ }
+ else
+ {
+ List<Usuario> usuarios = Auxiliar.Usuarios;
+ Func<Usuario, bool> func1 = func;
+ if (func1 == null)
+ {
+ Func<Usuario, bool> id = (Usuario usuario) => usuario.Id == (long)sqlDataReader["usuarioid"];
+ Func<Usuario, bool> func2 = id;
+ func = id;
+ func1 = func2;
+ }
+ usuario1 = usuarios.FirstOrDefault<Usuario>(func1);
+ }
+ statusDocumentoAssinado4.Usuario = usuario1;
+ statusDocumentoAssinados1.Add(statusDocumentoAssinado);
+ statusDocumentoAssinados1 = null;
+ statusDocumentoAssinado1 = null;
+ statusDocumentoAssinado3 = null;
+ statusDocumentoAssinado = null;
+ }
+ }
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ List<StatusDocumentoAssinado> statusDocumentoAssinados2 = statusDocumentoAssinados;
+ statusDocumentoAssinados = null;
+ return statusDocumentoAssinados2;
+ }
+
+ private async Task<List<VendedorParcela>> BuscaVendedoresPorIdParcela(long idParcela, long idEmpresa = 0L, long idSubTipo = 0L)
+ {
+ object connection;
+ string str;
+ string str1;
+ List<VendedorParcela> vendedorParcelas = new List<VendedorParcela>();
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ 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<VendedorParcela> vendedorParcelas1 = vendedorParcelas;
+ VendedorParcela vendedorParcela = new VendedorParcela();
+ TipoVendedor tipoVendedor = new TipoVendedor()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("idtipovendedor", true, true)
+ };
+ vendedorParcela.TipoVendedor = tipoVendedor;
+ Vendedor vendedor = new Vendedor()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("idvendedor", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("nomevendedor", true, true)
+ };
+ vendedorParcela.Vendedor = vendedor;
+ vendedorParcela.PorcentagemRepasse = sqlDataReader.GetFieldValue<decimal?>("vrep", true, true);
+ vendedorParcela.ValorRepasse = sqlDataReader.GetFieldValue<decimal?>("vlrrep", true, true);
+ vendedorParcela.DataPagamento = sqlDataReader.GetFieldValue<DateTime?>("datapgt", true, true);
+ vendedorParcela.DataPrePagamento = sqlDataReader.GetFieldValue<DateTime?>("dataprepagto", true, true);
+ vendedorParcelas1.Add(vendedorParcela);
+ }
+ if (idEmpresa > (long)0)
+ {
+ List<VendedorParcela> vendedorParcelas2 = vendedorParcelas;
+ if (!vendedorParcelas2.Any<VendedorParcela>((VendedorParcela v) => v.TipoVendedor.Id == (long)1))
+ {
+ List<VendedorParcela> vendedorParcelas3 = vendedorParcelas;
+ VendedorParcela vendedorParcela1 = new VendedorParcela()
+ {
+ TipoVendedor = new TipoVendedor()
+ {
+ Id = (long)1
+ },
+ Vendedor = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor v) => {
+ if (v.IdEmpresa != idEmpresa)
+ {
+ return false;
+ }
+ return v.Corretora;
+ }),
+ PorcentagemRepasse = new decimal?(new decimal())
+ };
+ vendedorParcelas3.Add(vendedorParcela1);
+ }
+ }
+ }
+ sqlDataReader = null;
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ List<VendedorParcela> vendedorParcelas4 = vendedorParcelas;
+ List<VendedorParcela> list = (
+ from v in vendedorParcelas4
+ orderby v.TipoVendedor.Id
+ select v).ToList<VendedorParcela>();
+ vendedorParcelas = null;
+ return list;
+ }
+
+ private List<Condicao> CriaCondicaoDocumento(Filtros filtro, string referencia)
+ {
+ bool count;
+ bool flag;
+ bool count1;
+ bool flag1;
+ bool count2;
+ bool flag2;
+ bool count3;
+ bool flag3;
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = referencia,
+ Valores = filtro.Inicio.CriarValor<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ },
+ new Condicao()
+ {
+ Campo = referencia,
+ Valores = filtro.Fim.CriarValor<DateTime>(),
+ Operador = Operador.MenorEIgual
+ }
+ };
+ List<long> seguradoras = filtro.Seguradoras;
+ if (seguradoras != null)
+ {
+ count = seguradoras.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (count)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idciaseg",
+ Valores = filtro.Seguradoras.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> ramos = filtro.Ramos;
+ if (ramos != null)
+ {
+ flag = ramos.Count > 0;
+ }
+ else
+ {
+ flag = false;
+ }
+ if (flag)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idramo",
+ Valores = filtro.Ramos.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> status = filtro.Status;
+ if (status != null)
+ {
+ count1 = status.Count > 0;
+ }
+ else
+ {
+ count1 = false;
+ }
+ if (count1)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = filtro.Status.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> tipoVendedor = filtro.TipoVendedor;
+ if (tipoVendedor != null)
+ {
+ flag1 = tipoVendedor.Count > 0;
+ }
+ else
+ {
+ flag1 = false;
+ }
+ if (flag1)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "vp.idtipovendedor",
+ Valores = filtro.TipoVendedor.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> vendedores = filtro.Vendedores;
+ if (vendedores != null)
+ {
+ count2 = vendedores.Count > 0;
+ }
+ else
+ {
+ count2 = false;
+ }
+ if (count2)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "vp.idvendedor",
+ Valores = filtro.Vendedores.CriarValor<long>(),
+ Grupo = 5,
+ Operacao = Operacao.Or
+ });
+ }
+ List<long> estipulantes = filtro.Estipulantes;
+ if (estipulantes != null)
+ {
+ flag2 = estipulantes.Count > 0;
+ }
+ else
+ {
+ flag2 = false;
+ }
+ if (flag2)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.idestipulante",
+ Valores = filtro.Estipulantes.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> produtos = filtro.Produtos;
+ if (produtos != null)
+ {
+ count3 = produtos.Count > 0;
+ }
+ else
+ {
+ count3 = false;
+ }
+ if (count3)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idproduto",
+ Valores = filtro.Produtos.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> negocio = filtro.Negocio;
+ if (negocio != null)
+ {
+ flag3 = negocio.Count > 0;
+ }
+ else
+ {
+ flag3 = false;
+ }
+ if (flag3)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.NegocioCorretora",
+ Valores = filtro.Negocio.CriarValor<long>(),
+ Operacao = Operacao.Or,
+ Grupo = 6
+ });
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.NegocioCorretora",
+ Valores = null,
+ Operacao = Operacao.Or,
+ Grupo = 6
+ });
+ }
+ if (filtro.IdEmpresa > (long)0)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idempresa",
+ Valores = filtro.IdEmpresa.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ return condicaos;
+ }
+
+ private List<Condicao> CriaCondicaoFaturaPendente(Filtros filtro, string referencia)
+ {
+ return new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = referencia,
+ Valores = filtro.Inicio.CriarValor<DateTime>(),
+ Operador = Operador.MenorEIgual
+ },
+ new Condicao()
+ {
+ Campo = referencia,
+ Valores = filtro.Fim.CriarValor<DateTime>(),
+ Operador = Operador.MaiorEIgual
+ }
+ };
+ }
+
+ private List<Condicao> CriaCondicaoFaturaPendenteVigencia(Filtros filtro, string referencia, string referencia2)
+ {
+ bool count;
+ bool flag;
+ bool count1;
+ bool flag1;
+ bool count2;
+ bool flag2;
+ bool count3;
+ bool flag3;
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = referencia,
+ Valores = filtro.Fim.CriarValor<DateTime>(),
+ Operador = Operador.MenorEIgual
+ },
+ new Condicao()
+ {
+ Campo = referencia2,
+ Valores = filtro.Inicio.CriarValor<DateTime>(),
+ Grupo = 1,
+ Operador = Operador.MaiorEIgual,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = referencia2,
+ Valores = null,
+ Grupo = 1
+ }
+ };
+ List<long> seguradoras = filtro.Seguradoras;
+ if (seguradoras != null)
+ {
+ count = seguradoras.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (count)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idciaseg",
+ Valores = filtro.Seguradoras.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> ramos = filtro.Ramos;
+ if (ramos != null)
+ {
+ flag = ramos.Count > 0;
+ }
+ else
+ {
+ flag = false;
+ }
+ if (flag)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idramo",
+ Valores = filtro.Ramos.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> status = filtro.Status;
+ if (status != null)
+ {
+ count1 = status.Count > 0;
+ }
+ else
+ {
+ count1 = false;
+ }
+ if (count1)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = filtro.Status.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> tipoVendedor = filtro.TipoVendedor;
+ if (tipoVendedor != null)
+ {
+ flag1 = tipoVendedor.Count > 0;
+ }
+ else
+ {
+ flag1 = false;
+ }
+ if (flag1)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "vp.idtipovendedor",
+ Valores = filtro.TipoVendedor.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> vendedores = filtro.Vendedores;
+ if (vendedores != null)
+ {
+ count2 = vendedores.Count > 0;
+ }
+ else
+ {
+ count2 = false;
+ }
+ if (count2)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "vp.idvendedor",
+ Valores = filtro.Vendedores.CriarValor<long>(),
+ Grupo = 5,
+ Operacao = Operacao.Or
+ });
+ }
+ List<long> estipulantes = filtro.Estipulantes;
+ if (estipulantes != null)
+ {
+ flag2 = estipulantes.Count > 0;
+ }
+ else
+ {
+ flag2 = false;
+ }
+ if (flag2)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.idestipulante",
+ Valores = filtro.Estipulantes.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> produtos = filtro.Produtos;
+ if (produtos != null)
+ {
+ count3 = produtos.Count > 0;
+ }
+ else
+ {
+ count3 = false;
+ }
+ if (count3)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "c.idproduto",
+ Valores = filtro.Produtos.CriarValor<long>(),
+ Grupo = 5
+ });
+ }
+ List<long> negocio = filtro.Negocio;
+ if (negocio != null)
+ {
+ flag3 = negocio.Count > 0;
+ }
+ else
+ {
+ flag3 = false;
+ }
+ if (flag3)
+ {
+ condicaos.Add(new Condicao()
+ {
+ Campo = "d.NegocioCorretora",
+ Valores = filtro.Negocio.CriarValor<long>(),
+ Operacao = Operacao.Or,
+ Grupo = 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<long>(),
+ Grupo = 5
+ });
+ }
+ return condicaos;
+ }
+
+ private List<Condicao> CriarCondicaoFatura(Filtros filtro, string referencia)
+ {
+ bool count;
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "d.Excluido",
+ Valores = null,
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.Excluido",
+ Valores = "0".CriarValor<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ },
+ new Condicao()
+ {
+ Campo = "d.tiporecebimento",
+ Valores = 2.CriarValor<int>()
+ }
+ };
+ Condicao condicao = new Condicao()
+ {
+ Campo = referencia
+ };
+ DateTime inicio = filtro.Inicio;
+ condicao.Valores = inicio.ToString("yyyy-MM-dd").CriarValor<string>();
+ condicao.Operador = Operador.MaiorEIgual;
+ condicaos.Add(condicao);
+ Condicao condicao1 = new Condicao()
+ {
+ Campo = referencia
+ };
+ inicio = filtro.Fim;
+ condicao1.Valores = inicio.ToString("yyyy-MM-dd").CriarValor<string>();
+ condicao1.Operador = Operador.MenorEIgual;
+ condicaos.Add(condicao1);
+ condicaos.Add(new Condicao()
+ {
+ Campo = "p.valorr",
+ Valores = 0.CriarValor<int>()
+ });
+ condicaos.Add(new Condicao()
+ {
+ Campo = "p.datarec",
+ Valores = null
+ });
+ List<Condicao> condicaos1 = condicaos;
+ if (filtro.Status.Count > 0)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "situacao",
+ Valores = filtro.Status.CriarValor<long>()
+ });
+ }
+ if (filtro.Negocio.Count > 0)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "negociocorretora",
+ Valores = filtro.Negocio.CriarValor<long>()
+ });
+ }
+ if (filtro.Seguradoras.Count > 0)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "c.idciaseg",
+ Valores = filtro.Seguradoras.CriarValor<long>()
+ });
+ }
+ if (filtro.Ramos.Count > 0)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "c.idramo",
+ Valores = filtro.Ramos.CriarValor<long>()
+ });
+ }
+ if (filtro.Produtos.Count > 0)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "c.idproduto",
+ Valores = filtro.Produtos.CriarValor<long>()
+ });
+ }
+ if (filtro.Vendedores.Count > 0)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "vp.idvendedor",
+ Valores = filtro.Vendedores.CriarValor<long>(),
+ 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<long>()
+ });
+ }
+ if (filtro.IdEmpresa > (long)0)
+ {
+ condicaos1.Add(new Condicao()
+ {
+ Campo = "c.idempresa",
+ Valores = filtro.IdEmpresa.CriarValor<long>()
+ });
+ }
+ List<long> 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<long>()
+ });
+ }
+ return condicaos1;
+ }
+
+ public void Delete(long id)
+ {
+ List<VendedorParcelaDb> list = (
+ from x in this._unitOfWork.Query<VendedorParcelaDb>()
+ where x.Parcela.Id == id
+ select x).ToList<VendedorParcelaDb>();
+ if (list.Any<VendedorParcelaDb>())
+ {
+ this._unitOfWork.Repository<VendedorParcelaDb>().DeleteRange(list);
+ }
+ ParcelaDb parcelaDb = base.FindEntityById(id);
+ if (parcelaDb == null)
+ {
+ return;
+ }
+ base.Delete(parcelaDb);
+ }
+
+ public void DeleteRange(long id)
+ {
+ List<VendedorParcelaDb> list = (
+ from x in this._unitOfWork.Query<VendedorParcelaDb>()
+ where x.Parcela.Documento.Id == id
+ select x).ToList<VendedorParcelaDb>();
+ if (list.Any<VendedorParcelaDb>())
+ {
+ this._unitOfWork.Repository<VendedorParcelaDb>().DeleteRange(list);
+ }
+ List<ParcelaDb> parcelaDbs = (
+ from i in base.All()
+ where i.Documento.Id == id && (int)i.SubTipo == 1
+ select i).ToList<ParcelaDb>();
+ base.DeleteRange(parcelaDbs);
+ }
+
+ public bool ExcluirVinculoParcelaPendenteDocExcluido(Documento doc)
+ {
+ object connection;
+ try
+ {
+ List<Parcela> 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<bool> ExisteTabelasAssinatura()
+ {
+ bool flag;
+ object connection;
+ using (SessionFactoryImpl sessionFactory = this._unitOfWork.Session.SessionFactory as SessionFactoryImpl)
+ {
+ SessionFactoryImpl sessionFactoryImpl = sessionFactory;
+ if (sessionFactoryImpl != null)
+ {
+ connection = sessionFactoryImpl.ConnectionProvider.GetConnection();
+ }
+ else
+ {
+ connection = null;
+ }
+ using (SqlConnection sqlConnection = connection as SqlConnection)
+ {
+ using (SqlCommand sqlCommand = sqlConnection.CreateCommand())
+ {
+ sqlCommand.CommandText = "SELECT OBJECT_ID('ArquivoParaAssinatura') AS existe";
+ flag = await sqlCommand.ExecuteScalarAsync() != DBNull.Value;
+ }
+ }
+ }
+ return flag;
+ }
+
+ public async Task<List<Documento>> FaturaPendente(Filtros filtro)
+ {
+ List<Documento> documentos;
+ NegocioCorretora fieldValue;
+ object connection;
+ bool count;
+ List<Item> itensAtivo;
+ DateTime dateTime;
+ DateTime dateTime1;
+ DateTime dateTime2;
+ DateTime dateTime3;
+ object produto;
+ string str;
+ Vendedor vendedor;
+ Estipulante estipulante;
+ object statu;
+ NegocioCorretora negocioCorretora;
+ Func<Vendedor, bool> func = null;
+ Func<Estipulante, bool> func1 = null;
+ string str1 = "f.vigenciai";
+ string str2 = "d.vigencia1";
+ string str3 = "d.vigencia2";
+ if (filtro.Referencia == "VENCIMENTO")
+ {
+ str1 = "p.vencto";
+ }
+ List<Condicao> condicaos = this.CriaCondicaoFaturaPendenteVigencia(filtro, str2, str3);
+ List<Condicao> condicaos1 = this.CriaCondicaoFaturaPendente(filtro, str1);
+ List<Condicao> condicaos2 = new List<Condicao>();
+ Condicao condicao = new Condicao()
+ {
+ Campo = "d.tiporecebimento",
+ Valores = 2.CriarValor<int>(),
+ Grupo = 2
+ };
+ condicaos2.Add(condicao);
+ List<Condicao> condicaos3 = condicaos2;
+ List<Condicao> condicaos4 = new List<Condicao>();
+ 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<string>(),
+ Grupo = 4
+ };
+ condicaos4.Add(condicao2);
+ List<Condicao> condicaos5 = condicaos4;
+ List<Condicao> condicaos6 = new List<Condicao>();
+ Condicao condicao3 = new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = 1.CriarValor<int>(),
+ Grupo = 3,
+ Operacao = Operacao.Or
+ };
+ condicaos6.Add(condicao3);
+ Condicao condicao4 = new Condicao()
+ {
+ Campo = "d.situacao",
+ Valores = 2.CriarValor<int>(),
+ Grupo = 3
+ };
+ condicaos6.Add(condicao4);
+ List<Condicao> condicaos7 = condicaos6;
+ condicaos.AddRange(condicaos3);
+ condicaos.AddRange(condicaos7);
+ condicaos.AddRange(condicaos5);
+ SqlQueryCondition sqlQueryCondition = condicaos.CreateParameters(0);
+ SqlQueryCondition sqlQueryCondition1 = condicaos1.CreateParameters(0);
+ List<Documento> documentos1 = new List<Documento>();
+ 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<TipoSeguro>("situacao", true, true);
+ if (!await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "negociocorretora"))
+ {
+ fieldValue = sqlDataReader.GetFieldValue<NegocioCorretora>("negociocorretora", true, true);
+ }
+ else
+ {
+ bool flag = tipoSeguro == TipoSeguro.Renovacao;
+ if (flag)
+ {
+ flag = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "idnegocio");
+ }
+ negocioCorretora = (!flag || !(sqlDataReader.GetFieldValue<string>("idnegocio", true, true) == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio);
+ fieldValue = negocioCorretora;
+ }
+ NegocioCorretora negocioCorretora1 = fieldValue;
+ List<long> negocio = filtro.Negocio;
+ if (negocio != null)
+ {
+ count = negocio.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (!count || filtro.Negocio.Any<long>((long n) => (int)n == (int)negocioCorretora1))
+ {
+ long num = sqlDataReader.GetFieldValue<long>("IdControle", true, true);
+ long fieldValue1 = sqlDataReader.GetFieldValue<long>("IdEmpresa", true, true);
+ Documento documento = documentos1.Find((Documento p) => p.Controle.Id == num);
+ if (documento != null)
+ {
+ itensAtivo = documento.ItensAtivo;
+ }
+ else
+ {
+ itensAtivo = null;
+ }
+ List<Item> items = itensAtivo;
+ if (items == null)
+ {
+ items = await this.BuscaItemsPorIdControle(num);
+ }
+ List<Item> items1 = items;
+ DateTime? nullable = sqlDataReader.GetFieldValue<DateTime?>("vigenciafultimafatura", true, true);
+ dateTime = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ DateTime dateTime4 = dateTime;
+ nullable = sqlDataReader.GetFieldValue<DateTime?>("vigenciaIultimafatura", true, true);
+ dateTime1 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ DateTime dateTime5 = dateTime1;
+ nullable = sqlDataReader.GetFieldValue<DateTime?>("vigenciainicial", true, true);
+ dateTime2 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ DateTime dateTime6 = dateTime2;
+ nullable = sqlDataReader.GetFieldValue<DateTime?>("vigenciafinalfatura", true, true);
+ dateTime3 = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ if (dateTime4 < dateTime3)
+ {
+ Documento observableCollection = new Documento()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("iddocumento", true, true)
+ };
+ Controle controle = new Controle()
+ {
+ IdEmpresa = fieldValue1
+ };
+ Cliente cliente = new Cliente()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("idcliente", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("cliente", true, true),
+ IdEmpresa = fieldValue1,
+ Pasta = sqlDataReader.GetFieldValue<string>("pastaCliente", true, true)
+ };
+ bool? nullable1 = sqlDataReader.GetFieldValue<bool?>("MalaDireta", true, true);
+ cliente.MalaDireta = new bool?(nullable1.GetValueOrDefault(true));
+ controle.Cliente = cliente;
+ Seguradora seguradora = new Seguradora()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("idseguradora", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("nomeseguradora", true, true)
+ };
+ controle.Seguradora = seguradora;
+ Ramo ramo = new Ramo()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("idramo", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("nomeramo", true, true)
+ };
+ controle.Ramo = ramo;
+ if (sqlDataReader.FieldIsNull("idproduto"))
+ {
+ produto = null;
+ }
+ else
+ {
+ produto = new Produto();
+ ((DomainBase)produto).Id = sqlDataReader.GetFieldValue<long>("idproduto", true, true);
+ ((Produto)produto).Nome = sqlDataReader.GetFieldValue<string>("nomeproduto", true, true);
+ }
+ controle.Produto = (Produto)produto;
+ observableCollection.Controle = controle;
+ observableCollection.TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura);
+ observableCollection.Apolice = sqlDataReader.GetFieldValue<string>("apolice", true, true);
+ observableCollection.Pasta = sqlDataReader.GetFieldValue<string>("Pasta", true, true);
+ str = (sqlDataReader.GetFieldValue<int>("tipo", true, true) == 0 ? "" : string.Concat("E ", sqlDataReader.GetFieldValue<string>("endosso", true, true)));
+ observableCollection.Endosso = str;
+ observableCollection.Vigencia2 = sqlDataReader.GetFieldValue<DateTime?>("vigenciafinal", true, true);
+ observableCollection.Vigencia1 = dateTime6;
+ observableCollection.Emissao = sqlDataReader.GetFieldValue<DateTime?>("emissao", true, true);
+ observableCollection.Remessa = sqlDataReader.GetFieldValue<DateTime?>("remessa", true, true);
+ if (sqlDataReader.GetFieldValue<object>("idvendedor", true, true) != null)
+ {
+ List<Vendedor> vendedores = Auxiliar.Vendedores;
+ Func<Vendedor, bool> func2 = func;
+ if (func2 == null)
+ {
+ Func<Vendedor, bool> id = (Vendedor p) => p.Id == sqlDataReader.GetFieldValue<long>("idvendedor", true, true);
+ Func<Vendedor, bool> func3 = id;
+ func = id;
+ func2 = func3;
+ }
+ vendedor = vendedores.FirstOrDefault<Vendedor>(func2);
+ }
+ else
+ {
+ vendedor = null;
+ }
+ observableCollection.VendedorPrincipal = vendedor;
+ if (sqlDataReader.GetFieldValue<object>("idestipulante", true, true) != null)
+ {
+ List<Estipulante> estipulantes = Auxiliar.Estipulantes;
+ Func<Estipulante, bool> func4 = func1;
+ if (func4 == null)
+ {
+ Func<Estipulante, bool> id1 = (Estipulante p) => p.Id == sqlDataReader.GetFieldValue<long>("idestipulante", true, true);
+ Func<Estipulante, bool> func5 = id1;
+ func1 = id1;
+ func4 = func5;
+ }
+ estipulante = estipulantes.FirstOrDefault<Estipulante>(func4);
+ }
+ else
+ {
+ estipulante = null;
+ }
+ observableCollection.Estipulante1 = estipulante;
+ observableCollection.NegocioCorretora = new NegocioCorretora?(negocioCorretora1);
+ observableCollection.Situacao = tipoSeguro;
+ List<Parcela> parcelas = new List<Parcela>();
+ Parcela parcela = new Parcela()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("idparcela", true, true),
+ VigenciaFinal = new DateTime?(dateTime4),
+ Fatura = sqlDataReader.GetFieldValue<string>("numfatura", true, true),
+ Vencimento = sqlDataReader.GetFieldValue<DateTime>("Vencimento", true, true),
+ VigenciaIncial = new DateTime?(dateTime5)
+ };
+ parcelas.Add(parcela);
+ observableCollection.Parcelas = new ObservableCollection<Parcela>(parcelas);
+ observableCollection.Tipo = sqlDataReader.GetFieldValue<int>("tipo", true, true);
+ observableCollection.DataControle = sqlDataReader.GetFieldValue<DateTime?>("datacontrole", true, true);
+ if (sqlDataReader.FieldIsNull("idstatus"))
+ {
+ statu = null;
+ }
+ else
+ {
+ statu = new Status();
+ ((DomainBase)statu).Id = sqlDataReader.GetFieldValue<long>("idstatus", true, true);
+ ((Status)statu).Nome = sqlDataReader.GetFieldValue<string>("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<Parcela> FindByDocumentId(List<long> ids)
+ {
+ List<Parcela> 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<long>(",", 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<Parcela>();
+ }
+ }
+ }
+ return parcelas;
+ Label0:
+ List<DataRow> list = dataTable.AsEnumerable().ToList<DataRow>();
+ return list.Select<DataRow, Parcela>((DataRow x) => {
+ Parcela parcela = new Parcela()
+ {
+ Id = x.Field<long>("idparcela"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ Documento = new Documento()
+ {
+ Id = x.Field<long>("iddocumento")
+ },
+ NumeroParcela = int.Parse(x.Field<object>("parcela").ToString())
+ };
+ DateTime? nullable = x.Field<DateTime?>("vencto");
+ parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.Today);
+ parcela.DataRecebimento = x.Field<DateTime?>("datarec");
+ parcela.DataQuitacao = x.Field<DateTime?>("dataquit");
+ parcela.DataControle = x.Field<DateTime?>("datacontrole");
+ parcela.DataCredito = x.Field<DateTime?>("datacred");
+ decimal? nullable1 = x.Field<decimal?>("valor");
+ parcela.Valor = nullable1.GetValueOrDefault();
+ nullable1 = x.Field<decimal?>("valorr");
+ parcela.ValorRealizado = nullable1.GetValueOrDefault();
+ nullable1 = x.Field<decimal?>("comiss");
+ parcela.Comissao = nullable1.GetValueOrDefault();
+ nullable1 = x.Field<decimal?>("vlrcomiss");
+ parcela.ValorComissao = nullable1.GetValueOrDefault();
+ nullable1 = x.Field<decimal?>("vlrcomdesc");
+ parcela.ValorComDesconto = nullable1.GetValueOrDefault();
+ parcela.Observacao = x.Field<string>("obs");
+ parcela.SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field<object>("idsubtipo").ToString());
+ parcela.TipoPagamento = (x.Field<object>("idtipopagto") == null ? TipoPagamento.Nenhum : (TipoPagamento)Enum.Parse(typeof(TipoPagamento), x.Field<object>("idtipopagto").ToString()));
+ nullable1 = x.Field<decimal?>("valorlf");
+ parcela.ValorLiquidoFatura = nullable1.GetValueOrDefault();
+ parcela.Fatura = x.Field<string>("numfatura");
+ parcela.VigenciaIncial = x.Field<DateTime?>("vigenciai");
+ parcela.VigenciaFinal = x.Field<DateTime?>("vigenciaf");
+ parcela.Emissao = x.Field<DateTime?>("emissao");
+ parcela.Extrato = x.Field<string>("extrato");
+ parcela.StatusPagamento = new StatusPagamento?((x.Field<object>("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field<object>("StatusPagamento").ToString())));
+ parcela.IdParcelaPendente = x.Field<long?>("IdParcelaPendente").GetValueOrDefault();
+ nullable1 = x.Field<decimal?>("irr");
+ parcela.Irr = nullable1.GetValueOrDefault();
+ nullable1 = x.Field<decimal?>("iss");
+ parcela.Iss = nullable1.GetValueOrDefault();
+ nullable1 = x.Field<decimal?>("desconto");
+ parcela.Desconto = nullable1.GetValueOrDefault();
+ nullable1 = x.Field<decimal?>("outros");
+ parcela.Outros = nullable1.GetValueOrDefault();
+ return parcela;
+ }).ToList<Parcela>();
+ }
+
+ public List<Parcela> FindByDocumentId(long id)
+ {
+ List<Parcela> 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<Parcela>();
+ }
+ }
+ }
+ return parcelas;
+ }
+
+ public List<Documento> FindByDocumentIds(string ids, List<Documento> 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<Parcela> parcelas = new List<Parcela>();
+ dataTable.AsEnumerable().Where<DataRow>((DataRow y) => y.Field<long>("iddocumento") == x.Id).ToList<DataRow>().ForEach((DataRow y) => {
+ Parcela parcela = new Parcela()
+ {
+ Id = y.Field<long>("idparcela"),
+ IdEmpresa = (!y.Field<long?>("idempresa").HasValue ? (long)0 : y.Field<long>("idempresa")),
+ NumeroParcela = int.Parse(y.Field<object>("parcela").ToString()),
+ Vencimento = (y.Field<object>("vencto") == null ? new DateTime() : y.Field<DateTime>("vencto")),
+ Valor = y.Field<decimal>("valor"),
+ TipoPagamento = (y.Field<object>("idtipopagto") == null ? TipoPagamento.Nenhum : (int)y.Field<long>("idtipopagto")),
+ StatusPagamento = new StatusPagamento?((y.Field<object>("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), y.Field<object>("StatusPagamento").ToString()))),
+ IdParcelaPendente = y.Field<long?>("IdParcelaPendente").GetValueOrDefault()
+ };
+ parcelas.Add(parcela);
+ });
+ x.Parcelas = new ObservableCollection<Parcela>(parcelas);
+ });
+ return documentos;
+ }
+
+ public List<Parcela> FindByDocumento(Documento documento)
+ {
+ List<Parcela> 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<Parcela>();
+ }
+ }
+ }
+ 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, Parcela>(parcelaDb);
+ }
+ FaturaDb faturaDb = this._unitOfWork.Query<FaturaDb>().FirstOrDefault<FaturaDb>((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, Parcela>(parcelaDb);
+ }
+
+ public List<VendedorParcela> FindByPagamento(Filtros filtro, bool reciboPagamento, bool segundaViaReciboPagamento, bool datacontrole)
+ {
+ List<VendedorParcela> vendedorParcelas;
+ string str;
+ object connection;
+ string str1 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join<long>(",",
+ from v in filtro.Status
+ select v), ")"));
+ string str2 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND (NegocioCorretora IN (", string.Join<long>(",",
+ from v in filtro.Negocio
+ select v), ") OR NegocioCorretora IS NULL)"));
+ string str3 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",",
+ from v in filtro.Seguradoras
+ select v), ")"));
+ string str4 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",",
+ from v in filtro.Ramos
+ select v), ")"));
+ string str5 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",",
+ from v in filtro.Produtos
+ select v), ")"));
+ string str6 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",",
+ from v in filtro.Vendedores
+ select v), ")"));
+ string str7 = (filtro.TipoVendedor == null || filtro.TipoVendedor.Count == 0 ? "" : string.Concat(" AND vp.idtipovendedor IN (", string.Join<long>(",",
+ from v in filtro.TipoVendedor
+ select v), ")"));
+ string str8 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",",
+ 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>((FiltroTipoParcela x) => x.Selecionado) ? string.Concat(" AND p.idsubtipo IN (", string.Join<int>(",",
+ 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>((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<DataRow> action = (DataRow x) => x.SetField<object>("NegocioCorretora", (!(x.Field<object>("situacao").ToString() == "2") || x.Field<object>("idnegocio") == null || !(x.Field<object>("idnegocio").ToString() == "1") ? "0" : "1"));
+ (
+ from x in dataTable.AsEnumerable().ToList<DataRow>()
+ where x.Field<object>("NegocioCorretora") == null
+ select x).ForEach<DataRow>(action);
+ if (!str2.IsNullOrEmpty())
+ {
+ Func<DataRow, bool> func = (DataRow p) => filtro.Negocio.Any<long>((long filter) => filter.ToString() == p.Field<object>("NegocioCorretora").ToString());
+ dataTable = dataTable.AsEnumerable().Where<DataRow>(func).CopyToDataTable<DataRow>();
+ }
+ goto Label0;
+ }
+ else
+ {
+ vendedorParcelas = new List<VendedorParcela>();
+ }
+ }
+ }
+ return vendedorParcelas;
+ Label0:
+ List<DataRow> list = dataTable.AsEnumerable().ToList<DataRow>();
+ return list.Select<DataRow, VendedorParcela>((DataRow x) => {
+ decimal? nullable;
+ decimal valueOrDefault;
+ decimal num;
+ VendedorParcela vendedorParcela = new VendedorParcela()
+ {
+ Id = x.Field<long>("idvendedorparcela"),
+ Vendedor = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")),
+ Repasse = new Repasse()
+ {
+ Id = x.Field<long>("idrepasse"),
+ Tipo = new TipoRepasse?((TipoRepasse)Enum.Parse(typeof(TipoRepasse), x.Field<object>("tiporepasse").ToString()))
+ }
+ };
+ Documento documento = new Documento()
+ {
+ Id = x.Field<long>("iddocumento"),
+ Controle = new Controle()
+ {
+ IdEmpresa = x.Field<long>("idempresa"),
+ Cliente = new Cliente()
+ {
+ Id = x.Field<long>("idcliente"),
+ Nome = x.Field<string>("cliente"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
+ },
+ Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null),
+ Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
+ Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Produto>((Produto p) => p.Id == x.Field<long>("idproduto")) : null)
+ },
+ Apolice = x.Field<string>("apolice"),
+ Endosso = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<string>("endosso") : string.Concat("F ", x.Field<string>("fatura"))),
+ Comissao = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<decimal>("comissao") : x.Field<decimal>("comiss"))
+ };
+ if (x.Field<object>("tiporecebimento").ToString() == "1")
+ {
+ nullable = x.Field<decimal?>("liquido");
+ valueOrDefault = nullable.GetValueOrDefault();
+ }
+ else
+ {
+ nullable = x.Field<decimal?>("liquidofatura");
+ valueOrDefault = nullable.GetValueOrDefault();
+ }
+ documento.PremioLiquido = valueOrDefault;
+ if (x.Field<object>("tiporecebimento").ToString() == "1")
+ {
+ nullable = x.Field<decimal?>("total");
+ num = nullable.GetValueOrDefault();
+ }
+ else
+ {
+ nullable = x.Field<decimal?>("valor");
+ num = nullable.GetValueOrDefault();
+ }
+ documento.PremioTotal = num;
+ documento.Vigencia1 = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<DateTime>("vigenciainicial") : (x.Field<object>("vigenciai") != null ? x.Field<DateTime>("vigenciai") : new DateTime()));
+ documento.Vigencia2 = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<DateTime?>("vigenciafinal") : x.Field<DateTime?>("vigenciaf"));
+ documento.Proposta = x.Field<string>("proposta");
+ documento.NegocioCorretora = new NegocioCorretora?((NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field<object>("NegocioCorretora").ToString()));
+ documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
+ documento.TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field<object>("tiporecebimento").ToString()));
+ documento.NumeroParcelas = x.Field<int>("numeroparcelas");
+ documento.DataCriacao = x.Field<DateTime?>("cri_data");
+ documento.DataControle = x.Field<DateTime?>("datacontrole");
+ documento.Emissao = x.Field<DateTime?>("emissao");
+ vendedorParcela.Documento = documento;
+ Parcela parcela = new Parcela()
+ {
+ NumeroParcela = int.Parse(x.Field<object>("parcela").ToString()),
+ Id = x.Field<long>("idparcela"),
+ SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field<object>("idsubtipo").ToString()),
+ IdEmpresa = x.Field<long>("idempresa"),
+ Valor = x.Field<decimal>("valor")
+ };
+ nullable = x.Field<decimal?>("vlrcomdesc");
+ parcela.ValorComDesconto = nullable.GetValueOrDefault();
+ parcela.DataRecebimento = x.Field<DateTime?>("datarec");
+ vendedorParcela.Parcela = parcela;
+ vendedorParcela.ValorRepasse = new decimal?(x.Field<decimal>("repasse"));
+ DateTime? nullable1 = x.Field<DateTime?>("recebimento");
+ vendedorParcela.DataPrePagamento = new DateTime?((nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue));
+ vendedorParcela.PorcentagemRepasse = new decimal?(x.Field<decimal>("percentual"));
+ vendedorParcela.DataPagamento = x.Field<DateTime?>("datapgt");
+ vendedorParcela.RecebidoPorCompleto = x.Field<string>("RecebidoPorCompleto");
+ return vendedorParcela;
+ }).ToList<VendedorParcela>();
+ }
+
+ public List<Parcela> FindByPendente(Filtros filtro, bool pendente, bool somenteAtivos)
+ {
+ List<Parcela> parcelas;
+ object connection;
+ List<long> nums = null;
+ string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join<long>(",",
+ from v in filtro.Status
+ select v), ")"));
+ string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join<long>(",",
+ from v in filtro.Negocio
+ select v), ")"));
+ string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",",
+ from v in filtro.Seguradoras
+ select v), ")"));
+ string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",",
+ from v in filtro.Ramos
+ select v), ")"));
+ string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",",
+ from v in filtro.Produtos
+ select v), ")"));
+ string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",",
+ from v in filtro.Vendedores
+ select v), ")"));
+ string str6 = (filtro.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<long>(",",
+ from v in filtro.TipoVendedor
+ select v), ")"));
+ string str7 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",",
+ from v in filtro.Estipulantes
+ select v), ")"));
+ string str8 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa));
+ 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<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("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<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("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<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("idcontrole"))), ")");
+ sqlCommand.CommandText = string.Concat(str14, " ", str18);
+ using (SqlDataAdapter sqlDataAdapter3 = new SqlDataAdapter())
+ {
+ sqlDataAdapter3.SelectCommand = sqlCommand;
+ sqlDataAdapter3.Fill(dataTable3);
+ }
+ for (List<long> i1 = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("idcliente")).Distinct<long>().ToList<long>(); i1.Count > 0; i1 = nums)
+ {
+ List<long> nums1 = i1.Take<long>(1000).ToList<long>();
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idcliente",
+ Valores = nums1.CriarValor<long>()
+ }
+ };
+ DataTable dataTable5 = sqlCommand.Select(condicaos.CreateParameters(0), str15, "");
+ dataTable4.Merge(dataTable5);
+ nums = (nums1.Count < 1000 ? new List<long>() : i1.Except<long>(nums1).ToList<long>());
+ }
+ goto Label0;
+ }
+ else
+ {
+ parcelas = new List<Parcela>();
+ }
+ }
+ }
+ return parcelas;
+ Label0:
+ return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, Parcela>((DataRow x) => {
+ decimal? nullable3;
+ decimal valueOrDefault;
+ decimal num;
+ Parcela observableCollection = new Parcela()
+ {
+ Id = x.Field<long>("id"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ NumeroParcela = int.Parse(x.Field<object>("parcela").ToString())
+ };
+ DateTime? nullable4 = x.Field<DateTime?>("vencimento");
+ observableCollection.Vencimento = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue);
+ observableCollection.Comissao = x.Field<decimal>("comiss");
+ observableCollection.DataQuitacao = x.Field<DateTime?>("quitacao");
+ observableCollection.DataControle = x.Field<DateTime?>("dataparcelacontrole");
+ observableCollection.Valor = x.Field<decimal>("valor");
+ observableCollection.SubTipo = (SubTipo)Enum.Parse(typeof(SubTipo), x.Field<object>("idsubtipo").ToString());
+ observableCollection.StatusPagamento = new StatusPagamento?((x.Field<object>("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field<object>("StatusPagamento").ToString())));
+ observableCollection.IdParcelaPendente = x.Field<long?>("IdParcelaPendente").GetValueOrDefault();
+ IEnumerable<DataRow> list =
+ from v in dataTable1.AsEnumerable().ToList<DataRow>()
+ where v.Field<long>("id") == x.Field<long>("id")
+ select v;
+ Func<DataRow, VendedorParcela> 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>((Vendedor p) => p.Id == v.Field<long>("idvendedor")),
+ ValorRepasse = new decimal?((v.Field<object>("valorrepasse") == null ? decimal.Zero : v.Field<decimal>("valorrepasse"))),
+ PorcentagemRepasse = new decimal?((v.Field<object>("porcentagemrepasse") == null ? decimal.Zero : v.Field<decimal>("porcentagemrepasse")))
+ };
+ if (v.Field<object>("datapagamento") == null)
+ {
+ nullable = null;
+ nullable1 = nullable;
+ }
+ else
+ {
+ nullable1 = v.Field<DateTime?>("datapagamento");
+ }
+ vendedorParcela.DataPagamento = nullable1;
+ if (v.Field<object>("dataprepagamento") == null)
+ {
+ nullable = null;
+ nullable2 = nullable;
+ }
+ else
+ {
+ nullable2 = v.Field<DateTime?>("dataprepagamento");
+ }
+ vendedorParcela.DataPrePagamento = nullable2;
+ return vendedorParcela;
+ };
+ ParcelaRepository.u003cu003ec.u003cu003e9__26_14 = u003cu003e9_2614;
+ }
+ observableCollection.Vendedores = new ObservableCollection<VendedorParcela>(list.Select<DataRow, VendedorParcela>(u003cu003e9_2614).ToList<VendedorParcela>());
+ Documento documento = new Documento()
+ {
+ Id = x.Field<long>("iddocumento"),
+ FormaPagamento = new FormaPagamento?((x.Field<object>("formapagamento") == null || !(x.Field<object>("formapagamento").ToString() != "") || string.IsNullOrWhiteSpace(x.Field<object>("formapagamento").ToString()) ? FormaPagamento.Nenhum : (FormaPagamento)Enum.Parse(typeof(FormaPagamento), x.Field<object>("formapagamento").ToString())))
+ };
+ Controle controle = new Controle()
+ {
+ Id = x.Field<long>("idcontrole"),
+ IdEmpresa = x.Field<long>("idempresa")
+ };
+ Cliente cliente = new Cliente()
+ {
+ Id = x.Field<long>("idcliente"),
+ Nome = x.Field<string>("cliente"),
+ Documento = x.Field<string>("cgccpf"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ Pasta = x.Field<string>("pastacliente")
+ };
+ EnumerableRowCollection<DataRow> dataRows = dataTable4.AsEnumerable().Where<DataRow>((DataRow t) => t.Field<long>("idcliente") == x.Field<long>("idcliente"));
+ Func<DataRow, ClienteTelefone> u003cu003e9_2627 = ParcelaRepository.u003cu003ec.u003cu003e9__26_27;
+ if (u003cu003e9_2627 == null)
+ {
+ u003cu003e9_2627 = (DataRow t) => new ClienteTelefone()
+ {
+ Id = t.Field<long>("idclitelefone"),
+ Prefixo = t.Field<string>("ddd"),
+ Numero = t.Field<string>("fone")
+ };
+ ParcelaRepository.u003cu003ec.u003cu003e9__26_27 = u003cu003e9_2627;
+ }
+ cliente.Telefones = new ObservableCollection<ClienteTelefone>(dataRows.Select<DataRow, ClienteTelefone>(u003cu003e9_2627));
+ cliente.MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true));
+ controle.Cliente = cliente;
+ controle.Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null);
+ controle.Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null);
+ controle.Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Produto>((Produto p) => p.Id == x.Field<long>("idproduto")) : null);
+ documento.Controle = controle;
+ documento.Pasta = x.Field<string>("Pasta");
+ documento.NumeroParcelas = x.Field<int>("numeroparcelas");
+ documento.AdicionalComiss = x.Field<string>("adinacomiss") == "1";
+ documento.Apolice = x.Field<string>("apolice");
+ documento.Endosso = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<string>("endosso") : string.Concat("F ", x.Field<string>("fatura")));
+ documento.Comissao = x.Field<decimal>("comiss");
+ documento.Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString())));
+ if (x.Field<object>("tiporecebimento").ToString() == "1")
+ {
+ nullable3 = x.Field<decimal?>("liquido");
+ valueOrDefault = nullable3.GetValueOrDefault();
+ }
+ else
+ {
+ nullable3 = x.Field<decimal?>("valorliquidofatura");
+ valueOrDefault = nullable3.GetValueOrDefault();
+ }
+ documento.PremioLiquido = valueOrDefault;
+ if (x.Field<object>("tiporecebimento").ToString() == "1")
+ {
+ nullable3 = x.Field<decimal?>("total");
+ num = nullable3.GetValueOrDefault();
+ }
+ else
+ {
+ nullable3 = x.Field<decimal?>("valor");
+ num = nullable3.GetValueOrDefault();
+ }
+ documento.PremioTotal = num;
+ nullable3 = x.Field<decimal?>("adicional");
+ documento.PremioAdicional = nullable3.GetValueOrDefault();
+ documento.Vigencia1 = (x.Field<object>("tiporecebimento").ToString() == "1" ? (x.Field<object>("vigenciainicial") == null ? DateTime.MinValue : x.Field<DateTime>("vigenciainicial")) : (x.Field<object>("vigenciai") != null ? x.Field<DateTime>("vigenciai") : (x.Field<object>("vigenciainicial") == null ? DateTime.MinValue : x.Field<DateTime>("vigenciainicial"))));
+ documento.Vigencia2 = (x.Field<object>("tiporecebimento").ToString() == "1" ? (x.Field<object>("vigenciafinal") == null ? new DateTime?(DateTime.MinValue) : x.Field<DateTime?>("vigenciafinal")) : new DateTime?((x.Field<object>("vigenciaf") != null ? x.Field<DateTime>("vigenciaf") : (x.Field<object>("vigenciafinal") == null ? DateTime.MinValue : x.Field<DateTime>("vigenciafinal")))));
+ documento.VendedorPrincipal = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")) : null);
+ documento.Proposta = x.Field<string>("proposta");
+ documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
+ documento.TipoRecebimento = new TipoRecebimento?((TipoRecebimento)Enum.Parse(typeof(TipoRecebimento), x.Field<object>("tiporecebimento").ToString()));
+ documento.PropostaAssinada = (x.Field<object>("propassinada") == null ? false : x.Field<string>("propassinada") == "1");
+ documento.Parcelas = new ObservableCollection<Parcela>(dataTable2.AsEnumerable().Where<DataRow>((DataRow p) => p.Field<long>("iddocumento") == x.Field<long>("iddocumento")).Select<DataRow, Parcela>((DataRow p) => {
+ Parcela parcela = new Parcela()
+ {
+ Id = p.Field<long>("id"),
+ NumeroParcela = int.Parse(p.Field<object>("parcela").ToString()),
+ DataRecebimento = p.Field<DateTime?>("recebimento")
+ };
+ DateTime? nullable = p.Field<DateTime?>("vencimento");
+ parcela.Vencimento = (nullable.HasValue ? nullable.GetValueOrDefault() : DateTime.MinValue);
+ parcela.ValorComissao = (x.Field<object>("valorcomissao") == null ? decimal.Zero : p.Field<decimal>("valorcomissao"));
+ parcela.ValorComDesconto = (p.Field<object>("valorcomdesconto") == null || p.Field<decimal>("valorcomdesconto") == decimal.Zero ? (x.Field<object>("valorcomissao") == null ? decimal.Zero : p.Field<decimal>("valorcomissao")) : p.Field<decimal>("valorcomdesconto"));
+ parcela.Comissao = p.Field<decimal>("comiss");
+ parcela.Valor = p.Field<decimal>("valor");
+ parcela.StatusPagamento = new StatusPagamento?((p.Field<object>("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), p.Field<object>("StatusPagamento").ToString())));
+ parcela.IdParcelaPendente = p.Field<long?>("IdParcelaPendente").GetValueOrDefault();
+ return parcela;
+ }).ToList<Parcela>());
+ documento.Tipo = x.Field<int>("tipo");
+ documento.DataControle = x.Field<DateTime?>("datacontrole");
+ documento.Status = (x.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault<Status>((Status p) => p.Id == x.Field<long>("idstatus")) : null);
+ IEnumerable<DataRow> list1 =
+ from i in dataTable3.AsEnumerable().ToList<DataRow>()
+ where i.Field<long>("idcontrole") == x.Field<long>("idcontrole")
+ select i;
+ Func<DataRow, Item> u003cu003e9_2622 = ParcelaRepository.u003cu003ec.u003cu003e9__26_22;
+ if (u003cu003e9_2622 == null)
+ {
+ u003cu003e9_2622 = (DataRow i) => new Item()
+ {
+ Id = i.Field<long>("iditem"),
+ Descricao = i.Field<string>("descricao")
+ };
+ ParcelaRepository.u003cu003ec.u003cu003e9__26_22 = u003cu003e9_2622;
+ }
+ documento.ItensAtivo = new List<Item>(list1.Select<DataRow, Item>(u003cu003e9_2622).ToList<Item>());
+ observableCollection.Documento = documento;
+ return observableCollection;
+ }).ToList<Parcela>();
+ }
+
+ public async Task<List<Parcela>> FindByRecebimento(Filtros filtro)
+ {
+ NegocioCorretora fieldValue;
+ bool flag;
+ bool count;
+ object connection;
+ bool count1;
+ bool flag1;
+ List<Item> 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<Parcela> parcelas = new List<Parcela>();
+ List<Condicao> condicaos = this.CriaCondicaoDocumento(filtro, "CAST(p.DATAREC AS DATE)");
+ List<Condicao> condicaos1 = new List<Condicao>();
+ 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<string>(),
+ Grupo = 1,
+ Operacao = Operacao.Or
+ };
+ condicaos1.Add(condicao1);
+ condicaos.AddRange(condicaos1);
+ List<long> vendedores = filtro.Vendedores;
+ if (vendedores != null)
+ {
+ count = vendedores.Count > 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (count)
+ {
+ if (await this.VerificaVendedorPropriaCorretora(filtro.Vendedores))
+ {
+ List<Condicao> 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>("NegocioCorretora", true, true);
+ }
+ else
+ {
+ flag = sqlDataReader.GetFieldValue<TipoSeguro>("Situacao", true, true) == TipoSeguro.Renovacao;
+ if (flag)
+ {
+ flag = !await SqlDataReaderHelper.FieldIsNullAsync(sqlDataReader, "Negocio");
+ }
+ negocioCorretora = (!flag || !(sqlDataReader.GetFieldValue<string>("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>((long n) => (int)n == (int)negocioCorretora1))
+ {
+ long fieldValue1 = sqlDataReader.GetFieldValue<long>("IdParcela", true, true);
+ Parcela observableCollection = parcelas.Find((Parcela p) => p.Id == fieldValue1);
+ if (observableCollection == null)
+ {
+ long fieldValue2 = sqlDataReader.GetFieldValue<long>("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<Item> items = itensAtivo;
+ if (items == null)
+ {
+ items = await this.BuscaItemsPorIdControle(fieldValue2);
+ }
+ TipoRecebimento tipoRecebimento = sqlDataReader.GetFieldValue<TipoRecebimento>("TipoRecebimento", true, true);
+ decimal fieldValue3 = sqlDataReader.GetFieldValue<decimal>("ValorComissao", true, true);
+ decimal fieldValue4 = sqlDataReader.GetFieldValue<decimal>("ValorComDesconto", true, true);
+ long num4 = sqlDataReader.GetFieldValue<long>("IdEmpresa", true, true);
+ parcela = new Parcela()
+ {
+ Id = fieldValue1,
+ NumeroParcela = sqlDataReader.GetFieldValue<int>("NumeroParcela", true, true),
+ DataRecebimento = sqlDataReader.GetFieldValue<DateTime?>("DataRecebimento", true, true),
+ DataQuitacao = sqlDataReader.GetFieldValue<DateTime?>("DataQuitacao", true, true),
+ DataControle = sqlDataReader.GetFieldValue<DateTime?>("DataControleParcela", true, true),
+ Vencimento = sqlDataReader.GetFieldValue<DateTime>("Vencimento", true, true),
+ ValorComissao = fieldValue3,
+ Irr = sqlDataReader.GetFieldValue<decimal>("Irr", true, true),
+ Iss = sqlDataReader.GetFieldValue<decimal>("Iss", true, true),
+ Desconto = sqlDataReader.GetFieldValue<decimal>("Desconto", true, true),
+ Outros = sqlDataReader.GetFieldValue<decimal>("Outros", true, true)
+ };
+ Parcela parcela2 = parcela;
+ num = (fieldValue4 == decimal.Zero ? fieldValue3 : fieldValue4);
+ parcela2.ValorComDesconto = num;
+ parcela.Comissao = sqlDataReader.GetFieldValue<decimal>("ComissaoParcela", true, true);
+ parcela.ValorRealizado = sqlDataReader.GetFieldValue<decimal>("ValorRealizado", true, true);
+ parcela.SubTipo = sqlDataReader.GetFieldValue<SubTipo>("SubTipo", true, true);
+ parcela.IdEmpresa = num4;
+ Parcela parcela3 = parcela;
+ Documento documento = new Documento()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdDocumento", true, true)
+ };
+ Documento documento1 = documento;
+ Controle controle = new Controle()
+ {
+ Id = fieldValue2,
+ IdEmpresa = num4
+ };
+ Controle controle1 = controle;
+ Cliente cliente = new Cliente()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdCliente", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("NomeCliente", true, true),
+ Pasta = sqlDataReader.GetFieldValue<string>("PastaCliente", true, true)
+ };
+ bool? nullable1 = sqlDataReader.GetFieldValue<bool?>("MalaDireta", true, true);
+ cliente.MalaDireta = new bool?(nullable1.GetValueOrDefault(true));
+ controle1.Cliente = cliente;
+ Controle controle2 = controle;
+ Ramo ramo = new Ramo()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdRamo", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("NomeRamo", true, true)
+ };
+ controle2.Ramo = ramo;
+ Controle controle3 = controle;
+ Seguradora seguradora = new Seguradora()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdCiaSeg", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("NomeCia", true, true),
+ NomeSocial = sqlDataReader.GetFieldValue<string>("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<long>("IdProduto", true, true);
+ ((Produto)produto).Nome = sqlDataReader.GetFieldValue<string>("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<long>("IdEstipulante", true, true);
+ ((Estipulante)estipulante).Nome = sqlDataReader.GetFieldValue<string>("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<long>("IdStatus", true, true);
+ ((Status)statu).Nome = sqlDataReader.GetFieldValue<string>("NomeStatus", true, true);
+ }
+ documento5.Status = (Status)statu;
+ documento.AdicionalComiss = sqlDataReader["AdicionalComiss"].ToString() == "1";
+ documento.Apolice = sqlDataReader.GetFieldValue<string>("Apolice", true, true);
+ Documento documento6 = documento;
+ str = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue<string>("Endosso", true, true) : string.Concat("F ", sqlDataReader.GetFieldValue<string>("Fatura", true, true)));
+ documento6.Endosso = str;
+ Documento documento7 = documento;
+ num1 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue<decimal>("ComissaoDocumento", true, true) : sqlDataReader.GetFieldValue<decimal>("ComissaoParcela", true, true));
+ documento7.Comissao = num1;
+ documento.NegocioCorretora = new NegocioCorretora?(negocioCorretora1);
+ Documento nullable2 = documento;
+ Negocio? nullable3 = sqlDataReader.GetFieldValue<Negocio?>("Negocio", true, true);
+ nullable2.Negocio = new Negocio?(nullable3.GetValueOrDefault(Negocio.Proprio));
+ Documento documento8 = documento;
+ num2 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue<decimal>("PremioLiquido", true, true) : sqlDataReader.GetFieldValue<decimal>("PremioLiquidoFatura", true, true));
+ documento8.PremioLiquido = num2;
+ Documento documento9 = documento;
+ num3 = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue<decimal>("PremioTotal", true, true) : sqlDataReader.GetFieldValue<decimal>("PremioTotalFatura", true, true));
+ documento9.PremioTotal = num3;
+ documento.PremioAdicional = sqlDataReader.GetFieldValue<decimal>("PremioAdicional", true, true);
+ Documento documento10 = documento;
+ if (tipoRecebimento == TipoRecebimento.Parcela)
+ {
+ dateTime = sqlDataReader.GetFieldValue<DateTime>("VigenciaInicial", true, true);
+ }
+ else
+ {
+ DateTime? nullable4 = sqlDataReader.GetFieldValue<DateTime?>("VigenciaInicialFatura", true, true);
+ dateTime = (nullable4.HasValue ? nullable4.GetValueOrDefault() : sqlDataReader.GetFieldValue<DateTime>("Vencimento", true, true));
+ }
+ documento10.Vigencia1 = dateTime;
+ Documento documento11 = documento;
+ nullable = (tipoRecebimento == TipoRecebimento.Parcela ? sqlDataReader.GetFieldValue<DateTime?>("VigenciaFinal", true, true) : sqlDataReader.GetFieldValue<DateTime?>("VigenciaFinalFatura", true, true));
+ documento11.Vigencia2 = nullable;
+ documento.Situacao = sqlDataReader.GetFieldValue<TipoSeguro>("Situacao", true, true);
+ documento.Tipo = sqlDataReader.GetFieldValue<int>("Tipo", true, true);
+ documento.TipoRecebimento = new TipoRecebimento?(tipoRecebimento);
+ documento.DataControle = sqlDataReader.GetFieldValue<DateTime?>("DataControleDocumento", true, true);
+ documento.Pasta = sqlDataReader.GetFieldValue<string>("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<VendedorParcela>();
+ }
+ parcelas.Add(observableCollection);
+ items = null;
+ }
+ List<long> tipoVendedor = filtro.TipoVendedor;
+ if (tipoVendedor != null)
+ {
+ count1 = tipoVendedor.Count > 0;
+ }
+ else
+ {
+ count1 = false;
+ }
+ if (!count1)
+ {
+ List<long> nums = filtro.Vendedores;
+ if (nums != null)
+ {
+ flag1 = nums.Count > 0;
+ }
+ else
+ {
+ flag1 = false;
+ }
+ if (!flag1)
+ {
+ long fieldValue5 = sqlDataReader.GetFieldValue<long>("IdVendedorParcela", true, true);
+ if (fieldValue5 > (long)0)
+ {
+ ObservableCollection<VendedorParcela> vendedores1 = observableCollection.Vendedores;
+ VendedorParcela vendedorParcela = new VendedorParcela()
+ {
+ Id = fieldValue5,
+ ValorRepasse = new decimal?(sqlDataReader.GetFieldValue<decimal>("ValorRepasse", true, true)),
+ PorcentagemRepasse = new decimal?(sqlDataReader.GetFieldValue<decimal>("PorcentagemRepasse", true, true)),
+ DataPagamento = sqlDataReader.GetFieldValue<DateTime?>("DataPagamento", true, true),
+ DataPrePagamento = sqlDataReader.GetFieldValue<DateTime?>("DataPrePagamento", true, true)
+ };
+ TipoVendedor tipoVendedor1 = new TipoVendedor()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdTipoVendedor", true, true)
+ };
+ vendedorParcela.TipoVendedor = tipoVendedor1;
+ Vendedor vendedor = new Vendedor()
+ {
+ Id = sqlDataReader.GetFieldValue<long>("IdVendedor", true, true),
+ Nome = sqlDataReader.GetFieldValue<string>("NomeVendedor", true, true)
+ };
+ vendedorParcela.Vendedor = vendedor;
+ vendedores1.Add(vendedorParcela);
+ }
+ }
+ }
+ }
+ }
+ }
+ sqlDataReader = null;
+ List<long> nums1 = filtro.TipoVendedor;
+ if (nums1 != null)
+ {
+ count2 = nums1.Count > 0;
+ }
+ else
+ {
+ count2 = false;
+ }
+ if (!count2)
+ {
+ List<long> 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<VendedorParcela> vendedorParcelas = await this.BuscaVendedoresPorIdParcela(parcela4.Id, parcela4.IdEmpresa, (long)0);
+ parcela.Vendedores = new ObservableCollection<VendedorParcela>(vendedorParcelas);
+ parcela = null;
+ }
+ Label0:
+ }
+ sqlCommand = null;
+ }
+ sqlConnection = null;
+ }
+ sessionFactory = null;
+ List<Parcela> parcelas1 = parcelas;
+ parcelas = null;
+ condicaos = null;
+ return parcelas1;
+ }
+
+ public List<Parcela> FindByVencimento(Filtros filtro)
+ {
+ List<Parcela> parcelas;
+ object connection;
+ string str = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND situacao IN (", string.Join<long>(",",
+ from v in filtro.Status
+ select v), ")"));
+ string str1 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join<long>(",",
+ from v in filtro.Negocio
+ select v), ")"));
+ string str2 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",",
+ from v in filtro.Seguradoras
+ select v), ")"));
+ string str3 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",",
+ from v in filtro.Ramos
+ select v), ")"));
+ string str4 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",",
+ from v in filtro.Produtos
+ select v), ")"));
+ string str5 = (filtro.Vendedores == null || filtro.Vendedores.Count == 0 ? "" : string.Concat(" AND vp.idvendedor IN (", string.Join<long>(",",
+ from v in filtro.Vendedores
+ select v), ")"));
+ string str6 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",",
+ from v in filtro.Estipulantes
+ select v), ")"));
+ string str7 = (filtro.IdEmpresa == 0 ? "" : string.Format(" AND c.idempresa = {0}", filtro.IdEmpresa));
+ 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<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
+ sqlCommand.CommandText = string.Concat(str9, " ", str10);
+ using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter())
+ {
+ sqlDataAdapter1.SelectCommand = sqlCommand;
+ sqlDataAdapter1.Fill(dataTable1);
+ goto Label0;
+ }
+ }
+ else
+ {
+ parcelas = new List<Parcela>();
+ }
+ }
+ }
+ return parcelas;
+ Label0:
+ return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, Parcela>((DataRow x) => {
+ decimal? nullable3;
+ decimal valueOrDefault;
+ decimal num;
+ Parcela parcela = new Parcela()
+ {
+ Id = x.Field<long>("id"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ NumeroParcela = int.Parse(x.Field<object>("parcela").ToString()),
+ DataRecebimento = x.Field<DateTime?>("recebimento")
+ };
+ DateTime? nullable4 = x.Field<DateTime?>("vencimento");
+ parcela.Vencimento = (nullable4.HasValue ? nullable4.GetValueOrDefault() : DateTime.MinValue);
+ parcela.ValorComDesconto = (x.Field<object>("valorcomdesconto") == null || x.Field<decimal>("valorcomdesconto") == decimal.Zero ? (x.Field<object>("valorcomissao") == null ? decimal.Zero : x.Field<decimal>("valorcomissao")) : x.Field<decimal>("valorcomdesconto"));
+ parcela.Comissao = x.Field<decimal>("comiss");
+ parcela.Valor = x.Field<decimal>("valor");
+ parcela.StatusPagamento = new StatusPagamento?((x.Field<object>("StatusPagamento") == null ? StatusPagamento.All : (StatusPagamento)Enum.Parse(typeof(StatusPagamento), x.Field<object>("StatusPagamento").ToString())));
+ parcela.IdParcelaPendente = x.Field<long?>("IdParcelaPendente").GetValueOrDefault();
+ IEnumerable<DataRow> list =
+ from v in dataTable1.AsEnumerable().ToList<DataRow>()
+ where v.Field<long>("id") == x.Field<long>("id")
+ select v;
+ Func<DataRow, VendedorParcela> 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>((Vendedor p) => p.Id == v.Field<long>("idvendedor")),
+ ValorRepasse = new decimal?((v.Field<object>("valorrepasse") == null ? decimal.Zero : v.Field<decimal>("valorrepasse"))),
+ PorcentagemRepasse = new decimal?((v.Field<object>("porcentagemrepasse") == null ? decimal.Zero : v.Field<decimal>("porcentagemrepasse")))
+ };
+ if (v.Field<object>("datapagamento") == null)
+ {
+ nullable = null;
+ nullable1 = nullable;
+ }
+ else
+ {
+ nullable1 = v.Field<DateTime?>("datapagamento");
+ }
+ vendedorParcela.DataPagamento = nullable1;
+ if (v.Field<object>("dataprepagamento") == null)
+ {
+ nullable = null;
+ nullable2 = nullable;
+ }
+ else
+ {
+ nullable2 = v.Field<DateTime?>("dataprepagamento");
+ }
+ vendedorParcela.DataPrePagamento = nullable2;
+ return vendedorParcela;
+ };
+ ParcelaRepository.u003cu003ec.u003cu003e9__28_10 = u003cu003e9_2810;
+ }
+ parcela.Vendedores = new ObservableCollection<VendedorParcela>(list.Select<DataRow, VendedorParcela>(u003cu003e9_2810).ToList<VendedorParcela>());
+ Documento documento = new Documento()
+ {
+ Controle = new Controle()
+ {
+ IdEmpresa = x.Field<long>("idempresa"),
+ Cliente = new Cliente()
+ {
+ Id = x.Field<long>("idcliente"),
+ Nome = x.Field<string>("cliente"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
+ },
+ Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null),
+ Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
+ Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Produto>((Produto p) => p.Id == x.Field<long>("idproduto")) : null)
+ },
+ AdicionalComiss = x.Field<string>("adinacomiss") == "1",
+ Apolice = x.Field<string>("apolice"),
+ Endosso = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<string>("endosso") : string.Concat("F ", x.Field<string>("fatura"))),
+ Comissao = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<decimal>("comissao") : x.Field<decimal>("comiss")),
+ Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString())))
+ };
+ if (x.Field<object>("tiporecebimento").ToString() == "1")
+ {
+ nullable3 = x.Field<decimal?>("liquido");
+ valueOrDefault = nullable3.GetValueOrDefault();
+ }
+ else
+ {
+ nullable3 = x.Field<decimal?>("valorliquidofatura");
+ valueOrDefault = nullable3.GetValueOrDefault();
+ }
+ documento.PremioLiquido = valueOrDefault;
+ if (x.Field<object>("tiporecebimento").ToString() == "1")
+ {
+ nullable3 = x.Field<decimal?>("total");
+ num = nullable3.GetValueOrDefault();
+ }
+ else
+ {
+ nullable3 = x.Field<decimal?>("valor");
+ num = nullable3.GetValueOrDefault();
+ }
+ documento.PremioTotal = num;
+ nullable3 = x.Field<decimal?>("adicional");
+ documento.PremioAdicional = nullable3.GetValueOrDefault();
+ documento.Vigencia1 = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<DateTime>("vigenciainicial") : x.Field<DateTime>("vigenciai"));
+ documento.Vigencia2 = (x.Field<object>("tiporecebimento").ToString() == "1" ? x.Field<DateTime?>("vigenciafinal") : x.Field<DateTime?>("vigenciaf"));
+ documento.VendedorPrincipal = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")) : null);
+ documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
+ documento.Tipo = x.Field<int>("tipo");
+ parcela.Documento = documento;
+ return parcela;
+ }).ToList<Parcela>();
+ }
+
+ public List<Documento> FindByVigencia(Filtros filtro)
+ {
+ return new List<Documento>();
+ }
+
+ public List<long> FindDocumentId(List<long> ids)
+ {
+ List<long> 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<long>(",", 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, long>((DataRow x) => x.Field<long>("iddocumento")).ToList<long>();
+ }
+ else
+ {
+ nums = new List<long>();
+ }
+ }
+ }
+ return nums;
+ }
+
+ public List<Documento> FindNumFatura(string numero)
+ {
+ List<Documento> 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<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
+ sqlCommand.CommandText = string.Concat(str1, " ", str2);
+ using (SqlDataAdapter sqlDataAdapter1 = new SqlDataAdapter())
+ {
+ sqlDataAdapter1.SelectCommand = sqlCommand;
+ sqlDataAdapter1.Fill(dataTable1);
+ goto Label0;
+ }
+ }
+ else
+ {
+ documentos = new List<Documento>();
+ }
+ }
+ }
+ return documentos;
+ Label0:
+ return dataTable.AsEnumerable().ToList<DataRow>().Select<DataRow, Documento>((DataRow x) => {
+ Func<DataRow, bool> func2 = null;
+ Documento documento = new Documento()
+ {
+ Id = x.Field<long>("iddocumento"),
+ Controle = new Controle()
+ {
+ Id = x.Field<long>("idcontrole"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ Cliente = new Cliente()
+ {
+ Nome = x.Field<string>("cliente"),
+ Id = x.Field<long>("idcliente"),
+ IdEmpresa = x.Field<long>("idempresa"),
+ MalaDireta = new bool?(x.Field<bool?>("MalaDireta").GetValueOrDefault(true))
+ },
+ Seguradora = (x.Field<object>("idseguradora") != null ? Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora p) => p.Id == x.Field<long>("idseguradora")) : null),
+ Ramo = (x.Field<object>("idramo") != null ? Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo p) => p.Id == x.Field<long>("idramo")) : null),
+ Produto = (x.Field<object>("idproduto") != null ? Auxiliar.Produtos.FirstOrDefault<Produto>((Produto p) => p.Id == x.Field<long>("idproduto")) : null)
+ },
+ Pasta = x.Field<string>("Pasta"),
+ TipoRecebimento = new TipoRecebimento?(TipoRecebimento.Fatura),
+ AdicionalComiss = false,
+ Apolice = x.Field<string>("apolice"),
+ Endosso = x.Field<string>("fatura"),
+ Comissao = x.Field<decimal>("comissao"),
+ NegocioCorretora = new NegocioCorretora?((x.Field<object>("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString()) != TipoSeguro.Renovacao || x.Field<object>("idnegocio") == null || x.Field<long>("idnegocio") != (long)1 ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field<object>("negociocorretora").ToString()))),
+ Negocio = new Negocio?((x.Field<object>("idnegocio") == null ? Negocio.Proprio : (Negocio)Enum.Parse(typeof(Negocio), x.Field<object>("idnegocio").ToString())))
+ };
+ decimal? nullable = x.Field<decimal?>("liquido");
+ documento.PremioLiquido = nullable.GetValueOrDefault();
+ nullable = x.Field<decimal?>("total");
+ documento.PremioTotal = nullable.GetValueOrDefault();
+ DateTime? nullable1 = x.Field<DateTime?>("vigenciainicial");
+ documento.Vigencia1 = (nullable1.HasValue ? nullable1.GetValueOrDefault() : DateTime.MinValue);
+ documento.Vigencia2 = x.Field<DateTime?>("vigenciafinal");
+ documento.Emissao = x.Field<DateTime?>("emissao");
+ documento.VendedorPrincipal = (x.Field<object>("idvendedor") != null ? Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor p) => p.Id == x.Field<long>("idvendedor")) : null);
+ documento.Estipulante1 = (x.Field<object>("idestipulante") != null ? Auxiliar.Estipulantes.FirstOrDefault<Estipulante>((Estipulante p) => p.Id == x.Field<long>("idestipulante")) : null);
+ documento.Situacao = (TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString());
+ documento.Vendedores = Auxiliar.Vendedores.Where<Vendedor>((Vendedor v) => {
+ List<DataRow> list = dataTable1.AsEnumerable().ToList<DataRow>();
+ Func<DataRow, bool> u003cu003e9_9 = func2;
+ if (u003cu003e9_9 == null)
+ {
+ Func<DataRow, bool> func = (DataRow d) => d.Field<long>("id") == x.Field<long>("id");
+ Func<DataRow, bool> func1 = func;
+ func2 = func;
+ u003cu003e9_9 = func1;
+ }
+ IEnumerable<DataRow> dataRows = list.Where<DataRow>(u003cu003e9_9);
+ Func<DataRow, long> u003cu003e9_2210 = ParcelaRepository.u003cu003ec.u003cu003e9__22_10;
+ if (u003cu003e9_2210 == null)
+ {
+ u003cu003e9_2210 = (DataRow d) => d.Field<long>("idvendedor");
+ ParcelaRepository.u003cu003ec.u003cu003e9__22_10 = u003cu003e9_2210;
+ }
+ return dataRows.Select<DataRow, long>(u003cu003e9_2210).ToList<long>().Contains(v.Id);
+ }).ToList<Vendedor>();
+ documento.Tipo = x.Field<int>("tipo");
+ documento.DataControle = x.Field<DateTime?>("dataparcelacontrole");
+ documento.Status = (x.Field<object>("idstatus") != null ? Auxiliar.StatusApolice.FirstOrDefault<Status>((Status p) => p.Id == x.Field<long>("idstatus")) : null);
+ documento.DataCriacao = x.Field<DateTime?>("cri_data");
+ documento.Banco = new Banco()
+ {
+ Nome = x.Field<string>("banco")
+ };
+ documento.Agencia = x.Field<string>("agencia");
+ documento.Conta = x.Field<string>("conta");
+ documento.PropostaAssinada = (x.Field<object>("propassinada") == null ? false : x.Field<string>("propassinada") == "1");
+ return documento;
+ }).ToList<Documento>();
+ }
+
+ 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, ParcelaDb>(parcela);
+ if (parcelaDb.IdEmpresa == 0)
+ {
+ parcelaDb.IdEmpresa = (long)1;
+ }
+ base.Merge(parcelaDb);
+ if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela)
+ {
+ return ApplicationMapper.Mapper.Map<ParcelaDb, Parcela>(parcelaDb);
+ }
+ FaturaDb fatura = this._unitOfWork.Query<FaturaDb>().FirstOrDefault<FaturaDb>((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<FaturaDb>().Merge(fatura);
+ }
+ else
+ {
+ this._unitOfWork.Repository<FaturaDb>().SaveOrUpdate(fatura);
+ }
+ return ApplicationMapper.Mapper.Map<ParcelaDb, Parcela>(parcelaDb);
+ }
+
+ public List<PrevisaoPagamento> PrevisaoPagamentoComissao(Filtros filtro)
+ {
+ object connection;
+ string str2 = (filtro.Status == null || filtro.Status.Count == 0 ? "" : string.Concat(" AND d.situacao IN (", string.Join<long>(",",
+ from v in filtro.Status
+ select v), ")"));
+ string str3 = (filtro.Negocio == null || filtro.Negocio.Count == 0 ? "" : string.Concat(" AND NegocioCorretora IN (", string.Join<long>(",",
+ from v in filtro.Negocio
+ select v), ")"));
+ string str4 = (filtro.Seguradoras == null || filtro.Seguradoras.Count == 0 ? "" : string.Concat(" AND c.idciaseg IN (", string.Join<long>(",",
+ from v in filtro.Seguradoras
+ select v), ")"));
+ string str5 = (filtro.Ramos == null || filtro.Ramos.Count == 0 ? "" : string.Concat(" AND c.idramo IN (", string.Join<long>(",",
+ from v in filtro.Ramos
+ select v), ")"));
+ string str6 = (filtro.Produtos == null || filtro.Produtos.Count == 0 ? "" : string.Concat(" AND c.idproduto IN (", string.Join<long>(",",
+ 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<long>(",",
+ 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<long>(",",
+ from v in filtro.TipoVendedor
+ select v), ")"));
+ string str9 = (filtro.Estipulantes == null || filtro.Estipulantes.Count == 0 ? "" : string.Concat(" AND d.idestipulante IN (", string.Join<long>(",",
+ 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<DataRow>().Select<DataRow, PrevisaoPagamento>((DataRow x) => {
+ string nome;
+ string str;
+ string nome1;
+ string str1;
+ PrevisaoPagamento previsaoPagamento = new PrevisaoPagamento()
+ {
+ Nome = x.Campo<string>("cliente"),
+ Apolice = (x.IsNull("tiporecebimento") ? "" : (x.Campo<string>("tiporecebimento") == "1" ? x.Campo<string>("contrato") : x.Campo<string>("NUMFATURA"))),
+ Endosso = (x.Campo<string>("tiporecebimento") == "1" ? x.Campo<string>("aditamento") : ""),
+ Status = x.Campo<TipoSeguro>("situacao").GetDescription<TipoSeguro>(),
+ VigenciaInicial = (x.Campo<string>("tiporecebimento") == "1" ? x.Campo<DateTime>("VIGENCIA1") : x.Campo<DateTime>("VIGENCIAI")),
+ TipoDocumento = (x.IsNull("tiporecebimento") ? "" : (x.Campo<string>("tiporecebimento") == "2" ? "FATURA" : (x.Campo<string>("tipo") == "0" ? "APÓLICE" : "ENDOSSO")))
+ };
+ Seguradora seguradora = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Campo<long>("idciaseg"));
+ if (seguradora != null)
+ {
+ nome = seguradora.Nome;
+ }
+ else
+ {
+ nome = null;
+ }
+ previsaoPagamento.NomeSeguradora = nome;
+ Ramo ramo = Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Campo<long>("idramo"));
+ if (ramo != null)
+ {
+ str = ramo.Nome;
+ }
+ else
+ {
+ str = null;
+ }
+ previsaoPagamento.NomeRamo = str;
+ previsaoPagamento.PremioLiquido = (x.Campo<string>("tiporecebimento") == "1" ? x.Campo<decimal>("pr_liq") : x.Campo<decimal>("valorlf"));
+ previsaoPagamento.Parcela = (x.Campo<long>("idsubtipo") > (long)1 ? "ESPECIAL" : (x.Campo<string>("tiporecebimento") == "1" ? string.Concat(x.Campo<string>("parcela").PadLeft(2, '0'), " DE ", x.Campo<string>("n_parc")) : x.Campo<string>("parcela").PadLeft(2, '0')));
+ previsaoPagamento.VencimentoParcela = x.Campo<DateTime>("vencto");
+ previsaoPagamento.RepasseLiquido = x.Campo<decimal>("vlrliquido") * (decimal.One - (x.Campo<decimal>("desconto") > decimal.One ? x.Campo<decimal>("desconto") * new decimal(1, 0, 0, false, 2) : x.Campo<decimal>("desconto")));
+ previsaoPagamento.Repasse = x.Campo<decimal>("vlrliquido");
+ previsaoPagamento.Vendedor = Auxiliar.Vendedores.Find((Vendedor p) => p.Id == x.Campo<long>("idvendedor"));
+ Seguradora seguradora1 = Auxiliar.Seguradoras.Find((Seguradora p) => p.Id == x.Campo<long>("idciaseg"));
+ if (seguradora1 != null)
+ {
+ nome1 = seguradora1.Nome;
+ }
+ else
+ {
+ nome1 = null;
+ }
+ previsaoPagamento.Seguradora = nome1;
+ Ramo ramo1 = Auxiliar.Ramos.Find((Ramo p) => p.Id == x.Campo<long>("idramo"));
+ if (ramo1 != null)
+ {
+ str1 = ramo1.Nome;
+ }
+ else
+ {
+ str1 = null;
+ }
+ previsaoPagamento.Ramo = str1;
+ return previsaoPagamento;
+ }).ToList<PrevisaoPagamento>();
+ }
+
+ public Parcela SaveOrUpdate(Parcela parcela)
+ {
+ ParcelaDb parcelaDb = ApplicationMapper.Mapper.Map<Parcela, ParcelaDb>(parcela);
+ if (parcelaDb.IdEmpresa == 0)
+ {
+ parcelaDb.IdEmpresa = (long)1;
+ }
+ this.SaveOrUpdate(parcelaDb);
+ if (parcelaDb.Documento.TipoRecebimento.GetValueOrDefault() == TipoRecebimento.Parcela)
+ {
+ return ApplicationMapper.Mapper.Map<ParcelaDb, Parcela>(parcelaDb);
+ }
+ FaturaDb faturaDb = new FaturaDb()
+ {
+ Parcela = parcelaDb,
+ Fatura = parcelaDb.Fatura,
+ VigenciaInicial = parcelaDb.VigenciaIncial,
+ VigenciaFinal = parcelaDb.VigenciaFinal,
+ Emissao = parcelaDb.Emissao
+ };
+ this._unitOfWork.Repository<FaturaDb>().SaveOrUpdate(faturaDb);
+ return ApplicationMapper.Mapper.Map<ParcelaDb, Parcela>(parcelaDb);
+ }
+
+ public int[] SincronizarPendencia(DateTime date, List<long> ids = null)
+ {
+ //
+ // Current member / type: System.Int32[] Gestor.Infrastructure.Repository.Logic.ParcelaRepository::SincronizarPendencia(System.DateTime,System.Collections.Generic.List`1<System.Int64>)
+ // 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<System.Int64>)
+ //
+ // 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 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<DetalheExtrato> detalhes, bool desabilitaAproximação)
+ {
+ //
+ // Current member / type: System.Boolean Gestor.Infrastructure.Repository.Logic.ParcelaRepository::Update(System.Collections.Generic.List`1<Gestor.Model.Domain.Seguros.DetalheExtrato>,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<Gestor.Model.Domain.Seguros.DetalheExtrato>,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 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<Parcela> UpdateRange(List<Parcela> parcelas)
+ {
+ List<ParcelaDb> parcelaDbs = ApplicationMapper.Mapper.Map<List<Parcela>, List<ParcelaDb>>(parcelas);
+ parcelaDbs.ForEach((ParcelaDb x) => {
+ if (x.IdEmpresa == 0)
+ {
+ x.IdEmpresa = (long)1;
+ }
+ });
+ ParcelaRepository parcelaRepository = this;
+ parcelaDbs.ForEach(new Action<ParcelaDb>(parcelaRepository.Merge));
+ return ApplicationMapper.Mapper.Map<List<ParcelaDb>, List<Parcela>>(parcelaDbs);
+ }
+
+ private async Task<bool> VerificaVendedorPropriaCorretora(List<long> vendedores)
+ {
+ bool valueOrDefault;
+ object connection;
+ List<Condicao> condicaos = new List<Condicao>();
+ Condicao condicao = new Condicao()
+ {
+ Campo = "IdVendedor",
+ Valores = vendedores.CriarValor<long>(),
+ 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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs
new file mode 100644
index 0000000..f3b92f0
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PatrimonialRepository.cs
@@ -0,0 +1,251 @@
+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<PatrimonialDb>, IPatrimonialRepository, IGenericRepository<PatrimonialDb>
+ {
+ 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<long> ids)
+ {
+ List<PatrimonialDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Item.Id)
+ select x).ToList<PatrimonialDb>();
+ base.DeleteRange(list);
+ }
+
+ public Patrimonial Find(long id)
+ {
+ PatrimonialDb patrimonialDb = base.All().FirstOrDefault<PatrimonialDb>((PatrimonialDb x) => x.Item.Id == id) ?? new PatrimonialDb();
+ return ApplicationMapper.Mapper.Map<PatrimonialDb, Patrimonial>(patrimonialDb);
+ }
+
+ public Patrimonial FindById(long id)
+ {
+ PatrimonialDb patrimonialDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<PatrimonialDb, Patrimonial>(patrimonialDb);
+ }
+
+ public List<PesquisaAvancada> FindImobiliaria(string imobiliaria, FiltroStatusDocumento status, List<VendedorUsuario> vendedorVinculado)
+ {
+ List<PesquisaAvancada> 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<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("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<long>(",", dataTable1.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
+ using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter())
+ {
+ sqlDataAdapter2.SelectCommand = sqlCommand;
+ sqlDataAdapter2.Fill(dataTable2);
+ }
+ string str1 = string.Concat(" AND d.idcontrole IN (", string.Join<long>(",", (
+ from x in dataTable2.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("idcontrole")).ToList<long>()), ")");
+ 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<long> list = null;
+ if (vendedorVinculado != null && vendedorVinculado.Count > 0)
+ {
+ list = dataTable3.AsEnumerable().Where<DataRow>((DataRow x) => {
+ List<VendedorUsuario> vendedorUsuarios = vendedorVinculado;
+ Func<VendedorUsuario, long> 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<VendedorUsuario, long>(u003cu003e9_85).Contains<long>(x.Field<long>("idvendedor"));
+ }).Select<DataRow, long>((DataRow x) => x.Field<long>("idcontrole")).ToList<long>();
+ }
+ if (list != null && list.Count == 0)
+ {
+ return new List<PesquisaAvancada>();
+ }
+ return Auxiliar.PesquisaAvancada(status, dataTable2, dataTable1, list);
+ }
+ }
+ else
+ {
+ pesquisaAvancadas = new List<PesquisaAvancada>();
+ }
+ }
+ }
+ return pesquisaAvancadas;
+ }
+
+ public List<PesquisaAvancada> Findlocatario(string imobiliaria, FiltroStatusDocumento status, List<VendedorUsuario> vendedorVinculado)
+ {
+ List<PesquisaAvancada> 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<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("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<long>(",", dataTable1.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("id"))), ")");
+ using (SqlDataAdapter sqlDataAdapter2 = new SqlDataAdapter())
+ {
+ sqlDataAdapter2.SelectCommand = sqlCommand;
+ sqlDataAdapter2.Fill(dataTable2);
+ }
+ string str1 = string.Concat(" AND d.idcontrole IN (", string.Join<long>(",", (
+ from x in dataTable2.AsEnumerable().ToList<DataRow>()
+ select x.Field<long>("idcontrole")).ToList<long>()), ")");
+ 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<PesquisaAvancada>();
+ }
+ }
+ }
+ return pesquisaAvancadas;
+ Label0:
+ List<long> list = null;
+ if (vendedorVinculado != null && vendedorVinculado.Count > 0)
+ {
+ list = dataTable3.AsEnumerable().Where<DataRow>((DataRow x) => {
+ List<VendedorUsuario> vendedorUsuarios = vendedorVinculado;
+ Func<VendedorUsuario, long> 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<VendedorUsuario, long>(u003cu003e9_97).Contains<long>(x.Field<long>("idvendedor"));
+ }).Select<DataRow, long>((DataRow x) => x.Field<long>("idcontrole")).ToList<long>();
+ }
+ if (vendedorVinculado != null)
+ {
+ List<VendedorUsuario> vendedorUsuarios1 = vendedorVinculado;
+ if (vendedorUsuarios1 != null)
+ {
+ count = vendedorUsuarios1.Count == 0;
+ }
+ else
+ {
+ count = false;
+ }
+ if (count)
+ {
+ list = dataTable2.AsEnumerable().Where<DataRow>((DataRow x) => x.Field<long?>("idcontrole").HasValue).Select<DataRow, long>((DataRow x) => x.Field<long>("idcontrole")).ToList<long>();
+ }
+ }
+ return Auxiliar.PesquisaAvancada(status, dataTable2, dataTable1, list);
+ }
+
+ public Patrimonial Merge(Patrimonial patrimonial)
+ {
+ PatrimonialDb patrimonialDb = ApplicationMapper.Mapper.Map<Patrimonial, PatrimonialDb>(patrimonial);
+ base.Merge(patrimonialDb);
+ return ApplicationMapper.Mapper.Map<PatrimonialDb, Patrimonial>(patrimonialDb);
+ }
+
+ public Patrimonial SaveOrUpdate(Patrimonial patrimonial)
+ {
+ PatrimonialDb patrimonialDb = ApplicationMapper.Mapper.Map<Patrimonial, PatrimonialDb>(patrimonial);
+ this.SaveOrUpdate(patrimonialDb);
+ return ApplicationMapper.Mapper.Map<PatrimonialDb, Patrimonial>(patrimonialDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs
new file mode 100644
index 0000000..b32c539
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilEmpresaRepository.cs
@@ -0,0 +1,64 @@
+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<PerfilEmpresaDb>, IPerfilEmpresaRepository, IGenericRepository<PerfilEmpresaDb>
+ {
+ 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>((PerfilEmpresaDb x) => x.Id == id);
+ return ApplicationMapper.Mapper.Map<PerfilEmpresaDb, PerfilEmpresa>(perfilEmpresaDb);
+ }
+
+ public PerfilEmpresa FindByControleId(long id)
+ {
+ PerfilEmpresaDb perfilEmpresaDb = (
+ from x in base.All()
+ where x.Controle.Id == id
+ select x).FirstOrDefault<PerfilEmpresaDb>();
+ return ApplicationMapper.Mapper.Map<PerfilEmpresaDb, PerfilEmpresa>(perfilEmpresaDb);
+ }
+
+ public PerfilEmpresa Merge(PerfilEmpresa perfil)
+ {
+ PerfilEmpresaDb perfilEmpresaDb = ApplicationMapper.Mapper.Map<PerfilEmpresa, PerfilEmpresaDb>(perfil);
+ base.Merge(perfilEmpresaDb);
+ return ApplicationMapper.Mapper.Map<PerfilEmpresaDb, PerfilEmpresa>(perfilEmpresaDb);
+ }
+
+ public PerfilEmpresa SaveOrUpdate(PerfilEmpresa perfilEmpresa)
+ {
+ PerfilEmpresaDb perfilEmpresaDb = ApplicationMapper.Mapper.Map<PerfilEmpresa, PerfilEmpresaDb>(perfilEmpresa);
+ this.SaveOrUpdate(perfilEmpresaDb);
+ return ApplicationMapper.Mapper.Map<PerfilEmpresaDb, PerfilEmpresa>(perfilEmpresaDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs
new file mode 100644
index 0000000..67375a5
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PerfilRepository.cs
@@ -0,0 +1,191 @@
+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<PerfilDb>, IPerfilRepository, IGenericRepository<PerfilDb>
+ {
+ 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>((PerfilDb x) => x.Id == id);
+ return ApplicationMapper.Mapper.Map<PerfilDb, Perfil>(perfilDb);
+ }
+
+ public List<Perfil> FindByControleId(long id)
+ {
+ List<PerfilDb> list = (
+ from x in base.All()
+ where x.Controle.Id == id
+ select x).ToList<PerfilDb>();
+ return ApplicationMapper.Mapper.Map<List<PerfilDb>, List<Perfil>>(list);
+ }
+
+ public List<Perfil> 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<Perfil>();
+ }
+ return dataTable.AsEnumerable().Select<DataRow, Perfil>((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<Perfil>();
+ }
+
+ public Perfil Merge(Perfil perfil)
+ {
+ PerfilDb perfilDb = ApplicationMapper.Mapper.Map<Perfil, PerfilDb>(perfil);
+ base.Merge(perfilDb);
+ return ApplicationMapper.Mapper.Map<PerfilDb, Perfil>(perfilDb);
+ }
+
+ public Perfil SaveOrUpdate(Perfil perfil)
+ {
+ PerfilDb perfilDb = ApplicationMapper.Mapper.Map<Perfil, PerfilDb>(perfil);
+ this.SaveOrUpdate(perfilDb);
+ return ApplicationMapper.Mapper.Map<PerfilDb, Perfil>(perfilDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs
new file mode 100644
index 0000000..50201a9
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoArquivoDigitalRepository.cs
@@ -0,0 +1,54 @@
+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<PermissaoArquivoDigitalDb>, 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>((PermissaoArquivoDigitalDb x) => x.Usuario.Id == id && (int)x.Tela == (int)tela);
+ return ApplicationMapper.Mapper.Map<PermissaoArquivoDigitalDb, PermissaoArquivoDigital>(permissaoArquivoDigitalDb);
+ }
+
+ public List<PermissaoArquivoDigital> FindByUsuario(long id)
+ {
+ List<PermissaoArquivoDigitalDb> list = this._unitOfWork.Session.CreateQuery(string.Format("from PermissaoArquivoDigitalDb WHERE IdUsuario = {0}", id)).List<PermissaoArquivoDigitalDb>().ToList<PermissaoArquivoDigitalDb>();
+ return ApplicationMapper.Mapper.Map<List<PermissaoArquivoDigitalDb>, List<PermissaoArquivoDigital>>(list);
+ }
+
+ public PermissaoArquivoDigital Merge(PermissaoArquivoDigital permissao)
+ {
+ PermissaoArquivoDigitalDb permissaoArquivoDigitalDb = ApplicationMapper.Mapper.Map<PermissaoArquivoDigital, PermissaoArquivoDigitalDb>(permissao);
+ base.Merge(permissaoArquivoDigitalDb);
+ return ApplicationMapper.Mapper.Map<PermissaoArquivoDigitalDb, PermissaoArquivoDigital>(permissaoArquivoDigitalDb);
+ }
+
+ public PermissaoArquivoDigital SaveOrUpdate(PermissaoArquivoDigital permissao)
+ {
+ PermissaoArquivoDigitalDb permissaoArquivoDigitalDb = ApplicationMapper.Mapper.Map<PermissaoArquivoDigital, PermissaoArquivoDigitalDb>(permissao);
+ this.SaveOrUpdate(permissaoArquivoDigitalDb);
+ return ApplicationMapper.Mapper.Map<PermissaoArquivoDigitalDb, PermissaoArquivoDigital>(permissaoArquivoDigitalDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs
new file mode 100644
index 0000000..e0e226c
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PermissaoUsuarioRepository.cs
@@ -0,0 +1,84 @@
+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<PermissaoUsuarioDb>, 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<PermissaoUsuario>();
+ }
+
+ public List<PermissaoUsuario> FindByUsuario(long id)
+ {
+ return this.Select(string.Format(" AND IdUsuario = {0}", id));
+ }
+
+ public PermissaoUsuario Merge(PermissaoUsuario permissao)
+ {
+ PermissaoUsuarioDb permissaoUsuarioDb = ApplicationMapper.Mapper.Map<PermissaoUsuario, PermissaoUsuarioDb>(permissao);
+ base.Merge(permissaoUsuarioDb);
+ return ApplicationMapper.Mapper.Map<PermissaoUsuarioDb, PermissaoUsuario>(permissaoUsuarioDb);
+ }
+
+ public PermissaoUsuario SaveOrUpdate(PermissaoUsuario permissao)
+ {
+ PermissaoUsuarioDb permissaoUsuarioDb = ApplicationMapper.Mapper.Map<PermissaoUsuario, PermissaoUsuarioDb>(permissao);
+ this.SaveOrUpdate(permissaoUsuarioDb);
+ return ApplicationMapper.Mapper.Map<PermissaoUsuarioDb, PermissaoUsuario>(permissaoUsuarioDb);
+ }
+
+ private List<PermissaoUsuario> 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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs
new file mode 100644
index 0000000..47044d1
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanoRepository.cs
@@ -0,0 +1,93 @@
+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<PlanoDb>, IPlanoRepository, IGenericRepository<PlanoDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public PlanoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Plano> Find(string filter)
+ {
+ PlanoRepository.u003cu003ec__DisplayClass2_0 variable = null;
+ IQueryable<PlanoDb> planoDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(PlanoDb), "x");
+ IQueryable<PlanoDb> planoDbs1 = planoDbs.Where<PlanoDb>(Expression.Lambda<Func<PlanoDb, bool>>(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<Expression>()), (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<PlanoDb, Plano>(Expression.Lambda<Func<PlanoDb, Plano>>(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<Plano>();
+ }
+
+ public List<Plano> 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<DataRow>()
+ select new Plano()
+ {
+ Id = a.Field<long>("id"),
+ Descricao = a.Field<string>("nome"),
+ Ativo = (a.Field<object>("ativo") == null ? true : a.Field<object>("ativo").ToString() == "1")
+ }).ToList<Plano>();
+ }
+
+ public Plano Merge(Plano plano)
+ {
+ PlanoDb planoDb = ApplicationMapper.Mapper.Map<Plano, PlanoDb>(plano);
+ base.Merge(planoDb);
+ return ApplicationMapper.Mapper.Map<PlanoDb, Plano>(planoDb);
+ }
+
+ public Plano SaveOrUpdate(Plano plano)
+ {
+ PlanoDb planoDb = ApplicationMapper.Mapper.Map<Plano, PlanoDb>(plano);
+ this.SaveOrUpdate(planoDb);
+ return ApplicationMapper.Mapper.Map<PlanoDb, Plano>(planoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs
new file mode 100644
index 0000000..d76619d
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/PlanosRepository.cs
@@ -0,0 +1,101 @@
+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<PlanosDb>, IPlanosRepository, IGenericRepository<PlanosDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public PlanosRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Planos> Find(string description)
+ {
+ PlanosRepository.u003cu003ec__DisplayClass3_0 variable = null;
+ IQueryable<PlanosDb> planosDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(PlanosDb), "x");
+ List<PlanosDb> list = planosDbs.Where<PlanosDb>(Expression.Lambda<Func<PlanosDb, bool>>(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<Expression>()), (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<PlanosDb>();
+ return ApplicationMapper.Mapper.Map<List<PlanosDb>, List<Planos>>(list);
+ }
+
+ public List<Planos> 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, Planos>(planosDb);
+ }
+
+ public List<Planos> FindByPlanoId(long id)
+ {
+ List<PlanosDb> list = (
+ from x in base.All()
+ where x.Plano.Id == id
+ select x).ToList<PlanosDb>();
+ return ApplicationMapper.Mapper.Map<List<PlanosDb>, List<Planos>>(list);
+ }
+
+ public Planos Merge(Planos planos)
+ {
+ PlanosDb planosDb = ApplicationMapper.Mapper.Map<Planos, PlanosDb>(planos);
+ base.Merge(planosDb);
+ return ApplicationMapper.Mapper.Map<PlanosDb, Planos>(planosDb);
+ }
+
+ public Planos SaveOrUpdate(Planos planos)
+ {
+ PlanosDb planosDb = ApplicationMapper.Mapper.Map<Planos, PlanosDb>(planos);
+ this.SaveOrUpdate(planosDb);
+ return ApplicationMapper.Mapper.Map<PlanosDb, Planos>(planosDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs
new file mode 100644
index 0000000..472ec21
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProdutoRepository.cs
@@ -0,0 +1,76 @@
+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<ProdutoDb>, IProdutoRepository, IGenericRepository<ProdutoDb>
+ {
+ 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<Produto> Find(string value)
+ {
+ ProdutoRepository.u003cu003ec__DisplayClass6_0 variable = null;
+ IQueryable<ProdutoDb> produtoDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(ProdutoDb), "x");
+ IQueryable<ProdutoDb> produtoDbs1 = produtoDbs.Where<ProdutoDb>(Expression.Lambda<Func<ProdutoDb, bool>>(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<Expression>()), (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<Expression>()), (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<ProdutoDb, Produto>(Expression.Lambda<Func<ProdutoDb, Produto>>(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<Produto>();
+ }
+
+ public List<Produto> Find()
+ {
+ return (
+ from x in this._unitOfWork.Session.CreateQuery("from ProdutoDb").List<ProdutoDb>()
+ select new Produto()
+ {
+ Id = x.Id,
+ Nome = x.Nome,
+ Ativo = x.Ativo
+ }).ToList<Produto>();
+ }
+
+ public Produto FindById(long id)
+ {
+ ProdutoDb produtoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ProdutoDb, Produto>(produtoDb);
+ }
+
+ public Produto Merge(Produto produto)
+ {
+ ProdutoDb produtoDb = ApplicationMapper.Mapper.Map<Produto, ProdutoDb>(produto);
+ base.Merge(produtoDb);
+ return ApplicationMapper.Mapper.Map<ProdutoDb, Produto>(produtoDb);
+ }
+
+ public Produto SaveOrUpdate(Produto produto)
+ {
+ ProdutoDb produtoDb = ApplicationMapper.Mapper.Map<Produto, ProdutoDb>(produto);
+ this.SaveOrUpdate(produtoDb);
+ return ApplicationMapper.Mapper.Map<ProdutoDb, Produto>(produtoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs
new file mode 100644
index 0000000..f251e6e
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProfissaoRepository.cs
@@ -0,0 +1,92 @@
+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<ProfissaoDb>, IProfissaoRepository, IGenericRepository<ProfissaoDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public ProfissaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Profissao> Find(string filter)
+ {
+ ProfissaoRepository.u003cu003ec__DisplayClass5_0 variable = null;
+ IQueryable<ProfissaoDb> profissaoDbs = base.All();
+ ParameterExpression parameterExpression = Expression.Parameter(typeof(ProfissaoDb), "x");
+ IQueryable<ProfissaoDb> profissaoDbs1 = profissaoDbs.Where<ProfissaoDb>(Expression.Lambda<Func<ProfissaoDb, bool>>(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<Expression>()), (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(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<Expression>()), (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(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<ProfissaoDb, Profissao>(Expression.Lambda<Func<ProfissaoDb, Profissao>>(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<Profissao>();
+ }
+
+ 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, ProfissaoDb>(profissao);
+ base.Merge(profissaoDb);
+ return ApplicationMapper.Mapper.Map<ProfissaoDb, Profissao>(profissaoDb);
+ }
+
+ public Profissao SaveOrUpdate(Profissao profissao)
+ {
+ ProfissaoDb profissaoDb = ApplicationMapper.Mapper.Map<Profissao, ProfissaoDb>(profissao);
+ this.SaveOrUpdate(profissaoDb);
+ return ApplicationMapper.Mapper.Map<ProfissaoDb, Profissao>(profissaoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs
new file mode 100644
index 0000000..8b4909c
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ProspectRepository.cs
@@ -0,0 +1,245 @@
+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<ProspeccaoDb>, IProspectRepository, IGenericRepository<ProspeccaoDb>
+ {
+ 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<Prospeccao> Find(long idempresa, long id, DateTime inicio, DateTime fim, StatusProspeccao? status)
+ {
+ VendedorDb vendedorDb = this._unitOfWork.Query<VendedorDb>().First<VendedorDb>((VendedorDb x) => x.Corretora);
+ List<ProspeccaoDb> prospeccaoDbs = new List<ProspeccaoDb>();
+ 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<ProspeccaoDb>();
+ }
+ 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<ProspeccaoDb>();
+ }
+ 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<ProspeccaoDb>();
+ }
+ 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<ProspeccaoDb>();
+ }
+ }
+ 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<ProspeccaoDb>();
+ }
+ 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<ProspeccaoDb>();
+ }
+ 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<ProspeccaoDb>();
+ }
+ 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<ProspeccaoDb>();
+ }
+ }
+ 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<ProspeccaoDb>, List<Prospeccao>>(prospeccaoDbs);
+ }
+
+ public List<Prospeccao> Find(Filtros filtro)
+ {
+ List<ProspeccaoDb> prospeccaoDbs;
+ VendedorDb vendedorDb = this._unitOfWork.Query<VendedorDb>().First<VendedorDb>((VendedorDb x) => x.Corretora);
+ List<StatusProspeccao> statusProspeccaos = new List<StatusProspeccao>()
+ {
+ 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<ProspeccaoDb>() : (
+ 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<ProspeccaoDb>());
+ 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<ProspeccaoDb>());
+ return ApplicationMapper.Mapper.Map<List<ProspeccaoDb>, List<Prospeccao>>(prospeccaoDbs);
+ }
+
+ public List<Prospeccao> FindByData(DateTime inicio, DateTime fim)
+ {
+ List<ProspeccaoDb> list = (
+ from x in base.All()
+ where (x.VigenciaFinal != null) && (x.VigenciaFinal >= (DateTime?)inicio) && (x.VigenciaFinal <= (DateTime?)fim)
+ select x).ToList<ProspeccaoDb>();
+ list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true)));
+ return ApplicationMapper.Mapper.Map<List<ProspeccaoDb>, List<Prospeccao>>(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<ProspeccaoDb, Prospeccao>(nullable);
+ }
+
+ public List<Prospeccao> FindByStatus(StatusProspeccao status)
+ {
+ List<ProspeccaoDb> list = (
+ from x in base.All()
+ where (int?)x.Status == (int?)status
+ select x).ToList<ProspeccaoDb>();
+ list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true)));
+ return ApplicationMapper.Mapper.Map<List<ProspeccaoDb>, List<Prospeccao>>(list);
+ }
+
+ public List<Prospeccao> FindByStatusPersonalizado(long statusId)
+ {
+ List<ProspeccaoDb> list = (
+ from x in base.All()
+ where x.StatusPersonalizado.Id == statusId
+ select x).ToList<ProspeccaoDb>();
+ list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true)));
+ return ApplicationMapper.Mapper.Map<List<ProspeccaoDb>, List<Prospeccao>>(list);
+ }
+
+ public Prospeccao FindByTarefa(long id)
+ {
+ ProspeccaoDb nullable = base.All().FirstOrDefault<ProspeccaoDb>((ProspeccaoDb x) => x.Tarefa.Id == id);
+ if (nullable != null)
+ {
+ bool? renovacao = nullable.Renovacao;
+ nullable.Renovacao = new bool?(renovacao.GetValueOrDefault(true));
+ }
+ return ApplicationMapper.Mapper.Map<ProspeccaoDb, Prospeccao>(nullable);
+ }
+
+ public List<Prospeccao> FindByVendedor(long id)
+ {
+ List<ProspeccaoDb> list = (
+ from x in base.All()
+ where x.Vendedor.Id == id
+ select x).ToList<ProspeccaoDb>();
+ list.ForEach((ProspeccaoDb x) => x.Renovacao = new bool?(x.Renovacao.GetValueOrDefault(true)));
+ return ApplicationMapper.Mapper.Map<List<ProspeccaoDb>, List<Prospeccao>>(list);
+ }
+
+ public Prospeccao Merge(Prospeccao prospeccao)
+ {
+ ProspeccaoDb prospeccaoDb = ApplicationMapper.Mapper.Map<Prospeccao, ProspeccaoDb>(prospeccao);
+ base.Merge(prospeccaoDb);
+ return ApplicationMapper.Mapper.Map<ProspeccaoDb, Prospeccao>(prospeccaoDb);
+ }
+
+ public Prospeccao SaveOrUpdate(Prospeccao prospeccao)
+ {
+ ProspeccaoDb prospeccaoDb = ApplicationMapper.Mapper.Map<Prospeccao, ProspeccaoDb>(prospeccao);
+ this.SaveOrUpdate(prospeccaoDb);
+ return ApplicationMapper.Mapper.Map<ProspeccaoDb, Prospeccao>(prospeccaoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs
new file mode 100644
index 0000000..e8c621b
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/QualificacaoRepository.cs
@@ -0,0 +1,38 @@
+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<QualificacaoDb>, IQualificacaoRepository, IGenericRepository<QualificacaoDb>
+ {
+ public QualificacaoRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ }
+
+ public Qualificacao FindById(long id)
+ {
+ QualificacaoDb qualificacaoDb = base.FindEntityById(id) ?? new QualificacaoDb();
+ return ApplicationMapper.Mapper.Map<QualificacaoDb, Qualificacao>(qualificacaoDb);
+ }
+
+ public Qualificacao Merge(Qualificacao qualificacao)
+ {
+ QualificacaoDb qualificacaoDb = ApplicationMapper.Mapper.Map<Qualificacao, QualificacaoDb>(qualificacao);
+ base.Merge(qualificacaoDb);
+ return ApplicationMapper.Mapper.Map<QualificacaoDb, Qualificacao>(qualificacaoDb);
+ }
+
+ public Qualificacao SaveOrUpdate(Qualificacao qualificacao)
+ {
+ QualificacaoDb qualificacaoDb = ApplicationMapper.Mapper.Map<Qualificacao, QualificacaoDb>(qualificacao);
+ this.SaveOrUpdate(qualificacaoDb);
+ return ApplicationMapper.Mapper.Map<QualificacaoDb, Qualificacao>(qualificacaoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs
new file mode 100644
index 0000000..563c6bf
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RamoRepository.cs
@@ -0,0 +1,85 @@
+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<RamoDb>, IRamoRepository, IGenericRepository<RamoDb>
+ {
+ 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<Ramo> Find(bool ativo)
+ {
+ return (
+ from x in this._unitOfWork.Session.CreateQuery("from RamoDb \r\n where ativo IS NULL OR ativo != '1'").List<RamoDb>()
+ select new Ramo()
+ {
+ Id = x.Id,
+ Nome = x.Nome,
+ Iof = x.Iof,
+ Ativo = x.Ativo
+ }).ToList<Ramo>();
+ }
+
+ public List<Ramo> Find()
+ {
+ return (
+ from x in this._unitOfWork.Session.CreateQuery("from RamoDb").List<RamoDb>()
+ select new Ramo()
+ {
+ Id = x.Id,
+ Nome = x.Nome,
+ Iof = x.Iof,
+ Ativo = x.Ativo
+ }).ToList<Ramo>();
+ }
+
+ public Ramo FindById(long id)
+ {
+ RamoDb ramoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<RamoDb, Ramo>(ramoDb);
+ }
+
+ public Ramo Merge(Ramo ramo)
+ {
+ RamoDb ramoDb = ApplicationMapper.Mapper.Map<Ramo, RamoDb>(ramo);
+ base.Merge(ramoDb);
+ return ApplicationMapper.Mapper.Map<RamoDb, Ramo>(ramoDb);
+ }
+
+ public List<Ramo> MergeRange(List<Ramo> ramos)
+ {
+ List<RamoDb> ramoDbs = ApplicationMapper.Mapper.Map<List<Ramo>, List<RamoDb>>(ramos);
+ RamoRepository ramoRepository = this;
+ ramoDbs.ForEach(new Action<RamoDb>(ramoRepository.Merge));
+ return ApplicationMapper.Mapper.Map<List<RamoDb>, List<Ramo>>(ramoDbs);
+ }
+
+ public Ramo SaveOrUpdate(Ramo ramo)
+ {
+ RamoDb ramoDb = ApplicationMapper.Mapper.Map<Ramo, RamoDb>(ramo);
+ this.SaveOrUpdate(ramoDb);
+ return ApplicationMapper.Mapper.Map<RamoDb, Ramo>(ramoDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs
new file mode 100644
index 0000000..cff93a5
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReciboRepository.cs
@@ -0,0 +1,71 @@
+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<ReciboDb>, IReciboRepository, IGenericRepository<ReciboDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public ReciboRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Recibo> BuscarRecibos()
+ {
+ List<ReciboDb> list = base.All().ToList<ReciboDb>();
+ return ApplicationMapper.Mapper.Map<List<ReciboDb>, List<Recibo>>(list);
+ }
+
+ public void Delete(long id)
+ {
+ ReciboDb reciboDb = base.FindEntityById(id);
+ if (reciboDb == null)
+ {
+ return;
+ }
+ base.Delete(reciboDb);
+ }
+
+ public void DeleteRange(List<long> ids)
+ {
+ List<ReciboDb> list = (
+ from x in base.All()
+ where ids.Contains(x.Id)
+ select x).ToList<ReciboDb>();
+ base.DeleteRange(list);
+ }
+
+ public Recibo FindById(long id)
+ {
+ ReciboDb reciboDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<ReciboDb, Recibo>(reciboDb);
+ }
+
+ public Recibo Merge(Recibo recibo)
+ {
+ ReciboDb reciboDb = ApplicationMapper.Mapper.Map<Recibo, ReciboDb>(recibo);
+ base.Merge(reciboDb);
+ return ApplicationMapper.Mapper.Map<ReciboDb, Recibo>(reciboDb);
+ }
+
+ public Recibo SaveOrUpdate(Recibo recibo)
+ {
+ ReciboDb reciboDb = ApplicationMapper.Mapper.Map<Recibo, ReciboDb>(recibo);
+ this.SaveOrUpdate(reciboDb);
+ return ApplicationMapper.Mapper.Map<ReciboDb, Recibo>(reciboDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs
new file mode 100644
index 0000000..158bcb9
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroAcaoRepository.cs
@@ -0,0 +1,183 @@
+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<RegistroAcaoDb>, IRegistroAcaoRepository, IGenericRepository<RegistroAcaoDb>
+ {
+ 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<RegistroAcao> Find(Filtros filtros)
+ {
+ return this.Select(filtros);
+ }
+
+ public List<RegistroAcao> FindByEntityId(long id, TipoTela tela)
+ {
+ List<RegistroAcaoDb> list = (
+ from x in base.All()
+ where x.EntidadeId == id && (int?)x.Tela == (int?)tela
+ select x).ToList<RegistroAcaoDb>();
+ return ApplicationMapper.Mapper.Map<List<RegistroAcaoDb>, List<RegistroAcao>>(list);
+ }
+
+ public RegistroAcao FindById(long id)
+ {
+ RegistroAcaoDb registroAcaoDb = base.FindEntityById(id);
+ return ApplicationMapper.Mapper.Map<RegistroAcaoDb, RegistroAcao>(registroAcaoDb);
+ }
+
+ public List<RegistroAcao> FindOld(Filtros filtros, string connection)
+ {
+ return this.SelectOld(filtros, connection);
+ }
+
+ public RegistroAcao SaveOrUpdate(RegistroAcao log)
+ {
+ RegistroAcaoDb registroAcaoDb = ApplicationMapper.Mapper.Map<RegistroAcao, RegistroAcaoDb>(log);
+ this.SaveOrUpdate(registroAcaoDb);
+ return ApplicationMapper.Mapper.Map<RegistroAcaoDb, RegistroAcao>(registroAcaoDb);
+ }
+
+ private List<RegistroAcao> Select(Filtros filtros)
+ {
+ List<RegistroAcao> registroAcaos;
+ object connection;
+ DataTable dataTable = new DataTable();
+ string str = (filtros.Usuarios == null || filtros.Usuarios.Count == 0 ? "" : string.Concat(" AND IdUsuario IN (", string.Join<long>(",",
+ from v in filtros.Usuarios
+ select v), ")"));
+ string str1 = (filtros.Telas == null || filtros.Telas.Count == 0 ? "" : string.Concat(" AND Tela IN (", string.Join<long>(",",
+ from v in filtros.Telas
+ select v), ")"));
+ string str2 = (filtros.Relatorios == null || filtros.Relatorios.Count == 0 ? "" : string.Concat(" AND Relatorio IN (", string.Join<long>(",",
+ 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<RegistroAcao>();
+ }
+ }
+ }
+ return registroAcaos;
+ }
+
+ private List<RegistroAcao> SelectOld(Filtros filtros, string conn)
+ {
+ List<RegistroAcao> registroAcaos;
+ object connection;
+ try
+ {
+ DataTable dataTable = new DataTable();
+ string str = (filtros.Usuarios == null || filtros.Usuarios.Count == 0 ? "" : string.Concat(" AND IDUSUARIO IN (", string.Join<long>(",",
+ 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<RegistroAcao>());
+ }
+ catch (Exception exception)
+ {
+ registroAcaos = new List<RegistroAcao>();
+ }
+ return registroAcaos;
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs
new file mode 100644
index 0000000..a57c17e
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RegistroLogRepository.cs
@@ -0,0 +1,222 @@
+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<RegistroLogDb>, IRegistroLogRepository, IGenericRepository<RegistroLogDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public RegistroLogRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public void AddRange(List<RegistroLog> registrosLog)
+ {
+ base.AddRange(ApplicationMapper.Mapper.Map<List<RegistroLog>, List<RegistroLogDb>>(registrosLog));
+ }
+
+ public List<RegistroLog> BuscaLogParcelas(List<long> entidadeId)
+ {
+ return this.Select((new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "Tela",
+ Valores = 5.CriarValor<int>()
+ },
+ new Condicao()
+ {
+ Campo = "EntidadeId",
+ Valores = entidadeId.CriarValor<long>()
+ }
+ }).CreateParameters(0));
+ }
+
+ public void Delete(long id)
+ {
+ base.Delete(base.FindEntityById(id));
+ }
+
+ public List<LogEmail> FindByCredential(long id)
+ {
+ List<LogEmailDb> list = (
+ from x in this._unitOfWork.Query<LogEmailDb>()
+ where x.Credencial.Id == id
+ select x).ToList<LogEmailDb>();
+ return ApplicationMapper.Mapper.Map<List<LogEmailDb>, List<LogEmail>>(list);
+ }
+
+ public List<LogEmail> FindByEntity(TipoTela tela, long id)
+ {
+ List<LogEmailDb> list = (
+ from x in this._unitOfWork.Query<LogEmailDb>()
+ where x.EntityId == id && (int)x.Tela == (int)tela
+ select x).ToList<LogEmailDb>();
+ return ApplicationMapper.Mapper.Map<List<LogEmailDb>, List<LogEmail>>(list);
+ }
+
+ public List<RegistroLog> FindByEntityId(TipoTela tela, long entidadeId)
+ {
+ List<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "Tela",
+ Valores = tela.CriarValor<int>()
+ }
+ };
+ Condicao condicao = new Condicao()
+ {
+ Campo = "EntidadeId",
+ Valores = entidadeId.CriarValor<long>()
+ };
+ 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, RegistroLog>(registroLogDb);
+ }
+
+ public List<LogEmail> FindByIdSingle(long id)
+ {
+ List<LogEmailDb> list = (
+ from x in this._unitOfWork.Query<LogEmailDb>()
+ where x.Id == id
+ select x).ToList<LogEmailDb>();
+ return ApplicationMapper.Mapper.Map<List<LogEmailDb>, List<LogEmail>>(list);
+ }
+
+ public List<RegistroLog> FindByUser(TipoTela tela, long idUsuario)
+ {
+ return this.Select((new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "IdUsuario",
+ Valores = idUsuario.CriarValor<long>()
+ },
+ new Condicao()
+ {
+ Campo = "Tela",
+ Valores = 0.CriarValor<int>(),
+ Operacao = Operacao.Or,
+ Grupo = 1
+ },
+ new Condicao()
+ {
+ Campo = "Tela",
+ Valores = tela.CriarValor<int>(),
+ Operacao = Operacao.Or,
+ Grupo = 1
+ }
+ }).CreateParameters(0));
+ }
+
+ public List<LogEmail> FindByUsuario(long id)
+ {
+ List<LogEmailDb> list = (
+ from x in this._unitOfWork.Query<LogEmailDb>()
+ where x.Usuario.Id == id
+ select x).ToList<LogEmailDb>();
+ return ApplicationMapper.Mapper.Map<List<LogEmailDb>, List<LogEmail>>(list);
+ }
+
+ public List<LogsEnvio> 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, LogsEnvio>((DataRow x) => new LogsEnvio()
+ {
+ Id = x.Campo<long>("id"),
+ Tela = x.Campo<TipoTela>("tela").GetDescription(),
+ Assunto = x.Campo<string>("assunto"),
+ Destinatarios = x.Campo<string>("destinatarios").Replace(";", ";\n"),
+ Data = x.Campo<DateTime>("data"),
+ Ip = x.Campo<string>("ip"),
+ Versao = x.Campo<string>("versao"),
+ Cco = x.Campo<string>("cco").Replace(";", ";\n"),
+ Maquina = x.Campo<string>("nomemaquina"),
+ UsuarioMaquina = x.Campo<string>("usuariomaquina"),
+ UsuarioAgger = x.Campo<string>("usuarionome"),
+ Remetente = x.Campo<string>("emailenvio")
+ }).ToList<LogsEnvio>();
+ }
+
+ public RegistroLog SaveOrUpdate(RegistroLog registroLog)
+ {
+ RegistroLogDb registroLogDb = ApplicationMapper.Mapper.Map<RegistroLog, RegistroLogDb>(registroLog);
+ this.SaveOrUpdate(registroLogDb);
+ return ApplicationMapper.Mapper.Map<RegistroLogDb, RegistroLog>(registroLogDb);
+ }
+
+ public LogEmail SaveOrUpdate(LogEmail log)
+ {
+ LogEmailDb logEmailDb = ApplicationMapper.Mapper.Map<LogEmail, LogEmailDb>(log);
+ this._unitOfWork.Repository<LogEmailDb>().SaveOrUpdate(logEmailDb);
+ return ApplicationMapper.Mapper.Map<LogEmailDb, LogEmail>(logEmailDb);
+ }
+
+ private List<RegistroLog> Select(SqlQueryCondition sqlCondition)
+ {
+ return this._unitOfWork.Select(sqlCondition, "SELECT DISTINCT * FROM RegistroLog WHERE", "").MapRegistroLog();
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs
new file mode 100644
index 0000000..861ac85
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RepasseRepository.cs
@@ -0,0 +1,298 @@
+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<RepasseDb>, IRepasseRepository, IGenericRepository<RepasseDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public RepasseRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<Repasse> DefaultSelect(long idempresa = 0L)
+ {
+ List<Repasse> repasses;
+ object connection;
+ List<long> nums = null;
+ Func<DataRow, VinculoRepasse> 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<Condicao> condicaos = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "idempresa",
+ Valores = idempresa.CriarValor<long>()
+ }
+ };
+ string str = "SELECT * FROM repasse WHERE ";
+ string str1 = "SELECT * FROM VinculoRepasse WHERE ";
+ List<Condicao> condicaos1 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "1",
+ Valores = "1".CriarValor<string>()
+ }
+ };
+ if (idempresa > (long)0)
+ {
+ condicaos1.AddRange(condicaos);
+ }
+ dataTable = sqlCommand.Select(condicaos1.CreateParameters(0), str, "");
+ if (dataTable.Rows.Count != 0)
+ {
+ for (List<long> i = dataTable.AsEnumerable().Select<DataRow, long>((DataRow x) => x.Field<long>("idrepasse")).Distinct<long>().ToList<long>(); i.Count > 0; i = nums)
+ {
+ List<long> nums1 = i.Take<long>(2000).ToList<long>();
+ List<Condicao> condicaos2 = new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "IdRepasse",
+ Valores = nums1.CriarValor<long>()
+ }
+ };
+ DataTable dataTable2 = sqlCommand.Select(condicaos2.CreateParameters(0), str1, "");
+ dataTable1.Merge(dataTable2);
+ nums = (nums1.Count < 2000 ? new List<long>() : i.Except<long>(nums1).ToList<long>());
+ }
+ List<Repasse> repasses1 = dataTable.AsEnumerable().Select<DataRow, Repasse>((DataRow x) => {
+ long? nullable1;
+ long? nullable2;
+ Repasse repasse = new Repasse()
+ {
+ Id = x.Field<long>("idrepasse"),
+ Ativo = (x.Field<object>("ativo") == null ? true : x.Field<object>("ativo").ToString() != "0"),
+ Base = (x.Field<object>("base") == null ? null : new BaseRepasse?((BaseRepasse)Enum.Parse(typeof(BaseRepasse), x.Field<object>("base").ToString()))),
+ Forma = (x.Field<object>("forma") == null ? null : new FormaRepasse?((FormaRepasse)Enum.Parse(typeof(FormaRepasse), x.Field<object>("forma").ToString()))),
+ Incidencia = (x.Field<object>("incidencia") == null ? null : new TipoIncidencia?((TipoIncidencia)Enum.Parse(typeof(TipoIncidencia), x.Field<object>("incidencia").ToString()))),
+ Tipo = (x.Field<object>("tipo") == null ? null : new TipoRepasse?((TipoRepasse)Enum.Parse(typeof(TipoRepasse), x.Field<object>("tipo").ToString())))
+ };
+ decimal? nullable3 = x.Field<decimal?>("vlrnovo");
+ repasse.ValorNovo = nullable3.GetValueOrDefault();
+ nullable3 = x.Field<decimal?>("vlrrenovacao");
+ repasse.ValorRenovacao = nullable3.GetValueOrDefault();
+ repasse.Vendedor = Auxiliar.Vendedores.FirstOrDefault<Vendedor>((Vendedor z) => z.Id == x.Field<long>("idvendedor"));
+ repasse.Ramo = (x.Field<object>("idramo") == null ? null : Auxiliar.Ramos.FirstOrDefault<Ramo>((Ramo z) => {
+ long id = z.Id;
+ long? nullable = x.Field<long?>("idramo");
+ return id == nullable.GetValueOrDefault() & nullable.HasValue;
+ }));
+ if (x.Field<object>("idciaseg") == null)
+ {
+ nullable1 = null;
+ nullable2 = nullable1;
+ }
+ else
+ {
+ Seguradora seguradora = Auxiliar.Seguradoras.FirstOrDefault<Seguradora>((Seguradora z) => {
+ long id = z.Id;
+ long? nullable = x.Field<long?>("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<Repasse>();
+ List<Repasse> repasses2 = (
+ from x in repasses1
+ where x.Ativo
+ select x).ToList<Repasse>();
+ repasses2.ForEach((Repasse x) => {
+ Repasse list = x;
+ EnumerableRowCollection<DataRow> dataRows = dataTable1.AsEnumerable().Where<DataRow>((DataRow r) => r.Field<long>("IdRepasse") == x.Id);
+ Func<DataRow, VinculoRepasse> u003cu003e9_8 = func1;
+ if (u003cu003e9_8 == null)
+ {
+ Func<DataRow, VinculoRepasse> vinculoRepasse = (DataRow v) => new VinculoRepasse()
+ {
+ Id = v.Field<long>("Id"),
+ IdRepasse = v.Field<long>("IdRepasse"),
+ RepasseVinculo = repasses1.Find((Repasse z) => z.Id == v.Field<long>("RepasseVinculo_id")),
+ TipoVendedor = Auxiliar.TipoVendedores.Find((TipoVendedor z) => z.Id == v.Field<long>("TipoVendedor_id")),
+ TipoVendedorVinculo = Auxiliar.TipoVendedores.Find((TipoVendedor z) => z.Id == v.Field<long>("TipoVendedorVinculo_id"))
+ };
+ Func<DataRow, VinculoRepasse> func = vinculoRepasse;
+ func1 = vinculoRepasse;
+ u003cu003e9_8 = func;
+ }
+ list.Vinculo = dataRows.Select<DataRow, VinculoRepasse>(u003cu003e9_8).ToList<VinculoRepasse>();
+ });
+ repasses = repasses2;
+ }
+ else
+ {
+ repasses = new List<Repasse>();
+ }
+ }
+ }
+ 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<VinculoRepasseDb>().FindEntityById(id);
+ if (vinculoRepasseDb == null)
+ {
+ return;
+ }
+ this._unitOfWork.Repository<VinculoRepasseDb>().Delete(vinculoRepasseDb);
+ }
+
+ public Repasse FindById(long id)
+ {
+ List<VinculoRepasse> vinculoRepasses;
+ RepasseDb repasseDb = base.FindEntityById(id);
+ List<VinculoRepasse> vinculoRepasses1 = this.FindByRepasse(id);
+ Repasse repasse = ApplicationMapper.Mapper.Map<RepasseDb, Repasse>(repasseDb);
+ if (vinculoRepasses1 == null || vinculoRepasses1.Count <= 0)
+ {
+ vinculoRepasses = null;
+ }
+ else
+ {
+ vinculoRepasses = vinculoRepasses1;
+ }
+ repasse.Vinculo = vinculoRepasses;
+ return repasse;
+ }
+
+ public List<VendedorParcela> 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, VendedorParcela>((DataRow x) => new VendedorParcela()
+ {
+ Id = x.Field<long>("idvendedorparcela")
+ }).ToList<VendedorParcela>();
+ }
+
+ public List<Repasse> FindByIdVendedor(long id)
+ {
+ List<RepasseDb> list = this._unitOfWork.Session.CreateQuery(string.Format("from RepasseDb \r\n where IdVendedor = {0}", id)).List<RepasseDb>().ToList<RepasseDb>();
+ List<Repasse> repasses = ApplicationMapper.Mapper.Map<List<RepasseDb>, List<Repasse>>(list);
+ repasses.ForEach((Repasse x) => {
+ List<VinculoRepasse> vinculoRepasses = this.FindByRepasse(x.Id);
+ x.Vinculo = (vinculoRepasses == null || vinculoRepasses.Count <= 0 ? null : vinculoRepasses);
+ });
+ return repasses;
+ }
+
+ public List<VinculoRepasse> FindByRepasse(long id)
+ {
+ List<VinculoRepasseDb> list = (
+ from x in this._unitOfWork.Query<VinculoRepasseDb>()
+ where x.IdRepasse == id
+ select x).ToList<VinculoRepasseDb>();
+ return ApplicationMapper.Mapper.Map<List<VinculoRepasseDb>, List<VinculoRepasse>>(list);
+ }
+
+ public Repasse Merge(Repasse repasse)
+ {
+ RepasseDb repasseDb = ApplicationMapper.Mapper.Map<Repasse, RepasseDb>(repasse);
+ base.Merge(repasseDb);
+ return ApplicationMapper.Mapper.Map<RepasseDb, Repasse>(repasseDb);
+ }
+
+ public VinculoRepasse Merge(VinculoRepasse vinculo)
+ {
+ VinculoRepasseDb vinculoRepasseDb = ApplicationMapper.Mapper.Map<VinculoRepasse, VinculoRepasseDb>(vinculo);
+ this._unitOfWork.Repository<VinculoRepasseDb>().Merge(vinculoRepasseDb);
+ return ApplicationMapper.Mapper.Map<VinculoRepasseDb, VinculoRepasse>(vinculoRepasseDb);
+ }
+
+ public Repasse SaveOrUpdate(Repasse repasse)
+ {
+ RepasseDb repasseDb = ApplicationMapper.Mapper.Map<Repasse, RepasseDb>(repasse);
+ this.SaveOrUpdate(repasseDb);
+ return ApplicationMapper.Mapper.Map<RepasseDb, Repasse>(repasseDb);
+ }
+
+ public VinculoRepasse SaveOrUpdate(VinculoRepasse vinculo)
+ {
+ VinculoRepasseDb vinculoRepasseDb = ApplicationMapper.Mapper.Map<VinculoRepasse, VinculoRepasseDb>(vinculo);
+ this._unitOfWork.Repository<VinculoRepasseDb>().SaveOrUpdate(vinculoRepasseDb);
+ return ApplicationMapper.Mapper.Map<VinculoRepasseDb, VinculoRepasse>(vinculoRepasseDb);
+ }
+ }
+} \ No newline at end of file
diff --git a/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs
new file mode 100644
index 0000000..990e3a2
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/ReportRepository.cs
@@ -0,0 +1,1991 @@
+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<DocumentoDb>, IReportRepository, IGenericRepository<DocumentoDb>
+ {
+ private readonly GenericUnitOfWork _unitOfWork;
+
+ public ReportRepository(GenericUnitOfWork unitOfWork) : base(unitOfWork.Session)
+ {
+ this._unitOfWork = unitOfWork;
+ }
+
+ public List<PlanilhaCompleta> PlanilhaCompleta(List<long> ids, bool configFranquia, bool configSomaPremio)
+ {
+ object connection;
+ List<long> nums = null;
+ List<long> nums1 = null;
+ if (ids == null || ids.Count == 0)
+ {
+ return new List<PlanilhaCompleta>();
+ }
+ 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<long> i1 = ids; i1.Count > 0; i1 = nums1)
+ {
+ List<long> nums2 = i1.Take<long>(2100).ToList<long>();
+ string str9 = string.Concat(" AND d.iddocumento IN (", string.Join<long>(",", 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<long>(",", dataTable.AsEnumerable().Select<DataRow, long>((DataRow v) => v.Field<long>("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<long> j = table.AsEnumerable().Select<DataRow, long>((DataRow i) => i.Field<long>("iditem")).ToList<long>(); j.Count > 0; j = nums)
+ {
+ List<long> nums3 = j.Take<long>(2000).ToList<long>();
+ SqlQueryCondition sqlQueryCondition = (new List<Condicao>()
+ {
+ new Condicao()
+ {
+ Campo = "iditem",
+ Valores = nums3.CriarValor<long>()
+ }
+ }).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<long>() : j.Except<long>(nums3).ToList<long>());
+ }
+ 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<long>() : i1.Except<long>(nums2).ToList<long>());
+ }
+ }
+ }
+ if (dataTable.Rows.Count == 0)
+ {
+ return new List<PlanilhaCompleta>();
+ }
+ List<PlanilhaCompleta> planilhaCompletas = new List<PlanilhaCompleta>();
+ dataTable.AsEnumerable().ToList<DataRow>().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>((DataRow e) => e.Field<long>("idcontrole") == x.Field<long>("idcontrole"));
+ List<DataRow> list = dataTable2.AsEnumerable().Where<DataRow>((DataRow e) => e.Field<long>("iddocumento") == x.Field<long>("iddocumento")).Take<DataRow>(3).ToList<DataRow>();
+ List<DataRow> dataRows = dataTable3.AsEnumerable().Where<DataRow>((DataRow e) => e.Field<long>("iddocumento") == x.Field<long>("iddocumento")).Take<DataRow>(2).ToList<DataRow>();
+ DataRow dataRow1 = dataTable4.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iddocumento") == x.Field<long>("iddocumento"));
+ DataRow dataRow2 = dataTable5.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iddocumento") == x.Field<long>("iddocumento"));
+ List<DataRow> list1 = dataTable6.AsEnumerable().Where<DataRow>((DataRow e) => e.Field<long>("idcontrole") == x.Field<long>("idcontrole")).ToList<DataRow>();
+ bool count = list1.Count != 1;
+ DataRow dataRow3 = (count ? null : dataTable9.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")));
+ DataRow dataRow4 = (count ? null : dataTable10.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")));
+ DataRow dataRow5 = (count ? null : dataTable11.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")));
+ DataRow dataRow6 = (count ? null : dataTable12.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")));
+ DataRow dataRow7 = (count ? null : dataTable13.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")));
+ DataRow dataRow8 = (count ? null : dataTable14.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")));
+ DataRow dataRow9 = (count ? null : dataTable8.AsEnumerable().FirstOrDefault<DataRow>((DataRow e) => e.Field<long>("iditem") == list1.First<DataRow>().Field<long>("iditem")));
+ NegocioCorretora negocioCorretora = (x.Field<object>("negociocorretora") == null ? ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString()) != TipoSeguro.Renovacao || x.Field<object>("idnegocio") == null || !(x.Field<object>("idnegocio").ToString() == "1") ? NegocioCorretora.Novo : NegocioCorretora.Proprio) : (NegocioCorretora)Enum.Parse(typeof(NegocioCorretora), x.Field<object>("negociocorretora").ToString()));
+ EnumerableRowCollection<DataRow> dataRows1 = dataTable1.AsEnumerable().Where<DataRow>((DataRow e) => e.Field<long>("iddocumento") == x.Field<long>("iddocumento"));
+ string str3 = (x.Field<object>("situacao") == null || !(x.Field<object>("situacao").ToString() != "") || string.IsNullOrWhiteSpace(x.Field<object>("situacao").ToString()) ? null : ((TipoSeguro)Enum.Parse(typeof(TipoSeguro), x.Field<object>("situacao").ToString())).GetDescription<TipoSeguro>());
+ string str4 = (x.Field<object>("sexo") == null || !(x.Field<object>("sexo").ToString() != "") || string.IsNullOrWhiteSpace(x.Field<object>("sexo").ToString()) ? "" : ((Sexo)Enum.Parse(typeof(Sexo), x.Field<object>("sexo").ToString())).GetDescription<Sexo>());
+ object obj2 = x.Field<object>("clibanco");
+ List<Banco> banco = Auxiliar.Banco;
+ List<Banco> bancos = banco;
+ Predicate<Banco> 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>((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<string>("observacao") != null)
+ {
+ str6 = (new Regex("<title>.*<\\/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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs
new file mode 100644
index 0000000..12ab574
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioCamposRelatoriosRepository.cs
@@ -0,0 +1,44 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs
new file mode 100644
index 0000000..3d1fbcc
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RestricaoUsuarioRepository.cs
@@ -0,0 +1,54 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs
new file mode 100644
index 0000000..6353540
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/RiscosDiversosRepository.cs
@@ -0,0 +1,66 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs
new file mode 100644
index 0000000..5249fcf
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SaldoRepository.cs
@@ -0,0 +1,136 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs
new file mode 100644
index 0000000..19ee09a
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraContatoRepository.cs
@@ -0,0 +1,131 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs
new file mode 100644
index 0000000..a88001e
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraEnderecoRepository.cs
@@ -0,0 +1,97 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs
new file mode 100644
index 0000000..328fa86
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SeguradoraRepository.cs
@@ -0,0 +1,76 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs
new file mode 100644
index 0000000..f4ad079
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroAutoRepository.cs
@@ -0,0 +1,61 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs
new file mode 100644
index 0000000..ba62ba0
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroRepository.cs
@@ -0,0 +1,415 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs
new file mode 100644
index 0000000..8f22151
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SinistroVidaRepository.cs
@@ -0,0 +1,56 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs
new file mode 100644
index 0000000..0bacb70
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/SocioRepository.cs
@@ -0,0 +1,75 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs
new file mode 100644
index 0000000..9e9cac0
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusProspeccaoRepository.cs
@@ -0,0 +1,54 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs
new file mode 100644
index 0000000..0eac8b3
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/StatusRepository.cs
@@ -0,0 +1,76 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs
new file mode 100644
index 0000000..bfcdd72
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TarefaRepository.cs
@@ -0,0 +1,462 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs
new file mode 100644
index 0000000..4f5a3cf
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoContaRepository.cs
@@ -0,0 +1,52 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs
new file mode 100644
index 0000000..df36a20
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoTarefaRepository.cs
@@ -0,0 +1,54 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs
new file mode 100644
index 0000000..30382b0
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TipoVendedorRepository.cs
@@ -0,0 +1,139 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs
new file mode 100644
index 0000000..4a0f512
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/TitularesVidaRepository.cs
@@ -0,0 +1,152 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs
new file mode 100644
index 0000000..f1f9993
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/UsuarioRepository.cs
@@ -0,0 +1,305 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs
new file mode 100644
index 0000000..e765212
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorParcelaRepository.cs
@@ -0,0 +1,474 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs
new file mode 100644
index 0000000..04a6532
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorRepository.cs
@@ -0,0 +1,132 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs
new file mode 100644
index 0000000..2f4d3c1
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorTelefoneRepository.cs
@@ -0,0 +1,115 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs
new file mode 100644
index 0000000..49c552f
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VendedorUsuarioRepository.cs
@@ -0,0 +1,94 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs
new file mode 100644
index 0000000..d5507ae
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VidaRepository.cs
@@ -0,0 +1,66 @@
+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/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs
new file mode 100644
index 0000000..4ad03aa
--- /dev/null
+++ b/Codemerx/Gestor.Infrastructure/Gestor.Infrastructure.Repository.Logic/VinculoDocumentoRepository.cs
@@ -0,0 +1,345 @@
+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