From 1f4e14b2e973ee7de337fd4866d9a5ceff5cb6d1 Mon Sep 17 00:00:00 2001 From: Lucas Faria Mendes Date: Mon, 30 Mar 2026 10:38:18 -0300 Subject: chore: location --- .../ViewModels/AnaliticoViewModel.cs | 210 + Codemerx/Gestor.Application/ViewModels/Arquivo.cs | 24 + .../ViewModels/BI/BISeriesViewModel.cs | 70 + .../ViewModels/BI/NotasViewModel.cs | 311 + .../ViewModels/BI/PainelBiViewModel.cs | 1590 ++ .../ViewModels/BI/ProspeccaoViewModel.cs | 553 + .../ViewModels/BI/TarefaBIViewModel.cs | 1453 ++ .../ViewModels/CoberturaViewModel.cs | 285 + .../ViewModels/Comissao/ComissaoViewModel.cs | 3450 +++++ .../ViewModels/Command/RelayCommand.cs | 29 + .../Configuracoes/ConfiguracoesViewModel.cs | 178 + .../ViewModels/DashboardViewModel.cs | 1111 ++ .../ViewModels/Drawer/AdiantamentoViewModel.cs | 310 + .../ViewModels/Drawer/AgendaViewModel.cs | 427 + .../Drawer/Ajuda/AtendimentosViewModel.cs | 514 + .../Drawer/Ajuda/BoletosNotasViewModel.cs | 122 + .../ViewModels/Drawer/Ajuda/ContratosViewModel.cs | 112 + .../ViewModels/Drawer/Ajuda/InstalacaoViewModel.cs | 281 + .../ViewModels/Drawer/ArquivoDigitalViewModel.cs | 1414 ++ .../ViewModels/Drawer/ExpedicaoViewModel.cs | 196 + .../ViewModels/Drawer/ExtratosViewModel.cs | 5516 +++++++ .../ViewModels/Drawer/ImpostoViewModel.cs | 484 + .../ViewModels/Drawer/InfoViewModel.cs | 208 + .../ViewModels/Drawer/LogAcaoViewModel.cs | 262 + .../ViewModels/Drawer/LogEmailViewModel.cs | 163 + .../ViewModels/Drawer/LogSistemaAntigoViewModel.cs | 42 + .../ViewModels/Drawer/LogViewModel.cs | 1784 +++ .../ViewModels/Drawer/MetaSeguradoraViewModel.cs | 258 + .../ViewModels/Drawer/MetaVendedorViewModel.cs | 244 + .../ViewModels/Drawer/PermissaoUsuarioViewModel.cs | 1939 +++ .../ViewModels/Drawer/TarefaDrawerViewModel.cs | 1283 ++ .../ViewModels/Drawer/ValoresApoliceViewModel.cs | 345 + .../ViewModels/Drawer/ValoresParcelaViewModel.cs | 583 + .../ViewModels/Drawer/VinculoVendedorViewModel.cs | 307 + .../Ferramentas/CadastroEmailViewModel.cs | 362 + .../Ferramentas/CadastroParceiroViewModel.cs | 413 + .../ViewModels/Ferramentas/ComboModelo.cs | 43 + .../ViewModels/Ferramentas/ComboVariavel.cs | 45 + .../ViewModels/Ferramentas/DownloadViewModel.cs | 550 + .../ViewModels/Ferramentas/EmpresaViewModel.cs | 512 + .../ViewModels/Ferramentas/EstipulanteViewModel.cs | 380 + .../ViewModels/Ferramentas/EtiquetaViewModel.cs | 1163 ++ .../ViewModels/Ferramentas/IncluirRamoViewModel.cs | 110 + .../Ferramentas/IncluirSeguradoraViewModel.cs | 110 + .../ViewModels/Ferramentas/MalaDiretaViewModel.cs | 821 ++ .../Ferramentas/ManutencaoPagamentosViewModel.cs | 821 ++ .../ViewModels/Ferramentas/NotaFiscalViewModel.cs | 482 + .../ViewModels/Ferramentas/ProdutoViewModel.cs | 303 + .../Ferramentas/ProtocoloDocumentosViewModel.cs | 399 + .../ViewModels/Ferramentas/ProtocoloEtiqueta.cs | 26 + .../Ferramentas/QualificacaoViewModel.cs | 122 + .../ViewModels/Ferramentas/RamoViewModel.cs | 332 + .../ViewModels/Ferramentas/ReciboViewModel.cs | 769 + .../ViewModels/Ferramentas/SeguradoraViewModel.cs | 621 + .../ViewModels/Ferramentas/SocioViewModel.cs | 358 + .../Ferramentas/StatusProspeccaoViewModel.cs | 326 + .../ViewModels/Ferramentas/StatusViewModel.cs | 367 + .../ViewModels/Ferramentas/TipoTarefaViewModel.cs | 325 + .../Ferramentas/TipoVendedorViewModel.cs | 338 + .../ViewModels/Ferramentas/UsuarioViewModel.cs | 826 ++ .../ViewModels/Ferramentas/VendedorViewModel.cs | 913 ++ .../ViewModels/Financeiro/BancosContasViewModel.cs | 604 + .../Financeiro/CentroDeCustoViewmodel.cs | 255 + .../ViewModels/Financeiro/ContasDialogModel.cs | 48 + .../Financeiro/CopiarClienteViewModel.cs | 28 + .../ViewModels/Financeiro/ExtratoContaViewModel.cs | 552 + .../ViewModels/Financeiro/FinanceiroViewModel.cs | 5973 ++++++++ .../ViewModels/Financeiro/FornecedorViewModel.cs | 780 + .../ViewModels/Financeiro/InfoExtratoViewModel.cs | 81 + .../Financeiro/MenuFinanceiroViewModel.cs | 30 + .../ViewModels/Financeiro/PlanoViewModel.cs | 147 + .../ViewModels/Financeiro/PlanosViewModel.cs | 330 + .../Relatorios/FechamentoFinanceiroViewModel.cs | 2746 ++++ .../ViewModels/Financeiro/TranferenciaViewModel.cs | 99 + .../ViewModels/Generic/BaseApoliceViewModel.cs | 6893 +++++++++ .../ViewModels/Generic/BaseDialogViewModel.cs | 11 + .../ViewModels/Generic/BaseFinanceiroViewModel.cs | 512 + .../ViewModels/Generic/BaseSegurosViewModel.cs | 1238 ++ .../ViewModels/Generic/BaseTarefaViewModel.cs | 233 + .../ViewModels/Generic/BaseViewModel.cs | 3140 ++++ .../Generic/DialogAdvertisingViewModel.cs | 292 + .../ViewModels/Generic/DialogAnexarViewModel.cs | 44 + .../ViewModels/Generic/DialogCopiaViewModel.cs | 168 + .../Generic/DialogCopiarPermissaoViewModel.cs | 350 + .../Generic/DialogEditarParcelasViewModel.cs | 342 + .../Generic/DialogEnviarEmailsViewModel.cs | 394 + .../Generic/DialogExportarPermissaoViewModel.cs | 122 + .../ViewModels/Generic/DialogGraficoViewModel.cs | 45 + .../ViewModels/Generic/DialogMedalhaViewModel.cs | 75 + .../Generic/DialogPesquisaAvancadaViewModel.cs | 604 + .../Generic/DialogProspeccaoViewModel.cs | 352 + .../ViewModels/Generic/DialogTarefaViewModel.cs | 296 + .../ViewModels/Generic/DialogTrilhaViewModel.cs | 102 + .../ViewModels/Generic/DialogViewModel.cs | 87 + .../ViewModels/Generic/DialogVinculoViewModel.cs | 257 + .../ViewModels/Generic/ErrorDialogViewModel.cs | 49 + .../ViewModels/Generic/ExtratoComissaoViewModel.cs | 147 + .../ViewModels/Generic/ItemViewModel.cs | 843 ++ .../ViewModels/Generic/ProtocoloViewModel.cs | 30 + .../ViewModels/Generic/ReordenarItensViewModel.cs | 68 + .../ViewModels/Generic/SelecionarItensViewModel.cs | 89 + .../ViewModels/ImportViewModel.cs | 105 + .../ViewModels/LoginImageModel.cs | 24 + .../ViewModels/LoginViewModel.cs | 1495 ++ .../Gestor.Application/ViewModels/MainViewModel.cs | 1273 ++ .../ViewModels/MenuBIViewModel.cs | 12 + .../ViewModels/MenuFerramentasViewModel.cs | 88 + .../ViewModels/MenuItemViewModel.cs | 1048 ++ .../ViewModels/Relatorios/DialogPrintViewModel.cs | 193 + .../ViewModels/Relatorios/RelatorioViewModel.cs | 14619 +++++++++++++++++++ .../ViewModels/Relatorios/SinteticoViewModel.cs | 424 + .../ViewModels/Seguros/ApoliceViewModel.cs | 124 + .../ViewModels/Seguros/ClienteViewModel.cs | 1787 +++ .../ViewModels/Seguros/ConsultaViewModel.cs | 2425 +++ .../ViewModels/Seguros/CriticaApoliceViewModel.cs | 1486 ++ .../Seguros/Itens/AeronauticoViewModel.cs | 554 + .../ViewModels/Seguros/Itens/AutoViewModel.cs | 3018 ++++ .../Seguros/Itens/BuscarModeloViewModel.cs | 95 + .../ViewModels/Seguros/Itens/ConsorcioViewModel.cs | 520 + .../ViewModels/Seguros/Itens/GranizoViewModel.cs | 500 + .../Seguros/Itens/PatrimonialViewModel.cs | 678 + .../Seguros/Itens/RiscosDiversosViewModel.cs | 626 + .../ViewModels/Seguros/Itens/VidaViewModel.cs | 661 + .../ViewModels/Seguros/PerfilEmpresaViewModel.cs | 274 + .../ViewModels/Seguros/PerfilViewModel.cs | 183 + .../ViewModels/Seguros/SinistroViewModel.cs | 2104 +++ .../ViewModels/Seguros/TrocarClienteViewModel.cs | 92 + .../ViewModels/TrilhaViewModel.cs | 284 + .../ViewModels/TutorialViewModel.cs | 612 + 129 files changed, 101655 insertions(+) create mode 100644 Codemerx/Gestor.Application/ViewModels/AnaliticoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Arquivo.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/BI/BISeriesViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/BI/NotasViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/BI/PainelBiViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/BI/ProspeccaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/BI/TarefaBIViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/CoberturaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Comissao/ComissaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Command/RelayCommand.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Configuracoes/ConfiguracoesViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/DashboardViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/AdiantamentoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/AgendaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/AtendimentosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/BoletosNotasViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/ContratosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/InstalacaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ArquivoDigitalViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ExpedicaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ExtratosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ImpostoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/InfoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/LogAcaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/LogEmailViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/LogSistemaAntigoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/LogViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/MetaSeguradoraViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/MetaVendedorViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/PermissaoUsuarioViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/TarefaDrawerViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ValoresApoliceViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/ValoresParcelaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Drawer/VinculoVendedorViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroEmailViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroParceiroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboModelo.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboVariavel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/DownloadViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/EmpresaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/EstipulanteViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/EtiquetaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirRamoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirSeguradoraViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/MalaDiretaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ManutencaoPagamentosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/NotaFiscalViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ProdutoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloDocumentosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloEtiqueta.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/QualificacaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/RamoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/ReciboViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/SeguradoraViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/SocioViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusProspeccaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoTarefaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoVendedorViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/UsuarioViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Ferramentas/VendedorViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/BancosContasViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/CentroDeCustoViewmodel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/ContasDialogModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/CopiarClienteViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/ExtratoContaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/FinanceiroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/FornecedorViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/InfoExtratoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/MenuFinanceiroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/PlanoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/PlanosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/Relatorios/FechamentoFinanceiroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Financeiro/TranferenciaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/BaseViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/ItemViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/ImportViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/LoginImageModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/LoginViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/MainViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/MenuBIViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/MenuFerramentasViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/MenuItemViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Relatorios/DialogPrintViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Relatorios/RelatorioViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Relatorios/SinteticoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/ApoliceViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/ClienteViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/ConsultaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/CriticaApoliceViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AeronauticoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AutoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/BuscarModeloViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/ConsorcioViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/GranizoViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/PatrimonialViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/RiscosDiversosViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/Itens/VidaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/PerfilEmpresaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/PerfilViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/SinistroViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/Seguros/TrocarClienteViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/TrilhaViewModel.cs create mode 100644 Codemerx/Gestor.Application/ViewModels/TutorialViewModel.cs (limited to 'Codemerx/Gestor.Application/ViewModels') diff --git a/Codemerx/Gestor.Application/ViewModels/AnaliticoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/AnaliticoViewModel.cs new file mode 100644 index 0000000..bdf394b --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/AnaliticoViewModel.cs @@ -0,0 +1,210 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.BI; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Data; + +namespace Gestor.Application.ViewModels +{ + internal class AnaliticoViewModel : BaseSegurosViewModel + { + private string _head; + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public TipoTela Tela { get; set; } = 1; + + public string Tipo + { + get; + set; + } + + public AnaliticoViewModel(string tipo) + { + this.Tipo = tipo; + string str = this.Tipo; + if (str == "PARCELAS") + { + this.Tela = 5; + return; + } + if (str != "APOLICES") + { + this.Tela = 1; + return; + } + this.Tela = 2; + } + + private async Task GerarHtml(DataGrid grid) + { + PropertyInfo[] properties = typeof(Analitico).GetProperties(); + List list = ( + from x in (IEnumerable)properties + select x.Name).ToList(); + List strs = new List(); + for (int i = 0; i < grid.Columns.Count; i++) + { + if (!(grid.Columns[i] is DataGridTemplateColumn)) + { + Binding binding = (grid.Columns[i] as DataGridBoundColumn).Binding as Binding; + strs.Add(binding.Path.Path); + } + } + List list1 = list.Except(strs).ToList(); + IEnumerable analiticos = grid.Items.Cast(); + string str = await Funcoes.GenerateTable(( + from x in analiticos + where x.get_Selecionado() + select x).ToList(), list1, false, true, "", null); + string str1 = Funcoes.CreateCard("", str, false); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome(string.Concat("ANALÍTICO - ", this.Head)); + string str2 = str1; + if (str2 == null) + { + str2 = ""; + } + string str3 = Funcoes.ExportarHtml(tipoRelatorio, str2, "60", "landscape", false, ""); + return str3; + } + + public async Task Print(DataGrid grid) + { + IEnumerable analiticos = grid.Items.Cast(); + if (analiticos.Any((Analitico x) => x.get_Selecionado())) + { + string str = await this.GerarHtml(grid); + if (!string.IsNullOrEmpty(str)) + { + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(this.Head, ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + } + } + else + { + await base.ShowMessage("É NECESSÁRIO SELECIONAR AO MENOS UM DOCUMENTO", "OK", "", false); + } + } + + public async Task Salvar(Trilha destino) + { + Trilha trilha; + List fases = destino.get_Fases(); + TarefaServico tarefaServico = new TarefaServico(); + Trilha trilha1 = await tarefaServico.Salvar(destino); + if (tarefaServico.Sucesso) + { + fases.ForEach((Fase x) => x.set_Trilha(trilha1)); + fases = await tarefaServico.Salvar(fases); + if (tarefaServico.Sucesso) + { + trilha1.set_Fases(fases); + trilha = trilha1; + } + else + { + trilha = null; + } + } + else + { + trilha = null; + } + fases = null; + tarefaServico = null; + return trilha; + } + + public async Task Save(List tarefas) + { + await (new TarefaServico()).Salvar(tarefas); + } + + public async Task> Validar(List analitico, Trilha trilha) + { + List list; + List analiticos; + TarefaServico tarefaServico = new TarefaServico(); + string tipo = this.Tipo; + if (tipo == "CLIENTES") + { + List analiticos1 = analitico; + list = ( + from x in analiticos1 + select x.get_Cliente().get_Id()).ToList(); + } + else if (tipo == "PARCELAS" || tipo == "COMISSÃO") + { + List analiticos2 = analitico; + list = ( + from x in analiticos2 + select x.get_Parcela().get_Id()).ToList(); + } + else + { + List analiticos3 = analitico; + list = ( + from x in analiticos3 + select x.get_Documento().get_Id()).ToList(); + } + List nums = await tarefaServico.Validar(list, trilha.get_Id()); + List nums1 = nums; + tipo = this.Head; + if (tipo == "CLIENTES") + { + analiticos = ( + from x in analitico + where nums1.Contains(x.get_Cliente().get_Id()) + select x).ToList(); + } + else + { + analiticos = (tipo == "PARCELAS" || tipo == "COMISSÃO" ? ( + from x in analitico + where nums1.Contains(x.get_Parcela().get_Id()) + select x).ToList() : ( + from x in analitico + where nums1.Contains(x.get_Documento().get_Id()) + select x).ToList()); + } + List list1 = analitico.Except(analiticos).ToList(); + return list1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Arquivo.cs b/Codemerx/Gestor.Application/ViewModels/Arquivo.cs new file mode 100644 index 0000000..5a1d80e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Arquivo.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels +{ + public class Arquivo + { + public string Nome + { + get; + set; + } + + public int Processo + { + get; + set; + } + + public Arquivo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/BI/BISeriesViewModel.cs b/Codemerx/Gestor.Application/ViewModels/BI/BISeriesViewModel.cs new file mode 100644 index 0000000..0d5a5f0 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/BI/BISeriesViewModel.cs @@ -0,0 +1,70 @@ +using Gestor.Application.ViewModels.Generic; +using LiveCharts; +using System; + +namespace Gestor.Application.ViewModels.BI +{ + public class BISeriesViewModel : BaseSegurosViewModel + { + private int _indice; + + private string _titulo; + + private SeriesCollection _serie; + + public int Indice + { + get + { + return this._indice; + } + set + { + if (this._indice == value) + { + return; + } + this._indice = value; + base.OnPropertyChanged("Indice"); + } + } + + public SeriesCollection Serie + { + get + { + return this._serie; + } + set + { + if ((object)this._serie == (object)value) + { + return; + } + this._serie = value; + base.OnPropertyChanged("Serie"); + } + } + + public string Titulo + { + get + { + return this._titulo; + } + set + { + if (this._titulo == value) + { + return; + } + this._titulo = value; + base.OnPropertyChanged("Titulo"); + } + } + + public BISeriesViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/BI/NotasViewModel.cs b/Codemerx/Gestor.Application/ViewModels/BI/NotasViewModel.cs new file mode 100644 index 0000000..dca2d31 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/BI/NotasViewModel.cs @@ -0,0 +1,311 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.BI +{ + public class NotasViewModel : BaseSegurosViewModel + { + private readonly TarefaServico _servico; + + private bool _enableIncluirNota = true; + + private bool _ocultarUsuarios; + + private ObservableCollection _usuarios; + + private Usuario _selectedUsuario; + + private Gestor.Model.Domain.Ferramentas.Tarefa _tarefa; + + private ObservableCollection _notas; + + private ObservableCollection _notasConcluidas; + + private Gestor.Model.Domain.Ferramentas.Tarefa _selectedNota; + + private bool _ocultarNotasConcluidas = true; + + public bool EnableIncluirNota + { + get + { + return this._enableIncluirNota; + } + set + { + this._enableIncluirNota = value; + base.OnPropertyChanged("EnableIncluirNota"); + } + } + + public ObservableCollection Notas + { + get + { + return this._notas; + } + set + { + this._notas = value; + base.OnPropertyChanged("Notas"); + } + } + + public ObservableCollection NotasConcluidas + { + get + { + return this._notasConcluidas; + } + set + { + this._notasConcluidas = value; + base.OnPropertyChanged("NotasConcluidas"); + } + } + + public bool OcultarNotasConcluidas + { + get + { + return this._ocultarNotasConcluidas; + } + set + { + this._ocultarNotasConcluidas = value; + base.OnPropertyChanged("OcultarNotasConcluidas"); + } + } + + public bool OcultarUsuarios + { + get + { + return this._ocultarUsuarios; + } + set + { + this._ocultarUsuarios = value; + base.OnPropertyChanged("OcultarUsuarios"); + } + } + + public Gestor.Model.Domain.Ferramentas.Tarefa SelectedNota + { + get + { + return this._selectedNota; + } + set + { + this._selectedNota = value; + base.OnPropertyChanged("SelectedNota"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + this.Carregar(); + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public Gestor.Model.Domain.Ferramentas.Tarefa Tarefa + { + get + { + return this._tarefa; + } + set + { + this._tarefa = value; + base.OnPropertyChanged("Tarefa"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public NotasViewModel() + { + bool administrador; + bool id; + this._servico = new TarefaServico(); + this.Usuarios = new ObservableCollection(Recursos.Usuarios.Where((Usuario x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + this.SelectedUsuario = this.Usuarios.FirstOrDefault((Usuario x) => x.get_Id() == Recursos.Usuario.get_Id()); + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + administrador = usuario.get_Administrador(); + } + else + { + administrador = false; + } + this.OcultarUsuarios = administrador; + Usuario usuario1 = Recursos.Usuario; + if (usuario1 != null) + { + id = usuario1.get_Id() > (long)0; + } + else + { + id = false; + } + this.EnableIncluirNota = id; + } + + public async Task AdicionarNota() + { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa; + if (this.Notas != null) + { + ObservableCollection notas = this.Notas; + if (notas.Any((Gestor.Model.Domain.Ferramentas.Tarefa x) => { + if (x.get_Titulo() != "TÍTULO") + { + return false; + } + return x.get_Descricao() == "DESCRIÇÃO"; + })) + { + await base.ShowMessage("PARA ADICIONAR OUTRA NOTA, INSERIR TÍTULO E DESCRIÇÃO DA NOTA JÁ ADICIONADA", "OK", "", false); + tarefa = null; + return; + } + } + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa1.set_Agendamento(Funcoes.GetNetworkTime()); + tarefa1.set_Titulo("TÍTULO"); + tarefa1.set_Anotacoes("DESCRIÇÃO"); + tarefa1.set_Usuario(this.Usuarios.First((Usuario x) => x.get_Id() == this.SelectedUsuario.get_Id())); + tarefa1.set_UsuarioCadastro(Recursos.Usuario); + tarefa1.set_Entidade(1); + tarefa1.set_Status(0); + tarefa = tarefa1; + tarefa = await this._servico.Salvar(tarefa); + await this.CarregarNotas(); + this.SelectedNota = tarefa; + tarefa = null; + } + + public async void Carregar() + { + await this.CarregarNotas(); + } + + public async Task CarregarNotas() + { + if (this.SelectedUsuario != null) + { + List tarefas = await this._servico.BuscarNotas(this.SelectedUsuario.get_Id()); + List tarefas1 = tarefas; + tarefas1.ForEach((Gestor.Model.Domain.Ferramentas.Tarefa x) => { + if (x.get_Titulo() == "TÍTULO" && x.get_Descricao() == "DESCRIÇÃO") + { + x.set_HabilitarPublica(true); + } + }); + this.Notas = new ObservableCollection(tarefas); + this.NotasConcluidas = new ObservableCollection(await this._servico.BuscarNotasConcluidas(this.SelectedUsuario.get_Id())); + } + } + + public async Task ExcluirNota(Gestor.Model.Domain.Ferramentas.Tarefa nota) + { + await this._servico.Excluir(nota.get_Id()); + } + + public async Task>> Salvar(Gestor.Model.Domain.Ferramentas.Tarefa destino) + { + List> keyValuePairs; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = destino; + List configuracoes = Recursos.Configuracoes; + tarefa.set_AgendamentoRetroativo(configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs1 = destino.Validate(); + if (keyValuePairs1.Count <= 0) + { + bool publica = destino.get_Publica(); + await this._servico.Salvar(destino); + if (this._servico.Sucesso) + { + if (publica) + { + long id = destino.get_Usuario().get_Id(); + List usuarios = Recursos.Usuarios; + List tasks = new List(); + foreach (Usuario usuario in usuarios) + { + if (id == usuario.get_Id()) + { + continue; + } + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = (Gestor.Model.Domain.Ferramentas.Tarefa)destino.Clone(); + tarefa1.set_Id((long)0); + tarefa1.set_Usuario(usuario); + tasks.Add(this._servico.Salvar(tarefa1)); + } + await Task.WhenAll(tasks); + } + await this.CarregarNotas(); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + public async Task SalvarNota(Gestor.Model.Domain.Ferramentas.Tarefa nota) + { + return await this._servico.Salvar(nota); + } + + public void ToggleNotasConcluidas() + { + this.OcultarNotasConcluidas = !this.OcultarNotasConcluidas; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/BI/PainelBiViewModel.cs b/Codemerx/Gestor.Application/ViewModels/BI/PainelBiViewModel.cs new file mode 100644 index 0000000..99695e4 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/BI/PainelBiViewModel.cs @@ -0,0 +1,1590 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.BI; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Seguros; +using LiveCharts; +using LiveCharts.Defaults; +using LiveCharts.Definitions.Series; +using LiveCharts.Helpers; +using LiveCharts.Wpf; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.BI +{ + public class PainelBiViewModel : BaseSegurosViewModel + { + private readonly ClienteServico _clienteServico; + + private readonly ApoliceServico _apoliceServico; + + private readonly ParcelaServico _parcelaServico; + + private Visibility _isVisibleProducao = Visibility.Collapsed; + + private Visibility _isVisibleClientes = Visibility.Collapsed; + + private Visibility _isVisiblePendencia = Visibility.Collapsed; + + private Visibility _isVisibleVencimento = Visibility.Collapsed; + + private DateTime _inicio; + + private DateTime _fim; + + private DateTime _inicioClientes; + + private DateTime _fimClientes; + + private DateTime _inicioVencimento; + + private DateTime _fimVencimento; + + private Grafico _producao; + + private Grafico _fechamento; + + private int _aniversariantes; + + private int _vencimentoCnh; + + private int _vencimentos; + + private int _parcelasPendentes; + + private int _parcelasAVencer; + + private int _cotacoes; + + private List _parcelasPendencia; + + private List _parcelasVencimento; + + private List _documentosVencimento; + + private List _clientesAniversariantes; + + private List _clientesCnh; + + private int _quatidadeProducao; + + private int _endossos; + + private int _faturas; + + private int _apolicesPendentes; + + private int _novosNegocios; + + private int _renovacoes; + + private int _cancelamentos; + + private decimal _producaoTotal; + + private decimal _producaoTotalAnterior; + + private decimal _comissaoTotal; + + private List _documentosProducao; + + private List _documentosPendentes; + + private List _documentosFechamento; + + private Grafico _gerada; + + private Grafico _mediaComissao; + + private Func _yFormatter; + + private Func _xFormatter; + + public int Aniversariantes + { + get + { + return this._aniversariantes; + } + set + { + this._aniversariantes = value; + base.OnPropertyChanged("Aniversariantes"); + } + } + + public int ApolicesPendentes + { + get + { + return this._apolicesPendentes; + } + set + { + this._apolicesPendentes = value; + base.OnPropertyChanged("ApolicesPendentes"); + } + } + + public int Cancelamentos + { + get + { + return this._cancelamentos; + } + set + { + this._cancelamentos = value; + base.OnPropertyChanged("Cancelamentos"); + } + } + + public decimal ComissaoTotal + { + get + { + return this._comissaoTotal; + } + set + { + this._comissaoTotal = value; + base.OnPropertyChanged("ComissaoTotal"); + } + } + + public int Cotacoes + { + get + { + return this._cotacoes; + } + set + { + this._cotacoes = value; + base.OnPropertyChanged("Cotacoes"); + } + } + + public int Endossos + { + get + { + return this._endossos; + } + set + { + this._endossos = value; + base.OnPropertyChanged("Endossos"); + } + } + + public int Faturas + { + get + { + return this._faturas; + } + set + { + this._faturas = value; + base.OnPropertyChanged("Faturas"); + } + } + + public Grafico Fechamento + { + get + { + return this._fechamento; + } + set + { + this._fechamento = value; + base.OnPropertyChanged("Fechamento"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public DateTime FimClientes + { + get + { + return this._fimClientes; + } + set + { + this._fimClientes = value; + base.OnPropertyChanged("FimClientes"); + } + } + + public DateTime FimVencimento + { + get + { + return this._fimVencimento; + } + set + { + this._fimVencimento = value; + base.OnPropertyChanged("FimVencimento"); + } + } + + public Grafico Gerada + { + get + { + return this._gerada; + } + set + { + this._gerada = value; + base.OnPropertyChanged("Gerada"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public DateTime InicioClientes + { + get + { + return this._inicioClientes; + } + set + { + this._inicioClientes = value; + base.OnPropertyChanged("InicioClientes"); + } + } + + public DateTime InicioVencimento + { + get + { + return this._inicioVencimento; + } + set + { + this._inicioVencimento = value; + base.OnPropertyChanged("InicioVencimento"); + } + } + + public Visibility IsVisibleClientes + { + get + { + return this._isVisibleClientes; + } + set + { + this._isVisibleClientes = value; + base.OnPropertyChanged("IsVisibleClientes"); + } + } + + public Visibility IsVisiblePendencia + { + get + { + return this._isVisiblePendencia; + } + set + { + this._isVisiblePendencia = value; + base.OnPropertyChanged("IsVisiblePendencia"); + } + } + + public Visibility IsVisibleProducao + { + get + { + return this._isVisibleProducao; + } + set + { + this._isVisibleProducao = value; + base.OnPropertyChanged("IsVisibleProducao"); + } + } + + public Visibility IsVisibleVencimento + { + get + { + return this._isVisibleVencimento; + } + set + { + this._isVisibleVencimento = value; + base.OnPropertyChanged("IsVisibleVencimento"); + } + } + + public Grafico MediaComissao + { + get + { + return this._mediaComissao; + } + set + { + this._mediaComissao = value; + base.OnPropertyChanged("MediaComissao"); + } + } + + public int NovosNegocios + { + get + { + return this._novosNegocios; + } + set + { + this._novosNegocios = value; + base.OnPropertyChanged("NovosNegocios"); + } + } + + public int ParcelasAVencer + { + get + { + return this._parcelasAVencer; + } + set + { + this._parcelasAVencer = value; + base.OnPropertyChanged("ParcelasAVencer"); + } + } + + public int ParcelasPendentes + { + get + { + return this._parcelasPendentes; + } + set + { + this._parcelasPendentes = value; + base.OnPropertyChanged("ParcelasPendentes"); + } + } + + public Grafico Producao + { + get + { + return this._producao; + } + set + { + this._producao = value; + base.OnPropertyChanged("Producao"); + } + } + + public decimal ProducaoTotal + { + get + { + return this._producaoTotal; + } + set + { + this._producaoTotal = value; + base.OnPropertyChanged("ProducaoTotal"); + } + } + + public decimal ProducaoTotalAnterior + { + get + { + return this._producaoTotalAnterior; + } + set + { + this._producaoTotalAnterior = value; + base.OnPropertyChanged("ProducaoTotalAnterior"); + } + } + + public int QuatidadeProducao + { + get + { + return this._quatidadeProducao; + } + set + { + this._quatidadeProducao = value; + base.OnPropertyChanged("QuatidadeProducao"); + } + } + + public int Renovacoes + { + get + { + return this._renovacoes; + } + set + { + this._renovacoes = value; + base.OnPropertyChanged("Renovacoes"); + } + } + + public int VencimentoCnh + { + get + { + return this._vencimentoCnh; + } + set + { + this._vencimentoCnh = value; + base.OnPropertyChanged("VencimentoCnh"); + } + } + + public int Vencimentos + { + get + { + return this._vencimentos; + } + set + { + this._vencimentos = value; + base.OnPropertyChanged("Vencimentos"); + } + } + + public Func XFormatter + { + get + { + return this._xFormatter; + } + set + { + this._xFormatter = value; + base.OnPropertyChanged("XFormatter"); + } + } + + public Func YFormatter + { + get + { + return this._yFormatter; + } + set + { + this._yFormatter = value; + base.OnPropertyChanged("YFormatter"); + } + } + + public PainelBiViewModel() + { + this._isVisibleProducao = Visibility.Collapsed; + this._isVisibleClientes = Visibility.Collapsed; + this._isVisiblePendencia = Visibility.Collapsed; + this._isVisibleVencimento = Visibility.Collapsed; + DateTime date = Funcoes.GetNetworkTime().Date; + this._inicio = date.AddDays(-7); + this._fim = Funcoes.GetNetworkTime().Date; + date = Funcoes.GetNetworkTime().Date; + this._inicioClientes = date.AddDays(-7); + this._fimClientes = Funcoes.GetNetworkTime().Date; + this._inicioVencimento = Funcoes.GetNetworkTime().Date; + date = Funcoes.GetNetworkTime().Date; + this._fimVencimento = date.AddDays(7); + base(); + this._clienteServico = new ClienteServico(); + this._apoliceServico = new ApoliceServico(); + this._parcelaServico = new ParcelaServico(); + this.LoadInicial(); + } + + public async void Detalhar(int tipo) + { + List list; + string str = ""; + string str1 = "APOLICES"; + List strs = new List() + { + "Nome", + "Apolice", + "Endosso", + "Status", + "Negocio", + "VigenciaInicial", + "VigenciaFinal", + "Comissao", + "PremioLiquido", + "PremioTotal", + "Seguradora", + "Ramo" + }; + List strs1 = strs; + switch (tipo) + { + case 1: + { + str = "COMPARATIVO"; + List documentos = this._documentosProducao; + List documentos1 = this._documentosFechamento; + List documentos2 = new List(); + documentos2.AddRange(documentos); + documentos2.AddRange(documentos1); + IOrderedEnumerable vigencia1 = + from x in documentos2 + orderby x.get_Vigencia1() + select x; + list = vigencia1.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 2: + { + str = "NOVOS NEGÓCIOS"; + List documentos3 = this._documentosProducao; + IEnumerable documentos4 = documentos3.Where((Documento x) => { + if (x.get_Tipo() != 0) + { + return false; + } + if (x.get_Situacao() == 1) + { + return true; + } + if (x.get_Situacao() != 2) + { + return false; + } + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + return negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue; + }); + IOrderedEnumerable vigencia11 = + from x in documentos4 + orderby x.get_Vigencia1() + select x; + list = vigencia11.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 3: + { + str = "RENOVAÇÕES"; + List documentos5 = this._documentosProducao; + IEnumerable documentos6 = documentos5.Where((Documento x) => { + if (x.get_Tipo() != 0) + { + return false; + } + if (x.get_Situacao() != 2) + { + return false; + } + if (x.get_NegocioCorretora().GetValueOrDefault() == 1) + { + return true; + } + return x.get_Negocio().GetValueOrDefault() == 1; + }); + IOrderedEnumerable vigencia12 = + from x in documentos6 + orderby x.get_Vigencia1() + select x; + list = vigencia12.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 4: + { + str = "CANCELAMENTOS"; + List documentos7 = this._documentosProducao; + IEnumerable documentos8 = documentos7.Where((Documento x) => { + if (x.get_Situacao() != 3) + { + return false; + } + return x.get_Tipo() == 1; + }); + IOrderedEnumerable vigencia13 = + from x in documentos8 + orderby x.get_Vigencia1() + select x; + list = vigencia13.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 5: + { + str1 = "CLIENTES"; + List strs2 = new List() + { + "Nome", + "DocumentoCliente", + "Dia/Mês", + "Nascimento", + "TipoPessoa", + "Cidade", + "Uf", + "Cep", + "Telefone", + "E-mail", + "Profissão" + }; + strs1 = strs2; + List clientesAtivosInativos = this._clientesAniversariantes; + list = clientesAtivosInativos.Select((ClientesAtivosInativos x) => { + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Nome() ?? ""); + analitico.set_DocumentoCliente(x.get_Documento()); + analitico.set_DiaMes(x.get_Aniversario()); + analitico.set_TipoPessoa((ValidationHelper.OnlyNumber(x.get_Documento()).Length > 11 ? "JURÍDICA" : "FÍSICA")); + analitico.set_Nascimento(x.get_Nascimento()); + analitico.set_VencimentoHabilitacao(x.get_VencimentoCnh()); + analitico.set_Cliente(x); + analitico.set_Cidade(x.get_Cidade()); + analitico.set_Uf(x.get_Estado()); + analitico.set_Cep(x.get_Cep()); + analitico.set_Telefone(x.get_Telefone()); + analitico.set_Email(x.get_Email()); + analitico.set_Profissao(x.get_Profissao()); + return analitico; + }).ToList(); + break; + } + case 6: + { + str1 = "CLIENTES"; + strs1 = new List() + { + "Nome", + "DocumentoCliente", + "Nascimento", + "VencimentoHabilitacao" + }; + List clientesAtivosInativos1 = this._clientesCnh; + list = clientesAtivosInativos1.Select((ClientesAtivosInativos x) => { + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Nome() ?? ""); + analitico.set_DocumentoCliente(x.get_Documento()); + analitico.set_Nascimento(x.get_Nascimento()); + analitico.set_VencimentoHabilitacao(x.get_VencimentoCnh()); + analitico.set_Cliente(x); + return analitico; + }).ToList(); + break; + } + case 7: + { + str = "APÓLICES À VENCER"; + List documentos9 = this._documentosVencimento; + IOrderedEnumerable vigencia14 = + from x in documentos9 + orderby x.get_Vigencia1() + select x; + list = vigencia14.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 8: + { + List strs3 = new List() + { + "Nome", + "Apolice", + "Endosso", + "Seguradora", + "Comissao", + "Vencimento", + "Recebimento", + "Valor", + "ComissaoGerada", + "NumeroParcela", + "Ramo" + }; + strs1 = strs3; + str = "PARCELAS À VENCER"; + str1 = "PARCELAS"; + List parcelas = this._parcelasVencimento; + IOrderedEnumerable vencimento = + from x in parcelas + orderby x.get_Vencimento() + select x; + list = vencimento.Select((Parcela x) => { + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Documento().get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Documento().get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + analitico.set_Seguradora(x.get_Documento().get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + analitico.set_Vencimento(x.get_Vencimento()); + analitico.set_Recebimento(x.get_DataRecebimento()); + analitico.set_Valor(x.get_Valor()); + analitico.set_ValorComissao(x.get_ValorComDesconto()); + analitico.set_NumeroParcela(x.get_NumeroParcela()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x.get_Documento()); + analitico.set_Parcela(x); + return analitico; + }).ToList(); + break; + } + case 9: + { + str = "APÓLICES PENDENTES"; + List documentos10 = this._documentosPendentes; + IEnumerable documentos11 = documentos10.Where((Documento x) => { + if (!string.IsNullOrEmpty(x.get_Apolice())) + { + return false; + } + return x.get_Tipo() != 2; + }); + IOrderedEnumerable vigencia15 = + from x in documentos11 + orderby x.get_Vigencia1() + select x; + list = vigencia15.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 10: + { + List strs4 = new List() + { + "Nome", + "Apolice", + "Endosso", + "Seguradora", + "Comissao", + "Vencimento", + "Valor", + "NumeroParcela", + "Ramo" + }; + strs1 = strs4; + str = "PARCELAS PENDENTES"; + str1 = "PARCELAS"; + List parcelas1 = this._parcelasPendencia; + IOrderedEnumerable vencimento1 = + from x in parcelas1 + orderby x.get_Vencimento() + select x; + list = vencimento1.Select((Parcela x) => { + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Documento().get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Documento().get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + analitico.set_Seguradora(x.get_Documento().get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + analitico.set_Vencimento(x.get_Vencimento()); + analitico.set_Recebimento(x.get_DataRecebimento()); + analitico.set_Valor(x.get_Valor()); + analitico.set_ValorComissao(x.get_ValorComissao()); + analitico.set_NumeroParcela(x.get_NumeroParcela()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x.get_Documento()); + analitico.set_Parcela(x); + return analitico; + }).ToList(); + break; + } + case 11: + { + str = "ENDOSSOS"; + List documentos12 = this._documentosProducao; + IEnumerable documentos13 = + from x in documentos12 + where x.get_Tipo() == 1 + select x; + IOrderedEnumerable vigencia16 = + from x in documentos13 + orderby x.get_Vigencia1() + select x; + list = vigencia16.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 12: + { + str = "FATURAS"; + List documentos14 = this._documentosProducao; + IEnumerable documentos15 = + from x in documentos14 + where x.get_Tipo() == 2 + select x; + IOrderedEnumerable vigencia17 = + from x in documentos15 + orderby x.get_Vigencia1() + select x; + list = vigencia17.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 13: + { + str = "TOTAL DOCUMENTOS"; + List documentos16 = this._documentosProducao; + IEnumerable documentos17 = + from x in documentos16 + where x.get_Tipo() != 2 + select x; + IOrderedEnumerable vigencia18 = + from x in documentos17 + orderby x.get_Vigencia1() + select x; + list = vigencia18.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + case 14: + { + str = "PRODUÇÃO ANTERIOR"; + List documentos18 = this._documentosFechamento; + list = documentos18.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + default: + { + str = "PRODUÇÃO"; + List documentos19 = this._documentosProducao; + list = documentos19.Select((Documento x) => { + object description; + Analitico analitico = new Analitico(); + analitico.set_Nome(x.get_Controle().get_Cliente().get_Nome() ?? ""); + analitico.set_Apolice(x.get_Apolice() ?? ""); + analitico.set_Endosso(x.get_Endosso() ?? ""); + analitico.set_Comissao(x.get_Comissao()); + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + if (!negocioCorretora.HasValue) + { + description = ValidationHelper.GetDescription(x.get_Negocio()); + } + else + { + negocioCorretora = x.get_NegocioCorretora(); + description = (negocioCorretora.HasValue ? ValidationHelper.GetDescription(negocioCorretora.GetValueOrDefault()) : null) ?? ""; + } + analitico.set_Negocio((string)description); + analitico.set_PremioLiquido(x.get_PremioLiquido()); + analitico.set_PremioTotal(x.get_PremioTotal()); + analitico.set_VigenciaFinal(x.get_Vigencia2()); + analitico.set_VigenciaInicial(x.get_Vigencia1()); + analitico.set_Status(ValidationHelper.GetDescription(x.get_Situacao()) ?? ""); + analitico.set_Seguradora(x.get_Controle().get_Seguradora().get_NomeSocial()); + analitico.set_Ramo(x.get_Controle().get_Ramo().get_Nome()); + ClientesAtivosInativos clientesAtivosInativo = new ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(x.get_Controle().get_Cliente().get_Id()); + clientesAtivosInativo.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + analitico.set_Cliente(clientesAtivosInativo); + analitico.set_Documento(x); + return analitico; + }).ToList(); + break; + } + } + if (list.Count != 0) + { + (new HosterWindow(new DialogAnaliticoBi(str, list, str1, strs1), "ANALÍTICO", new double?((double)1260), new double?((double)500), false)).Show(); + } + else + { + await base.ShowMessage("NÃO FOI POSSÍVEL DETALHAR POIS NÃO HÁ DADOS", "OK", "", false); + } + } + + public async Task GerarClientes() + { + long num; + this.IsVisibleClientes = Visibility.Collapsed; + Filtros filtro = new Filtros(); + filtro.set_Inicio(this.InicioClientes); + filtro.set_Fim(this.FimClientes); + num = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + filtro.set_IdEmpresa(num); + Filtros filtro1 = filtro; + this._clientesAniversariantes = await this._clienteServico.BuscarAniversariantes(filtro1); + this.Aniversariantes = this._clientesAniversariantes.Count; + this._clientesCnh = await this._clienteServico.BuscarVencimentosCnh(filtro1); + this.VencimentoCnh = this._clientesCnh.Count; + this.IsVisibleClientes = Visibility.Visible; + filtro1 = null; + } + + public async Task GerarPendencia() + { + long num; + this.IsVisiblePendencia = Visibility.Collapsed; + List vendedorUsuarios = await (new VendedorUsuarioServico()).FindByVinculo(Recursos.Usuario); + Filtros filtro = new Filtros(); + filtro.set_Inicio(this.Inicio); + filtro.set_Fim(this.Fim); + num = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + filtro.set_IdEmpresa(num); + List vendedorUsuarios1 = vendedorUsuarios; + filtro.set_Vendedores(( + from x in vendedorUsuarios1 + select x.get_Vendedor().get_Id()).ToList()); + List parcelas = await this._parcelaServico.BuscarParcelasPendentes(filtro, false); + PainelBiViewModel list = this; + List parcelas1 = parcelas; + list._parcelasPendencia = ( + from x in parcelas1 + where x.get_Documento().get_Situacao() != 7 + select x).ToList(); + this.ParcelasPendentes = this._parcelasPendencia.Count; + this.IsVisiblePendencia = Visibility.Visible; + } + + public async Task GerarProducao() + { + long num2; + long num3; + this.IsVisibleProducao = Visibility.Collapsed; + PainelBiViewModel painelBiViewModel = this; + Grafico grafico = new Grafico() + { + Series = new SeriesCollection(), + Formatter = (double value) => value.ToString("C0") + }; + painelBiViewModel.Producao = grafico; + PainelBiViewModel painelBiViewModel1 = this; + Grafico grafico1 = new Grafico() + { + Series = new SeriesCollection(), + Formatter = (double value) => value.ToString("C2") + }; + painelBiViewModel1.Gerada = grafico1; + PainelBiViewModel painelBiViewModel2 = this; + Grafico grafico2 = new Grafico() + { + Series = new SeriesCollection(), + Formatter = (double value) => value.ToString("P2") + }; + painelBiViewModel2.MediaComissao = grafico2; + PainelBiViewModel painelBiViewModel3 = this; + Grafico grafico3 = new Grafico() + { + Series = new SeriesCollection(), + Formatter = (double value) => value.ToString("C2") + }; + painelBiViewModel3.Fechamento = grafico3; + List vendedorUsuarios = await (new VendedorUsuarioServico()).FindByVinculo(Recursos.Usuario); + Filtros filtro = new Filtros(); + filtro.set_Inicio(this.Inicio); + filtro.set_Fim(this.Fim); + num2 = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + filtro.set_IdEmpresa(num2); + List vendedorUsuarios1 = vendedorUsuarios; + filtro.set_Vendedores(( + from x in vendedorUsuarios1 + select x.get_Vendedor().get_Id()).ToList()); + Filtros filtro1 = filtro; + Filtros filtro2 = new Filtros(); + DateTime inicio = this.Inicio; + filtro2.set_Inicio(inicio.AddYears(-1)); + inicio = this.Fim; + filtro2.set_Fim(inicio.AddYears(-1)); + num3 = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + filtro2.set_IdEmpresa(num3); + List vendedorUsuarios2 = vendedorUsuarios; + filtro2.set_Vendedores(( + from x in vendedorUsuarios2 + select x.get_Vendedor().get_Id()).ToList()); + Filtros filtro3 = filtro2; + List documentos = await this._apoliceServico.BuscarApolices(filtro1, false, true); + PainelBiViewModel list = this; + List documentos1 = documentos; + list._documentosProducao = ( + from x in documentos1 + where x.get_Situacao() != 7 + select x).ToList(); + this._documentosPendentes = await this._apoliceServico.BuscarApolicesPendentes(filtro1); + List documentos2 = await this._parcelaServico.BuscarFaturas(filtro1, false, true); + List documentos3 = this._documentosProducao; + List documentos4 = documentos2; + documentos3.AddRange( + from x in documentos4 + where x.get_Situacao() != 7 + select x); + PainelBiViewModel painelBiViewModel4 = this; + List documentos5 = this._documentosPendentes; + painelBiViewModel4.ApolicesPendentes = documentos5.Count((Documento x) => { + if (!string.IsNullOrEmpty(x.get_Apolice())) + { + return false; + } + return x.get_Tipo() != 2; + }); + await this.GerarPendencia(); + List documentos6 = await this._apoliceServico.BuscarApolices(filtro3, false, true); + PainelBiViewModel list1 = this; + List documentos7 = documentos6; + list1._documentosFechamento = ( + from x in documentos7 + where x.get_Situacao() != 7 + select x).ToList(); + List documentos8 = await this._parcelaServico.BuscarFaturas(filtro3, false, true); + List documentos9 = this._documentosFechamento; + List documentos10 = documentos8; + documentos9.AddRange( + from x in documentos10 + where x.get_Situacao() != 7 + select x); + this.Cotacoes = await this._apoliceServico.Cotacoes(filtro1); + PainelBiViewModel painelBiViewModel5 = this; + List documentos11 = this._documentosProducao; + painelBiViewModel5.QuatidadeProducao = documentos11.Count((Documento x) => x.get_Tipo() != 2); + PainelBiViewModel painelBiViewModel6 = this; + List documentos12 = this._documentosProducao; + painelBiViewModel6.Faturas = documentos12.Count((Documento x) => x.get_Tipo() == 2); + PainelBiViewModel painelBiViewModel7 = this; + List documentos13 = this._documentosProducao; + painelBiViewModel7.NovosNegocios = documentos13.Count((Documento x) => { + if (x.get_Tipo() != 0) + { + return false; + } + if (x.get_Situacao() == 1) + { + return true; + } + if (x.get_Situacao() != 2) + { + return false; + } + NegocioCorretora? negocioCorretora = x.get_NegocioCorretora(); + return negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue; + }); + PainelBiViewModel painelBiViewModel8 = this; + List documentos14 = this._documentosProducao; + painelBiViewModel8.Renovacoes = documentos14.Count((Documento x) => { + if (x.get_Tipo() != 0) + { + return false; + } + if (x.get_Situacao() != 2) + { + return false; + } + if (x.get_NegocioCorretora().GetValueOrDefault() == 1) + { + return true; + } + return x.get_Negocio().GetValueOrDefault() == 1; + }); + PainelBiViewModel painelBiViewModel9 = this; + List documentos15 = this._documentosProducao; + IEnumerable documentos16 = documentos15.Where((Documento x) => { + if (x.get_Situacao() != 3) + { + return false; + } + return x.get_Tipo() == 1; + }); + painelBiViewModel9.Cancelamentos = ( + from x in documentos16 + select x.get_Controle().get_Id()).Distinct().Count(); + PainelBiViewModel painelBiViewModel10 = this; + List documentos17 = this._documentosProducao; + painelBiViewModel10.Endossos = documentos17.Count((Documento x) => x.get_Tipo() == 1); + PainelBiViewModel painelBiViewModel11 = this; + List documentos18 = this._documentosProducao; + painelBiViewModel11.ProducaoTotal = documentos18.Sum((Documento x) => x.get_PremioLiquido()); + PainelBiViewModel painelBiViewModel12 = this; + List documentos19 = this._documentosFechamento; + painelBiViewModel12.ProducaoTotalAnterior = documentos19.Sum((Documento x) => x.get_PremioLiquido()); + PainelBiViewModel painelBiViewModel13 = this; + List documentos20 = this._documentosProducao; + painelBiViewModel13.ComissaoTotal = documentos20.Sum((Documento x) => ((x.get_PremioLiquido() + (x.get_AdicionalComiss() ? x.get_PremioAdicional() : decimal.Zero)) * x.get_Comissao()) * new decimal(1, 0, 0, false, 2)); + List documentos21 = this._documentosProducao; + IEnumerable> nomeSocial = + from x in documentos21 + group x by x.get_Controle().get_Seguradora().get_NomeSocial(); + ( + from x in nomeSocial + orderby x.Sum((Documento p) => p.get_PremioLiquido()) descending + select x).ToList>().ForEach((IGrouping x) => { + ColumnSeries columnSeries = new ColumnSeries(); + columnSeries.set_Title(x.Key); + ChartValues chartValue = new ChartValues(); + chartValue.Add(x.Sum((Documento p) => p.get_PremioLiquido())); + columnSeries.set_Values(chartValue); + columnSeries.set_LabelPoint((ChartPoint chartPoint) => { + IGrouping strs = x; + Func u003cu003e9_13631 = PainelBiViewModel.u003cu003ec.u003cu003e9__136_31; + if (u003cu003e9_13631 == null) + { + u003cu003e9_13631 = (Documento p) => p.get_PremioLiquido(); + PainelBiViewModel.u003cu003ec.u003cu003e9__136_31 = u003cu003e9_13631; + } + return string.Concat("R$ ", strs.Sum(u003cu003e9_13631).ToString("N2")); + }); + columnSeries.set_MaxColumnWidth(double.PositiveInfinity); + this.Producao.Series.Add(columnSeries); + decimal num = x.Sum((Documento p) => ((p.get_PremioLiquido() + (p.get_AdicionalComiss() ? p.get_PremioAdicional() : decimal.Zero)) * p.get_Comissao()) * new decimal(1, 0, 0, false, 2)); + PieSeries pieSeries = new PieSeries(); + pieSeries.set_Title(x.Key); + ChartValues chartValue1 = new ChartValues(); + chartValue1.Add((num > decimal.Zero ? num : num * decimal.MinusOne)); + pieSeries.set_Values(chartValue1); + pieSeries.set_DataLabels(false); + pieSeries.set_LabelPoint((ChartPoint chartPoint) => string.Concat("R$ ", num.ToString("N2"))); + this.Gerada.Series.Add(pieSeries); + decimal num1 = Math.Round(x.Sum((Documento p) => p.get_Comissao()) / x.Count(), 2); + PieSeries pieSeries1 = new PieSeries(); + pieSeries1.set_Title(x.Key); + ChartValues chartValue2 = new ChartValues(); + chartValue2.Add(num1); + pieSeries1.set_Values(chartValue2); + pieSeries1.set_DataLabels(false); + pieSeries1.set_LabelPoint((ChartPoint chartPoint) => string.Format(" Media de Comissão {0}% ", num1)); + this.MediaComissao.Series.Add(pieSeries1); + }); + TimeSpan fim = filtro1.get_Fim() - filtro1.get_Inicio(); + double totalDays = fim.TotalDays; + ChartValues chartValue3 = new ChartValues(); + ChartValues chartValue4 = new ChartValues(); + for (int i = 0; (double)i <= totalDays; i++) + { + inicio = filtro1.get_Inicio(); + DateTime dateTime = inicio.AddDays((double)i); + DateTime dateTime1 = dateTime.AddYears(-1); + IEnumerable vigencia1 = + from s in this._documentosFechamento + where s.get_Vigencia1() == dateTime1 + select s; + decimal num4 = vigencia1.Sum((Documento s) => s.get_PremioLiquido()); + IEnumerable vigencia11 = + from s in this._documentosProducao + where s.get_Vigencia1() == dateTime + select s; + decimal num5 = vigencia11.Sum((Documento s) => s.get_PremioLiquido()); + chartValue3.Add(new DateTimePoint(dateTime, (double)((double)num4))); + chartValue4.Add(new DateTimePoint(dateTime, (double)((double)num5))); + } + LineSeries lineSeries = new LineSeries(); + inicio = filtro3.get_Inicio(); + lineSeries.set_Title(string.Format("{0}", inicio.Year)); + lineSeries.set_Values(chartValue3); + LineSeries lineSeries1 = lineSeries; + LineSeries lineSeries2 = new LineSeries(); + inicio = filtro1.get_Inicio(); + lineSeries2.set_Title(string.Format("{0}", inicio.Year)); + lineSeries2.set_Values(chartValue4); + LineSeries lineSeries3 = lineSeries2; + this.Fechamento.Series.Add(lineSeries1); + this.Fechamento.Series.Add(lineSeries3); + PainelBiViewModel str = this; + str.XFormatter = (double val) => (new DateTime((long)val)).ToString("dd/MM"); + PainelBiViewModel str1 = this; + str1.YFormatter = (double val) => val.ToString("C2"); + this.IsVisibleProducao = Visibility.Visible; + filtro1 = null; + filtro3 = null; + } + + public async Task GerarVencimento() + { + long num; + this.IsVisibleVencimento = Visibility.Collapsed; + List vendedorUsuarios = await (new VendedorUsuarioServico()).FindByVinculo(Recursos.Usuario); + Filtros filtro = new Filtros(); + filtro.set_Inicio(this.InicioVencimento); + filtro.set_Fim(this.FimVencimento); + num = (Recursos.Usuario.get_IdEmpresa() == (long)1 ? (long)0 : Recursos.Usuario.get_IdEmpresa()); + filtro.set_IdEmpresa(num); + List vendedorUsuarios1 = vendedorUsuarios; + filtro.set_Vendedores(( + from x in vendedorUsuarios1 + select x.get_Vendedor().get_Id()).ToList()); + Filtros filtro1 = filtro; + List documentos = await this._apoliceServico.BuscarApolicesVigenciaFinal(filtro1, false); + PainelBiViewModel list = this; + List documentos1 = documentos; + list._documentosVencimento = ( + from x in documentos1 + where x.get_Situacao() != 7 + select x).ToList(); + this.Vencimentos = this._documentosVencimento.Count; + List parcelas = await this._parcelaServico.BuscarParcelas(filtro1, false); + PainelBiViewModel painelBiViewModel = this; + List parcelas1 = parcelas; + painelBiViewModel._parcelasVencimento = ( + from x in parcelas1 + where x.get_Documento().get_Situacao() != 7 + select x).ToList(); + this.ParcelasAVencer = this._parcelasVencimento.Count; + this.IsVisibleVencimento = Visibility.Visible; + filtro1 = null; + } + + private async void LoadInicial() + { + await this.GerarProducao(); + await this.GerarVencimento(); + await this.GerarClientes(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/BI/ProspeccaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/BI/ProspeccaoViewModel.cs new file mode 100644 index 0000000..4839d95 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/BI/ProspeccaoViewModel.cs @@ -0,0 +1,553 @@ +using ClosedXML.Excel; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +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 System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; + +namespace Gestor.Application.ViewModels.BI +{ + public class ProspeccaoViewModel : BaseViewModel + { + private readonly ProspeccaoServico _servico; + + private PermissaoUsuario SelectedPermissaoUsuario; + + private ObservableCollection _vendedores; + + private Vendedor _selectedVendedor = new Vendedor(); + + private List _searchStatus = new List() + { + "TODOS", + ValidationHelper.GetDescription((StatusProspeccao)1), + ValidationHelper.GetDescription((StatusProspeccao)5), + ValidationHelper.GetDescription((StatusProspeccao)2), + ValidationHelper.GetDescription((StatusProspeccao)4), + ValidationHelper.GetDescription((StatusProspeccao)3) + }; + + private string _selectedStatusSearch = "AGENDANDO"; + + private StatusProspeccao? _selectedStatus; + + private ObservableCollection _statusProspeccaoPersonalizado; + + private DateTime _inicio = Funcoes.GetNetworkTime().Date; + + private DateTime _fim = Funcoes.GetNetworkTime().Date.AddDays(7); + + private ObservableCollection _prospeccoesFiltradas; + + private Gestor.Model.Domain.Seguros.Prospeccao _selectedProspeccao; + + private ObservableCollection _prospeccao; + + private bool _naoHaDados; + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public bool NaoHaDados + { + get + { + return this._naoHaDados; + } + set + { + this._naoHaDados = value; + base.OnPropertyChanged("NaoHaDados"); + } + } + + public ObservableCollection Prospeccao + { + get + { + return this._prospeccao; + } + set + { + this._prospeccao = value; + this.NaoHaDados = (value == null ? true : value.Count == 0); + base.OnPropertyChanged("Prospeccao"); + } + } + + public AutoCompleteFilterPredicate ProspeccaoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_530 = ProspeccaoViewModel.u003cu003ec.u003cu003e9__53_0; + if (u003cu003e9_530 == null) + { + u003cu003e9_530 = new AutoCompleteFilterPredicate(ProspeccaoViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_Nome().ToUpper().Contains(searchText.ToUpper()) || ((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_Documento().ToString().ToUpper().Contains(searchText.ToUpper()) || ((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_Telefone1().ToString().ToUpper().Contains(searchText.ToUpper()) || ((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_Telefone2().ToString().ToUpper().Contains(searchText.ToUpper()) || ((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_Email().ToString().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Gestor.Model.Domain.Seguros.Prospeccao)obj).get_VigenciaFinal().ToString().ToUpper().Contains(searchText.ToUpper()); + }); + ProspeccaoViewModel.u003cu003ec.u003cu003e9__53_0 = u003cu003e9_530; + } + return u003cu003e9_530; + } + } + + public List Prospeccoes + { + get; + set; + } + + public ObservableCollection ProspeccoesFiltradas + { + get + { + return this._prospeccoesFiltradas; + } + set + { + this._prospeccoesFiltradas = value; + base.OnPropertyChanged("ProspeccoesFiltradas"); + } + } + + public List SearchStatus + { + get + { + return this._searchStatus; + } + set + { + this._searchStatus = value; + this.SelectedStatusSearch = value[1]; + base.OnPropertyChanged("SearchStatus"); + } + } + + public Gestor.Model.Domain.Seguros.Prospeccao SelectedProspeccao + { + get + { + return this._selectedProspeccao; + } + set + { + this._selectedProspeccao = value; + base.OnPropertyChanged("SelectedProspeccao"); + } + } + + public StatusProspeccao? SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + base.OnPropertyChanged("SelectedStatus"); + } + } + + public string SelectedStatusSearch + { + get + { + return this._selectedStatusSearch; + } + set + { + this._selectedStatusSearch = value; + if (value == "AGENDADO") + { + this.SelectedStatus = new StatusProspeccao?(1); + } + else if (value == "GANHO") + { + this.SelectedStatus = new StatusProspeccao?(2); + } + else if (value == "PERDIDO") + { + this.SelectedStatus = new StatusProspeccao?(3); + } + else if (value == "NÃO TRABALHADO") + { + this.SelectedStatus = new StatusProspeccao?(4); + } + else if (value == "EM ANDAMENTO") + { + this.SelectedStatus = new StatusProspeccao?(5); + } + else + { + this.SelectedStatus = null; + } + base.OnPropertyChanged("SelectedStatusSearch"); + } + } + + public Vendedor SelectedVendedor + { + get + { + return this._selectedVendedor; + } + set + { + this._selectedVendedor = value; + base.OnPropertyChanged("SelectedVendedor"); + } + } + + public ObservableCollection StatusProspeccaoPersonalizado + { + get + { + return this._statusProspeccaoPersonalizado; + } + set + { + this._statusProspeccaoPersonalizado = value; + base.OnPropertyChanged("StatusProspeccaoPersonalizado"); + } + } + + public ObservableCollection Vendedores + { + get + { + return this._vendedores; + } + set + { + this._vendedores = value; + base.OnPropertyChanged("Vendedores"); + } + } + + public ProspeccaoViewModel() + { + this._servico = new ProspeccaoServico(); + this.StatusProspeccaoPersonalizado = new ObservableCollection(( + from x in Recursos.StatusProspeccao + where x.get_Ativo() + select x).ToList()); + this.CarregaVendedores(); + this.SelectedStatusSearch = this.SearchStatus[1]; + this.CarregaProspeccoes(); + } + + public async Task BuscaPermissao(string Tipo) + { + bool flag; + ProspeccaoViewModel prospeccaoViewModel = this; + if (Recursos.Usuario.get_Administrador()) + { + flag = true; + } + else if (Tipo == "Alterar" && prospeccaoViewModel.SelectedPermissaoUsuario != null && !prospeccaoViewModel.SelectedPermissaoUsuario.get_Alterar()) + { + flag = false; + } + else if (!(Tipo == "Excluir") || prospeccaoViewModel.SelectedPermissaoUsuario == null || prospeccaoViewModel.SelectedPermissaoUsuario.get_Excluir()) + { + flag = (!(Tipo == "Incluir") || prospeccaoViewModel.SelectedPermissaoUsuario == null || prospeccaoViewModel.SelectedPermissaoUsuario.get_Incluir() ? true : false); + } + else + { + flag = false; + } + return flag; + } + + public async Task CarregaProspeccao() + { + ProspeccaoViewModel observableCollection = this; + if (observableCollection.ProspeccoesFiltradas != null) + { + observableCollection.ProspeccoesFiltradas = new ObservableCollection(observableCollection.ProspeccoesFiltradas.ToList()); + } + } + + public async void CarregaProspeccoes() + { + await this.CarregarProspeccoes(); + } + + public async Task CarregarPermissao() + { + this.SelectedPermissaoUsuario = await this.ServicoPermissUsuario.VerificarPermissao(Recursos.Usuario, 60); + } + + public async Task CarregarProspeccoes() + { + if (this.Inicio <= this.Fim) + { + base.Loading(true); + base.IsVisible = Visibility.Collapsed; + this.Prospeccoes = await this._servico.BuscarProspeccoes(this.SelectedVendedor.get_Id(), this.Inicio, this.Fim, this.SelectedStatus); + ProspeccaoViewModel observableCollection = this; + List prospeccoes = this.Prospeccoes; + observableCollection.ProspeccoesFiltradas = new ObservableCollection( + from x in prospeccoes + orderby x.get_VigenciaFinal() + select x); + this.SelectedProspeccao = this.ProspeccoesFiltradas.FirstOrDefault(); + base.IsVisible = Visibility.Visible; + base.Loading(false); + } + } + + public async Task CarregarVendedores() + { + List vendedorUsuarios = await (new VendedorUsuarioServico()).FindByVinculo(Recursos.Usuario); + List list = ( + from x in vendedorUsuarios + select x.get_Vendedor().get_Id()).ToList(); + List vendedors = new List(); + if (list.Count <= 0 || Recursos.Usuario.get_Administrador()) + { + Vendedor vendedor = new Vendedor(); + vendedor.set_Id((long)0); + vendedor.set_Nome("TODOS OS VENDEDORES"); + vendedors.Add(vendedor); + List vendedors1 = vendedors; + List vendedores = Recursos.Vendedores; + IEnumerable vendedors2 = vendedores.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }); + vendedors1.AddRange(( + from x in vendedors2 + orderby x.get_Nome() + select x).ToList()); + } + else + { + List vendedors3 = vendedors; + IEnumerable vendedors4 = Recursos.Vendedores.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa() || !x.get_Ativo()) + { + return false; + } + return list.Contains(x.get_Id()); + }); + vendedors3.AddRange(( + from x in vendedors4 + orderby x.get_Nome() + select x).ToList()); + } + this.Vendedores = new ObservableCollection(vendedors); + this.SelectedVendedor = this.Vendedores.FirstOrDefault(); + } + + public async void CarregaVendedores() + { + await this.CarregarVendedores(); + } + + public async void Excluir(Gestor.Model.Domain.Seguros.Prospeccao prospeccao) + { + if (await this.BuscaPermissao("Excluir")) + { + if (prospeccao != null) + { + bool tarefa = prospeccao.get_Tarefa() == null; + if (tarefa) + { + tarefa = !await base.ShowMessage("DESEJA EXCLUIR ESSA PROSPECÇÃO?", "SIM", "NÃO", false); + } + bool flag = tarefa; + if (!flag) + { + bool tarefa1 = prospeccao.get_Tarefa() != null; + if (tarefa1) + { + tarefa1 = !await base.ShowMessage(string.Concat("HÁ UMA TAREFA ANEXADA A ESSA PROSPECÇÃO. ESSE PROCEDIMENTO IRÁ EXCLUIR A TAREFA ANEXADA.", Environment.NewLine, "DESEJA REALMENTE PROSSEGUIR?"), "SIM", "NÃO", false); + } + flag = tarefa1; + } + if (!flag) + { + if (await this._servico.Delete(prospeccao)) + { + base.RegistrarAcao(string.Format("EXCLUIU PROSPECÇÃO DO ID: {0}", prospeccao.get_Id()), prospeccao.get_Id(), new TipoTela?(33), string.Format("CLIENTE \"{0}\", ID: {1}", prospeccao.get_Nome(), prospeccao.get_Id())); + await this.CarregarProspeccoes(); + base.ToggleSnackBar("PROSPECÇÃO EXCLUÍDA COM SUCESSO", true); + } + } + } + } + } + + public List Filtrar(string filter) + { + if (this.Prospeccoes == null) + { + return null; + } + this.ProspeccoesFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Prospeccoes) : new ObservableCollection(this.Prospeccoes.Where((Gestor.Model.Domain.Seguros.Prospeccao x) => { + if (ValidationHelper.RemoveDiacritics(ValidationHelper.RemoveDiacritics(x.get_Nome()).ToUpper().Trim()).Contains(filter) || x.get_Documento() != null && ValidationHelper.RemoveDiacritics(x.get_Documento().Trim()).Contains(filter) || x.get_Telefone1() != null && ValidationHelper.RemoveDiacritics(x.get_Telefone1().Trim()).Contains(filter) || x.get_Telefone2() != null && ValidationHelper.RemoveDiacritics(x.get_Telefone2().Trim()).Contains(filter) || x.get_Email() != null && ValidationHelper.RemoveDiacritics(x.get_Email().Trim()).Contains(filter)) + { + return true; + } + if (!x.get_VigenciaFinal().HasValue) + { + return false; + } + return ValidationHelper.RemoveDiacritics(x.get_VigenciaFinal().ToString().Trim()).Contains(filter); + }).OrderBy((Gestor.Model.Domain.Seguros.Prospeccao x) => x.get_VigenciaFinal()))); + return this.ProspeccoesFiltradas.ToList(); + } + + internal async Task> FiltrarProspecao(string value) + { + List prospeccaos = await Task.Run>(() => this.Filtrar(value)); + return prospeccaos; + } + + public async Task GerarExcel() + { + string str; + if (this.ProspeccoesFiltradas != null) + { + List prospeccaoToPrints = new List(); + this.ProspeccoesFiltradas.AsEnumerable().ToList().ForEach((Gestor.Model.Domain.Seguros.Prospeccao x) => { + ProspeccaoToPrint prospeccaoToPrint = new ProspeccaoToPrint(); + prospeccaoToPrint.set_Nome(x.get_Nome()); + prospeccaoToPrint.set_Documento(x.get_Documento() ?? ""); + prospeccaoToPrint.set_Nascimento(x.get_Nascimento()); + prospeccaoToPrint.set_Prefixo1(x.get_Prefixo1() ?? ""); + prospeccaoToPrint.set_Telefone1(x.get_Telefone1() ?? ""); + prospeccaoToPrint.set_Email(x.get_Email() ?? ""); + prospeccaoToPrint.set_VigenciaFinal(x.get_VigenciaFinal()); + prospeccaoToPrint.set_Item(x.get_Item() ?? ""); + prospeccaoToPrint.set_Status(x.get_Status()); + prospeccaoToPrint.set_StatusPersonalizadotoPrint((x.get_StatusPersonalizado() == null ? "" : x.get_StatusPersonalizado().get_Nome())); + prospeccaoToPrint.set_Tipo(x.get_Tipo() ?? ""); + object nome = x.get_Vendedor().get_Nome(); + if (nome == null) + { + nome = null; + } + prospeccaoToPrint.set_Vendedor((string)nome); + prospeccaoToPrint.set_Valor(x.get_Valor()); + prospeccaoToPrints.Add(prospeccaoToPrint); + }); + string tempPath = ""; + str = ""; + tempPath = Path.GetTempPath(); + str = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + string str1 = "PROSPECÇÃO"; + await Funcoes.GerarXls(new XLWorkbook(), str1, prospeccaoToPrints, new List()).SaveAs(str); + Process.Start(str); + } + else + { + base.ShowMessage("NÃO HÁ DADOS PARA A IMPRESSÃO EM EXCEL", "OK", "", false); + } + str = null; + } + + public async Task Print() + { + if (this.ProspeccoesFiltradas != null) + { + List prospeccaoToPrints = new List(); + this.ProspeccoesFiltradas.AsEnumerable().ToList().ForEach((Gestor.Model.Domain.Seguros.Prospeccao x) => { + ProspeccaoToPrint prospeccaoToPrint = new ProspeccaoToPrint(); + prospeccaoToPrint.set_Nome(x.get_Nome()); + prospeccaoToPrint.set_Documento(x.get_Documento() ?? ""); + prospeccaoToPrint.set_Nascimento(x.get_Nascimento()); + prospeccaoToPrint.set_Prefixo1(x.get_Prefixo1() ?? ""); + prospeccaoToPrint.set_Telefone1(x.get_Telefone1() ?? ""); + prospeccaoToPrint.set_Email(x.get_Email() ?? ""); + prospeccaoToPrint.set_VigenciaFinal(x.get_VigenciaFinal()); + prospeccaoToPrint.set_Item(x.get_Item() ?? ""); + prospeccaoToPrint.set_Status(x.get_Status()); + prospeccaoToPrint.set_StatusPersonalizadotoPrint((x.get_StatusPersonalizado() == null ? "" : x.get_StatusPersonalizado().get_Nome())); + prospeccaoToPrint.set_Tipo(x.get_Tipo() ?? ""); + object nome = x.get_Vendedor().get_Nome(); + if (nome == null) + { + nome = null; + } + prospeccaoToPrint.set_Vendedor((string)nome); + prospeccaoToPrint.set_Valor(x.get_Valor()); + prospeccaoToPrints.Add(prospeccaoToPrint); + }); + List prospeccaoToPrints1 = prospeccaoToPrints; + prospeccaoToPrints = ( + from x in prospeccaoToPrints1 + orderby x.get_Vendedor() + select x).ToList(); + string str = await Funcoes.GenerateTable(prospeccaoToPrints.ToList(), new List(), false, false, "", null); + if (!string.IsNullOrEmpty(str)) + { + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Inicio(this.Inicio); + tipoRelatorio.set_Fim(this.Fim); + tipoRelatorio.set_Nome(string.Concat("PROSPECÇÕES - ", this.SelectedVendedor.get_Nome())); + str = Funcoes.ExportarHtml(tipoRelatorio, str, "60", "landscaoe", false, ""); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}PROSPECÇÃO_{1:ddMMyyyyhhmmss}.html", tempPath, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + } + } + } + + public async Task>> Salvar(Gestor.Model.Domain.Seguros.Prospeccao prospecao) + { + return await base.SalvarProspeccao(prospecao); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/BI/TarefaBIViewModel.cs b/Codemerx/Gestor.Application/ViewModels/BI/TarefaBIViewModel.cs new file mode 100644 index 0000000..33d1096 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/BI/TarefaBIViewModel.cs @@ -0,0 +1,1453 @@ +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.BI +{ + public class TarefaBIViewModel : BaseTarefaViewModel + { + private bool _enableAlterarTarefa = true; + + private bool _administrador; + + private DateTime _inicio; + + private DateTime _fim; + + private List _status; + + private string _selectedStatus; + + private Visibility _isVisibleCliente; + + private Visibility _isVisibleApolice; + + private Visibility _isVisibleArquivoDigital; + + private Visibility _isVisibleSinistro; + + private ObservableCollection _usuariosFiltro; + + private ObservableCollection _usuarios; + + private ObservableCollection _tiposTarefa; + + private TipoDeTarefa _selectedTipoTarefa; + + private Usuario _selectedUsuarioFiltro; + + private Usuario _selectedUsuario; + + private DateTime _dataAgendamento; + + private DateTime _horaAgendamento; + + private bool _isAnotacoes; + + private string _descricao; + + private string _historicoInterno; + + private ObservableCollection _tarefas; + + private Tarefa _selectedTarefa; + + private ObservableCollection _telefones; + + private long _cancelTarefa; + + private ObservableCollection _tarefasFiltradas; + + private string _filtro; + + private ObservableCollection _filtroTarefa; + + private GridLength _columnUsuarioPrincipal; + + private GridLength _columnUsuarios; + + public bool Administrador + { + get + { + return this._administrador; + } + set + { + this._administrador = value; + base.OnPropertyChanged("Administrador"); + } + } + + private Gestor.Application.Servicos.Seguros.ClienteServico ClienteServico + { + get; + } + + public GridLength ColumnUsuarioPrincipal + { + get + { + return this._columnUsuarioPrincipal; + } + set + { + this._columnUsuarioPrincipal = value; + base.OnPropertyChanged("ColumnUsuarioPrincipal"); + } + } + + public GridLength ColumnUsuarios + { + get + { + return this._columnUsuarios; + } + set + { + this._columnUsuarios = value; + base.OnPropertyChanged("ColumnUsuarios"); + } + } + + public DateTime DataAgendamento + { + get + { + return this._dataAgendamento; + } + set + { + this._dataAgendamento = value; + if (this.SelectedTarefa != null) + { + this.SelectedTarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", value, this.SelectedTarefa.get_Agendamento()))); + } + base.OnPropertyChanged("DataAgendamento"); + } + } + + public string Descricao + { + get + { + return this._descricao; + } + set + { + this._descricao = value; + base.OnPropertyChanged("Descricao"); + } + } + + public override bool EnableAlterarTarefa + { + get + { + return this._enableAlterarTarefa; + } + set + { + this._enableAlterarTarefa = this._alterarPermissEnabled & value; + base.OnPropertyChanged("EnableAlterarTarefa"); + } + } + + public string Filtro + { + get + { + return this._filtro; + } + set + { + this._filtro = value; + base.OnPropertyChanged("Filtro"); + } + } + + public ObservableCollection FiltroTarefa + { + get + { + return this._filtroTarefa; + } + set + { + this._filtroTarefa = value; + base.OnPropertyChanged("FiltroTarefa"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + this.CarregaTarefas(false); + base.OnPropertyChanged("Fim"); + } + } + + public string HistoricoInterno + { + get + { + return this._historicoInterno; + } + set + { + this._historicoInterno = value; + base.OnPropertyChanged("HistoricoInterno"); + } + } + + public DateTime HoraAgendamento + { + get + { + return this._horaAgendamento; + } + set + { + this._horaAgendamento = value; + if (this.SelectedTarefa != null) + { + this.SelectedTarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", this.SelectedTarefa.get_Agendamento(), value))); + } + base.OnPropertyChanged("HoraAgendamento"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + this.CarregaTarefas(false); + base.OnPropertyChanged("Inicio"); + } + } + + public bool IsAnotacoes + { + get + { + return this._isAnotacoes; + } + set + { + this._isAnotacoes = value; + base.OnPropertyChanged("IsAnotacoes"); + } + } + + public Visibility IsVisibleApolice + { + get + { + return this._isVisibleApolice; + } + set + { + this._isVisibleApolice = value; + base.OnPropertyChanged("IsVisibleApolice"); + } + } + + public Visibility IsVisibleArquivoDigital + { + get + { + return this._isVisibleArquivoDigital; + } + set + { + this._isVisibleArquivoDigital = value; + base.OnPropertyChanged("IsVisibleArquivoDigital"); + } + } + + public Visibility IsVisibleCliente + { + get + { + return this._isVisibleCliente; + } + set + { + this._isVisibleCliente = value; + base.OnPropertyChanged("IsVisibleCliente"); + } + } + + public Visibility IsVisibleSinistro + { + get + { + return this._isVisibleSinistro; + } + set + { + this._isVisibleSinistro = value; + base.OnPropertyChanged("IsVisibleSinistro"); + } + } + + public string SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + this.CarregaTarefas(false); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public override Tarefa SelectedTarefa + { + get + { + return this._selectedTarefa; + } + set + { + long? nullable; + this._cancelTarefa = (value != null ? value.get_Id() : (long)0); + this.WorkOnSelectedTarefa(value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + this._selectedTarefa = value; + base.ValidaPermissaoParaEditarTarefa(); + base.OnPropertyChanged("SelectedTarefa"); + } + } + + public TipoDeTarefa SelectedTipoTarefa + { + get + { + return this._selectedTipoTarefa; + } + set + { + this._selectedTipoTarefa = value; + base.OnPropertyChanged("SelectedTipoTarefa"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public Usuario SelectedUsuarioFiltro + { + get + { + return this._selectedUsuarioFiltro; + } + set + { + this._selectedUsuarioFiltro = value; + this.CarregaTarefas(false); + base.OnPropertyChanged("SelectedUsuarioFiltro"); + } + } + + private new TarefaServico Servico + { + get; + } + + public List Status + { + get + { + return this._status; + } + set + { + this._status = value; + this.CarregaTarefas(false); + base.OnPropertyChanged("Status"); + } + } + + public ObservableCollection Tarefas + { + get + { + return this._tarefas; + } + set + { + this._tarefas = value; + base.OnPropertyChanged("Tarefas"); + } + } + + public ObservableCollection TarefasFiltradas + { + get + { + return this._tarefasFiltradas; + } + set + { + this._tarefasFiltradas = value; + base.IsVisible = (value.Count > 0 ? Visibility.Visible : Visibility.Collapsed); + base.OnPropertyChanged("TarefasFiltradas"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public ObservableCollection TiposTarefa + { + get + { + return this._tiposTarefa; + } + set + { + this._tiposTarefa = value; + base.OnPropertyChanged("TiposTarefa"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public ObservableCollection UsuariosFiltro + { + get + { + return this._usuariosFiltro; + } + set + { + this._usuariosFiltro = value; + base.OnPropertyChanged("UsuariosFiltro"); + } + } + + public TarefaBIViewModel() + { + this._enableAlterarTarefa = true; + DateTime date = Funcoes.GetNetworkTime().Date; + this._inicio = date.AddDays(-4); + date = Funcoes.GetNetworkTime().Date; + this._fim = date.AddDays(4); + this._status = new List() + { + "TODAS AS TAREFAS", + Gestor.Common.Validation.ValidationHelper.GetDescription((StatusTarefa)0), + Gestor.Common.Validation.ValidationHelper.GetDescription((StatusTarefa)2) + }; + this._isVisibleCliente = Visibility.Collapsed; + this._isVisibleApolice = Visibility.Collapsed; + this._isVisibleArquivoDigital = Visibility.Collapsed; + this._isVisibleSinistro = Visibility.Collapsed; + this._selectedUsuarioFiltro = new Usuario(); + this._selectedUsuario = new Usuario(); + this._dataAgendamento = Funcoes.GetNetworkTime(); + this._horaAgendamento = Funcoes.GetNetworkTime(); + this._isAnotacoes = true; + this._descricao = ""; + this._historicoInterno = ""; + this._tarefasFiltradas = new ObservableCollection(); + this._filtro = ""; + this._filtroTarefa = new ObservableCollection(); + this._columnUsuarioPrincipal = new GridLength(1, GridUnitType.Star); + this._columnUsuarios = new GridLength(0, GridUnitType.Pixel); + base(); + this.Servico = new TarefaServico(); + this.ClienteServico = new Gestor.Application.Servicos.Seguros.ClienteServico(); + this.Administrador = (Recursos.Usuario.get_Id() == 0 ? true : Recursos.Usuario.get_Administrador()); + this.CarregarUsuarios(); + List list = Recursos.Usuarios.Where((Usuario x) => { + if (!Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 36) && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList(); + Usuario usuario = new Usuario(); + usuario.set_Nome("TODOS OS USUÁRIOS"); + usuario.set_Id((long)0); + list.Insert(0, usuario); + this.UsuariosFiltro = new ObservableCollection(list); + this.TiposTarefa = new ObservableCollection(( + from x in Recursos.TiposTarefa + where x.get_Ativo() + select x).ToList()); + this.SelectedUsuarioFiltro = this.UsuariosFiltro.FirstOrDefault((Usuario x) => x.get_Id() == Recursos.Usuario.get_Id()) ?? this.UsuariosFiltro.FirstOrDefault(); + this.SelectedStatus = this.Status[1]; + this.CarregaTarefas(true); + } + + public async void Abrir(TipoTarefa tipo) + { + double? nullable; + long? nullable1; + long? nullable2; + switch (tipo) + { + case 0: + { + long idEntidade = this.SelectedTarefa.get_IdEntidade(); + if (this.SelectedTarefa.get_Entidade() == 4) + { + Sinistro sinistro = await base.CarregaSinistroApolice(this.SelectedTarefa.get_IdEntidade()); + if (sinistro != null) + { + ControleSinistro controleSinistro = sinistro.get_ControleSinistro(); + if (controleSinistro != null) + { + Item item = controleSinistro.get_Item(); + if (item != null) + { + Documento documento = item.get_Documento(); + if (documento != null) + { + nullable2 = new long?(documento.get_Id()); + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + nullable1 = nullable2; + idEntidade = nullable1.GetValueOrDefault(); + } + if (idEntidade != 0) + { + nullable = null; + double? nullable3 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(await base.CarregaApolice(idEntidade), true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICES - ", this.SelectedTarefa.get_Cliente()), nullable3, nullable, false)).Show(); + goto case 1; + } + else + { + break; + } + } + case 1: + { + break; + } + case 2: + { + nullable = null; + double? nullable4 = nullable; + nullable = null; + (new HosterWindow(new ClienteView(await base.CarregaCliente(this.SelectedTarefa.get_IdCliente()), true, null), string.Concat("CADASTRO DE CLIENTES - ", this.SelectedTarefa.get_Cliente()), nullable4, nullable, false)).Show(); + goto case 1; + } + case 3: + { + nullable = null; + double? nullable5 = nullable; + nullable = null; + (new HosterWindow(new ApoliceView(await base.CarregaApoliceParcela(this.SelectedTarefa.get_IdEntidade()), true, false, 0, (long)0, false), string.Concat("CADASTRO DE APÓLICES - ", this.SelectedTarefa.get_Cliente(), " - ", this.SelectedTarefa.get_Referencia()), nullable5, nullable, false)).Show(); + goto case 1; + } + case 4: + { + Sinistro sinistro1 = await base.CarregaSinistroApolice(this.SelectedTarefa.get_IdEntidade()); + if (sinistro1 != null) + { + nullable = null; + double? nullable6 = nullable; + nullable = null; + (new HosterWindow(new SinistroView(sinistro1.get_ControleSinistro().get_Item(), false), string.Concat("CADASTRO DE SINISTROS - ", this.SelectedTarefa.get_Cliente(), " - ", this.SelectedTarefa.get_Referencia()), nullable6, nullable, false)).Show(); + goto case 1; + } + else + { + await base.ShowMessage("SINISTRO NÃO ENCONTRADO!", "OK", "", false); + break; + } + } + default: + { + goto case 1; + } + } + } + + public async void AbrirArquivoDigital() + { + FiltroArquivoDigital filtroArquivoDigital; + if (this.SelectedTarefa.get_IdEntidade() != 0) + { + filtroArquivoDigital = new FiltroArquivoDigital(); + switch (this.SelectedTarefa.get_Entidade()) + { + case 0: + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 2).get_Consultar()) + { + Documento documento = await base.CarregaApolice(this.SelectedTarefa.get_IdEntidade()); + filtroArquivoDigital.set_Id(documento.get_Id()); + filtroArquivoDigital.set_Tipo(2); + filtroArquivoDigital.set_Parente(documento); + goto case 7; + } + else + { + await base.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)2), "."), "OK", "", false); + break; + } + } + case 1: + case 6: + case 7: + { + base.ShowDrawer(new ArquivoDigitalDrawer(filtroArquivoDigital), 0, false); + break; + } + case 2: + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 1).get_Consultar()) + { + Cliente cliente = await base.CarregaCliente(this.SelectedTarefa.get_IdCliente()); + filtroArquivoDigital.set_Id(cliente.get_Id()); + filtroArquivoDigital.set_Tipo(1); + filtroArquivoDigital.set_Parente(cliente); + goto case 7; + } + else + { + await base.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)1), "."), "OK", "", false); + break; + } + } + case 3: + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 3).get_Consultar()) + { + Parcela parcela = await base.CarregaParcela(this.SelectedTarefa.get_IdEntidade()); + filtroArquivoDigital.set_Id(parcela.get_Id()); + filtroArquivoDigital.set_Tipo(3); + filtroArquivoDigital.set_Parente(parcela); + filtroArquivoDigital.set_IdApolice(parcela.get_Documento().get_Id()); + goto case 7; + } + else + { + await base.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)3), "."), "OK", "", false); + break; + } + } + case 4: + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 5).get_Consultar()) + { + Sinistro sinistro = await base.CarregaSinistroApolice(this.SelectedTarefa.get_IdEntidade()); + filtroArquivoDigital.set_Id(sinistro.get_Id()); + filtroArquivoDigital.set_Tipo(5); + filtroArquivoDigital.set_Parente(sinistro); + filtroArquivoDigital.set_IdApolice(sinistro.get_ControleSinistro().get_Item().get_Documento().get_Id()); + goto case 7; + } + else + { + await base.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)5), "."), "OK", "", false); + break; + } + } + case 5: + { + if ((new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 11).get_Consultar()) + { + Prospeccao prospeccao = await base.CarregarProspeccao(this.SelectedTarefa.get_IdEntidade()); + filtroArquivoDigital.set_Id(prospeccao.get_Id()); + filtroArquivoDigital.set_Tipo(11); + filtroArquivoDigital.set_Parente(prospeccao); + goto case 7; + } + else + { + await base.ShowMessage(string.Concat("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR\nARQUIVO DIGITAL DE ", Gestor.Common.Validation.ValidationHelper.GetDescription((TipoArquivoDigital)11), "."), "OK", "", false); + break; + } + } + case 8: + { + break; + } + default: + { + goto case 7; + } + } + } + filtroArquivoDigital = null; + } + + public void AdcionarFiltro() + { + if (string.IsNullOrEmpty(this.Filtro)) + { + return; + } + if (this.FiltroTarefa == null) + { + this.FiltroTarefa = new ObservableCollection(); + } + this.FiltroTarefa.Add(this.Filtro); + this.Filtro = string.Empty; + this.FiltrarTarefa(); + } + + public async Task AdcionarResponsavel() + { + if (!await base.ValidaPermissaoParaEditarTarefa()) + { + await base.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA EXCLUIR ESSA TAREFA!", "OK", "", false); + } + else if (this.SelectedUsuario != null) + { + ObservableCollection responsaveis = base.Responsaveis; + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_Usuario(this.SelectedUsuario); + responsavelTarefa.set_IdTarefa(this.SelectedTarefa.get_Id()); + responsaveis.Add(responsavelTarefa); + this.Usuarios.Remove(this.SelectedUsuario); + this.SelectedUsuario = null; + } + } + + public async Task AlterarTarefa() + { + GridLength gridLength; + GridLength gridLength1; + if (this.SelectedTarefa != null) + { + if (await base.ValidaPermissaoParaEditarTarefa()) + { + this.CarregarUsuarios(); + base.Alterar(true); + TarefaBIViewModel tarefaBIViewModel = this; + gridLength = (base.EnableFields ? new GridLength(0, GridUnitType.Pixel) : new GridLength(1, GridUnitType.Star)); + tarefaBIViewModel.ColumnUsuarioPrincipal = gridLength; + TarefaBIViewModel tarefaBIViewModel1 = this; + gridLength1 = (base.EnableFields ? new GridLength(1, GridUnitType.Star) : new GridLength(0, GridUnitType.Pixel)); + tarefaBIViewModel1.ColumnUsuarios = gridLength1; + base.ListaUsuariosResponsaveis(); + base.HasResponsaveis = true; + this.SelectedUsuario = null; + base.Responsaveis.ToList().ForEach((ResponsavelTarefa x) => this.Usuarios.Remove(this.Usuarios.FirstOrDefault((Usuario u) => u.get_Id() == x.get_Usuario().get_Id()))); + } + else + { + await base.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA EXCLUIR ESSA TAREFA!", "OK", "", false); + } + } + } + + public async Task Cancelar() + { + if (this._cancelTarefa != 0) + { + long num = this._cancelTarefa; + await this.CarregarTarefas(); + this.SelectedTarefa = this.TarefasFiltradas.FirstOrDefault((Tarefa x) => x.get_Id() == num); + base.Alterar(false); + } + } + + public async Task CarregarTarefas() + { + long id; + bool? nullable; + this.ColumnUsuarioPrincipal = new GridLength(1, GridUnitType.Star); + this.ColumnUsuarios = new GridLength(0, GridUnitType.Pixel); + this.Filtro = string.Empty; + TarefaServico servico = this.Servico; + Usuario selectedUsuarioFiltro = this.SelectedUsuarioFiltro; + if (selectedUsuarioFiltro != null) + { + id = selectedUsuarioFiltro.get_Id(); + } + else + { + id = (long)0; + } + DateTime inicio = this.Inicio; + DateTime fim = this.Fim; + if (this.SelectedStatus == "TODAS AS TAREFAS") + { + nullable = null; + } + else + { + nullable = new bool?(this.SelectedStatus != "PENDENTE"); + } + List tarefas = await servico.BuscarTarefas(id, inicio, fim, nullable); + TarefaBIViewModel observableCollection = this; + List tarefas1 = tarefas; + IEnumerable entidade = + from x in tarefas1 + where x.get_Entidade() != 1 + select x; + observableCollection.Tarefas = new ObservableCollection( + from x in entidade + orderby x.get_Agendamento() + select x); + this.TarefasFiltradas = this.Tarefas; + this.SelectedTarefa = this.TarefasFiltradas.FirstOrDefault(); + if (this.FiltroTarefa.Count > 0) + { + this.FiltrarTarefa(); + } + } + + private void CarregarUsuarios() + { + this.Usuarios = new ObservableCollection(Recursos.Usuarios.Where((Usuario x) => { + if (!Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 36) && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + } + + public async void CarregaTarefas(bool permissoes = false) + { + if (permissoes) + { + await base.PermissaoTela(38); + base.Alterar(false); + } + await this.CarregarTarefas(); + } + + public async Task ConcluirTarefa(Tarefa tarefa) + { + Tarefa tarefa1; + if (await base.ValidaPermissaoParaEditarTarefa()) + { + tarefa1 = await this.Servico.Salvar(tarefa); + } + else + { + await base.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA EDITAR ESSA TAREFA!", "OK", "", false); + tarefa1 = null; + } + return tarefa1; + } + + public async Task CriarMalaDireta(TipoTarefa tipo) + { + MalaDireta malaDiretum; + switch (tipo) + { + case 0: + { + Documento documento = await base.CarregaApolice(this.SelectedTarefa.get_IdEntidade()); + MalaDireta malaDiretum1 = new MalaDireta(); + malaDiretum1.set_Cliente(documento.get_Controle().get_Cliente()); + malaDiretum1.set_Apolice(documento); + malaDiretum1.set_Tela(2); + malaDiretum = malaDiretum1; + break; + } + case 1: + case 6: + case 7: + { + malaDiretum = null; + break; + } + case 2: + { + Cliente cliente = await base.CarregaCliente(this.SelectedTarefa.get_IdCliente()); + MalaDireta malaDiretum2 = new MalaDireta(); + malaDiretum2.set_Cliente(cliente); + malaDiretum2.set_Tela(1); + malaDiretum = malaDiretum2; + break; + } + case 3: + { + Documento documento1 = await base.CarregaApoliceParcela(this.SelectedTarefa.get_IdEntidade()); + MalaDireta malaDiretum3 = new MalaDireta(); + malaDiretum3.set_Cliente(documento1.get_Controle().get_Cliente()); + malaDiretum3.set_Apolice(documento1); + malaDiretum3.set_Tela(5); + malaDiretum = malaDiretum3; + break; + } + case 4: + { + Sinistro sinistro = await base.CarregaSinistroApolice(this.SelectedTarefa.get_IdEntidade()); + MalaDireta malaDiretum4 = new MalaDireta(); + malaDiretum4.set_Cliente(sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente()); + malaDiretum4.set_Apolice(sinistro.get_ControleSinistro().get_Item().get_Documento()); + malaDiretum4.set_Sinistro(sinistro); + malaDiretum4.set_Tela(7); + malaDiretum = malaDiretum4; + break; + } + case 5: + { + Prospeccao prospeccao = await base.CarregarProspeccao(this.SelectedTarefa.get_IdEntidade()); + MalaDireta malaDiretum5 = new MalaDireta(); + malaDiretum5.set_Prospeccao(prospeccao); + malaDiretum5.set_Tela(33); + malaDiretum = malaDiretum5; + break; + } + case 8: + { + malaDiretum = null; + break; + } + default: + { + goto case 7; + } + } + return malaDiretum; + } + + public async Task Excluir() + { + bool id; + string titulo; + Tarefa selectedTarefa = this.SelectedTarefa; + if (selectedTarefa != null) + { + id = selectedTarefa.get_Id() == (long)0; + } + else + { + id = false; + } + if (!id) + { + TarefaBIViewModel tarefaBIViewModel = this; + string[] newLine = new string[] { "DESEJA REALMENTE EXCLUIR A TAREFA ", null, null, null, null }; + Tarefa tarefa = this.SelectedTarefa; + if (tarefa != null) + { + titulo = tarefa.get_Titulo(); + } + else + { + titulo = null; + } + newLine[1] = titulo; + newLine[2] = "?"; + newLine[3] = Environment.NewLine; + newLine[4] = "ESSE PROCEDIMENTO É IRREVERSÍVEL"; + if (await tarefaBIViewModel.ShowMessage(string.Concat(newLine), "SIM", "NÃO", false)) + { + if (await this.Servico.Excluir(this.SelectedTarefa.get_Id())) + { + await this.CarregarTarefas(); + Action atualizaTrilhas = Gestor.Application.Actions.Actions.AtualizaTrilhas; + if (atualizaTrilhas != null) + { + atualizaTrilhas(); + } + else + { + } + base.Alterar(false); + } + else + { + base.Alterar(false); + } + } + } + } + + public void ExcluirFiltro(string filtro) + { + this.FiltroTarefa.Remove(filtro); + this.FiltrarTarefa(); + } + + private List Filtrar() + { + List list = this.Tarefas.ToList(); + this.FiltroTarefa.ToList().ForEach((string f) => list = list.Where((Tarefa x) => { + if (Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Titulo()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)) || Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Cliente()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)) || Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Referencia()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)) || x.get_Agendamento().ToString("d").ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)) || x.get_Id().ToString().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)) || x.get_TipoDeTarefa() != null && Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_TipoDeTarefa().get_Nome()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f))) + { + return true; + } + if (x.get_Usuario() == null) + { + return false; + } + return x.get_Usuario().get_Nome().ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(f)); + }).ToList()); + return list; + } + + public void FiltrarTarefa() + { + this.TarefasFiltradas = new ObservableCollection(this.Filtrar()); + this.SelectedTarefa = this.TarefasFiltradas.FirstOrDefault(); + } + + public string GerarHtml() + { + string nome; + string str = " TAREFA
"; + str = string.Concat(str, "
"); + str = string.Concat(str, "

"); + str = string.Concat(str, "TAREFA


"); + str = string.Concat(str, ""); + int num = 0; + string[] cliente = new string[] { str, ""; + str = string.Concat(cliente); + string[] referencia = new string[] { str, ""; + str = string.Concat(referencia); + string[] titulo = new string[] { str, ""; + str = string.Concat(titulo); + string[] strArrays = new string[] { str, ""; + str = string.Concat(strArrays); + string[] nome1 = new string[] { str, ""; + str = string.Concat(nome1); + string[] description = new string[] { str, ""; + str = string.Concat(description); + string[] strArrays1 = new string[] { str, ""; + str = string.Concat(strArrays1); + str = string.Concat(str, "

CLIENTE: "; + cliente[4] = this.SelectedTarefa.get_Cliente(); + cliente[5] = "

REFERÊNCIA: "; + referencia[4] = this.SelectedTarefa.get_Referencia(); + referencia[5] = "

TÍTULO: "; + titulo[4] = this.SelectedTarefa.get_Titulo(); + titulo[5] = "

AGENDAMENTO: "; + DateTime agendamento = this.SelectedTarefa.get_Agendamento(); + strArrays[4] = agendamento.ToString(); + strArrays[5] = "

RESPONSÁVEL PRINCIPAL: "; + nome1[4] = this.SelectedTarefa.get_Usuario().get_Nome(); + nome1[5] = "

STATUS: "; + description[4] = Gestor.Common.Validation.ValidationHelper.GetDescription(this.SelectedTarefa.get_Status()); + description[5] = "

TIPO DE TAREFA: "; + TipoDeTarefa selectedTipoTarefa = this.SelectedTipoTarefa; + if (selectedTipoTarefa != null) + { + nome = selectedTipoTarefa.get_Nome(); + } + else + { + nome = null; + } + strArrays1[4] = nome; + strArrays1[5] = "

"); + if (base.Responsaveis != null && base.Responsaveis.Count > 0) + { + str = string.Concat(str, "

RESPONSÁVEIS VINCULADOS

"); + str = string.Concat(str, "
"); + str = string.Concat(str, ""); + List strs = new List(); + foreach (ResponsavelTarefa responsavei in base.Responsaveis) + { + strs.Add(responsavei.get_Usuario().get_Nome().Trim().ToUpper()); + } + str = string.Concat(str, ""); + str = string.Concat(str, "

", string.Join(", ", strs), "

"); + str = string.Concat(str, "

"); + } + str = string.Concat(str, "

"); + if (this.SelectedTarefa.get_Descricao() != null) + { + str = string.Concat(str, "

ANOTAÇÕES

"); + str = string.Concat(str, "
"); + str = string.Concat(str, ""); + str = string.Concat(str, ""); + str = string.Concat(str, "

", this.SelectedTarefa.get_Descricao().Replace("", "").Replace("", ""), "

"); + str = string.Concat(str, "

"); + } + str = string.Concat(str, "
"); + return str; + } + + public void Print() + { + string str = this.GerarHtml(); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoTela)38, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + } + + public async Task>> Salvar(string titulo) + { + List> keyValuePairs; + Usuario usuario; + string str; + if (this.SelectedTarefa != null) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 45) && this.SelectedTarefa.get_Status() != 2 && this.SelectedTarefa.get_Agendamento() < networkTime) + { + this.SelectedTarefa.set_Agendamento(networkTime); + } + if (this.SelectedTarefa.get_Status() == 2) + { + this.SelectedTarefa.set_Conclusao(new DateTime?(networkTime)); + } + this.SelectedTarefa.set_Responsaveis(base.Responsaveis.ToList()); + Tarefa selectedTarefa = this.SelectedTarefa; + ResponsavelTarefa responsavelTarefa = base.Responsaveis.FirstOrDefault(); + if (responsavelTarefa != null) + { + usuario = responsavelTarefa.get_Usuario(); + } + else + { + usuario = null; + } + selectedTarefa.set_Usuario(usuario); + Tarefa tarefa = this.SelectedTarefa; + List configuracaoSistemas = Recursos.Configuracoes; + tarefa.set_AgendamentoRetroativo(configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs1 = this.SelectedTarefa.Validate(); + string text = Funcoes.GetText(this.SelectedTarefa.get_Anotacoes()); + string text1 = Funcoes.GetText(this.SelectedTarefa.get_AnotacoesInternas()); + if (string.IsNullOrEmpty(text) && string.IsNullOrEmpty(text1)) + { + keyValuePairs1.Add(new KeyValuePair("Anotações", "OBRIGATÓRIO")); + } + if (keyValuePairs1.Count <= 0) + { + this.SelectedTarefa.set_Anotacoes(Funcoes.AdicionarLog(this.SelectedTarefa.get_Anotacoes())); + this.SelectedTarefa.set_Descricao(string.Concat(this.SelectedTarefa.get_Anotacoes(), "

", this.Descricao, "

")); + Tarefa selectedTarefa1 = this.SelectedTarefa; + str = (string.IsNullOrWhiteSpace(this.SelectedTarefa.get_AnotacoesInternas()) ? this.HistoricoInterno : string.Concat(this.SelectedTarefa.get_AnotacoesInternas(), "

", this.HistoricoInterno, "

")); + selectedTarefa1.set_DescricaoInterna(str); + this.SelectedTarefa.set_TipoDeTarefa(this.SelectedTipoTarefa); + this.SelectedTarefa.set_Titulo(titulo); + this.SelectedTarefa = await this.Servico.Salvar(this.SelectedTarefa); + if (this.Servico.Sucesso) + { + long id = this.SelectedTarefa.get_Id(); + await this.CarregarTarefas(); + TarefaBIViewModel tarefaBIViewModel = this; + Tarefa tarefa1 = this.TarefasFiltradas.FirstOrDefault((Tarefa x) => x.get_Id() == id); + if (tarefa1 == null) + { + tarefa1 = this.TarefasFiltradas.FirstOrDefault(); + } + tarefaBIViewModel.SelectedTarefa = tarefa1; + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + } + else + { + keyValuePairs = null; + } + return keyValuePairs; + } + + private async void WorkOnSelectedTarefa(Tarefa value) + { + Usuario usuario; + ObservableCollection observableCollection; + TipoTelefone tipoTelefone; + TipoTelefone tipoTelefone1; + bool flag; + ObservableCollection observableCollection1; + if (value != null) + { + TarefaBIViewModel tarefaBIViewModel = this; + if (value.get_Usuario() != null) + { + usuario = this.Usuarios.FirstOrDefault((Usuario x) => x.get_Id() == value.get_Usuario().get_Id()); + } + else + { + usuario = null; + } + tarefaBIViewModel.SelectedUsuario = usuario; + this.DataAgendamento = value.get_Agendamento(); + this.HoraAgendamento = value.get_Agendamento(); + this.Descricao = value.get_Descricao(); + this.HistoricoInterno = value.get_DescricaoInterna(); + TarefaBIViewModel tarefaBIViewModel1 = this; + if (value == null) + { + observableCollection = new ObservableCollection(); + } + else + { + observableCollection = (value.get_Responsaveis() == null ? new ObservableCollection() : new ObservableCollection(value.get_Responsaveis())); + } + tarefaBIViewModel1.Responsaveis = observableCollection; + if (!base.Responsaveis.Any()) + { + TarefaBIViewModel tarefaBIViewModel2 = this; + Tarefa tarefa = value; + if (tarefa != null) + { + flag = tarefa.get_Usuario(); + } + else + { + flag = false; + } + if (!flag) + { + observableCollection1 = new ObservableCollection(); + } + else + { + ResponsavelTarefa[] responsavelTarefaArray = new ResponsavelTarefa[1]; + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_Usuario(value.get_Usuario()); + responsavelTarefaArray[0] = responsavelTarefa; + observableCollection1 = new ObservableCollection(responsavelTarefaArray); + } + tarefaBIViewModel2.Responsaveis = observableCollection1; + } + if (value.get_TipoDeTarefa() != null) + { + if (!this.TiposTarefa.All((TipoDeTarefa x) => x.get_Id() != value.get_Id()) || value.get_TipoDeTarefa().get_Ativo()) + { + TarefaBIViewModel observableCollection2 = this; + ObservableCollection tiposTarefa = this.TiposTarefa; + observableCollection2.TiposTarefa = new ObservableCollection(( + from x in tiposTarefa + where x.get_Ativo() + select x).ToList()); + } + else + { + this.TiposTarefa.Add(value.get_TipoDeTarefa()); + } + } + this.SelectedTipoTarefa = value.get_TipoDeTarefa(); + this.IsVisibleCliente = Visibility.Collapsed; + this.IsVisibleApolice = Visibility.Collapsed; + this.IsVisibleSinistro = Visibility.Collapsed; + this.IsVisibleArquivoDigital = Visibility.Collapsed; + TipoTarefa entidade = value.get_Entidade(); + switch (entidade) + { + case 0: + case 3: + { + this.IsVisibleCliente = Visibility.Visible; + this.IsVisibleApolice = Visibility.Visible; + this.IsVisibleArquivoDigital = Visibility.Visible; + goto case 1; + } + case 1: + { + entidade = value.get_Entidade(); + if (entidade == 5) + { + Prospeccao prospeccao = await (new ProspeccaoServico()).BuscarProspeccao(value.get_IdEntidade()); + this.Telefones = new ObservableCollection(); + if (prospeccao != null && prospeccao.get_Telefone1() != null) + { + ObservableCollection telefones = this.Telefones; + TelefoneBase telefoneBase1 = new TelefoneBase(); + tipoTelefone1 = (prospeccao.get_Telefone1().StartsWith("9") ? 3 : 7); + telefoneBase1.set_Tipo(new TipoTelefone?(tipoTelefone1)); + telefoneBase1.set_Numero(prospeccao.get_Telefone1()); + telefoneBase1.set_Prefixo(prospeccao.get_Prefixo1()); + telefones.Add(telefoneBase1); + } + if (prospeccao != null && prospeccao.get_Telefone2() != null) + { + ObservableCollection telefones1 = this.Telefones; + TelefoneBase telefoneBase2 = new TelefoneBase(); + tipoTelefone = (prospeccao.get_Telefone2().StartsWith("9") ? 3 : 7); + telefoneBase2.set_Tipo(new TipoTelefone?(tipoTelefone)); + telefoneBase2.set_Numero(prospeccao.get_Telefone2()); + telefoneBase2.set_Prefixo(prospeccao.get_Prefixo2()); + telefones1.Add(telefoneBase2); + } + } + else if (entidade == 8) + { + this.Telefones = new ObservableCollection(); + } + else + { + ObservableCollection observableCollection3 = await this.ClienteServico.BuscarTelefonesAsync(value.get_IdCliente()); + TarefaBIViewModel tarefaBIViewModel3 = this; + ObservableCollection observableCollection4 = observableCollection3; + IEnumerable clienteTelefones = + from x in observableCollection4 + where Gestor.Model.Helper.ValidationHelper.ValidacaoTelefone(x.get_Numero()) + select x; + tarefaBIViewModel3.Telefones = new ObservableCollection(clienteTelefones.Select((ClienteTelefone x) => { + TelefoneBase telefoneBase = new TelefoneBase(); + telefoneBase.set_Tipo(x.get_Tipo()); + telefoneBase.set_Id(x.get_Id()); + telefoneBase.set_Numero(x.get_Numero()); + telefoneBase.set_Prefixo(x.get_Prefixo()); + return telefoneBase; + }).ToList()); + } + break; + } + case 2: + { + this.IsVisibleCliente = Visibility.Visible; + this.IsVisibleArquivoDigital = Visibility.Visible; + goto case 1; + } + case 4: + { + this.IsVisibleCliente = Visibility.Visible; + this.IsVisibleApolice = Visibility.Visible; + this.IsVisibleSinistro = Visibility.Visible; + this.IsVisibleArquivoDigital = Visibility.Visible; + goto case 1; + } + default: + { + goto case 1; + } + } + } + else + { + base.Responsaveis = new ObservableCollection(); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/CoberturaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/CoberturaViewModel.cs new file mode 100644 index 0000000..fb35f4d --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/CoberturaViewModel.cs @@ -0,0 +1,285 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels +{ + public class CoberturaViewModel : BaseSegurosViewModel + { + private readonly ItemServico _itemServico; + + private Cobertura _selectedCobertura; + + private List _coberturasPadrao; + + private ObservableCollection _coberturas; + + private readonly IComparer _comparerCobertura; + + public ObservableCollection Coberturas + { + get + { + return this._coberturas; + } + set + { + this._coberturas = value; + base.OnPropertyChanged("Coberturas"); + } + } + + public List CoberturasPadrao + { + get + { + return this._coberturasPadrao; + } + set + { + this._coberturasPadrao = value; + base.OnPropertyChanged("CoberturasPadrao"); + } + } + + public Gestor.Model.Domain.Seguros.Item Item + { + get; + set; + } + + public Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + set; + } + + public Cobertura SelectedCobertura + { + get + { + return this._selectedCobertura; + } + set + { + this._selectedCobertura = value; + base.OnPropertyChanged("SelectedCobertura"); + } + } + + public CoberturaViewModel(Gestor.Model.Domain.Seguros.Ramo ramo = null, Gestor.Model.Domain.Seguros.Item item = null) + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.CoberturaViewModel::.ctor(Gestor.Model.Domain.Seguros.Ramo,Gestor.Model.Domain.Seguros.Item) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void .ctor(Gestor.Model.Domain.Seguros.Ramo,Gestor.Model.Domain.Seguros.Item) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // 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 void AdicionaCobertura() + { + Cobertura cobertura = new Cobertura(); + cobertura.set_Item(this.Item); + Cobertura cobertura1 = cobertura; + ValidationHelper.AddSorted(this.Coberturas, cobertura1, this._comparerCobertura); + this.SelectedCobertura = cobertura1; + } + + internal async Task> BuscarCobertura(string value) + { + Func func2 = null; + List coberturaPadraos = await Task.Run>(() => { + List coberturasPadrao = this.CoberturasPadrao; + if (coberturasPadrao == null) + { + return null; + } + Func u003cu003e9_1 = func2; + if (u003cu003e9_1 == null) + { + Func func = (CoberturaPadrao x) => ValidationHelper.RemoveDiacritics(x.get_Descricao().ToUpper().Trim()).Contains(value.ToUpper()); + Func func1 = func; + func2 = func; + u003cu003e9_1 = func1; + } + return coberturasPadrao.Where(u003cu003e9_1).ToList(); + }); + return coberturaPadraos; + } + + public async Task CancelarAlteracao() + { + if (this.Item != null) + { + this.Coberturas = await this._itemServico.BuscarCoberturasPorItemAsync(this.Item.get_Id()); + } + } + + public ObservableCollection CarregaCoberturaPadrao() + { + List list; + List coberturasPadrao = this.CoberturasPadrao; + if (coberturasPadrao != null) + { + list = ( + from x in coberturasPadrao + where x.get_Padrao() + select x).Select((CoberturaPadrao x) => { + Cobertura cobertura = new Cobertura(); + cobertura.set_CoberturaPadrao(x); + cobertura.set_Observacao(x.get_Descricao()); + return cobertura; + }).ToList(); + } + else + { + list = null; + } + ObservableCollection observableCollection = new ObservableCollection(list); + ObservableCollection observableCollection1 = observableCollection; + this.Coberturas = observableCollection; + return observableCollection1; + } + + public void CarregaPadrao() + { + List list; + List coberturasPadrao = this.CoberturasPadrao; + if (coberturasPadrao != null) + { + list = ( + from x in coberturasPadrao + where x.get_Padrao() + select x).Select((CoberturaPadrao x) => { + Cobertura cobertura = new Cobertura(); + cobertura.set_CoberturaPadrao(x); + cobertura.set_Observacao(x.get_Descricao()); + return cobertura; + }).ToList(); + } + else + { + list = null; + } + List coberturas = list; + if (coberturas == null) + { + return; + } + this.Coberturas = new ObservableCollection(coberturas); + } + + public async void ExcluirCobertura(Cobertura cobertura) + { + if (cobertura != null) + { + string[] newLine = new string[] { "DESEJA REALMENTE EXCLUIR A COBERTURA", Environment.NewLine, "\"", cobertura.get_Observacao(), "\"?" }; + if (await base.ShowMessage(string.Concat(newLine), "SIM", "NÃO", false)) + { + this.Coberturas.Remove(cobertura); + } + } + } + + public async Task> LimpaCoberturas() + { + bool flag; + IList list; + if (this.Coberturas == null) + { + flag = false; + } + else + { + ObservableCollection coberturas = this.Coberturas; + flag = coberturas.Any((Cobertura x) => { + if (!(x.get_Franquia() == decimal.Zero) || !(x.get_Lmi() == decimal.Zero)) + { + return false; + } + return x.get_Premio() == decimal.Zero; + }); + } + bool flag1 = flag; + if (flag1) + { + flag1 = await base.ShowMessage("DESEJA LIMPAR AS COBERTURAS SEM VALOR DE FRANQUIA, LMI E PRÊMIO?", "SIM", "NÃO", false); + } + if (flag1) + { + ObservableCollection observableCollection = this.Coberturas; + if (observableCollection != null) + { + list = observableCollection.Where((Cobertura x) => { + if (string.IsNullOrEmpty(x.get_Observacao())) + { + return false; + } + if (x.get_Franquia() != decimal.Zero || x.get_Lmi() != decimal.Zero) + { + return true; + } + return x.get_Premio() != decimal.Zero; + }).ToList(); + } + else + { + list = null; + } + } + else + { + ObservableCollection coberturas1 = this.Coberturas; + if (coberturas1 != null) + { + list = coberturas1.ToList(); + } + else + { + list = null; + } + } + return list; + } + + public async Task SelectionaCoberturas() + { + if (this.Ramo != null) + { + this.CoberturasPadrao = ( + from x in Recursos.Coberturas + where x.get_IdRamo() == this.Ramo.get_Id() + select x).ToList(); + if (this.Item != null) + { + this.Coberturas = await this._itemServico.BuscarCoberturasPorItemAsync(this.Item.get_Id()); + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Comissao/ComissaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Comissao/ComissaoViewModel.cs new file mode 100644 index 0000000..54cff8f --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Comissao/ComissaoViewModel.cs @@ -0,0 +1,3450 @@ +using CsQuery.ExtensionMethods; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Infrastructure.Helpers; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.Extrato; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Comissao +{ + public class ComissaoViewModel : BaseSegurosViewModel + { + private readonly ServicoExtrato _servico; + + private readonly ApoliceServico _apoliceServico; + + private readonly ParcelaServico _parcelaServico; + + private readonly VendedorServico _vendedorServico; + + private bool _apelido; + + private bool _baixarVisibility; + + private bool _finalizarVisibility; + + private bool _desconsiderarVisibility; + + private bool _desfazerVisibility; + + private ObservableCollection _seguradoras = new ObservableCollection(); + + private DateTime _inicio; + + private DateTime _fim; + + private bool _baixarPendentes; + + private ObservableCollection _extratos; + + private ObservableCollection _extratosFiltrados; + + private Extrato _selectedExtrato; + + private ObservableCollection _usuarios; + + private Usuario _selectedUsuario; + + private List _statusExtrato; + + private StatusExtrato _selectedStatusExtrato; + + private Seguradora _selectedSeguradora; + + private Gestor.Model.Domain.Seguros.DetalheExtrato _selectedDetalhe; + + private FiltroStatusDocumento _selectedStatus; + + private Cliente _selectedCliente; + + private string _documentoPrincipal; + + private ObservableCollection _detalheExtrato; + + private bool _allSelected; + + private ObservableCollection _detalheExtratoFiltrados; + + private int _quantidade; + + private decimal _totalBaixado; + + private decimal _totalPendente; + + private Visibility _isVisibleCliente; + + private Visibility _isVisibleApolice; + + private Visibility _isVisibleMensagem; + + private Visibility _isVisibleDetalhes; + + private Visibility _isVisibleExtrato; + + private bool _isExpanded; + + private ObservableCollection _apolices; + + private bool _idFatura; + + private Documento _selectedDocumento; + + private Parcela _selectedParcela; + + private ObservableCollection _parcelas; + + private decimal _porcentagemExtrato; + + private decimal _porcentagem; + + private decimal _indiceTotal; + + private decimal _indice; + + private decimal _totaExtratosl; + + private decimal _total; + + private bool _criticando; + + private string _filtro; + + private string _pesquisaPagamento; + + private string _filtroApolice; + + private ObservableCollection _filtroPersonalizado; + + private bool _carregadoDetalhes + { + get; + set; + } + + public bool AllSelected + { + get + { + return this._allSelected; + } + set + { + this._allSelected = value; + base.OnPropertyChanged("AllSelected"); + if (this._carregadoDetalhes) + { + return; + } + this.Selecionar(value); + } + } + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public ObservableCollection Apolices + { + get + { + return this._apolices; + } + set + { + this._apolices = value; + base.OnPropertyChanged("Apolices"); + } + } + + public bool BaixarPendentes + { + get + { + return this._baixarPendentes; + } + set + { + this._baixarPendentes = value; + base.OnPropertyChanged("BaixarPendentes"); + } + } + + public bool BaixarVisibility + { + get + { + return this._baixarVisibility; + } + set + { + this._baixarVisibility = value; + base.OnPropertyChanged("BaixarVisibility"); + } + } + + public bool Buscando + { + get; + set; + } + + private bool Carregando + { + get; + set; + } + + public bool Criticando + { + get + { + return this._criticando; + } + set + { + this._criticando = value; + base.OnPropertyChanged("Criticando"); + } + } + + public bool DesconsiderarVisibility + { + get + { + return this._desconsiderarVisibility; + } + set + { + this._desconsiderarVisibility = value; + base.OnPropertyChanged("DesconsiderarVisibility"); + } + } + + public bool DesfazerVisibility + { + get + { + return this._desfazerVisibility; + } + set + { + this._desfazerVisibility = value; + base.OnPropertyChanged("DesfazerVisibility"); + } + } + + public ObservableCollection DetalheExtrato + { + get + { + return this._detalheExtrato; + } + set + { + bool hasValue; + decimal zero; + this._detalheExtrato = value; + this.Quantidade = (value != null ? value.Count : 0); + List statusParcelas = new List() + { + 1, + 10, + 13 + }; + this.TotalBaixado = (value != null ? value.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue || !x.get_ValorComissao().HasValue) + { + return false; + } + return statusParcelas.Contains(x.get_Status().Value); + }).Sum((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_ValorComissao().Value) : decimal.Zero); + Extrato selectedExtrato = this.SelectedExtrato; + if (selectedExtrato != null) + { + hasValue = selectedExtrato.get_Bruto().HasValue; + } + else + { + hasValue = false; + } + if (hasValue) + { + decimal? bruto = this.SelectedExtrato.get_Bruto(); + zero = bruto.Value - this.TotalBaixado; + } + else + { + zero = decimal.Zero; + } + this.TotalPendente = zero; + base.OnPropertyChanged("DetalheExtrato"); + } + } + + public ObservableCollection DetalheExtratoFiltrados + { + get + { + return this._detalheExtratoFiltrados; + } + set + { + this._detalheExtratoFiltrados = value; + base.OnPropertyChanged("DetalheExtratoFiltrados"); + } + } + + public string DocumentoPrincipal + { + get + { + return this._documentoPrincipal; + } + set + { + this._documentoPrincipal = value; + base.OnPropertyChanged("DocumentoPrincipal"); + } + } + + public ObservableCollection Extratos + { + get + { + return this._extratos; + } + set + { + this._extratos = value; + if (value == null || value.Count == 0) + { + this.DetalheExtrato = null; + this.DetalheExtratoFiltrados = null; + } + base.OnPropertyChanged("Extratos"); + } + } + + public ObservableCollection ExtratosFiltrados + { + get + { + return this._extratosFiltrados; + } + set + { + bool id; + this._extratosFiltrados = value; + this.BaixarPendentes = (value == null ? false : value.Count > 0); + if (value == null || value.Count <= 0) + { + id = false; + } + else + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + } + base.EnableButtons = id; + this.IsVisibleExtrato = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + base.OnPropertyChanged("ExtratosFiltrados"); + } + } + + public string Filtro + { + get + { + return this._filtro; + } + set + { + this._filtro = value; + base.OnPropertyChanged("Filtro"); + } + } + + public string FiltroApolice + { + get + { + return this._filtroApolice; + } + set + { + this._filtroApolice = value; + base.OnPropertyChanged("FiltroApolice"); + } + } + + public ObservableCollection FiltroPersonalizado + { + get + { + return this._filtroPersonalizado; + } + set + { + this._filtroPersonalizado = value; + base.OnPropertyChanged("FiltroPersonalizado"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public bool FinalizarVisibility + { + get + { + return this._finalizarVisibility; + } + set + { + this._finalizarVisibility = value; + base.OnPropertyChanged("FinalizarVisibility"); + } + } + + private List Impostos + { + get; + set; + } + + public decimal Indice + { + get + { + return this._indice; + } + set + { + this._indice = value; + base.OnPropertyChanged("Indice"); + } + } + + public decimal IndiceTotal + { + get + { + return this._indiceTotal; + } + set + { + this._indiceTotal = value; + base.OnPropertyChanged("IndiceTotal"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public bool IsFatura + { + get + { + return this._idFatura; + } + set + { + this._idFatura = value; + base.OnPropertyChanged("IsFatura"); + } + } + + public Visibility IsVisibleApolice + { + get + { + return this._isVisibleApolice; + } + set + { + this._isVisibleApolice = value; + base.OnPropertyChanged("IsVisibleApolice"); + } + } + + public Visibility IsVisibleCliente + { + get + { + return this._isVisibleCliente; + } + set + { + this._isVisibleCliente = value; + base.OnPropertyChanged("IsVisibleCliente"); + } + } + + public Visibility IsVisibleDetalhes + { + get + { + return this._isVisibleDetalhes; + } + set + { + this._isVisibleDetalhes = value; + base.OnPropertyChanged("IsVisibleDetalhes"); + } + } + + public Visibility IsVisibleExtrato + { + get + { + return this._isVisibleExtrato; + } + set + { + this._isVisibleExtrato = value; + base.OnPropertyChanged("IsVisibleExtrato"); + } + } + + public Visibility IsVisibleMensagem + { + get + { + return this._isVisibleMensagem; + } + set + { + this._isVisibleMensagem = value; + base.OnPropertyChanged("IsVisibleMensagem"); + } + } + + public ObservableCollection Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + base.OnPropertyChanged("Parcelas"); + } + } + + public string PesquisaPagamento + { + get + { + return this._pesquisaPagamento; + } + set + { + this._pesquisaPagamento = value; + base.OnPropertyChanged("PesquisaPagamento"); + } + } + + public decimal Porcentagem + { + get + { + return this._porcentagem; + } + set + { + this._porcentagem = value; + base.OnPropertyChanged("Porcentagem"); + } + } + + public decimal PorcentagemExtrato + { + get + { + return this._porcentagemExtrato; + } + set + { + this._porcentagemExtrato = value; + base.OnPropertyChanged("PorcentagemExtrato"); + } + } + + public int Quantidade + { + get + { + return this._quantidade; + } + set + { + this._quantidade = value; + base.OnPropertyChanged("Quantidade"); + } + } + + public ObservableCollection Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + this.SelectedSeguradora = this.SelectedSeguradora ?? value.FirstOrDefault(); + base.OnPropertyChanged("Seguradoras"); + } + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this.WorkOnSelectedCliente(value); + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public Gestor.Model.Domain.Seguros.DetalheExtrato SelectedDetalhe + { + get + { + return this._selectedDetalhe; + } + set + { + this._selectedDetalhe = value; + base.OnPropertyChanged("SelectedDetalhe"); + } + } + + public Documento SelectedDocumento + { + get + { + return this._selectedDocumento; + } + set + { + this._selectedDocumento = value; + this.WorkOnSelectedDocumento(value); + base.OnPropertyChanged("SelectedDocumento"); + } + } + + public Extrato SelectedExtrato + { + get + { + return this._selectedExtrato; + } + set + { + this._selectedExtrato = value; + this.IsVisibleExtrato = (value != null ? Visibility.Visible : Visibility.Collapsed); + base.OnPropertyChanged("SelectedExtrato"); + } + } + + public Parcela SelectedParcela + { + get + { + return this._selectedParcela; + } + set + { + this._selectedParcela = value; + base.OnPropertyChanged("SelectedParcela"); + } + } + + public Seguradora SelectedSeguradora + { + get + { + return this._selectedSeguradora; + } + set + { + this._selectedSeguradora = value; + this.FiltroPersonalizado = new ObservableCollection(); + this.SelecionaSeguradora(value, this.SelectedStatusExtrato, null); + base.OnPropertyChanged("SelectedSeguradora"); + } + } + + public FiltroStatusDocumento SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + this.WorkOnSelectedStatus(); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public StatusExtrato SelectedStatusExtrato + { + get + { + return this._selectedStatusExtrato; + } + set + { + this._selectedStatusExtrato = value; + this.SelecionaSeguradora(this.SelectedSeguradora, value, null); + base.OnPropertyChanged("SelectedStatusExtrato"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + this.SelecionaSeguradora(this.SelectedSeguradora, this.SelectedStatusExtrato, null); + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public List Status + { + get + { + return this._statusExtrato; + } + set + { + this._statusExtrato = value; + base.OnPropertyChanged("Status"); + } + } + + public ObservableCollection TodasApolices + { + get; + set; + } + + public decimal Total + { + get + { + return this._total; + } + set + { + this._total = value; + base.OnPropertyChanged("Total"); + } + } + + public decimal TotalBaixado + { + get + { + return this._totalBaixado; + } + set + { + this._totalBaixado = value; + base.OnPropertyChanged("TotalBaixado"); + } + } + + public decimal TotalExtratos + { + get + { + return this._totaExtratosl; + } + set + { + this._totaExtratosl = value; + base.OnPropertyChanged("TotalExtratos"); + } + } + + public decimal TotalPendente + { + get + { + return this._totalPendente; + } + set + { + this._totalPendente = value; + base.OnPropertyChanged("TotalPendente"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + this.SelectedUsuario = this.SelectedUsuario ?? value.FirstOrDefault(); + base.OnPropertyChanged("Usuarios"); + } + } + + public ComissaoViewModel() + { + this._seguradoras = new ObservableCollection(); + DateTime date = Funcoes.GetNetworkTime().Date; + int year = date.Year; + date = Funcoes.GetNetworkTime().Date; + this._inicio = new DateTime(year, date.Month, 1); + this._fim = Funcoes.GetNetworkTime().Date; + this._baixarPendentes = true; + this._extratos = new ObservableCollection(); + this._extratosFiltrados = new ObservableCollection(); + this._usuarios = new ObservableCollection(); + this._statusExtrato = new List() + { + 1, + 2, + 3, + 4 + }; + this._selectedStatusExtrato = 1; + this._documentoPrincipal = ""; + this._isVisibleCliente = Visibility.Collapsed; + this._isVisibleApolice = Visibility.Collapsed; + this._isVisibleMensagem = Visibility.Collapsed; + this._isVisibleDetalhes = Visibility.Collapsed; + this._isVisibleExtrato = Visibility.Collapsed; + this._isExpanded = true; + this._apolices = new ObservableCollection(); + this._selectedDocumento = new Documento(); + this._selectedParcela = new Parcela(); + this._parcelas = new ObservableCollection(); + this.Impostos = new List(); + this._filtro = ""; + this._pesquisaPagamento = ""; + this._filtroApolice = ""; + this._filtroPersonalizado = new ObservableCollection(); + base(); + this._servico = new ServicoExtrato(); + this._apoliceServico = new ApoliceServico(); + this._parcelaServico = new ParcelaServico(); + this._vendedorServico = new VendedorServico(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + this.SelecionaSeguradoras(); + base.EnableMenu = true; + } + + public void AdcionarFiltro() + { + if (string.IsNullOrEmpty(this.Filtro)) + { + return; + } + if (this.FiltroPersonalizado == null) + { + this.FiltroPersonalizado = new ObservableCollection(); + } + this.FiltroPersonalizado.Add(this.Filtro); + this.Filtro = string.Empty; + this.FiltrarExtrato(); + } + + public async Task AtualizarExtrato() + { + if (this.DetalheExtratoFiltrados != null && this.DetalheExtratoFiltrados.Count != 0) + { + ObservableCollection detalheExtratoFiltrados = this.DetalheExtratoFiltrados; + if (!detalheExtratoFiltrados.All((Gestor.Model.Domain.Seguros.DetalheExtrato x) => !x.get_Selecionado())) + { + base.Loading(true); + this.IsVisibleDetalhes = Visibility.Collapsed; + base.IsVisible = Visibility.Collapsed; + ParcelaServico parcelaServico = this._parcelaServico; + ObservableCollection observableCollection = this.DetalheExtratoFiltrados; + await parcelaServico.UpdateDetalhes(( + from x in observableCollection + where x.get_Selecionado() + select x).ToList()); + base.IsVisible = Visibility.Visible; + this.IsVisibleDetalhes = Visibility.Visible; + base.Loading(false); + base.RegistrarAcao(string.Format("ATUALIZOU EXTRATO DE ID \n{0}\n", this.SelectedExtrato.get_Id()), this.SelectedExtrato.get_Id(), new TipoTela?(35), null); + base.ToggleSnackBar("EXTRATO ATUALIZADO COM SUCESSO", true); + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR QUAL PARCELA DESEJA ATUALIZAR.", "OK", "", false); + } + } + } + + private async Task BaixarComissao(List extrato, bool selecionados = false) + { + bool flag; + try + { + List statusParcelas = new List() + { + 9, + 14, + 16, + 4, + 17, + 15, + 7, + 18 + }; + List statusParcelas1 = statusParcelas; + List statusParcelas2 = new List() + { + 16, + 18 + }; + flag = (selecionados ? false : this.DetalheExtrato.ToList().Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => statusParcelas2.Contains(x.get_Status().Value))); + bool flag1 = flag; + if (flag1) + { + flag1 = !await base.ShowMessage("O EXTRATO CONTÉM PARCELAS ENCONTRADAS POR APROXIMAÇÃO, DESEJA BAIXÁ-LAS?", "SIM", "NÃO", false); + } + if (flag1) + { + extrato = ( + from parcela in extrato + where !statusParcelas2.Contains(parcela.get_Status().Value) + select parcela).ToList(); + } + List list = extrato.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas1.Contains(x.get_Status().Value); + }).ToList(); + if (list.Any()) + { + ComissaoViewModel comissaoViewModel = this; + List detalheExtratos = list; + IOrderedEnumerable cliente = + from x in detalheExtratos + orderby x.get_Cliente() + select x; + IOrderedEnumerable detalheExtratos1 = cliente.ThenBy((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Apolice()); + IOrderedEnumerable detalheExtratos2 = detalheExtratos1.ThenBy((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Endosso()); + await comissaoViewModel.BaixarExtrato(detalheExtratos2.ThenBy((Gestor.Model.Domain.Seguros.DetalheExtrato x) => ValidationHelper.ToInt(x.get_NumeroParcela())).ToList()); + } + else + { + this.SelectedExtrato.set_Status(3); + await this._servico.Save(this.SelectedExtrato); + if (this._servico.Sucesso) + { + await base.ShowMessage("NÃO HÁ PARCELAS A BAIXAR NESSE EXTRATO", "OK", "", false); + return; + } + else + { + return; + } + } + } + catch (Exception exception) + { + } + } + + public async Task BaixarExtrato(bool selecionados = false) + { + List list; + if (this.DetalheExtrato != null && this.DetalheExtrato.Count != 0) + { + List detalheExtratos = this.DetalheExtrato.ToList(); + if (!detalheExtratos.All((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Status().GetValueOrDefault() == 6)) + { + StatusExtrato status = this.SelectedExtrato.get_Status(); + if (selecionados) + { + ObservableCollection detalheExtrato = this.DetalheExtrato; + list = ( + from x in detalheExtrato + where x.get_Selecionado() + select x).ToList(); + } + else + { + list = this.DetalheExtrato.ToList(); + } + await this.BaixarComissao(list, selecionados); + base.RegistrarAcao(string.Format("BAIXOU EXTRATO DE ID \n{0}\n", this.SelectedExtrato.get_Id()), this.SelectedExtrato.get_Id(), new TipoTela?(35), null); + if (this.SelectedExtrato.get_Status() != 3) + { + this.SelectedStatusExtrato = this.SelectedExtrato.get_Status(); + } + this.SelectedExtrato = null; + this.SelecionaSeguradora(this.SelectedSeguradora, status, null); + base.ToggleSnackBar("EXTRATO BAIXADO COM SUCESSO", true); + } + else + { + this.SelectedExtrato.set_Status(3); + await this._servico.Save(this.SelectedExtrato); + if (this._servico.Sucesso) + { + this.SelectedStatusExtrato = 3; + await this.SelecionaExtrato(this.SelectedExtrato); + base.ToggleSnackBar("TODAS AS PARCELAS FORAM DESCONSIDERADAS PELO USUARIO", true); + } + } + } + } + + private async Task BaixarExtrato(List baixar) + { + List documentos; + long num1; + List vendedorParcelas; + decimal? valorComissao; + DateTime? recebimento; + int? nullable; + List list; + StatusParcela? nullable1; + DateTime? nullable2; + bool valueOrDefault; + string str; + string str1; + DateTime? nullable3; + decimal comissao; + SubTipo subTipo; + int valueOrDefault1; + DateTime? nullable4; + string str2; + DateTime? nullable5; + int? nullable6; + decimal? nullable7; + decimal? nullable8; + decimal? comissao1; + bool ordem; + ComissaoViewModel.u003cu003ec__DisplayClass225_0 variable; + Parcela parcela1; + bool flag = true; + await this.CarregarImpostos(); + this._apoliceServico.Sucesso = true; + this._servico.Sucesso = true; + this.Porcentagem = decimal.Zero; + this.Indice = decimal.Zero; + this.Total = baixar.Count; + List detalheExtratos = baixar; + IEnumerable hasValue = + from x in detalheExtratos + where x.get_Documento().HasValue + select x; + List nums = ( + from x in hasValue + select x.get_Documento().Value).ToList(); + List detalheExtratos1 = baixar; + IEnumerable detalheExtratos2 = detalheExtratos1.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (x.get_Documento().HasValue) + { + return false; + } + return x.get_Parcela().HasValue; + }); + List list1 = ( + from x in detalheExtratos2 + select x.get_Parcela().Value).ToList(); + if (nums.Count <= 0) + { + documentos = new List(); + } + else + { + documentos = await this._apoliceServico.BuscarApolicesPorId(nums); + } + List documentos1 = documentos; + if (list1.Count > 0) + { + List documentos2 = documentos1; + documentos = await this._apoliceServico.BuscarApolicesPorIdParcela(list1); + documentos2.AddRange(documentos); + documentos2 = null; + } + ParcelaServico parcelaServico = this._parcelaServico; + List documentos3 = documentos1; + List parcelas = await parcelaServico.BuscarTodasParcelas(( + from x in documentos3 + select x.get_Id()).ToList()); + parcelas.ForEach((Parcela p) => p.set_Documento(documentos1.Find((Documento d) => d.get_Id() == p.get_Documento().get_Id()))); + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato in baixar) + { + long? documento = detalheExtrato.get_Documento(); + if (!documento.HasValue) + { + documento = detalheExtrato.get_Parcela(); + if (!documento.HasValue) + { + detalheExtrato.set_Status(new StatusParcela?(2)); + await this._servico.Save(detalheExtrato); + continue; + } + } + decimal indice = this.Indice; + this.Indice = indice++; + this.Porcentagem = (this.Indice * new decimal(100)) / this.Total; + bool flag1 = false; + Documento documento1 = null; + documento = detalheExtrato.get_Documento(); + if (documento.HasValue) + { + documento = detalheExtrato.get_Documento(); + num1 = (long)0; + if (documento.GetValueOrDefault() > num1 & documento.HasValue) + { + documento1 = documentos1.Find((Documento d) => d.get_Id() == detalheExtrato.get_Documento().Value); + } + } + if (!documento1.get_Excluido()) + { + if (documento1 != null && documento1.get_TipoRecebimento().GetValueOrDefault() == 1 && documento1.get_Comissao() == decimal.Zero) + { + documento = detalheExtrato.get_Parcela(); + if (documento.HasValue) + { + documento = detalheExtrato.get_Parcela(); + num1 = (long)999; + if (documento.GetValueOrDefault() != num1 | !documento.HasValue) + { + Documento documento2 = documento1; + if (documento2 != null) + { + ordem = documento2.get_Ordem() == 0; + } + else + { + ordem = false; + } + if (ordem) + { + continue; + } + } + } + } + bool flag2 = true; + documento = detalheExtrato.get_Documento(); + if (documento.HasValue) + { + IEnumerable id = + from p in parcelas + where p.get_Documento().get_Id() == detalheExtrato.get_Documento().Value + select p; + list = ( + from p in id + orderby p.get_NumeroParcela() + select p).ToList(); + } + else + { + list = null; + } + List parcelas1 = list; + documento = detalheExtrato.get_Parcela(); + if (!documento.HasValue) + { + if (parcelas1.Count <= 0) + { + VendedorServico vendedorServico = this._vendedorServico; + documento = detalheExtrato.get_Documento(); + vendedorParcelas = await vendedorServico.BuscaRepasse(documento.Value); + } + else + { + vendedorParcelas = await this._vendedorServico.BuscaRepasseParcela(parcelas1.First().get_Id()); + } + List vendedorParcelas1 = vendedorParcelas; + Imposto imposto = this.CarregarImposto(documento1); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal valueOrDefault2 = valorComissao.GetValueOrDefault() * imposto.get_Ir(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal num2 = valorComissao.GetValueOrDefault() * imposto.get_Iss(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal valueOrDefault3 = valorComissao.GetValueOrDefault() * imposto.get_Outros(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal num3 = valorComissao.GetValueOrDefault() * imposto.get_Desconto(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal valueOrDefault4 = valorComissao.GetValueOrDefault() - (((valueOrDefault2 + num2) + valueOrDefault3) + num3); + if (documento1.get_TipoRecebimento().GetValueOrDefault() == 1) + { + recebimento = null; + nullable3 = recebimento; + } + else + { + recebimento = detalheExtrato.get_Recebimento(); + nullable3 = (!recebimento.HasValue ? this.SelectedExtrato.get_Data() : detalheExtrato.get_Recebimento()); + } + DateTime? nullable9 = nullable3; + if (documento1.get_TipoRecebimento().GetValueOrDefault() == 1) + { + comissao = new decimal(100); + } + else + { + Parcela parcela2 = parcelas1.FirstOrDefault(); + if (parcela2 != null) + { + comissao = parcela2.get_Comissao(); + } + else + { + valorComissao = detalheExtrato.get_Comissao(); + comissao = valorComissao.GetValueOrDefault(new decimal(100)); + } + } + decimal value = comissao; + if (value == new decimal(100)) + { + valorComissao = detalheExtrato.get_Valor(); + if (valorComissao.HasValue) + { + valorComissao = detalheExtrato.get_Comissao(); + if (valorComissao.HasValue) + { + valorComissao = detalheExtrato.get_ValorComissao(); + if (valorComissao.HasValue) + { + valorComissao = detalheExtrato.get_Valor(); + decimal? comissao2 = detalheExtrato.get_Comissao(); + indice = 100; + if (comissao2.HasValue) + { + nullable7 = new decimal?(comissao2.GetValueOrDefault() / indice); + } + else + { + nullable7 = null; + } + decimal? nullable10 = nullable7; + if (valorComissao.HasValue & nullable10.HasValue) + { + nullable8 = new decimal?(valorComissao.GetValueOrDefault() * nullable10.GetValueOrDefault()); + } + else + { + comissao2 = null; + nullable8 = comissao2; + } + comissao2 = nullable8; + decimal value1 = comissao2.Value; + valorComissao = detalheExtrato.get_ValorComissao(); + decimal value2 = valorComissao.Value; + if (Math.Truncate(value1) == Math.Truncate(value2)) + { + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato1 = detalheExtrato; + if (detalheExtrato1 != null) + { + comissao1 = detalheExtrato1.get_Comissao(); + } + else + { + valorComissao = null; + comissao1 = valorComissao; + } + valorComissao = comissao1; + value = valorComissao.Value; + } + } + } + } + } + Parcela parcela3 = new Parcela(); + parcela3.set_Documento(documento1); + parcela3.set_Vencimento(Funcoes.GetNetworkTime().Date); + parcela3.set_Comissao(value); + if (documento1.get_TipoRecebimento().GetValueOrDefault() == 1) + { + subTipo = detalheExtrato.get_SubTipo().GetValueOrDefault(3); + } + else + { + subTipo = 1; + } + parcela3.set_SubTipo(subTipo); + if (documento1.get_TipoRecebimento().GetValueOrDefault() == 1) + { + valueOrDefault1 = 999; + } + else + { + List parcelas2 = parcelas1; + if (parcelas2 != null) + { + Parcela parcela4 = parcelas2.LastOrDefault(); + if (parcela4 != null) + { + nullable6 = new int?(parcela4.get_NumeroParcela()); + } + else + { + nullable = null; + nullable6 = nullable; + } + } + else + { + nullable = null; + nullable6 = nullable; + } + nullable = nullable6; + valueOrDefault1 = nullable.GetValueOrDefault() + 1; + } + parcela3.set_NumeroParcela(valueOrDefault1); + valorComissao = detalheExtrato.get_Valor(); + parcela3.set_Valor(valorComissao.GetValueOrDefault()); + valorComissao = detalheExtrato.get_Valor(); + parcela3.set_ValorRealizado(valorComissao.GetValueOrDefault()); + valorComissao = detalheExtrato.get_ValorComissao(); + parcela3.set_ValorComissao(valorComissao.GetValueOrDefault()); + parcela3.set_Irr(valueOrDefault2); + parcela3.set_Iss(num2); + parcela3.set_Outros(valueOrDefault3); + parcela3.set_Desconto(num3); + parcela3.set_ValorComDesconto(valueOrDefault4); + parcela3.set_DataRecebimento(this.SelectedExtrato.get_Data()); + recebimento = this.SelectedExtrato.get_DataCredito(); + nullable4 = (recebimento.HasValue ? recebimento : this.SelectedExtrato.get_Data()); + parcela3.set_DataCredito(nullable4); + str2 = (documento1.get_TipoRecebimento().GetValueOrDefault() == 1 ? "" : detalheExtrato.get_Endosso()); + parcela3.set_Fatura(str2); + parcela3.set_Emissao(nullable9); + parcela3.set_VigenciaIncial(nullable9); + if (documento1.get_TipoRecebimento().GetValueOrDefault() == 1) + { + recebimento = null; + nullable5 = recebimento; + } + else if (nullable9.HasValue) + { + DateTime dateTime = nullable9.GetValueOrDefault(); + nullable5 = new DateTime?(dateTime.AddMonths(1)); + } + else + { + recebimento = null; + nullable5 = recebimento; + } + parcela3.set_VigenciaFinal(nullable5); + parcela3.set_Extrato(detalheExtrato.get_Extrato().get_Numero()); + parcela3.set_DataCriacao(new DateTime?(DateTime.Now)); + parcela1 = parcela3; + if (documento1.get_Ordem() > 0) + { + VendedorServico vendedorServico1 = this._vendedorServico; + Controle controle = await this._apoliceServico.BuscarControleAsync(documento1.get_Controle().get_Id()); + VendedorServico vendedorServico2 = vendedorServico1; + IList documentos4 = controle.get_Documentos(); + vendedorServico1 = null; + vendedorParcelas1 = await vendedorServico2.BuscaRepasse(documentos4.First((Documento d) => d.get_Ordem() == 0).get_Id()); + List vendedorParcelas2 = vendedorParcelas1; + vendedorParcelas1 = Funcoes.DistinctBy(vendedorParcelas2, (VendedorParcela v) => v.get_TipoVendedor()).ToList(); + } + if (vendedorParcelas1 != null) + { + List vendedorParcelas3 = vendedorParcelas1; + ExtensionMethods.ForEach( + from v in vendedorParcelas3 + where v.get_Repasse() != null + select v, (VendedorParcela v) => { + v.set_Id((long)0); + decimal num = Funcoes.CalculaRepasse(v.get_Repasse(), parcela1, false); + if (v.get_Repasse().get_Forma().GetValueOrDefault() == 1) + { + v.set_DataPrePagamento(parcela1.get_DataRecebimento()); + } + BaseRepasse? @base = v.get_Repasse().get_Base(); + if (@base.HasValue) + { + switch (@base.GetValueOrDefault()) + { + case 1: + { + v.set_DataPrePagamento((documento1.get_TipoRecebimento().GetValueOrDefault() == 2 ? parcela1.get_VigenciaIncial() : new DateTime?(documento1.get_Vigencia1()))); + break; + } + case 2: + { + v.set_DataPrePagamento(parcela1.get_DataCriacao()); + break; + } + case 3: + { + v.set_DataPrePagamento(new DateTime?(parcela1.get_Vencimento())); + break; + } + case 4: + { + v.set_DataPrePagamento((documento1.get_TipoRecebimento().GetValueOrDefault() == 2 ? parcela1.get_Emissao() : documento1.get_Emissao())); + break; + } + case 5: + { + v.set_DataPrePagamento((documento1.get_TipoRecebimento().GetValueOrDefault() == 2 ? parcela1.get_Emissao() : documento1.get_Remessa())); + break; + } + } + } + v.set_ValorRepasse(new decimal?(num)); + v.set_ValorTotal(new decimal?(num)); + v.set_DataPagamento(null); + }); + } + if (vendedorParcelas1 == null || vendedorParcelas1.Count == 0) + { + vendedorParcelas1 = new List() + { + ComissaoViewModel.PropriaCorretora() + }; + } + if (parcela1.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1) + { + parcela1.set_Vendedores(new ObservableCollection(vendedorParcelas1)); + parcela1.set_Extrato(detalheExtrato.get_Extrato().get_Numero()); + Parcela parcela5 = await this._parcelaServico.Save(parcela1, this.Parcelas.ToList(), vendedorParcelas1, true); + parcela1 = parcela5; + if (this._parcelaServico.Sucesso) + { + detalheExtrato.set_Parcela(new long?(parcela1.get_Id())); + flag1 = true; + } + else + { + variable = null; + list1 = null; + parcelas = null; + return; + } + } + } + if (!flag1) + { + documento = detalheExtrato.get_Parcela(); + if (!documento.HasValue) + { + continue; + } + parcela1 = parcelas.Find((Parcela p) => p.get_Id() == detalheExtrato.get_Parcela().Value); + if (parcela1 == null) + { + continue; + } + detalheExtrato.set_Documento(new long?(parcela1.get_Documento().get_Id())); + recebimento = parcela1.get_DataRecebimento(); + if (!recebimento.HasValue) + { + List vendedorParcelas4 = await this._vendedorServico.BuscaRepasseParcela(parcela1.get_Id()); + Imposto imposto1 = this.CarregarImposto(documento1); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal num4 = valorComissao.GetValueOrDefault() * imposto1.get_Ir(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal valueOrDefault5 = valorComissao.GetValueOrDefault() * imposto1.get_Iss(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal num5 = valorComissao.GetValueOrDefault() * imposto1.get_Outros(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal valueOrDefault6 = valorComissao.GetValueOrDefault() * imposto1.get_Desconto(); + valorComissao = detalheExtrato.get_ValorComissao(); + decimal num6 = valorComissao.GetValueOrDefault() - (((num4 + valueOrDefault5) + num5) + valueOrDefault6); + Parcela parcela6 = parcela1; + valorComissao = detalheExtrato.get_Valor(); + parcela6.set_ValorRealizado(valorComissao.GetValueOrDefault()); + Parcela parcela7 = parcela1; + valorComissao = detalheExtrato.get_ValorComissao(); + parcela7.set_ValorComissao(valorComissao.GetValueOrDefault()); + parcela1.set_Irr(num4); + parcela1.set_Iss(valueOrDefault5); + parcela1.set_Outros(num5); + parcela1.set_Desconto(valueOrDefault6); + parcela1.set_ValorComDesconto(num6); + parcela1.set_DataRecebimento(this.SelectedExtrato.get_Data()); + Parcela parcela8 = parcela1; + recebimento = this.SelectedExtrato.get_DataCredito(); + nullable2 = (recebimento.HasValue ? recebimento : this.SelectedExtrato.get_Data()); + parcela8.set_DataCredito(nullable2); + parcela1.set_Extrato(this.SelectedExtrato.get_Numero()); + parcela1.set_Vendedores(new ObservableCollection(vendedorParcelas4)); + documento1 = parcela1.get_Documento(); + List list2 = parcelas1; + if (list2 == null) + { + IEnumerable id1 = + from p in parcelas + where p.get_Documento().get_Id() == documento1.get_Id() + select p; + list2 = ( + from p in id1 + orderby p.get_NumeroParcela() + select p).ToList(); + } + parcelas1 = list2; + parcelas1.ForEach((Parcela p) => { + if (p.get_Id() != parcela1.get_Id()) + { + return; + } + p.set_ValorRealizado(parcela1.get_ValorRealizado()); + p.set_ValorComissao(parcela1.get_ValorComissao()); + p.set_Irr(parcela1.get_Irr()); + p.set_Iss(parcela1.get_Iss()); + p.set_Outros(parcela1.get_Outros()); + p.set_Desconto(parcela1.get_Desconto()); + p.set_ValorComDesconto(parcela1.get_ValorComDesconto()); + p.set_DataRecebimento(parcela1.get_DataRecebimento()); + Parcela parcela = p; + DateTime? dataCredito = parcela1.get_DataCredito(); + parcela.set_DataCredito((dataCredito.HasValue ? dataCredito : parcela1.get_DataRecebimento())); + p.set_Extrato(parcela1.get_Extrato()); + }); + bool flag3 = true; + if (parcela1.get_SubTipo() == 1) + { + List parcelas3 = parcelas1; + Parcela parcela9 = parcelas3.FirstOrDefault((Parcela p) => !p.get_DataRecebimento().HasValue); + if (parcela9 != null && parcela9.get_NumeroParcela() < parcela1.get_NumeroParcela()) + { + detalheExtrato.set_Status(new StatusParcela?(7)); + flag3 = false; + flag2 = false; + } + } + if (flag3) + { + Parcela parcela10 = parcela1; + List parcelas4 = parcelas1; + List list3 = parcela1.get_Vendedores().ToList(); + valorComissao = parcela1.get_Documento().get_Controle().get_Seguradora().get_Tolerancia(); + recebimento = await Funcoes.BaixarComissao(parcela10, parcelas4, list3, valorComissao.GetValueOrDefault(), true).get_DataRecebimento(); + if (!recebimento.HasValue) + { + continue; + } + Documento documento3 = parcela1.get_Documento(); + if (documento3 != null) + { + valueOrDefault = documento3.get_TipoRecebimento().GetValueOrDefault() == 1; + } + else + { + valueOrDefault = false; + } + str = (valueOrDefault ? string.Format("PARCELA {0} BAIXADA POR COMISSÃO AUTOMÁTICA, EXTRATO {1}", parcela1.get_NumeroParcela(), detalheExtrato.get_Extrato().get_Numero()) : string.Concat("FATURA ", parcela1.get_Fatura(), " BAIXADA POR COMISSÃO AUTOMÁTICA, EXTRATO ", detalheExtrato.get_Extrato().get_Numero())); + string str3 = str; + RegistroAcao registroAcao = new RegistroAcao(); + registroAcao.set_Descricao(str3); + registroAcao.set_EntidadeId(parcela1.get_Id()); + registroAcao.set_Tela(new TipoTela?(35)); + RegistroAcao registroAcao1 = registroAcao; + if (documento1.get_Tipo() == 0) + { + str1 = string.Concat("APÓLICE: ", detalheExtrato.get_Apolice()); + } + else if (documento1.get_TipoRecebimento().GetValueOrDefault() == 2) + { + string[] apolice = new string[] { "APÓLICE: ", detalheExtrato.get_Apolice(), Environment.NewLine, "FATURA: ", detalheExtrato.get_Endosso() }; + str1 = string.Concat(apolice); + } + else + { + string[] strArrays = new string[] { "APÓLICE: ", detalheExtrato.get_Apolice(), Environment.NewLine, "ENDOSSO: ", detalheExtrato.get_Endosso() }; + str1 = string.Concat(strArrays); + } + string str4 = str1; + object[] cliente = new object[] { detalheExtrato.get_Cliente(), Environment.NewLine, str4, Environment.NewLine, detalheExtrato.get_NumeroParcela(), detalheExtrato.get_Valor(), detalheExtrato.get_Comissao(), detalheExtrato.get_ValorComissao() }; + string str5 = string.Format("CLIENTE: {0}{1}{2}{3}PARCELA: {4}, VALOR: {5:c2} COMISSÃO: {6:N2}% VALOR COMISSÃO: {7:c2}", cliente); + this._parcelaServico.SalvarAcao(registroAcao1, str5); + } + } + else + { + detalheExtrato.set_Status(new StatusParcela?(5)); + await this._servico.Save(detalheExtrato); + continue; + } + } + if (detalheExtrato.get_Corrigir()) + { + if (!await this._apoliceServico.AtualizarNumero(documento1.get_Id(), detalheExtrato.get_Apolice(), detalheExtrato.get_Endosso(), documento1.get_Tipo())) + { + flag = false; + } + } + StatusParcela? status = detalheExtrato.get_Status(); + if (status.HasValue) + { + StatusParcela statusParcela = status.GetValueOrDefault(); + if (statusParcela == 4) + { + detalheExtrato.set_Status(new StatusParcela?(10)); + goto Label1; + } + else + { + if (statusParcela != 14) + { + goto Label2; + } + detalheExtrato.set_Status(new StatusParcela?(13)); + goto Label1; + } + } + Label2: + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato2 = detalheExtrato; + nullable1 = (flag2 ? new StatusParcela?(1) : detalheExtrato.get_Status()); + detalheExtrato2.set_Status(nullable1); + Label1: + await this._servico.Save(detalheExtrato); + if (this._servico.Sucesso) + { + parcelas1 = null; + } + else + { + variable = null; + list1 = null; + parcelas = null; + return; + } + } + else + { + detalheExtrato.set_Status(new StatusParcela?(2)); + await this._servico.Save(detalheExtrato); + } + } + this.SelectedExtrato.set_Status(3); + await this._servico.Save(this.SelectedExtrato); + if (!flag) + { + await base.ShowMessage("OCORREU UM ERRO AO ATUALIZAR O NÚMERO DA APÓLICE/ENDOSSO DOS DOCUMENTOS BAIXADOS.", "OK", "", false); + } + variable = null; + list1 = null; + parcelas = null; + } + + public async Task BaixarTodosExtratos() + { + Func func1 = null; + if (this.Extratos != null && this.Extratos.Count != 0) + { + StatusExtrato status = this.Extratos[0].get_Status(); + this.PorcentagemExtrato = decimal.Zero; + this.IndiceTotal = decimal.Zero; + this.TotalExtratos = this.Extratos.Count; + List statusParcelas = new List() + { + 9, + 14, + 16, + 4, + 17, + 15, + 18 + }; + List statusParcelas1 = statusParcelas; + await Task.Run(async () => { + ObservableCollection extratos = this.Extratos; + Func u003cu003e9_2281 = ComissaoViewModel.u003cu003ec.u003cu003e9__228_1; + if (u003cu003e9_2281 == null) + { + u003cu003e9_2281 = (Extrato x) => x.get_Data(); + ComissaoViewModel.u003cu003ec.u003cu003e9__228_1 = u003cu003e9_2281; + } + foreach (Extrato extrato in extratos.OrderBy(u003cu003e9_2281)) + { + decimal indiceTotal = this.IndiceTotal; + this.IndiceTotal = indiceTotal++; + this.PorcentagemExtrato = (this.IndiceTotal * new decimal(100)) / this.TotalExtratos; + ObservableCollection observableCollection = await this.CarregarDetalhes(extrato); + Func u003cu003e9_2 = func1; + if (u003cu003e9_2 == null) + { + Func hasValue = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas1.Contains(x.get_Status().Value); + }; + Func func = hasValue; + func1 = hasValue; + u003cu003e9_2 = func; + } + List list = observableCollection.Where(u003cu003e9_2).ToList(); + this.SelectedExtrato = extrato; + ComissaoViewModel u003cu003e4_this = this; + List detalheExtratos = list; + Func u003cu003e9_2283 = ComissaoViewModel.u003cu003ec.u003cu003e9__228_3; + if (u003cu003e9_2283 == null) + { + u003cu003e9_2283 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Cliente(); + ComissaoViewModel.u003cu003ec.u003cu003e9__228_3 = u003cu003e9_2283; + } + IOrderedEnumerable detalheExtratos1 = detalheExtratos.OrderBy(u003cu003e9_2283); + Func u003cu003e9_2284 = ComissaoViewModel.u003cu003ec.u003cu003e9__228_4; + if (u003cu003e9_2284 == null) + { + u003cu003e9_2284 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Apolice(); + ComissaoViewModel.u003cu003ec.u003cu003e9__228_4 = u003cu003e9_2284; + } + IOrderedEnumerable detalheExtratos2 = detalheExtratos1.ThenBy(u003cu003e9_2284); + Func u003cu003e9_2285 = ComissaoViewModel.u003cu003ec.u003cu003e9__228_5; + if (u003cu003e9_2285 == null) + { + u003cu003e9_2285 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Endosso(); + ComissaoViewModel.u003cu003ec.u003cu003e9__228_5 = u003cu003e9_2285; + } + IOrderedEnumerable detalheExtratos3 = detalheExtratos2.ThenBy(u003cu003e9_2285); + Func u003cu003e9_2286 = ComissaoViewModel.u003cu003ec.u003cu003e9__228_6; + if (u003cu003e9_2286 == null) + { + u003cu003e9_2286 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_NumeroParcela(); + ComissaoViewModel.u003cu003ec.u003cu003e9__228_6 = u003cu003e9_2286; + } + await u003cu003e4_this.BaixarExtrato(detalheExtratos3.ThenBy(u003cu003e9_2286).ToList()); + } + }); + this.SelecionaSeguradora(this.SelectedSeguradora, status, null); + base.ToggleSnackBar("EXTRATOS BAIXADOS COM SUCESSO", true); + } + } + + public async Task BuscarCriticado(Gestor.Model.Domain.Seguros.DetalheExtrato detalhe) + { + long? parcela; + Parcela parcela1; + if (detalhe != null) + { + this.SelectedDetalhe = this.DetalheExtratoFiltrados.First((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Id() == detalhe.get_Id()); + if (this.SelectedDetalhe.get_Parcela().HasValue || this.SelectedDetalhe.get_Documento().HasValue) + { + this.Buscando = true; + ParcelaServico parcelaServico = new ParcelaServico(); + parcela1 = null; + Documento documento = null; + if (this.SelectedDetalhe.get_Parcela().HasValue) + { + parcela = this.SelectedDetalhe.get_Parcela(); + parcela1 = await parcelaServico.BuscarParcela(parcela.Value); + if (parcela1 != null) + { + detalhe.set_Documento(new long?(parcela1.get_Documento().get_Id())); + documento = parcela1.get_Documento(); + } + } + if (this.SelectedDetalhe.get_Documento().HasValue && !this.SelectedDetalhe.get_Parcela().HasValue) + { + ApoliceServico apoliceServico = this._apoliceServico; + parcela = this.SelectedDetalhe.get_Documento(); + Documento documento1 = await apoliceServico.BuscarApoliceAsync(parcela.Value, false, false); + documento = documento1; + } + if (documento != null) + { + this.SelectedCliente = documento.get_Controle().get_Cliente(); + await this.SelecionaCliente(documento.get_Controle().get_Cliente()); + this.SelectedDocumento = this.Apolices.FirstOrDefault((Documento x) => x.get_Id() == documento.get_Id()); + await this.SelecionaDocumento(documento); + this.SelecionaParcela(parcela1); + this.Buscando = false; + } + else + { + this.Buscando = false; + } + } + else + { + this.TodasApolices = null; + this.Apolices = null; + this.Parcelas = null; + } + } + parcela1 = null; + } + + public async Task CarregaDetalhes(Extrato extrato) + { + if (extrato != null && extrato.get_Id() != 0) + { + this._carregadoDetalhes = true; + this.AllSelected = false; + this.DetalheExtrato = await this._servico.BuscarDetalhes(extrato.get_Id()); + this.DetalheExtratoFiltrados = this.DetalheExtrato; + this.SelecionaNormal(); + this._carregadoDetalhes = false; + List statusParcelas = new List() + { + 2, + 3 + }; + List statusParcelas1 = new List() + { + 1, + 13, + 10 + }; + List statusParcelas2 = new List() + { + 16, + 9, + 14, + 4, + 17, + 18 + }; + List statusParcelas3 = statusParcelas2; + List statusParcelas4 = new List() + { + 1, + 13, + 10, + 5, + 12, + 6, + 8 + }; + List statusParcelas5 = statusParcelas4; + this.DesfazerVisibility = this.DetalheExtrato.Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas1.Contains(x.get_Status().Value); + }); + this.DesconsiderarVisibility = this.DetalheExtrato.Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas.Contains(x.get_Status().Value); + }); + this.BaixarVisibility = this.DetalheExtrato.Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas3.Contains(x.get_Status().Value); + }); + if (this.SelectedExtrato != null) + { + this.FinalizarVisibility = this.DetalheExtrato.All((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue || !statusParcelas5.Contains(x.get_Status().Value)) + { + return false; + } + if (this.SelectedExtrato.get_Status() == 1) + { + return true; + } + return !this.SelectedExtrato.get_Completo(); + }); + } + } + } + + private async Task> CarregarDetalhes(Extrato extrato) + { + return await this._servico.BuscarDetalhes(extrato.get_Id()); + } + + public Imposto CarregarImposto(Documento documento) + { + return this.Impostos.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != documento.get_Controle().get_Seguradora().get_Id() || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == documento.get_Controle().get_Ramo().get_Id(); + }) ?? this.Impostos.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != documento.get_Controle().get_Seguradora().get_Id()) + { + return false; + } + return x.get_Ramo() == null; + }) ?? this.Impostos.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() != null || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == documento.get_Controle().get_Ramo().get_Id(); + }) ?? this.Impostos.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() != null) + { + return false; + } + return x.get_Ramo() == null; + }) ?? new Imposto(); + } + + private async Task CarregarImpostos() + { + List impostos = await (new ImpostoServico()).Buscar(new bool?(true)); + ComissaoViewModel comissaoViewModel = this; + List impostos1 = impostos; + if (impostos1 == null) + { + impostos1 = new List(); + } + comissaoViewModel.Impostos = impostos1; + } + + public async Task Criticar(Gestor.Model.Domain.Seguros.DetalheExtrato detalhe, bool critica) + { + long? nullable; + StatusParcela statusParcela; + long? nullable1; + string str; + object obj; + bool subTipo; + StatusParcela statusParcela1; + ComissaoViewModel.u003cu003ec__DisplayClass215_0 variable; + List detalheExtratos; + if (detalhe != null && this.SelectedDocumento != null | !critica) + { + base.Loading(true); + this.IsVisibleDetalhes = Visibility.Collapsed; + detalheExtratos = new List(); + if (critica) + { + List configuracoes = Recursos.Configuracoes; + bool flag = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 12); + SubTipo? subTipo1 = detalhe.get_SubTipo(); + if (!subTipo1.HasValue || subTipo1.GetValueOrDefault() > 1) + { + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato = detalhe; + if (this.SelectedParcela == null || !flag && this.SelectedParcela.get_SubTipo() == 1) + { + statusParcela = 17; + } + else + { + statusParcela = (this.SelectedParcela.get_DataRecebimento().HasValue ? 5 : 14); + } + detalheExtrato.set_Status(new StatusParcela?(statusParcela)); + detalhe.set_Documento(new long?(this.SelectedDocumento.get_Id())); + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato1 = detalhe; + if (this.SelectedParcela != null && this.SelectedParcela.get_Id() != 0) + { + if (!flag) + { + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela != null) + { + subTipo = selectedParcela.get_SubTipo() == 1; + } + else + { + subTipo = false; + } + if (subTipo) + { + goto Label1; + } + } + nullable1 = new long?(this.SelectedParcela.get_Id()); + goto Label0; + } + Label1: + nullable = null; + nullable1 = nullable; + Label0: + detalheExtrato1.set_Parcela(nullable1); + } + else + { + ObservableCollection parcelas = this.Parcelas; + Parcela parcela1 = parcelas.FirstOrDefault((Parcela x) => !x.get_DataRecebimento().HasValue); + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato2 = detalhe; + if (parcela1 == null || parcela1.get_NumeroParcela() >= this.SelectedParcela.get_NumeroParcela()) + { + statusParcela1 = (this.SelectedParcela.get_DataRecebimento().HasValue ? 5 : 14); + } + else + { + statusParcela1 = 7; + } + detalheExtrato2.set_Status(new StatusParcela?(statusParcela1)); + detalhe.set_Documento(new long?(this.SelectedDocumento.get_Id())); + detalhe.set_Parcela(new long?(this.SelectedParcela.get_Id())); + IEnumerable detalheExtratos1 = this.DetalheExtrato.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!(x.get_Cliente() == this.detalhe.get_Cliente()) || !(x.get_Apolice() == this.detalhe.get_Apolice()) || !(x.get_NumeroParcela() != this.detalhe.get_NumeroParcela()) || x.get_SubTipo().GetValueOrDefault() != 1) + { + return false; + } + if (x.get_Status().GetValueOrDefault() == 2) + { + return true; + } + return x.get_Status().GetValueOrDefault() == 3; + }); + detalheExtratos = ( + from x in detalheExtratos1 + orderby x.get_NumeroParcela() + select x).ToList(); + bool count = detalheExtratos.Count > 0; + if (count) + { + count = await base.ShowMessage("DESEJA CRITICAR AUTOMATICAMENTE AS PRÓXIMAS PARCELAS DESTE DOCUMENTO?", "SIM", "NÃO", false); + } + if (!count) + { + detalheExtratos = null; + } + else + { + detalheExtratos.ForEach((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + int num; + if (!int.TryParse(x.get_NumeroParcela(), out num)) + { + return; + } + Parcela parcela = this.Parcelas.FirstOrDefault((Parcela p) => p.get_NumeroParcela() == int.Parse(x.get_NumeroParcela())); + if (parcela == null) + { + return; + } + x.set_Status(new StatusParcela?((parcela1 == null || parcela1.get_NumeroParcela() >= parcela.get_NumeroParcela() ? (parcela.get_DataRecebimento().HasValue ? 5 : 14) : 7))); + x.set_Documento(new long?(this.SelectedDocumento.get_Id())); + x.set_Parcela(new long?(parcela.get_Id())); + }); + } + } + } + else + { + detalhe.set_Status(new StatusParcela?(6)); + nullable = null; + detalhe.set_Documento(nullable); + nullable = null; + detalhe.set_Parcela(nullable); + } + await this._servico.Save(detalhe); + if (this._servico.Sucesso) + { + if (detalheExtratos != null && detalheExtratos.Count > 0) + { + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato3 in detalheExtratos) + { + await this._servico.Save(detalheExtrato3); + if (this._servico.Sucesso) + { + continue; + } + variable = null; + detalheExtratos = null; + return; + } + } + await this.CarregaDetalhes(this.SelectedExtrato); + this.IsVisibleDetalhes = Visibility.Visible; + base.Loading(false); + base.ToggleSnackBar("CRÍTICA REALIZADA COM SUCESSO", true); + str = (this.SelectedParcela == null ? "ESPECIAL" : this.SelectedParcela.get_NumeroParcela().ToString()); + string str1 = str; + ComissaoViewModel comissaoViewModel = this; + object[] numeroParcela = new object[] { (critica ? "CRITICOU" : "DESCONSIDEROU"), detalhe.get_NumeroParcela(), detalhe.get_Extrato().get_Numero(), detalhe.get_Extrato().get_Id() }; + string str2 = string.Format("{0} PARCELA NÚMERO \"{1}\" DO EXTRATO NÚMERO \n{2}\n, ID {3}", numeroParcela); + long id = this.SelectedExtrato.get_Id(); + TipoTela? nullable2 = new TipoTela?(35); + obj = (critica ? string.Format("CRITICOU A PARCELA \"{0}\" DO DOCUMENTO DE ID \n{1}\n", str1, this.SelectedDocumento.get_Id()) : ""); + comissaoViewModel.RegistrarAcao(str2, id, nullable2, obj); + } + else + { + base.Loading(false); + } + } + variable = null; + detalheExtratos = null; + } + + public async Task CriticarTodos(long id) + { + ObservableCollection observableCollection = await this._servico.BuscarDetalhes(id); + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato in observableCollection) + { + if (detalheExtrato.get_Status().GetValueOrDefault() != 2 && detalheExtrato.get_Status().GetValueOrDefault() != 3) + { + continue; + } + detalheExtrato.set_Status(new StatusParcela?(6)); + await this._servico.Save(detalheExtrato); + if (this._servico.Sucesso) + { + continue; + } + observableCollection = null; + return; + } + ObservableCollection observableCollection1 = observableCollection; + if (observableCollection1.All((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Status().GetValueOrDefault() == 6)) + { + this.SelectedExtrato.set_Status(3); + this.SelectedStatusExtrato = 3; + await this.SelecionaExtrato(this.SelectedExtrato); + } + await this.CarregaDetalhes(this.SelectedExtrato); + base.ToggleSnackBar("CRÍTICA REALIZADA COM SUCESSO", true); + base.RegistrarAcao(string.Format("DESCONSIDEROU TODAS AS PARCELAS COM O STATUS DE DOCUMENTO NÃO ENCONTRADO OU PARCELA NÃO ENCONTRADA DO EXTRATO DE ID \n{0}\n", id), id, new TipoTela?(35), null); + observableCollection = null; + } + + public async Task DesconsiderarSelecionadas() + { + if (this.DetalheExtrato != null && this.DetalheExtrato.Count != 0) + { + List statusParcelas = new List() + { + 1, + 5, + 8, + 10, + 12, + 13, + 21, + 8, + 6 + }; + List statusParcelas1 = statusParcelas; + ObservableCollection detalheExtrato = this.DetalheExtrato; + IEnumerable selecionado = + from parcelas in detalheExtrato + where parcelas.get_Selecionado() + select parcelas; + if (selecionado.Any((Gestor.Model.Domain.Seguros.DetalheExtrato parcelas) => statusParcelas1.Any((StatusParcela status) => { + StatusParcela? nullable = parcelas.get_Status(); + return status == nullable.GetValueOrDefault() & nullable.HasValue; + }))) + { + await base.ShowMessage("HÁ PARCELAS SELECIONADAS QUE JÁ ESTÃO BAIXADAS OU JÁ DESCONSIDERADAS", "OK", "", false); + } + else + { + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato1 in selecionado) + { + detalheExtrato1.set_Status(new StatusParcela?(6)); + await this._servico.Save(detalheExtrato1); + if (this._servico.Sucesso) + { + continue; + } + return; + } + await this.CarregaDetalhes(this.SelectedExtrato); + } + } + } + + public async Task DesfazerExtrato() + { + ObservableCollection observableCollection; + if (this.DetalheExtrato != null && this.DetalheExtrato.Count != 0) + { + List statusParcelas = new List() + { + 1, + 10, + 12, + 13 + }; + List list = this.DetalheExtrato.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas.Contains(x.get_Status().Value); + }).ToList(); + if (list.Count != 0) + { + this.Porcentagem = decimal.Zero; + this.Indice = decimal.Zero; + this.Total = list.Count; + List detalheExtratos4 = new List(); + await Task.Run(async () => { + List detalheExtratos = list; + Func u003cu003e9_2352 = ComissaoViewModel.u003cu003ec.u003cu003e9__235_2; + if (u003cu003e9_2352 == null) + { + u003cu003e9_2352 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Cliente(); + ComissaoViewModel.u003cu003ec.u003cu003e9__235_2 = u003cu003e9_2352; + } + IOrderedEnumerable detalheExtratos1 = detalheExtratos.OrderBy(u003cu003e9_2352); + Func u003cu003e9_2353 = ComissaoViewModel.u003cu003ec.u003cu003e9__235_3; + if (u003cu003e9_2353 == null) + { + u003cu003e9_2353 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Apolice(); + ComissaoViewModel.u003cu003ec.u003cu003e9__235_3 = u003cu003e9_2353; + } + IOrderedEnumerable detalheExtratos2 = detalheExtratos1.ThenBy(u003cu003e9_2353); + Func u003cu003e9_2354 = ComissaoViewModel.u003cu003ec.u003cu003e9__235_4; + if (u003cu003e9_2354 == null) + { + u003cu003e9_2354 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Endosso(); + ComissaoViewModel.u003cu003ec.u003cu003e9__235_4 = u003cu003e9_2354; + } + IOrderedEnumerable detalheExtratos3 = detalheExtratos2.ThenBy(u003cu003e9_2354); + Func u003cu003e9_2355 = ComissaoViewModel.u003cu003ec.u003cu003e9__235_5; + if (u003cu003e9_2355 == null) + { + u003cu003e9_2355 = (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_NumeroParcela(); + ComissaoViewModel.u003cu003ec.u003cu003e9__235_5 = u003cu003e9_2355; + } + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato in detalheExtratos3.ThenByDescending(u003cu003e9_2355)) + { + decimal indice = this.Indice; + this.Indice = indice++; + this.Porcentagem = (this.Indice * new decimal(100)) / this.Total; + if (!await this.DesfazerParcela(detalheExtrato)) + { + detalheExtratos4.Add(detalheExtrato); + } + } + }); + this.SelectedExtrato.set_Status(1); + await this._servico.Save(this.SelectedExtrato); + if (this._servico.Sucesso) + { + observableCollection = await this.CarregarDetalhes(this.SelectedExtrato); + if (detalheExtratos4.Count <= 0) + { + base.ToggleSnackBar("EXTRATO DESFEITO COM SUCESSO", true); + } + else + { + await base.ShowDetalheExtrato(detalheExtratos4); + } + base.RegistrarAcao(string.Format("DESFEZ EXTRATO DE ID \n{0}\n", this.SelectedExtrato.get_Id()), this.SelectedExtrato.get_Id(), new TipoTela?(35), null); + bool flag = !observableCollection.Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas.Contains(x.get_Status().Value); + }); + if (flag) + { + flag = await base.ShowMessage("DESEJA EXCLUIR O EXTRATO DESFEITO?", "SIM", "NÃO", false); + } + if (flag) + { + await this.ExcluirExtrato(); + this.SelectedExtrato = null; + } + this.Carregando = true; + this.SelectedStatusExtrato = 1; + this.Carregando = false; + this.SelecionaSeguradora(this.SelectedSeguradora, this.SelectedStatusExtrato, this.SelectedExtrato); + } + } + else + { + await base.ShowMessage("NÃO HÁ PARCELAS PARA SEREM DESFEITAS NO EXTRATO", "OK", "", false); + } + } + observableCollection = null; + } + + public async Task DesfazerParcela(Gestor.Model.Domain.Seguros.DetalheExtrato detalhe) + { + bool flag; + long? parcela; + bool hasValue; + bool flag1; + StatusParcela statusParcela; + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato = detalhe; + if (detalheExtrato != null) + { + parcela = detalheExtrato.get_Parcela(); + hasValue = !parcela.HasValue; + } + else + { + hasValue = true; + } + if (!hasValue) + { + try + { + ParcelaServico parcelaServico = this._parcelaServico; + parcela = detalhe.get_Parcela(); + Parcela parcela1 = await parcelaServico.BuscarParcela(parcela.Value); + if (parcela1 != null) + { + detalhe.set_Documento(new long?(parcela1.get_Documento().get_Id())); + parcela1.set_Extrato(null); + ParcelaServico parcelaServico1 = this._parcelaServico; + parcela = detalhe.get_Documento(); + List parcelas = await parcelaServico1.BuscarParcelas(parcela.Value); + List parcelas1 = parcelas; + IOrderedEnumerable numeroParcela = + from p in parcelas1 + orderby p.get_NumeroParcela() descending + select p; + Parcela parcela2 = numeroParcela.FirstOrDefault((Parcela p) => { + if (!p.get_DataRecebimento().HasValue) + { + return false; + } + return p.get_SubTipo() == 1; + }); + bool flag2 = await this._parcelaServico.TemPagamento(parcela1.get_Id()); + if (parcela1.get_Documento().get_TipoRecebimento().GetValueOrDefault() != 1) + { + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 28)) + { + goto Label0; + } + } + if (flag2) + { + flag1 = true; + } + else + { + flag1 = (parcela2 == null ? false : parcela2.get_NumeroParcela() > parcela1.get_NumeroParcela()); + } + flag2 = flag1; + Label0: + if (!flag2 || parcela1.get_Documento().get_Excluido()) + { + VendedorServico vendedorServico = this._vendedorServico; + parcela = detalhe.get_Documento(); + List vendedorParcelas = await vendedorServico.BuscaRepasse(parcela.Value); + await Funcoes.ExcluirBaixa(parcela1, vendedorParcelas, parcelas); + Parcela parcela3 = parcelas.FirstOrDefault((Parcela x) => x.get_NumeroParcela() == int.Parse(detalhe.get_NumeroParcela()) - 1); + Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtrato1 = detalhe; + if (parcela3 != null && !parcela3.get_DataRecebimento().HasValue) + { + statusParcela = 7; + } + else if (detalhe.get_Status().GetValueOrDefault() == 13) + { + statusParcela = 14; + } + else + { + decimal? comissao = detalhe.get_Comissao(); + if (comissao.HasValue) + { + decimal num = parcela1.get_Documento().get_Comissao(); + comissao = detalhe.get_Comissao(); + if ((num == comissao.GetValueOrDefault()) & comissao.HasValue) + { + goto Label2; + } + statusParcela = 4; + goto Label1; + } + Label2: + statusParcela = 9; + } + Label1: + detalheExtrato1.set_Status(new StatusParcela?(statusParcela)); + await this._servico.Save(detalhe); + flag = true; + } + else + { + flag = false; + } + } + else + { + parcela = null; + detalhe.set_Documento(parcela); + parcela = null; + detalhe.set_Parcela(parcela); + detalhe.set_Status(new StatusParcela?(2)); + await this._servico.Save(detalhe); + flag = false; + } + } + catch (Exception exception1) + { + Exception exception = exception1; + (new BaseServico()).Registrar(exception, 292, 3, detalhe, true); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task ExcluirExtrato() + { + if (this.SelectedExtrato != null) + { + List statusParcelas = new List() + { + 1, + 10, + 13 + }; + try + { + if (this.DetalheExtrato.Any((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (!x.get_Status().HasValue) + { + return false; + } + return statusParcelas.Contains(x.get_Status().Value); + })) + { + await base.ShowMessage("O EXTRATO NÃO PODE SER EXCLUÍDO POIS FOI UTILIZADO PARA BAIXAR PARCELAS, DESFAÇA O EXTRATO ANTES DE EXCLUÍ-LO", "OK", "", false); + return; + } + else if (await this._servico.Delete(this.SelectedExtrato)) + { + base.RegistrarAcao(string.Format("EXCLUIU EXTRATO DE ID \n{0}\n", this.SelectedExtrato.get_Id()), this.SelectedExtrato.get_Id(), new TipoTela?(35), null); + this.SelectedExtrato = null; + this.SelecionaSeguradora(this.SelectedSeguradora, 1, null); + base.ToggleSnackBar("EXTRATO EXCLUÍDO COM SUCESSO", true); + } + else + { + return; + } + } + catch (Exception exception) + { + } + } + } + + public void ExcluirFiltro(string filtro) + { + this.FiltroPersonalizado.Remove(filtro); + this.FiltrarExtrato(); + } + + private List Filtrar() + { + List list = this.Extratos.ToList(); + this.FiltroPersonalizado.ToList().ForEach((string f) => { + IEnumerable extratos = list.Where((Extrato x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Seguradora().get_Nome()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(f)) || ValidationHelper.RemoveDiacritics(x.get_Numero()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(f)) || x.get_Data().HasValue && x.get_Data().ToString().Contains(f) || x.get_Bruto().HasValue && x.get_Bruto().ToString().Contains(f) || x.get_Liquido().HasValue && x.get_Liquido().ToString().Contains(f)) + { + return true; + } + if (!x.get_DataCredito().HasValue) + { + return false; + } + return x.get_DataCredito().ToString().Contains(f); + }); + Func u003cu003e9_2542 = ComissaoViewModel.u003cu003ec.u003cu003e9__254_2; + if (u003cu003e9_2542 == null) + { + u003cu003e9_2542 = (Extrato x) => x.get_Numero(); + ComissaoViewModel.u003cu003ec.u003cu003e9__254_2 = u003cu003e9_2542; + } + IOrderedEnumerable extratos1 = extratos.OrderBy(u003cu003e9_2542); + Func u003cu003e9_2543 = ComissaoViewModel.u003cu003ec.u003cu003e9__254_3; + if (u003cu003e9_2543 == null) + { + u003cu003e9_2543 = (Extrato x) => x.get_DataCredito(); + ComissaoViewModel.u003cu003ec.u003cu003e9__254_3 = u003cu003e9_2543; + } + list = extratos1.ThenByDescending(u003cu003e9_2543).ToList(); + }); + return list; + } + + internal async Task> FiltrarApolices(string value) + { + List documentos = await Task.Run>(() => this.FiltrarDocumento(value)); + return documentos; + } + + internal async Task> FiltrarDetalhe(string value) + { + List detalheExtratos = await Task.Run>(() => this.FiltrarDetalheExtrato(value)); + return detalheExtratos; + } + + public List FiltrarDetalheExtrato(string filter) + { + if (this.DetalheExtrato == null) + { + return null; + } + this.DetalheExtratoFiltrados = (string.IsNullOrWhiteSpace(filter) ? this.DetalheExtrato : new ObservableCollection(this.DetalheExtrato.Where((Gestor.Model.Domain.Seguros.DetalheExtrato x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Cliente()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) || x.get_Apolice().Contains(filter)) + { + return true; + } + return x.get_Endosso().Contains(filter); + }).OrderBy((Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.get_Cliente()))); + return this.DetalheExtratoFiltrados.ToList(); + } + + public List FiltrarDetalheExtrato(long id) + { + this.DetalheExtratoFiltrados = new ObservableCollection( + from x in this.DetalheExtrato + where x.get_Id() == id + select x); + return this.DetalheExtratoFiltrados.ToList(); + } + + public List FiltrarDocumento(string filter) + { + this.Apolices = (string.IsNullOrWhiteSpace(filter) ? this.TodasApolices : new ObservableCollection(this.TodasApolices.Where((Documento x) => { + if (x.get_Apolice() != null && x.get_Apolice().ToUpper().Contains(filter.ToUpper()) || x.get_Endosso() != null && x.get_Endosso().ToUpper().Contains(filter.ToUpper()) || x.get_Vigencia1().ToString("d").Contains(filter)) + { + return true; + } + if (!x.get_Vigencia2().HasValue) + { + return false; + } + return x.get_Vigencia2().Value.ToString("d").Contains(filter); + }))); + this.SelectedDocumento = null; + this.SelectedParcela = null; + ObservableCollection apolices = this.Apolices; + if (apolices != null) + { + return apolices.ToList(); + } + return null; + } + + public void FiltrarExtrato() + { + bool count; + this.ExtratosFiltrados = new ObservableCollection(this.Filtrar()); + this.SelectedExtrato = this.ExtratosFiltrados.FirstOrDefault(); + ObservableCollection extratosFiltrados = this.ExtratosFiltrados; + if (extratosFiltrados != null) + { + count = extratosFiltrados.Count > 0; + } + else + { + count = false; + } + this.IsExpanded = count; + } + + public async Task FinalizarExtrato() + { + if (this.DetalheExtrato != null && this.DetalheExtrato.Count != 0) + { + StatusExtrato selectedStatusExtrato = this.SelectedStatusExtrato; + this.SelectedExtrato.set_Status(3); + Extrato extrato = await this._servico.Save(this.SelectedExtrato); + if (this._servico.Sucesso) + { + this.SelectedExtrato = null; + this.SelecionaSeguradora(this.SelectedSeguradora, selectedStatusExtrato, null); + base.ToggleSnackBar("EXTRATO FINALIZADO COM SUCESSO", true); + base.RegistrarAcao(string.Format("FINALIZOU EXTRATO DE ID \n{0}\n", extrato.get_Id()), extrato.get_Id(), new TipoTela?(35), null); + } + } + } + + public async Task GerarHtml() + { + string nome; + ExtratoComissao extratoComissao = new ExtratoComissao(); + Usuario usuario = Auxiliar.get_Usuarios().FirstOrDefault((Usuario x) => x.get_Id() == this.SelectedExtrato.get_IdUsuario()); + if (usuario != null) + { + nome = usuario.get_Nome(); + } + else + { + nome = null; + } + extratoComissao.set_Usuario(nome); + extratoComissao.set_Seguradora(this.SelectedExtrato.get_Seguradora().get_Nome()); + extratoComissao.set_DetalhesExtrato(new ObservableCollection()); + ObservableCollection observableCollection = new ObservableCollection(); + InformacoesExtrato informacoesExtrato = new InformacoesExtrato(); + informacoesExtrato.set_NumeroExtrato(this.SelectedExtrato.get_Numero()); + informacoesExtrato.set_DataExtrato(this.SelectedExtrato.get_Data()); + decimal? bruto = this.SelectedExtrato.get_Bruto(); + informacoesExtrato.set_Bruto(bruto.GetValueOrDefault()); + bruto = this.SelectedExtrato.get_Liquido(); + informacoesExtrato.set_Liquido(bruto.GetValueOrDefault()); + bruto = this.SelectedExtrato.get_Ir(); + informacoesExtrato.set_Ir(bruto.GetValueOrDefault()); + bruto = this.SelectedExtrato.get_Iss(); + informacoesExtrato.set_Iss(bruto.GetValueOrDefault()); + bruto = this.SelectedExtrato.get_Outro(); + informacoesExtrato.set_Outros(bruto.GetValueOrDefault()); + informacoesExtrato.set_Quantidade(this.Quantidade); + informacoesExtrato.set_TotalBaixado(this.TotalBaixado); + informacoesExtrato.set_TotalPendente(this.TotalPendente); + observableCollection.Add(informacoesExtrato); + extratoComissao.set_InformacoesExtrato(observableCollection); + ExtratoComissao extratoComissao1 = extratoComissao; + foreach (Gestor.Model.Domain.Seguros.DetalheExtrato detalheExtratoFiltrado in this.DetalheExtratoFiltrados) + { + DetalhesExtrato detalhesExtrato = new DetalhesExtrato(); + detalhesExtrato.set_Cliente(detalheExtratoFiltrado.get_Cliente()); + detalhesExtrato.set_Apolice(detalheExtratoFiltrado.get_Apolice()); + detalhesExtrato.set_Endosso(detalheExtratoFiltrado.get_Endosso()); + detalhesExtrato.set_Parcela(detalheExtratoFiltrado.get_NumeroParcela()); + detalhesExtrato.set_Pagto(detalheExtratoFiltrado.get_Valor()); + detalhesExtrato.set_Comissao(detalheExtratoFiltrado.get_Comissao()); + detalhesExtrato.set_ValorComissao(detalheExtratoFiltrado.get_ValorComissao()); + detalhesExtrato.set_Status(ValidationHelper.GetDescription(detalheExtratoFiltrado.get_Status())); + extratoComissao1.get_DetalhesExtrato().Add(detalhesExtrato); + } + string str = await Funcoes.GenerateTable(extratoComissao1.get_InformacoesExtrato().ToList(), new List(), false, false, "", null); + string str1 = await Funcoes.GenerateTable(extratoComissao1.get_DetalhesExtrato().ToList(), new List(), false, false, "", null); + string str2 = string.Concat(str, str1); + str = null; + string str3 = Funcoes.CreateCard(string.Concat("SEGURADORA: ", extratoComissao1.get_Seguradora(), "
USUÁRIO IMPORTAÇÃO: ", extratoComissao1.get_Usuario()), str2, false); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome("EXTRATO DE COMISSÃO"); + string str4 = str3; + if (str4 == null) + { + str4 = ""; + } + string str5 = Funcoes.ExportarHtml(tipoRelatorio, str4, "70", "landscape", false, ""); + extratoComissao1 = null; + return str5; + } + + private static VendedorParcela PropriaCorretora() + { + Vendedor vendedor = Recursos.Vendedores.FirstOrDefault((Vendedor x) => { + if (x.get_IdEmpresa() != Recursos.Empresa.get_Id()) + { + return false; + } + return x.get_Corretora(); + }); + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(null); + decimal num = new decimal(); + vendedorParcela.set_ValorRepasse(new decimal?(num)); + vendedorParcela.set_Vendedor(vendedor); + num = new decimal(); + vendedorParcela.set_PorcentagemRepasse(new decimal?(num)); + vendedorParcela.set_TipoVendedor(Recursos.TipoVendedor.First((TipoVendedor x) => x.get_Id() == (long)1)); + return vendedorParcela; + } + + public async Task SelecionaCliente(Cliente value) + { + ObservableCollection observableCollection; + long id; + Visibility visibility; + Visibility visibility1; + List nums; + if (value != null && value.get_Id() != 0) + { + observableCollection = await this._apoliceServico.BuscarApolicesComissao(value.get_Id(), this.SelectedStatus); + this.FiltroApolice = string.Empty; + id = this.SelectedExtrato.get_Seguradora().get_Id(); + if (id <= (long)544) + { + if (id <= (long)310) + { + if (id <= (long)182) + { + if (id > (long)93) + { + if (id - (long)112 > (long)1) + { + goto Label15; + } + nums = new List() + { + (long)112, + (long)113 + }; + goto Label11; + } + else + { + if (id == (long)28) + { + goto Label4; + } + if (id - (long)89 > (long)4) + { + goto Label12; + } + List nums1 = new List() + { + (long)89, + (long)90, + (long)91, + (long)92, + (long)93 + }; + nums = nums1; + goto Label11; + } + } + else if (id > (long)261) + { + if (id - (long)291 <= (long)1 || id == (long)296) + { + goto Label0; + } + if (id == (long)310) + { + goto Label5; + } + } + else + { + if (id == (long)216) + { + goto Label9; + } + if (id - (long)258 <= (long)3) + { + goto Label8; + } + } + } + else if (id <= (long)400) + { + if (id > (long)331) + { + if (id == (long)341) + { + goto Label6; + } + if (id == (long)374) + { + goto Label7; + } + if (id == (long)400) + { + goto Label0; + } + } + else + { + if (id == (long)328) + { + goto Label3; + } + if (id == (long)331) + { + goto Label1; + } + } + } + else if (id > (long)480) + { + if (id != (long)501) + { + goto Label13; + } + List nums2 = new List() + { + (long)498, + (long)499, + (long)500, + (long)501, + (long)502 + }; + nums = nums2; + goto Label11; + } + else + { + if (id == (long)402) + { + goto Label0; + } + if (id != (long)480) + { + goto Label12; + } + List nums3 = new List() + { + (long)475, + (long)476, + (long)477, + (long)478, + (long)479, + (long)480, + (long)481, + (long)482, + (long)483, + (long)484, + (long)485, + (long)486, + (long)487, + (long)558, + (long)580, + (long)664 + }; + nums = nums3; + goto Label11; + } + } + else if (id > (long)630) + { + if (id <= (long)674) + { + if (id > (long)643) + { + if (id == (long)649) + { + goto Label4; + } + if (id == (long)650) + { + goto Label5; + } + if (id == (long)674) + { + goto Label0; + } + } + else + { + if (id == (long)631) + { + goto Label6; + } + long num = id - (long)639; + if (num <= (long)4) + { + switch ((uint)num) + { + case 0: + { + goto Label5; + } + case 2: + case 4: + { + goto Label0; + } + } + } + else + { + } + } + } + else if (id > (long)711) + { + if (id == (long)884) + { + goto Label0; + } + if (id == (long)982) + { + goto Label1; + } + if (id == (long)1006) + { + goto Label2; + } + } + else + { + if (id == (long)694) + { + goto Label0; + } + if (id == (long)711) + { + goto Label3; + } + } + } + else if (id > (long)562) + { + if (id > (long)574) + { + if (id == (long)578) + { + goto Label7; + } + long num1 = id - (long)591; + if (num1 <= (long)7) + { + switch ((uint)num1) + { + case 0: + case 1: + case 3: + { + goto Label4; + } + case 2: + case 5: + case 6: + { + goto Label12; + } + case 4: + { + goto Label1; + } + case 7: + { + goto Label8; + } + } + } + else + { + } + if (id == (long)630) + { + goto Label5; + } + } + else + { + if (id == (long)570) + { + goto Label8; + } + if (id == (long)574) + { + goto Label0; + } + } + } + else if (id > (long)552) + { + if (id - (long)554 <= (long)1) + { + goto Label0; + } + if (id == (long)560) + { + goto Label9; + } + if (id == (long)562) + { + goto Label1; + } + } + else if (id == (long)548 || id == (long)552) + { + goto Label10; + } + List nums4 = new List() + { + this.SelectedExtrato.get_Seguradora().get_Id() + }; + nums = nums4; + goto Label11; + } + ComissaoViewModel.u003cu003ec__DisplayClass211_0 variable = null; + return; + List nums5 = new List() + { + (long)70, + (long)291, + (long)292, + (long)296, + (long)400, + (long)401, + (long)402, + (long)554, + (long)555, + (long)574, + (long)641, + (long)643, + (long)674, + (long)694, + (long)884, + (long)348 + }; + nums = nums5; + goto Label11; + List nums6 = new List() + { + (long)331, + (long)543, + (long)562, + (long)595, + (long)982 + }; + nums = nums6; + goto Label11; + nums = new List() + { + (long)182, + (long)1006 + }; + Label11: + ComissaoViewModel comissaoViewModel = this; + IEnumerable documentos = observableCollection.Where((Documento x) => { + if (x.get_Controle().get_Seguradora() == null) + { + return false; + } + return nums.Contains(x.get_Controle().get_Seguradora().get_Id()); + }); + IOrderedEnumerable vigencia2 = + from x in documentos + orderby x.get_Vigencia2() + select x; + comissaoViewModel.TodasApolices = new ObservableCollection(vigencia2.ThenBy((Documento x) => x.get_Controle().get_Id())); + this.Apolices = this.TodasApolices; + ComissaoViewModel comissaoViewModel1 = this; + visibility = (this.TodasApolices.Count > 0 ? Visibility.Visible : Visibility.Collapsed); + comissaoViewModel1.IsVisibleApolice = visibility; + ComissaoViewModel comissaoViewModel2 = this; + visibility1 = (this.TodasApolices.Count > 0 ? Visibility.Collapsed : Visibility.Visible); + comissaoViewModel2.IsVisibleMensagem = visibility1; + variable = null; + return; + List nums7 = new List() + { + (long)328, + (long)329, + (long)711 + }; + nums = nums7; + goto Label11; + List nums8 = new List() + { + (long)28, + (long)591, + (long)592, + (long)594, + (long)649 + }; + nums = nums8; + goto Label11; + List nums9 = new List() + { + (long)310, + (long)630, + (long)639, + (long)650 + }; + nums = nums9; + goto Label11; + nums = new List() + { + (long)341, + (long)631 + }; + goto Label11; + nums = new List() + { + (long)374, + (long)578 + }; + goto Label11; + List nums10 = new List() + { + (long)258, + (long)259, + (long)260, + (long)261, + (long)570, + (long)598, + (long)472, + (long)595, + (long)741, + (long)982 + }; + nums = nums10; + goto Label11; + nums = new List() + { + (long)560, + (long)216 + }; + goto Label11; + List nums11 = new List() + { + (long)544, + (long)548, + (long)552 + }; + nums = nums11; + goto Label11; + Label13: + if (id == (long)543) + { + goto Label1; + } + if (id == (long)544) + { + goto Label10; + } + goto Label12; + goto Label12; + Label15: + if (id == (long)182) + { + goto Label2; + } + goto Label12; + goto Label12; + } + + public async Task SelecionaDocumento(Documento value) + { + if (value != null && value.get_Id() != 0) + { + this.SelectedDocumento = this.Apolices.FirstOrDefault((Documento x) => x.get_Id() == value.get_Id()); + this.Parcelas = await this._parcelaServico.BuscarParcelasAsync(value.get_Id()); + } + } + + public async Task SelecionaExtrato(Extrato extrato) + { + if (extrato != null && extrato.get_Id() != 0) + { + base.Loading(true); + this.IsVisibleDetalhes = Visibility.Collapsed; + this.SelectedExtrato = extrato; + this.PesquisaPagamento = string.Empty; + await this.CarregaDetalhes(extrato); + this.IsVisibleDetalhes = Visibility.Visible; + base.Loading(false); + } + } + + private void SelecionaNormal() + { + ExtensionMethods.ForEach(this.DetalheExtrato, (Gestor.Model.Domain.Seguros.DetalheExtrato detalhe) => detalhe.IsNormal = detalhe.get_SubTipo().GetValueOrDefault() == 1); + } + + public void SelecionaParcela(Parcela value) + { + if (value == null || value.get_Id() == 0) + { + return; + } + this.SelectedParcela = this.Parcelas.FirstOrDefault((Parcela x) => x.get_Id() == value.get_Id()); + } + + private void Selecionar(bool value) + { + ExtensionMethods.ForEach(this.DetalheExtratoFiltrados, (Gestor.Model.Domain.Seguros.DetalheExtrato x) => x.set_Selecionado(value)); + } + + public async void SelecionaSeguradora(Seguradora value, StatusExtrato status, Extrato extrato = null) + { + StatusExtrato statusExtrato; + ObservableCollection observableCollection; + bool count; + Extrato extrato1; + if (!this.Carregando) + { + if (this.Inicio <= this.Fim) + { + this.Filtro = string.Empty; + this.FiltroApolice = string.Empty; + if (value != null) + { + base.Loading(true); + this.IsVisibleExtrato = Visibility.Collapsed; + this.BaixarPendentes = status == 1; + this.DetalheExtrato = null; + if (status == 2) + { + statusExtrato = 3; + } + else + { + statusExtrato = status; + } + StatusExtrato statusExtrato1 = statusExtrato; + List extratos = await this._servico.BuscarExtrato(value.get_Id(), this.SelectedUsuario.get_Id(), statusExtrato1, this.Inicio, this.Fim); + ComissaoViewModel comissaoViewModel = this; + if (status == 2) + { + List extratos1 = extratos; + observableCollection = new ObservableCollection( + from x in extratos1 + where !x.get_Completo() + select x); + } + else if (status == 3) + { + List extratos2 = extratos; + observableCollection = new ObservableCollection( + from x in extratos2 + where x.get_Completo() + select x); + } + else + { + observableCollection = new ObservableCollection(extratos); + } + comissaoViewModel.Extratos = observableCollection; + this.ExtratosFiltrados = this.Extratos; + if (this.FiltroPersonalizado.Count > 0) + { + this.FiltrarExtrato(); + } + ComissaoViewModel comissaoViewModel1 = this; + ObservableCollection extratosFiltrados = this.ExtratosFiltrados; + if (extratosFiltrados != null) + { + count = extratosFiltrados.Count > 0; + } + else + { + count = false; + } + comissaoViewModel1.IsExpanded = count; + extrato1 = (extrato == null ? this.ExtratosFiltrados.FirstOrDefault() : this.ExtratosFiltrados.FirstOrDefault((Extrato x) => x.get_Id() == extrato.get_Id())); + await this.SelecionaExtrato(extrato1); + base.Loading(false); + if (this.SelectedSeguradora != null) + { + string str = string.Format("CONSULTOU COMISSÃO AUTOMÁTICA NO PERÍODO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim); + long num = (long)0; + TipoTela? nullable = new TipoTela?(35); + object[] nome = new object[] { this.SelectedUsuario.get_Nome(), this.SelectedUsuario.get_Id(), this.SelectedSeguradora.get_Nome(), this.SelectedSeguradora.get_Id(), ValidationHelper.GetDescription(this.SelectedStatusExtrato), ValidationHelper.Join(this.FiltroPersonalizado, ", ") }; + base.RegistrarAcao(str, num, nullable, string.Format("USUÁRIO IMPORTAÇÃO: {0} ({1})\nSEGURADORA: {2} ({3})\nSTATUS: {4}\nPESQUISA PERSONALIZADA: \"{5}\"", nome)); + } + } + else + { + this.Extratos = null; + this.ExtratosFiltrados = null; + this.DetalheExtrato = null; + this.DetalheExtratoFiltrados = null; + this.SelectedExtrato = null; + this.SelectedDetalhe = null; + } + } + else + { + await base.ShowMessage("DATA DE INÍCIO NÃO PODE SER MAR QUE A DATA FINAL", "OK", "", false); + } + } + } + + public void SelecionaSeguradoras() + { + base.Loading(true); + List list = ( + from x in Recursos.Seguradoras + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id((long)0); + seguradora.set_Nome("TODAS AS SEGURADORAS"); + seguradora.set_NomeSocial("TODAS DAS SEGURADORAS"); + list.Insert(0, seguradora); + List usuarios = ( + from x in Recursos.Usuarios + where !x.get_Excluido() + orderby x.get_IdEmpresa(), x.get_Nome() + select x).ToList(); + Usuario usuario = new Usuario(); + usuario.set_Id((long)0); + usuario.set_Nome("TODOS OS USUÁRIOS"); + usuarios.Insert(0, usuario); + this.Usuarios = new ObservableCollection(usuarios); + this.Seguradoras = new ObservableCollection(list); + base.Loading(false); + } + + private async void WorkOnSelectedCliente(Cliente value) + { + if (value == null || value.get_Id() == 0) + { + this.IsVisibleCliente = Visibility.Collapsed; + this.IsVisibleApolice = Visibility.Collapsed; + this.IsVisibleMensagem = Visibility.Collapsed; + this.DocumentoPrincipal = string.Empty; + this.SelectedDocumento = null; + this.SelectedParcela = null; + } + else + { + this.IsVisibleCliente = Visibility.Visible; + if (!this.Buscando) + { + base.Loading(true); + this.IsVisibleDetalhes = Visibility.Collapsed; + } + if (!this.Buscando) + { + this.Buscando = true; + await this.SelecionaCliente(value); + await this.SelecionaDocumento(this.Apolices.FirstOrDefault()); + this.Buscando = false; + Cliente cliente = value; + TipoDocumento? documentoPrincipal = value.get_DocumentoPrincipal(); + cliente.set_DocumentoPrincipal(new TipoDocumento?(documentoPrincipal.GetValueOrDefault())); + documentoPrincipal = value.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + switch (documentoPrincipal.GetValueOrDefault()) + { + case 0: + { + ComissaoViewModel comissaoViewModel = this; + string documento = value.get_Documento(); + if (documento == null) + { + documento = ""; + } + comissaoViewModel.DocumentoPrincipal = documento; + break; + } + case 1: + { + ComissaoViewModel comissaoViewModel1 = this; + string rne = value.get_Rne(); + if (rne == null) + { + rne = ""; + } + comissaoViewModel1.DocumentoPrincipal = rne; + break; + } + case 2: + { + ComissaoViewModel comissaoViewModel2 = this; + string cei = value.get_Cei(); + if (cei == null) + { + cei = ""; + } + comissaoViewModel2.DocumentoPrincipal = cei; + break; + } + } + } + this.IsVisibleDetalhes = Visibility.Visible; + base.Loading(false); + } + } + } + + private void WorkOnSelectedDocumento(Documento value) + { + if (value == null || value.get_Id() == 0 || this.Buscando) + { + return; + } + TipoRecebimento? tipoRecebimento = value.get_TipoRecebimento(); + this.IsFatura = tipoRecebimento.GetValueOrDefault() == 2; + } + + public async void WorkOnSelectedStatus() + { + if (this.SelectedCliente != null) + { + if (!this.Buscando) + { + await this.SelecionaCliente(this.SelectedCliente); + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Command/RelayCommand.cs b/Codemerx/Gestor.Application/ViewModels/Command/RelayCommand.cs new file mode 100644 index 0000000..fb3d646 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Command/RelayCommand.cs @@ -0,0 +1,29 @@ +using System; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Windows.Input; + +namespace Gestor.Application.ViewModels.Command +{ + public class RelayCommand : ICommand + { + private Action mAction; + + public RelayCommand(Action action) + { + this.mAction = action; + } + + public bool CanExecute(object parameter) + { + return true; + } + + public void Execute(object parameter) + { + this.mAction(); + } + + public event EventHandler CanExecuteChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Configuracoes/ConfiguracoesViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Configuracoes/ConfiguracoesViewModel.cs new file mode 100644 index 0000000..b399eb5 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Configuracoes/ConfiguracoesViewModel.cs @@ -0,0 +1,178 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Configuracoes; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Configuracoes +{ + public class ConfiguracoesViewModel : BaseViewModel + { + private bool _hasRows; + + private ObservableCollection _configuracoes; + + private Configuracao _selectedConfiguracao; + + private string _descricao; + + private bool _carregando; + + private ObservableCollection _configuracoesAdicionadas; + + private ConfuguracoesServico _servico + { + get; + set; + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Configuracoes + { + get + { + return this._configuracoes; + } + set + { + this._configuracoes = value; + base.EnableFields = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("Configuracoes"); + } + } + + public ObservableCollection ConfiguracoesAdicionadas + { + get + { + return this._configuracoesAdicionadas; + } + set + { + this._configuracoesAdicionadas = value; + this.HasRows = (value != null ? value.Count > 0 : false); + this.PopularConfiguracoes(value); + base.OnPropertyChanged("ConfiguracoesAdicionadas"); + } + } + + public string Descricao + { + get + { + return this._descricao; + } + set + { + this._descricao = value; + base.OnPropertyChanged("Descricao"); + } + } + + public bool HasRows + { + get + { + return this._hasRows; + } + set + { + this._hasRows = value; + base.OnPropertyChanged("HasRows"); + } + } + + public Configuracao SelectedConfiguracao + { + get + { + return this._selectedConfiguracao; + } + set + { + this._selectedConfiguracao = value; + this.Descricao = ValidationHelper.GetCategory(value); + base.OnPropertyChanged("SelectedConfiguracao"); + } + } + + public ConfiguracoesViewModel() + { + this._servico = new ConfuguracoesServico(); + base.EnableMenu = true; + } + + public async Task BuscarConfiguracoes() + { + List configuracaoSistemas = await this._servico.Buscar(); + List configuracaoSistemas1 = configuracaoSistemas; + Recursos.Configuracoes = ( + from x in configuracaoSistemas1 + orderby ValidationHelper.GetDescription(x.get_Configuracao()) + select x).ToList(); + this.ConfiguracoesAdicionadas = new ObservableCollection(configuracaoSistemas); + } + + public async Task Excluir(ConfiguracaoSistema configuracao) + { + if (await this._servico.Excluir(configuracao)) + { + await this.BuscarConfiguracoes(); + } + } + + private void PopularConfiguracoes(ObservableCollection configuracoes) + { + if (configuracoes == null) + { + return; + } + List configuracaos = new List(); + foreach (Configuracao configuracao in + from x in (Configuracao[])Enum.GetValues(typeof(Configuracao)) + orderby ValidationHelper.GetDescription(x) + select x) + { + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == configuracao)) + { + continue; + } + configuracaos.Add(configuracao); + } + this.Configuracoes = new ObservableCollection(configuracaos); + this.SelectedConfiguracao = this.Configuracoes.FirstOrDefault(); + } + + public async Task Salvar() + { + ConfuguracoesServico confuguracoesServico = this._servico; + ConfiguracaoSistema configuracaoSistema = new ConfiguracaoSistema(); + configuracaoSistema.set_Configuracao(this.SelectedConfiguracao); + if (await confuguracoesServico.Salvar(configuracaoSistema).get_Id() != 0) + { + await this.BuscarConfiguracoes(); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/DashboardViewModel.cs b/Codemerx/Gestor.Application/ViewModels/DashboardViewModel.cs new file mode 100644 index 0000000..8ef9d41 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/DashboardViewModel.cs @@ -0,0 +1,1111 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Relatorios.Dashboard; +using Gestor.Model.Domain.Relatorios.Renovacao; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels +{ + public class DashboardViewModel : BaseSegurosViewModel + { + private readonly TarefaServico _servico; + + private readonly ApoliceServico _apoliceServico; + + private readonly ClienteServico _clienteServico; + + private readonly SinistroServico _sinitrosServico; + + private readonly TarefaServico _tarefaServico; + + private bool _renovacoesEnabled; + + private bool _tarefasEnabled; + + private bool _aniversariantesEnabled; + + private bool _sinistrosEnabled; + + private bool _prospeccoesEnabled; + + private bool _notasEnabled; + + private bool _publica; + + private string _quantidadeRenovacoes = "0"; + + private string _quantidadeAniversariantes = "0"; + + private string _quantidadeProspeccao = "0"; + + private string _quantidadeSinisto = "0"; + + private string _quantidadeTarefas = "0"; + + private List _intervalo = new List() + { + "HOJE", + "PRÓXIMOS 3 DIAS", + "PRÓXIMOS 7 DIAS" + }; + + private string _intervaloSelecionado = "HOJE"; + + private bool _isProspectar; + + private ObservableCollection _notas; + + private ObservableCollection _telefones = new ObservableCollection(); + + private string _anotacoes = ""; + + private ObservableCollection _prospeccoes; + + private ObservableCollection _aniversariantes; + + private ObservableCollection _sinistros; + + private ObservableCollection _renovacaoFiltrado; + + private ObservableCollection _tarefas = new ObservableCollection(); + + private List _ramos; + + private Ramo _selectedRamo; + + private List _referencias = new List() + { + "VENCIMENTO DA ÚLTIMA PARCELA", + "VIGÊNCIA INICIAL", + "VIGÊNCIA FINAL" + }; + + private string _referencia = "VENCIMENTO DA ÚLTIMA PARCELA"; + + private int _selectedTile = 1; + + private string _labelProspeccao; + + private List _filtroCliente = new List() + { + "AMBOS", + "CNPJ", + "CPF" + }; + + private string _filtroClientes; + + private Gestor.Model.Domain.Relatorios.Filtros _filtroAniversariantes + { + get; + set; + } + + private Gestor.Model.Domain.Relatorios.Filtros _filtroProspectar + { + get; + set; + } + + private Gestor.Model.Domain.Relatorios.Filtros _filtroRenovacao + { + get; + set; + } + + private Gestor.Model.Domain.Relatorios.Filtros _filtroSinistros + { + get; + set; + } + + private Gestor.Model.Domain.Relatorios.Filtros _filtroTarefas + { + get; + set; + } + + public ObservableCollection Aniversariantes + { + get + { + return this._aniversariantes; + } + set + { + this._aniversariantes = value; + base.OnPropertyChanged("Aniversariantes"); + } + } + + public bool AniversariantesEnabled + { + get + { + return this._aniversariantesEnabled; + } + set + { + this._aniversariantesEnabled = value; + base.OnPropertyChanged("AniversariantesEnabled"); + } + } + + public new string Anotacoes + { + get + { + return this._anotacoes; + } + set + { + this._anotacoes = value; + base.OnPropertyChanged("Anotacoes"); + } + } + + public List FiltroCliente + { + get + { + return this._filtroCliente; + } + set + { + this._filtroCliente = value; + base.OnPropertyChanged("FiltroCliente"); + } + } + + public string FiltroClientes + { + get + { + return this._filtroClientes; + } + set + { + this._filtroClientes = value; + base.OnPropertyChanged("FiltroClientes"); + } + } + + public Gestor.Model.Domain.Relatorios.Filtros Filtros + { + get; + set; + } + + public List Intervalo + { + get + { + return this._intervalo; + } + set + { + this._intervalo = value; + base.OnPropertyChanged("Intervalo"); + } + } + + public string IntervaloSelecionado + { + get + { + return this._intervaloSelecionado; + } + set + { + this._intervaloSelecionado = value; + base.OnPropertyChanged("IntervaloSelecionado"); + } + } + + public bool IsProspectar + { + get + { + return this._isProspectar; + } + set + { + this._isProspectar = value; + base.OnPropertyChanged("IsProspectar"); + } + } + + public string LabelProspeccao + { + get + { + return this._labelProspeccao; + } + set + { + this._labelProspeccao = value; + base.OnPropertyChanged("LabelProspeccao"); + } + } + + public bool Load { get; set; } = true; + + public ObservableCollection Notas + { + get + { + return this._notas; + } + set + { + this._notas = value; + base.OnPropertyChanged("Notas"); + } + } + + public bool NotasEnabled + { + get + { + return this._notasEnabled; + } + set + { + this._notasEnabled = value; + base.OnPropertyChanged("NotasEnabled"); + } + } + + public List Permissoes + { + get; + set; + } + + public ObservableCollection Prospeccoes + { + get + { + return this._prospeccoes; + } + set + { + this._prospeccoes = value; + base.OnPropertyChanged("Prospeccoes"); + } + } + + public bool ProspeccoesEnabled + { + get + { + return this._prospeccoesEnabled; + } + set + { + this._prospeccoesEnabled = value; + base.OnPropertyChanged("ProspeccoesEnabled"); + } + } + + public bool Publica + { + get + { + return this._publica; + } + set + { + this._publica = value; + base.OnPropertyChanged("Publica"); + } + } + + public string QuantidadeAniversariantes + { + get + { + return this._quantidadeAniversariantes; + } + set + { + this._quantidadeAniversariantes = value; + base.OnPropertyChanged("QuantidadeAniversariantes"); + } + } + + public string QuantidadeProspeccao + { + get + { + return this._quantidadeProspeccao; + } + set + { + this._quantidadeProspeccao = value; + base.OnPropertyChanged("QuantidadeProspeccao"); + } + } + + public string QuantidadeRenovacoes + { + get + { + return this._quantidadeRenovacoes; + } + set + { + this._quantidadeRenovacoes = value; + base.OnPropertyChanged("QuantidadeRenovacoes"); + } + } + + public string QuantidadeSinistro + { + get + { + return this._quantidadeSinisto; + } + set + { + this._quantidadeSinisto = value; + base.OnPropertyChanged("QuantidadeSinistro"); + } + } + + public string QuantidadeTarefas + { + get + { + return this._quantidadeTarefas; + } + set + { + this._quantidadeTarefas = value; + base.OnPropertyChanged("QuantidadeTarefas"); + } + } + + public List Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public string Referencia + { + get + { + return this._referencia; + } + set + { + this._referencia = value; + base.OnPropertyChanged("Referencia"); + } + } + + public List Referencias + { + get + { + return this._referencias; + } + set + { + this._referencias = value; + base.OnPropertyChanged("Referencias"); + } + } + + public ObservableCollection RenovacaoFiltrado + { + get + { + return this._renovacaoFiltrado; + } + set + { + this._renovacaoFiltrado = value; + base.OnPropertyChanged("RenovacaoFiltrado"); + } + } + + public bool RenovacoesEnabled + { + get + { + return this._renovacoesEnabled; + } + set + { + this._renovacoesEnabled = value; + base.OnPropertyChanged("RenovacoesEnabled"); + } + } + + public List Restricoes + { + get; + set; + } + + public Ramo SelectedRamo + { + get + { + return this._selectedRamo; + } + set + { + this._selectedRamo = value; + base.OnPropertyChanged("SelectedRamo"); + } + } + + public int SelectedTile + { + get + { + return this._selectedTile; + } + set + { + this._selectedTile = value; + this.IsProspectar = (value == 4 ? true : value == 5); + } + } + + public ObservableCollection Sinistros + { + get + { + return this._sinistros; + } + set + { + this._sinistros = value; + base.OnPropertyChanged("Sinistros"); + } + } + + public bool SinistrosEnabled + { + get + { + return this._sinistrosEnabled; + } + set + { + this._sinistrosEnabled = value; + base.OnPropertyChanged("SinistrosEnabled"); + } + } + + public ObservableCollection Tarefas + { + get + { + return this._tarefas; + } + set + { + this._tarefas = value; + base.OnPropertyChanged("Tarefas"); + } + } + + public bool TarefasEnabled + { + get + { + return this._tarefasEnabled; + } + set + { + this._tarefasEnabled = value; + base.OnPropertyChanged("TarefasEnabled"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public DashboardViewModel() + { + this._servico = new TarefaServico(); + this._apoliceServico = new ApoliceServico(); + this._clienteServico = new ClienteServico(); + this._tarefaServico = new TarefaServico(); + this._sinitrosServico = new SinistroServico(); + } + + public async Task BuscarRestricoes() + { + this.Restricoes = await this.ServicoRestriUsuario.BuscarRestricoes(Recursos.Usuario.get_Id()); + this.Permissoes = new List(); + PermissaoUsuario permissaoUsuario = await this.ServicoPermissUsuario.VerificarPermissao(Recursos.Usuario, 38); + if (permissaoUsuario != null) + { + this.Permissoes.Add(permissaoUsuario); + } + } + + public async Task CarregarAniversariantes(bool force = false) + { + List clientesAtivosInativos; + this.AniversariantesEnabled = false; + if (force || !this.CompararFiltros(this._filtroAniversariantes)) + { + this._filtroAniversariantes = this.Filtros; + List vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + List nums = new List(); + vendedorUsuarios.ForEach((VendedorUsuario v) => nums.Add(v.get_Vendedor().get_Id())); + clientesAtivosInativos = (vendedorUsuarios.Count <= 0 ? await this._clienteServico.BuscarAniversariantes(this.Filtros) : await this._clienteServico.BuscarAniversariantesVinculo(this.Filtros, vendedorUsuarios)); + List clientesAtivosInativos1 = clientesAtivosInativos; + this.QuantidadeAniversariantes = clientesAtivosInativos1.Count.ToString(); + if (clientesAtivosInativos1.Count != 0) + { + this.Aniversariantes = new ObservableCollection(clientesAtivosInativos1); + this.AniversariantesEnabled = true; + } + else + { + this.Aniversariantes = null; + this.AniversariantesEnabled = true; + } + } + else + { + this.AniversariantesEnabled = true; + } + } + + public async Task CarregarFiltros() + { + long num; + List nums = new List(); + List vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + if (vendedorUsuarios.Count > 0) + { + vendedorUsuarios.ForEach((VendedorUsuario x) => nums.Add(x.get_Vendedor().get_Id())); + } + DateTime today = DateTime.Today; + DateTime dateTime = DateTime.Today; + string intervaloSelecionado = this.IntervaloSelecionado; + if (intervaloSelecionado == "PRÓXIMOS 3 DIAS") + { + dateTime = today.AddDays(3); + } + else if (intervaloSelecionado == "PRÓXIMOS 7 DIAS") + { + dateTime = today.AddDays(7); + } + DashboardViewModel dashboardViewModel = this; + Gestor.Model.Domain.Relatorios.Filtros filtro = new Gestor.Model.Domain.Relatorios.Filtros(); + filtro.set_Inicio(today); + filtro.set_Fim(dateTime); + filtro.set_Vendedores(nums); + num = (Recursos.Usuario.get_IdEmpresa() > (long)1 ? Recursos.Usuario.get_IdEmpresa() : (long)0); + filtro.set_IdEmpresa(num); + filtro.set_Status(new List() + { + (long)1, + (long)2 + }); + dashboardViewModel.Filtros = filtro; + } + + public async Task CarregarNotas() + { + this.NotasEnabled = false; + this.Notas = new ObservableCollection(await this._servico.BuscarNotas(Recursos.Usuario.get_Id())); + this.NotasEnabled = true; + } + + public async Task CarregarProspect(DateTime inicio, DateTime fim) + { + this.ProspeccoesEnabled = false; + Gestor.Model.Domain.Relatorios.Filtros filtro = new Gestor.Model.Domain.Relatorios.Filtros(); + filtro.set_Inicio(inicio); + filtro.set_Fim(fim); + filtro.set_Ramos(new List() + { + this.SelectedRamo.get_Id() + }); + filtro.set_Vendedores(this.Filtros.get_Vendedores()); + filtro.set_Referencia(this.Referencia); + filtro.set_FiltrarDocumento(this.FiltroClientes); + Gestor.Model.Domain.Relatorios.Filtros filtro1 = filtro; + this.LabelProspeccao = string.Concat("CLIENTES QUE NÃO POSSUEM SEGUROS DO RAMO ", this.SelectedRamo.get_Nome(), " "); + string referencia = this.Referencia; + if (referencia == "VIGÊNCIA INICIAL") + { + this.LabelProspeccao = string.Concat(this.LabelProspeccao, "E QUE ESTÃO COM UMA APÓLICE INICIANDO NO PERÍODO"); + } + else if (referencia == "VIGÊNCIA FINAL") + { + this.LabelProspeccao = string.Concat(this.LabelProspeccao, "E QUE ESTÃO COM UMA APÓLICE VENCENDO NO PERÍODO"); + } + else + { + this.LabelProspeccao = string.Concat(this.LabelProspeccao, "E QUE ESTÃO COM A ULTIMA PARCELA VENCENDO NO PERÍODO"); + } + if (this._filtroProspectar == null || !(this._filtroProspectar.get_Inicio() == filtro1.get_Inicio()) || !(this._filtroProspectar.get_Fim() == filtro1.get_Fim()) || this._filtroProspectar.get_Ramos() != filtro1.get_Ramos() || !(this._filtroProspectar.get_Referencia() == filtro1.get_Referencia())) + { + this._filtroProspectar = filtro1; + List prospectars = await this._clienteServico.BuscarProspect(filtro1); + this.QuantidadeProspeccao = prospectars.Count.ToString(); + if (prospectars.Count == 0) + { + this.LabelProspeccao = "NÃO HÁ CLIENTES PARA PROSPECTAR"; + } + this.Prospeccoes = new ObservableCollection(prospectars); + this.ProspeccoesEnabled = true; + } + else + { + this.ProspeccoesEnabled = true; + } + } + + public void CarregarRamos() + { + List nums = new List() + { + (long)1, + (long)2, + (long)6, + (long)7 + }; + this.Ramos = ( + from x in Recursos.Ramos + where nums.Contains(x.get_Id()) + select x).ToList(); + this.SelectedRamo = this.Ramos.Find((Ramo x) => x.get_Id() == (long)1); + } + + public async Task CarregarRenovacoes(bool force = false) + { + List list; + this.RenovacoesEnabled = false; + if (force || !this.CompararFiltros(this._filtroRenovacao)) + { + this._filtroRenovacao = this.Filtros; + List documentos = await this._apoliceServico.BuscarApolicesVigenciaFinal(this.Filtros, false); + IEnumerable tipo = + from x in documentos + where x.get_Tipo() != 3 + select x; + list = tipo.Select((Documento x) => { + object nome; + object obj; + string str; + object nome1; + object obj1; + string str1; + object nome2; + Renovacao renovacao = new Renovacao(); + Cliente cliente = x.get_Controle().get_Cliente(); + if (cliente != null) + { + nome = cliente.get_Nome(); + } + else + { + nome = null; + } + if (nome == null) + { + nome = ""; + } + renovacao.set_Cliente((string)nome); + renovacao.set_Apolice(x.get_Apolice() ?? ""); + renovacao.set_PremioLiquido(x.get_PremioLiquido()); + renovacao.set_PremioTotal(x.get_PremioTotal()); + Negocio? negocio = x.get_Negocio(); + renovacao.set_Negocio((string)((negocio.HasValue ? ValidationHelper.GetDescription(negocio.GetValueOrDefault()) : null) ?? "")); + renovacao.set_VigenciaFinal(x.get_Vigencia2()); + Produto produto = x.get_Controle().get_Produto(); + if (produto != null) + { + obj = produto.get_Nome(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = ""; + } + renovacao.set_Produto((string)obj); + renovacao.set_Ramo(x.get_Controle().get_Ramo().get_Nome() ?? ""); + renovacao.set_Seguradora((!string.IsNullOrWhiteSpace(x.get_Controle().get_Seguradora().get_NomeSocial()) ? x.get_Controle().get_Seguradora().get_NomeSocial() : x.get_Controle().get_Seguradora().get_Nome())); + renovacao.set_Status((x.get_Situacao() == 1 || x.get_Situacao() == 2 ? "NÃO TRABALHADO" : ValidationHelper.GetDescription(x.get_Situacao()) ?? "")); + Vendedor vendedorPrincipal = x.get_VendedorPrincipal(); + if (vendedorPrincipal != null) + { + str = vendedorPrincipal.get_Nome(); + } + else + { + str = null; + } + renovacao.set_Vendedor(str); + Estipulante estipulante1 = x.get_Estipulante1(); + if (estipulante1 != null) + { + nome1 = estipulante1.get_Nome(); + } + else + { + nome1 = null; + } + if (nome1 == null) + { + nome1 = ""; + } + renovacao.set_Estipulante((string)nome1); + renovacao.set_TodosVendedores((x.get_Vendedores() == null || x.get_Vendedores().Count == 0 ? "" : string.Join("; ", + from v in x.get_Vendedores() + select v.get_Nome()))); + renovacao.set_Tipo(x.get_Tipo()); + renovacao.set_Documento(x); + renovacao.set_Comissao(x.get_Comissao()); + renovacao.set_Item((x.get_ItensAtivo() != null ? (x.get_ItensAtivo().Count > 1 ? "APÓLICE COLETIVA" : (x.get_ItensAtivo().Count == 1 ? x.get_ItensAtivo().First().get_Descricao() : "")) : "")); + renovacao.set_TipoDocumento((x.get_Tipo() == 0 ? "APÓLICE" : (x.get_Tipo() == 1 ? "ENDOSSO" : ""))); + renovacao.set_Sinistro((x.get_Sinistro() ? "SIM" : "NÃO")); + renovacao.set_DataControle(x.get_DataControle()); + Status status = x.get_Status(); + if (status != null) + { + obj1 = status.get_Nome(); + } + else + { + obj1 = null; + } + if (obj1 == null) + { + obj1 = ""; + } + renovacao.set_StatusApolice((string)obj1); + renovacao.set_IdEmpresa(x.get_Controle().get_IdEmpresa()); + Empresa empresa = Recursos.Empresas.FirstOrDefault((Empresa e) => e.get_Id() == x.get_Controle().get_IdEmpresa()); + if (empresa != null) + { + str1 = empresa.get_Nome(); + } + else + { + str1 = null; + } + renovacao.set_Empresa(str1); + renovacao.set_QtdSinistro(x.get_ItensAtivo().Sum((Item s) => s.get_Sinistros().Count)); + Banco banco = x.get_Banco(); + if (banco != null) + { + nome2 = banco.get_Nome(); + } + else + { + nome2 = null; + } + if (nome2 == null) + { + nome2 = ""; + } + renovacao.set_Banco((string)nome2); + renovacao.set_Conta(x.get_Conta()); + renovacao.set_Agencia(x.get_Agencia()); + renovacao.set_Pasta(x.get_Pasta()); + renovacao.set_PastaCliente(x.get_Controle().get_Cliente().get_Pasta()); + renovacao.set_Calculos(x.get_Calculos()); + return renovacao; + }).ToList(); + List prospeccaos = await (new ProspeccaoServico()).BuscarProspeccoes(this.Filtros); + IEnumerable prospeccaos1 = + from x in prospeccaos + where x.get_Renovacao() + select x; + List renovacaos = prospeccaos1.Select((Prospeccao x) => { + string nome; + string str; + string nome1; + Renovacao renovacao = new Renovacao(); + renovacao.set_Cliente(x.get_Nome() ?? ""); + renovacao.set_Apolice("PROSPECÇÃO"); + renovacao.set_VigenciaFinal(x.get_VigenciaFinal()); + Renovacao renovacao1 = renovacao; + StatusProspeccao? status = x.get_Status(); + renovacao1.set_Status((string)((status.HasValue ? ValidationHelper.GetDescription(status.GetValueOrDefault()) : null) ?? "")); + Renovacao renovacao2 = renovacao; + Vendedor vendedor = x.get_Vendedor(); + if (vendedor != null) + { + nome = vendedor.get_Nome(); + } + else + { + nome = null; + } + renovacao2.set_Vendedor(nome); + Renovacao renovacao3 = renovacao; + Vendedor vendedor1 = x.get_Vendedor(); + if (vendedor1 != null) + { + str = vendedor1.get_Nome(); + } + else + { + str = null; + } + renovacao3.set_TodosVendedores(str); + renovacao.set_Telefone(string.Concat(new string[] { x.get_Prefixo1(), " ", x.get_Telefone1(), " | ", x.get_Prefixo2(), " ", x.get_Telefone2() })); + renovacao.set_Tipo(3); + renovacao.set_TipoDocumento("PROSPECÇÃO"); + renovacao.set_Item(x.get_Item()); + Renovacao renovacao4 = renovacao; + Produto produto = x.get_Produto(); + if (produto != null) + { + nome1 = produto.get_Nome(); + } + else + { + nome1 = null; + } + renovacao4.set_Produto(nome1); + renovacao.set_Prospeccao(x); + return renovacao; + }).ToList(); + list.AddRange(renovacaos); + this.QuantidadeRenovacoes = list.Count.ToString(); + if (list.Count != 0) + { + DashboardViewModel observableCollection = this; + List renovacaos1 = list; + observableCollection.RenovacaoFiltrado = new ObservableCollection(( + from x in renovacaos1 + orderby x.get_VigenciaFinal() + select x).ToList()); + this.RenovacoesEnabled = true; + } + else + { + this.RenovacaoFiltrado = null; + this.RenovacoesEnabled = true; + } + } + else + { + this.RenovacoesEnabled = true; + } + list = null; + } + + public async Task CarregarSinistros(bool force = false) + { + this.SinistrosEnabled = false; + if (force || !this.CompararFiltros(this._filtroSinistros)) + { + this._filtroSinistros = this.Filtros; + List sinistros = await this._sinitrosServico.BuscarSinistroPendente(this.Filtros); + this.QuantidadeSinistro = sinistros.Count.ToString(); + if (sinistros.Count != 0) + { + this.Sinistros = new ObservableCollection(sinistros); + this.SinistrosEnabled = true; + } + else + { + this.Sinistros = null; + this.SinistrosEnabled = true; + } + } + else + { + this.SinistrosEnabled = true; + } + } + + public async Task CarregarSinistros(DateTime inicio, DateTime fim) + { + this._filtroSinistros.set_Fim(fim); + this._filtroSinistros.set_Inicio(inicio); + List sinistros = await this._sinitrosServico.BuscarSinistroPendente(this._filtroSinistros); + this.QuantidadeSinistro = sinistros.Count.ToString(); + this.Sinistros = new ObservableCollection(sinistros); + } + + public async Task CarregarTarefas(bool force = false) + { + this.TarefasEnabled = false; + if (force || !this.CompararFiltros(this._filtroTarefas)) + { + this._filtroTarefas = this.Filtros; + List tarefas = await this._tarefaServico.BuscarTarefas(Recursos.Usuario.get_Id(), this._filtroTarefas.get_Inicio(), this._filtroTarefas.get_Fim(), new bool?(false)); + this.QuantidadeTarefas = tarefas.Count.ToString(); + if (tarefas.Count != 0) + { + DashboardViewModel observableCollection = this; + List tarefas1 = tarefas; + IEnumerable entidade = + from x in tarefas1 + where x.get_Entidade() != 1 + select x; + observableCollection.Tarefas = new ObservableCollection( + from x in entidade + orderby x.get_Agendamento() + select x); + this.TarefasEnabled = true; + } + else + { + this.Tarefas = null; + this.TarefasEnabled = true; + } + } + else + { + this.TarefasEnabled = true; + } + } + + private bool CompararFiltros(Gestor.Model.Domain.Relatorios.Filtros comparacao) + { + if (comparacao == null) + { + return false; + } + if (this.Filtros == null) + { + return false; + } + if (comparacao.get_Inicio() != this.Filtros.get_Inicio()) + { + return false; + } + if (comparacao.get_Fim() != this.Filtros.get_Fim()) + { + return false; + } + return true; + } + + public async Task ExcluirNota(Tarefa nota) + { + await this._servico.Excluir(nota.get_Id()); + } + + public async Task GerarCsv() + { + string str = string.Concat(Path.GetFileNameWithoutExtension(Path.GetTempFileName()), ".csv"); + List list = this.Prospeccoes.ToList(); + List strs = new List() + { + "Nome", + "Documento", + "Telefone" + }; + string str1 = await Funcoes.GerarCsv(list, strs); + File.WriteAllText(str, str1.ToString(), Encoding.UTF8); + Process.Start(str); + bool flag = true; + str = null; + return flag; + } + + public void LimparProspeccao() + { + } + + public async Task>> Salvar(Tarefa destino) + { + List> keyValuePairs; + Tarefa tarefa = destino; + List configuracoes = Recursos.Configuracoes; + tarefa.set_AgendamentoRetroativo(configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs1 = destino.Validate(); + if (keyValuePairs1.Count <= 0) + { + await this._servico.Salvar(destino); + if (this._servico.Sucesso) + { + if (this.Publica) + { + long id = destino.get_Usuario().get_Id(); + List usuarios = Recursos.Usuarios; + List tasks = new List(); + foreach (Usuario usuario in usuarios) + { + if (id == usuario.get_Id()) + { + continue; + } + Tarefa tarefa1 = (Tarefa)destino.Clone(); + tarefa1.set_Id((long)0); + tarefa1.set_Usuario(usuario); + tasks.Add(this._servico.Salvar(tarefa1)); + } + await Task.WhenAll(tasks); + } + await this.CarregarNotas(); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + public async Task SalvarNota(Tarefa nota) + { + return await this._servico.Salvar(nota); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/AdiantamentoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/AdiantamentoViewModel.cs new file mode 100644 index 0000000..72b47ae --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/AdiantamentoViewModel.cs @@ -0,0 +1,310 @@ +using Assinador.Infrastructure.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class AdiantamentoViewModel : BaseSegurosViewModel + { + private readonly AdiantamentoServico _servico; + + private readonly Vendedor _selectedVendedor; + + private bool _carregando; + + private ObservableCollection _adiantamento = new ObservableCollection(); + + private Gestor.Model.Domain.Seguros.Adiantamento _selectedAdiantamento = new Gestor.Model.Domain.Seguros.Adiantamento(); + + private bool _logEnabled; + + public Gestor.Model.Domain.Seguros.Adiantamento CancelAdiantamento; + + public ObservableCollection Adiantamento + { + get + { + return this._adiantamento; + } + set + { + this._adiantamento = value; + base.OnPropertyChanged("Adiantamento"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool LogEnabled + { + get + { + return this._logEnabled; + } + set + { + this._logEnabled = value; + base.OnPropertyChanged("LogEnabled"); + } + } + + public Gestor.Model.Domain.Seguros.Adiantamento SelectedAdiantamento + { + get + { + return this._selectedAdiantamento; + } + set + { + long? nullable; + this._selectedAdiantamento = value; + this.CancelAdiantamento = (value == null || value.get_Id() <= (long)0 ? this.CancelAdiantamento : value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedAdiantamento"); + } + } + + public AdiantamentoViewModel(Vendedor vendedor) + { + this._servico = new AdiantamentoServico(); + this.Seleciona(vendedor); + this._selectedVendedor = vendedor; + } + + public void CancelarAlteracao() + { + this.Carregando = true; + if (this.CancelAdiantamento != null && this.Adiantamento.Any((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == this.CancelAdiantamento.get_Id())) + { + DomainBase.Copy(this.Adiantamento.First((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == this.CancelAdiantamento.get_Id()), this.CancelAdiantamento); + this.SelectedAdiantamento = this.Adiantamento.First((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == this.CancelAdiantamento.get_Id()); + } + base.Alterar(false); + this.Carregando = false; + } + + public async Task CarregarAdiantamento(int index) + { + this.Carregando = true; + this.Adiantamento = new ObservableCollection(await this._servico.BuscarAdiantamentos(this._selectedVendedor.get_Id(), index != 0)); + if (this.Adiantamento == null || this.Adiantamento.Count <= 0) + { + this.LogEnabled = false; + } + else + { + this.SelectedAdiantamento = this.Adiantamento.First(); + this.LogEnabled = true; + } + this.Carregando = false; + } + + public async Task Excluir() + { + bool flag; + object obj; + object obj1; + Gestor.Model.Domain.Seguros.Adiantamento adiantamento; + Gestor.Model.Domain.Seguros.Adiantamento adiantamento1; + if (this.SelectedAdiantamento == null || this.SelectedAdiantamento.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + this.Carregando = true; + if (await this._servico.Delete(this.SelectedAdiantamento)) + { + AdiantamentoViewModel adiantamentoViewModel = this; + string str = string.Concat("EXCLUIU O ADIANTAMENTO DO VENDEDOR \"", this.SelectedAdiantamento.get_Vendedor().get_Nome(), "\""); + long id = this.SelectedAdiantamento.get_Id(); + TipoTela? nullable = new TipoTela?(36); + object[] valor = new object[] { this.SelectedAdiantamento.get_Id(), null, null, null, null }; + obj = (!this.SelectedAdiantamento.get_Data().HasValue ? "-" : string.Format("{0:d}", this.SelectedAdiantamento.get_Data())); + valor[1] = obj; + valor[2] = this.SelectedAdiantamento.get_Valor(); + valor[3] = Functions.GetDescription(this.SelectedAdiantamento.get_TipoPagamento()); + obj1 = (this.SelectedAdiantamento.get_Pago() ? "SIM" : "NÃO"); + valor[4] = obj1; + adiantamentoViewModel.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nDATA: {1}\nVALOR: {2:c}\nTIPO PAGAMENTO: {3}\nPAGO: {4}", valor)); + int num = this.Adiantamento.IndexOf(this.SelectedAdiantamento); + this.Adiantamento.Remove(this.SelectedAdiantamento); + this.Adiantamento.Remove(this.SelectedAdiantamento); + this.Adiantamento = new ObservableCollection(this.Adiantamento); + if (this.Adiantamento.Count <= 0) + { + this.SelectedAdiantamento = new Gestor.Model.Domain.Seguros.Adiantamento(); + base.Alterar(false); + base.EnableMenu = false; + this.LogEnabled = false; + } + else + { + AdiantamentoViewModel adiantamentoViewModel1 = this; + adiantamento1 = (num < this.Adiantamento.Count ? this.Adiantamento.ElementAt(num) : this.Adiantamento.Last()); + adiantamentoViewModel1.SelectedAdiantamento = adiantamento1; + this.LogEnabled = true; + } + if (this.Adiantamento.Count <= 0) + { + this.SelectedAdiantamento = new Gestor.Model.Domain.Seguros.Adiantamento(); + this.LogEnabled = false; + base.Alterar(false); + } + else + { + AdiantamentoViewModel adiantamentoViewModel2 = this; + adiantamento = (num < this.Adiantamento.Count ? this.Adiantamento.ElementAt(num) : this.Adiantamento.Last()); + adiantamentoViewModel2.SelecionaAdiantamento(adiantamento); + this.LogEnabled = true; + } + this.Carregando = false; + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public void Incluir() + { + this.SelectedAdiantamento = new Gestor.Model.Domain.Seguros.Adiantamento(); + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + object obj; + object obj1; + string str1; + if (!string.IsNullOrWhiteSpace(this.SelectedAdiantamento.get_Historico())) + { + this.SelectedAdiantamento.set_Vendedor(this._selectedVendedor); + str = (this.SelectedAdiantamento.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Gestor.Model.Domain.Seguros.Adiantamento adiantamento = await this._servico.Save(this.SelectedAdiantamento); + if (this._servico.Sucesso) + { + AdiantamentoViewModel adiantamentoViewModel = this; + string str2 = string.Concat(str1, " ADIANTAMENTO DO VENDEDOR \"", adiantamento.get_Vendedor().get_Nome(), "\""); + long id = adiantamento.get_Id(); + TipoTela? nullable = new TipoTela?(36); + object[] valor = new object[] { adiantamento.get_Id(), null, null, null, null }; + obj = (!adiantamento.get_Data().HasValue ? "-" : string.Format("{0:d}", adiantamento.get_Data())); + valor[1] = obj; + valor[2] = adiantamento.get_Valor(); + valor[3] = Functions.GetDescription(adiantamento.get_TipoPagamento()); + obj1 = (adiantamento.get_Pago() ? "SIM" : "NÃO"); + valor[4] = obj1; + adiantamentoViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nDATA: {1}\nVALOR: {2:c}\nTIPO PAGAMENTO: {3}\nPAGO: {4}", valor)); + if (!this.Adiantamento.Any((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == adiantamento.get_Id())) + { + this.Adiantamento.Add(adiantamento); + } + else + { + DomainBase.Copy(this.Adiantamento.First((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == adiantamento.get_Id()), adiantamento); + } + this.Adiantamento = new ObservableCollection(this.Adiantamento); + this.SelectedAdiantamento = this.Adiantamento.First((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Id() == adiantamento.get_Id()); + this.LogEnabled = true; + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = new List>() + { + new KeyValuePair("Historico|HISTÓRICO", "OBRIGATÓRIO") + }; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona(Vendedor vendedor) + { + base.Loading(true); + await base.PermissaoTela(15); + await this.SelecionaAdiantamento(vendedor); + base.Loading(false); + } + + public void SelecionaAdiantamento(Gestor.Model.Domain.Seguros.Adiantamento adiantamento) + { + this.SelectedAdiantamento = adiantamento; + } + + private async Task SelecionaAdiantamento(Vendedor vendedor) + { + this.Carregando = true; + List adiantamentos = await (new BaseServico()).BuscarAdiantamentoAsync(vendedor); + IOrderedEnumerable pago = + from x in adiantamentos + orderby x.get_Pago() + select x; + List list = pago.ThenBy((Gestor.Model.Domain.Seguros.Adiantamento x) => x.get_Valor()).ToList(); + this.Adiantamento = new ObservableCollection(list); + if (this.Adiantamento.Count <= 0) + { + this.SelectedAdiantamento = new Gestor.Model.Domain.Seguros.Adiantamento(); + this.LogEnabled = false; + base.Alterar(false); + base.VerificarEnables(new long?(this.SelectedAdiantamento.get_Id())); + base.EnableMenu = false; + } + else + { + this.SelecionaAdiantamento(this.Adiantamento.First()); + this.LogEnabled = true; + } + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/AgendaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/AgendaViewModel.cs new file mode 100644 index 0000000..4701416 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/AgendaViewModel.cs @@ -0,0 +1,427 @@ +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class AgendaViewModel : BaseSegurosViewModel + { + private readonly AgendaServico _servico; + + private Agenda _selectedAgenda; + + private ObservableCollection _telefones = new ObservableCollection(); + + private ObservableCollection _emails = new ObservableCollection(); + + private long _ultimoId; + + public Agenda CancelAgenda; + + private ObservableCollection _agendasFiltradas = new ObservableCollection(); + + private bool _carregando; + + public List Agendas + { + get; + set; + } + + public ObservableCollection AgendasFiltradas + { + get + { + return this._agendasFiltradas; + } + set + { + this._agendasFiltradas = value; + base.OnPropertyChanged("AgendasFiltradas"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Emails + { + get + { + return this._emails; + } + set + { + this._emails = value; + base.OnPropertyChanged("Emails"); + } + } + + public Agenda SelectedAgenda + { + get + { + return this._selectedAgenda; + } + set + { + long? nullable; + this._selectedAgenda = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedAgenda"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public AgendaViewModel() + { + this._servico = new AgendaServico(); + this.Seleciona(); + } + + public void CancelarAlteracao() + { + this.Carregando = true; + if (this.SelectedAgenda.get_Id() != 0) + { + DomainBase.Copy(this.Agendas.First((Agenda x) => x.get_Id() == this.CancelAgenda.get_Id()), this.CancelAgenda); + if (this.AgendasFiltradas.Count <= 0 || !this.AgendasFiltradas.Any((Agenda x) => x.get_Id() == this.CancelAgenda.get_Id())) + { + this.AgendasFiltradas.Add(this.CancelAgenda); + } + else + { + DomainBase.Copy(this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this.CancelAgenda.get_Id()), this.CancelAgenda); + } + this.AgendasFiltradas = new ObservableCollection(this.AgendasFiltradas); + this.SelectedAgenda = this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this.CancelAgenda.get_Id()); + } + else if (this.AgendasFiltradas.Count <= 0 || !this.AgendasFiltradas.Any((Agenda x) => x.get_Id() == this._ultimoId)) + { + if (this.Agendas.Count <= 0 || !this.Agendas.Any((Agenda x) => x.get_Id() == this._ultimoId)) + { + this.SelectedAgenda = new Agenda(); + ObservableCollection observableCollection = new ObservableCollection(); + AgendaTelefone agendaTelefone = new AgendaTelefone(); + agendaTelefone.set_Agenda(this.SelectedAgenda); + agendaTelefone.set_Tipo(new TipoTelefone?(1)); + observableCollection.Add(agendaTelefone); + this.Telefones = observableCollection; + ObservableCollection observableCollection1 = new ObservableCollection(); + AgendaEmail agendaEmail = new AgendaEmail(); + agendaEmail.set_Agenda(this.SelectedAgenda); + observableCollection1.Add(agendaEmail); + this.Emails = observableCollection1; + base.Alterar(false); + this.Carregando = false; + return; + } + this.AgendasFiltradas.Add(this.Agendas.First((Agenda x) => x.get_Id() == this._ultimoId)); + this.SelectedAgenda = this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this._ultimoId); + } + else + { + this.SelectedAgenda = this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this._ultimoId); + } + base.Alterar(false); + this.Carregando = false; + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedAgenda == null || this.SelectedAgenda.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + this.Carregando = true; + if (await this._servico.Delete(this.SelectedAgenda)) + { + int num = this.AgendasFiltradas.IndexOf(this.SelectedAgenda); + this.Agendas.Remove(this.SelectedAgenda); + this.AgendasFiltradas.Remove(this.SelectedAgenda); + this.AgendasFiltradas = new ObservableCollection(this.AgendasFiltradas); + if (this.AgendasFiltradas.Count <= 0) + { + this.SelectedAgenda = new Agenda(); + this.Telefones = new ObservableCollection(); + this.Emails = new ObservableCollection(); + base.Alterar(false); + } + else if (num >= this.AgendasFiltradas.Count) + { + await this.SelecionaAgenda(this.AgendasFiltradas.Last()); + } + else + { + await this.SelecionaAgenda(this.AgendasFiltradas.ElementAt(num)); + } + this.Carregando = false; + flag = true; + } + else + { + base.Alterar(false); + this.Carregando = false; + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public void ExcluirEmail(AgendaEmail email) + { + this.Emails.Remove(email); + } + + public void ExcluirTelefone(AgendaTelefone telefone) + { + this.Telefones.Remove(telefone); + } + + internal async Task> Filtrar(string value) + { + List agendas = await Task.Run>(() => this.FiltrarAgenda(value)); + return agendas; + } + + public List FiltrarAgenda(string filter) + { + this.AgendasFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Agendas) : new ObservableCollection( + from x in this.Agendas + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Nome() + select x)); + return this.AgendasFiltradas.ToList(); + } + + public void Incluir() + { + if (this.SelectedAgenda != null) + { + this._ultimoId = this.SelectedAgenda.get_Id(); + } + this.SelectedAgenda = new Agenda(); + ObservableCollection observableCollection = new ObservableCollection(); + AgendaTelefone agendaTelefone = new AgendaTelefone(); + agendaTelefone.set_Agenda(this.SelectedAgenda); + agendaTelefone.set_Tipo(new TipoTelefone?(1)); + observableCollection.Add(agendaTelefone); + this.Telefones = observableCollection; + ObservableCollection observableCollection1 = new ObservableCollection(); + AgendaEmail agendaEmail = new AgendaEmail(); + agendaEmail.set_Agenda(this.SelectedAgenda); + observableCollection1.Add(agendaEmail); + this.Emails = observableCollection1; + base.Alterar(true); + } + + public void IncluirEmail() + { + if (this.SelectedAgenda == null) + { + return; + } + if (this.Emails == null) + { + this.Emails = new ObservableCollection(); + } + AgendaEmail agendaEmail = new AgendaEmail(); + agendaEmail.set_Agenda(this.SelectedAgenda); + this.Emails.Add(agendaEmail); + base.OnPropertyChanged("IncluirEmail"); + } + + public void IncluirTelefone() + { + if (this.SelectedAgenda == null) + { + return; + } + if (this.Telefones == null) + { + this.Telefones = new ObservableCollection(); + } + AgendaTelefone agendaTelefone = new AgendaTelefone(); + agendaTelefone.set_Agenda(this.SelectedAgenda); + agendaTelefone.set_Tipo(new TipoTelefone?(1)); + this.Telefones.Add(agendaTelefone); + base.OnPropertyChanged("IncluirTelefone"); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + int num; + List> keyValuePairs1 = this.SelectedAgenda.Validate(); + ObservableCollection telefones = this.Telefones; + List list = ( + from x in telefones + where !string.IsNullOrEmpty(x.get_Numero()) + select x).ToList(); + ObservableCollection emails = this.Emails; + List agendaEmails = ( + from x in emails + where !string.IsNullOrEmpty(x.get_Email()) + select x).ToList(); + foreach (AgendaTelefone agendaTelefone in list) + { + keyValuePairs1.AddRange(agendaTelefone.Validate()); + } + foreach (AgendaEmail agendaEmail in agendaEmails) + { + keyValuePairs1.AddRange(agendaEmail.Validate()); + } + if (keyValuePairs1.Count <= 0) + { + this.SelectedAgenda.set_Telefones(new ObservableCollection(list)); + this.SelectedAgenda.set_Emails(new ObservableCollection(agendaEmails)); + if (this.SelectedAgenda.get_Id() != 0) + { + this.SelectedAgenda = await this._servico.Save(this.SelectedAgenda); + if (this._servico.Sucesso) + { + this.Telefones = new ObservableCollection(this.SelectedAgenda.get_Telefones()); + this.Emails = new ObservableCollection(this.SelectedAgenda.get_Emails()); + DomainBase.Copy(this.Agendas.First((Agenda x) => x.get_Id() == this.SelectedAgenda.get_Id()), this.SelectedAgenda); + if (this.AgendasFiltradas.Count <= 0 || !this.AgendasFiltradas.Any((Agenda x) => x.get_Id() == this.SelectedAgenda.get_Id())) + { + this.AgendasFiltradas.Add(this.SelectedAgenda); + } + else + { + DomainBase.Copy(this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this.SelectedAgenda.get_Id()), this.SelectedAgenda); + } + } + else + { + keyValuePairs = null; + return keyValuePairs; + } + } + else + { + this.SelectedAgenda = await this._servico.Save(this.SelectedAgenda); + if (this._servico.Sucesso) + { + this.Telefones = new ObservableCollection(this.SelectedAgenda.get_Telefones()); + this.Emails = new ObservableCollection(this.SelectedAgenda.get_Emails()); + this.Agendas.Add(this.SelectedAgenda); + ObservableCollection agendasFiltradas = this.AgendasFiltradas; + num = (this._ultimoId == 0 ? 0 : this.AgendasFiltradas.IndexOf(this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this._ultimoId))); + agendasFiltradas.Insert(num, this.SelectedAgenda); + } + else + { + keyValuePairs = null; + return keyValuePairs; + } + } + this.AgendasFiltradas = new ObservableCollection(this.AgendasFiltradas); + this.SelectedAgenda = this.AgendasFiltradas.First((Agenda x) => x.get_Id() == this.SelectedAgenda.get_Id()); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(34); + await this.SelecionaAgendas(); + base.Loading(false); + } + + public async Task SelecionaAgenda(Agenda agenda = null) + { + Agenda agenda1; + this.Carregando = true; + AgendaViewModel agendaViewModel = this; + agenda1 = (agenda == null ? this.AgendasFiltradas.FirstOrDefault() : this.AgendasFiltradas.FirstOrDefault((Agenda x) => x.get_Id() == agenda.get_Id())); + agendaViewModel.SelectedAgenda = agenda1; + if (this.SelectedAgenda == null) + { + this.Emails = null; + this.Telefones = null; + } + else + { + this.Emails = await this._servico.BuscarEmailsAsync(this.SelectedAgenda.get_Id()); + this.Telefones = await this._servico.BuscarTelefonesAsync(this.SelectedAgenda.get_Id()); + } + this.Carregando = false; + } + + private async Task SelecionaAgendas() + { + Agenda agenda; + this.Carregando = true; + List agendas = await (new BaseServico()).BuscarAgendasAsync(); + AgendaViewModel list = this; + List agendas1 = agendas; + list.Agendas = ( + from x in agendas1 + orderby x.get_Nome() + select x).ToList(); + this.AgendasFiltradas = new ObservableCollection(this.Agendas); + AgendaViewModel agendaViewModel = this; + agenda = (this.AgendasFiltradas.Count > 0 ? this.AgendasFiltradas.First() : new Agenda()); + agendaViewModel.SelectedAgenda = agenda; + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/AtendimentosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/AtendimentosViewModel.cs new file mode 100644 index 0000000..6adad6a --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/AtendimentosViewModel.cs @@ -0,0 +1,514 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Model.Ajuda; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.API; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer.Ajuda +{ + public class AtendimentosViewModel : BaseViewModel + { + private readonly AjudaServico _ajudaServico; + + private List _status; + + private string _webbody; + + private Visibility _envioEmailVisibility = Visibility.Collapsed; + + private Visibility _atendimentoVisibility; + + private ObservableCollection _atendimentos; + + private Atendimento _selectedAtendimento; + + private string _nome; + + private string _ddd; + + private string _telefone; + + private string _email; + + private string _assunto; + + private string _idacesso; + + private string _corpo; + + private string _senhaacesso; + + private ObservableCollection _arquivosAnexados = new ObservableCollection(); + + private Gestor.Model.Domain.Common.ArquivoDigital _selectedAnexado = new Gestor.Model.Domain.Common.ArquivoDigital(); + + private string _head; + + public ObservableCollection ArquivosAnexados + { + get + { + return this._arquivosAnexados; + } + set + { + this._arquivosAnexados = value; + base.OnPropertyChanged("ArquivosAnexados"); + } + } + + public string Assunto + { + get + { + return this._assunto; + } + set + { + this._assunto = value; + base.OnPropertyChanged("Assunto"); + } + } + + public ObservableCollection Atendimentos + { + get + { + return this._atendimentos; + } + set + { + this._atendimentos = value; + base.OnPropertyChanged("Atendimentos"); + } + } + + public Visibility AtendimentoVisibility + { + get + { + return this._atendimentoVisibility; + } + set + { + this._atendimentoVisibility = value; + base.OnPropertyChanged("AtendimentoVisibility"); + } + } + + public string Corpo + { + get + { + return this._corpo; + } + set + { + this._corpo = value; + base.OnPropertyChanged("Corpo"); + } + } + + public string Ddd + { + get + { + return this._ddd; + } + set + { + this._ddd = value; + base.OnPropertyChanged("Ddd"); + } + } + + public string Email + { + get + { + return this._email; + } + set + { + this._email = value; + base.OnPropertyChanged("Email"); + } + } + + public Visibility EnvioEmailVisibility + { + get + { + return this._envioEmailVisibility; + } + set + { + this._envioEmailVisibility = value; + base.OnPropertyChanged("EnvioEmailVisibility"); + } + } + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public Gestor.Model.API.HorarioAtendimento HorarioAtendimento + { + get; + set; + } + + public string IdAcesso + { + get + { + return this._idacesso; + } + set + { + this._idacesso = value; + base.OnPropertyChanged("IdAcesso"); + } + } + + public string Nome + { + get + { + return this._nome; + } + set + { + this._nome = value; + base.OnPropertyChanged("Nome"); + } + } + + public Gestor.Model.Domain.Common.ArquivoDigital SelectedAnexado + { + get + { + return this._selectedAnexado; + } + set + { + this._selectedAnexado = value; + base.OnPropertyChanged("SelectedAnexado"); + } + } + + public Atendimento SelectedAtendimento + { + get + { + return this._selectedAtendimento; + } + set + { + this._selectedAtendimento = value; + this.WorkOnSelectedAtendimento(value); + base.OnPropertyChanged("SelectedAtendimento"); + } + } + + public string SenhaAcesso + { + get + { + return this._senhaacesso; + } + set + { + this._senhaacesso = value; + base.OnPropertyChanged("SenhaAcesso"); + } + } + + public List Status + { + get + { + return this._status; + } + set + { + this._status = value; + base.OnPropertyChanged("Status"); + } + } + + public string Telefone + { + get + { + return this._telefone; + } + set + { + this._telefone = value; + base.OnPropertyChanged("Telefone"); + } + } + + public string WebBody + { + get + { + string str = this._webbody; + if (str == null) + { + return null; + } + return str.ToUpper().Trim(); + } + set + { + this._webbody = value; + base.OnPropertyChanged("WebBody"); + } + } + + public AtendimentosViewModel() + { + base.EnableButtons = true; + this._ajudaServico = new AjudaServico(); + this.LoadCombo(); + this.InitialLoad(); + } + + public async void Anexar() + { + List arquivoDigitals = await base.AddAttachments(new List(), new List()); + if (arquivoDigitals != null) + { + arquivoDigitals.AddRange(this.ArquivosAnexados); + this.ArquivosAnexados = new ObservableCollection(arquivoDigitals); + } + } + + public void Delete(Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + if (this.SelectedAnexado == null) + { + return; + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = this.ArquivosAnexados.First((Gestor.Model.Domain.Common.ArquivoDigital x) => x.get_Descricao() == arquivo.get_Descricao()); + this.ArquivosAnexados.Remove(arquivoDigital); + this.ArquivosAnexados = new ObservableCollection(this.ArquivosAnexados); + } + + public async Task>> Enviar() + { + List> keyValuePairs; + object obj; + try + { + List> keyValuePairs1 = this.Validate(); + if (keyValuePairs1.Count <= 0) + { + CustomerData customerDatum = new CustomerData(); + customerDatum.set_Corretora(Recursos.Empresa.get_Nome()); + customerDatum.set_Name(this.Nome); + customerDatum.set_AreaCode(this.Ddd); + customerDatum.set_Number(this.Telefone); + customerDatum.set_Email(this.Email); + CustomerData customerDatum1 = customerDatum; + object[] corpo = new object[] { this.Corpo, this.IdAcesso, this.SenhaAcesso, ApplicationHelper.Versao, Recursos.Usuario.get_Id(), Recursos.Usuario.get_Login(), JsonConvert.SerializeObject(customerDatum1) }; + string str = string.Format("{0}

ID Acesso: {1}
Senha Acesso: {2}

VERSÃO DO SISTEMA: {3}
USUÁRIO SISTEMA:{4} {5}

{6}

", corpo); + CustomerAttendance customerAttendance = new CustomerAttendance(); + customerAttendance.set_CustomerData(customerDatum1); + customerAttendance.set_Subject(this.Assunto); + customerAttendance.set_Body(str); + ObservableCollection arquivosAnexados = this.ArquivosAnexados; + customerAttendance.set_Attachments(arquivosAnexados.Select((Gestor.Model.Domain.Common.ArquivoDigital x) => { + Attachment attachment = new Attachment(); + attachment.set_Description(x.get_Descricao()); + attachment.set_Extension(x.get_Extensao()); + attachment.set_File(x.get_Arquivo()); + return attachment; + }).ToList()); + this.LimparComponentes(); + this.SelecionaAtendimento(); + if (await Connection.Post("Attendance/Send", customerAttendance) == null) + { + obj = null; + } + else + { + obj = new List>(); + ((List>)obj).Add(new KeyValuePair("fail", "")); + } + keyValuePairs = (List>)obj; + } + else + { + keyValuePairs = keyValuePairs1; + } + } + catch (Exception exception) + { + keyValuePairs = new List>() + { + new KeyValuePair("fail", "") + }; + } + return keyValuePairs; + } + + private async void HabilitarAtendimento(Gestor.Model.API.HorarioAtendimento horario) + { + bool id; + string str; + if (horario == null || horario.get_Autorizado()) + { + AtendimentosViewModel atendimentosViewModel = this; + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + atendimentosViewModel.EnableButtons = id; + } + else + { + base.EnableButtons = false; + if (horario.get_InicioDia().HasValue) + { + string[] strArrays = new string[] { " de ", horario.get_InicioDia().DiaDaSemana(), " à ", horario.get_FimDia().DiaDaSemana(), ", das ", horario.get_InicioHora(), "hs às ", horario.get_FimHora(), "hs" }; + str = string.Concat(strArrays); + } + else + { + string[] inicioHora = new string[] { " das ", horario.get_InicioHora(), "hs às ", horario.get_FimHora(), "hs" }; + str = string.Concat(inicioHora); + } + string str1 = str; + string[] newLine = new string[] { "Prezado Cliente,", Environment.NewLine, Environment.NewLine, "Informamos Nosso horário de atendimento e recepção dos mesmos é ", str1, ".", Environment.NewLine, "Infelizmente não realizamos agendamento de data/hora de atendimento, por gentileza realize a solicitação dentro do horário comercial que retornaremos a você." }; + await base.ShowMessage(string.Concat(newLine), "OK", "", false); + } + } + + private async void InitialLoad() + { + base.IsEnabled = false; + this.HorarioAtendimento = await Connection.Get("Attendance", true, false); + this.HabilitarAtendimento(this.HorarioAtendimento); + base.IsEnabled = true; + } + + public void LimparComponentes() + { + this.Nome = Recursos.Usuario.get_Nome(); + this.Ddd = Recursos.Usuario.get_Prefixo(); + this.Telefone = Recursos.Usuario.get_Telefone(); + this.Email = Recursos.Usuario.get_Email(); + this.Assunto = null; + this.IdAcesso = null; + this.SenhaAcesso = null; + this.Corpo = string.Empty; + this.ArquivosAnexados = new ObservableCollection(); + } + + private void LoadCombo() + { + this.Status = new List() + { + "PENDENTES", + "FINALIZADOS" + }; + } + + public void SelecionaAtendimento() + { + if (this.Atendimentos != null && this.Atendimentos.Count > 0) + { + this.SelectedAtendimento = this.Atendimentos[0]; + } + this.AtendimentoVisibility = Visibility.Visible; + this.EnvioEmailVisibility = Visibility.Collapsed; + } + + public List> Validate() + { + List> keyValuePairs = ValidationHelper.AddValue(); + if (string.IsNullOrWhiteSpace(this.Nome)) + { + ValidationHelper.AddValue(keyValuePairs, "Nome", Messages.get_Obrigatorio(), true); + } + if (string.IsNullOrWhiteSpace(this.Ddd)) + { + ValidationHelper.AddValue(keyValuePairs, "Ddd", Messages.get_Obrigatorio(), true); + } + else if (!ValidationHelper.ValidacaoPrefixo(this.Ddd)) + { + ValidationHelper.AddValue(keyValuePairs, "Ddd", Messages.get_Invalido(), true); + } + if (string.IsNullOrWhiteSpace(this.Telefone)) + { + ValidationHelper.AddValue(keyValuePairs, "Telefone", Messages.get_Obrigatorio(), true); + } + else if (!ValidationHelper.ValidacaoTelefone(this.Telefone)) + { + ValidationHelper.AddValue(keyValuePairs, "Telefone", Messages.get_Invalido(), true); + } + if (string.IsNullOrWhiteSpace(this.Email)) + { + ValidationHelper.AddValue(keyValuePairs, "Email", Messages.get_Obrigatorio(), true); + } + else if (!ValidationHelper.ValidacaoEmail(this.Email)) + { + ValidationHelper.AddValue(keyValuePairs, "Email", Messages.get_Invalido(), true); + } + if (string.IsNullOrWhiteSpace(this.Corpo)) + { + ValidationHelper.AddValue(keyValuePairs, "Corpo", Messages.get_Obrigatorio(), true); + } + if (string.IsNullOrWhiteSpace(this.Assunto)) + { + ValidationHelper.AddValue(keyValuePairs, "Assunto", Messages.get_Obrigatorio(), true); + } + return keyValuePairs; + } + + private async void WorkOnSelectedAtendimento(Atendimento value) + { + if (value != null) + { + this.WebBody = await this._ajudaServico.BuscarCorpoAtendimentos(value.IdAtendimento); + } + } + + public async void WorkOnSelectedStatus(string value) + { + this.Atendimentos = await this._ajudaServico.BuscarAtendimentos(value); + this.SelecionaAtendimento(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/BoletosNotasViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/BoletosNotasViewModel.cs new file mode 100644 index 0000000..6f2e250 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/BoletosNotasViewModel.cs @@ -0,0 +1,122 @@ +using Gestor.Application.Model.Ajuda; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.ViewModels.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer.Ajuda +{ + public class BoletosNotasViewModel : BaseViewModel + { + private readonly AjudaServico _ajudaServico; + + private bool _carregando; + + private List _boletos; + + private string _boletoDisponivel; + + private List _status; + + public string BoletoDisponivel + { + get + { + return this._boletoDisponivel; + } + set + { + this._boletoDisponivel = value; + base.OnPropertyChanged("BoletoDisponivel"); + } + } + + public List Boletos + { + get + { + return this._boletos; + } + set + { + this._boletos = value; + base.OnPropertyChanged("Boletos"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public List Status + { + get + { + return this._status; + } + set + { + this._status = value; + base.OnPropertyChanged("Status"); + } + } + + public BoletosNotasViewModel() + { + this._ajudaServico = new AjudaServico(); + this.LoadCombos(); + this.BoletoDisponivel = "Disponível para impressão a partir de\n10 (dez) dias antes do vencimento"; + } + + private void LoadCombos() + { + this.Status = new List() + { + "PENDENTES", + "BAIXADOS" + }; + } + + public async void WorkOnSelectedStatus(string value) + { + List list; + this.Carregando = true; + this.Boletos = new List(); + List boletos = await this._ajudaServico.BuscarBoletosNotas(value); + BoletosNotasViewModel boletosNotasViewModel = this; + if (value == "BAIXADOS") + { + List boletos1 = boletos; + IEnumerable hasValue = + from x in boletos1 + where x.Pagamento.HasValue + select x; + list = ( + from x in hasValue + orderby x.Pagamento descending + select x).ToList(); + } + else + { + list = boletos; + } + boletosNotasViewModel.Boletos = list; + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/ContratosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/ContratosViewModel.cs new file mode 100644 index 0000000..fe46bb4 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/ContratosViewModel.cs @@ -0,0 +1,112 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Model.Ajuda; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.License; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer.Ajuda +{ + public class ContratosViewModel : BaseViewModel + { + private readonly AjudaServico _ajudaServico; + + private bool _carregando; + + private List _contratos; + + private Licenca _selectedContrato; + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public List Contratos + { + get + { + return this._contratos; + } + set + { + this._contratos = value; + base.OnPropertyChanged("Contratos"); + } + } + + public Licenca SelectedContrato + { + get + { + return this._selectedContrato; + } + set + { + this._selectedContrato = value; + this.WorkOnSelectedContrato(value); + base.OnPropertyChanged("SelectedContrato"); + } + } + + public ContratosViewModel() + { + this._ajudaServico = new AjudaServico(); + this.Contratos = LicenseHelper.Produtos; + } + + internal async void WorkOnSelectedContrato(Licenca value) + { + Contrato contrato = await this._ajudaServico.BuscarContrato(value.get_Produto()); + if (!string.IsNullOrEmpty(contrato.HtmlContrato) || contrato.IdModulo != (long)7) + { + if (string.IsNullOrEmpty(contrato.HtmlContrato) && contrato.IdModulo != (long)7) + { + contrato = await this._ajudaServico.BuscarContrato(1); + } + string empty = string.Empty; + LicenseHelper.Produtos.ForEach((Licenca x) => empty = string.Concat(empty, (string.IsNullOrEmpty(empty) ? ValidationHelper.GetDescription(x.get_Produto()) : string.Concat("/ ", ValidationHelper.GetDescription(x.get_Produto()))))); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<NOME>]", Recursos.Empresa.get_Nome()); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<ENDERECO>]", Recursos.Empresa.get_Endereco()); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<CIDADE>]", Recursos.Empresa.get_Cidade()); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<CNPJ>]", Recursos.Empresa.get_Documento()); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<NS>]", Recursos.Empresa.get_Serial()); + string htmlContrato = contrato.HtmlContrato; + DateTime date = Funcoes.GetNetworkTime().Date; + contrato.HtmlContrato = htmlContrato.Replace("[<DATA>]", date.ToString("dd/MM/yyyy")); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<VALOR>]", "Conforme Mensalidade"); + contrato.HtmlContrato = contrato.HtmlContrato.Replace("[<OUTROS>]", empty.Replace("*", "")); + string tempPath = Path.GetTempPath(); + string str = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(ValidationHelper.GetDescription(value.get_Produto()), ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str, true, Encoding.UTF8); + streamWriter.Write(contrato.HtmlContrato); + streamWriter.Close(); + Process.Start(str); + } + else + { + Process.Start(string.Format("https://aggilizador.com.br/Contrato.aspx?id={0}", ApplicationHelper.IdFornecedor)); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/InstalacaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/InstalacaoViewModel.cs new file mode 100644 index 0000000..8ee9f0b --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/Ajuda/InstalacaoViewModel.cs @@ -0,0 +1,281 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Model.Ajuda; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows.Controls; + +namespace Gestor.Application.ViewModels.Drawer.Ajuda +{ + public class InstalacaoViewModel : BaseViewModel + { + private readonly AjudaServico _ajudaServico; + + private bool _enableExclusao; + + private bool _mostrarAggilizador; + + private string _infoGestor; + + private string _infoAggilizador; + + private bool _carregando; + + private List _agger; + + private ObservableCollection _aggerFiltrado; + + private List _aggilizador; + + public List Agger + { + get + { + return this._agger; + } + set + { + this._agger = value; + base.OnPropertyChanged("Agger"); + } + } + + public ObservableCollection AggerFiltrado + { + get + { + return this._aggerFiltrado; + } + set + { + this._aggerFiltrado = value; + base.OnPropertyChanged("AggerFiltrado"); + } + } + + public List Aggilizador + { + get + { + return this._aggilizador; + } + set + { + this._aggilizador = value; + base.OnPropertyChanged("Aggilizador"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool EnableExclusao + { + get + { + return this._enableExclusao; + } + set + { + this._enableExclusao = value; + base.OnPropertyChanged("EnableExclusao"); + } + } + + public string InfoAggilizador + { + get + { + return this._infoAggilizador; + } + set + { + this._infoAggilizador = value; + base.OnPropertyChanged("InfoAggilizador"); + } + } + + public string InfoGestor + { + get + { + return this._infoGestor; + } + set + { + this._infoGestor = value; + base.OnPropertyChanged("InfoGestor"); + } + } + + public AutoCompleteFilterPredicate InstalacaoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_370 = InstalacaoViewModel.u003cu003ec.u003cu003e9__37_0; + if (u003cu003e9_370 == null) + { + u003cu003e9_370 = new AutoCompleteFilterPredicate(InstalacaoViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Gestor.Application.Model.Ajuda.Instalacao)obj).Maquina.ToUpper().Contains(searchText.ToUpper()) || ((Gestor.Application.Model.Ajuda.Instalacao)obj).Usuario.ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Gestor.Application.Model.Ajuda.Instalacao)obj).DataIntalacao.ToString().Contains(searchText.ToUpper()); + }); + InstalacaoViewModel.u003cu003ec.u003cu003e9__37_0 = u003cu003e9_370; + } + return u003cu003e9_370; + } + } + + public bool MostrarAggilizador + { + get + { + return this._mostrarAggilizador; + } + set + { + this._mostrarAggilizador = value; + base.OnPropertyChanged("MostrarAggilizador"); + } + } + + public InstalacaoViewModel() + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + this._enableExclusao = id; + base(); + bool id; + this._ajudaServico = new AjudaServico(); + this.LoadInstalacoes(); + } + + public async void Excluir(long id) + { + if (await this._ajudaServico.ExcluirInstalacao(id)) + { + this.LoadInstalacoes(); + } + } + + internal async Task> Filtrar(string value) + { + List instalacaos = await Task.Run>(() => this.FiltrarInstalacao(value)); + return instalacaos; + } + + public List FiltrarInstalacao(string filter) + { + this.AggerFiltrado = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Agger) : new ObservableCollection(this.Agger.Where((Gestor.Application.Model.Ajuda.Instalacao x) => { + if (ValidationHelper.RemoveDiacritics(x.Maquina.Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) || ValidationHelper.RemoveDiacritics(x.Usuario.Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter))) + { + return true; + } + return x.DataIntalacao.ToString().Contains(ValidationHelper.RemoveDiacritics(filter)); + }))); + return this.AggerFiltrado.ToList(); + } + + private async void LoadInstalacoes() + { + int? nullable; + List instalacaos; + int? nullable1; + int? nullable2; + string str; + this.Carregando = true; + ObservableCollection observableCollection = await this._ajudaServico.BuscarLicencas(); + InstalacaoViewModel list = this; + ObservableCollection observableCollection1 = observableCollection; + list.Agger = ( + from x in observableCollection1 + where !string.IsNullOrEmpty(x.IdGerenciador) + select x).ToList(); + this.AggerFiltrado = new ObservableCollection(this.Agger); + InstalacaoViewModel instalacaoViewModel = this; + List produtos = LicenseHelper.Produtos; + if (produtos.Any((Licenca x) => x.get_Produto() == 81)) + { + instalacaos = new List(); + } + else + { + ObservableCollection observableCollection2 = observableCollection; + instalacaos = ( + from x in observableCollection2 + where !string.IsNullOrEmpty(x.IdAggilizador) + select x).ToList(); + } + instalacaoViewModel.Aggilizador = instalacaos; + InstalacaoViewModel instalacaoViewModel1 = this; + object count = this.Agger.Count; + List licencas = LicenseHelper.Produtos; + Licenca licenca = licencas.FirstOrDefault((Licenca x) => x.get_Produto() == 1); + if (licenca != null) + { + nullable1 = new int?(licenca.get_Quantidade()); + } + else + { + nullable = null; + nullable1 = nullable; + } + instalacaoViewModel1.InfoGestor = string.Format("{0} LICENÇAS INSTALADAS DE {1} LICENÇAS CONTRATADAS.", count, nullable1); + InstalacaoViewModel instalacaoViewModel2 = this; + if (this.Aggilizador.Count > 0) + { + object obj = this.Aggilizador.Count; + List produtos1 = LicenseHelper.Produtos; + Licenca licenca1 = produtos1.FirstOrDefault((Licenca x) => x.get_Produto() == 81); + if (licenca1 != null) + { + nullable2 = new int?(licenca1.get_Quantidade()); + } + else + { + nullable = null; + nullable2 = nullable; + } + str = string.Format("{0} LICENÇAS INSTALADAS DE {1} LICENÇAS CONTRATADAS.", obj, nullable2); + } + else + { + str = ""; + } + instalacaoViewModel2.InfoAggilizador = str; + this.MostrarAggilizador = this.Aggilizador.Count > 0; + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ArquivoDigitalViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ArquivoDigitalViewModel.cs new file mode 100644 index 0000000..6963a1e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ArquivoDigitalViewModel.cs @@ -0,0 +1,1414 @@ +using Assinador.Model.Domain; +using Assinador.Model.Generic; +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Ferramentas; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.License; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ArquivoDigitalViewModel : BaseSegurosViewModel + { + private readonly ClienteServico _servico; + + private Visibility _assinarVisibility = Visibility.Collapsed; + + private Visibility _visibilityWhatsApp = Visibility.Collapsed; + + private bool _carregando; + + private bool _activated = true; + + private bool _adDocumento; + + private Visibility _adDocumentoVisibility; + + private bool _isVisibleSalvar; + + private Visibility _enviarSelecionadosVisibility; + + private Cliente _selectedCliente = new Cliente(); + + private ObservableCollection _telefones = new ObservableCollection(); + + private ObservableCollection _arquivos = new ObservableCollection(); + + private ObservableCollection _arquivosTela = new ObservableCollection(); + + private IndiceArquivoDigital _selectedArquivo = new IndiceArquivoDigital(); + + private ObservableCollection _arquivosAnexados = new ObservableCollection(); + + private Gestor.Model.Domain.Common.ArquivoDigital _selectedAnexado = new Gestor.Model.Domain.Common.ArquivoDigital(); + + private string _titulo = ""; + + private ObservableCollection _emails = new ObservableCollection(); + + private string _assunto; + + private string _corpo; + + private string _nome; + + private string _documento; + + private string _email; + + private string _licencas; + + private string _assinadorKey; + + public bool Activated + { + get + { + return this._activated; + } + set + { + this._activated = value; + base.OnPropertyChanged("Activated"); + } + } + + public bool AdDocumento + { + get + { + return this._adDocumento; + } + set + { + this._adDocumento = value; + this.CarregarArquivos(); + base.OnPropertyChanged("AdDocumento"); + } + } + + public Visibility AdDocumentoVisibility + { + get + { + return this._adDocumentoVisibility; + } + set + { + this._adDocumentoVisibility = value; + base.OnPropertyChanged("AdDocumentoVisibility"); + } + } + + public ObservableCollection Arquivos + { + get + { + return this._arquivos; + } + set + { + this._arquivos = value; + this.ArquivosTela = value; + base.OnPropertyChanged("Arquivos"); + } + } + + public ObservableCollection ArquivosAnexados + { + get + { + return this._arquivosAnexados; + } + set + { + this._arquivosAnexados = value; + this.IsVisibleSalvar = (value == null ? false : value.Count > 0); + base.OnPropertyChanged("ArquivosAnexados"); + } + } + + public ObservableCollection ArquivosTela + { + get + { + return this._arquivosTela; + } + set + { + this._arquivosTela = value; + base.OnPropertyChanged("ArquivosTela"); + } + } + + public Visibility AssinarVisibility + { + get + { + return this._assinarVisibility; + } + set + { + this._assinarVisibility = value; + base.OnPropertyChanged("AssinarVisibility"); + } + } + + public string Assunto + { + get + { + return this._assunto; + } + set + { + this._assunto = value; + base.OnPropertyChanged("Assunto"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public string Corpo + { + get + { + return this._corpo; + } + set + { + this._corpo = value; + base.OnPropertyChanged("Corpo"); + } + } + + public string Documento + { + get + { + return this._documento; + } + set + { + this._documento = value; + base.OnPropertyChanged("Documento"); + } + } + + public string Email + { + get + { + return this._email; + } + set + { + string str; + if (value != null) + { + str = value.Trim(); + } + else + { + str = null; + } + this._email = str; + base.OnPropertyChanged("Email"); + } + } + + public ObservableCollection Emails + { + get + { + return this._emails; + } + set + { + this._emails = value; + base.OnPropertyChanged("Emails"); + } + } + + public Visibility EnviarSelecionadosVisibility + { + get + { + return this._enviarSelecionadosVisibility; + } + set + { + this._enviarSelecionadosVisibility = (!base.Restricao(20) ? value : Visibility.Collapsed); + base.OnPropertyChanged("EnviarSelecionadosVisibility"); + } + } + + private FiltroArquivoDigital Filtro + { + get; + } + + public bool IsVisibleSalvar + { + get + { + return this._isVisibleSalvar; + } + set + { + this._isVisibleSalvar = value; + base.OnPropertyChanged("IsVisibleSalvar"); + } + } + + public string Licencas + { + get + { + return this._licencas; + } + set + { + this._licencas = value; + base.OnPropertyChanged("Licencas"); + } + } + + public string Nome + { + get + { + return this._nome; + } + set + { + this._nome = value; + base.OnPropertyChanged("Nome"); + } + } + + public Gestor.Model.Domain.Common.ArquivoDigital SelectedAnexado + { + get + { + return this._selectedAnexado; + } + set + { + this._selectedAnexado = value; + base.OnPropertyChanged("SelectedAnexado"); + } + } + + public IndiceArquivoDigital SelectedArquivo + { + get + { + return this._selectedArquivo; + } + set + { + this._selectedArquivo = value; + base.OnPropertyChanged("SelectedArquivo"); + } + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public string Titulo + { + get + { + return this._titulo; + } + set + { + this._titulo = value; + base.OnPropertyChanged("Titulo"); + } + } + + public Visibility VisibilityWhatsApp + { + get + { + return this._visibilityWhatsApp; + } + set + { + this._visibilityWhatsApp = value; + base.OnPropertyChanged("VisibilityWhatsApp"); + } + } + + public ArquivoDigitalViewModel(FiltroArquivoDigital filtro) + { + this.Filtro = filtro; + this._servico = new ClienteServico(); + this.CarregarArquivos(); + this.VisibilityWhatsApp = (filtro.get_Tipo() == 2 || filtro.get_Tipo() == 3 || filtro.get_Tipo() == 4 || filtro.get_Tipo() == 5 ? Visibility.Visible : Visibility.Collapsed); + this.AdDocumentoVisibility = ((filtro.get_Tipo() == 4 || filtro.get_Tipo() == 3 || filtro.get_Tipo() == 5) && (new PermissaoArquivoDigitalServico()).BuscarPermissao(Recursos.Usuario, 2).get_Consultar() ? Visibility.Visible : Visibility.Collapsed); + base.EnableMenu = true; + switch (filtro.get_Tipo()) + { + case 0: + case 6: + case 7: + case 8: + case 9: + case 10: + case 12: + case 13: + case 14: + case 15: + case 17: + { + this.EnviarSelecionadosVisibility = Visibility.Collapsed; + return; + } + default: + { + this.EnviarSelecionadosVisibility = Visibility.Visible; + return; + } + } + } + + public async void Anexar() + { + ObservableCollection arquivos = this.Arquivos; + List list = arquivos.Select((IndiceArquivoDigital x) => { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = new Gestor.Model.Domain.Common.ArquivoDigital(); + arquivoDigital.set_Descricao(x.get_Descricao()); + arquivoDigital.set_Extensao(x.get_Extensao()); + return arquivoDigital; + }).ToList(); + List arquivoDigitals = await base.AddAttachments(this.ArquivosAnexados.ToList(), list); + if (arquivoDigitals != null) + { + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 47)) + { + arquivoDigitals = await base.ShowDialogAnexar(arquivoDigitals, false); + if (arquivoDigitals == null) + { + return; + } + } + arquivoDigitals.AddRange(this.ArquivosAnexados); + this.ArquivosAnexados = new ObservableCollection(arquivoDigitals); + } + } + + public async Task Assinar(IndiceArquivoDigital indice, bool lote = false) + { + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador; + object obj; + int num = 0; + try + { + AssinaturaServico assinaturaServico = new AssinaturaServico(); + Gestor.Application.Servicos.ArquivoDigitalServico arquivoDigitalServico = new Gestor.Application.Servicos.ArquivoDigitalServico(); + if (await assinaturaServico.VerificarAssinado(indice.get_Id())) + { + if (!lote) + { + await base.ShowMessage("ARQUIVO JÁ ASSINADO", "OK", "", false); + } + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + else if (await assinaturaServico.VerificarEnviado(indice.get_Id())) + { + arquivoParaAssinaturaAssinador = await assinaturaServico.Reenviar(indice.get_Id()); + return arquivoParaAssinaturaAssinador; + } + else if (this.Nome == null || string.IsNullOrWhiteSpace(this.Nome)) + { + if (!lote) + { + await base.ShowMessage("É NECESSÁRIO QUE O ASSINANTE POSSUA UM NOME VÁLIDO", "OK", "", false); + } + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + else if (this.Documento == null || !Gestor.Common.Validation.ValidationHelper.ValidateDocument(this.Documento)) + { + if (!lote) + { + await base.ShowMessage("É NECESSÁRIO QUE O ASSINANTE POSSUA UM DOCUMENTO VÁLIDO", "OK", "", false); + } + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + else if (this.Documento.Length > 14) + { + if (!lote) + { + await base.ShowMessage("O DOCUMENTO DO ASSINANTE DEVE SER CPF E NÃO CNPJ", "OK", "", false); + } + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + else if (this.Email == null || !Gestor.Model.Helper.ValidationHelper.ValidacaoEmail(this.Email)) + { + if (!lote) + { + await base.ShowMessage("É NECESSÁRIO QUE O ASSINANTE POSSUA UM E-MAIL VÁLIDO", "OK", "", false); + } + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + else + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = await arquivoDigitalServico.BuscarPorId(indice.get_IdArquivoDigital(), indice.get_Bd()); + long id = (long)0; + Gestor.Model.Domain.Seguros.Documento documento = new Gestor.Model.Domain.Seguros.Documento(); + switch (this.Filtro.get_Tipo()) + { + case 2: + { + id = ((Gestor.Model.Domain.Seguros.Documento)this.Filtro.get_Parente()).get_Id(); + break; + } + case 3: + { + id = ((Parcela)this.Filtro.get_Parente()).get_Documento().get_Id(); + break; + } + case 4: + { + id = ((Item)this.Filtro.get_Parente()).get_Documento().get_Id(); + break; + } + case 5: + { + id = ((Sinistro)this.Filtro.get_Parente()).get_ControleSinistro().get_Item().get_Documento().get_Id(); + break; + } + default: + { + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + } + AssinaturaServico assinaturaServico1 = assinaturaServico; + ApoliceAssinador apoliceAssinador = new ApoliceAssinador(); + apoliceAssinador.set_ArquivoId(indice.get_Id()); + apoliceAssinador.set_ClienteId(this.SelectedCliente.get_Id()); + apoliceAssinador.set_Cliente(this.Nome); + apoliceAssinador.set_Email(this.Email); + apoliceAssinador.set_Documento(this.Documento); + apoliceAssinador.set_Id(id); + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador1 = await assinaturaServico1.Assinar(arquivoDigital, apoliceAssinador); + arquivoParaAssinaturaAssinador = await assinaturaServico.Save(arquivoParaAssinaturaAssinador1); + return arquivoParaAssinaturaAssinador; + } + } + catch (Exception exception) + { + obj = exception; + num = 1; + } + if (num != 1) + { + throw null; + } + Exception exception1 = (Exception)obj; + string[] newLine = new string[] { "ERRO AO ENVIAR PARA ASSINATURA", Environment.NewLine, exception1.Message, Environment.NewLine, "POR FAVOR CONTATE A AGGER ATRAVÉS DO PAINEL DE ATENDIMENTOS" }; + await base.ShowMessage(string.Concat(newLine), "OK", "", false); + arquivoParaAssinaturaAssinador = null; + return arquivoParaAssinaturaAssinador; + } + + private void AtualizaEmpresa() + { + Recursos.Empresa = (new BaseServico()).BuscarEmpresa(Recursos.Usuario.get_IdEmpresa()); + } + + public void Baixar(IndiceArquivoDigital arquivo, bool abrir = false) + { + if (arquivo == null || arquivo.get_IdArquivoDigital() == 0) + { + return; + } + base.Download(arquivo, abrir); + } + + public async Task BaixarTodos() + { + bool flag; + if (this.Arquivos == null || this.Arquivos.Count == 0) + { + flag = false; + } + else + { + flag = await base.DownloadAll(this.Arquivos.ToList(), this.Filtro.get_Id()); + } + return flag; + } + + public async Task CarregaArquivos() + { + TipoArquivoDigital tipo; + bool id; + string email; + object emailResponsavel; + object nomeResponsavel; + object documentoResponsavel; + string str; + string str1; + Cliente cliente; + FiltroArquivoDigital filtro = this.Filtro; + if (filtro != null) + { + id = filtro.get_Id() == (long)0; + } + else + { + id = false; + } + if (!id) + { + this.Carregando = true; + base.IsVisible = Visibility.Collapsed; + this.AssinarVisibility = Visibility.Collapsed; + if (this.Filtro != null) + { + List indiceArquivoDigitals = await this.ArquivoDigitalServico.BuscarPorTipo(this.Filtro.get_Tipo(), this.Filtro.get_Id()); + if (this.AdDocumento) + { + List indiceArquivoDigitals1 = indiceArquivoDigitals; + List indiceArquivoDigitals2 = await this.ArquivoDigitalServico.BuscarPorTipo(2, this.Filtro.get_IdApolice()); + indiceArquivoDigitals1.AddRange(indiceArquivoDigitals2); + indiceArquivoDigitals1 = null; + } + ArquivoDigitalViewModel observableCollection = this; + List indiceArquivoDigitals3 = indiceArquivoDigitals; + observableCollection.Arquivos = new ObservableCollection( + from x in indiceArquivoDigitals3 + orderby x.get_Descricao() + select x); + tipo = this.Filtro.get_Tipo(); + switch (tipo) + { + case 2: + { + this.AssinarVisibility = Visibility.Visible; + Gestor.Model.Domain.Seguros.Documento parente = (Gestor.Model.Domain.Seguros.Documento)this.Filtro.get_Parente(); + this.SelectedCliente = parente.get_Controle().get_Cliente(); + ArquivoDigitalViewModel arquivoDigitalViewModel = this; + str = (parente.get_Apolice() != string.Empty ? string.Concat("ARQUIVO DIGITAL DA APÓLICE \"", parente.get_Apolice(), "\"") : string.Concat("ARQUIVO DIGITAL DA PROPOSTA \"", parente.get_Proposta(), "\"")); + arquivoDigitalViewModel.Titulo = str; + break; + } + case 3: + { + this.AssinarVisibility = Visibility.Visible; + Parcela parcela = (Parcela)this.Filtro.get_Parente(); + this.SelectedCliente = parcela.get_Documento().get_Controle().get_Cliente(); + ArquivoDigitalViewModel arquivoDigitalViewModel1 = this; + str1 = (parcela.get_Documento().get_Apolice() != string.Empty ? string.Format("ARQUIVO DIGITAL DA PARCELA \"{0}\" DA APÓLICE \"{1}\"", parcela.get_NumeroParcela(), parcela.get_Documento().get_Apolice()) : string.Format("ARQUIVO DIGITAL DA PARCELA \"{0}\" DA PROPOSTA \"{1}\"", parcela.get_NumeroParcela(), parcela.get_Documento().get_Proposta())); + arquivoDigitalViewModel1.Titulo = str1; + DetalheExtrato detalheExtrato = await (new ServicoExtrato()).FindByParcelaId(parcela.get_Id()); + if (detalheExtrato == null) + { + break; + } + indiceArquivoDigitals = await this.ArquivoDigitalServico.BuscarPorTipo(7, detalheExtrato.get_Extrato().get_Id()); + List indiceArquivoDigitals4 = indiceArquivoDigitals; + indiceArquivoDigitals4.ForEach((IndiceArquivoDigital x) => x.set_NaoExcluir(true)); + ObservableCollection arquivos = this.Arquivos; + List indiceArquivoDigitals5 = indiceArquivoDigitals; + ExtensionMethods.AddRange(arquivos, new ObservableCollection( + from x in indiceArquivoDigitals5 + orderby x.get_Descricao() + select x)); + break; + } + case 4: + { + this.AssinarVisibility = Visibility.Visible; + Item item = (Item)this.Filtro.get_Parente(); + this.SelectedCliente = item.get_Documento().get_Controle().get_Cliente(); + this.Titulo = string.Concat("ARQUIVO DIGITAL DO ITEM \"", item.get_Descricao(), "\""); + break; + } + case 5: + { + this.AssinarVisibility = Visibility.Visible; + Sinistro sinistro = (Sinistro)this.Filtro.get_Parente(); + this.SelectedCliente = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente(); + string[] numero = new string[] { "ARQUIVO DIGITAL DO SINITRO \"", sinistro.get_Numero(), "\" DO ITEM \"", sinistro.get_ControleSinistro().get_Item().get_Descricao(), "\"" }; + this.Titulo = string.Concat(numero); + break; + } + case 6: + { + Vendedor vendedor = (Vendedor)this.Filtro.get_Parente(); + Cliente cliente1 = new Cliente(); + cliente1.set_Id(vendedor.get_Id()); + cliente1.set_Nome(vendedor.get_Nome()); + this.SelectedCliente = cliente1; + this.Titulo = string.Format("ARQUIVO DIGITAL DO VENDEDOR {0} {1}", vendedor.get_Nome(), vendedor.get_Id()); + break; + } + case 7: + { + Extrato extrato = (Extrato)this.Filtro.get_Parente(); + Cliente cliente2 = new Cliente(); + cliente2.set_Nome(string.Concat("EXTRATO ", extrato.get_Numero())); + this.SelectedCliente = cliente2; + this.Titulo = string.Format("ARQUIVO DIGITAL DO EXTRATO {0} ID:{1}", extrato.get_Numero(), extrato.get_Id()); + break; + } + case 8: + { + Seguradora seguradora = (Seguradora)this.Filtro.get_Parente(); + Cliente cliente3 = new Cliente(); + cliente3.set_Id(seguradora.get_Id()); + cliente3.set_Nome(seguradora.get_Nome()); + this.SelectedCliente = cliente3; + this.Titulo = string.Format("ARQUIVO DIGITAL DA SEGURADORA {0} {1}", seguradora.get_Nome(), seguradora.get_Id()); + break; + } + case 9: + { + Lancamento lancamento = (Lancamento)this.Filtro.get_Parente(); + if (!lancamento.get_Historico().Equals("TRANSFERÊNCIA ENTRE CONTAS")) + { + Cliente cliente4 = new Cliente(); + cliente4.set_Id(lancamento.get_Controle().get_Fornecedor().get_Id()); + cliente4.set_Nome(lancamento.get_Controle().get_Fornecedor().get_Nome()); + this.SelectedCliente = cliente4; + this.Titulo = string.Format("ARQUIVO DIGITAL DO LANCAMENTO {0}, PLANO {1}, CENTRO {2}", lancamento.get_Id(), lancamento.get_Controle().get_Plano().get_Nome(), lancamento.get_Controle().get_Centro().get_Descricao()); + break; + } + else + { + await base.ShowMessage("NÃO É POSSIVEL INCLUIR ARQUIVOS EM TRANSFERÊNCIA ENTRE CONTAS", "OK", "", false); + base.CloseDrawer(); + return; + } + } + case 10: + { + Fornecedor fornecedor = (Fornecedor)this.Filtro.get_Parente(); + Cliente cliente5 = new Cliente(); + cliente5.set_Id(fornecedor.get_Id()); + cliente5.set_Nome(fornecedor.get_Nome()); + this.SelectedCliente = cliente5; + this.Titulo = string.Format("ARQUIVO DIGITAL DO FORNECEDOR {0} {1}", fornecedor.get_Nome(), fornecedor.get_Id()); + break; + } + case 11: + { + Prospeccao prospeccao = (Prospeccao)this.Filtro.get_Parente(); + Cliente cliente6 = new Cliente(); + cliente6.set_Id(prospeccao.get_Id()); + cliente6.set_Nome(prospeccao.get_Nome()); + this.SelectedCliente = cliente6; + this.Titulo = string.Format("ARQUIVO DIGITAL DA PROSPECÇÃO {0} {1} {2}", prospeccao.get_Nome(), prospeccao.get_Id(), prospeccao.get_Item()); + break; + } + case 12: + { + Usuario usuario = (Usuario)this.Filtro.get_Parente(); + Cliente cliente7 = new Cliente(); + cliente7.set_Id(usuario.get_Id()); + cliente7.set_Nome(usuario.get_Nome()); + this.SelectedCliente = cliente7; + this.Titulo = string.Format("ARQUIVO DIGITAL DO USUÁRIO {0} {1}", usuario.get_Nome(), usuario.get_Id()); + break; + } + case 13: + { + Empresa empresa = (Empresa)this.Filtro.get_Parente(); + Cliente cliente8 = new Cliente(); + cliente8.set_Id(empresa.get_Id()); + cliente8.set_Nome(empresa.get_Nome()); + this.SelectedCliente = cliente8; + this.Titulo = string.Format("ARQUIVO DIGITAL DA EMPRESA {0} {1}", empresa.get_Nome(), empresa.get_Id()); + break; + } + case 14: + { + Socio socio = (Socio)this.Filtro.get_Parente(); + Cliente cliente9 = new Cliente(); + cliente9.set_Id(socio.get_Id()); + cliente9.set_Nome(socio.get_Nome()); + this.SelectedCliente = cliente9; + this.Titulo = string.Format("ARQUIVO DIGITAL DO SÓCIO {0} {1}", socio.get_Nome(), socio.get_Id()); + break; + } + case 15: + { + Tarefa tarefa = (Tarefa)this.Filtro.get_Parente(); + Cliente cliente10 = new Cliente(); + cliente10.set_Id(tarefa.get_Id()); + cliente10.set_Nome(string.Concat("TAREFA - ", tarefa.get_Titulo())); + this.SelectedCliente = cliente10; + this.Titulo = string.Format("ANEXO DA TAREFA {0} {1}", tarefa.get_Titulo(), tarefa.get_Id()); + break; + } + case 16: + { + NotaFiscal notaFiscal = (NotaFiscal)this.Filtro.get_Parente(); + Cliente cliente11 = new Cliente(); + cliente11.set_Id(notaFiscal.get_Id()); + cliente11.set_Nome(string.Format("NOTA FISCAL - {0} {1:d}", notaFiscal.get_Seguradora().get_NomeSocial(), notaFiscal.get_Data())); + this.SelectedCliente = cliente11; + this.Titulo = string.Format("ANEXO DA NOTA FISCAL {0} {1:d}", notaFiscal.get_Seguradora().get_NomeSocial(), notaFiscal.get_Data()); + break; + } + case 17: + { + Estipulante estipulante = (Estipulante)this.Filtro.get_Parente(); + Cliente cliente12 = new Cliente(); + cliente12.set_Id(estipulante.get_Id()); + cliente12.set_Nome(string.Concat("ESTIPULANTE - ", estipulante.get_Nome())); + this.SelectedCliente = cliente12; + this.Titulo = string.Concat("ANEXO DO ESTIPULANTE ", estipulante.get_Nome()); + break; + } + default: + { + this.SelectedCliente = (Cliente)this.Filtro.get_Parente(); + this.Titulo = string.Concat("ARQUIVO DIGITAL DO CLIENTE \"", this.SelectedCliente.get_Nome(), "\""); + break; + } + } + indiceArquivoDigitals = null; + } + if (this.Filtro != null) + { + tipo = this.Filtro.get_Tipo(); + switch (tipo) + { + case 1: + case 2: + case 3: + case 4: + case 5: + { + cliente = await this._servico.BuscarClienteAsync(this.SelectedCliente.get_Id()); + this.Telefones = await this._servico.BuscarTelefonesAsync(this.SelectedCliente.get_Id()); + ObservableCollection observableCollection1 = await (new ClienteServico()).BuscarEmailsAsync(this.SelectedCliente.get_Id()); + if (this.SelectedCliente.get_Documento() == null || Gestor.Common.Validation.ValidationHelper.OnlyNumber(this.SelectedCliente.get_Documento()).Length <= 11) + { + ArquivoDigitalViewModel arquivoDigitalViewModel2 = this; + ClienteEmail clienteEmail = observableCollection1.FirstOrDefault(); + if (clienteEmail != null) + { + email = clienteEmail.get_Email(); + } + else + { + email = null; + } + arquivoDigitalViewModel2.Email = email; + this.Nome = this.SelectedCliente.get_Nome(); + this.Documento = this.SelectedCliente.get_Documento(); + goto case 8; + } + else + { + ArquivoDigitalViewModel arquivoDigitalViewModel3 = this; + Cliente cliente13 = cliente; + if (cliente13 != null) + { + ResponsavelAssinatura responsavelAssinatura = cliente13.get_ResponsavelAssinatura(); + if (responsavelAssinatura != null) + { + emailResponsavel = responsavelAssinatura.get_EmailResponsavel(); + } + else + { + emailResponsavel = null; + } + } + else + { + emailResponsavel = null; + } + if (emailResponsavel == null) + { + ClienteEmail clienteEmail1 = observableCollection1.FirstOrDefault(); + if (clienteEmail1 != null) + { + emailResponsavel = clienteEmail1.get_Email(); + } + else + { + emailResponsavel = null; + } + } + arquivoDigitalViewModel3.Email = (string)emailResponsavel; + ArquivoDigitalViewModel arquivoDigitalViewModel4 = this; + Cliente cliente14 = cliente; + if (cliente14 != null) + { + ResponsavelAssinatura responsavelAssinatura1 = cliente14.get_ResponsavelAssinatura(); + if (responsavelAssinatura1 != null) + { + nomeResponsavel = responsavelAssinatura1.get_NomeResponsavel(); + } + else + { + nomeResponsavel = null; + } + } + else + { + nomeResponsavel = null; + } + if (nomeResponsavel == null) + { + nomeResponsavel = this.SelectedCliente.get_Nome(); + } + arquivoDigitalViewModel4.Nome = (string)nomeResponsavel; + ArquivoDigitalViewModel arquivoDigitalViewModel5 = this; + Cliente cliente15 = cliente; + if (cliente15 != null) + { + ResponsavelAssinatura responsavelAssinatura2 = cliente15.get_ResponsavelAssinatura(); + if (responsavelAssinatura2 != null) + { + documentoResponsavel = responsavelAssinatura2.get_DocumentoResponsavel(); + } + else + { + documentoResponsavel = null; + } + } + else + { + documentoResponsavel = null; + } + if (documentoResponsavel == null) + { + documentoResponsavel = this.SelectedCliente.get_Documento(); + } + arquivoDigitalViewModel5.Documento = (string)documentoResponsavel; + goto case 8; + } + } + case 6: + case 7: + case 8: + { + cliente = null; + break; + } + case 9: + { + Lancamento parente1 = (Lancamento)this.Filtro.get_Parente(); + ObservableCollection observableCollection2 = new ObservableCollection(); + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Prefixo(parente1.get_Controle().get_Fornecedor().get_Prefixo1()); + clienteTelefone.set_Numero(parente1.get_Controle().get_Fornecedor().get_Telefone1()); + observableCollection2.Add(clienteTelefone); + ClienteTelefone clienteTelefone1 = new ClienteTelefone(); + clienteTelefone1.set_Prefixo(parente1.get_Controle().get_Fornecedor().get_Prefixo2()); + clienteTelefone1.set_Numero(parente1.get_Controle().get_Fornecedor().get_Telefone2()); + observableCollection2.Add(clienteTelefone1); + this.Telefones = observableCollection2; + goto case 8; + } + case 10: + { + Fornecedor fornecedor1 = (Fornecedor)this.Filtro.get_Parente(); + ObservableCollection observableCollection3 = new ObservableCollection(); + ClienteTelefone clienteTelefone2 = new ClienteTelefone(); + clienteTelefone2.set_Prefixo(fornecedor1.get_Prefixo1()); + clienteTelefone2.set_Numero(fornecedor1.get_Telefone1()); + observableCollection3.Add(clienteTelefone2); + ClienteTelefone clienteTelefone3 = new ClienteTelefone(); + clienteTelefone3.set_Prefixo(fornecedor1.get_Prefixo2()); + clienteTelefone3.set_Numero(fornecedor1.get_Telefone2()); + observableCollection3.Add(clienteTelefone3); + this.Telefones = observableCollection3; + goto case 8; + } + default: + { + if (tipo == 17) + { + Estipulante estipulante1 = (Estipulante)this.Filtro.get_Parente(); + ObservableCollection observableCollection4 = new ObservableCollection(); + ClienteTelefone clienteTelefone4 = new ClienteTelefone(); + clienteTelefone4.set_Prefixo(estipulante1.get_PrimeiroPrefixo()); + clienteTelefone4.set_Numero(estipulante1.get_PrimeiroTelefone()); + observableCollection4.Add(clienteTelefone4); + ClienteTelefone clienteTelefone5 = new ClienteTelefone(); + clienteTelefone5.set_Prefixo(estipulante1.get_SegundoPrefixo()); + clienteTelefone5.set_Numero(estipulante1.get_SegundoTelefone()); + observableCollection4.Add(clienteTelefone5); + this.Telefones = observableCollection4; + goto case 8; + } + else + { + goto case 8; + } + } + } + } + base.IsVisible = Visibility.Visible; + this.Carregando = false; + } + } + + public async void CarregarArquivos() + { + await base.PermissaoTela(6); + await base.PermissaoArquivoDigital(this.Filtro.get_Tipo()); + await this.CarregaArquivos(); + string str = "PRODUTO NÃO CONTRATADO"; + List produtos = LicenseHelper.Produtos; + if (produtos.Any((Licenca x) => x.get_Produto() == 86)) + { + this._assinadorKey = await AssinadorHelper.Key(); + int num = await AssinadorHelper.Licencas(this._assinadorKey); + str = string.Format("{0} LICENÇAS DISPONÍVEIS", num); + } + this.Licencas = str; + base.VerificarEnables(new long?((long)0)); + } + + public string CarregarMensagem() + { + Gestor.Model.Domain.Seguros.Documento parente; + Item item; + string str; + string str1; + this.AtualizaEmpresa(); + if (Recursos.Empresa.get_TipoTelefone1() == 11) + { + str1 = "0300"; + } + else + { + str1 = (Recursos.Empresa.get_TipoTelefone1() == 10 ? "0800" : ""); + } + string str2 = str1; + str2 = string.Concat(new string[] { str2, " ", Recursos.Empresa.get_PrimeiroPrefixo(), " ", Recursos.Empresa.get_PrimeiroTelefone() }); + TipoArquivoDigital tipo = this.Filtro.get_Tipo(); + switch (tipo) + { + case 1: + { + return string.Concat(new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), ", segue o(s) link(s) para download referente ao(s) seu(s) arquivo(s). ", Environment.NewLine, Environment.NewLine, "[*LINK*]", Environment.NewLine, Environment.NewLine, "<|LINKASSINATURA|>", Environment.NewLine, Environment.NewLine, "Para mais informações entre contato conosco pelo ", str2, ".", Environment.NewLine, "Atenciosamente ", Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()), "." }); + } + case 2: + { + parente = (Gestor.Model.Domain.Seguros.Documento)this.Filtro.get_Parente(); + str = (string.IsNullOrWhiteSpace(parente.get_Apolice()) ? string.Concat("Proposta Número ", parente.get_Proposta()) : string.Concat("Apólice Número ", parente.get_Apolice())); + string[] strArrays = new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), " segue o(s) link(s) para download do(s) arquivo(s) referente ao seu seguro. ", Environment.NewLine, null }; + strArrays[4] = string.Format("{0}, {1}, {2} de Vigências entre {3:d} e {4:d}. {5}{6}[*LINK*]{7}{8}<|LINKASSINATURA|>Para mais informações entre contato conosco pelo {9}.{10}Atenciosamente {11}.", new object[] { Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Seguradora().get_Nome()), Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Ramo().get_Nome()), str, parente.get_Vigencia1(), parente.get_Vigencia2(), Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, str2, Environment.NewLine, Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()) }); + return string.Concat(strArrays); + } + case 3: + { + Parcela parcela = (Parcela)this.Filtro.get_Parente(); + parente = parcela.get_Documento(); + str = (string.IsNullOrWhiteSpace(parente.get_Apolice()) ? string.Concat("Proposta Número ", parente.get_Proposta()) : string.Concat("Apólice Número ", parente.get_Apolice())); + string[] strArrays1 = new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), " segue o(s) link(s) para download do(s) arquivo(s) referente a sua parcela. ", Environment.NewLine, null, null }; + strArrays1[4] = string.Format("Parcela {0} de {1}, valor {2:C2} de vencimento {3:d}. {4}", new object[] { parcela.get_NumeroParcela(), parente.get_NumeroParcelas(), parcela.get_Valor(), parcela.get_Vencimento(), Environment.NewLine }); + strArrays1[5] = string.Format("{0}, {1}, {2} de Vigências entre {3:d} e {4:d}. {5}{6}[*LINK*]{7}{8}<|LINKASSINATURA|>Para mais informações entre contato conosco pelo {9}.{10}Atenciosamente {11}.", new object[] { Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Seguradora().get_Nome()), Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Ramo().get_Nome()), str, parente.get_Vigencia1(), parente.get_Vigencia2(), Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, str2, Environment.NewLine, Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()) }); + return string.Concat(strArrays1); + } + case 4: + { + item = (Item)this.Filtro.get_Parente(); + parente = item.get_Documento(); + str = (string.IsNullOrWhiteSpace(parente.get_Apolice()) ? string.Concat("Proposta Número ", parente.get_Proposta()) : string.Concat("Apólice Número ", parente.get_Apolice())); + string[] strArrays2 = new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), " segue o(s) link(s) para download do(s) arquivo(s) referente ao seu seguro. ", Environment.NewLine, "Item ", item.get_Descricao(), ". ", Environment.NewLine, null }; + strArrays2[8] = string.Format("{0}, {1}, {2} de Vigências entre {3:d} e {4:d}. {5}{6}[*LINK*]{7}{8}<|LINKASSINATURA|>Para mais informações entre contato conosco pelo {9}.{10}Atenciosamente {11}.", new object[] { Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Seguradora().get_Nome()), Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Ramo().get_Nome()), str, parente.get_Vigencia1(), parente.get_Vigencia2(), Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, str2, Environment.NewLine, Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()) }); + return string.Concat(strArrays2); + } + case 5: + { + Sinistro sinistro = (Sinistro)this.Filtro.get_Parente(); + item = sinistro.get_ControleSinistro().get_Item(); + parente = item.get_Documento(); + str = (string.IsNullOrWhiteSpace(parente.get_Apolice()) ? string.Concat("Proposta Número ", parente.get_Proposta()) : string.Concat("Apólice Número ", parente.get_Apolice())); + string[] strArrays3 = new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), " segue o(s) link(s) para download do(s) arquivo(s) referente ao seu sinistro. ", Environment.NewLine, "Sinistro de número ", sinistro.get_Numero(), " Item sinistrado ", sinistro.get_ItemSinistrado(), ". ", Environment.NewLine, null }; + strArrays3[10] = string.Format("{0}, {1}, {2} de Vigências entre {3:d} e {4:d}. {5}{6}[*LINK*]{7}{8}<|LINKASSINATURA|>Para mais informações entre contato conosco pelo {9}.{10}Atenciosamente {11}.", new object[] { Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Seguradora().get_Nome()), Gestor.Common.Validation.ValidationHelper.Captalize(parente.get_Controle().get_Ramo().get_Nome()), str, parente.get_Vigencia1(), parente.get_Vigencia2(), Environment.NewLine, Environment.NewLine, Environment.NewLine, Environment.NewLine, str2, Environment.NewLine, Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()) }); + return string.Concat(strArrays3); + } + default: + { + if (tipo == 13) + { + break; + } + else + { + goto Label0; + } + } + } + return string.Concat(new string[] { "Prezado(a) ", Gestor.Common.Validation.ValidationHelper.Captalize(this.SelectedCliente.get_Nome()), ", segue o(s) link(s) para download referente ao(s) seu(s) arquivo(s). ", Environment.NewLine, Environment.NewLine, "[*LINK*]", Environment.NewLine, Environment.NewLine, "<|LINKASSINATURA|>", Environment.NewLine, Environment.NewLine, "Para mais informações entre contato conosco pelo ", str2, ".", Environment.NewLine, "Atenciosamente ", Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()), "." }); + Label0: + return string.Concat(new string[] { "Prezado(a), segue o(s) link(s) para download referente ao(s) seu(s) arquivo(s).", Environment.NewLine, Environment.NewLine, "[*LINK*]", Environment.NewLine, Environment.NewLine, " Para mais informações entre contato conosco pelo ", str2, ".", Environment.NewLine, "Atenciosamente ", Gestor.Common.Validation.ValidationHelper.Captalize(Recursos.Empresa.get_Nome()), "." }); + } + + public async Task CreateLink(IndiceArquivoDigital indice) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + string str = string.Format("{0}:{1}:F:{2}", networkTime.Ticks, ApplicationHelper.IdFornecedor, indice.get_Id()).Base64Encode(); + return Recursos.ApiArquivo.AddQuery("search", str); + } + + public void Delete(Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + if (this.SelectedAnexado == null) + { + return; + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = this.ArquivosAnexados.First((Gestor.Model.Domain.Common.ArquivoDigital x) => x.get_Descricao() == arquivo.get_Descricao()); + this.ArquivosAnexados.Remove(arquivoDigital); + this.ArquivosAnexados = new ObservableCollection(this.ArquivosAnexados); + } + + public async void Editar(IndiceArquivoDigital arquivo) + { + if (arquivo != null && arquivo.get_IdArquivoDigital() != 0) + { + await this.ArquivoDigitalServico.Save(arquivo); + } + } + + public async Task EnviarParaAssinatura() + { + bool flag; + object obj; + ObservableCollection arquivosTela = this.ArquivosTela; + if (!arquivosTela.Any((IndiceArquivoDigital x) => x.get_Assinar())) + { + await base.ShowMessage("É NECESSÁRIO SELECIONAR AO MENOS UM ARQUIVO PARA ENVIAR PARA ASSINATURA.", "OK", "", false); + flag = false; + } + else if (!await base.ShowMessage("DESEJA ENVIAR OS ARQUIVOS SELECIONADOS PARA ASSINATURA ELETRÔNICA DO SEGURADO?", "SIM", "NÃO", false)) + { + flag = false; + } + else if (!this.Email.EndsWith(";")) + { + base.Loading(true); + this._assinadorKey = await AssinadorHelper.Key(); + int num = await AssinadorHelper.Licencas(this._assinadorKey); + int num1 = num; + ObservableCollection arquivos = this.Arquivos; + if (num1 >= arquivos.Count((IndiceArquivoDigital x) => { + if (!x.get_Assinar()) + { + return false; + } + return !x.get_EnviadoAssinatura(); + })) + { + AssinadorHelper.Parametros = await AssinaturaServico.BuscarParametrosAssinatura(Recursos.Usuario.get_IdEmpresa()); + int num2 = 0; + ObservableCollection observableCollection = this.ArquivosTela; + int num3 = ( + from x in observableCollection + where x.get_Assinar() + select x).Count(); + ObservableCollection arquivosTela1 = this.ArquivosTela; + foreach (IndiceArquivoDigital indiceArquivoDigital in + from x in arquivosTela1 + where x.get_Assinar() + select x) + { + if (indiceArquivoDigital.get_Assinado()) + { + continue; + } + if (!indiceArquivoDigital.get_EnviadoAssinatura()) + { + ArquivoParaAssinaturaAssinador arquivoParaAssinaturaAssinador = await this.Assinar(indiceArquivoDigital, false); + if (arquivoParaAssinaturaAssinador == null) + { + continue; + } + num--; + indiceArquivoDigital.set_EnviadoAssinatura(true); + indiceArquivoDigital.set_UrlAssinatura(arquivoParaAssinaturaAssinador.get_UrlAssinatura()); + num2++; + indiceArquivoDigital = null; + } + else + { + await (new AssinaturaServico()).Reenviar(indiceArquivoDigital.get_Id()); + } + } + base.Loading(false); + this.Arquivos = new ObservableCollection(this.Arquivos); + await base.ShowMessage(string.Format("{0} DE {1} ARQUIVOS FORAM ENVIADOS PARA ASSINATURA. VOCÊ SERÁ NOTIFICADO QUANDO OS DOCUMENTOS FOREM ASSINADOS", num2, num3), "OK", "", false); + flag = true; + } + else if (base.Restricao(113)) + { + await base.ShowMessage("VOCÊ NÃO POSSUI MAIS LICENÇAS DISPONÍVEIS E O USUÁRIO NÃO PODE CONTRATAR, ENTRE EM CONTATO COM O ADMINISTRADOR DO SISTEMA.", "OK", "", false); + base.Loading(false); + flag = false; + } + else if (await base.ShowMessage("VOCÊ NÃO POSSUI MAIS LICENÇAS DISPONÍVEIS, DESEJA CONTRATAR MAIS?", "SIM", "NÃO", false)) + { + Token token = new Token(); + object[] numeroSerial = new object[] { ApplicationHelper.NumeroSerial, ApplicationHelper.IdFornecedor, Recursos.Usuario.get_Id(), null }; + obj = (ApplicationHelper.Beta ? "1" : "0"); + numeroSerial[3] = obj; + string str = token.Encrypt(string.Format("{0}:{1}:{2}:{3}", numeroSerial)); + Parameters parameter = new Parameters(); + parameter.set_Beta(ApplicationHelper.Beta); + parameter.set_Type(8); + parameter.set_Application("Assinador.Application.exe"); + parameter.set_Directory("Assinador.Application"); + parameter.set_Arguments(str); + parameter.set_Run(true); + (new DownloadWindow(parameter)).Show(); + base.Loading(false); + flag = false; + } + else + { + base.Loading(false); + flag = false; + } + } + else + { + await base.ShowMessage("É NECESSÁRIO QUE O ASSINANTE POSSUA UM E-MAIL VÁLIDO", "OK", "", false); + flag = false; + } + return flag; + } + + public async Task Excluir(IndiceArquivoDigital arquivo) + { + if (arquivo != null && arquivo.get_IdArquivoDigital() != 0) + { + if (await this.ArquivoDigitalServico.DeleteAttachment(arquivo)) + { + await this.CarregaArquivos(); + } + } + } + + public void LimparAnexos() + { + this.ArquivosAnexados = new ObservableCollection(); + } + + public async Task PrepararEnvio() + { + MalaDireta malaDiretum; + Item item; + string str; + Item item1; + string str1; + MalaDireta malaDiretum1; + Gestor.Model.Domain.Seguros.Documento parente; + Parcela parcela; + ObservableCollection arquivos = this.Arquivos; + if (arquivos.Any((IndiceArquivoDigital x) => x.get_Selecionado())) + { + MalaDireta malaDiretum2 = new MalaDireta(); + malaDiretum2.set_Cliente(this.SelectedCliente); + ObservableCollection observableCollection = this.Arquivos; + malaDiretum2.set_ArquivoDigital(( + from x in observableCollection + where x.get_Selecionado() + select x).ToList()); + malaDiretum1 = malaDiretum2; + TipoArquivoDigital tipo = this.Filtro.get_Tipo(); + switch (tipo) + { + case 2: + { + parente = (Gestor.Model.Domain.Seguros.Documento)this.Filtro.get_Parente(); + List items = await base.CarregarItem(parente.get_Controle().get_Id(), 0); + MalaDireta malaDiretum3 = malaDiretum1; + if (items.Count > 1) + { + item = new Item(); + item.set_Id((long)0); + item.set_Descricao("APÓLICE COLETIVA"); + } + else + { + item = items.FirstOrDefault(); + } + malaDiretum3.set_Item(item); + malaDiretum1.set_Apolice(parente); + ArquivoDigitalViewModel arquivoDigitalViewModel = this; + str = (parente.get_Apolice() != string.Empty ? string.Concat("DOCUMENTOS REFERENTES A APÓLICE ", parente.get_Apolice()) : string.Concat("DOCUMENTOS REFERENTES A PROPOSTA ", parente.get_Proposta())); + arquivoDigitalViewModel.Assunto = str; + this.Corpo = string.Concat("PREZADO CLIENTE ", this.SelectedCliente.get_Nome(), ", EM ANEXO OS DOCUMENTOS REFERENTES AO SEU SEGURO."); + malaDiretum1.set_Tela(2); + break; + } + case 3: + { + parcela = (Parcela)this.Filtro.get_Parente(); + malaDiretum1.set_Apolice(parcela.get_Documento()); + malaDiretum1.set_Parcela(parcela); + List items1 = await base.CarregarItem(parcela.get_Documento().get_Controle().get_Id(), 0); + MalaDireta malaDiretum4 = malaDiretum1; + if (items1.Count > 1) + { + item1 = new Item(); + item1.set_Id((long)0); + item1.set_Descricao("APÓLICE COLETIVA"); + } + else + { + item1 = items1.FirstOrDefault(); + } + malaDiretum4.set_Item(item1); + ArquivoDigitalViewModel arquivoDigitalViewModel1 = this; + str1 = (parcela.get_Documento().get_Apolice() != string.Empty ? string.Format("DOCUMENTOS REFERENTE A PARCELA {0} DA APÓLICE {1}", parcela.get_NumeroParcela(), parcela.get_Documento().get_Apolice()) : string.Format("DOCUMENTOS REFERENTE A PARCELA {0} DA PROPOSTA {1}", parcela.get_NumeroParcela(), parcela.get_Documento().get_Proposta())); + arquivoDigitalViewModel1.Assunto = str1; + this.Corpo = string.Concat("PREZADO CLIENTE ", this.SelectedCliente.get_Nome(), ", EM ANEXO OS DOCUMENTOS REFERENTES AS PARCELAS DE SEU SEGURO."); + malaDiretum1.set_Tela(5); + break; + } + case 4: + { + Item parente1 = (Item)this.Filtro.get_Parente(); + malaDiretum1.set_Apolice(parente1.get_Documento()); + malaDiretum1.set_Item(parente1); + this.Assunto = string.Concat("DOCUMENTOS REFERENTES AO ITEM ", parente1.get_Descricao()); + this.Corpo = string.Concat("PREZADO CLIENTE ", this.SelectedCliente.get_Nome(), ", EM ANEXO OS DOCUMENTOS REFERENTES AO SEU BEM."); + malaDiretum1.set_Tela(3); + break; + } + case 5: + { + Sinistro sinistro = (Sinistro)this.Filtro.get_Parente(); + malaDiretum1.set_Sinistro(sinistro); + malaDiretum1.set_Item(sinistro.get_ControleSinistro().get_Item()); + malaDiretum1.set_Apolice(sinistro.get_ControleSinistro().get_Item().get_Documento()); + this.Titulo = string.Concat("DOCUMENTOS REFERENTES AO SINITRO ", sinistro.get_Numero()); + string[] nome = new string[] { "PREZADO CLIENTE ", this.SelectedCliente.get_Nome(), ", EM ANEXO OS DOCUMENTOS REFERENTES SINISTRO DO ITEM ", sinistro.get_ControleSinistro().get_Item().get_Descricao(), "." }; + this.Corpo = string.Concat(nome); + malaDiretum1.set_Tela(7); + break; + } + default: + { + if (tipo == 11) + { + Prospeccao prospeccao = (Prospeccao)this.Filtro.get_Parente(); + malaDiretum1.set_Prospeccao(prospeccao); + malaDiretum1.get_Cliente().set_Id((long)0); + this.Assunto = string.Concat("DOCUMENTOS REFERENTES PROSPECÇÃO ", prospeccao.get_Nome()); + this.Corpo = ""; + malaDiretum1.set_Tela(33); + break; + } + else + { + this.SelectedCliente = (Cliente)this.Filtro.get_Parente(); + this.Titulo = string.Concat("ARQUIVO DIGITAL DO CLIENTE \"", this.SelectedCliente.get_Nome(), "\""); + break; + } + } + } + parente = null; + parcela = null; + malaDiretum = malaDiretum1; + } + else + { + await base.ShowMessage("É NECESSÁRIO SELECIONAR AO MENOS UM ARQUIVO PARA ENVIO.", "OK", "", false); + malaDiretum = null; + } + malaDiretum1 = null; + return malaDiretum; + } + + public async Task SalvarAnexos() + { + if (this.ArquivosAnexados != null && this.ArquivosAnexados.Count != 0) + { + this.Carregando = true; + List list = this.ArquivosAnexados.ToList(); + if (await base.SalvarAttachments(list, this.Filtro.get_Tipo(), this.Filtro.get_Id())) + { + await this.CarregaArquivos(); + this.ArquivosAnexados = new ObservableCollection(); + this.Carregando = false; + } + else + { + this.Carregando = false; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ExpedicaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ExpedicaoViewModel.cs new file mode 100644 index 0000000..2aff10f --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ExpedicaoViewModel.cs @@ -0,0 +1,196 @@ +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ExpedicaoViewModel : BaseSegurosViewModel + { + private readonly ExpedicaoServico _servico; + + private readonly Documento _documento; + + private bool _carregando; + + private Expedicao _selectedExpedicao = new Expedicao(); + + private ObservableCollection _expedicoes = new ObservableCollection(); + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Expedicoes + { + get + { + return this._expedicoes; + } + set + { + this._expedicoes = value; + base.OnPropertyChanged("Expedicoes"); + } + } + + public Expedicao SelectedExpedicao + { + get + { + return this._selectedExpedicao; + } + set + { + long? nullable; + this._selectedExpedicao = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedExpedicao"); + } + } + + public ExpedicaoViewModel(Documento documento) + { + this._servico = new ExpedicaoServico(); + this._documento = documento; + this.Seleciona(documento); + } + + public async void CancelarAlteracao() + { + Expedicao expedicao; + this.Carregando = true; + long id = this.SelectedExpedicao.get_Id(); + await this.Carregar(this.SelectedExpedicao.get_Apolice()); + ExpedicaoViewModel expedicaoViewModel = this; + if (this.Expedicoes.Count <= 0 || id <= (long)0) + { + expedicao = (this.Expedicoes.Count <= 0 || id != 0 ? new Expedicao() : this.Expedicoes.First()); + } + else + { + expedicao = this.Expedicoes.FirstOrDefault((Expedicao x) => x.get_Id() == id); + } + expedicaoViewModel.SelectedExpedicao = expedicao; + base.Alterar(false); + this.Carregando = false; + } + + private async Task Carregar(Documento documento) + { + this.Expedicoes = new ObservableCollection(await this._servico.BuscarExpedicoes(documento)); + } + + public async Task Excluir() + { + bool flag; + Expedicao expedicao; + if (this.SelectedExpedicao == null || this.SelectedExpedicao.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + this.Carregando = true; + if (await this._servico.Delete(this.SelectedExpedicao)) + { + int num = this.Expedicoes.IndexOf(this.SelectedExpedicao); + this.Expedicoes.Remove(this.SelectedExpedicao); + if (this.Expedicoes.Count <= 0) + { + this.SelectedExpedicao = new Expedicao(); + } + else + { + ExpedicaoViewModel expedicaoViewModel = this; + expedicao = (num < this.Expedicoes.Count ? this.Expedicoes.ElementAt(num) : this.Expedicoes.Last()); + expedicaoViewModel.SelectedExpedicao = expedicao; + } + this.Carregando = false; + flag = true; + } + else + { + this.Carregando = false; + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public void Incluir() + { + Expedicao expedicao = new Expedicao(); + expedicao.set_Apolice(this._documento); + this.SelectedExpedicao = expedicao; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + this.SelectedExpedicao = await this._servico.Save(this.SelectedExpedicao); + if (this._servico.Sucesso) + { + long id = this.SelectedExpedicao.get_Id(); + await this.Carregar(this.SelectedExpedicao.get_Apolice()); + this.SelectedExpedicao = this.Expedicoes.FirstOrDefault((Expedicao x) => x.get_Id() == id); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + return keyValuePairs; + } + + private async void Seleciona(Documento documento) + { + this.Carregando = true; + await base.PermissaoTela(46); + await this.Carregar(documento); + if (this.Expedicoes.Count <= 0) + { + this.SelectedExpedicao = new Expedicao(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelectedExpedicao = this.Expedicoes.First(); + } + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ExtratosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ExtratosViewModel.cs new file mode 100644 index 0000000..f07bd68 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ExtratosViewModel.cs @@ -0,0 +1,5516 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Seguros; +using NReco.PdfGenerator; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ExtratosViewModel : BaseSegurosViewModel + { + private readonly ClienteServico _clienteServico = new ClienteServico(); + + private List _documentos; + + private List _prospeccoes; + + private List _clientes; + + private bool _tipoExtratoEnabled = true; + + private bool _extratoResumido; + + private bool _segurosVigentes; + + private Visibility _clientePorPaginaVisibility; + + private bool _clientePorPagina; + + private bool _extratoPorPagina; + + private bool _clientePorPaginaEnabled = true; + + private bool _obsCliente; + + private bool _comissaoDocumento; + + private bool _premioParcela; + + private bool _obsApolice; + + private bool _beneficiariosItens; + + private bool _selecionarItens; + + private bool _endossos; + + private bool _somenteEndosso; + + private Visibility _selecionarItensVisibility; + + private Visibility _endossoVisibility; + + private Visibility _obsDocVisibility; + + private Visibility _segurosVigentesVisibility; + + private bool _obsItem; + + private bool _separarPagina; + + private bool _perfilCondutor; + + private bool _obsClienteEnabled = true; + + private bool _comissaoDocumentoEnabled; + + private bool _obsApoliceEnabled; + + private bool _beneficiariosItensEnabled; + + private bool _obsItemEnabled; + + private bool _separarPaginaEnabled; + + private bool _coberturasEnabled; + + private bool _coberturas; + + private bool _perfilCondutorEnabled; + + private bool _endossoEnabled; + + private bool _esconderResumido; + + private bool _clienteVisibility; + + private bool _documentoVisibility; + + private bool _itemVisibility; + + private bool _perfilVisibility; + + private TipoExtrato _selectedTipoExtrato; + + private bool _carregando; + + private List _itensSelecionados; + + internal Relatorio? TipoDeRelatorio; + + public bool BeneficiariosItens + { + get + { + return this._beneficiariosItens; + } + set + { + this._beneficiariosItens = value; + base.OnPropertyChanged("BeneficiariosItens"); + } + } + + public bool BeneficiariosItensEnabled + { + get + { + return this._beneficiariosItensEnabled; + } + set + { + this._beneficiariosItensEnabled = value; + base.OnPropertyChanged("BeneficiariosItensEnabled"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool ClientePorPagina + { + get + { + return this._clientePorPagina; + } + set + { + this._clientePorPagina = value; + base.OnPropertyChanged("ClientePorPagina"); + } + } + + public bool ClientePorPaginaEnabled + { + get + { + return this._clientePorPaginaEnabled; + } + set + { + this._clientePorPaginaEnabled = value; + base.OnPropertyChanged("ClientePorPaginaEnabled"); + } + } + + public Visibility ClientePorPaginaVisibility + { + get + { + return this._clientePorPaginaVisibility; + } + set + { + this._clientePorPaginaVisibility = value; + base.OnPropertyChanged("ClientePorPaginaVisibility"); + } + } + + public List Clientes + { + get + { + return this._clientes; + } + set + { + this._clientes = value; + base.OnPropertyChanged("Clientes"); + } + } + + public bool ClienteVisibility + { + get + { + return this._clienteVisibility; + } + set + { + this._clienteVisibility = value; + base.OnPropertyChanged("ClienteVisibility"); + } + } + + public bool Coberturas + { + get + { + return this._coberturas; + } + set + { + this._coberturas = value; + base.OnPropertyChanged("Coberturas"); + } + } + + public bool CoberturasEnabled + { + get + { + return this._coberturasEnabled; + } + set + { + this._coberturasEnabled = value; + base.OnPropertyChanged("CoberturasEnabled"); + } + } + + public bool ComissaoDocumento + { + get + { + return this._comissaoDocumento; + } + set + { + this._comissaoDocumento = value; + base.OnPropertyChanged("ComissaoDocumento"); + } + } + + public bool ComissaoDocumentoEnabled + { + get + { + return this._comissaoDocumentoEnabled; + } + set + { + this._comissaoDocumentoEnabled = value; + base.OnPropertyChanged("ComissaoDocumentoEnabled"); + } + } + + public List Documentos + { + get + { + return this._documentos; + } + set + { + this._documentos = value; + base.OnPropertyChanged("Documentos"); + } + } + + public bool DocumentoVisibility + { + get + { + return this._documentoVisibility; + } + set + { + this._documentoVisibility = value; + base.OnPropertyChanged("DocumentoVisibility"); + } + } + + public bool EndossoEnabled + { + get + { + return this._endossoEnabled; + } + set + { + this._endossoEnabled = value; + base.OnPropertyChanged("EndossoEnabled"); + } + } + + public bool Endossos + { + get + { + return this._endossos; + } + set + { + this._endossos = value; + if (this.SomenteEndossos != !value) + { + this.SomenteEndossos = !value; + } + base.OnPropertyChanged("Endossos"); + } + } + + public Visibility EndossoVisibility + { + get + { + return this._endossoVisibility; + } + set + { + this._endossoVisibility = value; + base.OnPropertyChanged("EndossoVisibility"); + } + } + + public bool EsconderResumido + { + get + { + return this._esconderResumido; + } + set + { + this._esconderResumido = value; + base.OnPropertyChanged("EsconderResumido"); + } + } + + public bool ExtratoPorPagina + { + get + { + return this._extratoPorPagina; + } + set + { + this._extratoPorPagina = value; + base.OnPropertyChanged("ExtratoPorPagina"); + } + } + + public bool ExtratoResumido + { + get + { + return this._extratoResumido; + } + set + { + this._extratoResumido = value; + if (!value) + { + this.ClienteVisibility = true; + this.DocumentoVisibility = true; + this.ItemVisibility = true; + this.AjustaTipoSelecionado(this.SelectedTipoExtrato); + } + else + { + this.ClienteVisibility = false; + this.DocumentoVisibility = false; + this.ItemVisibility = this.CoberturasEnabled; + this.SelecionarItensVisibility = Visibility.Collapsed; + this.BeneficiariosItensEnabled = false; + this.ObsItemEnabled = false; + this.SepararPaginaEnabled = false; + } + base.OnPropertyChanged("ExtratoResumido"); + } + } + + public bool ItemVisibility + { + get + { + return this._itemVisibility; + } + set + { + this._itemVisibility = value; + base.OnPropertyChanged("ItemVisibility"); + } + } + + public bool ObsApolice + { + get + { + return this._obsApolice; + } + set + { + this._obsApolice = value; + base.OnPropertyChanged("ObsApolice"); + } + } + + public bool ObsApoliceEnabled + { + get + { + return this._obsApoliceEnabled; + } + set + { + this._obsApoliceEnabled = value; + base.OnPropertyChanged("ObsApoliceEnabled"); + } + } + + public bool ObsCliente + { + get + { + return this._obsCliente; + } + set + { + this._obsCliente = value; + base.OnPropertyChanged("ObsCliente"); + } + } + + public bool ObsClienteEnabled + { + get + { + return this._obsClienteEnabled; + } + set + { + this._obsClienteEnabled = value; + base.OnPropertyChanged("ObsClienteEnabled"); + } + } + + public Visibility ObsDocVisibility + { + get + { + return this._obsDocVisibility; + } + set + { + this._obsDocVisibility = value; + base.OnPropertyChanged("ObsDocVisibility"); + } + } + + public bool ObsItem + { + get + { + return this._obsItem; + } + set + { + this._obsItem = value; + base.OnPropertyChanged("ObsItem"); + } + } + + public bool ObsItemEnabled + { + get + { + return this._obsItemEnabled; + } + set + { + this._obsItemEnabled = value; + base.OnPropertyChanged("ObsItemEnabled"); + } + } + + public bool PerfilCondutor + { + get + { + return this._perfilCondutor; + } + set + { + this._perfilCondutor = value; + base.OnPropertyChanged("PerfilCondutor"); + } + } + + public bool PerfilCondutorEnabled + { + get + { + return this._perfilCondutorEnabled; + } + set + { + this._perfilCondutorEnabled = value; + base.OnPropertyChanged("PerfilCondutorEnabled"); + } + } + + public bool PerfilVisibility + { + get + { + return this._perfilVisibility; + } + set + { + this._perfilVisibility = value; + base.OnPropertyChanged("PerfilVisibility"); + } + } + + public bool PremioParcela + { + get + { + return this._premioParcela; + } + set + { + this._premioParcela = value; + base.OnPropertyChanged("PremioParcela"); + } + } + + public List Prospeccoes + { + get + { + return this._prospeccoes; + } + set + { + this._prospeccoes = value; + base.OnPropertyChanged("Prospeccoes"); + } + } + + public bool SegurosVigentes + { + get + { + return this._segurosVigentes; + } + set + { + this._segurosVigentes = value; + base.OnPropertyChanged("SegurosVigentes"); + } + } + + public Visibility SegurosVigentesVisibility + { + get + { + return this._segurosVigentesVisibility; + } + set + { + this._segurosVigentesVisibility = value; + base.OnPropertyChanged("SegurosVigentesVisibility"); + } + } + + public bool SelecionarItens + { + get + { + return this._selecionarItens; + } + set + { + this._selecionarItens = value; + if (!value) + { + this._itensSelecionados = new List(); + } + base.OnPropertyChanged("SelecionarItens"); + } + } + + public Visibility SelecionarItensVisibility + { + get + { + return this._selecionarItensVisibility; + } + set + { + this._selecionarItensVisibility = value; + base.OnPropertyChanged("SelecionarItensVisibility"); + } + } + + public TipoExtrato SelectedTipoExtrato + { + get + { + return this._selectedTipoExtrato; + } + set + { + this._selectedTipoExtrato = value; + this.AjustaTipoSelecionado(value); + base.OnPropertyChanged("SelectedTipoExtrato"); + } + } + + public bool SepararPagina + { + get + { + return this._separarPagina; + } + set + { + this._separarPagina = value; + base.OnPropertyChanged("SepararPagina"); + } + } + + public bool SepararPaginaEnabled + { + get + { + return this._separarPaginaEnabled; + } + set + { + this._separarPaginaEnabled = value; + base.OnPropertyChanged("SepararPaginaEnabled"); + } + } + + public bool SomenteEndossos + { + get + { + return this._somenteEndosso; + } + set + { + this._somenteEndosso = value; + if (this.Endossos != !value) + { + this.Endossos = !value; + } + base.OnPropertyChanged("SomenteEndossos"); + } + } + + public bool TipoExtratoEnabled + { + get + { + return this._tipoExtratoEnabled; + } + set + { + this._tipoExtratoEnabled = value; + base.OnPropertyChanged("TipoExtratoEnabled"); + } + } + + public ExtratosViewModel() + { + } + + public void AjustaTipoSelecionado(TipoExtrato tipoExtrato) + { + switch (tipoExtrato) + { + case 0: + { + this.ClienteVisibility = true; + this.ClientePorPaginaVisibility = Visibility.Hidden; + this.DocumentoVisibility = false; + this.ItemVisibility = false; + this.PerfilVisibility = false; + this.EsconderResumido = true; + this.SelecionarItensVisibility = Visibility.Collapsed; + this.SegurosVigentesVisibility = Visibility.Collapsed; + this.SegurosVigentes = false; + this.EndossoVisibility = Visibility.Collapsed; + this.ObsDocVisibility = Visibility.Collapsed; + this.ExtratoCliente(); + return; + } + case 1: + { + this.ClienteVisibility = true; + this.ClientePorPaginaVisibility = Visibility.Visible; + this.DocumentoVisibility = true; + this.ItemVisibility = true; + this.PerfilVisibility = true; + this.EsconderResumido = false; + this.SelecionarItensVisibility = (!this.TipoDeRelatorio.HasValue ? Visibility.Visible : Visibility.Collapsed); + this.SegurosVigentesVisibility = Visibility.Collapsed; + this.SegurosVigentes = false; + this.EndossoVisibility = Visibility.Visible; + this.ObsDocVisibility = Visibility.Visible; + this.ApoliceSelecionada(); + return; + } + case 2: + { + this.ClienteVisibility = false; + this.ClientePorPaginaVisibility = Visibility.Collapsed; + this.DocumentoVisibility = true; + this.ItemVisibility = false; + this.PerfilVisibility = true; + this.EsconderResumido = false; + this.SelecionarItensVisibility = Visibility.Collapsed; + this.SegurosVigentesVisibility = Visibility.Visible; + this.EndossoVisibility = Visibility.Collapsed; + this.ObsDocVisibility = Visibility.Collapsed; + this.RelacaoApolices(); + return; + } + default: + { + return; + } + } + } + + private void ApoliceSelecionada() + { + this.SetAllFalse(); + this.ObsClienteEnabled = true; + this.ClientePorPaginaEnabled = true; + this.ComissaoDocumentoEnabled = true; + this.ObsApoliceEnabled = true; + this.BeneficiariosItensEnabled = true; + this.ObsItemEnabled = true; + this.SepararPaginaEnabled = true; + this.PerfilCondutorEnabled = true; + this.EndossoEnabled = true; + this.CoberturasEnabled = true; + } + + private void ExtratoCliente() + { + this.SetAllFalse(); + this.ObsClienteEnabled = true; + } + + public async Task Gerar(Relatorio? tipoRelatorio = null, bool pdf = false) + { + DateTime date; + List items; + int numeroParcela; + DateTime? clienteDesde; + EstadoCivil? estadoCivil; + Sexo? sexo; + TipoTelefone? nullable; + TipoTelefone tipoTelefone; + decimal premioLiquido; + List controleSinistros; + long id; + Patrimonial patrimonial; + Auto auto; + TipoCobertura? tipoCobertura; + int? bonus; + TabelaReferencia? tabelaReferencia; + Vida vida; + RiscosDiversos riscosDiverso; + Aeronautico aeronautico; + Granizo granizo; + string str14; + string str15; + string str16; + string str17; + string str18; + string str19; + string str20; + string str21; + string str22; + string shortDateString; + string str23; + string str24; + string shortDateString1; + string str25; + string str26; + string str27; + string str28; + string str29; + string str30; + string str31; + string str32; + string shortDateString2; + string str33; + string str34; + string str35; + string str36; + string str37; + string str38; + string str39; + string str40; + string str41; + string str42; + string str43; + string str44; + string str45; + string str46; + string str47; + string str48; + string shortDateString3; + string str49; + string str50; + string str51; + string str52; + string str53; + string endosso; + string str54; + string str55; + string str56; + string str57; + string str58; + string str59; + string str60; + string str61; + string str62; + string str63; + string str64; + string str65; + string str66; + string str67; + string str68; + string str69; + string str70; + string str71; + string str72; + string shortDateString4; + string str73; + string shortDateString5; + string str74; + string str75; + string str76; + string str77; + string str78; + string str79; + string str80; + string str81; + string str82; + string str83; + string str84; + string str85; + string str86; + string str87; + string str88; + string str89; + string str90; + string description; + string str91; + string str92; + string str93; + string str94; + string description1; + string str95; + string str96; + string str97; + string str98; + string str99; + string str100; + string str101; + string str102; + string str103; + string str104; + string str105; + string str106; + DateTime? dataReclamacao; + string shortDateString6; + string str107; + string description2; + string str108; + string str109; + string currency; + string str110; + string str111; + string descricao; + string str112; + string str113; + string str114; + string str115; + string str116; + string str117; + string str118; + string shortDateString7; + string str119; + string str120; + string str121; + string str122; + string str123; + string str124; + string str125; + string str126; + string str127; + string str128; + string str129; + string str130; + string str131; + string str132; + string str133; + string str134; + string str135; + string str136; + string str137; + string str138; + string str139; + string str140; + string str141; + string str142; + string str143; + string str144; + string str145; + string str146; + string str147; + string str148; + string str149; + string str150; + string str151; + string str152; + string str153; + string str154; + string str155; + string str156; + string str157; + string str158; + string str159; + string str160; + string str161; + string str162; + string str163; + bool count; + string str164; + string str165; + string str166; + string str167; + string str168; + string str169; + string str170; + string str171; + string str172; + string str173; + string str174; + string str175; + NegocioCorretora negocioCorretora; + string str176; + string str177; + string str178; + string str179; + string shortDateString8; + string str180; + string str181; + string str182; + string str183; + string str184; + string str185; + string shortDateString9; + string str186; + string str187; + string str188; + string str189; + string str190; + string str191; + string str192; + string str193; + string str194; + string str195; + string str196; + string str197; + string str198; + string str199; + string str200; + string str201; + string str202; + string str203; + string str204; + string str205; + string str206; + string str207; + string str208; + string str209; + string str210; + string str211; + string str212; + string str213; + string str214; + string str215; + string str216; + string str217; + string str218; + string str219; + string str220; + string str221; + string str222; + string str223; + string str224; + string shortDateString10; + string str225; + string str226; + string str227; + string str228; + string str229; + string shortDateString11; + string str230; + string shortDateString12; + string str231; + string shortDateString13; + string str232; + string str233; + string str234; + string str235; + string str236; + string str237; + string str238; + string str239; + string str240; + string str241; + string str242; + string str243; + Documento documento; + string str244; + string str245; + string str246; + string shortDateString14; + string str247; + string str248; + string str249; + string str250; + string str251; + string endosso1; + string str252; + string str253; + string str254; + string str255; + string str256; + string str257; + string str258; + string str259; + string str260; + string str261; + string str262; + string str263; + string str264; + string str265; + string str266; + string str267; + string str268; + string str269; + string str270; + string str271; + string str272; + string str273; + string str274; + string str275; + string str276; + string str277; + string description3; + string str278; + string str279; + string str280; + string str281; + string description4; + string str282; + string str283; + string str284; + string str285; + string str286; + string str287; + string str288; + string str289; + string str290; + string str291; + DateTime? dataReclamacao1; + string shortDateString15; + string str292; + string str293; + string str294; + string str295; + string descricao1; + string str296; + string str297; + string str298; + string str299; + string str300; + string str301; + string str302; + string shortDateString16; + string str303; + string str304; + string str305; + string str306; + string str307; + string str308; + string str309; + string str310; + string str311; + string str312; + string str313; + string str314; + string str315; + string str316; + string str317; + string str318; + string str319; + string str320; + string str321; + string str322; + string str323; + string str324; + string str325; + string str326; + string str327; + string str328; + string str329; + string str330; + string str331; + NegocioCorretora negocioCorretora1; + string str332; + string str333; + string str334; + string str335; + string str336; + string str337; + string str338; + string str339; + string str340; + string str341; + string str342; + string str343; + string str344; + string str345; + string str346; + string str347; + string str348; + string str349; + string str350; + string str351; + string str352; + string shortDateString17; + string str353; + string str354; + string str355; + string str356; + string str357; + string str358; + string str359; + string str360; + string str361; + string str362; + string str363; + string str364; + string str365; + string str366; + string str367; + string str368; + string str369; + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable9 = null; + int num10; + List list; + Item item = null; + Item item1; + string str370; + string str371 = ""; + if (this.Clientes != null && this.Documentos == null) + { + str371 = string.Concat(str371, ""); + str367 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str367, " DO CLIENTE"); + str371 = string.Concat(str371, str370); + str371 = string.Concat(str371, "
"); + str371 = string.Concat(str371, ""); + long id1 = (long)0; + this.Clientes.ForEach((Cliente x) => { + TipoTelefone? tipo; + TipoTelefone valueOrDefault; + string str; + string str1; + string upper; + string str2; + string str3; + string str4; + string upper1; + string str5; + string str6; + string str7; + string str8; + int num = 0; + if (id1 != x.get_Id()) + { + id1 = x.get_Id(); + str371 = string.Concat(str371, (!this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
")); + str371 = string.Concat(str371, "

"); + str370 = string.Concat("EXTRATO", (this.ExtratoResumido ? " RESUMIDO" : ""), " DO CLIENTE: ", x.get_Nome()); + str371 = string.Concat(str371, str370, "


"); + string str9 = (x.get_Atividade() == null ? "NASCIMENTO" : "ABERTURA"); + bool pessoaFisica = x.get_PessoaFisica(); + ExtratosViewModel.u003cu003ec__DisplayClass170_0 cSu0024u003cu003e8_locals1 = variable9; + string[] strArrays = new string[] { str371, ""; + cSu0024u003cu003e8_locals1.html = string.Concat(strArrays); + if (!pessoaFisica) + { + num++; + } + else + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable = variable9; + string[] cSu0024u003cu003e8_locals11 = new string[] { str371, ""; + variable.html = string.Concat(cSu0024u003cu003e8_locals11); + } + str371 = string.Concat(str371, ""); + if (x.get_Atividade() != null) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable1 = variable9; + string[] nome = new string[] { str371, ""; + variable1.html = string.Concat(nome); + if (!pessoaFisica) + { + num++; + } + } + if (this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + if (pessoaFisica) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 cSu0024u003cu003e8_locals12 = variable9; + string[] strArrays1 = new string[] { str371, ""; + cSu0024u003cu003e8_locals12.html = string.Concat(strArrays1); + } + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable2 = variable9; + string[] strArrays2 = new string[] { str371, ""; + cSu0024u003cu003e8_locals13.html = string.Concat(strArrays3); + } + if (!string.IsNullOrWhiteSpace(x.get_Identidade())) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable3 = variable9; + string[] cSu0024u003cu003e8_locals14 = new string[] { str371, ""; + variable3.html = string.Concat(cSu0024u003cu003e8_locals14); + } + if (this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable4 = variable9; + string[] strArrays4 = new string[] { str371, ""; + variable4.html = string.Concat(strArrays4); + } + if ((x.get_Telefones() != null || x.get_Emails() != null) && this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + if (x.get_Telefones() != null) + { + string str10 = ""; + foreach (ClienteTelefone telefone in x.get_Telefones()) + { + string[] prefixo = new string[] { str10, "
", null, null, null, null, null }; + tipo = telefone.get_Tipo(); + if (tipo.HasValue) + { + valueOrDefault = tipo.GetValueOrDefault(); + upper1 = valueOrDefault.ToString().ToUpper(); + } + else + { + upper1 = null; + } + prefixo[2] = upper1; + prefixo[3] = " ("; + prefixo[4] = telefone.get_Prefixo(); + prefixo[5] = ") "; + prefixo[6] = telefone.get_Numero(); + str10 = string.Concat(prefixo); + } + ExtratosViewModel.u003cu003ec__DisplayClass170_0 cSu0024u003cu003e8_locals15 = variable9; + string[] strArrays5 = new string[] { str371, "
"; + cSu0024u003cu003e8_locals15.html = string.Concat(strArrays5); + } + if (x.get_Emails() != null && !this.ExtratoResumido) + { + string str11 = ""; + foreach (ClienteEmail email in x.get_Emails()) + { + str11 = string.Concat(str11, "
", email.get_Email()); + } + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable5 = variable9; + string[] cSu0024u003cu003e8_locals16 = new string[] { str371, "
"; + variable5.html = string.Concat(cSu0024u003cu003e8_locals16); + } + num++; + str371 = string.Concat(str371, ""); + } + if (x.get_Enderecos() != null && this.SelectedTipoExtrato != 2) + { + string str12 = ""; + foreach (ClienteEndereco endereco in x.get_Enderecos()) + { + string[] bairro = new string[] { str12, "
", endereco.get_Endereco(), ", ", endereco.get_Numero(), ", ", null, null, null, null, null, null, null, null }; + bairro[6] = (string.IsNullOrWhiteSpace(endereco.get_Complemento()) ? "" : string.Concat(endereco.get_Complemento(), ", ")); + bairro[7] = endereco.get_Bairro(); + bairro[8] = " - "; + bairro[9] = endereco.get_Cidade(); + bairro[10] = " - "; + bairro[11] = endereco.get_Estado(); + bairro[12] = " - "; + bairro[13] = endereco.get_Cep(); + str12 = string.Concat(bairro); + } + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable6 = variable9; + string[] strArrays6 = new string[] { str371, "
"; + variable6.html = string.Concat(strArrays6); + } + if (x.get_Profissao() != null && this.SelectedTipoExtrato != 2) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 cSu0024u003cu003e8_locals17 = variable9; + string[] nome1 = new string[] { str371, ""; + cSu0024u003cu003e8_locals17.html = string.Concat(nome1); + } + if (x.get_Contatos() != null && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + string str13 = ""; + foreach (MaisContato contato in x.get_Contatos()) + { + string[] nome2 = new string[15]; + nome2[0] = str13; + nome2[1] = "
NOME: "; + nome2[2] = contato.get_Nome(); + nome2[3] = (!string.IsNullOrWhiteSpace(contato.get_Documento()) ? string.Concat(", DOCUMENTO: ", contato.get_Documento()) : ""); + nascimento = contato.get_Nascimento(); + if (nascimento.HasValue) + { + nascimento = contato.get_Nascimento(); + str = string.Concat(", NASCIMENTO: ", (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null)); + } + else + { + str = ""; + } + nome2[4] = str; + Parentesco? parentesco = contato.get_Parentesco(); + if (parentesco.HasValue) + { + parentesco = contato.get_Parentesco(); + str1 = string.Concat(", PARENTESCO: ", (parentesco.HasValue ? parentesco.GetValueOrDefault().ToString().ToUpper() : null)); + } + else + { + str1 = ""; + } + nome2[5] = str1; + nome2[6] = (!string.IsNullOrWhiteSpace(contato.get_Banco()) || !string.IsNullOrWhiteSpace(contato.get_Agencia()) || !string.IsNullOrWhiteSpace(contato.get_Conta()) ? "
" : ""); + nome2[7] = (!string.IsNullOrWhiteSpace(contato.get_Banco()) ? string.Concat("BANCO: ", contato.get_Banco()) : ""); + nome2[8] = (!string.IsNullOrWhiteSpace(contato.get_Agencia()) ? string.Concat((!string.IsNullOrWhiteSpace(contato.get_Banco()) ? ", AGÊNCIA: " : "AGÊNCIA: "), contato.get_Agencia()) : ""); + nome2[9] = (!string.IsNullOrWhiteSpace(contato.get_Conta()) ? string.Concat((!string.IsNullOrWhiteSpace(contato.get_Banco()) || !string.IsNullOrWhiteSpace(contato.get_Agencia()) ? ", CONTA: " : "CONTA: "), contato.get_Conta()) : ""); + tipo = contato.get_Tipo(); + nome2[10] = (tipo.HasValue || !string.IsNullOrWhiteSpace(contato.get_Prefixo()) && !string.IsNullOrWhiteSpace(contato.get_Telefone()) || !string.IsNullOrWhiteSpace(contato.get_Email()) ? "
" : ""); + tipo = contato.get_Tipo(); + if (tipo.HasValue) + { + tipo = contato.get_Tipo(); + if (tipo.HasValue) + { + valueOrDefault = tipo.GetValueOrDefault(); + upper = valueOrDefault.ToString().ToUpper(); + } + else + { + upper = null; + } + str2 = string.Concat("TIPO DO TELEFONE: ", upper); + } + else + { + str2 = ""; + } + nome2[11] = str2; + if (string.IsNullOrWhiteSpace(contato.get_Prefixo()) || string.IsNullOrWhiteSpace(contato.get_Telefone())) + { + str3 = ""; + } + else + { + tipo = contato.get_Tipo(); + str3 = string.Concat((tipo.HasValue ? ", TELEFONE: (" : "TELEFONE: ("), contato.get_Prefixo(), ") ", contato.get_Telefone()); + } + nome2[12] = str3; + if (!string.IsNullOrWhiteSpace(contato.get_Email())) + { + tipo = contato.get_Tipo(); + str4 = string.Concat((tipo.HasValue || !string.IsNullOrWhiteSpace(contato.get_Prefixo()) && !string.IsNullOrWhiteSpace(contato.get_Telefone()) ? ", EMAIL: " : "EMAIL: "), contato.get_Email()); + } + else + { + str4 = ""; + } + nome2[13] = str4; + nome2[14] = "
"; + str13 = string.Concat(nome2); + } + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable7 = variable9; + string[] strArrays7 = new string[] { str371, "
"; + variable7.html = string.Concat(strArrays7); + } + if (this.ObsCliente && this.ClienteVisibility && this.ObsClienteEnabled && !string.IsNullOrWhiteSpace(x.get_Observacao()) && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + x.set_Observacao(string.Concat("
", x.get_Observacao().Replace("\r\n", "
"))); + ExtratosViewModel.u003cu003ec__DisplayClass170_0 cSu0024u003cu003e8_locals18 = variable9; + string[] observacao = new string[] { str371, "
"; + cSu0024u003cu003e8_locals18.html = string.Concat(observacao); + } + if (!string.IsNullOrWhiteSpace(x.get_Pasta()) && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + ExtratosViewModel.u003cu003ec__DisplayClass170_0 variable8 = variable9; + string[] pasta = new string[] { str371, ""; + variable8.html = string.Concat(pasta); + } + str371 = string.Concat(str371, "

CLIENTE: ", x.get_Nome(), "

CPF/CNPJ: ", x.get_Documento(), "

", str9, ": ", null, null }; + DateTime? nascimento = x.get_Nascimento(); + strArrays[20] = (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null); + strArrays[21] = "

FALECIDO: "; + cSu0024u003cu003e8_locals11[4] = (x.get_Falecido() ? "SIM" : "NÃO"); + cSu0024u003cu003e8_locals11[5] = "

RAMO DE ATIVIDADE: "; + nome[4] = x.get_Atividade().get_Nome(); + nome[5] = "

ESTADO CIVIL: "; + strArrays1[4] = (x.get_EstadoCivil().HasValue ? x.get_EstadoCivil().ToString().ToUpper() : "-"); + strArrays1[5] = "

SEXO: "; + strArrays1[8] = (x.get_Sexo().HasValue ? x.get_Sexo().ToString().ToUpper() : "-"); + strArrays1[9] = "

HABILITAÇÃO: ", (!string.IsNullOrWhiteSpace(x.get_Habilitacao()) ? x.get_Habilitacao() : "-"), "

CATEGORIA: ", (!string.IsNullOrWhiteSpace(x.get_CategoriaHabilitacao()) ? x.get_CategoriaHabilitacao() : "-"), "

1ª HAB.: ", null, null, null, null, null, null }; + nascimento = x.get_PrimeiraHabilitacao(); + if (nascimento.HasValue) + { + nascimento = x.get_PrimeiraHabilitacao(); + str6 = (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null); + } + else + { + str6 = "-"; + } + strArrays3[12] = str6; + strArrays3[13] = "

VENCIMENTO: "; + nascimento = x.get_VencimentoHabilitacao(); + if (nascimento.HasValue) + { + nascimento = x.get_VencimentoHabilitacao(); + str7 = (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null); + } + else + { + str7 = "-"; + } + strArrays3[16] = str7; + strArrays3[17] = "

RG: ", (!string.IsNullOrWhiteSpace(x.get_Identidade()) ? x.get_Identidade() : "-"), "

ORGÃO EMISSOR: ", (!string.IsNullOrWhiteSpace(x.get_Emissor()) ? x.get_Emissor() : "-"), "

ESTADO EMISSOR: ", (!string.IsNullOrWhiteSpace(x.get_EstadoEmissor()) ? x.get_EstadoEmissor() : "-"), "

EXPEDIÇÃO: "; + nascimento = x.get_Expedicao(); + if (nascimento.HasValue) + { + nascimento = x.get_Expedicao(); + str5 = (nascimento.HasValue ? nascimento.GetValueOrDefault().ToShortDateString() : null); + } + else + { + str5 = "-"; + } + cSu0024u003cu003e8_locals14[16] = str5; + cSu0024u003cu003e8_locals14[17] = "

BANCO: ", (x.get_Banco() != null ? x.get_Banco().get_Nome() : "-"), "

AGÊNCIA: ", (!string.IsNullOrWhiteSpace(x.get_Agencia()) ? x.get_Agencia() : "-"), "

CONTA: ", (!string.IsNullOrWhiteSpace(x.get_Conta()) ? x.get_Conta() : "-"), "

TIPO: "; + strArrays4[16] = (!string.IsNullOrWhiteSpace(x.get_TipoConta()) ? x.get_TipoConta() : "-"); + strArrays4[17] = "

CONTATOS: "; + strArrays5[4] = str10; + strArrays5[5] = "

EMAILS: "; + cSu0024u003cu003e8_locals16[4] = str11; + cSu0024u003cu003e8_locals16[5] = "

ENDEREÇOS: "; + strArrays6[4] = str12; + strArrays6[5] = "

PROFISSÃO: "; + nome1[4] = x.get_Profissao().get_Nome(); + nome1[5] = "

MAIS CONTATOS: "; + strArrays7[4] = str13; + strArrays7[5] = "

OBSERVAÇÕES: "; + observacao[4] = x.get_Observacao(); + observacao[5] = "

PASTA: "; + pasta[4] = x.get_Pasta(); + pasta[5] = "

"); + str371 = string.Concat(str371, (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
")); + } + }); + DateTime networkTime = Funcoes.GetNetworkTime(); + string[] strArrays8 = new string[] { str371, "

", Recursos.Usuario.get_Nome(), " - ", null, null }; + date = networkTime.Date; + strArrays8[4] = date.ToShortDateString(); + strArrays8[5] = "
"; + str371 = string.Concat(strArrays8); + string tempPath = Path.GetTempPath(); + string str372 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, networkTime); + if (!pdf) + { + StreamWriter streamWriter = new StreamWriter(str372, true, Encoding.UTF8); + streamWriter.Write(str371); + streamWriter.Close(); + } + else + { + str372 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.pdf", tempPath, (TipoExtrato)0, networkTime); + File.WriteAllBytes(str372, (new NRecoHtmlToPdfConverter()).GeneratePdf(str371)); + } + Process.Start(str372); + ExtratosViewModel extratosViewModel = this; + str368 = (this.ExtratoResumido ? " RESUMIDO" : ""); + if (this.Clientes != null) + { + str369 = (this.Clientes.Count > 1 ? string.Format("DE {0} CLIENTES", this.Clientes.Count) : string.Concat("DO CLIENTE ", this.Clientes[0].get_Nome())); + } + else + { + str369 = ""; + } + string str373 = string.Concat("GEROU O EXTRATO", str368, " ", str369); + long num11 = (long)0; + TipoTela? nullable1 = new TipoTela?(23); + List clientes = this.Clientes; + extratosViewModel.RegistrarAcao(str373, num11, nullable1, string.Concat("NOMES DOS CLIENTES:\n", string.Join("\n", + from x in clientes + select x.get_Nome()), this.GerarOpcoes())); + this.Documentos = null; + this.Clientes = null; + } + else if ((this.Documentos != null || this.Prospeccoes != null) && this.Clientes == null) + { + str371 = ""; + str370 = ""; + switch (this.SelectedTipoExtrato) + { + case 0: + { + str14 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str14, " DO CLIENTE"); + break; + } + case 1: + { + str364 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str364, " DA APÓLICE SELECIONADA"); + if (!tipoRelatorio.HasValue || tipoRelatorio.GetValueOrDefault() != 4) + { + break; + } + str365 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str365, " DO RELATÓRIO DE RENOVAÇÕES"); + break; + } + case 2: + { + str366 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str366, " DE RELAÇÃO DE APÓLICES"); + break; + } + } + str371 = string.Concat(str371, str370); + str371 = string.Concat(str371, "
"); + List nums = new List(); + if (this.Documentos != null && this.Documentos.Count > 0) + { + List configuracoes = Recursos.Configuracoes; + bool flag = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 42); + foreach (Documento documento1 in this.Documentos) + { + Documento documento2 = documento1; + ObservableCollection observableCollection = await (new ParcelaServico()).BuscarParcelasAsync(documento1.get_Id()); + documento2.set_Parcelas(observableCollection); + documento2 = null; + Controle controle = documento1.get_Controle(); + Cliente cliente = await this._clienteServico.BuscarCliente(documento1.get_Controle().get_Cliente().get_Id()); + controle.set_Cliente(cliente); + controle = null; + Cliente cliente1 = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection1 = await this._clienteServico.BuscarEnderecosAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente1.set_Enderecos(observableCollection1); + cliente1 = null; + cliente1 = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection2 = await this._clienteServico.BuscarEmailsAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente1.set_Emails(observableCollection2); + cliente1 = null; + cliente1 = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection3 = await this._clienteServico.BuscarTelefonesAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente1.set_Telefones(observableCollection3); + cliente1 = null; + cliente1 = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection4 = await this._clienteServico.BuscarContatosAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente1.set_Contatos(observableCollection4); + cliente1 = null; + } + bool flag1 = true; + foreach (Documento documento3 in this.Documentos) + { + List items1 = new List(); + items = (!this.Endossos ? await (new ItemServico()).BuscarItens(documento3.get_Controle().get_Id(), 0).ToList() : await (new ItemServico()).BuscarItens(documento3.get_Id(), 2).ToList()); + List items2 = items; + if (this._itensSelecionados == null || this._itensSelecionados.Count <= 0) + { + items1.AddRange(items2); + } + else + { + items2.ForEach((Item x) => { + if (this._itensSelecionados.Any((Item y) => y.get_Id() == x.get_Id())) + { + items1.Add(x); + } + }); + } + List perfils = await (new PerfilServico()).BuscarPerfis(documento3.get_Controle().get_Id()); + long num12 = (long)0; + num10 = 0; + if (!flag1) + { + string str374 = str371; + str363 = (this.ExtratoPorPagina ? "
" : ""); + str371 = string.Concat(str374, str363); + } + if (num12 != documento3.get_Controle().get_Cliente().get_Id()) + { + string str375 = str371; + str40 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled || this.ExtratoPorPagina ? "" : "
"); + str371 = string.Concat(str375, str40); + str371 = string.Concat(str371, "

"); + switch (this.SelectedTipoExtrato) + { + case 0: + { + str41 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str41, " DO CLIENTE: ", documento3.get_Controle().get_Cliente().get_Nome()); + break; + } + case 1: + { + str359 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str359, " DA APÓLICE SELECIONADA: ", documento3.get_Apolice()); + if (tipoRelatorio.HasValue && tipoRelatorio.GetValueOrDefault() == 4) + { + str361 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str361, " DA APÓLICE: ", documento3.get_Apolice()); + } + if (!string.IsNullOrEmpty(documento3.get_Endosso()) && !documento3.get_Endosso().Equals("0")) + { + str370 = string.Concat(str370, " E DO ENDOSSO: ", documento3.get_Endosso()); + } + if (!this.SomenteEndossos) + { + break; + } + str360 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str360, " DO ENDOSSO: ", documento3.get_Endosso()); + break; + } + case 2: + { + str362 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str362, " DE RELAÇÃO DE APÓLICES"); + break; + } + } + str371 = string.Concat(str371, str370, "


"); + str371 = string.Concat(str371, ""); + if (!this.ExtratoResumido) + { + if ((!this.Endossos || !this.SomenteEndossos) && !nums.Any((long x) => x == this.documento.get_Controle().get_Id())) + { + str176 = (documento3.get_Controle().get_Cliente().get_Atividade() == null ? "NASCIMENTO" : "ABERTURA"); + string str376 = str176; + bool flag2 = documento3.get_Controle().get_Cliente().get_PessoaFisica(); + string[] documento4 = new string[24]; + documento4[0] = str371; + documento4[1] = ""; + str371 = string.Concat(strArrays9); + } + str371 = string.Concat(str371, ""); + if (documento3.get_Controle().get_Cliente().get_Atividade() != null) + { + string[] strArrays10 = new string[] { str371, ""); + if (documento3.get_Controle().get_Cliente().get_Profissao() == null || this.SelectedTipoExtrato == 2) + { + numeroParcela = num10; + num10 = numeroParcela + 1; + } + else + { + string[] strArrays13 = new string[] { str371, ""; + str371 = string.Concat(strArrays13); + } + str371 = string.Concat(str371, ""); + } + if (flag2) + { + string[] strArrays14 = new string[18]; + strArrays14[0] = str371; + strArrays14[1] = ""; + str371 = string.Concat(strArrays14); + } + if (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Identidade())) + { + string[] strArrays15 = new string[18]; + strArrays15[0] = str371; + strArrays15[1] = ""; + str371 = string.Concat(strArrays15); + } + if (this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + string[] strArrays16 = new string[18]; + strArrays16[0] = str371; + strArrays16[1] = ""; + str371 = string.Concat(strArrays16); + } + if ((documento3.get_Controle().get_Cliente().get_Telefones() != null || documento3.get_Controle().get_Cliente().get_Emails() != null) && this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + if (documento3.get_Controle().get_Cliente().get_Telefones() != null) + { + string str378 = ""; + foreach (ClienteTelefone clienteTelefone in documento3.get_Controle().get_Cliente().get_Telefones()) + { + string[] numero = new string[] { str378, "
", null, null, null, null, null, null, null, null }; + nullable = clienteTelefone.get_Tipo(); + if (nullable.HasValue) + { + tipoTelefone = nullable.GetValueOrDefault(); + str208 = tipoTelefone.ToString().ToUpper(); + } + else + { + str208 = null; + } + numero[2] = str208; + numero[3] = " ("; + numero[4] = clienteTelefone.get_Prefixo(); + numero[5] = ") "; + numero[6] = clienteTelefone.get_Numero(); + numero[7] = " ("; + numero[8] = clienteTelefone.get_Observacao(); + numero[9] = ") "; + str378 = string.Concat(numero); + } + string[] strArrays17 = new string[] { str371, "
"; + str371 = string.Concat(strArrays17); + } + if (documento3.get_Controle().get_Cliente().get_Emails() != null && !this.ExtratoResumido) + { + string str379 = ""; + foreach (ClienteEmail clienteEmail in documento3.get_Controle().get_Cliente().get_Emails()) + { + str379 = string.Concat(str379, "
", clienteEmail.get_Email()); + } + string[] strArrays18 = new string[] { str371, "
"; + str371 = string.Concat(strArrays18); + } + else if (documento3.get_Controle().get_Cliente().get_Enderecos() != null && this.SelectedTipoExtrato != 2) + { + string str380 = ""; + foreach (ClienteEndereco clienteEndereco in documento3.get_Controle().get_Cliente().get_Enderecos()) + { + string[] cidade = new string[] { str380, "
", clienteEndereco.get_Endereco(), ", ", clienteEndereco.get_Numero(), ", ", null, null, null, null, null, null, null, null }; + str205 = (string.IsNullOrWhiteSpace(clienteEndereco.get_Complemento()) ? "" : string.Concat(clienteEndereco.get_Complemento(), ", ")); + cidade[6] = str205; + cidade[7] = clienteEndereco.get_Bairro(); + cidade[8] = " - "; + cidade[9] = clienteEndereco.get_Cidade(); + cidade[10] = " - "; + cidade[11] = clienteEndereco.get_Estado(); + cidade[12] = " - "; + cidade[13] = clienteEndereco.get_Cep(); + str380 = string.Concat(cidade); + } + string[] strArrays19 = new string[] { str371, "
"; + str371 = string.Concat(strArrays19); + } + numeroParcela = num10; + num10 = numeroParcela + 1; + str371 = string.Concat(str371, ""); + } + if (documento3.get_Controle().get_Cliente().get_Enderecos() != null && this.SelectedTipoExtrato != 2 && documento3.get_Controle().get_Cliente().get_Emails() == null && this.ExtratoResumido) + { + string str381 = ""; + foreach (ClienteEndereco clienteEndereco1 in documento3.get_Controle().get_Cliente().get_Enderecos()) + { + string[] estado = new string[] { str381, "
", clienteEndereco1.get_Endereco(), ", ", clienteEndereco1.get_Numero(), ", ", null, null, null, null, null, null, null, null }; + str203 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Complemento()) ? "" : string.Concat(clienteEndereco1.get_Complemento(), ", ")); + estado[6] = str203; + estado[7] = clienteEndereco1.get_Bairro(); + estado[8] = " - "; + estado[9] = clienteEndereco1.get_Cidade(); + estado[10] = " - "; + estado[11] = clienteEndereco1.get_Estado(); + estado[12] = " - "; + estado[13] = clienteEndereco1.get_Cep(); + str381 = string.Concat(estado); + } + string[] strArrays20 = new string[] { str371, "
"; + str371 = string.Concat(strArrays20); + } + if (documento3.get_Controle().get_Cliente().get_Contatos() != null && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + string str382 = ""; + foreach (MaisContato maisContato in documento3.get_Controle().get_Cliente().get_Contatos()) + { + string[] strArrays21 = new string[15]; + strArrays21[0] = str382; + strArrays21[1] = "
NOME: "; + strArrays21[2] = maisContato.get_Nome(); + str185 = (!string.IsNullOrWhiteSpace(maisContato.get_Documento()) ? string.Concat(", DOCUMENTO: ", maisContato.get_Documento()) : ""); + strArrays21[3] = str185; + clienteDesde = maisContato.get_Nascimento(); + if (clienteDesde.HasValue) + { + clienteDesde = maisContato.get_Nascimento(); + if (clienteDesde.HasValue) + { + shortDateString9 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString9 = null; + } + str186 = string.Concat(", NASCIMENTO: ", shortDateString9); + } + else + { + str186 = ""; + } + strArrays21[4] = str186; + Parentesco? nullable2 = maisContato.get_Parentesco(); + if (nullable2.HasValue) + { + nullable2 = maisContato.get_Parentesco(); + if (nullable2.HasValue) + { + str187 = nullable2.GetValueOrDefault().ToString().ToUpper(); + } + else + { + str187 = null; + } + str188 = string.Concat(", PARENTESCO: ", str187); + } + else + { + str188 = ""; + } + strArrays21[5] = str188; + str189 = (!string.IsNullOrWhiteSpace(maisContato.get_Banco()) || !string.IsNullOrWhiteSpace(maisContato.get_Agencia()) || !string.IsNullOrWhiteSpace(maisContato.get_Conta()) ? "
" : ""); + strArrays21[6] = str189; + str190 = (!string.IsNullOrWhiteSpace(maisContato.get_Banco()) ? string.Concat("BANCO: ", maisContato.get_Banco()) : ""); + strArrays21[7] = str190; + if (!string.IsNullOrWhiteSpace(maisContato.get_Agencia())) + { + str191 = (!string.IsNullOrWhiteSpace(maisContato.get_Banco()) ? ", AGÊNCIA: " : "AGÊNCIA: "); + str192 = string.Concat(str191, maisContato.get_Agencia()); + } + else + { + str192 = ""; + } + strArrays21[8] = str192; + if (!string.IsNullOrWhiteSpace(maisContato.get_Conta())) + { + str193 = (!string.IsNullOrWhiteSpace(maisContato.get_Banco()) || !string.IsNullOrWhiteSpace(maisContato.get_Agencia()) ? ", CONTA: " : "CONTA: "); + str194 = string.Concat(str193, maisContato.get_Conta()); + } + else + { + str194 = ""; + } + strArrays21[9] = str194; + nullable = maisContato.get_Tipo(); + str195 = (nullable.HasValue || !string.IsNullOrWhiteSpace(maisContato.get_Prefixo()) && !string.IsNullOrWhiteSpace(maisContato.get_Telefone()) || !string.IsNullOrWhiteSpace(maisContato.get_Email()) ? "
" : ""); + strArrays21[10] = str195; + nullable = maisContato.get_Tipo(); + if (nullable.HasValue) + { + nullable = maisContato.get_Tipo(); + if (nullable.HasValue) + { + tipoTelefone = nullable.GetValueOrDefault(); + str196 = tipoTelefone.ToString().ToUpper(); + } + else + { + str196 = null; + } + str197 = string.Concat("TIPO DO TELEFONE: ", str196); + } + else + { + str197 = ""; + } + strArrays21[11] = str197; + if (string.IsNullOrWhiteSpace(maisContato.get_Prefixo()) || string.IsNullOrWhiteSpace(maisContato.get_Telefone())) + { + str198 = ""; + } + else + { + nullable = maisContato.get_Tipo(); + str201 = (nullable.HasValue ? ", TELEFONE: (" : "TELEFONE: ("); + str198 = string.Concat(str201, maisContato.get_Prefixo(), ") ", maisContato.get_Telefone()); + } + strArrays21[12] = str198; + if (!string.IsNullOrWhiteSpace(maisContato.get_Email())) + { + nullable = maisContato.get_Tipo(); + str199 = (nullable.HasValue || !string.IsNullOrWhiteSpace(maisContato.get_Prefixo()) && !string.IsNullOrWhiteSpace(maisContato.get_Telefone()) ? ", EMAIL: " : "EMAIL: "); + str200 = string.Concat(str199, maisContato.get_Email()); + } + else + { + str200 = ""; + } + strArrays21[13] = str200; + strArrays21[14] = "
"; + str382 = string.Concat(strArrays21); + } + string[] strArrays22 = new string[] { str371, "
"; + str371 = string.Concat(strArrays22); + } + if (documento3.get_Controle().get_Cliente().get_Enderecos() != null && !this.ExtratoResumido) + { + string str383 = ""; + foreach (ClienteEndereco clienteEndereco2 in documento3.get_Controle().get_Cliente().get_Enderecos()) + { + string[] cep = new string[] { str383, "
", clienteEndereco2.get_Endereco(), ", ", clienteEndereco2.get_Numero(), ", ", null, null, null, null, null, null, null, null }; + str183 = (string.IsNullOrWhiteSpace(clienteEndereco2.get_Complemento()) ? "" : string.Concat(clienteEndereco2.get_Complemento(), ", ")); + cep[6] = str183; + cep[7] = clienteEndereco2.get_Bairro(); + cep[8] = " - "; + cep[9] = clienteEndereco2.get_Cidade(); + cep[10] = " - "; + cep[11] = clienteEndereco2.get_Estado(); + cep[12] = " - "; + cep[13] = clienteEndereco2.get_Cep(); + str383 = string.Concat(cep); + } + string[] strArrays23 = new string[] { str371, "
"; + str371 = string.Concat(strArrays23); + } + if (this.ObsCliente && this.ClienteVisibility && this.ObsClienteEnabled && !string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Observacao()) && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + documento3.get_Controle().get_Cliente().set_Observacao(string.Concat("
", documento3.get_Controle().get_Cliente().get_Observacao().Replace("\r\n", "
"))); + string[] strArrays24 = new string[] { str371, "
"; + str371 = string.Concat(strArrays24); + } + if (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Pasta()) && this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + string[] strArrays25 = new string[] { str371, ""; + str371 = string.Concat(strArrays25); + } + str371 = string.Concat(str371, "

FALECIDO: "; + str239 = (documento3.get_Controle().get_Cliente().get_Falecido() ? "SIM" : "NÃO"); + strArrays9[4] = str239; + strArrays9[5] = "

ESTADO CIVIL: ", null, null, null, null, null, null, null, null }; + if (documento3.get_Controle().get_Cliente().get_EstadoCivil().HasValue) + { + estadoCivil = documento3.get_Controle().get_Cliente().get_EstadoCivil(); + str233 = estadoCivil.ToString().ToUpper(); + } + else + { + str233 = "-"; + } + strArrays12[2] = str233; + strArrays12[3] = "

SEXO: "; + if (documento3.get_Controle().get_Cliente().get_Sexo().HasValue) + { + sexo = documento3.get_Controle().get_Cliente().get_Sexo(); + str235 = sexo.ToString().ToUpper(); + } + else + { + str235 = "-"; + } + strArrays12[6] = str235; + strArrays12[7] = "

"; + str371 = string.Concat(strArrays12); + } + string str377 = str371; + clienteDesde = documento3.get_Controle().get_Cliente().get_ClienteDesde(); + if (clienteDesde.HasValue) + { + clienteDesde = documento3.get_Controle().get_Cliente().get_ClienteDesde(); + if (clienteDesde.HasValue) + { + shortDateString13 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString13 = null; + } + } + else + { + shortDateString13 = "-"; + } + str371 = string.Concat(str377, "

CLIENTE DESDE: ", shortDateString13, "

PROFISSÃO: "; + strArrays13[4] = documento3.get_Controle().get_Cliente().get_Profissao().get_Nome(); + strArrays13[5] = "

HABILITAÇÃO: "; + str226 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Habilitacao()) ? documento3.get_Controle().get_Cliente().get_Habilitacao() : "-"); + strArrays14[4] = str226; + strArrays14[5] = "

CATEGORIA: "; + str228 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_CategoriaHabilitacao()) ? documento3.get_Controle().get_Cliente().get_CategoriaHabilitacao() : "-"); + strArrays14[8] = str228; + strArrays14[9] = "

1ª HAB.: "; + clienteDesde = documento3.get_Controle().get_Cliente().get_PrimeiraHabilitacao(); + if (clienteDesde.HasValue) + { + clienteDesde = documento3.get_Controle().get_Cliente().get_PrimeiraHabilitacao(); + if (clienteDesde.HasValue) + { + shortDateString11 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString11 = null; + } + } + else + { + shortDateString11 = "-"; + } + strArrays14[12] = shortDateString11; + strArrays14[13] = "

VENCIMENTO: "; + clienteDesde = documento3.get_Controle().get_Cliente().get_VencimentoHabilitacao(); + if (clienteDesde.HasValue) + { + clienteDesde = documento3.get_Controle().get_Cliente().get_VencimentoHabilitacao(); + if (clienteDesde.HasValue) + { + shortDateString12 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString12 = null; + } + } + else + { + shortDateString12 = "-"; + } + strArrays14[16] = shortDateString12; + strArrays14[17] = "

RG: "; + str219 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Identidade()) ? documento3.get_Controle().get_Cliente().get_Identidade() : "-"); + strArrays15[4] = str219; + strArrays15[5] = "

ORGÃO EMISSOR: "; + str221 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Emissor()) ? documento3.get_Controle().get_Cliente().get_Emissor() : "-"); + strArrays15[8] = str221; + strArrays15[9] = "

ESTADO EMISSOR: "; + str223 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_EstadoEmissor()) ? documento3.get_Controle().get_Cliente().get_EstadoEmissor() : "-"); + strArrays15[12] = str223; + strArrays15[13] = "

EXPEDIÇÃO: "; + clienteDesde = documento3.get_Controle().get_Cliente().get_Expedicao(); + if (clienteDesde.HasValue) + { + clienteDesde = documento3.get_Controle().get_Cliente().get_Expedicao(); + if (clienteDesde.HasValue) + { + shortDateString10 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString10 = null; + } + } + else + { + shortDateString10 = "-"; + } + strArrays15[16] = shortDateString10; + strArrays15[17] = "

BANCO: "; + str211 = (documento3.get_Controle().get_Cliente().get_Banco() != null ? documento3.get_Controle().get_Cliente().get_Banco().get_Nome() : "-"); + strArrays16[4] = str211; + strArrays16[5] = "

AGÊNCIA: "; + str213 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Agencia()) ? documento3.get_Controle().get_Cliente().get_Agencia() : "-"); + strArrays16[8] = str213; + strArrays16[9] = "

CONTA: "; + str215 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Conta()) ? documento3.get_Controle().get_Cliente().get_Conta() : "-"); + strArrays16[12] = str215; + strArrays16[13] = "

TIPO: "; + str217 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_TipoConta()) ? documento3.get_Controle().get_Cliente().get_TipoConta() : "-"); + strArrays16[16] = str217; + strArrays16[17] = "

CONTATOS: "; + strArrays17[4] = str378; + strArrays17[5] = "

EMAILS: "; + strArrays18[4] = str379; + strArrays18[5] = "

ENDEREÇOS: "; + strArrays19[4] = str380; + strArrays19[5] = "

ENDEREÇOS: "; + strArrays20[4] = str381; + strArrays20[5] = "

MAIS CONTATOS: "; + strArrays22[4] = str382; + strArrays22[5] = "

ENDEREÇOS: "; + strArrays23[4] = str383; + strArrays23[5] = "

OBSERVAÇÕES: "; + strArrays24[4] = documento3.get_Controle().get_Cliente().get_Observacao(); + strArrays24[5] = "

PASTA: "; + strArrays25[4] = documento3.get_Controle().get_Cliente().get_Pasta(); + strArrays25[5] = "

"); + if (!flag1) + { + string str384 = str371; + str180 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
"); + str371 = string.Concat(str384, str180); + } + } + else + { + string[] documento5 = new string[14]; + documento5[0] = str371; + documento5[1] = "

CLIENTE: "; + documento5[4] = documento3.get_Controle().get_Cliente().get_Nome(); + documento5[5] = "

RG: "; + str44 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Identidade()) ? documento3.get_Controle().get_Cliente().get_Identidade() : "-"); + documento5[8] = str44; + documento5[9] = "

CPF/CNPJ: "; + documento5[12] = documento3.get_Controle().get_Cliente().get_Documento(); + documento5[13] = "

"; + str371 = string.Concat(documento5); + } + if (this.SelectedTipoExtrato != null) + { + num10 = 0; + string[] shortDateString18 = new string[58]; + shortDateString18[0] = str371; + shortDateString18[1] = "
"; + str371 = string.Concat(shortDateString18); + if (!documento3.get_NegocioCorretora().HasValue) + { + Documento documento6 = documento3; + negocioCorretora = (documento3.get_Situacao() != 2 || !documento3.get_Negocio().HasValue || documento3.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + documento6.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora)); + } + if (this.ComissaoDocumento && this.ComissaoDocumentoEnabled) + { + if (this.SelectedTipoExtrato == 2) + { + string[] strArrays26 = new string[] { str371, ""; + str371 = string.Concat(strArrays26); + } + else + { + string[] description5 = new string[14]; + description5[0] = str371; + description5[1] = ""; + str371 = string.Concat(description5); + } + } + else if (this.SelectedTipoExtrato != 2) + { + string[] description6 = new string[] { str371, ""; + str371 = string.Concat(description6); + } + string[] strArrays27 = new string[14]; + strArrays27[0] = str371; + strArrays27[1] = ""; + str371 = string.Concat(strArrays27); + if (this.SelectedTipoExtrato != 2 && !this.ExtratoResumido) + { + str371 = string.Concat(str371, ""); + string str385 = ""; + if (documento3.get_Estipulante1() != null) + { + str385 = string.Concat(str385, documento3.get_Estipulante1().get_Nome(), ", "); + } + if (documento3.get_Estipulante2() != null) + { + str385 = string.Concat(str385, documento3.get_Estipulante2().get_Nome(), ", "); + } + if (documento3.get_Estipulante3() != null) + { + str385 = string.Concat(str385, documento3.get_Estipulante3().get_Nome(), ", "); + } + if (documento3.get_Estipulante4() != null) + { + str385 = string.Concat(str385, documento3.get_Estipulante4().get_Nome(), ", "); + } + if (documento3.get_Estipulante5() != null) + { + str385 = string.Concat(str385, documento3.get_Estipulante5().get_Nome(), ", "); + } + if (!string.IsNullOrWhiteSpace(str385)) + { + int num13 = str385.LastIndexOf(", ", StringComparison.Ordinal); + str385 = str385.Remove(num13, 2).Insert(num13, "."); + } + string[] strArrays28 = new string[] { str371, ""; + str371 = string.Concat(strArrays28); + } + if (this.SelectedTipoExtrato == 2) + { + string[] strArrays29 = new string[] { str371, ""; + str371 = string.Concat(strArrays29); + } + else + { + string[] strArrays30 = new string[] { str371, ""; + str371 = string.Concat(strArrays30); + if (documento3.get_Controle().get_SeguradoraAnterior() != null && !this.ExtratoResumido) + { + string[] strArrays31 = new string[] { str371, ""; + str371 = string.Concat(strArrays31); + } + } + str371 = string.Concat(str371, "

RAMO: "; + shortDateString18[4] = documento3.get_Controle().get_Ramo().get_Nome(); + shortDateString18[5] = "

VIGÊNCIA INICIAL: "; + date = documento3.get_Vigencia1(); + shortDateString18[8] = date.ToShortDateString(); + shortDateString18[9] = "

VIGÊNCIA FINAL: "; + clienteDesde = documento3.get_Vigencia2(); + if (!clienteDesde.HasValue) + { + shortDateString3 = "-"; + } + else + { + clienteDesde = documento3.get_Vigencia2(); + if (clienteDesde.HasValue) + { + shortDateString3 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString3 = null; + } + } + shortDateString18[12] = shortDateString3; + shortDateString18[13] = "

CONTRATO: "; + str50 = (string.IsNullOrWhiteSpace(documento3.get_Apolice()) ? "-" : documento3.get_Apolice()); + shortDateString18[16] = str50; + shortDateString18[17] = "

POSSUI ENDOSSO? "; + str52 = (documento3.get_TemEndosso() ? "SIM" : "NÃO"); + shortDateString18[20] = str52; + shortDateString18[21] = "

ADITAMENTO: "; + if (string.IsNullOrWhiteSpace(documento3.get_Endosso())) + { + if (flag) + { + IList documentos = documento3.get_Controle().get_Documentos(); + if (documentos.Where((Documento x) => { + if (x.get_Excluido()) + { + return false; + } + return x.get_Ordem() != 0; + }).ToList().Count <= 0) + { + goto Label2; + } + IList documentos1 = documento3.get_Controle().get_Documentos(); + endosso = documentos1.Last((Documento x) => { + if (x.get_Excluido()) + { + return false; + } + return x.get_Ordem() != 0; + }).get_Endosso(); + goto Label1; + } + Label2: + endosso = "-"; + } + else + { + endosso = documento3.get_Endosso(); + } + Label1: + shortDateString18[24] = endosso; + shortDateString18[25] = "

APÓLICE ANTERIOR: "; + str55 = (string.IsNullOrWhiteSpace(documento3.get_ApoliceAnterior()) ? "-" : documento3.get_ApoliceAnterior()); + shortDateString18[28] = str55; + shortDateString18[29] = "

BANCO: "; + str57 = (documento3.get_Banco() == null ? "-" : documento3.get_Banco().get_Nome()); + shortDateString18[32] = str57; + shortDateString18[33] = "

AGÊNCIA: "; + str59 = (string.IsNullOrWhiteSpace(documento3.get_Agencia()) ? "-" : documento3.get_Agencia()); + shortDateString18[36] = str59; + shortDateString18[37] = "

CONTA: "; + str61 = (string.IsNullOrWhiteSpace(documento3.get_Conta()) ? "-" : documento3.get_Conta()); + shortDateString18[40] = str61; + shortDateString18[41] = "

NUMERO CARTÃO: "; + str63 = (string.IsNullOrWhiteSpace(documento3.get_NumeroCartao()) ? "-" : documento3.get_NumeroCartao()); + shortDateString18[44] = str63; + shortDateString18[45] = "

VENCIMENTO: "; + str65 = (string.IsNullOrWhiteSpace(documento3.get_VencimentoCartao()) ? "-" : documento3.get_VencimentoCartao()); + shortDateString18[48] = str65; + shortDateString18[49] = "

BANDEIRA: "; + str67 = (!documento3.get_Bandeira().HasValue ? "-" : ValidationHelper.GetDescription(documento3.get_Bandeira())); + shortDateString18[52] = str67; + shortDateString18[53] = "

TITULAR/PROPONENTE: "; + str69 = (string.IsNullOrWhiteSpace(documento3.get_NomeProponente()) ? "-" : documento3.get_NomeProponente()); + shortDateString18[56] = str69; + shortDateString18[57] = "

COMISSÃO: "; + strArrays26[4] = string.Format("{0}%", documento3.get_Comissao()); + strArrays26[5] = "

NEGÓCIO CORRETORA: "; + description5[4] = ValidationHelper.GetDescription(documento3.get_NegocioCorretora()); + description5[5] = "

STATUS DO SEGURO: "; + description5[8] = ValidationHelper.GetDescription(documento3.get_Situacao()); + description5[9] = "

COMISSÃO: "; + description5[12] = string.Format("{0}%", documento3.get_Comissao()); + description5[13] = "

NEGÓCIO CORRETORA: "; + description6[4] = ValidationHelper.GetDescription(documento3.get_NegocioCorretora()); + description6[5] = "

STATUS DO SEGURO: "; + description6[8] = ValidationHelper.GetDescription(documento3.get_Situacao()); + description6[9] = "

VENDEDOR: "; + str71 = (documento3.get_VendedorPrincipal() == null ? "-" : documento3.get_VendedorPrincipal().get_Nome()); + strArrays27[4] = str71; + strArrays27[5] = "

REMESSA: "; + clienteDesde = documento3.get_Remessa(); + if (!clienteDesde.HasValue) + { + shortDateString4 = "-"; + } + else + { + clienteDesde = documento3.get_Remessa(); + if (clienteDesde.HasValue) + { + shortDateString4 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString4 = null; + } + } + strArrays27[8] = shortDateString4; + strArrays27[9] = "

EMISSÃO: "; + clienteDesde = documento3.get_Emissao(); + if (!clienteDesde.HasValue) + { + shortDateString5 = "-"; + } + else + { + clienteDesde = documento3.get_Emissao(); + if (clienteDesde.HasValue) + { + shortDateString5 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString5 = null; + } + } + strArrays27[12] = shortDateString5; + strArrays27[13] = "

ESTIPULANTE(S): "; + str169 = (string.IsNullOrWhiteSpace(str385) ? "-" : str385); + strArrays28[4] = str169; + strArrays28[5] = "

SEGURADORA: "; + strArrays29[4] = documento3.get_Controle().get_Seguradora().get_Nome(); + strArrays29[5] = "

SEGURADORA: "; + strArrays30[4] = documento3.get_Controle().get_Seguradora().get_Nome(); + strArrays30[5] = "

APÓLICE SINISTRADA: "; + str166 = (documento3.get_Sinistro() ? "SIM" : "NÃO"); + strArrays30[8] = str166; + strArrays30[9] = "

SEGURADORA ANTERIOR: "; + strArrays31[4] = documento3.get_Controle().get_SeguradoraAnterior().get_Nome(); + strArrays31[5] = "

"); + if (!this.ExtratoResumido && (this.PremioParcela || this.ObsApoliceEnabled)) + { + str371 = string.Concat(str371, ""); + if (this.PremioParcela) + { + string[] strArrays32 = new string[24]; + strArrays32[0] = str371; + strArrays32[1] = "

PRÊMIO LÍQUIDO:
"; + premioLiquido = documento3.get_PremioLiquido(); + strArrays32[4] = premioLiquido.ToString("c"); + strArrays32[5] = "

ADICIONAL:
"; + premioLiquido = documento3.get_PremioAdicional(); + strArrays32[8] = premioLiquido.ToString("c"); + strArrays32[9] = "

CUSTO APÓLICE:
"; + premioLiquido = documento3.get_Custo(); + strArrays32[12] = premioLiquido.ToString("c"); + strArrays32[13] = "

I.O.F.:
"; + premioLiquido = documento3.get_Iof(); + strArrays32[16] = premioLiquido.ToString("c"); + strArrays32[17] = "

"); + str371 = string.Concat(str371, "

"); + ObservableCollection parcelas = documento3.get_Parcelas(); + if (parcelas != null) + { + count = parcelas.Count > 0; + } + else + { + count = false; + } + if (count) + { + str371 = string.Concat(str371, ""); + foreach (Parcela parcela in documento3.get_Parcelas()) + { + string[] description7 = new string[] { str371, ""; + str371 = string.Concat(description7); + } + } + } + if (this.ObsApolice && this.ObsApoliceEnabled) + { + string[] strArrays33 = new string[] { str371, ""; + str371 = string.Concat(strArrays33); + } + str371 = string.Concat(str371, "

PARCELA

VENCIMENTO

VALOR

FORMA DE PAGAMENTO

", null, null, null, null, null, null, null, null }; + numeroParcela = parcela.get_NumeroParcela(); + description7[2] = numeroParcela.ToString(); + description7[3] = "

"; + date = parcela.get_Vencimento(); + description7[4] = date.ToShortDateString(); + description7[5] = "

"; + description7[6] = string.Format("{0:c}", parcela.get_Valor()); + description7[7] = "

"; + description7[8] = ValidationHelper.GetDescription(documento3.get_FormaPagamento()); + description7[9] = "

OBSERVAÇÕES: "; + str157 = (string.IsNullOrWhiteSpace(documento3.get_Observacao()) ? "-" : documento3.get_Observacao()); + strArrays33[4] = str157; + strArrays33[5] = "

"); + } + if (this.PerfilCondutor && this.PerfilVisibility && documento3.get_Controle().get_Ramo().get_Id() == (long)5 && this.PerfilCondutorEnabled) + { + List list1 = perfils.ToList(); + foreach (Perfil perfil in list1) + { + num10 = 0; + if (string.IsNullOrEmpty(perfil.get_Nome())) + { + continue; + } + string[] description8 = new string[92]; + description8[0] = str371; + description8[1] = "

"; + description8[4] = string.Format("CONDUTOR {0}: ", list1.IndexOf(perfil) + 1); + description8[5] = ""; + description8[6] = perfil.get_Nome(); + description8[7] = "

CPF: "; + str117 = (string.IsNullOrWhiteSpace(perfil.get_Cpf()) ? "-" : perfil.get_Cpf()); + description8[10] = str117; + description8[11] = "

NASCIMENTO: "; + clienteDesde = perfil.get_Nascimento(); + if (!clienteDesde.HasValue) + { + shortDateString7 = "-"; + } + else + { + clienteDesde = perfil.get_Nascimento(); + if (clienteDesde.HasValue) + { + shortDateString7 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString7 = null; + } + } + description8[14] = shortDateString7; + description8[15] = "

ESTADO CIVIL: "; + str120 = (!perfil.get_EstadoCivil().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_EstadoCivil())); + description8[18] = str120; + description8[19] = "

SEXO: "; + str122 = (!perfil.get_Sexo().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_Sexo())); + description8[22] = str122; + description8[23] = "

RELAÇÃO SEGURADO/CONDUTOR: "; + description8[26] = ValidationHelper.GetDescription(perfil.get_Relacao()); + description8[27] = "

HABILITAÇÃO: "; + str125 = (string.IsNullOrWhiteSpace(perfil.get_Habilitacao()) ? "-" : perfil.get_Habilitacao()); + description8[30] = str125; + description8[31] = "

TEMPO DE HABILITAÇÃO: "; + str127 = (!perfil.get_TempoHabilitacao().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_TempoHabilitacao())); + description8[34] = str127; + description8[35] = "

QUATIDADE DE VEÍCULOS: "; + if (!perfil.get_VeiculoResidencia().HasValue) + { + str129 = "-"; + } + else + { + numeroParcela = perfil.get_VeiculoResidencia().Value; + str129 = numeroParcela.ToString(); + } + description8[38] = str129; + description8[39] = "

GARAGEM NA RESIDÊNCIA: "; + str131 = (!perfil.get_GaragemResidencia().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_GaragemResidencia())); + description8[42] = str131; + description8[43] = "

GARAGEM NO TRABALHO: "; + str133 = (!perfil.get_GaragemTrabalho().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_GaragemTrabalho())); + description8[46] = str133; + description8[47] = "

GARAGEM NO ESTUDO: "; + str135 = (!perfil.get_GaragemEstudo().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_GaragemEstudo())); + description8[50] = str135; + description8[51] = "

TIPO DE RESIDÊNCIA: "; + str137 = (!perfil.get_TipoResidencia().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_TipoResidencia())); + description8[54] = str137; + description8[55] = "

QUILOMETRAGEM MENSAL: "; + str139 = (string.IsNullOrWhiteSpace(perfil.get_KmMensal()) ? "-" : perfil.get_KmMensal()); + description8[58] = str139; + description8[59] = "

DISTÂNCIA ATÉ O TRABALHO: "; + str141 = (!perfil.get_DistanciaResidenciaTrabalho().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_DistanciaResidenciaTrabalho())); + description8[62] = str141; + description8[63] = "

USO PROFISSIONAL: "; + str143 = (!perfil.get_UsoProfissional().HasValue || !perfil.get_UsoProfissional().Value ? "NÃO" : "SIM"); + description8[66] = str143; + description8[67] = "

USO POR DEPENDENTES: "; + str145 = (!perfil.get_UsoDependentes().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_UsoDependentes())); + description8[70] = str145; + description8[71] = "

OCUPAÇÃO: "; + str147 = (!perfil.get_Ocupacao().HasValue ? "-" : ValidationHelper.GetDescription(perfil.get_Ocupacao())); + description8[74] = str147; + description8[75] = "

SEGURO VIDA: "; + str149 = (!perfil.get_SeguroVida().HasValue || !perfil.get_SeguroVida().Value ? "NÃO" : "SIM"); + description8[78] = str149; + description8[79] = "

ISENÇÃO DE IMPOSTOS: "; + str151 = (!perfil.get_Isencao().HasValue || !perfil.get_Isencao().Value ? "NÃO" : "SIM"); + description8[82] = str151; + description8[83] = "

ANTIFURTO: "; + str153 = (perfil.get_AntiFurto().HasValue ? ValidationHelper.GetDescription(perfil.get_AntiFurto()) : ""); + description8[86] = str153; + description8[87] = "

COBERTURA ESTENDIDA PARA RESIDENTES HABILITADOS: "; + str155 = (!perfil.get_EstenderCobertura().HasValue || !perfil.get_EstenderCobertura().Value ? "NÃO" : "SIM"); + description8[90] = str155; + description8[91] = "

"; + str371 = string.Concat(description8); + } + } + list = items1.ToList(); + if (list.Count != 0) + { + num10 = 0; + foreach (Item item in list) + { + if (item.get_Sinistros().Count > 0) + { + item1 = item; + controleSinistros = await (new SinistroServico()).BuscarControles(item.get_Id()); + item1.set_Sinistros(controleSinistros); + item1 = null; + } + string str386 = str371; + str75 = (!this.SepararPagina || !this.SepararPaginaEnabled ? "" : "
"); + str371 = string.Concat(str386, str75); + string str387 = str371; + str76 = (this.SelectedTipoExtrato != 2 || list.IndexOf(item) == 0 ? "
" : ""); + str371 = string.Concat(str387, str76); + str371 = string.Concat(str371, ""); + str371 = string.Concat(str371, ""); + str371 = string.Concat(str371, ""); + if (this.SelectedTipoExtrato != 2) + { + id = documento3.get_Controle().get_Ramo().get_Id(); + if (id > (long)5) + { + if (id == (long)15 || id == (long)18) + { + goto Label5; + } + if (id == (long)37) + { + goto Label3; + } + goto Label4; + } + else + { + if (id - (long)1 <= (long)2) + { + goto Label5; + } + if (id == (long)5) + { + goto Label3; + } + goto Label4; + } + Label5: + item1 = item; + patrimonial = await (new ItemServico()).BuscaPatrimonial(item.get_Id()); + item1.set_Patrimonial(patrimonial); + item1 = null; + string[] numero1 = new string[19]; + numero1[0] = str371; + numero1[1] = ""; + str371 = string.Concat(numero1); + } + else + { + string[] descricao2 = new string[] { str371, ""; + str371 = string.Concat(descricao2); + } + Label9: + if (item.get_Sinistros().Count > 0) + { + Item item2 = item; + if (item2 != null) + { + IList sinistros = item2.get_Sinistros(); + if (sinistros != null) + { + ControleSinistro controleSinistro = sinistros.LastOrDefault(); + if (controleSinistro != null) + { + List sinistros1 = controleSinistro.get_Sinistros(); + if (sinistros1 != null) + { + Sinistro sinistro = sinistros1.LastOrDefault(); + if (sinistro != null) + { + dataReclamacao = sinistro.get_DataReclamacao(); + } + else + { + clienteDesde = null; + dataReclamacao = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao = clienteDesde; + } + DateTime? nullable3 = dataReclamacao; + if (nullable3.HasValue) + { + date = nullable3.Value; + shortDateString6 = date.ToShortDateString(); + } + else + { + shortDateString6 = "-"; + } + string str388 = shortDateString6; + string[] strArrays34 = new string[18]; + strArrays34[0] = str371; + strArrays34[1] = ""; + str371 = string.Concat(strArrays34); + } + str371 = string.Concat(str371, ""); + if (this.SelectedTipoExtrato != 2) + { + string[] strArrays35 = new string[] { str371, ""; + str371 = string.Concat(strArrays35); + id = documento3.get_Controle().get_Ramo().get_Id(); + long num14 = id - (long)1; + if (num14 <= (long)58) + { + switch ((uint)num14) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays36 = new string[] { str371, ""; + str371 = string.Concat(strArrays36); + break; + } + case 3: + case 7: + case 15: + case 16: + case 18: + case 22: + case 23: + case 25: + case 27: + case 30: + case 32: + case 38: + case 40: + case 43: + case 48: + case 58: + { + item1 = item; + riscosDiverso = await (new ItemServico()).BuscaRiscosDiversos(item.get_Id()); + item1.set_RiscosDiversos(riscosDiverso); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays37 = new string[] { str371, ""; + str371 = string.Concat(strArrays37); + break; + } + case 4: + case 36: + { + if (this.ObsItem && this.ObsItemEnabled) + { + string[] strArrays38 = new string[] { str371, ""; + str371 = string.Concat(strArrays38); + } + string[] strArrays39 = new string[30]; + strArrays39[0] = str371; + strArrays39[1] = ""; + str371 = string.Concat(strArrays39); + break; + } + case 5: + case 6: + case 8: + case 9: + case 52: + { + item1 = item; + vida = await (new ItemServico()).BuscaVida(item.get_Id()); + item1.set_Vida(vida); + item1 = null; + if (!item.get_Sinistrado() || !this.BeneficiariosItens || !this.BeneficiariosItensEnabled) + { + break; + } + string str389 = str371; + str102 = (num10 % 2 == 0 ? "WhiteSmoke" : "White"); + str371 = string.Concat(str389, ""); + break; + } + case 12: + { + item1 = item; + aeronautico = await (new ItemServico()).BuscaAeronautico(item.get_Id()); + item1.set_Aeronautico(aeronautico); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays40 = new string[] { str371, ""; + str371 = string.Concat(strArrays40); + break; + } + case 19: + { + item1 = item; + granizo = await (new ItemServico()).BuscaGranizo(item.get_Id()); + item1.set_Granizo(granizo); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays41 = new string[] { str371, ""; + str371 = string.Concat(strArrays41); + break; + } + } + } + else + { + } + } + str371 = string.Concat(str371, "

"; + numero1[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + numero1[5] = ""; + numero1[6] = item.get_Patrimonial().get_Endereco(); + numero1[7] = ", "; + numero1[8] = item.get_Patrimonial().get_Numero(); + numero1[9] = ", "; + str78 = (string.IsNullOrWhiteSpace(item.get_Patrimonial().get_Complemento()) ? "" : string.Concat(item.get_Patrimonial().get_Complemento(), ", ")); + numero1[10] = str78; + numero1[11] = item.get_Patrimonial().get_Bairro(); + numero1[12] = " - "; + numero1[13] = item.get_Patrimonial().get_Cidade(); + numero1[14] = " - "; + numero1[15] = item.get_Patrimonial().get_Estado(); + numero1[16] = " - "; + numero1[17] = item.get_Patrimonial().get_Cep(); + numero1[18] = "

"; + descricao2[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + descricao2[5] = ""; + descricao2[6] = item.get_Descricao(); + descricao2[7] = "

SINISTRO STATUS: "; + Item item3 = item; + if (item3 != null) + { + IList controleSinistros1 = item3.get_Sinistros(); + if (controleSinistros1 != null) + { + ControleSinistro controleSinistro1 = controleSinistros1.LastOrDefault(); + if (controleSinistro1 != null) + { + List sinistros2 = controleSinistro1.get_Sinistros(); + if (sinistros2 != null) + { + Sinistro sinistro1 = sinistros2.LastOrDefault(); + if (sinistro1 != null) + { + description2 = ValidationHelper.GetDescription(sinistro1.get_StatusSinistro()); + } + else + { + description2 = null; + } + } + else + { + description2 = null; + } + } + else + { + description2 = null; + } + } + else + { + description2 = null; + } + } + else + { + description2 = null; + } + strArrays34[4] = description2; + strArrays34[5] = "

DATA: "; + strArrays34[8] = str388; + strArrays34[9] = "

VALOR: "; + Item item4 = item; + if (item4 != null) + { + IList controleSinistros2 = item4.get_Sinistros(); + if (controleSinistros2 != null) + { + ControleSinistro controleSinistro2 = controleSinistros2.LastOrDefault(); + if (controleSinistro2 != null) + { + List sinistros3 = controleSinistro2.get_Sinistros(); + if (sinistros3 != null) + { + Sinistro sinistro2 = sinistros3.LastOrDefault(); + if (sinistro2 != null) + { + currency = ValidationHelper.ToCurrency(sinistro2.get_Valor(), "pt-BR"); + } + else + { + currency = null; + } + } + else + { + currency = null; + } + } + else + { + currency = null; + } + } + else + { + currency = null; + } + } + else + { + currency = null; + } + strArrays34[12] = currency; + strArrays34[13] = "

QTDE SINISTRO(S): "; + numeroParcela = item.get_Sinistros().Count; + strArrays34[16] = numeroParcela.ToString(); + strArrays34[17] = "

STATUS: "; + str81 = (string.IsNullOrWhiteSpace(item.get_Status()) ? item.get_StatusInclusao() : item.get_Status()); + strArrays35[4] = str81; + strArrays35[5] = "

ATIVO: "; + str83 = (!item.get_Substituido().HasValue ? "SIM" : "NÃO"); + strArrays35[8] = str83; + strArrays35[9] = "

OBSERVAÇÕES: "; + str85 = (string.IsNullOrWhiteSpace(item.get_Patrimonial().get_Item().get_Observacao()) ? "-" : item.get_Patrimonial().get_Item().get_Observacao()); + strArrays36[4] = str85; + strArrays36[5] = "

BENS E INFORMAÇÕES: "; + str87 = (string.IsNullOrWhiteSpace(item.get_Patrimonial().get_Bens()) ? "-" : item.get_Patrimonial().get_Bens()); + strArrays36[8] = str87; + strArrays36[9] = "

OBSERVAÇÕES: "; + str89 = (string.IsNullOrWhiteSpace(item.get_RiscosDiversos().get_Observacao()) ? "-" : item.get_RiscosDiversos().get_Observacao()); + strArrays37[4] = str89; + strArrays37[5] = "

OBSERVAÇÕES: "; + str101 = (string.IsNullOrWhiteSpace(item.get_Auto().get_Observacao()) ? "-" : item.get_Auto().get_Observacao()); + strArrays38[4] = str101; + strArrays38[5] = "

COBERTURA PADRÃO: "; + tipoCobertura = item.get_Auto().get_TipoCobertura(); + if (tipoCobertura.HasValue) + { + description = ValidationHelper.GetDescription(tipoCobertura.GetValueOrDefault()); + } + else + { + description = null; + } + strArrays39[4] = description; + strArrays39[5] = "

BÔNUS: "; + bonus = item.get_Auto().get_Bonus(); + strArrays39[8] = bonus.ToString(); + strArrays39[9] = "

REGIÃO DE CIRCULAÇÃO: "; + str93 = (string.IsNullOrWhiteSpace(item.get_Auto().get_RegiaoCirculacao()) ? "-" : item.get_Auto().get_RegiaoCirculacao()); + strArrays39[12] = str93; + strArrays39[13] = "

TABELA DE REFERÊNCIA: "; + tabelaReferencia = item.get_Auto().get_TabelaReferencia(); + if (tabelaReferencia.HasValue) + { + description1 = ValidationHelper.GetDescription(tabelaReferencia.GetValueOrDefault()); + } + else + { + description1 = null; + } + strArrays39[16] = description1; + strArrays39[17] = "

% DE REFERÊNCIA: "; + strArrays39[20] = string.Format("{0}%", item.get_Auto().get_PorcentagemReferencia()); + strArrays39[21] = "

CÓDIGO FIPE: "; + str97 = (string.IsNullOrWhiteSpace(item.get_Auto().get_Fipe()) ? "-" : item.get_Auto().get_Fipe()); + strArrays39[24] = str97; + strArrays39[25] = "

COR DO VEÍCULO: "; + str99 = (!item.get_Auto().get_Cor().HasValue ? "-" : ValidationHelper.GetDescription(item.get_Auto().get_Cor())); + strArrays39[28] = str99; + strArrays39[29] = "

BENEFICIÁRIOS: "); + string str390 = ""; + foreach (ControleSinistro sinistro3 in item.get_Sinistros()) + { + if (sinistro3.get_Sinistros() == null) + { + continue; + } + foreach (Sinistro sinistro4 in sinistro3.get_Sinistros()) + { + if (string.IsNullOrWhiteSpace(sinistro4.get_SinistroVida().get_Beneficiario())) + { + continue; + } + str390 = string.Concat(str390, sinistro4.get_SinistroVida().get_Beneficiario(), ", "); + } + } + if (!string.IsNullOrWhiteSpace(str390)) + { + int num15 = str390.LastIndexOf(", ", StringComparison.Ordinal); + str390 = str390.Remove(num15, 2).Insert(num15, "."); + } + str371 = string.Concat(str371, str390, "

OBSERVAÇÕES: "; + str104 = (string.IsNullOrWhiteSpace(item.get_Aeronautico().get_Observacao()) ? "-" : item.get_Aeronautico().get_Observacao()); + strArrays40[4] = str104; + strArrays40[5] = "

OBSERVAÇÕES: "; + str106 = (string.IsNullOrWhiteSpace(item.get_Granizo().get_Observacao()) ? "-" : item.get_Granizo().get_Observacao()); + strArrays41[4] = str106; + strArrays41[5] = "

"); + if (this.SelectedTipoExtrato != 2) + { + ObservableCollection observableCollection5 = await (new ItemServico()).BuscarCoberturasPorItemAsync(item.get_Id()); + if (observableCollection5.Count > 0 && this.Coberturas) + { + str371 = string.Concat(str371, "
"); + foreach (Cobertura cobertura in observableCollection5) + { + string[] strArrays42 = new string[] { str371, "" }; + str371 = string.Concat(strArrays42); + } + str371 = string.Concat(str371, "

COBERTURA

FRANQUIA

L.M.I.

PRÊMIO

", cobertura.get_Observacao(), "

", string.Format("{0:c}", cobertura.get_Franquia()), "

", string.Format("{0:c}", cobertura.get_Lmi()), "

", string.Format("{0:c}", cobertura.get_Premio()), "

"); + } + string str391 = str371; + str79 = (!this.SepararPagina || !this.SepararPaginaEnabled ? "" : "
"); + str371 = string.Concat(str391, str79); + } + if (this.SelectedTipoExtrato != 2) + { + num10 = 0; + } + } + } + else + { + str371 = string.Concat(str371, "

ESTA APÓLICE NÃO POSSUI ITENS

"); + } + list = null; + } + else + { + variable9 = null; + return; + } + } + else + { + bool flag3 = documento3.get_Controle().get_Cliente().get_PessoaFisica(); + if ((!this.Endossos || !this.SomenteEndossos) && !nums.Any((long x) => x == this.documento.get_Controle().get_Id())) + { + string[] strArrays43 = new string[] { str371, ""; + str371 = string.Concat(strArrays44); + } + string[] documento7 = new string[] { str371, ""; + str371 = string.Concat(documento7); + if (this.SelectedTipoExtrato != 2) + { + str351 = (documento3.get_Controle().get_Cliente().get_Atividade() == null ? "NASCIMENTO" : "ABERTURA"); + string str392 = str351; + string[] strArrays45 = new string[] { str371, ""; + str371 = string.Concat(strArrays46); + } + } + if (this.SelectedTipoExtrato != 2) + { + string[] strArrays47 = new string[18]; + strArrays47[0] = str371; + strArrays47[1] = ""; + str371 = string.Concat(strArrays47); + } + if (this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + string str393 = ""; + if (documento3.get_Controle().get_Cliente().get_Telefones() != null) + { + foreach (ClienteTelefone clienteTelefone1 in documento3.get_Controle().get_Cliente().get_Telefones()) + { + string[] numero2 = new string[] { str393, "
", null, null, null, null, null }; + nullable = clienteTelefone1.get_Tipo(); + if (nullable.HasValue) + { + tipoTelefone = nullable.GetValueOrDefault(); + str342 = tipoTelefone.ToString().ToUpper(); + } + else + { + str342 = null; + } + numero2[2] = str342; + numero2[3] = " ("; + numero2[4] = clienteTelefone1.get_Prefixo(); + numero2[5] = ") "; + numero2[6] = clienteTelefone1.get_Numero(); + str393 = string.Concat(numero2); + } + } + string[] strArrays48 = new string[] { str371, "
"; + str371 = string.Concat(strArrays48); + string str394 = ""; + if (documento3.get_Controle().get_Cliente().get_Emails() != null) + { + foreach (ClienteEmail clienteEmail1 in documento3.get_Controle().get_Cliente().get_Emails()) + { + str394 = string.Concat(str394, "
", clienteEmail1.get_Email()); + } + } + string[] strArrays49 = new string[] { str371, "
"; + str371 = string.Concat(strArrays49); + string str395 = ""; + if (documento3.get_Controle().get_Cliente().get_Enderecos() != null) + { + foreach (ClienteEndereco clienteEndereco3 in documento3.get_Controle().get_Cliente().get_Enderecos()) + { + string[] cidade1 = new string[] { str395, "
", clienteEndereco3.get_Endereco(), ", ", clienteEndereco3.get_Numero(), ", ", null, null, null, null, null, null, null, null }; + str341 = (string.IsNullOrWhiteSpace(clienteEndereco3.get_Complemento()) ? "" : string.Concat(clienteEndereco3.get_Complemento(), ", ")); + cidade1[6] = str341; + cidade1[7] = clienteEndereco3.get_Bairro(); + cidade1[8] = " - "; + cidade1[9] = clienteEndereco3.get_Cidade(); + cidade1[10] = " - "; + cidade1[11] = clienteEndereco3.get_Estado(); + cidade1[12] = " - "; + cidade1[13] = clienteEndereco3.get_Cep(); + str395 = string.Concat(cidade1); + } + } + string[] strArrays50 = new string[] { str371, "
"; + str371 = string.Concat(strArrays50); + str371 = string.Concat(str371, ""); + } + str371 = string.Concat(str371, "

RG: "; + str358 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Identidade()) ? documento3.get_Controle().get_Cliente().get_Identidade() : "-"); + strArrays44[4] = str358; + strArrays44[5] = "

CPF/CNPJ: "; + documento7[4] = documento3.get_Controle().get_Cliente().get_Documento(); + documento7[5] = "

ESTADO CIVIL: "; + if (documento3.get_Controle().get_Cliente().get_EstadoCivil().HasValue) + { + estadoCivil = documento3.get_Controle().get_Cliente().get_EstadoCivil(); + str354 = estadoCivil.ToString().ToUpper(); + } + else + { + str354 = "-"; + } + strArrays46[4] = str354; + strArrays46[5] = "

SEXO: "; + if (documento3.get_Controle().get_Cliente().get_Sexo().HasValue) + { + sexo = documento3.get_Controle().get_Cliente().get_Sexo(); + str356 = sexo.ToString().ToUpper(); + } + else + { + str356 = "-"; + } + strArrays46[8] = str356; + strArrays46[9] = "

BANCO: "; + str344 = (documento3.get_Controle().get_Cliente().get_Banco() != null ? documento3.get_Controle().get_Cliente().get_Banco().get_Nome() : "-"); + strArrays47[4] = str344; + strArrays47[5] = "

AGÊNCIA: "; + str346 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Agencia()) ? documento3.get_Controle().get_Cliente().get_Agencia() : "-"); + strArrays47[8] = str346; + strArrays47[9] = "

CONTA: "; + str348 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Conta()) ? documento3.get_Controle().get_Cliente().get_Conta() : "-"); + strArrays47[12] = str348; + strArrays47[13] = "

TIPO: "; + str350 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_TipoConta()) ? documento3.get_Controle().get_Cliente().get_TipoConta() : "-"); + strArrays47[16] = str350; + strArrays47[17] = "

CONTATOS: "; + str336 = (string.IsNullOrEmpty(str393) ? "-" : str393); + strArrays48[4] = str336; + strArrays48[5] = "

EMAILS: "; + str338 = (string.IsNullOrEmpty(str394) ? "-" : str394); + strArrays49[4] = str338; + strArrays49[5] = "

ENDEREÇOS: "; + str340 = (string.IsNullOrEmpty(str395) ? "-" : str395); + strArrays50[4] = str340; + strArrays50[5] = "

"); + string str396 = str371; + str334 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
"); + str371 = string.Concat(str396, str334); + } + else + { + string[] documento8 = new string[14]; + documento8[0] = str371; + documento8[1] = "

CLIENTE: "; + documento8[4] = documento3.get_Controle().get_Cliente().get_Nome(); + documento8[5] = "

RG: "; + str242 = (!string.IsNullOrWhiteSpace(documento3.get_Controle().get_Cliente().get_Identidade()) ? documento3.get_Controle().get_Cliente().get_Identidade() : "-"); + documento8[8] = str242; + documento8[9] = "

CPF/CNPJ: "; + documento8[12] = documento3.get_Controle().get_Cliente().get_Documento(); + documento8[13] = "

"; + str371 = string.Concat(documento8); + } + if (this.SelectedTipoExtrato != null) + { + num10 = 0; + IList documentos2 = documento3.get_Controle().get_Documentos(); + if (documentos2 != null) + { + documento = documentos2.LastOrDefault((Documento x) => { + if (x.get_Excluido()) + { + return false; + } + return x.get_Ordem() != 0; + }); + } + else + { + documento = null; + } + Documento documento9 = documento; + string[] shortDateString19 = new string[26]; + shortDateString19[0] = str371; + shortDateString19[1] = "
"; + str371 = string.Concat(shortDateString19); + if (!documento3.get_NegocioCorretora().HasValue) + { + Documento documento10 = documento3; + negocioCorretora1 = (documento3.get_Situacao() != 2 || !documento3.get_Negocio().HasValue || documento3.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + documento10.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora1)); + } + if (this.SelectedTipoExtrato != 2) + { + string[] description9 = new string[] { str371, ""; + str371 = string.Concat(description9); + } + string[] strArrays51 = new string[] { str371, ""; + str371 = string.Concat(strArrays51); + if (this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + string str397 = ""; + if (documento3.get_Estipulante1() != null) + { + str397 = string.Concat(str397, documento3.get_Estipulante1().get_Nome(), ", "); + } + if (documento3.get_Estipulante2() != null) + { + str397 = string.Concat(str397, documento3.get_Estipulante2().get_Nome(), ", "); + } + if (documento3.get_Estipulante3() != null) + { + str397 = string.Concat(str397, documento3.get_Estipulante3().get_Nome(), ", "); + } + if (documento3.get_Estipulante4() != null) + { + str397 = string.Concat(str397, documento3.get_Estipulante4().get_Nome(), ", "); + } + if (documento3.get_Estipulante5() != null) + { + str397 = string.Concat(str397, documento3.get_Estipulante5().get_Nome(), ", "); + } + if (!string.IsNullOrWhiteSpace(str397)) + { + int num16 = str397.LastIndexOf(", ", StringComparison.Ordinal); + str397 = str397.Remove(num16, 2).Insert(num16, "."); + } + string[] strArrays52 = new string[] { str371, ""; + str371 = string.Concat(strArrays52); + } + if (this.SelectedTipoExtrato == 2) + { + string[] strArrays53 = new string[] { str371, ""; + str371 = string.Concat(strArrays53); + } + else + { + string[] strArrays54 = new string[] { str371, ""; + str371 = string.Concat(strArrays54); + } + string[] description10 = new string[] { str371, ""; + str371 = string.Concat(description10); + str371 = string.Concat(str371, "

RAMO: "; + shortDateString19[4] = documento3.get_Controle().get_Ramo().get_Nome(); + shortDateString19[5] = "

VIGÊNCIA INICIAL: "; + date = documento3.get_Vigencia1(); + shortDateString19[8] = date.ToShortDateString(); + shortDateString19[9] = "

VIGÊNCIA FINAL: "; + clienteDesde = documento3.get_Vigencia2(); + if (!clienteDesde.HasValue) + { + shortDateString14 = "-"; + } + else + { + clienteDesde = documento3.get_Vigencia2(); + if (clienteDesde.HasValue) + { + shortDateString14 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString14 = null; + } + } + shortDateString19[12] = shortDateString14; + shortDateString19[13] = "

CONTRATO: "; + str248 = (string.IsNullOrWhiteSpace(documento3.get_Apolice()) ? "-" : documento3.get_Apolice()); + shortDateString19[16] = str248; + shortDateString19[17] = "

POSSUI ENDOSSO? "; + str250 = (documento3.get_TemEndosso() ? "SIM" : "NÃO"); + shortDateString19[20] = str250; + shortDateString19[21] = "

ADITAMENTO: "; + if (string.IsNullOrWhiteSpace(documento3.get_Endosso())) + { + endosso1 = (!flag || documento9 == null ? "-" : documento9.get_Endosso()); + } + else + { + endosso1 = documento3.get_Endosso(); + } + shortDateString19[24] = endosso1; + shortDateString19[25] = "

NEGÓCIO CORRETORA: "; + description9[4] = ValidationHelper.GetDescription(documento3.get_NegocioCorretora()); + description9[5] = "

STATUS DO SEGURO: "; + description9[8] = ValidationHelper.GetDescription(documento3.get_Situacao()); + description9[9] = "

VENDEDOR: "; + str253 = (documento3.get_VendedorPrincipal() == null ? "-" : documento3.get_VendedorPrincipal().get_Nome()); + strArrays51[4] = str253; + strArrays51[5] = "

ESTIPULANTE(S): "; + str329 = (string.IsNullOrWhiteSpace(str397) ? "-" : str397); + strArrays52[4] = str329; + strArrays52[5] = "

SEGURADORA: "; + strArrays53[4] = documento3.get_Controle().get_Seguradora().get_Nome(); + strArrays53[5] = "

SEGURADORA: "; + strArrays54[4] = documento3.get_Controle().get_Seguradora().get_Nome(); + strArrays54[5] = "

APÓLICE SINISTRADA: "; + str327 = (documento3.get_Sinistro() ? "SIM" : "NÃO"); + strArrays54[8] = str327; + strArrays54[9] = "

FORMA PAGAMENTO: "; + description10[4] = ValidationHelper.GetDescription(documento3.get_FormaPagamento()); + description10[5] = "

"); + if (this.PremioParcela || this.ExtratoResumido) + { + str371 = string.Concat(str371, ""); + if (this.ComissaoDocumento && this.ComissaoDocumentoEnabled || this.ExtratoResumido) + { + string[] strArrays55 = new string[] { str371, ""; + str371 = string.Concat(strArrays55); + } + string[] strArrays56 = new string[26]; + strArrays56[0] = str371; + strArrays56[1] = ""; + str371 = string.Concat(strArrays56); + str371 = string.Concat(str371, "

COMISSÃO: "; + strArrays55[4] = string.Format("{0:n2}%", Math.Round(documento3.get_Comissao(), 2)); + strArrays55[5] = "

PRÊMIO LÍQUIDO: "; + strArrays56[4] = string.Format("{0:c}", Math.Round(documento3.get_PremioLiquido(), 2)); + strArrays56[5] = "

ADICIONAL: "; + strArrays56[8] = string.Format("{0:c}", Math.Round(documento3.get_PremioAdicional(), 2)); + strArrays56[9] = "

CUSTO APÓLICE: "; + strArrays56[12] = string.Format("{0:c}", Math.Round(documento3.get_Custo(), 2)); + strArrays56[13] = "

I.O.F.: "; + strArrays56[16] = string.Format("{0:c}", Math.Round(documento3.get_Iof(), 2)); + strArrays56[17] = "

PRÊMIO TOTAL: "; + strArrays56[20] = string.Format("{0:c}", Math.Round(documento3.get_PremioTotal(), 2)); + strArrays56[21] = "

Nº PARCELAS: "; + premioLiquido = documento3.get_NumeroParcelas(); + strArrays56[24] = premioLiquido.ToString(); + strArrays56[25] = "

"); + } + if (this.PerfilCondutor && this.PerfilVisibility && documento3.get_Controle().get_Ramo().get_Id() == (long)5 && this.PerfilCondutorEnabled) + { + List perfils1 = perfils.ToList(); + foreach (Perfil perfil1 in perfils1) + { + num10 = 0; + if (string.IsNullOrEmpty(perfil1.get_Nome())) + { + continue; + } + string[] description11 = new string[60]; + description11[0] = str371; + description11[1] = "

"; + description11[4] = string.Format("CONDUTOR {0}: ", perfils1.IndexOf(perfil1) + 1); + description11[5] = ""; + description11[6] = perfil1.get_Nome(); + description11[7] = "

CPF: "; + str301 = (string.IsNullOrWhiteSpace(perfil1.get_Cpf()) ? "-" : perfil1.get_Cpf()); + description11[10] = str301; + description11[11] = "

NASCIMENTO: "; + clienteDesde = perfil1.get_Nascimento(); + if (!clienteDesde.HasValue) + { + shortDateString16 = "-"; + } + else + { + clienteDesde = perfil1.get_Nascimento(); + if (clienteDesde.HasValue) + { + shortDateString16 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString16 = null; + } + } + description11[14] = shortDateString16; + description11[15] = "

ESTADO CIVIL: "; + str304 = (!perfil1.get_EstadoCivil().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_EstadoCivil())); + description11[18] = str304; + description11[19] = "

SEXO: "; + str306 = (!perfil1.get_Sexo().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_Sexo())); + description11[22] = str306; + description11[23] = "

RELAÇÃO SEGURADO/CONDUTOR: "; + description11[26] = ValidationHelper.GetDescription(perfil1.get_Relacao()); + description11[27] = "

GARAGEM NA RESIDÊNCIA: "; + str309 = (!perfil1.get_GaragemResidencia().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_GaragemResidencia())); + description11[30] = str309; + description11[31] = "

GARAGEM NO TRABALHO: "; + str311 = (!perfil1.get_GaragemTrabalho().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_GaragemTrabalho())); + description11[34] = str311; + description11[35] = "

GARAGEM NO ESTUDO: "; + str313 = (!perfil1.get_GaragemEstudo().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_GaragemEstudo())); + description11[38] = str313; + description11[39] = "

TIPO DE RESIDÊNCIA: "; + str315 = (!perfil1.get_TipoResidencia().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_TipoResidencia())); + description11[42] = str315; + description11[43] = "

DISTÂNCIA ATÉ O TRABALHO: "; + str317 = (!perfil1.get_DistanciaResidenciaTrabalho().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_DistanciaResidenciaTrabalho())); + description11[46] = str317; + description11[47] = "

USO PROFISSIONAL: "; + str319 = (!perfil1.get_UsoProfissional().HasValue || !perfil1.get_UsoProfissional().Value ? "NÃO" : "SIM"); + description11[50] = str319; + description11[51] = "

USO POR DEPENDENTES: "; + str321 = (!perfil1.get_UsoDependentes().HasValue ? "-" : ValidationHelper.GetDescription(perfil1.get_UsoDependentes())); + description11[54] = str321; + description11[55] = "

ISENÇÃO DE IMPOSTOS: "; + str323 = (!perfil1.get_Isencao().HasValue || !perfil1.get_Isencao().Value ? "NÃO" : "SIM"); + description11[58] = str323; + description11[59] = "

"; + str371 = string.Concat(description11); + } + } + list = items1.ToList(); + if (list.Count != 0) + { + num10 = 0; + foreach (Item item5 in list) + { + if (item5.get_Sinistros().Count > 0) + { + item1 = item5; + controleSinistros = await (new SinistroServico()).BuscarControles(item5.get_Id()); + item1.set_Sinistros(controleSinistros); + item1 = null; + } + string str398 = str371; + str262 = (!this.SepararPagina || !this.SepararPaginaEnabled ? "" : "
"); + str371 = string.Concat(str398, str262); + string str399 = str371; + str263 = (this.SelectedTipoExtrato != 2 || list.IndexOf(item5) == 0 ? "
" : ""); + str371 = string.Concat(str399, str263); + str371 = string.Concat(str371, ""); + str371 = string.Concat(str371, ""); + str371 = string.Concat(str371, ""); + if (this.SelectedTipoExtrato != 2) + { + id = documento3.get_Controle().get_Ramo().get_Id(); + if (id > (long)5) + { + if (id == (long)15 || id == (long)18) + { + goto Label8; + } + if (id == (long)37) + { + goto Label6; + } + goto Label7; + } + else + { + if (id - (long)1 <= (long)2) + { + goto Label8; + } + if (id == (long)5) + { + goto Label6; + } + goto Label7; + } + Label8: + item1 = item5; + patrimonial = await (new ItemServico()).BuscaPatrimonial(item5.get_Id()); + item1.set_Patrimonial(patrimonial); + item1 = null; + string[] estado1 = new string[19]; + estado1[0] = str371; + estado1[1] = ""; + str371 = string.Concat(estado1); + } + else + { + string[] descricao3 = new string[] { str371, ""; + str371 = string.Concat(descricao3); + } + Label10: + if (item5.get_Sinistros().Count > 0) + { + Item item6 = item5; + if (item6 != null) + { + IList controleSinistros3 = item6.get_Sinistros(); + if (controleSinistros3 != null) + { + ControleSinistro controleSinistro3 = controleSinistros3.LastOrDefault(); + if (controleSinistro3 != null) + { + List sinistros4 = controleSinistro3.get_Sinistros(); + if (sinistros4 != null) + { + Sinistro sinistro5 = sinistros4.LastOrDefault(); + if (sinistro5 != null) + { + dataReclamacao1 = sinistro5.get_DataReclamacao(); + } + else + { + clienteDesde = null; + dataReclamacao1 = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao1 = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao1 = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao1 = clienteDesde; + } + } + else + { + clienteDesde = null; + dataReclamacao1 = clienteDesde; + } + DateTime? nullable4 = dataReclamacao1; + if (nullable4.HasValue) + { + date = nullable4.Value; + shortDateString15 = date.ToShortDateString(); + } + else + { + shortDateString15 = "-"; + } + string str400 = shortDateString15; + string[] currency1 = new string[14]; + currency1[0] = str371; + currency1[1] = ""; + str371 = string.Concat(currency1); + } + str371 = string.Concat(str371, ""); + if (this.SelectedTipoExtrato != 2) + { + string[] strArrays57 = new string[] { str371, ""; + str371 = string.Concat(strArrays57); + id = documento3.get_Controle().get_Ramo().get_Id(); + long num17 = id - (long)1; + if (num17 <= (long)58) + { + switch ((uint)num17) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays58 = new string[] { str371, ""; + str371 = string.Concat(strArrays58); + break; + } + case 3: + case 7: + case 15: + case 16: + case 18: + case 22: + case 23: + case 25: + case 27: + case 30: + case 32: + case 38: + case 40: + case 43: + case 48: + case 58: + { + item1 = item5; + riscosDiverso = await (new ItemServico()).BuscaRiscosDiversos(item5.get_Id()); + item1.set_RiscosDiversos(riscosDiverso); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays59 = new string[] { str371, ""; + str371 = string.Concat(strArrays59); + break; + } + case 4: + case 36: + { + if (this.ObsItem && this.ObsItemEnabled) + { + string[] strArrays60 = new string[] { str371, ""; + str371 = string.Concat(strArrays60); + } + string[] strArrays61 = new string[26]; + strArrays61[0] = str371; + strArrays61[1] = ""; + str371 = string.Concat(strArrays61); + break; + } + case 5: + case 6: + case 8: + case 9: + case 52: + { + item1 = item5; + vida = await (new ItemServico()).BuscaVida(item5.get_Id()); + item1.set_Vida(vida); + item1 = null; + if (!item5.get_Sinistrado() || !this.BeneficiariosItens || !this.BeneficiariosItensEnabled) + { + break; + } + string str401 = str371; + str287 = (num10 % 2 == 0 ? "WhiteSmoke" : "White"); + str371 = string.Concat(str401, ""); + break; + } + case 12: + { + item1 = item5; + aeronautico = await (new ItemServico()).BuscaAeronautico(item5.get_Id()); + item1.set_Aeronautico(aeronautico); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays62 = new string[] { str371, ""; + str371 = string.Concat(strArrays62); + break; + } + case 19: + { + item1 = item5; + granizo = await (new ItemServico()).BuscaGranizo(item5.get_Id()); + item1.set_Granizo(granizo); + item1 = null; + if (!this.ObsItem || !this.ObsItemEnabled) + { + break; + } + string[] strArrays63 = new string[] { str371, ""; + str371 = string.Concat(strArrays63); + break; + } + } + } + else + { + } + } + str371 = string.Concat(str371, "

"; + estado1[4] = string.Format("ITEM {0}: ", item5.get_Ordem()); + estado1[5] = ""; + estado1[6] = item5.get_Patrimonial().get_Endereco(); + estado1[7] = ", "; + estado1[8] = item5.get_Patrimonial().get_Numero(); + estado1[9] = ", "; + str265 = (string.IsNullOrWhiteSpace(item5.get_Patrimonial().get_Complemento()) ? "" : string.Concat(item5.get_Patrimonial().get_Complemento(), ", ")); + estado1[10] = str265; + estado1[11] = item5.get_Patrimonial().get_Bairro(); + estado1[12] = " - "; + estado1[13] = item5.get_Patrimonial().get_Cidade(); + estado1[14] = " - "; + estado1[15] = item5.get_Patrimonial().get_Estado(); + estado1[16] = " - "; + estado1[17] = item5.get_Patrimonial().get_Cep(); + estado1[18] = "

"; + descricao3[4] = string.Format("ITEM {0}: ", item5.get_Ordem()); + descricao3[5] = ""; + descricao3[6] = item5.get_Descricao(); + descricao3[7] = "

SINISTRO STATUS: "; + currency1[4] = ValidationHelper.GetDescription(item5.get_Sinistros().LastOrDefault().get_Sinistros().LastOrDefault().get_StatusSinistro()); + currency1[5] = "

DATA: "; + currency1[8] = str400; + currency1[9] = "

VALOR: "; + currency1[12] = ValidationHelper.ToCurrency(item5.get_Sinistros().LastOrDefault().get_Sinistros().LastOrDefault().get_Valor(), "pt-BR"); + currency1[13] = "

ATIVO: "; + str272 = (!item5.get_Substituido().HasValue ? "SIM" : "NÃO"); + strArrays57[4] = str272; + strArrays57[5] = "

OBSERVAÇÕES: "; + str274 = (string.IsNullOrWhiteSpace(item5.get_Patrimonial().get_Bens()) ? "-" : item5.get_Patrimonial().get_Bens()); + strArrays58[4] = str274; + strArrays58[5] = "

OBSERVAÇÕES: "; + str276 = (string.IsNullOrWhiteSpace(item5.get_RiscosDiversos().get_Observacao()) ? "-" : item5.get_RiscosDiversos().get_Observacao()); + strArrays59[4] = str276; + strArrays59[5] = "

OBSERVAÇÕES: "; + str286 = (string.IsNullOrWhiteSpace(item5.get_Auto().get_Observacao()) ? "-" : item5.get_Auto().get_Observacao()); + strArrays60[4] = str286; + strArrays60[5] = "

COBERTURA PADRÃO: "; + tipoCobertura = item5.get_Auto().get_TipoCobertura(); + if (tipoCobertura.HasValue) + { + description3 = ValidationHelper.GetDescription(tipoCobertura.GetValueOrDefault()); + } + else + { + description3 = null; + } + strArrays61[4] = description3; + strArrays61[5] = "

BÔNUS: "; + bonus = item5.get_Auto().get_Bonus(); + strArrays61[8] = bonus.ToString(); + strArrays61[9] = "

REGIÃO DE CIRCULAÇÃO: "; + str280 = (string.IsNullOrWhiteSpace(item5.get_Auto().get_RegiaoCirculacao()) ? "-" : item5.get_Auto().get_RegiaoCirculacao()); + strArrays61[12] = str280; + strArrays61[13] = "

TABELA DE REFERÊNCIA: "; + tabelaReferencia = item5.get_Auto().get_TabelaReferencia(); + if (tabelaReferencia.HasValue) + { + description4 = ValidationHelper.GetDescription(tabelaReferencia.GetValueOrDefault()); + } + else + { + description4 = null; + } + strArrays61[16] = description4; + strArrays61[17] = "

FIPE: "; + str283 = (string.IsNullOrWhiteSpace(item5.get_Auto().get_Fipe()) ? "-" : item5.get_Auto().get_Fipe()); + strArrays61[20] = str283; + strArrays61[21] = "

% DE REFERÊNCIA: "; + strArrays61[24] = string.Format("{0}%", item5.get_Auto().get_PorcentagemReferencia()); + strArrays61[25] = "

BENEFICIÁRIOS: "); + string str402 = ""; + foreach (ControleSinistro controleSinistro4 in item5.get_Sinistros()) + { + if (controleSinistro4.get_Sinistros() == null) + { + continue; + } + foreach (Sinistro sinistro6 in controleSinistro4.get_Sinistros()) + { + if (string.IsNullOrWhiteSpace(sinistro6.get_SinistroVida().get_Beneficiario())) + { + continue; + } + str402 = string.Concat(str402, sinistro6.get_SinistroVida().get_Beneficiario(), ", "); + } + } + if (!string.IsNullOrWhiteSpace(str402)) + { + int num18 = str402.LastIndexOf(", ", StringComparison.Ordinal); + str402 = str402.Remove(num18, 2).Insert(num18, "."); + } + str371 = string.Concat(str371, str402, "

OBSERVAÇÕES: "; + str289 = (string.IsNullOrWhiteSpace(item5.get_Aeronautico().get_Observacao()) ? "-" : item5.get_Aeronautico().get_Observacao()); + strArrays62[4] = str289; + strArrays62[5] = "

OBSERVAÇÕES: "; + str291 = (string.IsNullOrWhiteSpace(item5.get_Granizo().get_Observacao()) ? "-" : item5.get_Granizo().get_Observacao()); + strArrays63[4] = str291; + strArrays63[5] = "

"); + if (this.SelectedTipoExtrato != 2) + { + ObservableCollection observableCollection6 = await (new ItemServico()).BuscarCoberturasPorItemAsync(item5.get_Id()); + if (observableCollection6.Count > 0 && this.Coberturas) + { + str371 = string.Concat(str371, "
"); + foreach (Cobertura cobertura1 in observableCollection6) + { + numeroParcela = num10; + num10 = numeroParcela + 1; + string[] strArrays64 = new string[18]; + strArrays64[0] = str371; + strArrays64[1] = "

COBERTURA

FRANQUIA

LMI

PRÊMIO

"; + strArrays64[4] = cobertura1.get_Observacao(); + strArrays64[5] = "

"); + } + string str403 = str371; + str266 = (!this.SepararPagina || !this.SepararPaginaEnabled ? "" : "
"); + str371 = string.Concat(str403, str266); + } + if (this.SelectedTipoExtrato != 2) + { + num10 = 0; + } + } + } + else + { + str371 = string.Concat(str371, "

ESTA APÓLICE NÃO POSSUI ITENS

"); + } + list = null; + } + else + { + variable9 = null; + return; + } + } + } + nums.Add(documento3.get_Controle().get_Id()); + flag1 = false; + } + } + if (this.Prospeccoes != null && this.Prospeccoes.Count > 0) + { + foreach (Prospeccao prospecco in this.Prospeccoes) + { + int num19 = 0; + string str404 = str371; + str19 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
"); + str371 = string.Concat(str404, str19); + str371 = string.Concat(str371, "

"); + if (this.SelectedTipoExtrato == null) + { + str39 = (this.ExtratoResumido ? " RESUMIDO" : ""); + str370 = string.Concat("EXTRATO", str39, " DO CLIENTE: ", prospecco.get_Nome()); + } + str371 = string.Concat(str371, str370, "


"); + str371 = string.Concat(str371, ""); + if (!this.ExtratoResumido) + { + string str405 = "NASCIMENTO"; + string[] documento11 = new string[16]; + documento11[0] = str371; + documento11[1] = ""; + str371 = string.Concat(documento11); + if ((prospecco.get_Telefone1() != null || prospecco.get_Email() != null) && this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + if (prospecco.get_Telefone1() != null) + { + string str406 = ""; + string[] prefixo1 = new string[] { str406, "
(", prospecco.get_Prefixo1(), ") ", prospecco.get_Telefone1() }; + str406 = string.Concat(prefixo1); + if (prospecco.get_Telefone2() != null) + { + string[] prefixo2 = new string[] { str406, "
(", prospecco.get_Prefixo2(), ") ", prospecco.get_Telefone2() }; + str406 = string.Concat(prefixo2); + } + string[] strArrays65 = new string[] { str371, "
"; + str371 = string.Concat(strArrays65); + } + if (prospecco.get_Email() != null && !this.ExtratoResumido) + { + string str407 = ""; + str407 = string.Concat(str407, "
", prospecco.get_Email()); + string[] strArrays66 = new string[] { str371, "
"; + str371 = string.Concat(strArrays66); + } + num19++; + str371 = string.Concat(str371, ""); + } + string str408 = str371; + str23 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : ""); + str371 = string.Concat(str408, str23); + if (this.SelectedTipoExtrato != null) + { + num19 = 0; + string[] strArrays67 = new string[] { str371, "

CLIENTE: "; + documento11[4] = prospecco.get_Nome(); + documento11[5] = "

CPF/CNPJ: "; + documento11[8] = prospecco.get_Documento(); + documento11[9] = "

"; + documento11[12] = str405; + documento11[13] = ": "; + clienteDesde = prospecco.get_Nascimento(); + if (clienteDesde.HasValue) + { + shortDateString = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + documento11[14] = shortDateString; + documento11[15] = "

CONTATOS: "; + strArrays65[4] = str406; + strArrays65[5] = "

EMAILS: "; + strArrays66[4] = str407; + strArrays66[5] = "

"; + str371 = string.Concat(strArrays67); + string[] strArrays68 = new string[] { str371, ""; + str371 = string.Concat(strArrays68); + str371 = string.Concat(str371, "

VIGÊNCIA FINAL: "; + clienteDesde = prospecco.get_VigenciaFinal(); + if (!clienteDesde.HasValue) + { + shortDateString1 = "-"; + } + else + { + clienteDesde = prospecco.get_VigenciaFinal(); + if (clienteDesde.HasValue) + { + shortDateString1 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString1 = null; + } + } + strArrays67[4] = shortDateString1; + strArrays67[5] = "

VENDEDOR: "; + str26 = (prospecco.get_Vendedor() == null ? "-" : prospecco.get_Vendedor().get_Nome()); + strArrays68[4] = str26; + strArrays68[5] = "

"); + } + else + { + variable9 = null; + return; + } + } + else + { + string[] documento12 = new string[] { str371, ""; + str371 = string.Concat(documento12); + if (this.SelectedTipoExtrato != 2) + { + str371 = string.Concat(str371, ""); + string str409 = ""; + if (prospecco.get_Telefone1() != null) + { + string[] prefixo11 = new string[] { str409, "
(", prospecco.get_Prefixo1(), ") ", prospecco.get_Telefone1() }; + str409 = string.Concat(prefixo11); + } + if (prospecco.get_Telefone2() != null) + { + string[] prefixo21 = new string[] { str409, "
(", prospecco.get_Prefixo2(), ") ", prospecco.get_Telefone2() }; + str409 = string.Concat(prefixo21); + } + string[] strArrays69 = new string[] { str371, "
"; + str371 = string.Concat(strArrays69); + string str410 = ""; + if (prospecco.get_Email() != null) + { + str410 = string.Concat("
", prospecco.get_Email()); + } + string[] strArrays70 = new string[] { str371, "
"; + str371 = string.Concat(strArrays70); + } + str371 = string.Concat(str371, "

CLIENTE: "; + documento12[4] = prospecco.get_Nome(); + documento12[5] = "

CPF/CNPJ: "; + documento12[8] = prospecco.get_Documento(); + documento12[9] = "

CONTATOS: "; + str36 = (string.IsNullOrEmpty(str409) ? "-" : str409); + strArrays69[4] = str36; + strArrays69[5] = "

EMAILS: "; + str38 = (string.IsNullOrEmpty(str410) ? "-" : str410); + strArrays70[4] = str38; + strArrays70[5] = "

"); + string str411 = str371; + str31 = (this.ClientePorPaginaVisibility != Visibility.Visible || !this.ClientePorPagina || !this.ClientePorPaginaEnabled ? "" : "
"); + str371 = string.Concat(str411, str31); + if (this.SelectedTipoExtrato != null) + { + num19 = 0; + string[] strArrays71 = new string[] { str371, "
"; + str371 = string.Concat(strArrays71); + string[] strArrays72 = new string[] { str371, ""; + str371 = string.Concat(strArrays72); + str371 = string.Concat(str371, "

VIGÊNCIA FINAL: "; + clienteDesde = prospecco.get_VigenciaFinal(); + if (!clienteDesde.HasValue) + { + shortDateString2 = "-"; + } + else + { + clienteDesde = prospecco.get_VigenciaFinal(); + if (clienteDesde.HasValue) + { + shortDateString2 = clienteDesde.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString2 = null; + } + } + strArrays71[4] = shortDateString2; + strArrays71[5] = "

VENDEDOR: "; + str34 = (prospecco.get_Vendedor() == null ? "-" : prospecco.get_Vendedor().get_Nome()); + strArrays72[4] = str34; + strArrays72[5] = "

"); + } + else + { + variable9 = null; + return; + } + } + } + } + DateTime dateTime = Funcoes.GetNetworkTime(); + string[] shortDateString20 = new string[] { str371, "

", Recursos.Usuario.get_Nome(), " - ", null, null }; + date = dateTime.Date; + shortDateString20[4] = date.ToShortDateString(); + shortDateString20[5] = "
"; + str371 = string.Concat(shortDateString20); + string tempPath1 = Path.GetTempPath(); + string str412 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath1, (TipoExtrato)0, dateTime); + if (!pdf) + { + StreamWriter streamWriter1 = new StreamWriter(str412, true, Encoding.UTF8); + streamWriter1.Write(str371); + streamWriter1.Close(); + } + else + { + str412 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.pdf", tempPath1, (TipoExtrato)0, dateTime); + File.WriteAllBytes(str412, (new NRecoHtmlToPdfConverter()).GeneratePdf(str371)); + } + Process.Start(str412); + if (this.Documentos != null && this.Documentos.Count > 1) + { + ExtratosViewModel extratosViewModel1 = this; + str17 = (this.ExtratoResumido ? " RESUMIDO" : ""); + if (this.Documentos != null) + { + str18 = (this.Documentos.Count > 1 ? string.Format("DE {0} DOCUMENTOS", this.Documentos.Count) : string.Format("DO DOCUMENTO {0}", this.Documentos[0].get_Id())); + } + else + { + str18 = ""; + } + string str413 = string.Concat("GEROU O EXTRATO", str17, " ", str18); + long num24 = (long)0; + TipoTela? nullable5 = new TipoTela?(23); + List documentos3 = this.Documentos; + extratosViewModel1.RegistrarAcao(str413, num24, nullable5, string.Concat("IDS DOS DOCUMENTOS:\n", string.Join("\n", + from x in documentos3 + select x.get_Id()), this.GerarOpcoes())); + } + if (this.Prospeccoes != null && this.Prospeccoes.Count > 1) + { + ExtratosViewModel extratosViewModel2 = this; + str15 = (this.ExtratoResumido ? " RESUMIDO" : ""); + if (this.Prospeccoes != null) + { + str16 = (this.Prospeccoes.Count > 1 ? string.Format("DE {0} PROSPECÇÕES", this.Prospeccoes.Count) : string.Format("DA PROSPÇÃO{0}", this.Prospeccoes[0].get_Id())); + } + else + { + str16 = ""; + } + string str414 = string.Concat("GEROU O EXTRATO", str15, " ", str16); + long num25 = (long)0; + TipoTela? nullable6 = new TipoTela?(23); + List prospeccoes = this.Prospeccoes; + extratosViewModel2.RegistrarAcao(str414, num25, nullable6, string.Concat("IDS DOS DOCUMENTOS:\n", string.Join("\n", + from x in prospeccoes + select x.get_Id()), this.GerarOpcoes())); + } + this.Documentos = null; + this.Clientes = null; + this.Prospeccoes = null; + nums = null; + } + variable9 = null; + return; + Label3: + item1 = item; + auto = await (new ItemServico()).BuscaAuto(item.get_Id()); + item1.set_Auto(auto); + item1 = null; + string[] modelo = new string[26]; + modelo[0] = str371; + modelo[1] = "

"; + modelo[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + modelo[5] = "
"; + Fabricante fabricante = item.get_Auto().get_Fabricante(); + if (fabricante != null) + { + descricao = fabricante.get_Descricao(); + } + else + { + descricao = null; + } + modelo[6] = descricao; + modelo[7] = " "; + modelo[8] = item.get_Auto().get_Modelo(); + modelo[9] = " ("; + modelo[10] = item.get_Auto().get_AnoFabricacao(); + modelo[11] = "/"; + modelo[12] = item.get_Auto().get_AnoModelo(); + modelo[13] = ")
PLACA: "; + modelo[14] = item.get_Auto().get_Placa(); + modelo[15] = ", CHASSI: "; + modelo[16] = item.get_Auto().get_Chassi(); + modelo[17] = "
C.I.: "; + modelo[18] = item.get_Auto().get_Ci(); + modelo[19] = ", RENAVAM: "; + modelo[20] = item.get_Auto().get_Renavam(); + modelo[21] = ", CEP PERNOITE: "; + modelo[22] = item.get_Auto().get_CepPernoite(); + modelo[23] = "
FINANCIADO: "; + str112 = (item.get_Auto().get_Financiado().GetValueOrDefault() ? "SIM" : "NÃO"); + modelo[24] = str112; + modelo[25] = "

"; + str371 = string.Concat(modelo); + goto Label9; + Label4: + string[] descricao4 = new string[] { str371, "

"; + descricao4[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + descricao4[5] = ""; + descricao4[6] = item.get_Descricao(); + descricao4[7] = "

QTDE SINISTRO(S): "; + numeroParcela = item.get_Sinistros().Count; + descricao4[8] = numeroParcela.ToString(); + descricao4[9] = "

"; + str371 = string.Concat(descricao4); + goto Label9; + Label6: + item1 = item; + auto = await (new ItemServico()).BuscaAuto(item.get_Id()); + item1.set_Auto(auto); + item1 = null; + string[] anoFabricacao = new string[26]; + anoFabricacao[0] = str371; + anoFabricacao[1] = "

"; + anoFabricacao[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + anoFabricacao[5] = "
"; + Fabricante fabricante1 = item.get_Auto().get_Fabricante(); + if (fabricante1 != null) + { + descricao1 = fabricante1.get_Descricao(); + } + else + { + descricao1 = null; + } + anoFabricacao[6] = descricao1; + anoFabricacao[7] = " "; + anoFabricacao[8] = item.get_Auto().get_Modelo(); + anoFabricacao[9] = " ("; + anoFabricacao[10] = item.get_Auto().get_AnoFabricacao(); + anoFabricacao[11] = "/"; + anoFabricacao[12] = item.get_Auto().get_AnoModelo(); + anoFabricacao[13] = ")
PLACA: "; + anoFabricacao[14] = item.get_Auto().get_Placa(); + anoFabricacao[15] = ", CHASSI: "; + anoFabricacao[16] = item.get_Auto().get_Chassi(); + anoFabricacao[17] = "
C.I.: "; + anoFabricacao[18] = item.get_Auto().get_Ci(); + anoFabricacao[19] = ", RENAVAM: "; + anoFabricacao[20] = item.get_Auto().get_Renavam(); + anoFabricacao[21] = ", CEP PERNOITE: "; + anoFabricacao[22] = item.get_Auto().get_CepPernoite(); + anoFabricacao[23] = "
FINANCIADO: "; + str296 = (item.get_Auto().get_Financiado().GetValueOrDefault() ? "SIM" : "NÃO"); + anoFabricacao[24] = str296; + anoFabricacao[25] = "

"; + str371 = string.Concat(anoFabricacao); + goto Label10; + Label7: + string[] descricao5 = new string[] { str371, "

"; + descricao5[4] = string.Format("ITEM {0}: ", item.get_Ordem()); + descricao5[5] = ""; + descricao5[6] = item.get_Descricao(); + descricao5[7] = "

"; + str371 = string.Concat(descricao5); + goto Label10; + } + + public string GerarOpcoes() + { + string str = ""; + if (this.ClienteVisibility && this.ObsCliente && this.ObsClienteEnabled) + { + str = string.Concat(str, "\nOBSERVAÇÕES DO CLIENTE"); + } + if (this.ClientePorPaginaVisibility == Visibility.Visible && this.ClientePorPagina && this.ClientePorPaginaEnabled) + { + str = string.Concat(str, "\nSEPARAR CLIENTES POR PÁGINA"); + } + if (this.DocumentoVisibility) + { + if (this.ComissaoDocumentoEnabled && this.ComissaoDocumento) + { + str = string.Concat(str, "\nCOMISSÕES DO DOCUMENTO"); + } + if (this.ObsApoliceEnabled && this.ObsApolice) + { + str = string.Concat(str, "\nOBSERVAÇÕES DA APÓLICE"); + } + if (this.SegurosVigentesVisibility == Visibility.Visible && this.SegurosVigentes) + { + str = string.Concat(str, "\nAPENAS SEGUROS VIGENTES"); + } + } + if (this.ItemVisibility) + { + if (this.SelecionarItensVisibility == Visibility.Visible && this.SelecionarItens) + { + str = string.Concat(str, "\nSELECIONAR ITENS"); + } + if (this.BeneficiariosItensEnabled && this.BeneficiariosItens) + { + str = string.Concat(str, "\nBENEFICIÁRIOS DOS ITENS"); + } + if (this.ObsItemEnabled && this.ObsItem) + { + str = string.Concat(str, "\nOBSERVAÇÕES DO ITEM"); + } + if (this.SepararPaginaEnabled && this.SepararPagina) + { + str = string.Concat(str, "\nSEPARAR ITENS POR PÁGINA"); + } + } + if (this.PerfilCondutor && this.PerfilVisibility && this.PerfilCondutorEnabled) + { + str = string.Concat(str, "\nPERFIL DO CONDUTOR"); + } + if (string.IsNullOrWhiteSpace(str)) + { + return ""; + } + return string.Concat("\n\nOPÇÕES:", str); + } + + public async Task PrepararExtrato(List clientes, List documentos, List prospeccoes, Relatorio? tipoRelatorio = null, List selecionadosDoc = null, List selecionadosPros = null, bool pdf = false) + { + ObservableCollection observableCollection; + ObservableCollection observableCollection1; + ObservableCollection observableCollection2; + ObservableCollection observableCollection3; + ObservableCollection observableCollection4; + bool count; + List documentos1; + bool flag; + List clientes1; + Cliente cliente; + Cliente cliente1; + List documentos2; + this.Carregando = true; + Relatorio? nullable = tipoRelatorio; + if (nullable.GetValueOrDefault() != 0 | !nullable.HasValue && tipoRelatorio.GetValueOrDefault() != 1) + { + if ((documentos == null || documentos.Count == 0) && (prospeccoes == null || prospeccoes.Count == 0)) + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM DOCUMENTO OU PROSPECÇÃO", "OK", "", false); + this.Carregando = false; + return; + } + else + { + List documentos3 = documentos; + if (documentos3 != null) + { + count = documentos3.Count > 200; + } + else + { + count = false; + } + if (!count) + { + List prospeccaos = prospeccoes; + if (prospeccaos != null) + { + flag = prospeccaos.Count > 200; + } + else + { + flag = false; + } + if (!flag) + { + goto Label1; + } + } + if (!await base.ShowMessage("A SELEÇÃO DE MUITOS EXTRATOS PODE DEMORAR MAIS DE 30 MINUTOS! CONTINUAR?", "SIM", "NÃO", false)) + { + this.Carregando = false; + return; + } + Label1: + switch (this.SelectedTipoExtrato) + { + case 0: + { + if (selecionadosDoc == null || selecionadosDoc.Count == 0) + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM DOCUMENTO SELECIONADO", "OK", "", false); + this.Carregando = false; + return; + } + else + { + clientes1 = new List(); + foreach (Documento documento in documentos) + { + cliente = await (new ClienteServico()).BuscarCliente(documento.get_Controle().get_Cliente().get_Id()); + cliente1 = cliente; + observableCollection = await this._clienteServico.BuscarEnderecosAsync(cliente.get_Id()); + cliente1.set_Enderecos(observableCollection); + cliente1 = null; + cliente1 = cliente; + observableCollection1 = await this._clienteServico.BuscarEmailsAsync(cliente.get_Id()); + cliente1.set_Emails(observableCollection1); + cliente1 = null; + cliente1 = cliente; + observableCollection2 = await this._clienteServico.BuscarTelefonesAsync(cliente.get_Id()); + cliente1.set_Telefones(observableCollection2); + cliente1 = null; + cliente1 = cliente; + observableCollection3 = await this._clienteServico.BuscarContatosAsync(cliente.get_Id()); + cliente1.set_Contatos(observableCollection3); + cliente1 = null; + cliente1 = cliente; + observableCollection4 = await this._clienteServico.BuscarVinculosAsync(cliente.get_Id()); + cliente1.set_Vinculos(observableCollection4); + cliente1 = null; + clientes1.Add(cliente); + cliente = null; + } + this.Clientes = clientes1; + this.Prospeccoes = prospeccoes; + break; + } + } + case 1: + { + if ((selecionadosDoc == null || selecionadosDoc.Count == 0) && (selecionadosPros == null || selecionadosPros.Count == 0)) + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM DOCUMENTO SELECIONADO", "OK", "", false); + this.Carregando = false; + return; + } + else + { + this.Documentos = new List(); + this.Prospeccoes = new List(); + if (selecionadosDoc != null) + { + foreach (long num in selecionadosDoc) + { + Documento documento1 = await (new ApoliceServico()).BuscarApoliceAsync(num, false, true); + Documento documento2 = documento1; + documentos1 = (!this.SomenteEndossos || documento2.get_Ordem() == 1 ? new List() + { + documento2 + } : new List()); + List documentos4 = documentos1; + if (this.SomenteEndossos) + { + IEnumerable documentos5 = documento2.get_Controle().get_Documentos().Where((Documento x) => { + if (x.get_Excluido() || x.get_Ordem() == 0) + { + return false; + } + return !documentos4.Any((Documento y) => y.get_Id() == x.get_Id()); + }); + foreach (Documento documento3 in documentos5) + { + documento3.set_Sinistro(documento2.get_Sinistro()); + } + documentos4.AddRange(documentos5); + } + else if (this.Endossos) + { + IEnumerable documentos6 = documento2.get_Controle().get_Documentos().Where((Documento x) => { + if (x.get_Id() == documento2.get_Id()) + { + return false; + } + return !x.get_Excluido(); + }); + foreach (Documento documento4 in documentos6) + { + documento4.set_Sinistro(documento2.get_Sinistro()); + } + documentos4.AddRange(documentos6); + } + if (documento2.get_Controle().get_Documentos().Any((Documento x) => { + if (x.get_Id() == documento2.get_Id() || x.get_Excluido()) + { + return false; + } + return x.get_Ordem() > documento2.get_Ordem(); + })) + { + documento2.set_TemEndosso(true); + } + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 31) && documento2.get_TemEndosso()) + { + Documento documento5 = documento2; + IList documentos7 = documento2.get_Controle().get_Documentos(); + IEnumerable excluido = + from x in documentos7 + where !x.get_Excluido() + select x; + documento5.set_PremioTotal(excluido.Sum((Documento x) => x.get_PremioTotal())); + Documento documento6 = documento2; + IList documentos8 = documento2.get_Controle().get_Documentos(); + IEnumerable excluido1 = + from x in documentos8 + where !x.get_Excluido() + select x; + documento6.set_Iof(excluido1.Sum((Documento x) => x.get_Iof())); + Documento documento7 = documento2; + IList documentos9 = documento2.get_Controle().get_Documentos(); + IEnumerable excluido2 = + from x in documentos9 + where !x.get_Excluido() + select x; + documento7.set_Custo(excluido2.Sum((Documento x) => x.get_Custo())); + Documento documento8 = documento2; + IList documentos10 = documento2.get_Controle().get_Documentos(); + IEnumerable excluido3 = + from x in documentos10 + where !x.get_Excluido() + select x; + documento8.set_PremioLiquido(excluido3.Sum((Documento x) => x.get_PremioLiquido())); + Documento documento9 = documento2; + IList documentos11 = documento2.get_Controle().get_Documentos(); + IEnumerable excluido4 = + from x in documentos11 + where !x.get_Excluido() + select x; + documento9.set_PremioAdicional(excluido4.Sum((Documento x) => x.get_PremioAdicional())); + } + List documentos12 = this.Documentos; + List documentos13 = documentos4; + documentos12.AddRange(( + from x in documentos13 + orderby x.get_Ordem() + select x).ToList()); + } + } + if (selecionadosPros != null) + { + foreach (long selecionadosPro in selecionadosPros) + { + Prospeccao prospeccao = await (new ProspeccaoServico()).BuscarProspeccao(selecionadosPro); + this.Prospeccoes.Add(prospeccao); + } + } + if (this.SelecionarItensVisibility == Visibility.Visible && this.SelecionarItens && this.Documentos != null && this.Documentos.Count > 0) + { + ObservableCollection observableCollection5 = await base.ShowSelecionarItensDialog(this.Documentos.First().get_Controle().get_Id()); + ExtratosViewModel list = this; + ObservableCollection observableCollection6 = observableCollection5; + list._itensSelecionados = ( + from x in observableCollection6 + where x.get_Selecionado() + select x).ToList(); + } + if (this.Documentos != null && this.Documentos.Count != 0 || this.Prospeccoes != null && this.Prospeccoes.Count != 0) + { + break; + } + if (!this.SomenteEndossos) + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM DOCUMENTO OU PROSPECÇÃO SELECIONADO", "OK", "", false); + } + else + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM ENDOSSO OU PROSPECÇÃO SELECIONADO", "OK", "", false); + } + this.Carregando = false; + return; + } + } + case 2: + { + documentos2 = new List(); + ApoliceServico apoliceServico = new ApoliceServico(); + long id = documentos.First().get_Controle().get_Cliente().get_Id(); + FiltroStatusDocumento statusSelecionado = MainViewModel.StatusSelecionado; + List vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + ObservableCollection observableCollection7 = await apoliceServico.BuscarApolicesAsync(id, statusSelecionado, vendedorUsuarios); + apoliceServico = null; + this.Documentos = new List(observableCollection7); + foreach (Documento documento10 in this.Documentos) + { + foreach (Documento documento11 in documento10.get_Controle().get_Documentos()) + { + if (documento11.get_Tipo() != 1) + { + continue; + } + documentos2.Add(documento11); + documento10.set_TemEndosso(true); + } + } + this.Documentos.AddRange(documentos2); + break; + } + } + documentos2 = null; + clientes1 = null; + } + } + else if (clientes == null || clientes.Count == 0) + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM CLIENTE", "OK", "", false); + this.Carregando = false; + return; + } + else + { + if (clientes.Count > 200) + { + if (!await base.ShowMessage("A SELEÇÃO DE MUITOS EXTRATOS PODE DEMORAR MAIS DE 30 MINUTOS! CONTINUAR?", "SIM", "NÃO", false)) + { + this.Carregando = false; + return; + } + } + clientes1 = new List(); + List clientesAtivosInativos = clientes; + foreach (ClientesAtivosInativos clientesAtivosInativo in + from x in clientesAtivosInativos + where x.get_Selecionado() + select x) + { + cliente = await (new ClienteServico()).BuscarCliente(clientesAtivosInativo.get_Id()); + cliente1 = cliente; + observableCollection = await this._clienteServico.BuscarEnderecosAsync(cliente.get_Id()); + cliente1.set_Enderecos(observableCollection); + cliente1 = null; + cliente1 = cliente; + observableCollection1 = await this._clienteServico.BuscarEmailsAsync(cliente.get_Id()); + cliente1.set_Emails(observableCollection1); + cliente1 = null; + cliente1 = cliente; + observableCollection2 = await this._clienteServico.BuscarTelefonesAsync(cliente.get_Id()); + cliente1.set_Telefones(observableCollection2); + cliente1 = null; + cliente1 = cliente; + observableCollection3 = await this._clienteServico.BuscarContatosAsync(cliente.get_Id()); + cliente1.set_Contatos(observableCollection3); + cliente1 = null; + cliente1 = cliente; + observableCollection4 = await this._clienteServico.BuscarVinculosAsync(cliente.get_Id()); + cliente1.set_Vinculos(observableCollection4); + cliente1 = null; + clientes1.Add(cliente); + cliente = null; + } + this.Clientes = clientes1; + clientes1 = null; + } + if (this.SegurosVigentesVisibility == Visibility.Visible && this.SegurosVigentes) + { + ExtratosViewModel extratosViewModel = this; + List documentos14 = this.Documentos; + extratosViewModel.Documentos = documentos14.Where((Documento x) => { + DateTime? vigencia2 = x.get_Vigencia2(); + DateTime dateTime = Funcoes.GetNetworkTime().Date.AddDays(-5); + if ((vigencia2.HasValue ? vigencia2.GetValueOrDefault() <= dateTime : true)) + { + vigencia2 = x.get_Vigencia2(); + if (vigencia2.HasValue) + { + return false; + } + } + return x.get_Situacao() != 7; + }).ToList(); + } + await this.Gerar(tipoRelatorio, pdf); + this.Carregando = false; + } + + private void RelacaoApolices() + { + this.SetAllFalse(); + this.ComissaoDocumentoEnabled = true; + this.PerfilCondutorEnabled = true; + } + + private void SetAllFalse() + { + this.ObsClienteEnabled = false; + this.ClientePorPaginaEnabled = false; + this.ComissaoDocumentoEnabled = false; + this.ObsApoliceEnabled = false; + this.BeneficiariosItensEnabled = false; + this.ObsItemEnabled = false; + this.SepararPaginaEnabled = false; + this.CoberturasEnabled = false; + this.PerfilCondutorEnabled = false; + this.EndossoEnabled = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ImpostoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ImpostoViewModel.cs new file mode 100644 index 0000000..e2ec7d5 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ImpostoViewModel.cs @@ -0,0 +1,484 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ImpostoViewModel : BaseViewModel + { + private bool _carregando; + + private bool _apelido; + + public int Tipo; + + private List _seguradoras; + + private List _ramos; + + private ObservableCollection _impostos = new ObservableCollection(); + + private Imposto _selectedImposto = new Imposto(); + + private Ramo _selectedRamo = new Ramo(); + + private Seguradora _selectedSeguradora = new Seguradora(); + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public bool? Ativo { get; set; } = new bool?(true); + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Impostos + { + get + { + return this._impostos; + } + set + { + this._impostos = value; + base.OnPropertyChanged("Impostos"); + } + } + + public List Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public List Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public Imposto SelectedImposto + { + get + { + return this._selectedImposto; + } + set + { + long? nullable; + this._selectedImposto = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedImposto"); + } + } + + public Ramo SelectedRamo + { + get + { + return this._selectedRamo; + } + set + { + this._selectedRamo = value; + base.OnPropertyChanged("SelectedRamo"); + } + } + + public Seguradora SelectedSeguradora + { + get + { + return this._selectedSeguradora; + } + set + { + this._selectedSeguradora = value; + base.OnPropertyChanged("SelectedSeguradora"); + } + } + + private ImpostoServico Servico + { + get; + } + + public ImpostoViewModel() + { + this.Servico = new ImpostoServico(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + } + + public void AlterarImposto() + { + base.Alterar(true); + } + + public async Task Cancelar() + { + long id; + Imposto selectedImposto = this.SelectedImposto; + if (selectedImposto != null) + { + id = selectedImposto.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + base.Alterar(false); + await this.Carregar(num); + } + + public async Task Carregar(int tipo, long id) + { + string str; + this.Tipo = tipo; + await base.PermissaoTela(56); + List list = Recursos.Seguradoras.Where((Seguradora x) => { + if (x.get_Ativo()) + { + return true; + } + if (tipo != 0) + { + return false; + } + return x.get_Id() == id; + }).OrderBy((Seguradora x) => { + if (!this.Apelido) + { + return x.get_Nome(); + } + return x.get_NomeSocial(); + }).ToList(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Nome("TODAS SEGURADORAS"); + seguradora.set_NomeSocial("TODAS SEGURADORAS"); + seguradora.set_Id((long)0); + list.Insert(0, seguradora); + this.Seguradoras = list; + this.SelectedSeguradora = this.Seguradoras.First(); + IEnumerable ramos = Recursos.Ramos.Where((Ramo x) => { + if (x.get_Ativo()) + { + return true; + } + if (tipo != 1) + { + return false; + } + return x.get_Id() == id; + }); + List list1 = ( + from x in ramos + orderby x.get_Nome() + select x).ToList(); + Ramo ramo = new Ramo(); + ramo.set_Nome("TODOS OS RAMOS"); + ramo.set_Id((long)0); + list1.Insert(0, ramo); + this.Ramos = list1; + this.SelectedRamo = this.Ramos.First(); + str = (tipo == 1 ? string.Concat("O RAMO \"", this.Ramos.First((Ramo x) => x.get_Id() == id).get_Nome(), "\"") : string.Concat("A SEGURADORA \"", this.Seguradoras.First((Seguradora x) => x.get_Id() == id).get_Nome(), "\"")); + string str1 = str; + base.RegistrarAcao(string.Concat("ACESSOU IMPOSTOS D", str1), id, new TipoTela?(56), string.Format("ID: {0}", id)); + List impostos = await this.Servico.Buscar(new bool?(true)); + if (tipo == 1) + { + impostos = impostos.Where((Imposto x) => { + if (x.get_Ramo() == null || x.get_Ramo().get_Id() != id) + { + return false; + } + return x.get_Seguradora() == null; + }).ToList(); + this.SelectedRamo = this.Ramos.Find((Ramo x) => x.get_Id() == id); + } + else + { + impostos = impostos.Where((Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != id) + { + return false; + } + return x.get_Ramo() == null; + }).ToList(); + this.SelectedSeguradora = this.Seguradoras.Find((Seguradora x) => x.get_Id() == id); + } + ImpostoViewModel observableCollection = this; + List impostos1 = impostos; + observableCollection.Impostos = new ObservableCollection( + from x in impostos1 + orderby x.get_Ativo() descending + select x); + this.SelectedImposto = this.Impostos.FirstOrDefault(); + } + + public async Task Carregar(long id = 0L) + { + Imposto imposto; + List list = await this.Servico.Buscar(this.Ativo); + if (this.SelectedSeguradora.get_Id() == 0) + { + List impostos = list; + list = ( + from x in impostos + where x.get_Seguradora() == null + select x).ToList(); + } + if (this.SelectedSeguradora.get_Id() > (long)0) + { + list = list.Where((Imposto x) => { + if (x.get_Seguradora() == null) + { + return false; + } + return x.get_Seguradora().get_Id() == this.SelectedSeguradora.get_Id(); + }).ToList(); + } + if (this.SelectedRamo.get_Id() == 0) + { + List impostos1 = list; + list = ( + from x in impostos1 + where x.get_Ramo() == null + select x).ToList(); + } + if (this.SelectedRamo.get_Id() > (long)0) + { + list = list.Where((Imposto x) => { + if (x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == this.SelectedRamo.get_Id(); + }).ToList(); + } + this.Impostos = new ObservableCollection(list.Where((Imposto x) => { + if (!this.Ativo.HasValue) + { + return true; + } + return x.get_Ativo() == this.Ativo.Value; + }).ToList()); + ImpostoViewModel impostoViewModel = this; + imposto = (id == 0 ? this.Impostos.FirstOrDefault() : this.Impostos.FirstOrDefault((Imposto x) => x.get_Id() == id)); + impostoViewModel.SelectedImposto = imposto; + } + + public void Incluir() + { + Seguradora selectedSeguradora; + Ramo selectedRamo; + Imposto imposto = new Imposto(); + if (this.SelectedSeguradora.get_Id() > (long)0) + { + selectedSeguradora = this.SelectedSeguradora; + } + else + { + selectedSeguradora = null; + } + imposto.set_Seguradora(selectedSeguradora); + if (this.SelectedRamo.get_Id() > (long)0) + { + selectedRamo = this.SelectedRamo; + } + else + { + selectedRamo = null; + } + imposto.set_Ramo(selectedRamo); + imposto.set_Ativo(true); + this.SelectedImposto = imposto; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + string str2; + object obj; + string str3; + List> keyValuePairs1 = this.SelectedImposto.Validate(); + keyValuePairs1.AddRange(this.Validate(this.SelectedImposto)); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedImposto.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str; + Imposto imposto = await this.Servico.Salvar(this.SelectedImposto); + if (this.Servico.Sucesso) + { + str1 = (imposto.get_Seguradora() == null ? "TODAS AS SEGURADORAS" : string.Concat(" SEGURADORA ", imposto.get_Seguradora().get_Nome())); + string str4 = str1; + str2 = (imposto.get_Ramo() == null ? "TODOS OS RAMOS" : string.Concat(" RAMO ", imposto.get_Ramo().get_Nome())); + string str5 = str2; + string str6 = string.Concat(" ", str4, " E ", str5); + ImpostoViewModel impostoViewModel = this; + string str7 = string.Concat(str3, " IMPOSTO PARA ", str6); + long id = imposto.get_Id(); + TipoTela? nullable = new TipoTela?(31); + object[] ir = new object[] { imposto.get_Id(), str4, str5, null, null, null, null, null }; + obj = (imposto.get_Ativo() ? "ATIVO" : "INATIVO"); + ir[3] = obj; + ir[4] = imposto.get_Ir(); + ir[5] = imposto.get_Iss(); + ir[6] = imposto.get_Outros(); + ir[7] = imposto.get_Desconto(); + impostoViewModel.RegistrarAcao(str7, id, nullable, string.Format("ID: {0}{1}{2}\nSTATUS: {3}\nIR: {4:p2}\nISS: {5:p2}\nOUTROS: {6:p2}\nDESCONTO: {7:p2}", ir)); + base.Alterar(false); + await this.Carregar(imposto.get_Id()); + keyValuePairs = null; + } + else + { + keyValuePairs = new List>() + { + new KeyValuePair("GRAVAR", "HOUVE UM ERRO AO SALVAR O IMPOSTO SELECIONADO.") + }; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + public List> Validate(Imposto imposto) + { + List> keyValuePairs = new List>(); + if (imposto == null) + { + return keyValuePairs; + } + if (imposto.get_Ativo() && this.Impostos.Any((Imposto x) => { + long? nullable; + long? nullable1; + long? nullable2; + long? nullable3; + long? nullable4; + if (x.get_Id() != imposto.get_Id()) + { + Seguradora seguradora = x.get_Seguradora(); + if (seguradora != null) + { + nullable1 = new long?(seguradora.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable5 = nullable1; + Seguradora seguradora1 = imposto.get_Seguradora(); + if (seguradora1 != null) + { + nullable2 = new long?(seguradora1.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + long? nullable6 = nullable2; + if (nullable5.GetValueOrDefault() == nullable6.GetValueOrDefault() & nullable5.HasValue == nullable6.HasValue) + { + Ramo ramo = x.get_Ramo(); + if (ramo != null) + { + nullable3 = new long?(ramo.get_Id()); + } + else + { + nullable = null; + nullable3 = nullable; + } + nullable6 = nullable3; + Ramo ramo1 = imposto.get_Ramo(); + if (ramo1 != null) + { + nullable4 = new long?(ramo1.get_Id()); + } + else + { + nullable = null; + nullable4 = nullable; + } + nullable5 = nullable4; + if (nullable6.GetValueOrDefault() == nullable5.GetValueOrDefault() & nullable6.HasValue == nullable5.HasValue) + { + return x.get_Ativo(); + } + } + } + return false; + })) + { + keyValuePairs.Add(new KeyValuePair("IMPOSTO DUPLICADO", "NÃO É POSSIVEL INSERIR UM NOVO PARAMETRO DE IMPOSTO, POIS JÁ EXISTEM PARAMETROS PARA A MESMA SEGURADORA E RAMO")); + } + return keyValuePairs.Distinct>().ToList>(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/InfoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/InfoViewModel.cs new file mode 100644 index 0000000..1352f12 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/InfoViewModel.cs @@ -0,0 +1,208 @@ +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class InfoViewModel : BaseViewModel + { + private ObservableCollection _contatos = new ObservableCollection(); + + private ObservableCollection _itens = new ObservableCollection(); + + private ObservableCollection _parcelas = new ObservableCollection(); + + private Gestor.Model.Domain.Seguros.Documento _documento; + + private Visibility _ocultarInfos; + + private bool _carregando; + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Contatos + { + get + { + return this._contatos; + } + set + { + this._contatos = value; + base.OnPropertyChanged("Contatos"); + } + } + + public Gestor.Model.Domain.Seguros.Documento Documento + { + get + { + return this._documento; + } + set + { + this._documento = value; + base.OnPropertyChanged("Documento"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public Visibility OcultarInfos + { + get + { + return this._ocultarInfos; + } + set + { + this._ocultarInfos = value; + base.OnPropertyChanged("OcultarInfos"); + } + } + + public ObservableCollection Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + base.OnPropertyChanged("Parcelas"); + } + } + + public InfoViewModel(Gestor.Model.Domain.Seguros.Documento documento, bool ocultarInfos) + { + this.Documento = documento; + this.OcultarInfos = (ocultarInfos ? Visibility.Collapsed : Visibility.Visible); + this.Seleciona(); + } + + public string GerarObs(Gestor.Model.Domain.Seguros.Documento doc) + { + if (doc.get_Tipo() == 0) + { + return string.Format("CLIENTE: {0}{1}CÓDIGO: {2}{3}PROPOSTA: {4}{5}APÓLICE: {6}", new object[] { doc.get_Controle().get_Cliente().get_Nome(), Environment.NewLine, doc.get_Id(), Environment.NewLine, doc.get_Proposta(), Environment.NewLine, doc.get_Apolice() }); + } + return string.Format("CLIENTE: {0}{1}CÓDIGO: {2}{3}PROPOSTA: {4}{5}APÓLICE: {6}{7}PROPOSTA DE ENDOSSO: {8}{9}ENDOSSO: {10}", new object[] { doc.get_Controle().get_Cliente().get_Nome(), Environment.NewLine, doc.get_Id(), Environment.NewLine, doc.get_Proposta(), Environment.NewLine, doc.get_Apolice(), Environment.NewLine, doc.get_PropostaEndosso(), Environment.NewLine, doc.get_Endosso() }); + } + + public async void Seleciona() + { + bool controle; + ObservableCollection observableCollection; + this.Carregando = true; + if (this.Documento != null) + { + this.Documento = await (new ApoliceServico()).BuscarApoliceAsync(this.Documento.get_Id(), false, false); + } + if (this.OcultarInfos == Visibility.Visible && this.Documento != null) + { + ObservableCollection observableCollection1 = await (new ParcelaServico()).BuscarParcelasAsync(this.Documento.get_Id()); + InfoViewModel infoViewModel = this; + if (this.Documento.get_TipoRecebimento().GetValueOrDefault() == 2) + { + ObservableCollection observableCollection2 = observableCollection1; + observableCollection = new ObservableCollection( + from x in observableCollection2 + orderby x.get_VigenciaIncial() descending + select x); + } + else + { + observableCollection = observableCollection1; + } + infoViewModel.Parcelas = observableCollection; + } + Gestor.Model.Domain.Seguros.Documento documento = this.Documento; + if (documento != null) + { + controle = documento.get_Controle(); + } + else + { + controle = false; + } + if (controle) + { + this.Itens = await (new ItemServico()).BuscarItens(this.Documento.get_Controle().get_Id(), 0); + List contatos = new List(); + ClienteServico clienteServico = new ClienteServico(); + if (this.Documento.get_Controle().get_Cliente() != null) + { + ObservableCollection observableCollection3 = await clienteServico.BuscarTelefonesAsync(this.Documento.get_Controle().get_Cliente().get_Id()); + ObservableCollection observableCollection4 = await clienteServico.BuscarEmailsAsync(this.Documento.get_Controle().get_Cliente().get_Id()); + if (observableCollection3 != null) + { + List contatos1 = contatos; + ObservableCollection observableCollection5 = observableCollection3; + contatos1.AddRange(observableCollection5.Select((ClienteTelefone x) => { + Contato contato = new Contato(); + contato.set_Tipo(0); + contato.set_TipoTelefone(new TipoTelefone?(x.get_Tipo().GetValueOrDefault(1))); + contato.set_Numero(string.Concat(x.get_Prefixo(), " ", x.get_Numero())); + return contato; + }).Take(2).ToList()); + } + if (observableCollection4 != null) + { + List contatos2 = contatos; + ObservableCollection observableCollection6 = observableCollection4; + contatos2.AddRange(observableCollection6.Select((ClienteEmail x) => { + Contato contato = new Contato(); + contato.set_Tipo(1); + contato.set_TipoTelefone(null); + contato.set_Numero(x.get_Email()); + return contato; + }).Take(1).ToList()); + } + observableCollection3 = null; + } + this.Contatos = new ObservableCollection(contatos); + contatos = null; + clienteServico = null; + } + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/LogAcaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/LogAcaoViewModel.cs new file mode 100644 index 0000000..dec7ea3 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/LogAcaoViewModel.cs @@ -0,0 +1,262 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +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 Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class LogAcaoViewModel : BaseViewModel + { + private RegistroAcao _log; + + private string _obs; + + public RegistroAcao Log + { + get + { + return this._log; + } + set + { + this._log = value; + base.OnPropertyChanged("Log"); + } + } + + public string Obs + { + get + { + return this._obs; + } + set + { + this._obs = value; + base.OnPropertyChanged("Obs"); + } + } + + private Gestor.Model.Common.Relatorio Relatorio + { + get; + set; + } + + public LogAcaoViewModel(RegistroAcao registro, Gestor.Model.Common.Relatorio relatorio) + { + this.Relatorio = relatorio; + this.CarregarLog(registro); + } + + private void CarregarLog(RegistroAcao registro) + { + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + string str8; + string str9; + string str10; + if (registro.get_Tela().HasValue || string.IsNullOrEmpty(registro.get_Observacao()) || this.Relatorio == 25) + { + this.Log = registro; + this.Obs = registro.get_Observacao(); + return; + } + this.Log = registro; + Filtros filtro = JsonConvert.DeserializeObject(registro.get_Observacao()); + if (filtro.get_Seguradoras() == null || filtro.get_Seguradoras().Count == 0) + { + str = ""; + } + else + { + string[] newLine = new string[] { "SEGURADORAS FILTRADAS: ", Environment.NewLine, null, null, null }; + newLine[2] = string.Join(Environment.NewLine, + from x in Recursos.Seguradoras + where filtro.get_Seguradoras().Contains(x.get_Id()) + select x.get_NomeSocial()); + newLine[3] = Environment.NewLine; + newLine[4] = Environment.NewLine; + str = string.Concat(newLine); + } + string str11 = str; + if (filtro.get_Status() == null || filtro.get_Status().Count == 0) + { + str1 = ""; + } + else + { + string[] strArrays = new string[] { "STATUS FILTRADOS: ", Environment.NewLine, null, null, null }; + strArrays[2] = string.Join(Environment.NewLine, + from x in filtro.get_Status() + select (int)x); + strArrays[3] = Environment.NewLine; + strArrays[4] = Environment.NewLine; + str1 = string.Concat(strArrays); + } + string str12 = str1; + if (filtro.get_Ramos() == null || filtro.get_Ramos().Count == 0) + { + str2 = ""; + } + else + { + string[] newLine1 = new string[] { "RAMOS FILTRADOS: ", Environment.NewLine, null, null, null }; + newLine1[2] = string.Join(Environment.NewLine, + from x in Recursos.Ramos + where filtro.get_Ramos().Contains(x.get_Id()) + select x.get_Nome()); + newLine1[3] = Environment.NewLine; + newLine1[4] = Environment.NewLine; + str2 = string.Concat(newLine1); + } + string str13 = str2; + if (filtro.get_Vendedores() == null || filtro.get_Vendedores().Count == 0) + { + str3 = ""; + } + else + { + string[] strArrays1 = new string[] { "VENDEDORES FILTRADOS: ", Environment.NewLine, null, null, null }; + strArrays1[2] = string.Join(Environment.NewLine, + from x in Recursos.Vendedores + where filtro.get_Vendedores().Contains(x.get_Id()) + select x.get_Nome()); + strArrays1[3] = Environment.NewLine; + strArrays1[4] = Environment.NewLine; + str3 = string.Concat(strArrays1); + } + string str14 = str3; + if (filtro.get_Estipulantes() == null || filtro.get_Estipulantes().Count == 0) + { + str4 = ""; + } + else + { + string[] newLine2 = new string[] { "ESTIPULANTES FILTRADOS: ", Environment.NewLine, null, null, null }; + newLine2[2] = string.Join(Environment.NewLine, + from x in Recursos.Estipulantes + where filtro.get_Estipulantes().Contains(x.get_Id()) + select x.get_Nome()); + newLine2[3] = Environment.NewLine; + newLine2[4] = Environment.NewLine; + str4 = string.Concat(newLine2); + } + string str15 = str4; + if (filtro.get_Produtos() == null || filtro.get_Produtos().Count == 0) + { + str5 = ""; + } + else + { + string[] strArrays2 = new string[] { "PRODUTOS FILTRADOS: ", Environment.NewLine, null, null, null }; + strArrays2[2] = string.Join(Environment.NewLine, + from x in Recursos.Produtos + where filtro.get_Produtos().Contains(x.get_Id()) + select x.get_Nome()); + strArrays2[3] = Environment.NewLine; + strArrays2[4] = Environment.NewLine; + str5 = string.Concat(strArrays2); + } + string str16 = str5; + if (filtro.get_Negocio() == null || filtro.get_Negocio().Count == 0) + { + str6 = ""; + } + else + { + string[] newLine3 = new string[] { "TIPOS DE NEGÓCIOS FILTRADOS: ", Environment.NewLine, null, null, null }; + newLine3[2] = string.Join(Environment.NewLine, + from x in filtro.get_Negocio() + select (int)x); + newLine3[3] = Environment.NewLine; + newLine3[4] = Environment.NewLine; + str6 = string.Concat(newLine3); + } + string str17 = str6; + if (filtro.get_Usuarios() == null || filtro.get_Usuarios().Count == 0) + { + str7 = ""; + } + else + { + string[] strArrays3 = new string[] { "USUÁRIOS FILTRADOS: ", Environment.NewLine, null, null, null }; + strArrays3[2] = string.Join(Environment.NewLine, + from x in Recursos.Usuarios + where filtro.get_Usuarios().Contains(x.get_Id()) + select x.get_Nome()); + strArrays3[3] = Environment.NewLine; + strArrays3[4] = Environment.NewLine; + str7 = string.Concat(strArrays3); + } + string str18 = str7; + if (filtro.get_Telas() == null || filtro.get_Telas().Count == 0) + { + str8 = ""; + } + else + { + string[] newLine4 = new string[] { "TELAS FILTRADAS: ", Environment.NewLine, null, null, null }; + newLine4[2] = string.Join(Environment.NewLine, + from x in filtro.get_Telas() + select (int)x); + newLine4[3] = Environment.NewLine; + newLine4[4] = Environment.NewLine; + str8 = string.Concat(newLine4); + } + string str19 = str8; + if (filtro.get_Relatorios() == null || filtro.get_Relatorios().Count == 0) + { + str9 = ""; + } + else + { + string[] strArrays4 = new string[] { "RELATÓRIOS FILTRADOS: ", Environment.NewLine, null, null, null }; + strArrays4[2] = string.Join(Environment.NewLine, + from x in filtro.get_Relatorios() + select (int)x); + strArrays4[3] = Environment.NewLine; + strArrays4[4] = Environment.NewLine; + str9 = string.Concat(strArrays4); + } + string str20 = str9; + if (filtro.get_ParcelasEspeciais() != null) + { + if (!filtro.get_ParcelasEspeciais().Any((FiltroTipoParcela x) => x.get_Selecionado())) + { + goto Label1; + } + string[] newLine5 = new string[] { "TIPOS DE PARCELAS FILTRADOS: ", Environment.NewLine, null, null, null }; + newLine5[2] = string.Join(Environment.NewLine, + from x in filtro.get_ParcelasEspeciais() + select x.get_Tipo()); + newLine5[3] = Environment.NewLine; + newLine5[4] = Environment.NewLine; + str10 = string.Concat(newLine5); + goto Label0; + } + Label1: + str10 = ""; + Label0: + string str21 = str10; + string str22 = (filtro.get_IdEmpresa() == 0 ? "" : string.Concat(new string[] { "EMPRESA: ", Environment.NewLine, Recursos.Empresas.Find((Empresa x) => x.get_Id() == filtro.get_IdEmpresa()).get_Nome(), Environment.NewLine, Environment.NewLine })); + string.Format("PERÍODO DE {0:d} ATÉ {1:d}", filtro.get_Inicio(), filtro.get_Fim()); + this.Obs = string.Concat(new string[] { ValidationHelper.GetDescription(registro.get_Relatorio()), Environment.NewLine, Environment.NewLine, str22, str11, str13, str16, str14, str15, str12, str17, str21, str18, str19, str20 }); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/LogEmailViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/LogEmailViewModel.cs new file mode 100644 index 0000000..8a71635 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/LogEmailViewModel.cs @@ -0,0 +1,163 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class LogEmailViewModel : BaseSegurosViewModel + { + private readonly LogServico _servico; + + private Visibility _visibilityDetalhesLog = Visibility.Hidden; + + private bool _mostrarMensagem; + + private ObservableCollection _logs = new ObservableCollection(); + + private LogEmail _selectedLog; + + private List _lists = new List(); + + public List Lists + { + get + { + return this._lists; + } + set + { + this._lists = value; + base.OnPropertyChanged("Lists"); + } + } + + public ObservableCollection Logs + { + get + { + return this._logs; + } + set + { + this._logs = value; + base.OnPropertyChanged("Logs"); + } + } + + public bool MostrarMensagem + { + get + { + return this._mostrarMensagem; + } + set + { + this._mostrarMensagem = value; + base.OnPropertyChanged("MostrarMensagem"); + } + } + + public LogEmail SelectedLog + { + get + { + return this._selectedLog; + } + set + { + this._selectedLog = value; + this.Lists = this.SelectedLog.CriarLogEmail(); + base.OnPropertyChanged("SelectedLog"); + } + } + + public Visibility VisiblityDetalhesLog + { + get + { + return this._visibilityDetalhesLog; + } + set + { + this._visibilityDetalhesLog = value; + base.OnPropertyChanged("VisiblityDetalhesLog"); + } + } + + public LogEmailViewModel(TipoTela tela, long id, bool singleMode) + { + this._servico = new LogServico(); + this.VisiblityDetalhesLog = (Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 55) ? Visibility.Visible : Visibility.Hidden); + this.Seleciona(tela, id, singleMode); + } + + public void Imprimir() + { + string str = "LOGS
LOG ENVIO DE E-MAIL"; + foreach (TupleList list in this.Lists) + { + foreach (Tuple tuple in list.get_Tuples()) + { + if (tuple == list.get_Tuples().First>()) + { + str = string.Concat(str, ""); + str = string.Concat(str, "
DESCRIÇÃOE-MAIL ENVIADO
"); + } + bool flag = tuple.Item1.Contains("$"); + string[] item2 = new string[] { str, ""; + str = string.Concat(item2); + str = string.Concat(str, "
"; + item2[4] = tuple.Item1.Replace(" ", " ").Replace("$", ""); + item2[5] = ""; + item2[6] = tuple.Item2; + item2[7] = "
"); + } + } + str = string.Concat(str, "
"); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + } + + private async void Seleciona(TipoTela tela, long id, bool singleMode) + { + base.Loading(true); + if (!singleMode) + { + this.Logs = await this._servico.FindByEntity(tela, id); + } + else + { + this.Logs = await this._servico.FindById(id); + } + if (this.Logs.Count <= 0) + { + this.MostrarMensagem = true; + } + else + { + this.SelectedLog = this.Logs[0]; + } + base.Loading(false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/LogSistemaAntigoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/LogSistemaAntigoViewModel.cs new file mode 100644 index 0000000..5c97aca --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/LogSistemaAntigoViewModel.cs @@ -0,0 +1,42 @@ +using Gestor.Application.ViewModels.Generic; +using System; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class LogSistemaAntigoViewModel : BaseViewModel + { + private string _descricao; + + private string _log; + + public string Descricao + { + get + { + return this._descricao; + } + set + { + this._descricao = value; + base.OnPropertyChanged("Descricao"); + } + } + + public string Log + { + get + { + return this._log; + } + set + { + this._log = value; + base.OnPropertyChanged("Log"); + } + } + + public LogSistemaAntigoViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/LogViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/LogViewModel.cs new file mode 100644 index 0000000..cdeb60c --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/LogViewModel.cs @@ -0,0 +1,1784 @@ +using ControlzEx; +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Validation; +using MaterialDesignThemes.Wpf; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class LogViewModel : BaseSegurosViewModel + { + private readonly LogServico _servico; + + private readonly TipoTela _tipoTela; + + private readonly long _id; + + private Visibility _visibilityDetalhesLog = Visibility.Hidden; + + private bool _mostrar; + + private bool _mostrarMensagem; + + private string _mostrarToolTip = "MOSTRAR TODAS OS CAMPOS"; + + private long _mostrarColuna = (long)120; + + private PackIcon _mostrarIcone; + + private ObservableCollection _logs; + + private string _currentDescription; + + private RegistroLog _selectedLog; + + private List _lists; + + private ObservableCollection _listsAlterados; + + private ObservableCollection _listsAdicionados; + + private ObservableCollection _listsRemovidos; + + private string _textAdicoes; + + public string CurrentDescription + { + get + { + return this._currentDescription; + } + set + { + this._currentDescription = value; + base.OnPropertyChanged("CurrentDescription"); + } + } + + public List Lists + { + get + { + return this._lists; + } + set + { + this._lists = value; + this.SetListaFiltrada(value); + base.OnPropertyChanged("Lists"); + } + } + + public ObservableCollection ListsAdicionados + { + get + { + return this._listsAdicionados; + } + set + { + this._listsAdicionados = value; + base.OnPropertyChanged("ListsAdicionados"); + } + } + + public ObservableCollection ListsAlterados + { + get + { + return this._listsAlterados; + } + set + { + this._listsAlterados = value; + base.OnPropertyChanged("ListsAlterados"); + } + } + + public ObservableCollection ListsRemovidos + { + get + { + return this._listsRemovidos; + } + set + { + this._listsRemovidos = value; + if (this.ListsAlterados != null || this.ListsAdicionados != null || value != null) + { + this.MostrarMensagem = false; + } + else + { + this.MostrarMensagem = true; + } + base.OnPropertyChanged("ListsRemovidos"); + } + } + + public ObservableCollection Logs + { + get + { + return this._logs; + } + set + { + this._logs = value; + base.OnPropertyChanged("Logs"); + } + } + + public bool Mostrar + { + get + { + return this._mostrar; + } + set + { + this._mostrar = value; + if (!value) + { + this.MostrarColuna = (long)240; + this.MostrarToolTip = "MOSTRAR TODOS OS CAMPOS"; + PackIcon packIcon = new PackIcon(); + packIcon.set_Kind(1497); + this.MostrarIcone = packIcon; + } + else + { + this.MostrarColuna = (long)240; + this.MostrarToolTip = "ESCONDER CAMPOS INALTERADOS"; + PackIcon packIcon1 = new PackIcon(); + packIcon1.set_Kind(1492); + this.MostrarIcone = packIcon1; + } + base.OnPropertyChanged("Mostrar"); + } + } + + public long MostrarColuna + { + get + { + return this._mostrarColuna; + } + set + { + this._mostrarColuna = value; + base.OnPropertyChanged("MostrarColuna"); + } + } + + public PackIcon MostrarIcone + { + get + { + return this._mostrarIcone; + } + set + { + this._mostrarIcone = value; + base.OnPropertyChanged("MostrarIcone"); + } + } + + public bool MostrarMensagem + { + get + { + return this._mostrarMensagem; + } + set + { + this._mostrarMensagem = value; + base.OnPropertyChanged("MostrarMensagem"); + } + } + + public string MostrarToolTip + { + get + { + return this._mostrarToolTip; + } + set + { + this._mostrarToolTip = value; + base.OnPropertyChanged("MostrarToolTip"); + } + } + + public RegistroLog SelectedLog + { + get + { + return this._selectedLog; + } + set + { + List tupleLists; + ObservableCollection> observableCollection; + List.Enumerator enumerator; + this._selectedLog = value; + List tupleLists1 = new List(); + try + { + if (!value.get_ModeloNovo()) + { + switch (this._tipoTela) + { + case 1: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 2: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(base.Restricao(14)); + break; + } + case 3: + { + Item item = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()); + if (item.get_Aeronautico() != null) + { + tupleLists1 = Aeronautico.Log(item); + break; + } + else if (item.get_Auto() != null) + { + tupleLists1 = Auto.Log(item); + break; + } + else if (item.get_Granizo() != null) + { + tupleLists1 = Granizo.Log(item); + break; + } + else if (item.get_Patrimonial() != null) + { + tupleLists1 = Patrimonial.Log(item); + break; + } + else if (item.get_RiscosDiversos() == null) + { + if (item.get_Vida() == null) + { + break; + } + tupleLists1 = Vida.Log(item); + break; + } + else + { + tupleLists1 = RiscosDiversos.Log(item); + break; + } + } + case 4: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 5: + { + try + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(base.Restricao(14), base.Restricao(95)); + break; + } + catch + { + tupleLists1 = LogViewModel.DefaultLog(this.SelectedLog.get_Descricao(), this.SelectedLog.get_Acao()); + break; + } + break; + } + case 6: + case 8: + case 20: + case 21: + case 23: + case 25: + case 27: + case 32: + case 35: + case 39: + case 40: + case 44: + case 47: + case 49: + case 50: + case 51: + case 53: + { + tupleLists1 = LogViewModel.DefaultLog(this.SelectedLog.get_Descricao(), this.SelectedLog.get_Acao()); + break; + } + case 7: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 9: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 10: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 11: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 12: + { + Ramo ramo = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()); + List list = ( + from x in Recursos.Coberturas + where x.get_IdRamo() == ramo.get_Id() + orderby x.get_Padrao() descending, x.get_Descricao() + select x).ToList(); + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(list); + break; + } + case 13: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 14: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 15: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 16: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 17: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 18: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 19: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 22: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 24: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 26: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 28: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 29: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 30: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 31: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 33: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 34: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 36: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 37: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(base.Restricao(14), base.Restricao(95)); + break; + } + case 38: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 41: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 42: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 43: + { + List>>>>> tuples = JsonConvert.DeserializeObject>>>>>>(this.SelectedLog.get_Descricao()); + tupleLists = new List(); + foreach (Tuple>>>> tuple in tuples) + { + observableCollection = new ObservableCollection>() + { + new Tuple(string.Concat(tuple.Item1, "$"), "", "") + }; + foreach (Tuple>> item2 in tuple.Item2) + { + observableCollection.Add(new Tuple(string.Concat(" ", item2.Item1, "$"), "", "")); + foreach (Tuple item21 in item2.Item2) + { + observableCollection.Add(new Tuple(string.Concat(" ", item21.Item1), item21.Item2, "")); + } + } + TupleList tupleList = new TupleList(); + tupleList.set_Tuples(observableCollection); + tupleLists.Add(tupleList); + } + enumerator = tupleLists.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + tupleLists1.Add(enumerator.Current); + } + break; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + break; + } + case 45: + { + List vendedors = JsonConvert.DeserializeObject>(this.SelectedLog.get_Descricao()); + tupleLists = new List(); + observableCollection = new ObservableCollection>() + { + new Tuple("VENDEDORES VINCULADOS$", "", "") + }; + foreach (Vendedor vendedor in vendedors) + { + observableCollection.Add(new Tuple(string.Format(" VENDEDOR {0}", vendedors.IndexOf(vendedor) + 1), vendedor.get_Nome(), "")); + } + TupleList tupleList1 = new TupleList(); + tupleList1.set_Tuples(observableCollection); + tupleLists.Add(tupleList1); + enumerator = tupleLists.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + tupleLists1.Add(enumerator.Current); + } + break; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + break; + } + case 46: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 48: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 52: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 54: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 55: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + case 56: + { + tupleLists1 = JsonConvert.DeserializeObject(this.SelectedLog.get_Descricao()).Log(); + break; + } + default: + { + goto case 53; + } + } + } + else + { + switch (value.get_Acao()) + { + case 0: + case 2: + { + tupleLists1 = JsonConvert.DeserializeObject>(this.SelectedLog.get_Descricao()).LogList(base.Restricao(14)); + break; + } + case 1: + { + tupleLists1 = JsonConvert.DeserializeObject>(this.SelectedLog.get_Descricao()).LogList(base.Restricao(14)); + break; + } + } + } + } + catch (Exception exception) + { + } + this.Lists = tupleLists1; + base.OnPropertyChanged("SelectedLog"); + } + } + + public string TextAdicoes + { + get + { + return this._textAdicoes; + } + set + { + this._textAdicoes = value; + base.OnPropertyChanged("TextAdicoes"); + } + } + + public Visibility VisiblityDetalhesLog + { + get + { + return this._visibilityDetalhesLog; + } + set + { + this._visibilityDetalhesLog = value; + base.OnPropertyChanged("VisiblityDetalhesLog"); + } + } + + public LogViewModel(TipoTela tela, long id, List parcelas = null, int numparcela = 0) + { + this._visibilityDetalhesLog = Visibility.Hidden; + this._mostrarToolTip = "MOSTRAR TODAS OS CAMPOS"; + this._mostrarColuna = (long)120; + PackIcon packIcon = new PackIcon(); + packIcon.set_Kind(1497); + this._mostrarIcone = packIcon; + this._logs = new ObservableCollection(); + this._currentDescription = ""; + this._lists = new List(); + this._listsAlterados = new ObservableCollection(); + this._listsAdicionados = new ObservableCollection(); + this._listsRemovidos = new ObservableCollection(); + this._textAdicoes = "INCLUSÃO"; + base(); + this._servico = new LogServico(); + this._tipoTela = tela; + this._id = id; + this.VisiblityDetalhesLog = (Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 55) ? Visibility.Visible : Visibility.Hidden); + base.EnableMenu = true; + if (parcelas != null) + { + this.LogParcelas(id, parcelas, numparcela); + return; + } + this.Seleciona(tela, id, null, null); + } + + public int BuscaNumeroParcela(string json) + { + int num; + int num1; + try + { + string[] strArrays = json.Split(new char[] { '}' }).FirstOrDefault((string x) => x.Contains("NumeroParcela")).Split(new char[] { ':' }); + num1 = (int.TryParse(strArrays[(int)strArrays.Length - 1].Replace("\"", ""), out num) ? num : 0); + } + catch + { + num1 = 0; + } + return num1; + } + + private static List DefaultLog(string log, TipoAcao acao) + { + List tupleLists = new List(); + TupleList tupleList = new TupleList(); + tupleList.set_Tuples(new ObservableCollection>() + { + new Tuple(Gestor.Model.Validation.Funcoes.GetDescription(acao), log, "") + }); + tupleLists.Add(tupleList); + return tupleLists; + } + + public void Imprimir() + { + bool count; + bool flag; + bool count1; + bool flag1; + bool count2; + bool flag2; + string str = "LOGS
"; + ObservableCollection listsAlterados = this.ListsAlterados; + if (listsAlterados != null) + { + count = listsAlterados.Count > 0; + } + else + { + count = false; + } + if (count) + { + str = string.Concat(str, "ALTERAÇÃO"); + } + if (this.ListsAlterados != null) + { + foreach (TupleList listsAlterado in this.ListsAlterados) + { + foreach (Tuple tuple in listsAlterado.get_Tuples()) + { + if (tuple == listsAlterado.get_Tuples().First>()) + { + str = string.Concat(str, ""); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
DESCRIÇÃOVALOR LOG SELECIONADOVALOR LOG ANTERIOR
"); + } + bool flag3 = tuple.Item1.Contains("$"); + string[] item2 = new string[] { str, ""; + str = string.Concat(item2); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
"; + item2[4] = tuple.Item1.Replace(" ", " ").Replace("$", ""); + item2[5] = ""; + item2[8] = tuple.Item2; + item2[9] = "", tuple.Item3, "
"); + } + if ((object)listsAlterado == (object)this.ListsAlterados.Last()) + { + continue; + } + str = string.Concat(str, "
"); + } + } + ObservableCollection listsAdicionados = this.ListsAdicionados; + if (listsAdicionados != null) + { + flag = listsAdicionados.Count > 0; + } + else + { + flag = false; + } + if (flag) + { + ObservableCollection observableCollection = this.ListsAlterados; + if (observableCollection != null) + { + flag2 = observableCollection.Count > 0; + } + else + { + flag2 = false; + } + if (flag2) + { + str = string.Concat(str, "


"); + } + str = string.Concat(str, "INCLUSÃO"); + } + if (this.ListsAdicionados != null) + { + foreach (TupleList listsAdicionado in this.ListsAdicionados) + { + foreach (Tuple tuple1 in listsAdicionado.get_Tuples()) + { + if (tuple1 == listsAdicionado.get_Tuples().First>()) + { + str = string.Concat(str, ""); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
DESCRIÇÃOVALOR LOG SELECIONADOVALOR LOG ANTERIOR
"); + } + bool flag4 = tuple1.Item1.Contains("$"); + string[] strArrays = new string[] { str, ""; + str = string.Concat(strArrays); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
"; + strArrays[4] = tuple1.Item1.Replace(" ", " ").Replace("$", ""); + strArrays[5] = ""; + strArrays[8] = tuple1.Item2; + strArrays[9] = "", tuple1.Item3, "
"); + } + if ((object)listsAdicionado == (object)this.ListsAdicionados.Last()) + { + continue; + } + str = string.Concat(str, "
"); + } + } + ObservableCollection listsRemovidos = this.ListsRemovidos; + if (listsRemovidos != null) + { + count1 = listsRemovidos.Count > 0; + } + else + { + count1 = false; + } + if (count1) + { + ObservableCollection listsAlterados1 = this.ListsAlterados; + if (listsAlterados1 != null) + { + flag1 = listsAlterados1.Count > 0; + } + else + { + flag1 = false; + } + if (!flag1) + { + ObservableCollection listsAdicionados1 = this.ListsAdicionados; + if (listsAdicionados1 != null) + { + count2 = listsAdicionados1.Count > 0; + } + else + { + count2 = false; + } + if (!count2) + { + goto Label0; + } + } + str = string.Concat(str, "


"); + Label0: + str = string.Concat(str, "EXCLUSÃO"); + } + if (this.ListsRemovidos != null) + { + foreach (TupleList listsRemovido in this.ListsRemovidos) + { + foreach (Tuple tuple2 in listsRemovido.get_Tuples()) + { + if (tuple2 == listsRemovido.get_Tuples().First>()) + { + str = string.Concat(str, ""); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
DESCRIÇÃOVALOR LOG SELECIONADOVALOR LOG ANTERIOR
"); + } + bool flag5 = tuple2.Item1.Contains("$"); + string[] item21 = new string[] { str, ""; + str = string.Concat(item21); + if (!this.Mostrar) + { + str = string.Concat(str, ""); + } + str = string.Concat(str, "
"; + item21[4] = tuple2.Item1.Replace(" ", " ").Replace("$", ""); + item21[5] = ""; + item21[8] = tuple2.Item2; + item21[9] = "", tuple2.Item3, "
"); + } + if ((object)listsRemovido == (object)this.ListsRemovidos.Last()) + { + continue; + } + str = string.Concat(str, "
"); + } + } + str = string.Concat(str, "
"); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, Gestor.Application.Helpers.Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + base.RegistrarAcao(string.Format("IMPRIMIU O LOG DE ALTERAÇÕES DE {0} DO ID \"{1}\"", Gestor.Model.Validation.Funcoes.GetDescription(this._tipoTela), this._id), this._id, new TipoTela?(this._tipoTela), string.Format("ID ENTIDADE: {0}\nTIPO: {1}", this._id, Gestor.Model.Validation.Funcoes.GetDescription(this._tipoTela))); + } + + private async void LogParcelas(long documento, List parcelas, int numparcela) + { + base.Loading(true); + List nums = new List(); + nums.AddRange(parcelas); + nums.Add(documento); + this.Logs = new ObservableCollection((IEnumerable)await this._servico.BuscaLogParcelas(nums)); + ObservableCollection observableCollection = new ObservableCollection(); + List list = this.Logs.Where((RegistroLog x) => { + if (x.get_ModeloNovo()) + { + return false; + } + return x.get_EntidadeId() == documento; + }).ToList(); + for (int i = list.Count - 1; i >= 0; i--) + { + ObservableCollection observableCollection1 = new ObservableCollection(); + try + { + for (int j = i; j >= 0 && list[j].get_DataHora() < list[i].get_DataHora().AddSeconds(4); j--) + { + Parcela parcela = JsonConvert.DeserializeObject(this.Logs[j].get_Descricao()); + if (parcela != null && (numparcela == 0 || this.BuscaNumeroParcela(this.Logs[j].get_Descricao()) == numparcela)) + { + observableCollection1.Add(parcela); + } + i = j; + } + } + catch (Exception exception1) + { + try + { + List parcelas1 = JsonConvert.DeserializeObject>(this.Logs[i].get_Descricao()); + if (parcelas1 != null && (numparcela == 0 || this.BuscaNumeroParcela(this.Logs[i].get_Descricao()) == numparcela)) + { + ExtensionMethods.AddRange(observableCollection1, parcelas1); + } + } + catch (Exception exception) + { + RegistroLog item = this.Logs[i]; + string descricao = this.Logs[i].get_Descricao(); + if (descricao == null) + { + descricao = ""; + } + item.set_Descricao(descricao); + observableCollection.Insert(0, this.Logs[i]); + goto Label0; + } + } + ObservableCollection observableCollection2 = observableCollection1; + observableCollection1 = new ObservableCollection( + from x in observableCollection2 + orderby x.get_NumeroParcela() + select x); + if (observableCollection1 != null && observableCollection1.Count != 0 && observableCollection1[0].get_Documento() != null) + { + RegistroLog registroLog = list[i]; + Parcelas parcela1 = new Parcelas(); + parcela1.set_ParcelasList(observableCollection1); + parcela1.set_TipoRecebimento(observableCollection1[0].get_Documento().get_TipoRecebimento()); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(parcela1, jsonSerializerSetting)); + observableCollection.Insert(0, list[i]); + } + Label0: + } + List registroLogs = new List(); + ObservableCollection logs = this.Logs; + List list1 = ( + from x in logs + where x.get_ModeloNovo() + select x).ToList(); + if (numparcela != 0) + { + foreach (RegistroLog registroLog1 in list1) + { + int num = this.BuscaNumeroParcela(registroLog1.get_Descricao()); + if ((num == 0 || num != numparcela) && (numparcela == 0 || parcelas.Count != 1 || registroLog1.get_EntidadeId() == documento)) + { + continue; + } + registroLogs.Add(registroLog1); + } + } + else + { + registroLogs.AddRange(list1); + } + this.Logs = observableCollection; + ExtensionMethods.AddRange(this.Logs, registroLogs); + if (this.Logs.Count <= 0) + { + this.SetListaFiltrada(this.Lists); + } + else + { + this.SelectedLog = this.Logs[0]; + } + base.Loading(false); + } + + public void MostrarCampos() + { + if (this.SelectedLog == null || this.SelectedLog.get_ModeloNovo()) + { + return; + } + this.Mostrar = !this.Mostrar; + this.Lists = this.Lists; + } + + private static int QntEspaco(string str) + { + return Regex.Match(str, "[^\\s]").Index; + } + + private async void Seleciona(TipoTela tela, long id, List parcelas = null, long? parcela = null) + { + base.Loading(true); + this.Logs = new ObservableCollection((IEnumerable)await this._servico.FindByEntityId(tela, id)); + if (tela == 37) + { + ObservableCollection observableCollection = new ObservableCollection(); + ObservableCollection logs = this.Logs; + List list = ( + from x in logs + where !x.get_ModeloNovo() + select x).ToList(); + for (int i = list.Count - 1; i >= 0; i--) + { + ObservableCollection observableCollection1 = new ObservableCollection(); + for (int j = i; j >= 0 && list[j].get_DataHora() < list[i].get_DataHora().AddSeconds(4); j--) + { + observableCollection1.Add(JsonConvert.DeserializeObject(list[j].get_Descricao())); + i = j; + } + ObservableCollection observableCollection2 = observableCollection1; + observableCollection1 = new ObservableCollection( + from x in observableCollection2 + orderby x.get_Id() + select x); + RegistroLog item = list[i]; + VendedorParcelas vendedorParcela = new VendedorParcelas(); + vendedorParcela.set_VendedorParcelasList(observableCollection1); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + item.set_Descricao(JsonConvert.SerializeObject(vendedorParcela, jsonSerializerSetting)); + observableCollection.Insert(0, list[i]); + } + ObservableCollection logs1 = this.Logs; + List registroLogs = ( + from x in logs1 + where x.get_ModeloNovo() + select x).ToList(); + this.Logs = observableCollection; + ExtensionMethods.AddRange(this.Logs, registroLogs); + } + if (this.Logs.Count <= 0) + { + this.SetListaFiltrada(this.Lists); + } + else + { + this.SelectedLog = this.Logs[0]; + } + base.Loading(false); + } + + public void SetListaFiltrada(List listAtual) + { + List tupleLists; + ObservableCollection> observableCollection; + List.Enumerator enumerator; + ObservableCollection observableCollection1; + ObservableCollection observableCollection2; + ObservableCollection observableCollection3; + if (this.Logs.Count == 0) + { + this.ListsAlterados = null; + this.ListsAdicionados = null; + this.ListsRemovidos = null; + return; + } + if (this.SelectedLog.get_ModeloNovo() && this.SelectedLog.get_Acao() == 1) + { + this.TextAdicoes = "ALTERAÇÕES"; + this.ListsAdicionados = null; + this.ListsRemovidos = null; + this.ListsAlterados = new ObservableCollection(this.Lists); + this.MostrarMensagem = false; + return; + } + if (this.SelectedLog.get_ModeloNovo() && this.SelectedLog.get_Acao() == null) + { + this.TextAdicoes = "INCLUSÕES"; + this.ListsAlterados = null; + this.ListsRemovidos = null; + this.ListsAdicionados = new ObservableCollection(listAtual); + this.MostrarMensagem = false; + return; + } + if (this.SelectedLog.get_ModeloNovo() && this.SelectedLog.get_Acao() == 2) + { + this.TextAdicoes = "EXCLUSÕES"; + this.ListsAlterados = null; + this.ListsAdicionados = null; + this.ListsRemovidos = new ObservableCollection(listAtual); + this.MostrarMensagem = false; + return; + } + if (this.Mostrar || (object)this.Logs.Last() == (object)this.SelectedLog) + { + this.TextAdicoes = ((object)this.Logs.Last() != (object)this.SelectedLog ? "LOG COMPLETO" : "INCLUSÃO"); + this.ListsAlterados = null; + this.ListsAdicionados = new ObservableCollection(listAtual); + this.ListsRemovidos = null; + return; + } + this.TextAdicoes = "INCLUSÃO"; + List tupleLists1 = new List(); + try + { + switch (this._tipoTela) + { + case 1: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 2: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(base.Restricao(14)); + goto case 53; + } + case 3: + { + Item item = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()); + if (item.get_Aeronautico() != null) + { + tupleLists1 = Aeronautico.Log(item); + goto case 53; + } + else if (item.get_Auto() != null) + { + tupleLists1 = Auto.Log(item); + goto case 53; + } + else if (item.get_Granizo() != null) + { + tupleLists1 = Granizo.Log(item); + goto case 53; + } + else if (item.get_Patrimonial() != null) + { + tupleLists1 = Patrimonial.Log(item); + goto case 53; + } + else if (item.get_RiscosDiversos() == null) + { + if (item.get_Vida() == null) + { + goto case 53; + } + tupleLists1 = Vida.Log(item); + goto case 53; + } + else + { + tupleLists1 = RiscosDiversos.Log(item); + goto case 53; + } + } + case 4: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 5: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(base.Restricao(14), base.Restricao(95)); + goto case 53; + } + case 6: + case 8: + case 20: + case 21: + case 23: + case 25: + case 27: + case 32: + case 35: + case 39: + case 40: + case 44: + case 47: + case 49: + case 50: + case 51: + case 53: + { + break; + } + case 7: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 9: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 10: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 11: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 12: + { + Ramo ramo = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()); + List list = ( + from x in Recursos.Coberturas + where x.get_IdRamo() == ramo.get_Id() + orderby x.get_Padrao() descending, x.get_Descricao() + select x).ToList(); + tupleLists1 = ramo.Log(list); + goto case 53; + } + case 13: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 14: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 15: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 16: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 17: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 18: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 19: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 22: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 24: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 26: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 28: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 29: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 30: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 31: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 33: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 34: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 36: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 37: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(base.Restricao(14), base.Restricao(95)); + goto case 53; + } + case 38: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 41: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 42: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 43: + { + List>>>>> tuples = JsonConvert.DeserializeObject>>>>>>(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()); + tupleLists = new List(); + foreach (Tuple>>>> tuple in tuples) + { + observableCollection = new ObservableCollection>() + { + new Tuple(string.Concat(tuple.Item1, "$"), "", "") + }; + foreach (Tuple>> item2 in tuple.Item2) + { + observableCollection.Add(new Tuple(string.Concat(" ", item2.Item1, "$"), "", "")); + foreach (Tuple item21 in item2.Item2) + { + observableCollection.Add(new Tuple(string.Concat(" ", item21.Item1), item21.Item2, "")); + } + } + TupleList tupleList = new TupleList(); + tupleList.set_Tuples(observableCollection); + tupleLists.Add(tupleList); + } + enumerator = tupleLists.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + tupleLists1.Add(enumerator.Current); + } + goto case 53; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + break; + } + case 45: + { + List vendedors = JsonConvert.DeserializeObject>(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()); + tupleLists = new List(); + observableCollection = new ObservableCollection>() + { + new Tuple("VENDEDORES VINCULADOS$", "", "") + }; + foreach (Vendedor vendedor in vendedors) + { + observableCollection.Add(new Tuple(string.Format(" VENDEDOR {0}", vendedors.IndexOf(vendedor) + 1), vendedor.get_Nome(), "")); + } + TupleList tupleList1 = new TupleList(); + tupleList1.set_Tuples(observableCollection); + tupleLists.Add(tupleList1); + enumerator = tupleLists.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + tupleLists1.Add(enumerator.Current); + } + goto case 53; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + break; + } + case 46: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 48: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 52: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 54: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 55: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + case 56: + { + tupleLists1 = JsonConvert.DeserializeObject(this.Logs[this.Logs.IndexOf(this.SelectedLog) + 1].get_Descricao()).Log(); + goto case 53; + } + default: + { + goto case 53; + } + } + } + catch (Exception exception) + { + } + ObservableCollection observableCollection4 = new ObservableCollection(); + foreach (TupleList tupleList2 in listAtual) + { + int num = -1; + if (tupleLists1.Count - 1 < listAtual.IndexOf(tupleList2)) + { + continue; + } + for (int i = 0; i < tupleList2.get_Tuples().Count; i++) + { + Tuple item1 = tupleList2.get_Tuples()[i]; + if (LogViewModel.QntEspaco(item1.Item1) != 0) + { + List strs = new List(); + int num1 = LogViewModel.QntEspaco(item1.Item1); + for (int j = i; j >= 0; j--) + { + if (LogViewModel.QntEspaco(tupleList2.get_Tuples()[j].Item1) <= num1) + { + strs.Insert(0, tupleList2.get_Tuples()[j].Item1); + num1 = LogViewModel.QntEspaco(tupleList2.get_Tuples()[j].Item1); + } + } + bool flag = false; + int num2 = 0; + Label2: + foreach (string str in strs) + { + if (!flag) + { + int num3 = num2; + while (num3 < tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples().Count) + { + if (num3 == tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples().Count - 1 && str != tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[num3].Item1) + { + flag = true; + goto Label2; + } + else if (str != tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[num3].Item1) + { + num3++; + } + else + { + num2 = num3; + goto Label2; + } + } + } + else + { + goto Label1; + } + } + Label1: + if (!flag && item1.Item2 != tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[num2].Item2) + { + if (num < listAtual.IndexOf(tupleList2)) + { + TupleList tupleList3 = new TupleList(); + tupleList3.set_Tuples(new ObservableCollection>()); + observableCollection4.Add(tupleList3); + num = listAtual.IndexOf(tupleList2); + } + int count = observableCollection4.Last().get_Tuples().Count; + int num4 = LogViewModel.QntEspaco(item1.Item1); + for (int k = i - 1; k >= 0; k--) + { + if (LogViewModel.QntEspaco(tupleList2.get_Tuples()[k].Item1) < LogViewModel.QntEspaco(item1.Item1) && LogViewModel.QntEspaco(tupleList2.get_Tuples()[k].Item1) < num4) + { + bool flag1 = false; + int count1 = observableCollection4.Last().get_Tuples().Count - 1; + while (count1 >= 0) + { + if (observableCollection4.Last().get_Tuples()[count1].Item1 != tupleList2.get_Tuples()[k].Item1) + { + count1--; + } + else + { + flag1 = true; + break; + } + } + if (flag1) + { + break; + } + num4 = LogViewModel.QntEspaco(tupleList2.get_Tuples()[k].Item1); + observableCollection4.Last().get_Tuples().Insert(count, new Tuple(tupleList2.get_Tuples()[k].Item1, tupleList2.get_Tuples()[k].Item2, "")); + } + } + observableCollection4.Last().get_Tuples().Add(new Tuple(item1.Item1, item1.Item2, tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[num2].Item2)); + } + } + else if (item1.Item2 != tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[tupleList2.get_Tuples().IndexOf(item1)].Item2) + { + if (num < listAtual.IndexOf(tupleList2)) + { + TupleList tupleList4 = new TupleList(); + tupleList4.set_Tuples(new ObservableCollection>()); + observableCollection4.Add(tupleList4); + num = listAtual.IndexOf(tupleList2); + } + observableCollection4.Last().get_Tuples().Add(new Tuple(item1.Item1, item1.Item2, tupleLists1[listAtual.IndexOf(tupleList2)].get_Tuples()[tupleList2.get_Tuples().IndexOf(item1)].Item2)); + } + } + } + if (observableCollection4.Count == 0) + { + observableCollection1 = null; + } + else + { + observableCollection1 = observableCollection4; + } + this.ListsAlterados = observableCollection1; + observableCollection4 = new ObservableCollection(); + foreach (TupleList tupleList5 in listAtual) + { + int num5 = -1; + if (tupleLists1.Count - 1 < listAtual.IndexOf(tupleList5)) + { + continue; + } + for (int l = 0; l < tupleList5.get_Tuples().Count; l++) + { + Tuple tuple1 = tupleList5.get_Tuples()[l]; + if (LogViewModel.QntEspaco(tuple1.Item1) > 0) + { + List strs1 = new List(); + int num6 = LogViewModel.QntEspaco(tuple1.Item1); + for (int m = l; m >= 0; m--) + { + if (LogViewModel.QntEspaco(tupleList5.get_Tuples()[m].Item1) <= num6) + { + strs1.Insert(0, tupleList5.get_Tuples()[m].Item1); + num6 = LogViewModel.QntEspaco(tupleList5.get_Tuples()[m].Item1); + } + } + bool flag2 = false; + int num7 = 0; + Label4: + foreach (string str1 in strs1) + { + if (!flag2) + { + int num8 = num7; + while (num8 < tupleLists1[listAtual.IndexOf(tupleList5)].get_Tuples().Count) + { + if (num8 == tupleLists1[listAtual.IndexOf(tupleList5)].get_Tuples().Count - 1 && str1 != tupleLists1[listAtual.IndexOf(tupleList5)].get_Tuples()[num8].Item1) + { + flag2 = true; + goto Label4; + } + else if (str1 != tupleLists1[listAtual.IndexOf(tupleList5)].get_Tuples()[num8].Item1) + { + num8++; + } + else + { + num7 = num8; + goto Label4; + } + } + } + else + { + goto Label3; + } + } + Label3: + if (flag2) + { + if (num5 < listAtual.IndexOf(tupleList5)) + { + TupleList tupleList6 = new TupleList(); + tupleList6.set_Tuples(new ObservableCollection>()); + observableCollection4.Add(tupleList6); + num5 = listAtual.IndexOf(tupleList5); + } + int count2 = observableCollection4.Last().get_Tuples().Count; + int num9 = LogViewModel.QntEspaco(tuple1.Item1); + for (int n = l - 1; n >= 0; n--) + { + if (LogViewModel.QntEspaco(tupleList5.get_Tuples()[n].Item1) < LogViewModel.QntEspaco(tuple1.Item1) && LogViewModel.QntEspaco(tupleList5.get_Tuples()[n].Item1) < num9) + { + bool flag3 = false; + int count3 = observableCollection4.Last().get_Tuples().Count - 1; + while (count3 >= 0) + { + if (observableCollection4.Last().get_Tuples()[count3].Item1 != tupleList5.get_Tuples()[n].Item1) + { + count3--; + } + else + { + flag3 = true; + break; + } + } + if (flag3) + { + break; + } + num9 = LogViewModel.QntEspaco(tupleList5.get_Tuples()[n].Item1); + observableCollection4.Last().get_Tuples().Insert(count2, new Tuple(tupleList5.get_Tuples()[n].Item1, tupleList5.get_Tuples()[n].Item2, "")); + } + } + observableCollection4.Last().get_Tuples().Add(new Tuple(tuple1.Item1, tuple1.Item2, "")); + } + } + } + } + if (observableCollection4.Count == 0) + { + observableCollection2 = null; + } + else + { + observableCollection2 = observableCollection4; + } + this.ListsAdicionados = observableCollection2; + observableCollection4 = new ObservableCollection(); + foreach (TupleList tupleList7 in tupleLists1) + { + int num10 = -1; + for (int o = 0; o < tupleList7.get_Tuples().Count; o++) + { + Tuple tuple2 = tupleList7.get_Tuples()[o]; + if (LogViewModel.QntEspaco(tuple2.Item1) > 0) + { + List strs2 = new List(); + int num11 = LogViewModel.QntEspaco(tuple2.Item1); + for (int p = o; p >= 0; p--) + { + if (LogViewModel.QntEspaco(tupleList7.get_Tuples()[p].Item1) <= num11) + { + strs2.Insert(0, tupleList7.get_Tuples()[p].Item1); + num11 = LogViewModel.QntEspaco(tupleList7.get_Tuples()[p].Item1); + } + } + bool flag4 = false; + int num12 = 0; + Label6: + foreach (string str2 in strs2) + { + if (!flag4) + { + if (listAtual.Count - 1 < tupleLists1.IndexOf(tupleList7)) + { + continue; + } + int num13 = num12; + while (num13 < listAtual[tupleLists1.IndexOf(tupleList7)].get_Tuples().Count) + { + if (num13 == listAtual[tupleLists1.IndexOf(tupleList7)].get_Tuples().Count - 1 && str2 != listAtual[tupleLists1.IndexOf(tupleList7)].get_Tuples()[num13].Item1) + { + flag4 = true; + goto Label6; + } + else if (str2 != listAtual[tupleLists1.IndexOf(tupleList7)].get_Tuples()[num13].Item1) + { + num13++; + } + else + { + num12 = num13; + goto Label6; + } + } + } + else + { + goto Label5; + } + } + Label5: + if (flag4) + { + if (num10 < tupleLists1.IndexOf(tupleList7)) + { + TupleList tupleList8 = new TupleList(); + tupleList8.set_Tuples(new ObservableCollection>()); + observableCollection4.Add(tupleList8); + num10 = tupleLists1.IndexOf(tupleList7); + } + int count4 = observableCollection4.Last().get_Tuples().Count; + int num14 = LogViewModel.QntEspaco(tuple2.Item1); + for (int q = o - 1; q >= 0; q--) + { + if (LogViewModel.QntEspaco(tupleList7.get_Tuples()[q].Item1) < LogViewModel.QntEspaco(tuple2.Item1) && LogViewModel.QntEspaco(tupleList7.get_Tuples()[q].Item1) < num14) + { + bool flag5 = false; + int count5 = observableCollection4.Last().get_Tuples().Count - 1; + while (count5 >= 0) + { + if (observableCollection4.Last().get_Tuples()[count5].Item1 != tupleList7.get_Tuples()[q].Item1) + { + count5--; + } + else + { + flag5 = true; + break; + } + } + if (flag5) + { + break; + } + num14 = LogViewModel.QntEspaco(tupleList7.get_Tuples()[q].Item1); + observableCollection4.Last().get_Tuples().Insert(count4, new Tuple(tupleList7.get_Tuples()[q].Item1, tupleList7.get_Tuples()[q].Item2, "")); + } + } + observableCollection4.Last().get_Tuples().Add(new Tuple(tuple2.Item1, "", tuple2.Item2)); + } + } + } + } + if (observableCollection4.Count == 0) + { + observableCollection3 = null; + } + else + { + observableCollection3 = observableCollection4; + } + this.ListsRemovidos = observableCollection3; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/MetaSeguradoraViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/MetaSeguradoraViewModel.cs new file mode 100644 index 0000000..71d96c5 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/MetaSeguradoraViewModel.cs @@ -0,0 +1,258 @@ +using Assinador.Infrastructure.Helpers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class MetaSeguradoraViewModel : BaseSegurosViewModel + { + private readonly MetaSeguradoraServico _servico; + + private readonly Seguradora _selectedSeguradora; + + private MetaSeguradora _selectedMetaSeguradora = new MetaSeguradora(); + + private ObservableCollection _metasSeguradora = new ObservableCollection(); + + private bool _carregando; + + public MetaSeguradora CancelMetaSeguradora; + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection MetasSeguradora + { + get + { + return this._metasSeguradora; + } + set + { + this._metasSeguradora = value; + base.OnPropertyChanged("MetasSeguradora"); + } + } + + public MetaSeguradora SelectedMetaSeguradora + { + get + { + return this._selectedMetaSeguradora; + } + set + { + long? nullable; + this._selectedMetaSeguradora = value; + this.CancelMetaSeguradora = (value == null || value.get_Id() <= (long)0 ? this.CancelMetaSeguradora : value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedMetaSeguradora"); + } + } + + public MetaSeguradoraViewModel(Seguradora seguradora) + { + this._servico = new MetaSeguradoraServico(); + this.Seleciona(seguradora); + this._selectedSeguradora = seguradora; + } + + public void CancelarAlteracao() + { + this.Carregando = true; + if (this.CancelMetaSeguradora != null && this.MetasSeguradora.Any((MetaSeguradora x) => x.get_Id() == this.CancelMetaSeguradora.get_Id())) + { + DomainBase.Copy(this.MetasSeguradora.First((MetaSeguradora x) => x.get_Id() == this.CancelMetaSeguradora.get_Id()), this.CancelMetaSeguradora); + this.SelectedMetaSeguradora = this.MetasSeguradora.First((MetaSeguradora x) => x.get_Id() == this.CancelMetaSeguradora.get_Id()); + } + base.Alterar(false); + this.Carregando = false; + } + + private async Task CarregarMetas(Seguradora seguradora) + { + List metaSeguradoras = await (new BaseServico()).BuscarMetaSeguradoraAsync(seguradora); + MetaSeguradoraViewModel observableCollection = this; + List metaSeguradoras1 = metaSeguradoras; + IOrderedEnumerable mes = + from x in metaSeguradoras1 + orderby x.get_Mes() + select x; + observableCollection.MetasSeguradora = new ObservableCollection(mes.ThenBy((MetaSeguradora x) => x.get_Valor())); + } + + public async Task Excluir() + { + bool flag; + string nome; + MetaSeguradora metaSeguradora; + if (this.SelectedMetaSeguradora == null || this.SelectedMetaSeguradora.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + this.Carregando = true; + if (await this._servico.Delete(this.SelectedMetaSeguradora)) + { + MetaSeguradoraViewModel metaSeguradoraViewModel = this; + Seguradora seguradora = this.SelectedMetaSeguradora.get_Seguradora(); + if (seguradora != null) + { + nome = seguradora.get_Nome(); + } + else + { + nome = null; + } + string str = string.Concat("EXCLUIU META DA SEGURADORA \"", nome, "\""); + long id = this.SelectedMetaSeguradora.get_Id(); + TipoTela? nullable = new TipoTela?(31); + object[] objArray = new object[] { this.SelectedMetaSeguradora.get_Id(), this.SelectedMetaSeguradora.get_Valor(), Functions.GetDescription(this.SelectedMetaSeguradora.get_Mes()), this.SelectedMetaSeguradora.get_Ano() }; + metaSeguradoraViewModel.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nVALOR: {1:C}\nMÊS: {2}\nANO: {3}", objArray)); + int num = this.MetasSeguradora.IndexOf(this.SelectedMetaSeguradora); + this.MetasSeguradora.Remove(this.SelectedMetaSeguradora); + this.MetasSeguradora.Remove(this.SelectedMetaSeguradora); + this.MetasSeguradora = new ObservableCollection(this.MetasSeguradora); + if (this.MetasSeguradora.Count <= 0) + { + this.SelectedMetaSeguradora = new MetaSeguradora(); + base.Alterar(false); + base.EnableMenu = false; + base.EnableAlterar = false; + base.EnableExcluir = false; + } + else + { + MetaSeguradoraViewModel metaSeguradoraViewModel1 = this; + metaSeguradora = (num < this.MetasSeguradora.Count ? this.MetasSeguradora.ElementAt(num) : this.MetasSeguradora.Last()); + metaSeguradoraViewModel1.SelectedMetaSeguradora = metaSeguradora; + } + this.Carregando = false; + flag = true; + } + else + { + this.Carregando = false; + base.Alterar(false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public void Incluir() + { + DateTime date = Funcoes.GetNetworkTime().Date; + MetaSeguradora metaSeguradora = new MetaSeguradora(); + metaSeguradora.set_Ano((long)date.Year); + metaSeguradora.set_Mes(date.Month); + this.SelectedMetaSeguradora = metaSeguradora; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + this.SelectedMetaSeguradora.set_Seguradora(this._selectedSeguradora); + str = (this.SelectedMetaSeguradora.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + string str1 = str; + MetaSeguradora metaSeguradora = await this._servico.Save(this.SelectedMetaSeguradora); + if (this._servico.Sucesso) + { + string str2 = string.Concat(str1, " META DA SEGURADORA \"", metaSeguradora.get_Seguradora().get_Nome(), "\""); + long id = metaSeguradora.get_Id(); + TipoTela? nullable = new TipoTela?(31); + object[] objArray = new object[] { metaSeguradora.get_Id(), metaSeguradora.get_Valor(), Functions.GetDescription(metaSeguradora.get_Mes()), metaSeguradora.get_Ano() }; + base.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nVALOR: {1:C}\nMÊS: {2}\nANO: {3}", objArray)); + if (!this.MetasSeguradora.Any((MetaSeguradora x) => x.get_Id() == metaSeguradora.get_Id())) + { + this.MetasSeguradora.Add(metaSeguradora); + } + else + { + DomainBase.Copy(this.MetasSeguradora.First((MetaSeguradora x) => x.get_Id() == metaSeguradora.get_Id()), metaSeguradora); + } + this.MetasSeguradora = new ObservableCollection(this.MetasSeguradora); + this.SelectedMetaSeguradora = this.MetasSeguradora.First((MetaSeguradora x) => x.get_Id() == metaSeguradora.get_Id()); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona(Seguradora seguradora) + { + base.Loading(true); + await base.PermissaoTela(31); + await this.SelecionaMetasSeguradora(seguradora); + base.Loading(false); + } + + public void SelecionaMetaSeguradora(MetaSeguradora metaSeguradora) + { + this.SelectedMetaSeguradora = metaSeguradora; + } + + private async Task SelecionaMetasSeguradora(Seguradora seguradora) + { + this.Carregando = true; + await this.CarregarMetas(seguradora); + if (this.MetasSeguradora.Count <= 0) + { + this.SelectedMetaSeguradora = new MetaSeguradora(); + base.Alterar(false); + base.EnableMenu = false; + base.EnableAlterar = false; + base.EnableExcluir = false; + } + else + { + this.SelecionaMetaSeguradora(this.MetasSeguradora.First()); + } + this.Carregando = false; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/MetaVendedorViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/MetaVendedorViewModel.cs new file mode 100644 index 0000000..23f8929 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/MetaVendedorViewModel.cs @@ -0,0 +1,244 @@ +using Assinador.Infrastructure.Helpers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class MetaVendedorViewModel : BaseSegurosViewModel + { + private readonly MetaVendedorServico _servico; + + private readonly Vendedor _selectedVendedor; + + private MetaVendedor _selectedMetaVendedor = new MetaVendedor(); + + private ObservableCollection _metasVendedor = new ObservableCollection(); + + private bool _carregando; + + public MetaVendedor CancelMetaVendedor; + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection MetasVendedor + { + get + { + return this._metasVendedor; + } + set + { + this._metasVendedor = value; + base.OnPropertyChanged("MetasVendedor"); + } + } + + public MetaVendedor SelectedMetaVendedor + { + get + { + return this._selectedMetaVendedor; + } + set + { + long? nullable; + this._selectedMetaVendedor = value; + this.CancelMetaVendedor = (value == null || value.get_Id() <= (long)0 ? this.CancelMetaVendedor : value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedMetaVendedor"); + } + } + + public MetaVendedorViewModel(Vendedor vendedor) + { + this._servico = new MetaVendedorServico(); + this.Seleciona(vendedor); + this._selectedVendedor = vendedor; + } + + public void CancelarAlteracao() + { + this.Carregando = true; + if (this.CancelMetaVendedor != null && this.MetasVendedor.Any((MetaVendedor x) => x.get_Id() == this.CancelMetaVendedor.get_Id())) + { + DomainBase.Copy(this.MetasVendedor.First((MetaVendedor x) => x.get_Id() == this.CancelMetaVendedor.get_Id()), this.CancelMetaVendedor); + this.SelectedMetaVendedor = this.MetasVendedor.First((MetaVendedor x) => x.get_Id() == this.CancelMetaVendedor.get_Id()); + } + base.Alterar(false); + this.Carregando = false; + } + + private async Task CarregarMetas(Vendedor vendedor) + { + List metaVendedors = await (new BaseServico()).BuscarMetaVendedorAsync(vendedor); + MetaVendedorViewModel observableCollection = this; + List metaVendedors1 = metaVendedors; + IOrderedEnumerable mes = + from x in metaVendedors1 + orderby x.get_Mes() + select x; + observableCollection.MetasVendedor = new ObservableCollection(mes.ThenBy((MetaVendedor x) => x.get_Valor()).ToList()); + } + + public async Task Excluir() + { + bool flag; + string str; + string str1; + if (this.SelectedMetaVendedor == null || this.SelectedMetaVendedor.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + this.Carregando = true; + str = string.Concat("EXCLUIU META DO VENDEDOR \"", this._selectedVendedor.get_Nome(), "\""); + long id = this.SelectedMetaVendedor.get_Id(); + object[] objArray = new object[] { this.SelectedMetaVendedor.get_Id(), this.SelectedMetaVendedor.get_Valor(), Functions.GetDescription(this.SelectedMetaVendedor.get_Mes()), this.SelectedMetaVendedor.get_Ano() }; + str1 = string.Format("ID: {0}\nVALOR: {1:C}\nMÊS: {2}\nANO: {3}", objArray); + if (await this._servico.Delete(this.SelectedMetaVendedor)) + { + base.RegistrarAcao(str, id, new TipoTela?(30), str1); + await this.CarregarMetas(this._selectedVendedor); + if (this.MetasVendedor.Count <= 0) + { + this.SelectedMetaVendedor = new MetaVendedor(); + base.Alterar(false); + base.EnableMenu = false; + base.EnableAlterar = false; + base.EnableExcluir = false; + } + else + { + this.SelectedMetaVendedor = this.MetasVendedor.First(); + } + this.Carregando = false; + flag = true; + } + else + { + this.Carregando = false; + base.Alterar(false); + flag = false; + } + } + else + { + flag = false; + } + str = null; + str1 = null; + return flag; + } + + public void Incluir() + { + DateTime date = Funcoes.GetNetworkTime().Date; + MetaVendedor metaVendedor = new MetaVendedor(); + metaVendedor.set_Ano((long)date.Year); + metaVendedor.set_Mes(date.Month); + this.SelectedMetaVendedor = metaVendedor; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + this.SelectedMetaVendedor.set_Vendedor(this._selectedVendedor); + this._servico.Sucesso = true; + str = (this.SelectedMetaVendedor.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + string str1 = str; + MetaVendedor metaVendedor = await this._servico.Save(this.SelectedMetaVendedor); + if (this._servico.Sucesso) + { + string str2 = string.Concat(str1, " META DO VENDEDOR \"", metaVendedor.get_Vendedor().get_Nome(), "\""); + long id = metaVendedor.get_Id(); + TipoTela? nullable = new TipoTela?(30); + object[] objArray = new object[] { metaVendedor.get_Id(), metaVendedor.get_Valor(), Functions.GetDescription(metaVendedor.get_Mes()), metaVendedor.get_Ano() }; + base.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nVALOR: {1:C}\nMÊS: {2}\nANO: {3}", objArray)); + if (!this.MetasVendedor.Any((MetaVendedor x) => x.get_Id() == metaVendedor.get_Id())) + { + this.MetasVendedor.Add(metaVendedor); + } + else + { + DomainBase.Copy(this.MetasVendedor.First((MetaVendedor x) => x.get_Id() == metaVendedor.get_Id()), metaVendedor); + } + this.MetasVendedor = new ObservableCollection(this.MetasVendedor); + this.SelectedMetaVendedor = this.MetasVendedor.First((MetaVendedor x) => x.get_Id() == metaVendedor.get_Id()); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona(Vendedor vendedor) + { + base.Loading(true); + await base.PermissaoTela(30); + await this.SelecionaMetasVendedor(vendedor); + base.Loading(false); + } + + private async Task SelecionaMetasVendedor(Vendedor vendedor) + { + this.Carregando = true; + await this.CarregarMetas(vendedor); + if (this.MetasVendedor.Count <= 0) + { + this.SelectedMetaVendedor = new MetaVendedor(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaMetaVendedor(this.MetasVendedor.First()); + } + this.Carregando = false; + } + + public void SelecionaMetaVendedor(MetaVendedor metaVendedor) + { + this.SelectedMetaVendedor = metaVendedor; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/PermissaoUsuarioViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/PermissaoUsuarioViewModel.cs new file mode 100644 index 0000000..3f8c7ac --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/PermissaoUsuarioViewModel.cs @@ -0,0 +1,1939 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class PermissaoUsuarioViewModel : BaseSegurosViewModel + { + private readonly UsuarioServico _servicoUsuario; + + private Usuario _selectedUsuario; + + private bool _expandedBis; + + private bool _expandedSeguros; + + private bool _expandedRelatorios; + + private bool _expandedCampos; + + private bool _expandedTotalizacoes; + + private bool _expandedFinanceiros; + + private bool _expandedFerramentas; + + private bool _expandedAjudas; + + private ObservableCollection _seguros; + + private ObservableCollection _ferramentas; + + private ObservableCollection _arquivosDigitais; + + private bool _enableAlterarPermiss = true; + + private ObservableCollection _restricoesBisFiltradas; + + private ObservableCollection _restricoesSegurosFiltradas; + + private ObservableCollection _restricoesRelatoriosFiltrados; + + private ObservableCollection _restricoesTotalizacoesRelatoriosFiltrados; + + private ObservableCollection _restricoesCamposRelatoriosFiltrados; + + private ObservableCollection _restricoesFinanceirosFiltradas; + + private ObservableCollection _restricoesFerramentasFiltradas; + + private ObservableCollection _restricoesAjudasFiltrados; + + private List _restricoesBis; + + private List _restricoesSeguros; + + private List _restricoesRelatorios; + + private List _restricoesTotalizacoesRelatorios; + + private List _restricoesCamposRelatorios; + + private List _restricoesFinanceiros; + + private List _restricoesFerramentas; + + private List _restricoesAjudas; + + private Visibility _restricoesBisVisibility; + + private Visibility _restricoesSegurosVisibility; + + private Visibility _restricoesRelatoriosVisibility; + + private Visibility _restricoesTotalizacoesRelatoriosVisibility; + + private Visibility _restricoesCamposRelatoriosVisibility; + + private Visibility _restricoesFinanceirosVisibility; + + private Visibility _restricoesFerramentasVisibility; + + private Visibility _restricoesAjudasVisibility; + + private List _permissaoAggilizador; + + private Gestor.Model.Common.PermissaoAggilizador _selectedPermissao; + + private bool _admUsuario; + + private bool _importarEnabled; + + private bool _carregando; + + private bool _ativarDesativarPermissoesBool = true; + + private bool _ativarDesativarRestricoesBool = true; + + public bool AdmUsuario + { + get + { + return this._admUsuario; + } + set + { + this._admUsuario = value; + this.ImportarEnabled = !value; + this.SelectedUsuario.set_Administrador(value); + if (value && !this.Carregando) + { + this.AtivarDesativarPermissoes(true); + this.AtivarDesativarRestricoes(false); + } + base.OnPropertyChanged("AdmUsuario"); + } + } + + public ObservableCollection ArquivosDigitais + { + get + { + return this._arquivosDigitais; + } + set + { + this._arquivosDigitais = value; + base.OnPropertyChanged("ArquivosDigitais"); + Gestor.Application.Actions.Actions.OcultarTogglesArquivoDigital(); + } + } + + public bool AtivarDesativarPermissoesBool + { + get + { + return this._ativarDesativarPermissoesBool; + } + set + { + this._ativarDesativarPermissoesBool = value; + base.OnPropertyChanged("AtivarDesativarPermissoesBool"); + } + } + + public bool AtivarDesativarRestricoesBool + { + get + { + return this._ativarDesativarRestricoesBool; + } + set + { + this._ativarDesativarRestricoesBool = value; + base.OnPropertyChanged("AtivarDesativarRestricoesBool"); + } + } + + public bool Carregado + { + get; + set; + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.EnableMenu = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool EnableAlterarPermiss + { + get + { + return this._enableAlterarPermiss; + } + set + { + this._enableAlterarPermiss = value; + base.OnPropertyChanged("EnableAlterarPermiss"); + } + } + + public bool ExpandedAjudas + { + get + { + return this._expandedAjudas; + } + set + { + this._expandedAjudas = value; + base.OnPropertyChanged("ExpandedAjudas"); + } + } + + public bool ExpandedBis + { + get + { + return this._expandedBis; + } + set + { + this._expandedBis = value; + base.OnPropertyChanged("ExpandedBis"); + } + } + + public bool ExpandedCampos + { + get + { + return this._expandedCampos; + } + set + { + this._expandedCampos = value; + base.OnPropertyChanged("ExpandedCampos"); + } + } + + public bool ExpandedFerramentas + { + get + { + return this._expandedFerramentas; + } + set + { + this._expandedFerramentas = value; + base.OnPropertyChanged("ExpandedFerramentas"); + } + } + + public bool ExpandedFinanceiros + { + get + { + return this._expandedFinanceiros; + } + set + { + this._expandedFinanceiros = value; + base.OnPropertyChanged("ExpandedFinanceiros"); + } + } + + public bool ExpandedRelatorios + { + get + { + return this._expandedRelatorios; + } + set + { + this._expandedRelatorios = value; + base.OnPropertyChanged("ExpandedRelatorios"); + } + } + + public bool ExpandedSeguros + { + get + { + return this._expandedSeguros; + } + set + { + this._expandedSeguros = value; + base.OnPropertyChanged("ExpandedSeguros"); + } + } + + public bool ExpandedTotalizacoes + { + get + { + return this._expandedTotalizacoes; + } + set + { + this._expandedTotalizacoes = value; + base.OnPropertyChanged("ExpandedTotalizacoes"); + } + } + + public ObservableCollection Ferramentas + { + get + { + return this._ferramentas; + } + set + { + this._ferramentas = value; + base.OnPropertyChanged("Ferramentas"); + if (value != null && this.Seguros != null) + { + if (value.All((PermissaoUsuario x) => { + if (x.get_Tela() == 18 && x.get_Consultar() && x.get_Alterar() || x.get_Tela() == 10 && x.get_Consultar() && x.get_Alterar() && x.get_Incluir() || x.get_Tela() == 12 && x.get_Consultar() && x.get_Alterar() || x.get_Tela() == 13 && x.get_Consultar() && x.get_Alterar() && x.get_Incluir()) + { + return true; + } + if (x.get_Tela() == 18 || x.get_Tela() == 10 || x.get_Tela() == 12 || x.get_Tela() == 13 || !x.get_Consultar() || !x.get_Alterar() || !x.get_Incluir()) + { + return false; + } + return x.get_Excluir(); + })) + { + if (this.Seguros.All((PermissaoUsuario x) => { + if (x.get_Tela() == 21 && x.get_Consultar() || x.get_Tela() == 5 && x.get_Alterar() && x.get_Incluir() && x.get_Excluir()) + { + return true; + } + if (x.get_Tela() == 21 || x.get_Tela() == 5 || !x.get_Consultar() || !x.get_Alterar() || !x.get_Incluir()) + { + return false; + } + return x.get_Excluir(); + })) + { + this.AtivarDesativarPermissoesBool = false; + } + } + } + Gestor.Application.Actions.Actions.OcultarTogglesFerramentas(); + } + } + + public bool ImportarEnabled + { + get + { + return this._importarEnabled; + } + set + { + this._importarEnabled = value; + base.OnPropertyChanged("ImportarEnabled"); + } + } + + public List PermissaoAggilizador + { + get + { + return this._permissaoAggilizador; + } + set + { + this._permissaoAggilizador = value; + base.OnPropertyChanged("PermissaoAggilizador"); + } + } + + public List RestricoesAjudas + { + get + { + return this._restricoesAjudas; + } + set + { + this._restricoesAjudas = value; + base.OnPropertyChanged("RestricoesAjudas"); + } + } + + public ObservableCollection RestricoesAjudasFiltrados + { + get + { + return this._restricoesAjudasFiltrados; + } + set + { + this.RestricoesAjudasVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesAjudasFiltrados = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesAjudasFiltrados"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesAjudasVisibility + { + get + { + return this._restricoesAjudasVisibility; + } + set + { + this._restricoesAjudasVisibility = value; + base.OnPropertyChanged("RestricoesAjudasVisibility"); + } + } + + public List RestricoesBis + { + get + { + return this._restricoesBis; + } + set + { + this._restricoesBis = value; + base.OnPropertyChanged("RestricoesBis"); + } + } + + public ObservableCollection RestricoesBisFiltradas + { + get + { + return this._restricoesBisFiltradas; + } + set + { + this.RestricoesBisVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesBisFiltradas = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesBisFiltradas"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesBisVisibility + { + get + { + return this._restricoesBisVisibility; + } + set + { + this._restricoesBisVisibility = value; + base.OnPropertyChanged("RestricoesBisVisibility"); + } + } + + public List RestricoesCamposRelatorios + { + get + { + return this._restricoesCamposRelatorios; + } + set + { + this._restricoesCamposRelatorios = value; + base.OnPropertyChanged("RestricoesCamposRelatorios"); + } + } + + public ObservableCollection RestricoesCamposRelatoriosFiltrados + { + get + { + return this._restricoesCamposRelatoriosFiltrados; + } + set + { + this.RestricoesCamposRelatoriosVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesCamposRelatoriosFiltrados = new ObservableCollection( + from x in value.ToList() + orderby x.get_Relatorio(), x.get_Campo() + select x); + base.OnPropertyChanged("RestricoesCamposRelatoriosFiltrados"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesCamposRelatoriosVisibility + { + get + { + return this._restricoesCamposRelatoriosVisibility; + } + set + { + this._restricoesCamposRelatoriosVisibility = value; + base.OnPropertyChanged("RestricoesCamposRelatoriosVisibility"); + } + } + + public List RestricoesFerramentas + { + get + { + return this._restricoesFerramentas; + } + set + { + this._restricoesFerramentas = value; + base.OnPropertyChanged("RestricoesFerramentas"); + } + } + + public ObservableCollection RestricoesFerramentasFiltradas + { + get + { + return this._restricoesFerramentasFiltradas; + } + set + { + this.RestricoesFerramentasVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesFerramentasFiltradas = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesFerramentasFiltradas"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesFerramentasVisibility + { + get + { + return this._restricoesFerramentasVisibility; + } + set + { + this._restricoesFerramentasVisibility = value; + base.OnPropertyChanged("RestricoesFerramentasVisibility"); + } + } + + public List RestricoesFinanceiros + { + get + { + return this._restricoesFinanceiros; + } + set + { + this._restricoesFinanceiros = value; + base.OnPropertyChanged("RestricoesFinanceiros"); + } + } + + public ObservableCollection RestricoesFinanceirosFiltradas + { + get + { + return this._restricoesFinanceirosFiltradas; + } + set + { + this.RestricoesFinanceirosVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesFinanceirosFiltradas = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesFinanceirosFiltradas"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesFinanceirosVisibility + { + get + { + return this._restricoesFinanceirosVisibility; + } + set + { + this._restricoesFinanceirosVisibility = value; + base.OnPropertyChanged("RestricoesFinanceirosVisibility"); + } + } + + public List RestricoesRelatorios + { + get + { + return this._restricoesRelatorios; + } + set + { + this._restricoesRelatorios = value; + base.OnPropertyChanged("RestricoesRelatorios"); + } + } + + public ObservableCollection RestricoesRelatoriosFiltrados + { + get + { + return this._restricoesRelatoriosFiltrados; + } + set + { + this.RestricoesRelatoriosVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesRelatoriosFiltrados = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesRelatoriosFiltrados"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesRelatoriosVisibility + { + get + { + return this._restricoesRelatoriosVisibility; + } + set + { + this._restricoesRelatoriosVisibility = value; + base.OnPropertyChanged("RestricoesRelatoriosVisibility"); + } + } + + public List RestricoesSeguros + { + get + { + return this._restricoesSeguros; + } + set + { + this._restricoesSeguros = value; + base.OnPropertyChanged("RestricoesSeguros"); + } + } + + public ObservableCollection RestricoesSegurosFiltradas + { + get + { + return this._restricoesSegurosFiltradas; + } + set + { + this.RestricoesSegurosVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesSegurosFiltradas = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesSegurosFiltradas"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesSegurosVisibility + { + get + { + return this._restricoesSegurosVisibility; + } + set + { + this._restricoesSegurosVisibility = value; + base.OnPropertyChanged("RestricoesSegurosVisibility"); + } + } + + public List RestricoesTotalizacoesRelatorios + { + get + { + return this._restricoesTotalizacoesRelatorios; + } + set + { + this._restricoesTotalizacoesRelatorios = value; + base.OnPropertyChanged("RestricoesTotalizacoesRelatorios"); + } + } + + public ObservableCollection RestricoesTotalizacoesRelatoriosFiltrados + { + get + { + return this._restricoesTotalizacoesRelatoriosFiltrados; + } + set + { + this.RestricoesTotalizacoesRelatoriosVisibility = (value == null || value.Count <= 0 ? Visibility.Collapsed : Visibility.Visible); + this._restricoesTotalizacoesRelatoriosFiltrados = new ObservableCollection( + from x in value.ToList() + orderby ValidationHelper.GetDescription(x.get_Tipo()) + select x); + base.OnPropertyChanged("RestricoesTotalizacoesRelatoriosFiltrados"); + this.AtivarDesativarRestricoes(); + } + } + + public Visibility RestricoesTotalizacoesRelatoriosVisibility + { + get + { + return this._restricoesTotalizacoesRelatoriosVisibility; + } + set + { + this._restricoesTotalizacoesRelatoriosVisibility = value; + base.OnPropertyChanged("RestricoesTotalizacoesRelatoriosVisibility"); + } + } + + public ObservableCollection Seguros + { + get + { + return this._seguros; + } + set + { + this._seguros = value; + base.OnPropertyChanged("Seguros"); + if (value != null && this.Ferramentas != null) + { + if (value.All((PermissaoUsuario x) => { + if (x.get_Tela() == 21 && x.get_Consultar() || x.get_Tela() == 5 && x.get_Alterar() && x.get_Incluir() && x.get_Excluir()) + { + return true; + } + if (x.get_Tela() == 21 || x.get_Tela() == 5 || !x.get_Consultar() || !x.get_Alterar() || !x.get_Incluir()) + { + return false; + } + return x.get_Excluir(); + })) + { + if (this.Ferramentas.All((PermissaoUsuario x) => { + if (x.get_Tela() == 18 && x.get_Consultar() && x.get_Alterar() || x.get_Tela() == 10 && x.get_Consultar() && x.get_Alterar() && x.get_Incluir() || x.get_Tela() == 12 && x.get_Consultar() && x.get_Alterar() || x.get_Tela() == 13 && x.get_Consultar() && x.get_Alterar() && x.get_Incluir()) + { + return true; + } + if (x.get_Tela() == 18 || x.get_Tela() == 10 || x.get_Tela() == 12 || x.get_Tela() == 13 || !x.get_Consultar() || !x.get_Alterar() || !x.get_Incluir()) + { + return false; + } + return x.get_Excluir(); + })) + { + this.AtivarDesativarPermissoesBool = false; + } + } + } + Gestor.Application.Actions.Actions.OcultarTogglesSeguros(); + } + } + + public Gestor.Model.Common.PermissaoAggilizador SelectedPermissao + { + get + { + return this._selectedPermissao; + } + set + { + this._selectedPermissao = value; + base.OnPropertyChanged("SelectedPermissao"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public PermissaoUsuarioViewModel(Usuario usuario) + { + this.SelectedUsuario = usuario; + this._servicoUsuario = new UsuarioServico(); + this.CarregarModulos(usuario); + this.EnableAlterarPermiss = Recursos.Usuario.get_Id() > (long)0; + } + + public void AtivarDesativarPermissoes(bool permiss) + { + Gestor.Model.Common.PermissaoAggilizador permissaoAggilizador; + this.AtivarDesativarPermissoesBool = !permiss; + this.Seguros.ToList().ForEach((PermissaoUsuario x) => { + x.set_Consultar(permiss); + x.set_Incluir(permiss); + x.set_Alterar(permiss); + x.set_Excluir(permiss); + }); + this.Ferramentas.ToList().ForEach((PermissaoUsuario x) => { + x.set_Consultar(permiss); + x.set_Incluir(permiss); + x.set_Alterar(permiss); + x.set_Excluir(permiss); + }); + this.ArquivosDigitais.ToList().ForEach((PermissaoArquivoDigital x) => { + x.set_Consultar(permiss); + x.set_Incluir(permiss); + x.set_Excluir(permiss); + }); + if (permiss) + { + permissaoAggilizador = this.PermissaoAggilizador.FirstOrDefault((Gestor.Model.Common.PermissaoAggilizador x) => x.get_Descricao() == "ADMINISTRADOR"); + } + else + { + permissaoAggilizador = null; + } + this.SelectedPermissao = permissaoAggilizador; + this.Seguros = new ObservableCollection(this.Seguros); + this.Ferramentas = new ObservableCollection(this.Ferramentas); + this.ArquivosDigitais = new ObservableCollection(this.ArquivosDigitais); + } + + public void AtivarDesativarRestricoes(bool restricao) + { + this.AtivarDesativarRestricoesBool = !restricao; + foreach (RestricaoUsuario restricoesBisFiltrada in this.RestricoesBisFiltradas) + { + restricoesBisFiltrada.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesSegurosFiltrada in this.RestricoesSegurosFiltradas) + { + restricoesSegurosFiltrada.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesRelatoriosFiltrado in this.RestricoesRelatoriosFiltrados) + { + restricoesRelatoriosFiltrado.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesTotalizacoesRelatoriosFiltrado in this.RestricoesTotalizacoesRelatoriosFiltrados) + { + restricoesTotalizacoesRelatoriosFiltrado.set_Restricao(restricao); + } + foreach (RestricaoUsuarioCamposRelatorios restricoesCamposRelatoriosFiltrado in this.RestricoesCamposRelatoriosFiltrados) + { + restricoesCamposRelatoriosFiltrado.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesFinanceirosFiltrada in this.RestricoesFinanceirosFiltradas) + { + restricoesFinanceirosFiltrada.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesFerramentasFiltrada in this.RestricoesFerramentasFiltradas) + { + restricoesFerramentasFiltrada.set_Restricao(restricao); + } + foreach (RestricaoUsuario restricoesAjudasFiltrado in this.RestricoesAjudasFiltrados) + { + restricoesAjudasFiltrado.set_Restricao(restricao); + } + this.RestricoesBisFiltradas = new ObservableCollection(this.RestricoesBisFiltradas); + this.RestricoesSegurosFiltradas = new ObservableCollection(this.RestricoesSegurosFiltradas); + this.RestricoesRelatoriosFiltrados = new ObservableCollection(this.RestricoesRelatoriosFiltrados); + this.RestricoesTotalizacoesRelatoriosFiltrados = new ObservableCollection(this.RestricoesTotalizacoesRelatoriosFiltrados); + this.RestricoesCamposRelatoriosFiltrados = new ObservableCollection(this.RestricoesCamposRelatoriosFiltrados); + this.RestricoesFinanceirosFiltradas = new ObservableCollection(this.RestricoesFinanceirosFiltradas); + this.RestricoesFerramentasFiltradas = new ObservableCollection(this.RestricoesFerramentasFiltradas); + this.RestricoesAjudasFiltrados = new ObservableCollection(this.RestricoesAjudasFiltrados); + } + + public void AtivarDesativarRestricoes() + { + if (this.RestricoesBisFiltradas != null && this.RestricoesAjudasFiltrados != null && this.RestricoesSegurosFiltradas != null && this.RestricoesRelatoriosFiltrados != null && this.RestricoesFinanceirosFiltradas != null && this.RestricoesFerramentasFiltradas != null && this.RestricoesTotalizacoesRelatoriosFiltrados != null && this.RestricoesCamposRelatoriosFiltrados != null) + { + if (this.RestricoesBisFiltradas.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesAjudasFiltrados.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesSegurosFiltradas.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesRelatoriosFiltrados.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesFinanceirosFiltradas.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesFerramentasFiltradas.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesTotalizacoesRelatoriosFiltrados.All((RestricaoUsuario x) => x.get_Restricao())) + { + if (this.RestricoesCamposRelatoriosFiltrados.All((RestricaoUsuarioCamposRelatorios x) => x.get_Restricao())) + { + this.AtivarDesativarRestricoesBool = false; + } + } + } + } + } + } + } + } + } + } + + private async void CarregarModulos(Usuario usuario) + { + await this.Modulos(usuario); + this.Carregado = true; + } + + public bool CopiarPermissoes(Tuple, Usuario, List, List, List> copiarPermiss) + { + Gestor.Model.Common.PermissaoAggilizador permissaoAggilizador1; + if (copiarPermiss.Item1.Count <= 0) + { + this.Seguros.ToList().ForEach((PermissaoUsuario x) => { + x.set_Consultar(false); + x.set_Incluir(false); + x.set_Alterar(false); + x.set_Excluir(false); + x.set_Usuario(this._selectedUsuario); + }); + this.Ferramentas.ToList().ForEach((PermissaoUsuario x) => { + x.set_Consultar(false); + x.set_Incluir(false); + x.set_Alterar(false); + x.set_Excluir(false); + x.set_Usuario(this._selectedUsuario); + }); + } + else + { + copiarPermiss.Item1.ForEach((PermissaoUsuario x) => { + this.Seguros.ToList().ForEach((PermissaoUsuario y) => { + if (x.get_Tela() != y.get_Tela()) + { + return; + } + y.set_Consultar(x.get_Consultar()); + y.set_Incluir(x.get_Incluir()); + y.set_Alterar(x.get_Alterar()); + y.set_Excluir(x.get_Excluir()); + y.set_Usuario(this._selectedUsuario); + }); + this.Ferramentas.ToList().ForEach((PermissaoUsuario y) => { + if (x.get_Tela() != y.get_Tela()) + { + return; + } + y.set_Consultar(x.get_Consultar()); + y.set_Incluir(x.get_Incluir()); + y.set_Alterar(x.get_Alterar()); + y.set_Excluir(x.get_Excluir()); + y.set_Usuario(this._selectedUsuario); + }); + }); + } + if (copiarPermiss.Item4.Count <= 0) + { + this.ArquivosDigitais.ToList().ForEach((PermissaoArquivoDigital x) => { + x.set_Consultar(false); + x.set_Incluir(false); + x.set_Excluir(false); + x.set_Usuario(this._selectedUsuario); + }); + } + else + { + copiarPermiss.Item4.ForEach((PermissaoArquivoDigital x) => this.ArquivosDigitais.ToList().ForEach((PermissaoArquivoDigital y) => { + if (x.get_Tela() != y.get_Tela()) + { + return; + } + y.set_Consultar(x.get_Consultar()); + y.set_Incluir(x.get_Incluir()); + y.set_Excluir(x.get_Excluir()); + y.set_Usuario(this._selectedUsuario); + })); + } + if (copiarPermiss.Item2.get_PermissaoAggilizador().HasValue) + { + permissaoAggilizador1 = this.PermissaoAggilizador.FirstOrDefault((Gestor.Model.Common.PermissaoAggilizador x) => { + long id = x.get_Id(); + long? permissaoAggilizador = copiarPermiss.Item2.get_PermissaoAggilizador(); + return id == permissaoAggilizador.GetValueOrDefault() & permissaoAggilizador.HasValue; + }); + } + else + { + permissaoAggilizador1 = null; + } + this.SelectedPermissao = permissaoAggilizador1; + copiarPermiss.Item3.ForEach((RestricaoUsuario x) => { + foreach (RestricaoUsuario restricoesBi in this.RestricoesBis) + { + if (restricoesBi.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesBi.set_Restricao(x.get_Restricao()); + restricoesBi.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesSeguro in this.RestricoesSeguros) + { + if (restricoesSeguro.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesSeguro.set_Restricao(x.get_Restricao()); + restricoesSeguro.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesRelatorio in this.RestricoesRelatorios) + { + if (restricoesRelatorio.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesRelatorio.set_Restricao(x.get_Restricao()); + restricoesRelatorio.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesTotalizacoesRelatorio in this.RestricoesTotalizacoesRelatorios) + { + if (restricoesTotalizacoesRelatorio.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesTotalizacoesRelatorio.set_Restricao(x.get_Restricao()); + restricoesTotalizacoesRelatorio.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesFinanceiro in this.RestricoesFinanceiros) + { + if (restricoesFinanceiro.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesFinanceiro.set_Restricao(x.get_Restricao()); + restricoesFinanceiro.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesFerramenta in this.RestricoesFerramentas) + { + if (restricoesFerramenta.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesFerramenta.set_Restricao(x.get_Restricao()); + restricoesFerramenta.set_Usuario(this._selectedUsuario); + } + foreach (RestricaoUsuario restricoesAjuda in this.RestricoesAjudas) + { + if (restricoesAjuda.get_Tipo() != x.get_Tipo()) + { + continue; + } + restricoesAjuda.set_Restricao(x.get_Restricao()); + restricoesAjuda.set_Usuario(this._selectedUsuario); + } + }); + copiarPermiss.Item5.ForEach((RestricaoUsuarioCamposRelatorios x) => { + foreach (RestricaoUsuarioCamposRelatorios restricoesCamposRelatorio in this.RestricoesCamposRelatorios) + { + if (!(restricoesCamposRelatorio.get_Campo() == x.get_Campo()) || restricoesCamposRelatorio.get_Relatorio() != x.get_Relatorio()) + { + continue; + } + restricoesCamposRelatorio.set_Restricao(x.get_Restricao()); + restricoesCamposRelatorio.set_Usuario(this._selectedUsuario); + } + }); + base.RegistrarAcao(string.Concat("IMPORTOU PERMISSÕES/RESTRIÇÕES DO USUÁRIO \"", copiarPermiss.Item2.get_Nome(), "\""), this.SelectedUsuario.get_Id(), new TipoTela?(43), string.Format("ID USUÁRIO: {0}", copiarPermiss.Item2.get_Id())); + return true; + } + + public void DesabilitarArquivoDigital(PermissaoArquivoDigital desabilitar) + { + PermissaoArquivoDigital permissaoArquivoDigital = this.ArquivosDigitais.First((PermissaoArquivoDigital x) => x.get_Tela() == desabilitar.get_Tela()); + if (!permissaoArquivoDigital.get_Incluir() && !permissaoArquivoDigital.get_Excluir()) + { + return; + } + permissaoArquivoDigital.set_Incluir(false); + permissaoArquivoDigital.set_Excluir(false); + this.ArquivosDigitais = new ObservableCollection(this.ArquivosDigitais); + } + + public void DesabilitarConsulta(PermissaoUsuario desabilitar, string source) + { + if (source != "Ferramentas") + { + PermissaoUsuario permissaoUsuario = this.Seguros.First((PermissaoUsuario x) => x.get_Tela() == desabilitar.get_Tela()); + if (!permissaoUsuario.get_Incluir() && !permissaoUsuario.get_Alterar() && !permissaoUsuario.get_Excluir()) + { + return; + } + permissaoUsuario.set_Alterar(false); + permissaoUsuario.set_Incluir(false); + permissaoUsuario.set_Excluir(false); + this.Seguros = new ObservableCollection(this.Seguros); + return; + } + PermissaoUsuario permissaoUsuario1 = this.Ferramentas.First((PermissaoUsuario x) => x.get_Tela() == desabilitar.get_Tela()); + if (!permissaoUsuario1.get_Incluir() && !permissaoUsuario1.get_Alterar() && !permissaoUsuario1.get_Excluir()) + { + return; + } + permissaoUsuario1.set_Alterar(false); + permissaoUsuario1.set_Incluir(false); + permissaoUsuario1.set_Excluir(false); + this.Ferramentas = new ObservableCollection(this.Ferramentas); + } + + public async Task ExportarPermissoes(List usuarios) + { + object obj; + List usuarios1 = usuarios; + foreach (Usuario usuario in + from x in usuarios1 + where x.get_Selecionado() + select x) + { + await this.Salvar(new long?(usuario.get_Id()), false); + } + PermissaoUsuarioViewModel permissaoUsuarioViewModel = this; + string nome = this.SelectedUsuario.get_Nome(); + object count = usuarios.Count; + obj = (usuarios.Count == 1 ? "" : "S"); + string str = string.Format("EXPORTOU PERMISSÕES/RESTRIÇÕES DO USUÁRIO \"{0}\" PARA {1} USUÁRIO{2}", nome, count, obj); + long id = this.SelectedUsuario.get_Id(); + TipoTela? nullable = new TipoTela?(43); + List usuarios2 = usuarios; + permissaoUsuarioViewModel.RegistrarAcao(str, id, nullable, string.Concat("IDS E NOMES DOS USUÁRIOS: ", string.Join("\n", + from x in usuarios2 + select string.Format("{0}: \"{1}\"", x.get_Id(), x.get_Nome())))); + return true; + } + + internal async Task> FiltrarRestricoesAjuda(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesAjudas(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesAjudas(string filter) + { + this.RestricoesAjudasFiltrados = (filter == "" ? new ObservableCollection(this.RestricoesAjudas) : new ObservableCollection( + from x in this.RestricoesAjudas + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedAjudas = (this.RestricoesAjudasFiltrados.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesAjudasFiltrados.ToList(); + } + + internal async Task> FiltrarRestricoesBi(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesBis(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesBis(string filter) + { + this.RestricoesBisFiltradas = (filter == "" ? new ObservableCollection(this.RestricoesBis) : new ObservableCollection( + from x in this.RestricoesBis + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedBis = (this.RestricoesBisFiltradas.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesBisFiltradas.ToList(); + } + + internal async Task> FiltrarRestricoesCamposRelatorio(string value) + { + List restricaoUsuarioCamposRelatorios = await Task.Run>(() => this.FiltrarRestricoesCamposRelatorios(value)); + return restricaoUsuarioCamposRelatorios; + } + + public List FiltrarRestricoesCamposRelatorios(string filter) + { + this.RestricoesCamposRelatoriosFiltrados = (filter == "" ? new ObservableCollection(this.RestricoesCamposRelatorios) : new ObservableCollection(this.RestricoesCamposRelatorios.Where((RestricaoUsuarioCamposRelatorios x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Campo().ToUpper().Trim()).Contains(filter.ToUpper())) + { + return true; + } + return ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Relatorio()).Trim()).ToUpper().Contains(filter.ToUpper()); + }))); + this.ExpandedCampos = (this.RestricoesCamposRelatoriosFiltrados.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesCamposRelatoriosFiltrados.ToList(); + } + + internal async Task> FiltrarRestricoesFerramenta(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesFerramentas(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesFerramentas(string filter) + { + this.RestricoesFerramentasFiltradas = (filter == "" ? new ObservableCollection(this.RestricoesFerramentas) : new ObservableCollection( + from x in this.RestricoesFerramentas + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedFerramentas = (this.RestricoesFerramentasFiltradas.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesFerramentasFiltradas.ToList(); + } + + internal async Task> FiltrarRestricoesFinanceiro(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesFinanceiros(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesFinanceiros(string filter) + { + this.RestricoesFinanceirosFiltradas = (filter == "" ? new ObservableCollection(this.RestricoesFinanceiros) : new ObservableCollection( + from x in this.RestricoesFinanceiros + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedFinanceiros = (this.RestricoesFinanceirosFiltradas.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesFinanceirosFiltradas.ToList(); + } + + internal async Task> FiltrarRestricoesRelatorio(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesRelatorios(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesRelatorios(string filter) + { + this.RestricoesRelatoriosFiltrados = (filter == "" ? new ObservableCollection(this.RestricoesRelatorios) : new ObservableCollection( + from x in this.RestricoesRelatorios + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedRelatorios = (this.RestricoesRelatoriosFiltrados.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesRelatoriosFiltrados.ToList(); + } + + internal async Task> FiltrarRestricoesSeguro(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesSeguros(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesSeguros(string filter) + { + this.RestricoesSegurosFiltradas = (filter == "" ? new ObservableCollection(this.RestricoesSeguros) : new ObservableCollection( + from x in this.RestricoesSeguros + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedSeguros = (this.RestricoesSegurosFiltradas.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesSegurosFiltradas.ToList(); + } + + internal async Task> FiltrarRestricoesTotalizacoesRelatorio(string value) + { + List restricaoUsuarios = await Task.Run>(() => this.FiltrarRestricoesTotalizacoesRelatorios(value)); + return restricaoUsuarios; + } + + public List FiltrarRestricoesTotalizacoesRelatorios(string filter) + { + this.RestricoesTotalizacoesRelatoriosFiltrados = (filter == "" ? new ObservableCollection(this.RestricoesTotalizacoesRelatorios) : new ObservableCollection( + from x in this.RestricoesTotalizacoesRelatorios + where ValidationHelper.RemoveDiacritics(ValidationHelper.GetDescription(x.get_Tipo()).Trim()).ToUpper().Contains(filter.ToUpper()) + select x)); + this.ExpandedTotalizacoes = (this.RestricoesTotalizacoesRelatoriosFiltrados.Count <= 0 ? false : filter != ""); + if (filter == "") + { + return null; + } + return this.RestricoesTotalizacoesRelatoriosFiltrados.ToList(); + } + + private async Task> GetPermissoes(Usuario usuario, string modulo) + { + List permissaoUsuarios = new List(); + IEnumerable tipoTelas = Enum.GetValues(typeof(TipoTela)).Cast(); + IEnumerable str = + from v in tipoTelas + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List permissaoUsuarios1 = await this.ServicoPermissUsuario.PermissUsuario(usuario); + list.ForEach((string x) => { + TipoTela tipoTela = (TipoTela)Enum.Parse(typeof(TipoTela), x); + if (!string.Equals(ValidationHelper.GetCategory(tipoTela), modulo, StringComparison.CurrentCultureIgnoreCase)) + { + return; + } + long id = (long)0; + bool consultar = true; + bool incluir = true; + bool alterar = true; + bool excluir = true; + if (permissaoUsuarios1.Count > 0 && permissaoUsuarios1.Any((PermissaoUsuario y) => y.get_Tela() == tipoTela)) + { + id = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Id(); + consultar = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Consultar(); + incluir = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Incluir(); + alterar = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Alterar(); + excluir = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Excluir(); + } + PermissaoUsuario permissaoUsuario = new PermissaoUsuario(); + permissaoUsuario.set_Id(id); + permissaoUsuario.set_Tela(tipoTela); + permissaoUsuario.set_Consultar(consultar); + permissaoUsuario.set_Incluir(incluir); + permissaoUsuario.set_Alterar(alterar); + permissaoUsuario.set_Excluir(excluir); + permissaoUsuarios.Add(permissaoUsuario); + }); + List permissaoUsuarios2 = permissaoUsuarios; + list = null; + return permissaoUsuarios2; + } + + private async Task> GetPermissoesArquivoDigital(Usuario usuario) + { + List permissaoArquivoDigitals = new List(); + IEnumerable tipoArquivoDigitals = Enum.GetValues(typeof(TipoArquivoDigital)).Cast(); + IEnumerable str = + from v in tipoArquivoDigitals + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List permissaoArquivoDigitals1 = await this.ServicoPermissArquivoDigital.PermissArquivoDigital(usuario); + list.ForEach((string x) => { + TipoArquivoDigital tipoArquivoDigital = (TipoArquivoDigital)Enum.Parse(typeof(TipoArquivoDigital), x); + long id = (long)0; + bool consultar = true; + bool incluir = true; + bool excluir = true; + if (permissaoArquivoDigitals1.Count > 0 && permissaoArquivoDigitals1.Any((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital)) + { + id = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Id(); + consultar = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Consultar(); + incluir = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Incluir(); + excluir = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Excluir(); + } + PermissaoArquivoDigital permissaoArquivoDigital = new PermissaoArquivoDigital(); + permissaoArquivoDigital.set_Id(id); + permissaoArquivoDigital.set_Tela(tipoArquivoDigital); + permissaoArquivoDigital.set_Consultar(consultar); + permissaoArquivoDigital.set_Incluir(incluir); + permissaoArquivoDigital.set_Excluir(excluir); + permissaoArquivoDigitals.Add(permissaoArquivoDigital); + }); + List permissaoArquivoDigitals2 = permissaoArquivoDigitals; + list = null; + return permissaoArquivoDigitals2; + } + + private async Task> GetRestricoes(Usuario usuario, string modulo) + { + List restricaoUsuarios = new List(); + IEnumerable tipoRestricaos = Enum.GetValues(typeof(TipoRestricao)).Cast(); + IEnumerable str = + from v in tipoRestricaos + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List restricaoUsuarios1 = await this.ServicoRestriUsuario.BuscarRestricoes(usuario.get_Id()); + List restricaoUsuarios2 = restricaoUsuarios1; + list.ForEach((string x) => { + TipoRestricao tipoRestricao = (TipoRestricao)Enum.Parse(typeof(TipoRestricao), x); + if (!string.Equals(ValidationHelper.GetCategory(tipoRestricao), modulo, StringComparison.CurrentCultureIgnoreCase)) + { + return; + } + string help = ValidationHelper.GetHelp(tipoRestricao); + long id = (long)0; + bool restricao = false; + if (restricaoUsuarios2.Count > 0 && restricaoUsuarios2.Any((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao)) + { + id = restricaoUsuarios2.First((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao).get_Id(); + restricao = restricaoUsuarios2.First((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao).get_Restricao(); + } + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id(id); + restricaoUsuario.set_Tipo(tipoRestricao); + restricaoUsuario.set_Restricao(restricao); + restricaoUsuario.set_Ajuda(help); + restricaoUsuarios.Add(restricaoUsuario); + }); + List restricaoUsuarios3 = restricaoUsuarios; + list = null; + return restricaoUsuarios3; + } + + private async Task> GetRestricoesCamposRelatorios(Usuario usuario) + { + List restricaoUsuarioCamposRelatorios = new List(); + List parametrosRelatorios = new List(); + foreach (Relatorio relatorio in Enum.GetValues(typeof(Relatorio)).Cast()) + { + switch (relatorio) + { + case 0: + case 1: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 2: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 3: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 4: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 5: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 6: + case 16: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 7: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 8: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 9: + case 10: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 11: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 12: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 13: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 14: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 15: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 17: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 18: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 19: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 20: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 23: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 27: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + default: + { + continue; + } + } + } + List restricaoUsuarioCamposRelatorios1 = await this.ServicoRestriUsuario.BuscarRestricoesCamposRelatorios(usuario.get_Id()); + List restricaoUsuarioCamposRelatorios2 = restricaoUsuarioCamposRelatorios1; + parametrosRelatorios.ForEach((ParametrosRelatorio x) => { + long id = (long)0; + bool restricao = false; + if (restricaoUsuarioCamposRelatorios2.Count > 0 && restricaoUsuarioCamposRelatorios2.Any((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + })) + { + id = restricaoUsuarioCamposRelatorios2.First((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + }).get_Id(); + restricao = restricaoUsuarioCamposRelatorios2.First((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + }).get_Restricao(); + } + RestricaoUsuarioCamposRelatorios restricaoUsuarioCamposRelatorio = new RestricaoUsuarioCamposRelatorios(); + restricaoUsuarioCamposRelatorio.set_Id(id); + restricaoUsuarioCamposRelatorio.set_Campo(x.get_Header()); + restricaoUsuarioCamposRelatorio.set_Relatorio(x.get_Relatorio()); + restricaoUsuarioCamposRelatorio.set_Restricao(restricao); + restricaoUsuarioCamposRelatorios.Add(restricaoUsuarioCamposRelatorio); + }); + List restricaoUsuarioCamposRelatorios3 = restricaoUsuarioCamposRelatorios; + parametrosRelatorios = null; + return restricaoUsuarioCamposRelatorios3; + } + + public void HabilitarArquivoDigital(PermissaoArquivoDigital habilitar) + { + PermissaoArquivoDigital permissaoArquivoDigital = this.ArquivosDigitais.First((PermissaoArquivoDigital x) => x.get_Tela() == habilitar.get_Tela()); + if (permissaoArquivoDigital.get_Consultar()) + { + return; + } + permissaoArquivoDigital.set_Consultar(true); + this.ArquivosDigitais = new ObservableCollection(this.ArquivosDigitais); + } + + public void HabilitarConsulta(PermissaoUsuario habilitar, string source) + { + if (source != "Ferramentas") + { + PermissaoUsuario permissaoUsuario = this.Seguros.First((PermissaoUsuario x) => x.get_Tela() == habilitar.get_Tela()); + if (permissaoUsuario.get_Consultar()) + { + return; + } + permissaoUsuario.set_Consultar(true); + this.Seguros = new ObservableCollection(this.Seguros); + return; + } + PermissaoUsuario permissaoUsuario1 = this.Ferramentas.First((PermissaoUsuario x) => x.get_Tela() == habilitar.get_Tela()); + if (permissaoUsuario1.get_Consultar()) + { + return; + } + permissaoUsuario1.set_Consultar(true); + this.Ferramentas = new ObservableCollection(this.Ferramentas); + } + + private async Task Modulos(Usuario usuario) + { + Gestor.Model.Common.PermissaoAggilizador permissaoAggilizador1; + Usuario usuario1 = usuario; + this.Carregando = true; + Usuario usuario2 = await this._servicoUsuario.BuscarUsuarioPorId(usuario1.get_Id()); + usuario1 = usuario2; + this.Seguros = new ObservableCollection(await this.GetPermissoes(usuario1, "seguros")); + this.Ferramentas = new ObservableCollection(await this.GetPermissoes(usuario1, "ferramentas")); + this.ArquivosDigitais = new ObservableCollection(await this.GetPermissoesArquivoDigital(usuario1)); + this.PermissaoAggilizador = new List((IEnumerable)await this._servicoUsuario.BuscarPermissaoAggilizador()); + this.RestricoesBis = await this.GetRestricoes(usuario1, "b.i."); + this.RestricoesBisFiltradas = new ObservableCollection(this.RestricoesBis); + this.RestricoesSeguros = await this.GetRestricoes(usuario1, "seguros"); + this.RestricoesSegurosFiltradas = new ObservableCollection(this.RestricoesSeguros); + this.RestricoesRelatorios = await this.GetRestricoes(usuario1, "relatorios"); + this.RestricoesRelatoriosFiltrados = new ObservableCollection(this.RestricoesRelatorios); + this.RestricoesFinanceiros = await this.GetRestricoes(usuario1, "financeiro"); + this.RestricoesFinanceirosFiltradas = new ObservableCollection(this.RestricoesFinanceiros); + this.RestricoesFerramentas = await this.GetRestricoes(usuario1, "ferramentas"); + this.RestricoesFerramentasFiltradas = new ObservableCollection(this.RestricoesFerramentas); + this.RestricoesAjudas = await this.GetRestricoes(usuario1, "ajuda"); + this.RestricoesAjudasFiltrados = new ObservableCollection(this.RestricoesAjudas); + this.RestricoesTotalizacoesRelatorios = await this.GetRestricoes(usuario1, "totalizacoesRelatorios"); + this.RestricoesTotalizacoesRelatoriosFiltrados = new ObservableCollection(this.RestricoesTotalizacoesRelatorios); + this.RestricoesCamposRelatorios = await this.GetRestricoesCamposRelatorios(usuario1); + this.RestricoesCamposRelatoriosFiltrados = new ObservableCollection(this.RestricoesCamposRelatorios); + this.Carregando = false; + this.AdmUsuario = usuario1.get_Administrador(); + PermissaoUsuarioViewModel permissaoUsuarioViewModel = this; + if (!usuario1.get_PermissaoAggilizador().HasValue) + { + List permissaoAggilizadors = this.PermissaoAggilizador; + permissaoAggilizador1 = permissaoAggilizadors.FirstOrDefault((Gestor.Model.Common.PermissaoAggilizador x) => x.get_Id() == (long)2); + } + else + { + permissaoAggilizador1 = this.PermissaoAggilizador.FirstOrDefault((Gestor.Model.Common.PermissaoAggilizador x) => { + long id = x.get_Id(); + long? permissaoAggilizador = usuario1.get_PermissaoAggilizador(); + return id == permissaoAggilizador.GetValueOrDefault() & permissaoAggilizador.HasValue; + }); + } + permissaoUsuarioViewModel.SelectedPermissao = permissaoAggilizador1; + } + + public async Task Salvar(long? idUsuario = null, bool registrar = true) + { + bool flag; + bool alterar; + long num; + long id; + List permissaoUsuarios; + List restricaoUsuarioCamposRelatorios; + PermissaoUsuario permissaoUsuario1 = this.ServicoPermissUsuario.BuscarPermissao(Recursos.Usuario, 43); + if (permissaoUsuario1 != null) + { + alterar = !permissaoUsuario1.get_Alterar(); + } + else + { + alterar = false; + } + if (!alterar || Recursos.Usuario.get_Administrador()) + { + UsuarioServico usuarioServico = this._servicoUsuario; + long? nullable = idUsuario; + num = (nullable.HasValue ? nullable.GetValueOrDefault() : this._selectedUsuario.get_Id()); + Usuario usuario = await usuarioServico.BuscarUsuarioPorId(num); + List permissaoUsuarios1 = new List(); + List permissaoUsuarios2 = permissaoUsuarios1; + List permissoes = await this.GetPermissoes(usuario, "seguros"); + permissaoUsuarios2.AddRange(permissoes); + permissaoUsuarios2 = null; + permissaoUsuarios2 = permissaoUsuarios1; + permissoes = await this.GetPermissoes(usuario, "ferramentas"); + permissaoUsuarios2.AddRange(permissoes); + permissaoUsuarios2 = null; + List permissaoArquivoDigitals = new List(); + List permissaoArquivoDigitals1 = permissaoArquivoDigitals; + permissaoArquivoDigitals1.AddRange(await this.GetPermissoesArquivoDigital(usuario)); + permissaoArquivoDigitals1 = null; + List list = this.ArquivosDigitais.Select((PermissaoArquivoDigital x) => { + PermissaoArquivoDigital permissaoArquivoDigital = new PermissaoArquivoDigital(); + permissaoArquivoDigital.set_Id((permissaoArquivoDigitals.Count == 0 ? (long)0 : permissaoArquivoDigitals.First((PermissaoArquivoDigital y) => y.get_Tela() == x.get_Tela()).get_Id())); + permissaoArquivoDigital.set_Tela(x.get_Tela()); + permissaoArquivoDigital.set_Consultar(x.get_Consultar()); + permissaoArquivoDigital.set_Incluir(x.get_Incluir()); + permissaoArquivoDigital.set_Excluir(x.get_Excluir()); + permissaoArquivoDigital.set_Usuario(usuario); + return permissaoArquivoDigital; + }).ToList(); + permissaoUsuarios = new List(); + List list1 = this.Seguros.Select((PermissaoUsuario x) => { + PermissaoUsuario permissaoUsuario = new PermissaoUsuario(); + permissaoUsuario.set_Id((permissaoUsuarios1.Count == 0 ? (long)0 : permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == x.get_Tela()).get_Id())); + permissaoUsuario.set_Tela(x.get_Tela()); + permissaoUsuario.set_Consultar(x.get_Consultar()); + permissaoUsuario.set_Incluir(x.get_Incluir()); + permissaoUsuario.set_Alterar(x.get_Alterar()); + permissaoUsuario.set_Excluir(x.get_Excluir()); + permissaoUsuario.set_Usuario(usuario); + return permissaoUsuario; + }).ToList(); + permissaoUsuarios.AddRange(list1); + list1 = this.Ferramentas.Select((PermissaoUsuario x) => { + PermissaoUsuario permissaoUsuario = new PermissaoUsuario(); + permissaoUsuario.set_Id((permissaoUsuarios1.Count == 0 ? (long)0 : permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == x.get_Tela()).get_Id())); + permissaoUsuario.set_Tela(x.get_Tela()); + permissaoUsuario.set_Consultar(x.get_Consultar()); + permissaoUsuario.set_Incluir(x.get_Incluir()); + permissaoUsuario.set_Alterar(x.get_Alterar()); + permissaoUsuario.set_Excluir(x.get_Excluir()); + permissaoUsuario.set_Usuario(usuario); + return permissaoUsuario; + }).ToList(); + permissaoUsuarios.AddRange(list1); + Usuario usuario1 = usuario; + Gestor.Model.Common.PermissaoAggilizador selectedPermissao = this.SelectedPermissao; + if (selectedPermissao != null) + { + id = selectedPermissao.get_Id(); + } + else + { + id = (long)0; + } + usuario1.set_PermissaoAggilizador(new long?(id)); + usuario.set_Administrador(this.AdmUsuario); + await this.ServicoPermissArquivoDigital.SavePermiss(list, permissaoArquivoDigitals); + if (this.ServicoPermissArquivoDigital.Sucesso) + { + await this.ServicoPermissUsuario.SavePermiss(permissaoUsuarios, permissaoUsuarios1); + if (this.ServicoPermissUsuario.Sucesso) + { + await this._servicoUsuario.Save(usuario); + if (this._servicoUsuario.Sucesso) + { + if (Recursos.Usuario.get_Id() == this._selectedUsuario.get_Id()) + { + Recursos.Usuario = usuario; + } + List restricaoUsuarios = new List(); + List restricaoUsuarios1 = restricaoUsuarios; + List restricoes = await this.GetRestricoes(usuario, "b.i."); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "seguros"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "relatorios"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "financeiro"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "ferramentas"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "ajuda"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "totalizacoesRelatorios"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + restricaoUsuarios1 = restricaoUsuarios; + restricoes = await this.GetRestricoes(usuario, "camposRelatorios"); + restricaoUsuarios1.AddRange(restricoes); + restricaoUsuarios1 = null; + List restricaoUsuarioCamposRelatorios1 = new List(); + List restricaoUsuarioCamposRelatorios2 = restricaoUsuarioCamposRelatorios1; + restricaoUsuarioCamposRelatorios2.AddRange(await this.GetRestricoesCamposRelatorios(usuario)); + restricaoUsuarioCamposRelatorios2 = null; + List restricaoUsuarios2 = new List(); + restricaoUsuarioCamposRelatorios = new List(); + List list2 = this.RestricoesBis.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesSeguros.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesRelatorios.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesTotalizacoesRelatorios.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesFinanceiros.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesFerramentas.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + list2 = this.RestricoesAjudas.Select((RestricaoUsuario x) => { + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id((restricaoUsuarios.Count == 0 ? (long)0 : restricaoUsuarios.First((RestricaoUsuario y) => y.get_Tipo() == x.get_Tipo()).get_Id())); + restricaoUsuario.set_Tipo(x.get_Tipo()); + restricaoUsuario.set_Restricao(x.get_Restricao()); + restricaoUsuario.set_Usuario(usuario); + return restricaoUsuario; + }).ToList(); + restricaoUsuarios2.AddRange(list2); + List list3 = this.RestricoesCamposRelatorios.Select((RestricaoUsuarioCamposRelatorios x) => { + RestricaoUsuarioCamposRelatorios restricaoUsuarioCamposRelatorio = new RestricaoUsuarioCamposRelatorios(); + restricaoUsuarioCamposRelatorio.set_Id((restricaoUsuarioCamposRelatorios1.Count == 0 ? (long)0 : restricaoUsuarioCamposRelatorios1.First((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Campo()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + }).get_Id())); + restricaoUsuarioCamposRelatorio.set_Campo(x.get_Campo()); + restricaoUsuarioCamposRelatorio.set_Restricao(x.get_Restricao()); + restricaoUsuarioCamposRelatorio.set_Relatorio(x.get_Relatorio()); + restricaoUsuarioCamposRelatorio.set_Usuario(usuario); + return restricaoUsuarioCamposRelatorio; + }).ToList(); + restricaoUsuarioCamposRelatorios.AddRange(list3); + await this.ServicoRestriUsuario.SaveRestri(restricaoUsuarios2, restricaoUsuarios); + if (this.ServicoRestriUsuario.Sucesso) + { + await this.ServicoRestriUsuario.SaveRestriCamposRelatorios(restricaoUsuarioCamposRelatorios, restricaoUsuarioCamposRelatorios1); + if (this.ServicoRestriUsuario.Sucesso) + { + if (registrar) + { + base.RegistrarAcao(string.Concat("ALTEROU PERMISSÕES/RESTRIÇÕES DO USUÁRIO \"", this.SelectedUsuario.get_Nome(), "\""), this.SelectedUsuario.get_Id(), new TipoTela?(43), "ACESSE O LOG DE ALTERAÇÕES NA TELA DE PERMISSÕES/RESTRIÇÕES PARA VER EXATAMENTE O QUE FOI ALTERADO."); + } + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + else + { + flag = false; + } + } + else + { + await base.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA ALTERAR PERMISSÕES!", "OK", "", false); + flag = false; + } + permissaoUsuarios = null; + restricaoUsuarioCamposRelatorios = null; + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/TarefaDrawerViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/TarefaDrawerViewModel.cs new file mode 100644 index 0000000..6a68199 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/TarefaDrawerViewModel.cs @@ -0,0 +1,1283 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class TarefaDrawerViewModel : BaseTarefaViewModel + { + private bool _enableMenu = true; + + private GridLength _dados = new GridLength(0, GridUnitType.Pixel); + + private GridLength _grid = new GridLength(1, GridUnitType.Star); + + private GridLength _anotacoesLength = new GridLength(0, GridUnitType.Pixel); + + private GridLength _descricaoLength = new GridLength(1, GridUnitType.Star); + + private GridLength _anotacoesInternasLength = new GridLength(0, GridUnitType.Pixel); + + private GridLength _descricaoInternaLength = new GridLength(1, GridUnitType.Star); + + private bool _enableAlterarTarefa = true; + + private Visibility _visibilityMenu; + + private bool _isVisibleDescricao; + + private bool _isSelected; + + private bool _concluido; + + private bool _carregando; + + private string _tituloTarefas; + + private string _titulo; + + private string _subTitulo; + + private Gestor.Model.Domain.Ferramentas.Tarefa _tarefa = new Gestor.Model.Domain.Ferramentas.Tarefa(); + + private ObservableCollection _tarefasFiltradas = new ObservableCollection(); + + private List _tarefas = new List(); + + private bool _isAnotacoes = true; + + private Gestor.Model.Domain.Ferramentas.Tarefa _selectedTarefa; + + private ObservableCollection _usuarios; + + private ObservableCollection _tiposTarefa; + + private List _telefones; + + private DateTime _dataAgendamento = Funcoes.GetNetworkTime(); + + private DateTime _horaAgendamento = Funcoes.GetNetworkTime(); + + private Usuario _selectedUsuario; + + private TipoDeTarefa _selectedTipoTarefa; + + private Gestor.Model.Domain.Common.ArquivoDigital _selectedAnexado = new Gestor.Model.Domain.Common.ArquivoDigital(); + + private ObservableCollection _arquivosAnexados = new ObservableCollection(); + + private List _arquivosFinais = new List(); + + private bool _inclusaoArquivoDigitalEnable = true; + + public GridLength AnotacoesInternasLength + { + get + { + return this._anotacoesInternasLength; + } + set + { + this._anotacoesInternasLength = value; + base.OnPropertyChanged("AnotacoesInternasLength"); + } + } + + public GridLength AnotacoesLength + { + get + { + return this._anotacoesLength; + } + set + { + this._anotacoesLength = value; + base.OnPropertyChanged("AnotacoesLength"); + } + } + + public ObservableCollection ArquivosAnexados + { + get + { + return this._arquivosAnexados; + } + set + { + this._arquivosAnexados = value; + base.OnPropertyChanged("ArquivosAnexados"); + } + } + + public List ArquivosFinais + { + get + { + return this._arquivosFinais; + } + set + { + this._arquivosFinais = value; + base.OnPropertyChanged("ArquivosFinais"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.IsEnabled = !value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool Concluido + { + get + { + return this._concluido; + } + set + { + this._concluido = value; + base.OnPropertyChanged("Concluido"); + } + } + + public GridLength Dados + { + get + { + return this._dados; + } + set + { + this._dados = value; + base.OnPropertyChanged("Dados"); + } + } + + public DateTime DataAgendamento + { + get + { + return this._dataAgendamento; + } + set + { + this._dataAgendamento = value; + if (this.SelectedTarefa != null) + { + this.SelectedTarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", value, this.SelectedTarefa.get_Agendamento()))); + } + base.OnPropertyChanged("DataAgendamento"); + } + } + + public GridLength DescricaoInternaLength + { + get + { + return this._descricaoInternaLength; + } + set + { + this._descricaoInternaLength = value; + base.OnPropertyChanged("DescricaoInternaLength"); + } + } + + public GridLength DescricaoLength + { + get + { + return this._descricaoLength; + } + set + { + this._descricaoLength = value; + base.OnPropertyChanged("DescricaoLength"); + } + } + + public override bool EnableAlterarTarefa + { + get + { + return this._enableAlterarTarefa; + } + set + { + this._enableAlterarTarefa = this._alterarPermissEnabled & value; + base.OnPropertyChanged("EnableAlterarTarefa"); + } + } + + public GridLength Grid + { + get + { + return this._grid; + } + set + { + this._grid = value; + base.OnPropertyChanged("Grid"); + } + } + + public DateTime HoraAgendamento + { + get + { + return this._horaAgendamento; + } + set + { + this._horaAgendamento = value; + if (this.SelectedTarefa != null) + { + this.SelectedTarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", this.SelectedTarefa.get_Agendamento(), value))); + } + base.OnPropertyChanged("HoraAgendamento"); + } + } + + public long IdCliente + { + get; + set; + } + + public bool InclusaoArquivoDigitalEnable + { + get + { + return this._inclusaoArquivoDigitalEnable; + } + set + { + this._inclusaoArquivoDigitalEnable = value; + base.OnPropertyChanged("InclusaoArquivoDigitalEnable"); + } + } + + private int Index { get; set; } = 1; + + public bool IsAnotacoes + { + get + { + return this._isAnotacoes; + } + set + { + this._isAnotacoes = value; + base.OnPropertyChanged("IsAnotacoes"); + } + } + + public bool IsSelected + { + get + { + return this._isSelected; + } + set + { + this._isSelected = value; + base.OnPropertyChanged("IsSelected"); + } + } + + public bool IsVisibleDescricao + { + get + { + return this._isVisibleDescricao; + } + set + { + this._isVisibleDescricao = value; + base.OnPropertyChanged("IsVisibleDescricao"); + } + } + + public Gestor.Model.Domain.Common.ArquivoDigital SelectedAnexado + { + get + { + return this._selectedAnexado; + } + set + { + this._selectedAnexado = value; + base.OnPropertyChanged("SelectedAnexado"); + } + } + + public override Gestor.Model.Domain.Ferramentas.Tarefa SelectedTarefa + { + get + { + return this._selectedTarefa; + } + set + { + DateTime agendamento; + DateTime dateTime; + bool status; + ObservableCollection observableCollection; + bool tipoDeTarefa; + TipoDeTarefa tipoDeTarefa1; + long? nullable; + bool usuario; + ObservableCollection observableCollection1; + DateTime networkTime = Funcoes.GetNetworkTime(); + this.IsSelected = value != null; + this._selectedTarefa = value; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = value; + if (tarefa != null) + { + agendamento = tarefa.get_Agendamento(); + } + else + { + agendamento = networkTime; + } + this.DataAgendamento = agendamento; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = value; + if (tarefa1 != null) + { + dateTime = tarefa1.get_Agendamento(); + } + else + { + dateTime = networkTime; + } + this.HoraAgendamento = dateTime; + this.IsVisibleDescricao = value != null; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa2 = value; + if (tarefa2 != null) + { + status = tarefa2.get_Status() == 2; + } + else + { + status = false; + } + this.Concluido = status; + if (value == null) + { + observableCollection = new ObservableCollection(); + } + else + { + observableCollection = (value.get_Responsaveis() == null ? new ObservableCollection() : new ObservableCollection(value.get_Responsaveis())); + } + base.Responsaveis = observableCollection; + if (!base.Responsaveis.Any()) + { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa3 = value; + if (tarefa3 != null) + { + usuario = tarefa3.get_Usuario(); + } + else + { + usuario = false; + } + if (!usuario) + { + observableCollection1 = new ObservableCollection(); + } + else + { + ResponsavelTarefa[] responsavelTarefaArray = new ResponsavelTarefa[1]; + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_Usuario(value.get_Usuario()); + responsavelTarefaArray[0] = responsavelTarefa; + observableCollection1 = new ObservableCollection(responsavelTarefaArray); + } + base.Responsaveis = observableCollection1; + } + if (value != null && value.get_Id() > (long)0) + { + this.AlterarTamanho(false); + } + if (value != null) + { + this.AnotacoesLength = new GridLength(0, GridUnitType.Pixel); + this.AnotacoesInternasLength = new GridLength(0, GridUnitType.Pixel); + this.DescricaoLength = (string.IsNullOrWhiteSpace(value.get_Descricao()) ? new GridLength(0, GridUnitType.Pixel) : new GridLength(1, GridUnitType.Star)); + this.DescricaoInternaLength = (string.IsNullOrWhiteSpace(value.get_DescricaoInterna()) ? new GridLength(0, GridUnitType.Pixel) : new GridLength(1, GridUnitType.Star)); + } + Gestor.Model.Domain.Ferramentas.Tarefa tarefa4 = value; + if (tarefa4 != null) + { + tipoDeTarefa = tarefa4.get_TipoDeTarefa(); + } + else + { + tipoDeTarefa = false; + } + if (tipoDeTarefa) + { + if (!this.TiposTarefa.All((TipoDeTarefa x) => x.get_Id() != value.get_Id()) || value.get_TipoDeTarefa().get_Ativo()) + { + this.TiposTarefa = new ObservableCollection(( + from x in this.TiposTarefa + where x.get_Ativo() + select x).ToList()); + } + else + { + this.TiposTarefa.Add(value.get_TipoDeTarefa()); + } + } + Gestor.Model.Domain.Ferramentas.Tarefa tarefa5 = value; + if (tarefa5 != null) + { + tipoDeTarefa1 = tarefa5.get_TipoDeTarefa(); + } + else + { + tipoDeTarefa1 = null; + } + this.SelectedTipoTarefa = tipoDeTarefa1; + if (base.EnableIncluir || base.EnableFields || base.EnableButtons) + { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa6 = value; + if (tarefa6 != null) + { + nullable = new long?(tarefa6.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + } + base.ValidaPermissaoParaEditarTarefa(); + base.OnPropertyChanged("SelectedTarefa"); + } + } + + public TipoDeTarefa SelectedTipoTarefa + { + get + { + return this._selectedTipoTarefa; + } + set + { + this._selectedTipoTarefa = value; + base.OnPropertyChanged("SelectedTipoTarefa"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + private new TarefaServico Servico + { + get; + } + + public string SubTitulo + { + get + { + return this._subTitulo; + } + set + { + this._subTitulo = value; + base.OnPropertyChanged("SubTitulo"); + } + } + + public Gestor.Model.Domain.Ferramentas.Tarefa Tarefa + { + get + { + return this._tarefa; + } + set + { + this._tarefa = value; + base.OnPropertyChanged("Tarefa"); + } + } + + public List Tarefas + { + get + { + return this._tarefas; + } + set + { + this._tarefas = value; + base.OnPropertyChanged("Tarefas"); + } + } + + public ObservableCollection TarefasFiltradas + { + get + { + return this._tarefasFiltradas; + } + set + { + this._tarefasFiltradas = value; + base.OnPropertyChanged("TarefasFiltradas"); + } + } + + public List Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public ObservableCollection TiposTarefa + { + get + { + return this._tiposTarefa; + } + set + { + this._tiposTarefa = value; + base.OnPropertyChanged("TiposTarefa"); + } + } + + public string Titulo + { + get + { + return this._titulo; + } + set + { + this._titulo = value; + base.OnPropertyChanged("Titulo"); + } + } + + public string TituloTarefas + { + get + { + return this._tituloTarefas; + } + set + { + this._tituloTarefas = value; + base.OnPropertyChanged("TituloTarefas"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public Visibility VisibilityMenu + { + get + { + return this._visibilityMenu; + } + set + { + this._visibilityMenu = value; + base.OnPropertyChanged("VisibilityMenu"); + } + } + + public TarefaDrawerViewModel(Gestor.Model.Domain.Ferramentas.Tarefa tarefa, bool enableMenu) + { + this.Servico = new TarefaServico(); + this.Tarefa = tarefa; + this._enableMenu = enableMenu; + this.CarregarUsuarios(); + this.TiposTarefa = new ObservableCollection(( + from x in Recursos.TiposTarefa + where x.get_Ativo() + select x).ToList()); + DateTime? conclusao = tarefa.get_Conclusao(); + this.SelecionarTarefas(tarefa, new bool?(conclusao.HasValue)); + this.TituloTarefas = (tarefa.get_Conclusao().HasValue ? "TAREFAS CONCLUÍDAS" : "TAREFAS PENDENTES"); + base.EnableMenu = true; + } + + public void AdcionarResponsavel() + { + if (this.SelectedUsuario == null) + { + return; + } + ObservableCollection responsaveis = base.Responsaveis; + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_Usuario(this.SelectedUsuario); + responsavelTarefa.set_IdTarefa(this.SelectedTarefa.get_Id()); + responsaveis.Add(responsavelTarefa); + this.Usuarios.Remove(this.SelectedUsuario); + this.SelectedUsuario = null; + } + + public void AlterarTamanho(bool alterar) + { + if (!alterar) + { + if (this.TituloTarefas.Contains("TODAS")) + { + this.TituloTarefas = "TODAS TAREFAS DO CLIENTE"; + } + else if (this.TituloTarefas.Contains("PENDENTES")) + { + this.TituloTarefas = "TAREFAS PENDENTES"; + } + else if (this.TituloTarefas.Contains("CONCLUÍDAS")) + { + this.TituloTarefas = "TAREFAS CONCLUÍDAS"; + } + } + this.Grid = (alterar ? new GridLength(0, GridUnitType.Star) : new GridLength(1, GridUnitType.Star)); + this.Dados = (alterar ? new GridLength(1, GridUnitType.Star) : new GridLength(360, GridUnitType.Pixel)); + } + + public void AlterarTarefa() + { + string descricao; + string descricaoInterna; + this.CarregarUsuarios(); + if (this.SelectedTarefa == null) + { + return; + } + this.EnableAlterarTarefa = false; + this.AlterarTamanho(true); + this.TituloTarefas = string.Concat(this.TituloTarefas, " (ALTERANDO \"", this.SelectedTarefa.get_Titulo(), "\")"); + base.Alterar(true); + this.AnotacoesLength = new GridLength(1, GridUnitType.Star); + this.AnotacoesInternasLength = new GridLength(1, GridUnitType.Star); + Gestor.Model.Domain.Ferramentas.Tarefa selectedTarefa = this.SelectedTarefa; + if (selectedTarefa != null) + { + descricao = selectedTarefa.get_Descricao(); + } + else + { + descricao = null; + } + this.DescricaoLength = (string.IsNullOrWhiteSpace(descricao) ? new GridLength(0, GridUnitType.Pixel) : new GridLength(1, GridUnitType.Star)); + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = this.SelectedTarefa; + if (tarefa != null) + { + descricaoInterna = tarefa.get_DescricaoInterna(); + } + else + { + descricaoInterna = null; + } + this.DescricaoInternaLength = (string.IsNullOrWhiteSpace(descricaoInterna) ? new GridLength(0, GridUnitType.Pixel) : new GridLength(1, GridUnitType.Star)); + this.TarefasFiltradas = new ObservableCollection() + { + this.SelectedTarefa + }; + base.ListaUsuariosResponsaveis(); + base.Responsaveis.ToList().ForEach((ResponsavelTarefa x) => this.Usuarios.Remove(x.get_Usuario())); + } + + public async void Anexar() + { + this.InclusaoArquivoDigitalEnable = false; + List arquivoDigitals = await base.AddAttachments(this.ArquivosAnexados.ToList(), new List()); + await Task.Run(async () => { + await Task.Delay(200); + this.InclusaoArquivoDigitalEnable = true; + }); + if (arquivoDigitals != null) + { + arquivoDigitals.AddRange(this.ArquivosAnexados); + this.ArquivosAnexados = new ObservableCollection(arquivoDigitals); + } + arquivoDigitals = null; + } + + public async Task Cancelar() + { + long id; + this.CarregarUsuarios(); + this.AlterarTamanho(false); + Gestor.Model.Domain.Ferramentas.Tarefa selectedTarefa = this.SelectedTarefa; + if (selectedTarefa != null) + { + id = selectedTarefa.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + await this.CarregarTarefas(this.Index); + base.Alterar(false); + await base.ValidaPermissaoParaEditarTarefa(); + if (num != 0) + { + this.SelectedTarefa = this.TarefasFiltradas.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Tarefa x) => x.get_Id() == num); + } + } + + public async void CarregarInformacoes(Gestor.Model.Domain.Ferramentas.Tarefa tarefa) + { + string str; + string str1; + ClienteServico clienteServico = new ClienteServico(); + TarefaDrawerViewModel tarefaDrawerViewModel = this; + str = (tarefa.get_IdEntidade() != 0 ? "TODAS AS TAREFAS PENDENTES DO CLIENTE" : ""); + tarefaDrawerViewModel.SubTitulo = str; + this.IdCliente = tarefa.get_IdCliente(); + this.Titulo = tarefa.get_Cliente(); + ObservableCollection observableCollection = await clienteServico.BuscarTelefonesAsync(tarefa.get_IdCliente()); + TarefaDrawerViewModel list = this; + ObservableCollection observableCollection1 = observableCollection; + IEnumerable clienteTelefones = + from x in observableCollection1 + where Gestor.Model.Helper.ValidationHelper.ValidacaoTelefone(x.get_Numero()) + select x; + list.Telefones = clienteTelefones.Select((ClienteTelefone x) => { + TelefoneBase telefoneBase = new TelefoneBase(); + telefoneBase.set_Tipo(x.get_Tipo()); + telefoneBase.set_Id(x.get_Id()); + telefoneBase.set_Numero(x.get_Numero()); + telefoneBase.set_Prefixo(x.get_Prefixo()); + return telefoneBase; + }).ToList(); + if (tarefa.get_IdEntidade() != 0) + { + TipoTarefa entidade = tarefa.get_Entidade(); + if (entidade == null) + { + Documento documento = await (new ApoliceServico()).BuscarApoliceAsync(tarefa.get_IdEntidade(), false, false); + this.IdCliente = documento.get_Controle().get_Cliente().get_Id(); + this.Titulo = documento.get_Controle().get_Cliente().get_Nome(); + TarefaDrawerViewModel tarefaDrawerViewModel1 = this; + if (documento.get_Tipo() != 0 || string.IsNullOrWhiteSpace(documento.get_Apolice())) + { + str1 = (documento.get_Tipo() > 0 ? string.Concat("APÓLICE NÚMERO ", documento.get_Apolice(), " ENDOSSO ", documento.get_Endosso()) : string.Concat("PROPOSTA NÚMERO ", documento.get_Proposta())); + } + else + { + str1 = string.Concat("APÓLICE NÚMERO ", documento.get_Apolice()); + } + tarefaDrawerViewModel1.SubTitulo = str1; + observableCollection = await clienteServico.BuscarTelefonesAsync(documento.get_Controle().get_Cliente().get_Id()); + TarefaDrawerViewModel list1 = this; + ObservableCollection observableCollection2 = observableCollection; + IEnumerable clienteTelefones1 = + from x in observableCollection2 + where Gestor.Model.Helper.ValidationHelper.ValidacaoTelefone(x.get_Numero()) + select x; + list1.Telefones = clienteTelefones1.Select((ClienteTelefone x) => { + TelefoneBase telefoneBase = new TelefoneBase(); + telefoneBase.set_Tipo(x.get_Tipo()); + telefoneBase.set_Id(x.get_Id()); + telefoneBase.set_Numero(x.get_Numero()); + telefoneBase.set_Prefixo(x.get_Prefixo()); + return telefoneBase; + }).ToList(); + } + else if (entidade == 4) + { + Sinistro sinistro = await (new SinistroServico()).BuscarSinistro(tarefa.get_IdEntidade()); + if (sinistro != null) + { + this.IdCliente = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id(); + this.Titulo = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome(); + this.SubTitulo = string.Concat("SINISTRO ", sinistro.get_Numero(), " ITEM ", sinistro.get_ItemSinistrado()); + observableCollection = await clienteServico.BuscarTelefonesAsync(this.IdCliente); + TarefaDrawerViewModel list2 = this; + ObservableCollection observableCollection3 = observableCollection; + IEnumerable clienteTelefones2 = + from x in observableCollection3 + where Gestor.Model.Helper.ValidationHelper.ValidacaoTelefone(x.get_Numero()) + select x; + list2.Telefones = clienteTelefones2.Select((ClienteTelefone x) => { + TelefoneBase telefoneBase = new TelefoneBase(); + telefoneBase.set_Tipo(x.get_Tipo()); + telefoneBase.set_Id(x.get_Id()); + telefoneBase.set_Numero(x.get_Numero()); + telefoneBase.set_Prefixo(x.get_Prefixo()); + return telefoneBase; + }).ToList(); + } + else + { + clienteServico = null; + return; + } + } + } + clienteServico = null; + } + + public async Task CarregarTarefas(int index) + { + List tarefas; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa; + if (this.Tarefa.get_IdEntidade() != 0) + { + this.Carregando = true; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa1.set_Cliente(this.Tarefa.get_Cliente()); + tarefa1.set_IdCliente(this.Tarefa.get_IdCliente()); + tarefa1.set_Entidade(this.Tarefa.get_Entidade()); + tarefa1.set_IdEntidade(this.Tarefa.get_IdEntidade()); + Gestor.Model.Domain.Ferramentas.Tarefa tarefa2 = tarefa1; + this.Index = index; + int num = index; + if (num == 1) + { + this.CarregarInformacoes(tarefa2); + tarefas = await this.Servico.BuscarTarefas(this.Tarefa.get_Entidade(), this.Tarefa.get_IdEntidade(), new bool?(false)); + } + else if (num == 2) + { + tarefa2.set_Entidade(2); + this.CarregarInformacoes(tarefa2); + tarefas = await this.Servico.BuscarTarefasCliente(this.Tarefa.get_IdCliente()); + } + else + { + this.CarregarInformacoes(tarefa2); + tarefas = await this.Servico.BuscarTarefas(this.Tarefa.get_Entidade(), this.Tarefa.get_IdEntidade(), new bool?(true)); + } + TarefaDrawerViewModel list = this; + List tarefas1 = tarefas; + list.Tarefas = ( + from x in tarefas1 + orderby x.get_Agendamento() descending + select x).ToList(); + this.TarefasFiltradas = new ObservableCollection(this.Tarefas); + TarefaDrawerViewModel tarefaDrawerViewModel = this; + if (this.TarefasFiltradas == null || this.TarefasFiltradas.Count == 0) + { + tarefa = null; + } + else + { + tarefa = (tarefa2.get_Id() != 0 ? this.TarefasFiltradas.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Tarefa x) => x.get_Id() == tarefa2.get_Id()) : this.TarefasFiltradas.First()); + } + tarefaDrawerViewModel.SelectedTarefa = tarefa; + this.Carregando = false; + } + } + + public async Task CarregarTarefas(Gestor.Model.Domain.Ferramentas.Tarefa tarefa, bool? concluido) + { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1; + this.Carregando = true; + if (tarefa.get_IdEntidade() != 0) + { + List tarefas = await this.Servico.BuscarTarefas(tarefa.get_Entidade(), tarefa.get_IdEntidade(), concluido); + TarefaDrawerViewModel list = this; + List tarefas1 = tarefas; + list.Tarefas = ( + from x in tarefas1 + orderby x.get_Agendamento() + select x).ToList(); + this.TarefasFiltradas = new ObservableCollection(this.Tarefas); + TarefaDrawerViewModel tarefaDrawerViewModel = this; + if (this.TarefasFiltradas == null || this.TarefasFiltradas.Count == 0) + { + tarefa1 = null; + } + else + { + tarefa1 = (tarefa.get_Id() != 0 ? this.TarefasFiltradas.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Tarefa x) => x.get_Id() == tarefa.get_Id()) : this.TarefasFiltradas.First()); + } + tarefaDrawerViewModel.SelectedTarefa = tarefa1; + } + else if (tarefa.get_Id() > (long)0) + { + this.SelectedTarefa = await this.Servico.BuscarTarefa(tarefa.get_Id()); + } + this.Carregando = false; + } + + private void CarregarUsuarios() + { + this.Usuarios = new ObservableCollection(Recursos.Usuarios.Where((Usuario x) => { + if (!Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 36) && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa() || x.get_Excluido()) + { + return false; + } + long? permissaoAggilizador = x.get_PermissaoAggilizador(); + long num = (long)4; + return !(permissaoAggilizador.GetValueOrDefault() == num & permissaoAggilizador.HasValue); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + } + + public void Delete(Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + if (this.SelectedAnexado == null) + { + return; + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = this.ArquivosAnexados.First((Gestor.Model.Domain.Common.ArquivoDigital x) => x.get_Descricao() == arquivo.get_Descricao()); + this.ArquivosAnexados.Remove(arquivoDigital); + this.ArquivosAnexados = new ObservableCollection(this.ArquivosAnexados); + } + + public async void Editar(IndiceArquivoDigital arquivo) + { + if (arquivo != null && arquivo.get_IdArquivoDigital() != 0) + { + await this.ArquivoDigitalServico.Save(arquivo); + } + } + + public async Task Excluir(Gestor.Model.Domain.Ferramentas.Tarefa item) + { + bool flag; + string titulo; + if (this.VisibilityMenu != Visibility.Collapsed) + { + string[] strArrays = new string[] { "DESEJA REALMENTE EXCLUIR A TAREFA ", item.get_Titulo(), "?", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL" }; + if (await base.ShowMessage(string.Concat(strArrays), "SIM", "NÃO", false)) + { + titulo = item.get_Titulo(); + long id = item.get_Id(); + if (await this.Servico.Excluir(item.get_Id())) + { + base.RegistrarAcao("EXCLUIU TAREFA", item.get_Id(), new TipoTela?(38), string.Format("TAREFA \"{0}\", ID: {1}", titulo, id)); + await this.CarregarTarefas(this.Index); + base.Alterar(false); + flag = true; + } + else + { + base.Alterar(false); + flag = true; + } + } + else + { + flag = false; + } + } + else + { + await base.ShowMessage("NÃO É POSSÍVEL EXCLUIR TAREFA PELO RELATÓRIO!", "OK", "", false); + flag = false; + } + titulo = null; + return flag; + } + + public string GerarHtml() + { + string nome; + string str = " TAREFA
"; + str = string.Concat(str, "
"); + str = string.Concat(str, "

"); + str = string.Concat(str, "TAREFA


"); + str = string.Concat(str, ""); + int num = 0; + string[] cliente = new string[] { str, ""; + str = string.Concat(cliente); + string[] referencia = new string[] { str, ""; + str = string.Concat(referencia); + string[] titulo = new string[] { str, ""; + str = string.Concat(titulo); + string[] strArrays = new string[] { str, ""; + str = string.Concat(strArrays); + string[] nome1 = new string[] { str, ""; + str = string.Concat(nome1); + string[] description = new string[] { str, ""; + str = string.Concat(description); + string[] strArrays1 = new string[] { str, ""; + str = string.Concat(strArrays1); + str = string.Concat(str, "

CLIENTE: "; + cliente[4] = this.SelectedTarefa.get_Cliente(); + cliente[5] = "

REFERÊNCIA: "; + referencia[4] = this.SelectedTarefa.get_Referencia(); + referencia[5] = "

TÍTULO: "; + titulo[4] = this.SelectedTarefa.get_Titulo(); + titulo[5] = "

AGENDAMENTO: "; + DateTime agendamento = this.SelectedTarefa.get_Agendamento(); + strArrays[4] = agendamento.ToString(); + strArrays[5] = "

RESPONSÁVEL PRINCIPAL: "; + nome1[4] = this.SelectedTarefa.get_Usuario().get_Nome(); + nome1[5] = "

STATUS: "; + description[4] = Gestor.Common.Validation.ValidationHelper.GetDescription(this.SelectedTarefa.get_Status()); + description[5] = "

TIPO DE TAREFA: "; + TipoDeTarefa selectedTipoTarefa = this.SelectedTipoTarefa; + if (selectedTipoTarefa != null) + { + nome = selectedTipoTarefa.get_Nome(); + } + else + { + nome = null; + } + strArrays1[4] = nome; + strArrays1[5] = "

"); + if (base.Responsaveis != null && base.Responsaveis.Count > 0) + { + str = string.Concat(str, "

RESPONSÁVEIS VINCULADOS

"); + str = string.Concat(str, "
"); + str = string.Concat(str, ""); + List strs = new List(); + foreach (ResponsavelTarefa responsavei in base.Responsaveis) + { + strs.Add(responsavei.get_Usuario().get_Nome().Trim().ToUpper()); + } + str = string.Concat(str, ""); + str = string.Concat(str, "

", string.Join(", ", strs), "

"); + str = string.Concat(str, "

"); + } + str = string.Concat(str, "

"); + if (this.SelectedTarefa.get_Descricao() != null) + { + str = string.Concat(str, "

ANOTAÇÕES

"); + str = string.Concat(str, "
"); + str = string.Concat(str, ""); + str = string.Concat(str, ""); + str = string.Concat(str, "

", this.SelectedTarefa.get_Descricao().Replace("", "").Replace("", ""), "

"); + str = string.Concat(str, "

"); + } + str = string.Concat(str, "
"); + return str; + } + + public async Task Incluir() + { + TarefaDrawerViewModel observableCollection = this; + observableCollection.CarregarUsuarios(); + observableCollection.Responsaveis = new ObservableCollection(); + TarefaDrawerViewModel tarefaDrawerViewModel = observableCollection; + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa.set_IdCliente(observableCollection.IdCliente); + tarefa.set_Cliente(observableCollection.Titulo); + tarefa.set_Referencia(observableCollection.SubTitulo); + tarefa.set_Entidade(observableCollection.Tarefa.get_Entidade()); + tarefa.set_IdEntidade(observableCollection.Tarefa.get_IdEntidade()); + tarefa.set_Trilha(observableCollection.Tarefa.get_Trilha()); + tarefa.set_Status(0); + tarefa.set_Agendamento(Funcoes.GetNetworkTime().AddHours(1)); + tarefa.set_UsuarioCadastro(Recursos.Usuario); + ObservableCollection usuarios = observableCollection.Usuarios; + tarefa.set_Usuario(usuarios.FirstOrDefault((Usuario x) => x.get_Id() == Recursos.Usuario.get_Id())); + tarefa.set_Restrito(new bool?(false)); + tarefa.set_Responsaveis(observableCollection.Responsaveis.ToList()); + tarefaDrawerViewModel.SelectedTarefa = tarefa; + observableCollection.ArquivosFinais = new List(); + observableCollection.AlterarTamanho(true); + observableCollection.TituloTarefas = string.Concat(observableCollection.TituloTarefas, " (INCLUINDO)"); + observableCollection.Alterar(true); + observableCollection.AnotacoesLength = new GridLength(1, GridUnitType.Star); + observableCollection.AnotacoesInternasLength = new GridLength(1, GridUnitType.Star); + observableCollection.DescricaoLength = new GridLength(0, GridUnitType.Pixel); + observableCollection.DescricaoInternaLength = new GridLength(0, GridUnitType.Pixel); + observableCollection.EnableAlterarTarefa = false; + } + + public void LimparAnexos() + { + this.ArquivosAnexados = new ObservableCollection(); + } + + public void Print() + { + string str = this.GerarHtml(); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoTela)38, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + base.RegistrarAcao("IMPRIMIU A TAREFA", this.SelectedTarefa.get_Id(), new TipoTela?(38), string.Format("TAREFA \"{0}\", ID: {1}", this.SelectedTarefa.get_Titulo(), this.SelectedTarefa.get_Id())); + } + + public async Task>> Salvar(string anotacoes, string anotacoesInternas) + { + List> keyValuePairs; + Usuario usuario; + DateTime networkTime = Funcoes.GetNetworkTime(); + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 45) && this.SelectedTarefa.get_Status() != 2 && this.SelectedTarefa.get_Agendamento() < networkTime) + { + this.SelectedTarefa.set_Agendamento(networkTime); + } + if (this.SelectedTarefa.get_Status() == 2) + { + this.SelectedTarefa.set_Conclusao(new DateTime?(networkTime)); + } + if (this.SelectedTarefa.get_Status() == null) + { + this.SelectedTarefa.set_Conclusao(null); + } + this.SelectedTarefa.set_Responsaveis(base.Responsaveis.ToList()); + Gestor.Model.Domain.Ferramentas.Tarefa selectedTarefa = this.SelectedTarefa; + ResponsavelTarefa responsavelTarefa = base.Responsaveis.FirstOrDefault(); + if (responsavelTarefa != null) + { + usuario = responsavelTarefa.get_Usuario(); + } + else + { + usuario = null; + } + selectedTarefa.set_Usuario(usuario); + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = this.SelectedTarefa; + List configuracaoSistemas = Recursos.Configuracoes; + tarefa.set_AgendamentoRetroativo(configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs1 = this.SelectedTarefa.Validate(); + if (this.SelectedTarefa.get_Descricao() == null && string.IsNullOrWhiteSpace(anotacoes) && string.IsNullOrWhiteSpace(anotacoesInternas)) + { + keyValuePairs1.Add(new KeyValuePair("ANOTAÇÕES", "OBRIGATÓRIO")); + } + if (keyValuePairs1.Count <= 0) + { + if (!string.IsNullOrWhiteSpace(anotacoes)) + { + this.SelectedTarefa.set_Anotacoes(Funcoes.AdicionarLog(this.SelectedTarefa.get_Anotacoes())); + this.SelectedTarefa.set_Descricao(string.Concat(this.SelectedTarefa.get_Anotacoes(), "

", this.SelectedTarefa.get_Descricao(), "

")); + } + if (!string.IsNullOrWhiteSpace(anotacoesInternas)) + { + this.SelectedTarefa.set_AnotacoesInternas(Funcoes.AdicionarLog(this.SelectedTarefa.get_AnotacoesInternas())); + this.SelectedTarefa.set_DescricaoInterna(string.Concat(this.SelectedTarefa.get_AnotacoesInternas(), "

", this.SelectedTarefa.get_DescricaoInterna(), "

")); + } + this.SelectedTarefa.set_TipoDeTarefa(this.SelectedTipoTarefa); + bool id = this.SelectedTarefa.get_Id() == (long)0; + this.SelectedTarefa = await this.Servico.Salvar(this.SelectedTarefa); + string str = (id ? "INCLUIU" : "ALTEROU"); + base.RegistrarAcao(string.Concat(str, " TAREFA"), this.SelectedTarefa.get_Id(), new TipoTela?(38), string.Format("TAREFA \"{0}\", ID: {1}", this.SelectedTarefa.get_Titulo(), this.SelectedTarefa.get_Id())); + if (id) + { + foreach (Gestor.Model.Domain.Common.ArquivoDigital arquivosFinai in this.ArquivosFinais) + { + arquivosFinai.set_IdTarefa(this.SelectedTarefa.get_Id()); + } + await this.ArquivoDigitalServico.Insert(this.ArquivosFinais); + } + if (this.Servico.Sucesso) + { + long num = this.SelectedTarefa.get_Id(); + await this.CarregarTarefas(this.Index); + this.SelectedTarefa = this.TarefasFiltradas.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Tarefa x) => x.get_Id() == num); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + public void SalvarAnexos() + { + this.ArquivosFinais = this.ArquivosAnexados.ToList(); + } + + public async void SelecionarTarefas(Gestor.Model.Domain.Ferramentas.Tarefa tarefa, bool? concluido) + { + await base.PermissaoTela(38); + this.CarregarInformacoes(tarefa); + await this.CarregarTarefas(tarefa, concluido); + if (tarefa.get_Id() != 0 && !this._enableMenu) + { + this.VisibilityMenu = Visibility.Collapsed; + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresApoliceViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresApoliceViewModel.cs new file mode 100644 index 0000000..df49b81 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresApoliceViewModel.cs @@ -0,0 +1,345 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ValoresApoliceViewModel : BaseSegurosViewModel + { + private Visibility _isVisibleEspecial; + + private Visibility _isVisibleVendedores; + + private decimal _prevista; + + private decimal _recebida; + + private decimal _recebidaEspecial; + + private decimal _pendente; + + private decimal _repasse; + + private decimal _repasseEspecial; + + private decimal _paga; + + private decimal _pagaEspecial; + + private string _apoliceLabel = "DESCRIÇÃO DE VALORES"; + + private string _apoliceDescricao = "VALORES BASEADOS NO DOCUMENTO SELECIONADO ATÉ O MOMENTO, OS VALORES PODEM SER DIFERENTES EM CASO DE ALTERAÇÕES POR OUTROS USUÁRIOS."; + + private Documento _selectedDocumento; + + private ObservableCollection _pagamentos; + + public string ApoliceDescricao + { + get + { + return this._apoliceDescricao; + } + set + { + this._apoliceDescricao = value; + base.OnPropertyChanged("ApoliceDescricao"); + } + } + + public string ApoliceLabel + { + get + { + return this._apoliceLabel; + } + set + { + this._apoliceLabel = value; + base.OnPropertyChanged("ApoliceLabel"); + } + } + + public Visibility IsVisibleEspecial + { + get + { + return this._isVisibleEspecial; + } + set + { + this._isVisibleEspecial = value; + base.OnPropertyChanged("IsVisibleEspecial"); + } + } + + public Visibility IsVisibleVendedores + { + get + { + return this._isVisibleVendedores; + } + set + { + this._isVisibleVendedores = value; + base.OnPropertyChanged("IsVisibleVendedores"); + } + } + + public decimal Paga + { + get + { + return this._paga; + } + set + { + this._paga = value; + base.OnPropertyChanged("Paga"); + } + } + + public decimal PagaEspecial + { + get + { + return this._pagaEspecial; + } + set + { + this._pagaEspecial = value; + base.OnPropertyChanged("PagaEspecial"); + } + } + + public ObservableCollection Pagamentos + { + get + { + return this._pagamentos; + } + set + { + this._pagamentos = value; + base.OnPropertyChanged("Pagamentos"); + } + } + + public decimal Pendente + { + get + { + return this._pendente; + } + set + { + this._pendente = value; + base.OnPropertyChanged("Pendente"); + } + } + + public decimal Prevista + { + get + { + return this._prevista; + } + set + { + this._prevista = value; + base.OnPropertyChanged("Prevista"); + } + } + + public decimal Recebida + { + get + { + return this._recebida; + } + set + { + this._recebida = value; + base.OnPropertyChanged("Recebida"); + } + } + + public decimal RecebidaEspecial + { + get + { + return this._recebidaEspecial; + } + set + { + this._recebidaEspecial = value; + base.OnPropertyChanged("RecebidaEspecial"); + } + } + + public decimal Repasse + { + get + { + return this._repasse; + } + set + { + this._repasse = value; + base.OnPropertyChanged("Repasse"); + } + } + + public decimal RepasseEspecial + { + get + { + return this._repasseEspecial; + } + set + { + this._repasseEspecial = value; + base.OnPropertyChanged("RepasseEspecial"); + } + } + + public Documento SelectedDocumento + { + get + { + return this._selectedDocumento; + } + set + { + this._selectedDocumento = value; + base.OnPropertyChanged("SelectedDocumento"); + } + } + + public ValoresApoliceViewModel(Documento documento) + { + base.EnableMenu = true; + this.Seleciona(documento); + } + + private void CalculaComissao() + { + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1) + { + this.Prevista = ( + from x in this.SelectedDocumento.get_Parcelas() + where x.get_SubTipo() == 1 + select x).Sum((Parcela x) => x.get_ValorLiquidoFatura() * (x.get_Comissao() < decimal.One ? x.get_Comissao() : (x.get_Comissao() > new decimal(100) ? decimal.One : x.get_Comissao() * new decimal(1, 0, 0, false, 2)))); + } + else + { + decimal num = (this.SelectedDocumento.get_AdicionalComiss() ? this.SelectedDocumento.get_PremioLiquido() + this.SelectedDocumento.get_PremioAdicional() : this.SelectedDocumento.get_PremioLiquido()); + decimal comissao = this.SelectedDocumento.get_Comissao() * new decimal(1, 0, 0, false, 2); + this.Prevista = num * comissao; + } + this.Recebida = ( + from x in this.SelectedDocumento.get_Parcelas() + where x.get_SubTipo() == 1 + select x).Sum((Parcela x) => x.get_ValorComissao()); + this.Pendente = this.Prevista - this.Recebida; + this.Repasse = ( + from x in this.SelectedDocumento.get_Pagamentos() + where x.get_Parcela().get_SubTipo() == 1 + select x).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + this.Paga = this.SelectedDocumento.get_Pagamentos().Where((VendedorParcela x) => { + if (x.get_Parcela().get_SubTipo() != 1) + { + return false; + } + return x.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + } + + private void CalculaEspecial() + { + if (this.SelectedDocumento.get_Parcelas().All((Parcela x) => x.get_SubTipo() == 1)) + { + this.IsVisibleEspecial = Visibility.Collapsed; + return; + } + this.RecebidaEspecial = ( + from x in this.SelectedDocumento.get_Parcelas() + where x.get_SubTipo() != 1 + select x).Sum((Parcela x) => x.get_ValorComissao()); + this.RepasseEspecial = ( + from x in this.SelectedDocumento.get_Pagamentos() + where x.get_Parcela().get_SubTipo() != 1 + select x).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + this.PagaEspecial = this.SelectedDocumento.get_Pagamentos().Where((VendedorParcela x) => { + if (x.get_Parcela().get_SubTipo() == 1) + { + return false; + } + return x.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + } + + private void CalculaRepasse() + { + if (this.SelectedDocumento.get_Pagamentos().All((VendedorParcela x) => x.get_Vendedor().get_Corretora())) + { + this.IsVisibleVendedores = Visibility.Collapsed; + return; + } + List list = ( + from x in this.SelectedDocumento.get_Pagamentos() + where !x.get_Vendedor().get_Corretora() + group x by x.get_Vendedor().get_Id()).Select, VendedorParcela>((IGrouping x) => { + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(x.First().get_Repasse()); + vendedorParcela.set_Documento(this.SelectedDocumento); + vendedorParcela.set_ValorTotal(x.First().get_ValorTotal()); + vendedorParcela.set_Vendedor(x.First().get_Vendedor()); + vendedorParcela.set_ValorTotalPago(x.Where((VendedorParcela y) => { + if (y.get_Parcela().get_SubTipo() != 1) + { + return false; + } + return y.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela y) => y.get_ValorRepasse())); + vendedorParcela.set_ValorRepasseB(( + from y in x + where y.get_Parcela().get_SubTipo() != 1 + select y).Sum((VendedorParcela y) => y.get_ValorRepasse())); + vendedorParcela.set_ValorRepasse(x.Where((VendedorParcela y) => { + if (y.get_Parcela().get_SubTipo() == 1) + { + return false; + } + return y.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela y) => y.get_ValorRepasse())); + decimal? porcentagemRepasse = x.First().get_PorcentagemRepasse(); + vendedorParcela.set_PorcentagemRepasse((porcentagemRepasse.HasValue ? new decimal?(porcentagemRepasse.GetValueOrDefault() / 100) : null)); + vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); + return vendedorParcela; + }).ToList(); + this.Pagamentos = new ObservableCollection(list); + } + + public void Seleciona(Documento documento) + { + this.SelectedDocumento = documento; + if (this.SelectedDocumento.get_Tipo() != 1) + { + this.ApoliceLabel = (!this.SelectedDocumento.get_Emissao().HasValue ? string.Concat("VALORES DA PROPOSTA ", this.SelectedDocumento.get_Proposta()) : string.Concat("VALORES DA APÓLICE ", this.SelectedDocumento.get_Apolice())); + this.ApoliceDescricao = (!this.SelectedDocumento.get_Emissao().HasValue ? string.Concat("VALORES BASEADOS NA PROPOSTA ", this.SelectedDocumento.get_Proposta(), " ATÉ O MOMENTO, OS VALORES PODEM SER DIFERENTES EM CASO DE ALTERAÇÕES POR OUTROS USUÁRIOS.") : string.Concat("VALORES BASEADOS NA APÓLICE ", this.SelectedDocumento.get_Apolice(), " ATÉ O MOMENTO, OS VALORES PODEM SER DIFERENTES EM CASO DE ALTERAÇÕES POR OUTROS USUÁRIOS.")); + } + this.CalculaComissao(); + this.CalculaEspecial(); + this.CalculaRepasse(); + base.RegistrarAcao(string.Format("CONSULTOU MAIS INFORMAÇÕES DOS VALORES DO DOCUMENTO DE ID {0}", documento.get_Id()), documento.get_Id(), new TipoTela?(21), null); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresParcelaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresParcelaViewModel.cs new file mode 100644 index 0000000..867e88d --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/ValoresParcelaViewModel.cs @@ -0,0 +1,583 @@ +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class ValoresParcelaViewModel : BaseSegurosViewModel + { + private ParcelaPendente _pendecia; + + private Visibility _isVisiblePendencia = Visibility.Collapsed; + + private Visibility _isVisibleFatura; + + private Visibility _isVisibleVendedores; + + private decimal _prevista; + + private decimal _ir; + + private decimal _iss; + + private string _repassePago; + + private decimal _recebidaLiquida; + + private decimal _recebida; + + private decimal _recebidaEspecial; + + private decimal _pendente; + + private decimal _repasse; + + private decimal _repasseEspecial; + + private decimal _paga; + + private decimal _pagaEspecial; + + private string _apoliceLabel = "DESCRIÇÃO DE VALORES"; + + private string _apoliceDescricao = "VALORES BASEADOS NO DOCUMENTO SELECIONADO ATÉ O MOMENTO, OS VALORES PODEM SER DIFERENTES EM CASO DE ALTERAÇÕES POR OUTROS USUÁRIOS."; + + private Parcela _selectedParcela; + + private string _statusBaixa; + + private string _statusParc; + + private Visibility _isVisiblestatusparc = Visibility.Collapsed; + + private ObservableCollection _pagamentos; + + public string ApoliceDescricao + { + get + { + return this._apoliceDescricao; + } + set + { + this._apoliceDescricao = value; + base.OnPropertyChanged("ApoliceDescricao"); + } + } + + public string ApoliceLabel + { + get + { + return this._apoliceLabel; + } + set + { + this._apoliceLabel = value; + base.OnPropertyChanged("ApoliceLabel"); + } + } + + public decimal Ir + { + get + { + return this._ir; + } + set + { + this._ir = value; + base.OnPropertyChanged("Ir"); + } + } + + public decimal Iss + { + get + { + return this._iss; + } + set + { + this._iss = value; + base.OnPropertyChanged("Iss"); + } + } + + public Visibility IsVisibleFatura + { + get + { + return this._isVisibleFatura; + } + set + { + this._isVisibleFatura = value; + base.OnPropertyChanged("IsVisibleFatura"); + } + } + + public Visibility IsVisiblePendencia + { + get + { + return this._isVisiblePendencia; + } + set + { + this._isVisiblePendencia = value; + base.OnPropertyChanged("IsVisiblePendencia"); + } + } + + public Visibility IsVisibleStatusParc + { + get + { + return this._isVisiblestatusparc; + } + set + { + this._isVisiblestatusparc = value; + base.OnPropertyChanged("IsVisibleStatusParc"); + } + } + + public Visibility IsVisibleVendedores + { + get + { + return this._isVisibleVendedores; + } + set + { + this._isVisibleVendedores = value; + base.OnPropertyChanged("IsVisibleVendedores"); + } + } + + public decimal Paga + { + get + { + return this._paga; + } + set + { + this._paga = value; + base.OnPropertyChanged("Paga"); + } + } + + public decimal PagaEspecial + { + get + { + return this._pagaEspecial; + } + set + { + this._pagaEspecial = value; + base.OnPropertyChanged("PagaEspecial"); + } + } + + public ObservableCollection Pagamentos + { + get + { + return this._pagamentos; + } + set + { + this._pagamentos = value; + base.OnPropertyChanged("Pagamentos"); + } + } + + public ParcelaPendente Pendecia + { + get + { + return this._pendecia; + } + set + { + this._pendecia = value; + this.IsVisiblePendencia = (value == null ? Visibility.Collapsed : Visibility.Visible); + base.OnPropertyChanged("Pendecia"); + } + } + + public decimal Pendente + { + get + { + return this._pendente; + } + set + { + if (value >= new decimal(1, 0, 0, false, 2)) + { + this._pendente = value; + } + else + { + this._pendente = new decimal(); + } + base.OnPropertyChanged("Pendente"); + } + } + + public decimal Prevista + { + get + { + return this._prevista; + } + set + { + this._prevista = value; + base.OnPropertyChanged("Prevista"); + } + } + + public decimal Recebida + { + get + { + return this._recebida; + } + set + { + this._recebida = value; + base.OnPropertyChanged("Recebida"); + } + } + + public decimal RecebidaEspecial + { + get + { + return this._recebidaEspecial; + } + set + { + this._recebidaEspecial = value; + base.OnPropertyChanged("RecebidaEspecial"); + } + } + + public decimal RecebidaLiquida + { + get + { + return this._recebidaLiquida; + } + set + { + this._recebidaLiquida = value; + base.OnPropertyChanged("RecebidaLiquida"); + } + } + + public decimal Repasse + { + get + { + return this._repasse; + } + set + { + this._repasse = value; + base.OnPropertyChanged("Repasse"); + } + } + + public decimal RepasseEspecial + { + get + { + return this._repasseEspecial; + } + set + { + this._repasseEspecial = value; + base.OnPropertyChanged("RepasseEspecial"); + } + } + + public string RepassePago + { + get + { + return this._repassePago; + } + set + { + this._repassePago = value; + base.OnPropertyChanged("RepassePago"); + } + } + + public Parcela SelectedParcela + { + get + { + return this._selectedParcela; + } + set + { + this._selectedParcela = value; + base.OnPropertyChanged("SelectedParcela"); + } + } + + public string StatusBaixa + { + get + { + return this._statusBaixa; + } + set + { + this._statusBaixa = value; + base.OnPropertyChanged("StatusBaixa"); + } + } + + public string StatusParc + { + get + { + return this._statusParc; + } + set + { + this._statusParc = value; + base.OnPropertyChanged("StatusParc"); + } + } + + public ValoresParcelaViewModel(Parcela parcela, Documento documento) + { + this.Seleciona(parcela, documento); + } + + private async void BuscarPendencia() + { + this.Pendecia = await (new BaseServico()).BuscarParcelaPendente(this.SelectedParcela.get_IdParcelaPendente()); + } + + private void CalculaComissao(Documento documento) + { + decimal valor; + if (this.SelectedParcela.get_SubTipo() != 1) + { + valor = this.SelectedParcela.get_Valor(); + } + else if (documento.get_NumeroParcelas() == decimal.Zero) + { + valor = decimal.Zero; + } + else + { + valor = (documento.get_AdicionalComiss() ? (documento.get_PremioLiquido() + documento.get_PremioAdicional()) / documento.get_NumeroParcelas() : documento.get_PremioLiquido() / documento.get_NumeroParcelas()); + } + decimal num = valor; + this.Prevista = (this.SelectedParcela.get_ValorLiquidoFatura() != decimal.Zero ? (this.SelectedParcela.get_ValorLiquidoFatura() * this.SelectedParcela.get_Comissao()) * new decimal(1, 0, 0, false, 2) : (num * this.SelectedParcela.get_Comissao()) * new decimal(1, 0, 0, false, 2)); + this.Recebida = this.SelectedParcela.get_ValorComissao(); + this.Pendente = this.Prevista - this.Recebida; + this.Repasse = this.SelectedParcela.get_Vendedores().Where((VendedorParcela x) => { + if (this.SelectedParcela.get_SubTipo() == 1) + { + return x.get_Parcela().get_SubTipo() == 1; + } + return x.get_Parcela().get_SubTipo() != 1; + }).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + this.Paga = this.SelectedParcela.get_Vendedores().Where((VendedorParcela x) => { + if (this.SelectedParcela.get_SubTipo() == 1) + { + return x.get_Parcela().get_SubTipo() == 1; + } + if (x.get_Parcela().get_SubTipo() == 1) + { + return false; + } + return x.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + this.Ir = this.SelectedParcela.get_Irr(); + this.Iss = this.SelectedParcela.get_Iss(); + this.RecebidaLiquida = this.SelectedParcela.get_ValorComDesconto(); + } + + private void CalculaRepasse() + { + if (this.SelectedParcela.get_Vendedores().All((VendedorParcela x) => x.get_Vendedor().get_Corretora())) + { + this.IsVisibleVendedores = Visibility.Collapsed; + return; + } + List list = ( + from x in this.SelectedParcela.get_Vendedores() + where !x.get_Vendedor().get_Corretora() + group x by x.get_Vendedor().get_Id()).Select, VendedorParcela>((IGrouping x) => { + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(x.First().get_Repasse()); + vendedorParcela.set_Documento(this.SelectedParcela.get_Documento()); + vendedorParcela.set_ValorTotal(x.First().get_ValorTotal()); + vendedorParcela.set_Vendedor(x.First().get_Vendedor()); + vendedorParcela.set_ValorTotalPago(x.Where((VendedorParcela y) => { + if (y.get_Parcela().get_SubTipo() != 1) + { + return false; + } + return y.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela y) => y.get_ValorRepasse())); + vendedorParcela.set_ValorRepasseB(( + from y in x + where y.get_Parcela().get_SubTipo() != 1 + select y).Sum((VendedorParcela y) => y.get_ValorRepasse())); + vendedorParcela.set_ValorRepasse(x.Where((VendedorParcela y) => { + if (y.get_Parcela().get_SubTipo() == 1) + { + return false; + } + return y.get_DataPrePagamento().HasValue; + }).Sum((VendedorParcela y) => y.get_ValorRepasse())); + decimal? porcentagemRepasse = x.First().get_PorcentagemRepasse(); + vendedorParcela.set_PorcentagemRepasse((porcentagemRepasse.HasValue ? new decimal?(porcentagemRepasse.GetValueOrDefault() / 100) : null)); + vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); + return vendedorParcela; + }).ToList(); + this.Pagamentos = new ObservableCollection(list); + } + + public async void Seleciona(Parcela parcela, Documento documento) + { + StatusPagamento? statusPagamento; + Visibility visibility; + string str; + string str1; + this.SelectedParcela = parcela; + ValoresParcelaViewModel valoresParcelaViewModel = this; + visibility = (this.SelectedParcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2 ? Visibility.Visible : Visibility.Collapsed); + valoresParcelaViewModel.IsVisibleFatura = visibility; + this.ApoliceLabel = string.Format("VALORES DA PARCELA {0} VENCIMENTO {1:d}", this.SelectedParcela.get_NumeroParcela(), parcela.get_Vencimento()); + this.ApoliceDescricao = string.Format("VALORES BASEADOS NA PARCELA {0} ATÉ O MOMENTO, OS VALORES PODEM SER DIFERENTES EM CASO DE ALTERAÇÕES POR OUTROS USUÁRIOS.", this.SelectedParcela.get_NumeroParcela()); + this.StatusBaixa = "PENDENTE"; + this.RepassePago = "REPASSE A SER PAGO"; + if (this.SelectedParcela.get_DataRecebimento().HasValue) + { + ValoresParcelaViewModel valoresParcelaViewModel1 = this; + if (this.SelectedParcela.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2) + { + str = "BAIXA MANUAL"; + } + else + { + str = (this.SelectedParcela.get_ValorRealizado() == decimal.Zero ? "BAIXA ESGOTAMENTO" : "BAIXA MANUAL"); + } + valoresParcelaViewModel1.StatusBaixa = str; + DetalheExtrato detalheExtrato = await (new ServicoExtrato()).FindByParcelaId(this.SelectedParcela.get_Id()); + if (detalheExtrato != null) + { + StatusParcela? status = detalheExtrato.get_Status(); + if (status.HasValue) + { + StatusParcela valueOrDefault = status.GetValueOrDefault(); + if (valueOrDefault != 1) + { + if (valueOrDefault != 5) + { + switch (valueOrDefault) + { + case 10: + case 13: + { + goto Label1; + } + case 11: + { + this.CalculaComissao(documento); + this.CalculaRepasse(); + if (this.SelectedParcela.get_IdParcelaPendente() > (long)0) + { + statusPagamento = this.SelectedParcela.get_StatusPagamento(); + if (statusPagamento.GetValueOrDefault() != 0 | !statusPagamento.HasValue) + { + this.BuscarPendencia(); + } + } + return; + } + case 12: + { + break; + } + default: + { + this.CalculaComissao(documento); + this.CalculaRepasse(); + if (this.SelectedParcela.get_IdParcelaPendente() > (long)0) + { + statusPagamento = this.SelectedParcela.get_StatusPagamento(); + if (statusPagamento.GetValueOrDefault() != 0 | !statusPagamento.HasValue) + { + this.BuscarPendencia(); + } + } + return; + } + } + } + this.RepassePago = "REPASSE PAGO"; + this.StatusBaixa = "BAIXA MANUAL"; + this.CalculaComissao(documento); + this.CalculaRepasse(); + if (this.SelectedParcela.get_IdParcelaPendente() > (long)0) + { + statusPagamento = this.SelectedParcela.get_StatusPagamento(); + if (statusPagamento.GetValueOrDefault() != 0 | !statusPagamento.HasValue) + { + this.BuscarPendencia(); + } + } + return; + } + Label1: + this.IsVisibleStatusParc = Visibility.Visible; + this.StatusParc = ValidationHelper.GetDescription(detalheExtrato.get_Status()); + this.RepassePago = "REPASSE PAGO"; + ValoresParcelaViewModel valoresParcelaViewModel2 = this; + str1 = (this.SelectedParcela.get_ValorRealizado() == decimal.Zero ? "BAIXA AUTOMATICA ESGOTAMENTO" : "BAIXA AUTOMATICA"); + valoresParcelaViewModel2.StatusBaixa = str1; + } + } + } + this.CalculaComissao(documento); + this.CalculaRepasse(); + if (this.SelectedParcela.get_IdParcelaPendente() > (long)0) + { + statusPagamento = this.SelectedParcela.get_StatusPagamento(); + if (statusPagamento.GetValueOrDefault() != 0 | !statusPagamento.HasValue) + { + this.BuscarPendencia(); + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Drawer/VinculoVendedorViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Drawer/VinculoVendedorViewModel.cs new file mode 100644 index 0000000..bba206b --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Drawer/VinculoVendedorViewModel.cs @@ -0,0 +1,307 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Infrastructure.UnitOfWork.Generic; +using Gestor.Infrastructure.UnitOfWork.Logic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Net; +using System.Net.Sockets; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Drawer +{ + public class VinculoVendedorViewModel : BaseSegurosViewModel + { + private readonly VendedorUsuarioServico _servicoVendedorUsuario; + + private readonly VendedorServico _servicoVendedor; + + public readonly Usuario SelectedUsuario; + + private bool _isVisibleVinculado; + + private bool _enableAlterarVinculo; + + private bool _isVisibleVendedor = true; + + private List _vinculado; + + private List _vinculadoFiltro; + + private List _vendedor; + + private List _vendedorFiltro; + + public bool EnableAlterarVinculo + { + get + { + return this._enableAlterarVinculo; + } + set + { + this._enableAlterarVinculo = value; + base.OnPropertyChanged("EnableAlterarVinculo"); + } + } + + public bool IsVisibleVendedor + { + get + { + return this._isVisibleVendedor; + } + set + { + this._isVisibleVendedor = value; + base.OnPropertyChanged("IsVisibleVendedor"); + } + } + + public bool IsVisibleVinculado + { + get + { + return this._isVisibleVinculado; + } + set + { + this._isVisibleVinculado = value; + base.OnPropertyChanged("IsVisibleVinculado"); + } + } + + public List Vendedor + { + get + { + return this._vendedor; + } + set + { + this._vendedor = value; + this.IsVisibleVendedor = (value == null ? false : value.Count > 0); + base.OnPropertyChanged("Vendedor"); + } + } + + public List VendedorFiltro + { + get + { + return this._vendedorFiltro; + } + set + { + this._vendedorFiltro = value; + base.OnPropertyChanged("VendedorFiltro"); + } + } + + public List Vinculado + { + get + { + return this._vinculado; + } + set + { + this._vinculado = value; + this.IsVisibleVinculado = (value == null ? false : value.Count > 0); + base.OnPropertyChanged("Vinculado"); + } + } + + public List VinculadoFiltro + { + get + { + return this._vinculadoFiltro; + } + set + { + this._vinculadoFiltro = value; + base.OnPropertyChanged("VinculadoFiltro"); + } + } + + public VinculoVendedorViewModel(Usuario usuario) + { + this.SelectedUsuario = usuario; + this._servicoVendedorUsuario = new VendedorUsuarioServico(); + this._servicoVendedor = new VendedorServico(); + this.Load(usuario); + this.EnableAlterarVinculo = Recursos.Usuario.get_Id() > (long)0; + base.EnableMenu = true; + } + + private async Task AwaitLoad(Usuario usuario) + { + this.Vinculado = await this.GetVinculo(usuario); + this.Vendedor = await this.GetVendedor(usuario); + this.VinculadoFiltro = this.Vinculado; + this.VendedorFiltro = this.Vendedor; + } + + internal async Task BuscarVinculoVendedor(string value) + { + await Task.Run(() => this.FiltrarVinculoVendedor(value)); + } + + internal void FiltrarVinculoVendedor(string filter) + { + this.Vinculado = (string.IsNullOrEmpty(filter) ? this.VinculadoFiltro : new List( + from x in this.VinculadoFiltro + where Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Vendedor().get_Nome().ToUpper().Trim()).Contains(filter.ToUpper()) + select x)); + this.Vendedor = (string.IsNullOrEmpty(filter) ? this.VendedorFiltro : new List( + from x in this.VendedorFiltro + where Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Vendedor().get_Nome().ToUpper().Trim()).Contains(filter.ToUpper()) + select x)); + } + + private async Task> GetVendedor(Usuario usuario) + { + List list; + List vinculoVendedors; + List vendedors = await this._servicoVendedor.BuscarVendedoresAtivosAsync(); + if (vendedors != null) + { + list = ( + from x in vendedors + where x.get_IdEmpresa() == usuario.get_IdEmpresa() + select x).ToList(); + } + else + { + list = null; + } + vendedors = list; + if (vendedors == null || vendedors.Count == 0) + { + vinculoVendedors = null; + } + else + { + IEnumerable vendedors1 = + from vendedor in vendedors + where this.Vinculado.All((VinculoVendedor x) => x.get_Vendedor().get_Id() != vendedor.get_Id()) + select vendedor; + vinculoVendedors = vendedors1.Select((Gestor.Model.Domain.Seguros.Vendedor vendedor) => { + VinculoVendedor vinculoVendedor = new VinculoVendedor(); + vinculoVendedor.set_Id((long)0); + vinculoVendedor.set_Vendedor(vendedor); + vinculoVendedor.set_Vinculado(false); + return vinculoVendedor; + }).ToList(); + } + List vinculoVendedors1 = vinculoVendedors; + return vinculoVendedors1; + } + + private async Task> GetVinculo(Usuario usuario) + { + List vinculoVendedors = new List(); + await this._servicoVendedorUsuario.FindByVinculo(usuario).ForEach((VendedorUsuario x) => { + VinculoVendedor vinculoVendedor = new VinculoVendedor(); + vinculoVendedor.set_Id(x.get_Id()); + vinculoVendedor.set_Vendedor(x.get_Vendedor()); + vinculoVendedor.set_Vinculado(true); + vinculoVendedors.Add(vinculoVendedor); + }); + List vinculoVendedors1 = vinculoVendedors; + return vinculoVendedors1; + } + + private async void Load(Usuario usuario) + { + await this.AwaitLoad(usuario); + } + + public async Task Salvar() + { + string str; + List vinculado = this.Vinculado; + List list = ( + from x in vinculado + where !x.get_Vinculado() + select x).Select((VinculoVendedor x) => { + VendedorUsuario vendedorUsuario = new VendedorUsuario(); + vendedorUsuario.set_Id(x.get_Id()); + vendedorUsuario.set_Vendedor(x.get_Vendedor()); + vendedorUsuario.set_Usuario(this.SelectedUsuario); + return vendedorUsuario; + }).ToList(); + if (list.Count > 0) + { + if (!await this._servicoVendedorUsuario.Delete(list)) + { + return; + } + } + List vendedor = this.Vendedor; + List vendedorUsuarios = ( + from x in vendedor + where x.get_Vinculado() + select x).Select((VinculoVendedor x) => { + VendedorUsuario vendedorUsuario = new VendedorUsuario(); + vendedorUsuario.set_Id(x.get_Id()); + vendedorUsuario.set_Vendedor(x.get_Vendedor()); + vendedorUsuario.set_Usuario(this.SelectedUsuario); + return vendedorUsuario; + }).ToList(); + if (vendedorUsuarios.Count > 0) + { + await this._servicoVendedorUsuario.SaveOrUpdate(vendedorUsuarios); + } + await this.AwaitLoad(this.SelectedUsuario); + using (UnitOfWork commited = Instancia.Commited) + { + IPHostEntry hostEntry = Dns.GetHostEntry(Dns.GetHostName()); + RegistroLog registroLog = new RegistroLog(); + registroLog.set_Acao(0); + registroLog.set_Usuario(Recursos.Usuario); + registroLog.set_DataHora(Funcoes.GetNetworkTime()); + List vinculoVendedors = this.Vinculado; + List vendedors = ( + from x in vinculoVendedors + select x.get_Vendedor()).ToList(); + JsonSerializerSettings jsonSerializerSetting = new JsonSerializerSettings(); + jsonSerializerSetting.set_ReferenceLoopHandling(1); + registroLog.set_Descricao(JsonConvert.SerializeObject(vendedors, jsonSerializerSetting)); + registroLog.set_EntidadeId(this.SelectedUsuario.get_Id()); + registroLog.set_Tela(45); + registroLog.set_Versao(LoginViewModel.VersaoAtual); + registroLog.set_NomeMaquina(Environment.MachineName); + registroLog.set_UsuarioMaquina(Environment.UserName); + IPAddress[] addressList = hostEntry.AddressList; + IPAddress pAddress = ((IEnumerable)addressList).FirstOrDefault((IPAddress ip) => ip.AddressFamily == AddressFamily.InterNetwork); + if (pAddress != null) + { + str = pAddress.ToString(); + } + else + { + str = null; + } + registroLog.set_Ip(str); + this._servicoVendedorUsuario.SaveLog(registroLog, commited); + commited.Commit(); + } + base.RegistrarAcao(string.Concat("ALTEROU VÍNCULOS DE VENDEDOR DO USUÁRIO \"", this.SelectedUsuario.get_Nome(), "\""), this.SelectedUsuario.get_Id(), new TipoTela?(45), string.Format("ID: {0}\n\nACESSE O LOG DE ALTERAÇÕES NA TELA DE VÍNCULO DE VENDEDOR PARA VER EXATAMENTE O QUE FOI ALTERADO.", this.SelectedUsuario.get_Id())); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroEmailViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroEmailViewModel.cs new file mode 100644 index 0000000..2294490 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroEmailViewModel.cs @@ -0,0 +1,362 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class CadastroEmailViewModel : BaseSegurosViewModel + { + private readonly EmailServico _servico; + + public Credencial CancelCredencial; + + private Credencial _selectedCredencial; + + private ObservableCollection _credenciaisFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public List Credenciais + { + get; + set; + } + + public ObservableCollection CredenciaisFiltrados + { + get + { + return this._credenciaisFiltrados; + } + set + { + this._credenciaisFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("CredenciaisFiltrados"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Credencial SelectedCredencial + { + get + { + return this._selectedCredencial; + } + set + { + long? nullable; + this._selectedCredencial = value; + this.WorkOnSelectedCredencial(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedCredencial"); + } + } + + public CadastroEmailViewModel() + { + this._servico = new EmailServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public async Task CancelarAlteracao() + { + long id; + await this.CarregarCredenciais(); + if (!this.CredenciaisFiltrados.Any()) + { + this.SelectedCredencial = new Credencial(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + Credencial cancelCredencial = this.CancelCredencial; + if (cancelCredencial != null) + { + id = cancelCredencial.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault((Credencial x) => x.get_Id() == num); + } + base.Alterar(false); + } + + private async Task CarregarCredenciais() + { + List credencials = await (new BaseServico()).BuscarCredenciais(); + foreach (Credencial credencial in credencials) + { + if (credencial.get_Email().Contains("@gmail.com")) + { + credencial.set_Tipo(1); + } + credencial.set_Senha(EncryptionHelper.Decrypt(credencial.get_Senha())); + } + CadastroEmailViewModel list = this; + List credencials1 = credencials; + list.Credenciais = ( + from x in credencials1 + orderby x.get_Descricao() + select x).ToList(); + this.CredenciaisFiltrados = new ObservableCollection(this.Credenciais); + } + + public async Task EnviarTesteEmail() + { + bool flag; + if (this.SelectedCredencial != null) + { + TipoEmail tipo = this.SelectedCredencial.get_Tipo(); + if (tipo != null) + { + if (tipo - 1 <= 1) + { + if (string.IsNullOrWhiteSpace(this.SelectedCredencial.get_Email())) + { + await base.ShowMessage("NECESSÁRIO PREENCHER O E-MAIL PARA ENVIAR UM E-MAIL DE TESTE", "OK", "", false); + flag = false; + return flag; + } + } + } + else if (string.IsNullOrWhiteSpace(this.SelectedCredencial.get_Email()) || !this.SelectedCredencial.get_Porta().HasValue || string.IsNullOrWhiteSpace(this.SelectedCredencial.get_Dominio())) + { + await base.ShowMessage("NECESSÁRIO PREENCHER O E-MAIL, PORTA E DOMÍNIO PARA ENVIAR UM E-MAIL DE TESTE", "OK", "", false); + flag = false; + return flag; + } + MailHelper mailHelper = new MailHelper(); + Destinatario destinatario = new Destinatario(); + destinatario.set_Assunto("TESTE ENVIO E-MAIL"); + destinatario.set_Corpo("TESTE DE ENVIO DE E-MAIL"); + destinatario.set_Email(this.SelectedCredencial.get_Email()); + destinatario.set_Nome(this.SelectedCredencial.get_Descricao()); + Destinatario destinatario1 = destinatario; + LogEnvio logEnvio = await mailHelper.SendAsync(this.SelectedCredencial, destinatario1, null, null, 0, false); + if (logEnvio.get_Enviado()) + { + flag = true; + } + else + { + await base.ShowMessage(logEnvio.get_Erro(), "OK", "", false); + flag = false; + } + } + else + { + await base.ShowMessage("NECESSÁRIO CRIAR UM E-MAIL DE ENVIO PARA PROSSEGUIR.", "OK", "", false); + flag = false; + } + return flag; + } + + public async Task Excluir() + { + if (this.SelectedCredencial != null && this.SelectedCredencial.get_Id() != 0) + { + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR O E-MAIL ", this.SelectedCredencial.get_Email(), " PERMANENTEMENTE?"), "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedCredencial)) + { + base.RegistrarAcao(string.Concat("EXCLUIU E-MAIL \"", this.SelectedCredencial.get_Email(), "\""), this.SelectedCredencial.get_Id(), new TipoTela?(17), string.Format("E-MAIL: {0}\nID: {1}", this.SelectedCredencial.get_Email(), this.SelectedCredencial.get_Id())); + await this.CarregarCredenciais(); + if (!this.CredenciaisFiltrados.Any()) + { + this.SelectedCredencial = new Credencial(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault(); + } + base.Loading(false); + base.ToggleSnackBar("E-MAIL EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List credencials = await Task.Run>(() => this.FiltrarCredenciais(value)); + return credencials; + } + + public List FiltrarCredenciais(string filter) + { + this.CredenciaisFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Credenciais) : new ObservableCollection( + from x in this.Credenciais + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + select x)); + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault(); + return this.CredenciaisFiltrados.ToList(); + } + + public void Incluir() + { + Credencial credencial = new Credencial(); + credencial.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + credencial.set_IdUsuario(Recursos.Usuario.get_Id()); + this.SelectedCredencial = credencial; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + List> keyValuePairs1 = this.SelectedCredencial.Validate(); + keyValuePairs1.AddRange(this.Validate()); + if (keyValuePairs1.Count <= 0) + { + this.SelectedCredencial.set_Assinatura(this.SelectedCredencial.get_Assinatura().GetBody()); + this.SelectedCredencial.set_Cabecalho(this.SelectedCredencial.get_Cabecalho().GetBody()); + if (this.SelectedCredencial.get_Senha() == null) + { + this.SelectedCredencial.set_Senha(""); + } + str = (this.SelectedCredencial.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Credencial credencial = await this._servico.Save(this.SelectedCredencial); + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " E-MAIL \"", credencial.get_Email(), "\""), credencial.get_Id(), new TipoTela?(17), string.Format("E-MAIL: {0}\nID: {1}", credencial.get_Email(), credencial.get_Id())); + await this.CarregarCredenciais(); + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault((Credencial x) => x.get_Id() == credencial.get_Id()); + base.Alterar(false); + base.ToggleSnackBar("E-MAIL SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(17); + base.Loading(false); + } + + public async Task SelecionaCredenciais() + { + base.Loading(true); + await this.CarregarCredenciais(); + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault(); + base.Loading(false); + } + + public void SelecionaCredencial(Credencial credencial) + { + this.SelectedCredencial = this.CredenciaisFiltrados.First((Credencial x) => x.get_Id() == credencial.get_Id()); + } + + public List> Validate() + { + List> keyValuePairs = new List>(); + if (this.Credenciais.Any((Credencial x) => { + if (x.get_Id() == this.SelectedCredencial.get_Id()) + { + return false; + } + return x.get_Descricao() == this.SelectedCredencial.get_Descricao(); + })) + { + keyValuePairs.Add(new KeyValuePair("Descricao", "UM E-MAIL COM A MESMA DESCRIÇÃO/NOME JÁ EXISTE.")); + } + return keyValuePairs; + } + + private void WorkOnSelectedCredencial(Credencial value, bool registrar = true) + { + long? nullable; + this.CancelCredencial = (value == null || value.get_Id() == 0 ? this.CancelCredencial : (Credencial)value.Clone()); + if (value == null || value.get_Id() == 0) + { + return; + } + if (this.LastAccessId == value.get_Id() && this.LastAccessTela == 17) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU E-MAIL \"", value.get_Email(), "\""), value.get_Id(), new TipoTela?(17), string.Format("ID E-MAIL: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 17; + Credencial selectedCredencial = this.SelectedCredencial; + if (selectedCredencial != null) + { + nullable = new long?(selectedCredencial.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedCredencial = this.CredenciaisFiltrados.FirstOrDefault((Credencial x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroParceiroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroParceiroViewModel.cs new file mode 100644 index 0000000..9b8f08c --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/CadastroParceiroViewModel.cs @@ -0,0 +1,413 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class CadastroParceiroViewModel : BaseSegurosViewModel + { + private readonly ParceiroServico _servico; + + private Parceiro _selectedParceiro; + + private ObservableCollection _parceirosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public Parceiro CancelParceiro; + + private Item _selectedItem = new Item(); + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public List Parceiros + { + get; + set; + } + + public ObservableCollection ParceirosFiltrados + { + get + { + return this._parceirosFiltrados; + } + set + { + this._parceirosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("ParceirosFiltrados"); + } + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + this._selectedItem = value; + base.OnPropertyChanged("SelectedItem"); + } + } + + public Parceiro SelectedParceiro + { + get + { + return this._selectedParceiro; + } + set + { + long? nullable; + this._selectedParceiro = value; + this.WorkOnSelectedParceiro(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedParceiro"); + } + } + + public CadastroParceiroViewModel(Parceiro parceiro) + { + this._servico = new ParceiroServico(); + base.EnableMenu = true; + this.Seleciona(parceiro); + } + + public void CancelarAlteracao() + { + if (this.CancelParceiro == null || !this.Parceiros.Any((Parceiro x) => x.get_Id() == this.CancelParceiro.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Parceiros.First((Parceiro x) => x.get_Id() == this.CancelParceiro.get_Id()), this.CancelParceiro); + if (this.ParceirosFiltrados.Count <= 0 || !this.ParceirosFiltrados.Any((Parceiro x) => x.get_Id() == this.CancelParceiro.get_Id())) + { + this.ParceirosFiltrados.Add(this.CancelParceiro); + } + else + { + DomainBase.Copy(this.ParceirosFiltrados.First((Parceiro x) => x.get_Id() == this.CancelParceiro.get_Id()), this.CancelParceiro); + } + this.ParceirosFiltrados = new ObservableCollection(this.ParceirosFiltrados); + this.SelecionarParceiro(this.ParceirosFiltrados.First((Parceiro x) => x.get_Id() == this.CancelParceiro.get_Id())); + } + base.Alterar(false); + } + + public async void Excluir() + { + string complemento; + Parceiro parceiro; + if (this.SelectedParceiro != null && this.SelectedParceiro.get_Id() != 0) + { + if (await (new BaseServico()).ParceiroUtilizado(this.SelectedParceiro.get_Id())) + { + await base.ShowMessage("PARCEIRO NÃO PODE SER EXCLUÍDO POIS ESTÁ SENDO UTILIZADO.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedParceiro)) + { + CadastroParceiroViewModel cadastroParceiroViewModel = this; + string str = string.Concat("EXCLUIU O PARCEIRO \"", this.SelectedParceiro.get_Nome(), "\""); + long id = this.SelectedParceiro.get_Id(); + TipoTela? nullable = new TipoTela?(22); + string[] cgccpf = new string[] { "DOCUMENTO: ", this.SelectedParceiro.get_Cgccpf(), "\nTELEFONE 1: (", this.SelectedParceiro.get_Ddd1(), ") ", this.SelectedParceiro.get_Telefone1(), "\nTELEFONE 2: (", this.SelectedParceiro.get_Ddd2(), ") ", this.SelectedParceiro.get_Telefone2(), "\nTELEFONE 3: (", this.SelectedParceiro.get_Ddd3(), ") ", this.SelectedParceiro.get_Telefone3(), "\nE-MAIL: ", this.SelectedParceiro.get_Email(), "\n\nENDEREÇO: ", this.SelectedParceiro.get_Endereco(), ", ", this.SelectedParceiro.get_Numero(), ", ", null, null, null, null, null, null, null, null, null }; + if (string.IsNullOrWhiteSpace(this.SelectedParceiro.get_Complemento())) + { + complemento = "-"; + } + else + { + complemento = this.SelectedParceiro.get_Complemento(); + if (complemento == null) + { + complemento = ""; + } + } + cgccpf[21] = complemento; + cgccpf[22] = ", "; + cgccpf[23] = this.SelectedParceiro.get_Bairro(); + cgccpf[24] = ", "; + cgccpf[25] = this.SelectedParceiro.get_Cidade(); + cgccpf[26] = "/"; + cgccpf[27] = this.SelectedParceiro.get_Uf(); + cgccpf[28] = " - "; + cgccpf[29] = this.SelectedParceiro.get_Cep(); + cadastroParceiroViewModel.RegistrarAcao(str, id, nullable, string.Concat(cgccpf)); + int num = this.ParceirosFiltrados.IndexOf(this.SelectedParceiro); + this.Parceiros.Remove(this.SelectedParceiro); + this.ParceirosFiltrados.Remove(this.SelectedParceiro); + this.ParceirosFiltrados = new ObservableCollection(this.ParceirosFiltrados); + if (this.ParceirosFiltrados.Count <= 0) + { + this.Incluir(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + CadastroParceiroViewModel cadastroParceiroViewModel1 = this; + parceiro = (num < this.ParceirosFiltrados.Count ? this.ParceirosFiltrados.ElementAt(num) : this.ParceirosFiltrados.Last()); + cadastroParceiroViewModel1.SelecionarParceiro(parceiro); + } + base.Loading(false); + base.ToggleSnackBar("PARCEIRO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List parceiros = await Task.Run>(() => this.FiltrarParceiro(value)); + return parceiros; + } + + public List FiltrarParceiro(string filter) + { + this.ParceirosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Parceiros) : new ObservableCollection( + from x in this.Parceiros + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + select x)); + return this.ParceirosFiltrados.ToList(); + } + + public void Incluir() + { + this.SelectedParceiro = new Parceiro(); + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string complemento; + string str1; + List> keyValuePairs1 = this.SelectedParceiro.Validate(); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedParceiro.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Parceiro parceiro = await this._servico.Save(this.SelectedParceiro); + if (this._servico.Sucesso) + { + CadastroParceiroViewModel cadastroParceiroViewModel = this; + string str2 = string.Concat(str1, " PARCEIRO \"", parceiro.get_Nome(), "\""); + long id = parceiro.get_Id(); + TipoTela? nullable = new TipoTela?(22); + string[] cgccpf = new string[] { "DOCUMENTO: ", parceiro.get_Cgccpf(), "\nTELEFONE 1: (", parceiro.get_Ddd1(), ") ", parceiro.get_Telefone1(), "\nTELEFONE 2: (", parceiro.get_Ddd2(), ") ", parceiro.get_Telefone2(), "\nTELEFONE 3: (", parceiro.get_Ddd3(), ") ", parceiro.get_Telefone3(), "\nE-MAIL: ", parceiro.get_Email(), "\n\nENDEREÇO: ", parceiro.get_Endereco(), ", ", parceiro.get_Numero(), ", ", null, null, null, null, null, null, null, null, null }; + if (string.IsNullOrWhiteSpace(parceiro.get_Complemento())) + { + complemento = "-"; + } + else + { + complemento = parceiro.get_Complemento(); + if (complemento == null) + { + complemento = ""; + } + } + cgccpf[21] = complemento; + cgccpf[22] = ", "; + cgccpf[23] = parceiro.get_Bairro(); + cgccpf[24] = ", "; + cgccpf[25] = parceiro.get_Cidade(); + cgccpf[26] = "/"; + cgccpf[27] = parceiro.get_Uf(); + cgccpf[28] = " - "; + cgccpf[29] = parceiro.get_Cep(); + cadastroParceiroViewModel.RegistrarAcao(str2, id, nullable, string.Concat(cgccpf)); + if (!this.Parceiros.Any((Parceiro x) => x.get_Id() == parceiro.get_Id())) + { + this.Parceiros.Add(parceiro); + } + else + { + DomainBase.Copy(this.Parceiros.First((Parceiro x) => x.get_Id() == parceiro.get_Id()), parceiro); + } + if (!this.ParceirosFiltrados.Any((Parceiro x) => x.get_Id() == parceiro.get_Id())) + { + this.ParceirosFiltrados.Add(parceiro); + } + else + { + DomainBase.Copy(this.ParceirosFiltrados.First((Parceiro x) => x.get_Id() == parceiro.get_Id()), parceiro); + } + this.ParceirosFiltrados = new ObservableCollection(this.ParceirosFiltrados); + Recursos.Parceiros = this.Parceiros; + this.WorkOnSelectedParceiro(parceiro, false); + base.Alterar(false); + base.ToggleSnackBar("PARCEIRO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona(Parceiro parceiro) + { + base.Loading(true); + await base.PermissaoTela(22); + await this.SelecionaParceiro(parceiro); + base.Loading(false); + } + + private async Task SelecionaParceiro(Parceiro parceiro = null) + { + base.Loading(true); + List parceiros = await (new BaseServico()).BuscarParceirosAsync(); + CadastroParceiroViewModel list = this; + List parceiros1 = parceiros; + list.Parceiros = ( + from x in parceiros1 + orderby x.get_Nome() + select x).ToList(); + this.ParceirosFiltrados = new ObservableCollection(this.Parceiros); + CadastroParceiroViewModel cadastroParceiroViewModel = this; + Parceiro parceiro1 = parceiro; + if (parceiro1 == null) + { + parceiro1 = this.ParceirosFiltrados.FirstOrDefault(); + } + cadastroParceiroViewModel.SelecionarParceiro(parceiro1); + base.Loading(false); + } + + public async void SelecionarParceiro(Parceiro parceiro) + { + if (parceiro != null) + { + Parceiro parceiro1 = await this._servico.BuscarParceiro(parceiro.get_Id()); + DomainBase.Copy(this.ParceirosFiltrados.First((Parceiro x) => x.get_Id() == parceiro.get_Id()), parceiro1); + this.SelectedParceiro = this.ParceirosFiltrados.First((Parceiro x) => x.get_Id() == parceiro.get_Id()); + } + else + { + this.SelectedParceiro = null; + } + } + + private async void WorkOnSelectedParceiro(Parceiro value, bool registrar = true) + { + Parceiro parceiro; + long? nullable; + string complemento; + CadastroParceiroViewModel cadastroParceiroViewModel = this; + parceiro = (value == null || value.get_Id() == 0 ? this.CancelParceiro : (Parceiro)value.Clone()); + cadastroParceiroViewModel.CancelParceiro = parceiro; + if (value != null && value.get_Id() != 0 && (this.LastAccessId != value.get_Id() || this.LastAccessTela != 22)) + { + if (registrar) + { + CadastroParceiroViewModel cadastroParceiroViewModel1 = this; + string str = string.Concat("ACESSOU PARCEIRO \"", value.get_Nome(), "\""); + long id = value.get_Id(); + TipoTela? nullable1 = new TipoTela?(22); + string[] cgccpf = new string[] { "DOCUMENTO: ", value.get_Cgccpf(), "\nTELEFONE 1: (", value.get_Ddd1(), ") ", value.get_Telefone1(), "\nTELEFONE 2: (", value.get_Ddd2(), ") ", value.get_Telefone2(), "\nTELEFONE 3: (", value.get_Ddd3(), ") ", value.get_Telefone3(), "\nE-MAIL: ", value.get_Email(), "\n\nENDEREÇO: ", value.get_Endereco(), ", ", value.get_Numero(), ", ", null, null, null, null, null, null, null, null, null }; + if (string.IsNullOrWhiteSpace(value.get_Complemento())) + { + complemento = "-"; + } + else + { + complemento = value.get_Complemento(); + if (complemento == null) + { + complemento = ""; + } + } + cgccpf[21] = complemento; + cgccpf[22] = ", "; + cgccpf[23] = value.get_Bairro(); + cgccpf[24] = ", "; + cgccpf[25] = value.get_Cidade(); + cgccpf[26] = "/"; + cgccpf[27] = value.get_Uf(); + cgccpf[28] = " - "; + cgccpf[29] = value.get_Cep(); + cadastroParceiroViewModel1.RegistrarAcao(str, id, nullable1, string.Concat(cgccpf)); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 22; + Parceiro selectedParceiro = this.SelectedParceiro; + if (selectedParceiro != null) + { + nullable = new long?(selectedParceiro.get_Id()); + } + else + { + nullable = null; + } + long? nullable2 = nullable; + long num = value.get_Id(); + if (nullable2.GetValueOrDefault() != num | !nullable2.HasValue) + { + Parceiro parceiro1 = await this._servico.BuscarParceiro(value.get_Id()); + DomainBase.Copy(this.SelectedParceiro, parceiro1); + Parceiro selectedParceiro1 = this.SelectedParceiro; + if (selectedParceiro1 != null) + { + selectedParceiro1.Initialize(); + } + else + { + } + this.Initialized = true; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboModelo.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboModelo.cs new file mode 100644 index 0000000..97b1ae0 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboModelo.cs @@ -0,0 +1,43 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.MalaDireta; +using System; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ComboModelo : BaseViewModel + { + private Gestor.Model.Domain.MalaDireta.ModeloMalaDireta _modeloMalaDireta = new Gestor.Model.Domain.MalaDireta.ModeloMalaDireta(); + + private bool _indisponivel; + + public bool Indisponivel + { + get + { + return this._indisponivel; + } + set + { + this._indisponivel = value; + base.OnPropertyChanged("Indisponivel"); + } + } + + public Gestor.Model.Domain.MalaDireta.ModeloMalaDireta ModeloMalaDireta + { + get + { + return this._modeloMalaDireta; + } + set + { + this._modeloMalaDireta = value; + base.OnPropertyChanged("ModeloMalaDireta"); + } + } + + public ComboModelo() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboVariavel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboVariavel.cs new file mode 100644 index 0000000..6fd4392 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ComboVariavel.cs @@ -0,0 +1,45 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.MalaDireta; +using System; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ComboVariavel : BaseViewModel + { + private Gestor.Model.Domain.MalaDireta.VariaveisMalaDireta _variaveisMalaDireta; + + private bool _indisponivel; + + public bool Indisponivel + { + get + { + return this._indisponivel; + } + set + { + this._indisponivel = value; + base.OnPropertyChanged("Indisponivel"); + } + } + + public Gestor.Model.Domain.MalaDireta.VariaveisMalaDireta VariaveisMalaDireta + { + get + { + return this._variaveisMalaDireta; + } + set + { + this._variaveisMalaDireta = value; + base.OnPropertyChanged("VariaveisMalaDireta"); + } + } + + public ComboVariavel(Gestor.Model.Domain.MalaDireta.VariaveisMalaDireta variaveisMalaDireta, bool indisponivel) + { + this.VariaveisMalaDireta = variaveisMalaDireta; + this.Indisponivel = indisponivel; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/DownloadViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/DownloadViewModel.cs new file mode 100644 index 0000000..66da49e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/DownloadViewModel.cs @@ -0,0 +1,550 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using IWshRuntimeLibrary; +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.IO.Compression; +using System.Linq; +using System.Net; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Media; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class DownloadViewModel : BaseSegurosViewModel + { + private const string _path = "c:\\AggerSeguros\\"; + + private string _head; + + private string _total; + + private string _progresso; + + private decimal _porcentagem; + + private bool _processando = true; + + private Geometry _maximizeRestore = Geometry.Parse((string)System.Windows.Application.Current.Resources["Maximize"]); + + private string CurrentVersion + { + get; + set; + } + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public Geometry MaximizeRestore + { + get + { + return this._maximizeRestore; + } + set + { + this._maximizeRestore = value; + base.OnPropertyChanged("MaximizeRestore"); + } + } + + private Gestor.Model.API.Parameters Parameters + { + get; + set; + } + + public decimal Porcentagem + { + get + { + return this._porcentagem; + } + set + { + this._porcentagem = value; + this.Progresso = string.Format("{0}% de {1} MB", value, this.Total); + base.OnPropertyChanged("Porcentagem"); + } + } + + public bool Processando + { + get + { + return this._processando; + } + set + { + this._processando = value; + base.OnPropertyChanged("Processando"); + } + } + + public string Progresso + { + get + { + return this._progresso; + } + set + { + this._progresso = value; + base.OnPropertyChanged("Progresso"); + } + } + + public string Total + { + get + { + return this._total; + } + set + { + this._total = value; + base.OnPropertyChanged("Total"); + } + } + + public DownloadViewModel(Gestor.Model.API.Parameters parameters) + { + this.Parameters = parameters; + base.IsEnabled = false; + this.Head = string.Concat("ATUALIZAÇÃO ", this.Parameters.get_Directory().ToUpper()); + } + + public async Task Atualizar() + { + System.Version version; + string str; + FileVersionInfo versionInfo; + str = (this.Parameters.get_Beta() ? "Beta" : "Released"); + string str1 = str; + int type = this.Parameters.get_Type(); + if (type == 7) + { + try + { + Gestor.Model.API.Version version1 = await Gestor.Application.Helpers.Connection.Get(string.Format("Update/{0}/{1}", str1, this.Parameters.get_Type()), true, false); + if (File.Exists("c:\\AggerSeguros\\Agger.Gestor.exe")) + { + versionInfo = FileVersionInfo.GetVersionInfo("c:\\AggerSeguros\\Agger.Gestor.exe"); + } + else + { + versionInfo = null; + } + FileVersionInfo fileVersionInfo = versionInfo; + if (fileVersionInfo == null || !System.Version.TryParse(fileVersionInfo.FileVersion, out version) || !(version >= System.Version.Parse(version1.get_VersaoAplicacao()))) + { + await this.AtualizarGestor(version1, true); + } + else + { + Funcoes.Destroy(); + str1 = null; + return; + } + } + catch (Exception exception) + { + Funcoes.Destroy(); + } + } + else if (type != 88) + { + if (type == 99) + { + Gestor.Model.API.Version version2 = await Gestor.Application.Helpers.Connection.Get(string.Format("Update/Released/{0}", this.Parameters.get_Type()), true, false); + await this.Atualizar(version2); + } + else + { + this.CurrentVersion = await this.GetCurrentVersion(this.Parameters.get_Directory()); + Gestor.Model.API.Version version3 = await Gestor.Application.Helpers.Connection.Get(string.Format("Update/{0}/{1}", str1, this.Parameters.get_Type()), true, false); + if (!this.VerificarVersao(version3)) + { + await this.Atualizar(version3); + } + else + { + this.Open(); + } + } + } + else if (File.Exists("c:\\AggerSeguros\\Aggilizador.Application.exe")) + { + this.Parameters.set_Application("Aggilizador.Application.exe"); + this.Open(); + } + else + { + this.Parameters.set_Arguments(""); + await this.AtualizarAggilizador(); + } + str1 = null; + } + + public async Task Atualizar(Gestor.Model.API.Version version) + { + string str; + string str1; + if (this.CheckFreeSpace()) + { + string str2 = string.Concat("c:\\AggerSeguros\\", version.get_Name()); + if (Directory.Exists(str2)) + { + Directory.Delete(str2, true); + } + while (Directory.Exists(str2)) + { + Thread.Sleep(500); + } + Directory.CreateDirectory(str2); + using (WebClient webClient = new WebClient()) + { + webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.DownloadFileComplete); + webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressCallback); + this.CurrentVersion = version.get_Name(); + str = (this.Parameters.get_Type() == 99 ? string.Concat(version.get_Uri(), "/", version.get_Name(), ".exe") : string.Concat(version.get_Uri(), "/", version.get_Name(), ".zip")); + string str3 = str; + str1 = (this.Parameters.get_Type() == 99 ? string.Concat(str2, ".exe") : string.Concat(str2, "//", version.get_Name(), ".zip")); + string str4 = str1; + Stream stream = webClient.OpenRead(str3); + double num = Math.Round((double)((float)long.Parse(webClient.ResponseHeaders["Content-Length"]) / 1024f / 1024f), 2); + this.Total = num.ToString(CultureInfo.InvariantCulture); + if (stream != null) + { + stream.Dispose(); + } + else + { + } + await webClient.DownloadFileTaskAsync(str3, str4); + webClient.Dispose(); + } + webClient = null; + } + else + { + LogError logError = new LogError(); + logError.set_IdFornecedor(ApplicationHelper.IdFornecedor); + logError.set_Fornecedor(Recursos.Empresa.get_Nome()); + logError.set_UsuarioLogado(Recursos.Usuario.get_Nome()); + logError.set_IdUsuarioLogado(Recursos.Usuario.get_Id()); + logError.set_Versao(ApplicationHelper.Versao.ToString()); + logError.set_Data(Funcoes.GetNetworkTime()); + logError.set_IdErro(1001); + logError.set_Erro(string.Concat(Gestor.Common.Validation.ValidationHelper.GetDescription((TipoErro)1001), " - ", version.get_Name())); + logError.set_HResult(0); + logError.set_HelpLink(""); + logError.set_Message(""); + logError.set_Source(""); + logError.set_StackTrace(""); + logError.set_Maquina(Environment.MachineName); + logError.set_UsuarioMaquina(Environment.UserName); + Erro.RegistrarErro(logError, true); + } + } + + public async Task AtualizarAggilizador() + { + if (this.CheckFreeSpace()) + { + using (WebClient webClient = new WebClient()) + { + webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.DownloadFileComplete); + webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressCallback); + string str = "https://update.aggilizador.com.br/stable/Instalador.exe"; + string str1 = string.Concat("c:\\AggerSeguros\\", this.Parameters.get_Application()); + Stream stream = webClient.OpenRead(str); + double num = Math.Round((double)((float)long.Parse(webClient.ResponseHeaders["Content-Length"]) / 1024f / 1024f), 2); + this.Total = num.ToString(CultureInfo.InvariantCulture); + if (stream != null) + { + stream.Dispose(); + } + else + { + } + await webClient.DownloadFileTaskAsync(str, str1); + webClient.Dispose(); + } + webClient = null; + } + else + { + LogError logError = new LogError(); + logError.set_IdFornecedor(ApplicationHelper.IdFornecedor); + logError.set_Fornecedor(Recursos.Empresa.get_Nome()); + logError.set_UsuarioLogado(Recursos.Usuario.get_Nome()); + logError.set_IdUsuarioLogado(Recursos.Usuario.get_Id()); + logError.set_Versao(ApplicationHelper.Versao.ToString()); + logError.set_Data(Funcoes.GetNetworkTime()); + logError.set_IdErro(1001); + logError.set_Erro(string.Concat(Gestor.Common.Validation.ValidationHelper.GetDescription((TipoErro)1001), " - AGGILIZADOR")); + logError.set_HResult(0); + logError.set_HelpLink(""); + logError.set_Message(""); + logError.set_Source(""); + logError.set_StackTrace(""); + logError.set_Maquina(Environment.MachineName); + logError.set_UsuarioMaquina(Environment.UserName); + Erro.RegistrarErro(logError, true); + } + } + + public async Task AtualizarGestor(Gestor.Model.API.Version version, bool criarAtalho = false) + { + string str = "c:\\AggerSeguros\\"; + using (WebClient webClient = new WebClient()) + { + webClient.DownloadFileCompleted += new AsyncCompletedEventHandler(this.DownloadFileCompleteGestor); + webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressCallback); + this.CurrentVersion = version.get_Name(); + string str1 = string.Concat(version.get_Uri(), "/", version.get_Name(), ".zip"); + string str2 = string.Concat(str, version.get_Name(), ".zip"); + Stream stream = webClient.OpenRead(str1); + double num = Math.Round((double)((float)long.Parse(webClient.ResponseHeaders["Content-Length"]) / 1024f / 1024f), 2); + this.Total = num.ToString(CultureInfo.InvariantCulture); + if (stream != null) + { + stream.Dispose(); + } + else + { + } + await webClient.DownloadFileTaskAsync(str1, str2); + webClient.Dispose(); + } + webClient = null; + if (criarAtalho) + { + this.CriarAtalho(); + } + } + + private bool CheckFreeSpace() + { + DriveInfo driveInfo = new DriveInfo("C"); + if (!driveInfo.IsReady) + { + return false; + } + return driveInfo.AvailableFreeSpace > (long)314572800; + } + + private void CriarAtalho() + { + WshShell variable = (WshShell)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("72C24DD5-D70A-438B-8A42-98424B88AFB8"))); + string str = "c:\\AggerSeguros\\"; + string str1 = "Agger.Gestor.exe"; + string str2 = "Agger Gestor"; + try + { + IWshShortcut variable1 = variable.CreateShortcut(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "\\Agger Gestor.lnk")) as IWshShortcut; + if (variable1 != null) + { + variable1.TargetPath = string.Concat(str, str1); + variable1.WindowStyle = 1; + variable1.Description = str2; + variable1.WorkingDirectory = str; + variable1.IconLocation = string.Concat(str, str1, ",0"); + variable1.Save(); + } + } + catch (Exception exception) + { + } + try + { + IWshShortcut variable2 = variable.CreateShortcut(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "\\Agger Gestor.lnk")) as IWshShortcut; + if (variable2 != null) + { + variable2.TargetPath = string.Concat(str, str1); + variable2.WindowStyle = 1; + variable2.Description = str2; + variable2.WorkingDirectory = str; + variable2.IconLocation = string.Concat(str, str1, ",0"); + variable2.Save(); + } + } + catch (Exception exception1) + { + } + try + { + IWshShortcut variable3 = variable.CreateShortcut(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "\\Agger Gestor.lnk")) as IWshShortcut; + if (variable3 != null) + { + variable3.TargetPath = string.Concat(str, str1); + variable3.WindowStyle = 1; + variable3.Description = str2; + variable3.WorkingDirectory = str; + variable3.IconLocation = string.Concat(str, str1, ",0"); + variable3.Save(); + } + } + catch (Exception exception2) + { + } + try + { + IWshShortcut variable4 = variable.CreateShortcut(string.Concat(Environment.GetFolderPath(Environment.SpecialFolder.StartMenu), "\\Agger Gestor.lnk")) as IWshShortcut; + if (variable4 != null) + { + variable4.TargetPath = string.Concat(str, str1); + variable4.WindowStyle = 1; + variable4.Description = str2; + variable4.WorkingDirectory = str; + variable4.IconLocation = string.Concat(str, str1, ",0"); + variable4.Save(); + } + } + catch (Exception exception3) + { + } + } + + private void DownloadFileComplete(object sender, AsyncCompletedEventArgs e) + { + this.Processando = true; + this.Porcentagem = decimal.Zero; + this.Extract(); + this.Open(); + } + + private void DownloadFileCompleteGestor(object sender, AsyncCompletedEventArgs e) + { + this.Processando = true; + this.Porcentagem = decimal.Zero; + this.ExtractGestor(); + Funcoes.Destroy(); + } + + private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e) + { + this.Processando = false; + this.Porcentagem = e.ProgressPercentage; + } + + public void Extract() + { + if (this.Parameters.get_Type() == 99 || this.Parameters.get_Type() == 88) + { + return; + } + string str = string.Concat("c:\\AggerSeguros\\", this.CurrentVersion); + string str1 = string.Concat(str, "\\", this.CurrentVersion, ".zip"); + string.Concat(str, "\\", this.Parameters.get_Application()); + ZipFile.ExtractToDirectory(str1, str); + File.Delete(str1); + } + + public void ExtractGestor() + { + string str = string.Concat("c:\\AggerSeguros\\", this.CurrentVersion, ".zip"); + ZipArchive zipArchive = ZipFile.OpenRead(str); + try + { + foreach (ZipArchiveEntry entry in zipArchive.get_Entries()) + { + string fullPath = Path.GetFullPath(Path.Combine("c:\\AggerSeguros\\", entry.get_FullName())); + fullPath.StartsWith("c:\\AggerSeguros\\", StringComparison.OrdinalIgnoreCase); + if (entry.get_Name() != "") + { + entry.ExtractToFile(fullPath, true); + } + else + { + Directory.CreateDirectory(Path.GetDirectoryName(fullPath)); + } + } + zipArchive.Dispose(); + File.Delete(str); + } + catch (Exception exception) + { + } + } + + private async Task GetCurrentVersion(string name) + { + string str1 = await Task.Run(() => { + string[] directories = Directory.GetDirectories("c:\\AggerSeguros\\"); + List nums = new List(); + string[] strArrays = directories; + for (int i = 0; i < (int)strArrays.Length; i++) + { + string str = strArrays[i]; + if (str.IndexOf(name, StringComparison.Ordinal) > -1) + { + System.Text.RegularExpressions.Match match = (new Regex("(^[A-Za-z]+)(.)([A-Za-z]+)(\\d+)", RegexOptions.IgnoreCase)).Match(str.Replace("c:\\AggerSeguros\\", "")); + if (match.Success) + { + nums.Add(long.Parse(match.Groups[4].Value)); + } + } + } + nums.Reverse(); + if (nums.Count == 0) + { + return ""; + } + return string.Format("{0}{1}", name, nums.First()); + }); + return str1; + } + + public void Open() + { + if (!this.Parameters.get_Run()) + { + Funcoes.Destroy(); + return; + } + string str = Path.Combine((this.Parameters.get_Type() == 99 || this.Parameters.get_Type() == 88 ? "c:\\AggerSeguros\\" : string.Concat("c:\\AggerSeguros\\", this.CurrentVersion)), this.Parameters.get_Application()); + try + { + Process.Start(str, this.Parameters.get_Arguments()); + } + catch + { + } + Funcoes.Destroy(); + } + + private bool VerificarVersao(Gestor.Model.API.Version versao) + { + bool flag = File.Exists(string.Concat("c:\\AggerSeguros\\\\", this.CurrentVersion, "\\", this.Parameters.get_Application())); + return (versao.get_Name() == this.CurrentVersion) & flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/EmpresaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EmpresaViewModel.cs new file mode 100644 index 0000000..6f528ac --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EmpresaViewModel.cs @@ -0,0 +1,512 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Command; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; +using System.Windows.Input; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class EmpresaViewModel : BaseSegurosViewModel + { + private readonly EmpresaServico _servico; + + public Empresa CancelEmpresa; + + private Empresa _selectedEmpresa = new Empresa(); + + private string _logoLabel = "ANEXAR LOGOTIPO"; + + private bool _passWordReadOnly; + + private bool _enableConsultaEspaco = true; + + private double _espaco; + + private string _senha; + + private string _confirmaSenha; + + private ObservableCollection _empresasFiltradas = new ObservableCollection(); + + private bool _isExpanded; + + private Visibility _confirmacaoSenha { get; set; } = Visibility.Collapsed; + + private Visibility _visualizacaoMatriz { get; set; } = Visibility.Collapsed; + + public Visibility ConfirmacaoSenha + { + get + { + return this._confirmacaoSenha; + } + set + { + this._confirmacaoSenha = value; + base.OnPropertyChanged("ConfirmacaoSenha"); + } + } + + public string ConfirmaSenha + { + get + { + return this._confirmaSenha; + } + set + { + this._confirmaSenha = value; + base.OnPropertyChanged("ConfirmaSenha"); + } + } + + public ICommand ConsultarEspacoCommand + { + get; + set; + } + + public List Empresas + { + get; + set; + } + + public ObservableCollection EmpresasFiltradas + { + get + { + return this._empresasFiltradas; + } + set + { + this._empresasFiltradas = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("EmpresasFiltradas"); + } + } + + public bool EnableConsultaEspaco + { + get + { + return this._enableConsultaEspaco; + } + set + { + this._enableConsultaEspaco = value; + base.OnPropertyChanged("EnableConsultaEspaco"); + } + } + + public double Espaco + { + get + { + return this._espaco; + } + set + { + this._espaco = value; + base.OnPropertyChanged("Espaco"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public string LogoLabel + { + get + { + return this._logoLabel; + } + set + { + this._logoLabel = value; + base.OnPropertyChanged("LogoLabel"); + } + } + + public bool PassWordReadOnly + { + get + { + return this._passWordReadOnly; + } + set + { + bool flag; + if (!value) + { + flag = false; + } + else + { + flag = (Recursos.Usuario.get_Administrador() ? true : Recursos.Usuario.get_Id() == (long)0); + } + this._passWordReadOnly = flag; + base.OnPropertyChanged("PassWordReadOnly"); + } + } + + public Empresa SelectedEmpresa + { + get + { + return this._selectedEmpresa; + } + set + { + string str; + long? nullable; + this._selectedEmpresa = value; + if (value != null) + { + string senhaAdmin = value.get_SenhaAdmin(); + if (senhaAdmin != null) + { + str = EncryptionHelper.Decrypt(senhaAdmin); + } + else + { + str = null; + } + } + else + { + str = null; + } + this.Senha = str; + this.ConfirmaSenha = string.Empty; + this.WorkOnSelectedEmpresa(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedEmpresa"); + } + } + + public string Senha + { + get + { + return this._senha; + } + set + { + this._senha = value; + base.OnPropertyChanged("Senha"); + } + } + + public Visibility VisualizacaoMatriz + { + get + { + return this._visualizacaoMatriz; + } + set + { + this._visualizacaoMatriz = value; + base.OnPropertyChanged("VisualizacaoMatriz"); + } + } + + public EmpresaViewModel() + { + this.ConsultarEspacoCommand = new RelayCommand(async () => await this.ConsultaEspacoUsadoClienteInGb()); + this._servico = new EmpresaServico(); + base.EnableMenu = true; + this.PassWordReadOnly = (!Recursos.Usuario.get_Administrador() ? false : base.EnableFields); + this.Seleciona(); + } + + public async Task AnexarLogo() + { + string fileName = ""; + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Multiselect = false; + openFileDialog.Filter = "Imagens|*.jpg;*.jpeg;*.png;"; + openFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString(); + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + fileName = openFileDialog.FileName; + } + else + { + return; + } + } + int num = 0; + try + { + using (MemoryStream memoryStream = new MemoryStream(File.ReadAllBytes(fileName))) + { + byte[] numArray = new byte[checked((IntPtr)memoryStream.Length)]; + memoryStream.Position = (long)0; + memoryStream.Read(numArray, 0, (int)numArray.Length); + this.SelectedEmpresa.set_Logo(numArray); + } + } + catch (Exception exception) + { + num = 1; + } + if (num == 1) + { + string[] newLine = new string[] { "NÃO FOI POSSÍVEL CARREGAR O ARQUIVO ", fileName, ".", Environment.NewLine, "O ARQUIVO ESTÁ INACESSÍVEL OU SENDO UTILIZADO POR OUTRO PROCESSO." }; + await base.ShowMessage(string.Concat(newLine), "OK", "", false); + } + } + + public void CancelarAlteracao() + { + if (this.CancelEmpresa == null || !this.Empresas.Any((Empresa x) => x.get_Id() == this.CancelEmpresa.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Empresas.First((Empresa x) => x.get_Id() == this.CancelEmpresa.get_Id()), this.CancelEmpresa); + if (this.EmpresasFiltradas.Count <= 0 || !this.EmpresasFiltradas.Any((Empresa x) => x.get_Id() == this.CancelEmpresa.get_Id())) + { + this.EmpresasFiltradas.Add(this.CancelEmpresa); + } + else + { + DomainBase.Copy(this.EmpresasFiltradas.First((Empresa x) => x.get_Id() == this.CancelEmpresa.get_Id()), this.CancelEmpresa); + } + this.EmpresasFiltradas = new ObservableCollection(this.EmpresasFiltradas); + this.SelectedEmpresa = this.EmpresasFiltradas.First((Empresa x) => x.get_Id() == this.CancelEmpresa.get_Id()); + } + base.Alterar(false); + } + + public async Task ConsultaEspacoUsadoClienteInGb() + { + this.EnableConsultaEspaco = false; + base.Loading(true); + double num = await this._servico.ConsultaEspacoBancoInGb(); + double num1 = 0; + if (Connection.ConnectionAddress.get_UsaAzureStorage()) + { + double num2 = await Connection.EspacoUsadoAzureInBytes(""); + if (num2 > 0) + { + num1 = num2 / 1024 / 1024 / 1024; + } + } + this.Espaco = num + num1; + if (this.Espaco == 0) + { + this.EnableConsultaEspaco = true; + } + base.Loading(false); + } + + internal async Task> Filtrar(string value) + { + List empresas = await Task.Run>(() => this.FiltrarEmpresa(value)); + return empresas; + } + + public List FiltrarEmpresa(string filter) + { + this.EmpresasFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Empresas) : new ObservableCollection( + from x in this.Empresas + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Nome() + select x)); + return this.EmpresasFiltradas.ToList(); + } + + public void Incluir() + { + this.SelectedEmpresa = new Empresa(); + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + List> keyValuePairs1 = this.SelectedEmpresa.Validate(); + if (this.VisualizacaoMatriz != Visibility.Collapsed && this.ConfirmaSenha != this.Senha) + { + keyValuePairs1.Add(new KeyValuePair("SenhaAdmin|SENHA ADM", "A SENHA E A CONFIRMAÇÃO DA SENHA DEVEM SER IGUAIS.")); + } + if (keyValuePairs1.Count <= 0) + { + if (this.SelectedEmpresa.get_Id() == (long)1) + { + this.SelectedEmpresa.set_SenhaAdmin(EncryptionHelper.Encrypt(this.Senha)); + } + str = (this.SelectedEmpresa.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Empresa empresa = await this._servico.Save(this.SelectedEmpresa); + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " EMPRESA \"", empresa.get_Nome(), "\""), empresa.get_Id(), new TipoTela?(18), string.Format("EMPRESA \"{0}\", ID: {1}", empresa.get_Nome(), empresa.get_Id())); + if (!this.Empresas.Any((Empresa x) => x.get_Id() == empresa.get_Id())) + { + this.Empresas.Add(empresa); + } + else + { + DomainBase.Copy(this.Empresas.First((Empresa x) => x.get_Id() == empresa.get_Id()), empresa); + } + if (!this.EmpresasFiltradas.Any((Empresa x) => x.get_Id() == empresa.get_Id())) + { + this.EmpresasFiltradas.Add(empresa); + } + else + { + DomainBase.Copy(this.EmpresasFiltradas.First((Empresa x) => x.get_Id() == empresa.get_Id()), empresa); + } + this.EmpresasFiltradas = new ObservableCollection(this.EmpresasFiltradas); + Recursos.Empresas = this.Empresas; + this.WorkOnSelectedEmpresa(empresa, false); + base.Alterar(false); + base.ToggleSnackBar("EMPRESA SALVA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(18); + await this.SelecionaEmpresas(); + base.Loading(false); + } + + public async void SelecionaEmpresa(Empresa empresa) + { + Empresa empresa1 = await this._servico.BuscarEmpresaPorId(empresa.get_Id()); + DomainBase.Copy(this.EmpresasFiltradas.First((Empresa x) => x.get_Id() == empresa.get_Id()), empresa1); + this.SelectedEmpresa = this.EmpresasFiltradas.First((Empresa x) => x.get_Id() == empresa.get_Id()); + } + + private async Task SelecionaEmpresas() + { + base.Loading(true); + List empresas = await (new BaseServico()).BuscarEmpresasAsync(); + EmpresaViewModel list = this; + List empresas1 = empresas; + IEnumerable empresas2 = empresas1.Where((Empresa x) => { + if (Recursos.Usuario.get_IdEmpresa() == (long)1) + { + return true; + } + return x.get_Id() == Recursos.Usuario.get_IdEmpresa(); + }); + list.Empresas = ( + from x in empresas2 + orderby x.get_Nome() + select x).ToList(); + this.EmpresasFiltradas = new ObservableCollection(this.Empresas); + if (this.EmpresasFiltradas.Count <= 0) + { + this.SelectedEmpresa = new Empresa(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaEmpresa(this.EmpresasFiltradas.First()); + } + base.Loading(false); + } + + private void WorkOnSelectedEmpresa(Empresa value, bool registrar = true) + { + long? nullable; + bool logo; + this.CancelEmpresa = (value == null || value.get_Id() == 0 ? this.CancelEmpresa : (Empresa)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 18) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU EMPRESA \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(18), string.Format("ID EMPRESA: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 18; + Empresa selectedEmpresa = this.SelectedEmpresa; + if (selectedEmpresa != null) + { + nullable = new long?(selectedEmpresa.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedEmpresa = this.EmpresasFiltradas.FirstOrDefault((Empresa x) => x.get_Id() == value.get_Id()); + } + Empresa empresa = this.SelectedEmpresa; + if (empresa != null) + { + logo = empresa.get_Logo(); + } + else + { + logo = false; + } + this.LogoLabel = (!logo ? "ANEXAR LOGOTIPO" : "ALTERAR LOGOTIPO"); + this.VisualizacaoMatriz = (this.SelectedEmpresa.get_Id() == (long)1 ? Visibility.Visible : Visibility.Collapsed); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/EstipulanteViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EstipulanteViewModel.cs new file mode 100644 index 0000000..a084abd --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EstipulanteViewModel.cs @@ -0,0 +1,380 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class EstipulanteViewModel : BaseSegurosViewModel + { + private readonly EstipulanteServico _servico; + + public Estipulante CancelEstipulante; + + private Estipulante _selectedEstipulante = new Estipulante(); + + private ObservableCollection _estipulantesFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public List Estipulantes + { + get; + set; + } + + public ObservableCollection EstipulantesFiltrados + { + get + { + return this._estipulantesFiltrados; + } + set + { + this._estipulantesFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("EstipulantesFiltrados"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Estipulante SelectedEstipulante + { + get + { + return this._selectedEstipulante; + } + set + { + long? nullable; + this._selectedEstipulante = value; + this.WorkOnSelectedEstipulante(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedEstipulante"); + if (value == null) + { + return; + } + this.SelectedEstipulante.Initialize(); + } + } + + public EstipulanteViewModel() + { + this._servico = new EstipulanteServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelEstipulante == null || !this.Estipulantes.Any((Estipulante x) => x.get_Id() == this.CancelEstipulante.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Estipulantes.First((Estipulante x) => x.get_Id() == this.CancelEstipulante.get_Id()), this.CancelEstipulante); + if (this.EstipulantesFiltrados.Count <= 0 || !this.EstipulantesFiltrados.Any((Estipulante x) => x.get_Id() == this.CancelEstipulante.get_Id())) + { + this.EstipulantesFiltrados.Add(this.CancelEstipulante); + } + else + { + DomainBase.Copy(this.EstipulantesFiltrados.First((Estipulante x) => x.get_Id() == this.CancelEstipulante.get_Id()), this.CancelEstipulante); + } + this.EstipulantesFiltrados = new ObservableCollection(this.EstipulantesFiltrados); + this.SelectedEstipulante = this.EstipulantesFiltrados.First((Estipulante x) => x.get_Id() == this.CancelEstipulante.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + Estipulante estipulante; + if (this.SelectedEstipulante != null && this.SelectedEstipulante.get_Id() != 0) + { + base.Loading(true); + List documentos = await (new BaseServico()).BuscarDocumentosPorEstipulante(this.SelectedEstipulante.get_Id()); + base.Loading(false); + if (documentos.Count > 0) + { + string str = "ESTIPULANTE NÃO PODE SER EXCLUÍDO POIS ESTÁ VINCULADO AOS SEGUINTES DOCUMENTOS:"; + foreach (Documento documento in documentos) + { + if (!string.IsNullOrWhiteSpace(documento.get_Apolice())) + { + object[] newLine = new object[] { Environment.NewLine, documentos.IndexOf(documento) + 1, documento.get_Proposta(), documento.get_Apolice() }; + str = string.Concat(str, string.Format("{0}DOCUMENTO {1} (NÚMERO DA PROPOSTA: {2}, NÚMERO DA APÓLICE: {3})", newLine)); + } + else + { + str = string.Concat(str, string.Format("{0}DOCUMENTO {1} (NÚMERO DA PROPOSTA: {2})", Environment.NewLine, documentos.IndexOf(documento) + 1, documento.get_Proposta())); + } + } + await base.ShowMessage(str, "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedEstipulante)) + { + base.RegistrarAcao(string.Concat("EXCLUIU ESTIPULANTE \"", this.SelectedEstipulante.get_Nome(), "\""), this.SelectedEstipulante.get_Id(), new TipoTela?(9), string.Format("ESTIPULANTE \"{0}\", ID: {1}", this.SelectedEstipulante.get_Nome(), this.SelectedEstipulante.get_Id())); + int num = this.EstipulantesFiltrados.IndexOf(this.SelectedEstipulante); + this.Estipulantes.Remove(this.SelectedEstipulante); + this.EstipulantesFiltrados.Remove(this.SelectedEstipulante); + this.EstipulantesFiltrados = new ObservableCollection(this.EstipulantesFiltrados); + if (this.EstipulantesFiltrados.Count <= 0) + { + this.SelectedEstipulante = new Estipulante(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + EstipulanteViewModel estipulanteViewModel = this; + estipulante = (num < this.EstipulantesFiltrados.Count ? this.EstipulantesFiltrados.ElementAt(num) : this.EstipulantesFiltrados.Last()); + estipulanteViewModel.SelectedEstipulante = estipulante; + } + Recursos.Estipulantes = await (new BaseServico()).BuscarEstipulantesAsync(); + base.Loading(false); + base.ToggleSnackBar("ESTIPULANTE EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List estipulantes = await Task.Run>(() => this.FiltrarEstipulante(value)); + return estipulantes; + } + + public List FiltrarEstipulante(string filter) + { + this.EstipulantesFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Estipulantes) : new ObservableCollection( + from x in this.Estipulantes + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + this.SelectedEstipulante = this.EstipulantesFiltrados.FirstOrDefault(); + return this.EstipulantesFiltrados.ToList(); + } + + public void Incluir() + { + Estipulante estipulante = new Estipulante(); + estipulante.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + estipulante.set_Ativo(true); + this.SelectedEstipulante = estipulante; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + List> keyValuePairs1 = this.SelectedEstipulante.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedEstipulante.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Estipulante estipulante = await this._servico.Save(this.SelectedEstipulante); + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " ESTIPULANTE \"", estipulante.get_Nome(), "\""), estipulante.get_Id(), new TipoTela?(9), string.Format("ESTIPULANTE \"{0}\", ID: {1}", estipulante.get_Nome(), estipulante.get_Id())); + if (!this.Estipulantes.Any((Estipulante x) => x.get_Id() == estipulante.get_Id())) + { + this.Estipulantes.Add(estipulante); + } + else + { + DomainBase.Copy(this.Estipulantes.First((Estipulante x) => x.get_Id() == estipulante.get_Id()), estipulante); + } + if (!this.EstipulantesFiltrados.Any((Estipulante x) => x.get_Id() == estipulante.get_Id())) + { + this.EstipulantesFiltrados.Add(estipulante); + } + else + { + DomainBase.Copy(this.EstipulantesFiltrados.First((Estipulante x) => x.get_Id() == estipulante.get_Id()), estipulante); + } + this.EstipulantesFiltrados = new ObservableCollection(this.EstipulantesFiltrados); + Recursos.Estipulantes = this.Estipulantes; + this.WorkOnSelectedEstipulante(estipulante, false); + base.Alterar(false); + this.SelectedEstipulante.Initialize(); + base.ToggleSnackBar("ESTIPULANTE SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(9); + await this.SelecionaEstipulantes(); + base.Loading(false); + } + + public async void SelecionaEstipulante(Estipulante estipulante) + { + Estipulante estipulante1 = await this._servico.BuscarEstipulantePorId(estipulante.get_Id()); + DomainBase.Copy(this.EstipulantesFiltrados.First((Estipulante x) => x.get_Id() == estipulante.get_Id()), estipulante1); + this.SelectedEstipulante = this.EstipulantesFiltrados.First((Estipulante x) => x.get_Id() == estipulante.get_Id()); + } + + private async Task SelecionaEstipulantes() + { + base.Loading(true); + List estipulantes = await (new BaseServico()).BuscarEstipulantesAsync(); + EstipulanteViewModel list = this; + List estipulantes1 = estipulantes; + IEnumerable estipulantes2 = estipulantes1.Where((Estipulante x) => { + if (Recursos.Usuario.get_IdEmpresa() == (long)1) + { + return true; + } + return Recursos.Usuario.get_IdEmpresa() == x.get_IdEmpresa(); + }); + IOrderedEnumerable ativo = + from x in estipulantes2 + orderby x.get_Ativo() descending + select x; + list.Estipulantes = ativo.ThenBy((Estipulante x) => x.get_Nome()).ToList(); + this.EstipulantesFiltrados = new ObservableCollection(this.Estipulantes); + if (this.EstipulantesFiltrados.Count <= 0) + { + this.SelectedEstipulante = new Estipulante(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaEstipulante(this.EstipulantesFiltrados.First()); + } + Recursos.Estipulantes = estipulantes; + base.Loading(false); + } + + public async Task>> Validate() + { + List estipulantes; + List> keyValuePairs = new List>(); + bool flag = !string.IsNullOrEmpty(this.SelectedEstipulante.get_Nome()); + if (!ValidationHelper.ValidateDocument(this.SelectedEstipulante.get_Documento())) + { + estipulantes = new List(); + } + else + { + estipulantes = await (new BaseServico()).BuscarEstipulante(this.SelectedEstipulante.get_Documento()); + } + List estipulantes1 = estipulantes; + string nome = ""; + if (estipulantes1.Count > 0) + { + estipulantes1.ForEach((Estipulante x) => { + if (x.get_Id() == this.SelectedEstipulante.get_Id()) + { + return; + } + if (!string.IsNullOrEmpty(this.SelectedEstipulante.get_Documento()) && x.get_Documento() == this.SelectedEstipulante.get_Documento()) + { + flag = false; + nome = x.get_Nome(); + } + }); + } + if (!flag) + { + keyValuePairs.Add(new KeyValuePair("Documento", string.Concat("O DOCUMENTO ESTÁ CADASTRADO PARA O ESTIPULANTE ", nome, "."))); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + + private void WorkOnSelectedEstipulante(Estipulante value, bool registrar = true) + { + long? nullable; + this.CancelEstipulante = (value == null || value.get_Id() == 0 ? this.CancelEstipulante : (Estipulante)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 9) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU ESTIPULANTE \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(9), string.Format("ID ESTIPULANTE: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 9; + Estipulante selectedEstipulante = this.SelectedEstipulante; + if (selectedEstipulante != null) + { + nullable = new long?(selectedEstipulante.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedEstipulante = this.EstipulantesFiltrados.FirstOrDefault((Estipulante x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/EtiquetaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EtiquetaViewModel.cs new file mode 100644 index 0000000..c19b97e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/EtiquetaViewModel.cs @@ -0,0 +1,1163 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class EtiquetaViewModel : BaseSegurosViewModel + { + private bool _allSelectedChanging; + + private List _tiposEtiqueta = new List() + { + "CLIENTE", + "APÓLICE" + }; + + private string _tipoEtiqueta = "CLIENTE"; + + private bool? _allSelected; + + private ObservableCollection _apolicesFiltrados = new ObservableCollection(); + + private bool _duasColunas = true; + + private bool _tresColunas; + + private bool _umaPagina; + + private bool _mostrarNascimento; + + private int _pular; + + private object _visibilityColunas; + + private bool _mostrarApolice = true; + + private bool _mostrarVendedor = true; + + private bool _mostrarItem = true; + + public bool? AllSelected + { + get + { + return this._allSelected; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelected; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelected = value; + this.AllSelectedChanged(); + this.Apolices = new List(this.Apolices); + base.OnPropertyChanged("AllSelected"); + } + } + + public List Apolices + { + get; + set; + } + + public ObservableCollection ApolicesFiltrados + { + get + { + return this._apolicesFiltrados; + } + set + { + this._apolicesFiltrados = value; + foreach (Documento apolicesFiltrado in this.ApolicesFiltrados) + { + apolicesFiltrado.add_PropertyChanged(new PropertyChangedEventHandler(this.EntryOnPropertyChanged)); + } + base.OnPropertyChanged("ApolicesFiltrados"); + } + } + + public bool DuasColunas + { + get + { + return this._duasColunas; + } + set + { + this._duasColunas = value; + base.OnPropertyChanged("DuasColunas"); + } + } + + public Visibility ExibirControlesEtiquetaApolice + { + get + { + if (this.TipoEtiqueta != "APÓLICE") + { + return Visibility.Collapsed; + } + return Visibility.Visible; + } + } + + public Visibility ExibirControlesEtiquetaCliente + { + get + { + if (this.TipoEtiqueta != "CLIENTE") + { + return Visibility.Collapsed; + } + return Visibility.Visible; + } + } + + public bool MostrarApolice + { + get + { + return this._mostrarApolice; + } + set + { + this._mostrarApolice = value; + base.OnPropertyChanged("MostrarApolice"); + } + } + + public bool MostrarItem + { + get + { + return this._mostrarItem; + } + set + { + this._mostrarItem = value; + base.OnPropertyChanged("MostrarItem"); + } + } + + public bool MostrarNascimento + { + get + { + return this._mostrarNascimento; + } + set + { + this._mostrarNascimento = value; + base.OnPropertyChanged("MostrarNascimento"); + } + } + + public bool MostrarVendedor + { + get + { + return this._mostrarVendedor; + } + set + { + this._mostrarVendedor = value; + base.OnPropertyChanged("MostrarVendedor"); + } + } + + public int Pular + { + get + { + return this._pular; + } + set + { + this._pular = value; + base.OnPropertyChanged("Pular"); + } + } + + public string TipoEtiqueta + { + get + { + return this._tipoEtiqueta; + } + set + { + this._tipoEtiqueta = value; + base.OnPropertyChanged("TipoEtiqueta"); + base.OnPropertyChanged("ExibirControlesEtiquetaApolice"); + base.OnPropertyChanged("ExibirControlesEtiquetaCliente"); + } + } + + public List TiposEtiqueta + { + get + { + return this._tiposEtiqueta; + } + set + { + this._tiposEtiqueta = value; + base.OnPropertyChanged("TiposEtiqueta"); + } + } + + public bool TresColunas + { + get + { + return this._tresColunas; + } + set + { + this._tresColunas = value; + base.OnPropertyChanged("TresColunas"); + } + } + + public bool UmaPagina + { + get + { + return this._umaPagina; + } + set + { + this._umaPagina = value; + this.VisibilityColunas = (value ? Visibility.Collapsed : Visibility.Visible); + base.OnPropertyChanged("UmaPagina"); + } + } + + public object VisibilityColunas + { + get + { + return this._visibilityColunas; + } + set + { + this._visibilityColunas = value; + base.OnPropertyChanged("VisibilityColunas"); + } + } + + public EtiquetaViewModel() + { + } + + private void AllSelectedChanged() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.AllSelected.HasValue) + { + foreach (Documento apolice in this.Apolices) + { + apolice.set_Selecionado(this.AllSelected.Value); + } + } + } + finally + { + this._allSelectedChanging = false; + } + } + + public async Task CarregarDados(List list, bool apenasCliente) + { + ObservableCollection observableCollection; + List documentos = list.ToList(); + List clientes = documentos.Select((Documento x) => { + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Controle().get_Cliente().get_Id()); + return cliente; + }).ToList(); + ClienteServico clienteServico = new ClienteServico(); + ItemServico itemServico = new ItemServico(); + List clientes1 = clientes; + List clienteEnderecos = await clienteServico.BuscarEnderecosPorCliente(( + from x in clientes1 + where x.get_Id() > (long)0 + select x).ToList()); + if (!apenasCliente) + { + observableCollection = await itemServico.BuscarItens(list.ToList()); + } + else + { + observableCollection = null; + } + ObservableCollection observableCollection1 = observableCollection; + foreach (Documento documento in list) + { + if (( + from y in clienteEnderecos + where y.get_Cliente().get_Id() == documento.get_Controle().get_Cliente().get_Id() + select y).Count() == 0) + { + continue; + } + if (documento.get_Controle().get_Cliente().get_Id() > (long)0) + { + Cliente cliente2 = documento.get_Controle().get_Cliente(); + List clienteEnderecos1 = ( + from y in clienteEnderecos + where y.get_Cliente().get_Id() == documento.get_Controle().get_Cliente().get_Id() + select y).ToList(); + cliente2.set_Enderecos(new ObservableCollection( + from y in clienteEnderecos1 + orderby y.get_Ordem() + select y)); + } + if (apenasCliente) + { + continue; + } + documento.set_ItensAtivo(( + from y in observableCollection1 + where y.get_Documento().get_Id() == documento.get_Id() + select y).ToList()); + } + this.TipoEtiqueta = (apenasCliente ? "CLIENTE" : "APÓLICE"); + EtiquetaViewModel etiquetaViewModel = this; + List documentos1 = list; + IEnumerable documentos2 = documentos1.Where((Documento x) => { + bool enderecos; + Cliente cliente = x.get_Controle().get_Cliente(); + if (cliente != null) + { + enderecos = cliente.get_Enderecos(); + } + else + { + enderecos = false; + } + if (!enderecos) + { + return false; + } + Cliente cliente1 = x.get_Controle().get_Cliente(); + if (cliente1 == null) + { + return false; + } + return cliente1.get_Enderecos().Count() > 0; + }); + etiquetaViewModel.Apolices = ( + from x in documentos2 + orderby x.get_Controle().get_Cliente().get_Nome() + select x).ToList(); + this.ApolicesFiltrados = new ObservableCollection(this.Apolices); + this.AllSelected = new bool?(true); + this.RecheckAllSelected(); + itemServico = null; + clienteEnderecos = null; + } + + public void EmitirEtiquetas() + { + double num; + DateTime? nascimento; + DateTime valueOrDefault; + string str; + string str1; + object obj; + string str2; + string str3; + string complemento; + string str4; + string str5; + string str6; + string cidade; + string str7; + string estado; + string str8; + string str9; + string str10; + object obj1; + string str11; + string str12; + string complemento1; + string str13; + string str14; + string str15; + string str16; + string str17; + object obj2; + object obj3; + object obj4; + string upper; + object obj5; + object obj6; + object obj7; + string upper1; + string str18 = ""; + List list = ( + from x in this.Apolices + where x.get_Selecionado() + select x).ToList(); + string tipoEtiqueta = this.TipoEtiqueta; + if (tipoEtiqueta == "CLIENTE") + { + list = this.Apolices.Where((Documento x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Controle().get_Cliente().get_Enderecos() != null; + }).ToList(); + if (!this.UmaPagina) + { + int num1 = 0; + int num2 = 0; + double num3 = 0; + if (this.DuasColunas) + { + num1 = 10; + num2 = 2; + num3 = 10.52; + } + else if (this.TresColunas) + { + num1 = 10; + num2 = 3; + num3 = 6.82; + } + this.Pular = this.Pular % (num1 * num2); + int pular = this.Pular; + str18 = "ETIQUETAS
"; + int num4 = 0; + while (num4 < list.Count) + { + str18 = string.Concat(str18, "
"); + bool flag = (num4 == 0 ? true : num4 == num1 * num2); + str18 = string.Concat(str18, ""); + for (int i = 0; i < num1 * num2; i += num2) + { + str18 = string.Concat(str18, ""); + if (this.DuasColunas) + { + str18 = string.Concat(str18, ""); + for (int j = 0; j < num2; j++) + { + str18 = string.Concat(str18, ""); + if (j < num2 - 1) + { + if (this.DuasColunas) + { + str18 = string.Concat(str18, ""); + } + } + str18 = string.Concat(str18, "
"); + } + else if (this.TresColunas) + { + str18 = string.Concat(str18, ""); + } + str18 = string.Concat(str18, ""); + if (i + j >= this.Pular) + { + if (num4 < list.Count) + { + Documento item = list[num4]; + if (this.MostrarNascimento) + { + item.get_Controle().get_Cliente().set_Nascimento((new ClienteServico()).BuscarNascimento(item.get_Controle().get_Cliente().get_Id())); + } + if (item.get_Controle().get_Cliente().get_Enderecos().Count() > 0) + { + string[] strArrays = new string[] { str18, item.get_Controle().get_Cliente().get_Nome().Trim(), " ", null, null, null, null, null }; + nascimento = item.get_Controle().get_Cliente().get_Nascimento(); + if (!nascimento.HasValue || !this.MostrarNascimento) + { + str = ""; + } + else + { + nascimento = item.get_Controle().get_Cliente().get_Nascimento(); + if (nascimento.HasValue) + { + valueOrDefault = nascimento.GetValueOrDefault(); + str = valueOrDefault.ToString("dd/MM"); + } + else + { + str = null; + } + } + strArrays[3] = str; + strArrays[4] = "
"; + if (item.get_Controle().get_Cliente().get_Id() == 0) + { + str1 = ""; + } + else + { + string[] strArrays1 = new string[10]; + ClienteEndereco clienteEndereco = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco != null) + { + string endereco = clienteEndereco.get_Endereco(); + if (endereco != null) + { + str2 = endereco.Trim(); + } + else + { + str2 = null; + } + } + else + { + str2 = null; + } + strArrays1[0] = str2; + strArrays1[1] = ", "; + ClienteEndereco clienteEndereco1 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco1 != null) + { + string numero = clienteEndereco1.get_Numero(); + if (numero != null) + { + str3 = numero.Trim(); + } + else + { + str3 = null; + } + } + else + { + str3 = null; + } + strArrays1[2] = str3; + ClienteEndereco clienteEndereco2 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco2 != null) + { + complemento = clienteEndereco2.get_Complemento(); + } + else + { + complemento = null; + } + if (!string.IsNullOrWhiteSpace(complemento)) + { + ClienteEndereco clienteEndereco3 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco3 != null) + { + str4 = clienteEndereco3.get_Complemento().Trim(); + } + else + { + str4 = null; + } + str5 = string.Concat("
", str4); + } + else + { + str5 = ""; + } + strArrays1[3] = str5; + strArrays1[4] = "
"; + ClienteEndereco clienteEndereco4 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco4 != null) + { + string bairro = clienteEndereco4.get_Bairro(); + if (bairro != null) + { + str6 = bairro.Trim(); + } + else + { + str6 = null; + } + } + else + { + str6 = null; + } + strArrays1[5] = str6; + strArrays1[6] = " - "; + ClienteEndereco clienteEndereco5 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco5 != null) + { + cidade = clienteEndereco5.get_Cidade(); + } + else + { + cidade = null; + } + if (!string.IsNullOrEmpty(cidade)) + { + ClienteEndereco clienteEndereco6 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco6 != null) + { + str7 = clienteEndereco6.get_Cidade().Trim(); + } + else + { + str7 = null; + } + } + else + { + str7 = ""; + } + strArrays1[7] = str7; + strArrays1[8] = "/"; + ClienteEndereco clienteEndereco7 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco7 != null) + { + estado = clienteEndereco7.get_Estado(); + } + else + { + estado = null; + } + if (!string.IsNullOrEmpty(estado)) + { + ClienteEndereco clienteEndereco8 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco8 != null) + { + str8 = clienteEndereco8.get_Estado().Trim(); + } + else + { + str8 = null; + } + } + else + { + str8 = ""; + } + strArrays1[9] = str8; + str1 = string.Concat(strArrays1); + } + strArrays[5] = str1; + strArrays[6] = "
"; + if (item.get_Controle().get_Cliente().get_Id() == 0) + { + obj = ""; + } + else + { + ClienteEndereco clienteEndereco9 = item.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco9 != null) + { + obj = clienteEndereco9.get_Cep().Trim(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = ""; + } + } + strArrays[7] = (string)obj; + str18 = string.Concat(strArrays); + } + num4++; + } + this.Pular = 0; + } + str18 = string.Concat(str18, "
"); + } + else if (this.TresColunas) + { + str18 = string.Concat(str18, ""); + } + } + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + } + this.Pular = (pular + list.Count) % (num1 * num2); + } + else + { + str18 = "ETIQUETAS"; + for (int k = 0; k < list.Count; k++) + { + str18 = string.Concat(str18, "
" : "30%'>")); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, ""); + num = 10.7; + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, "
"); + Documento documento = list[k]; + if (this.MostrarNascimento) + { + documento.get_Controle().get_Cliente().set_Nascimento((new ClienteServico()).BuscarNascimento(documento.get_Controle().get_Cliente().get_Id())); + } + string[] strArrays2 = new string[] { str18, documento.get_Controle().get_Cliente().get_Nome().Trim(), " ", null, null, null, null, null, null }; + nascimento = documento.get_Controle().get_Cliente().get_Nascimento(); + if (!nascimento.HasValue || !this.MostrarNascimento) + { + str9 = ""; + } + else + { + nascimento = documento.get_Controle().get_Cliente().get_Nascimento(); + if (nascimento.HasValue) + { + valueOrDefault = nascimento.GetValueOrDefault(); + str9 = valueOrDefault.ToString("dd/MM"); + } + else + { + str9 = null; + } + } + strArrays2[3] = str9; + strArrays2[4] = "
"; + if (documento.get_Controle().get_Cliente().get_Id() == 0) + { + str10 = ""; + } + else + { + string[] strArrays3 = new string[10]; + ClienteEndereco clienteEndereco10 = ( + from x in documento.get_Controle().get_Cliente().get_Enderecos() + orderby x.get_Ordem() + select x).FirstOrDefault(); + if (clienteEndereco10 != null) + { + string endereco1 = clienteEndereco10.get_Endereco(); + if (endereco1 != null) + { + str11 = endereco1.Trim(); + } + else + { + str11 = null; + } + } + else + { + str11 = null; + } + strArrays3[0] = str11; + strArrays3[1] = ", "; + ClienteEndereco clienteEndereco11 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco11 != null) + { + string numero1 = clienteEndereco11.get_Numero(); + if (numero1 != null) + { + str12 = numero1.Trim(); + } + else + { + str12 = null; + } + } + else + { + str12 = null; + } + strArrays3[2] = str12; + ClienteEndereco clienteEndereco12 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco12 != null) + { + complemento1 = clienteEndereco12.get_Complemento(); + } + else + { + complemento1 = null; + } + if (!string.IsNullOrWhiteSpace(complemento1)) + { + ClienteEndereco clienteEndereco13 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco13 != null) + { + string complemento2 = clienteEndereco13.get_Complemento(); + if (complemento2 != null) + { + str13 = complemento2.Trim(); + } + else + { + str13 = null; + } + } + else + { + str13 = null; + } + str14 = string.Concat("
", str13); + } + else + { + str14 = ""; + } + strArrays3[3] = str14; + strArrays3[4] = "
"; + ClienteEndereco clienteEndereco14 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco14 != null) + { + string bairro1 = clienteEndereco14.get_Bairro(); + if (bairro1 != null) + { + str15 = bairro1.Trim(); + } + else + { + str15 = null; + } + } + else + { + str15 = null; + } + strArrays3[5] = str15; + strArrays3[6] = " - "; + ClienteEndereco clienteEndereco15 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco15 != null) + { + string cidade1 = clienteEndereco15.get_Cidade(); + if (cidade1 != null) + { + str16 = cidade1.Trim(); + } + else + { + str16 = null; + } + } + else + { + str16 = null; + } + strArrays3[7] = str16; + strArrays3[8] = "/"; + ClienteEndereco clienteEndereco16 = documento.get_Controle().get_Cliente().get_Enderecos().FirstOrDefault(); + if (clienteEndereco16 != null) + { + string estado1 = clienteEndereco16.get_Estado(); + if (estado1 != null) + { + str17 = estado1.Trim(); + } + else + { + str17 = null; + } + } + else + { + str17 = null; + } + strArrays3[9] = str17; + str10 = string.Concat(strArrays3); + } + strArrays2[5] = str10; + strArrays2[6] = "
"; + if (documento.get_Controle().get_Cliente().get_Id() == 0) + { + obj1 = ""; + } + else + { + ClienteEndereco clienteEndereco17 = ( + from x in documento.get_Controle().get_Cliente().get_Enderecos() + orderby x.get_Ordem() + select x).FirstOrDefault(); + if (clienteEndereco17 != null) + { + obj1 = clienteEndereco17.get_Cep().Trim(); + } + else + { + obj1 = null; + } + if (obj1 == null) + { + obj1 = ""; + } + } + strArrays2[7] = (string)obj1; + strArrays2[8] = "
"; + str18 = string.Concat(strArrays2); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + } + } + base.RegistrarAcao(string.Format("EMITIU ETIQUETA DE {0} CLIENTE{1}", list.Count, (list.Count == 1 ? "" : "S")), (long)0, new TipoTela?(59), string.Concat("IDS E NOMES DOS CLIENTES:\n", string.Join("\n", + from x in list + select string.Concat(x.get_Controle().get_Cliente().get_Id().ToString(), ": \"", x.get_Controle().get_Cliente().get_Nome(), "\"")))); + } + else if (tipoEtiqueta == "APÓLICE") + { + if (!this.UmaPagina) + { + int num5 = 0; + int num6 = 0; + double num7 = 0; + if (this.DuasColunas) + { + num5 = 10; + num6 = 2; + num7 = 10.52; + } + else if (this.TresColunas) + { + num5 = 10; + num6 = 3; + num7 = 6.87; + } + this.Pular = this.Pular % (num5 * num6); + int pular1 = this.Pular; + str18 = "ETIQUETAS
"; + int num8 = 0; + while (num8 < list.Count) + { + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, ""); + for (int l = 0; l < num5 * num6; l += num6) + { + str18 = string.Concat(str18, ""); + for (int m = 0; m < num6; m++) + { + str18 = string.Concat(str18, ""); + } + } + str18 = string.Concat(str18, "
"); + if (l + m >= this.Pular) + { + if (num8 < list.Count) + { + Documento item1 = list[num8]; + string[] strArrays4 = new string[] { str18, item1.get_Controle().get_Cliente().get_Nome().Trim(), "
", null, null, null, null }; + if (this.MostrarItem) + { + if (item1.get_ItensAtivo().Count > 1) + { + obj2 = "APÓLICE COLETIVA
"; + } + else + { + Item item2 = item1.get_ItensAtivo().FirstOrDefault(); + if (item2 != null) + { + upper = item2.get_Descricao().ToUpper(); + } + else + { + upper = null; + } + obj2 = string.Concat(upper, "
"); + } + if (obj2 == null) + { + obj2 = ""; + } + } + else + { + obj2 = null; + } + strArrays4[3] = (string)obj2; + if (this.MostrarApolice) + { + obj3 = (item1.get_Apolice() == "PROSPECÇÃO" ? string.Format("{0:d} - APÓLICE: {1}
", item1.get_Vigencia2(), item1.get_Apolice()) : string.Concat(string.Format("{0:d} - {1:d} - APÓLICE: {2}", item1.get_Vigencia1(), item1.get_Vigencia2(), item1.get_Apolice()), (string.IsNullOrEmpty(item1.get_Endosso()) ? "
" : string.Concat(" /", item1.get_Endosso(), "
")))) ?? ""; + } + else + { + obj3 = null; + } + strArrays4[4] = (string)obj3; + strArrays4[5] = (item1.get_Apolice() == "PROSPECÇÃO" ? "" : string.Concat(item1.get_Controle().get_Seguradora().get_Nome(), " - ", item1.get_Controle().get_Ramo().get_Nome(), "
")); + if (this.MostrarVendedor) + { + obj4 = (item1.get_VendedorPrincipal() == null ? "" : string.Concat("VENDEDOR: ", item1.get_VendedorPrincipal().get_Nome())) ?? ""; + } + else + { + obj4 = null; + } + strArrays4[6] = (string)obj4; + str18 = string.Concat(strArrays4); + num8++; + } + this.Pular = 0; + } + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + } + this.Pular = (pular1 + list.Count) % (num5 * num6); + } + else + { + str18 = "ETIQUETAS"; + for (int n = 0; n < list.Count; n++) + { + str18 = string.Concat(str18, "
" : "30%'>")); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, ""); + num = 10.7; + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, ""); + str18 = string.Concat(str18, "
"); + Documento documento1 = list[n]; + string[] strArrays5 = new string[] { str18, documento1.get_Controle().get_Cliente().get_Nome().Trim(), "
", null, null, null, null }; + if (this.MostrarItem) + { + if (documento1.get_ItensAtivo().Count > 1) + { + obj5 = "APÓLICE COLETIVA
"; + } + else + { + Item item3 = documento1.get_ItensAtivo().FirstOrDefault(); + if (item3 != null) + { + upper1 = item3.get_Descricao().ToUpper(); + } + else + { + upper1 = null; + } + obj5 = string.Concat(upper1, "
"); + } + if (obj5 == null) + { + obj5 = ""; + } + } + else + { + obj5 = null; + } + strArrays5[3] = (string)obj5; + if (this.MostrarApolice) + { + obj6 = (documento1.get_Apolice() == "PROSPECÇÃO" ? string.Format("{0:d} - APÓLICE: {1}
", documento1.get_Vigencia2(), documento1.get_Apolice()) : string.Concat(string.Format("{0:d} - {1:d} - APÓLICE: {2}", documento1.get_Vigencia1(), documento1.get_Vigencia2(), documento1.get_Apolice()), (string.IsNullOrEmpty(documento1.get_Endosso()) ? "
" : string.Concat(" /", documento1.get_Endosso(), "
")))) ?? ""; + } + else + { + obj6 = null; + } + strArrays5[4] = (string)obj6; + strArrays5[5] = (documento1.get_Apolice() == "PROSPECÇÃO" ? "" : string.Concat(documento1.get_Controle().get_Seguradora().get_Nome(), " - ", documento1.get_Controle().get_Ramo().get_Nome(), "
")); + if (this.MostrarVendedor) + { + obj7 = (documento1.get_VendedorPrincipal() == null ? "" : string.Concat("VENDEDOR: ", documento1.get_VendedorPrincipal().get_Nome())) ?? ""; + } + else + { + obj7 = null; + } + strArrays5[6] = (string)obj7; + str18 = string.Concat(strArrays5); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + str18 = string.Concat(str18, "
"); + } + } + base.RegistrarAcao(string.Format("EMITIU ETIQUETA DE {0} DOCUMENTO{1}", list.Count, (list.Count == 1 ? "" : "S")), (long)0, new TipoTela?(59), string.Concat("IDS DOS DOCUMENTOS:\n", string.Join(", ", + from x in list + select x.get_Id()))); + } + str18 = string.Concat(str18, ""); + string tempPath = Path.GetTempPath(); + string str19 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str19, true, Encoding.UTF8); + streamWriter.Write(str18); + streamWriter.Close(); + Process.Start(str19); + } + + private void EntryOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (args.PropertyName == "Selecionado") + { + this.RecheckAllSelected(); + } + } + + internal async Task> Filtrar(string value) + { + List documentos = await Task.Run>(() => this.FiltrarApolice(value)); + return documentos; + } + + public List FiltrarApolice(string filter) + { + this.ApolicesFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Apolices) : new ObservableCollection( + from x in this.Apolices + where ValidationHelper.RemoveDiacritics(x.get_Controle().get_Cliente().get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Controle().get_Cliente().get_Nome() descending, x.get_Id() + select x)); + return this.ApolicesFiltrados.ToList(); + } + + private void RecheckAllSelected() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.Apolices.All((Documento e) => e.get_Selecionado())) + { + this.AllSelected = new bool?(true); + } + else if (!this.Apolices.All((Documento e) => !e.get_Selecionado())) + { + this.AllSelected = null; + } + else + { + this.AllSelected = new bool?(false); + } + } + finally + { + this._allSelectedChanging = false; + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirRamoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirRamoViewModel.cs new file mode 100644 index 0000000..89f3758 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirRamoViewModel.cs @@ -0,0 +1,110 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class IncluirRamoViewModel : BaseSegurosViewModel + { + private Ramo _selectedRamo; + + private Ramo _adicionarRamo; + + private List _ramosAdicionadas; + + private ObservableCollection _ramos; + + private string _filtro; + + public Ramo AdicionarRamo + { + get + { + return this._adicionarRamo; + } + set + { + this._adicionarRamo = value; + base.OnPropertyChanged("AdicionarRamo"); + } + } + + public string Filtro + { + get + { + return this._filtro; + } + set + { + this._filtro = value; + base.OnPropertyChanged("Filtro"); + } + } + + public ObservableCollection Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public List RamosAdicionadas + { + get + { + return this._ramosAdicionadas; + } + set + { + this._ramosAdicionadas = value; + base.OnPropertyChanged("RamosAdicionadas"); + } + } + + public Ramo SelectedRamo + { + get + { + return this._selectedRamo; + } + set + { + this._selectedRamo = value; + base.OnPropertyChanged("SelectedRamo"); + } + } + + public IncluirRamoViewModel(List ramos) + { + this.RamosAdicionadas = ramos; + } + + public async void Pesquisar() + { + if (!string.IsNullOrWhiteSpace(this.Filtro) && this.Filtro.Length >= 3) + { + string str = Uri.EscapeDataString(this.Filtro); + List ramos = await Connection.Get>(string.Concat("Ramos/search?ramo=", str), true, false); + this.Ramos = new ObservableCollection( + from x in ramos + where this.RamosAdicionadas.All((Ramo y) => y.get_Id() != x.get_Id()) + select x); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirSeguradoraViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirSeguradoraViewModel.cs new file mode 100644 index 0000000..ebeed40 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/IncluirSeguradoraViewModel.cs @@ -0,0 +1,110 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class IncluirSeguradoraViewModel : BaseSegurosViewModel + { + private Seguradora _selectedSeguradora; + + private Seguradora _adicionarSeguradora; + + private List _seguradorasAdicionadas; + + private ObservableCollection _seguradoras; + + private string _filtro; + + public Seguradora AdicionarSeguradora + { + get + { + return this._adicionarSeguradora; + } + set + { + this._adicionarSeguradora = value; + base.OnPropertyChanged("AdicionarSeguradora"); + } + } + + public string Filtro + { + get + { + return this._filtro; + } + set + { + this._filtro = value; + base.OnPropertyChanged("Filtro"); + } + } + + public ObservableCollection Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public List SeguradorasAdicionadas + { + get + { + return this._seguradorasAdicionadas; + } + set + { + this._seguradorasAdicionadas = value; + base.OnPropertyChanged("SeguradorasAdicionadas"); + } + } + + public Seguradora SelectedSeguradora + { + get + { + return this._selectedSeguradora; + } + set + { + this._selectedSeguradora = value; + base.OnPropertyChanged("SelectedSeguradora"); + } + } + + public IncluirSeguradoraViewModel(List seguradoras) + { + this.SeguradorasAdicionadas = seguradoras; + } + + public async void Pesquisar() + { + if (!string.IsNullOrWhiteSpace(this.Filtro) && this.Filtro.Length >= 3) + { + string str = Uri.EscapeDataString(this.Filtro); + List seguradoras = await Connection.Get>(string.Concat("Seguradoras/search?cia=", str), true, false); + this.Seguradoras = new ObservableCollection( + from x in seguradoras + where this.SeguradorasAdicionadas.All((Seguradora y) => y.get_Id() != x.get_Id()) + select x); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/MalaDiretaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/MalaDiretaViewModel.cs new file mode 100644 index 0000000..0009fb4 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/MalaDiretaViewModel.cs @@ -0,0 +1,821 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class MalaDiretaViewModel : BaseSegurosViewModel + { + private readonly MalaDiretaServico _servico; + + private readonly FiltroArquivoDigital _filtro; + + private ObservableCollection _malaDireta = new ObservableCollection(); + + private ObservableCollection _variaveis = new ObservableCollection(); + + private bool _enableCredencial; + + private ObservableCollection _modelos = new ObservableCollection(); + + private ComboModelo _selectedModelo = new ComboModelo(); + + private ComboVariavel _selectedVariavel; + + private string _assunto; + + private string _corpo; + + private ObservableCollection _credenciais = new ObservableCollection(); + + private Credencial _selectedCredencial = new Credencial(); + + private ObservableCollection _arquivos = new ObservableCollection(); + + private ObservableCollection _arquivosAnexados = new ObservableCollection(); + + private Gestor.Model.Domain.Common.ArquivoDigital _selectedAnexado = new Gestor.Model.Domain.Common.ArquivoDigital(); + + private Visibility _visibilitySalvarAnexos = Visibility.Hidden; + + private bool _enviarOriginal; + + private bool _salvarArquivoDigital; + + private bool _assinatura; + + public bool _confirmarLeitura; + + public ObservableCollection Arquivos + { + get + { + return this._arquivos; + } + set + { + this._arquivos = value; + base.OnPropertyChanged("Arquivos"); + } + } + + public ObservableCollection ArquivosAnexados + { + get + { + return this._arquivosAnexados; + } + set + { + this._arquivosAnexados = value; + base.OnPropertyChanged("ArquivosAnexados"); + } + } + + public bool Assinatura + { + get + { + return this._assinatura; + } + set + { + this._assinatura = value; + base.OnPropertyChanged("Assinatura"); + } + } + + public string Assunto + { + get + { + return this._assunto; + } + set + { + this._assunto = value; + base.OnPropertyChanged("Assunto"); + } + } + + public bool ConfirmarLeitura + { + get + { + return this._confirmarLeitura; + } + set + { + this._confirmarLeitura = value; + } + } + + public string Corpo + { + get + { + return this._corpo; + } + set + { + this._corpo = value; + base.OnPropertyChanged("Corpo"); + } + } + + public ObservableCollection Credenciais + { + get + { + return this._credenciais; + } + set + { + this._credenciais = value; + base.OnPropertyChanged("Credenciais"); + } + } + + public bool EnableCredencial + { + get + { + return this._enableCredencial; + } + set + { + this._enableCredencial = value; + base.OnPropertyChanged("EnableCredencial"); + } + } + + public bool Enviado + { + get; + set; + } + + public bool EnviarOriginal + { + get + { + return this._enviarOriginal; + } + set + { + this._enviarOriginal = value; + base.OnPropertyChanged("EnviarOriginal"); + } + } + + public ObservableCollection MalaDireta + { + get + { + return this._malaDireta; + } + set + { + this._malaDireta = value; + base.OnPropertyChanged("MalaDireta"); + } + } + + public ObservableCollection Modelos + { + get + { + return this._modelos; + } + set + { + Func func = null; + List list = ( + from variavel in (VariaveisMalaDireta[])Enum.GetValues(typeof(VariaveisMalaDireta)) + select ValidationHelper.GetEntity(variavel)).ToList(); + List strs = ( + from x in this.Variaveis + where !x.Indisponivel + select x into v + select ValidationHelper.GetEntity(v.VariaveisMalaDireta)).ToList(); + List comboModelos = new List(); + foreach (ComboModelo comboModelo in value) + { + IEnumerable strs1 = list.Where(new Func(comboModelo.ModeloMalaDireta.get_Corpo().Contains)); + Func func1 = func; + if (func1 == null) + { + Func func2 = (string s) => strs.Contains(s); + Func func3 = func2; + func = func2; + func1 = func3; + } + if (!strs1.All(func1)) + { + comboModelos.Add(new ComboModelo() + { + ModeloMalaDireta = comboModelo.ModeloMalaDireta, + Indisponivel = true + }); + } + else + { + comboModelos.Add(comboModelo); + } + } + this._modelos = new ObservableCollection( + from x in comboModelos + orderby x.Indisponivel, x.ModeloMalaDireta.get_Assunto() + select x); + base.OnPropertyChanged("Modelos"); + } + } + + public bool SalvarArquivoDigital + { + get + { + return this._salvarArquivoDigital; + } + set + { + this._salvarArquivoDigital = value; + base.OnPropertyChanged("SalvarArquivoDigital"); + } + } + + public Gestor.Model.Domain.Common.ArquivoDigital SelectedAnexado + { + get + { + return this._selectedAnexado; + } + set + { + this._selectedAnexado = value; + base.OnPropertyChanged("SelectedAnexado"); + } + } + + public Credencial SelectedCredencial + { + get + { + return this._selectedCredencial; + } + set + { + this._selectedCredencial = value; + base.OnPropertyChanged("SelectedCredencial"); + } + } + + public ComboModelo SelectedModelo + { + get + { + return this._selectedModelo; + } + set + { + long? nullable; + ModeloMalaDireta modeloMalaDireta; + this._selectedModelo = value; + if (value != null) + { + nullable = new long?(value.ModeloMalaDireta.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + if (value != null) + { + modeloMalaDireta = value.ModeloMalaDireta; + } + else + { + modeloMalaDireta = null; + } + this.WorkOnSelectedModelo(modeloMalaDireta); + base.OnPropertyChanged("SelectedModelo"); + } + } + + public ComboVariavel SelectedVariavel + { + get + { + return this._selectedVariavel; + } + set + { + this._selectedVariavel = value; + base.OnPropertyChanged("SelectedVariavel"); + } + } + + public ObservableCollection Variaveis + { + get + { + return this._variaveis; + } + set + { + this._variaveis = new ObservableCollection( + from x in value + orderby x.Indisponivel, x.VariaveisMalaDireta.ToString() + select x); + base.OnPropertyChanged("Variaveis"); + } + } + + public Visibility VisibilitySalvarAnexos + { + get + { + return this._visibilitySalvarAnexos; + } + set + { + this._visibilitySalvarAnexos = value; + base.OnPropertyChanged("VisibilitySalvarAnexos"); + } + } + + public MalaDiretaViewModel(FiltroArquivoDigital filtro = null) + { + this._servico = new MalaDiretaServico(); + this._filtro = filtro; + this.BuscarCredenciais(); + } + + public async void Anexar() + { + ObservableCollection arquivos = this.Arquivos; + List list = arquivos.Select((IndiceArquivoDigital x) => { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = new Gestor.Model.Domain.Common.ArquivoDigital(); + arquivoDigital.set_Descricao(x.get_Descricao()); + arquivoDigital.set_Extensao(x.get_Extensao()); + return arquivoDigital; + }).ToList(); + List arquivoDigitals = await base.AddAttachments(this.ArquivosAnexados.ToList(), list); + if (arquivoDigitals != null) + { + arquivoDigitals.AddRange(this.ArquivosAnexados); + this.ArquivosAnexados = new ObservableCollection(arquivoDigitals); + } + } + + private async void BuscarCredenciais() + { + Credencial credencial; + await base.PermissaoTela(39); + base.VerificarEnables(null); + List credencials = await (new BaseServico()).BuscarCredenciais(); + MalaDiretaViewModel observableCollection = this; + List credencials1 = credencials; + observableCollection.Credenciais = new ObservableCollection( + from x in credencials1 + orderby x.get_Descricao() + select x); + this.EnableCredencial = !base.Restricao(110); + MalaDiretaViewModel malaDiretaViewModel = this; + if (this.EnableCredencial) + { + ObservableCollection credenciais = this.Credenciais; + credencial = credenciais.FirstOrDefault((Credencial x) => x.get_IdUsuario() == Recursos.Usuario.get_Id()); + if (credencial == null) + { + credencial = this.Credenciais.FirstOrDefault(); + } + } + else + { + ObservableCollection credenciais1 = this.Credenciais; + credencial = credenciais1.FirstOrDefault((Credencial x) => x.get_IdUsuario() == Recursos.Usuario.get_Id()); + } + malaDiretaViewModel.SelectedCredencial = credencial; + } + + public void CancelarAlteracao() + { + base.Alterar(false); + this.SelectedModelo = null; + } + + public async Task CarregarEmails(List maladireta, string assunto = null, string corpo = null) + { + Visibility visibility; + ComboVariavel comboVariavel; + ComboVariavel comboVariavel1; + ComboVariavel comboVariavel2; + ComboVariavel comboVariavel3; + ComboVariavel comboVariavel4; + ComboVariavel comboVariavel5; + ComboVariavel comboVariavel6; + ComboVariavel comboVariavel7; + ClienteServico clienteServico = new ClienteServico(); + List malaDiretas = maladireta; + IEnumerable malaDiretas1 = + from x in malaDiretas + where x.get_Cliente() != null + select x; + List nums = ( + from x in malaDiretas1 + select x.get_Cliente().get_Id()).ToList(); + MalaDiretaViewModel malaDiretaViewModel = this; + visibility = (nums.Count > 1 ? Visibility.Hidden : Visibility.Visible); + malaDiretaViewModel.VisibilitySalvarAnexos = visibility; + List clienteEmails = await clienteServico.BuscarEmailsPorCliente(nums); + List malaDiretas2 = new List(); + maladireta.ForEach((Gestor.Model.Domain.MalaDireta.MalaDireta x) => { + bool flag; + if (x.get_Cliente() != null) + { + MalaDiretaViewModel u003cu003e4_this = this; + if (this.Assinatura) + { + flag = true; + } + else if (x.get_ArquivoDigital() == null) + { + flag = false; + } + else + { + List arquivoDigital = x.get_ArquivoDigital(); + Func u003cu003e9_8417 = MalaDiretaViewModel.u003cu003ec.u003cu003e9__84_17; + if (u003cu003e9_8417 == null) + { + u003cu003e9_8417 = (IndiceArquivoDigital a) => { + if (string.IsNullOrEmpty(a.get_UrlAssinatura())) + { + return false; + } + return !a.get_Assinado(); + }; + MalaDiretaViewModel.u003cu003ec.u003cu003e9__84_17 = u003cu003e9_8417; + } + flag = arquivoDigital.Any(u003cu003e9_8417); + } + u003cu003e4_this.Assinatura = flag; + List list = ( + from e in clienteEmails + where e.get_Cliente().get_Id() == this.x.get_Cliente().get_Id() + select e).ToList(); + int num = 0; + Func u003cu003e9_8419 = MalaDiretaViewModel.u003cu003ec.u003cu003e9__84_19; + if (u003cu003e9_8419 == null) + { + u003cu003e9_8419 = (ClienteEmail o) => o.get_Ordem().GetValueOrDefault(); + MalaDiretaViewModel.u003cu003ec.u003cu003e9__84_19 = u003cu003e9_8419; + } + list.OrderBy(u003cu003e9_8419).ToList().ForEach((ClienteEmail e) => { + x.set_Selecionado((!string.IsNullOrWhiteSpace(x.get_Email()) ? false : x.get_Cliente().get_MalaDireta().GetValueOrDefault(true))); + if (num <= 0) + { + x.set_Email(e.get_Email()); + x.set_Ordem(e.get_Ordem().GetValueOrDefault()); + Gestor.Model.Domain.MalaDireta.MalaDireta malaDiretum = new Gestor.Model.Domain.MalaDireta.MalaDireta(); + DomainBase.Copy(malaDiretum, x); + malaDiretas2.Add(malaDiretum); + } + else + { + Gestor.Model.Domain.MalaDireta.MalaDireta malaDiretum1 = new Gestor.Model.Domain.MalaDireta.MalaDireta(); + DomainBase.Copy(malaDiretum1, x); + malaDiretum1.set_Email(e.get_Email()); + malaDiretum1.set_Selecionado(false); + malaDiretas2.Add(malaDiretum1); + } + num++; + }); + } + if (x.get_Prospeccao() == null) + { + return; + } + Gestor.Model.Domain.MalaDireta.MalaDireta malaDiretum2 = new Gestor.Model.Domain.MalaDireta.MalaDireta(); + Gestor.Model.Domain.MalaDireta.MalaDireta malaDiretum3 = x; + Cliente cliente = x.get_Cliente(); + if (cliente == null) + { + cliente = new Cliente(); + cliente.set_Nome(x.get_Prospeccao().get_Nome()); + cliente.set_Documento(x.get_Prospeccao().get_Documento()); + } + malaDiretum3.set_Cliente(cliente); + if (string.IsNullOrEmpty(x.get_Cliente().get_Documento())) + { + x.get_Cliente().set_Documento(x.get_Prospeccao().get_Documento()); + } + x.set_Email(x.get_Prospeccao().get_Email()); + x.set_Ordem(0); + x.set_Selecionado(true); + DomainBase.Copy(malaDiretum2, x); + malaDiretas2.Add(malaDiretum2); + }); + MalaDiretaViewModel observableCollection = this; + List malaDiretas3 = malaDiretas2; + IOrderedEnumerable nome = + from x in malaDiretas3 + orderby x.get_Cliente().get_Nome() + select x; + observableCollection.MalaDireta = new ObservableCollection(nome.ThenBy((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Ordem())); + this.Variaveis.Add(new ComboVariavel(18, false)); + this.Variaveis.Add(new ComboVariavel(0, false)); + this.Variaveis.Add(new ComboVariavel(1, false)); + this.Variaveis.Add(new ComboVariavel(2, false)); + ObservableCollection variaveis = this.Variaveis; + ObservableCollection malaDireta = this.MalaDireta; + comboVariavel = (malaDireta.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Cliente().get_VencimentoHabilitacao().HasValue) ? new ComboVariavel(16, false) : new ComboVariavel(16, true)); + variaveis.Add(comboVariavel); + ObservableCollection malaDireta1 = this.MalaDireta; + if (!malaDireta1.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Cliente().get_Nascimento().HasValue)) + { + this.Variaveis.Add(new ComboVariavel(14, true)); + this.Variaveis.Add(new ComboVariavel(15, true)); + } + else + { + this.Variaveis.Add(new ComboVariavel(14, false)); + this.Variaveis.Add(new ComboVariavel(15, false)); + } + ObservableCollection variaveis1 = this.Variaveis; + ObservableCollection observableCollection1 = this.MalaDireta; + comboVariavel1 = (observableCollection1.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => { + if (x.get_ArquivoDigital() == null) + { + return false; + } + return x.get_ArquivoDigital().Any((IndiceArquivoDigital z) => !string.IsNullOrWhiteSpace(z.get_UrlAssinatura())); + }) ? new ComboVariavel(17, false) : new ComboVariavel(17, true)); + variaveis1.Add(comboVariavel1); + ObservableCollection malaDireta2 = this.MalaDireta; + if (!malaDireta2.All((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Apolice() != null)) + { + this.Variaveis.Add(new ComboVariavel(19, true)); + this.Variaveis.Add(new ComboVariavel(3, true)); + this.Variaveis.Add(new ComboVariavel(4, true)); + this.Variaveis.Add(new ComboVariavel(7, true)); + this.Variaveis.Add(new ComboVariavel(8, true)); + this.Variaveis.Add(new ComboVariavel(5, true)); + this.Variaveis.Add(new ComboVariavel(6, true)); + } + else + { + this.Variaveis.Add(new ComboVariavel(3, false)); + this.Variaveis.Add(new ComboVariavel(4, false)); + this.Variaveis.Add(new ComboVariavel(7, false)); + ObservableCollection variaveis2 = this.Variaveis; + ObservableCollection observableCollection2 = this.MalaDireta; + comboVariavel7 = (observableCollection2.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Apolice().get_Vigencia2().HasValue) ? new ComboVariavel(8, false) : new ComboVariavel(8, true)); + variaveis2.Add(comboVariavel7); + this.Variaveis.Add(new ComboVariavel(19, false)); + this.Variaveis.Add(new ComboVariavel(23, false)); + this.Variaveis.Add(new ComboVariavel(24, false)); + ObservableCollection malaDireta3 = this.MalaDireta; + if (!malaDireta3.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Apolice().get_Controle() != null)) + { + this.Variaveis.Add(new ComboVariavel(5, true)); + this.Variaveis.Add(new ComboVariavel(6, true)); + } + else + { + this.Variaveis.Add(new ComboVariavel(5, false)); + this.Variaveis.Add(new ComboVariavel(6, false)); + } + } + ObservableCollection observableCollection3 = this.MalaDireta; + if (!observableCollection3.All((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Parcela() != null)) + { + this.Variaveis.Add(new ComboVariavel(9, true)); + this.Variaveis.Add(new ComboVariavel(10, true)); + this.Variaveis.Add(new ComboVariavel(13, true)); + } + else + { + this.Variaveis.Add(new ComboVariavel(9, false)); + this.Variaveis.Add(new ComboVariavel(10, false)); + this.Variaveis.Add(new ComboVariavel(13, false)); + } + ObservableCollection variaveis3 = this.Variaveis; + ObservableCollection malaDireta4 = this.MalaDireta; + comboVariavel2 = (malaDireta4.All((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Item() != null) ? new ComboVariavel(11, false) : new ComboVariavel(11, true)); + variaveis3.Add(comboVariavel2); + ObservableCollection variaveis4 = this.Variaveis; + ObservableCollection observableCollection4 = this.MalaDireta; + comboVariavel3 = (observableCollection4.All((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.get_Sinistro() != null) ? new ComboVariavel(12, false) : new ComboVariavel(12, true)); + variaveis4.Add(comboVariavel3); + this.Variaveis = new ObservableCollection(this.Variaveis); + ObservableCollection variaveis5 = this.Variaveis; + ObservableCollection malaDireta5 = this.MalaDireta; + comboVariavel4 = (malaDireta5.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => { + Documento apolice = x.get_Apolice(); + if (apolice == null) + { + return false; + } + apolice.get_PremioLiquido(); + return true; + }) ? new ComboVariavel(20, false) : new ComboVariavel(20, true)); + variaveis5.Add(comboVariavel4); + ObservableCollection observableCollection5 = this.Variaveis; + ObservableCollection malaDireta6 = this.MalaDireta; + comboVariavel5 = (malaDireta6.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => { + Documento apolice = x.get_Apolice(); + if (apolice == null) + { + return false; + } + apolice.get_PremioTotal(); + return true; + }) ? new ComboVariavel(21, false) : new ComboVariavel(21, true)); + observableCollection5.Add(comboVariavel5); + ObservableCollection variaveis6 = this.Variaveis; + ObservableCollection observableCollection6 = this.MalaDireta; + comboVariavel6 = (observableCollection6.Any((Gestor.Model.Domain.MalaDireta.MalaDireta x) => { + Documento apolice = x.get_Apolice(); + if (apolice == null) + { + return false; + } + return apolice.get_FormaPagamento().HasValue; + }) ? new ComboVariavel(22, false) : new ComboVariavel(22, true)); + variaveis6.Add(comboVariavel6); + await this.CarregarModelos(null); + if (assunto != null) + { + this.Assunto = assunto; + } + if (corpo != null) + { + this.Corpo = corpo; + } + } + + private async Task CarregarModelos(ModeloMalaDireta modelo = null) + { + List modeloMalaDiretas = await this._servico.BuscarModelos(); + List comboModelos = new List(); + foreach (ModeloMalaDireta modeloMalaDiretum in modeloMalaDiretas) + { + comboModelos.Add(new ComboModelo() + { + ModeloMalaDireta = modeloMalaDiretum + }); + } + this.Modelos = new ObservableCollection(comboModelos); + if (modelo != null) + { + this.SelectedModelo = this.Modelos.FirstOrDefault((ComboModelo x) => x.ModeloMalaDireta.get_Id() == modelo.get_Id()); + } + } + + public void Delete(Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + if (this.SelectedAnexado == null) + { + return; + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = this.ArquivosAnexados.First((Gestor.Model.Domain.Common.ArquivoDigital x) => x.get_Descricao() == arquivo.get_Descricao()); + this.ArquivosAnexados.Remove(arquivoDigital); + this.ArquivosAnexados = new ObservableCollection(this.ArquivosAnexados); + } + + public async Task Enviar() + { + bool flag; + if (string.IsNullOrWhiteSpace(this.Corpo) || string.IsNullOrWhiteSpace(this.Assunto)) + { + await base.ShowMessage("NECESSÁRIO CONTER ASSUNTO E MENSAGEM PARA PROSSEGUIR.", "OK", "", false); + flag = false; + } + else if (this.SelectedCredencial == null || this.SelectedCredencial.get_Id() == 0) + { + await base.ShowMessage("NECESSÁRIO SELECIONAR O E-MAIL DE ENVIO PARA PROSSEGUIR.", "OK", "", false); + flag = false; + } + else + { + ObservableCollection malaDireta = this.MalaDireta; + List list = ( + from x in malaDireta + where x.get_Selecionado() + select x).ToList(); + if (list.Count != 0) + { + await base.ShowEnviarEmailsDialog(list, this.Assinatura, this.EnviarOriginal, this.ArquivosAnexados.ToList(), this.Assunto, this.Corpo, this.SelectedCredencial, this._filtro, this.SalvarArquivoDigital, this.ConfirmarLeitura); + this.Enviado = true; + flag = true; + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM DESTINATÁRIO PARA PROSSEGUIR.", "OK", "", false); + flag = false; + } + } + return flag; + } + + public async void Excluir() + { + if (this.SelectedModelo != null && this.SelectedModelo.ModeloMalaDireta.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA REALMENTE EXCLUIR O MODELO?", "SIM", "NÃO", false)) + { + if (await this._servico.Delete(this.SelectedModelo.ModeloMalaDireta)) + { + base.RegistrarAcao(string.Concat("EXCLUIU MODELO ", this.SelectedModelo.ModeloMalaDireta.get_Assunto()), this.SelectedModelo.ModeloMalaDireta.get_Id(), new TipoTela?(39), null); + await this.CarregarModelos(null); + this.SelectedModelo = null; + base.ToggleSnackBar("MODELO EXCLUÍDO COM SUCESSO", true); + } + } + } + } + + public void Incluir() + { + this.SelectedModelo = new ComboModelo(); + this.Corpo = string.Empty; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + if (this.SelectedModelo != null) + { + this.SelectedModelo.ModeloMalaDireta.set_Assunto(this.Assunto); + this.SelectedModelo.ModeloMalaDireta.set_Corpo(this.Corpo); + } + else + { + ComboModelo comboModelo = new ComboModelo(); + ModeloMalaDireta modeloMalaDiretum = new ModeloMalaDireta(); + modeloMalaDiretum.set_Assunto(this.Assunto); + modeloMalaDiretum.set_Corpo(this.Corpo); + comboModelo.ModeloMalaDireta = modeloMalaDiretum; + this.SelectedModelo = comboModelo; + } + List> keyValuePairs1 = this.SelectedModelo.ModeloMalaDireta.Validate(); + if (keyValuePairs1.Count <= 0) + { + ModeloMalaDireta modeloMalaDiretum1 = await this._servico.Save(this.SelectedModelo.ModeloMalaDireta); + if (this._servico.Sucesso) + { + base.Alterar(false); + await this.CarregarModelos(modeloMalaDiretum1); + base.ToggleSnackBar("MODELO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + public void Selecionar() + { + this.MalaDireta.ToList().ForEach((Gestor.Model.Domain.MalaDireta.MalaDireta x) => x.set_Selecionado(!x.get_Selecionado())); + this.MalaDireta = new ObservableCollection(this.MalaDireta); + } + + private void WorkOnSelectedModelo(ModeloMalaDireta value) + { + if (value == null) + { + return; + } + this.Corpo = this.SelectedModelo.ModeloMalaDireta.get_Corpo(); + this.Assunto = this.SelectedModelo.ModeloMalaDireta.get_Assunto(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ManutencaoPagamentosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ManutencaoPagamentosViewModel.cs new file mode 100644 index 0000000..5270c3f --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ManutencaoPagamentosViewModel.cs @@ -0,0 +1,821 @@ +using CsQuery.ExtensionMethods; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.ViewModels.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 System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Data; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ManutencaoPagamentosViewModel : BaseSegurosViewModel + { + private Visibility _filtrosPersonalizados = Visibility.Collapsed; + + private Visibility _visibilityFiltroPersonalizado = Visibility.Collapsed; + + private List _filtroRelatorioPersonalizado; + + private Gestor.Model.Domain.Relatorios.FiltroPersonalizado _filtroPersonalizado; + + private Type _tipoString = typeof(string); + + private Type _tipoEnum = typeof(Enum); + + private Type _tipoDateTime = typeof(DateTime); + + private Type _tipoDecimal = typeof(decimal); + + private Type _tipoInt = typeof(int); + + private Type _tipoLong = typeof(long); + + private string _valorIncial = ""; + + private string _valorFinal = ""; + + private bool _semValor; + + private Visibility _visibilitySemValor = Visibility.Collapsed; + + private ObservableCollection _filtroPersonalizadoSelecionado; + + private ObservableCollection _filtroRelatorioSelecionado = new ObservableCollection(); + + private ObservableCollection _vendedores = new ObservableCollection(); + + private Vendedor _selectedVendedor; + + private bool _enableExcluirManutPagamento; + + private ObservableCollection _pagamentos; + + private ListCollectionView _view; + + private bool _allSelected; + + private string _selectedFiltro; + + private ObservableCollection _filtros; + + private DateTime? _inicio; + + private DateTime? _fim; + + private List _todosPagamentos; + + public bool AllSelected + { + get + { + return this._allSelected; + } + set + { + this._allSelected = value; + base.OnPropertyChanged("AllSelected"); + this.Selecionar(value); + } + } + + public bool EnableExcluirManutPagamento + { + get + { + return this._enableExcluirManutPagamento; + } + set + { + this._enableExcluirManutPagamento = value; + base.OnPropertyChanged("EnableExcluirManutPagamento"); + } + } + + public Gestor.Model.Domain.Relatorios.FiltroPersonalizado FiltroPersonalizado + { + get + { + return this._filtroPersonalizado; + } + set + { + char chr; + this._filtroPersonalizado = value; + this.VisibilitySemValor = (value != null ? Visibility.Visible : Visibility.Collapsed); + base.OnPropertyChanged("FiltroPersonalizado"); + if (value == null) + { + return; + } + string name = value.get_Tipo().Name; + if (name != null) + { + switch (name.Length) + { + case 3: + { + if (name == "int") + { + break; + } + return; + } + case 4: + { + chr = name[0]; + if (chr == 'E') + { + if (name == "Enum") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + else + { + if (chr != 'l') + { + return; + } + if (name == "long") + { + break; + } + return; + } + } + case 5: + { + chr = name[3]; + if (chr == '3') + { + if (name == "int32") + { + break; + } + return; + } + else + { + if (chr != '6') + { + return; + } + if (name == "int64") + { + break; + } + return; + } + } + case 6: + { + if (name != "String") + { + return; + } + this.ValorInicial = ""; + this.ValorFinal = ""; + return; + } + case 7: + { + if (name != "Decimal") + { + return; + } + this.ValorInicial = "0,00"; + this.ValorFinal = "0,00"; + return; + } + case 8: + { + if (name == "DateTime") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + default: + { + return; + } + } + this.ValorInicial = "0"; + this.ValorFinal = "0"; + } + } + } + + public ObservableCollection FiltroPersonalizadoSelecionado + { + get + { + return this._filtroPersonalizadoSelecionado; + } + set + { + this._filtroPersonalizadoSelecionado = value; + base.OnPropertyChanged("FiltroPersonalizadoSelecionado"); + } + } + + public ObservableCollection FiltroRelatorioSelecionado + { + get + { + return this._filtroRelatorioSelecionado; + } + set + { + this._filtroRelatorioSelecionado = value; + base.OnPropertyChanged("FiltroRelatorioSelecionado"); + } + } + + public ObservableCollection Filtros + { + get + { + return this._filtros; + } + set + { + this._filtros = value; + base.OnPropertyChanged("Filtros"); + } + } + + public Visibility FiltrosPersonalizados + { + get + { + return this._filtrosPersonalizados; + } + set + { + this._filtrosPersonalizados = value; + base.OnPropertyChanged("FiltrosPersonalizados"); + } + } + + public DateTime? Fim + { + get + { + return this._fim; + } + set + { + if (value.HasValue && value.Value < new DateTime(1754, 1, 1)) + { + value = new DateTime?(new DateTime(1754, 1, 1)); + } + if (value.HasValue && value.Value > new DateTime(9999, 12, 31)) + { + value = new DateTime?(new DateTime(9999, 12, 31)); + } + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public DateTime? Inicio + { + get + { + return this._inicio; + } + set + { + if (value.HasValue && value.Value < new DateTime(1754, 1, 1)) + { + value = new DateTime?(new DateTime(1754, 1, 1)); + } + if (value.HasValue && value.Value > new DateTime(9999, 12, 31)) + { + value = new DateTime?(new DateTime(9999, 12, 31)); + } + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public ObservableCollection Pagamentos + { + get + { + return this._pagamentos; + } + set + { + this._pagamentos = value; + this.View = new ListCollectionView(value); + this.View.GroupDescriptions.Add(new PropertyGroupDescription("Pagamento")); + this.View.GroupDescriptions.Add(new PropertyGroupDescription("Vendedor")); + base.OnPropertyChanged("Pagamentos"); + } + } + + public List RelatorioFiltroPersonalizado + { + get + { + return this._filtroRelatorioPersonalizado; + } + set + { + this._filtroRelatorioPersonalizado = value; + base.OnPropertyChanged("RelatorioFiltroPersonalizado"); + } + } + + public string SelectedFiltro + { + get + { + return this._selectedFiltro; + } + set + { + this._selectedFiltro = value; + base.OnPropertyChanged("SelectedFiltro"); + } + } + + public Vendedor SelectedVendedor + { + get + { + return this._selectedVendedor; + } + set + { + this._selectedVendedor = value; + base.OnPropertyChanged("SelectedVendedor"); + } + } + + public bool SemValor + { + get + { + return this._semValor; + } + set + { + this._semValor = value; + if (value) + { + this.ValorInicial = null; + this.ValorFinal = null; + } + base.OnPropertyChanged("SemValor"); + } + } + + public Type TipoDateTime + { + get + { + return this._tipoDateTime; + } + set + { + this._tipoDateTime = value; + base.OnPropertyChanged("TipoDateTime"); + } + } + + public Type TipoDecimal + { + get + { + return this._tipoDecimal; + } + set + { + this._tipoDecimal = value; + base.OnPropertyChanged("TipoDecimal"); + } + } + + public Type TipoEnum + { + get + { + return this._tipoEnum; + } + set + { + this._tipoEnum = value; + base.OnPropertyChanged("TipoEnum"); + } + } + + public Type TipoInt + { + get + { + return this._tipoInt; + } + set + { + this._tipoInt = value; + base.OnPropertyChanged("TipoInt"); + } + } + + public Type TipoLong + { + get + { + return this._tipoLong; + } + set + { + this._tipoLong = value; + base.OnPropertyChanged("TipoLong"); + } + } + + public Type TipoString + { + get + { + return this._tipoString; + } + set + { + this._tipoString = value; + base.OnPropertyChanged("TipoString"); + } + } + + private List TodosPagamentos + { + get + { + return this._todosPagamentos; + } + set + { + this.FiltrosPersonalizados = (value == null || !value.Any() ? Visibility.Collapsed : Visibility.Visible); + this._todosPagamentos = value; + } + } + + public string ValorFinal + { + get + { + return this._valorFinal; + } + set + { + this._valorFinal = value; + base.OnPropertyChanged("ValorFinal"); + } + } + + public string ValorInicial + { + get + { + return this._valorIncial; + } + set + { + this._valorIncial = value; + base.OnPropertyChanged("ValorInicial"); + } + } + + public ObservableCollection Vendedores + { + get + { + return this._vendedores; + } + set + { + this._vendedores = value; + this.SelectedVendedor = this.SelectedVendedor ?? value.FirstOrDefault(); + base.OnPropertyChanged("Vendedores"); + } + } + + public ListCollectionView View + { + get + { + return this._view; + } + set + { + this._view = value; + base.OnPropertyChanged("View"); + } + } + + public Visibility VisibilityFiltroPersonalizado + { + get + { + return this._visibilityFiltroPersonalizado; + } + set + { + this._visibilityFiltroPersonalizado = value; + base.OnPropertyChanged("VisibilityFiltroPersonalizado"); + } + } + + public Visibility VisibilitySemValor + { + get + { + return this._visibilitySemValor; + } + set + { + this._visibilitySemValor = value; + base.OnPropertyChanged("VisibilitySemValor"); + } + } + + public ManutencaoPagamentosViewModel() + { + this._filtrosPersonalizados = Visibility.Collapsed; + this._visibilityFiltroPersonalizado = Visibility.Collapsed; + this._tipoString = typeof(string); + this._tipoEnum = typeof(Enum); + this._tipoDateTime = typeof(DateTime); + this._tipoDecimal = typeof(decimal); + this._tipoInt = typeof(int); + this._tipoLong = typeof(long); + this._valorIncial = ""; + this._valorFinal = ""; + this._visibilitySemValor = Visibility.Collapsed; + this._filtroRelatorioSelecionado = new ObservableCollection(); + this._vendedores = new ObservableCollection(); + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + this._enableExcluirManutPagamento = id; + this._inicio = new DateTime?(Funcoes.GetNetworkTime()); + DateTime networkTime = Funcoes.GetNetworkTime(); + this._fim = new DateTime?(networkTime.AddDays(7)); + base(); + bool id; + this.Filtros = new ObservableCollection() + { + "DATA DE EMISSÃO DO RECEBIMENTO", + "DATA DE EMISSÃO DO RECIBO DE PAGAMENTO" + }; + this.SelectedFiltro = this.Filtros.First(); + List list = ( + from x in Recursos.Vendedores + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList(); + Vendedor vendedor = new Vendedor(); + vendedor.set_Id((long)0); + vendedor.set_Nome("TODAS OS VENDEDORES"); + list.Insert(0, vendedor); + this.Vendedores = new ObservableCollection(list); + this.RelatorioFiltroPersonalizado = Funcoes.PopularFiltroPersonalizado(); + } + + public async void AdcionarFiltroPersonalizado() + { + string str; + DateTime dateTime; + decimal num; + int num1; + long num2; + List filtroPersonalizados; + List filtroPersonalizados1; + if (this.FiltroPersonalizado != null) + { + if (this.SemValor) + { + filtroPersonalizados = (this.FiltroPersonalizadoSelecionado == null ? new List() : ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Propriedade() == this.FiltroPersonalizado.get_Propriedade() + select x).ToList()); + List filtroPersonalizados2 = filtroPersonalizados; + if (filtroPersonalizados2.Count > 0) + { + filtroPersonalizados2.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.FiltroPersonalizadoSelecionado.Remove(x)); + } + str = string.Concat(this.FiltroPersonalizado.get_Nome(), ": EM BRANCO"); + } + else + { + filtroPersonalizados1 = (this.FiltroPersonalizadoSelecionado == null ? new List() : this.FiltroPersonalizadoSelecionado.Where((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => { + if (x.get_Propriedade() != this.FiltroPersonalizado.get_Propriedade()) + { + return false; + } + return x.get_SemValor(); + }).ToList()); + List filtroPersonalizados3 = filtroPersonalizados1; + if (filtroPersonalizados3.Count > 0) + { + filtroPersonalizados3.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.FiltroPersonalizadoSelecionado.Remove(x)); + } + string name = this.FiltroPersonalizado.get_Tipo().Name; + if (name == "DateTime") + { + if (!DateTime.TryParse(this.ValorInicial, out dateTime) || !DateTime.TryParse(this.ValorFinal, out dateTime) || DateTime.Parse(this.ValorInicial) > DateTime.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:d} até {2:d}", this.FiltroPersonalizado.get_Nome(), DateTime.Parse(this.ValorInicial), DateTime.Parse(this.ValorFinal)); + } + } + else if (name == "Decimal") + { + if (!decimal.TryParse(this.ValorInicial, out num) || !decimal.TryParse(this.ValorFinal, out num) || Math.Abs(decimal.Parse(this.ValorInicial)) > Math.Abs(decimal.Parse(this.ValorFinal))) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n2} até {2:n2}", this.FiltroPersonalizado.get_Nome(), decimal.Parse(this.ValorInicial), decimal.Parse(this.ValorFinal)); + } + } + else if (name == "Int32") + { + if (!int.TryParse(this.ValorInicial, out num1) || !int.TryParse(this.ValorFinal, out num1) || int.Parse(this.ValorInicial) > int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.FiltroPersonalizado.get_Nome(), int.Parse(this.ValorInicial), int.Parse(this.ValorFinal)); + } + } + else if (name != "Int64") + { + if (!string.IsNullOrEmpty(this.ValorInicial)) + { + str = string.Concat(this.FiltroPersonalizado.get_Nome(), " = ", this.ValorInicial); + } + else + { + await base.ShowMessage("O VALOR DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + } + else if (!long.TryParse(this.ValorInicial, out num2) || !long.TryParse(this.ValorFinal, out num2) || long.Parse(this.ValorInicial) > (long)int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.FiltroPersonalizado.get_Nome(), long.Parse(this.ValorInicial), long.Parse(this.ValorFinal)); + } + } + if (this.FiltroPersonalizadoSelecionado == null) + { + this.FiltroPersonalizadoSelecionado = new ObservableCollection(); + } + ObservableCollection filtroPersonalizadoSelecionado = this.FiltroPersonalizadoSelecionado; + Gestor.Model.Domain.Relatorios.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Relatorios.FiltroPersonalizado(); + filtroPersonalizado.set_Nome(this.FiltroPersonalizado.get_Nome()); + filtroPersonalizado.set_Propriedade(this.FiltroPersonalizado.get_Propriedade()); + filtroPersonalizado.set_Tipo(this.FiltroPersonalizado.get_Tipo()); + filtroPersonalizado.set_ValorIncial(this.ValorInicial); + filtroPersonalizado.set_ValorFinal(this.ValorFinal); + filtroPersonalizado.set_SemValor(this.SemValor); + filtroPersonalizado.set_Descricao(str); + filtroPersonalizadoSelecionado.Add(filtroPersonalizado); + this.FiltroPersonalizado = null; + this.ValorInicial = string.Empty; + this.ValorFinal = string.Empty; + this.PesquisaPersonalizada(); + } + } + + public async Task Buscar() + { + if (this.Inicio.HasValue && this.Fim.HasValue) + { + this.FiltroPersonalizadoSelecionado = null; + this.VisibilityFiltroPersonalizado = Visibility.Visible; + Gestor.Model.Domain.Relatorios.Filtros filtro = new Gestor.Model.Domain.Relatorios.Filtros(); + filtro.set_Inicio(this.Inicio.Value); + filtro.set_Fim(this.Fim.Value); + Gestor.Model.Domain.Relatorios.Filtros filtro1 = filtro; + if (this.SelectedVendedor.get_Id() > (long)0) + { + filtro1.set_Vendedores(new List() + { + this.SelectedVendedor.get_Id() + }); + } + if (this.SelectedFiltro == "DATA DE EMISSÃO DO RECEBIMENTO") + { + filtro1.set_Referencia("DATA PREVISÃO"); + } + else + { + filtro1.set_Referencia("DATA PAGAMENTO"); + } + this.TodosPagamentos = await (new VendedorServico()).BuscarPagos(filtro1); + this.Pagamentos = new ObservableCollection(this.TodosPagamentos); + string[] shortDateString = new string[] { "CONSULTOU OS PAGAMENTOS DE \"", null, null, null, null, null }; + DateTime value = this.Inicio.Value; + shortDateString[1] = value.ToShortDateString(); + shortDateString[2] = "\" A \""; + value = this.Fim.Value; + shortDateString[3] = value.ToShortDateString(); + shortDateString[4] = "\" POR "; + shortDateString[5] = this.SelectedFiltro; + base.RegistrarAcao(string.Concat(shortDateString), (long)0, new TipoTela?(58), null); + } + } + + public async Task Excluir() + { + object obj; + string str; + ObservableCollection pagamentos = this.Pagamentos; + List list = ( + from x in pagamentos + where x.get_Selecionado() + select x).ToList(); + if (list.Count != 0) + { + str = "PAGAMENTOS EXCLUÍDOS:"; + foreach (ManutencaoPagamentos manutencaoPagamento in list) + { + str = string.Concat(str, string.Format("\nID: {0}, NÚMERO: {1}, ID DOCUMENTO: {2}", manutencaoPagamento.get_Id(), manutencaoPagamento.get_Parcela(), manutencaoPagamento.get_IdDocumento())); + VendedorParcela vendedorParcela = await (new VendedorServico()).BuscarVendedorParcelaCompleto(manutencaoPagamento.get_Id()); + vendedorParcela.set_DataPagamento(null); + await (new ParcelaServico()).Save(vendedorParcela); + } + ManutencaoPagamentosViewModel manutencaoPagamentosViewModel = this; + object count = list.Count; + obj = (list.Count > 1 ? "S" : ""); + manutencaoPagamentosViewModel.RegistrarAcao(string.Format("EXCLUIU {0} PAGAMENTO{1}", count, obj), (long)0, new TipoTela?(58), str); + for (int i = this.Pagamentos.Count - 1; i >= 0; i--) + { + if (this.Pagamentos[i].get_Selecionado()) + { + this.Pagamentos.RemoveAt(i); + } + } + base.ToggleSnackBar("PAGAMENTOS EXCLUÍDOS COM SUCESSO.", true); + } + list = null; + str = null; + } + + public void PesquisaPersonalizada() + { + this.Pagamentos = new ObservableCollection(this.TodosPagamentos.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), false)); + } + + public void Selecionar(bool value) + { + if (this.Pagamentos == null || this.Pagamentos.Count == 0) + { + return; + } + ExtensionMethods.ForEach(this.Pagamentos, (ManutencaoPagamentos x) => x.set_Selecionado(value)); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/NotaFiscalViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/NotaFiscalViewModel.cs new file mode 100644 index 0000000..61ee285 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/NotaFiscalViewModel.cs @@ -0,0 +1,482 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class NotaFiscalViewModel : BaseSegurosViewModel + { + private readonly NotaFiscalServico _servico; + + private readonly ServicoExtrato _servicoExtrato; + + private bool _apelido; + + private List _estipulantes; + + private List _seguradoras; + + private ObservableCollection _notasFiscaisFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private string _numExtrato; + + private NotaFiscal _selectedNotaFiscal; + + public NotaFiscal CancelNotaFiscal; + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public List Estipulantes + { + get + { + return this._estipulantes; + } + set + { + this._estipulantes = value; + base.OnPropertyChanged("Estipulantes"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public List NotasFiscais + { + get; + set; + } + + public ObservableCollection NotasFiscaisFiltrados + { + get + { + return this._notasFiscaisFiltrados; + } + set + { + this._notasFiscaisFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("NotasFiscaisFiltrados"); + } + } + + public string NumExtrato + { + get + { + return this._numExtrato; + } + set + { + this._numExtrato = value; + base.OnPropertyChanged("NumExtrato"); + } + } + + public List Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public NotaFiscal SelectedNotaFiscal + { + get + { + return this._selectedNotaFiscal; + } + set + { + long? nullable; + this._selectedNotaFiscal = value; + this.WorkOnSelectedNotaFiscal(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedNotaFiscal"); + } + } + + public NotaFiscalViewModel() + { + this._servicoExtrato = new ServicoExtrato(); + this._servico = new NotaFiscalServico(); + this.Seguradoras = ( + from x in Recursos.Seguradoras + where x.get_Ativo() + select x).ToList(); + this.Estipulantes = ( + from e in Recursos.Estipulantes + where e.get_Ativo() + select e).ToList(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + base.EnableMenu = true; + this.Seleciona(); + } + + public async Task BuscarImposto() + { + decimal iss; + List impostos = await (new ImpostoServico()).Buscar(new bool?(true)); + Imposto imposto = impostos.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != this.SelectedNotaFiscal.get_Seguradora().get_Id()) + { + return false; + } + return x.get_Ramo() == null; + }); + if (imposto == null) + { + List impostos1 = impostos; + imposto = impostos1.FirstOrDefault((Imposto x) => { + if (x.get_Seguradora() != null) + { + return false; + } + return x.get_Ramo() == null; + }); + } + if (imposto != null) + { + iss = imposto.get_Iss(); + } + else + { + iss = decimal.Zero; + } + return iss; + } + + public void CancelarAlteracao() + { + if (this.CancelNotaFiscal == null || !this.NotasFiscais.Any((NotaFiscal x) => x.get_Id() == this.CancelNotaFiscal.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.NotasFiscais.First((NotaFiscal x) => x.get_Id() == this.CancelNotaFiscal.get_Id()), this.CancelNotaFiscal); + if (this.NotasFiscaisFiltrados.Count <= 0 || !this.NotasFiscaisFiltrados.Any((NotaFiscal x) => x.get_Id() == this.CancelNotaFiscal.get_Id())) + { + this.NotasFiscaisFiltrados.Add(this.CancelNotaFiscal); + } + else + { + DomainBase.Copy(this.NotasFiscaisFiltrados.First((NotaFiscal x) => x.get_Id() == this.CancelNotaFiscal.get_Id()), this.CancelNotaFiscal); + } + this.NotasFiscaisFiltrados = new ObservableCollection(this.NotasFiscaisFiltrados); + this.SelectedNotaFiscal = this.NotasFiscaisFiltrados.First((NotaFiscal x) => x.get_Id() == this.CancelNotaFiscal.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + object obj; + if (this.SelectedNotaFiscal != null && this.SelectedNotaFiscal.get_Id() != 0) + { + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR A NOTA FISCAL DA ", this.SelectedNotaFiscal.get_Seguradora().get_Nome(), "?"), "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedNotaFiscal)) + { + NotaFiscalViewModel notaFiscalViewModel = this; + string str = string.Format("EXCLUIU NOTA FISCAL DE ID \"{0}\"", this.SelectedNotaFiscal.get_Id()); + long id = this.SelectedNotaFiscal.get_Id(); + TipoTela? nullable = new TipoTela?(55); + object[] nome = new object[] { this.SelectedNotaFiscal.get_Seguradora().get_Nome(), null, null, null, null }; + obj = (!this.SelectedNotaFiscal.get_Data().HasValue ? "-" : string.Format("{0:d}", this.SelectedNotaFiscal.get_Data())); + nome[1] = obj; + nome[2] = this.SelectedNotaFiscal.get_ValorBruto(); + nome[3] = this.SelectedNotaFiscal.get_Iss(); + nome[4] = this.SelectedNotaFiscal.get_ValorLiquido(); + notaFiscalViewModel.RegistrarAcao(str, id, nullable, string.Format("SEGURADORA: {0}\nDATA: {1}\nBRUTO: {2:c}\nISS: {3:c}\nLÍQUIDO: {4:c}", nome)); + await this.SelecionaNotaFiscal(); + base.Loading(false); + base.ToggleSnackBar("RECIBO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public async Task> Filtrar(string value) + { + List notaFiscals = await Task.Run>(() => this.FiltrarNotaFiscal(value)); + return notaFiscals; + } + + public List FiltrarNotaFiscal(string filter) + { + this.NotasFiscaisFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.NotasFiscais) : new ObservableCollection(this.NotasFiscais.Where((NotaFiscal x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Seguradora().get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) || ValidationHelper.RemoveDiacritics(x.get_ValorBruto().ToString(CultureInfo.InvariantCulture).Trim()).Contains(ValidationHelper.RemoveDiacritics(filter))) + { + return true; + } + return ValidationHelper.RemoveDiacritics(x.get_Data().ToString().Trim()).Contains(ValidationHelper.RemoveDiacritics(filter)); + }).OrderBy((NotaFiscal x) => x.get_Seguradora().get_Nome()))); + return this.NotasFiscaisFiltrados.ToList(); + } + + public void Incluir() + { + NotaFiscal notaFiscal = new NotaFiscal(); + notaFiscal.set_Seguradora(new Seguradora()); + notaFiscal.set_Estipulante(new Estipulante()); + notaFiscal.set_Iss(decimal.Zero); + notaFiscal.set_ValorLiquido(decimal.Zero); + notaFiscal.set_ValorBruto(decimal.Zero); + notaFiscal.set_Extrato(""); + this.SelectedNotaFiscal = notaFiscal; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + long? nullable; + bool valueOrDefault; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedNotaFiscal.Validate(); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedNotaFiscal.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + NotaFiscal selectedNotaFiscal = this.SelectedNotaFiscal; + if (selectedNotaFiscal != null) + { + Estipulante estipulante = selectedNotaFiscal.get_Estipulante(); + if (estipulante != null) + { + nullable = new long?(estipulante.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + valueOrDefault = nullable1.GetValueOrDefault() <= num & nullable1.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + this.SelectedNotaFiscal.set_Estipulante(null); + } + NotaFiscal notaFiscal = await this._servico.Save(this.SelectedNotaFiscal); + if (this._servico.Sucesso) + { + NotaFiscalViewModel notaFiscalViewModel = this; + string str2 = string.Format("{0} NOTA FISCAL DE ID \"{1}\"", str1, notaFiscal.get_Id()); + long id = notaFiscal.get_Id(); + TipoTela? nullable2 = new TipoTela?(55); + object[] nome = new object[] { notaFiscal.get_Seguradora().get_Nome(), null, null, null, null }; + obj = (!notaFiscal.get_Data().HasValue ? "-" : string.Format("{0:d}", notaFiscal.get_Data())); + nome[1] = obj; + nome[2] = notaFiscal.get_ValorBruto(); + nome[3] = notaFiscal.get_Iss(); + nome[4] = notaFiscal.get_ValorLiquido(); + notaFiscalViewModel.RegistrarAcao(str2, id, nullable2, string.Format("SEGURADORA: {0}\nDATA: {1}\nBRUTO: {2:c}\nISS: {3:c}\nLÍQUIDO: {4:c}", nome)); + if (!this.NotasFiscais.Any((NotaFiscal x) => x.get_Id() == notaFiscal.get_Id())) + { + this.NotasFiscais.Add(notaFiscal); + } + else + { + DomainBase.Copy(this.NotasFiscais.First((NotaFiscal x) => x.get_Id() == notaFiscal.get_Id()), notaFiscal); + } + if (!this.NotasFiscaisFiltrados.Any((NotaFiscal x) => x.get_Id() == notaFiscal.get_Id())) + { + this.NotasFiscaisFiltrados.Add(notaFiscal); + } + else + { + DomainBase.Copy(this.NotasFiscaisFiltrados.First((NotaFiscal x) => x.get_Id() == notaFiscal.get_Id()), notaFiscal); + } + this.NotasFiscaisFiltrados = new ObservableCollection(this.NotasFiscaisFiltrados); + this.WorkOnSelectedNotaFiscal(notaFiscal, false); + base.Alterar(false); + base.ToggleSnackBar("NOTA FISCAL SALVA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + public async Task SalvarLote(List notas) + { + foreach (NotaFiscal nota in notas) + { + bool hasValue = nota.get_IdExtrato().HasValue; + if (hasValue) + { + NotaFiscalServico notaFiscalServico = this._servico; + long? idExtrato = nota.get_IdExtrato(); + hasValue = await notaFiscalServico.Cadatrada(idExtrato.Value); + } + if (hasValue) + { + continue; + } + this.SelectedNotaFiscal = nota; + await this.Salvar(); + } + base.ToggleSnackBar("NOTAS FISCAIS SALVAS COM SUCESSO", true); + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(55); + await this.SelecionaNotaFiscal(); + base.Loading(false); + } + + public async Task SelecionaNotaFiscal() + { + base.Loading(true); + List notaFiscals = await this._servico.BuscarNotasFiscais(); + NotaFiscalViewModel list = this; + List notaFiscals1 = notaFiscals; + list.NotasFiscais = ( + from x in notaFiscals1 + orderby x.get_Seguradora().get_Nome() + select x).ToList(); + this.NotasFiscaisFiltrados = new ObservableCollection(this.NotasFiscais); + this.SelectedNotaFiscal = this.NotasFiscaisFiltrados.FirstOrDefault(); + base.Loading(false); + } + + private async Task WorkOnSelectedNotaFiscal(NotaFiscal value, bool registrar = true) + { + string str; + long? idExtrato; + NotaFiscal notaFiscal; + long? nullable; + object obj; + NotaFiscalViewModel notaFiscalViewModel = this; + notaFiscal = (value == null || value.get_Id() == 0 ? this.CancelNotaFiscal : (NotaFiscal)value.Clone()); + notaFiscalViewModel.CancelNotaFiscal = notaFiscal; + if (value != null && value.get_Id() != 0 && (this.LastAccessId != value.get_Id() || this.LastAccessTela != 55)) + { + if (registrar) + { + NotaFiscalViewModel notaFiscalViewModel1 = this; + string str1 = string.Format("ACESSOU NOTA FISCAL DE ID \"{0}\"", value.get_Id()); + long id = value.get_Id(); + TipoTela? nullable1 = new TipoTela?(55); + object[] nome = new object[] { value.get_Seguradora().get_Nome(), null, null, null, null }; + obj = (!value.get_Data().HasValue ? "-" : string.Format("{0:d}", value.get_Data())); + nome[1] = obj; + nome[2] = value.get_ValorBruto(); + nome[3] = value.get_Iss(); + nome[4] = value.get_ValorLiquido(); + notaFiscalViewModel1.RegistrarAcao(str1, id, nullable1, string.Format("SEGURADORA: {0}\nDATA: {1}\nBRUTO: {2:c}\nISS: {3:c}\nLÍQUIDO: {4:c}", nome)); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 55; + if (string.IsNullOrEmpty(this.SelectedNotaFiscal.get_Extrato())) + { + NotaFiscal selectedNotaFiscal = this.SelectedNotaFiscal; + idExtrato = this.SelectedNotaFiscal.get_IdExtrato(); + if (!idExtrato.HasValue) + { + str = ""; + } + else + { + str = await this._servicoExtrato.BuscarNumExtrato(this.SelectedNotaFiscal.get_IdExtrato()); + } + selectedNotaFiscal.set_Extrato(str); + selectedNotaFiscal = null; + } + NotaFiscal selectedNotaFiscal1 = this.SelectedNotaFiscal; + if (selectedNotaFiscal1 != null) + { + nullable = new long?(selectedNotaFiscal1.get_Id()); + } + else + { + nullable = null; + } + idExtrato = nullable; + long num = value.get_Id(); + if (idExtrato.GetValueOrDefault() != num | !idExtrato.HasValue) + { + this.SelectedNotaFiscal = this.NotasFiscaisFiltrados.FirstOrDefault((NotaFiscal x) => x.get_Id() == value.get_Id()); + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProdutoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProdutoViewModel.cs new file mode 100644 index 0000000..40f14ae --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProdutoViewModel.cs @@ -0,0 +1,303 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ProdutoViewModel : BaseSegurosViewModel + { + private readonly ProdutoServico _servico; + + private Produto _selectedProduto; + + public Produto CancelProduto; + + private ObservableCollection _produtosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public List Produtos + { + get; + set; + } + + public ObservableCollection ProdutosFiltrados + { + get + { + return this._produtosFiltrados; + } + set + { + this._produtosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("ProdutosFiltrados"); + } + } + + public Produto SelectedProduto + { + get + { + return this._selectedProduto; + } + set + { + long? nullable; + this._selectedProduto = value; + this.WorkOnSelectedProduto(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedProduto"); + } + } + + public ProdutoViewModel() + { + this._servico = new ProdutoServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelProduto == null || !this.Produtos.Any((Produto x) => x.get_Id() == this.CancelProduto.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Produtos.First((Produto x) => x.get_Id() == this.CancelProduto.get_Id()), this.CancelProduto); + if (this.ProdutosFiltrados.Count <= 0 || !this.ProdutosFiltrados.Any((Produto x) => x.get_Id() == this.CancelProduto.get_Id())) + { + this.ProdutosFiltrados.Add(this.CancelProduto); + } + else + { + DomainBase.Copy(this.ProdutosFiltrados.First((Produto x) => x.get_Id() == this.CancelProduto.get_Id()), this.CancelProduto); + } + this.ProdutosFiltrados = new ObservableCollection(this.ProdutosFiltrados); + this.SelectedProduto = this.ProdutosFiltrados.First((Produto x) => x.get_Id() == this.CancelProduto.get_Id()); + } + base.Alterar(false); + } + + internal async Task> Filtrar(string value) + { + List produtos = await Task.Run>(() => this.FiltrarProduto(value)); + return produtos; + } + + public List FiltrarProduto(string filter) + { + this.ProdutosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Produtos) : new ObservableCollection( + from x in this.Produtos + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + this.SelectedProduto = this.ProdutosFiltrados.FirstOrDefault(); + return this.ProdutosFiltrados.ToList(); + } + + public void Incluir() + { + Produto produto = new Produto(); + produto.set_Ativo(true); + this.SelectedProduto = produto; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + List> keyValuePairs1 = this.SelectedProduto.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedProduto.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Produto produto = await this._servico.Save(this.SelectedProduto); + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " PRODUTO \"", produto.get_Nome(), "\""), produto.get_Id(), new TipoTela?(10), string.Format("PRODUTO \"{0}\", ID: {1}", produto.get_Nome(), produto.get_Id())); + if (!this.Produtos.Any((Produto x) => x.get_Id() == produto.get_Id())) + { + this.Produtos.Add(produto); + } + else + { + DomainBase.Copy(this.Produtos.First((Produto x) => x.get_Id() == produto.get_Id()), produto); + } + if (!this.ProdutosFiltrados.Any((Produto x) => x.get_Id() == produto.get_Id())) + { + this.ProdutosFiltrados.Add(produto); + } + else + { + DomainBase.Copy(this.ProdutosFiltrados.First((Produto x) => x.get_Id() == produto.get_Id()), produto); + } + this.ProdutosFiltrados = new ObservableCollection(this.ProdutosFiltrados); + List produtos = this.Produtos; + Recursos.Produtos = ( + from x in produtos + orderby x.get_Nome() + select x).ToList(); + this.WorkOnSelectedProduto(produto, false); + base.Alterar(false); + base.ToggleSnackBar("PRODUTO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(10); + await this.SelecionaProdutos(); + base.Loading(false); + } + + public void SelecionaProduto(Produto produto) + { + this.SelectedProduto = produto; + } + + private async Task SelecionaProdutos() + { + base.Loading(true); + List produtos = await (new BaseServico()).BuscarProdutosAsync(); + ProdutoViewModel list = this; + List produtos1 = produtos; + IOrderedEnumerable ativo = + from x in produtos1 + orderby x.get_Ativo() descending + select x; + list.Produtos = ativo.ThenBy((Produto x) => x.get_Nome()).ToList(); + this.ProdutosFiltrados = new ObservableCollection(this.Produtos); + this.SelectedProduto = this.ProdutosFiltrados.FirstOrDefault(); + List produtos2 = this.Produtos; + Recursos.Produtos = ( + from x in produtos2 + orderby x.get_Nome() + select x).ToList(); + base.Loading(false); + base.Loading(true); + } + + public async Task>> Validate() + { + List> keyValuePairs; + List> keyValuePairs1; + if (!string.IsNullOrWhiteSpace(this.SelectedProduto.get_Nome())) + { + keyValuePairs1 = new List>(); + bool flag = true; + List produtos = await (new BaseServico()).BuscarProduto(this.SelectedProduto.get_Nome()); + if (produtos.Count > 0) + { + produtos.ForEach((Produto x) => { + if (x.get_Id() == this.SelectedProduto.get_Id()) + { + return; + } + if (x.get_Nome() == this.SelectedProduto.get_Nome()) + { + flag = false; + } + }); + } + if (!flag) + { + keyValuePairs1.Add(new KeyValuePair("Nome", "UM PRODUTO COM O MESMO NOME JÁ EXISTE.")); + } + keyValuePairs = keyValuePairs1; + } + else + { + keyValuePairs = new List>(); + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private void WorkOnSelectedProduto(Produto value, bool registrar = true) + { + long? nullable; + this.CancelProduto = (value == null || value.get_Id() == 0 ? this.CancelProduto : (Produto)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 10) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU PRODUTO \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(10), string.Format("ID PRODUTO: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 10; + Produto selectedProduto = this.SelectedProduto; + if (selectedProduto != null) + { + nullable = new long?(selectedProduto.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedProduto = this.ProdutosFiltrados.FirstOrDefault((Produto x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloDocumentosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloDocumentosViewModel.cs new file mode 100644 index 0000000..027f344 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloDocumentosViewModel.cs @@ -0,0 +1,399 @@ +using Assinador.Infrastructure.Helpers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ProtocoloDocumentosViewModel : BaseSegurosViewModel + { + private Cliente _selectedCliente = new Cliente(); + + private ObservableCollection _apolicesFiltradas = new ObservableCollection(); + + private ObservableCollection _apolicesAdicionadas = new ObservableCollection(); + + private FiltroStatusDocumento _selectedStatus; + + public ObservableCollection ApolicesAdicionadas + { + get + { + return this._apolicesAdicionadas; + } + set + { + this._apolicesAdicionadas = value; + base.OnPropertyChanged("ApolicesAdicionadas"); + } + } + + public ObservableCollection ApolicesFiltradas + { + get + { + return this._apolicesFiltradas; + } + set + { + this._apolicesFiltradas = value; + base.OnPropertyChanged("ApolicesFiltradas"); + } + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this._selectedCliente = value; + if (this.SelectedCliente != null && this.SelectedCliente.get_Id() != 0 && (this.LastAccessId != this.SelectedCliente.get_Id() || this.LastAccessTela != 59)) + { + this.SelecionarDocumentos(); + this.LastAccessId = this.SelectedCliente.get_Id(); + this.LastAccessTela = 59; + } + base.OnPropertyChanged("SelectedCliente"); + } + } + + public FiltroStatusDocumento SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + this.SelectedCliente = this.SelectedCliente; + this.SelecionarDocumentos(); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public ProtocoloDocumentosViewModel() + { + } + + public async void AdicionarEtiqueta(Documento documento) + { + ObservableCollection apolicesAdicionadas = this.ApolicesAdicionadas; + ProtocoloEtiqueta protocoloEtiquetum = new ProtocoloEtiqueta(); + ProtocoloEtiqueta protocoloEtiquetum1 = protocoloEtiquetum; + Documento documento1 = await (new ApoliceServico()).BuscarApoliceAsync(documento.get_Id(), false, false); + protocoloEtiquetum1.Documento = documento1; + protocoloEtiquetum.Tipo = 1; + apolicesAdicionadas.Add(protocoloEtiquetum); + apolicesAdicionadas = null; + protocoloEtiquetum1 = null; + protocoloEtiquetum = null; + ProtocoloDocumentosViewModel observableCollection = this; + ObservableCollection apolicesAdicionadas1 = this.ApolicesAdicionadas; + observableCollection.ApolicesAdicionadas = new ObservableCollection( + from x in apolicesAdicionadas1 + orderby x.Documento.get_Id() + select x); + } + + public async void AdicionarEtiquetaCliente() + { + if (this.SelectedCliente != null && this.SelectedCliente.get_Id() != 0) + { + bool flag = this.ApolicesAdicionadas.Any((ProtocoloEtiqueta x) => { + if (x.Documento.get_Controle().get_Cliente().get_Id() != this.SelectedCliente.get_Id()) + { + return false; + } + return x.Tipo == 1; + }); + if (flag) + { + flag = !await base.ShowMessage("JÁ EXISTE UMA ETIQUETA ADICIONADA PARA O CLIENTE SELECIONADO, DESEJA ADICIONAR NOVAMENTE?", "SIM", "NÃO", false); + } + if (!flag) + { + ObservableCollection apolicesAdicionadas = this.ApolicesAdicionadas; + ProtocoloEtiqueta protocoloEtiquetum = new ProtocoloEtiqueta(); + Documento documento = new Documento(); + Controle controle = new Controle(); + controle.set_Cliente(this.SelectedCliente); + documento.set_Controle(controle); + protocoloEtiquetum.Documento = documento; + protocoloEtiquetum.Tipo = 1; + apolicesAdicionadas.Add(protocoloEtiquetum); + ProtocoloDocumentosViewModel observableCollection = this; + ObservableCollection apolicesAdicionadas1 = this.ApolicesAdicionadas; + IOrderedEnumerable tipo = + from x in apolicesAdicionadas1 + orderby x.Tipo + select x; + observableCollection.ApolicesAdicionadas = new ObservableCollection(tipo.ThenBy((ProtocoloEtiqueta x) => x.Documento.get_Controle().get_Cliente().get_Id())); + } + } + } + + public async void AdicionarEtiquetaCorretora() + { + ProtocoloDocumentosViewModel protocoloDocumentosViewModel = this; + ClienteEndereco clienteEndereco = new ClienteEndereco(); + clienteEndereco.set_Endereco(Recursos.Empresa.get_Endereco()); + clienteEndereco.set_Bairro(Recursos.Empresa.get_Bairro()); + clienteEndereco.set_Numero(Recursos.Empresa.get_Numero()); + clienteEndereco.set_Complemento(Recursos.Empresa.get_Complemento()); + clienteEndereco.set_Cidade(Recursos.Empresa.get_Cidade()); + clienteEndereco.set_Estado(Recursos.Empresa.get_Estado()); + clienteEndereco.set_Cep(Recursos.Empresa.get_Cep()); + ObservableCollection observableCollection = new ObservableCollection() + { + clienteEndereco + }; + ObservableCollection apolicesAdicionadas = protocoloDocumentosViewModel.ApolicesAdicionadas; + ProtocoloEtiqueta protocoloEtiquetum = new ProtocoloEtiqueta(); + Documento documento = new Documento(); + Controle controle = new Controle(); + Cliente cliente = new Cliente(); + cliente.set_Nome(Recursos.Empresa.get_Nome()); + cliente.set_Id((long)-1); + cliente.set_Enderecos(observableCollection); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + protocoloEtiquetum.Documento = documento; + protocoloEtiquetum.Tipo = 1; + apolicesAdicionadas.Add(protocoloEtiquetum); + ProtocoloDocumentosViewModel observableCollection1 = protocoloDocumentosViewModel; + ObservableCollection apolicesAdicionadas1 = protocoloDocumentosViewModel.ApolicesAdicionadas; + IOrderedEnumerable tipo = + from x in apolicesAdicionadas1 + orderby x.Tipo + select x; + observableCollection1.ApolicesAdicionadas = new ObservableCollection(tipo.ThenBy((ProtocoloEtiqueta x) => x.Documento.get_Controle().get_Cliente().get_Id())); + } + + public async void AdicionarProtocolo(Documento documento) + { + bool flag = this.ApolicesAdicionadas.Any((ProtocoloEtiqueta x) => { + if (x.Documento.get_Id() != documento.get_Id()) + { + return false; + } + return x.Tipo == 0; + }); + if (flag) + { + flag = !await base.ShowMessage("JÁ EXISTE UM PROTOCOLO ADICIONADO PARA O DOCUMENTO SELECIONADO, DESEJA ADICIONAR NOVAMENTE?", "SIM", "NÃO", false); + } + if (!flag) + { + ObservableCollection apolicesAdicionadas = this.ApolicesAdicionadas; + ProtocoloEtiqueta protocoloEtiquetum = new ProtocoloEtiqueta(); + ProtocoloEtiqueta protocoloEtiquetum1 = protocoloEtiquetum; + Documento documento1 = await (new ApoliceServico()).BuscarApoliceAsync(documento.get_Id(), false, false); + protocoloEtiquetum1.Documento = documento1; + protocoloEtiquetum.Tipo = 0; + apolicesAdicionadas.Add(protocoloEtiquetum); + apolicesAdicionadas = null; + protocoloEtiquetum1 = null; + protocoloEtiquetum = null; + ProtocoloDocumentosViewModel observableCollection = this; + ObservableCollection apolicesAdicionadas1 = this.ApolicesAdicionadas; + observableCollection.ApolicesAdicionadas = new ObservableCollection( + from x in apolicesAdicionadas1 + orderby x.Documento.get_Id() + select x); + } + } + + public async void Imprimir(TipoProtocoloEtiqueta tipo) + { + if (this.ApolicesAdicionadas.Count != 0) + { + TipoProtocoloEtiqueta tipoProtocoloEtiquetum = tipo; + if (tipoProtocoloEtiquetum == null) + { + ObservableCollection apolicesAdicionadas = this.ApolicesAdicionadas; + if (!apolicesAdicionadas.All((ProtocoloEtiqueta x) => x.Tipo != 0)) + { + ObservableCollection observableCollection = this.ApolicesAdicionadas; + if (observableCollection.Any((ProtocoloEtiqueta x) => x.Tipo == 0)) + { + ProtocoloDocumentosViewModel protocoloDocumentosViewModel = this; + ObservableCollection apolicesAdicionadas1 = this.ApolicesAdicionadas; + IEnumerable protocoloEtiquetas = + from x in apolicesAdicionadas1 + where x.Tipo == 0 + select x; + List documentos = await protocoloDocumentosViewModel.ShowProtocoloDialog(( + from x in protocoloEtiquetas + select x.Documento).ToList()); + if (documentos != null) + { + bool flag = await base.ShowMessage(string.Concat("DESEJA EMITIR DOIS PROTOCOLOS POR PÁGINA?", Environment.NewLine, "A QUANTIDADE DE INFORMÃÇÕES PODE IMPEDIR QUE ESSA FUNÇÃO FUNCIONE CORRETAMENTE"), "SIM", "NÃO", false); + this.PrepararProtocolo(documentos, flag); + documentos = null; + } + else + { + return; + } + } + } + else + { + await base.ShowMessage(string.Concat("NECESSÁRIO ADICIONAR DOCUMENTOS PARA EMISSÃO DE ", Functions.GetDescription(tipo)), "OK", "", false); + return; + } + } + else if (tipoProtocoloEtiquetum == 1) + { + ObservableCollection observableCollection1 = this.ApolicesAdicionadas; + if (!observableCollection1.All((ProtocoloEtiqueta x) => x.Tipo != 1)) + { + ObservableCollection apolicesAdicionadas2 = this.ApolicesAdicionadas; + if (apolicesAdicionadas2.Any((ProtocoloEtiqueta x) => { + if (x.Tipo != 1) + { + return false; + } + return x.Documento.get_Id() == (long)0; + })) + { + ObservableCollection observableCollection2 = this.ApolicesAdicionadas; + if (observableCollection2.Any((ProtocoloEtiqueta x) => { + if (x.Tipo != 1) + { + return false; + } + return x.Documento.get_Id() != (long)0; + })) + { + await base.ShowMessage("COMO EXISTEM ETIQUETAS DE CLIENTES E DOCUMENTOS,\nPRIMEIRO CONFIGURE AS DE SOMENTE CLIENTE.\nDEPOIS DE GERAR AS ETIQUETAS DE CLIENTE, CONFIGURAR AS DE DOCUMENTOS", "OK", "", false); + } + ObservableCollection apolicesAdicionadas3 = this.ApolicesAdicionadas; + IEnumerable protocoloEtiquetas1 = apolicesAdicionadas3.Where((ProtocoloEtiqueta x) => { + if (x.Tipo != 1) + { + return false; + } + return x.Documento.get_Id() == (long)0; + }); + (new HosterWindow(new EtiquetaView(( + from x in protocoloEtiquetas1 + select x.Documento).ToList(), true), "ETIQUETAS", new double?((double)900), new double?((double)600), false)).Show(); + } + ObservableCollection observableCollection3 = this.ApolicesAdicionadas; + if (observableCollection3.Any((ProtocoloEtiqueta x) => { + if (x.Tipo != 1) + { + return false; + } + return x.Documento.get_Id() != (long)0; + })) + { + ObservableCollection apolicesAdicionadas4 = this.ApolicesAdicionadas; + IEnumerable protocoloEtiquetas2 = apolicesAdicionadas4.Where((ProtocoloEtiqueta x) => { + if (x.Tipo != 1) + { + return false; + } + return x.Documento.get_Id() != (long)0; + }); + (new HosterWindow(new EtiquetaView(( + from x in protocoloEtiquetas2 + select x.Documento).ToList(), false), "ETIQUETAS", new double?((double)900), new double?((double)600), false)).Show(); + } + } + else + { + await base.ShowMessage(string.Concat("NECESSÁRIO ADICIONAR DOCUMENTOS PARA EMISSÃO DE ", Functions.GetDescription(tipo)), "OK", "", false); + return; + } + } + } + else + { + await base.ShowMessage(string.Concat("NECESSÁRIO ADICIONAR DOCUMENTOS PARA EMISSÃO DE ", Functions.GetDescription(tipo)), "OK", "", false); + } + } + + public async void PrepararProtocolo(List documentos, bool doisPorPagina) + { + if (await base.ShowMessage("DESEJA EMITIR O CHECKLIST?", "SIM", "NÃO", false)) + { + await base.EmitirCheckList(documentos); + } + if (documentos != null) + { + List documentos1 = documentos; + List> list = ( + from x in documentos1 + select new Tuple(x.get_Id(), x.get_ObsProtocolo())).ToList>(); + await base.EmitirProtocolos(list, doisPorPagina, documentos); + } + } + + public void Remover(ProtocoloEtiqueta documento) + { + this.ApolicesAdicionadas.Remove(documento); + this.SelecionarDocumentos(); + } + + public async void SelecionarDocumentos() + { + long? nullable; + object obj; + object nome; + long num; + base.Loading(true); + if (this.SelectedCliente != null) + { + this.ApolicesFiltradas = await (new ApoliceServico()).BuscarApolicesComissao(this.SelectedCliente.get_Id(), this.SelectedStatus); + ProtocoloDocumentosViewModel protocoloDocumentosViewModel = this; + obj = (this.SelectedStatus == 4 ? "TODOS OS DOCUMENTOS" : string.Concat("OS ", Functions.GetDescription(this.SelectedStatus))); + Cliente selectedCliente = this.SelectedCliente; + if (selectedCliente != null) + { + nome = selectedCliente.get_Nome(); + } + else + { + nome = null; + } + Cliente cliente = this.SelectedCliente; + if (cliente != null) + { + nullable = new long?(cliente.get_Id()); + } + else + { + nullable = null; + } + string str = string.Format("CONSULTOU {0} DO CLIENTE {1} ({2})", obj, nome, nullable); + num = (this.SelectedCliente == null ? (long)0 : this.SelectedCliente.get_Id()); + protocoloDocumentosViewModel.RegistrarAcao(str, num, new TipoTela?(59), null); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloEtiqueta.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloEtiqueta.cs new file mode 100644 index 0000000..7e46a89 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ProtocoloEtiqueta.cs @@ -0,0 +1,26 @@ +using Gestor.Model.Common; +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ProtocoloEtiqueta + { + public Gestor.Model.Domain.Seguros.Documento Documento + { + get; + set; + } + + public TipoProtocoloEtiqueta Tipo + { + get; + set; + } + + public ProtocoloEtiqueta() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/QualificacaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/QualificacaoViewModel.cs new file mode 100644 index 0000000..c259f93 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/QualificacaoViewModel.cs @@ -0,0 +1,122 @@ +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class QualificacaoViewModel : BaseSegurosViewModel + { + private readonly QualificacaoServico _servico; + + private Qualificacao _selectedQualificacao; + + public Qualificacao CancelQualificacao; + + public Qualificacao SelectedQualificacao + { + get + { + return this._selectedQualificacao; + } + set + { + if (value == null || value.get_Id() == 0) + { + Qualificacao qualificacao = new Qualificacao(); + qualificacao.set_Liquido1(decimal.Zero); + qualificacao.set_Liquido2(new decimal(1000)); + qualificacao.set_Liquido3(new decimal(5000)); + qualificacao.set_Comissao1(new decimal(10)); + qualificacao.set_Comissao2(new decimal(15)); + qualificacao.set_Comissao3(new decimal(20)); + qualificacao.set_Resultado1(new decimal(100)); + qualificacao.set_Resultado2(new decimal(200)); + qualificacao.set_Resultado3(new decimal(300)); + qualificacao.set_Id((long)1); + value = qualificacao; + } + this._selectedQualificacao = value; + base.VerificarEnables(new long?(value.get_Id())); + base.OnPropertyChanged("SelectedQualificacao"); + } + } + + public QualificacaoViewModel() + { + this._servico = new QualificacaoServico(); + this.Seleciona(); + } + + public void CancelarAlteracao() + { + base.Loading(true); + if (this.SelectedQualificacao.get_Id() != 0) + { + this.SelectedQualificacao = this.CancelQualificacao; + } + else + { + this.SelectedQualificacao = null; + base.Alterar(false); + base.EnableMenu = false; + base.Loading(false); + } + base.Alterar(false); + base.Loading(false); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + if (await this._servico.BuscarQualificacaoAsync().get_Id() == 0) + { + this.SelectedQualificacao.set_Id((long)0); + } + List> keyValuePairs1 = this.SelectedQualificacao.Validate(); + if (keyValuePairs1.Count <= 0) + { + this.SelectedQualificacao = await this._servico.Save(this.SelectedQualificacao); + if (this._servico.Sucesso) + { + base.RegistrarAcao("ALTEROU QUALIFICAÇÃO", (long)0, new TipoTela?(48), null); + base.Alterar(false); + base.ToggleSnackBar("QUALIFICACAO SALVA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(48); + await this.SelecionaQualificacao(); + base.Loading(false); + } + + private async Task SelecionaQualificacao() + { + base.Loading(true); + this.SelectedQualificacao = await this._servico.BuscarQualificacaoAsync(); + base.RegistrarAcao("ACESSOU QUALIFICAÇÃO", (long)0, new TipoTela?(48), null); + base.Loading(false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/RamoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/RamoViewModel.cs new file mode 100644 index 0000000..09ab1ea --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/RamoViewModel.cs @@ -0,0 +1,332 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class RamoViewModel : BaseSegurosViewModel + { + private readonly RamoServico _servico; + + private Ramo _selectedRamo = new Ramo(); + + private decimal _iof; + + private ObservableCollection _ramosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private List _coberturas = new List(); + + private ObservableCollection _coberturasFiltradas = new ObservableCollection(); + + public Ramo CancelRamo; + + public List Coberturas + { + get + { + return this._coberturas; + } + set + { + this._coberturas = value; + base.OnPropertyChanged("Coberturas"); + } + } + + public ObservableCollection CoberturasFiltradas + { + get + { + return this._coberturasFiltradas; + } + set + { + this._coberturasFiltradas = value; + base.OnPropertyChanged("CoberturasFiltradas"); + } + } + + public decimal Iof + { + get + { + return this._iof; + } + set + { + this._iof = value; + base.OnPropertyChanged("Iof"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public List Ramos + { + get; + set; + } + + public ObservableCollection RamosFiltrados + { + get + { + return this._ramosFiltrados; + } + set + { + this._ramosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("RamosFiltrados"); + } + } + + public Ramo SelectedRamo + { + get + { + return this._selectedRamo; + } + set + { + long? nullable; + this._selectedRamo = value; + this.WorkOnSelectedRamo(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedRamo"); + } + } + + public RamoViewModel() + { + this._servico = new RamoServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelRamo != null && this.Ramos.Any((Ramo x) => x.get_Id() == this.CancelRamo.get_Id())) + { + DomainBase.Copy(this.Ramos.First((Ramo x) => x.get_Id() == this.CancelRamo.get_Id()), this.CancelRamo); + if (this.RamosFiltrados.Count <= 0 || !this.RamosFiltrados.Any((Ramo x) => x.get_Id() == this.CancelRamo.get_Id())) + { + this.RamosFiltrados.Add(this.CancelRamo); + } + else + { + DomainBase.Copy(this.RamosFiltrados.First((Ramo x) => x.get_Id() == this.CancelRamo.get_Id()), this.CancelRamo); + } + this.RamosFiltrados = new ObservableCollection(this.RamosFiltrados); + this.SelectedRamo = this.RamosFiltrados.First((Ramo x) => x.get_Id() == this.CancelRamo.get_Id()); + } + base.Alterar(false); + } + + internal async Task> Filtrar(string value) + { + List ramos = await Task.Run>(() => this.FiltrarRamo(value)); + return ramos; + } + + internal async Task> FiltrarCobertura(string value) + { + List coberturaPadraos = await Task.Run>(() => this.FiltrarCoberturaRamo(value)); + return coberturaPadraos; + } + + public List FiltrarCoberturaRamo(string filter) + { + this.CoberturasFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Coberturas) : new ObservableCollection( + from x in this.Coberturas + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + select x)); + return this.CoberturasFiltradas.ToList(); + } + + public List FiltrarRamo(string filter) + { + this.RamosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Ramos) : new ObservableCollection( + from x in this.Ramos + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + return this.RamosFiltrados.ToList(); + } + + public async void Incluir(Ramo ramo) + { + ramo.set_Ativo(true); + await this._servico.Insert(ramo); + if (this._servico.Sucesso) + { + await this.SelecionaRamos(ramo); + } + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + this.SelectedRamo.set_Iof(this.Iof); + List> keyValuePairs1 = this.SelectedRamo.Validate(); + if (keyValuePairs1.Count <= 0) + { + Ramo selectedRamo = this.SelectedRamo; + selectedRamo.set_Iof(selectedRamo.get_Iof() * new decimal(100)); + str = (this.SelectedRamo.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Ramo ramo = await this._servico.Save(this.SelectedRamo, this.Coberturas); + Ramo ramo1 = ramo; + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " RAMO \"", ramo1.get_Nome(), "\""), ramo1.get_Id(), new TipoTela?(12), string.Format("RAMO \"{0}\", ID: {1}", ramo1.get_Nome(), ramo1.get_Id())); + if (!this.Ramos.Any((Ramo x) => x.get_Id() == ramo1.get_Id())) + { + this.Ramos.Add(ramo1); + } + else + { + DomainBase.Copy(this.Ramos.First((Ramo x) => x.get_Id() == ramo1.get_Id()), ramo1); + } + if (!this.RamosFiltrados.Any((Ramo x) => x.get_Id() == ramo1.get_Id())) + { + this.RamosFiltrados.Add(ramo1); + } + else + { + DomainBase.Copy(this.RamosFiltrados.First((Ramo x) => x.get_Id() == ramo1.get_Id()), ramo1); + } + this.RamosFiltrados = new ObservableCollection(this.RamosFiltrados); + Recursos.Ramos = this.Ramos; + await RamoViewModel.SelecionaCoberturas(); + this.WorkOnSelectedRamo(ramo1, false); + base.Alterar(false); + base.ToggleSnackBar("RAMO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + public async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(12); + await this.SelecionaRamos(null); + base.Loading(false); + } + + private static async Task SelecionaCoberturas() + { + Recursos.Coberturas = await (new BaseServico()).BuscaCoberturas(); + } + + public void SelecionaRamo(Ramo ramo) + { + this.SelectedRamo = ramo; + } + + private async Task SelecionaRamos(Ramo ramo = null) + { + Ramo ramo1; + base.Loading(true); + await RamoViewModel.SelecionaCoberturas(); + List ramos = await (new BaseServico()).BuscarRamosAsync(); + RamoViewModel list = this; + List ramos1 = ramos; + IOrderedEnumerable ativo = + from x in ramos1 + orderby x.get_Ativo() descending + select x; + list.Ramos = ativo.ThenBy((Ramo x) => x.get_Nome()).ToList(); + this.RamosFiltrados = new ObservableCollection(this.Ramos); + RamoViewModel ramoViewModel = this; + ramo1 = (ramo == null ? this.RamosFiltrados.First() : this.RamosFiltrados.FirstOrDefault((Ramo x) => x.get_Id() == ramo.get_Id())); + ramoViewModel.SelectedRamo = ramo1; + Recursos.Ramos = ramos; + base.Loading(false); + } + + private void WorkOnSelectedRamo(Ramo value, bool registrar = true) + { + long? nullable; + this.CancelRamo = (value == null || value.get_Id() == 0 ? this.CancelRamo : (Ramo)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 12) + { + return; + } + this.Coberturas = ( + from x in Recursos.Coberturas + where x.get_IdRamo() == value.get_Id() + orderby x.get_Padrao() descending, x.get_Descricao() + select x).ToList(); + this.CoberturasFiltradas = new ObservableCollection(this.Coberturas); + this.Iof = value.get_Iof() * new decimal(1, 0, 0, false, 2); + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU RAMO \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(12), string.Format("ID RAMO: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 12; + Ramo selectedRamo = this.SelectedRamo; + if (selectedRamo != null) + { + nullable = new long?(selectedRamo.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedRamo = this.RamosFiltrados.FirstOrDefault((Ramo x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/ReciboViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ReciboViewModel.cs new file mode 100644 index 0000000..e00947c --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/ReciboViewModel.cs @@ -0,0 +1,769 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Drawing; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class ReciboViewModel : BaseSegurosViewModel + { + private readonly ReciboServico _servico; + + public Recibo CancelRecibo; + + private Recibo _selectedRecibo = new Recibo(); + + private DateTime? _horaRecibo; + + private ObservableCollection _recibosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private Cliente _pagante; + + private Cliente _recebedor; + + public DateTime? HoraRecibo + { + get + { + return this._horaRecibo; + } + set + { + DateTime? nullable; + this._horaRecibo = value; + if (!value.HasValue) + { + return; + } + Recibo selectedRecibo = this.SelectedRecibo; + DateTime? dataRecibo = this.SelectedRecibo.get_DataRecibo(); + if (dataRecibo.HasValue) + { + dataRecibo = this.SelectedRecibo.get_DataRecibo(); + nullable = new DateTime?(DateTime.Parse(string.Format("{0:d} {1:T}", dataRecibo.Value, value))); + } + else + { + dataRecibo = null; + nullable = dataRecibo; + } + selectedRecibo.set_DataRecibo(nullable); + base.OnPropertyChanged("HoraRecibo"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Cliente Pagante + { + get + { + return this._pagante; + } + set + { + this._pagante = value; + this.WorkOnSelectedPagante(value); + base.OnPropertyChanged("Pagante"); + } + } + + public Cliente Recebedor + { + get + { + return this._recebedor; + } + set + { + this._recebedor = value; + this.WorkOnSelectedRecebedor(value); + base.OnPropertyChanged("Recebedor"); + } + } + + public List Recibos + { + get; + set; + } + + public ObservableCollection RecibosFiltrados + { + get + { + return this._recibosFiltrados; + } + set + { + this._recibosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("RecibosFiltrados"); + } + } + + public Recibo SelectedRecibo + { + get + { + return this._selectedRecibo; + } + set + { + long? nullable; + this._selectedRecibo = value; + this.WorkOnSelectedRecibo(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + if (!value.get_DataRecibo().HasValue) + { + value.set_DataRecibo(new DateTime?(DateTime.Now)); + } + if (value != null) + { + this.HoraRecibo = value.get_DataRecibo(); + } + base.OnPropertyChanged("SelectedRecibo"); + } + } + + public ReciboViewModel() + { + this._servico = new ReciboServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelRecibo == null || !this.Recibos.Any((Recibo x) => x.get_Id() == this.CancelRecibo.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Recibos.First((Recibo x) => x.get_Id() == this.CancelRecibo.get_Id()), this.CancelRecibo); + if (this.RecibosFiltrados.Count <= 0 || !this.RecibosFiltrados.Any((Recibo x) => x.get_Id() == this.CancelRecibo.get_Id())) + { + this.RecibosFiltrados.Add(this.CancelRecibo); + } + else + { + DomainBase.Copy(this.RecibosFiltrados.First((Recibo x) => x.get_Id() == this.CancelRecibo.get_Id()), this.CancelRecibo); + } + this.RecibosFiltrados = new ObservableCollection(this.RecibosFiltrados); + this.SelectedRecibo = this.RecibosFiltrados.First((Recibo x) => x.get_Id() == this.CancelRecibo.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + string description; + object obj; + if (this.SelectedRecibo != null && this.SelectedRecibo.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA REALMENTE EXCLUIR O RECIBO PERMANENTEMENTE?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedRecibo)) + { + ReciboViewModel reciboViewModel = this; + string str = string.Format("EXCLUIU RECIBO DE NÚMERO \"{0}\"", this.SelectedRecibo.get_Id()); + long id = this.SelectedRecibo.get_Id(); + TipoTela? nullable = new TipoTela?(42); + object[] valor = new object[9]; + if (this.SelectedRecibo.get_Tipo().HasValue) + { + TipoRecibo? tipo = this.SelectedRecibo.get_Tipo(); + description = ValidationHelper.GetDescription(tipo.Value); + if (description == null) + { + description = ""; + } + } + else + { + description = "-"; + } + valor[0] = description; + TipoPagamento? pagamento = this.SelectedRecibo.get_Pagamento(); + if (pagamento.HasValue) + { + obj = ValidationHelper.GetDescription(pagamento.GetValueOrDefault()); + } + else + { + obj = null; + } + valor[1] = obj; + valor[2] = this.SelectedRecibo.get_Valor(); + valor[3] = this.SelectedRecibo.get_DataRecibo(); + valor[4] = this.SelectedRecibo.get_Pagante(); + valor[5] = this.SelectedRecibo.get_DocumentoPagante(); + valor[6] = this.SelectedRecibo.get_Recebedor(); + valor[7] = this.SelectedRecibo.get_DocumentoRecebedor(); + valor[8] = this.SelectedRecibo.get_Referente(); + reciboViewModel.RegistrarAcao(str, id, nullable, string.Format("TIPO: {0}\nPAGAMENTO: {1}\nVALOR: {2:c}\nDATA RECIBO: {3:G}\nPAGANTE: {4}, {5}\nRECEBEDOR: {6}, {7}\nREFERENTE: \"{8}\"", valor)); + await this.SelecionaRecibo(); + base.Loading(false); + base.ToggleSnackBar("RECIBO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List recibos = await Task.Run>(() => this.FiltrarRecibo(value)); + return recibos; + } + + public List FiltrarRecibo(string filter) + { + this.RecibosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Recibos) : new ObservableCollection(this.Recibos.Where((Recibo x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Pagante().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter))) + { + return true; + } + return ValidationHelper.RemoveDiacritics(x.get_Recebedor()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)); + }))); + return this.RecibosFiltrados.ToList(); + } + + private static string GetImage(byte[] bytes, string extensao) + { + string str; + try + { + Image image = Image.FromStream(new MemoryStream(bytes)); + string str1 = (extensao.ToUpper().Contains("JPG") ? string.Concat("data:image/jpeg;base64,", Convert.ToBase64String(bytes, Base64FormattingOptions.None)) : string.Concat("data:image/png;base64,", Convert.ToBase64String(bytes, Base64FormattingOptions.None))); + string[] strArrays = new string[] { ""; + str = string.Concat(strArrays); + } + catch (Exception exception) + { + str = ""; + } + return str; + } + + public void Incluir() + { + this.SelectedRecibo = new Recibo(); + base.Alterar(true); + } + + private bool IsImage(string extensao) + { + if (extensao == null) + { + return false; + } + if (extensao.ToLower().Contains("jpg")) + { + return true; + } + if (extensao.ToLower().Contains("jpeg")) + { + return true; + } + if (extensao.ToLower().Contains("png")) + { + return true; + } + return false; + } + + public async void Print() + { + bool referente; + byte[] arquivo; + string str; + string str1; + string str2; + string upper; + string str3; + string str4; + string upper1; + string description; + object obj; + string extensao; + string extensao1; + long? nullable; + string bd; + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital; + string image; + string str5; + Recibo selectedRecibo = this.SelectedRecibo; + if (selectedRecibo != null) + { + referente = selectedRecibo.get_Referente(); + } + else + { + referente = false; + } + if (referente && this.SelectedRecibo.get_Recebedor() != null) + { + arquivoDigital = null; + List indiceArquivoDigitals = await this.ArquivoDigitalServico.BuscarPorTipo(13, Recursos.Empresa.get_Id()); + if (indiceArquivoDigitals != null) + { + List indiceArquivoDigitals1 = indiceArquivoDigitals; + if (indiceArquivoDigitals1.Any((IndiceArquivoDigital x) => x.get_Descricao() == "LOGO")) + { + List indiceArquivoDigitals2 = indiceArquivoDigitals; + IndiceArquivoDigital indiceArquivoDigital = indiceArquivoDigitals2.FirstOrDefault((IndiceArquivoDigital x) => x.get_Descricao() == "LOGO"); + if (indiceArquivoDigital != null) + { + nullable = new long?(indiceArquivoDigital.get_IdArquivoDigital()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + List indiceArquivoDigitals3 = indiceArquivoDigitals; + IndiceArquivoDigital indiceArquivoDigital1 = indiceArquivoDigitals3.FirstOrDefault((IndiceArquivoDigital x) => x.get_Descricao() == "LOGO"); + if (indiceArquivoDigital1 != null) + { + bd = indiceArquivoDigital1.get_Bd(); + } + else + { + bd = null; + } + string str6 = bd; + if (nullable1.HasValue) + { + arquivoDigital = await this.ArquivoDigitalServico.BuscarPorId(nullable1.Value, str6); + } + } + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital1 = arquivoDigital; + if (arquivoDigital1 != null) + { + arquivo = arquivoDigital1.get_Arquivo(); + } + else + { + arquivo = null; + } + byte[] numArray = arquivo; + image = ""; + if (numArray != null && numArray.Length != 0) + { + ReciboViewModel reciboViewModel = this; + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital2 = arquivoDigital; + if (arquivoDigital2 != null) + { + extensao = arquivoDigital2.get_Extensao(); + } + else + { + extensao = null; + } + if (reciboViewModel.IsImage(extensao)) + { + byte[] numArray1 = numArray; + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital3 = arquivoDigital; + if (arquivoDigital3 != null) + { + extensao1 = arquivoDigital3.get_Extensao(); + } + else + { + extensao1 = null; + } + image = ReciboViewModel.GetImage(numArray1, extensao1); + } + } + string longDatePattern = (new CultureInfo("pt-PT", false)).DateTimeFormat.LongDatePattern; + DateTime? dataRecibo = this.SelectedRecibo.get_DataRecibo(); + if (dataRecibo.HasValue) + { + DateTime valueOrDefault = dataRecibo.GetValueOrDefault(); + str = valueOrDefault.ToString(longDatePattern, new CultureInfo("pt-PT")); + } + else + { + str = null; + } + str5 = str; + bool flag = await base.ShowMessage("DESEJA IMPRIMIR DUAS VIAS DO RECIBO?", "SIM", "NÃO", false); + int num = (!flag ? 1 : 2); + flag = !string.IsNullOrEmpty(image); + if (flag) + { + flag = await base.ShowMessage("DESEJA IMPRIMIR O LOGO DA CORRETORA NO RECIBO?\nPARA ADICIONAR UM LOGO, É NECESSÁRIO COLOCÁ-LO NO ARQUIVO\nDIGITAL NA TELA DE EMPRESA E FILIAIS COM DESCRIÇÃO \"LOGO\"", "SIM", "NÃO", false); + } + bool flag1 = flag; + string str7 = "RECIBO"; + for (int i = 0; i < num; i++) + { + if (!flag1) + { + str7 = string.Concat(str7, "
"); + } + else + { + str7 = string.Concat(str7, "
", image, "
"); + str7 = string.Concat(str7, "
"); + } + str7 = string.Concat(str7, string.Format("
N° {0}

", this.SelectedRecibo.get_Id())); + str7 = string.Concat(str7, "R E C I B O

"); + if (this.SelectedRecibo.get_Tipo().GetValueOrDefault() != 1) + { + str1 = (this.SelectedRecibo.get_DocumentoPagante() == null || this.SelectedRecibo.get_DocumentoPagante().Clear().Length < 12 ? "EU" : "A"); + string str8 = str1; + str2 = (this.SelectedRecibo.get_DocumentoPagante() == null || this.SelectedRecibo.get_DocumentoPagante().Clear().Length < 12 ? "CPF" : "CNPJ"); + string str9 = str2; + string str10 = (str8 == "EU" ? "O" : "A"); + string str11 = (str8 == "EU" ? "PAGUEI" : "PAGOU"); + object[] pagante = new object[] { str8, this.SelectedRecibo.get_Pagante(), str10, str9, this.SelectedRecibo.get_DocumentoPagante(), str10, str11, this.SelectedRecibo.get_DataRecibo(), this.SelectedRecibo.get_Valor(), ValidationHelper.GetDescription(this.SelectedRecibo.get_Pagamento()), this.SelectedRecibo.get_Recebedor(), this.SelectedRecibo.get_DocumentoRecebedor(), this.SelectedRecibo.get_Referente().ToUpper() }; + str7 = string.Concat(str7, string.Format("PELO PRESENTE, {0}, {1}, INSCRIT{2} NO {3} SOB Nº {4}, DECLAR{5} QUE {6}, NA DATA DE HOJE, {7:dd/MM/yyyy HH:mm}, O VALOR DE R$ {8:0.00} POR MEIO DE {9}, PARA {10}, INSCRITO NO CPF/CNPJ SOB Nº {11}, REFERENTE À(AO) {12}. DANDO-LHE POR ESTE RECIBO A DEVIDA QUITAÇÃO.
", pagante)); + string[] cidade = new string[] { str7, "
", Recursos.Empresa.get_Cidade(), ", ", null, null }; + string str12 = str5; + if (str12 != null) + { + upper = str12.ToUpper(); + } + else + { + upper = null; + } + cidade[4] = upper; + cidade[5] = ".

"; + str7 = string.Concat(cidade); + string[] recebedor = new string[] { str7, "_________________________________
ASSINATURA ", this.SelectedRecibo.get_Recebedor(), "
", this.SelectedRecibo.get_DocumentoRecebedor() }; + str7 = string.Concat(recebedor); + } + else + { + str3 = (this.SelectedRecibo.get_DocumentoRecebedor() == null || this.SelectedRecibo.get_DocumentoRecebedor().Clear().Length < 12 ? "EU" : "A"); + string str13 = str3; + str4 = (this.SelectedRecibo.get_DocumentoRecebedor() == null || this.SelectedRecibo.get_DocumentoRecebedor().Clear().Length < 12 ? "CPF" : "CNPJ"); + string str14 = str4; + string str15 = (str13 == "EU" ? "O" : "A"); + string str16 = (str13 == "EU" ? "RECEBI" : "RECEBEU"); + object[] objArray = new object[] { str13, this.SelectedRecibo.get_Recebedor(), str15, str14, this.SelectedRecibo.get_DocumentoRecebedor(), str15, str16, this.SelectedRecibo.get_DataRecibo(), this.SelectedRecibo.get_Valor(), ValidationHelper.GetDescription(this.SelectedRecibo.get_Pagamento()), this.SelectedRecibo.get_Pagante(), this.SelectedRecibo.get_DocumentoPagante(), this.SelectedRecibo.get_Referente().ToUpper() }; + str7 = string.Concat(str7, string.Format("PELO PRESENTE, {0}, {1}, INSCRIT{2} NO {3} SOB Nº {4}, DECLAR{5} QUE {6}, NA DATA DE HOJE, {7:dd/MM/yyyy HH:mm}, O VALOR DE R$ {8:0.00} POR MEIO DE {9}, DE {10}, INSCRITO NO CPF/CNPJ SOB Nº {11}, REFERENTE À(AO) {12}. DANDO-LHE POR ESTE RECIBO A DEVIDA QUITAÇÃO.
", objArray)); + string[] strArrays = new string[] { str7, "", Recursos.Empresa.get_Cidade(), ", ", null, null }; + string str17 = str5; + if (str17 != null) + { + upper1 = str17.ToUpper(); + } + else + { + upper1 = null; + } + strArrays[4] = upper1; + strArrays[5] = ".

"; + str7 = string.Concat(strArrays); + string[] recebedor1 = new string[] { str7, "_________________________________
ASSINATURA ", this.SelectedRecibo.get_Recebedor(), "
", this.SelectedRecibo.get_DocumentoRecebedor() }; + str7 = string.Concat(recebedor1); + } + str7 = string.Concat(str7, "
"); + } + str7 = string.Concat(str7, " "); + string tempPath = Path.GetTempPath(); + string str18 = string.Format("{0}_{1:ddMMyyyyhhmmss}.html", tempPath, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str18, true, Encoding.UTF8); + streamWriter.Write(str7); + streamWriter.Close(); + Process.Start(str18); + ReciboViewModel reciboViewModel1 = this; + string str19 = string.Format("IMPRIMIU O RECIBO DE NÚMERO \"{0}\"", this.SelectedRecibo.get_Id()); + long id = this.SelectedRecibo.get_Id(); + TipoTela? nullable2 = new TipoTela?(42); + object[] valor = new object[9]; + if (this.SelectedRecibo.get_Tipo().HasValue) + { + TipoRecibo? tipo = this.SelectedRecibo.get_Tipo(); + description = ValidationHelper.GetDescription(tipo.Value); + if (description == null) + { + description = ""; + } + } + else + { + description = "-"; + } + valor[0] = description; + TipoPagamento? pagamento = this.SelectedRecibo.get_Pagamento(); + if (pagamento.HasValue) + { + obj = ValidationHelper.GetDescription(pagamento.GetValueOrDefault()); + } + else + { + obj = null; + } + valor[1] = obj; + valor[2] = this.SelectedRecibo.get_Valor(); + valor[3] = this.SelectedRecibo.get_DataRecibo(); + valor[4] = this.SelectedRecibo.get_Pagante(); + valor[5] = this.SelectedRecibo.get_DocumentoPagante(); + valor[6] = this.SelectedRecibo.get_Recebedor(); + valor[7] = this.SelectedRecibo.get_DocumentoRecebedor(); + valor[8] = this.SelectedRecibo.get_Referente(); + reciboViewModel1.RegistrarAcao(str19, id, nullable2, string.Format("TIPO: {0}\nPAGAMENTO: {1}\nVALOR: {2:c}\nDATA RECIBO: {3:G}\nPAGANTE: {4}, {5}\nRECEBEDOR: {6}, {7}\nREFERENTE: \"{8}\"", valor)); + } + arquivoDigital = null; + image = null; + str5 = null; + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string description; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedRecibo.Validate(); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedRecibo.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Recibo recibo = await this._servico.Save(this.SelectedRecibo); + if (this._servico.Sucesso) + { + ReciboViewModel reciboViewModel = this; + string str2 = string.Format("{0} RECIBO DE NÚMERO \"{1}\"", str1, recibo.get_Id()); + long id = recibo.get_Id(); + TipoTela? nullable = new TipoTela?(42); + object[] valor = new object[9]; + if (recibo.get_Tipo().HasValue) + { + TipoRecibo? tipo = recibo.get_Tipo(); + description = ValidationHelper.GetDescription(tipo.Value); + if (description == null) + { + description = ""; + } + } + else + { + description = "-"; + } + valor[0] = description; + TipoPagamento? pagamento = recibo.get_Pagamento(); + if (pagamento.HasValue) + { + obj = ValidationHelper.GetDescription(pagamento.GetValueOrDefault()); + } + else + { + obj = null; + } + valor[1] = obj; + valor[2] = recibo.get_Valor(); + valor[3] = recibo.get_DataRecibo(); + valor[4] = recibo.get_Pagante(); + valor[5] = recibo.get_DocumentoPagante(); + valor[6] = recibo.get_Recebedor(); + valor[7] = recibo.get_DocumentoRecebedor(); + valor[8] = recibo.get_Referente(); + reciboViewModel.RegistrarAcao(str2, id, nullable, string.Format("TIPO: {0}\nPAGAMENTO: {1}\nVALOR: {2:c}\nDATA RECIBO: {3:G}\nPAGANTE: {4}, {5}\nRECEBEDOR: {6}, {7}\nREFERENTE: \"{8}\"", valor)); + if (!this.Recibos.Any((Recibo x) => x.get_Id() == recibo.get_Id())) + { + this.Recibos.Add(recibo); + } + else + { + DomainBase.Copy(this.Recibos.First((Recibo x) => x.get_Id() == recibo.get_Id()), recibo); + } + if (!this.RecibosFiltrados.Any((Recibo x) => x.get_Id() == recibo.get_Id())) + { + this.RecibosFiltrados.Add(recibo); + } + else + { + DomainBase.Copy(this.RecibosFiltrados.First((Recibo x) => x.get_Id() == recibo.get_Id()), recibo); + } + this.RecibosFiltrados = new ObservableCollection(this.RecibosFiltrados); + this.WorkOnSelectedRecibo(recibo, false); + base.Alterar(false); + base.ToggleSnackBar("RECIBO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(42); + await this.SelecionaRecibo(); + base.Loading(false); + } + + private async Task SelecionaRecibo() + { + base.Loading(true); + List recibos = await this._servico.BuscarRecibos(); + this.Recibos = recibos.ToList(); + this.RecibosFiltrados = new ObservableCollection(this.Recibos); + if (this.RecibosFiltrados.Count <= 0) + { + this.SelectedRecibo = new Recibo(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelectedRecibo = this.RecibosFiltrados.First(); + } + base.Loading(false); + } + + private void WorkOnSelectedPagante(Cliente value) + { + if (value != null) + { + this.SelectedRecibo.set_Pagante(Regex.Replace(value.get_NomeSocial(), "\\-\\s\\d.*", "").Trim()); + this.SelectedRecibo.set_DocumentoPagante(value.get_Documento()); + this.SelectedRecibo = this.SelectedRecibo; + } + } + + private void WorkOnSelectedRecebedor(Cliente value) + { + if (value != null) + { + this.SelectedRecibo.set_Recebedor(Regex.Replace(value.get_NomeSocial(), "\\-\\s\\d.*", "").Trim()); + this.SelectedRecibo.set_DocumentoRecebedor(value.get_Documento()); + this.SelectedRecibo = this.SelectedRecibo; + } + } + + private void WorkOnSelectedRecibo(Recibo value, bool registrar = true) + { + long? nullable; + string description; + object obj; + this.CancelRecibo = (value == null || value.get_Id() == 0 ? this.CancelRecibo : (Recibo)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 42) + { + return; + } + if (registrar) + { + string str = string.Format("ACESSOU RECIBO DE NÚMERO \"{0}\"", value.get_Id()); + long id = value.get_Id(); + TipoTela? nullable1 = new TipoTela?(42); + object[] valor = new object[9]; + if (value.get_Tipo().HasValue) + { + TipoRecibo? tipo = value.get_Tipo(); + description = ValidationHelper.GetDescription(tipo.Value) ?? ""; + } + else + { + description = "-"; + } + valor[0] = description; + TipoPagamento? pagamento = value.get_Pagamento(); + if (pagamento.HasValue) + { + obj = ValidationHelper.GetDescription(pagamento.GetValueOrDefault()); + } + else + { + obj = null; + } + valor[1] = obj; + valor[2] = value.get_Valor(); + valor[3] = value.get_DataRecibo(); + valor[4] = value.get_Pagante(); + valor[5] = value.get_DocumentoPagante(); + valor[6] = value.get_Recebedor(); + valor[7] = value.get_DocumentoRecebedor(); + valor[8] = value.get_Referente(); + base.RegistrarAcao(str, id, nullable1, string.Format("TIPO: {0}\nPAGAMENTO: {1}\nVALOR: {2:c}\nDATA RECIBO: {3:G}\nPAGANTE: {4}, {5}\nRECEBEDOR: {6}, {7}\nREFERENTE: \"{8}\"", valor)); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 42; + Recibo selectedRecibo = this.SelectedRecibo; + if (selectedRecibo != null) + { + nullable = new long?(selectedRecibo.get_Id()); + } + else + { + nullable = null; + } + long? nullable2 = nullable; + long num = value.get_Id(); + if (nullable2.GetValueOrDefault() != num | !nullable2.HasValue) + { + this.SelectedRecibo = this.RecibosFiltrados.FirstOrDefault((Recibo x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/SeguradoraViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/SeguradoraViewModel.cs new file mode 100644 index 0000000..f7daced --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/SeguradoraViewModel.cs @@ -0,0 +1,621 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class SeguradoraViewModel : BaseSegurosViewModel + { + private readonly SeguradoraServico _servico; + + private bool _apelido; + + private Seguradora _selectedSeguradora; + + private SeguradoraEndereco _selectedEndereco = new SeguradoraEndereco(); + + private ObservableCollection _contatos = new ObservableCollection(); + + private ObservableCollection _enderecos = new ObservableCollection(); + + private SeguradoraContato _selectedTelefone = new SeguradoraContato(); + + private Visibility _tipoTelefone; + + private Visibility _telefone; + + private Visibility _prefixo; + + private ObservableCollection _configFiltrados = new ObservableCollection(); + + public Seguradora CancelSeguradora; + + public ObservableCollection CancelEnderecos; + + public ObservableCollection CancelContatos; + + private ObservableCollection _seguradorasFiltradas = new ObservableCollection(); + + private bool _isExpanded; + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public List Config + { + get; + set; + } + + public ObservableCollection ConfigFiltrados + { + get + { + return this._configFiltrados; + } + set + { + this._configFiltrados = value; + base.OnPropertyChanged("ConfigFiltrados"); + } + } + + public ObservableCollection Contatos + { + get + { + return this._contatos; + } + set + { + this._contatos = value; + base.OnPropertyChanged("Contatos"); + } + } + + public ObservableCollection Enderecos + { + get + { + return this._enderecos; + } + set + { + this._enderecos = value; + base.OnPropertyChanged("Enderecos"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public string Pesquisa + { + get; + set; + } + + public Visibility PrefixoVisibility + { + get + { + return this._prefixo; + } + set + { + if (this.SelectedTelefone.get_TipoContato() != 2) + { + this._prefixo = Visibility.Visible; + } + else + { + this._prefixo = Visibility.Collapsed; + } + base.OnPropertyChanged("PrefixoVisibility"); + } + } + + public List Seguradoras + { + get; + set; + } + + public ObservableCollection SeguradorasFiltradas + { + get + { + return this._seguradorasFiltradas; + } + set + { + this._seguradorasFiltradas = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("SeguradorasFiltradas"); + } + } + + public SeguradoraEndereco SelectedEndereco + { + get + { + return this._selectedEndereco; + } + set + { + this._selectedEndereco = value; + base.OnPropertyChanged("SelectedEndereco"); + } + } + + public Seguradora SelectedSeguradora + { + get + { + return this._selectedSeguradora; + } + set + { + long? nullable; + this._selectedSeguradora = value; + this.WorkOnSelectedSeguradora(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedSeguradora"); + } + } + + public SeguradoraContato SelectedTelefone + { + get + { + return this._selectedTelefone; + } + set + { + this._selectedTelefone = value; + base.OnPropertyChanged("SelectedTelefone"); + } + } + + public Visibility TelefoneVisibility + { + get + { + return this._telefone; + } + set + { + if (this.SelectedTelefone.get_TipoContato() != 2) + { + this._telefone = Visibility.Visible; + } + else + { + this._telefone = Visibility.Collapsed; + } + base.OnPropertyChanged("TelefoneVisibility"); + } + } + + public Visibility TipoTelefoneVisibility + { + get + { + return this._tipoTelefone; + } + set + { + if (this.SelectedTelefone.get_TipoContato() != 2) + { + this._tipoTelefone = Visibility.Visible; + } + else + { + this._tipoTelefone = Visibility.Collapsed; + } + base.OnPropertyChanged("TipoTelefoneVisibility"); + } + } + + public decimal Tolerancia + { + get; + set; + } + + public SeguradoraViewModel() + { + this._servico = new SeguradoraServico(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelSeguradora != null && this.Seguradoras.Any((Seguradora x) => x.get_Id() == this.CancelSeguradora.get_Id())) + { + DomainBase.Copy(this.Seguradoras.First((Seguradora x) => x.get_Id() == this.CancelSeguradora.get_Id()), this.CancelSeguradora); + if (this.SeguradorasFiltradas.Count <= 0 || !this.SeguradorasFiltradas.Any((Seguradora x) => x.get_Id() == this.CancelSeguradora.get_Id())) + { + this.SeguradorasFiltradas.Add(this.CancelSeguradora); + } + else + { + DomainBase.Copy(this.SeguradorasFiltradas.First((Seguradora x) => x.get_Id() == this.CancelSeguradora.get_Id()), this.CancelSeguradora); + } + this.SeguradorasFiltradas = new ObservableCollection(this.SeguradorasFiltradas); + this.ConfigFiltrados = new ObservableCollection(this.ConfigFiltrados); + this.SelectedSeguradora = this.SeguradorasFiltradas.First((Seguradora x) => x.get_Id() == this.CancelSeguradora.get_Id()); + this.Enderecos = this.CancelEnderecos; + this.Contatos = this.CancelContatos; + } + base.Alterar(false); + } + + public void Clonar() + { + this.CancelSeguradora = (Seguradora)this.SelectedSeguradora.Clone(); + this.CancelEnderecos = new ObservableCollection(this.Enderecos); + this.CancelContatos = new ObservableCollection(this.Contatos); + } + + public void ExcluirEndereco(SeguradoraEndereco endereco) + { + this.Enderecos.Remove(endereco); + } + + public void ExcluirTelefone(SeguradoraContato contato) + { + this.Contatos.Remove(contato); + } + + internal async Task> Filtrar(string value) + { + List seguradoras = await Task.Run>(() => this.FiltrarSeguradora(value)); + return seguradoras; + } + + internal async Task> FiltrarConfig(string value) + { + List configExtratoImports = await Task.Run>(() => this.FiltrarDescricao(value)); + return configExtratoImports; + } + + public List FiltrarDescricao(string filter) + { + this.ConfigFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Config) : new ObservableCollection( + from x in this.Config + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Descricao() + select x)); + return this.ConfigFiltrados.ToList(); + } + + public List FiltrarSeguradora(string filter) + { + this.Pesquisa = filter; + this.SeguradorasFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Seguradoras) : new ObservableCollection(this.Seguradoras.Where((Seguradora x) => { + if (ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter))) + { + return true; + } + return ValidationHelper.RemoveDiacritics(x.get_NomeSocial()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)); + }).OrderByDescending((Seguradora x) => x.get_Ativo()).ThenBy((Seguradora x) => x.get_Nome()))); + return this.SeguradorasFiltradas.ToList(); + } + + public async void Incluir(Seguradora seguradora) + { + seguradora.set_Tolerancia(new decimal?(2)); + seguradora.set_ToleranciaPremio(new decimal?(2)); + seguradora.set_Ativo(true); + await this._servico.Insert(seguradora); + if (this._servico.Sucesso) + { + await this.SelecionaSeguradoras(seguradora); + } + } + + public void IncluirEndereco() + { + if (this.SelectedSeguradora == null) + { + return; + } + if (this.Enderecos == null) + { + this.Enderecos = new ObservableCollection(); + } + SeguradoraEndereco seguradoraEndereco = new SeguradoraEndereco(); + seguradoraEndereco.set_Empresa(Recursos.Empresa); + seguradoraEndereco.set_Seguradora(this.SelectedSeguradora); + seguradoraEndereco.set_Tipo(4); + SeguradoraEndereco seguradoraEndereco1 = seguradoraEndereco; + this.Enderecos.Add(seguradoraEndereco1); + this.SelectedEndereco = seguradoraEndereco1; + } + + public void IncluirTelefone() + { + if (this.SelectedSeguradora == null) + { + return; + } + if (this.Contatos == null) + { + this.Contatos = new ObservableCollection(); + } + SeguradoraContato seguradoraContato = new SeguradoraContato(); + seguradoraContato.set_Empresa(Recursos.Empresa); + seguradoraContato.set_Seguradora(this.SelectedSeguradora); + seguradoraContato.set_Tipo(new TipoTelefone?(2)); + SeguradoraContato seguradoraContato1 = seguradoraContato; + this.Contatos.Add(seguradoraContato1); + this.SelectedTelefone = seguradoraContato1; + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + List> keyValuePairs1 = this.SelectedSeguradora.Validate(); + keyValuePairs1.AddRange(this.Validate(this.Contatos.ToList())); + keyValuePairs1.AddRange(this.Validate(this.Enderecos.ToList())); + if (keyValuePairs1.Count <= 0) + { + Seguradora selectedSeguradora = this.SelectedSeguradora; + ObservableCollection contatos = this.Contatos; + selectedSeguradora.set_Contatos(contatos.Where((SeguradoraContato x) => { + if (!string.IsNullOrEmpty(x.get_NomeContato())) + { + return true; + } + return x.get_TipoContato() == 1; + }).ToList()); + Seguradora seguradora = this.SelectedSeguradora; + ObservableCollection enderecos = this.Enderecos; + seguradora.set_Enderecos(( + from x in enderecos + where !string.IsNullOrEmpty(x.get_Bairro()) + select x).ToList()); + Seguradora seguradora1 = await this._servico.Save(this.SelectedSeguradora, this.Config, false); + Seguradora seguradora2 = seguradora1; + str = (this.SelectedSeguradora.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + string str1 = str; + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str1, " SEGURADORA \"", seguradora2.get_Nome(), "\""), seguradora2.get_Id(), new TipoTela?(13), string.Format("SEGURADORA \"{0}\", ID: {1}", seguradora2.get_Nome(), seguradora2.get_Id())); + await this.SelecionaSeguradoras(null); + this.FiltrarSeguradora(this.Pesquisa); + SeguradoraViewModel seguradoraViewModel = this; + Seguradora seguradora3 = this.SeguradorasFiltradas.FirstOrDefault((Seguradora x) => x.get_Id() == seguradora2.get_Id()); + if (seguradora3 == null) + { + seguradora3 = this.SeguradorasFiltradas.FirstOrDefault(); + } + seguradoraViewModel.SelectedSeguradora = seguradora3; + base.Alterar(false); + base.ToggleSnackBar("SEGURADORA SALVA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(13); + await this.SelecionaSeguradoras(null); + base.Loading(false); + } + + public async void SelecionaSeguradora(Seguradora seguradora) + { + base.Loading(true); + this.SelectedSeguradora = seguradora; + this.Contatos = await this._servico.BuscarContatos(this.SelectedSeguradora.get_Id()); + this.Enderecos = await this._servico.BuscarEnderecos(this.SelectedSeguradora.get_Id()); + this.Config = await this._servico.BuscarConfig(this.SelectedSeguradora.get_Id()); + this.ConfigFiltrados = new ObservableCollection(this.Config); + base.Loading(false); + } + + private async Task SelecionaSeguradoras(Seguradora seguradora = null) + { + base.Loading(true); + List seguradoras = await (new BaseServico()).BuscarSeguradorasAsync(); + SeguradoraViewModel list = this; + List seguradoras1 = seguradoras; + IOrderedEnumerable ativo = + from x in seguradoras1 + orderby x.get_Ativo() descending + select x; + list.Seguradoras = ativo.ThenBy((Seguradora x) => x.get_Nome()).ToList(); + this.SeguradorasFiltradas = new ObservableCollection(this.Seguradoras); + if (seguradora != null) + { + this.SelecionaSeguradora(this.SeguradorasFiltradas.FirstOrDefault((Seguradora x) => x.get_Id() == seguradora.get_Id())); + } + else if (this.SeguradorasFiltradas.Count <= 0) + { + this.SelectedSeguradora = new Seguradora(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaSeguradora(this.SeguradorasFiltradas.First()); + } + Recursos.Seguradoras = seguradoras; + base.Loading(false); + } + + public List> Validate(List endereco) + { + List> keyValuePairs = new List>(); + if (endereco != null) + { + endereco.ForEach((SeguradoraEndereco x) => keyValuePairs.AddRange(x.Validate())); + } + return keyValuePairs.Distinct>().ToList>(); + } + + public List> Validate(List contatos) + { + List list; + List> keyValuePairs = new List>(); + if (contatos != null) + { + contatos.ForEach((SeguradoraContato x) => keyValuePairs.AddRange(x.Validate())); + } + if (contatos != null) + { + list = ( + from x in contatos + where x.get_TipoContato() == 1 + select x).ToList(); + } + else + { + list = null; + } + List seguradoraContatos = list; + if (seguradoraContatos == null) + { + return keyValuePairs; + } + if (seguradoraContatos.Count > 4) + { + keyValuePairs.Add(new KeyValuePair("ASSISTÊNCIAS 24 HORAS", "NÃO É POSSÍVEL ADICIONAR MAIS QUE 4 NUMEROS DE ASSISTÊNCIA 24 HORAS")); + } + return keyValuePairs.Distinct>().ToList>(); + } + + private void WorkOnSelectedSeguradora(Seguradora value, bool registrar = true) + { + decimal? nullable; + bool contatos; + bool enderecos; + long? nullable1; + decimal? tolerancia; + this.CancelSeguradora = (value == null || value.get_Id() == 0 ? this.CancelSeguradora : (Seguradora)value.Clone()); + this.CancelEnderecos = new ObservableCollection(this.Enderecos); + this.CancelContatos = new ObservableCollection(this.Contatos); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 13) + { + return; + } + Seguradora selectedSeguradora = this.SelectedSeguradora; + if (selectedSeguradora != null) + { + contatos = selectedSeguradora.get_Contatos(); + } + else + { + contatos = false; + } + if (contatos) + { + this.Contatos = new ObservableCollection(this.SelectedSeguradora.get_Contatos()); + } + Seguradora seguradora = this.SelectedSeguradora; + if (seguradora != null) + { + enderecos = seguradora.get_Enderecos(); + } + else + { + enderecos = false; + } + if (enderecos) + { + this.Enderecos = new ObservableCollection(this.SelectedSeguradora.get_Enderecos()); + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU SEGURADORA \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(13), string.Format("ID SEGURADORA: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 13; + Seguradora selectedSeguradora1 = this.SelectedSeguradora; + if (selectedSeguradora1 != null) + { + nullable1 = new long?(selectedSeguradora1.get_Id()); + } + else + { + nullable1 = null; + } + long? nullable2 = nullable1; + long id = value.get_Id(); + if (nullable2.GetValueOrDefault() != id | !nullable2.HasValue) + { + this.SelectedSeguradora = this.SeguradorasFiltradas.FirstOrDefault((Seguradora x) => x.get_Id() == value.get_Id()); + } + Seguradora seguradora1 = this.SelectedSeguradora; + if (seguradora1 != null) + { + tolerancia = seguradora1.get_Tolerancia(); + } + else + { + nullable = null; + tolerancia = nullable; + } + nullable = tolerancia; + this.Tolerancia = nullable.GetValueOrDefault(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/SocioViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/SocioViewModel.cs new file mode 100644 index 0000000..d946d89 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/SocioViewModel.cs @@ -0,0 +1,358 @@ +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class SocioViewModel : BaseSegurosViewModel + { + private readonly SocioServico _servico; + + public Socio CancelSocio; + + private ObservableCollection _empresas = new ObservableCollection(); + + private Empresa _selectedEmpresa; + + private Socio _selectedSocio = new Socio(); + + private ObservableCollection _sociosFiltradas = new ObservableCollection(); + + private bool _isExpanded; + + private bool _isLoading; + + public ObservableCollection Empresas + { + get + { + return this._empresas; + } + set + { + this._empresas = value; + base.OnPropertyChanged("Empresas"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public bool IsLoading + { + get + { + return this._isLoading; + } + set + { + this._isLoading = value; + base.OnPropertyChanged("IsLoading"); + } + } + + public Empresa SelectedEmpresa + { + get + { + return this._selectedEmpresa; + } + set + { + this._selectedEmpresa = value; + this.WorkOnSelectedEmpresa(value); + base.OnPropertyChanged("SelectedEmpresa"); + } + } + + public Socio SelectedSocio + { + get + { + return this._selectedSocio; + } + set + { + long? nullable; + this._selectedSocio = value; + this.WorkOnSelectedSocio(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedSocio"); + } + } + + public List Socios + { + get; + set; + } + + public ObservableCollection SociosFiltradas + { + get + { + return this._sociosFiltradas; + } + set + { + this._sociosFiltradas = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("SociosFiltradas"); + } + } + + public SocioViewModel() + { + this._servico = new SocioServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelSocio == null || !this.Socios.Any((Socio x) => x.get_Id() == this.CancelSocio.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Socios.First((Socio x) => x.get_Id() == this.CancelSocio.get_Id()), this.CancelSocio); + if (this.SociosFiltradas.Count <= 0 || !this.SociosFiltradas.Any((Socio x) => x.get_Id() == this.CancelSocio.get_Id())) + { + this.SociosFiltradas.Add(this.CancelSocio); + } + else + { + DomainBase.Copy(this.SociosFiltradas.First((Socio x) => x.get_Id() == this.CancelSocio.get_Id()), this.CancelSocio); + } + this.SociosFiltradas = new ObservableCollection(this.SociosFiltradas); + this.SelectedSocio = this.SociosFiltradas.First((Socio x) => x.get_Id() == this.CancelSocio.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + Socio socio; + if (this.SelectedSocio != null && this.SelectedSocio.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + this.IsLoading = true; + if (await this._servico.Delete(this.SelectedSocio)) + { + string str = string.Concat("EXCLUIU SÓCIO \"", this.SelectedSocio.get_Nome(), "\""); + long id = this.SelectedSocio.get_Id(); + TipoTela? nullable = new TipoTela?(19); + object[] objArray = new object[] { this.SelectedSocio.get_Id(), this.SelectedSocio.get_Prefixo(), this.SelectedSocio.get_Telefone(), this.SelectedSocio.get_Email() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nTELEFONE: ({1}) {2}\nE-MAIL: {3}", objArray)); + int num = this.SociosFiltradas.IndexOf(this.SelectedSocio); + this.Socios.Remove(this.SelectedSocio); + this.SociosFiltradas.Remove(this.SelectedSocio); + this.SociosFiltradas = new ObservableCollection(this.SociosFiltradas); + if (this.SociosFiltradas.Count <= 0) + { + this.SelectedSocio = new Socio(); + base.Alterar(false); + } + else + { + SocioViewModel socioViewModel = this; + socio = (num < this.SociosFiltradas.Count ? this.SociosFiltradas.ElementAt(num) : this.SociosFiltradas.Last()); + socioViewModel.SelectedSocio = socio; + } + base.Loading(false); + this.IsLoading = false; + base.ToggleSnackBar("SÓCIO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + this.IsLoading = false; + } + } + } + } + + internal async Task> Filtrar(string value) + { + List socios = await Task.Run>(() => this.FiltrarSocio(value)); + return socios; + } + + public List FiltrarSocio(string filter) + { + this.SociosFiltradas = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Socios) : new ObservableCollection( + from x in this.Socios + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Nome() + select x)); + return this.SociosFiltradas.ToList(); + } + + public void Incluir() + { + Socio socio = new Socio(); + socio.set_IdEmpresa(this.SelectedEmpresa.get_Id()); + this.SelectedSocio = socio; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + List> keyValuePairs1 = this.SelectedSocio.Validate(); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedSocio.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Socio socio = await this._servico.Save(this.SelectedSocio); + if (this._servico.Sucesso) + { + string str2 = string.Concat(str1, " SÓCIO \"", socio.get_Nome(), "\""); + long id = socio.get_Id(); + TipoTela? nullable = new TipoTela?(19); + object[] objArray = new object[] { socio.get_Id(), socio.get_Prefixo(), socio.get_Telefone(), socio.get_Email() }; + base.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nTELEFONE: ({1}) {2}\nE-MAIL: {3}", objArray)); + if (!this.Socios.Any((Socio x) => x.get_Id() == socio.get_Id())) + { + this.Socios.Add(socio); + } + else + { + DomainBase.Copy(this.Socios.First((Socio x) => x.get_Id() == socio.get_Id()), socio); + } + if (!this.SociosFiltradas.Any((Socio x) => x.get_Id() == socio.get_Id())) + { + this.SociosFiltradas.Add(socio); + } + else + { + DomainBase.Copy(this.SociosFiltradas.First((Socio x) => x.get_Id() == socio.get_Id()), socio); + } + this.SociosFiltradas = new ObservableCollection(this.SociosFiltradas); + this.WorkOnSelectedSocio(socio, false); + base.Alterar(false); + base.ToggleSnackBar("SÓCIO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(19); + this.Empresas = new ObservableCollection(await (new EmpresaServico()).BuscarEmpresas()); + base.Loading(false); + this.SelectedEmpresa = this.Empresas.FirstOrDefault(); + } + + private async Task SelecionaSocios(long? id) + { + this.Socios = null; + this.SociosFiltradas = null; + if (id.HasValue) + { + long? nullable = id; + long num = (long)0; + if (!(nullable.GetValueOrDefault() == num & nullable.HasValue)) + { + base.Loading(true); + List socios = await (new BaseServico()).BuscarSociosAsync(id.Value); + SocioViewModel list = this; + List socios1 = socios; + list.Socios = ( + from x in socios1 + orderby x.get_Nome() + select x).ToList(); + this.SociosFiltradas = new ObservableCollection(this.Socios); + this.SelectedSocio = this.SociosFiltradas.FirstOrDefault(); + base.Loading(false); + return; + } + } + } + + private async void WorkOnSelectedEmpresa(Empresa value) + { + if (value != null && value.get_Id() != 0) + { + await this.SelecionaSocios(new long?(value.get_Id())); + } + } + + private void WorkOnSelectedSocio(Socio value, bool registrar = true) + { + long? nullable; + this.CancelSocio = (value == null || value.get_Id() == 0 ? this.CancelSocio : (Socio)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 19) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU SÓCIO \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(19), string.Format("ID: {0}\nTELEFONE: ({1}) {2}\nE-MAIL: {3}", new object[] { value.get_Id(), value.get_Prefixo(), value.get_Telefone(), value.get_Email() })); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 19; + Socio selectedSocio = this.SelectedSocio; + if (selectedSocio != null) + { + nullable = new long?(selectedSocio.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedSocio = this.SociosFiltradas.FirstOrDefault((Socio x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusProspeccaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusProspeccaoViewModel.cs new file mode 100644 index 0000000..4643cd1 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusProspeccaoViewModel.cs @@ -0,0 +1,326 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class StatusProspeccaoViewModel : BaseSegurosViewModel + { + private readonly StatusProspeccaoServico _servico; + + private readonly ProspeccaoServico _servicoProspeccao; + + public StatusDeProspeccao CancelStatusProspeccao; + + private ObservableCollection _statusProspeccaoFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private StatusDeProspeccao _selectedStatusProspeccao; + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public StatusDeProspeccao SelectedStatusProspeccao + { + get + { + return this._selectedStatusProspeccao; + } + set + { + long? nullable; + this._selectedStatusProspeccao = value; + this.WorkOnSelectedStatusProspeccao(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedStatusProspeccao"); + } + } + + public List StatusProspeccao + { + get; + set; + } + + public ObservableCollection StatusProspeccaoFiltrados + { + get + { + return this._statusProspeccaoFiltrados; + } + set + { + this._statusProspeccaoFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("StatusProspeccaoFiltrados"); + } + } + + public StatusProspeccaoViewModel() + { + this._servico = new StatusProspeccaoServico(); + this._servicoProspeccao = new ProspeccaoServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelStatusProspeccao == null || !this.StatusProspeccao.Any((StatusDeProspeccao x) => x.get_Id() == this.CancelStatusProspeccao.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.StatusProspeccao.First((StatusDeProspeccao x) => x.get_Id() == this.CancelStatusProspeccao.get_Id()), this.CancelStatusProspeccao); + if (this.StatusProspeccaoFiltrados.Count <= 0 || !this.StatusProspeccaoFiltrados.Any((StatusDeProspeccao x) => x.get_Id() == this.CancelStatusProspeccao.get_Id())) + { + this.StatusProspeccaoFiltrados.Add(this.CancelStatusProspeccao); + } + else + { + DomainBase.Copy(this.StatusProspeccaoFiltrados.First((StatusDeProspeccao x) => x.get_Id() == this.CancelStatusProspeccao.get_Id()), this.CancelStatusProspeccao); + } + this.StatusProspeccaoFiltrados = new ObservableCollection(this.StatusProspeccaoFiltrados); + this.SelectedStatusProspeccao = this.StatusProspeccaoFiltrados.First((StatusDeProspeccao x) => x.get_Id() == this.CancelStatusProspeccao.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + object obj; + if (this.SelectedStatusProspeccao != null && this.SelectedStatusProspeccao.get_Id() != 0) + { + if (await this._servicoProspeccao.BuscarProspeccoesPorStatus(this.SelectedStatusProspeccao).Count > 0) + { + await base.ShowMessage(string.Concat("O STATUS ", this.SelectedStatusProspeccao.get_Nome(), ", NÃO PODE SER EXCLUÍDO, POIS ESTÁ CADASTRADO EM UMA PROSPECÇÃO"), "OK", "", false); + } + else if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR O STATUS DE PROSPECÇÃO ", this.SelectedStatusProspeccao.get_Nome(), "?"), "SIM", "NÃO", false)) + { + base.Loading(true); + this.SelectedStatusProspeccao.set_Excluido(true); + this.SelectedStatusProspeccao.set_Ativo(false); + await this._servico.Save(this.SelectedStatusProspeccao); + if (this._servico.Sucesso) + { + StatusProspeccaoViewModel statusProspeccaoViewModel = this; + string str = string.Concat("EXCLUIU STATUS DE PROSPECÇÃO \"", this.SelectedStatusProspeccao.get_Nome(), "\""); + long id = this.SelectedStatusProspeccao.get_Id(); + TipoTela? nullable = new TipoTela?(57); + object id1 = this.SelectedStatusProspeccao.get_Id(); + obj = (this.SelectedStatusProspeccao.get_Ativo() ? "SIM" : "NÃO"); + statusProspeccaoViewModel.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", id1, obj, this.SelectedStatusProspeccao.get_Descricao())); + this.StatusProspeccao.Remove(this.SelectedStatusProspeccao); + this.StatusProspeccaoFiltrados.Remove(this.SelectedStatusProspeccao); + Recursos.StatusProspeccao.Remove(this.SelectedStatusProspeccao); + this.SelectedStatusProspeccao = this.StatusProspeccaoFiltrados.FirstOrDefault(); + await this.SelecionaStatusProspeccao(); + base.Loading(false); + base.ToggleSnackBar("STATUS DE PROSPECÇÃO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public async Task> Filtrar(string value) + { + List statusDeProspeccaos = await Task.Run>(() => this.FiltrarStatusProspeccao(value)); + return statusDeProspeccaos; + } + + public List FiltrarStatusProspeccao(string filter) + { + this.StatusProspeccaoFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.StatusProspeccao) : new ObservableCollection( + from x in this.StatusProspeccao + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + this.SelectedStatusProspeccao = this.StatusProspeccaoFiltrados.FirstOrDefault(); + return this.StatusProspeccaoFiltrados.ToList(); + } + + public void Incluir() + { + StatusDeProspeccao statusDeProspeccao = new StatusDeProspeccao(); + statusDeProspeccao.set_Ativo(true); + statusDeProspeccao.set_Excluido(false); + this.SelectedStatusProspeccao = statusDeProspeccao; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedStatusProspeccao.Validate(); + keyValuePairs1.AddRange(this.Validate()); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedStatusProspeccao.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + StatusDeProspeccao statusDeProspeccao = await this._servico.Save(this.SelectedStatusProspeccao); + if (this._servico.Sucesso) + { + StatusProspeccaoViewModel statusProspeccaoViewModel = this; + string str2 = string.Concat(str1, " STATUS DE PROSPECÇÃO \"", statusDeProspeccao.get_Nome(), "\""); + long id = statusDeProspeccao.get_Id(); + TipoTela? nullable = new TipoTela?(57); + object id1 = statusDeProspeccao.get_Id(); + obj = (statusDeProspeccao.get_Ativo() ? "SIM" : "NÃO"); + statusProspeccaoViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", id1, obj, statusDeProspeccao.get_Descricao())); + if (!this.StatusProspeccao.Any((StatusDeProspeccao x) => x.get_Id() == statusDeProspeccao.get_Id())) + { + this.StatusProspeccao.Add(statusDeProspeccao); + } + else + { + DomainBase.Copy(this.StatusProspeccao.First((StatusDeProspeccao x) => x.get_Id() == statusDeProspeccao.get_Id()), statusDeProspeccao); + } + if (!this.StatusProspeccaoFiltrados.Any((StatusDeProspeccao x) => x.get_Id() == statusDeProspeccao.get_Id())) + { + this.StatusProspeccaoFiltrados.Add(statusDeProspeccao); + } + else + { + DomainBase.Copy(this.StatusProspeccaoFiltrados.First((StatusDeProspeccao x) => x.get_Id() == statusDeProspeccao.get_Id()), statusDeProspeccao); + } + this.StatusProspeccaoFiltrados = new ObservableCollection(this.StatusProspeccaoFiltrados); + this.WorkOnSelectedStatusProspeccao(statusDeProspeccao, false); + Recursos.StatusProspeccao = this.StatusProspeccao; + base.Alterar(false); + base.ToggleSnackBar("STATUS DE PROSPECÇÃO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(57); + await this.SelecionaStatusProspeccao(); + base.Loading(false); + } + + private async Task SelecionaStatusProspeccao() + { + base.Loading(true); + List statusDeProspeccaos = await this._servico.BuscarProspeccoes(); + StatusProspeccaoViewModel list = this; + List statusDeProspeccaos1 = statusDeProspeccaos; + IEnumerable excluido = + from x in statusDeProspeccaos1 + where !x.get_Excluido() + select x; + IOrderedEnumerable ativo = + from x in excluido + orderby x.get_Ativo() descending + select x; + list.StatusProspeccao = ativo.ThenBy((StatusDeProspeccao x) => x.get_Nome()).ToList(); + this.StatusProspeccaoFiltrados = new ObservableCollection(this.StatusProspeccao); + this.SelectedStatusProspeccao = this.StatusProspeccaoFiltrados.FirstOrDefault(); + base.Loading(false); + } + + public List> Validate() + { + List> keyValuePairs = new List>(); + if (string.IsNullOrWhiteSpace(this.SelectedStatusProspeccao.get_Nome())) + { + return keyValuePairs; + } + if (this.StatusProspeccao.Any((StatusDeProspeccao x) => { + if (!x.get_Nome().Contains(this.SelectedStatusProspeccao.get_Nome())) + { + return false; + } + return x.get_Id() != this.SelectedStatusProspeccao.get_Id(); + })) + { + keyValuePairs.Add(new KeyValuePair("Nome", "UM STATUS DE PROSPECÇÃO COM O MESMO NOME JÁ EXISTE.")); + } + return keyValuePairs; + } + + private void WorkOnSelectedStatusProspeccao(StatusDeProspeccao value, bool registrar = true) + { + long? nullable; + this.CancelStatusProspeccao = (value == null || value.get_Id() == 0 ? this.CancelStatusProspeccao : (StatusDeProspeccao)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 57) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU STATUS DE PROSPECÇÃO \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(57), string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", value.get_Id(), (value.get_Ativo() ? "SIM" : "NÃO"), value.get_Descricao())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 57; + StatusDeProspeccao selectedStatusProspeccao = this.SelectedStatusProspeccao; + if (selectedStatusProspeccao != null) + { + nullable = new long?(selectedStatusProspeccao.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedStatusProspeccao = this.StatusProspeccaoFiltrados.FirstOrDefault((StatusDeProspeccao x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusViewModel.cs new file mode 100644 index 0000000..93b36c1 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/StatusViewModel.cs @@ -0,0 +1,367 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class StatusViewModel : BaseSegurosViewModel + { + private readonly StatusServico _servico; + + private Gestor.Model.Domain.Seguros.Status _selectedStatus; + + public Gestor.Model.Domain.Seguros.Status CancelStatus; + + private ObservableCollection _statusFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Gestor.Model.Domain.Seguros.Status SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + long? nullable; + this._selectedStatus = value; + this.WorkOnSelectedStatus(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public List Status + { + get; + set; + } + + public ObservableCollection StatusFiltrados + { + get + { + return this._statusFiltrados; + } + set + { + this._statusFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("StatusFiltrados"); + } + } + + public StatusViewModel() + { + this._servico = new StatusServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelStatus == null || !this.Status.Any((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == this.CancelStatus.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Status.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == this.CancelStatus.get_Id()), this.CancelStatus); + if (this.StatusFiltrados.Count <= 0 || !this.StatusFiltrados.Any((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == this.CancelStatus.get_Id())) + { + this.StatusFiltrados.Add(this.CancelStatus); + } + else + { + DomainBase.Copy(this.StatusFiltrados.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == this.CancelStatus.get_Id()), this.CancelStatus); + } + this.StatusFiltrados = new ObservableCollection(this.StatusFiltrados); + this.SelectedStatus = this.StatusFiltrados.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == this.CancelStatus.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + object obj; + Gestor.Model.Domain.Seguros.Status statu; + if (this.SelectedStatus != null && this.SelectedStatus.get_Id() != 0) + { + base.Loading(true); + List documentos = await (new BaseServico()).BuscarDocumentosPorStatus(this.SelectedStatus.get_Id()); + base.Loading(false); + if (documentos.Count > 0) + { + string str = "ESTIPULANTE NÃO PODE SER EXCLUÍDO POIS ESTÁ VINCULADO AOS SEGUINTES DOCUMENTOS:"; + foreach (Documento documento in documentos) + { + if (!string.IsNullOrWhiteSpace(documento.get_Apolice())) + { + object[] newLine = new object[] { Environment.NewLine, documentos.IndexOf(documento) + 1, documento.get_Proposta(), documento.get_Apolice() }; + str = string.Concat(str, string.Format("{0}DOCUMENTO {1} (NÚMERO DA PROPOSTA: {2}, NÚMERO DA APÓLICE: {3})", newLine)); + } + else + { + str = string.Concat(str, string.Format("{0}DOCUMENTO {1} (NÚMERO DA PROPOSTA: {2})", Environment.NewLine, documentos.IndexOf(documento) + 1, documento.get_Proposta())); + } + } + await base.ShowMessage(str, "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedStatus)) + { + StatusViewModel statusViewModel = this; + string str1 = string.Concat("EXCLUIU STATUS \"", this.SelectedStatus.get_Nome(), "\""); + long id = this.SelectedStatus.get_Id(); + TipoTela? nullable = new TipoTela?(11); + object id1 = this.SelectedStatus.get_Id(); + obj = (this.SelectedStatus.get_Ativo() ? "SIM" : "NÃO"); + statusViewModel.RegistrarAcao(str1, id, nullable, string.Format("ID: {0}\nATIVO: {1}", id1, obj)); + int num = this.StatusFiltrados.IndexOf(this.SelectedStatus); + this.Status.Remove(this.SelectedStatus); + this.StatusFiltrados.Remove(this.SelectedStatus); + this.StatusFiltrados = new ObservableCollection(this.StatusFiltrados); + if (this.StatusFiltrados.Count <= 0) + { + this.SelectedStatus = new Gestor.Model.Domain.Seguros.Status(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + StatusViewModel statusViewModel1 = this; + statu = (num < this.StatusFiltrados.Count ? this.StatusFiltrados.ElementAt(num) : this.StatusFiltrados.Last()); + statusViewModel1.SelectedStatus = statu; + } + base.Loading(false); + base.ToggleSnackBar("ESTIPULANTE EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List statuses = await Task.Run>(() => this.FiltrarStatus(value)); + return statuses; + } + + public List FiltrarStatus(string filter) + { + this.StatusFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Status) : new ObservableCollection( + from x in this.Status + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + return this.StatusFiltrados.ToList(); + } + + public void Incluir() + { + Gestor.Model.Domain.Seguros.Status statu = new Gestor.Model.Domain.Seguros.Status(); + statu.set_Ativo(true); + this.SelectedStatus = statu; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedStatus.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedStatus.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Gestor.Model.Domain.Seguros.Status statu = await this._servico.Save(this.SelectedStatus); + if (this._servico.Sucesso) + { + StatusViewModel statusViewModel = this; + string str2 = string.Concat(str1, " STATUS ID \"", statu.get_Nome(), "\""); + long id = statu.get_Id(); + TipoTela? nullable = new TipoTela?(11); + object id1 = statu.get_Id(); + obj = (statu.get_Ativo() ? "SIM" : "NÃO"); + statusViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nATIVO: {1}", id1, obj)); + if (!this.Status.Any((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == statu.get_Id())) + { + this.Status.Add(statu); + } + else + { + DomainBase.Copy(this.Status.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == statu.get_Id()), statu); + } + if (!this.StatusFiltrados.Any((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == statu.get_Id())) + { + this.StatusFiltrados.Add(statu); + } + else + { + DomainBase.Copy(this.StatusFiltrados.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == statu.get_Id()), statu); + } + this.StatusFiltrados = new ObservableCollection(this.StatusFiltrados); + this.WorkOnSelectedStatus(statu, false); + Recursos.Status = this.Status; + base.Alterar(false); + base.ToggleSnackBar("STATUS SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(11); + await this.SelecionaStatuses(); + base.Loading(false); + } + + public async void SelecionaStatus(Gestor.Model.Domain.Seguros.Status status) + { + Gestor.Model.Domain.Seguros.Status statu = await this._servico.BuscarStatusPorId(status.get_Id()); + DomainBase.Copy(this.StatusFiltrados.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == status.get_Id()), statu); + this.SelectedStatus = this.StatusFiltrados.First((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == status.get_Id()); + } + + private async Task SelecionaStatuses() + { + base.Loading(true); + List statuses = await (new BaseServico()).BuscarStatusAsync(); + StatusViewModel list = this; + List statuses1 = statuses; + IOrderedEnumerable ativo = + from x in statuses1 + orderby x.get_Ativo() descending + select x; + list.Status = ativo.ThenBy((Gestor.Model.Domain.Seguros.Status x) => x.get_Nome()).ToList(); + this.StatusFiltrados = new ObservableCollection(this.Status); + this.SelectedStatus = this.StatusFiltrados.FirstOrDefault(); + Recursos.Status = this.Status; + base.Loading(false); + } + + public async Task>> Validate() + { + List> keyValuePairs; + List> keyValuePairs1; + if (!string.IsNullOrWhiteSpace(this.SelectedStatus.get_Nome())) + { + keyValuePairs1 = new List>(); + bool flag = true; + List statuses = await (new BaseServico()).BuscarStatus(this.SelectedStatus.get_Nome()); + if (statuses.Count > 0) + { + statuses.ForEach((Gestor.Model.Domain.Seguros.Status x) => { + if (x.get_Id() == this.SelectedStatus.get_Id()) + { + return; + } + if (x.get_Nome() == this.SelectedStatus.get_Nome()) + { + flag = false; + } + }); + } + if (!flag) + { + keyValuePairs1.Add(new KeyValuePair("Nome", "UM STATUS COM O MESMO NOME JÁ EXISTE.")); + } + keyValuePairs = keyValuePairs1; + } + else + { + keyValuePairs = new List>(); + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private void WorkOnSelectedStatus(Gestor.Model.Domain.Seguros.Status value, bool registrar = true) + { + long? nullable; + this.CancelStatus = (value == null || value.get_Id() == 0 ? this.CancelStatus : (Gestor.Model.Domain.Seguros.Status)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 11) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU STATUS \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(11), string.Format("ID: {0}\nATIVO: {1}", value.get_Id(), (value.get_Ativo() ? "SIM" : "NÃO"))); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 11; + Gestor.Model.Domain.Seguros.Status selectedStatus = this.SelectedStatus; + if (selectedStatus != null) + { + nullable = new long?(selectedStatus.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedStatus = this.StatusFiltrados.FirstOrDefault((Gestor.Model.Domain.Seguros.Status x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoTarefaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoTarefaViewModel.cs new file mode 100644 index 0000000..07b51e1 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoTarefaViewModel.cs @@ -0,0 +1,325 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class TipoTarefaViewModel : BaseSegurosViewModel + { + private readonly TipoTarefaServico _servico; + + private readonly TarefaServico _servicoTarefa; + + public TipoDeTarefa CancelTipoTarefa; + + private ObservableCollection _tiposTarefaFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private TipoDeTarefa _selectedTipoTarefa; + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public TipoDeTarefa SelectedTipoTarefa + { + get + { + return this._selectedTipoTarefa; + } + set + { + long? nullable; + this._selectedTipoTarefa = value; + this.WorkOnSelectedTipoTarefa(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedTipoTarefa"); + } + } + + public List TiposTarefa + { + get; + set; + } + + public ObservableCollection TiposTarefaFiltrados + { + get + { + return this._tiposTarefaFiltrados; + } + set + { + this._tiposTarefaFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("TiposTarefaFiltrados"); + } + } + + public TipoTarefaViewModel() + { + this._servico = new TipoTarefaServico(); + this._servicoTarefa = new TarefaServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelTipoTarefa == null || !this.TiposTarefa.Any((TipoDeTarefa x) => x.get_Id() == this.CancelTipoTarefa.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.TiposTarefa.First((TipoDeTarefa x) => x.get_Id() == this.CancelTipoTarefa.get_Id()), this.CancelTipoTarefa); + if (this.TiposTarefaFiltrados.Count <= 0 || !this.TiposTarefaFiltrados.Any((TipoDeTarefa x) => x.get_Id() == this.CancelTipoTarefa.get_Id())) + { + this.TiposTarefaFiltrados.Add(this.CancelTipoTarefa); + } + else + { + DomainBase.Copy(this.TiposTarefaFiltrados.First((TipoDeTarefa x) => x.get_Id() == this.CancelTipoTarefa.get_Id()), this.CancelTipoTarefa); + } + this.TiposTarefaFiltrados = new ObservableCollection(this.TiposTarefaFiltrados); + this.SelectedTipoTarefa = this.TiposTarefaFiltrados.First((TipoDeTarefa x) => x.get_Id() == this.CancelTipoTarefa.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + object obj; + if (this.SelectedTipoTarefa != null && this.SelectedTipoTarefa.get_Id() != 0) + { + if (await this._servicoTarefa.BuscarTarefasPorTipo(this.SelectedTipoTarefa).Count > 0) + { + await base.ShowMessage(string.Concat("O TIPO ", this.SelectedTipoTarefa.get_Nome(), ", NÃO PODE SER EXCLUÍDO, POIS ESTÁ CADASTRADO EM UMA TAREFA"), "OK", "", false); + } + else if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR O TIPO DE TAREFA ", this.SelectedTipoTarefa.get_Nome(), "?"), "SIM", "NÃO", false)) + { + base.Loading(true); + this.SelectedTipoTarefa.set_Excluido(true); + this.SelectedTipoTarefa.set_Ativo(false); + await this._servico.Save(this.SelectedTipoTarefa); + if (this._servico.Sucesso) + { + TipoTarefaViewModel tipoTarefaViewModel = this; + string str = string.Concat("EXCLUIU TIPO DE TAREFA \"", this.SelectedTipoTarefa.get_Nome(), "\""); + long id = this.SelectedTipoTarefa.get_Id(); + TipoTela? nullable = new TipoTela?(52); + object id1 = this.SelectedTipoTarefa.get_Id(); + obj = (this.SelectedTipoTarefa.get_Ativo() ? "SIM" : "NÃO"); + tipoTarefaViewModel.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", id1, obj, this.SelectedTipoTarefa.get_Descricao())); + this.TiposTarefa.Remove(this.SelectedTipoTarefa); + this.TiposTarefaFiltrados.Remove(this.SelectedTipoTarefa); + Recursos.TiposTarefa.Remove(this.SelectedTipoTarefa); + this.SelectedTipoTarefa = this.TiposTarefaFiltrados.FirstOrDefault(); + await this.SelecionaTipoTarefa(); + base.Loading(false); + base.ToggleSnackBar("TIPO DE TAREFA EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public async Task> Filtrar(string value) + { + List tipoDeTarefas = await Task.Run>(() => this.FiltrarTipoTarefa(value)); + return tipoDeTarefas; + } + + public List FiltrarTipoTarefa(string filter) + { + this.TiposTarefaFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.TiposTarefa) : new ObservableCollection( + from x in this.TiposTarefa + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + this.SelectedTipoTarefa = this.TiposTarefaFiltrados.FirstOrDefault(); + return this.TiposTarefaFiltrados.ToList(); + } + + public void Incluir() + { + TipoDeTarefa tipoDeTarefa = new TipoDeTarefa(); + tipoDeTarefa.set_Ativo(true); + tipoDeTarefa.set_Excluido(false); + this.SelectedTipoTarefa = tipoDeTarefa; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedTipoTarefa.Validate(); + keyValuePairs1.AddRange(this.Validate()); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedTipoTarefa.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + TipoDeTarefa tipoDeTarefa = await this._servico.Save(this.SelectedTipoTarefa); + if (this._servico.Sucesso) + { + TipoTarefaViewModel tipoTarefaViewModel = this; + string str2 = string.Concat(str1, " TIPO DE TAREFA \"", tipoDeTarefa.get_Nome(), "\""); + long id = tipoDeTarefa.get_Id(); + TipoTela? nullable = new TipoTela?(52); + object id1 = tipoDeTarefa.get_Id(); + obj = (tipoDeTarefa.get_Ativo() ? "SIM" : "NÃO"); + tipoTarefaViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", id1, obj, tipoDeTarefa.get_Descricao())); + if (!this.TiposTarefa.Any((TipoDeTarefa x) => x.get_Id() == tipoDeTarefa.get_Id())) + { + this.TiposTarefa.Add(tipoDeTarefa); + } + else + { + DomainBase.Copy(this.TiposTarefa.First((TipoDeTarefa x) => x.get_Id() == tipoDeTarefa.get_Id()), tipoDeTarefa); + } + if (!this.TiposTarefaFiltrados.Any((TipoDeTarefa x) => x.get_Id() == tipoDeTarefa.get_Id())) + { + this.TiposTarefaFiltrados.Add(tipoDeTarefa); + } + else + { + DomainBase.Copy(this.TiposTarefaFiltrados.First((TipoDeTarefa x) => x.get_Id() == tipoDeTarefa.get_Id()), tipoDeTarefa); + } + this.TiposTarefaFiltrados = new ObservableCollection(this.TiposTarefaFiltrados); + this.WorkOnSelectedTipoTarefa(tipoDeTarefa, false); + Recursos.TiposTarefa = this.TiposTarefa; + base.Alterar(false); + base.ToggleSnackBar("TIPO DE TAREFA SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(52); + await this.SelecionaTipoTarefa(); + base.Loading(false); + } + + private async Task SelecionaTipoTarefa() + { + base.Loading(true); + List tipoDeTarefas = await this._servico.BuscarTarefas(); + TipoTarefaViewModel list = this; + List tipoDeTarefas1 = tipoDeTarefas; + IEnumerable excluido = + from x in tipoDeTarefas1 + where !x.get_Excluido() + select x; + IOrderedEnumerable ativo = + from x in excluido + orderby x.get_Ativo() descending + select x; + list.TiposTarefa = ativo.ThenBy((TipoDeTarefa x) => x.get_Nome()).ToList(); + this.TiposTarefaFiltrados = new ObservableCollection(this.TiposTarefa); + this.SelectedTipoTarefa = this.TiposTarefaFiltrados.FirstOrDefault(); + base.Loading(false); + } + + public List> Validate() + { + List> keyValuePairs = new List>(); + if (string.IsNullOrWhiteSpace(this.SelectedTipoTarefa.get_Nome())) + { + return keyValuePairs; + } + if (this.TiposTarefa.Any((TipoDeTarefa x) => { + if (!x.get_Nome().Contains(this.SelectedTipoTarefa.get_Nome())) + { + return false; + } + return x.get_Id() != this.SelectedTipoTarefa.get_Id(); + })) + { + keyValuePairs.Add(new KeyValuePair("Nome", "UM TIPO DE TAREFA COM O MESMO NOME JÁ EXISTE.")); + } + return keyValuePairs; + } + + private void WorkOnSelectedTipoTarefa(TipoDeTarefa value, bool registrar = true) + { + long? nullable; + this.CancelTipoTarefa = (value == null || value.get_Id() == 0 ? this.CancelTipoTarefa : (TipoDeTarefa)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 52) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU TIPO DE TAREFA \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(52), string.Format("ID: {0}\nATIVO: {1}\nDESCRIÇÃO: \"{2}\"", value.get_Id(), (value.get_Ativo() ? "SIM" : "NÃO"), value.get_Descricao())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 52; + TipoDeTarefa selectedTipoTarefa = this.SelectedTipoTarefa; + if (selectedTipoTarefa != null) + { + nullable = new long?(selectedTipoTarefa.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedTipoTarefa = this.TiposTarefaFiltrados.FirstOrDefault((TipoDeTarefa x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoVendedorViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoVendedorViewModel.cs new file mode 100644 index 0000000..c4ff8bc --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/TipoVendedorViewModel.cs @@ -0,0 +1,338 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class TipoVendedorViewModel : BaseSegurosViewModel + { + private readonly TipoVendedorServico _servico; + + public TipoVendedor CancelTipoVendedor; + + private Visibility _ativoVisibility = Visibility.Collapsed; + + private TipoVendedor _selectedTipoVendedor = new TipoVendedor(); + + private ObservableCollection _tipoVendedoresFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + public Visibility AtivoVisibility + { + get + { + return this._ativoVisibility; + } + set + { + this._ativoVisibility = value; + base.OnPropertyChanged("AtivoVisibility"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public TipoVendedor SelectedTipoVendedor + { + get + { + return this._selectedTipoVendedor; + } + set + { + long? nullable; + this._selectedTipoVendedor = value; + this.WorkOnSelectedTipoVendedor(value, true); + this.AtivoVisibility = ((value != null ? value.get_Id() != (long)1 : true) ? Visibility.Visible : Visibility.Collapsed); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedTipoVendedor"); + } + } + + public List TipoVendedores + { + get; + set; + } + + public ObservableCollection TipoVendedoresFiltrados + { + get + { + return this._tipoVendedoresFiltrados; + } + set + { + this._tipoVendedoresFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("TipoVendedoresFiltrados"); + } + } + + public TipoVendedorViewModel() + { + this._servico = new TipoVendedorServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public void CancelarAlteracao() + { + if (this.CancelTipoVendedor == null || !this.TipoVendedores.Any((TipoVendedor x) => x.get_Id() == this.CancelTipoVendedor.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.TipoVendedores.First((TipoVendedor x) => x.get_Id() == this.CancelTipoVendedor.get_Id()), this.CancelTipoVendedor); + if (this.TipoVendedoresFiltrados.Count <= 0 || !this.TipoVendedoresFiltrados.Any((TipoVendedor x) => x.get_Id() == this.CancelTipoVendedor.get_Id())) + { + this.TipoVendedoresFiltrados.Add(this.CancelTipoVendedor); + } + else + { + DomainBase.Copy(this.TipoVendedoresFiltrados.First((TipoVendedor x) => x.get_Id() == this.CancelTipoVendedor.get_Id()), this.CancelTipoVendedor); + } + this.TipoVendedoresFiltrados = new ObservableCollection(this.TipoVendedoresFiltrados); + this.SelectedTipoVendedor = this.TipoVendedoresFiltrados.First((TipoVendedor x) => x.get_Id() == this.CancelTipoVendedor.get_Id()); + } + base.Alterar(false); + } + + public async void Excluir() + { + object obj; + TipoVendedor tipoVendedor; + if (this.SelectedTipoVendedor != null && this.SelectedTipoVendedor.get_Id() != 0 && this.SelectedTipoVendedor.get_Id() != (long)1) + { + if (await (new BaseServico()).TipoVendedorUtilizado(this.SelectedTipoVendedor.get_Id())) + { + await base.ShowMessage("TIPO VENDEDOR NÃO PODE SER EXCLUÍDO POIS ESTÁ SENDO UTILIZADO.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedTipoVendedor)) + { + TipoVendedorViewModel tipoVendedorViewModel = this; + string str = string.Concat("EXCLUIU TIPO VENDEDOR \"", this.SelectedTipoVendedor.get_Descricao(), "\""); + long id = this.SelectedTipoVendedor.get_Id(); + TipoTela? nullable = new TipoTela?(14); + object id1 = this.SelectedTipoVendedor.get_Id(); + obj = (!this.SelectedTipoVendedor.get_Ativo().HasValue || !this.SelectedTipoVendedor.get_Ativo().Value ? "NÃO" : "SIM"); + tipoVendedorViewModel.RegistrarAcao(str, id, nullable, string.Format("ID: {0}\nATIVO: {1}", id1, obj)); + int num = this.TipoVendedoresFiltrados.IndexOf(this.SelectedTipoVendedor); + this.TipoVendedores.Remove(this.SelectedTipoVendedor); + this.TipoVendedoresFiltrados.Remove(this.SelectedTipoVendedor); + this.TipoVendedoresFiltrados = new ObservableCollection(this.TipoVendedoresFiltrados); + if (this.TipoVendedoresFiltrados.Count <= 0) + { + this.SelectedTipoVendedor = new TipoVendedor(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + TipoVendedorViewModel tipoVendedorViewModel1 = this; + tipoVendedor = (num < this.TipoVendedoresFiltrados.Count ? this.TipoVendedoresFiltrados.ElementAt(num) : this.TipoVendedoresFiltrados.Last()); + tipoVendedorViewModel1.SelectedTipoVendedor = tipoVendedor; + } + Recursos.TipoVendedor = this.TipoVendedores; + base.Loading(false); + base.ToggleSnackBar("TIPO VENDEDOR EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List tipoVendedors = await Task.Run>(() => this.FiltrarTipoVendedor(value)); + return tipoVendedors; + } + + public List FiltrarTipoVendedor(string filter) + { + this.TipoVendedoresFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.TipoVendedores) : new ObservableCollection( + from x in this.TipoVendedores + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Descricao() + select x)); + this.SelectedTipoVendedor = this.TipoVendedoresFiltrados.FirstOrDefault(); + return this.TipoVendedoresFiltrados.ToList(); + } + + public void Incluir() + { + TipoVendedor tipoVendedor = new TipoVendedor(); + tipoVendedor.set_Ativo(new bool?(true)); + tipoVendedor.set_Inserido(new bool?(false)); + this.SelectedTipoVendedor = tipoVendedor; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + object obj; + string str1; + List> keyValuePairs1 = this.SelectedTipoVendedor.Validate(); + if (keyValuePairs1.Count <= 0) + { + str = (this.SelectedTipoVendedor.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + TipoVendedor tipoVendedor = await this._servico.Save(this.SelectedTipoVendedor); + if (this._servico.Sucesso) + { + TipoVendedorViewModel tipoVendedorViewModel = this; + string str2 = string.Concat(str1, " TIPO VENDEDOR \"", tipoVendedor.get_Descricao(), "\""); + long id = tipoVendedor.get_Id(); + TipoTela? nullable = new TipoTela?(14); + object id1 = tipoVendedor.get_Id(); + obj = (!tipoVendedor.get_Ativo().HasValue || !tipoVendedor.get_Ativo().Value ? "NÃO" : "SIM"); + tipoVendedorViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nATIVO: {1}", id1, obj)); + if (!this.TipoVendedores.Any((TipoVendedor x) => x.get_Id() == tipoVendedor.get_Id())) + { + this.TipoVendedores.Add(tipoVendedor); + } + else + { + DomainBase.Copy(this.TipoVendedores.First((TipoVendedor x) => x.get_Id() == tipoVendedor.get_Id()), tipoVendedor); + } + if (!this.TipoVendedoresFiltrados.Any((TipoVendedor x) => x.get_Id() == tipoVendedor.get_Id())) + { + this.TipoVendedoresFiltrados.Add(tipoVendedor); + } + else + { + DomainBase.Copy(this.TipoVendedoresFiltrados.First((TipoVendedor x) => x.get_Id() == tipoVendedor.get_Id()), tipoVendedor); + } + this.TipoVendedoresFiltrados = new ObservableCollection(this.TipoVendedoresFiltrados); + this.WorkOnSelectedTipoVendedor(tipoVendedor, false); + Recursos.TipoVendedor = this.TipoVendedores; + base.Alterar(false); + base.ToggleSnackBar("TIPO VENDEDOR SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + public async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(14); + await this.SelecionaTipoVendedores(); + base.Loading(false); + } + + public void SelecionaTipoVendedor(TipoVendedor tipoVendedor) + { + this.SelectedTipoVendedor = tipoVendedor; + } + + private async Task SelecionaTipoVendedores() + { + base.Loading(true); + List tipoVendedors = await (new BaseServico()).BuscarTipoVendedoresAsync(); + TipoVendedorViewModel list = this; + List tipoVendedors1 = tipoVendedors; + IOrderedEnumerable ativo = + from x in tipoVendedors1 + orderby x.get_Ativo() descending + select x; + list.TipoVendedores = ativo.ThenBy((TipoVendedor x) => x.get_Descricao()).ToList(); + this.TipoVendedoresFiltrados = new ObservableCollection(this.TipoVendedores); + if (this.TipoVendedoresFiltrados.Count <= 0) + { + this.SelectedTipoVendedor = new TipoVendedor(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaTipoVendedor(this.TipoVendedoresFiltrados.First()); + } + Recursos.TipoVendedor = tipoVendedors; + base.Loading(false); + } + + private void WorkOnSelectedTipoVendedor(TipoVendedor value, bool registrar = true) + { + long? nullable; + this.CancelTipoVendedor = (value == null || value.get_Id() == 0 ? this.CancelTipoVendedor : (TipoVendedor)value.Clone()); + if (value == null || value.get_Id() == 0 || this.LastAccessId == value.get_Id() && this.LastAccessTela == 14) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU TIPO VENDEDOR \"", value.get_Descricao(), "\""), value.get_Id(), new TipoTela?(14), string.Format("ID: {0}\nATIVO: {1}", value.get_Id(), (!value.get_Ativo().HasValue || !value.get_Ativo().Value ? "NÃO" : "SIM"))); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 14; + TipoVendedor selectedTipoVendedor = this.SelectedTipoVendedor; + if (selectedTipoVendedor != null) + { + nullable = new long?(selectedTipoVendedor.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedTipoVendedor = this.TipoVendedoresFiltrados.FirstOrDefault((TipoVendedor x) => x.get_Id() == value.get_Id()); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/UsuarioViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/UsuarioViewModel.cs new file mode 100644 index 0000000..7f04040 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/UsuarioViewModel.cs @@ -0,0 +1,826 @@ +using Agger.Registro; +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using MaterialDesignThemes.Wpf; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Net.Http; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class UsuarioViewModel : BaseSegurosViewModel + { + private readonly UsuarioServico _servico; + + private readonly PermissaoUsuarioServico _permissaoUsuarioServico; + + public Usuario CancelUsuario; + + private string _inicioAcesso; + + private string _fimAcesso; + + private Usuario _selectedUsuario; + + private Empresa _selectedFilial; + + private bool _cartaoCriado; + + private ObservableCollection _usuariosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private bool _enableGrid = true; + + private Visibility _horarioAcessoVisible; + + private List _empresas = Recursos.Empresas; + + private string _confirmaSenha; + + private string _labelCartao; + + public Visibility AddUsuarioCentralSeguradoVisibility { get; set; } = (string.IsNullOrEmpty(Connection.UrlCentralSegurado) ? Visibility.Collapsed : Visibility.Visible); + + public bool CartaoCriado + { + get + { + return this._cartaoCriado; + } + set + { + this._cartaoCriado = value; + base.OnPropertyChanged("CartaoCriado"); + } + } + + public string ConfirmaSenha + { + get + { + return this._confirmaSenha; + } + set + { + this._confirmaSenha = value; + base.OnPropertyChanged("ConfirmaSenha"); + } + } + + public static DrawerHost Drawer + { + get; + set; + } + + public List Empresas + { + get + { + return this._empresas; + } + set + { + this._empresas = value; + base.OnPropertyChanged("Empresas"); + } + } + + public bool EnableGrid + { + get + { + return this._enableGrid; + } + set + { + this._enableGrid = value; + base.OnPropertyChanged("EnableGrid"); + } + } + + public string FimAcesso + { + get + { + return this._fimAcesso; + } + set + { + this._fimAcesso = value; + base.OnPropertyChanged("FimAcesso"); + } + } + + public Visibility HorarioAcessoVisible + { + get + { + return this._horarioAcessoVisible; + } + set + { + this._horarioAcessoVisible = value; + base.OnPropertyChanged("HorarioAcessoVisible"); + } + } + + public string InicioAcesso + { + get + { + return this._inicioAcesso; + } + set + { + this._inicioAcesso = value; + base.OnPropertyChanged("InicioAcesso"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public string LabelCartao + { + get + { + return this._labelCartao; + } + set + { + this._labelCartao = value; + base.OnPropertyChanged("LabelCartao"); + } + } + + public List PermissaoUsuario + { + get; + set; + } + + public Empresa SelectedFilial + { + get + { + return this._selectedFilial; + } + set + { + this._selectedFilial = value; + base.OnPropertyChanged("SelectedFilial"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + long? nullable; + this._selectedUsuario = value; + this.WorkOnSelectedUsuario(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedUsuario"); + } + } + + private string SenhaOriginal + { + get; + set; + } + + public List Usuarios + { + get; + set; + } + + public ObservableCollection UsuariosFiltrados + { + get + { + return this._usuariosFiltrados; + } + set + { + this._usuariosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("UsuariosFiltrados"); + } + } + + public UsuarioViewModel() + { + this._servico = new UsuarioServico(); + this._permissaoUsuarioServico = new PermissaoUsuarioServico(); + base.EnableMenu = true; + } + + public async Task AddUsuarioAdiministadorCentralSegurado() + { + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + if (this.SelectedUsuario != null) + { + base.Loading(true); + str7 = "USUÁRIO CADASTRADO/ALTERADO COM SUCESSO!"; + try + { + str = (this.SelectedUsuario.get_Telefone() == null ? string.Empty : string.Concat("(", this.SelectedUsuario.get_Prefixo(), ") ", this.SelectedUsuario.get_Telefone())); + string str8 = str; + Token token = new Token(); + UsuarioCentralSegurado usuarioCentralSegurado = new UsuarioCentralSegurado(); + usuarioCentralSegurado.set_Id(""); + usuarioCentralSegurado.set_Senha(""); + usuarioCentralSegurado.set_Serial(token.Encrypt(Recursos.Empresa.get_Serial())); + usuarioCentralSegurado.set_FornecedorId(ApplicationHelper.IdFornecedor); + usuarioCentralSegurado.set_Nome(token.Encrypt(this.SelectedUsuario.get_Nome())); + usuarioCentralSegurado.set_Documento(token.Encrypt(this.SelectedUsuario.get_Documento().Clear())); + usuarioCentralSegurado.set_Email(token.Encrypt(this.SelectedUsuario.get_Email())); + usuarioCentralSegurado.set_IdEmpresa(this.SelectedUsuario.get_IdEmpresa()); + usuarioCentralSegurado.set_Telefone(token.Encrypt(str8)); + str1 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Endereco()) : string.Empty); + usuarioCentralSegurado.set_Rua(str1); + str2 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Numero()) : string.Empty); + usuarioCentralSegurado.set_Numero(str2); + str3 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Bairro()) : string.Empty); + usuarioCentralSegurado.set_Bairro(str3); + str4 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Cidade()) : string.Empty); + usuarioCentralSegurado.set_Cidade(str4); + str5 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Estado()) : string.Empty); + usuarioCentralSegurado.set_Estado(str5); + str6 = (this.SelectedUsuario.get_Cidade() != null ? token.Encrypt(this.SelectedUsuario.get_Cep()) : string.Empty); + usuarioCentralSegurado.set_Cep(str6); + usuarioCentralSegurado.set_Corretora(token.Encrypt(Recursos.Empresa.get_Nome())); + usuarioCentralSegurado.set_UriCorretora(token.Encrypt(Connection.UrlCentralSegurado)); + usuarioCentralSegurado.set_Admin(this.SelectedUsuario.get_AdministradorCentralSegurado()); + UsuarioCentralSegurado usuarioCentralSegurado1 = usuarioCentralSegurado; + using (HttpClient httpClient = new HttpClient()) + { + StringContent stringContent = new StringContent(JsonConvert.SerializeObject(usuarioCentralSegurado1), Encoding.UTF8, "application/json"); + Uri centralSegurado = Address.get_CentralSegurado(); + string[] strArrays = new string[] { "Usuario" }; + Uri uri = centralSegurado.Append(strArrays); + string[] strArrays1 = new string[] { "AddAggerApp" }; + Uri uri1 = uri.Append(strArrays1); + HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri1, stringContent); + await this._servico.AddCentralSegurado(this.SelectedUsuario.get_Id(), httpResponseMessage.get_IsSuccessStatusCode()); + if (!httpResponseMessage.get_IsSuccessStatusCode()) + { + string str9 = await httpResponseMessage.get_Content().ReadAsStringAsync(); + str7 = string.Concat("HOUVE(RAM) O(S) SEGUINTE(S) ERROS: ", str9.Replace(";", ", ").ToUpper()); + } + httpResponseMessage = null; + } + httpClient = null; + } + catch + { + str7 = "HOUVERAM ERROS AO CADASTRAR/ALTERAR O USUÁRIO!"; + } + base.Loading(false); + await base.ShowMessage(str7, "OK", "", false); + } + str7 = null; + } + + public async Task AlterarUsuario() + { + if (this.SelectedUsuario != null) + { + Usuario usuario = await this._servico.BuscarUsuarioPorId(this.SelectedUsuario.get_Id()); + this.SenhaOriginal = (new Token()).AggerDecrypt(usuario.get_Senha()); + await this.SelecionaUsuario(this.SelectedUsuario); + } + } + + public async void AtualizaUsuario() + { + if (!base.EnableFields) + { + await this.CarregarUsuarios(); + } + } + + private async Task BuscaAlteracaoUsuarios(long idUsuario) + { + bool flag; + bool valueOrDefault; + bool flag1; + bool? nullable; + Usuario usuario = await (new UsuarioServico()).BuscarUsuarioPorId(idUsuario); + if (usuario == null) + { + valueOrDefault = false; + } + else + { + if (usuario != null) + { + nullable = new bool?(usuario.get_AdministradorCentralSegurado()); + } + else + { + nullable = null; + } + bool? nullable1 = nullable; + bool administradorCentralSegurado = this.SelectedUsuario.get_AdministradorCentralSegurado(); + valueOrDefault = !(nullable1.GetValueOrDefault() == administradorCentralSegurado & nullable1.HasValue); + } + bool flag2 = valueOrDefault; + flag1 = (flag2 || !this.SelectedUsuario.get_AdministradorCentralSegurado() ? false : this.SelectedUsuario.get_Id() == (long)0); + bool flag3 = flag1; + List usuarios = this.Usuarios; + IEnumerable administradorCentralSegurado1 = + from x in usuarios + where x.get_AdministradorCentralSegurado() + select x; + List list = ( + from x in administradorCentralSegurado1 + orderby x.get_Nome() + select x).ToList(); + if (flag2 && !flag3 && list.Count == 0) + { + if (!await base.ShowMessage("ESTE USUÁRIO É O ÚNICO ADM DA CENTRAL DO SEGURADO.\nTEM CERTEZA QUE DESEJA REMOVER?", "SIM", "CANCELAR", false)) + { + this.CancelarAlteracao(); + flag = false; + return flag; + } + } + if (!(flag3 | flag2) || !string.IsNullOrEmpty(Connection.UrlCentralSegurado)) + { + flag = flag2 | flag3; + } + else + { + if (this.SelectedUsuario != null) + { + this.SelectedUsuario.set_AdministradorCentralSegurado(false); + } + await base.ShowMessage("NÃO FOI POSSÍVEL ADICIONAR UM USUÁRIO ADM CENTRAL SEGURADO, POR FAVOR ENTRE EM CONTATO COM O SUPORTE AGGER. \nURL AUSENTE!", "OK", "", false); + flag = false; + } + return flag; + } + + private async Task BuscaPermissao() + { + this.PermissaoUsuario = await this._permissaoUsuarioServico.PermissUsuario(Recursos.Usuario); + } + + public async Task CancelarAlteracao() + { + long id; + await this.CarregarUsuarios(); + if (!this.UsuariosFiltrados.Any()) + { + this.SelectedUsuario = new Usuario(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + Usuario cancelUsuario = this.CancelUsuario; + if (cancelUsuario != null) + { + id = cancelUsuario.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + this.SelectedUsuario = this.UsuariosFiltrados.FirstOrDefault((Usuario x) => x.get_Id() == num); + } + base.Alterar(false); + this.ConfirmaSenha = ""; + } + + private async Task CarregarUsuarios() + { + List usuarios = await (new BaseServico()).CarregarUsuarios(); + UsuarioViewModel list = this; + List usuarios1 = usuarios; + IEnumerable usuarios2 = usuarios1.Where((Usuario x) => { + if (x.get_Excluido()) + { + return false; + } + long? permissaoAggilizador = x.get_PermissaoAggilizador(); + long num = (long)4; + return !(permissaoAggilizador.GetValueOrDefault() == num & permissaoAggilizador.HasValue); + }); + list.Usuarios = ( + from x in usuarios2 + orderby x.get_Nome() + select x).ToList(); + this.UsuariosFiltrados = new ObservableCollection(this.Usuarios); + await this.BuscaPermissao(); + } + + public async Task CriarCartao(bool dadosUsuario) + { + await base.ShowMessage("CARTÃO CRIADO/ATUALIZADO COM SUCESSO", "OK", "", false); + } + + public async Task Excluir() + { + if (this.SelectedUsuario != null && this.SelectedUsuario.get_Id() != 0) + { + if (await (new VendedorUsuarioServico()).FindVinculoByUsuario(this.SelectedUsuario.get_Id())) + { + await base.ShowMessage("O USUÁRIO POSSUI VÍNCULO DE VENDEDOR, REMOVA O VÍNCULO ANTES DE EXCLUIR.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedUsuario)) + { + base.RegistrarAcao(string.Concat("EXCLUIU USUÁRIO \"", this.SelectedUsuario.get_Nome(), "\""), this.SelectedUsuario.get_Id(), new TipoTela?(16), string.Format("ID: {0}", this.SelectedUsuario.get_Id())); + await this.CarregarUsuarios(); + if (!this.UsuariosFiltrados.Any()) + { + this.SelectedUsuario = new Usuario(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelectedUsuario = this.UsuariosFiltrados.FirstOrDefault(); + } + base.Loading(false); + base.ToggleSnackBar("USUÁRIO EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + internal async Task> Filtrar(string value) + { + List usuarios = await Task.Run>(() => this.FiltrarUsuario(value)); + return usuarios; + } + + public List FiltrarUsuario(string filter) + { + this.UsuariosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Usuarios) : new ObservableCollection( + from x in this.Usuarios + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby !x.get_Excluido() descending, x.get_Nome() + select x)); + return this.UsuariosFiltrados.ToList(); + } + + public void Incluir() + { + Usuario usuario = new Usuario(); + usuario.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + usuario.set_Segunda(new bool?(true)); + usuario.set_Terca(new bool?(true)); + usuario.set_Quarta(new bool?(true)); + usuario.set_Quinta(new bool?(true)); + usuario.set_Sexta(new bool?(true)); + usuario.set_Sabado(new bool?(true)); + usuario.set_Domingo(new bool?(true)); + usuario.set_Excluido(false); + usuario.set_FiltroInicial(new TipoFiltroCliente?(0)); + this.SelectedUsuario = usuario; + this.SenhaOriginal = null; + base.Alterar(true); + } + + public async Task OpenPermissao() + { + bool selectedUsuario = this.SelectedUsuario == null; + if (selectedUsuario) + { + selectedUsuario = await base.ShowMessage("É NECESSÁRIO SELECIONAR UM USUÁRIO!", "OK", "", false); + } + if (!selectedUsuario) + { + Gestor.Application.Actions.Actions.AtualizaUsuario = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.AtualizaUsuario, new Action(this.AtualizaUsuario)); + Gestor.Application.Actions.Actions.AtualizaUsuario = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.AtualizaUsuario, new Action(this.AtualizaUsuario)); + base.ShowDrawer(new PermissaoUsuarioDrawer(this.SelectedUsuario), 0, false); + } + } + + public async Task OpenVinculo() + { + bool selectedUsuario = this.SelectedUsuario == null; + if (selectedUsuario) + { + selectedUsuario = await base.ShowMessage("É NECESSÁRIO SELECIONAR UM USUÁRIO!", "OK", "", false); + } + if (!selectedUsuario) + { + base.ShowDrawer(new VinculoVendedorDrawer(this.SelectedUsuario), 0, true); + } + } + + public async Task>> Salvar() + { + List> keyValuePairs; + DateTime dateTime; + DateTime dateTime1; + string str; + long num; + string str1; + string str2; + if (!DateTime.TryParse(this.InicioAcesso, out dateTime) || !DateTime.TryParse(this.FimAcesso, out dateTime1)) + { + DateTime? nullable = null; + this.SelectedUsuario.set_InicioAcesso(nullable); + nullable = null; + this.SelectedUsuario.set_FimAcesso(nullable); + } + else + { + this.SelectedUsuario.set_InicioAcesso(new DateTime?(dateTime)); + this.SelectedUsuario.set_FimAcesso(new DateTime?(dateTime1)); + } + Usuario selectedUsuario = this.SelectedUsuario; + str = (!string.IsNullOrEmpty(this.SelectedUsuario.get_Senha()) ? this.SelectedUsuario.get_Senha() : this.SenhaOriginal); + selectedUsuario.set_Senha(str); + List> keyValuePairs1 = this.SelectedUsuario.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + this.SelectedUsuario.set_Senha((new Token()).AggerEncrypt(this.SelectedUsuario.get_Senha())); + Usuario usuario = this.SelectedUsuario; + num = (this.SelectedUsuario.get_IdEmpresa() == 0 ? Recursos.Usuario.get_IdEmpresa() : this.SelectedUsuario.get_IdEmpresa()); + usuario.set_IdEmpresa(num); + bool flag = await this.BuscaAlteracaoUsuarios(this.SelectedUsuario.get_Id()); + str1 = (this.SelectedUsuario.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str2 = str1; + Usuario usuario1 = await this._servico.Save(this.SelectedUsuario); + if (this._servico.Sucesso) + { + base.RegistrarAcao(string.Concat(str2, " USUÁRIO \"", usuario1.get_Nome(), "\""), usuario1.get_Id(), new TipoTela?(16), string.Format("ID: {0}", usuario1.get_Id())); + if (flag) + { + await this.AddUsuarioAdiministadorCentralSegurado(); + } + await this.CarregarUsuarios(); + this.SelectedUsuario = this.UsuariosFiltrados.FirstOrDefault((Usuario x) => x.get_Id() == usuario1.get_Id()); + Recursos.Usuarios = this.Usuarios; + this.ConfirmaSenha = ""; + base.Alterar(false); + base.ToggleSnackBar("USUÁRIO SALVO COM SUCESSO", true); + this.IsExpanded = true; + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + str2 = null; + return keyValuePairs; + } + + public async Task Seleciona() + { + Visibility visibility; + UsuarioViewModel usuarioViewModel = this; + visibility = (base.Restricao(94) ? Visibility.Collapsed : Visibility.Visible); + usuarioViewModel.HorarioAcessoVisible = visibility; + await base.PermissaoTela(16); + await this.SelecionaUsuarios(); + } + + public async Task SelecionaUsuario(Usuario usuario) + { + Usuario usuario1 = await this._servico.BuscarUsuarioPorId(usuario.get_Id()); + bool? segunda = usuario1.get_Segunda(); + usuario1.set_Segunda(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Terca(); + usuario1.set_Terca(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Quarta(); + usuario1.set_Quarta(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Quinta(); + usuario1.set_Quinta(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Sexta(); + usuario1.set_Sexta(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Sabado(); + usuario1.set_Sabado(new bool?(segunda.GetValueOrDefault(true))); + segunda = usuario1.get_Domingo(); + usuario1.set_Domingo(new bool?(segunda.GetValueOrDefault(true))); + if (Recursos.Usuario.get_Id() == usuario.get_Id()) + { + usuario1.set_Senha((new Token()).AggerDecrypt(usuario1.get_Senha())); + this.SenhaOriginal = usuario1.get_Senha(); + this.ConfirmaSenha = ""; + DomainBase.Copy(this.UsuariosFiltrados.First((Usuario x) => x.get_Id() == usuario.get_Id()), usuario1); + } + this.SelectedUsuario = this.UsuariosFiltrados.First((Usuario x) => x.get_Id() == usuario.get_Id()); + } + + private async Task SelecionaUsuarios() + { + this.EnableGrid = false; + base.Loading(true); + await this.CarregarUsuarios(); + if (this.UsuariosFiltrados.Count <= 0) + { + Usuario usuario = new Usuario(); + usuario.set_Segunda(new bool?(true)); + usuario.set_Terca(new bool?(true)); + usuario.set_Quarta(new bool?(true)); + usuario.set_Quinta(new bool?(true)); + usuario.set_Sexta(new bool?(true)); + usuario.set_Sabado(new bool?(true)); + usuario.set_Domingo(new bool?(true)); + this.SelectedUsuario = usuario; + base.Alterar(false); + base.EnableMenu = false; + } + else + { + await this.SelecionaUsuario(this.UsuariosFiltrados.First()); + } + base.Loading(false); + this.EnableGrid = true; + } + + public async Task>> Validate() + { + List usuarios; + List> keyValuePairs = new List>(); + if (this.SenhaOriginal == null || this.SenhaOriginal != this.SelectedUsuario.get_Senha()) + { + string senha = (new Token()).Decrypt(this.SelectedUsuario.get_Senha()); + if (senha == null) + { + senha = this.SelectedUsuario.get_Senha(); + } + string str = senha; + if (string.IsNullOrWhiteSpace(this.ConfirmaSenha)) + { + keyValuePairs.Add(new KeyValuePair("ConfirmaSenha|CONFIRMAÇÃO SENHA", "OBRIGATÓRIO")); + } + else if (!string.Equals(this.ConfirmaSenha, str)) + { + keyValuePairs.Add(new KeyValuePair("ConfirmaSenha|CONFIRMAÇÃO SENHA", "INVÁLIDO")); + } + } + if (string.IsNullOrWhiteSpace(this.SelectedUsuario.get_Login())) + { + usuarios = new List(); + } + else + { + usuarios = await (new BaseServico()).BuscarUsuarioPorLoginInteiro(this.SelectedUsuario.get_Login()); + } + foreach (Usuario usuario in usuarios) + { + if (usuario.get_Id() == this.SelectedUsuario.get_Id()) + { + continue; + } + keyValuePairs.Add(new KeyValuePair("Login", string.Concat("O LOGIN JÁ ESTÁ CADASTRADO PARA O USUÁRIO \"", usuario.get_Nome(), "\"."))); + } + if (this.SelectedUsuario.get_InicioAcesso().HasValue && !this.SelectedUsuario.get_FimAcesso().HasValue) + { + keyValuePairs.Add(new KeyValuePair("FIM DO ACESSO", "NECESSÁRIO PREENCHER O CAMPO FIM DO ACESSO!")); + } + if (!this.SelectedUsuario.get_InicioAcesso().HasValue && this.SelectedUsuario.get_FimAcesso().HasValue) + { + keyValuePairs.Add(new KeyValuePair("INÍCIO DO ACESSO", "NECESSÁRIO PREENCHER O CAMPO INÍCIO DO ACESSO!")); + } + bool flag = !string.IsNullOrWhiteSpace(this.SelectedUsuario.get_Documento()); + if (flag) + { + flag = await (new BaseServico()).BuscarUsuarioMesmoDocumento(ValidationHelper.OnlyNumber(this.SelectedUsuario.get_Documento()), this.SelectedUsuario.get_Id(), this.SelectedUsuario.get_IdEmpresa()); + } + if (flag) + { + keyValuePairs.Add(new KeyValuePair("Documento", "O DOCUMENTO JÁ ESTÁ SENDO USADO EM OUTRO USUÁRIO")); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + + public async Task VerificaUsuarioAdmCentralSegurado() + { + await this.BuscaAlteracaoUsuarios(this.SelectedUsuario.get_Id()); + } + + private void WorkOnSelectedUsuario(Usuario value, bool registrar = true) + { + long? nullable; + this.CartaoCriado = false; + this.CancelUsuario = (value == null || value.get_Id() == 0 ? this.CancelUsuario : (Usuario)value.Clone()); + if (value == null || value.get_Id() == 0) + { + return; + } + value.set_Senha(EncryptionHelper.Decrypt(value.get_Senha())); + if (this.LastAccessId == value.get_Id() && this.LastAccessTela == 16) + { + return; + } + if (registrar) + { + base.RegistrarAcao(string.Concat("ACESSOU USUÁRIO \"", value.get_Nome(), "\""), value.get_Id(), new TipoTela?(16), string.Format("ID USUÁRIO: {0}", value.get_Id())); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 16; + Usuario selectedUsuario = this.SelectedUsuario; + if (selectedUsuario != null) + { + nullable = new long?(selectedUsuario.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() != id | !nullable1.HasValue) + { + this.SelectedUsuario = this.UsuariosFiltrados.FirstOrDefault((Usuario x) => x.get_Id() == value.get_Id()); + } + if (this.SelectedUsuario.get_InicioAcesso().HasValue && this.SelectedUsuario.get_FimAcesso().HasValue) + { + DateTime? inicioAcesso = this.SelectedUsuario.get_InicioAcesso(); + DateTime dateTime = inicioAcesso.Value; + this.InicioAcesso = dateTime.ToString("HH:mm"); + inicioAcesso = this.SelectedUsuario.get_FimAcesso(); + dateTime = inicioAcesso.Value; + this.FimAcesso = dateTime.ToString("HH:mm"); + } + if (!this.SelectedUsuario.get_InicioAcesso().HasValue && !this.SelectedUsuario.get_FimAcesso().HasValue) + { + this.InicioAcesso = null; + this.FimAcesso = null; + } + this.CartaoCriado = !string.IsNullOrEmpty(value.get_Visita()); + this.LabelCartao = (this.CartaoCriado ? "ATUALIZAR CARTÃO" : "CRIAR CARTÃO"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Ferramentas/VendedorViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Ferramentas/VendedorViewModel.cs new file mode 100644 index 0000000..32b04c4 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Ferramentas/VendedorViewModel.cs @@ -0,0 +1,913 @@ +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Attributes; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Ferramentas +{ + public class VendedorViewModel : BaseSegurosViewModel + { + private readonly VendedorServico _servico; + + public Vendedor CancelVendedor; + + private Vendedor _selectedVendedor; + + private GridLength _gridHeight = new GridLength(1, GridUnitType.Star); + + private GridLength _gridHeight2 = new GridLength(0); + + private ObservableCollection _vendedoresFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private VendedorTelefone _selectedTelefone = new VendedorTelefone(); + + private ObservableCollection _telefones = new ObservableCollection(); + + private Repasse _selectedRepasse = new Repasse(); + + private ObservableCollection _repasses = new ObservableCollection(); + + private string _pesquisa; + + private Visibility _mostrarRamo; + + private ObservableCollection _ramos = new ObservableCollection(); + + private Visibility _visualizacaoPropriaCorretora { get; set; } = Visibility.Collapsed; + + public bool CoCorretagemAtiva { get; set; } = Recursos.Configuracoes.Any(new Func((// + // Current member / type: System.Boolean Gestor.Application.ViewModels.Ferramentas.VendedorViewModel::CoCorretagemAtiva() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Boolean CoCorretagemAtiva() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.GetArgumentName(ParameterReference parameter) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 2276 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.VisitLambdaParameterExpression(LambdaParameterExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 4496 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Languages.BaseLanguageWriter.Write(Action writeEntity) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseLanguageWriter.cs:line 339 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 1133 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.VisitMethodParametersInternal(IList`1 list, Boolean isExtensionMethod) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 2769 + // at Telerik.JustDecompiler.Languages.CSharp.CSharpWriter.VisitLambdaExpression(LambdaExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\CSharp\CSharpWriter.cs:line 1077 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Languages.BaseLanguageWriter.Write(Action writeEntity) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseLanguageWriter.cs:line 339 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 1133 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.VisitDelegateCreationExpression(DelegateCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 4667 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Languages.BaseLanguageWriter.Write(Action writeEntity) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseLanguageWriter.cs:line 339 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 1133 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.VisitMethodParametersInternal(IList`1 list, Boolean isExtensionMethod) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 2769 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 2750 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Languages.BaseLanguageWriter.Write(Action writeEntity) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseLanguageWriter.cs:line 339 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 1133 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.WriteInitializedAutoProperty(PropertyDefinition property, Expression assignment) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseImperativeLanguageWriter.cs:line 1457 + // at Telerik.JustDecompiler.Languages.BaseImperativeLanguageWriter.Write(PropertyDefinition property) + // at Telerik.JustDecompiler.Languages.BaseLanguageWriter.WriteInternal(IMemberDefinition member) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Languages\BaseLanguageWriter.cs:line 583 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + + public GridLength GridHeight + { + get + { + return this._gridHeight; + } + set + { + this._gridHeight = value; + base.OnPropertyChanged("GridHeight"); + } + } + + public GridLength GridHeight2 + { + get + { + return this._gridHeight2; + } + set + { + this._gridHeight2 = value; + base.OnPropertyChanged("GridHeight2"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Visibility MostrarRamo + { + get + { + return this._mostrarRamo; + } + set + { + this._mostrarRamo = value; + base.OnPropertyChanged("MostrarRamo"); + } + } + + public string Pesquisa + { + get + { + return this._pesquisa; + } + set + { + this._pesquisa = value; + base.OnPropertyChanged("Pesquisa"); + } + } + + public ObservableCollection Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public ObservableCollection Repasses + { + get + { + return this._repasses; + } + set + { + if (value != null && value.Count > 0) + { + foreach (Repasse repasse in value) + { + if (repasse.get_Ramo() != null) + { + continue; + } + repasse.set_Ramo(new Ramo()); + } + } + this._repasses = value; + base.OnPropertyChanged("Repasses"); + } + } + + public Repasse SelectedRepasse + { + get + { + return this._selectedRepasse; + } + set + { + this._selectedRepasse = value; + base.OnPropertyChanged("SelectedRepasse"); + } + } + + public VendedorTelefone SelectedTelefone + { + get + { + return this._selectedTelefone; + } + set + { + this._selectedTelefone = value; + base.OnPropertyChanged("SelectedTelefone"); + } + } + + public Vendedor SelectedVendedor + { + get + { + return this._selectedVendedor; + } + set + { + long? nullable; + this._selectedVendedor = value; + this.WorkOnSelectedVendedor(value, true); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedVendedor"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public List TiposRepasseFiltrados + { + get + { + return Enum.GetValues(typeof(TipoRepasse)).Cast().Where((TipoRepasse tipo) => { + TipoAttribute tipoAttribute = (TipoAttribute)typeof(TipoRepasse).GetField(tipo.ToString()).GetCustomAttributes(typeof(TipoAttribute), false).FirstOrDefault(); + if (tipoAttribute == null || tipoAttribute.get_Tipo() == "0" || this.CoCorretagemAtiva) + { + return true; + } + TipoRepasse? nullable = this.SelectedRepasse.get_Tipo(); + return tipo == nullable.GetValueOrDefault() & nullable.HasValue; + }).ToList(); + } + } + + public List Vendedores + { + get; + set; + } + + public ObservableCollection VendedoresFiltrados + { + get + { + return this._vendedoresFiltrados; + } + set + { + this._vendedoresFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("VendedoresFiltrados"); + } + } + + public Visibility VisualizacaoPropriaCorretora + { + get + { + return this._visualizacaoPropriaCorretora; + } + set + { + this._visualizacaoPropriaCorretora = value; + base.OnPropertyChanged("VisualizacaoPropriaCorretora"); + } + } + + public VendedorViewModel() + { + this._servico = new VendedorServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public async Task AtivarInativarRepasse(Repasse repasse) + { + bool id; + Ramo ramo; + object obj; + string str; + if (repasse != null && repasse.get_Id() != 0) + { + str = (repasse.get_Ativo() ? "INATIVOU REPASSE" : "ATIVOU REPASSE"); + repasse.set_Ativo(!repasse.get_Ativo()); + Repasse repasse1 = repasse; + Ramo ramo1 = repasse.get_Ramo(); + if (ramo1 != null) + { + id = ramo1.get_Id() == (long)0; + } + else + { + id = false; + } + if (id) + { + ramo = null; + } + else + { + ramo = repasse.get_Ramo(); + } + repasse1.set_Ramo(ramo); + repasse = await this._servico.Save(repasse); + long num = this.SelectedVendedor.get_Id(); + VendedorViewModel vendedorViewModel = this; + string str1 = string.Concat(str, " \"", this.SelectedVendedor.get_Nome(), "\""); + long id1 = this.SelectedVendedor.get_Id(); + TipoTela? nullable = new TipoTela?(15); + object[] objArray = new object[] { repasse.get_Id(), repasse.get_ValorNovo(), repasse.get_ValorRenovacao(), null }; + obj = (repasse.get_Ativo() ? "SIM" : "NÃO"); + objArray[3] = obj; + vendedorViewModel.RegistrarAcao(str1, id1, nullable, string.Format("ID: {0}\nVALOR NOVO: {1:N2}\nVALOR RENOVAÇÃO: {2:N2}\nATIVO: {3}", objArray)); + this.Pesquisa = string.Empty; + this.SelectedVendedor = null; + await this.SelecionaVendedores(false); + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault((Vendedor x) => x.get_Id() == num); + Recursos.Vendedores = this.Vendedores; + base.Alterar(false); + base.ToggleSnackBar("REPASSE SALVO COM SUCESSO", true); + } + str = null; + } + + public async Task AtivarInativarVendedor(Vendedor vendedor) + { + object nome; + object obj; + string str; + Vendedor vendedor1 = vendedor; + if (vendedor1 != null && vendedor1.get_Id() != 0) + { + str = (vendedor1.get_Ativo() ? "INATIVOU VENDEDOR" : "ATIVOU VENDEDOR"); + vendedor1.set_Ativo(!vendedor1.get_Ativo()); + Vendedor vendedor2 = await this._servico.Save(vendedor1, this.Repasses.ToList()); + vendedor1 = vendedor2; + VendedorViewModel vendedorViewModel = this; + string str1 = string.Concat(str, " \"", vendedor1.get_Nome(), "\""); + long id = vendedor1.get_Id(); + TipoTela? nullable = new TipoTela?(15); + object[] agencia = new object[] { vendedor1.get_Id(), Recursos.Empresas.First((Empresa x) => x.get_Id() == (vendedor1.get_IdEmpresa() == 0 ? (long)1 : vendedor1.get_IdEmpresa())).get_Nome(), vendedor1.get_Documento(), null, null, null, null, null }; + Banco banco = vendedor1.get_Banco(); + if (banco != null) + { + nome = banco.get_Nome(); + } + else + { + nome = null; + } + agencia[3] = nome; + agencia[4] = vendedor1.get_Agencia(); + agencia[5] = vendedor1.get_Conta(); + agencia[6] = vendedor1.get_Desconto(); + obj = (vendedor1.get_Ativo() ? "SIM" : "NÃO"); + agencia[7] = obj; + vendedorViewModel.RegistrarAcao(str1, id, nullable, string.Format("ID: {0}\nFILIAL DO VENDEDOR: {1}\nDOCUMENTO: {2}\nBANCO: {3}\nAGÊNCIA: {4}\nCONTA: {5}\nDESCONTO: {6:N2}\nATIVO: {7}", agencia)); + this.Pesquisa = string.Empty; + this.SelectedVendedor = null; + await this.SelecionaVendedores(false); + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault((Vendedor x) => x.get_Id() == vendedor1.get_Id()); + Recursos.Vendedores = this.Vendedores; + base.Alterar(false); + base.ToggleSnackBar("VENDEDOR SALVO COM SUCESSO", true); + } + str = null; + } + + public void CancelarAlteracao() + { + if (this.CancelVendedor == null || !this.Vendedores.Any((Vendedor x) => x.get_Id() == this.CancelVendedor.get_Id())) + { + this.Incluir(); + } + else + { + DomainBase.Copy(this.Vendedores.First((Vendedor x) => x.get_Id() == this.CancelVendedor.get_Id()), this.CancelVendedor); + if (this.VendedoresFiltrados.Count <= 0 || !this.VendedoresFiltrados.Any((Vendedor x) => x.get_Id() == this.CancelVendedor.get_Id())) + { + this.VendedoresFiltrados.Add(this.CancelVendedor); + } + else + { + DomainBase.Copy(this.VendedoresFiltrados.First((Vendedor x) => x.get_Id() == this.CancelVendedor.get_Id()), this.CancelVendedor); + } + this.VendedoresFiltrados = new ObservableCollection(this.VendedoresFiltrados); + this.SelectedVendedor = this.VendedoresFiltrados.First((Vendedor x) => x.get_Id() == this.CancelVendedor.get_Id()); + } + base.Alterar(false); + } + + public void ExcluirTelefone(VendedorTelefone telefone) + { + this.Telefones.Remove(telefone); + } + + public async Task ExcluirVinculo(VinculoRepasse vinculo) + { + if (await base.ShowMessage("DESEJA REALMENTE EXCLUIR O VÍNCULO DO REPASSE SELECIONADO?", "SIM", "NÃO", false)) + { + await this._servico.Delete(vinculo); + this.Repasses = new ObservableCollection((IEnumerable)await this._servico.BuscaRepassesPorIdVendedor(this.SelectedVendedor.get_Id())); + base.ToggleSnackBar("VINCULO EXCLUÍDO COM SUCESSO", true); + } + } + + internal async Task> Filtrar(string value) + { + List vendedors = await Task.Run>(() => this.FiltrarVendedor(value)); + return vendedors; + } + + public List FiltrarVendedor(string filter) + { + this.VendedoresFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Vendedores) : new ObservableCollection( + from x in this.Vendedores + where ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Nome() + select x)); + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault(); + return this.VendedoresFiltrados.ToList(); + } + + public void Incluir() + { + Vendedor vendedor = new Vendedor(); + vendedor.set_Ativo(true); + vendedor.set_Desconto(new decimal?(new decimal())); + this.SelectedVendedor = vendedor; + this.Telefones = new ObservableCollection(); + this.Repasses = new ObservableCollection(); + base.Alterar(true); + } + + public void IncluirRepasse() + { + if (this.SelectedVendedor == null) + { + return; + } + if (this.Repasses == null) + { + this.Repasses = new ObservableCollection(); + } + Repasse repasse = new Repasse(); + repasse.set_Vendedor(this.SelectedVendedor); + repasse.set_Forma(new FormaRepasse?(1)); + repasse.set_Incidencia(new TipoIncidencia?(1)); + repasse.set_Tipo(new TipoRepasse?(2)); + repasse.set_Ativo(true); + repasse.set_Ramo(this.Ramos.First()); + Repasse repasse1 = repasse; + this.Repasses.Insert(0, repasse1); + this.SelectedRepasse = repasse1; + } + + public void IncluirTelefone() + { + if (this.SelectedVendedor == null) + { + return; + } + if (this.Telefones == null) + { + this.Telefones = new ObservableCollection(); + } + VendedorTelefone vendedorTelefone = new VendedorTelefone(); + vendedorTelefone.set_Vendedor(this.SelectedVendedor); + vendedorTelefone.set_Tipo(new TipoTelefone?(1)); + VendedorTelefone vendedorTelefone1 = vendedorTelefone; + this.Telefones.Add(vendedorTelefone1); + this.SelectedTelefone = vendedorTelefone1; + } + + public async Task>> Salvar() + { + List> keyValuePairs1; + string str; + object nome; + object obj; + VendedorViewModel.u003cu003ec__DisplayClass55_0 variable; + List list; + string str1; + this.SelectedVendedor.set_Telefones(this.Telefones.ToList()); + List> keyValuePairs2 = this.SelectedVendedor.Validate(); + List> keyValuePairs3 = keyValuePairs2; + keyValuePairs3.AddRange(await this.Validate()); + keyValuePairs3 = null; + if (keyValuePairs2.Count <= 0) + { + Vendedor selectedVendedor = this.SelectedVendedor; + ObservableCollection telefones = this.Telefones; + selectedVendedor.set_Telefones(( + from x in telefones + where !string.IsNullOrEmpty(x.get_Nome()) + select x).ToList()); + List repasses = this.Repasses.ToList(); + list = repasses.Where((Repasse x) => { + List> keyValuePairs = x.Validate(); + if (keyValuePairs == null) + { + return false; + } + return keyValuePairs.Count == 0; + }).ToList(); + if (list.Count < this.Repasses.Count) + { + if (!await base.ShowMessage(string.Concat("HÁ REPASSES INVÁLIDOS, DESEJA PROSSEGUIR?", Environment.NewLine, "CASO PROSSIGA OS REPASSES INVÁLIDOS NÃO SERÃO SALVOS."), "SIM", "NÃO", false)) + { + this.Repasses.ToList().ForEach((Repasse x) => keyValuePairs2.AddRange(x.Validate())); + keyValuePairs1 = keyValuePairs2; + variable = null; + list = null; + str1 = null; + return keyValuePairs1; + } + } + this.Repasses = new ObservableCollection(list); + str = (this.SelectedVendedor.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Vendedor vendedor = await this._servico.Save(this.SelectedVendedor, this.Repasses.ToList()); + Vendedor vendedor1 = vendedor; + if (this._servico.Sucesso) + { + VendedorViewModel vendedorViewModel = this; + string str2 = string.Concat(str1, " VENDEDOR \"", vendedor1.get_Nome(), "\""); + long id = vendedor1.get_Id(); + TipoTela? nullable = new TipoTela?(15); + object[] agencia = new object[] { vendedor1.get_Id(), Recursos.Empresas.First((Empresa x) => x.get_Id() == (vendedor1.get_IdEmpresa() == 0 ? (long)1 : vendedor1.get_IdEmpresa())).get_Nome(), vendedor1.get_Documento(), null, null, null, null, null }; + Banco banco = vendedor1.get_Banco(); + if (banco != null) + { + nome = banco.get_Nome(); + } + else + { + nome = null; + } + agencia[3] = nome; + agencia[4] = vendedor1.get_Agencia(); + agencia[5] = vendedor1.get_Conta(); + agencia[6] = vendedor1.get_Desconto(); + obj = (vendedor1.get_Ativo() ? "SIM" : "NÃO"); + agencia[7] = obj; + vendedorViewModel.RegistrarAcao(str2, id, nullable, string.Format("ID: {0}\nFILIAL DO VENDEDOR: {1}\nDOCUMENTO: {2}\nBANCO: {3}\nAGÊNCIA: {4}\nCONTA: {5}\nDESCONTO: {6:N2}\nATIVO: {7}", agencia)); + this.Pesquisa = string.Empty; + this.SelectedVendedor = null; + await this.SelecionaVendedores(false); + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault((Vendedor x) => x.get_Id() == vendedor1.get_Id()); + Recursos.Vendedores = this.Vendedores; + base.Alterar(false); + base.ToggleSnackBar("VENDEDOR SALVO COM SUCESSO", true); + keyValuePairs1 = null; + } + else + { + keyValuePairs1 = null; + } + } + else + { + keyValuePairs1 = keyValuePairs2; + } + variable = null; + list = null; + str1 = null; + return keyValuePairs1; + } + + public async Task SalvarVinculo(VinculoRepasse vinculo) + { + await this._servico.Save(vinculo); + this.Repasses = new ObservableCollection((IEnumerable)await this._servico.BuscaRepassesPorIdVendedor(this.SelectedVendedor.get_Id())); + base.ToggleSnackBar("VINCULO SALVO COM SUCESSO", true); + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(15); + await this.SelecionaVendedores(true); + await this.SelecionaRamos(); + base.Loading(false); + } + + private async Task SelecionaRamos() + { + Visibility visibility; + VendedorViewModel vendedorViewModel = this; + List configuracoes = Recursos.Configuracoes; + visibility = (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 20) ? Visibility.Collapsed : Visibility.Visible); + vendedorViewModel.MostrarRamo = visibility; + ObservableCollection ramos = this.Ramos; + Ramo ramo = new Ramo(); + ramo.set_Nome("TODOS OS RAMOS"); + ramos.Add(ramo); + List ramos1 = await (new BaseServico()).BuscarRamosAsync(); + ObservableCollection observableCollection = this.Ramos; + List ramos2 = ramos1; + IEnumerable ativo = + from x in ramos2 + where x.get_Ativo() + select x; + ExtensionMethods.AddRange(observableCollection, + from x in ativo + orderby x.get_Nome() + select x); + } + + private async Task SelecionaVendedores(bool selecionar = true) + { + List vendedors = await (new BaseServico()).BuscarVendedoresAsync(); + VendedorViewModel list = this; + List vendedors1 = vendedors; + IEnumerable vendedors2 = vendedors1.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() == (long)1) + { + return true; + } + return x.get_IdEmpresa() == Recursos.Usuario.get_IdEmpresa(); + }); + IOrderedEnumerable ativo = + from x in vendedors2 + orderby x.get_Ativo() descending + select x; + list.Vendedores = ativo.ThenBy((Vendedor x) => x.get_Nome()).ToList(); + this.VendedoresFiltrados = new ObservableCollection(this.Vendedores); + if (selecionar) + { + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault(); + } + Recursos.Vendedores = vendedors; + } + + private async Task>> Validate() + { + List vendedors; + IEnumerable repasses; + List> keyValuePairs = new List>(); + if (!ValidationHelper.ValidateDocument(this.SelectedVendedor.get_Documento())) + { + vendedors = new List(); + } + else + { + vendedors = await (new BaseServico()).BuscarVendedor(this.SelectedVendedor.get_Documento()); + } + Vendedor vendedor = vendedors.FirstOrDefault((Vendedor x) => { + if (x.get_Id() == this.SelectedVendedor.get_Id() || !(x.get_Documento() == this.SelectedVendedor.get_Documento())) + { + return false; + } + return x.get_Ativo(); + }); + if (vendedor != null) + { + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 7)) + { + keyValuePairs.Add(new KeyValuePair("Documento", string.Concat("O DOCUMENTO JÁ ESTÁ CADASTRADO PARA O VENDEDOR ", vendedor.get_Nome(), "."))); + } + } + List configuracaoSistemas = Recursos.Configuracoes; + if (configuracaoSistemas.All((ConfiguracaoSistema x) => x.get_Configuracao() != 15)) + { + ObservableCollection observableCollection = this.Repasses; + if (observableCollection != null) + { + repasses = observableCollection.Where((Repasse x) => { + if (x.get_Tipo().GetValueOrDefault() != 2) + { + return false; + } + if (x.get_ValorNovo() > new decimal(100)) + { + return true; + } + return x.get_ValorRenovacao() > new decimal(100); + }); + } + else + { + repasses = null; + } + IEnumerable repasses1 = repasses; + if (repasses1 != null && repasses1.Any()) + { + keyValuePairs.Add(new KeyValuePair("VALOR REPASSE", "O VALOR DE REPASSE NÃO PODE SER SUPERIOR A 100%")); + } + } + ObservableCollection observableCollection1 = await this._servico.BuscaRepassesPorIdVendedor(this.SelectedVendedor.get_Id()); + if (observableCollection1 != null && observableCollection1.Count > 0) + { + foreach (Repasse repasse1 in observableCollection1) + { + if (!this.Repasses.Any((Repasse repasse) => { + long? nullable; + long? nullable1; + long? nullable2; + bool id; + if (repasse1.get_Id() != repasse.get_Id()) + { + return false; + } + TipoRepasse? tipo = repasse1.get_Tipo(); + TipoRepasse? tipo1 = repasse.get_Tipo(); + if (tipo.GetValueOrDefault() == tipo1.GetValueOrDefault() & tipo.HasValue == tipo1.HasValue && !(repasse1.get_ValorNovo() != repasse.get_ValorNovo()) && !(repasse1.get_ValorRenovacao() != repasse.get_ValorRenovacao())) + { + TipoIncidencia? incidencia = repasse1.get_Incidencia(); + TipoIncidencia? incidencia1 = repasse.get_Incidencia(); + if (incidencia.GetValueOrDefault() == incidencia1.GetValueOrDefault() & incidencia.HasValue == incidencia1.HasValue) + { + FormaRepasse? forma = repasse1.get_Forma(); + FormaRepasse? forma1 = repasse.get_Forma(); + if (forma.GetValueOrDefault() == forma1.GetValueOrDefault() & forma.HasValue == forma1.HasValue) + { + BaseRepasse? @base = repasse1.get_Base(); + BaseRepasse? base1 = repasse.get_Base(); + if (@base.GetValueOrDefault() == base1.GetValueOrDefault() & @base.HasValue == base1.HasValue) + { + long? seguradora = repasse1.get_Seguradora(); + long? seguradora1 = repasse.get_Seguradora(); + if (seguradora.GetValueOrDefault() == seguradora1.GetValueOrDefault() & seguradora.HasValue == seguradora1.HasValue) + { + if (repasse1.get_Ramo() == null) + { + Ramo ramo = repasse.get_Ramo(); + id = (ramo != null ? ramo.get_Id() != (long)0 : true); + if (!id) + { + return false; + } + } + Ramo ramo1 = repasse1.get_Ramo(); + if (ramo1 != null) + { + nullable1 = new long?(ramo1.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + seguradora1 = nullable1; + Ramo ramo2 = repasse.get_Ramo(); + if (ramo2 != null) + { + nullable2 = new long?(ramo2.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + seguradora = nullable2; + return !(seguradora1.GetValueOrDefault() == seguradora.GetValueOrDefault() & seguradora1.HasValue == seguradora.HasValue); + } + } + } + } + } + return true; + })) + { + continue; + } + if (await this._servico.BuscarVendedorParcela(repasse1.get_Id()).Count > 1) + { + keyValuePairs.Add(new KeyValuePair("REPASSE", string.Format("O REPASSE, DE ID {0}, NÃO PODE SER ALTERADO POIS JÁ ESTÁ CADASTRADO EM ALGUM DOCUMENTO!", repasse1.get_Id()))); + } + } + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + + private async void WorkOnSelectedVendedor(Vendedor value, bool registrar = true) + { + Vendedor vendedor; + long? nullable; + bool corretora; + bool flag; + object nome; + object obj; + VendedorViewModel vendedorViewModel = this; + vendedor = (value == null || value.get_Id() == 0 ? this.CancelVendedor : (Vendedor)value.Clone()); + vendedorViewModel.CancelVendedor = vendedor; + if (value != null && value.get_Id() != 0) + { + base.Loading(true); + this.Repasses = new ObservableCollection((IEnumerable)await this._servico.BuscaRepassesPorIdVendedor(value.get_Id())); + this.Telefones = new ObservableCollection((IEnumerable)await this._servico.BuscarTelefonesAsync(value.get_Id())); + base.Loading(false); + if (this.LastAccessId != value.get_Id() || this.LastAccessTela != 15) + { + if (registrar) + { + VendedorViewModel vendedorViewModel1 = this; + string str = string.Concat("ACESSOU VENDEDOR \"", value.get_Nome(), "\""); + long id = value.get_Id(); + TipoTela? nullable1 = new TipoTela?(15); + object[] agencia = new object[] { value.get_Id(), Recursos.Empresas.First((Empresa x) => x.get_Id() == (value.get_IdEmpresa() == 0 ? (long)1 : value.get_IdEmpresa())).get_Nome(), value.get_Documento(), null, null, null, null, null }; + Banco banco = value.get_Banco(); + if (banco != null) + { + nome = banco.get_Nome(); + } + else + { + nome = null; + } + agencia[3] = nome; + agencia[4] = value.get_Agencia(); + agencia[5] = value.get_Conta(); + agencia[6] = value.get_Desconto(); + obj = (value.get_Ativo() ? "SIM" : "NÃO"); + agencia[7] = obj; + vendedorViewModel1.RegistrarAcao(str, id, nullable1, string.Format("ID: {0}\nFILIAL DO VENDEDOR: {1}\nDOCUMENTO: {2}\nBANCO: {3}\nAGÊNCIA: {4}\nCONTA: {5}\nDESCONTO: {6:N2}\nATIVO: {7}", agencia)); + } + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 15; + Vendedor selectedVendedor = this.SelectedVendedor; + if (selectedVendedor != null) + { + nullable = new long?(selectedVendedor.get_Id()); + } + else + { + nullable = null; + } + long? nullable2 = nullable; + long num = value.get_Id(); + if (nullable2.GetValueOrDefault() != num | !nullable2.HasValue) + { + this.SelectedVendedor = this.VendedoresFiltrados.FirstOrDefault((Vendedor x) => x.get_Id() == value.get_Id()); + } + VendedorViewModel vendedorViewModel2 = this; + Vendedor selectedVendedor1 = this.SelectedVendedor; + if (selectedVendedor1 != null) + { + corretora = selectedVendedor1.get_Corretora(); + } + else + { + corretora = false; + } + vendedorViewModel2.VisualizacaoPropriaCorretora = (corretora ? Visibility.Visible : Visibility.Collapsed); + if (Recursos.Usuario.get_Id() == 0) + { + Vendedor vendedor1 = this.SelectedVendedor; + if (vendedor1 != null) + { + flag = vendedor1.get_Corretora(); + } + else + { + flag = false; + } + if (!flag) + { + this._alterarPermissEnabled = false; + base.EnableAlterar = false; + } + else + { + this._alterarPermissEnabled = true; + base.EnableAlterar = true; + } + } + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/BancosContasViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/BancosContasViewModel.cs new file mode 100644 index 0000000..e83a4eb --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/BancosContasViewModel.cs @@ -0,0 +1,604 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows.Media; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class BancosContasViewModel : BaseFinanceiroViewModel + { + private readonly BancosContasServico _bancosContasServico; + + public Gestor.Model.Domain.Financeiro.BancosContas CancelBancosContas; + + private long _ultimoId; + + private Gestor.Model.Domain.Financeiro.BancosContas _selectedBancosContas; + + private SolidColorBrush _corDoSaldo = new SolidColorBrush(Colors.Green); + + private ObservableCollection _bancosContasFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private ObservableCollection _saldos = new ObservableCollection(); + + private bool _habilitarFecharSaldo; + + private Saldo _selectedSaldo = new Saldo(); + + private string _saldoAtual; + + private decimal? _valorAbertura; + + private DateTime? _dataAbertura; + + private bool _incluindo; + + public List BancosContas + { + get; + set; + } + + public ObservableCollection BancosContasFiltrados + { + get + { + return this._bancosContasFiltrados; + } + set + { + this._bancosContasFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("BancosContasFiltrados"); + } + } + + public SolidColorBrush CorDoSaldo + { + get + { + return this._corDoSaldo; + } + set + { + this._corDoSaldo = value; + base.OnPropertyChanged("CorDoSaldo"); + } + } + + public DateTime? DataAbertura + { + get + { + return this._dataAbertura; + } + set + { + this._dataAbertura = value; + base.OnPropertyChanged("DataAbertura"); + } + } + + public bool HabilitarFecharSaldo + { + get + { + return this._habilitarFecharSaldo; + } + set + { + this._habilitarFecharSaldo = value; + base.OnPropertyChanged("HabilitarFecharSaldo"); + } + } + + public bool Incluindo + { + get + { + return this._incluindo; + } + set + { + this._incluindo = value; + base.OnPropertyChanged("Incluindo"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public string SaldoAtual + { + get + { + return this._saldoAtual; + } + set + { + this._saldoAtual = value; + base.OnPropertyChanged("SaldoAtual"); + } + } + + public ObservableCollection Saldos + { + get + { + return this._saldos; + } + set + { + this._saldos = value; + if (value != null && value.Count > 0) + { + this.SelectedSaldo = value.FirstOrDefault((Saldo x) => !x.get_DataFinal().HasValue); + if (this.SelectedSaldo == null) + { + this.UltimoSladoNaoAberto(); + } + } + base.OnPropertyChanged("Saldos"); + } + } + + public Gestor.Model.Domain.Financeiro.BancosContas SelectedBancosContas + { + get + { + return this._selectedBancosContas; + } + set + { + long? nullable; + this._selectedBancosContas = value; + this.CarregarSaldos(value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + this.Incluindo = (value == null ? false : value.get_Id() == (long)0); + base.OnPropertyChanged("SelectedBancosContas"); + } + } + + public Saldo SelectedSaldo + { + get + { + return this._selectedSaldo; + } + set + { + bool id; + this._selectedSaldo = value; + if (value == null || value.get_DataFinal().HasValue) + { + id = false; + } + else + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + } + this.HabilitarFecharSaldo = id; + base.OnPropertyChanged("SelectedSaldo"); + Saldo selectedSaldo = this.SelectedSaldo; + if (selectedSaldo == null) + { + return; + } + selectedSaldo.Initialize(); + } + } + + public decimal? ValorAbertura + { + get + { + return this._valorAbertura; + } + set + { + this._valorAbertura = value; + base.OnPropertyChanged("ValorAbertura"); + } + } + + public BancosContasViewModel() + { + this._bancosContasServico = new BancosContasServico(); + this.Seleciona(); + } + + public async Task CalcularValor() + { + decimal? valorFinal = await this._bancosContasServico.FecharSaldo(this.SelectedSaldo).get_ValorFinal(); + return valorFinal.GetValueOrDefault(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + if (this.SelectedBancosContas.get_Id() > (long)0) + { + await this.SelecionaBancosDeContas(); + } + BancosContasViewModel bancosContasViewModel = this; + Gestor.Model.Domain.Financeiro.BancosContas bancosConta = this.BancosContasFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.BancosContas x) => x.get_Id() == this._ultimoId); + if (bancosConta == null) + { + bancosConta = this.BancosContasFiltrados.FirstOrDefault(); + } + bancosContasViewModel.SelecionaBancosContas(bancosConta); + base.Alterar(false); + base.Loading(false); + } + + public async void CarregarSaldos(Gestor.Model.Domain.Financeiro.BancosContas banco) + { + if (banco != null && banco.get_Id() != 0) + { + List saldos = await this._bancosContasServico.BuscarSaldos(banco.get_Id()); + this.CorDoSaldo = new SolidColorBrush(Colors.Green); + this.SaldoAtual = string.Empty; + BancosContasViewModel observableCollection = this; + List saldos1 = saldos; + observableCollection.Saldos = new ObservableCollection( + from x in saldos1 + orderby x.get_DataInicio() descending + select x); + if (this.Saldos.FirstOrDefault() != null) + { + Saldo saldo = new Saldo(); + saldo.set_Conta(this.Saldos.First().get_Conta()); + saldo.set_ValorInicio(this.Saldos.First().get_ValorInicio()); + saldo.set_DataInicio(this.Saldos.First().get_DataInicio()); + saldo.set_DataFinal(new DateTime?(Funcoes.GetNetworkTime())); + Saldo saldo1 = saldo; + saldo1 = await this._bancosContasServico.FecharSaldo(saldo1); + decimal? valorFinal = saldo1.get_ValorFinal(); + decimal num = new decimal(); + if ((valorFinal.GetValueOrDefault() < num) & valorFinal.HasValue) + { + this.CorDoSaldo = new SolidColorBrush(Colors.Red); + } + valorFinal = saldo1.get_ValorFinal(); + this.SaldoAtual = string.Format("SALDO: {0:c}", Math.Round(valorFinal.GetValueOrDefault(), 2)); + } + } + } + + public async void Excluir() + { + if (this.SelectedBancosContas != null && this.SelectedBancosContas.get_Id() != 0) + { + if (await (new BaseServico()).BancosContasUtilizado(this.SelectedBancosContas.get_Id())) + { + await base.ShowMessage("NÃO PODE SER EXCLUÍDO POIS ESTÁ SENDO UTILIZADO EM UM LANÇAMENTO.", "OK", "", false); + } + else if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR A CONTA ", this.SelectedBancosContas.get_Descricao(), " PERMANENTEMENTE?"), "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._bancosContasServico.Delete(this.SelectedBancosContas)) + { + await this.SelecionaBancosDeContas(); + base.Loading(false); + base.ToggleSnackBar("CONTA EXCLUÍDA COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public async void ExcluirSaldo() + { + if (this.SelectedSaldo != null && this.SelectedSaldo.get_Id() != 0) + { + if (this.Saldos.Count <= 1) + { + await base.ShowMessage("NÃO É POSSÍVEL EXCLUIR O SALDO INICIAL DA CONTA.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA REALMENTE EXCLUIR O SALDO PERMANENTEMENTE?", "SIM", "NÃO", false)) + { + base.Loading(true); + Saldo saldo = this.Saldos.FirstOrDefault((Saldo x) => { + DateTime? dataFinal = x.get_DataFinal(); + DateTime? dataInicio = this.SelectedSaldo.get_DataInicio(); + if (dataFinal.HasValue != dataInicio.HasValue) + { + return false; + } + if (!dataFinal.HasValue) + { + return true; + } + return dataFinal.GetValueOrDefault() == dataInicio.GetValueOrDefault(); + }); + if (saldo != null) + { + saldo.set_DataFinal(null); + saldo.set_ValorFinal(null); + await this._bancosContasServico.Save(saldo); + if (!this._bancosContasServico.Sucesso) + { + base.Loading(false); + } + else if (await this._bancosContasServico.DeleteSaldo(this.SelectedSaldo)) + { + this.CarregarSaldos(this.SelectedBancosContas); + base.Loading(false); + base.ToggleSnackBar("SALDO EXCLUÍDO COM SUCESSO", true); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + else + { + base.Loading(false); + await base.ShowMessage("NÃO É POSSÍVEL EXCLUIR O SALDO DA CONTA.", "OK", "", false); + } + } + } + } + + public async Task FecharSaldo() + { + this.SelectedSaldo = await this._bancosContasServico.Save(this.SelectedSaldo); + if (this._bancosContasServico.Sucesso) + { + DateTime? dataFinal = this.SelectedSaldo.get_DataFinal(); + if (dataFinal.HasValue) + { + decimal? valorFinal = this.SelectedSaldo.get_ValorFinal(); + if (valorFinal.HasValue) + { + Saldo saldo = new Saldo(); + saldo.set_Conta(this.SelectedSaldo.get_Conta()); + dataFinal = null; + saldo.set_DataFinal(dataFinal); + dataFinal = this.SelectedSaldo.get_DataFinal(); + saldo.set_DataInicio(new DateTime?(dataFinal.Value)); + valorFinal = null; + saldo.set_ValorFinal(valorFinal); + valorFinal = this.SelectedSaldo.get_ValorFinal(); + saldo.set_ValorInicio(valorFinal.Value); + await this._bancosContasServico.Save(saldo); + if (!this._bancosContasServico.Sucesso) + { + return; + } + } + } + this.CarregarSaldos(this.SelectedBancosContas); + base.ToggleSnackBar("SALDO FECHADO COM SUCESSO", true); + } + } + + internal async Task> Filtrar(string value) + { + List bancosContas = await Task.Run>(() => this.FiltrarBancosContas(value)); + return bancosContas; + } + + public List FiltrarBancosContas(string filter) + { + this.BancosContasFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.BancosContas) : new ObservableCollection( + from x in this.BancosContas + where Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ativo() descending, x.get_Descricao() + select x)); + return this.BancosContasFiltrados.ToList(); + } + + public void Incluir() + { + this._ultimoId = this.SelectedBancosContas.get_Id(); + this.DataAbertura = null; + this.ValorAbertura = new decimal?(new decimal()); + this.SaldoAtual = ""; + Gestor.Model.Domain.Financeiro.BancosContas bancosConta = new Gestor.Model.Domain.Financeiro.BancosContas(); + bancosConta.set_Ativo(true); + this.SelectedBancosContas = bancosConta; + this.Saldos = new ObservableCollection(); + this.SelectedSaldo = null; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + Gestor.Model.Domain.Financeiro.BancosContas bancosConta; + List> keyValuePairs1 = this.SelectedBancosContas.Validate(); + keyValuePairs1.AddRange(this.Validate()); + if (keyValuePairs1.Count <= 0) + { + bancosConta = await this._bancosContasServico.Save(this.SelectedBancosContas); + if (this._bancosContasServico.Sucesso) + { + if (this.SelectedBancosContas.get_Id() == 0 && this.DataAbertura.HasValue && this.ValorAbertura.HasValue) + { + Saldo saldo = new Saldo(); + saldo.set_Conta(bancosConta); + saldo.set_DataInicio(new DateTime?(this.DataAbertura.Value)); + saldo.set_ValorInicio(this.ValorAbertura.Value); + await this._bancosContasServico.Save(saldo); + if (!this._bancosContasServico.Sucesso) + { + keyValuePairs = null; + bancosConta = null; + return keyValuePairs; + } + } + await this.SelecionaBancosDeContas(); + this.SelecionaBancosContas(bancosConta); + Recursos.BancosContas = this.BancosContas; + base.Alterar(false); + base.ToggleSnackBar("CONTA SALVA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + bancosConta = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(26); + await this.SelecionaBancosDeContas(); + base.Loading(false); + } + + public void SelecionaBancosContas(Gestor.Model.Domain.Financeiro.BancosContas bancosContas) + { + base.Loading(true); + this.SelectedBancosContas = this.BancosContasFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.BancosContas x) => x.get_Id() == bancosContas.get_Id()); + base.Loading(false); + } + + private async Task SelecionaBancosDeContas() + { + base.Loading(true); + List bancosContas = await this._bancosContasServico.BuscarBancos(); + BancosContasViewModel list = this; + List bancosContas1 = bancosContas; + IOrderedEnumerable ativo = + from x in bancosContas1 + orderby x.get_Ativo() descending + select x; + list.BancosContas = ativo.ThenBy((Gestor.Model.Domain.Financeiro.BancosContas x) => x.get_Descricao()).ToList(); + this.BancosContasFiltrados = new ObservableCollection(this.BancosContas); + if (this.BancosContasFiltrados.Count <= 0) + { + this.SelectedBancosContas = new Gestor.Model.Domain.Financeiro.BancosContas(); + this.Saldos = new ObservableCollection(); + this.DataAbertura = null; + this.ValorAbertura = new decimal?(new decimal()); + this.SaldoAtual = ""; + base.Alterar(false); + base.EnableMenu = false; + } + else + { + this.SelecionaBancosContas(this.BancosContasFiltrados.First()); + } + Recursos.BancosContas = bancosContas; + base.Loading(false); + } + + private async void UltimoSladoNaoAberto() + { + Saldo saldo = this.Saldos.ToList().Find((Saldo x) => { + DateTime? dataInicio = x.get_DataInicio(); + DateTime? nullable = this.Saldos.Max((Saldo r) => r.get_DataInicio()); + if (dataInicio.HasValue != nullable.HasValue) + { + return false; + } + if (!dataInicio.HasValue) + { + return true; + } + return dataInicio.GetValueOrDefault() == nullable.GetValueOrDefault(); + }); + DateTime? dataFinal = saldo.get_DataFinal(); + bool hasValue = dataFinal.HasValue; + if (hasValue) + { + hasValue = await base.ShowMessage("O ÚLTIMO SALDO NÃO ESTÁ ABERTO. DESEJA ABRÍ-LO AGORA?", "SIM", "NÃO", false); + } + if (hasValue) + { + dataFinal = null; + saldo.set_DataFinal(dataFinal); + saldo.set_ValorFinal(null); + this.SelectedSaldo = await this._bancosContasServico.Save(saldo); + this.SelectedBancosContas = this.SelectedBancosContas; + } + saldo = null; + } + + public List> Validate() + { + List> keyValuePairs = new List>(); + if (this.BancosContas.Where((Gestor.Model.Domain.Financeiro.BancosContas x) => { + if (x.get_Descricao() != this.SelectedBancosContas.get_Descricao()) + { + return false; + } + return x.get_Id() != this.SelectedBancosContas.get_Id(); + }).Any()) + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs, "Descricao|DESCRIÇÃO", "NÃO É POSSÍVEL SALVAR MAIS DE UMA CONTA COM A MESMA DESCRIÇÃO.", true); + } + if (this.SelectedBancosContas.get_Id() == 0) + { + if (!this.DataAbertura.HasValue) + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs, "DataAbertura|ABERTURA", "É NECESSÁRIO PREENCHER A DATA DE ABERTURA DA CONTA.", true); + } + else if (DateTime.Compare(this.DataAbertura.Value, new DateTime(1753, 1, 1)) < 0 || DateTime.Compare(this.DataAbertura.Value, new DateTime(9999, 12, 31)) > 0) + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs, "DataAbertura|ABERTURA", "DATA INVÁLIDA", true); + } + if (!this.ValorAbertura.HasValue) + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs, "ValorAbertura|VALOR", "É NECESSÁRIO PREENCHER O VALOR DE ABERTURA DA CONTA.", true); + } + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/CentroDeCustoViewmodel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/CentroDeCustoViewmodel.cs new file mode 100644 index 0000000..ef57541 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/CentroDeCustoViewmodel.cs @@ -0,0 +1,255 @@ +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class CentroDeCustoViewmodel : BaseFinanceiroViewModel + { + private readonly CentroServico _centroServico; + + private ObservableCollection _centrosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private Centro _selectedCentro; + + private bool _ativo; + + private long _ultimoId; + + public Centro CancelCentro; + + public bool Ativo + { + get + { + return this._ativo; + } + set + { + this._ativo = bool.Parse(value.ToString()); + base.OnPropertyChanged("Ativo"); + } + } + + public List Centros + { + get; + set; + } + + public ObservableCollection CentrosFiltrados + { + get + { + return this._centrosFiltrados; + } + set + { + this._centrosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("CentrosFiltrados"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Centro SelectedCentro + { + get + { + return this._selectedCentro; + } + set + { + this._selectedCentro = value; + if (value.get_Id() > (long)0) + { + this._ultimoId = value.get_Id(); + } + base.VerificarEnables(new long?(value.get_Id())); + base.OnPropertyChanged("SelectedCentro"); + } + } + + public CentroDeCustoViewmodel() + { + this._centroServico = new CentroServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + base.Alterar(false); + if (this.SelectedCentro.get_Id() > (long)0) + { + await this.SelecionaCentro(); + } + await this.SelecionaCentro(this.CentrosFiltrados.FirstOrDefault((Centro x) => x.get_Id() == this._ultimoId)); + base.Loading(false); + } + + public async Task> Filtrar(string value) + { + List centros = await Task.Run>(() => this.FiltrarCentro(value)); + return centros; + } + + public List FiltrarCentro(string filter) + { + this.CentrosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Centros) : new ObservableCollection( + from x in this.Centros + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby this.Ativo descending, x.get_Descricao() + select x)); + return this.CentrosFiltrados.ToList(); + } + + public void Incluir() + { + long id; + Centro selectedCentro = this.SelectedCentro; + if (selectedCentro != null) + { + id = selectedCentro.get_Id(); + } + else + { + id = (long)0; + } + this._ultimoId = id; + Centro centro = new Centro(); + centro.set_Ativo(true); + this.SelectedCentro = centro; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedCentro.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + this.SelectedCentro = await this._centroServico.Save(this.SelectedCentro); + if (this._centroServico.Sucesso) + { + await this.SelecionaCentro(); + await this.SelecionaCentro(this.CentrosFiltrados.First((Centro x) => x.get_Id() == this.SelectedCentro.get_Id())); + base.Alterar(false); + base.ToggleSnackBar("CENTRO DE CUSTO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(29); + await this.SelecionaCentro(); + await this.SelecionaCentro(this.CentrosFiltrados.FirstOrDefault()); + base.Loading(false); + } + + private async Task SelecionaCentro(Centro centros) + { + if (centros != null) + { + base.Loading(true); + List centros1 = await (new BaseServico()).BuscarCentroAsync(); + DomainBase.Copy(this.CentrosFiltrados.First((Centro x) => x.get_Id() == centros.get_Id()), centros1.First((Centro x) => x.get_Id() == centros.get_Id())); + this.SelectedCentro = this.CentrosFiltrados.First((Centro x) => x.get_Id() == centros.get_Id()); + base.Loading(false); + } + else + { + base.Alterar(false); + base.EnableMenu = false; + base.EnableAlterar = false; + } + } + + private async Task SelecionaCentro() + { + List centros = await (new BaseServico()).BuscarCentroAsync(); + CentroDeCustoViewmodel list = this; + List centros1 = centros; + IOrderedEnumerable ativo = + from x in centros1 + orderby x.get_Ativo() descending + select x; + IOrderedEnumerable centros2 = ativo.ThenBy((Centro x) => x.get_Descricao()); + list.Centros = centros2.ThenBy((Centro x) => x.get_Descricao()).ToList(); + this.CentrosFiltrados = new ObservableCollection(this.Centros); + } + + public void SelecionaCentroDeCusto(Centro centro) + { + this.SelectedCentro = this.CentrosFiltrados.First((Centro x) => x.get_Id() == centro.get_Id()); + } + + public async Task>> Validate() + { + List> keyValuePairs = new List>(); + bool flag = true; + List centros = await (new BaseServico()).BuscarCentroAsync(); + if (centros.Count > 0) + { + centros.ForEach((Centro x) => { + if (x.get_Id() == this.SelectedCentro.get_Id()) + { + return; + } + if (x.get_Descricao() == this.SelectedCentro.get_Descricao() && x.get_IdEmpresa() == this.SelectedCentro.get_IdEmpresa()) + { + flag = false; + } + }); + } + if (!flag) + { + keyValuePairs.Add(new KeyValuePair("Descricao", "UM CENTRO COM ESSE NOME JÁ EXISTE.")); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/ContasDialogModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/ContasDialogModel.cs new file mode 100644 index 0000000..8e112a4 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/ContasDialogModel.cs @@ -0,0 +1,48 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Financeiro; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class ContasDialogModel : BaseViewModel + { + private ObservableCollection _contasFiltradas; + + private BancosContas _conta; + + public BancosContas Conta + { + get + { + return this._conta; + } + set + { + this._conta = value; + base.OnPropertyChanged("Conta"); + } + } + + public ObservableCollection ContasFiltradas + { + get + { + return this._contasFiltradas; + } + set + { + this._contasFiltradas = value; + base.OnPropertyChanged("ContasFiltradas"); + } + } + + public ContasDialogModel(List contas) + { + this.ContasFiltradas = new ObservableCollection(contas); + this.Conta = this.ContasFiltradas.FirstOrDefault(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/CopiarClienteViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/CopiarClienteViewModel.cs new file mode 100644 index 0000000..3bde895 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/CopiarClienteViewModel.cs @@ -0,0 +1,28 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Seguros; +using System; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class CopiarClienteViewModel : BaseSegurosViewModel + { + private Cliente _selectedCliente; + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public CopiarClienteViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/ExtratoContaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/ExtratoContaViewModel.cs new file mode 100644 index 0000000..114d175 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/ExtratoContaViewModel.cs @@ -0,0 +1,552 @@ +using ClosedXML.Excel; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; +using System.Windows.Media; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class ExtratoContaViewModel : BaseFinanceiroViewModel + { + private Geometry _maximizeRestore = Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]); + + private string _head; + + private readonly FinanceiroServico _servico; + + private ObservableCollection _contas; + + private ObservableCollection _contasFilter; + + private Gestor.Model.Domain.Financeiro.BancosContas _selectedConta; + + private DateTime? _inicio; + + private DateTime? _fim; + + private static ObservableCollection _bancosContas; + + private string _selectedBancosContas; + + private ObservableCollection _extrato; + + private bool _saldoFinal; + + private bool _naoHaDados; + + public ObservableCollection BancosContas + { + get + { + return ExtratoContaViewModel._bancosContas; + } + set + { + ExtratoContaViewModel._bancosContas = value; + base.OnPropertyChanged("BancosContas"); + } + } + + public ObservableCollection Contas + { + get + { + return this._contas; + } + set + { + this._contas = value; + base.OnPropertyChanged("Contas"); + } + } + + public ObservableCollection ContasFilter + { + get + { + return this._contasFilter; + } + set + { + this._contasFilter = value; + base.OnPropertyChanged("ContasFilter"); + } + } + + public ObservableCollection Extrato + { + get + { + return this._extrato; + } + set + { + this._extrato = value; + this.NaoHaDados = (value == null ? true : value.Count == 0); + base.OnPropertyChanged("Extrato"); + } + } + + public DateTime? Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public DateTime? Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public Geometry MaximizeRestore + { + get + { + return this._maximizeRestore; + } + set + { + this._maximizeRestore = value; + base.OnPropertyChanged("MaximizeRestore"); + } + } + + public bool NaoHaDados + { + get + { + return this._naoHaDados; + } + set + { + this._naoHaDados = value; + base.OnPropertyChanged("NaoHaDados"); + } + } + + public bool SaldoFinal + { + get + { + return this._saldoFinal; + } + set + { + this._saldoFinal = value; + base.OnPropertyChanged("SaldoFinal"); + } + } + + public string SelectedBancosContas + { + get + { + return this._selectedBancosContas; + } + set + { + this._selectedBancosContas = value; + if (value == null || this.Contas == null || this.Contas.Count <= 0) + { + return; + } + if (value == "TODOS") + { + this.ContasFilter = this.Contas; + } + else if (value == "ATIVOS") + { + this.ContasFilter = new ObservableCollection(( + from x in this.Contas + where x.get_Ativo() + select x).ToList()); + } + else if (value == "INATIVOS") + { + this.ContasFilter = new ObservableCollection(( + from x in this.Contas + where !x.get_Ativo() + select x).ToList()); + } + base.OnPropertyChanged("SelectedBancosContas"); + } + } + + public Gestor.Model.Domain.Financeiro.BancosContas SelectedConta + { + get + { + return this._selectedConta; + } + set + { + this._selectedConta = value; + base.OnPropertyChanged("SelectedConta"); + } + } + + static ExtratoContaViewModel() + { + ExtratoContaViewModel._bancosContas = new ObservableCollection() + { + "TODOS", + "ATIVOS", + "INATIVOS" + }; + } + + public ExtratoContaViewModel(long id) + { + this._maximizeRestore = Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]); + DateTime date = Funcoes.GetNetworkTime().Date; + int year = date.Year; + date = Funcoes.GetNetworkTime().Date; + this._inicio = new DateTime?(new DateTime(year, date.Month, 1)); + this._fim = new DateTime?(Funcoes.GetNetworkTime()); + this._selectedBancosContas = "TODOS"; + base(); + this._servico = new FinanceiroServico(); + this.BuscaInicial(id); + } + + private async void BuscaInicial(long id) + { + Gestor.Model.Domain.Financeiro.BancosContas bancosConta; + base.Loading(true); + List bancosContas = await (new BancosContasServico()).BuscarBancos(); + ExtratoContaViewModel observableCollection = this; + List bancosContas1 = bancosContas; + observableCollection.Contas = new ObservableCollection( + from x in bancosContas1 + orderby x.get_Descricao() + select x); + ExtratoContaViewModel extratoContaViewModel = this; + List bancosContas2 = bancosContas; + extratoContaViewModel.ContasFilter = new ObservableCollection( + from x in bancosContas2 + orderby x.get_Descricao() + select x); + ExtratoContaViewModel extratoContaViewModel1 = this; + bancosConta = (id > (long)0 ? this.Contas.FirstOrDefault((Gestor.Model.Domain.Financeiro.BancosContas x) => x.get_Id() == id) : this.Contas.FirstOrDefault()); + extratoContaViewModel1.SelectedConta = bancosConta; + await this.GerarRelatorio(); + base.Loading(false); + } + + public async Task GerarExcel() + { + string str; + string str1; + if (this.Extrato == null || this.Extrato.Count == 0) + { + base.ShowMessage("NÃO HÁ DADOS PARA A IMPRESSÃO EM EXCEL", "OK", "", false); + } + else + { + List list = this.Extrato.ToList(); + string tempPath = ""; + str1 = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str1 = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + str1 = null; + return; + } + } + string[] descricao = new string[] { tempPath, "EXTRATO CONTA - ", this.SelectedConta.get_Descricao(), " ", null, null }; + DateTime date = Functions.GetNetworkTime().Date; + descricao[4] = date.ToShortDateString().Replace("/", ""); + descricao[5] = ".xlsx"; + str1 = string.Concat(descricao); + } + XLWorkbook xLWorkbook = new XLWorkbook(); + string str2 = string.Concat("EXTRATO CONTA - ", this.SelectedConta.get_Descricao()); + str = (str2.Length < 30 ? str2 : str2.Substring(0, 30)); + str2 = str; + await Funcoes.GerarXls(xLWorkbook, str2, list, new List()).SaveAs(str1); + Process.Start(str1); + } + str1 = null; + } + + public async Task GerarRelatorio() + { + DateTime? dataInicio; + bool flag; + Sinal sinal; + Sinal sinal1; + string str; + ExtratoContaViewModel.u003cu003ec__DisplayClass52_0 variable; + if (this.SelectedConta != null && this.SelectedConta.get_Id() != 0) + { + DateTime? inicio = this.Inicio; + if (inicio.HasValue) + { + inicio = this.Fim; + if (inicio.HasValue) + { + BancosContasServico bancosContasServico = new BancosContasServico(); + Saldo saldo = await bancosContasServico.BuscarSaldoInicial(this.SelectedConta.get_Id()); + if (saldo != null) + { + dataInicio = saldo.get_DataInicio(); + } + else + { + dataInicio = null; + } + inicio = dataInicio; + DateTime? fim = this.Inicio; + flag = (inicio.HasValue & fim.HasValue ? inicio.GetValueOrDefault() > fim.GetValueOrDefault() : false); + if (!flag) + { + FinanceiroServico financeiroServico = this._servico; + fim = this.Inicio; + DateTime value = fim.Value; + fim = this.Fim; + List extratoContas2 = await financeiroServico.BuscarLancamentosPorConta(value, fim.Value, this.SelectedConta.get_Id()); + List extratoContas3 = extratoContas2; + BancosContasServico bancosContasServico1 = bancosContasServico; + fim = this.Inicio; + Saldo saldo1 = await bancosContasServico1.BuscarSaldo(fim.Value, this.SelectedConta.get_Id()); + if (extratoContas3.Count != 0) + { + if (saldo1 == null) + { + Saldo saldo2 = new Saldo(); + saldo2.set_Conta(this.SelectedConta); + saldo2.set_DataInicio(this.Inicio); + saldo2.set_ValorInicio(decimal.Zero); + saldo1 = saldo2; + } + fim = this.Inicio; + saldo1.set_DataFinal(new DateTime?(fim.Value)); + decimal num1 = new decimal(); + saldo1.set_ValorFinal(new decimal?(num1)); + saldo1 = await bancosContasServico.FecharSaldo(saldo1); + List extratoContas4 = new List(); + ExtratoConta extratoContum2 = new ExtratoConta(); + fim = this.Inicio; + extratoContum2.set_Baixa(new DateTime?(fim.Value)); + extratoContum2.set_Fornecedor("SALDO INICIAL"); + decimal? valorFinal = saldo1.get_ValorFinal(); + extratoContum2.set_Valor(new decimal?(valorFinal.GetValueOrDefault())); + valorFinal = saldo1.get_ValorFinal(); + sinal = (valorFinal.GetValueOrDefault() < decimal.Zero ? 1 : 0); + extratoContum2.set_Sinal(sinal); + extratoContum2.set_Bold(true); + ExtratoConta extratoContum3 = extratoContum2; + extratoContas4.Add(extratoContum3); + decimal? valor = extratoContum3.get_Valor(); + List extratoContas5 = extratoContas3; + IOrderedEnumerable extratoContas6 = + from x in extratoContas5 + orderby x.get_Baixa() + select x; + ( + from x in extratoContas6 + group x by x.get_Baixa()).ToList>().ForEach((IGrouping g) => { + decimal? nullable; + decimal? nullable1; + List list = extratoContas3.Where((ExtratoConta x) => { + DateTime? baixa = x.get_Baixa(); + DateTime? key = g.Key; + if (baixa.HasValue != key.HasValue) + { + return false; + } + if (!baixa.HasValue) + { + return true; + } + return baixa.GetValueOrDefault() == key.GetValueOrDefault(); + }).ToList(); + ExtratoConta extratoContum = new ExtratoConta(); + extratoContum.set_Baixa(g.Key); + extratoContum.set_Fornecedor("SALDO FINAL DO DIA"); + decimal? nullable2 = valor; + List extratoContas = list; + Func u003cu003e9_524 = ExtratoContaViewModel.u003cu003ec.u003cu003e9__52_4; + if (u003cu003e9_524 == null) + { + u003cu003e9_524 = (ExtratoConta x) => x.get_Valor(); + ExtratoContaViewModel.u003cu003ec.u003cu003e9__52_4 = u003cu003e9_524; + } + decimal? nullable3 = extratoContas.Sum(u003cu003e9_524); + if (nullable2.HasValue & nullable3.HasValue) + { + nullable1 = new decimal?(nullable2.GetValueOrDefault() + nullable3.GetValueOrDefault()); + } + else + { + nullable = null; + nullable1 = nullable; + } + extratoContum.set_Valor(nullable1); + nullable2 = valor; + List extratoContas1 = list; + Func u003cu003e9_525 = ExtratoContaViewModel.u003cu003ec.u003cu003e9__52_5; + if (u003cu003e9_525 == null) + { + u003cu003e9_525 = (ExtratoConta x) => x.get_Valor(); + ExtratoContaViewModel.u003cu003ec.u003cu003e9__52_5 = u003cu003e9_525; + } + nullable = extratoContas1.Sum(u003cu003e9_525); + nullable3 = (nullable2.HasValue & nullable.HasValue ? new decimal?(nullable2.GetValueOrDefault() + nullable.GetValueOrDefault()) : null); + decimal num = new decimal(); + extratoContum.set_Sinal(((nullable3.GetValueOrDefault() < num) & nullable3.HasValue ? 1 : 0)); + extratoContum.set_Bold(true); + ExtratoConta extratoContum1 = extratoContum; + if (!this.SaldoFinal) + { + extratoContas4.AddRange(list); + } + extratoContas4.Add(extratoContum1); + valor = extratoContum1.get_Valor(); + }); + List extratoContas7 = extratoContas4; + ExtratoConta extratoContum4 = new ExtratoConta(); + fim = this.Fim; + extratoContum4.set_Baixa(new DateTime?(fim.Value)); + extratoContum4.set_Fornecedor("SALDO FINAL"); + extratoContum4.set_Valor(valor); + valorFinal = valor; + num1 = new decimal(); + sinal1 = ((valorFinal.GetValueOrDefault() < num1) & valorFinal.HasValue ? 1 : 0); + extratoContum4.set_Sinal(sinal1); + extratoContum4.set_Bold(true); + extratoContas7.Add(extratoContum4); + this.Extrato = new ObservableCollection(extratoContas4); + bancosContasServico = null; + } + else + { + this.NaoHaDados = true; + variable = null; + return; + } + } + else + { + ExtratoContaViewModel extratoContaViewModel = this; + string descricao = saldo.get_Conta().get_Descricao(); + fim = saldo.get_DataInicio(); + if (fim.HasValue) + { + str = fim.GetValueOrDefault().ToString("dd/MM/yyyy"); + } + else + { + str = null; + } + extratoContaViewModel.ShowMessage(string.Concat("DATA DE INÍCIO É MENOR QUE A CRIAÇÃO DA CONTA ", descricao, ",\nDATA DE ABERTURA ", str), "OK", "", false); + this.NaoHaDados = true; + variable = null; + return; + } + } + } + } + variable = null; + } + + public void LimparRelatorio() + { + this.Extrato = null; + } + + public async Task Print() + { + DateTime dateTime; + DateTime dateTime1; + string str; + if (this.Extrato == null || this.Extrato.Count == 0) + { + base.ShowMessage("NÃO HÁ DADOS PARA A IMPRESSÃO", "OK", "", false); + } + else + { + string str1 = await Funcoes.GenerateTable(this.Extrato.ToList(), new List(), false, false, "", null); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome(string.Concat("EXTRATO CONTA - ", this.SelectedConta.get_Descricao())); + DateTime? inicio = this.Inicio; + dateTime = (inicio.HasValue ? inicio.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Inicio(dateTime); + inicio = this.Fim; + dateTime1 = (inicio.HasValue ? inicio.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Fim(dateTime1); + TipoRelatorio tipoRelatorio1 = tipoRelatorio; + TipoRelatorio tipoRelatorio2 = tipoRelatorio1; + str = (tipoRelatorio1.get_Nome().Length < 30 ? tipoRelatorio1.get_Nome() : tipoRelatorio1.get_Nome().Substring(0, 30)); + tipoRelatorio2.set_Nome(str); + string str2 = Funcoes.ExportarHtml(tipoRelatorio1, str1, "60", "portrait", false, ""); + string tempPath = Path.GetTempPath(); + string str3 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(tipoRelatorio1.get_Nome(), ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str3, true, Encoding.UTF8); + streamWriter.Write(str2); + streamWriter.Close(); + Process.Start(str3); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/FinanceiroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/FinanceiroViewModel.cs new file mode 100644 index 0000000..630e3db --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/FinanceiroViewModel.cs @@ -0,0 +1,5973 @@ +using ClosedXML.Excel; +using CsQuery.ExtensionMethods; +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Relatorios; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using OfxSharpLib; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class FinanceiroViewModel : BaseFinanceiroViewModel + { + private readonly FinanceiroServico _servico; + + private bool _enableIncluirNovo; + + private bool _enableChanges; + + private SinteticoFinanceiroTipo _sinteticoTipo; + + private Visibility _isVisibleData; + + private Visibility _isVisibleFornecedor = Visibility.Collapsed; + + private Visibility _isVisiblePersonalizado = Visibility.Collapsed; + + private Visibility _isVisibleFiltros = Visibility.Collapsed; + + private Visibility _isVisibleLancamento; + + private Visibility _isvisibleStatus; + + private FiltroLancamento _selectedFiltro; + + private FiltroLancamentoData _selectedFiltroData; + + private StatusLancamento _selectedStatus; + + private StatusLancamento _selectedStatusImportacao = 2; + + private Visibility _botaoSalvarVisibility; + + private DateTime? _inicio = new DateTime?(Funcoes.GetNetworkTime()); + + private DateTime? _fim = new DateTime?(Funcoes.GetNetworkTime().AddDays(7)); + + private Fornecedor _selectedFornecedor; + + private ObservableCollection _saldos = new ObservableCollection(); + + private Saldo _selectedSaldo = new Saldo(); + + private ObservableCollection _lancamentos = new ObservableCollection(); + + private bool _dontSort; + + private ObservableCollection _lancamentosFiltrados = new ObservableCollection(); + + private ObservableCollection _lancamentosFiltradosCopia = new ObservableCollection(); + + private ObservableCollection _lancamentosVinculo = new ObservableCollection(); + + private Lancamento _lancamentoVinculo; + + private Lancamento _selectedLancamento; + + private Fornecedor _fornecedorInclusao; + + private long _idLancamento; + + private string _historico; + + private string _observacao; + + private string _documento; + + private string _complemento; + + private string _competencia; + + private int _parcela; + + private double _dropDownHeight; + + private int _parcelas; + + public bool VencimentoAlterado; + + private DateTime _vencimento; + + private DateTime? _baixa; + + private DateTime? _pagamento; + + private decimal _valor; + + private decimal? _valorPago; + + private Gestor.Model.Common.Sinal _sinal; + + private Gestor.Model.Domain.Financeiro.Planos _plano; + + private Gestor.Model.Domain.Financeiro.Centro _centro; + + private BancosContas _conta; + + private Gestor.Model.Common.TipoPagamento _tipoPagamento; + + private List _planosFiltro; + + private List _centroFiltro; + + private List _contaFiltro; + + private List _planos; + + private ObservableCollection _planosFiltrados; + + private List _contas; + + private ObservableCollection _contasFiltradas; + + private List _centros; + + private ObservableCollection _centrosFiltrados; + + private ObservableCollection _totalizacao; + + private Visibility _visibilityFornecedor; + + private Visibility _visibilityCentro; + + private Visibility _visibilityConta; + + private Visibility _alterando = Visibility.Collapsed; + + private bool _buscaHabilitada = true; + + private bool _alteracao = true; + + private List _filtroRelatorioPersonalizado; + + private List _filtros; + + private ObservableCollection _personalizadoSelecionado; + + private ObservableCollection _filtroRelatorioSelecionado = new ObservableCollection(); + + private Visibility _visibilitySemValor = Visibility.Collapsed; + + private Gestor.Model.Domain.Relatorios.FiltroPersonalizado _filtro; + + private Type _tipoString = typeof(string); + + private Type _tipoEnum = typeof(Enum); + + private Type _tipoDateTime = typeof(DateTime); + + private Type _tipoDecimal = typeof(decimal); + + private Type _tipoInt = typeof(int); + + private Type _tipoLong = typeof(long); + + private string _valorIncial = ""; + + private string _valorFinal = ""; + + private bool _semValor; + + private List _filtroPersonalizado; + + private ObservableCollection _filtroPersonalizadoSelecionado = new ObservableCollection(); + + private Visibility _visibleFiltros = Visibility.Collapsed; + + private Visibility _visibleOlho = Visibility.Collapsed; + + private bool importando; + + private bool _isExpanded; + + public bool Alteracao + { + get + { + return this._alteracao; + } + set + { + this._alteracao = value; + base.OnPropertyChanged("Alteracao"); + } + } + + public Visibility Alterando + { + get + { + return this._alterando; + } + set + { + this._alterando = value; + base.OnPropertyChanged("Alterando"); + } + } + + public DateTime? Baixa + { + get + { + return this._baixa; + } + set + { + this._baixa = value; + base.OnPropertyChanged("Baixa"); + } + } + + public Visibility BotaoSalvarVisibility + { + get + { + return this._isvisibleStatus; + } + set + { + this._isvisibleStatus = value; + base.OnPropertyChanged("BotaoSalvarVisibility"); + } + } + + public bool BuscaHabilitada + { + get + { + return this._buscaHabilitada; + } + set + { + this._buscaHabilitada = value; + base.OnPropertyChanged("BuscaHabilitada"); + } + } + + private bool Carregar { get; set; } = true; + + public Gestor.Model.Domain.Financeiro.Centro Centro + { + get + { + return this._centro; + } + set + { + this._centro = value; + base.OnPropertyChanged("Centro"); + } + } + + public List CentroFiltro + { + get + { + return this._centroFiltro; + } + set + { + this._centroFiltro = value; + base.OnPropertyChanged("CentroFiltro"); + } + } + + public List Centros + { + get + { + return this._centros; + } + set + { + this._centros = value; + base.OnPropertyChanged("Centros"); + } + } + + public ObservableCollection CentrosFiltrados + { + get + { + return this._centrosFiltrados; + } + set + { + this._centrosFiltrados = value; + base.OnPropertyChanged("CentrosFiltrados"); + } + } + + public string CodigoBanco + { + get; + set; + } + + public string Competencia + { + get + { + return this._competencia; + } + set + { + this._competencia = value; + base.OnPropertyChanged("Competencia"); + } + } + + public string Complemento + { + get + { + return this._complemento; + } + set + { + this._complemento = value; + base.OnPropertyChanged("Complemento"); + } + } + + public BancosContas Conta + { + get + { + return this._conta; + } + set + { + this._conta = value; + base.OnPropertyChanged("Conta"); + } + } + + public List ContaFiltro + { + get + { + return this._contaFiltro; + } + set + { + this._contaFiltro = value; + base.OnPropertyChanged("ContaFiltro"); + } + } + + public List Contas + { + get + { + return this._contas; + } + set + { + this._contas = value; + base.OnPropertyChanged("Contas"); + } + } + + public ObservableCollection ContasFiltradas + { + get + { + return this._contasFiltradas; + } + set + { + this._contasFiltradas = value; + base.OnPropertyChanged("ContasFiltradas"); + } + } + + public string Documento + { + get + { + return this._documento; + } + set + { + this._documento = value; + base.OnPropertyChanged("Documento"); + } + } + + public double DropDownHeight + { + get + { + return this._dropDownHeight; + } + set + { + this._dropDownHeight = value; + base.OnPropertyChanged("DropDownHeight"); + } + } + + public bool EnableChanges + { + get + { + return this._enableChanges; + } + set + { + this._enableChanges = value; + base.OnPropertyChanged("EnableChanges"); + } + } + + public bool EnableIncluirNovo + { + get + { + return this._enableIncluirNovo; + } + set + { + this._enableIncluirNovo = value; + base.OnPropertyChanged("EnableIncluirNovo"); + } + } + + public Gestor.Model.Domain.Relatorios.FiltroPersonalizado Filtro + { + get + { + return this._filtro; + } + set + { + char chr; + this._filtro = value; + this.VisibilitySemValor = (value != null ? Visibility.Visible : Visibility.Collapsed); + base.OnPropertyChanged("Filtro"); + if (value == null) + { + return; + } + string name = value.get_Tipo().Name; + if (name != null) + { + switch (name.Length) + { + case 3: + { + if (name == "int") + { + break; + } + return; + } + case 4: + { + chr = name[0]; + if (chr == 'E') + { + if (name == "Enum") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + else + { + if (chr != 'l') + { + return; + } + if (name == "long") + { + break; + } + return; + } + } + case 5: + { + chr = name[3]; + if (chr == '3') + { + if (name == "int32") + { + break; + } + return; + } + else + { + if (chr != '6') + { + return; + } + if (name == "int64") + { + break; + } + return; + } + } + case 6: + { + if (name != "String") + { + return; + } + this.ValorInicial = ""; + this.ValorFinal = ""; + return; + } + case 7: + { + if (name != "Decimal") + { + return; + } + this.ValorInicial = "0,00"; + this.ValorFinal = "0,00"; + return; + } + case 8: + { + if (name == "DateTime") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + default: + { + return; + } + } + this.ValorInicial = "0"; + this.ValorFinal = "0"; + } + } + } + + public List FiltroPersonalizado + { + get + { + return this._filtroPersonalizado; + } + set + { + this._filtroPersonalizado = value; + base.OnPropertyChanged("FiltroPersonalizado"); + } + } + + public AutoCompleteFilterPredicate FiltroPersonalizadoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_3690 = FinanceiroViewModel.u003cu003ec.u003cu003e9__369_0; + if (u003cu003e9_3690 == null) + { + u003cu003e9_3690 = new AutoCompleteFilterPredicate(FinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Gestor.Model.Domain.Financeiro.FiltroPersonalizado)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + FinanceiroViewModel.u003cu003ec.u003cu003e9__369_0 = u003cu003e9_3690; + } + return u003cu003e9_3690; + } + } + + public ObservableCollection FiltroPersonalizadoSelecionado + { + get + { + return this._filtroPersonalizadoSelecionado; + } + set + { + this._filtroPersonalizadoSelecionado = value; + base.OnPropertyChanged("FiltroPersonalizadoSelecionado"); + } + } + + public ObservableCollection FiltroRelatorioSelecionado + { + get + { + return this._filtroRelatorioSelecionado; + } + set + { + this._filtroRelatorioSelecionado = value; + base.OnPropertyChanged("FiltroRelatorioSelecionado"); + } + } + + public List Filtros + { + get + { + return this._filtros; + } + set + { + this._filtros = value; + base.OnPropertyChanged("Filtros"); + } + } + + public DateTime? Fim + { + get + { + return this._fim; + } + set + { + if (value.HasValue && value.Value < new DateTime(1754, 1, 1)) + { + value = new DateTime?(new DateTime(1754, 1, 1)); + } + if (value.HasValue && value.Value > new DateTime(9999, 12, 31)) + { + value = new DateTime?(new DateTime(9999, 12, 31)); + } + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public Fornecedor FornecedorInclusao + { + get + { + return this._fornecedorInclusao; + } + set + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.Financeiro.FinanceiroViewModel::set_FornecedorInclusao(Gestor.Model.Domain.Financeiro.Fornecedor) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void set_FornecedorInclusao(Gestor.Model.Domain.Financeiro.Fornecedor) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // 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.PropertyDecompiler.DecompileMethod(MethodBody body, MethodSpecificContext& methodContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\PropertyDecompiler.cs:line 347 + // + // mailto: JustDecompilePublicFeedback@telerik.com + + } + } + + public string Historico + { + get + { + return this._historico; + } + set + { + this._historico = value; + base.OnPropertyChanged("Historico"); + } + } + + public long IdLancamento + { + get + { + return this._idLancamento; + } + set + { + this._idLancamento = value; + base.OnPropertyChanged("IdLancamento"); + } + } + + public bool Importando + { + get + { + return this.importando; + } + set + { + this.importando = value; + base.OnPropertyChanged("Importando"); + } + } + + public DateTime? Inicio + { + get + { + return this._inicio; + } + set + { + if (value.HasValue && value.Value < new DateTime(1754, 1, 1)) + { + value = new DateTime?(new DateTime(1754, 1, 1)); + } + if (value.HasValue && value.Value > new DateTime(9999, 12, 31)) + { + value = new DateTime?(new DateTime(9999, 12, 31)); + } + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public Visibility IsVisibleData + { + get + { + return this._isVisibleData; + } + set + { + this._isVisibleData = value; + base.OnPropertyChanged("IsVisibleData"); + } + } + + public Visibility IsVisibleFiltros + { + get + { + return this._isVisibleFiltros; + } + set + { + this._isVisibleFiltros = value; + base.OnPropertyChanged("IsVisibleFiltros"); + } + } + + public Visibility IsVisibleFornecedor + { + get + { + return this._isVisibleFornecedor; + } + set + { + this._isVisibleFornecedor = value; + base.OnPropertyChanged("IsVisibleFornecedor"); + } + } + + public Visibility IsVisibleLancamento + { + get + { + return this._isVisibleLancamento; + } + set + { + this._isVisibleLancamento = value; + base.OnPropertyChanged("IsVisibleLancamento"); + } + } + + public Visibility IsVisiblePersonalizado + { + get + { + return this._isVisiblePersonalizado; + } + set + { + this._isVisiblePersonalizado = value; + base.OnPropertyChanged("IsVisiblePersonalizado"); + } + } + + public Visibility IsvisibleStatus + { + get + { + return this._isvisibleStatus; + } + set + { + this._isvisibleStatus = value; + base.OnPropertyChanged("IsvisibleStatus"); + } + } + + public ObservableCollection Lancamentos + { + get + { + return this._lancamentos; + } + set + { + this._lancamentos = value; + base.OnPropertyChanged("Lancamentos"); + } + } + + private Lancamento LancamentoSelecionado + { + get; + set; + } + + public ObservableCollection LancamentosFiltrados + { + get + { + return this._lancamentosFiltrados; + } + set + { + if (!this._dontSort) + { + Action saveSortLancamentos = Gestor.Application.Actions.Actions.SaveSortLancamentos; + if (saveSortLancamentos != null) + { + saveSortLancamentos(); + } + else + { + } + } + this._lancamentosFiltrados = value; + this.Totalizar(); + base.OnPropertyChanged("LancamentosFiltrados"); + if (!this._dontSort) + { + Action sortLancamentos = Gestor.Application.Actions.Actions.SortLancamentos; + if (sortLancamentos == null) + { + return; + } + sortLancamentos(); + } + } + } + + public ObservableCollection LancamentosFiltradosCopia + { + get + { + return this._lancamentosFiltradosCopia; + } + set + { + this._lancamentosFiltradosCopia = value; + base.OnPropertyChanged("LancamentosFiltradosCopia"); + } + } + + public ObservableCollection LancamentosVinculo + { + get + { + return this._lancamentosVinculo; + } + set + { + this._lancamentosVinculo = value; + base.OnPropertyChanged("LancamentosVinculo"); + } + } + + public Lancamento LancamentoVinculo + { + get + { + return this._lancamentoVinculo; + } + set + { + this._lancamentoVinculo = value; + base.OnPropertyChanged("LancamentoVinculo"); + } + } + + public bool NotImportando + { + get + { + return !this.Importando; + } + } + + public string Observacao + { + get + { + return this._observacao; + } + set + { + this._observacao = value; + base.OnPropertyChanged("Observacao"); + } + } + + public DateTime? Pagamento + { + get + { + return this._pagamento; + } + set + { + this._pagamento = value; + base.OnPropertyChanged("Pagamento"); + } + } + + public int Parcela + { + get + { + return this._parcela; + } + set + { + this._parcela = value; + base.OnPropertyChanged("Parcela"); + } + } + + public int Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + base.OnPropertyChanged("Parcelas"); + } + } + + public ObservableCollection PersonalizadoSelecionado + { + get + { + return this._personalizadoSelecionado; + } + set + { + this._personalizadoSelecionado = value; + base.OnPropertyChanged("PersonalizadoSelecionado"); + } + } + + public Gestor.Model.Domain.Financeiro.Planos Plano + { + get + { + return this._plano; + } + set + { + this._plano = value; + base.OnPropertyChanged("Plano"); + if (value == null || value.get_Id() == 0) + { + return; + } + this.Sinal = (this.importando ? this.Sinal : value.get_Sinal()); + } + } + + public List Planos + { + get + { + return this._planos; + } + set + { + this._planos = value; + base.OnPropertyChanged("Planos"); + } + } + + public ObservableCollection PlanosFiltrados + { + get + { + return this._planosFiltrados; + } + set + { + this._planosFiltrados = value; + base.OnPropertyChanged("PlanosFiltrados"); + } + } + + public List PlanosFiltro + { + get + { + return this._planosFiltro; + } + set + { + this._planosFiltro = value; + base.OnPropertyChanged("PlanosFiltro"); + } + } + + public List RelatorioFiltroPersonalizado + { + get + { + return this._filtroRelatorioPersonalizado; + } + set + { + this._filtroRelatorioPersonalizado = value; + base.OnPropertyChanged("RelatorioFiltroPersonalizado"); + } + } + + public ObservableCollection Saldos + { + get + { + return this._saldos; + } + set + { + this._saldos = value; + base.OnPropertyChanged("Saldos"); + } + } + + private bool Salvando + { + get; + set; + } + + public FiltroLancamento SelectedFiltro + { + get + { + return this._selectedFiltro; + } + set + { + this._selectedFiltro = value; + this.LimparLancamentos(); + base.OnPropertyChanged("SelectedFiltro"); + } + } + + public FiltroLancamentoData SelectedFiltroData + { + get + { + return this._selectedFiltroData; + } + set + { + this._selectedFiltroData = value; + this.LimparLancamentos(); + base.OnPropertyChanged("SelectedFiltroData"); + } + } + + public Fornecedor SelectedFornecedor + { + get + { + return this._selectedFornecedor; + } + set + { + this._selectedFornecedor = value; + this.LimparLancamentos(); + base.OnPropertyChanged("SelectedFornecedor"); + } + } + + public Lancamento SelectedLancamento + { + get + { + return this._selectedLancamento; + } + set + { + bool id; + bool flag; + bool id1; + if (value != null && value.get_Id() != 0) + { + this.IdLancamento = value.get_Id(); + } + else if (this.importando) + { + this.IdLancamento = (long)0; + } + if (value == null || value.get_Id() <= (long)0) + { + id = false; + } + else + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + } + this.EnableIncluirNovo = id; + this._selectedLancamento = value; + if (value == null || value.get_Id() <= (long)0) + { + flag = false; + } + else + { + Usuario usuario1 = Recursos.Usuario; + if (usuario1 != null) + { + flag = usuario1.get_Id() > (long)0; + } + else + { + flag = false; + } + } + base.EnableButtons = flag; + Usuario usuario2 = Recursos.Usuario; + if (usuario2 != null) + { + id1 = usuario2.get_Id() > (long)0; + } + else + { + id1 = false; + } + this.EnableChanges = id1; + this.Alteracao = (value == null ? false : value.get_Controle().get_Id() > (long)0); + base.OnPropertyChanged("SelectedLancamento"); + this.Feed(value); + if (value == null || value.get_Id() == 0) + { + return; + } + this.LancamentoSelecionado = value; + } + } + + public Saldo SelectedSaldo + { + get + { + return this._selectedSaldo; + } + set + { + this._selectedSaldo = value; + base.OnPropertyChanged("SelectedSaldo"); + } + } + + public StatusLancamento SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + this.LimparLancamentos(); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public StatusLancamento SelectedStatusImportacao + { + get + { + return this._selectedStatusImportacao; + } + set + { + this._selectedStatusImportacao = value; + base.OnPropertyChanged("SelectedStatusImportacao"); + } + } + + public bool SemValor + { + get + { + return this._semValor; + } + set + { + this._semValor = value; + if (value) + { + this.ValorInicial = null; + this.ValorFinal = null; + } + base.OnPropertyChanged("SemValor"); + } + } + + public Gestor.Model.Common.Sinal Sinal + { + get + { + return this._sinal; + } + set + { + this._sinal = value; + base.OnPropertyChanged("Sinal"); + } + } + + public SinteticoFinanceiroTipo SinteticoTipo + { + get + { + return this._sinteticoTipo; + } + set + { + this._sinteticoTipo = value; + base.OnPropertyChanged("SinteticoTipo"); + } + } + + public Type TipoDateTime + { + get + { + return this._tipoDateTime; + } + set + { + this._tipoDateTime = value; + base.OnPropertyChanged("TipoDateTime"); + } + } + + public Type TipoDecimal + { + get + { + return this._tipoDecimal; + } + set + { + this._tipoDecimal = value; + base.OnPropertyChanged("TipoDecimal"); + } + } + + public Type TipoEnum + { + get + { + return this._tipoEnum; + } + set + { + this._tipoEnum = value; + base.OnPropertyChanged("TipoEnum"); + } + } + + public Type TipoInt + { + get + { + return this._tipoInt; + } + set + { + this._tipoInt = value; + base.OnPropertyChanged("TipoInt"); + } + } + + public Type TipoLong + { + get + { + return this._tipoLong; + } + set + { + this._tipoLong = value; + base.OnPropertyChanged("TipoLong"); + } + } + + public Gestor.Model.Common.TipoPagamento TipoPagamento + { + get + { + return this._tipoPagamento; + } + set + { + this._tipoPagamento = value; + base.OnPropertyChanged("TipoPagamento"); + } + } + + public Type TipoString + { + get + { + return this._tipoString; + } + set + { + this._tipoString = value; + base.OnPropertyChanged("TipoString"); + } + } + + public ObservableCollection Totalizacao + { + get + { + return this._totalizacao; + } + set + { + this._totalizacao = value; + base.OnPropertyChanged("Totalizacao"); + } + } + + public Func>> ValidationEvent + { + get + { + return new Func>>(this.ValidateIncluir); + } + } + + public decimal Valor + { + get + { + return this._valor; + } + set + { + this._valor = value; + if (this.Vencimento <= Funcoes.GetNetworkTime().Date) + { + this.ValorPago = new decimal?(value); + } + base.OnPropertyChanged("Valor"); + } + } + + public string ValorFinal + { + get + { + return this._valorFinal; + } + set + { + this._valorFinal = value; + base.OnPropertyChanged("ValorFinal"); + } + } + + public string ValorInicial + { + get + { + return this._valorIncial; + } + set + { + this._valorIncial = value; + base.OnPropertyChanged("ValorInicial"); + } + } + + public decimal? ValorPago + { + get + { + return this._valorPago; + } + set + { + this._valorPago = value; + base.OnPropertyChanged("ValorPago"); + } + } + + public DateTime Vencimento + { + get + { + return this._vencimento; + } + set + { + if (this.Alterando == Visibility.Visible && value != this.VencimentoAnt) + { + this.VencimentoAlterado = true; + } + this.VencimentoAnt = value; + this._vencimento = value; + base.OnPropertyChanged("Vencimento"); + } + } + + public DateTime VencimentoAnt + { + get; + set; + } + + public Visibility VisibilityCentro + { + get + { + return this._visibilityCentro; + } + set + { + this._visibilityCentro = value; + base.OnPropertyChanged("VisibilityCentro"); + } + } + + public Visibility VisibilityConta + { + get + { + return this._visibilityConta; + } + set + { + this._visibilityConta = value; + base.OnPropertyChanged("VisibilityConta"); + } + } + + public Visibility VisibilityFornecedor + { + get + { + return this._visibilityFornecedor; + } + set + { + this._visibilityFornecedor = value; + base.OnPropertyChanged("VisibilityFornecedor"); + } + } + + public Visibility VisibilitySemValor + { + get + { + return this._visibilitySemValor; + } + set + { + this._visibilitySemValor = value; + base.OnPropertyChanged("VisibilitySemValor"); + } + } + + public Visibility VisibleFiltros + { + get + { + return this._visibleFiltros; + } + set + { + this._visibleFiltros = value; + base.OnPropertyChanged("VisibleFiltros"); + } + } + + public Visibility VisibleOlho + { + get + { + return this._visibleOlho; + } + set + { + this._visibleOlho = value; + base.OnPropertyChanged("VisibleOlho"); + } + } + + public FinanceiroViewModel() + { + this._servico = new FinanceiroServico(); + this.RelatorioFiltroPersonalizado = Funcoes.PopularFiltroFinanceiro(); + this.BuscaInicial(); + } + + public async void AdcionarFiltroPersonalizado() + { + string str; + DateTime dateTime; + decimal num; + int num1; + long num2; + List filtroPersonalizados; + List filtroPersonalizados1; + if (this.Filtro != null) + { + if (this.SemValor) + { + filtroPersonalizados = (this.PersonalizadoSelecionado == null ? new List() : ( + from x in this.PersonalizadoSelecionado + where x.get_Propriedade() == this.Filtro.get_Propriedade() + select x).ToList()); + List filtroPersonalizados2 = filtroPersonalizados; + if (filtroPersonalizados2.Count > 0) + { + filtroPersonalizados2.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.PersonalizadoSelecionado.Remove(x)); + } + str = string.Concat(this.Filtro.get_Nome(), ": EM BRANCO"); + } + else + { + filtroPersonalizados1 = (this.PersonalizadoSelecionado == null ? new List() : this.PersonalizadoSelecionado.Where((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => { + if (x.get_Propriedade() != this.Filtro.get_Propriedade()) + { + return false; + } + return x.get_SemValor(); + }).ToList()); + List filtroPersonalizados3 = filtroPersonalizados1; + if (filtroPersonalizados3.Count > 0) + { + filtroPersonalizados3.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.PersonalizadoSelecionado.Remove(x)); + } + string name = this.Filtro.get_Tipo().Name; + if (name == "DateTime") + { + if (!DateTime.TryParse(this.ValorInicial, out dateTime) || !DateTime.TryParse(this.ValorFinal, out dateTime) || DateTime.Parse(this.ValorInicial) > DateTime.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:d} até {2:d}", this.Filtro.get_Nome(), DateTime.Parse(this.ValorInicial), DateTime.Parse(this.ValorFinal)); + } + } + else if (name == "Decimal") + { + if (!decimal.TryParse(this.ValorInicial, out num) || !decimal.TryParse(this.ValorFinal, out num) || Math.Abs(decimal.Parse(this.ValorInicial)) > Math.Abs(decimal.Parse(this.ValorFinal))) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n2} até {2:n2}", this.Filtro.get_Nome(), decimal.Parse(this.ValorInicial), decimal.Parse(this.ValorFinal)); + } + } + else if (name == "Int32") + { + if (!int.TryParse(this.ValorInicial, out num1) || !int.TryParse(this.ValorFinal, out num1) || int.Parse(this.ValorInicial) > int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.Filtro.get_Nome(), int.Parse(this.ValorInicial), int.Parse(this.ValorFinal)); + } + } + else if (name != "Int64") + { + if (!string.IsNullOrEmpty(this.ValorInicial)) + { + str = string.Concat(this.Filtro.get_Nome(), " = ", this.ValorInicial); + } + else + { + await base.ShowMessage("O VALOR DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + } + else if (!long.TryParse(this.ValorInicial, out num2) || !long.TryParse(this.ValorFinal, out num2) || long.Parse(this.ValorInicial) > (long)int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.Filtro.get_Nome(), long.Parse(this.ValorInicial), long.Parse(this.ValorFinal)); + } + } + if (this.PersonalizadoSelecionado == null) + { + this.PersonalizadoSelecionado = new ObservableCollection(); + } + ObservableCollection personalizadoSelecionado = this.PersonalizadoSelecionado; + Gestor.Model.Domain.Relatorios.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Relatorios.FiltroPersonalizado(); + filtroPersonalizado.set_Nome(this.Filtro.get_Nome()); + filtroPersonalizado.set_Propriedade(this.Filtro.get_Propriedade()); + filtroPersonalizado.set_Tipo(this.Filtro.get_Tipo()); + filtroPersonalizado.set_ValorIncial(this.ValorInicial); + filtroPersonalizado.set_ValorFinal(this.ValorFinal); + filtroPersonalizado.set_SemValor(this.SemValor); + filtroPersonalizado.set_Descricao(str); + personalizadoSelecionado.Add(filtroPersonalizado); + this.Filtro = null; + this.ValorInicial = string.Empty; + this.ValorFinal = string.Empty; + this.PesquisaPersonalizada(); + } + } + + public void AdicionarFiltro(Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtro) + { + if (filtro == null) + { + return; + } + if (this.FiltroPersonalizadoSelecionado == null) + { + this.FiltroPersonalizadoSelecionado = new ObservableCollection(); + } + this.VisibleFiltros = Visibility.Visible; + if (this.FiltroPersonalizadoSelecionado.Any((Gestor.Model.Domain.Financeiro.FiltroPersonalizado x) => { + if (x.get_Id() != filtro.get_Id()) + { + return false; + } + return x.get_Tipo() == filtro.get_Tipo(); + })) + { + return; + } + this.FiltroPersonalizadoSelecionado.Add(filtro); + this.FiltrarPersonalizado(); + } + + public void AdicionarFiltros() + { + ExtensionMethods.ForEach( + from x in this.PlanosFiltro + where x.get_Selecionado() + select x, (Gestor.Model.Domain.Financeiro.Planos x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Id(x.get_Id()); + filtroPersonalizado.set_Tipo(1); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + this.AdicionarFiltro(filtroPersonalizado); + }); + this.PlanosFiltro = new List( + from x in this.Planos + orderby x.get_Descricao() + select x); + ExtensionMethods.ForEach( + from x in this.ContaFiltro + where x.get_Selecionado() + select x, (BancosContas x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Id(x.get_Id()); + filtroPersonalizado.set_Tipo(3); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + this.AdicionarFiltro(filtroPersonalizado); + }); + this.ContaFiltro = new List( + from x in this.Contas + orderby x.get_Descricao() + select x); + ExtensionMethods.ForEach( + from x in this.CentroFiltro + where x.get_Selecionado() + select x, (Gestor.Model.Domain.Financeiro.Centro x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Id(x.get_Id()); + filtroPersonalizado.set_Tipo(2); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + this.AdicionarFiltro(filtroPersonalizado); + x.set_Selecionado(false); + }); + this.CentroFiltro = new List( + from x in this.Centros + orderby x.get_Descricao() + select x); + } + + private async Task AdicionarParcelaRange() + { + base.Loading(true); + List lancamentos = new List(); + ObservableCollection lancamentosFiltrados = this.LancamentosFiltrados; + IEnumerable selecionado = + from x in lancamentosFiltrados + where x.get_Selecionado() + select x; + List list = selecionado.Select((Lancamento x) => { + Lancamento lancamento = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Centro(x.get_Controle().get_Centro()); + controleFinanceiro.set_Fornecedor(x.get_Controle().get_Fornecedor()); + controleFinanceiro.set_Historico(x.get_Controle().get_Historico()); + controleFinanceiro.set_Id(x.get_Controle().get_Id()); + controleFinanceiro.set_Parcelas(x.get_Controle().get_Parcelas() + 1); + controleFinanceiro.set_Plano(x.get_Controle().get_Plano()); + lancamento.set_Controle(controleFinanceiro); + lancamento.set_Historico(x.get_Historico()); + lancamento.set_Observacao(x.get_Observacao()); + lancamento.set_Vencimento(x.get_Vencimento().AddMonths(1)); + lancamento.set_Conta(x.get_Conta()); + lancamento.set_Parcela(x.get_Parcela() + 1); + lancamento.set_Documento(x.get_Documento()); + lancamento.set_Sinal(x.get_Sinal()); + lancamento.set_TipoPagamento(x.get_TipoPagamento()); + lancamento.set_Valor(x.get_Valor()); + return lancamento; + }).ToList(); + foreach (Lancamento lancamento1 in list) + { + if (await this._servico.BuscarLancamento(lancamento1.get_Controle().get_Id(), lancamento1.get_Parcela()) != null) + { + continue; + } + lancamentos.Add(lancamento1); + } + await this._servico.IncluirRange(lancamentos); + if (this._servico.Sucesso) + { + await this.Buscar(); + base.ToggleSnackBar("INCLUSÃO DE PARCELA REALIZADA COM SUCESSO", true); + base.Loading(false); + } + else + { + base.Loading(false); + } + lancamentos = null; + } + + public async Task AlterarLancamentos(Lancamento lancamentoAtual, bool alterarVencimento, bool alterarValores) + { + Func func = null; + List lancamentos = await this._servico.BuscarLancamentosPorControle(lancamentoAtual.get_Controle().get_Id()); + int num = 1; + List lancamentos1 = lancamentos; + Func func1 = func; + if (func1 == null) + { + Func parcela = (Lancamento l) => l.get_Parcela() > lancamentoAtual.get_Parcela(); + Func func2 = parcela; + func = parcela; + func1 = func2; + } + foreach (Lancamento lancamento in lancamentos1.Where(func1)) + { + if (!lancamento.get_Baixado()) + { + if (alterarVencimento) + { + lancamento.set_Vencimento(lancamentoAtual.get_Vencimento().AddMonths(num)); + } + if (alterarValores) + { + lancamento.set_Valor(lancamentoAtual.get_Valor()); + } + await this._servico.Save(lancamento); + } + num++; + } + this.SelectedLancamento = lancamentoAtual; + } + + public async Task Atualizar(List list) + { + DateTime? baixa; + DateTime? nullable; + string str; + bool flag; + base.Loading(true); + List lancamentos = new List(); + List lancamentos1 = new List(); + List lancamentos2 = new List(); + foreach (Lancamento lancamento in list) + { + if (lancamento.get_Baixado()) + { + continue; + } + if (!lancamento.get_Selecionado()) + { + baixa = null; + lancamento.set_Baixa(baixa); + } + baixa = lancamento.get_Baixa(); + if (baixa.HasValue) + { + Saldo saldo = await this.VerificaSaldo(lancamento.get_Conta().get_Id(), false); + if (saldo == null) + { + continue; + } + baixa = saldo.get_DataInicio(); + nullable = lancamento.get_Baixa(); + flag = (baixa.HasValue & nullable.HasValue ? baixa.GetValueOrDefault() > nullable.GetValueOrDefault() : false); + if (flag) + { + continue; + } + } + if (lancamento.get_Selecionado()) + { + str = (lancamento.get_Observacao() == null ? "" : string.Concat("\n ", lancamento.get_Observacao())); + string str1 = str; + Lancamento lancamento1 = lancamento; + object[] id = new object[] { Recursos.Usuario.get_Id(), Recursos.Usuario.get_Nome(), null, null }; + DateTime networkTime = Funcoes.GetNetworkTime(); + id[2] = networkTime.ToString("F").ToUpper(); + id[3] = str1; + lancamento1.set_Observacao(string.Format("BAIXA AGRUPADA REALIZADA PELO USUARIO {0} {1} EM {2}{3}", id)); + } + List> keyValuePairs = lancamento.Validate(); + if (keyValuePairs != null && keyValuePairs.Count > 0) + { + continue; + } + nullable = lancamento.get_Baixa(); + if (!nullable.HasValue) + { + lancamentos.Add(lancamento); + } + else + { + lancamentos1.Add(lancamento); + } + lancamentos2.Add(lancamento); + } + if (lancamentos2.Count != 0) + { + object[] count = new object[] { lancamentos.Count, Environment.NewLine, lancamentos1.Count, Environment.NewLine, Environment.NewLine }; + if (await base.ShowMessage(string.Format("{0} LANÇAMENTOS SERÃO ATUALIZADOS.{1}{2} LANÇAMENTOS SERÃO BAIXADOS.{3}{4}DESEJA REALMENTE PROSSEGUIR?", count), "SIM", "NÃO", false)) + { + await this._servico.Atualizar(lancamentos2); + if (this._servico.Sucesso) + { + if (await base.ShowMessage("DESEJA GERAR O RELATÓRIO NOVAMENTE?", "SIM,", "NÃO", false)) + { + await this.Buscar(); + } + base.ToggleSnackBar("ATUALIZAÇÃO REALIZADA COM SUCESSO", true); + await this.CarregarSaldos(); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + else + { + base.Loading(false); + } + } + else + { + await base.ShowMessage("NÃO HÁ LANÇAMENTOS PARA SEREM ATUALIZADOS.", "OK", "", false); + base.Loading(false); + } + lancamentos = null; + lancamentos1 = null; + lancamentos2 = null; + } + + public void Bind() + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.Financeiro.FinanceiroViewModel::Bind() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void Bind() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // 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 void BindImportando() + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.Financeiro.FinanceiroViewModel::BindImportando() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void BindImportando() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // 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 + + } + + private async void BuscaInicial() + { + base.Loading(true); + this.Planos = await (new PlanoServico()).BuscarPlanos(); + FinanceiroViewModel observableCollection = this; + List planos = this.Planos; + IEnumerable ativo = + from x in planos + where x.get_Ativo() + select x; + observableCollection.PlanosFiltrados = new ObservableCollection( + from x in ativo + orderby x.get_Descricao() + select x); + this.Contas = await (new BancosContasServico()).BuscarBancos(); + FinanceiroViewModel financeiroViewModel = this; + List contas = this.Contas; + IEnumerable bancosContas = + from x in contas + where x.get_Ativo() + select x; + financeiroViewModel.ContasFiltradas = new ObservableCollection( + from x in bancosContas + orderby x.get_Descricao() + select x); + this.Centros = await (new CentroServico()).BuscarCentros(); + FinanceiroViewModel observableCollection1 = this; + List centros = this.Centros; + IEnumerable ativo1 = + from x in centros + where x.get_Ativo() + select x; + observableCollection1.CentrosFiltrados = new ObservableCollection( + from x in ativo1 + orderby x.get_Descricao() + select x); + FinanceiroViewModel planos1 = this; + List planos2 = this.Planos; + planos1.PlanosFiltro = new List( + from x in planos2 + orderby x.get_Descricao() + select x); + FinanceiroViewModel bancosContas1 = this; + List contas1 = this.Contas; + bancosContas1.ContaFiltro = new List( + from x in contas1 + orderby x.get_Descricao() + select x); + FinanceiroViewModel centros1 = this; + List centros2 = this.Centros; + centros1.CentroFiltro = new List( + from x in centros2 + orderby x.get_Descricao() + select x); + this.PopularFiltro(); + await this.Buscar(); + base.Loading(false); + } + + public async Task Buscar() + { + List list; + bool flag; + List nums; + List list1; + List nums1; + List list2; + List nums2; + this.Importando = false; + DateTime? inicio = this.Inicio; + if (inicio.HasValue) + { + inicio = this.Fim; + if (inicio.HasValue) + { + inicio = this.Inicio; + DateTime? fim = this.Fim; + flag = (inicio.HasValue & fim.HasValue ? inicio.GetValueOrDefault() > fim.GetValueOrDefault() : false); + if (!flag) + { + this.PersonalizadoSelecionado = null; + switch (this.SelectedFiltro) + { + case 1: + { + FinanceiroServico financeiroServico = this._servico; + fim = this.Inicio; + DateTime value = fim.Value; + fim = this.Fim; + list = await financeiroServico.BuscarLancamentosPorBaixa(value, fim.Value); + break; + } + case 2: + { + FinanceiroServico financeiroServico1 = this._servico; + fim = this.Inicio; + DateTime dateTime = fim.Value; + fim = this.Fim; + list = await financeiroServico1.BuscarLancamentosPorPagamento(dateTime, fim.Value); + break; + } + case 3: + { + if (this.SelectedFornecedor != null) + { + list = await this._servico.BuscarLancamentosPorFornecedor(this.SelectedFornecedor.get_Id(), this.SelectedStatus); + break; + } + else + { + return; + } + } + case 4: + { + FinanceiroServico financeiroServico2 = this._servico; + fim = this.Inicio; + DateTime value1 = fim.Value; + fim = this.Fim; + list = await financeiroServico2.BuscarLancamentosPorLancamento(value1, fim.Value, this.SelectedStatus); + break; + } + case 5: + { + FinanceiroServico financeiroServico3 = this._servico; + fim = this.Inicio; + DateTime dateTime1 = fim.Value; + fim = this.Fim; + List lancamentos = await financeiroServico3.BuscarLancamentosPersonalizados(dateTime1, fim.Value, this.SelectedStatus, this.SelectedFiltroData); + if (this.FiltroPersonalizadoSelecionado != null) + { + ObservableCollection filtroPersonalizadoSelecionado = this.FiltroPersonalizadoSelecionado; + IEnumerable tipo = + from x in filtroPersonalizadoSelecionado + where x.get_Tipo() == 0 + select x; + nums = ( + from x in tipo + select x.get_Id()).ToList(); + } + else + { + nums = new List(); + } + List nums3 = nums; + if (this.FiltroPersonalizadoSelecionado != null) + { + ObservableCollection observableCollection = this.FiltroPersonalizadoSelecionado; + IEnumerable filtroPersonalizados = + from x in observableCollection + where x.get_Tipo() == 2 + select x; + list1 = ( + from x in filtroPersonalizados + select x.get_Id()).ToList(); + } + else + { + list1 = new List(); + } + List nums4 = list1; + if (this.FiltroPersonalizadoSelecionado != null) + { + ObservableCollection filtroPersonalizadoSelecionado1 = this.FiltroPersonalizadoSelecionado; + IEnumerable tipo1 = + from x in filtroPersonalizadoSelecionado1 + where x.get_Tipo() == 1 + select x; + nums1 = ( + from x in tipo1 + select x.get_Id()).ToList(); + } + else + { + nums1 = new List(); + } + List nums5 = nums1; + if (this.FiltroPersonalizadoSelecionado != null) + { + ObservableCollection observableCollection1 = this.FiltroPersonalizadoSelecionado; + IEnumerable filtroPersonalizados1 = + from x in observableCollection1 + where x.get_Tipo() == 3 + select x; + list2 = ( + from x in filtroPersonalizados1 + select x.get_Id()).ToList(); + } + else + { + list2 = new List(); + } + List nums6 = list2; + if (this.FiltroPersonalizadoSelecionado != null) + { + ObservableCollection filtroPersonalizadoSelecionado2 = this.FiltroPersonalizadoSelecionado; + IEnumerable tipo2 = + from x in filtroPersonalizadoSelecionado2 + where x.get_Tipo() == 4 + select x; + nums2 = ( + from x in tipo2 + select x.get_Id()).ToList(); + } + else + { + nums2 = new List(); + } + List nums7 = nums2; + list = lancamentos.Where((Lancamento x) => { + if (nums3.Count != 0 && (x.get_Controle().get_Fornecedor() == null || !nums3.Contains(x.get_Controle().get_Fornecedor().get_Id())) || nums4.Count != 0 && (x.get_Controle().get_Centro() == null || !nums4.Contains(x.get_Controle().get_Centro().get_Id())) || nums5.Count != 0 && (x.get_Controle().get_Plano() == null || !nums5.Contains(x.get_Controle().get_Plano().get_Id())) || nums6.Count != 0 && (x.get_Conta() == null || !nums6.Contains(x.get_Conta().get_Id()))) + { + return false; + } + if (nums7.Count == 0) + { + return true; + } + return nums7.Contains((long)x.get_Sinal()); + }).ToList(); + break; + } + default: + { + FinanceiroServico financeiroServico4 = this._servico; + fim = this.Inicio; + DateTime value2 = fim.Value; + fim = this.Fim; + list = await financeiroServico4.BuscarLancamentos(value2, fim.Value, this.SelectedStatus); + break; + } + } + List lancamentos1 = list; + lancamentos1.ForEach((Lancamento x) => x.Initialize()); + this.Lancamentos = new ObservableCollection(list); + this.LancamentosFiltrados = this.Lancamentos; + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + this.SelectedLancamento = this.LancamentosFiltrados.FirstOrDefault(); + await this.CarregarSaldos(); + return; + } + else + { + await base.ShowMessage("A DATA DE INÍCIO NÃO PODE SER SUPERIOR A DATA FINAL.", "OK", "", false); + return; + } + } + } + await base.ShowMessage("NECESSÁRIO PREENCHER TANTO A DATA DE INÍCIO QUANTO A DATA FINAL PARA REALIZAR A PESQUISA.", "OK", "", false); + } + + internal async Task BuscarLancamentosVinculo() + { + DateTime vencimento; + DateTime? dataInicio; + DateTime valueOrDefault; + if (this.SelectedLancamento.get_Conta() != null) + { + Saldo saldo = this.Saldos.FirstOrDefault((Saldo x) => x.get_Id() == this.SelectedLancamento.get_Conta().get_Id()); + if (saldo != null) + { + dataInicio = saldo.get_DataInicio(); + } + else + { + dataInicio = null; + } + } + else + { + vencimento = this.SelectedLancamento.get_Vencimento(); + dataInicio = new DateTime?(vencimento.AddDays(-5)); + } + DateTime? nullable = dataInicio; + if (nullable.HasValue) + { + valueOrDefault = nullable.GetValueOrDefault(); + } + else + { + vencimento = this.SelectedLancamento.get_Vencimento(); + valueOrDefault = vencimento.AddDays(-5); + } + DateTime dateTime = valueOrDefault; + List list = await this._servico.BuscarLancamentosPorFornecedor(this.FornecedorInclusao.get_Id(), dateTime, this.Sinal); + ObservableCollection lancamentos = this.Lancamentos; + List nums = ( + from x in lancamentos + select x.get_Id()).ToList(); + list = ( + from x in list + where !nums.Contains(x.get_Id()) + select x).ToList(); + this.LancamentosVinculo = new ObservableCollection(list); + } + + public void CancelarAlteracao() + { + this.LancamentosFiltrados = this.LancamentosFiltradosCopia; + this.SelectedLancamento = this.LancamentosFiltrados.FirstOrDefault((Lancamento x) => { + long? nullable; + long id = x.get_Id(); + Lancamento lancamentoSelecionado = this.LancamentoSelecionado; + if (lancamentoSelecionado != null) + { + nullable = new long?(lancamentoSelecionado.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + } + + public async Task CarregarSaldos() + { + this.Saldos = new ObservableCollection(); + BancosContasServico bancosContasServico = new BancosContasServico(); + foreach (BancosContas contasFiltrada in this.ContasFiltradas) + { + Saldo saldo = await bancosContasServico.BuscarSaldoAberto(contasFiltrada.get_Id()); + if (saldo == null) + { + continue; + } + DateTime date = Funcoes.GetNetworkTime().Date; + saldo.set_DataFinal(new DateTime?(date.AddDays(1))); + saldo = await bancosContasServico.FecharSaldo(saldo); + this.Saldos.Add(saldo); + } + this.SelectedSaldo = this.Saldos.FirstOrDefault(); + bancosContasServico = null; + } + + private Tuple CorrigeLancamentos(OfxDocument lancamentos, List codigoBanco) + { + DateTime? nullable; + DateTime? nullable1; + DateTime? nullable2; + if (!this.VerificaFiltroErrado(lancamentos)) + { + if (this.VerificaDataInvertida(lancamentos)) + { + return new Tuple(lancamentos.get_StatementEnd(), lancamentos.get_StatementStart()); + } + return new Tuple(lancamentos.get_StatementStart(), lancamentos.get_StatementEnd()); + } + Transaction transaction = ( + from lanc in lancamentos.get_Transactions() + orderby lanc.get_Date() + select lanc).First(); + if (transaction != null) + { + nullable1 = new DateTime?(transaction.get_Date()); + } + else + { + nullable = null; + nullable1 = nullable; + } + nullable = nullable1; + DateTime value = nullable.Value; + Transaction transaction1 = ( + from lanc in lancamentos.get_Transactions() + orderby lanc.get_Date() descending + select lanc).First(); + if (transaction1 != null) + { + nullable2 = new DateTime?(transaction1.get_Date()); + } + else + { + nullable = null; + nullable2 = nullable; + } + nullable = nullable2; + return new Tuple(value, nullable.Value); + } + + public void DeSelecionarLancamento(Lancamento lancamento) + { + Lancamento lancamento1 = (lancamento.get_Id() > (long)0 ? this.LancamentosFiltrados.First((Lancamento x) => x.get_Id() == lancamento.get_Id()) : this.LancamentosFiltrados.First((Lancamento x) => { + long? nullable; + long? nullable1; + long? nullable2; + long? nullable3; + long? nullable4; + if (x.get_Id() == lancamento.get_Id()) + { + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + nullable1 = new long?(fornecedor.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable5 = nullable1; + ControleFinanceiro controleFinanceiro = lancamento.get_Controle(); + if (controleFinanceiro != null) + { + Fornecedor fornecedor1 = controleFinanceiro.get_Fornecedor(); + if (fornecedor1 != null) + { + nullable2 = new long?(fornecedor1.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + } + else + { + nullable = null; + nullable2 = nullable; + } + long? nullable6 = nullable2; + if (nullable5.GetValueOrDefault() == nullable6.GetValueOrDefault() & nullable5.HasValue == nullable6.HasValue && x.get_Valor() == lancamento.get_Valor() && x.get_Vencimento() == lancamento.get_Vencimento()) + { + ControleFinanceiro controle1 = x.get_Controle(); + if (controle1 != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle1.get_Plano(); + if (plano != null) + { + nullable3 = new long?(plano.get_Id()); + } + else + { + nullable = null; + nullable3 = nullable; + } + } + else + { + nullable = null; + nullable3 = nullable; + } + nullable6 = nullable3; + ControleFinanceiro controleFinanceiro1 = lancamento.get_Controle(); + if (controleFinanceiro1 != null) + { + Gestor.Model.Domain.Financeiro.Planos plano1 = controleFinanceiro1.get_Plano(); + if (plano1 != null) + { + nullable4 = new long?(plano1.get_Id()); + } + else + { + nullable = null; + nullable4 = nullable; + } + } + else + { + nullable = null; + nullable4 = nullable; + } + nullable5 = nullable4; + return nullable6.GetValueOrDefault() == nullable5.GetValueOrDefault() & nullable6.HasValue == nullable5.HasValue; + } + } + return false; + })); + lancamento1.set_Selecionado(false); + if (!lancamento1.get_Baixado()) + { + DateTime? nullable7 = null; + lancamento1.set_Baixa(nullable7); + nullable7 = null; + lancamento1.set_Pagamento(nullable7); + lancamento1.set_ValorPago(new decimal?(new decimal())); + } + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + this.Totalizar(); + } + + public async Task Excluir() + { + bool flag; + long? nullable; + object historico; + bool flag1; + long num; + Lancamento lancamento; + if (this.SelectedLancamento != null && this.SelectedLancamento.get_Id() != 0) + { + base.Loading(true); + lancamento = await this._servico.BuscarLancamento(this.SelectedLancamento.get_Id()); + Saldo saldo = await this.VerificaSaldo(this.SelectedLancamento.get_Conta().get_Id(), true); + if (saldo != null) + { + DateTime? dataInicio = saldo.get_DataInicio(); + DateTime? baixa = lancamento.get_Baixa(); + flag = (dataInicio.HasValue & baixa.HasValue ? dataInicio.GetValueOrDefault() > baixa.GetValueOrDefault() : false); + if (flag) + { + await base.ShowMessage("LANÇAMENTO NÃO PODE SER EXCLUÍDO POIS NÃO POSSUI SALDO ABERTO PARA O PERÍODO.", "OK", "", false); + base.Loading(false); + } + else if (!await base.ShowMessage("DESEJA REAMENTE EXCLUIR O LANÇAMENTO SELECIONADO?", "SIM", "NÃO", false)) + { + base.Loading(false); + } + else if (await this._servico.Excluir(this.SelectedLancamento)) + { + FinanceiroViewModel financeiroViewModel = this; + Lancamento selectedLancamento = this.SelectedLancamento; + if (selectedLancamento != null) + { + nullable = new long?(selectedLancamento.get_Id()); + } + else + { + nullable = null; + } + object obj = nullable; + Lancamento selectedLancamento1 = this.SelectedLancamento; + if (selectedLancamento1 != null) + { + historico = selectedLancamento1.get_Historico(); + } + else + { + historico = null; + } + string str = string.Format("EXCLUIU O LANÇAMENTO DO ID {0} HISTORICO: {1}", obj, historico); + Lancamento lancamento1 = this.SelectedLancamento; + if (lancamento1 != null) + { + lancamento1.get_Id(); + flag1 = false; + } + else + { + flag1 = true; + } + num = (flag1 ? (long)0 : this.SelectedLancamento.get_Id()); + financeiroViewModel.RegistrarAcao(str, num, new TipoTela?(25), null); + base.ToggleSnackBar("EXCLUSÃO REALIZADA COM SUCESSO", true); + await this.Buscar(); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + } + lancamento = null; + } + + public async Task ExcluirBaixa() + { + bool flag; + if (this.SelectedLancamento != null && this.SelectedLancamento.get_Id() != 0) + { + base.Loading(true); + DateTime? baixa = await this._servico.BuscarLancamento(this.SelectedLancamento.get_Id()).get_Baixa(); + if (!baixa.HasValue) + { + await base.ShowMessage("LANÇAMENTO AINDA NÃO BAIXADO. PROCESSO INTERROMPIDO", "OK", "", false); + base.Loading(false); + } + else if (await base.ShowMessage("DESEJA REAMENTE EXCLUIR A BAIXA DO LANÇAMENTO SELECIONADO?", "SIM", "NÃO", false)) + { + Saldo saldo = await this.VerificaSaldo(this.SelectedLancamento.get_Conta().get_Id(), true); + if (saldo != null) + { + baixa = saldo.get_DataInicio(); + DateTime? nullable = this.SelectedLancamento.get_Baixa(); + flag = (baixa.HasValue & nullable.HasValue ? baixa.GetValueOrDefault() > nullable.GetValueOrDefault() : false); + if (!flag) + { + nullable = null; + this.SelectedLancamento.set_Baixa(nullable); + this.SelectedLancamento.set_ValorPago(new decimal?(new decimal())); + nullable = null; + this.SelectedLancamento.set_Pagamento(nullable); + this.SelectedLancamento.set_Baixado(false); + this.SelectedLancamento = await this._servico.Save(this.SelectedLancamento); + if (this.importando) + { + this.BindImportando(); + this.LancamentosFiltrados = this.Lancamentos; + base.Loading(false); + } + else if (this._servico.Sucesso) + { + base.ToggleSnackBar("EXCLUSÃO DE BAIXA REALIZADA COM SUCESSO", true); + await this.Buscar(); + base.Loading(false); + } + } + else + { + await base.ShowMessage("LANÇAMENTO NÃO PODE TER SUA BAIXA EXCLUÍDA POIS NÃO POSSUI SALDO ABERTO PARA O PERÍODO.", "OK", "", false); + base.Loading(false); + } + } + } + else + { + base.Loading(false); + } + } + } + + public async Task ExcluirBaixaRange() + { + bool flag; + List lancamentos; + ObservableCollection lancamentosFiltrados = this.LancamentosFiltrados; + List list = lancamentosFiltrados.Where((Lancamento x) => { + if (x.get_Selecionado() && x.get_Controle().get_Plano() != null) + { + return true; + } + if (!x.get_Historico().Equals("TRANSFERÊNCIA ENTRE CONTAS") || !x.get_Selecionado()) + { + return false; + } + return x.get_Controle().get_Plano() == null; + }).ToList(); + if (list.Count == 0) + { + await base.ShowMessage("NÃO HÁ LANÇAMENTOS SELECIONADOS, SELECIONE-OS ANTES DE EXCLUIR A BAIXA.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA REAMENTE EXCLUIR A BAIXA DOS LANÇAMENTOS SELECIONADOS?", "SIM", "NÃO", false)) + { + base.Loading(true); + lancamentos = new List(); + bool flag1 = false; + foreach (Lancamento lancamento in list) + { + Saldo saldo = await this.VerificaSaldo(lancamento.get_Conta().get_Id(), false); + if (saldo == null || !lancamento.get_Baixado()) + { + continue; + } + DateTime? dataInicio = saldo.get_DataInicio(); + DateTime? baixa = lancamento.get_Baixa(); + flag = (dataInicio.HasValue & baixa.HasValue ? dataInicio.GetValueOrDefault() > baixa.GetValueOrDefault() : false); + if (!flag) + { + baixa = null; + lancamento.set_Baixa(baixa); + lancamento.set_ValorPago(new decimal?(new decimal())); + baixa = null; + lancamento.set_Pagamento(baixa); + lancamentos.Add(lancamento); + lancamento = null; + } + else + { + flag1 = true; + } + } + if (lancamentos.Count != 0) + { + bool flag2 = flag1; + if (flag2) + { + flag2 = !await base.ShowMessage(string.Concat("HÁ LANÇAMENTOS SELECIONADOS QUE NÃO PODERÃO TER A BAIXA EXCLUÍDA. ", Environment.NewLine, "DESEJA PROSSEGUIR COM A EXCLUSÃO DA BAIXA DOS DEMAIS LANÇAMENTOS?"), "SIM", "NÃO", false); + } + if (!flag2) + { + await this._servico.Atualizar(lancamentos); + if (this._servico.Sucesso) + { + base.ToggleSnackBar(string.Format("EXCLUSÃO DE BAIXA DE {0} DO TOTAL DE {1} LANÇAMENTOS SELECIONADOS REALIZADA COM SUCESSO.", lancamentos.Count, list.Count), true); + await this.Buscar(); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + else + { + base.Loading(false); + } + } + else + { + await base.ShowMessage("NÃO FOI POSSÍVEL FAZER A EXCLUSÃO, POIS NÃO HÁ LANÇAMENTOS BAIXADOS DENTRO DO ÚLTIMO SALDO ABERTO. PROCESSO INTERROMPIDO", "OK", "", false); + base.Loading(false); + } + } + list = null; + lancamentos = null; + } + + public void ExcluirFiltro(Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtro) + { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = this.FiltroPersonalizadoSelecionado.First((Gestor.Model.Domain.Financeiro.FiltroPersonalizado x) => { + if (x.get_Id() != filtro.get_Id()) + { + return false; + } + return x.get_Tipo() == filtro.get_Tipo(); + }); + this.FiltroPersonalizadoSelecionado.Remove(filtroPersonalizado); + this.FiltroPersonalizadoSelecionado = new ObservableCollection(this.FiltroPersonalizadoSelecionado); + this.FiltrarPersonalizado(); + } + + public async Task ExcluirRange() + { + int? nullable; + bool flag1; + List lancamentos; + ObservableCollection lancamentosFiltrados = this.LancamentosFiltrados; + List list = ( + from x in lancamentosFiltrados + where x.get_Selecionado() + select x).ToList(); + if (list.Count == 0) + { + await base.ShowMessage("NÃO HÁ LANÇAMENTOS SELECIONADOS, SELECIONE-OS ANTES DE EXCLUIR.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA REAMENTE EXCLUIR OS LANÇAMENTOS SELECIONADOS? ESSE PROCESSO É IRREVERSÍVEL.", "SIM", "NÃO", false)) + { + base.Loading(true); + List lancamentos1 = new List(); + ObservableCollection observableCollection = this.LancamentosFiltrados; + List list1 = observableCollection.Where((Lancamento x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Historico().Equals("TRANSFERÊNCIA ENTRE CONTAS"); + }).ToList(); + list1.ForEach((Lancamento x) => { + Lancamento lancamento = list1.FirstOrDefault((Lancamento z) => { + if (z.get_Controle().get_Id() != this.x.get_Controle().get_Id() || !(this.x.get_Valor() == z.get_Valor())) + { + return false; + } + return this.x.get_Sinal() != z.get_Sinal(); + }); + if (lancamento == null || lancamentos1.Where((Lancamento z) => { + if ((object)z == (object)x) + { + return true; + } + return (object)z == (object)lancamento; + }).ToList().Count > 0) + { + return; + } + lancamentos1.AddRange(new List() + { + x, + lancamento + }); + }); + List lancamentos2 = list1; + if (lancamentos2 != null) + { + nullable = new int?(lancamentos2.Count); + } + else + { + nullable = null; + } + int? nullable1 = nullable; + int count = lancamentos1.Count; + bool valueOrDefault = !(nullable1.GetValueOrDefault() == count & nullable1.HasValue); + if (valueOrDefault) + { + valueOrDefault = !await base.ShowMessage(string.Concat("HÁ TRANSFERÊNCIA ENTRE CONTAS SELECIONADOS QUE NÃO PODERÃO TER A BAIXA EXCLUÍDA, PARA EXCLUIR É NECESSÁRIO SELECIONAR O DÉBITO E O CRÉDITO DA TRANSFERENCIA", Environment.NewLine, "DESEJA PROSSEGUIR COM A EXCLUSÃO DOS DEMAIS LANÇAMENTOS?"), "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + bool flag2 = false; + lancamentos = new List(); + List lancamentos3 = list; + IOrderedEnumerable id = + from x in lancamentos3 + orderby x.get_Controle().get_Id() + select x; + foreach (Lancamento lancamento1 in id.ThenByDescending((Lancamento x) => x.get_Parcela()).ToList()) + { + if (lancamento1.get_Baixado()) + { + Saldo saldo = await this.VerificaSaldo(lancamento1.get_Conta().get_Id(), false); + if (saldo == null) + { + continue; + } + DateTime? dataInicio = saldo.get_DataInicio(); + DateTime? baixa = lancamento1.get_Baixa(); + flag1 = (dataInicio.HasValue & baixa.HasValue ? dataInicio.GetValueOrDefault() > baixa.GetValueOrDefault() : false); + if (flag1) + { + flag2 = true; + continue; + } + } + Lancamento lancamento2 = await this._servico.BuscarLancamento(lancamento1.get_Controle().get_Id(), lancamento1.get_Parcela() + 1); + Lancamento lancamento3 = lancamento2; + if (lancamento3 != null) + { + List lancamentos4 = await this._servico.BuscarLancamentosPorControle(lancamento1.get_Controle().get_Id()); + lancamentos = lancamentos4.Where((Lancamento c) => { + if (c.get_Baixado()) + { + return false; + } + return c.get_Parcela() >= lancamento1.get_Parcela() + 1; + }).AsEnumerable().ToList(); + } + if (lancamento3 == null || !lancamentos1.All((Lancamento l) => l.get_Id() != lancamento3.get_Id())) + { + if (lancamento1.get_Controle().get_Plano() != null) + { + lancamentos1.Add(lancamento1); + } + } + else + { + flag2 = true; + } + } + if (lancamentos1.Count != 0 || lancamentos.Count != 0) + { + valueOrDefault = flag2; + if (valueOrDefault) + { + valueOrDefault = !await base.ShowMessage(string.Concat("HÁ LANÇAMENTOS SELECIONADOS QUE NÃO PODERÃO SER EXCLUÍDOS. ", Environment.NewLine, "DESEJA PROSSEGUIR COM A EXCLUSÃO DOS DEMAIS LANÇAMENTOS?"), "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + valueOrDefault = lancamentos.Count > 0; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA EXCLUIR LANÇAMENTOS/PARCELAS CADASTRADOS ACIMA DAS SELECIONADAS.", "SIM", "NÃO", false); + } + if (valueOrDefault) + { + lancamentos1.AddRange(lancamentos); + } + if (await this._servico.Excluir(lancamentos1)) + { + if (lancamentos1 != null && lancamentos1.Count > 0) + { + lancamentos1.ForEach((Lancamento x) => { + bool flag; + FinanceiroViewModel u003cu003e4_this = this; + string str = string.Format("EXCLUIU O LANÇAMENTO DO ID {0} HISTORICO: {1}", (x != null ? new long?(x.get_Id()) : null), (x != null ? x.get_Historico() : null)); + if (x != null) + { + x.get_Id(); + flag = false; + } + else + { + flag = true; + } + u003cu003e4_this.RegistrarAcao(str, (flag ? (long)0 : x.get_Id()), new TipoTela?(25), null); + }); + } + base.ToggleSnackBar(string.Format("EXCLUSÃO DE {0} DO TOTAL DE {1} LANÇAMENTOS SELECIONADOS REALIZADA COM SUCESSO.", lancamentos1.Count, list.Count), true); + await this.Buscar(); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + else + { + base.Loading(false); + } + } + else + { + await base.ShowMessage("OS LANÇAMENTOS SELECIONADOS NÃO PODEM SER EXCLUÍDOS. NENHUMA ALTERAÇÃO FOI FEITA", "OK", "", false); + base.Loading(false); + } + } + else + { + base.Loading(false); + } + } + list = null; + lancamentos = null; + } + + public void Feed(Lancamento lancamento) + { + bool id; + Fornecedor fornecedor; + Gestor.Model.Domain.Financeiro.Planos plano; + BancosContas bancosConta; + if (lancamento == null || this.Salvando) + { + return; + } + if (!this.importando && lancamento.get_Controle().get_Plano() == null) + { + return; + } + Fornecedor fornecedor1 = lancamento.get_Controle().get_Fornecedor(); + if (fornecedor1 != null) + { + id = fornecedor1.get_Id() == (long)0; + } + else + { + id = false; + } + if (id) + { + fornecedor = null; + } + else + { + fornecedor = lancamento.get_Controle().get_Fornecedor(); + } + this.FornecedorInclusao = fornecedor; + if (lancamento.get_Controle().get_Plano() != null) + { + plano = this.PlanosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == lancamento.get_Controle().get_Plano().get_Id()); + } + else + { + plano = null; + } + this.Plano = plano; + this.Centro = this.CentrosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Centro x) => x.get_Id() == lancamento.get_Controle().get_Centro().get_Id()); + if (lancamento.get_Conta() != null) + { + bancosConta = this.ContasFiltradas.FirstOrDefault((BancosContas x) => x.get_Id() == lancamento.get_Conta().get_Id()); + } + else + { + bancosConta = null; + } + this.Conta = bancosConta; + this.TipoPagamento = lancamento.get_TipoPagamento(); + this.Historico = lancamento.get_Historico(); + this.Observacao = lancamento.get_Observacao(); + this.Complemento = lancamento.get_Complemento(); + this.Competencia = lancamento.get_Competencia(); + this.Documento = lancamento.get_Documento(); + this.Parcela = lancamento.get_Parcela(); + this.Parcelas = lancamento.get_Controle().get_Parcelas(); + this.Valor = lancamento.get_Valor(); + this.ValorPago = lancamento.get_ValorPago(); + this.Vencimento = lancamento.get_Vencimento(); + this.Pagamento = lancamento.get_Pagamento(); + this.Baixa = lancamento.get_Baixa(); + this.Sinal = lancamento.get_Sinal(); + this.CodigoBanco = lancamento.get_CodigoBanco(); + } + + public void FeedImportando(Lancamento lancamento) + { + BancosContas bancosConta; + Gestor.Model.Domain.Financeiro.Planos plano; + if (lancamento == null || this.Salvando) + { + return; + } + if (!this.importando && lancamento.get_Controle().get_Plano() == null) + { + return; + } + if (this.Conta == null) + { + bancosConta = this.ContasFiltradas.FirstOrDefault((BancosContas x) => x.get_Id() == lancamento.get_Conta().get_Id()); + } + else + { + bancosConta = null; + } + this.Conta = bancosConta; + this.SelectedLancamento.set_Id(lancamento.get_Id()); + this.SelectedLancamento.get_Controle().set_Id(lancamento.get_Controle().get_Id()); + this.SelectedLancamento.get_Controle().set_Historico(lancamento.get_Controle().get_Historico()); + this.SelectedLancamento.set_Baixado(lancamento.get_Baixa().HasValue); + decimal? valorPago = this.SelectedLancamento.get_ValorPago(); + this.IdLancamento = lancamento.get_Id(); + if (lancamento.get_Controle().get_Plano() != null) + { + plano = this.PlanosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == lancamento.get_Controle().get_Plano().get_Id()); + } + else + { + plano = null; + } + this.Plano = plano; + this.Centro = this.CentrosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Centro x) => x.get_Id() == lancamento.get_Controle().get_Centro().get_Id()); + this.TipoPagamento = lancamento.get_TipoPagamento(); + this.Historico = lancamento.get_Historico(); + this.Observacao = lancamento.get_Observacao(); + this.Complemento = lancamento.get_Complemento(); + this.Documento = lancamento.get_Documento(); + this.Parcela = lancamento.get_Parcela(); + this.Parcelas = lancamento.get_Controle().get_Parcelas(); + this.Valor = lancamento.get_Valor(); + this.ValorPago = valorPago; + this.Vencimento = lancamento.get_Vencimento(); + this.Pagamento = (lancamento.get_Pagamento().HasValue ? lancamento.get_Pagamento() : this.Pagamento); + } + + public List Filtrar(string filter) + { + this._dontSort = true; + this.LancamentosFiltrados = (string.IsNullOrWhiteSpace(filter) ? this.Lancamentos : new ObservableCollection(this.Lancamentos.Where((Lancamento x) => { + bool plano; + bool centro; + bool fornecedor; + if ((x.get_Historico() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Historico().Trim()).Contains(filter)) && (x.get_Documento() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Documento().Trim()).Contains(filter)) && (x.get_Competencia() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Competencia().Trim()).Contains(filter)) && (x.get_Complemento() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Complemento().Trim()).Contains(filter)) && (x.get_Observacao() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Observacao().Trim()).Contains(filter)) && !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Vencimento().ToString(CultureInfo.CurrentCulture).Trim()).ToUpper().Contains(filter) && (!x.get_Baixa().HasValue || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Baixa().ToString().Trim()).ToUpper().Contains(filter)) && (!x.get_Pagamento().HasValue || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Pagamento().ToString().Trim()).ToUpper().Contains(filter)) && (x.get_Conta() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Conta().get_Descricao().Trim()).ToUpper().Contains(filter)) && (x.get_Controle().get_Historico() == null || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Controle().get_Historico().Trim()).ToUpper().Contains(filter)) && !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(EnumHelper.GetDescription(x.get_Sinal()).Trim()).Contains(filter)) + { + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = false; + } + if (!plano || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Controle().get_Plano().get_Descricao().Trim()).ToUpper().Contains(filter)) + { + x.get_TipoPagamento(); + if (!Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(EnumHelper.GetDescription(x.get_TipoPagamento()).Trim()).ToUpper().Contains(filter)) + { + ControleFinanceiro controleFinanceiro = x.get_Controle(); + if (controleFinanceiro != null) + { + centro = controleFinanceiro.get_Centro(); + } + else + { + centro = false; + } + if (!centro || !Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Controle().get_Centro().get_Descricao().Trim()).ToUpper().Contains(filter)) + { + ControleFinanceiro controle1 = x.get_Controle(); + if (controle1 != null) + { + fornecedor = controle1.get_Fornecedor(); + } + else + { + fornecedor = false; + } + if (!fornecedor) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Controle().get_Fornecedor().get_Nome().Trim()).ToUpper().Contains(filter); + } + } + } + } + return true; + }))); + this._dontSort = false; + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + return this.LancamentosFiltrados.ToList(); + } + + public List FiltrarLancamento(long id) + { + this.LancamentosFiltrados = new ObservableCollection( + from x in this.Lancamentos + where x.get_Id() == id + select x); + return this.LancamentosFiltrados.ToList(); + } + + public List FiltrarLancamento(Lancamento lancamento) + { + this.LancamentosFiltrados = new ObservableCollection(this.Lancamentos.Where((Lancamento x) => { + if (!(x.get_Valor() == lancamento.get_Valor()) || !(x.get_Vencimento() == lancamento.get_Vencimento())) + { + return false; + } + return x.get_Historico() == lancamento.get_Historico(); + })); + return this.LancamentosFiltrados.ToList(); + } + + public async Task> FiltrarLancamento(string value) + { + List lancamentos = await Task.Run>(() => this.Filtrar(value)); + return lancamentos; + } + + public void FiltrarPersonalizado() + { + List nums = (this.FiltroPersonalizadoSelecionado != null ? ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Tipo() == 0 + select x.get_Id()).ToList() : new List()); + List nums1 = (this.FiltroPersonalizadoSelecionado != null ? ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Tipo() == 2 + select x.get_Id()).ToList() : new List()); + List nums2 = (this.FiltroPersonalizadoSelecionado != null ? ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Tipo() == 1 + select x.get_Id()).ToList() : new List()); + List nums3 = (this.FiltroPersonalizadoSelecionado != null ? ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Tipo() == 3 + select x.get_Id()).ToList() : new List()); + List nums4 = (this.FiltroPersonalizadoSelecionado != null ? ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Tipo() == 4 + select x.get_Id()).ToList() : new List()); + List list = this.Lancamentos.Where((Lancamento x) => { + if (nums.Count != 0 && (x.get_Controle().get_Fornecedor() == null || !nums.Contains(x.get_Controle().get_Fornecedor().get_Id())) || nums1.Count != 0 && (x.get_Controle().get_Centro() == null || !nums1.Contains(x.get_Controle().get_Centro().get_Id())) || nums2.Count != 0 && (x.get_Controle().get_Plano() == null || !nums2.Contains(x.get_Controle().get_Plano().get_Id())) || nums3.Count != 0 && (x.get_Conta() == null || !nums3.Contains(x.get_Conta().get_Id()))) + { + return false; + } + if (nums4.Count == 0) + { + return true; + } + return nums4.Contains((long)x.get_Sinal()); + }).ToList(); + this.LancamentosFiltrados = new ObservableCollection(list); + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + this.SelectedLancamento = this.LancamentosFiltrados.FirstOrDefault(); + } + + public List FiltrarPersonalizado(string filter) + { + if (this.FiltroPersonalizado == null) + { + this.PopularFiltro(); + } + return ( + from x in this.FiltroPersonalizado + where Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(filter.ToUpper()) + select x).ToList(); + } + + public void FiltroImportacao() + { + if (!this.importando) + { + return; + } + switch (this.SelectedStatusImportacao) + { + case 0: + { + this.LancamentosFiltrados = new ObservableCollection( + from x in this.Lancamentos + where !x.get_Baixado() + select x); + return; + } + case 1: + { + this.LancamentosFiltrados = new ObservableCollection( + from x in this.Lancamentos + where x.get_Baixado() + select x); + return; + } + case 2: + { + this.LancamentosFiltrados = new ObservableCollection(this.Lancamentos); + return; + } + default: + { + return; + } + } + } + + internal async Task> FiltroPersonalizadoTask(string value) + { + List filtroPersonalizados = await Task.Run>(() => this.FiltrarPersonalizado(value)); + return filtroPersonalizados; + } + + public async Task GerarExcel(List relatorioGrid) + { + List list; + string str1; + FinanceiroViewModel.u003cu003ec__DisplayClass266_0 variable; + bool flag = await base.ShowMessage(string.Concat("DESEJA AGRUPAR POR ", EnumHelper.GetDescription(this.SinteticoTipo)), "SIM", "NÃO", false); + XLWorkbook xLWorkbook = new XLWorkbook(); + string str2 = "LANÇAMENTOS FINANCEIROS"; + List relatorioLancamentos = new List(); + List lancamentos = new List(); + List lancamentos1 = relatorioGrid; + bool flag1 = lancamentos1.Any((Lancamento x) => x.get_Selecionado()); + relatorioGrid.ToList().ForEach((Lancamento lancamentoGrid) => { + decimal? valorPago; + if (flag1 && !lancamentoGrid.get_Selecionado()) + { + return; + } + Lancamento lancamento2 = (Lancamento)lancamentoGrid.Clone(); + lancamento2.set_Valor((lancamento2.get_Sinal() == 1 ? -lancamento2.get_Valor() : lancamento2.get_Valor())); + Lancamento lancamento1 = lancamento2; + if (lancamento2.get_Sinal() == 1) + { + decimal? nullable = lancamento2.get_ValorPago(); + valorPago = (nullable.HasValue ? new decimal?(-nullable.GetValueOrDefault()) : null); + } + else + { + valorPago = lancamento2.get_ValorPago(); + } + lancamento1.set_ValorPago(valorPago); + lancamentos.Add(lancamento2); + }); + IEnumerable> groupings = lancamentos.GroupBy((Lancamento lancamento) => { + object descricao; + if (this.SinteticoTipo == 1) + { + Gestor.Model.Domain.Financeiro.Centro centro = lancamento.get_Controle().get_Centro(); + if (centro != null) + { + descricao = centro.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + } + else if (this.SinteticoTipo == null) + { + Gestor.Model.Domain.Financeiro.Planos plano = lancamento.get_Controle().get_Plano(); + if (plano != null) + { + descricao = plano.get_Nome(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + else + { + if (this.SinteticoTipo != 3) + { + Fornecedor fornecedor = lancamento.get_Controle().get_Fornecedor(); + if (fornecedor != null) + { + return fornecedor.get_Nome(); + } + return null; + } + BancosContas conta = lancamento.get_Conta(); + if (conta != null) + { + descricao = conta.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + return descricao; + }); + List sinteticoFinanceiros = groupings.Select, Gestor.Model.Domain.Relatorios.SinteticoFinanceiro>((IGrouping lancamento) => { + Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sinteticoFinanceiro = new Gestor.Model.Domain.Relatorios.SinteticoFinanceiro(); + sinteticoFinanceiro.set_Agrupamento(lancamento.Key ?? "TRANSFERÊNCIAS"); + sinteticoFinanceiro.set_Valor(new decimal?(lancamento.Sum((Lancamento sintetic) => sintetic.get_Valor()))); + sinteticoFinanceiro.set_ValorPago(new decimal?(lancamento.Sum((Lancamento sintetic) => sintetic.get_ValorPago()).GetValueOrDefault())); + return sinteticoFinanceiro; + }).ToList(); + List sinteticoFinanceiros1 = sinteticoFinanceiros; + sinteticoFinanceiros = ( + from lancamento in sinteticoFinanceiros1 + orderby lancamento.get_Agrupamento() + select lancamento).ToList(); + List sinteticoFinanceiros2 = sinteticoFinanceiros; + Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sinteticoFinanceiro1 = new Gestor.Model.Domain.Relatorios.SinteticoFinanceiro(); + sinteticoFinanceiro1.set_Agrupamento("TOTAL"); + List sinteticoFinanceiros3 = sinteticoFinanceiros; + sinteticoFinanceiro1.set_Valor(sinteticoFinanceiros3.Sum((Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sintetic) => sintetic.get_Valor())); + List sinteticoFinanceiros4 = sinteticoFinanceiros; + sinteticoFinanceiro1.set_ValorPago(sinteticoFinanceiros4.Sum((Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sintetic) => sintetic.get_ValorPago())); + sinteticoFinanceiros2.Add(sinteticoFinanceiro1); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "SINTÉTICO", sinteticoFinanceiros, null); + if (!flag) + { + relatorioLancamentos = FinanceiroViewModel.GerarRelatorio(lancamentos); + List relatorioLancamentos1 = relatorioLancamentos; + RelatorioLancamentos relatorioLancamento = new RelatorioLancamentos(); + relatorioLancamento.set_Fornecedor("TOTAL"); + List relatorioLancamentos2 = relatorioLancamentos; + relatorioLancamento.set_Valor(relatorioLancamentos2.Sum((RelatorioLancamentos lancamento) => lancamento.get_Valor())); + List relatorioLancamentos3 = relatorioLancamentos; + relatorioLancamento.set_ValorPago(relatorioLancamentos3.Sum((RelatorioLancamentos lancamento) => lancamento.get_ValorPago())); + relatorioLancamentos1.Add(relatorioLancamento); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2, relatorioLancamentos, null); + } + else + { + switch (this.SinteticoTipo) + { + case 0: + { + List lancamentos2 = lancamentos; + list = lancamentos2.Select((Lancamento x) => { + object descricao; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle.get_Plano(); + if (plano != null) + { + descricao = plano.get_Descricao(); + } + else + { + descricao = null; + } + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + return descricao; + }).Distinct().ToList(); + foreach (string str3 in list) + { + List list1 = lancamentos.Where((Lancamento lancamento) => { + string descricao; + string str; + if (string.IsNullOrWhiteSpace(str3)) + { + ControleFinanceiro controle = lancamento.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle.get_Plano(); + if (plano != null) + { + str = plano.get_Descricao(); + } + else + { + str = null; + } + } + else + { + str = null; + } + return string.IsNullOrEmpty(str); + } + ControleFinanceiro controleFinanceiro = lancamento.get_Controle(); + if (controleFinanceiro != null) + { + Gestor.Model.Domain.Financeiro.Planos plano1 = controleFinanceiro.get_Plano(); + if (plano1 != null) + { + descricao = plano1.get_Descricao(); + } + else + { + descricao = null; + } + } + else + { + descricao = null; + } + return descricao == str3; + }).ToList(); + if (list1.Count == 0) + { + continue; + } + relatorioLancamentos = FinanceiroViewModel.GerarRelatorio(list1); + List relatorioLancamentos4 = relatorioLancamentos; + RelatorioLancamentos relatorioLancamento1 = new RelatorioLancamentos(); + relatorioLancamento1.set_Fornecedor("TOTAL"); + List lancamentos3 = list1; + relatorioLancamento1.set_Valor(lancamentos3.Sum((Lancamento lancamento) => lancamento.get_Valor())); + List lancamentos4 = list1; + relatorioLancamento1.set_ValorPago(lancamentos4.Sum((Lancamento lancamento) => lancamento.get_ValorPago())); + relatorioLancamentos4.Add(relatorioLancamento1); + str1 = (!string.IsNullOrWhiteSpace(str3) ? str3.ValidaNomePlanilha("", 0) : "TRANSFERENCIAS"); + str2 = str1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2, relatorioLancamentos, null); + } + break; + } + case 1: + { + List lancamentos5 = lancamentos; + list = lancamentos5.Select((Lancamento lancamento) => { + object descricao; + ControleFinanceiro controle = lancamento.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Centro centro = controle.get_Centro(); + if (centro != null) + { + descricao = centro.get_Descricao(); + } + else + { + descricao = null; + } + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + return descricao; + }).Distinct().ToList(); + foreach (string str4 in list) + { + List list2 = lancamentos.Where((Lancamento lanamento) => { + string descricao; + string str; + if (string.IsNullOrWhiteSpace(str4)) + { + ControleFinanceiro controle = lanamento.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Centro centro = controle.get_Centro(); + if (centro != null) + { + str = centro.get_Descricao(); + } + else + { + str = null; + } + } + else + { + str = null; + } + return string.IsNullOrEmpty(str); + } + ControleFinanceiro controleFinanceiro = lanamento.get_Controle(); + if (controleFinanceiro != null) + { + Gestor.Model.Domain.Financeiro.Centro centro1 = controleFinanceiro.get_Centro(); + if (centro1 != null) + { + descricao = centro1.get_Descricao(); + } + else + { + descricao = null; + } + } + else + { + descricao = null; + } + return descricao == str4; + }).ToList(); + if (list2.Count == 0) + { + continue; + } + relatorioLancamentos = FinanceiroViewModel.GerarRelatorio(list2); + List relatorioLancamentos5 = relatorioLancamentos; + RelatorioLancamentos relatorioLancamento2 = new RelatorioLancamentos(); + relatorioLancamento2.set_Fornecedor("TOTAL"); + List lancamentos6 = list2; + relatorioLancamento2.set_Valor(lancamentos6.Sum((Lancamento lancamento) => lancamento.get_Valor())); + List lancamentos7 = list2; + relatorioLancamento2.set_ValorPago(lancamentos7.Sum((Lancamento lancamento) => lancamento.get_ValorPago())); + relatorioLancamentos5.Add(relatorioLancamento2); + str2 = str4.ValidaNomePlanilha("", 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2, relatorioLancamentos, null); + } + break; + } + case 2: + { + List lancamentos8 = lancamentos; + list = lancamentos8.Select((Lancamento lancamento) => { + object nome; + ControleFinanceiro controle = lancamento.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + nome = fornecedor.get_Nome(); + } + else + { + nome = null; + } + } + else + { + nome = null; + } + if (nome == null) + { + nome = ""; + } + return nome; + }).Distinct().ToList(); + foreach (string str5 in list) + { + List list3 = lancamentos.Where((Lancamento lancamento) => { + string nome; + string str; + if (string.IsNullOrWhiteSpace(str5)) + { + ControleFinanceiro controle = lancamento.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + str = fornecedor.get_Nome(); + } + else + { + str = null; + } + } + else + { + str = null; + } + return string.IsNullOrEmpty(str); + } + ControleFinanceiro controleFinanceiro = lancamento.get_Controle(); + if (controleFinanceiro != null) + { + Fornecedor fornecedor1 = controleFinanceiro.get_Fornecedor(); + if (fornecedor1 != null) + { + nome = fornecedor1.get_Nome(); + } + else + { + nome = null; + } + } + else + { + nome = null; + } + return nome == str5; + }).ToList(); + if (list3.Count == 0) + { + continue; + } + relatorioLancamentos = FinanceiroViewModel.GerarRelatorio(list3); + List relatorioLancamentos6 = relatorioLancamentos; + RelatorioLancamentos relatorioLancamento3 = new RelatorioLancamentos(); + relatorioLancamento3.set_Fornecedor("TOTAL"); + List lancamentos9 = list3; + relatorioLancamento3.set_Valor(lancamentos9.Sum((Lancamento lancamento) => lancamento.get_Valor())); + List lancamentos10 = list3; + relatorioLancamento3.set_ValorPago(lancamentos10.Sum((Lancamento lancamento) => lancamento.get_ValorPago())); + relatorioLancamentos6.Add(relatorioLancamento3); + str2 = str5.ValidaNomePlanilha("", 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2, relatorioLancamentos, null); + } + break; + } + case 3: + { + List lancamentos11 = lancamentos; + list = lancamentos11.Select((Lancamento x) => { + object descricao; + BancosContas conta = x.get_Conta(); + if (conta != null) + { + descricao = conta.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + return descricao; + }).Distinct().ToList(); + foreach (string str6 in list) + { + if (string.IsNullOrWhiteSpace(str6)) + { + continue; + } + List list4 = lancamentos.Where((Lancamento lancamento) => { + string descricao; + string str; + if (string.IsNullOrWhiteSpace(str6)) + { + BancosContas conta = lancamento.get_Conta(); + if (conta != null) + { + str = conta.get_Descricao(); + } + else + { + str = null; + } + return string.IsNullOrEmpty(str); + } + BancosContas bancosConta = lancamento.get_Conta(); + if (bancosConta != null) + { + descricao = bancosConta.get_Descricao(); + } + else + { + descricao = null; + } + return descricao == str6; + }).ToList(); + if (list4.Count == 0) + { + continue; + } + relatorioLancamentos = FinanceiroViewModel.GerarRelatorio(list4); + List relatorioLancamentos7 = relatorioLancamentos; + RelatorioLancamentos relatorioLancamento4 = new RelatorioLancamentos(); + relatorioLancamento4.set_Fornecedor("TOTAL"); + List lancamentos12 = list4; + relatorioLancamento4.set_Valor(lancamentos12.Sum((Lancamento lancamento) => lancamento.get_Valor())); + List lancamentos13 = list4; + relatorioLancamento4.set_ValorPago(lancamentos13.Sum((Lancamento lancamento) => lancamento.get_ValorPago())); + relatorioLancamentos7.Add(relatorioLancamento4); + str2 = str6.ValidaNomePlanilha("", 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2, relatorioLancamentos, null); + } + break; + } + } + } + string tempPath = ""; + string str7 = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str7 = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + variable = null; + str2 = null; + return; + } + } + string[] strArrays = new string[] { tempPath, str2, " ", null, null }; + DateTime date = Functions.GetNetworkTime().Date; + strArrays[3] = date.ToShortDateString().Replace("/", ""); + strArrays[4] = ".xlsx"; + str7 = string.Concat(strArrays); + } + xLWorkbook.SaveAs(str7); + Process.Start(str7); + variable = null; + str2 = null; + } + + private async Task GerarHtml(List relatorioGrid, bool posicao = false) + { + DateTime dateTime; + DateTime dateTime1; + int num; + string str1; + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome("RELATÓRIO FINANCEIRO"); + DateTime? inicio = this.Inicio; + dateTime = (inicio.HasValue ? inicio.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Inicio(dateTime); + inicio = this.Fim; + dateTime1 = (inicio.HasValue ? inicio.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Fim(dateTime1); + TipoRelatorio tipoRelatorio1 = tipoRelatorio; + switch (this.SelectedFiltro) + { + case 0: + { + tipoRelatorio1.set_Nome("RELATORIO FINANCEIRO - VENCIMENTO"); + break; + } + case 1: + { + tipoRelatorio1.set_Nome("RELATORIO FINANCEIRO - BAIXA"); + break; + } + case 2: + { + tipoRelatorio1.set_Nome("RELATORIO FINANCEIRO - PAGAMENTO"); + break; + } + case 3: + { + tipoRelatorio1.set_Nome(this.SelectedFornecedor.get_Nome()); + tipoRelatorio1.set_Inicio(DateTime.MinValue); + tipoRelatorio1.set_Fim(DateTime.MinValue); + break; + } + } + List strs = Funcoes.OcultarColunasDescricao(typeof(Sintetico), "FINANCEIRO"); + List lancamentos = new List(); + List lancamentos1 = relatorioGrid; + bool flag = lancamentos1.Any((Lancamento x) => x.get_Selecionado()); + relatorioGrid.ToList().ForEach((Lancamento lancamentoGrid) => { + decimal? valorPago; + if (flag && !lancamentoGrid.get_Selecionado()) + { + return; + } + Lancamento lancamento2 = (Lancamento)lancamentoGrid.Clone(); + lancamento2.set_Valor((lancamento2.get_Sinal() == 1 ? -lancamento2.get_Valor() : lancamento2.get_Valor())); + Lancamento lancamento1 = lancamento2; + if (lancamento2.get_Sinal() == 1) + { + decimal? nullable = lancamento2.get_ValorPago(); + valorPago = (nullable.HasValue ? new decimal?(-nullable.GetValueOrDefault()) : null); + } + else + { + valorPago = lancamento2.get_ValorPago(); + } + lancamento1.set_ValorPago(valorPago); + lancamentos.Add(lancamento2); + }); + IEnumerable> groupings = lancamentos.GroupBy((Lancamento lancamento) => { + object descricao; + if (this.SinteticoTipo == 1) + { + Gestor.Model.Domain.Financeiro.Centro centro = lancamento.get_Controle().get_Centro(); + if (centro != null) + { + descricao = centro.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + } + else if (this.SinteticoTipo == null) + { + Gestor.Model.Domain.Financeiro.Planos plano = lancamento.get_Controle().get_Plano(); + if (plano != null) + { + descricao = plano.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + else + { + if (this.SinteticoTipo != 3) + { + Fornecedor fornecedor = lancamento.get_Controle().get_Fornecedor(); + if (fornecedor != null) + { + return fornecedor.get_Nome(); + } + return null; + } + BancosContas conta = lancamento.get_Conta(); + if (conta != null) + { + descricao = conta.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + return descricao; + }); + List list = groupings.Select, Gestor.Model.Domain.Relatorios.SinteticoFinanceiro>((IGrouping lancamento) => { + Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sinteticoFinanceiro = new Gestor.Model.Domain.Relatorios.SinteticoFinanceiro(); + sinteticoFinanceiro.set_Agrupamento(lancamento.Key ?? "TRANSFERÊNCIAS"); + sinteticoFinanceiro.set_Valor(new decimal?(lancamento.Sum((Lancamento sintetic) => sintetic.get_Valor()))); + sinteticoFinanceiro.set_ValorPago(new decimal?(lancamento.Sum((Lancamento sintetic) => sintetic.get_ValorPago()).GetValueOrDefault())); + return sinteticoFinanceiro; + }).ToList(); + List sinteticoFinanceiros = list; + list = ( + from lancamento in sinteticoFinanceiros + orderby lancamento.get_Agrupamento() + select lancamento).ToList(); + List sinteticoFinanceiros1 = list; + Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sinteticoFinanceiro1 = new Gestor.Model.Domain.Relatorios.SinteticoFinanceiro(); + sinteticoFinanceiro1.set_Agrupamento("TOTAL"); + List sinteticoFinanceiros2 = list; + sinteticoFinanceiro1.set_Valor(sinteticoFinanceiros2.Sum((Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sintetic) => sintetic.get_Valor())); + List sinteticoFinanceiros3 = list; + sinteticoFinanceiro1.set_ValorPago(sinteticoFinanceiros3.Sum((Gestor.Model.Domain.Relatorios.SinteticoFinanceiro sintetic) => sintetic.get_ValorPago())); + sinteticoFinanceiros1.Add(sinteticoFinanceiro1); + string str2 = await Funcoes.GenerateTable(list, strs, false, false, "", null); + string str3 = Funcoes.CreateCard(string.Concat("SINTÉTICO ", EnumHelper.GetDescription(this.SinteticoTipo)), str2, false); + IEnumerable> groupings1 = lancamentos.GroupBy((Lancamento lancamento) => { + object descricao; + if (this.SinteticoTipo == 1) + { + Gestor.Model.Domain.Financeiro.Centro centro = lancamento.get_Controle().get_Centro(); + if (centro != null) + { + descricao = centro.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + descricao = ""; + } + } + else if (this.SinteticoTipo == null) + { + Gestor.Model.Domain.Financeiro.Planos plano = lancamento.get_Controle().get_Plano(); + if (plano != null) + { + descricao = plano.get_Nome(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + else + { + if (this.SinteticoTipo != 3) + { + Fornecedor fornecedor = lancamento.get_Controle().get_Fornecedor(); + if (fornecedor != null) + { + return fornecedor.get_Nome(); + } + return null; + } + BancosContas conta = lancamento.get_Conta(); + if (conta != null) + { + descricao = conta.get_Descricao(); + } + else + { + descricao = null; + } + if (descricao == null) + { + return ""; + } + } + return descricao; + }); + List list1 = ( + from lancamento in groupings1 + select lancamento.Key).Distinct().ToList(); + foreach (string str4 in list1) + { + List list2 = lancamentos.Where((Lancamento lancamento) => { + string descricao; + string nome; + string str; + string nome1; + if (this.SinteticoTipo == 1) + { + Gestor.Model.Domain.Financeiro.Centro centro = lancamento.get_Controle().get_Centro(); + if (centro != null) + { + descricao = centro.get_Descricao(); + } + else + { + descricao = null; + } + return descricao == str4; + } + if (this.SinteticoTipo == null) + { + Gestor.Model.Domain.Financeiro.Planos plano = lancamento.get_Controle().get_Plano(); + if (plano != null) + { + nome = plano.get_Nome(); + } + else + { + nome = null; + } + return nome == str4; + } + if (this.SinteticoTipo == 3) + { + BancosContas conta = lancamento.get_Conta(); + if (conta != null) + { + str = conta.get_Descricao(); + } + else + { + str = null; + } + return str == str4; + } + Fornecedor fornecedor = lancamento.get_Controle().get_Fornecedor(); + if (fornecedor != null) + { + nome1 = fornecedor.get_Nome(); + } + else + { + nome1 = null; + } + return nome1 == str4; + }).ToList(); + if (list2.Count == 0) + { + continue; + } + List lancamentos2 = list2; + Lancamento lancamento3 = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + Fornecedor fornecedor1 = new Fornecedor(); + fornecedor1.set_Nome("TOTAL"); + controleFinanceiro.set_Fornecedor(fornecedor1); + lancamento3.set_Controle(controleFinanceiro); + List lancamentos3 = list2; + lancamento3.set_Valor(lancamentos3.Sum((Lancamento lancamento) => lancamento.get_Valor())); + List lancamentos4 = list2; + lancamento3.set_ValorPago(lancamentos4.Sum((Lancamento lancamento) => lancamento.get_ValorPago())); + lancamentos2.Add(lancamento3); + string str5 = await Funcoes.GenerateTable(FinanceiroViewModel.GerarRelatorio(list2), new List(), false, false, "", null); + str3 = string.Concat(str3, Funcoes.CreateCard(str4, str5, false)); + } + List configuracoes = Recursos.Configuracoes; + num = (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 14) ? 70 : 50); + int num1 = num; + TipoRelatorio tipoRelatorio2 = tipoRelatorio1; + string str6 = str3; + if (str6 == null) + { + str6 = ""; + } + string str7 = num1.ToString(); + str1 = (posicao ? "landscape" : "portrait"); + string str8 = Funcoes.ExportarHtml(tipoRelatorio2, str6, str7, str1, false, ""); + tipoRelatorio1 = null; + str3 = null; + return str8; + } + + private static List GerarRelatorio(List lancamentos) + { + return lancamentos.Select((Lancamento x) => { + string nome; + string descricao; + string str; + string descricao1; + string str1; + string nome1; + RelatorioLancamentos relatorioLancamento = new RelatorioLancamentos(); + Fornecedor fornecedor = x.get_Controle().get_Fornecedor(); + if (fornecedor != null) + { + nome = fornecedor.get_Nome(); + } + else + { + nome = null; + } + relatorioLancamento.set_Fornecedor(nome); + relatorioLancamento.set_Historico(x.get_Historico()); + relatorioLancamento.set_Observacao(x.get_Observacao()); + relatorioLancamento.set_Documento(x.get_Documento()); + relatorioLancamento.set_Parcela(x.get_Parcela()); + relatorioLancamento.set_Vencimento(x.get_Vencimento()); + relatorioLancamento.set_Valor(x.get_Valor()); + relatorioLancamento.set_Baixa(x.get_Baixa()); + relatorioLancamento.set_ValorPago(x.get_ValorPago()); + relatorioLancamento.set_Pagamento(x.get_Pagamento()); + Gestor.Model.Domain.Financeiro.Planos plano = x.get_Controle().get_Plano(); + if (plano != null) + { + descricao = plano.get_Descricao(); + } + else + { + descricao = null; + } + relatorioLancamento.set_Plano(descricao); + Gestor.Model.Domain.Financeiro.Planos plano1 = x.get_Controle().get_Plano(); + if (plano1 != null) + { + str = plano1.get_Plano().get_Descricao(); + } + else + { + str = null; + } + relatorioLancamento.set_Planos(str); + Gestor.Model.Domain.Financeiro.Centro centro = x.get_Controle().get_Centro(); + if (centro != null) + { + descricao1 = centro.get_Descricao(); + } + else + { + descricao1 = null; + } + relatorioLancamento.set_Centro(descricao1); + BancosContas conta = x.get_Conta(); + if (conta != null) + { + str1 = conta.get_Descricao(); + } + else + { + str1 = null; + } + relatorioLancamento.set_Conta(str1); + Fornecedor fornecedor1 = x.get_Controle().get_Fornecedor(); + if (fornecedor1 != null) + { + nome1 = fornecedor1.get_Nome(); + } + else + { + nome1 = null; + } + relatorioLancamento.set_Sinal((nome1 == "TOTAL" ? "" : EnumHelper.GetDescription(x.get_Sinal()))); + relatorioLancamento.set_Competencia(x.get_Competencia()); + return relatorioLancamento; + }).ToList(); + } + + public void IncluirLancamento() + { + Gestor.Model.Common.TipoPagamento? nullable; + bool hasValue; + bool flag; + bool hasValue1; + Gestor.Model.Common.TipoPagamento? tipoPagamento; + Gestor.Model.Common.Sinal sinal; + this.Alterando = Visibility.Visible; + this.BuscaHabilitada = false; + Fornecedor selectedFornecedor = null; + if (this.SelectedFiltro == 3 && this.SelectedFornecedor != null && this.SelectedFornecedor.get_Id() > (long)0) + { + selectedFornecedor = this.SelectedFornecedor; + } + this.VisibilityFornecedor = (selectedFornecedor == null ? Visibility.Visible : Visibility.Collapsed); + Fornecedor fornecedor = selectedFornecedor; + if (fornecedor != null) + { + hasValue = fornecedor.get_IdPlano().HasValue; + } + else + { + hasValue = false; + } + Gestor.Model.Domain.Financeiro.Planos plano = (hasValue ? this.PlanosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Planos x) => { + long id = x.get_Id(); + long? idPlano = selectedFornecedor.get_IdPlano(); + return id == idPlano.GetValueOrDefault() & idPlano.HasValue; + }) ?? this.PlanosFiltrados.FirstOrDefault() : this.PlanosFiltrados.FirstOrDefault()); + Fornecedor fornecedor1 = selectedFornecedor; + if (fornecedor1 != null) + { + flag = fornecedor1.get_IdConta().HasValue; + } + else + { + flag = false; + } + BancosContas bancosConta = (flag ? this.ContasFiltradas.FirstOrDefault((BancosContas x) => { + long id = x.get_Id(); + long? idConta = selectedFornecedor.get_IdConta(); + return id == idConta.GetValueOrDefault() & idConta.HasValue; + }) ?? this.ContasFiltradas.FirstOrDefault() : this.ContasFiltradas.FirstOrDefault()); + Fornecedor fornecedor2 = selectedFornecedor; + if (fornecedor2 != null) + { + hasValue1 = fornecedor2.get_IdCentro().HasValue; + } + else + { + hasValue1 = false; + } + Gestor.Model.Domain.Financeiro.Centro centro = (hasValue1 ? this.CentrosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Centro x) => { + long id = x.get_Id(); + long? idCentro = selectedFornecedor.get_IdCentro(); + return id == idCentro.GetValueOrDefault() & idCentro.HasValue; + }) ?? this.CentrosFiltrados.FirstOrDefault() : this.CentrosFiltrados.FirstOrDefault()); + Fornecedor fornecedor3 = selectedFornecedor; + if (fornecedor3 != null) + { + tipoPagamento = fornecedor3.get_TipoPagamento(); + } + else + { + nullable = null; + tipoPagamento = nullable; + } + nullable = tipoPagamento; + Gestor.Model.Common.TipoPagamento valueOrDefault = nullable.GetValueOrDefault(); + DateTime date = Funcoes.GetNetworkTime().Date; + Lancamento lancamento = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Fornecedor(selectedFornecedor); + controleFinanceiro.set_Centro(centro); + controleFinanceiro.set_Plano(plano); + controleFinanceiro.set_Parcelas(1); + lancamento.set_Controle(controleFinanceiro); + lancamento.set_Conta(bancosConta); + lancamento.set_Vencimento(date); + lancamento.set_Parcela(1); + lancamento.set_TipoPagamento(valueOrDefault); + this.SelectedLancamento = lancamento; + this.FornecedorInclusao = selectedFornecedor ?? new Fornecedor(); + this.Historico = ""; + this.Documento = ""; + this.Competencia = ""; + this.Complemento = ""; + this.Plano = plano; + this.Centro = centro; + this.Conta = bancosConta; + Gestor.Model.Domain.Financeiro.Planos plano1 = this.Plano; + if (plano1 != null) + { + sinal = plano1.get_Sinal(); + } + else + { + sinal = 0; + } + this.Sinal = sinal; + this.Parcelas = 1; + this.Parcela = 0; + this.Vencimento = date; + this.Valor = decimal.Zero; + DateTime? nullable1 = null; + this.Baixa = nullable1; + this.ValorPago = new decimal?(new decimal()); + nullable1 = null; + this.Pagamento = nullable1; + this.TipoPagamento = valueOrDefault; + this.Observacao = ""; + this.Alteracao = false; + this.VisibilityCentro = (this.CentrosFiltrados.Count > 1 ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityConta = (this.ContasFiltradas.Count > 1 ? Visibility.Visible : Visibility.Collapsed); + } + + public async void IncluirParcela() + { + bool controle; + Visibility visibility; + Visibility visibility1; + ObservableCollection lancamentosFiltrados = this.LancamentosFiltrados; + if (lancamentosFiltrados.Any((Lancamento x) => x.get_Selecionado())) + { + ObservableCollection observableCollection = this.LancamentosFiltrados; + if (observableCollection.Count((Lancamento x) => x.get_Selecionado()) == 1) + { + FinanceiroViewModel financeiroViewModel = this; + ObservableCollection lancamentosFiltrados1 = this.LancamentosFiltrados; + financeiroViewModel.SelectedLancamento = lancamentosFiltrados1.FirstOrDefault((Lancamento x) => x.get_Selecionado()); + } + ObservableCollection observableCollection1 = this.LancamentosFiltrados; + if (observableCollection1.Count((Lancamento x) => x.get_Selecionado()) <= 1) + { + Lancamento selectedLancamento = this.SelectedLancamento; + if (selectedLancamento != null) + { + controle = selectedLancamento.get_Controle(); + } + else + { + controle = false; + } + if (controle && this.SelectedLancamento.get_Controle().get_Id() != 0) + { + this.VisibilityFornecedor = Visibility.Collapsed; + this.Alterando = Visibility.Visible; + this.BuscaHabilitada = false; + Lancamento lancamento = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Centro(this.SelectedLancamento.get_Controle().get_Centro()); + controleFinanceiro.set_Fornecedor(this.SelectedLancamento.get_Controle().get_Fornecedor()); + controleFinanceiro.set_Historico(this.SelectedLancamento.get_Controle().get_Historico()); + controleFinanceiro.set_Id(this.SelectedLancamento.get_Controle().get_Id()); + controleFinanceiro.set_Parcelas(this.SelectedLancamento.get_Controle().get_Parcelas() + 1); + controleFinanceiro.set_Plano(this.SelectedLancamento.get_Controle().get_Plano()); + lancamento.set_Controle(controleFinanceiro); + lancamento.set_Historico(this.SelectedLancamento.get_Historico()); + lancamento.set_Observacao(this.SelectedLancamento.get_Observacao()); + DateTime vencimento = this.SelectedLancamento.get_Vencimento(); + lancamento.set_Vencimento(vencimento.AddMonths(1)); + lancamento.set_Conta(this.SelectedLancamento.get_Conta()); + lancamento.set_Parcela(this.SelectedLancamento.get_Parcela() + 1); + lancamento.set_Documento(this.SelectedLancamento.get_Documento()); + lancamento.set_Sinal(this.SelectedLancamento.get_Sinal()); + lancamento.set_TipoPagamento(this.SelectedLancamento.get_TipoPagamento()); + lancamento.set_Valor(this.SelectedLancamento.get_Valor()); + this.SelectedLancamento = lancamento; + FinanceiroViewModel financeiroViewModel1 = this; + visibility = (this.CentrosFiltrados.Count > 1 ? Visibility.Visible : Visibility.Collapsed); + financeiroViewModel1.VisibilityCentro = visibility; + FinanceiroViewModel financeiroViewModel2 = this; + visibility1 = (this.ContasFiltradas.Count > 1 ? Visibility.Visible : Visibility.Collapsed); + financeiroViewModel2.VisibilityConta = visibility1; + } + } + else if (await base.ShowMessage("HÁ MAIS DE UM LANÇAMENTO SELECIONADO, DESEJA FAZER A INCLUSÃO DE NOVAS PARCELAS PARA TODOS OS LANÇAMENTOS SELECIONADOS?", "SIM", "NÃO", false)) + { + await this.AdicionarParcelaRange(); + } + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM LANCAMENTOS PARA INCLUIR UMA NOVA PARCELA.", "OK", "", false); + } + } + + public void LimparFiltros() + { + this.FiltroPersonalizadoSelecionado = null; + this.VisibleFiltros = Visibility.Collapsed; + } + + public void LimparLancamentos() + { + this.Lancamentos = new ObservableCollection(); + this.LancamentosFiltrados = new ObservableCollection(); + this.LimparFiltros(); + } + + public async Task ParseOfx(BancosContas conta) + { + FinanceiroViewModel.u003cu003ec__DisplayClass256_1 variable = null; + Func func2 = null; + this.SelectedStatusImportacao = 2; + this.Importando = true; + this.VisibleFiltros = Visibility.Collapsed; + List ofxDocuments = await base.ImportarOfx(); + if (ofxDocuments == null || ofxDocuments.Count == 0) + { + this.Importando = false; + } + else + { + List strs = new List() + { + "0237", + "033" + }; + List lancamentos = new List(); + foreach (OfxDocument ofxDocument in ofxDocuments) + { + Tuple tuple = this.CorrigeLancamentos(ofxDocument, strs); + ofxDocument.set_StatementStart(tuple.Item1); + ofxDocument.set_StatementEnd(tuple.Item2); + FinanceiroServico financeiroServico = this._servico; + DateTime statementStart = ofxDocument.get_StatementStart(); + DateTime dateTime2 = statementStart.AddDays(-5); + statementStart = ofxDocument.get_StatementEnd(); + List lancamentos1 = await financeiroServico.BuscarLancamentos(dateTime2, statementStart.AddDays(5), conta.get_Id()); + List lancamentos2 = lancamentos1; + ofxDocument.get_Transactions().ForEach((Transaction t) => { + DateTime dateTime1; + bool length; + string str; + string str1; + string str2; + string str3; + string str4; + if (t.get_Date() < ofxDocument.get_StatementStart().AddDays(-5) && t.get_Date() < ofxDocument.get_StatementEnd().AddDays(5)) + { + List cSu0024u003cu003e8_locals1 = strs; + Func u003cu003e9_2 = func2; + if (u003cu003e9_2 == null) + { + FinanceiroViewModel.u003cu003ec__DisplayClass256_1 cSu0024u003cu003e8_locals2 = variable; + Func func = (string c) => c == this.x.get_Account().get_BankId().Trim(); + Func func1 = func; + cSu0024u003cu003e8_locals2.u003cu003e9__2 = func; + u003cu003e9_2 = func1; + } + if (!cSu0024u003cu003e8_locals1.Any(u003cu003e9_2)) + { + return; + } + } + Gestor.Model.Common.Sinal sinal = (t.get_Amount() < decimal.Zero ? 1 : 0); + Lancamento lancamento = lancamentos2.FirstOrDefault((Lancamento l) => { + if ((!l.get_ValorPago().HasValue || !(Math.Abs(l.get_ValorPago().Value) > decimal.Zero) || !(Math.Abs(l.get_ValorPago().Value) == Math.Abs(t.get_Amount()))) && !(Math.Abs(l.get_Valor()) == Math.Abs(t.get_Amount())) || l.get_Sinal() != sinal || l.get_Documento() == null || !t.get_TransactionId().Contains(l.get_Documento())) + { + return false; + } + DateTime? pagamento = l.get_Pagamento(); + DateTime date = t.get_Date(); + if ((pagamento.HasValue ? pagamento.GetValueOrDefault() == date : false) || l.get_Vencimento() == t.get_Date()) + { + return true; + } + DateTime vencimento = l.get_Vencimento(); + date = t.get_Date(); + if (vencimento < date.AddDays(-5)) + { + return false; + } + DateTime dateTime = l.get_Vencimento(); + date = t.get_Date(); + return dateTime <= date.AddDays(5); + }); + Gestor.Model.Common.TipoPagamento tipoPagamento = t.get_TransType().ParseTransactionType(); + string transactionId = t.get_TransactionId(); + length = (transactionId != null ? transactionId.Trim().Length > 50 : false); + if (length) + { + string transactionId1 = t.get_TransactionId(); + if (transactionId1 != null) + { + string str5 = transactionId1.Trim(); + if (str5 != null) + { + str = str5.Substring(0, 50); + } + else + { + str = null; + } + } + else + { + str = null; + } + } + else + { + string transactionId2 = t.get_TransactionId(); + if (transactionId2 != null) + { + str = transactionId2.Trim(); + } + else + { + str = null; + } + } + string str6 = str; + if (lancamento == null) + { + Lancamento lancamento1 = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Fornecedor(null); + controleFinanceiro.set_Centro(this.Centros.FirstOrDefault()); + controleFinanceiro.set_Plano(null); + controleFinanceiro.set_Parcelas(1); + string memo = t.get_Memo(); + if (memo != null) + { + str1 = memo.Trim(); + } + else + { + str1 = null; + } + controleFinanceiro.set_Historico(str1); + lancamento1.set_Controle(controleFinanceiro); + lancamento1.set_Valor(Math.Abs(t.get_Amount())); + lancamento1.set_ValorPago(new decimal?(Math.Abs(t.get_Amount()))); + string memo1 = t.get_Memo(); + if (memo1 != null) + { + str2 = memo1.Trim(); + } + else + { + str2 = null; + } + lancamento1.set_Historico(str2); + lancamento1.set_Sinal((t.get_Amount() < decimal.Zero ? 1 : 0)); + lancamento1.set_Conta(conta); + lancamento1.set_Vencimento(t.get_Date()); + lancamento1.set_Baixa(new DateTime?(t.get_Date())); + lancamento1.set_Pagamento(new DateTime?(t.get_Date())); + string transactionId3 = t.get_TransactionId(); + if (transactionId3 != null) + { + str3 = transactionId3.Trim(); + } + else + { + str3 = null; + } + lancamento1.set_Documento(str3); + lancamento1.set_TipoPagamento(tipoPagamento); + dateTime1 = t.get_Date(); + lancamento1.set_Competencia(dateTime1.ToString("MM/yyyy")); + lancamento1.set_Parcela(1); + string transactionId4 = t.get_TransactionId(); + if (transactionId4 != null) + { + str4 = transactionId4.Trim(); + } + else + { + str4 = null; + } + lancamento1.set_CodigoBanco(str4); + lancamento1.set_Baixado(false); + lancamento = lancamento1; + } + else + { + lancamento.set_Baixado(lancamento.get_Baixa().HasValue); + lancamento.set_Conta(conta); + lancamento.set_ValorPago(new decimal?(Math.Abs(t.get_Amount()))); + dateTime1 = t.get_Date(); + lancamento.set_Competencia(dateTime1.ToString("MM/yyyy")); + lancamento.set_Baixa((!lancamento.get_Baixa().HasValue ? new DateTime?(t.get_Date()) : lancamento.get_Baixa())); + lancamento.set_Pagamento((!lancamento.get_Pagamento().HasValue ? new DateTime?(t.get_Date()) : lancamento.get_Pagamento())); + lancamento.set_Documento(str6); + lancamento.set_CodigoBanco(t.get_TransactionId()); + lancamento.set_TipoPagamento((lancamento.get_TipoPagamento() == null ? tipoPagamento : lancamento.get_TipoPagamento())); + } + lancamentos.Add(lancamento); + }); + } + this.Lancamentos = new ObservableCollection(lancamentos); + this.LancamentosFiltrados = this.Lancamentos; + ExtensionMethods.ForEach(this.LancamentosFiltrados, (Lancamento x) => this.SelecionarLancamento(x)); + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + } + } + + public void PesquisaPersonalizada() + { + List list = ( + from x in this.PersonalizadoSelecionado + where !x.get_Propriedade().Contains(".") + select x).ToList(); + List list1 = this.Lancamentos.ToList().CustomWhere(list, false); + ( + from x in this.PersonalizadoSelecionado + where x.get_Propriedade().Contains(".") + select x).ToList().ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => { + string str = x.get_Nome(); + if (str == "FORNECEDOR") + { + list1 = list1.Where((Lancamento l) => { + bool nomeSocial; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + nomeSocial = (fornecedor != null ? fornecedor.get_NomeSocial() : false); + } + else + { + nomeSocial = false; + } + if (!nomeSocial) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(l.get_Controle().get_Fornecedor().get_NomeSocial().ToLower().Trim()).Contains(Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(x.get_ValorIncial().ToLower().Trim())); + }).ToList(); + return; + } + if (str == "FORNECEDOR ATIVO") + { + if (x.get_ValorIncial().Trim().Equals("SIM")) + { + List lancamentos = list1; + Func u003cu003e9_3584 = FinanceiroViewModel.u003cu003ec.u003cu003e9__358_4; + if (u003cu003e9_3584 == null) + { + u003cu003e9_3584 = (Lancamento l) => { + bool flag; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + fornecedor.get_Ativo(); + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + if (!flag) + { + return false; + } + return l.get_Controle().get_Fornecedor().get_Ativo(); + }; + FinanceiroViewModel.u003cu003ec.u003cu003e9__358_4 = u003cu003e9_3584; + } + list1 = lancamentos.Where(u003cu003e9_3584).ToList(); + return; + } + if (x.get_ValorIncial().Equals("NÃO")) + { + List lancamentos1 = list1; + Func u003cu003e9_3585 = FinanceiroViewModel.u003cu003ec.u003cu003e9__358_5; + if (u003cu003e9_3585 == null) + { + u003cu003e9_3585 = (Lancamento l) => { + bool flag; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + fornecedor.get_Ativo(); + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + if (!flag) + { + return false; + } + return !l.get_Controle().get_Fornecedor().get_Ativo(); + }; + FinanceiroViewModel.u003cu003ec.u003cu003e9__358_5 = u003cu003e9_3585; + } + list1 = lancamentos1.Where(u003cu003e9_3585).ToList(); + return; + } + } + else + { + if (str == "CONTA") + { + list1 = list1.Where((Lancamento l) => { + bool descricao; + BancosContas conta = l.get_Conta(); + descricao = (conta != null ? conta.get_Descricao() : false); + if (!descricao) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(l.get_Conta().get_Descricao().ToLower().Trim()).Contains(Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(x.get_ValorIncial().ToLower().Trim())); + }).ToList(); + return; + } + if (str == "PLANO DE CONTAS") + { + list1 = list1.Where((Lancamento l) => { + bool descricao; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle.get_Plano(); + descricao = (plano != null ? plano.get_Descricao() : false); + } + else + { + descricao = false; + } + if (!descricao) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(l.get_Controle().get_Plano().get_Descricao().ToLower().Trim()).Contains(Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(x.get_ValorIncial().ToLower().Trim())); + }).ToList(); + return; + } + if (str == "CENTRO DE CUSTO") + { + list1 = list1.Where((Lancamento l) => { + bool descricao; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Centro centro = controle.get_Centro(); + descricao = (centro != null ? centro.get_Descricao() : false); + } + else + { + descricao = false; + } + if (!descricao) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(l.get_Controle().get_Centro().get_Descricao().ToLower().Trim()).Contains(Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(x.get_ValorIncial().ToLower().Trim())); + }).ToList(); + return; + } + if (str != "PLANO") + { + return; + } + list1 = list1.Where((Lancamento l) => { + bool nome; + ControleFinanceiro controle = l.get_Controle(); + if (controle != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle.get_Plano(); + nome = (plano != null ? plano.get_Nome() : false); + } + else + { + nome = false; + } + if (!nome) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(l.get_Controle().get_Plano().get_Nome().ToLower().Trim()).Contains(Gestor.Common.Validation.ValidationHelper.AlphanumericAndSpace(x.get_ValorIncial().ToLower().Trim())); + }).ToList(); + } + }); + this.LancamentosFiltrados = new ObservableCollection(list1); + } + + public async void PopularFiltro() + { + if (this.FiltroPersonalizado == null || this.FiltroPersonalizado.Count <= 0) + { + this.FiltroPersonalizado = new List(); + List fornecedors = await (new BaseServico()).BuscarFornecedor(); + List list = fornecedors.Select((Fornecedor x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Tipo(0); + filtroPersonalizado.set_Descricao(string.Concat(x.get_Nome(), " ", x.get_Documento())); + filtroPersonalizado.set_Id(x.get_Id()); + return filtroPersonalizado; + }).ToList(); + this.FiltroPersonalizado.AddRange(list); + List centros = this.Centros; + list = centros.Select((Gestor.Model.Domain.Financeiro.Centro x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Tipo(2); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + filtroPersonalizado.set_Id(x.get_Id()); + return filtroPersonalizado; + }).ToList(); + this.FiltroPersonalizado.AddRange(list); + List planos = this.Planos; + list = planos.Select((Gestor.Model.Domain.Financeiro.Planos x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Tipo(1); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + filtroPersonalizado.set_Id(x.get_Id()); + return filtroPersonalizado; + }).ToList(); + this.FiltroPersonalizado.AddRange(list); + List contas = this.Contas; + list = contas.Select((BancosContas x) => { + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado.set_Tipo(3); + filtroPersonalizado.set_Descricao(x.get_Descricao()); + filtroPersonalizado.set_Id(x.get_Id()); + return filtroPersonalizado; + }).ToList(); + this.FiltroPersonalizado.AddRange(list); + List filtroPersonalizados = this.FiltroPersonalizado; + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado1 = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado1.set_Descricao(EnumHelper.GetDescription(0)); + filtroPersonalizado1.set_Id((long)0); + filtroPersonalizado1.set_Tipo(4); + filtroPersonalizados.Add(filtroPersonalizado1); + List filtroPersonalizados1 = this.FiltroPersonalizado; + Gestor.Model.Domain.Financeiro.FiltroPersonalizado filtroPersonalizado2 = new Gestor.Model.Domain.Financeiro.FiltroPersonalizado(); + filtroPersonalizado2.set_Descricao(EnumHelper.GetDescription(1)); + filtroPersonalizado2.set_Id((long)1); + filtroPersonalizado2.set_Tipo(4); + filtroPersonalizados1.Add(filtroPersonalizado2); + } + } + + public async Task Print(List relatorioGrid, bool posicao = false) + { + string tempPath = Path.GetTempPath(); + string str = await this.GerarHtml(relatorioGrid, posicao); + string str1 = string.Format("{0}RELATORIO FINANCEIRO_{1:ddMMyyyyhhmmss}.html", tempPath, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + tempPath = null; + } + + public async Task>> Salvar(Transferencia transferencia) + { + List> keyValuePairs; + List> keyValuePairs1 = transferencia.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validar(transferencia)); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Historico("TRANSFERÊNCIA ENTRE CONTAS"); + controleFinanceiro.set_Parcelas(2); + ControleFinanceiro controleFinanceiro1 = controleFinanceiro; + Lancamento lancamento = new Lancamento(); + lancamento.set_Controle(controleFinanceiro1); + lancamento.set_Historico("TRANSFERÊNCIA ENTRE CONTAS"); + lancamento.set_Vencimento(transferencia.get_Data()); + lancamento.set_Conta(transferencia.get_Origem()); + lancamento.set_Valor(transferencia.get_Valor()); + lancamento.set_ValorPago(new decimal?(transferencia.get_Valor())); + lancamento.set_Pagamento(new DateTime?(transferencia.get_Data())); + lancamento.set_Baixa(new DateTime?(transferencia.get_Data())); + lancamento.set_Parcela(1); + lancamento.set_Sinal(1); + lancamento.set_TipoPagamento(11); + Lancamento lancamento1 = lancamento; + Lancamento lancamento2 = new Lancamento(); + lancamento2.set_Controle(controleFinanceiro1); + lancamento2.set_Historico("TRANSFERÊNCIA ENTRE CONTAS"); + lancamento2.set_Vencimento(transferencia.get_Data()); + lancamento2.set_Conta(transferencia.get_Destino()); + lancamento2.set_Valor(transferencia.get_Valor()); + lancamento2.set_ValorPago(new decimal?(transferencia.get_Valor())); + lancamento2.set_Pagamento(new DateTime?(transferencia.get_Data())); + lancamento2.set_Baixa(new DateTime?(transferencia.get_Data())); + lancamento2.set_Parcela(2); + lancamento2.set_Sinal(0); + lancamento2.set_TipoPagamento(11); + if (await this._servico.Transferir(lancamento1, lancamento2)) + { + await this.CarregarSaldos(); + base.ToggleSnackBar("TRANSFERÊNCIA REALIZADA COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + public async Task>> Salvar() + { + List> keyValuePairs; + DateTime? nullable; + DateTime vencimento; + decimal? nullable1; + DateTime? pagamento; + DateTime? baixa; + string str; + long? nullable2; + object historico; + bool flag; + long num; + List> keyValuePairs1 = this.SelectedLancamento.Validate(); + if (keyValuePairs1 == null) + { + keyValuePairs1 = new List>(); + } + List> keyValuePairs2 = keyValuePairs1; + List> keyValuePairs3 = keyValuePairs2; + keyValuePairs3.AddRange(await this.Validar()); + keyValuePairs3 = null; + if (keyValuePairs2.Count > 0) + { + keyValuePairs = keyValuePairs2; + } + else if (this.SelectedLancamento.get_Controle().get_Id() != (long)0 || this.SelectedLancamento.get_Controle().get_Parcelas() <= 0) + { + if (this.SelectedLancamento.get_Controle().get_Id() == 0) + { + this.VencimentoAlterado = false; + } + this.SelectedLancamento = await this._servico.Save(this.SelectedLancamento); + if (this.VencimentoAlterado && this.SelectedLancamento.get_Controle().get_Parcelas() > 1) + { + if (await base.ShowMessage("DESEJA ALTERAR O VENCIMENTO PARA OS PRÓXIMOS LANÇAMENTOS?", "SIM", "NÃO", false)) + { + await this.AlterarLancamentos(this.SelectedLancamento, true, false); + } + this.VencimentoAlterado = false; + } + if (this.SelectedLancamento.get_Controle().get_Parcelas() > 1) + { + if (await base.ShowMessage("DESEJA ALTERAR O VALOR PARA OS PRÓXIMOS LANÇAMENTOS?", "SIM", "NÃO", false)) + { + await this.AlterarLancamentos(this.SelectedLancamento, false, true); + } + } + if (this._servico.Sucesso) + { + await this.Buscar(); + base.ToggleSnackBar("LANÇAMENTO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + List lancamentos = new List(); + for (int i = 1; i <= this.SelectedLancamento.get_Controle().get_Parcelas(); i++) + { + Lancamento lancamento = new Lancamento(); + ControleFinanceiro controleFinanceiro = new ControleFinanceiro(); + controleFinanceiro.set_Centro(this.SelectedLancamento.get_Controle().get_Centro()); + controleFinanceiro.set_Fornecedor(this.SelectedLancamento.get_Controle().get_Fornecedor()); + controleFinanceiro.set_Historico(this.SelectedLancamento.get_Controle().get_Historico()); + controleFinanceiro.set_Id(this.SelectedLancamento.get_Controle().get_Id()); + controleFinanceiro.set_Parcelas(this.SelectedLancamento.get_Controle().get_Parcelas()); + controleFinanceiro.set_Plano(this.SelectedLancamento.get_Controle().get_Plano()); + lancamento.set_Controle(controleFinanceiro); + lancamento.set_Historico(this.SelectedLancamento.get_Historico()); + lancamento.set_Observacao(this.SelectedLancamento.get_Observacao()); + lancamento.set_Complemento(this.SelectedLancamento.get_Complemento()); + lancamento.set_Competencia(this.SelectedLancamento.get_Competencia()); + if (i == 1) + { + vencimento = this.SelectedLancamento.get_Vencimento(); + } + else + { + DateTime dateTime = this.SelectedLancamento.get_Vencimento(); + vencimento = dateTime.AddMonths(i - 1); + } + lancamento.set_Vencimento(vencimento); + lancamento.set_Conta(this.SelectedLancamento.get_Conta()); + nullable1 = (i == 1 ? this.SelectedLancamento.get_ValorPago() : new decimal?(new decimal())); + lancamento.set_ValorPago(nullable1); + if (i == 1) + { + pagamento = this.SelectedLancamento.get_Pagamento(); + } + else + { + nullable = null; + pagamento = nullable; + } + lancamento.set_Pagamento(pagamento); + if (i == 1) + { + baixa = this.SelectedLancamento.get_Baixa(); + } + else + { + nullable = null; + baixa = nullable; + } + lancamento.set_Baixa(baixa); + lancamento.set_Parcela(i); + str = (i == 1 ? this.SelectedLancamento.get_Documento() : ""); + lancamento.set_Documento(str); + lancamento.set_Sinal(this.SelectedLancamento.get_Sinal()); + lancamento.set_TipoPagamento(this.SelectedLancamento.get_TipoPagamento()); + lancamento.set_Valor(this.SelectedLancamento.get_Valor()); + lancamentos.Add(lancamento); + } + List lancamentos1 = await this._servico.AddRange(lancamentos); + this.SelectedLancamento = lancamentos1.FirstOrDefault(); + FinanceiroViewModel financeiroViewModel = this; + Lancamento selectedLancamento = this.SelectedLancamento; + if (selectedLancamento != null) + { + nullable2 = new long?(selectedLancamento.get_Id()); + } + else + { + nullable2 = null; + } + object obj = nullable2; + Lancamento selectedLancamento1 = this.SelectedLancamento; + if (selectedLancamento1 != null) + { + historico = selectedLancamento1.get_Historico(); + } + else + { + historico = null; + } + string str1 = string.Format("INSERIU O LANÇAMENTO DO ID {0} HISTORICO: {1}", obj, historico); + Lancamento lancamento1 = this.SelectedLancamento; + if (lancamento1 != null) + { + lancamento1.get_Id(); + flag = false; + } + else + { + flag = true; + } + num = (flag ? (long)0 : this.SelectedLancamento.get_Id()); + financeiroViewModel.RegistrarAcao(str1, num, new TipoTela?(25), null); + this.VencimentoAlterado = false; + keyValuePairs = null; + } + keyValuePairs2 = null; + return keyValuePairs; + } + + public async Task SalvarImportacao(List list) + { + bool flag; + DateTime? baixa; + DateTime? nullable; + string[] strArrays; + bool flag1; + bool flag2; + string historico; + object obj; + bool flag3; + long num; + Lancamento lancamento = null; + List lancamentos = new List(); + List lancamentos1 = new List(); + List lancamentos2 = new List(); + List lancamentos3 = new List(); + foreach (Lancamento lancamento in list) + { + if (lancamento.get_Baixado()) + { + continue; + } + if (!lancamento.get_Selecionado()) + { + baixa = null; + lancamento.set_Baixa(baixa); + } + baixa = lancamento.get_Baixa(); + if (baixa.HasValue) + { + Saldo saldo = await this.VerificaSaldo(lancamento.get_Conta().get_Id(), false); + if (saldo == null) + { + continue; + } + baixa = saldo.get_DataInicio(); + nullable = lancamento.get_Baixa(); + flag1 = (baixa.HasValue & nullable.HasValue ? baixa.GetValueOrDefault() > nullable.GetValueOrDefault() : false); + if (flag1) + { + continue; + } + } + string observacao = lancamento.get_Observacao(); + if (observacao != null) + { + strArrays = observacao.Split(new char[] { '\n' }); + } + else + { + strArrays = null; + } + string[] strArrays1 = strArrays; + StringBuilder stringBuilder = new StringBuilder(); + string str = "IMPORTAÇÃO OFX REALIZADA PELO USUÁRIO"; + if (strArrays1 != null) + { + string[] strArrays2 = strArrays1; + for (int i = 0; i < (int)strArrays2.Length; i++) + { + string str1 = strArrays2[i]; + if (str1.IndexOf(str, StringComparison.InvariantCulture) != 0) + { + stringBuilder.Append(string.Concat(str1, "\n")); + } + } + } + Lancamento lancamento1 = lancamento; + object[] id = new object[] { stringBuilder, Recursos.Usuario.get_Id(), Recursos.Usuario.get_Nome(), null }; + DateTime networkTime = Funcoes.GetNetworkTime(); + id[3] = networkTime.ToString("F").ToUpper(); + lancamento1.set_Observacao(string.Format("{0}IMPORTAÇÃO OFX REALIZADA PELO USUÁRIO {1} {2} EM {3}", id)); + if (lancamento.get_Id() <= (long)0) + { + lancamentos2.Add(lancamento); + } + else + { + nullable = lancamento.get_Baixa(); + if (!nullable.HasValue) + { + lancamentos.Add(lancamento); + } + else + { + lancamentos1.Add(lancamento); + } + } + lancamentos3.Add(lancamento); + } + if (lancamentos3.Count != 0) + { + object[] count = new object[] { lancamentos2.Count, Environment.NewLine, lancamentos.Count, Environment.NewLine, lancamentos1.Count, Environment.NewLine, Environment.NewLine }; + if (await base.ShowMessage(string.Format("{0} LANÇAMENTOS SERÃO CRIADOS.{1}{2} LANÇAMENTOS SERÃO ATUALIZADOS.{3}{4} LANÇAMENTOS SERÃO BAIXADOS.{5}{6}DESEJA REALMENTE PROSSEGUIR?", count), "SIM", "NÃO", false)) + { + bool flag4 = true; + foreach (Lancamento lancamento2 in lancamentos3) + { + await this._servico.Save(lancamento2); + flag4 = (flag4 ? this._servico.Sucesso : false); + flag2 = (lancamento2 == null ? false : lancamento2.get_Id() != (long)0); + if (flag2 & flag4) + { + FinanceiroViewModel financeiroViewModel = this; + object id1 = lancamento2.get_Id(); + Lancamento lancamento3 = lancamento2; + if (lancamento3 != null) + { + obj = lancamento3.get_Historico(); + } + else + { + obj = null; + } + string str2 = string.Format("BAIXOU/ATUALIZOU O LANÇAMENTO DO ID {0}POR IMPORTAÇÃO HISTORICO: {1}", id1, obj); + Lancamento lancamento4 = lancamento2; + if (lancamento4 != null) + { + lancamento4.get_Id(); + flag3 = false; + } + else + { + flag3 = true; + } + num = (flag3 ? (long)0 : lancamento2.get_Id()); + financeiroViewModel.RegistrarAcao(str2, num, new TipoTela?(25), null); + } + else if (lancamento2 != null & flag4) + { + FinanceiroViewModel financeiroViewModel1 = this; + Lancamento lancamento5 = lancamento2; + if (lancamento5 != null) + { + historico = lancamento5.get_Historico(); + } + else + { + historico = null; + } + financeiroViewModel1.RegistrarAcao(string.Concat("INSERIU O LANÇAMENTO POR IMPORTAÇÃO HISTORICO: ", historico), (long)0, new TipoTela?(25), null); + } + } + if (flag4) + { + await this.Buscar(); + base.ToggleSnackBar("ATUALIZAÇÃO REALIZADA COM SUCESSO", true); + await this.CarregarSaldos(); + flag = true; + } + else + { + await base.ShowMessage("HOUVERAM PROBLEMAS AO INCLUIR OU ATUALIZAR LANÇAMENTOS, FAVOR CONFERIR A IMPORTAÇÃO.", "OK", "", false); + flag = false; + } + } + else + { + base.Loading(false); + flag = false; + } + } + else + { + await base.ShowMessage("NÃO HÁ LANÇAMENTOS PARA SEREM ATUALIZADOS.", "OK", "", false); + base.Loading(false); + flag = false; + } + lancamentos = null; + lancamentos1 = null; + lancamentos2 = null; + lancamentos3 = null; + return flag; + } + + public void SelecionarLancamento(Lancamento lancamento) + { + Lancamento lancamento1 = (lancamento.get_Id() > (long)0 ? this.LancamentosFiltrados.First((Lancamento x) => x.get_Id() == lancamento.get_Id()) : this.LancamentosFiltrados.First((Lancamento x) => { + long? nullable; + long? nullable1; + long? nullable2; + long? nullable3; + long? nullable4; + if (x.get_Id() == lancamento.get_Id()) + { + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + Fornecedor fornecedor = controle.get_Fornecedor(); + if (fornecedor != null) + { + nullable1 = new long?(fornecedor.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable5 = nullable1; + ControleFinanceiro controleFinanceiro = lancamento.get_Controle(); + if (controleFinanceiro != null) + { + Fornecedor fornecedor1 = controleFinanceiro.get_Fornecedor(); + if (fornecedor1 != null) + { + nullable2 = new long?(fornecedor1.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + } + else + { + nullable = null; + nullable2 = nullable; + } + long? nullable6 = nullable2; + if (nullable5.GetValueOrDefault() == nullable6.GetValueOrDefault() & nullable5.HasValue == nullable6.HasValue && x.get_Valor() == lancamento.get_Valor() && x.get_Vencimento() == lancamento.get_Vencimento()) + { + ControleFinanceiro controle1 = x.get_Controle(); + if (controle1 != null) + { + Gestor.Model.Domain.Financeiro.Planos plano = controle1.get_Plano(); + if (plano != null) + { + nullable3 = new long?(plano.get_Id()); + } + else + { + nullable = null; + nullable3 = nullable; + } + } + else + { + nullable = null; + nullable3 = nullable; + } + nullable6 = nullable3; + ControleFinanceiro controleFinanceiro1 = lancamento.get_Controle(); + if (controleFinanceiro1 != null) + { + Gestor.Model.Domain.Financeiro.Planos plano1 = controleFinanceiro1.get_Plano(); + if (plano1 != null) + { + nullable4 = new long?(plano1.get_Id()); + } + else + { + nullable = null; + nullable4 = nullable; + } + } + else + { + nullable = null; + nullable4 = nullable; + } + nullable5 = nullable4; + if (nullable6.GetValueOrDefault() == nullable5.GetValueOrDefault() & nullable6.HasValue == nullable5.HasValue) + { + return lancamento.get_Documento() == x.get_Documento(); + } + } + } + return false; + })); + DateTime date = Funcoes.GetNetworkTime().Date; + lancamento1.set_Selecionado(true); + Lancamento lancamento2 = lancamento1; + DateTime? baixa = lancamento1.get_Baixa(); + lancamento2.set_Baixa(new DateTime?((baixa.HasValue ? baixa.GetValueOrDefault() : lancamento1.get_Pagamento().GetValueOrDefault(date)))); + baixa = lancamento1.get_Pagamento(); + lancamento1.set_Pagamento(new DateTime?(baixa.GetValueOrDefault(date))); + Lancamento lancamento3 = lancamento1; + decimal? valorPago = lancamento1.get_ValorPago(); + decimal num = new decimal(); + lancamento3.set_ValorPago(((valorPago.GetValueOrDefault() == num) & valorPago.HasValue ? new decimal?(lancamento.get_Valor()) : lancamento1.get_ValorPago())); + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + this.Totalizar(); + } + + public void SelecionarTodos() + { + List list = this.LancamentosFiltrados.ToList(); + list.ForEach((Lancamento x) => { + DateTime? baixa; + decimal num; + x.set_Selecionado(!x.get_Selecionado()); + if (x.get_Baixado() || this.importando) + { + return; + } + if (!x.get_Selecionado()) + { + baixa = null; + x.set_Baixa(baixa); + baixa = null; + x.set_Pagamento(baixa); + num = new decimal(); + x.set_ValorPago(new decimal?(num)); + return; + } + DateTime date = Funcoes.GetNetworkTime().Date; + Lancamento lancamento = x; + baixa = x.get_Baixa(); + lancamento.set_Baixa((!baixa.HasValue ? new DateTime?(date) : x.get_Baixa())); + x.set_Baixa(new DateTime?(date)); + Lancamento lancamento1 = x; + baixa = x.get_Pagamento(); + lancamento1.set_Pagamento((!baixa.HasValue ? new DateTime?(date) : x.get_Pagamento())); + Lancamento lancamento2 = x; + decimal? valorPago = x.get_ValorPago(); + num = new decimal(); + lancamento2.set_ValorPago(((valorPago.GetValueOrDefault() == num) & valorPago.HasValue ? new decimal?(x.get_Valor()) : x.get_ValorPago())); + }); + this.LancamentosFiltrados = new ObservableCollection(list); + this.LancamentosFiltradosCopia = this.LancamentosFiltrados; + } + + public void Sintetizar() + { + List list; + switch (this.SinteticoTipo) + { + case 1: + { + list = ( + from x in this.LancamentosFiltrados + where x.get_Controle().get_Plano() != null + group x by new { Id = x.get_Controle().get_Centro().get_Id(), Descricao = x.get_Controle().get_Centro().get_Descricao() }).Select((x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key.Descricao); + sintetico.set_Valor(new decimal?(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + }))); + sintetico.set_ValorPago(new decimal?(x.Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + }))); + return sintetico; + }).ToList(); + break; + } + case 2: + { + list = ( + from x in this.LancamentosFiltrados + where x.get_Controle().get_Plano() != null + group x by new { Id = x.get_Controle().get_Fornecedor().get_Id(), Nome = x.get_Controle().get_Fornecedor().get_Nome() }).Select((x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key.Nome); + sintetico.set_Valor(new decimal?(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + }))); + sintetico.set_ValorPago(new decimal?(x.Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + }))); + return sintetico; + }).ToList(); + break; + } + case 3: + { + list = ( + from x in this.LancamentosFiltrados + where x.get_Controle().get_Plano() != null + group x by new { Id = x.get_Conta().get_Id(), Descricao = x.get_Conta().get_Descricao() }).Select((x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key.Descricao); + sintetico.set_Valor(new decimal?(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + }))); + sintetico.set_ValorPago(new decimal?(x.Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + }))); + return sintetico; + }).ToList(); + break; + } + case 4: + { + list = this.LancamentosFiltrados.Where((Lancamento x) => { + if (x.get_Controle().get_Plano() == null) + { + return false; + } + return x.get_Controle().get_Plano().get_Plano() != null; + }).GroupBy((Lancamento x) => new { Id = x.get_Controle().get_Plano().get_Plano().get_Id(), Descricao = x.get_Controle().get_Plano().get_Plano().get_Descricao() }).Select((x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key.Descricao); + sintetico.set_Valor(new decimal?(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + }))); + sintetico.set_ValorPago(new decimal?(x.Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + }))); + return sintetico; + }).ToList(); + break; + } + default: + { + list = ( + from x in this.LancamentosFiltrados + where x.get_Controle().get_Plano() != null + group x by new { Id = x.get_Controle().get_Plano().get_Id(), Descricao = x.get_Controle().get_Plano().get_Descricao() }).Select((x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key.Descricao); + sintetico.set_Valor(new decimal?(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + }))); + sintetico.set_ValorPago(new decimal?(x.Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + }))); + return sintetico; + }).ToList(); + break; + } + } + if (list.Count == 0) + { + return; + } + (new SinteticoView(list, "RELATORIO FINANCEIRO", this.Inicio, this.Fim)).Show(); + } + + public void Totalizar() + { + if (this.LancamentosFiltrados == null) + { + this.Totalizacao = null; + return; + } + List list = ( + from x in this.LancamentosFiltrados + where x.get_Conta() != null + group x by new { Id = x.get_Conta().get_Id(), Descricao = x.get_Conta().get_Descricao() }).Select((x) => { + Gestor.Model.Domain.Financeiro.SinteticoFinanceiro sinteticoFinanceiro = new Gestor.Model.Domain.Financeiro.SinteticoFinanceiro(); + BancosContas bancosConta = new BancosContas(); + bancosConta.set_Id(x.Key.Id); + bancosConta.set_Descricao(x.Key.Descricao); + sinteticoFinanceiro.set_Conta(bancosConta); + sinteticoFinanceiro.set_Filtrados(x.Count()); + sinteticoFinanceiro.set_Credito(x.Sum((Lancamento s) => { + if (s.get_Sinal() != null) + { + return decimal.Zero; + } + return s.get_Valor(); + })); + sinteticoFinanceiro.set_Debito(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return decimal.Zero; + } + return -s.get_Valor(); + })); + sinteticoFinanceiro.set_Liquido(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_Valor(); + } + return -s.get_Valor(); + })); + sinteticoFinanceiro.set_LiquidoPago(x.Sum((Lancamento s) => { + if (s.get_Sinal() == null) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + if (!valorPago.HasValue) + { + return null; + } + return new decimal?(-valorPago.GetValueOrDefault()); + }).GetValueOrDefault()); + sinteticoFinanceiro.set_Selecionados(x.Count((Lancamento s) => s.get_Selecionado())); + sinteticoFinanceiro.set_LiquidoSelecionados(( + from s in x + where s.get_Selecionado() + select s).Sum((Lancamento s) => { + decimal? valorPago; + decimal? nullable; + if (s.get_Sinal() == null) + { + valorPago = s.get_ValorPago(); + return valorPago.GetValueOrDefault(); + } + decimal? valorPago1 = s.get_ValorPago(); + if (valorPago1.HasValue) + { + nullable = new decimal?(-valorPago1.GetValueOrDefault()); + } + else + { + valorPago = null; + nullable = valorPago; + } + valorPago = nullable; + return valorPago.GetValueOrDefault(); + })); + return sinteticoFinanceiro; + }).ToList(); + if (list.Count > 1) + { + List sinteticoFinanceiros = list; + Gestor.Model.Domain.Financeiro.SinteticoFinanceiro sinteticoFinanceiro1 = new Gestor.Model.Domain.Financeiro.SinteticoFinanceiro(); + BancosContas bancosConta1 = new BancosContas(); + bancosConta1.set_Id((long)0); + bancosConta1.set_Descricao("TOTAL"); + sinteticoFinanceiro1.set_Conta(bancosConta1); + sinteticoFinanceiro1.set_Filtrados(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_Filtrados())); + sinteticoFinanceiro1.set_Credito(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_Credito())); + sinteticoFinanceiro1.set_Debito(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_Debito())); + sinteticoFinanceiro1.set_Liquido(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_Liquido())); + sinteticoFinanceiro1.set_LiquidoPago(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_LiquidoPago())); + sinteticoFinanceiro1.set_Selecionados(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_Selecionados())); + sinteticoFinanceiro1.set_LiquidoSelecionados(list.Sum((Gestor.Model.Domain.Financeiro.SinteticoFinanceiro x) => x.get_LiquidoSelecionados())); + sinteticoFinanceiros.Add(sinteticoFinanceiro1); + } + this.Totalizacao = new ObservableCollection(list); + } + + private async Task>> Validar(Transferencia transferencia) + { + List> keyValuePairs; + DateTime? dataFinal; + DateTime data; + bool origem; + bool destino; + bool flag; + bool flag1; + bool flag2; + bool hasValue; + List saldos1; + Saldo saldo; + List> keyValuePairs1 = Gestor.Model.Helper.ValidationHelper.AddValue(); + BancosContasServico bancosContasServico = new BancosContasServico(); + Transferencia transferencium = transferencia; + if (transferencium != null) + { + origem = transferencium.get_Origem(); + } + else + { + origem = false; + } + if (origem) + { + Transferencia transferencium1 = transferencia; + if (transferencium1 != null) + { + destino = transferencium1.get_Destino(); + } + else + { + destino = false; + } + if (destino) + { + List nums = new List() + { + transferencia.get_Origem().get_Id(), + transferencia.get_Destino().get_Id() + }; + saldos1 = await bancosContasServico.BuscarSaldoAberto(nums); + saldo = saldos1.FirstOrDefault((Saldo s) => s.get_Conta().get_Id() == transferencia.get_Origem().get_Id()); + if (saldo == null) + { + List saldos2 = await bancosContasServico.BuscarSaldos(transferencia.get_Origem().get_Id()); + List saldos3 = saldos2; + Saldo saldo1 = saldos3.Find((Saldo x) => { + DateTime? dataInicio = x.get_DataInicio(); + List saldos = saldos3; + Func u003cu003e9_3863 = FinanceiroViewModel.u003cu003ec.u003cu003e9__386_3; + if (u003cu003e9_3863 == null) + { + u003cu003e9_3863 = (Saldo r) => r.get_DataInicio(); + FinanceiroViewModel.u003cu003ec.u003cu003e9__386_3 = u003cu003e9_3863; + } + DateTime? nullable = saldos.Max(u003cu003e9_3863); + if (dataInicio.HasValue != nullable.HasValue) + { + return false; + } + if (!dataInicio.HasValue) + { + return true; + } + return dataInicio.GetValueOrDefault() == nullable.GetValueOrDefault(); + }); + dataFinal = saldo1.get_DataInicio(); + data = transferencia.get_Data(); + flag2 = (dataFinal.HasValue ? dataFinal.GetValueOrDefault() <= data : false); + if (!flag2) + { + hasValue = false; + } + else + { + dataFinal = saldo1.get_DataFinal(); + hasValue = dataFinal.HasValue; + } + bool flag3 = hasValue; + if (flag3) + { + flag3 = await base.ShowMessage("O ÚLTIMO SALDO NÃO ESTÁ ABERTO. DESEJA ABRÍ-LO AGORA E CONTINUAR?", "SIM", "NÃO", false); + } + if (flag3) + { + dataFinal = null; + saldo1.set_DataFinal(dataFinal); + saldo1.set_ValorFinal(null); + saldo = await bancosContasServico.Save(saldo1); + } + saldo1 = null; + } + if (saldo != null) + { + dataFinal = saldo.get_DataInicio(); + data = transferencia.get_Data(); + flag1 = (dataFinal.HasValue ? dataFinal.GetValueOrDefault() > data : false); + if (!flag1) + { + goto Label0; + } + } + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "SALDO", string.Concat("NÃO É POSSÍVEL REALIZAR A BAIXA DO LANÇAMENTO POIS NÃO HÁ SALDO ABERTO NO PERÍODO PARA A CONTA ", transferencia.get_Origem().get_Descricao(), "."), true); + Label0: + saldo = saldos1.FirstOrDefault((Saldo s) => s.get_Conta().get_Id() == transferencia.get_Destino().get_Id()); + if (saldo != null) + { + dataFinal = saldo.get_DataInicio(); + data = transferencia.get_Data(); + flag = (dataFinal.HasValue ? dataFinal.GetValueOrDefault() > data : false); + if (!flag) + { + goto Label1; + } + } + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "SALDO", string.Concat("NÃO É POSSÍVEL REALIZAR A BAIXA DO LANÇAMENTO POIS NÃO HÁ SALDO ABERTO NO PERÍODO PARA A CONTA ", transferencia.get_Destino().get_Descricao(), "."), true); + Label1: + keyValuePairs = keyValuePairs1; + } + else + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "DESTINO", "NÃO É POSSÍVEL FAZER UMA TRANSFERÊNCIA SEM BANDO DESTINO", true); + keyValuePairs = keyValuePairs1; + } + } + else + { + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "ORIGEM", "NÃO É POSSÍVEL FAZER UMA TRANSFERÊNCIA SEM BANDO ORIGEM", true); + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + bancosContasServico = null; + saldos1 = null; + saldo = null; + return keyValuePairs; + } + + private async Task>> Validar() + { + List> keyValuePairs; + DateTime? baixa; + DateTime? dataFinal; + bool flag; + bool flag1; + bool flag2; + bool hasValue; + List> keyValuePairs1 = Gestor.Model.Helper.ValidationHelper.AddValue(); + BancosContasServico bancosContasServico = new BancosContasServico(); + BancosContasServico bancosContasServico1 = bancosContasServico; + List contas = this.Contas; + List saldos1 = await bancosContasServico1.BuscarSaldoAberto(( + from x in contas + select x.get_Id()).ToList()); + Saldo saldo = saldos1.FirstOrDefault((Saldo s) => { + long? nullable; + long? nullable1; + long id = s.get_Conta().get_Id(); + Lancamento selectedLancamento = this.SelectedLancamento; + if (selectedLancamento != null) + { + BancosContas conta = selectedLancamento.get_Conta(); + if (conta != null) + { + nullable1 = new long?(conta.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable2 = nullable1; + return id == nullable2.GetValueOrDefault() & nullable2.HasValue; + }); + if (saldo == null) + { + Lancamento lancamento = this.SelectedLancamento; + if (lancamento != null) + { + flag1 = lancamento.get_Conta(); + } + else + { + flag1 = false; + } + if (flag1) + { + List saldos2 = await bancosContasServico.BuscarSaldos(this.SelectedLancamento.get_Conta().get_Id()); + List saldos3 = saldos2; + Saldo saldo1 = saldos3.Find((Saldo x) => { + DateTime? dataInicio = x.get_DataInicio(); + List saldos = saldos3; + Func u003cu003e9_3893 = FinanceiroViewModel.u003cu003ec.u003cu003e9__389_3; + if (u003cu003e9_3893 == null) + { + u003cu003e9_3893 = (Saldo r) => r.get_DataInicio(); + FinanceiroViewModel.u003cu003ec.u003cu003e9__389_3 = u003cu003e9_3893; + } + DateTime? nullable = saldos.Max(u003cu003e9_3893); + if (dataInicio.HasValue != nullable.HasValue) + { + return false; + } + if (!dataInicio.HasValue) + { + return true; + } + return dataInicio.GetValueOrDefault() == nullable.GetValueOrDefault(); + }); + baixa = saldo1.get_DataInicio(); + dataFinal = this.SelectedLancamento.get_Baixa(); + flag2 = (baixa.HasValue & dataFinal.HasValue ? baixa.GetValueOrDefault() <= dataFinal.GetValueOrDefault() : false); + if (!flag2) + { + hasValue = false; + } + else + { + dataFinal = saldo1.get_DataFinal(); + hasValue = dataFinal.HasValue; + } + bool flag3 = hasValue; + if (flag3) + { + flag3 = await base.ShowMessage("O ÚLTIMO SALDO NÃO ESTÁ ABERTO. DESEJA ABRÍ-LO AGORA E CONTINUAR?", "SIM", "NÃO", false); + } + if (flag3) + { + dataFinal = null; + saldo1.set_DataFinal(dataFinal); + saldo1.set_ValorFinal(null); + saldo = await bancosContasServico.Save(saldo1); + } + saldo1 = null; + } + } + if (saldo != null) + { + dataFinal = saldo.get_DataInicio(); + baixa = this.SelectedLancamento.get_Baixa(); + flag = (dataFinal.HasValue & baixa.HasValue ? dataFinal.GetValueOrDefault() > baixa.GetValueOrDefault() : false); + if (!flag) + { + keyValuePairs = new List>(); + keyValuePairs1 = null; + bancosContasServico = null; + saldo = null; + return keyValuePairs; + } + } + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "SALDO", "NÃO É POSSÍVEL REALIZAR A BAIXA DO LANÇAMENTO POIS NÃO HÁ SALDO ABERTO NO PERÍODO.", true); + keyValuePairs = keyValuePairs1; + keyValuePairs1 = null; + bancosContasServico = null; + saldo = null; + return keyValuePairs; + } + + public List> ValidateIncluir() + { + // + // Current member / type: System.Collections.Generic.List`1> Gestor.Application.ViewModels.Financeiro.FinanceiroViewModel::ValidateIncluir() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Collections.Generic.List> ValidateIncluir() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // 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 + + } + + private bool VerificaDataInvertida(OfxDocument lancamentos) + { + List strs = new List() + { + "0104" + }; + if (lancamentos.get_StatementStart() <= lancamentos.get_StatementEnd()) + { + return false; + } + return strs.Any((string banco) => banco == lancamentos.get_Account().get_BankId()); + } + + private bool VerificaFiltroErrado(OfxDocument lancamentos) + { + List strs = new List() + { + "0237", + "756" + }; + if (lancamentos.get_StatementStart() != lancamentos.get_StatementEnd()) + { + return false; + } + return strs.Any((string idbanco) => idbanco == lancamentos.get_Account().get_BankId()); + } + + private async Task VerificaSaldo(long contaId, bool reabrirSaldo) + { + BancosContasServico bancosContasServico = new BancosContasServico(); + List contas = this.Contas; + List saldos = await bancosContasServico.BuscarSaldoAberto(( + from x in contas + select x.get_Id()).ToList()); + Saldo saldo = saldos.FirstOrDefault((Saldo s) => s.get_Conta().get_Id() == contaId); + if (saldo == null & reabrirSaldo) + { + await base.ShowMessage("NÃO FOI ENCONTRADO UM SALDO ABERTO PARA FAZER A EXCLUSÃO.", "OK", "", false); + } + Saldo saldo1 = saldo; + saldo = null; + return saldo1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/FornecedorViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/FornecedorViewModel.cs new file mode 100644 index 0000000..6d1dc77 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/FornecedorViewModel.cs @@ -0,0 +1,780 @@ +using Assinador.Infrastructure.Helpers; +using ClosedXML.Excel; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class FornecedorViewModel : BaseFinanceiroViewModel + { + private readonly FornecedorServico _servico; + + private List _planos; + + private ObservableCollection _planosFiltrados; + + private List _contas; + + private ObservableCollection _contasFiltradas; + + private List _centros; + + private ObservableCollection _centrosFiltrados; + + private ObservableCollection _fornecedorFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private Gestor.Model.Domain.Financeiro.Fornecedor _selectedFornecedor; + + private string _anotacoes; + + private long _ultimoId; + + public Gestor.Model.Domain.Financeiro.Fornecedor CancelProduto; + + public string Anotacoes + { + get + { + return this._anotacoes; + } + set + { + this._anotacoes = value; + base.OnPropertyChanged("Anotacoes"); + } + } + + public List Centros + { + get + { + return this._centros; + } + set + { + this._centros = value; + base.OnPropertyChanged("Centros"); + } + } + + public ObservableCollection CentrosFiltrados + { + get + { + return this._centrosFiltrados; + } + set + { + this._centrosFiltrados = value; + base.OnPropertyChanged("CentrosFiltrados"); + } + } + + public List Contas + { + get + { + return this._contas; + } + set + { + this._contas = value; + base.OnPropertyChanged("Contas"); + } + } + + public ObservableCollection ContasFiltradas + { + get + { + return this._contasFiltradas; + } + set + { + this._contasFiltradas = value; + base.OnPropertyChanged("ContasFiltradas"); + } + } + + public List Fornecedor + { + get; + set; + } + + public ObservableCollection FornecedorFiltrados + { + get + { + return this._fornecedorFiltrados; + } + set + { + this._fornecedorFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("FornecedorFiltrados"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public List Planos + { + get + { + return this._planos; + } + set + { + this._planos = value; + base.OnPropertyChanged("Planos"); + } + } + + public ObservableCollection PlanosFiltrados + { + get + { + return this._planosFiltrados; + } + set + { + this._planosFiltrados = value; + base.OnPropertyChanged("PlanosFiltrados"); + } + } + + public Gestor.Model.Domain.Financeiro.Fornecedor SelectedFornecedor + { + get + { + return this._selectedFornecedor; + } + set + { + long? nullable; + this._selectedFornecedor = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + this.Anotacoes = string.Empty; + this._ultimoId = (value == null || value.get_Id() <= (long)0 ? this._ultimoId : value.get_Id()); + base.OnPropertyChanged("SelectedFornecedor"); + } + } + + public FornecedorViewModel() + { + this._servico = new FornecedorServico(); + base.EnableMenu = true; + this.BuscaIncial(); + } + + private async void BuscaIncial() + { + base.Loading(true); + await base.PermissaoTela(24); + this.Planos = await (new PlanoServico()).BuscarPlanos(); + FornecedorViewModel observableCollection = this; + List planos = this.Planos; + IEnumerable ativo = + from x in planos + where x.get_Ativo() + select x; + observableCollection.PlanosFiltrados = new ObservableCollection( + from x in ativo + orderby x.get_Descricao() + select x); + this.Contas = await (new BancosContasServico()).BuscarBancos(); + FornecedorViewModel fornecedorViewModel = this; + List contas = this.Contas; + IEnumerable bancosContas = + from x in contas + where x.get_Ativo() + select x; + fornecedorViewModel.ContasFiltradas = new ObservableCollection( + from x in bancosContas + orderby x.get_Descricao() + select x); + this.Centros = await (new CentroServico()).BuscarCentros(); + FornecedorViewModel observableCollection1 = this; + List centros = this.Centros; + IEnumerable ativo1 = + from x in centros + where x.get_Ativo() + select x; + observableCollection1.CentrosFiltrados = new ObservableCollection( + from x in ativo1 + orderby x.get_Descricao() + select x); + await this.SelecionaFornecedor(); + this.SelectedFornecedor = this.FornecedorFiltrados.FirstOrDefault(); + base.Loading(false); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + base.Alterar(false); + if (this.SelectedFornecedor.get_Id() > (long)0) + { + await this.SelecionaFornecedor(); + } + this.SelectedFornecedor = this.FornecedorFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Fornecedor x) => x.get_Id() == this._ultimoId); + base.Loading(false); + } + + public void Copiar(Cliente cliente) + { + TipoTelefone? nullable; + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + TipoTelefone? tipo; + string str7; + string str8; + TipoTelefone? tipo1; + string str9; + string str10; + string str11; + if (this.SelectedFornecedor == null) + { + this.Incluir(); + } + this.SelectedFornecedor.set_Nome(cliente.get_Nome()); + this.SelectedFornecedor.set_Documento(cliente.get_Documento()); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str = null; + } + else + { + ClienteEndereco clienteEndereco = cliente.get_Enderecos().First(); + if (clienteEndereco != null) + { + string cep = clienteEndereco.get_Cep(); + if (cep != null) + { + str = cep.Trim(); + } + else + { + str = null; + } + } + else + { + str = null; + } + } + selectedFornecedor.set_Cep(str); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str1 = null; + } + else + { + ClienteEndereco clienteEndereco1 = cliente.get_Enderecos().First(); + if (clienteEndereco1 != null) + { + string endereco = clienteEndereco1.get_Endereco(); + if (endereco != null) + { + str1 = endereco.Trim(); + } + else + { + str1 = null; + } + } + else + { + str1 = null; + } + } + fornecedor.set_Endereco(str1); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor1 = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str2 = null; + } + else + { + ClienteEndereco clienteEndereco2 = cliente.get_Enderecos().First(); + if (clienteEndereco2 != null) + { + string numero = clienteEndereco2.get_Numero(); + if (numero != null) + { + str2 = numero.Trim(); + } + else + { + str2 = null; + } + } + else + { + str2 = null; + } + } + selectedFornecedor1.set_Numero(str2); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor1 = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str3 = null; + } + else + { + ClienteEndereco clienteEndereco3 = cliente.get_Enderecos().First(); + if (clienteEndereco3 != null) + { + string complemento = clienteEndereco3.get_Complemento(); + if (complemento != null) + { + str3 = complemento.Trim(); + } + else + { + str3 = null; + } + } + else + { + str3 = null; + } + } + fornecedor1.set_Complemento(str3); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor2 = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str4 = null; + } + else + { + ClienteEndereco clienteEndereco4 = cliente.get_Enderecos().First(); + if (clienteEndereco4 != null) + { + string bairro = clienteEndereco4.get_Bairro(); + if (bairro != null) + { + str4 = bairro.Trim(); + } + else + { + str4 = null; + } + } + else + { + str4 = null; + } + } + selectedFornecedor2.set_Bairro(str4); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor2 = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str5 = null; + } + else + { + ClienteEndereco clienteEndereco5 = cliente.get_Enderecos().First(); + if (clienteEndereco5 != null) + { + string cidade = clienteEndereco5.get_Cidade(); + if (cidade != null) + { + str5 = cidade.Trim(); + } + else + { + str5 = null; + } + } + else + { + str5 = null; + } + } + fornecedor2.set_Cidade(str5); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor3 = this.SelectedFornecedor; + if (cliente.get_Enderecos() == null || !cliente.get_Enderecos().Any()) + { + str6 = null; + } + else + { + ClienteEndereco clienteEndereco6 = cliente.get_Enderecos().First(); + if (clienteEndereco6 != null) + { + string estado = clienteEndereco6.get_Estado(); + if (estado != null) + { + str6 = estado.Trim(); + } + else + { + str6 = null; + } + } + else + { + str6 = null; + } + } + selectedFornecedor3.set_Estado(str6); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor3 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || !cliente.get_Telefones().Any()) + { + nullable = null; + tipo = nullable; + } + else + { + tipo = cliente.get_Telefones().First().get_Tipo(); + } + fornecedor3.set_TipoTelefone1(tipo); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor4 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || !cliente.get_Telefones().Any()) + { + str7 = null; + } + else + { + string prefixo = cliente.get_Telefones().First().get_Prefixo(); + if (prefixo != null) + { + str7 = prefixo.Trim(); + } + else + { + str7 = null; + } + } + selectedFornecedor4.set_Prefixo1(str7); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor4 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || !cliente.get_Telefones().Any()) + { + str8 = null; + } + else + { + string numero1 = cliente.get_Telefones().First().get_Numero(); + if (numero1 != null) + { + str8 = numero1.Trim(); + } + else + { + str8 = null; + } + } + fornecedor4.set_Telefone1(str8); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor5 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || !cliente.get_Telefones().Any() || cliente.get_Telefones().Count <= 2) + { + nullable = null; + tipo1 = nullable; + } + else + { + tipo1 = cliente.get_Telefones()[1].get_Tipo(); + } + selectedFornecedor5.set_TipoTelefone2(tipo1); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor5 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || cliente.get_Telefones().Count <= 2) + { + str9 = null; + } + else + { + string prefixo1 = cliente.get_Telefones()[1].get_Prefixo(); + if (prefixo1 != null) + { + str9 = prefixo1.Trim(); + } + else + { + str9 = null; + } + } + fornecedor5.set_Prefixo2(str9); + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor6 = this.SelectedFornecedor; + if (cliente.get_Telefones() == null || cliente.get_Telefones().Count <= 2) + { + str10 = null; + } + else + { + string numero2 = cliente.get_Telefones()[1].get_Numero(); + if (numero2 != null) + { + str10 = numero2.Trim(); + } + else + { + str10 = null; + } + } + selectedFornecedor6.set_Telefone2(str10); + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor6 = this.SelectedFornecedor; + if (cliente.get_Emails() == null || !cliente.get_Emails().Any() || cliente.get_Emails().Count <= 0) + { + str11 = null; + } + else + { + string email = cliente.get_Emails().First().get_Email(); + if (email != null) + { + str11 = email.Trim(); + } + else + { + str11 = null; + } + } + fornecedor6.set_Email(str11); + base.OnPropertyChanged("SelectedFornecedor"); + } + + public async Task Delete() + { + if (this.SelectedFornecedor != null && this.SelectedFornecedor.get_Id() != 0) + { + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR O FORNECEDOR ", this.SelectedFornecedor.get_Nome(), "?"), "SIM", "NÃO", false)) + { + base.Loading(true); + if (await (new FinanceiroServico()).TemLancamentosPorFornecedor(this.SelectedFornecedor.get_Id())) + { + await base.ShowMessage("IMPOSSÍVEL REAIZAR A EXCLUSÃO POIS EXISTEM LANCAMENTOS PARA ESSE FORNECEDOR. PROCESSO INTERROMPIDO", "OK", "", false); + base.Loading(false); + } + else if (await this._servico.Delete(this.SelectedFornecedor)) + { + await this.SelecionaFornecedor(); + this.SelectedFornecedor = this.FornecedorFiltrados.FirstOrDefault(); + base.ToggleSnackBar("FORNECEDOR EXCLUÍDO COM SUCESSO", true); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + } + } + + public async void Excel() + { + XLWorkbook xLWorkbook = new XLWorkbook(); + string str = "RELAÓRIO DE FORNECEDOR"; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, this.FornecedorFiltrados.ToList(), null); + string tempPath = ""; + string str1 = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str1 = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + str = null; + return; + } + } + string[] strArrays = new string[] { tempPath, str, " ", null, null }; + DateTime date = Functions.GetNetworkTime().Date; + strArrays[3] = date.ToShortDateString().Replace("/", ""); + strArrays[4] = ".xlsx"; + str1 = string.Concat(strArrays); + } + xLWorkbook.SaveAs(str1); + Process.Start(str1); + str = null; + } + + internal async Task> Filtrar(string value) + { + List fornecedors = await Task.Run>(() => this.FiltrarFornecedor(value)); + return fornecedors; + } + + public List FiltrarFornecedor(string filter) + { + this.FornecedorFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Fornecedor) : new ObservableCollection(this.Fornecedor.Where((Gestor.Model.Domain.Financeiro.Fornecedor x) => { + if (Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(filter)) || x.get_Documento() != null && Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Documento().Trim()).Contains(filter) || x.get_Telefone1() != null && Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Telefone1().Trim()).Contains(filter) || x.get_Telefone2() != null && Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Telefone2().Trim()).Contains(filter)) + { + return true; + } + if (x.get_Email() == null) + { + return false; + } + return Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Email().Trim()).Contains(filter); + }).OrderByDescending((Gestor.Model.Domain.Financeiro.Fornecedor x) => x.get_Nome()))); + if (this.FornecedorFiltrados.Count == 1) + { + this.SelectedFornecedor = this.FornecedorFiltrados.First(); + } + return this.FornecedorFiltrados.ToList(); + } + + public async void Imprimir() + { + await base.ImprimirFornecedor(this.FornecedorFiltrados.ToList()); + } + + public void Incluir() + { + long id; + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor = this.SelectedFornecedor; + if (selectedFornecedor != null) + { + id = selectedFornecedor.get_Id(); + } + else + { + id = (long)0; + } + this._ultimoId = id; + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor = new Gestor.Model.Domain.Financeiro.Fornecedor(); + fornecedor.set_IdEmpresa((long)1); + fornecedor.set_Ativo(true); + this.SelectedFornecedor = fornecedor; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedFornecedor.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + if (!this.SelectedFornecedor.get_TipoPagamento().HasValue) + { + this.SelectedFornecedor.set_TipoPagamento(new TipoPagamento?(12)); + } + if (!string.IsNullOrWhiteSpace(this.Anotacoes)) + { + Gestor.Model.Domain.Financeiro.Fornecedor selectedFornecedor = this.SelectedFornecedor; + object[] nome = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), Funcoes.GetNetworkTime(), Environment.NewLine, this.Anotacoes, Environment.NewLine, Environment.NewLine, this.SelectedFornecedor.get_Observacao() }; + selectedFornecedor.set_Observacao(string.Format("{0}, ID: {1}, {2:g}{3}{4}{5}{6}{7}", nome)); + } + Gestor.Model.Domain.Financeiro.Fornecedor fornecedor = await this._servico.Save(this.SelectedFornecedor); + if (this._servico.Sucesso) + { + await this.SelecionaFornecedor(); + this.SelectedFornecedor = this.FornecedorFiltrados.First((Gestor.Model.Domain.Financeiro.Fornecedor x) => x.get_Id() == fornecedor.get_Id()); + base.ToggleSnackBar("FORNECEDOR SALVO COM SUCESSO", true); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private async Task SelecionaFornecedor() + { + this.Fornecedor = await this._servico.BuscarFornecedores(); + FornecedorViewModel observableCollection = this; + List fornecedor = this.Fornecedor; + observableCollection.FornecedorFiltrados = new ObservableCollection( + from x in fornecedor + orderby x.get_Nome() + select x); + } + + public async Task>> Validate() + { + List> keyValuePairs = Gestor.Model.Helper.ValidationHelper.AddValue(); + if (!string.IsNullOrWhiteSpace(this.SelectedFornecedor.get_Documento())) + { + List list = await this._servico.BuscarFornecedores(); + list = list.Where((Gestor.Model.Domain.Financeiro.Fornecedor x) => { + if (x.get_Id() == this.SelectedFornecedor.get_Id()) + { + return false; + } + return Gestor.Model.Helper.ValidationHelper.DocumentoFornecedor(x.get_Documento()) == Gestor.Model.Helper.ValidationHelper.DocumentoFornecedor(this.SelectedFornecedor.get_Documento()); + }).ToList(); + if (list.Count > 0) + { + List> keyValuePairs1 = keyValuePairs; + List fornecedors = list; + Gestor.Model.Helper.ValidationHelper.AddValue(keyValuePairs1, "DOCUMENTO", string.Concat("DOCUMENTO JÁ CADASTRADO PARA OUTROS FORNECEDORES ", string.Join(" | ", + from x in fornecedors + select x.get_Nome())), true); + } + } + List> keyValuePairs2 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/InfoExtratoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/InfoExtratoViewModel.cs new file mode 100644 index 0000000..d1a0c38 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/InfoExtratoViewModel.cs @@ -0,0 +1,81 @@ +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class InfoExtratoViewModel : BaseFinanceiroViewModel + { + private readonly BancosContasServico _saldoServico; + + private Saldo _selectedSaldo; + + public bool _telaBancos + { + get; + set; + } + + public Saldo SelectedSaldo + { + get + { + return this._selectedSaldo; + } + set + { + if (value != null && !this._telaBancos) + { + value.set_DataFinal(null); + value.set_ValorFinal(null); + } + this._selectedSaldo = value; + base.OnPropertyChanged("SelectedSaldo"); + this.SelectedSaldo.Initialize(); + } + } + + public InfoExtratoViewModel(bool telaBancos) + { + this._telaBancos = telaBancos; + this._saldoServico = new BancosContasServico(); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedSaldo.Validate(); + if (keyValuePairs1.Count <= 0) + { + if (!this._telaBancos) + { + this.SelectedSaldo.set_DataFinal(null); + this.SelectedSaldo.set_ValorFinal(null); + } + this.SelectedSaldo = await this._saldoServico.Save(this.SelectedSaldo); + if (this._saldoServico.Sucesso) + { + base.Alterar(false); + base.ToggleSnackBar("SALDO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/MenuFinanceiroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/MenuFinanceiroViewModel.cs new file mode 100644 index 0000000..9c1bdee --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/MenuFinanceiroViewModel.cs @@ -0,0 +1,30 @@ +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Financeiro; +using System; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class MenuFinanceiroViewModel : BaseViewModel + { + private object _content; + + public Gestor.Application.Views.Financeiro.FinanceiroView FinanceiroView; + + public object Content + { + get + { + return this._content; + } + set + { + this._content = value; + base.OnPropertyChanged("Content"); + } + } + + public MenuFinanceiroViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanoViewModel.cs new file mode 100644 index 0000000..e62f957 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanoViewModel.cs @@ -0,0 +1,147 @@ +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class PlanoViewModel : BaseFinanceiroViewModel + { + private readonly PlanoServico _planoServico; + + private Plano _selectedPlano; + + public Plano Cancel; + + public Plano SelectedPlano + { + get + { + return this._selectedPlano; + } + set + { + long? nullable; + this._selectedPlano = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedPlano"); + } + } + + public PlanoViewModel(Plano plano) + { + this._planoServico = new PlanoServico(); + this.Seleciona(plano); + } + + public void Cancelar() + { + base.Loading(true); + if (this.SelectedPlano.get_Id() != 0) + { + base.Alterar(false); + base.Loading(false); + return; + } + this.SelectedPlano = new Plano(); + base.Alterar(false); + base.Loading(false); + } + + public void Incluir() + { + Plano plano = new Plano(); + plano.set_Ativo(true); + this.SelectedPlano = plano; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedPlano.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + this.SelectedPlano = await this._planoServico.Save(this.SelectedPlano); + if (this._planoServico.Sucesso) + { + base.Alterar(false); + base.ToggleSnackBar("PLANO SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private async void Seleciona(Plano plano) + { + base.Loading(true); + await base.PermissaoTela(27); + if (plano != null) + { + this.SelectedPlano = plano; + } + else + { + Plano plano1 = new Plano(); + plano1.set_Descricao(""); + plano1.set_Ativo(true); + this.SelectedPlano = plano1; + } + base.Loading(false); + } + + public async Task>> Validate() + { + List> keyValuePairs = new List>(); + bool flag = true; + List planos = await (new BaseServico()).BuscarPlanoAsync(); + if (planos.Count > 0) + { + planos.ForEach((Plano x) => { + if (x.get_Id() == this.SelectedPlano.get_Id()) + { + return; + } + if (x.get_Descricao() == this.SelectedPlano.get_Descricao()) + { + flag = false; + } + }); + } + if (!flag) + { + keyValuePairs.Add(new KeyValuePair("Descricao", "UM PLANO COM ESSE NOME JÁ EXISTE.")); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanosViewModel.cs new file mode 100644 index 0000000..e2251f3 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/PlanosViewModel.cs @@ -0,0 +1,330 @@ +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class PlanosViewModel : BaseFinanceiroViewModel + { + private readonly PlanosServico _planosServico; + + private ObservableCollection _plano = new ObservableCollection(); + + private ObservableCollection _planosFiltrados = new ObservableCollection(); + + private bool _isExpanded; + + private Gestor.Model.Domain.Financeiro.Planos _selectedPlanos; + + private Gestor.Model.Domain.Financeiro.Plano _selectedPlano; + + private bool _ativo; + + private long _ultimoId; + + public bool Ativo + { + get + { + return this._ativo; + } + set + { + this._ativo = value; + base.OnPropertyChanged("Ativo"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public ObservableCollection Plano + { + get + { + return this._plano; + } + set + { + this._plano = value; + base.OnPropertyChanged("Plano"); + } + } + + public List Planos + { + get; + set; + } + + public ObservableCollection PlanosFiltrados + { + get + { + return this._planosFiltrados; + } + set + { + this._planosFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("PlanosFiltrados"); + } + } + + public Gestor.Model.Domain.Financeiro.Plano SelectedPlano + { + get + { + return this._selectedPlano; + } + set + { + this._selectedPlano = value; + base.OnPropertyChanged("SelectedPlano"); + } + } + + public Gestor.Model.Domain.Financeiro.Planos SelectedPlanos + { + get + { + return this._selectedPlanos; + } + set + { + bool plano; + Gestor.Model.Domain.Financeiro.Plano plano1; + bool id; + long? nullable; + this._selectedPlanos = value; + Gestor.Model.Domain.Financeiro.Planos plano2 = value; + if (plano2 != null) + { + plano = plano2.get_Plano(); + } + else + { + plano = false; + } + if (plano) + { + plano1 = this.Plano.FirstOrDefault((Gestor.Model.Domain.Financeiro.Plano x) => x.get_Id() == value.get_Plano().get_Id()); + } + else + { + plano1 = null; + } + this.SelectedPlano = plano1; + Gestor.Model.Domain.Financeiro.Planos plano3 = value; + if (plano3 != null) + { + id = plano3.get_Id() > (long)0; + } + else + { + id = false; + } + if (id) + { + this._ultimoId = value.get_Id(); + } + Gestor.Model.Domain.Financeiro.Planos plano4 = value; + if (plano4 != null) + { + nullable = new long?(plano4.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedPlanos"); + } + } + + public PlanosViewModel() + { + this._planosServico = new PlanosServico(); + base.EnableMenu = true; + this.Seleciona(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + base.Alterar(false); + if (this.SelectedPlanos.get_Id() > (long)0) + { + await this.SelecionaPlanos(); + } + await this.SelecionaPlanos(this.PlanosFiltrados.FirstOrDefault((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == this._ultimoId)); + base.Loading(false); + } + + public async Task> Filtrar(string value) + { + ObservableCollection observableCollection = await Task.Run>(() => this.FiltrarPlanos(value)); + return observableCollection; + } + + public ObservableCollection FiltrarPlanos(string filter) + { + this.PlanosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Planos) : new ObservableCollection( + from x in this.Planos + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby this.Ativo descending, x.get_Descricao() + select x)); + return this.PlanosFiltrados; + } + + public void Incluir() + { + Gestor.Model.Domain.Financeiro.Planos plano = new Gestor.Model.Domain.Financeiro.Planos(); + plano.set_Plano(this.SelectedPlano); + this.SelectedPlanos = plano; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + this.SelectedPlanos.set_Plano(this.SelectedPlano); + List> keyValuePairs1 = this.SelectedPlanos.Validate(); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + this.SelectedPlanos.set_Plano(this.SelectedPlano); + this.SelectedPlanos = await this._planosServico.Save(this.SelectedPlanos); + if (this._planosServico.Sucesso) + { + await this.SelecionaPlanos(); + await this.SelecionaPlanos(this.PlanosFiltrados.First((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == this.SelectedPlanos.get_Id())); + base.Alterar(false); + base.ToggleSnackBar("SUBNÍVEL SALVO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private async void Seleciona() + { + base.Loading(true); + await base.PermissaoTela(28); + await this.SelecionaPlanos(); + await this.SelecionaPlanos(this.PlanosFiltrados.FirstOrDefault()); + base.Loading(false); + } + + private async Task SelecionaPlanos() + { + List planos = await (new BaseServico()).BuscarPlanosAsync(); + PlanosViewModel list = this; + List planos1 = planos; + IOrderedEnumerable ativo = + from x in planos1 + orderby x.get_Ativo() descending + select x; + IOrderedEnumerable planos2 = ativo.ThenBy((Gestor.Model.Domain.Financeiro.Planos x) => { + Gestor.Model.Domain.Financeiro.Plano plano = x.get_Plano(); + if (plano != null) + { + return plano.get_Descricao(); + } + return null; + }); + list.Planos = planos2.ThenBy((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Descricao()).ToList(); + this.PlanosFiltrados = new ObservableCollection(this.Planos); + } + + public async Task SelecionaPlanos(Gestor.Model.Domain.Financeiro.Planos planos) + { + if (planos != null) + { + base.Loading(true); + ObservableCollection observableCollection = await this._planosServico.BuscarPlanos(); + DomainBase.Copy(this.PlanosFiltrados.First((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == planos.get_Id()), observableCollection.First((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == planos.get_Id())); + if (this.Plano == null) + { + List planos1 = await (new BaseServico()).BuscarPlanoAsync(); + PlanosViewModel planosViewModel = this; + List planos2 = planos1; + IOrderedEnumerable ativo = + from x in planos2 + orderby x.get_Ativo() descending + select x; + planosViewModel.Plano = new ObservableCollection(ativo.ThenBy((Gestor.Model.Domain.Financeiro.Plano x) => x.get_Descricao()).ToList()); + } + this.SelectedPlanos = this.PlanosFiltrados.First((Gestor.Model.Domain.Financeiro.Planos x) => x.get_Id() == planos.get_Id()); + base.Loading(false); + } + else + { + base.Alterar(false); + base.EnableMenu = false; + base.EnableAlterar = false; + } + } + + public async Task>> Validate() + { + List> keyValuePairs = new List>(); + bool flag = true; + List planos = await (new BaseServico()).BuscarPlanosAsync(); + if (planos != null) + { + planos.ForEach((Gestor.Model.Domain.Financeiro.Planos x) => { + if (x.get_Id() == this.SelectedPlanos.get_Id()) + { + return; + } + if (x.get_Descricao() == this.SelectedPlanos.get_Descricao()) + { + flag = false; + } + }); + } + else + { + } + if (!flag) + { + keyValuePairs.Add(new KeyValuePair("Descricao", "UM SUBNÍVEL COM ESSE NOME JÁ EXISTE.")); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/Relatorios/FechamentoFinanceiroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/Relatorios/FechamentoFinanceiroViewModel.cs new file mode 100644 index 0000000..084c527 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/Relatorios/FechamentoFinanceiroViewModel.cs @@ -0,0 +1,2746 @@ +using ClosedXML.Excel; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Financeiro.Relatorios; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows.Forms; + +namespace Gestor.Application.ViewModels.Financeiro.Relatorios +{ + public class FechamentoFinanceiroViewModel : BaseViewModel + { + private readonly FinanceiroServico _servico; + + private bool _isExpanded; + + private bool _analitico; + + private List _plano; + + private List _planos; + + private List _centro; + + private List _conta; + + private DateTime? _inicio; + + private DateTime? _fim; + + private List _fechamento; + + private List _fechamentoAnalitico; + + private string _htmlContent; + + private bool _print; + + public bool Analitico + { + get + { + return this._analitico; + } + set + { + this._analitico = value; + base.OnPropertyChanged("Analitico"); + } + } + + public List Centro + { + get + { + return this._centro; + } + set + { + this._centro = value; + base.OnPropertyChanged("Centro"); + } + } + + public List Conta + { + get + { + return this._conta; + } + set + { + this._conta = value; + base.OnPropertyChanged("Conta"); + } + } + + public List Fechamento + { + get + { + return this._fechamento; + } + set + { + this._fechamento = value; + base.OnPropertyChanged("Fechamento"); + } + } + + public List FechamentoAnalitico + { + get + { + return this._fechamentoAnalitico; + } + set + { + this._fechamentoAnalitico = value; + base.OnPropertyChanged("FechamentoAnalitico"); + } + } + + public DateTime? Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public string HtmlContent + { + get + { + return this._htmlContent; + } + set + { + this._htmlContent = value; + this.IsPrintable = !string.IsNullOrWhiteSpace(this._htmlContent); + base.OnPropertyChanged("HtmlContent"); + } + } + + public DateTime? Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public bool IsPrintable + { + get + { + return this._print; + } + set + { + this._print = value; + base.OnPropertyChanged("IsPrintable"); + } + } + + public List Plano + { + get + { + return this._plano; + } + set + { + this._plano = value; + base.OnPropertyChanged("Plano"); + } + } + + public List Planos + { + get + { + return this._planos; + } + set + { + this._planos = value; + base.OnPropertyChanged("Planos"); + } + } + + public FechamentoFinanceiroViewModel() + { + DateTime date = Funcoes.GetNetworkTime().Date; + int year = date.Year; + date = Funcoes.GetNetworkTime().Date; + this._inicio = new DateTime?(new DateTime(year, date.Month, 1)); + this._fim = new DateTime?(Funcoes.GetNetworkTime()); + base(); + this._servico = new FinanceiroServico(); + this.LoadInicial(); + } + + public async Task GerarExcel() + { + string tempPath = ""; + string str = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + str = null; + return; + } + } + DateTime date = Functions.GetNetworkTime().Date; + str = string.Concat(tempPath, "FECHAMENTO ", date.ToShortDateString().Replace("/", ""), ".xlsx"); + } + XLWorkbook xLWorkbook = new XLWorkbook(); + int num = 1; + if (this.Analitico) + { + if (this.FechamentoAnalitico == null || this.FechamentoAnalitico.Count == 0) + { + str = null; + return; + } + else + { + foreach (FechamentoFinanceiroAnalitico fechamentoAnalitico in this.FechamentoAnalitico) + { + string str1 = string.Format("{0}_{1}", num, fechamentoAnalitico.get_NomeConta()); + while (str1.Replace("/", "_").Trim().Length > 30) + { + str1 = Regex.Replace(str1.Trim(), "[^\\s]*$", ""); + } + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str1.Replace("/", "_"), fechamentoAnalitico.get_Dados().ToList(), null); + } + } + } + else if (this.Fechamento == null || this.Fechamento.Count == 0) + { + str = null; + return; + } + else + { + List fechamentoFinanceiros = new List(); + fechamentoFinanceiros.AddRange(this.Fechamento); + List fechamentoFinanceiros1 = fechamentoFinanceiros; + FechamentoFinanceiro fechamentoFinanceiro = new FechamentoFinanceiro(); + fechamentoFinanceiro.set_Plano("TOTAL NO PERÍODO"); + List dadosFechamentos = new List(); + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos("TOTAL"); + List fechamento = this.Fechamento; + IEnumerable plano = + from x in fechamento + where x.get_Plano() == "TIPO PAGAMENTO" + select x; + dadosFechamento.set_Soma(plano.Sum((FechamentoFinanceiro x) => x.get_Dados().Sum((DadosFechamento y) => y.get_Soma()))); + dadosFechamentos.Add(dadosFechamento); + fechamentoFinanceiro.set_Dados(dadosFechamentos); + fechamentoFinanceiros1.Add(fechamentoFinanceiro); + num = 1; + foreach (FechamentoFinanceiro fechamentoFinanceiro1 in fechamentoFinanceiros) + { + string str2 = string.Format("{0}_{1}", num, fechamentoFinanceiro1.get_Plano()); + num++; + while (str2.Replace("/", "_").Trim().Length > 30) + { + str2 = Regex.Replace(str2.Trim(), "[^\\s]*$", ""); + } + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str2.Replace("/", "_"), fechamentoFinanceiro1.get_Dados().ToList(), null); + } + } + base.RegistrarAcao(string.Format("EMITIU EXCEL DO RELATÓRIO PERÍODO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim), new Relatorio?(11), null); + xLWorkbook.SaveAs(str); + Process.Start(str); + str = null; + } + + private async Task GerarHtml(bool screen) + { + string str; + string str1 = ""; + if (!this.Analitico) + { + foreach (FechamentoFinanceiro fechamento in this.Fechamento) + { + List dados = fechamento.get_Dados(); + List strs = new List() + { + "TOTAL CRÉDITO - TOTAL DÉBITO", + "% TOTAL DE CRÉDITO - % TOTAL DE DÉBITO" + }; + string str2 = await Funcoes.GenerateTable(dados, strs, false, screen, "", null); + str1 = string.Concat(str1, Funcoes.CreateCard(fechamento.get_Plano(), str2, false)); + } + FechamentoFinanceiro fechamentoFinanceiro = new FechamentoFinanceiro(); + fechamentoFinanceiro.set_Plano("TOTAL NO PERÍODO"); + List dadosFechamentos = new List(); + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos("TOTAL"); + List fechamentoFinanceiros = this.Fechamento; + IEnumerable plano = + from x in fechamentoFinanceiros + where x.get_Plano() == "TIPO PAGAMENTO" + select x; + dadosFechamento.set_Soma(plano.Sum((FechamentoFinanceiro x) => x.get_Dados().Sum((DadosFechamento y) => y.get_Soma()))); + List fechamento1 = this.Fechamento; + IEnumerable plano1 = + from x in fechamento1 + where x.get_Plano() == "TIPO PAGAMENTO" + select x; + dadosFechamento.set_SomaPercentual(plano1.Sum((FechamentoFinanceiro x) => x.get_Dados().Sum((DadosFechamento y) => y.get_SomaPercentual()))); + dadosFechamentos.Add(dadosFechamento); + fechamentoFinanceiro.set_Dados(dadosFechamentos); + FechamentoFinanceiro fechamentoFinanceiro1 = fechamentoFinanceiro; + List dados1 = fechamentoFinanceiro1.get_Dados(); + List strs1 = new List() + { + "TOTAL CRÉDITO", + "TOTAL DÉBITO", + "% CRÉDITO", + "% DÉBITO" + }; + string str3 = await Funcoes.GenerateTable(dados1, strs1, false, screen, "", null); + str1 = string.Concat(str1, Funcoes.CreateCard(fechamentoFinanceiro1.get_Plano(), str3, false)); + fechamentoFinanceiro1 = null; + } + else + { + foreach (FechamentoFinanceiroAnalitico fechamentoAnalitico in this.FechamentoAnalitico) + { + string str4 = await Funcoes.GenerateTable(fechamentoAnalitico.get_Dados(), new List(), false, screen, "", null); + str1 = string.Concat(str1, Funcoes.CreateCard(fechamentoAnalitico.get_NomeConta(), str4, false)); + } + } + if (!this.Inicio.HasValue || !this.Fim.HasValue) + { + str = null; + } + else + { + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome((this.Analitico ? "RELATÓRIO FECHAMENTO FINANCEIRO ANALÍTICO" : "RELATÓRIO FECHAMENTO FINANCEIRO")); + tipoRelatorio.set_Inicio(this.Inicio.Value); + tipoRelatorio.set_Fim(this.Fim.Value); + str = Funcoes.ExportarHtml(tipoRelatorio, str1, "50", "portrait", false, ""); + } + str1 = null; + return str; + } + + public async Task GerarRelatorio() + { + decimal num7; + decimal num8; + decimal num9; + decimal num10; + decimal num11; + decimal num12; + decimal num13; + decimal num14; + decimal num15; + decimal num16; + decimal num17; + Func func8 = null; + Func func9 = null; + Func func10 = null; + Func func11 = null; + Func func12 = null; + Func func13 = null; + Func func14 = null; + Func func15 = null; + Func func16 = null; + Func func17 = null; + Func func18 = null; + Func func19 = null; + if (this.Inicio.HasValue && this.Fim.HasValue) + { + List planos = this.Plano; + IEnumerable selecionado = + from x in planos + where x.get_Selecionado() + select x; + List nums20 = ( + from x in selecionado + select x.get_Id()).ToList(); + List planos1 = this.Planos; + IEnumerable selecionado1 = + from x in planos1 + where x.get_Selecionado() + select x; + List nums21 = ( + from x in selecionado1 + select x.get_Id()).ToList(); + List centro = this.Centro; + IEnumerable centros = + from x in centro + where x.get_Selecionado() + select x; + List nums22 = ( + from x in centros + select x.get_Id()).ToList(); + List conta = this.Conta; + IEnumerable bancosContas = + from x in conta + where x.get_Selecionado() + select x; + List nums23 = ( + from x in bancosContas + select x.get_Id()).ToList(); + FiltroFinanceiro filtroFinanceiro = new FiltroFinanceiro(); + filtroFinanceiro.set_Inicio(this.Inicio.Value); + filtroFinanceiro.set_Fim(this.Fim.Value); + filtroFinanceiro.set_Plano(nums20); + filtroFinanceiro.set_Planos(nums21); + filtroFinanceiro.set_Centro(nums22); + filtroFinanceiro.set_Conta(nums23); + filtroFinanceiro.set_Referencia("l.dtbaixa"); + FiltroFinanceiro filtroFinanceiro1 = filtroFinanceiro; + List lancamentos13 = await this._servico.BuscarFechamento(filtroFinanceiro1); + if (!this.Analitico) + { + this.Fechamento = new List(); + List lancamentos14 = lancamentos13; + IEnumerable lancamentos15 = lancamentos14.Where((Lancamento x) => { + object plano; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = null; + } + return plano != null; + }); + IOrderedEnumerable nome = + from x in lancamentos15 + orderby x.get_Controle().get_Plano().get_Nome() + select x; + ( + from x in nome + group x by x.get_Controle().get_Plano().get_Plano().get_Id()).ToList>().ForEach((IGrouping x) => { + decimal num3; + decimal num4; + FechamentoFinanceiro fechamentoFinanceiro = new FechamentoFinanceiro(); + fechamentoFinanceiro.set_Plano(x.First().get_Controle().get_Plano().get_Nome().ToUpper()); + IGrouping nums8 = x; + Func u003cu003e9_5197 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_97; + if (u003cu003e9_5197 == null) + { + u003cu003e9_5197 = (Lancamento f) => f.get_Controle().get_Plano().get_Nome(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_97 = u003cu003e9_5197; + } + IOrderedEnumerable lancamentos8 = nums8.OrderBy(u003cu003e9_5197); + Func u003cu003e9_5198 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_98; + if (u003cu003e9_5198 == null) + { + u003cu003e9_5198 = (Lancamento f) => f.get_Controle().get_Plano().get_Id(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_98 = u003cu003e9_5198; + } + fechamentoFinanceiro.set_Dados(lancamentos8.GroupBy(u003cu003e9_5198).Select, DadosFechamento>((IGrouping f) => { + decimal zero; + decimal num; + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(f.First().get_Controle().get_Plano().get_Descricao()); + IGrouping nums = f; + Func u003cu003e9_51100 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_100; + if (u003cu003e9_51100 == null) + { + u003cu003e9_51100 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_100 = u003cu003e9_51100; + } + IEnumerable lancamentos = nums.Where(u003cu003e9_51100); + Func u003cu003e9_51101 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_101; + if (u003cu003e9_51101 == null) + { + u003cu003e9_51101 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_101 = u003cu003e9_51101; + } + dadosFechamento.set_Credito(lancamentos.Sum(u003cu003e9_51101)); + IGrouping nums1 = f; + Func u003cu003e9_51102 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_102; + if (u003cu003e9_51102 == null) + { + u003cu003e9_51102 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_102 = u003cu003e9_51102; + } + IEnumerable lancamentos1 = nums1.Where(u003cu003e9_51102); + Func u003cu003e9_51103 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_103; + if (u003cu003e9_51103 == null) + { + u003cu003e9_51103 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_103 = u003cu003e9_51103; + } + if (lancamentos1.Sum(u003cu003e9_51103) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping nums2 = f; + Func u003cu003e9_51104 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_104; + if (u003cu003e9_51104 == null) + { + u003cu003e9_51104 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_104 = u003cu003e9_51104; + } + IEnumerable lancamentos2 = nums2.Where(u003cu003e9_51104); + Func u003cu003e9_51105 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_105; + if (u003cu003e9_51105 == null) + { + u003cu003e9_51105 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_105 = u003cu003e9_51105; + } + decimal num1 = lancamentos2.Sum(u003cu003e9_51105); + IGrouping nums3 = x; + Func u003cu003e9_51106 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_106; + if (u003cu003e9_51106 == null) + { + u003cu003e9_51106 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_106 = u003cu003e9_51106; + } + IEnumerable lancamentos3 = nums3.Where(u003cu003e9_51106); + Func u003cu003e9_51107 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_107; + if (u003cu003e9_51107 == null) + { + u003cu003e9_51107 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_107 = u003cu003e9_51107; + } + zero = (num1 / lancamentos3.Sum(u003cu003e9_51107)) * new decimal(100); + } + dadosFechamento.set_PercentualCredito(zero); + IGrouping nums4 = f; + Func u003cu003e9_51108 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_108; + if (u003cu003e9_51108 == null) + { + u003cu003e9_51108 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_108 = u003cu003e9_51108; + } + IEnumerable lancamentos4 = nums4.Where(u003cu003e9_51108); + Func u003cu003e9_51109 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_109; + if (u003cu003e9_51109 == null) + { + u003cu003e9_51109 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_109 = u003cu003e9_51109; + } + dadosFechamento.set_Debito(lancamentos4.Sum(u003cu003e9_51109)); + IGrouping nums5 = f; + Func u003cu003e9_51110 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_110; + if (u003cu003e9_51110 == null) + { + u003cu003e9_51110 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_110 = u003cu003e9_51110; + } + IEnumerable lancamentos5 = nums5.Where(u003cu003e9_51110); + Func u003cu003e9_51111 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_111; + if (u003cu003e9_51111 == null) + { + u003cu003e9_51111 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_111 = u003cu003e9_51111; + } + if (lancamentos5.Sum(u003cu003e9_51111) == decimal.Zero) + { + num = decimal.Zero; + } + else + { + IGrouping nums6 = f; + Func u003cu003e9_51112 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_112; + if (u003cu003e9_51112 == null) + { + u003cu003e9_51112 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_112 = u003cu003e9_51112; + } + IEnumerable lancamentos6 = nums6.Where(u003cu003e9_51112); + Func u003cu003e9_51113 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_113; + if (u003cu003e9_51113 == null) + { + u003cu003e9_51113 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_113 = u003cu003e9_51113; + } + decimal num2 = lancamentos6.Sum(u003cu003e9_51113); + IGrouping nums7 = x; + Func u003cu003e9_51114 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_114; + if (u003cu003e9_51114 == null) + { + u003cu003e9_51114 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_114 = u003cu003e9_51114; + } + IEnumerable lancamentos7 = nums7.Where(u003cu003e9_51114); + Func u003cu003e9_51115 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_115; + if (u003cu003e9_51115 == null) + { + u003cu003e9_51115 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_115 = u003cu003e9_51115; + } + num = (num2 / lancamentos7.Sum(u003cu003e9_51115)) * new decimal(100); + } + dadosFechamento.set_PercentualDebito(num); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro1 = fechamentoFinanceiro; + List dados = fechamentoFinanceiro1.get_Dados(); + DadosFechamento dadosFechamento1 = new DadosFechamento(); + dadosFechamento1.set_Planos("TOTAL"); + List dadosFechamentos = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51116 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_116; + if (u003cu003e9_51116 == null) + { + u003cu003e9_51116 = (DadosFechamento t) => t.get_Credito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_116 = u003cu003e9_51116; + } + dadosFechamento1.set_Credito(dadosFechamentos.Sum(u003cu003e9_51116)); + List dados1 = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51117 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_117; + if (u003cu003e9_51117 == null) + { + u003cu003e9_51117 = (DadosFechamento t) => t.get_Debito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_117 = u003cu003e9_51117; + } + dadosFechamento1.set_Debito(dados1.Sum(u003cu003e9_51117)); + List dadosFechamentos1 = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51118 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_118; + if (u003cu003e9_51118 == null) + { + u003cu003e9_51118 = (DadosFechamento t) => t.get_Credito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_118 = u003cu003e9_51118; + } + if (dadosFechamentos1.Sum(u003cu003e9_51118) == decimal.Zero) + { + num3 = decimal.Zero; + } + else + { + List dados2 = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51119 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_119; + if (u003cu003e9_51119 == null) + { + u003cu003e9_51119 = (DadosFechamento t) => t.get_Credito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_119 = u003cu003e9_51119; + } + decimal num5 = dados2.Sum(u003cu003e9_51119); + List lancamentos9 = lancamentos13; + Func u003cu003e9_51120 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_120; + if (u003cu003e9_51120 == null) + { + u003cu003e9_51120 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_120 = u003cu003e9_51120; + } + IEnumerable lancamentos10 = lancamentos9.Where(u003cu003e9_51120); + Func u003cu003e9_51121 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_121; + if (u003cu003e9_51121 == null) + { + u003cu003e9_51121 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_121 = u003cu003e9_51121; + } + num3 = (num5 / lancamentos10.Sum(u003cu003e9_51121)) * new decimal(100); + } + dadosFechamento1.set_PercentualCredito(num3); + List dadosFechamentos2 = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51122 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_122; + if (u003cu003e9_51122 == null) + { + u003cu003e9_51122 = (DadosFechamento t) => t.get_Debito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_122 = u003cu003e9_51122; + } + if (dadosFechamentos2.Sum(u003cu003e9_51122) == decimal.Zero) + { + num4 = decimal.Zero; + } + else + { + List dados3 = fechamentoFinanceiro1.get_Dados(); + Func u003cu003e9_51123 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_123; + if (u003cu003e9_51123 == null) + { + u003cu003e9_51123 = (DadosFechamento t) => t.get_Debito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_123 = u003cu003e9_51123; + } + decimal num6 = dados3.Sum(u003cu003e9_51123); + List lancamentos11 = lancamentos13; + Func u003cu003e9_51124 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_124; + if (u003cu003e9_51124 == null) + { + u003cu003e9_51124 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_124 = u003cu003e9_51124; + } + IEnumerable lancamentos12 = lancamentos11.Where(u003cu003e9_51124); + Func u003cu003e9_51125 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_125; + if (u003cu003e9_51125 == null) + { + u003cu003e9_51125 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_125 = u003cu003e9_51125; + } + num4 = (num6 / lancamentos12.Sum(u003cu003e9_51125)) * new decimal(100); + } + dadosFechamento1.set_PercentualDebito(num4); + dados.Add(dadosFechamento1); + this.Fechamento.Add(fechamentoFinanceiro1); + }); + FechamentoFinanceiro fechamentoFinanceiro2 = new FechamentoFinanceiro(); + fechamentoFinanceiro2.set_Plano("CONTA CORRENTE"); + List lancamentos16 = lancamentos13; + IEnumerable lancamentos17 = lancamentos16.Where((Lancamento x) => { + object plano; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = null; + } + return plano != null; + }); + IOrderedEnumerable descricao = + from x in lancamentos17 + orderby x.get_Conta().get_Descricao() + select x; + fechamentoFinanceiro2.set_Dados(( + from x in descricao + group x by x.get_Conta().get_Id()).Select, DadosFechamento>((IGrouping f) => { + decimal zero; + decimal num; + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(f.First().get_Conta().get_Descricao()); + IGrouping nums = f; + Func u003cu003e9_51130 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_130; + if (u003cu003e9_51130 == null) + { + u003cu003e9_51130 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_130 = u003cu003e9_51130; + } + IEnumerable lancamentos = nums.Where(u003cu003e9_51130); + Func u003cu003e9_51131 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_131; + if (u003cu003e9_51131 == null) + { + u003cu003e9_51131 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_131 = u003cu003e9_51131; + } + dadosFechamento.set_Credito(lancamentos.Sum(u003cu003e9_51131)); + IGrouping nums1 = f; + Func u003cu003e9_51132 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_132; + if (u003cu003e9_51132 == null) + { + u003cu003e9_51132 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_132 = u003cu003e9_51132; + } + IEnumerable lancamentos1 = nums1.Where(u003cu003e9_51132); + Func u003cu003e9_51133 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_133; + if (u003cu003e9_51133 == null) + { + u003cu003e9_51133 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_133 = u003cu003e9_51133; + } + if (lancamentos1.Sum(u003cu003e9_51133) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping nums2 = f; + Func u003cu003e9_51134 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_134; + if (u003cu003e9_51134 == null) + { + u003cu003e9_51134 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_134 = u003cu003e9_51134; + } + IEnumerable lancamentos2 = nums2.Where(u003cu003e9_51134); + Func u003cu003e9_51135 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_135; + if (u003cu003e9_51135 == null) + { + u003cu003e9_51135 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_135 = u003cu003e9_51135; + } + decimal num1 = lancamentos2.Sum(u003cu003e9_51135); + List lancamentos3 = lancamentos13; + Func u003cu003e9_51136 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_136; + if (u003cu003e9_51136 == null) + { + u003cu003e9_51136 = (Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 0; + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_136 = u003cu003e9_51136; + } + IEnumerable lancamentos4 = lancamentos3.Where(u003cu003e9_51136); + Func u003cu003e9_51137 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_137; + if (u003cu003e9_51137 == null) + { + u003cu003e9_51137 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_137 = u003cu003e9_51137; + } + zero = (num1 / lancamentos4.Sum(u003cu003e9_51137)) * new decimal(100); + } + dadosFechamento.set_PercentualCredito(zero); + IGrouping nums3 = f; + Func u003cu003e9_51138 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_138; + if (u003cu003e9_51138 == null) + { + u003cu003e9_51138 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_138 = u003cu003e9_51138; + } + IEnumerable lancamentos5 = nums3.Where(u003cu003e9_51138); + Func u003cu003e9_51139 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_139; + if (u003cu003e9_51139 == null) + { + u003cu003e9_51139 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_139 = u003cu003e9_51139; + } + dadosFechamento.set_Debito(lancamentos5.Sum(u003cu003e9_51139)); + IGrouping nums4 = f; + Func u003cu003e9_51140 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_140; + if (u003cu003e9_51140 == null) + { + u003cu003e9_51140 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_140 = u003cu003e9_51140; + } + IEnumerable lancamentos6 = nums4.Where(u003cu003e9_51140); + Func u003cu003e9_51141 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_141; + if (u003cu003e9_51141 == null) + { + u003cu003e9_51141 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_141 = u003cu003e9_51141; + } + if (lancamentos6.Sum(u003cu003e9_51141) == decimal.Zero) + { + num = decimal.Zero; + } + else + { + IGrouping nums5 = f; + Func u003cu003e9_51142 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_142; + if (u003cu003e9_51142 == null) + { + u003cu003e9_51142 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_142 = u003cu003e9_51142; + } + IEnumerable lancamentos7 = nums5.Where(u003cu003e9_51142); + Func u003cu003e9_51143 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_143; + if (u003cu003e9_51143 == null) + { + u003cu003e9_51143 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_143 = u003cu003e9_51143; + } + decimal num2 = lancamentos7.Sum(u003cu003e9_51143); + List lancamentos8 = lancamentos13; + Func u003cu003e9_51144 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_144; + if (u003cu003e9_51144 == null) + { + u003cu003e9_51144 = (Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 1; + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_144 = u003cu003e9_51144; + } + IEnumerable lancamentos9 = lancamentos8.Where(u003cu003e9_51144); + Func u003cu003e9_51145 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_145; + if (u003cu003e9_51145 == null) + { + u003cu003e9_51145 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_145 = u003cu003e9_51145; + } + num = (num2 / lancamentos9.Sum(u003cu003e9_51145)) * new decimal(100); + } + dadosFechamento.set_PercentualDebito(num); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro3 = fechamentoFinanceiro2; + List dadosFechamentos3 = fechamentoFinanceiro3.get_Dados(); + DadosFechamento dadosFechamento2 = new DadosFechamento(); + dadosFechamento2.set_Planos("TOTAL"); + List dadosFechamentos4 = fechamentoFinanceiro3.get_Dados(); + dadosFechamento2.set_Credito(dadosFechamentos4.Sum((DadosFechamento t) => t.get_Credito())); + List dadosFechamentos5 = fechamentoFinanceiro3.get_Dados(); + dadosFechamento2.set_Debito(dadosFechamentos5.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos6 = fechamentoFinanceiro3.get_Dados(); + if (dadosFechamentos6.Sum((DadosFechamento t) => t.get_Credito()) == decimal.Zero) + { + num7 = decimal.Zero; + } + else + { + List dadosFechamentos7 = fechamentoFinanceiro3.get_Dados(); + decimal num18 = dadosFechamentos7.Sum((DadosFechamento t) => t.get_Credito()); + List lancamentos18 = lancamentos13; + IEnumerable lancamentos19 = lancamentos18.Where((Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 0; + }); + num7 = (num18 / lancamentos19.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento2.set_PercentualCredito(num7); + List dadosFechamentos8 = fechamentoFinanceiro3.get_Dados(); + if (dadosFechamentos8.Sum((DadosFechamento t) => t.get_Debito()) == decimal.Zero) + { + num8 = decimal.Zero; + } + else + { + List dadosFechamentos9 = fechamentoFinanceiro3.get_Dados(); + decimal num19 = dadosFechamentos9.Sum((DadosFechamento t) => t.get_Debito()); + List lancamentos20 = lancamentos13; + IEnumerable lancamentos21 = lancamentos20.Where((Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 1; + }); + num8 = (num19 / lancamentos21.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento2.set_PercentualDebito(num8); + dadosFechamentos3.Add(dadosFechamento2); + this.Fechamento.Add(fechamentoFinanceiro3); + FechamentoFinanceiro fechamentoFinanceiro4 = new FechamentoFinanceiro(); + fechamentoFinanceiro4.set_Plano("TRANSFERÊNCIA"); + List lancamentos22 = lancamentos13; + IEnumerable lancamentos23 = lancamentos22.Where((Lancamento x) => { + object plano; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = null; + } + return plano == null; + }); + IOrderedEnumerable descricao1 = + from x in lancamentos23 + orderby x.get_Conta().get_Descricao() + select x; + IEnumerable> id = + from x in descricao1 + group x by x.get_Conta().get_Id(); + fechamentoFinanceiro4.set_Dados(id.Select, DadosFechamento>((IGrouping f) => { + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(f.First().get_Conta().get_Descricao()); + dadosFechamento.set_Credito(( + from s in f + where s.get_Sinal() == 0 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())); + dadosFechamento.set_PercentualCredito((( + from s in f + where s.get_Sinal() == 0 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault()) == decimal.Zero ? decimal.Zero : (( + from s in f + where s.get_Sinal() == 0 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault()) / ( + from s in f + where s.get_Sinal() == 0 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100))); + dadosFechamento.set_Debito(( + from s in f + where s.get_Sinal() == 1 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())); + dadosFechamento.set_PercentualDebito((( + from s in f + where s.get_Sinal() == 1 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault()) == decimal.Zero ? decimal.Zero : (( + from s in f + where s.get_Sinal() == 1 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault()) / ( + from s in f + where s.get_Sinal() == 1 + select s).Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100))); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro5 = fechamentoFinanceiro4; + List dadosFechamentos10 = fechamentoFinanceiro5.get_Dados(); + DadosFechamento dadosFechamento3 = new DadosFechamento(); + dadosFechamento3.set_Planos("TOTAL"); + List dadosFechamentos11 = fechamentoFinanceiro5.get_Dados(); + dadosFechamento3.set_Credito(dadosFechamentos11.Sum((DadosFechamento t) => t.get_Credito())); + List dadosFechamentos12 = fechamentoFinanceiro5.get_Dados(); + dadosFechamento3.set_Debito(dadosFechamentos12.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos13 = fechamentoFinanceiro5.get_Dados(); + if (dadosFechamentos13.Sum((DadosFechamento t) => t.get_Credito()) == decimal.Zero) + { + num9 = decimal.Zero; + } + else + { + List dadosFechamentos14 = fechamentoFinanceiro5.get_Dados(); + decimal num20 = dadosFechamentos14.Sum((DadosFechamento t) => t.get_Credito()); + List lancamentos24 = lancamentos13; + IEnumerable lancamentos25 = lancamentos24.Where((Lancamento s) => { + bool plano; + ControleFinanceiro controle = s.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = false; + } + if (plano) + { + return false; + } + return s.get_Sinal() == 0; + }); + num9 = (num20 / lancamentos25.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento3.set_PercentualCredito(num9); + List dadosFechamentos15 = fechamentoFinanceiro5.get_Dados(); + if (dadosFechamentos15.Sum((DadosFechamento t) => t.get_Debito()) == decimal.Zero) + { + num10 = decimal.Zero; + } + else + { + List dadosFechamentos16 = fechamentoFinanceiro5.get_Dados(); + decimal num21 = dadosFechamentos16.Sum((DadosFechamento t) => t.get_Debito()); + List lancamentos26 = lancamentos13; + IEnumerable lancamentos27 = lancamentos26.Where((Lancamento s) => { + bool plano; + ControleFinanceiro controle = s.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = false; + } + if (plano) + { + return false; + } + return s.get_Sinal() == 1; + }); + num10 = (num21 / lancamentos27.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento3.set_PercentualDebito(num10); + dadosFechamentos10.Add(dadosFechamento3); + this.Fechamento.Add(fechamentoFinanceiro5); + FechamentoFinanceiro fechamentoFinanceiro6 = new FechamentoFinanceiro(); + fechamentoFinanceiro6.set_Plano("CONTA CORRENTE + TRANSFERÊNCIA"); + List lancamentos28 = lancamentos13; + IOrderedEnumerable descricao2 = + from x in lancamentos28 + orderby x.get_Conta().get_Descricao() + select x; + fechamentoFinanceiro6.set_Dados(( + from x in descricao2 + group x by x.get_Conta().get_Id()).Select, DadosFechamento>((IGrouping f) => { + decimal zero; + decimal num; + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(f.First().get_Conta().get_Descricao()); + IGrouping nums = f; + Func u003cu003e9_51189 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_189; + if (u003cu003e9_51189 == null) + { + u003cu003e9_51189 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_189 = u003cu003e9_51189; + } + IEnumerable lancamentos = nums.Where(u003cu003e9_51189); + Func u003cu003e9_51190 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_190; + if (u003cu003e9_51190 == null) + { + u003cu003e9_51190 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_190 = u003cu003e9_51190; + } + dadosFechamento.set_Credito(lancamentos.Sum(u003cu003e9_51190)); + IGrouping nums1 = f; + Func u003cu003e9_51191 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_191; + if (u003cu003e9_51191 == null) + { + u003cu003e9_51191 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_191 = u003cu003e9_51191; + } + IEnumerable lancamentos1 = nums1.Where(u003cu003e9_51191); + Func u003cu003e9_51192 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_192; + if (u003cu003e9_51192 == null) + { + u003cu003e9_51192 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_192 = u003cu003e9_51192; + } + if (lancamentos1.Sum(u003cu003e9_51192) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping nums2 = f; + Func u003cu003e9_51193 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_193; + if (u003cu003e9_51193 == null) + { + u003cu003e9_51193 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_193 = u003cu003e9_51193; + } + IEnumerable lancamentos2 = nums2.Where(u003cu003e9_51193); + Func u003cu003e9_51194 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_194; + if (u003cu003e9_51194 == null) + { + u003cu003e9_51194 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_194 = u003cu003e9_51194; + } + decimal num1 = lancamentos2.Sum(u003cu003e9_51194); + List lancamentos3 = lancamentos13; + Func u003cu003e9_51195 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_195; + if (u003cu003e9_51195 == null) + { + u003cu003e9_51195 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_195 = u003cu003e9_51195; + } + IEnumerable lancamentos4 = lancamentos3.Where(u003cu003e9_51195); + Func u003cu003e9_51196 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_196; + if (u003cu003e9_51196 == null) + { + u003cu003e9_51196 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_196 = u003cu003e9_51196; + } + zero = (num1 / lancamentos4.Sum(u003cu003e9_51196)) * new decimal(100); + } + dadosFechamento.set_PercentualCredito(zero); + IGrouping nums3 = f; + Func u003cu003e9_51197 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_197; + if (u003cu003e9_51197 == null) + { + u003cu003e9_51197 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_197 = u003cu003e9_51197; + } + IEnumerable lancamentos5 = nums3.Where(u003cu003e9_51197); + Func u003cu003e9_51198 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_198; + if (u003cu003e9_51198 == null) + { + u003cu003e9_51198 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_198 = u003cu003e9_51198; + } + dadosFechamento.set_Debito(lancamentos5.Sum(u003cu003e9_51198)); + IGrouping nums4 = f; + Func u003cu003e9_51199 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_199; + if (u003cu003e9_51199 == null) + { + u003cu003e9_51199 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_199 = u003cu003e9_51199; + } + IEnumerable lancamentos6 = nums4.Where(u003cu003e9_51199); + Func u003cu003e9_51200 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_200; + if (u003cu003e9_51200 == null) + { + u003cu003e9_51200 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_200 = u003cu003e9_51200; + } + if (lancamentos6.Sum(u003cu003e9_51200) == decimal.Zero) + { + num = decimal.Zero; + } + else + { + IGrouping nums5 = f; + Func u003cu003e9_51201 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_201; + if (u003cu003e9_51201 == null) + { + u003cu003e9_51201 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_201 = u003cu003e9_51201; + } + IEnumerable lancamentos7 = nums5.Where(u003cu003e9_51201); + Func u003cu003e9_51202 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_202; + if (u003cu003e9_51202 == null) + { + u003cu003e9_51202 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_202 = u003cu003e9_51202; + } + decimal num2 = lancamentos7.Sum(u003cu003e9_51202); + List lancamentos8 = lancamentos13; + Func u003cu003e9_51203 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_203; + if (u003cu003e9_51203 == null) + { + u003cu003e9_51203 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_203 = u003cu003e9_51203; + } + IEnumerable lancamentos9 = lancamentos8.Where(u003cu003e9_51203); + Func u003cu003e9_51204 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_204; + if (u003cu003e9_51204 == null) + { + u003cu003e9_51204 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_204 = u003cu003e9_51204; + } + num = (num2 / lancamentos9.Sum(u003cu003e9_51204)) * new decimal(100); + } + dadosFechamento.set_PercentualDebito(num); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro7 = fechamentoFinanceiro6; + List dadosFechamentos17 = fechamentoFinanceiro7.get_Dados(); + DadosFechamento dadosFechamento4 = new DadosFechamento(); + dadosFechamento4.set_Planos("TOTAL"); + List dadosFechamentos18 = fechamentoFinanceiro7.get_Dados(); + dadosFechamento4.set_Credito(dadosFechamentos18.Sum((DadosFechamento t) => t.get_Credito())); + List dadosFechamentos19 = fechamentoFinanceiro7.get_Dados(); + dadosFechamento4.set_Debito(dadosFechamentos19.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos20 = fechamentoFinanceiro7.get_Dados(); + if (dadosFechamentos20.Sum((DadosFechamento t) => t.get_Credito()) == decimal.Zero) + { + num11 = decimal.Zero; + } + else + { + List dadosFechamentos21 = fechamentoFinanceiro7.get_Dados(); + decimal num22 = dadosFechamentos21.Sum((DadosFechamento t) => t.get_Credito()); + List lancamentos29 = lancamentos13; + IEnumerable sinal = + from s in lancamentos29 + where s.get_Sinal() == 0 + select s; + num11 = (num22 / sinal.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento4.set_PercentualCredito(num11); + List dadosFechamentos22 = fechamentoFinanceiro7.get_Dados(); + if (dadosFechamentos22.Sum((DadosFechamento t) => t.get_Debito()) == decimal.Zero) + { + num12 = decimal.Zero; + } + else + { + List dadosFechamentos23 = fechamentoFinanceiro7.get_Dados(); + decimal num23 = dadosFechamentos23.Sum((DadosFechamento t) => t.get_Debito()); + List lancamentos30 = lancamentos13; + IEnumerable sinal1 = + from s in lancamentos30 + where s.get_Sinal() == 1 + select s; + num12 = (num23 / sinal1.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento4.set_PercentualDebito(num12); + dadosFechamentos17.Add(dadosFechamento4); + this.Fechamento.Add(fechamentoFinanceiro7); + FechamentoFinanceiro fechamentoFinanceiro8 = new FechamentoFinanceiro(); + fechamentoFinanceiro8.set_Plano("CENTRO DE CUSTO"); + List lancamentos31 = lancamentos13; + IEnumerable lancamentos32 = lancamentos31.Where((Lancamento x) => { + object plano; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = null; + } + return plano != null; + }); + IOrderedEnumerable descricao3 = + from x in lancamentos32 + orderby x.get_Controle().get_Centro().get_Descricao() + select x; + fechamentoFinanceiro8.set_Dados(( + from x in descricao3 + group x by x.get_Controle().get_Centro().get_Id()).Select, DadosFechamento>((IGrouping f) => { + decimal zero; + decimal num; + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(f.First().get_Controle().get_Centro().get_Descricao()); + IGrouping nums = f; + Func u003cu003e9_51219 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_219; + if (u003cu003e9_51219 == null) + { + u003cu003e9_51219 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_219 = u003cu003e9_51219; + } + IEnumerable lancamentos = nums.Where(u003cu003e9_51219); + Func u003cu003e9_51220 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_220; + if (u003cu003e9_51220 == null) + { + u003cu003e9_51220 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_220 = u003cu003e9_51220; + } + dadosFechamento.set_Credito(lancamentos.Sum(u003cu003e9_51220)); + IGrouping nums1 = f; + Func u003cu003e9_51221 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_221; + if (u003cu003e9_51221 == null) + { + u003cu003e9_51221 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_221 = u003cu003e9_51221; + } + IEnumerable lancamentos1 = nums1.Where(u003cu003e9_51221); + Func u003cu003e9_51222 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_222; + if (u003cu003e9_51222 == null) + { + u003cu003e9_51222 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_222 = u003cu003e9_51222; + } + if (lancamentos1.Sum(u003cu003e9_51222) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping nums2 = f; + Func u003cu003e9_51223 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_223; + if (u003cu003e9_51223 == null) + { + u003cu003e9_51223 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_223 = u003cu003e9_51223; + } + IEnumerable lancamentos2 = nums2.Where(u003cu003e9_51223); + Func u003cu003e9_51224 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_224; + if (u003cu003e9_51224 == null) + { + u003cu003e9_51224 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_224 = u003cu003e9_51224; + } + decimal num1 = lancamentos2.Sum(u003cu003e9_51224); + List lancamentos3 = lancamentos13; + Func u003cu003e9_51225 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_225; + if (u003cu003e9_51225 == null) + { + u003cu003e9_51225 = (Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 0; + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_225 = u003cu003e9_51225; + } + IEnumerable lancamentos4 = lancamentos3.Where(u003cu003e9_51225); + Func u003cu003e9_51226 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_226; + if (u003cu003e9_51226 == null) + { + u003cu003e9_51226 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_226 = u003cu003e9_51226; + } + zero = (num1 / lancamentos4.Sum(u003cu003e9_51226)) * new decimal(100); + } + dadosFechamento.set_PercentualCredito(zero); + IGrouping nums3 = f; + Func u003cu003e9_51227 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_227; + if (u003cu003e9_51227 == null) + { + u003cu003e9_51227 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_227 = u003cu003e9_51227; + } + IEnumerable lancamentos5 = nums3.Where(u003cu003e9_51227); + Func u003cu003e9_51228 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_228; + if (u003cu003e9_51228 == null) + { + u003cu003e9_51228 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_228 = u003cu003e9_51228; + } + dadosFechamento.set_Debito(lancamentos5.Sum(u003cu003e9_51228)); + IGrouping nums4 = f; + Func u003cu003e9_51229 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_229; + if (u003cu003e9_51229 == null) + { + u003cu003e9_51229 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_229 = u003cu003e9_51229; + } + IEnumerable lancamentos6 = nums4.Where(u003cu003e9_51229); + Func u003cu003e9_51230 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_230; + if (u003cu003e9_51230 == null) + { + u003cu003e9_51230 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_230 = u003cu003e9_51230; + } + if (lancamentos6.Sum(u003cu003e9_51230) == decimal.Zero) + { + num = decimal.Zero; + } + else + { + IGrouping nums5 = f; + Func u003cu003e9_51231 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_231; + if (u003cu003e9_51231 == null) + { + u003cu003e9_51231 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_231 = u003cu003e9_51231; + } + IEnumerable lancamentos7 = nums5.Where(u003cu003e9_51231); + Func u003cu003e9_51232 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_232; + if (u003cu003e9_51232 == null) + { + u003cu003e9_51232 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_232 = u003cu003e9_51232; + } + decimal num2 = lancamentos7.Sum(u003cu003e9_51232); + List lancamentos8 = lancamentos13; + Func u003cu003e9_51233 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_233; + if (u003cu003e9_51233 == null) + { + u003cu003e9_51233 = (Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 1; + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_233 = u003cu003e9_51233; + } + IEnumerable lancamentos9 = lancamentos8.Where(u003cu003e9_51233); + Func u003cu003e9_51234 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_234; + if (u003cu003e9_51234 == null) + { + u003cu003e9_51234 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_234 = u003cu003e9_51234; + } + num = (num2 / lancamentos9.Sum(u003cu003e9_51234)) * new decimal(100); + } + dadosFechamento.set_PercentualDebito(num); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro9 = fechamentoFinanceiro8; + List dadosFechamentos24 = fechamentoFinanceiro9.get_Dados(); + DadosFechamento dadosFechamento5 = new DadosFechamento(); + dadosFechamento5.set_Planos("TOTAL"); + List dadosFechamentos25 = fechamentoFinanceiro9.get_Dados(); + dadosFechamento5.set_Credito(dadosFechamentos25.Sum((DadosFechamento t) => t.get_Credito())); + List dadosFechamentos26 = fechamentoFinanceiro9.get_Dados(); + dadosFechamento5.set_Debito(dadosFechamentos26.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos27 = fechamentoFinanceiro9.get_Dados(); + if (dadosFechamentos27.Sum((DadosFechamento t) => t.get_Credito()) == decimal.Zero) + { + num13 = decimal.Zero; + } + else + { + List dadosFechamentos28 = fechamentoFinanceiro9.get_Dados(); + decimal num24 = dadosFechamentos28.Sum((DadosFechamento t) => t.get_Credito()); + List lancamentos33 = lancamentos13; + IEnumerable lancamentos34 = lancamentos33.Where((Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 0; + }); + num13 = (num24 / lancamentos34.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento5.set_PercentualCredito(num13); + List dadosFechamentos29 = fechamentoFinanceiro9.get_Dados(); + if (dadosFechamentos29.Sum((DadosFechamento t) => t.get_Debito()) == decimal.Zero) + { + num14 = decimal.Zero; + } + else + { + List dadosFechamentos30 = fechamentoFinanceiro9.get_Dados(); + decimal num25 = dadosFechamentos30.Sum((DadosFechamento t) => t.get_Debito()); + List lancamentos35 = lancamentos13; + IEnumerable lancamentos36 = lancamentos35.Where((Lancamento s) => { + if (s.get_Controle() == null) + { + return false; + } + return s.get_Sinal() == 1; + }); + num14 = (num25 / lancamentos36.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento5.set_PercentualDebito(num14); + dadosFechamentos24.Add(dadosFechamento5); + this.Fechamento.Add(fechamentoFinanceiro9); + FechamentoFinanceiro fechamentoFinanceiro10 = new FechamentoFinanceiro(); + fechamentoFinanceiro10.set_Plano("TIPO PAGAMENTO"); + List lancamentos37 = lancamentos13; + IOrderedEnumerable description = + from x in lancamentos37 + orderby EnumHelper.GetDescription(x.get_TipoPagamento()) + select x; + fechamentoFinanceiro10.set_Dados(( + from x in description + group x by x.get_TipoPagamento()).Select, DadosFechamento>((IGrouping f) => { + decimal zero; + decimal num; + DadosFechamento dadosFechamento = new DadosFechamento(); + dadosFechamento.set_Planos(EnumHelper.GetDescription(f.First().get_TipoPagamento())); + IGrouping tipoPagamentos = f; + Func u003cu003e9_51248 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_248; + if (u003cu003e9_51248 == null) + { + u003cu003e9_51248 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_248 = u003cu003e9_51248; + } + IEnumerable lancamentos = tipoPagamentos.Where(u003cu003e9_51248); + Func u003cu003e9_51249 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_249; + if (u003cu003e9_51249 == null) + { + u003cu003e9_51249 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_249 = u003cu003e9_51249; + } + dadosFechamento.set_Credito(lancamentos.Sum(u003cu003e9_51249)); + IGrouping tipoPagamentos1 = f; + Func u003cu003e9_51250 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_250; + if (u003cu003e9_51250 == null) + { + u003cu003e9_51250 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_250 = u003cu003e9_51250; + } + IEnumerable lancamentos1 = tipoPagamentos1.Where(u003cu003e9_51250); + Func u003cu003e9_51251 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_251; + if (u003cu003e9_51251 == null) + { + u003cu003e9_51251 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_251 = u003cu003e9_51251; + } + if (lancamentos1.Sum(u003cu003e9_51251) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping tipoPagamentos2 = f; + Func u003cu003e9_51252 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_252; + if (u003cu003e9_51252 == null) + { + u003cu003e9_51252 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_252 = u003cu003e9_51252; + } + IEnumerable lancamentos2 = tipoPagamentos2.Where(u003cu003e9_51252); + Func u003cu003e9_51253 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_253; + if (u003cu003e9_51253 == null) + { + u003cu003e9_51253 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_253 = u003cu003e9_51253; + } + decimal num1 = lancamentos2.Sum(u003cu003e9_51253); + List lancamentos3 = lancamentos13; + Func u003cu003e9_51254 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_254; + if (u003cu003e9_51254 == null) + { + u003cu003e9_51254 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_254 = u003cu003e9_51254; + } + IEnumerable lancamentos4 = lancamentos3.Where(u003cu003e9_51254); + Func u003cu003e9_51255 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_255; + if (u003cu003e9_51255 == null) + { + u003cu003e9_51255 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_255 = u003cu003e9_51255; + } + zero = (num1 / lancamentos4.Sum(u003cu003e9_51255)) * new decimal(100); + } + dadosFechamento.set_PercentualCredito(zero); + IGrouping tipoPagamentos3 = f; + Func u003cu003e9_51256 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_256; + if (u003cu003e9_51256 == null) + { + u003cu003e9_51256 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_256 = u003cu003e9_51256; + } + IEnumerable lancamentos5 = tipoPagamentos3.Where(u003cu003e9_51256); + Func u003cu003e9_51257 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_257; + if (u003cu003e9_51257 == null) + { + u003cu003e9_51257 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_257 = u003cu003e9_51257; + } + dadosFechamento.set_Debito(lancamentos5.Sum(u003cu003e9_51257)); + IGrouping tipoPagamentos4 = f; + Func u003cu003e9_51258 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_258; + if (u003cu003e9_51258 == null) + { + u003cu003e9_51258 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_258 = u003cu003e9_51258; + } + IEnumerable lancamentos6 = tipoPagamentos4.Where(u003cu003e9_51258); + Func u003cu003e9_51259 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_259; + if (u003cu003e9_51259 == null) + { + u003cu003e9_51259 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_259 = u003cu003e9_51259; + } + if (lancamentos6.Sum(u003cu003e9_51259) == decimal.Zero) + { + num = decimal.Zero; + } + else + { + IGrouping tipoPagamentos5 = f; + Func u003cu003e9_51260 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_260; + if (u003cu003e9_51260 == null) + { + u003cu003e9_51260 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_260 = u003cu003e9_51260; + } + IEnumerable lancamentos7 = tipoPagamentos5.Where(u003cu003e9_51260); + Func u003cu003e9_51261 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_261; + if (u003cu003e9_51261 == null) + { + u003cu003e9_51261 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_261 = u003cu003e9_51261; + } + decimal num2 = lancamentos7.Sum(u003cu003e9_51261); + List lancamentos8 = lancamentos13; + Func u003cu003e9_51262 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_262; + if (u003cu003e9_51262 == null) + { + u003cu003e9_51262 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_262 = u003cu003e9_51262; + } + IEnumerable lancamentos9 = lancamentos8.Where(u003cu003e9_51262); + Func u003cu003e9_51263 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_263; + if (u003cu003e9_51263 == null) + { + u003cu003e9_51263 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_263 = u003cu003e9_51263; + } + num = (num2 / lancamentos9.Sum(u003cu003e9_51263)) * new decimal(100); + } + dadosFechamento.set_PercentualDebito(num); + return dadosFechamento; + }).ToList()); + FechamentoFinanceiro fechamentoFinanceiro11 = fechamentoFinanceiro10; + List dadosFechamentos31 = fechamentoFinanceiro11.get_Dados(); + DadosFechamento dadosFechamento6 = new DadosFechamento(); + dadosFechamento6.set_Planos("TOTAL"); + List dadosFechamentos32 = fechamentoFinanceiro11.get_Dados(); + dadosFechamento6.set_Credito(dadosFechamentos32.Sum((DadosFechamento t) => t.get_Credito())); + List dadosFechamentos33 = fechamentoFinanceiro11.get_Dados(); + dadosFechamento6.set_Debito(dadosFechamentos33.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos34 = fechamentoFinanceiro11.get_Dados(); + if (dadosFechamentos34.Sum((DadosFechamento t) => t.get_Credito()) == decimal.Zero) + { + num15 = decimal.Zero; + } + else + { + List dadosFechamentos35 = fechamentoFinanceiro11.get_Dados(); + decimal num26 = dadosFechamentos35.Sum((DadosFechamento t) => t.get_Credito()); + List lancamentos38 = lancamentos13; + IEnumerable sinal2 = + from s in lancamentos38 + where s.get_Sinal() == 0 + select s; + num15 = (num26 / sinal2.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento6.set_PercentualCredito(num15); + List dadosFechamentos36 = fechamentoFinanceiro11.get_Dados(); + if (dadosFechamentos36.Sum((DadosFechamento t) => t.get_Debito()) == decimal.Zero) + { + num16 = decimal.Zero; + } + else + { + List dadosFechamentos37 = fechamentoFinanceiro11.get_Dados(); + decimal num27 = dadosFechamentos37.Sum((DadosFechamento t) => t.get_Debito()); + List lancamentos39 = lancamentos13; + IEnumerable sinal3 = + from s in lancamentos39 + where s.get_Sinal() == 1 + select s; + num16 = (num27 / sinal3.Sum((Lancamento s) => s.get_ValorPago().GetValueOrDefault())) * new decimal(100); + } + dadosFechamento6.set_PercentualDebito(num16); + List dadosFechamentos38 = fechamentoFinanceiro11.get_Dados(); + decimal num28 = dadosFechamentos38.Sum((DadosFechamento t) => t.get_Credito()); + List dadosFechamentos39 = fechamentoFinanceiro11.get_Dados(); + dadosFechamento6.set_Soma(num28 - dadosFechamentos39.Sum((DadosFechamento t) => t.get_Debito())); + List dadosFechamentos40 = fechamentoFinanceiro11.get_Dados(); + decimal num29 = dadosFechamentos40.Sum((DadosFechamento t) => t.get_Credito()); + List dadosFechamentos41 = fechamentoFinanceiro11.get_Dados(); + if ((num29 + dadosFechamentos41.Sum((DadosFechamento t) => t.get_Debito())) == decimal.Zero) + { + num17 = decimal.Zero; + } + else + { + List dadosFechamentos42 = fechamentoFinanceiro11.get_Dados(); + decimal num30 = dadosFechamentos42.Sum((DadosFechamento t) => t.get_Credito()); + List dadosFechamentos43 = fechamentoFinanceiro11.get_Dados(); + decimal num31 = (num30 - dadosFechamentos43.Sum((DadosFechamento t) => t.get_Debito())) * new decimal(100); + List dadosFechamentos44 = fechamentoFinanceiro11.get_Dados(); + decimal num32 = dadosFechamentos44.Sum((DadosFechamento t) => t.get_Credito()); + List dadosFechamentos45 = fechamentoFinanceiro11.get_Dados(); + num17 = num31 / (num32 + dadosFechamentos45.Sum((DadosFechamento t) => t.get_Debito())); + } + dadosFechamento6.set_SomaPercentual(num17); + dadosFechamentos31.Add(dadosFechamento6); + this.Fechamento.Add(fechamentoFinanceiro11); + } + else + { + this.FechamentoAnalitico = new List(); + List lancamentos40 = lancamentos13; + IEnumerable lancamentos41 = lancamentos40.Where((Lancamento x) => { + object plano; + ControleFinanceiro controle = x.get_Controle(); + if (controle != null) + { + plano = controle.get_Plano(); + } + else + { + plano = null; + } + return plano != null; + }); + IOrderedEnumerable nome1 = + from x in lancamentos41 + orderby x.get_Controle().get_Plano().get_Nome() + select x; + ( + from x in nome1 + group x by x.get_Controle().get_Plano().get_Plano().get_Id()).ToList>().ForEach((IGrouping x) => { + FechamentoFinanceiroAnalitico fechamentoFinanceiroAnalitico = new FechamentoFinanceiroAnalitico(); + fechamentoFinanceiroAnalitico.set_NomeConta(x.First().get_Controle().get_Plano().get_Plano().get_Descricao().ToUpper()); + IGrouping nums19 = x; + Func u003cu003e9_5112 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_12; + if (u003cu003e9_5112 == null) + { + u003cu003e9_5112 = (Lancamento f) => f.get_Controle().get_Plano().get_Id(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_12 = u003cu003e9_5112; + } + IOrderedEnumerable lancamentos12 = nums19.OrderBy(u003cu003e9_5112); + Func u003cu003e9_5113 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_13; + if (u003cu003e9_5113 == null) + { + u003cu003e9_5113 = (Lancamento f) => f.get_Controle().get_Plano().get_Id(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_13 = u003cu003e9_5113; + } + fechamentoFinanceiroAnalitico.set_Dados(lancamentos12.GroupBy(u003cu003e9_5113).Select, DadosFechamentoAnalitico>((IGrouping f) => { + Func func; + decimal zero; + decimal zero1; + DadosFechamentoAnalitico dadosFechamentoAnalitico = new DadosFechamentoAnalitico(); + dadosFechamentoAnalitico.set_Nome(f.First().get_Controle().get_Plano().get_Descricao()); + IGrouping nums = f; + Func u003cu003e9_15 = func8; + if (u003cu003e9_15 == null) + { + Func cSu0024u003cu003e8_locals11 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 1, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 1, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = cSu0024u003cu003e8_locals11; + func8 = cSu0024u003cu003e8_locals11; + u003cu003e9_15 = func; + } + List list = nums.Where(u003cu003e9_15).ToList(); + Func u003cu003e9_5116 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_16; + if (u003cu003e9_5116 == null) + { + u003cu003e9_5116 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_16 = u003cu003e9_5116; + } + dadosFechamentoAnalitico.set_Jan(list.Sum(u003cu003e9_5116)); + IGrouping nums1 = f; + Func u003cu003e9_17 = func9; + if (u003cu003e9_17 == null) + { + Func func1 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 2, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + int year = filtroFinanceiro1.get_Inicio().Year; + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(year, 2, DateTime.DaysInMonth(inicio.Year, 2)); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func1; + func9 = func1; + u003cu003e9_17 = func; + } + List lancamentos = nums1.Where(u003cu003e9_17).ToList(); + Func u003cu003e9_5118 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_18; + if (u003cu003e9_5118 == null) + { + u003cu003e9_5118 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_18 = u003cu003e9_5118; + } + dadosFechamentoAnalitico.set_Fev(lancamentos.Sum(u003cu003e9_5118)); + IGrouping nums2 = f; + Func u003cu003e9_19 = func10; + if (u003cu003e9_19 == null) + { + Func cSu0024u003cu003e8_locals12 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 3, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 3, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = cSu0024u003cu003e8_locals12; + func10 = cSu0024u003cu003e8_locals12; + u003cu003e9_19 = func; + } + List list1 = nums2.Where(u003cu003e9_19).ToList(); + Func u003cu003e9_5120 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_20; + if (u003cu003e9_5120 == null) + { + u003cu003e9_5120 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_20 = u003cu003e9_5120; + } + dadosFechamentoAnalitico.set_Mar(list1.Sum(u003cu003e9_5120)); + IGrouping nums3 = f; + Func u003cu003e9_21 = func11; + if (u003cu003e9_21 == null) + { + Func func2 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 4, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 4, 30); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func2; + func11 = func2; + u003cu003e9_21 = func; + } + List lancamentos1 = nums3.Where(u003cu003e9_21).ToList(); + Func u003cu003e9_5122 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_22; + if (u003cu003e9_5122 == null) + { + u003cu003e9_5122 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_22 = u003cu003e9_5122; + } + dadosFechamentoAnalitico.set_Abr(lancamentos1.Sum(u003cu003e9_5122)); + IGrouping nums4 = f; + Func u003cu003e9_23 = func12; + if (u003cu003e9_23 == null) + { + Func func3 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 5, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 5, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func3; + func12 = func3; + u003cu003e9_23 = func; + } + List list2 = nums4.Where(u003cu003e9_23).ToList(); + Func u003cu003e9_5124 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_24; + if (u003cu003e9_5124 == null) + { + u003cu003e9_5124 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_24 = u003cu003e9_5124; + } + dadosFechamentoAnalitico.set_Mai(list2.Sum(u003cu003e9_5124)); + IGrouping nums5 = f; + Func u003cu003e9_25 = func13; + if (u003cu003e9_25 == null) + { + Func cSu0024u003cu003e8_locals14 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 6, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 6, 30); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = cSu0024u003cu003e8_locals14; + func13 = cSu0024u003cu003e8_locals14; + u003cu003e9_25 = func; + } + List lancamentos2 = nums5.Where(u003cu003e9_25).ToList(); + Func u003cu003e9_5126 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_26; + if (u003cu003e9_5126 == null) + { + u003cu003e9_5126 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_26 = u003cu003e9_5126; + } + dadosFechamentoAnalitico.set_Jun(lancamentos2.Sum(u003cu003e9_5126)); + IGrouping nums6 = f; + Func u003cu003e9_27 = func14; + if (u003cu003e9_27 == null) + { + Func func4 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 7, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 7, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func4; + func14 = func4; + u003cu003e9_27 = func; + } + List list3 = nums6.Where(u003cu003e9_27).ToList(); + Func u003cu003e9_5128 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_28; + if (u003cu003e9_5128 == null) + { + u003cu003e9_5128 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_28 = u003cu003e9_5128; + } + dadosFechamentoAnalitico.set_Jul(list3.Sum(u003cu003e9_5128)); + IGrouping nums7 = f; + Func u003cu003e9_29 = func15; + if (u003cu003e9_29 == null) + { + Func func5 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 8, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 8, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func5; + func15 = func5; + u003cu003e9_29 = func; + } + List lancamentos3 = nums7.Where(u003cu003e9_29).ToList(); + Func u003cu003e9_5130 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_30; + if (u003cu003e9_5130 == null) + { + u003cu003e9_5130 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_30 = u003cu003e9_5130; + } + dadosFechamentoAnalitico.set_Ago(lancamentos3.Sum(u003cu003e9_5130)); + IGrouping nums8 = f; + Func u003cu003e9_31 = func16; + if (u003cu003e9_31 == null) + { + Func cSu0024u003cu003e8_locals16 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 9, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 9, 30); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = cSu0024u003cu003e8_locals16; + func16 = cSu0024u003cu003e8_locals16; + u003cu003e9_31 = func; + } + List list4 = nums8.Where(u003cu003e9_31).ToList(); + Func u003cu003e9_5132 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_32; + if (u003cu003e9_5132 == null) + { + u003cu003e9_5132 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_32 = u003cu003e9_5132; + } + dadosFechamentoAnalitico.set_Set(list4.Sum(u003cu003e9_5132)); + IGrouping nums9 = f; + Func u003cu003e9_33 = func17; + if (u003cu003e9_33 == null) + { + Func func6 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 10, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 10, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func6; + func17 = func6; + u003cu003e9_33 = func; + } + List lancamentos4 = nums9.Where(u003cu003e9_33).ToList(); + Func u003cu003e9_5134 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_34; + if (u003cu003e9_5134 == null) + { + u003cu003e9_5134 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_34 = u003cu003e9_5134; + } + dadosFechamentoAnalitico.set_Out(lancamentos4.Sum(u003cu003e9_5134)); + IGrouping nums10 = f; + Func u003cu003e9_35 = func18; + if (u003cu003e9_35 == null) + { + Func func7 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 11, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 11, 30); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = func7; + func18 = func7; + u003cu003e9_35 = func; + } + List list5 = nums10.Where(u003cu003e9_35).ToList(); + Func u003cu003e9_5136 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_36; + if (u003cu003e9_5136 == null) + { + u003cu003e9_5136 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_36 = u003cu003e9_5136; + } + dadosFechamentoAnalitico.set_Nov(list5.Sum(u003cu003e9_5136)); + IGrouping nums11 = f; + Func u003cu003e9_37 = func19; + if (u003cu003e9_37 == null) + { + Func cSu0024u003cu003e8_locals18 = (Lancamento s) => { + DateTime? baixa = s.get_Baixa(); + DateTime inicio = filtroFinanceiro1.get_Inicio(); + DateTime dateTime = new DateTime(inicio.Year, 12, 1); + if ((baixa.HasValue ? baixa.GetValueOrDefault() < dateTime : true)) + { + return false; + } + baixa = s.get_Baixa(); + inicio = filtroFinanceiro1.get_Inicio(); + dateTime = new DateTime(inicio.Year, 12, 31); + if (!baixa.HasValue) + { + return false; + } + return baixa.GetValueOrDefault() <= dateTime; + }; + func = cSu0024u003cu003e8_locals18; + func19 = cSu0024u003cu003e8_locals18; + u003cu003e9_37 = func; + } + List lancamentos5 = nums11.Where(u003cu003e9_37).ToList(); + Func u003cu003e9_5138 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_38; + if (u003cu003e9_5138 == null) + { + u003cu003e9_5138 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_38 = u003cu003e9_5138; + } + dadosFechamentoAnalitico.set_Dez(lancamentos5.Sum(u003cu003e9_5138)); + IGrouping nums12 = f; + Func u003cu003e9_5139 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_39; + if (u003cu003e9_5139 == null) + { + u003cu003e9_5139 = (Lancamento s) => { + if (s.get_Sinal() != 1) + { + return s.get_ValorPago(); + } + decimal? valorPago = s.get_ValorPago(); + decimal num = 2; + decimal? nullable = s.get_ValorPago(); + decimal? nullable1 = (nullable.HasValue ? new decimal?(num * nullable.GetValueOrDefault()) : null); + if (!valorPago.HasValue | !nullable1.HasValue) + { + nullable = null; + return nullable; + } + return new decimal?(valorPago.GetValueOrDefault() - nullable1.GetValueOrDefault()); + }; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_39 = u003cu003e9_5139; + } + dadosFechamentoAnalitico.set_Total(nums12.Sum(u003cu003e9_5139)); + IGrouping nums13 = f; + Func u003cu003e9_5140 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_40; + if (u003cu003e9_5140 == null) + { + u003cu003e9_5140 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_40 = u003cu003e9_5140; + } + IEnumerable lancamentos6 = nums13.Where(u003cu003e9_5140); + Func u003cu003e9_5141 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_41; + if (u003cu003e9_5141 == null) + { + u003cu003e9_5141 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_41 = u003cu003e9_5141; + } + if (lancamentos6.Sum(u003cu003e9_5141) == decimal.Zero) + { + zero = decimal.Zero; + } + else + { + IGrouping nums14 = f; + Func u003cu003e9_5142 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_42; + if (u003cu003e9_5142 == null) + { + u003cu003e9_5142 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_42 = u003cu003e9_5142; + } + IEnumerable lancamentos7 = nums14.Where(u003cu003e9_5142); + Func u003cu003e9_5143 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_43; + if (u003cu003e9_5143 == null) + { + u003cu003e9_5143 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_43 = u003cu003e9_5143; + } + decimal num1 = lancamentos7.Sum(u003cu003e9_5143); + IGrouping nums15 = x; + Func u003cu003e9_5144 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_44; + if (u003cu003e9_5144 == null) + { + u003cu003e9_5144 = (Lancamento s) => s.get_Sinal() == 0; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_44 = u003cu003e9_5144; + } + IEnumerable lancamentos8 = nums15.Where(u003cu003e9_5144); + Func u003cu003e9_5145 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_45; + if (u003cu003e9_5145 == null) + { + u003cu003e9_5145 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_45 = u003cu003e9_5145; + } + zero = (num1 / lancamentos8.Sum(u003cu003e9_5145)) * new decimal(100); + } + dadosFechamentoAnalitico.set_PercentualCredito(zero); + IGrouping nums16 = f; + Func u003cu003e9_5146 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_46; + if (u003cu003e9_5146 == null) + { + u003cu003e9_5146 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_46 = u003cu003e9_5146; + } + IEnumerable lancamentos9 = nums16.Where(u003cu003e9_5146); + Func u003cu003e9_5147 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_47; + if (u003cu003e9_5147 == null) + { + u003cu003e9_5147 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_47 = u003cu003e9_5147; + } + if (lancamentos9.Sum(u003cu003e9_5147) == decimal.Zero) + { + zero1 = decimal.Zero; + } + else + { + IGrouping nums17 = f; + Func u003cu003e9_5148 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_48; + if (u003cu003e9_5148 == null) + { + u003cu003e9_5148 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_48 = u003cu003e9_5148; + } + IEnumerable lancamentos10 = nums17.Where(u003cu003e9_5148); + Func u003cu003e9_5149 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_49; + if (u003cu003e9_5149 == null) + { + u003cu003e9_5149 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_49 = u003cu003e9_5149; + } + decimal num2 = lancamentos10.Sum(u003cu003e9_5149); + IGrouping nums18 = x; + Func u003cu003e9_5150 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_50; + if (u003cu003e9_5150 == null) + { + u003cu003e9_5150 = (Lancamento s) => s.get_Sinal() == 1; + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_50 = u003cu003e9_5150; + } + IEnumerable lancamentos11 = nums18.Where(u003cu003e9_5150); + Func u003cu003e9_5151 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_51; + if (u003cu003e9_5151 == null) + { + u003cu003e9_5151 = (Lancamento s) => s.get_ValorPago().GetValueOrDefault(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_51 = u003cu003e9_5151; + } + zero1 = (num2 / lancamentos11.Sum(u003cu003e9_5151)) * new decimal(100); + } + dadosFechamentoAnalitico.set_PercentualDebito(zero1); + return dadosFechamentoAnalitico; + }).ToList()); + FechamentoFinanceiroAnalitico fechamentoFinanceiroAnalitico1 = fechamentoFinanceiroAnalitico; + List dados = fechamentoFinanceiroAnalitico1.get_Dados(); + DadosFechamentoAnalitico dadosFechamentoAnalitico1 = new DadosFechamentoAnalitico(); + dadosFechamentoAnalitico1.set_Nome("TOTAL"); + List dadosFechamentoAnaliticos = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5152 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_52; + if (u003cu003e9_5152 == null) + { + u003cu003e9_5152 = (DadosFechamentoAnalitico t) => t.get_Jan(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_52 = u003cu003e9_5152; + } + dadosFechamentoAnalitico1.set_Jan(dadosFechamentoAnaliticos.Sum(u003cu003e9_5152)); + List dados1 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5153 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_53; + if (u003cu003e9_5153 == null) + { + u003cu003e9_5153 = (DadosFechamentoAnalitico t) => t.get_Fev(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_53 = u003cu003e9_5153; + } + dadosFechamentoAnalitico1.set_Fev(dados1.Sum(u003cu003e9_5153)); + List dadosFechamentoAnaliticos1 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5154 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_54; + if (u003cu003e9_5154 == null) + { + u003cu003e9_5154 = (DadosFechamentoAnalitico t) => t.get_Mar(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_54 = u003cu003e9_5154; + } + dadosFechamentoAnalitico1.set_Mar(dadosFechamentoAnaliticos1.Sum(u003cu003e9_5154)); + List dados2 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5155 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_55; + if (u003cu003e9_5155 == null) + { + u003cu003e9_5155 = (DadosFechamentoAnalitico t) => t.get_Abr(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_55 = u003cu003e9_5155; + } + dadosFechamentoAnalitico1.set_Abr(dados2.Sum(u003cu003e9_5155)); + List dadosFechamentoAnaliticos2 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5156 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_56; + if (u003cu003e9_5156 == null) + { + u003cu003e9_5156 = (DadosFechamentoAnalitico t) => t.get_Mai(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_56 = u003cu003e9_5156; + } + dadosFechamentoAnalitico1.set_Mai(dadosFechamentoAnaliticos2.Sum(u003cu003e9_5156)); + List dados3 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5157 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_57; + if (u003cu003e9_5157 == null) + { + u003cu003e9_5157 = (DadosFechamentoAnalitico t) => t.get_Jun(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_57 = u003cu003e9_5157; + } + dadosFechamentoAnalitico1.set_Jun(dados3.Sum(u003cu003e9_5157)); + List dadosFechamentoAnaliticos3 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5158 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_58; + if (u003cu003e9_5158 == null) + { + u003cu003e9_5158 = (DadosFechamentoAnalitico t) => t.get_Jul(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_58 = u003cu003e9_5158; + } + dadosFechamentoAnalitico1.set_Jul(dadosFechamentoAnaliticos3.Sum(u003cu003e9_5158)); + List dados4 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5159 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_59; + if (u003cu003e9_5159 == null) + { + u003cu003e9_5159 = (DadosFechamentoAnalitico t) => t.get_Ago(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_59 = u003cu003e9_5159; + } + dadosFechamentoAnalitico1.set_Ago(dados4.Sum(u003cu003e9_5159)); + List dadosFechamentoAnaliticos4 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5160 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_60; + if (u003cu003e9_5160 == null) + { + u003cu003e9_5160 = (DadosFechamentoAnalitico t) => t.get_Set(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_60 = u003cu003e9_5160; + } + dadosFechamentoAnalitico1.set_Set(dadosFechamentoAnaliticos4.Sum(u003cu003e9_5160)); + List dados5 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5161 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_61; + if (u003cu003e9_5161 == null) + { + u003cu003e9_5161 = (DadosFechamentoAnalitico t) => t.get_Out(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_61 = u003cu003e9_5161; + } + dadosFechamentoAnalitico1.set_Out(dados5.Sum(u003cu003e9_5161)); + List dadosFechamentoAnaliticos5 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5162 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_62; + if (u003cu003e9_5162 == null) + { + u003cu003e9_5162 = (DadosFechamentoAnalitico t) => t.get_Nov(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_62 = u003cu003e9_5162; + } + dadosFechamentoAnalitico1.set_Nov(dadosFechamentoAnaliticos5.Sum(u003cu003e9_5162)); + List dados6 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5163 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_63; + if (u003cu003e9_5163 == null) + { + u003cu003e9_5163 = (DadosFechamentoAnalitico t) => t.get_Dez(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_63 = u003cu003e9_5163; + } + dadosFechamentoAnalitico1.set_Dez(dados6.Sum(u003cu003e9_5163)); + List dadosFechamentoAnaliticos6 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5164 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_64; + if (u003cu003e9_5164 == null) + { + u003cu003e9_5164 = (DadosFechamentoAnalitico t) => t.get_Total(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_64 = u003cu003e9_5164; + } + dadosFechamentoAnalitico1.set_Total(dadosFechamentoAnaliticos6.Sum(u003cu003e9_5164)); + List dados7 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5165 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_65; + if (u003cu003e9_5165 == null) + { + u003cu003e9_5165 = (DadosFechamentoAnalitico t) => t.get_PercentualCredito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_65 = u003cu003e9_5165; + } + dadosFechamentoAnalitico1.set_PercentualCredito(dados7.Sum(u003cu003e9_5165)); + List dadosFechamentoAnaliticos7 = fechamentoFinanceiroAnalitico1.get_Dados(); + Func u003cu003e9_5166 = FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_66; + if (u003cu003e9_5166 == null) + { + u003cu003e9_5166 = (DadosFechamentoAnalitico t) => t.get_PercentualDebito(); + FechamentoFinanceiroViewModel.u003cu003ec.u003cu003e9__51_66 = u003cu003e9_5166; + } + dadosFechamentoAnalitico1.set_PercentualDebito(dadosFechamentoAnaliticos7.Sum(u003cu003e9_5166)); + dados.Add(dadosFechamentoAnalitico1); + this.FechamentoAnalitico.Add(fechamentoFinanceiroAnalitico1); + }); + FechamentoFinanceiroAnalitico fechamentoFinanceiroAnalitico2 = new FechamentoFinanceiroAnalitico(); + fechamentoFinanceiroAnalitico2.set_NomeConta("TOTAL NO PERÍODO"); + fechamentoFinanceiroAnalitico2.set_Dados(new List()); + FechamentoFinanceiroAnalitico fechamentoFinanceiroAnalitico3 = fechamentoFinanceiroAnalitico2; + List dadosFechamentoAnaliticos8 = fechamentoFinanceiroAnalitico3.get_Dados(); + DadosFechamentoAnalitico dadosFechamentoAnalitico2 = new DadosFechamentoAnalitico(); + dadosFechamentoAnalitico2.set_Nome("TOTAL"); + List fechamentoAnalitico = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Jan(fechamentoAnalitico.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Jan(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Fev(fechamentoFinanceiroAnaliticos.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Fev(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico1 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Mar(fechamentoAnalitico1.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Mar(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos1 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Abr(fechamentoFinanceiroAnaliticos1.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Abr(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico2 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Mai(fechamentoAnalitico2.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Mai(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos2 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Jun(fechamentoFinanceiroAnaliticos2.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Jun(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico3 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Jul(fechamentoAnalitico3.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Jul(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos3 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Ago(fechamentoFinanceiroAnaliticos3.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Ago(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico4 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Set(fechamentoAnalitico4.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Set(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos4 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Out(fechamentoFinanceiroAnaliticos4.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Out(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico5 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Nov(fechamentoAnalitico5.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Nov(); + } + return new decimal?(new decimal()); + }))); + List fechamentoFinanceiroAnaliticos5 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Dez(fechamentoFinanceiroAnaliticos5.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Dez(); + } + return new decimal?(new decimal()); + }))); + List fechamentoAnalitico6 = this.FechamentoAnalitico; + dadosFechamentoAnalitico2.set_Total(fechamentoAnalitico6.Sum((FechamentoFinanceiroAnalitico x) => x.get_Dados().Sum((DadosFechamentoAnalitico y) => { + if (y.get_Nome() != "TOTAL") + { + return y.get_Total(); + } + return new decimal?(new decimal()); + }))); + dadosFechamentoAnalitico2.set_PercentualCredito(new decimal(100)); + dadosFechamentoAnalitico2.set_PercentualDebito(new decimal(100)); + dadosFechamentoAnaliticos8.Add(dadosFechamentoAnalitico2); + this.FechamentoAnalitico.Add(fechamentoFinanceiroAnalitico3); + } + this.HtmlContent = await this.GerarHtml(true); + } + } + + private async void LoadInicial() + { + this.Plano = await this._servico.BuscarPlanoAsync(); + this.Planos = await this._servico.BuscarPlanosAsync(); + this.Centro = await this._servico.BuscarCentroAsync(); + this.Conta = await (new BancosContasServico()).BuscarBancos(); + } + + public async Task Print() + { + string tempPath = Path.GetTempPath(); + string str = await this.GerarHtml(false); + string str1 = string.Format("{0}FECHAMENTO_FINANCEIRO_{1:ddMMyyyyhhmmss}.html", tempPath, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + tempPath = null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Financeiro/TranferenciaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Financeiro/TranferenciaViewModel.cs new file mode 100644 index 0000000..d4e189a --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Financeiro/TranferenciaViewModel.cs @@ -0,0 +1,99 @@ +using Gestor.Application.Servicos.Financeiro; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Financeiro +{ + public class TranferenciaViewModel : BaseViewModel + { + private Gestor.Model.Domain.Financeiro.Transferencia _transferencia; + + private ObservableCollection _contas; + + private BancosContasServico _servico + { + get; + set; + } + + public ObservableCollection Contas + { + get + { + return this._contas; + } + set + { + this._contas = value; + base.OnPropertyChanged("Contas"); + } + } + + public Gestor.Model.Domain.Financeiro.Transferencia Transferencia + { + get + { + return this._transferencia; + } + set + { + this._transferencia = value; + base.OnPropertyChanged("Transferencia"); + } + } + + public TranferenciaViewModel(Gestor.Model.Domain.Financeiro.Transferencia transferencia) + { + this._servico = new BancosContasServico(); + this.Carregar(transferencia); + } + + private async void Carregar(Gestor.Model.Domain.Financeiro.Transferencia transferencia) + { + BancosContas bancosConta; + BancosContas bancosConta1; + List bancosContas = await this._servico.BuscarBancos(); + TranferenciaViewModel observableCollection = this; + List bancosContas1 = bancosContas; + IEnumerable ativo = + from x in bancosContas1 + where x.get_Ativo() + select x; + observableCollection.Contas = new ObservableCollection( + from x in ativo + orderby x.get_Descricao() + select x); + TranferenciaViewModel tranferenciaViewModel = this; + Gestor.Model.Domain.Financeiro.Transferencia transferencium = new Gestor.Model.Domain.Financeiro.Transferencia(); + if (transferencia.get_Origem() != null) + { + bancosConta = bancosContas.First((BancosContas x) => x.get_Id() == transferencia.get_Origem().get_Id()); + } + else + { + bancosConta = null; + } + transferencium.set_Origem(bancosConta); + transferencium.set_Data(transferencia.get_Data()); + transferencium.set_Valor(transferencia.get_Valor()); + if (transferencia.get_Destino() != null) + { + bancosConta1 = bancosContas.First((BancosContas x) => x.get_Id() == transferencia.get_Destino().get_Id()); + } + else + { + bancosConta1 = null; + } + transferencium.set_Destino(bancosConta1); + tranferenciaViewModel.Transferencia = transferencium; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs new file mode 100644 index 0000000..5bb2e93 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs @@ -0,0 +1,6893 @@ +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Generic +{ + public class BaseApoliceViewModel : BaseSegurosViewModel + { + internal ApoliceServico Servico; + + internal Gestor.Application.Servicos.Seguros.PerfilServico PerfilServico; + + internal Gestor.Application.Servicos.Ferramentas.RamoServico RamoServico; + + internal Gestor.Application.Servicos.Ferramentas.SeguradoraServico SeguradoraServico; + + internal Gestor.Application.Servicos.Ferramentas.VendedorServico VendedorServico; + + internal Gestor.Application.Servicos.ParcelaServico ParcelaServico; + + internal Gestor.Application.Servicos.Ferramentas.ProdutoServico ProdutoServico; + + internal Gestor.Application.Servicos.Ferramentas.EstipulanteServico EstipulanteServico; + + internal Gestor.Application.Servicos.TarefaServico TarefaServico; + + private bool _invoke = true; + + public bool UpdatePremio; + + private bool _enableControle = true; + + private bool _apelido; + + private bool _controleAdm; + + private Documento _selectedDocumento; + + private Visibility _visibilityExcluirParcela = Visibility.Collapsed; + + private Visibility _visibilityReplicarFatura = Visibility.Collapsed; + + private Visibility _visibilityAlterarVencimento; + + private string _importado = "CLIQUE PARA VER INFORMAÇÕES SOBRE A INCLUSÃO"; + + private string _codigoDocumento; + + private DateTime? _emissaoDocumento; + + private DateTime? _transmissaoDocumento; + + private bool _editandoParcela; + + private bool _botoesParcelaEnabled = true; + + private List _vendedores; + + private List _todosVendedores; + + private ObservableCollection _pagamentos; + + private ObservableCollection _situacao = new ObservableCollection(new List() + { + 1, + 2, + 5 + }); + + private ObservableCollection _tipoEndosso = new ObservableCollection(new List() + { + 0, + 1, + 2, + 4, + 3 + }); + + private Parcela _selectedParcela; + + private bool _coCorretagem; + + private Visibility _baixarParcelaVisibility = Visibility.Collapsed; + + private ObservableCollection _parcelas; + + private decimal _gerada; + + private decimal _comissOriginal; + + private Visibility _comissOriginalVisibility = Visibility.Collapsed; + + private decimal _recebida; + + private decimal _pendente; + + private decimal _repasse; + + private Visibility _recusaVisibility; + + private string _excluirParcelaLabel = "EXCLUIR BAIXA"; + + private bool _isEnableSituacao; + + private List _produtos = Recursos.Produtos; + + private List _status = Recursos.Status; + + private List _ramos; + + private List _seguradorasAnteriores; + + private List _seguradoras; + + private Visibility _isRenovacaoVisibility = Visibility.Collapsed; + + private bool _isEndosso; + + private bool _enableAlterarSituacao; + + private string _assinada = "PROPOSTA ASSINADA"; + + private string _conferida = "APÓLICE CONFERIDA"; + + private string _transmissao = "TRANSMISSÃO DE PROPOSTA"; + + private string _emissao = "EMISSÃO DA APÓLICE"; + + private List _tiposVendedor; + + private List _estipulantes; + + public Documento CancelDocumento; + + private List _repasses; + + private List _repassesVendedores; + + private List _repassesVendedor; + + private VendedorParcela _selectedPagamento; + + private bool _baixarParcelas; + + private bool _isFatura; + + private bool _ultimaFatura; + + private bool _allowEditVendedor; + + private bool _alteracaoEnabled; + + private bool _allowEditEmissao; + + private bool _allowEditApolice; + + private bool _allowVigenciaFinal; + + private bool _novaApolice; + + private bool _renovar; + + public decimal Tolerancia; + + private bool _enableRepasse; + + private bool _bloquearObservacao; + + private string _editarParcelasLabel; + + private string _anotacoes; + + private int _quantidadeFaturas; + + private double _tamanhoGrid; + + private bool _inclusao; + + private bool _criandoParcelaEspecial; + + private bool _visibilityLogAntigo; + + public AcessoApolice Acesso + { + get; + set; + } + + public bool AllowEditApolice + { + get + { + return this._allowEditApolice; + } + set + { + this._allowEditApolice = value; + this.AllowVigenciaFinal = (value ? true : this.IsFatura); + base.OnPropertyChanged("AllowEditApolice"); + } + } + + public bool AllowEditEmissao + { + get + { + return this._allowEditEmissao; + } + set + { + this._allowEditEmissao = value; + base.OnPropertyChanged("AllowEditEmissao"); + } + } + + public bool AllowEditVendedor + { + get + { + return this._allowEditVendedor; + } + set + { + this._allowEditVendedor = this._incluirPermissEnabled & value; + base.OnPropertyChanged("AllowEditVendedor"); + } + } + + public bool AllowVigenciaFinal + { + get + { + return this._allowVigenciaFinal; + } + set + { + this._allowVigenciaFinal = value; + base.OnPropertyChanged("AllowVigenciaFinal"); + } + } + + public bool AlteracaoEnabled + { + get + { + return this._alteracaoEnabled; + } + set + { + this._alteracaoEnabled = value; + base.OnPropertyChanged("AlteracaoEnabled"); + } + } + + public new string Anotacoes + { + get + { + return this._anotacoes; + } + set + { + this._anotacoes = value; + base.OnPropertyChanged("Anotacoes"); + } + } + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public string Assinada + { + get + { + return this._assinada; + } + set + { + this._assinada = value; + base.OnPropertyChanged("Assinada"); + } + } + + public bool BaixarParcelas + { + get + { + return this._baixarParcelas; + } + set + { + this._baixarParcelas = value; + base.OnPropertyChanged("BaixarParcelas"); + } + } + + public Visibility BaixarParcelaVisibility + { + get + { + return this._baixarParcelaVisibility; + } + set + { + if (base.Restricao(15)) + { + return; + } + this._baixarParcelaVisibility = value; + base.OnPropertyChanged("BaixarParcelaVisibility"); + } + } + + public bool BloquearObservacao + { + get + { + return this._bloquearObservacao; + } + set + { + this._bloquearObservacao = value; + base.OnPropertyChanged("BloquearObservacao"); + } + } + + public bool BotoesParcelaEnabled + { + get + { + return this._botoesParcelaEnabled; + } + set + { + this._botoesParcelaEnabled = value; + base.OnPropertyChanged("BotoesParcelaEnabled"); + } + } + + public bool CoCorretagem + { + get + { + return this._coCorretagem; + } + set + { + if (this.SelectedPagamento != null) + { + this.SelectedPagamento.set_CoCorretagem(value); + } + this._coCorretagem = value; + base.OnPropertyChanged("CoCorretagem"); + } + } + + public string CodigoDocumento + { + get + { + return this._codigoDocumento; + } + set + { + this._codigoDocumento = value; + base.OnPropertyChanged("CodigoDocumento"); + } + } + + public decimal ComissOriginal + { + get + { + return this._comissOriginal; + } + set + { + this.ComissOriginalVisibility = (this.VerificaCoCorretagem() ? Visibility.Visible : Visibility.Collapsed); + this._comissOriginal = value; + base.OnPropertyChanged("ComissOriginal"); + } + } + + public Visibility ComissOriginalVisibility + { + get + { + return this._comissOriginalVisibility; + } + set + { + this._comissOriginalVisibility = value; + base.OnPropertyChanged("ComissOriginalVisibility"); + } + } + + public string Conferida + { + get + { + return this._conferida; + } + set + { + this._conferida = value; + base.OnPropertyChanged("Conferida"); + } + } + + public bool ControleAdm + { + get + { + return this._controleAdm; + } + set + { + this._controleAdm = value; + base.OnPropertyChanged("ControleAdm"); + } + } + + public bool CriandoParcelaEspecial + { + get + { + return this._criandoParcelaEspecial; + } + set + { + this._criandoParcelaEspecial = value; + } + } + + private Documento DocumentoRenovado + { + get; + set; + } + + internal Documento DocumentoSelecionado + { + get; + set; + } + + public bool EditandoParcela + { + get + { + return this._editandoParcela; + } + set + { + this._editandoParcela = value; + base.OnPropertyChanged("EditandoParcela"); + } + } + + public string EditarParcelasLabel + { + get + { + return this._editarParcelasLabel; + } + set + { + this._editarParcelasLabel = value; + base.OnPropertyChanged("EditarParcelasLabel"); + } + } + + public string Emissao + { + get + { + return this._emissao; + } + set + { + this._emissao = value; + base.OnPropertyChanged("Emissao"); + } + } + + public DateTime? EmissaoDocumento + { + get + { + return this._emissaoDocumento; + } + set + { + this._emissaoDocumento = value; + base.OnPropertyChanged("EmissaoDocumento"); + } + } + + public bool EnableAlterarSituacao + { + get + { + return this._enableAlterarSituacao; + } + set + { + this._enableAlterarSituacao = value; + base.OnPropertyChanged("EnableAlterarSituacao"); + } + } + + public bool EnableControle + { + get + { + return this._enableControle; + } + set + { + this._enableControle = value; + base.OnPropertyChanged("EnableControle"); + } + } + + public bool EnableRepasse + { + get + { + return this._enableRepasse; + } + set + { + this._enableRepasse = value; + base.OnPropertyChanged("EnableRepasse"); + } + } + + public List Estipulantes + { + get + { + return this._estipulantes; + } + set + { + this._estipulantes = value; + base.OnPropertyChanged("Estipulantes"); + } + } + + public string ExcluirParcelaLabel + { + get + { + return this._excluirParcelaLabel; + } + set + { + this._excluirParcelaLabel = value; + base.OnPropertyChanged("ExcluirParcelaLabel"); + } + } + + public decimal Gerada + { + get + { + return this._gerada; + } + set + { + this._gerada = value; + base.OnPropertyChanged("Gerada"); + } + } + + public string Importado + { + get + { + return this._importado; + } + set + { + this._importado = value; + base.OnPropertyChanged("Importado"); + } + } + + public Gestor.Model.Domain.Ferramentas.Imposto Imposto + { + get; + set; + } + + public bool Inclusao + { + get + { + return this._inclusao; + } + set + { + this._inclusao = value; + base.OnPropertyChanged("Inclusao"); + } + } + + public bool Invoke + { + get + { + return this._invoke; + } + set + { + this._invoke = value; + base.OnPropertyChanged("Invoke"); + } + } + + public bool IsEnableSituacao + { + get + { + return this._isEnableSituacao; + } + set + { + this._isEnableSituacao = value; + base.OnPropertyChanged("IsEnableSituacao"); + } + } + + public bool IsEndosso + { + get + { + return this._isEndosso; + } + set + { + this._isEndosso = value; + this.WorkOnSelectedTipo(value); + base.OnPropertyChanged("IsEndosso"); + } + } + + public bool IsFatura + { + get + { + return this._isFatura; + } + set + { + this._isFatura = value; + base.OnPropertyChanged("IsFatura"); + } + } + + public Visibility IsRenovacaoVisibility + { + get + { + return this._isRenovacaoVisibility; + } + set + { + this._isRenovacaoVisibility = value; + base.OnPropertyChanged("IsRenovacaoVisibility"); + } + } + + public bool Loaded + { + get; + set; + } + + public bool NovaApolice + { + get + { + return this._novaApolice; + } + set + { + this._novaApolice = value; + base.OnPropertyChanged("NovaApolice"); + } + } + + public ObservableCollection Pagamentos + { + get + { + return this._pagamentos; + } + set + { + this._pagamentos = value; + base.OnPropertyChanged("Pagamentos"); + } + } + + public ObservableCollection Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + if (value != null && value.Count == 0) + { + this.VisibilityExcluirParcela = Visibility.Collapsed; + this.VisibilityReplicarFatura = Visibility.Collapsed; + this.BaixarParcelaVisibility = Visibility.Collapsed; + this.VisibilityAlterarVencimento = Visibility.Collapsed; + } + base.OnPropertyChanged("Parcelas"); + } + } + + internal long ParcelaSelecionada + { + get; + set; + } + + public decimal Pendente + { + get + { + return this._pendente; + } + set + { + this._pendente = value; + base.OnPropertyChanged("Pendente"); + } + } + + public List Produtos + { + get + { + return this._produtos; + } + set + { + this._produtos = value; + base.OnPropertyChanged("Produtos"); + } + } + + public int QuantidadeFaturas + { + get + { + return this._quantidadeFaturas; + } + set + { + if (value < 0) + { + value = 0; + } + if (value > 12) + { + value = 12; + } + this._quantidadeFaturas = value; + base.OnPropertyChanged("QuantidadeFaturas"); + } + } + + public List Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public decimal Recebida + { + get + { + return this._recebida; + } + set + { + this._recebida = value; + base.OnPropertyChanged("Recebida"); + } + } + + public Visibility RecusaVisibility + { + get + { + return this._recusaVisibility; + } + set + { + this._recusaVisibility = (!base.Restricao(18) ? value : Visibility.Collapsed); + base.OnPropertyChanged("RecusaVisibility"); + } + } + + public bool Renovar + { + get + { + return this._renovar; + } + set + { + this._renovar = value; + base.OnPropertyChanged("Renovar"); + } + } + + public decimal Repasse + { + get + { + return this._repasse; + } + set + { + this._repasse = value; + base.OnPropertyChanged("Repasse"); + } + } + + public List Repasses + { + get + { + return this._repasses; + } + set + { + this._repasses = value; + base.OnPropertyChanged("Repasses"); + } + } + + public List RepassesVendedor + { + get + { + return this._repassesVendedor; + } + set + { + this._repassesVendedor = value; + this.EnableRepasse = (value == null ? false : value.Count > 0); + base.OnPropertyChanged("RepassesVendedor"); + } + } + + public List RepassesVendedores + { + get + { + return this._repassesVendedores; + } + set + { + this._repassesVendedores = value; + base.OnPropertyChanged("RepassesVendedores"); + } + } + + public List Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public List SeguradorasAnteriores + { + get + { + return this._seguradorasAnteriores; + } + set + { + this._seguradorasAnteriores = value; + base.OnPropertyChanged("SeguradorasAnteriores"); + } + } + + public Documento SelectedDocumento + { + get + { + return this._selectedDocumento; + } + set + { + DateTime networkTime; + long? nullable; + bool flag; + DateTime? emissao; + DateTime? remessa; + Visibility visibility; + long? nullable1; + string apolice; + if (value != null && value.get_Id() == 0) + { + this.VisibilityLogAntigo = false; + } + this._selectedDocumento = value; + this.Anotacoes = string.Empty; + base.EnableButtons = (value == null ? false : value.get_Id() > (long)0); + base.EnableIncluir = (value == null ? true : value.get_Id() > (long)0); + bool flag1 = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 13); + if (value == null || value.get_Id() <= (long)0) + { + flag = false; + } + else if (flag1) + { + flag = true; + } + else + { + flag = (string.IsNullOrWhiteSpace(value.get_Apolice()) || string.IsNullOrWhiteSpace(value.get_Proposta()) ? false : value.get_Emissao().HasValue); + } + base.EnableEndossar = flag; + base.EnableRenovar = (value == null || value.get_Id() <= (long)0 || !value.get_Vigencia2().HasValue ? false : !string.IsNullOrWhiteSpace(value.get_Apolice())); + if (value == null || value.get_Id() == 0) + { + this.ZeraComissao(); + } + this.CodigoDocumento = (this.SelectedDocumento == null || this.SelectedDocumento.get_Id() == 0 ? "" : string.Format("{0}", this.SelectedDocumento.get_Id())); + if (value != null && value.get_Status() == null && this.Status.First().get_Nome() == "SEM STATUS") + { + value.set_Status(this.Status.First()); + } + if (value == null || !value.get_Emissao().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + emissao = new DateTime?(networkTime.Date); + } + else + { + emissao = value.get_Emissao(); + } + this.EmissaoDocumento = emissao; + if (value == null || !value.get_Remessa().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + remessa = new DateTime?(networkTime.Date); + } + else + { + remessa = value.get_Remessa(); + } + this.TransmissaoDocumento = remessa; + if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 19)) + { + if (value != null) + { + apolice = value.get_Apolice(); + } + else + { + apolice = null; + } + if (string.IsNullOrWhiteSpace(apolice) || !value.get_Emissao().HasValue) + { + visibility = Visibility.Visible; + this.RecusaVisibility = visibility; + if (value != null) + { + nullable1 = new long?(value.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + base.VerificarEnables(nullable1); + base.OnPropertyChanged("SelectedDocumento"); + return; + } + visibility = Visibility.Collapsed; + this.RecusaVisibility = visibility; + if (value != null) + { + nullable1 = new long?(value.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + base.VerificarEnables(nullable1); + base.OnPropertyChanged("SelectedDocumento"); + return; + } + visibility = Visibility.Visible; + this.RecusaVisibility = visibility; + if (value != null) + { + nullable1 = new long?(value.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + base.VerificarEnables(nullable1); + base.OnPropertyChanged("SelectedDocumento"); + } + } + + public VendedorParcela SelectedPagamento + { + get + { + return this._selectedPagamento; + } + set + { + this._selectedPagamento = value; + base.OnPropertyChanged("SelectedPagamento"); + } + } + + public Parcela SelectedParcela + { + get + { + return this._selectedParcela; + } + set + { + this._selectedParcela = value; + this.WorkOnSelectedParcela(value); + base.OnPropertyChanged("SelectedParcela"); + } + } + + public ObservableCollection Situacao + { + get + { + return this._situacao; + } + set + { + this._situacao = value; + base.OnPropertyChanged("Situacao"); + } + } + + public List Status + { + get + { + return this._status; + } + set + { + if (value.All((Gestor.Model.Domain.Seguros.Status x) => x.get_Nome() != "SEM STATUS")) + { + Gestor.Model.Domain.Seguros.Status statu = new Gestor.Model.Domain.Seguros.Status(); + statu.set_Nome("SEM STATUS"); + statu.set_Id((long)0); + statu.set_Ativo(true); + value.Insert(0, statu); + } + this._status = value; + base.OnPropertyChanged("Status"); + } + } + + public double TamanhoGrid + { + get + { + return this._tamanhoGrid; + } + set + { + this._tamanhoGrid = value; + base.OnPropertyChanged("TamanhoGrid"); + } + } + + public ObservableCollection TipoEndossoList + { + get + { + return this._tipoEndosso; + } + set + { + this._tipoEndosso = value; + base.OnPropertyChanged("TipoEndossoList"); + } + } + + public List TiposVendedor + { + get + { + return this._tiposVendedor; + } + set + { + this._tiposVendedor = value; + base.OnPropertyChanged("TiposVendedor"); + } + } + + public List TodosVendedores + { + get + { + return this._todosVendedores; + } + set + { + this._todosVendedores = value; + base.OnPropertyChanged("TodosVendedores"); + } + } + + public string Transmissao + { + get + { + return this._transmissao; + } + set + { + this._transmissao = value; + base.OnPropertyChanged("Transmissao"); + } + } + + public DateTime? TransmissaoDocumento + { + get + { + return this._transmissaoDocumento; + } + set + { + this._transmissaoDocumento = value; + base.OnPropertyChanged("TransmissaoDocumento"); + } + } + + public bool UltimaFatura + { + get + { + return this._ultimaFatura; + } + set + { + this._ultimaFatura = value; + base.OnPropertyChanged("UltimaFatura"); + } + } + + public List Vendedores + { + get + { + return this._vendedores; + } + set + { + this._vendedores = value; + base.OnPropertyChanged("Vendedores"); + } + } + + public Visibility VisibilityAlterarVencimento + { + get + { + return this._visibilityAlterarVencimento; + } + set + { + this._visibilityAlterarVencimento = value; + base.OnPropertyChanged("VisibilityAlterarVencimento"); + } + } + + public Visibility VisibilityExcluirParcela + { + get + { + return this._visibilityExcluirParcela; + } + set + { + this._visibilityExcluirParcela = value; + base.OnPropertyChanged("VisibilityExcluirParcela"); + } + } + + public bool VisibilityLogAntigo + { + get + { + return this._visibilityLogAntigo; + } + set + { + this._visibilityLogAntigo = value; + base.OnPropertyChanged("VisibilityLogAntigo"); + } + } + + public Visibility VisibilityReplicarFatura + { + get + { + return this._visibilityReplicarFatura; + } + set + { + this._visibilityReplicarFatura = value; + base.OnPropertyChanged("VisibilityReplicarFatura"); + } + } + + public BaseApoliceViewModel() + { + this._invoke = true; + this._enableControle = true; + this._visibilityExcluirParcela = Visibility.Collapsed; + this._visibilityReplicarFatura = Visibility.Collapsed; + this._importado = "CLIQUE PARA VER INFORMAÇÕES SOBRE A INCLUSÃO"; + this._botoesParcelaEnabled = true; + this._situacao = new ObservableCollection(new List() + { + 1, + 2, + 5 + }); + this._tipoEndosso = new ObservableCollection(new List() + { + 0, + 1, + 2, + 4, + 3 + }); + this._baixarParcelaVisibility = Visibility.Collapsed; + this._comissOriginalVisibility = Visibility.Collapsed; + this._excluirParcelaLabel = "EXCLUIR BAIXA"; + this._produtos = Recursos.Produtos; + this._status = Recursos.Status; + this._isRenovacaoVisibility = Visibility.Collapsed; + this._assinada = "PROPOSTA ASSINADA"; + this._conferida = "APÓLICE CONFERIDA"; + this._transmissao = "TRANSMISSÃO DE PROPOSTA"; + this._emissao = "EMISSÃO DA APÓLICE"; + List tipoVendedor = Recursos.TipoVendedor; + if (tipoVendedor != null) + { + list = tipoVendedor.Where((TipoVendedor x) => { + if (!x.get_Ativo().HasValue) + { + return true; + } + return x.get_Ativo().Value; + }).ToList(); + } + else + { + list = null; + } + this._tiposVendedor = list; + this._allowEditVendedor = true; + this._alteracaoEnabled = true; + this._allowEditEmissao = true; + this._allowEditApolice = true; + this._allowVigenciaFinal = true; + this._bloquearObservacao = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 39); + this._editarParcelasLabel = "EDITAR PARCELAS"; + this._visibilityLogAntigo = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 22); + base(); + List list; + this.Servico = new ApoliceServico(); + this.VendedorServico = new Gestor.Application.Servicos.Ferramentas.VendedorServico(); + this.ParcelaServico = new Gestor.Application.Servicos.ParcelaServico(); + this.RamoServico = new Gestor.Application.Servicos.Ferramentas.RamoServico(); + this.SeguradoraServico = new Gestor.Application.Servicos.Ferramentas.SeguradoraServico(); + this.ProdutoServico = new Gestor.Application.Servicos.Ferramentas.ProdutoServico(); + this.EstipulanteServico = new Gestor.Application.Servicos.Ferramentas.EstipulanteServico(); + this.TarefaServico = new Gestor.Application.Servicos.TarefaServico(); + this.PerfilServico = new Gestor.Application.Servicos.Seguros.PerfilServico(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + this.ControleAdm = (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 33) ? true : Recursos.Usuario.get_Administrador()); + } + + public Documento AbrirDetalhes() + { + Documento selectedDocumento = this.SelectedDocumento; + selectedDocumento.set_Parcelas(this.Parcelas); + selectedDocumento.set_Pagamentos(this.Repasses); + return selectedDocumento; + } + + public Parcela AbrirDetalhesParcela() + { + Parcela selectedParcela = this.SelectedParcela; + selectedParcela.set_Vendedores(this.Pagamentos); + return selectedParcela; + } + + public async void AbrirLogAntigo() + { + base.Loading(true); + string str = await this.Servico.BuscarLogAntigo(this.SelectedDocumento.get_Id()); + base.Loading(false); + if (!string.IsNullOrEmpty(str)) + { + base.ShowDrawer(new LogSistemaAntigo(this.SelectedDocumento.get_Id(), str), 0, false); + } + else + { + await base.ShowMessage("NÃO HÁ LOG PARA ESSE DOCUMENTO", "OK", "", false); + } + } + + public async void AbrirLogAntigoParcela() + { + base.Loading(true); + string str = ""; + foreach (Parcela parcela in await this.ParcelaServico.BuscarParcelas(this.SelectedDocumento.get_Id())) + { + string str1 = str; + string str2 = await this.ParcelaServico.BuscarLogAntigo(parcela.get_Id()); + str = string.Concat(str1, str2); + str1 = null; + } + base.Loading(false); + if (!string.IsNullOrEmpty(str)) + { + base.ShowDrawer(new LogSistemaAntigo(this.SelectedDocumento.get_Id(), str), 0, false); + } + else + { + await base.ShowMessage("NÃO HÁ LOG PARA PARCELAS", "OK", "", false); + } + str = null; + } + + public async Task AdicionarParcelaEspecial() + { + long num; + DateTime? nullable; + DateTime valueOrDefault; + string str; + long num1; + DateTime? nullable1; + DateTime? nullable2; + DateTime? nullable3; + DateTime? nullable4; + DateTime? nullable5; + DateTime? nullable6; + string str1; + string str2; + string str3; + if (this.SelectedParcela != null && !this.CriandoParcelaEspecial) + { + this.CriandoParcelaEspecial = true; + if (this.SelectedPagamento == null || this.SelectedPagamento.get_Vendedor().get_Corretora()) + { + this.SelectedPagamento = this.PropriaCorretora(); + } + else + { + List> keyValuePairs = await this.AdicionarVendedorParcelaEspecial(); + if (keyValuePairs.Count > 0) + { + this._criandoParcelaEspecial = false; + await base.ShowMessage(keyValuePairs, " PROCESSO INTERROMPIDO, PARCELA/FATURA SEM VENDENDEDOR", "OK", ""); + return; + } + } + this.SelectedParcela.set_Documento(this.SelectedDocumento); + DateTime vencimento = this.SelectedParcela.get_Vencimento(); + DateTime? dataRecebimento = this.SelectedParcela.get_DataRecebimento(); + DateTime? dataCredito = this.SelectedParcela.get_DataCredito(); + DateTime? dataControle = this.SelectedParcela.get_DataControle(); + int numeroParcela = this.SelectedParcela.get_NumeroParcela(); + DateTime? vigenciaIncial = this.SelectedParcela.get_VigenciaIncial(); + DateTime? vigenciaFinal = this.SelectedParcela.get_VigenciaFinal(); + DateTime? emissao = this.SelectedParcela.get_Emissao(); + str = (string.IsNullOrWhiteSpace(Gestor.Common.Validation.ValidationHelper.OnlyNumber(this.SelectedParcela.get_Fatura())) ? "1" : Gestor.Common.Validation.ValidationHelper.OnlyNumber(this.SelectedParcela.get_Fatura())); + num1 = (long.TryParse(str, out num) ? num : (long)1); + long num2 = num1; + if (this.QuantidadeFaturas == 0 || !this.IsFatura) + { + this.QuantidadeFaturas = 1; + } + if (this.QuantidadeFaturas <= 12) + { + for (int i = 0; i < this.QuantidadeFaturas; i++) + { + this.SelectedParcela.set_Vencimento(vencimento.AddMonths(i)); + Parcela selectedParcela = this.SelectedParcela; + ref Nullable nullablePointer = ref vigenciaIncial; + if (nullablePointer.HasValue) + { + valueOrDefault = nullablePointer.GetValueOrDefault(); + nullable1 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable1 = nullable; + } + selectedParcela.set_VigenciaIncial(nullable1); + Parcela parcela = this.SelectedParcela; + ref Nullable nullablePointer1 = ref vigenciaFinal; + if (nullablePointer1.HasValue) + { + valueOrDefault = nullablePointer1.GetValueOrDefault(); + nullable2 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable2 = nullable; + } + parcela.set_VigenciaFinal(nullable2); + Parcela selectedParcela1 = this.SelectedParcela; + ref Nullable nullablePointer2 = ref emissao; + if (nullablePointer2.HasValue) + { + valueOrDefault = nullablePointer2.GetValueOrDefault(); + nullable3 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable3 = nullable; + } + selectedParcela1.set_Emissao(nullable3); + Parcela parcela1 = this.SelectedParcela; + ref Nullable nullablePointer3 = ref dataRecebimento; + if (nullablePointer3.HasValue) + { + valueOrDefault = nullablePointer3.GetValueOrDefault(); + nullable4 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable4 = nullable; + } + parcela1.set_DataRecebimento(nullable4); + Parcela selectedParcela2 = this.SelectedParcela; + ref Nullable nullablePointer4 = ref dataCredito; + if (nullablePointer4.HasValue) + { + valueOrDefault = nullablePointer4.GetValueOrDefault(); + nullable5 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable5 = nullable; + } + selectedParcela2.set_DataCredito(nullable5); + Parcela parcela2 = this.SelectedParcela; + ref Nullable nullablePointer5 = ref dataControle; + if (nullablePointer5.HasValue) + { + valueOrDefault = nullablePointer5.GetValueOrDefault(); + nullable6 = new DateTime?(valueOrDefault.AddMonths(i)); + } + else + { + nullable = null; + nullable6 = nullable; + } + parcela2.set_DataControle(nullable6); + this.SelectedParcela.set_NumeroParcela(numeroParcela + i); + if (i > 0) + { + num2 += (long)1; + this.SelectedParcela.set_Fatura(string.Format("{0}", num2)); + nullable = null; + this.SelectedParcela.set_DataQuitacao(nullable); + } + List repasses = this.Repasses; + if (repasses != null) + { + repasses.ForEach((VendedorParcela x) => { + if (x.get_Repasse() == null) + { + return; + } + if (x.get_Repasse().get_Forma().GetValueOrDefault() == 1) + { + x.set_DataPrePagamento(this.SelectedParcela.get_DataRecebimento()); + } + x.set_Parcela(this.SelectedParcela); + BaseRepasse? @base = x.get_Repasse().get_Base(); + if (@base.HasValue) + { + switch (@base.GetValueOrDefault()) + { + case 1: + { + x.set_DataPrePagamento((this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? x.get_Parcela().get_VigenciaIncial() : new DateTime?(this.SelectedDocumento.get_Vigencia1()))); + return; + } + case 2: + { + x.set_DataPrePagamento(x.get_Parcela().get_DataCriacao()); + return; + } + case 3: + { + x.set_DataPrePagamento(new DateTime?((x.get_Parcela().get_Vencimento() == DateTime.MinValue ? this.SelectedDocumento.get_Vigencia1() : x.get_Parcela().get_Vencimento()))); + return; + } + case 4: + { + x.set_DataPrePagamento((this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? x.get_Parcela().get_Emissao() : this.SelectedDocumento.get_Emissao())); + return; + } + case 5: + { + x.set_DataPrePagamento((this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? x.get_Parcela().get_Emissao() : this.SelectedDocumento.get_Remessa())); + break; + } + default: + { + return; + } + } + } + }); + } + else + { + } + if (this.Repasses == null) + { + this.Repasses = new List() + { + this.PropriaCorretora() + }; + } + List vendedorParcelas = this.Repasses; + if (vendedorParcelas.All((VendedorParcela x) => x.get_TipoVendedor().get_Id() != (long)1)) + { + this.Repasses.Add(this.PropriaCorretora()); + } + Parcela parcela3 = await this.ParcelaServico.Save(this.SelectedParcela, this.Parcelas.ToList(), this.Repasses, true); + if (i == this.QuantidadeFaturas - 1) + { + this.SelectedParcela = parcela3; + } + } + this.QuantidadeFaturas = 0; + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("NA PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("NA PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("NO ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str1 = string.Concat("NA APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str4 = str1; + str2 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? string.Concat("PARCELA ESPECIAL ADICIONADA, ", str4) : string.Concat("FATURA ", this.SelectedParcela.get_Fatura(), " ADICIONADA, ", str4)); + string str5 = str2; + base.RegistrarAcao(str5, this.SelectedParcela.get_Id(), new TipoTela?(5), this.GerarObs(this.SelectedDocumento)); + if (this.ParcelaServico.Sucesso) + { + BaseApoliceViewModel baseApoliceViewModel = this; + str3 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? "PARCELA ESPECIAL ADICIONADA COM SUCESSO" : "FATURA ADICIONADA COM SUCESSO"); + baseApoliceViewModel.ToggleSnackBar(str3, true); + } + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + BaseApoliceViewModel baseApoliceViewModel1 = this; + Parcela selectedParcela3 = this.SelectedParcela; + if (selectedParcela3 == null) + { + selectedParcela3 = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel1.SelecionaParcela(selectedParcela3); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + this.BaixarParcelas = false; + this.CriandoParcelaEspecial = false; + } + else + { + this.CriandoParcelaEspecial = false; + await base.ShowMessage("NÃO É POSSIVEL REPLICAR MAIS QUE 12 VEZES A MESMA FATURA. PROCESSO CANCELADO", "OK", "", false); + } + } + } + + public async Task>> AdicionarVendedor() + { + // + // Current member / type: System.Threading.Tasks.Task`1>> Gestor.Application.ViewModels.Generic.BaseApoliceViewModel::AdicionarVendedor() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task>> AdicionarVendedor() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // 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.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 60 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 31 + // 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 + + } + + public async Task>> AdicionarVendedorParcelaEspecial() + { + List> keyValuePairs; + List list; + bool valueOrDefault; + bool flag; + bool flag1; + string str1; + DateTime? nullable; + DateTime dateTime; + DateTime? nullable1; + DateTime? nullable2; + bool flag2; + decimal num; + List vinculoRepasses; + List vendedorParcelas; + List> keyValuePairs1 = new List>(); + if (this.SelectedPagamento == null) + { + keyValuePairs1.Add(new KeyValuePair("SelectedPagamento|PAGAMENTO", "ERRO AO INCLUIR VENDEDOR.")); + keyValuePairs = keyValuePairs1; + } + else if (this.SelectedPagamento.get_Repasse() != null) + { + this.SelectedPagamento.set_Parcela(this.SelectedParcela); + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 2 || this.SelectedPagamento.get_Repasse().get_Forma().GetValueOrDefault() != 3) + { + Gestor.Model.Domain.Seguros.Repasse repasse = this.SelectedPagamento.get_Repasse(); + if (repasse != null) + { + List vinculo = repasse.get_Vinculo(); + if (vinculo != null) + { + list = ( + from x in vinculo + where x.get_TipoVendedor().get_Id() == this.SelectedPagamento.get_TipoVendedor().get_Id() + select x).ToList(); + } + else + { + list = null; + } + } + else + { + list = null; + } + vinculoRepasses = list; + vendedorParcelas = new List() + { + this.SelectedPagamento + }; + if (this.SelectedDocumento.get_NegocioCorretora().HasValue) + { + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + valueOrDefault = negocioCorretora.GetValueOrDefault() == 1; + } + else if (this.SelectedDocumento.get_Situacao() != 2 || !this.SelectedDocumento.get_Negocio().HasValue) + { + valueOrDefault = false; + } + else + { + Negocio? negocio = this.SelectedDocumento.get_Negocio(); + valueOrDefault = negocio.GetValueOrDefault() == 1; + } + bool flag3 = valueOrDefault; + flag = (vinculoRepasses == null ? false : vinculoRepasses.Count > 0); + bool flag4 = flag; + if (flag4) + { + flag4 = await base.ShowMessage("DESEJA ADICIONAR OS REPASSES VINCULADOS?", "SIM", "NÃO", false); + } + if (flag4) + { + foreach (VinculoRepasse vinculoRepasse in vinculoRepasses) + { + Gestor.Model.Domain.Seguros.Repasse repasseVinculo = vinculoRepasse.get_RepasseVinculo(); + Parcela parcela = this.SelectedPagamento.get_Parcela(); + flag2 = (this.SelectedPagamento.get_Parcela() == null ? true : this.SelectedPagamento.get_Parcela().get_SubTipo() == 1); + decimal num1 = Funcoes.CalculaRepasse(repasseVinculo, parcela, flag2); + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_TipoVendedor(vinculoRepasse.get_TipoVendedorVinculo()); + vendedorParcela.set_Vendedor(vinculoRepasse.get_RepasseVinculo().get_Vendedor()); + vendedorParcela.set_Repasse(vinculoRepasse.get_RepasseVinculo()); + vendedorParcela.set_Documento(this.SelectedPagamento.get_Documento()); + vendedorParcela.set_Parcela(this.SelectedPagamento.get_Parcela()); + num = (flag3 ? vinculoRepasse.get_RepasseVinculo().get_ValorRenovacao() : vinculoRepasse.get_RepasseVinculo().get_ValorNovo()); + vendedorParcela.set_PorcentagemRepasse(new decimal?(num)); + vendedorParcela.set_ValorRepasse(new decimal?(num1)); + vendedorParcela.set_ValorTotal(new decimal?(num1)); + vendedorParcelas.Add(vendedorParcela); + } + } + foreach (VendedorParcela vendedorParcela1 in vendedorParcelas) + { + VendedorParcela vendedorParcela2 = vendedorParcela1; + keyValuePairs1 = vendedorParcela2.Validate(); + keyValuePairs1.AddRange(this.ValidateEspecial(vendedorParcela2)); + if (keyValuePairs1.Count <= 0) + { + if (vendedorParcela2.get_Repasse() != null) + { + BaseRepasse? @base = vendedorParcela2.get_Repasse().get_Base(); + if (@base.HasValue) + { + switch (@base.GetValueOrDefault()) + { + case 1: + { + VendedorParcela vendedorParcela3 = vendedorParcela2; + nullable = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? vendedorParcela2.get_Parcela().get_VigenciaIncial() : new DateTime?(this.SelectedDocumento.get_Vigencia1())); + vendedorParcela3.set_DataPrePagamento(nullable); + break; + } + case 2: + { + vendedorParcela2.set_DataPrePagamento(vendedorParcela2.get_Parcela().get_DataCriacao()); + break; + } + case 3: + { + VendedorParcela vendedorParcela4 = vendedorParcela2; + dateTime = (vendedorParcela2.get_Parcela().get_Vencimento() == DateTime.MinValue ? this.SelectedDocumento.get_Vigencia1() : vendedorParcela2.get_Parcela().get_Vencimento()); + vendedorParcela4.set_DataPrePagamento(new DateTime?(dateTime)); + break; + } + case 4: + { + VendedorParcela vendedorParcela5 = vendedorParcela2; + nullable1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? vendedorParcela2.get_Parcela().get_Emissao() : this.SelectedDocumento.get_Emissao()); + vendedorParcela5.set_DataPrePagamento(nullable1); + break; + } + case 5: + { + VendedorParcela vendedorParcela6 = vendedorParcela2; + nullable2 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? vendedorParcela2.get_Parcela().get_Emissao() : this.SelectedDocumento.get_Remessa()); + vendedorParcela6.set_DataPrePagamento(nullable2); + break; + } + } + } + } + if (this.Pagamentos == null) + { + this.Pagamentos = new ObservableCollection(); + } + VendedorParcela vendedorParcela7 = this.Repasses.FirstOrDefault((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != this.SelectedParcela.get_Id() || x.get_TipoVendedor().get_Id() != (long)1) + { + return false; + } + return x.get_Vendedor().get_Corretora(); + }); + flag1 = (vendedorParcela2.get_TipoVendedor().get_Id() != (long)1 ? false : vendedorParcela7 != null); + bool flag5 = flag1; + if (this.SelectedParcela.get_Id() != 0) + { + if (vendedorParcela2.get_Repasse().get_Forma().GetValueOrDefault() == 1) + { + vendedorParcela2.set_DataPrePagamento(this.SelectedParcela.get_DataRecebimento()); + } + List vendedorParcelas1 = new List() + { + vendedorParcela2 + }; + vendedorParcelas1 = await this.Servico.IncluirVendedores(vendedorParcelas1); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("NA PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("NA PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("NO ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str1 = string.Concat("NA APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str2 = str1; + if (vendedorParcelas1 != null) + { + vendedorParcelas1.ForEach((VendedorParcela x) => { + string str = string.Concat("VENDEDOR ", x.get_Vendedor().get_Nome(), " ADICIONADO A PARCELA ESPECIAL, ", str2); + base.RegistrarAcao(str, x.get_Id(), new TipoTela?(37), string.Format("{0}{1}VENDEDOR: {2}{3}COMISSÃO TOTAL: {4:C2}", new object[] { this.GerarObs(this.SelectedDocumento), Environment.NewLine, x.get_Vendedor().get_Nome(), Environment.NewLine, x.get_ValorTotal() })); + }); + } + this.Repasses.AddRange(vendedorParcelas1); + if (flag5) + { + await this.ExcluirVendedor(vendedorParcela7, false); + } + this.Repasses = await this.VendedorServico.BuscaRepasse(this.SelectedDocumento.get_Id()); + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela == null) + { + selectedParcela = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela); + this.SelectedPagamento = null; + vendedorParcela7 = null; + } + else + { + this.Repasses.Add(vendedorParcela2); + this.Pagamentos.Add(vendedorParcela2); + this.SelectedPagamento = null; + if (!this.IsFatura && this.SelectedParcela.get_SubTipo() == 1 || !flag5) + { + continue; + } + await this.ExcluirVendedor(vendedorParcela7, false); + } + } + else + { + if (this.SelectedPagamento == null) + { + this.SelectedPagamento = vendedorParcela2; + } + keyValuePairs = keyValuePairs1; + vinculoRepasses = null; + vendedorParcelas = null; + return keyValuePairs; + } + } + base.ToggleSnackBar("VENDEDOR ADICIONADO COM SUCESSO", true); + keyValuePairs = null; + } + else + { + base.ShowMessage("NÃO É POSSÍVEL ADICIONAR UM VENDEDOR COM A FORMA DE PAGAMENTO À PRAZO EM DOCUMENTOS DO TIPO FATURA", "OK", "", false); + keyValuePairs = null; + } + } + else + { + keyValuePairs1.Add(new KeyValuePair("Repasse|REPASSE", "ERRO AO INCLUIR VENDEDOR.")); + keyValuePairs = keyValuePairs1; + } + vinculoRepasses = null; + vendedorParcelas = null; + return keyValuePairs; + } + + public async void AjustaParcelasCoCorretagem() + { + int num = 0; + try + { + ObservableCollection parcelas = this.Parcelas; + foreach (Parcela parcela in parcelas) + { + if (parcela.get_NumeroParcela() != 999) + { + parcela.set_Comissao(this.SelectedDocumento.get_Comissao()); + } + else + { + return; + } + } + this.Parcelas = new ObservableCollection(await this.ParcelaServico.SaveRange(parcelas.ToList())); + await this.CarregarParcelas(this.SelectedDocumento); + } + catch + { + num = 1; + } + if (num == 1) + { + await base.ShowMessage("NÃO FOI POSSÍVEL SALVAR AS PARCELAS", "OK", "", false); + } + } + + public async Task AjusteComissãoCoCorretagem(bool removido = false) + { + decimal? nullable; + decimal valorNovo; + decimal? comissaoTotal; + int num = 0; + try + { + if (!removido) + { + VendedorParcela selectedPagamento = this.SelectedPagamento; + if (selectedPagamento != null) + { + valorNovo = selectedPagamento.get_Repasse().get_ValorNovo(); + } + else + { + valorNovo = decimal.Zero; + } + decimal num1 = valorNovo; + decimal comissao = this.SelectedDocumento.get_Comissao(); + this.SelectedDocumento.set_ComissaoTotal(new decimal?(comissao)); + this.SelectedDocumento.set_Comissao(Math.Round(comissao - (comissao * num1 * new decimal(1, 0, 0, false, 2)), 2)); + this.SelectedDocumento = await this.Servico.Save(this.SelectedDocumento, false, false); + this.AjustaParcelasCoCorretagem(); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + } + else + { + Documento selectedDocumento = this.SelectedDocumento; + Documento documento = this.SelectedDocumento; + if (documento != null) + { + comissaoTotal = documento.get_ComissaoTotal(); + } + else + { + nullable = null; + comissaoTotal = nullable; + } + nullable = comissaoTotal; + selectedDocumento.set_Comissao(nullable.GetValueOrDefault()); + this.SelectedDocumento = await this.Servico.Save(this.SelectedDocumento, false, false); + this.AjustaParcelasCoCorretagem(); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + return; + } + } + catch + { + num = 1; + } + if (num == 1) + { + await base.ShowMessage("NÃO FOI POSSÍVEL ALTERAR A COMISSÃO DA CO-CORRETAGEM", "OK", "", false); + } + } + + public async Task AlterarVencimento() + { + // + // Current member / type: System.Threading.Tasks.Task Gestor.Application.ViewModels.Generic.BaseApoliceViewModel::AlterarVencimento() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task AlterarVencimento() + // + // An item with the same key has already been added. Key: Label0 + // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) + // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection>.Add(KeyValuePair`2 keyValuePair) + // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 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 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 30 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.VisitIfStatement(IfStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 409 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(IEnumerable collection) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 384 + // 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.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.VisitIfStatement(IfStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 408 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(IEnumerable collection) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 384 + // 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 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 + + } + + private void AtualizaValores(bool renovacao) + { + this.Repasses.ForEach((VendedorParcela x) => { + decimal? nullable; + decimal? comissaoTotal; + if (x.get_Repasse() == null) + { + return; + } + if (x.get_Repasse().get_Tipo().GetValueOrDefault() == 1) + { + return; + } + Parcela parcela = x.get_Parcela(); + if (parcela.get_SubTipo() != 1) + { + return; + } + parcela.set_Documento(this.SelectedDocumento); + decimal numeroParcelas = Funcoes.CalculaRepasse(x.get_Repasse(), parcela, true); + decimal valorNovo = (renovacao ? x.get_Repasse().get_ValorRenovacao() : x.get_Repasse().get_ValorNovo()); + if (x.get_CoCorretagem()) + { + valorNovo = x.get_Repasse().get_ValorNovo(); + } + if (x.get_Repasse().get_Forma().GetValueOrDefault() == 3) + { + numeroParcelas /= this.SelectedDocumento.get_NumeroParcelas(); + } + if (x.get_CoCorretagem()) + { + decimal comissao = this.SelectedDocumento.get_Comissao(); + Documento selectedDocumento = this.SelectedDocumento; + if (selectedDocumento != null) + { + comissaoTotal = selectedDocumento.get_ComissaoTotal(); + } + else + { + nullable = null; + comissaoTotal = nullable; + } + nullable = comissaoTotal; + decimal valueOrDefault = nullable.GetValueOrDefault(); + numeroParcelas = this.SelectedDocumento.get_PremioLiquido() * ((valueOrDefault - comissao) / new decimal(100)); + } + x.set_PorcentagemRepasse(new decimal?(valorNovo)); + x.set_ValorRepasse(new decimal?(numeroParcelas)); + x.set_ValorTotal(new decimal?(numeroParcelas)); + }); + decimal num = (this.Parcelas.Count((Parcela x) => x.get_SubTipo() == 1) > 0 ? this.SelectedDocumento.get_PremioTotal() / this.Parcelas.Count((Parcela x) => x.get_SubTipo() == 1) : decimal.Zero); + ( + from x in this.Parcelas + where x.get_SubTipo() == 1 + select x).ToList().ForEach((Parcela x) => { + x.set_Valor(num); + x.set_Comissao(this.SelectedDocumento.get_Comissao()); + x.set_Vendedores(new ObservableCollection( + from r in this.Repasses + where r.get_Parcela().get_Id() == x.get_Id() + select r)); + }); + } + + internal async Task BaixarComissao() + { + decimal? nullable; + bool valueOrDefault; + decimal? tolerancia; + decimal num; + bool tipo; + bool flag; + string endosso; + string propostaEndosso; + string str; + bool valueOrDefault1; + string str1; + bool flag1; + long? nullable1; + if (this.SelectedParcela != null) + { + base.Loading(true); + if (!this.IsFatura) + { + valueOrDefault = false; + } + else + { + ObservableCollection parcelas = this.Parcelas; + IOrderedEnumerable numeroParcela = + from x in parcelas + orderby x.get_NumeroParcela() + select x; + Parcela parcela = numeroParcela.LastOrDefault((Parcela x) => x.get_SubTipo() == 1); + if (parcela != null) + { + nullable1 = new long?(parcela.get_Id()); + } + else + { + nullable1 = null; + } + long? nullable2 = nullable1; + long id = this.SelectedParcela.get_Id(); + valueOrDefault = nullable2.GetValueOrDefault() == id & nullable2.HasValue; + } + bool flag2 = valueOrDefault; + this.SelectedParcela.set_Documento(this.SelectedDocumento); + Parcela selectedParcela = this.SelectedParcela; + List list = this.Parcelas.ToList(); + List repasses = this.Repasses; + Documento selectedDocumento = this.SelectedDocumento; + if (selectedDocumento != null) + { + Controle controle = selectedDocumento.get_Controle(); + if (controle != null) + { + Seguradora seguradora = controle.get_Seguradora(); + if (seguradora != null) + { + tolerancia = seguradora.get_Tolerancia(); + } + else + { + nullable = null; + tolerancia = nullable; + } + } + else + { + nullable = null; + tolerancia = nullable; + } + } + else + { + nullable = null; + tolerancia = nullable; + } + decimal? nullable3 = tolerancia; + num = (nullable3.HasValue ? nullable3.GetValueOrDefault() : this.Tolerancia); + this.SelectedParcela = await Funcoes.BaixarComissao(selectedParcela, list, repasses, num, false); + Documento documento = this.SelectedDocumento; + if (documento != null) + { + tipo = documento.get_Tipo() == 0; + } + else + { + tipo = false; + } + if (!tipo || !string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + Documento selectedDocumento1 = this.SelectedDocumento; + if (selectedDocumento1 != null) + { + flag = selectedDocumento1.get_Tipo() == 0; + } + else + { + flag = false; + } + if (!flag || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + Documento documento1 = this.SelectedDocumento; + if (documento1 != null) + { + endosso = documento1.get_Endosso(); + } + else + { + endosso = null; + } + if (string.IsNullOrEmpty(endosso)) + { + Documento selectedDocumento2 = this.SelectedDocumento; + if (selectedDocumento2 != null) + { + propostaEndosso = selectedDocumento2.get_PropostaEndosso(); + } + else + { + propostaEndosso = null; + } + str = string.Concat("PROPOSTA DE ENDOSSO ", propostaEndosso); + } + else + { + str = string.Concat("ENDOSSO ", this.SelectedDocumento.get_Endosso()); + } + } + else + { + str = string.Concat("APÓLICE ", this.SelectedDocumento.get_Apolice()); + } + } + else + { + str = string.Concat("PROPOSTA ", this.SelectedDocumento.get_Proposta()); + } + string str2 = str; + Documento documento2 = this.SelectedDocumento; + if (documento2 != null) + { + valueOrDefault1 = documento2.get_TipoRecebimento().GetValueOrDefault() == 1; + } + else + { + valueOrDefault1 = false; + } + str1 = (valueOrDefault1 ? string.Format("PARCELA {0} BAIXADA, {1}", this.SelectedParcela.get_NumeroParcela(), str2) : string.Concat("FATURA ", this.SelectedParcela.get_Fatura(), " BAIXADA, ", str2)); + string str3 = str1; + base.RegistrarAcao(str3, this.SelectedParcela.get_Id(), new TipoTela?(5), this.GerarObs(this.SelectedDocumento)); + if (this.SelectedDocumento != null) + { + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + } + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela1 = this.SelectedParcela; + if (selectedParcela1 == null) + { + selectedParcela1 = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela1); + this.BaixarParcelas = false; + BaseApoliceViewModel baseApoliceViewModel1 = this; + ObservableCollection observableCollection = this.Parcelas; + IEnumerable subTipo = + from x in observableCollection + where x.get_SubTipo() == 1 + select x; + if (!subTipo.All((Parcela x) => !x.get_DataRecebimento().HasValue)) + { + flag1 = false; + } + else + { + List vendedorParcelas = this.Repasses; + IEnumerable subTipo1 = + from x in vendedorParcelas + where x.get_Parcela().get_SubTipo() == 1 + select x; + flag1 = subTipo1.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + baseApoliceViewModel1.AllowEditApolice = flag1; + base.Loading(false); + bool flag3 = flag2; + if (flag3) + { + flag3 = await base.ShowMessage("DESEJA INCLUIR A PRÓXIMA FATURA?", "SIM", "NÃO", false); + } + if (flag3) + { + this.UltimaFatura = true; + } + base.ToggleSnackBar("PARCELA BAIXADA COM SUCESSO", true); + } + } + + public async Task BuscarVendedores(bool verificarRamo = true) + { + List vendedors1; + List vendedores; + bool ramo; + bool id; + Func func = null; + if (this.RepassesVendedores == null) + { + this.RepassesVendedores = await this.VendedorServico.BuscaRepasses(); + BaseApoliceViewModel list = this; + List repassesVendedores = this.RepassesVendedores; + IEnumerable> groupings = + from x in repassesVendedores + group x by x.get_Vendedor().get_Id(); + IEnumerable vendedor = + from x in groupings + select x.First().get_Vendedor(); + list.TodosVendedores = ( + from x in vendedor + orderby x.get_Nome() + select x).ToList(); + } + Documento selectedDocumento = this.SelectedDocumento; + if (selectedDocumento != null) + { + vendedores = selectedDocumento.get_Vendedores(); + } + else + { + vendedores = null; + } + List vendedors2 = vendedores; + if (vendedors2 == null) + { + Documento documento = this.SelectedDocumento; + if (documento != null) + { + id = documento.get_Id() > (long)0; + } + else + { + id = false; + } + if (!id) + { + vendedors1 = new List(); + } + else + { + vendedors1 = await this.ParcelaServico.BuscarVendedores(this.SelectedDocumento.get_Id()); + } + vendedors2 = vendedors1; + } + List vendedors3 = vendedors2; + this.Vendedores = this.TodosVendedores.Where((Vendedor x) => { + if (x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + List vendedors = vendedors3; + Func u003cu003e9_1475 = BaseApoliceViewModel.u003cu003ec.u003cu003e9__147_5; + if (u003cu003e9_1475 == null) + { + u003cu003e9_1475 = (Vendedor y) => y.get_Id(); + BaseApoliceViewModel.u003cu003ec.u003cu003e9__147_5 = u003cu003e9_1475; + } + if (!vendedors.Select(u003cu003e9_1475).Contains(x.get_Id())) + { + return false; + } + } + if (x.get_Ativo()) + { + return !x.get_Corretora(); + } + return false; + }).ToList(); + List vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + if (vendedorUsuarios.Count > 0) + { + vendedorUsuarios.ForEach((VendedorUsuario x) => vendedors3.Add(x.get_Vendedor())); + this.Vendedores = vendedors3; + } + if (verificarRamo) + { + Documento selectedDocumento1 = this.SelectedDocumento; + if (selectedDocumento1 != null) + { + Controle controle = selectedDocumento1.get_Controle(); + if (controle != null) + { + ramo = controle.get_Ramo(); + } + else + { + ramo = false; + } + } + else + { + ramo = false; + } + if (ramo) + { + for (int i = this.Vendedores.Count - 1; i >= 0; i--) + { + List repasses = this.GetRepasses(this.Vendedores[i]); + List repasses1 = repasses; + if (!repasses1.Any((Gestor.Model.Domain.Seguros.Repasse x) => x.get_Ramo() == null)) + { + List repasses2 = repasses; + Func func1 = func; + if (func1 == null) + { + Func id1 = (Gestor.Model.Domain.Seguros.Repasse x) => x.get_Ramo().get_Id() != this.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + Func func2 = id1; + func = id1; + func1 = func2; + } + if (repasses2.All(func1)) + { + this.Vendedores.Remove(this.Vendedores[i]); + } + } + } + } + } + } + + private void CalculaComissao(Documento documento, ObservableCollection parcelas) + { + decimal? nullable; + decimal? comissaoTotal; + decimal num = (documento.get_AdicionalComiss() ? documento.get_PremioLiquido() + documento.get_PremioAdicional() : documento.get_PremioLiquido()); + decimal comissao = documento.get_Comissao() * new decimal(1, 0, 0, false, 2); + this.Gerada = num * comissao; + this.Recebida = (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 32) ? parcelas.Where((Parcela x) => { + if (x.get_SubTipo() == 1) + { + return true; + } + return x.get_SubTipo() == 6; + }).Sum((Parcela x) => x.get_ValorComissao()) : ( + from x in parcelas + where x.get_SubTipo() == 1 + select x).Sum((Parcela x) => x.get_ValorComissao())); + this.Pendente = this.Gerada - this.Recebida; + this.Pendente = (this.Pendente < new decimal(1, 0, 0, false, 2) ? new decimal(0, 0, 0, false, 2) : this.Pendente); + this.Repasse = this.Repasses.Where((VendedorParcela x) => { + if (!x.get_DataPrePagamento().HasValue) + { + return false; + } + return !x.get_CoCorretagem(); + }).Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()); + if (this.Pendente < this.Tolerancia) + { + this.Pendente = decimal.Zero; + } + if (this.VerificaCoCorretagem()) + { + Documento selectedDocumento = this.SelectedDocumento; + if (selectedDocumento != null) + { + comissaoTotal = selectedDocumento.get_ComissaoTotal(); + } + else + { + nullable = null; + comissaoTotal = nullable; + } + nullable = comissaoTotal; + this.ComissOriginal = nullable.GetValueOrDefault(); + } + } + + public VendedorParcela CalculaRepasse(Gestor.Model.Domain.Seguros.Repasse repasse, TipoVendedor tipoVendedor) + { + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + bool valueOrDefault = negocioCorretora.GetValueOrDefault() == 1; + if (this.SelectedParcela == null) + { + Parcela parcela = new Parcela(); + parcela.set_SubTipo(1); + parcela.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + this.SelectedParcela = parcela; + } + this.SelectedParcela.set_Documento(this.SelectedDocumento); + decimal num = Funcoes.CalculaRepasse(repasse, this.SelectedParcela, true); + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(repasse); + vendedorParcela.set_ValorRepasse(new decimal?(num)); + vendedorParcela.set_ValorTotal(new decimal?(num)); + vendedorParcela.set_Vendedor(repasse.get_Vendedor()); + vendedorParcela.set_PorcentagemRepasse(new decimal?((valueOrDefault ? repasse.get_ValorRenovacao() : repasse.get_ValorNovo()))); + vendedorParcela.set_TipoVendedor(tipoVendedor); + vendedorParcela.set_CoCorretagem((repasse != null ? repasse.get_Tipo().GetValueOrDefault() == 3 : false)); + return vendedorParcela; + } + + public async Task CancelarAlteracao() + { + this.Acesso = 0; + if (this.CancelDocumento == null || this.CancelDocumento.get_Id() == 0) + { + this.SelectedDocumento = null; + } + else + { + await this.SelecionaDocumento(this.CancelDocumento); + } + this.Anotacoes = string.Empty; + base.EnableFields = false; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(true); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(true); + } + else + { + } + Action enablePesquisarClientes = Gestor.Application.Actions.Actions.EnablePesquisarClientes; + if (enablePesquisarClientes != null) + { + enablePesquisarClientes(true); + } + else + { + } + } + + public async void CancelPagamento() + { + ObservableCollection observableCollection; + this.BaixarParcelas = false; + this.SelectedParcela.set_Baixando(false); + ObservableCollection observableCollection1 = await this.ParcelaServico.BuscarParcelasAsync(this.SelectedDocumento.get_Id()); + BaseApoliceViewModel baseApoliceViewModel = this; + if (this.IsFatura) + { + ObservableCollection observableCollection2 = observableCollection1; + observableCollection = new ObservableCollection( + from x in observableCollection2 + orderby x.get_NumeroParcela() descending + select x); + } + else + { + observableCollection = observableCollection1; + } + baseApoliceViewModel.Parcelas = observableCollection; + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + await this.SelecionaParcela(this.Parcelas.FirstOrDefault()); + } + + public async Task CarregaRepasse(long id) + { + this.Repasses = await this.VendedorServico.BuscaRepasse(id); + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela == null) + { + selectedParcela = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela); + } + + public async Task CarregarImposto() + { + List impostos = await (new ImpostoServico()).Buscar(new bool?(true)); + Gestor.Model.Domain.Ferramentas.Imposto imposto = impostos.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != this.SelectedDocumento.get_Controle().get_Seguradora().get_Id() || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == this.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + }); + if (imposto == null) + { + imposto = impostos.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Imposto x) => { + if (x.get_Seguradora() == null || x.get_Seguradora().get_Id() != this.SelectedDocumento.get_Controle().get_Seguradora().get_Id()) + { + return false; + } + return x.get_Ramo() == null; + }); + } + if (imposto == null) + { + imposto = impostos.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Imposto x) => { + if (x.get_Seguradora() != null || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == this.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + }); + } + if (imposto == null) + { + List impostos1 = impostos; + imposto = impostos1.FirstOrDefault((Gestor.Model.Domain.Ferramentas.Imposto x) => { + if (x.get_Seguradora() != null) + { + return false; + } + return x.get_Ramo() == null; + }); + } + Gestor.Model.Domain.Ferramentas.Imposto imposto1 = imposto; + BaseApoliceViewModel baseApoliceViewModel = this; + Gestor.Model.Domain.Ferramentas.Imposto imposto2 = imposto1; + if (imposto2 == null) + { + imposto2 = new Gestor.Model.Domain.Ferramentas.Imposto(); + } + baseApoliceViewModel.Imposto = imposto2; + } + + public async Task CarregarParcelas(Documento documento) + { + ObservableCollection observableCollection; + if (documento != null) + { + ObservableCollection observableCollection1 = await this.ParcelaServico.BuscarParcelasPorDocumento(documento); + BaseApoliceViewModel baseApoliceViewModel = this; + if (this.IsFatura) + { + ObservableCollection observableCollection2 = observableCollection1; + observableCollection = new ObservableCollection( + from x in observableCollection2 + orderby x.get_NumeroParcela() descending + select x); + } + else + { + observableCollection = observableCollection1; + } + baseApoliceViewModel.Parcelas = observableCollection; + if (this.Invoke) + { + Action recarregarParcelas = Gestor.Application.Actions.Actions.RecarregarParcelas; + if (recarregarParcelas != null) + { + recarregarParcelas(this.SelectedDocumento); + } + else + { + } + } + } + } + + public bool CompararValores() + { + if (this.SelectedDocumento.get_Id() == 0 || this.SelectedDocumento.HasChange("PremioLiquido") || this.SelectedDocumento.HasChange("PremioAdicional") || this.SelectedDocumento.HasChange("Comissao") || this.SelectedDocumento.HasChange("Iof")) + { + return true; + } + return this.SelectedDocumento.HasChange("AdicionalComiss"); + } + + private void CriarParcelas(bool insert) + { + if (this.Repasses == null) + { + this.Repasses = new List(); + } + var list = this.Repasses.Where((VendedorParcela x) => { + if (insert) + { + return true; + } + return x.get_Parcela().get_SubTipo() == 1; + }).GroupBy((VendedorParcela x) => new { Repasse = x.get_Repasse(), TipoVendedor = x.get_TipoVendedor() }).Distinct().ToList(); + List vendedorParcelas = new List(); + list.ForEach((x) => { + decimal num; + if (x.Key.Repasse == null) + { + return; + } + VendedorParcela vendedorParcela = this.CalculaRepasse(x.Key.Repasse, x.Key.TipoVendedor); + if (vendedorParcela.get_Repasse().get_Forma().GetValueOrDefault() == 3) + { + VendedorParcela vendedorParcela1 = vendedorParcela; + decimal? valorRepasse = vendedorParcela1.get_ValorRepasse(); + num = (this.SelectedDocumento.get_NumeroParcelas() > decimal.Zero ? this.SelectedDocumento.get_NumeroParcelas() : decimal.One); + vendedorParcela1.set_ValorRepasse((valorRepasse.HasValue ? new decimal?(valorRepasse.GetValueOrDefault() / num) : null)); + } + vendedorParcelas.Add(vendedorParcela); + }); + if (vendedorParcelas.All((VendedorParcela x) => x.get_TipoVendedor().get_Id() != (long)1)) + { + vendedorParcelas.Add(this.PropriaCorretora()); + } + this.Parcelas = new ObservableCollection(this.CriarParcelas(vendedorParcelas)); + } + + private List CriarParcelas(List vendedores) + { + TipoPagamento tipoPagamento; + List parcelas = new List(); + if (this.SelectedDocumento.get_NumeroParcelas() == decimal.Zero) + { + return parcelas; + } + decimal premioTotal = this.SelectedDocumento.get_PremioTotal() / this.SelectedDocumento.get_NumeroParcelas(); + FormaPagamento? formaPagamento = this.SelectedDocumento.get_FormaPagamento(); + if (!formaPagamento.HasValue) + { + this.SelectedDocumento.set_FormaPagamento(new FormaPagamento?(0)); + } + for (int i = 1; i <= this.SelectedDocumento.get_NumeroParcelas(); i++) + { + Parcela parcela = new Parcela(); + parcela.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + parcela.set_NumeroParcela(i); + parcela.set_Valor(premioTotal); + parcela.set_Comissao(this.SelectedDocumento.get_Comissao()); + DateTime vigencia1 = this.SelectedDocumento.get_Vigencia1(); + parcela.set_Vencimento(vigencia1.AddMonths(i - 1)); + parcela.set_SubTipo(1); + parcela.set_Vendedores(new ObservableCollection((i == 1 ? vendedores : vendedores.Where((VendedorParcela x) => { + Gestor.Model.Domain.Seguros.Repasse repasse = x.get_Repasse(); + if (repasse == null) + { + return false; + } + return repasse.get_Forma().GetValueOrDefault() == 3; + }).ToList()))); + formaPagamento = this.SelectedDocumento.get_FormaPagamento(); + if (formaPagamento.GetValueOrDefault() == 0 & formaPagamento.HasValue) + { + tipoPagamento = 7; + } + else + { + formaPagamento = this.SelectedDocumento.get_FormaPagamento(); + if (formaPagamento.GetValueOrDefault() == 1) + { + tipoPagamento = 3; + } + else + { + formaPagamento = this.SelectedDocumento.get_FormaPagamento(); + if (formaPagamento.GetValueOrDefault() == 2) + { + tipoPagamento = 15; + } + else + { + formaPagamento = this.SelectedDocumento.get_FormaPagamento(); + tipoPagamento = (formaPagamento.GetValueOrDefault() != 3 || i != 1 ? 7 : 15); + } + } + } + parcela.set_TipoPagamento(tipoPagamento); + parcela.set_DataCriacao(new DateTime?(Funcoes.GetNetworkTime())); + parcela.set_UsuarioCriacao(Recursos.Usuario.get_Id()); + parcelas.Add(parcela); + } + return parcelas; + } + + private List CriarRepasses(VendedorParcela repasse) + { + decimal? nullable; + if (this.Parcelas == null || this.Parcelas.Count == 0 || this.SelectedDocumento == null) + { + return null; + } + List vendedorParcelas = new List(); + VendedorParcela vendedorParcela1 = repasse; + if (repasse.get_Repasse().get_Forma().GetValueOrDefault() == 3) + { + decimal? valorRepasse = repasse.get_ValorRepasse(); + decimal numeroParcelas = this.SelectedDocumento.get_NumeroParcelas(); + if (valorRepasse.HasValue) + { + nullable = new decimal?(valorRepasse.GetValueOrDefault() / numeroParcelas); + } + else + { + nullable = null; + } + } + else + { + nullable = repasse.get_ValorRepasse(); + } + vendedorParcela1.set_ValorRepasse(nullable); + this.Parcelas.ToList().ForEach((Parcela x) => { + if (repasse.get_Repasse().get_Forma().GetValueOrDefault() != 3 && x.get_NumeroParcela() > 1) + { + return; + } + VendedorParcela vendedorParcela = (VendedorParcela)repasse.Clone(); + if (repasse.get_Repasse().get_Forma().GetValueOrDefault() == 3) + { + vendedorParcela.set_DataPrePagamento(new DateTime?(x.get_Vencimento())); + } + vendedorParcela.set_Parcela(x); + vendedorParcelas.Add(vendedorParcela); + }); + return vendedorParcelas; + } + + private async Task DesfazerAlteracoes() + { + IEnumerable list; + ItemServico itemServico = new ItemServico(); + IList documentos = this.SelectedDocumento.get_Controle().get_Documentos(); + ObservableCollection observableCollection = await itemServico.BuscarItems(documentos.FirstOrDefault((Documento x) => { + if (x.get_Excluido() || x.get_Situacao() == 7) + { + return false; + } + return x.get_Ordem() == 0; + }).get_Id(), 2, false); + ObservableCollection observableCollection1 = await (new ItemServico()).BuscarItems(this.SelectedDocumento.get_Id(), 2, false); + ObservableCollection observableCollection2 = observableCollection1; + List items = observableCollection.Where((Item x) => { + long? idDocumentoCancelado = x.get_IdDocumentoCancelado(); + long id = this.SelectedDocumento.get_Id(); + return idDocumentoCancelado.GetValueOrDefault() == id & idDocumentoCancelado.HasValue; + }).ToList(); + List items1 = items; + IEnumerable items2 = observableCollection.Where((Item x) => { + long? nullable; + long? nullable1 = x.get_Substituido(); + if (!nullable1.HasValue) + { + return false; + } + nullable1 = x.get_Substituido(); + Item item = observableCollection2.FirstOrDefault((Item d) => { + long id = d.get_Id(); + long? substituido = x.get_Substituido(); + return id == substituido.GetValueOrDefault() & substituido.HasValue; + }); + if (item != null) + { + nullable = new long?(item.get_Id()); + } + else + { + nullable = null; + } + long? nullable2 = nullable; + return nullable1.GetValueOrDefault() == nullable2.GetValueOrDefault() & nullable1.HasValue == nullable2.HasValue; + }); + if (items2 != null) + { + list = items2.ToList(); + } + else + { + list = null; + } + items1.AddRange(list); + if (items.Count == 0) + { + items = observableCollection.Where((Item x) => { + if (x.get_Status() == null || Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(x.get_Status()) || !x.get_Status().Contains("ORDEM")) + { + return false; + } + return x.get_Status().Replace("ORDEM", "-").Split(new char[] { '-' })[1].Trim().Equals(string.Format("{0}", this.SelectedDocumento.get_Ordem())); + }).ToList(); + } + foreach (Item item1 in items) + { + await (new ItemServico()).Reativar(item1, ""); + } + observableCollection = null; + } + + public void EditarParcelaEspecial() + { + this.AllowEditVendedor = true; + } + + public async Task EditarParcelas() + { + if (this.DocumentoSelecionado == null) + { + this.DocumentoSelecionado = this.SelectedDocumento; + } + await base.ShowEditarParcelasDialog(this.DocumentoSelecionado); + await this.CarregarParcelas(this.DocumentoSelecionado); + } + + public async Task ExcluirApolice() + { + string str; + int ordem; + string str1; + string str2; + TipoSeguro value; + int? nullable; + Documento selectedDocumento; + string str3; + string str4; + if (this.SelectedDocumento != null) + { + if (this.AllowEditApolice) + { + ObservableCollection parcelas = this.Parcelas; + if (!parcelas.Any((Parcela x) => x.get_DataRecebimento().HasValue)) + { + List repasses = this.Repasses; + if (!repasses.Any((VendedorParcela x) => x.get_DataPagamento().HasValue)) + { + if (this.SelectedDocumento.get_Tipo() <= 0 || !this.SelectedDocumento.get_Sinistro()) + { + selectedDocumento = this.SelectedDocumento; + if (selectedDocumento.get_Tipo() != 0 || !string.IsNullOrEmpty(selectedDocumento.get_Apolice())) + { + str = (selectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(selectedDocumento.get_Apolice()) ? "O ENDOSSO SELECIONADO" : "A APÓLICE SELECIONADA"); + } + else + { + str = "A PROPOSTA SELECIONADA"; + } + str3 = str; + int num = this.SelectedDocumento.get_Ordem(); + IList documentos = this.SelectedDocumento.get_Controle().get_Documentos(); + Documento documento = ( + from x in documentos + orderby x.get_Ordem() descending + select x).FirstOrDefault((Documento x) => { + if (!x.get_Excluido() && x.get_Situacao() != 7) + { + return true; + } + return x.get_Id() == this.SelectedDocumento.get_Id(); + }); + if (documento != null) + { + ordem = documento.get_Ordem(); + } + else + { + ordem = this.SelectedDocumento.get_Ordem(); + } + if (num == ordem) + { + string[] newLine = new string[] { "DESEJA REALMENTE EXCLUIR ", str3, "?", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL." }; + if (await base.ShowMessage(string.Concat(newLine), "SIM", "NÃO", false)) + { + bool hasValue = selectedDocumento.get_TipoEndosso().HasValue; + if (hasValue) + { + hasValue = await base.ShowMessage("DESEJA DESFAZER AS ALTERAÇOES NOS ITENS VINCULADOS A ESSE ENDOSSO ?", "SIM", "NÃO", false); + } + if (hasValue) + { + IList documentos1 = this.SelectedDocumento.get_Controle().get_Documentos(); + Documento documento1 = ( + from x in documentos1 + orderby x.get_Ordem() descending + select x).FirstOrDefault((Documento x) => { + if (x.get_Excluido() || x.get_Situacao() == 7) + { + return false; + } + return x.get_Ordem() > this.SelectedDocumento.get_Ordem(); + }); + if (documento1 != null) + { + nullable = new int?(documento1.get_Ordem()); + } + else + { + nullable = null; + } + int? nullable1 = nullable; + int ordem1 = this.SelectedDocumento.get_Ordem(); + if (!(nullable1.GetValueOrDefault() > ordem1 & nullable1.HasValue)) + { + await this.DesfazerAlteracoes(); + } + else + { + await base.ShowMessage(string.Concat("NÃO É POSSIVEL DESFAZER AS ALTERAÇÕES, POIS ", str3, " POSSUE ENDOSSOS ATIVOS ACIMA."), "OK", "", false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + if (selectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(selectedDocumento.get_Apolice())) + { + str1 = string.Concat("EXCLUIU PROPOSTA ", selectedDocumento.get_Proposta()); + } + else if (selectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(selectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(selectedDocumento.get_Endosso()) ? string.Concat("EXCLUIU PROPOSTA DE ENDOSSO ", selectedDocumento.get_PropostaEndosso()) : string.Concat("EXCLUIU ENDOSSO ", selectedDocumento.get_Endosso())); + } + else + { + str1 = string.Concat("EXCLUIU APÓLICE ", selectedDocumento.get_Apolice()); + } + string str5 = str1; + base.RegistrarAcao(str5, this.SelectedDocumento.get_Id(), new TipoTela?(2), this.GerarObs(selectedDocumento)); + base.Loading(true); + if (selectedDocumento.get_Tipo() != 0 || !string.IsNullOrEmpty(selectedDocumento.get_Apolice())) + { + str2 = (selectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(selectedDocumento.get_Apolice()) ? "ENDOSSO EXCLUÍDO" : "APÓLICE EXCLUÍDA"); + } + else + { + str2 = "PROPOSTA EXCLUÍDA"; + } + str4 = str2; + selectedDocumento.set_Excluido(true); + this.Servico.Sucesso = true; + await this.Servico.ExcluirCritica(selectedDocumento.get_Id()); + if (this.Servico.Sucesso) + { + Gestor.Application.Servicos.TarefaServico tarefaServico = this.TarefaServico; + hasValue = await this.TarefaServico.ExcluirTarefasDocumento(selectedDocumento.get_Id()); + tarefaServico.Sucesso = hasValue; + tarefaServico = null; + if (this.TarefaServico.Sucesso) + { + this.Servico.Sucesso = true; + if (selectedDocumento.get_TipoEndosso().HasValue && selectedDocumento.get_TipoEndosso().GetValueOrDefault() == 2) + { + IList documentos2 = this.CancelDocumento.get_Controle().get_Documentos(); + Documento documento2 = documentos2.FirstOrDefault((Documento x) => { + if (x.get_Tipo() != 0) + { + return false; + } + return !x.get_Excluido(); + }); + IList documentos3 = this.CancelDocumento.get_Controle().get_Documentos(); + List list = documentos3.Where((Documento x) => { + if (x.get_Tipo() != 1) + { + return false; + } + return !x.get_Excluido(); + }).ToList(); + if (documento2 != null) + { + Documento documento3 = documento2; + if (!documento2.get_SituacaoAnterior().HasValue || documento2.get_SituacaoAnterior().GetValueOrDefault() == 3) + { + value = (documento2.get_NegocioCorretora().GetValueOrDefault() == 1 ? 2 : 1); + } + else + { + value = documento2.get_SituacaoAnterior().Value; + } + documento3.set_Situacao(value); + await this.Servico.Save(documento2, false, false); + foreach (Documento documento4 in list) + { + documento4.set_Situacao(documento2.get_Situacao()); + await this.Servico.Save(documento4, false, false); + } + } + documento2 = null; + list = null; + } + await this.Servico.Excluir(selectedDocumento); + if (this.Servico.Sucesso) + { + if (selectedDocumento.get_Tipo() > 0) + { + await Funcoes.OrganizarDocumentos(selectedDocumento.get_Controle().get_Id()); + await Funcoes.InativarItens(selectedDocumento.get_Id(), selectedDocumento.get_Controle().get_Ramo().get_Id(), true); + } + if (this.Invoke) + { + ConsultaViewModel.DocumentoSelecionado = null; + Action recarregarDocumentos = Gestor.Application.Actions.Actions.RecarregarDocumentos; + if (recarregarDocumentos != null) + { + recarregarDocumentos(null); + } + else + { + } + } + base.Loading(false); + base.ToggleSnackBar(string.Concat(str4, " COM SUCESSO"), true); + if (this.Invoke) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(21, ""); + } + else + { + } + } + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + else + { + base.Loading(false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + else + { + base.Loading(false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + else + { + base.Loading(false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + else + { + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + else + { + await base.ShowMessage(string.Concat(str3, " NÃO PODE SER EXCLUÍDO(A) POIS POSSUEM DOCUMENTOS ATIVOS ACIMA."), "OK", "", false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + else + { + await base.ShowMessage("DOCUMENTO NÃO PODE SER EXCLUÍDO POIS POSSUI SINISTROS PARA UM OU MAIS DE SEUS ITENS.", "OK", "", false); + selectedDocumento = null; + str3 = null; + str4 = null; + return; + } + } + } + } + await base.ShowMessage("DOCUMENTO NÃO PODE SER EXCLUÍDO POIS POSSUI BAIXAS DE COMISSÃO OU PAGAMENTO DE VENDEDORES.", "OK", "", false); + } + selectedDocumento = null; + str3 = null; + str4 = null; + } + + internal async Task ExcluirBaixa() + { + string str; + string str1; + bool flag; + if (this.SelectedParcela != null) + { + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR A BAIXA DA PARCELA SELECIONADA?", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL."), "SIM", "NÃO", false)) + { + base.Loading(true); + this.SelectedParcela.set_Documento(this.SelectedDocumento); + this.SelectedParcela = await Funcoes.ExcluirBaixa(this.SelectedParcela, this.Repasses, this.Parcelas.ToList()); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str = string.Concat("PROPOSTA ", this.SelectedDocumento.get_Proposta()); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("PROPOSTA DE ENDOSSO ", this.SelectedDocumento.get_PropostaEndosso()) : string.Concat("ENDOSSO ", this.SelectedDocumento.get_Endosso())); + } + else + { + str = string.Concat("APÓLICE ", this.SelectedDocumento.get_Apolice()); + } + string str2 = str; + str1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? string.Format("BAIXA DA PARCELA {0} EXCLUÍDA, {1}", this.SelectedParcela.get_NumeroParcela(), str2) : string.Concat("BAIXA DA FATURA ", this.SelectedParcela.get_Fatura(), " EXCLUÍDA, ", str2)); + string str3 = str1; + base.RegistrarAcao(str3, this.SelectedParcela.get_Id(), new TipoTela?(5), this.GerarObs(this.SelectedDocumento)); + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela == null) + { + selectedParcela = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela); + this.BaixarParcelas = false; + BaseApoliceViewModel baseApoliceViewModel1 = this; + ObservableCollection parcelas = this.Parcelas; + IEnumerable subTipo = + from x in parcelas + where x.get_SubTipo() == 1 + select x; + if (!subTipo.All((Parcela x) => !x.get_DataRecebimento().HasValue)) + { + flag = false; + } + else + { + List repasses = this.Repasses; + IEnumerable vendedorParcelas = + from x in repasses + where x.get_Parcela().get_SubTipo() == 1 + select x; + flag = vendedorParcelas.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + baseApoliceViewModel1.AllowEditApolice = flag; + base.Loading(false); + base.ToggleSnackBar("BAIXA EXCLUÍDA COM SUCESSO", true); + } + } + } + + public async Task ExcluirPagamento(VendedorParcela pagamento) + { + bool flag; + string str; + base.Loading(true); + if (await Funcoes.ExcluirPagamento(pagamento)) + { + base.ToggleSnackBar("PAGAMENTO EXCLUÍDO COM SUCESSO", true); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str = string.Concat("NA PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("NA PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("NO ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str = string.Concat("NA APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str1 = str; + string str2 = string.Concat("PAGAMENTO DO VENDEDOR ", pagamento.get_Vendedor().get_Nome(), " EXCLUÍDO, ", str1); + long id = pagamento.get_Id(); + TipoTela? nullable = new TipoTela?(37); + object[] objArray = new object[] { this.GerarObs(this.SelectedDocumento), Environment.NewLine, pagamento.get_Vendedor().get_Nome(), Environment.NewLine, pagamento.get_ValorTotal() }; + base.RegistrarAcao(str2, id, nullable, string.Format("{0}{1}VENDEDOR: {2}{3}COMISSÃO TOTAL: {4:C2}", objArray)); + } + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + await this.SelecionaParcela(this.Parcelas.FirstOrDefault()); + BaseApoliceViewModel baseApoliceViewModel = this; + ObservableCollection parcelas = this.Parcelas; + IEnumerable subTipo = + from x in parcelas + where x.get_SubTipo() == 1 + select x; + if (!subTipo.All((Parcela x) => !x.get_DataRecebimento().HasValue)) + { + flag = false; + } + else + { + List repasses = this.Repasses; + IEnumerable vendedorParcelas = + from x in repasses + where x.get_Parcela().get_SubTipo() == 1 + select x; + flag = vendedorParcelas.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + baseApoliceViewModel.AllowEditApolice = flag; + this.BaixarParcelas = false; + base.Loading(false); + } + + public async Task ExcluirParcela() + { + string str; + string str1; + string str2; + if (this.SelectedParcela != null) + { + if (this.SelectedParcela.get_SubTipo() != 1 || this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1) + { + if (this.SelectedParcela.get_SubTipo() == 1) + { + ObservableCollection parcelas = this.Parcelas; + IOrderedEnumerable numeroParcela = + from x in parcelas + orderby x.get_NumeroParcela() + select x; + Parcela parcela = numeroParcela.Last((Parcela x) => x.get_SubTipo() == 1); + if (this.SelectedParcela.get_Id() != parcela.get_Id()) + { + await base.ShowMessage("A FATURA NÃO PODE SER EXCLUÍDA POIS HÁ FATURAS CADASTRADAS ACIMA DA SELECIONADA.", "OK", "", false); + return; + } + } + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE EXCLUIR A PARCELA SELECIONADA?", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL."), "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this.ParcelaServico.Delete(this.SelectedParcela, this.Parcelas.ToList())) + { + BaseApoliceViewModel baseApoliceViewModel = this; + str = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? "PARCELA EXCLUÍDA COM SUCESSO" : "FATURA EXCLUÍDA COM SUCESSO"); + baseApoliceViewModel.ToggleSnackBar(str, true); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("PROPOSTA ", this.SelectedDocumento.get_Proposta()); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("PROPOSTA DE ENDOSSO ", this.SelectedDocumento.get_PropostaEndosso()) : string.Concat("ENDOSSO ", this.SelectedDocumento.get_Endosso())); + } + else + { + str1 = string.Concat("APÓLICE ", this.SelectedDocumento.get_Apolice()); + } + string str3 = str1; + str2 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? string.Format("PARCELA {0} EXCLUÍDA, {1}", this.SelectedParcela.get_NumeroParcela(), str3) : string.Concat("FATURA ", this.SelectedParcela.get_Fatura(), " EXCLUÍDA, ", str3)); + string str4 = str2; + base.RegistrarAcao(str4, this.SelectedParcela.get_Id(), new TipoTela?(5), this.GerarObs(this.SelectedDocumento)); + } + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + await this.SelecionaParcela(this.Parcelas.FirstOrDefault()); + this.BaixarParcelas = false; + if (this.Parcelas == null || this.Parcelas.Count == 0) + { + this.VisibilityExcluirParcela = Visibility.Collapsed; + this.VisibilityReplicarFatura = Visibility.Collapsed; + this.BaixarParcelaVisibility = Visibility.Collapsed; + } + base.Loading(false); + this.AllowEditVendedor = this.Parcelas.Any(); + } + } + } + } + + public async Task ExcluirVendedor(VendedorParcela pagamento, bool incluirCorretora = true) + { + List vendedorParcelas; + bool flag; + Vendedor vendedor; + string str1; + List list; + if (this.IsEndosso && this.SelectedDocumento.get_Id() == 0) + { + this.RemoverVendedor(pagamento.get_Vendedor().get_Id()); + base.ToggleSnackBar("VENDEDOR EXCLUÍDO COM SUCESSO", true); + } + else if (!this.AllowEditApolice && !this.IsFatura && this.SelectedParcela.get_SubTipo() == 1) + { + string[] upper = new string[] { "O VENDEDOR ", pagamento.get_Vendedor().get_Nome().ToUpper(), " NÃO PODE SER EXCLUÍDO.", Environment.NewLine, "JÁ EXISTEM RECEBIMENTOS OU PAGAMENTOS DE COMISSÃO PARA ESSE DOCUMENTO." }; + await base.ShowMessage(string.Concat(upper), "OK", "", false); + } + else if (this.SelectedDocumento.get_Id() > (long)0 && (this.IsFatura || this.SelectedParcela.get_SubTipo() != 1) && (this.SelectedParcela.get_Id() > (long)0 && this.SelectedParcela.get_DataRecebimento().HasValue || this.Repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != this.SelectedParcela.get_Id()) + { + return false; + } + return x.get_DataPagamento().HasValue; + }))) + { + string[] strArrays = new string[] { "O VENDEDOR ", pagamento.get_Vendedor().get_Nome().ToUpper(), " NÃO PODE SER EXCLUÍDO.", Environment.NewLine, "JÁ EXISTEM RECEBIMENTOS OU PAGAMENTOS DE COMISSÃO PARA ESSA FATURA." }; + await base.ShowMessage(string.Concat(strArrays), "OK", "", false); + } + else if (this.SelectedDocumento.get_Id() != 0) + { + vendedorParcelas = (this.SelectedParcela.get_SubTipo() != 1 || this.IsFatura ? this.Repasses.Where((VendedorParcela x) => { + if (x.get_Vendedor().get_Id() != pagamento.get_Vendedor().get_Id()) + { + return false; + } + return x.get_Parcela().get_Id() == this.SelectedParcela.get_Id(); + }).ToList() : this.Repasses.Where((VendedorParcela x) => { + if (x.get_Vendedor().get_Id() != pagamento.get_Vendedor().get_Id()) + { + return false; + } + return x.get_Parcela().get_NumeroParcela() != 999; + }).ToList()); + list = vendedorParcelas.Distinct().ToList(); + if (await this.Servico.ExcluirPagamento(list)) + { + if (this.SelectedParcela.get_Id() > (long)0) + { + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("NA PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("NA PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("NO ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str1 = string.Concat("NA APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str2 = str1; + list.ForEach((VendedorParcela x) => { + string str = string.Concat("VENDEDOR ", x.get_Vendedor().get_Nome(), " EXCLUÍDO, ", str2); + base.RegistrarAcao(str, x.get_Id(), new TipoTela?(37), string.Format("{0}{1}VENDEDOR: {2}{3}COMISSÃO TOTAL: {4:C2}", new object[] { this.GerarObs(this.SelectedDocumento), Environment.NewLine, x.get_Vendedor().get_Nome(), Environment.NewLine, x.get_ValorTotal() })); + }); + } + this.RemoverVendedor(pagamento.get_Vendedor().get_Id()); + if (this.IsFatura || this.SelectedParcela.get_SubTipo() != 1) + { + flag = this.Repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != this.SelectedParcela.get_Id()) + { + return false; + } + return x.get_TipoVendedor().get_Id() == (long)1; + }); + } + else + { + List repasses = this.Repasses; + flag = repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_SubTipo() != 1 || x.get_TipoVendedor().get_Id() != (long)1) + { + return false; + } + return !x.get_CoCorretagem(); + }); + } + bool flag1 = flag; + if (pagamento.get_TipoVendedor().get_Id() == (long)1 & incluirCorretora && !flag1) + { + VendedorParcela vendedorParcela = await this.IncluirPropriaCorretora(); + if (vendedorParcela != null) + { + this.Repasses.Add(vendedorParcela); + Documento selectedDocumento = this.SelectedDocumento; + List repasses1 = this.Repasses; + VendedorParcela vendedorParcela1 = repasses1.FirstOrDefault((VendedorParcela x) => x.get_TipoVendedor().get_Id() == (long)1); + if (vendedorParcela1 != null) + { + vendedor = vendedorParcela1.get_Vendedor(); + } + else + { + vendedor = null; + } + selectedDocumento.set_VendedorPrincipal(vendedor); + } + } + if (this.Repasses != null) + { + this.Pagamentos = new ObservableCollection(( + from x in this.Repasses + where x.get_Parcela().get_Id() == this.SelectedParcela.get_Id() + select x).ToList()); + } + base.ToggleSnackBar("VENDEDOR EXCLUÍDO COM SUCESSO", true); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + } + else + { + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela == null) + { + selectedParcela = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela); + } + } + else + { + this.RemoverVendedor(pagamento.get_Vendedor().get_Id()); + base.ToggleSnackBar("VENDEDOR EXCLUÍDO COM SUCESSO", true); + } + list = null; + } + + public void FiltrarRepasse(Vendedor vendedor) + { + if (this.SelectedPagamento == null) + { + this.SelectedPagamento = new VendedorParcela(); + } + this.SelectedPagamento.set_Vendedor(vendedor); + this.RepassesVendedor = this.GetRepasses(vendedor); + } + + public string GerarObs(Documento doc) + { + if (doc.get_Tipo() == 0) + { + return string.Format("CLIENTE: {0}{1}CÓDIGO: {2}{3}PROPOSTA: {4}{5}APÓLICE: {6}", new object[] { doc.get_Controle().get_Cliente().get_Nome(), Environment.NewLine, doc.get_Id(), Environment.NewLine, doc.get_Proposta(), Environment.NewLine, doc.get_Apolice() }); + } + return string.Format("CLIENTE: {0}{1}CÓDIGO: {2}{3}PROPOSTA: {4}{5}APÓLICE: {6}{7}PROPOSTA DE ENDOSSO: {8}{9}ENDOSSO: {10}", new object[] { doc.get_Controle().get_Cliente().get_Nome(), Environment.NewLine, doc.get_Id(), Environment.NewLine, doc.get_Proposta(), Environment.NewLine, doc.get_Apolice(), Environment.NewLine, doc.get_PropostaEndosso(), Environment.NewLine, doc.get_Endosso() }); + } + + public List GetRepasses(Vendedor vendedor) + { + List repasses; + if (this.CoCorretagem) + { + IEnumerable repassesVendedores = + from x in this.RepassesVendedores + where x.get_Vendedor().get_Id() == vendedor.get_Id() + select x; + if (repassesVendedores == null) + { + return null; + } + IEnumerable valueOrDefault = + from x in repassesVendedores + where x.get_Tipo().GetValueOrDefault() == 3 + select x; + if (valueOrDefault == null) + { + return null; + } + return ( + from x in valueOrDefault + orderby x.get_ValorNovo() + select x).ToList(); + } + if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 20)) + { + IEnumerable repassesVendedores1 = + from x in this.RepassesVendedores + where x.get_Vendedor().get_Id() == vendedor.get_Id() + select x; + if (repassesVendedores1 == null) + { + return null; + } + return ( + from x in repassesVendedores1 + where x.get_Tipo().GetValueOrDefault() != 3 + orderby x.get_ValorNovo() + select x).ToList(); + } + repasses = (!this.RepassesVendedores.Any((Gestor.Model.Domain.Seguros.Repasse x) => { + if (x.get_Vendedor().get_Id() != vendedor.get_Id() || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == this.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + }) ? this.RepassesVendedores.Where((Gestor.Model.Domain.Seguros.Repasse x) => { + if (x.get_Vendedor().get_Id() != vendedor.get_Id()) + { + return false; + } + return x.get_Ramo() == null; + }).OrderBy((Gestor.Model.Domain.Seguros.Repasse x) => x.get_ValorNovo()).ToList() : this.RepassesVendedores.Where((Gestor.Model.Domain.Seguros.Repasse x) => { + if (x.get_Vendedor().get_Id() != vendedor.get_Id() || x.get_Ramo() == null) + { + return false; + } + return x.get_Ramo().get_Id() == this.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + }).OrderBy((Gestor.Model.Domain.Seguros.Repasse x) => x.get_ValorNovo()).ToList()); + return repasses; + } + + public List> HabilitarVendedor(int editarParcelaTipo = 0) + { + IEnumerable u00210s; + List> keyValuePairs = new List>(); + if (editarParcelaTipo != 4) + { + keyValuePairs.AddRange(this.SelectedDocumento.Validate(this.IsEndosso, Recursos.Configuracoes.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 11))); + } + else if (this.SelectedParcela != null) + { + List> keyValuePairs1 = keyValuePairs; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela != null) + { + u00210s = selectedParcela.Validate(Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 9), Recursos.Configuracoes.Any((ConfiguracaoSistema y) => y.get_Configuracao() == 11), this.EditandoParcela, Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 16)); + } + else + { + u00210s = null; + } + keyValuePairs1.AddRange(u00210s); + } + return keyValuePairs; + } + + public async Task Importacao() + { + DateTime? dataCriacao; + DateTime? dataImportacao; + RegistroLog registroLog; + DateTime? nullable; + object nome; + string str; + object obj; + string str1; + bool flag; + string str2; + DateTime? nullable1; + object nome1; + bool flag1; + string str3; + DateTime? nullable2; + object obj1; + string str4; + string str5; + List criticaApolices = await (new CriticaApoliceServico()).BuscarImportacao(this.SelectedDocumento.get_Id()); + List list = await (new LogServico()).FindByEntityId(2, this.SelectedDocumento.get_Id()).ToList(); + if (list.Count > 0) + { + registroLog = list.Last(); + } + else + { + registroLog = null; + } + RegistroLog registroLog1 = registroLog; + switch (criticaApolices.Count) + { + case 0: + { + BaseApoliceViewModel baseApoliceViewModel = this; + dataCriacao = this.SelectedDocumento.get_DataCriacao(); + if (!dataCriacao.HasValue) + { + if (registroLog1 != null) + { + nome = registroLog1.get_Usuario().get_Nome(); + } + else + { + nome = null; + } + if (registroLog1 != null) + { + nullable = new DateTime?(registroLog1.get_DataHora()); + } + else + { + dataCriacao = null; + nullable = dataCriacao; + } + str = string.Format("CADASTRO MANUAL: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", nome, nullable); + } + else + { + Usuario usuarioCriacao = this.SelectedDocumento.get_UsuarioCriacao(); + if (usuarioCriacao != null) + { + obj = usuarioCriacao.get_Nome(); + } + else + { + obj = null; + } + str = string.Format("CADASTRO MANUAL: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", obj, this.SelectedDocumento.get_DataCriacao()); + } + baseApoliceViewModel.Importado = str; + break; + } + case 1: + { + if (string.IsNullOrWhiteSpace(criticaApolices[0].get_Tipo()) || criticaApolices[0].get_Tipo() == "0") + { + BaseApoliceViewModel baseApoliceViewModel1 = this; + str1 = (!criticaApolices[0].get_Aggilizador().HasValue || !criticaApolices[0].get_Aggilizador().Value ? string.Format("IMPORTAÇÃO DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao()) : string.Format("IMPORTAÇÃO DA PROPOSTA VIA AGGILIZADOR: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao())); + baseApoliceViewModel1.Importado = str1; + } + if (criticaApolices[0].get_Tipo() == "1") + { + dataCriacao = this.SelectedDocumento.get_DataCriacao(); + if (dataCriacao.HasValue) + { + dataCriacao = criticaApolices[0].get_DataImportacao(); + if (dataCriacao.HasValue) + { + dataCriacao = this.SelectedDocumento.get_DataCriacao(); + DateTime value = dataCriacao.Value; + dataCriacao = criticaApolices[0].get_DataImportacao(); + if (DateTime.Compare(value, dataCriacao.Value) < 0) + { + this.Importado = string.Format("CADASTRO MANUAL DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", this.SelectedDocumento.get_UsuarioCriacao(), this.SelectedDocumento.get_DataCriacao()); + } + } + } + else + { + BaseApoliceViewModel baseApoliceViewModel2 = this; + if (registroLog1 != null) + { + obj1 = registroLog1.get_Usuario().get_Nome(); + } + else + { + obj1 = null; + } + if (registroLog1 != null) + { + nullable2 = new DateTime?(registroLog1.get_DataHora()); + } + else + { + dataCriacao = null; + nullable2 = dataCriacao; + } + baseApoliceViewModel2.Importado = string.Format("CADASTRO MANUAL DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", obj1, nullable2); + } + dataCriacao = this.SelectedDocumento.get_DataCriacao(); + dataImportacao = criticaApolices[0].get_DataImportacao(); + flag1 = (dataCriacao.HasValue & dataImportacao.HasValue ? dataCriacao.GetValueOrDefault() <= dataImportacao.GetValueOrDefault() : false); + if (flag1) + { + BaseApoliceViewModel baseApoliceViewModel3 = this; + str3 = (!criticaApolices[0].get_Aggilizador().HasValue || !criticaApolices[0].get_Aggilizador().Value ? string.Format("IMPORTAÇÃO DA APÓLICE: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao()) : string.Format("IMPORTAÇÃO DA APÓLICE VIA AGGILIZADOR: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao())); + baseApoliceViewModel3.Importado = str3; + } + } + if (criticaApolices[0].get_Tipo() != "2") + { + break; + } + dataImportacao = this.SelectedDocumento.get_DataCriacao(); + if (dataImportacao.HasValue) + { + dataImportacao = criticaApolices[0].get_DataImportacao(); + if (dataImportacao.HasValue) + { + dataImportacao = this.SelectedDocumento.get_DataCriacao(); + DateTime dateTime = dataImportacao.Value; + dataImportacao = criticaApolices[0].get_DataImportacao(); + if (DateTime.Compare(dateTime, dataImportacao.Value) < 0) + { + this.Importado = string.Format("CADASTRO MANUAL DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", this.SelectedDocumento.get_UsuarioCriacao(), this.SelectedDocumento.get_DataCriacao()); + } + } + } + else + { + BaseApoliceViewModel baseApoliceViewModel4 = this; + if (registroLog1 != null) + { + nome1 = registroLog1.get_Usuario().get_Nome(); + } + else + { + nome1 = null; + } + if (registroLog1 != null) + { + nullable1 = new DateTime?(registroLog1.get_DataHora()); + } + else + { + dataImportacao = null; + nullable1 = dataImportacao; + } + baseApoliceViewModel4.Importado = string.Format("CADASTRO MANUAL DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", nome1, nullable1); + } + dataImportacao = this.SelectedDocumento.get_DataCriacao(); + dataCriacao = criticaApolices[0].get_DataImportacao(); + flag = (dataImportacao.HasValue & dataCriacao.HasValue ? dataImportacao.GetValueOrDefault() <= dataCriacao.GetValueOrDefault() : false); + if (!flag) + { + break; + } + BaseApoliceViewModel baseApoliceViewModel5 = this; + str2 = (!criticaApolices[0].get_Aggilizador().HasValue || !criticaApolices[0].get_Aggilizador().Value ? string.Format("IMPORTAÇÃO DO ENDOSSO: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao()) : string.Format("IMPORTAÇÃO DO ENDOSSO VIA AGGILIZADOR: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolices[0].get_UsuarioImportacao().get_Nome(), criticaApolices[0].get_DataImportacao())); + baseApoliceViewModel5.Importado = str2; + break; + } + case 2: + case 3: + { + List criticaApolices1 = criticaApolices; + CriticaApolice criticaApolouse = criticaApolices1.Find((CriticaApolice x) => { + if (string.IsNullOrWhiteSpace(x.get_Tipo())) + { + return true; + } + return x.get_Tipo() == "0"; + }); + List criticaApolices2 = criticaApolices; + CriticaApolice criticaApolouse1 = criticaApolices2.Find((CriticaApolice x) => x.get_Tipo() == "1"); + BaseApoliceViewModel baseApoliceViewModel6 = this; + str4 = (!criticaApolouse.get_Aggilizador().HasValue || !criticaApolouse.get_Aggilizador().Value ? string.Format("IMPORTAÇÃO DA PROPOSTA: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", criticaApolouse.get_UsuarioImportacao().get_Nome(), criticaApolouse.get_DataImportacao()) : string.Format("IMPORTAÇÃO DA PROPOSTA VIA AGGILIZADOR: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}\n", criticaApolouse.get_UsuarioImportacao().get_Nome(), criticaApolouse.get_DataImportacao())); + baseApoliceViewModel6.Importado = str4; + if (criticaApolouse1 == null) + { + break; + } + BaseApoliceViewModel baseApoliceViewModel7 = this; + string importado = this.Importado; + str5 = (!criticaApolouse1.get_Aggilizador().HasValue || !criticaApolouse1.get_Aggilizador().Value ? string.Format("IMPORTAÇÃO DA APÓLICE: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolouse1.get_UsuarioImportacao().get_Nome(), criticaApolouse1.get_DataImportacao()) : string.Format("IMPORTAÇÃO DA APÓLICE VIA AGGILIZADOR: {0} - {1:dd/MM/yyyy 'ÀS' HH:mm:ss}", criticaApolouse1.get_UsuarioImportacao().get_Nome(), criticaApolouse1.get_DataImportacao())); + baseApoliceViewModel7.Importado = string.Concat(importado, str5); + break; + } + } + criticaApolices = null; + } + + public async Task IncluirApolice(bool renovar = false) + { + bool flag; + DateTime? emissao; + FormaPagamento? nullable1; + List list; + List vendedors; + DateTime dateTime; + ObservableCollection observableCollection; + Documento documento; + if (renovar) + { + if (!string.IsNullOrWhiteSpace(this.SelectedDocumento.get_Apolice())) + { + emissao = this.SelectedDocumento.get_Emissao(); + if (emissao.HasValue) + { + goto Label1; + } + } + await base.ShowMessage("PROPOSTA NÃO PODE SER RENOVADA. NECESSÁRIO PREENCHER O NÚMERO DA APÓLICE E DATA DE EMISSÃO ANTES DE PROSSEGUIR.", "OK", "", false); + flag = false; + documento = null; + return flag; + } + Label1: + List seguradoras = Recursos.Seguradoras; + IEnumerable ativo = + from x in seguradoras + where x.get_Ativo() + select x; + List list1 = ( + from x in ativo + orderby x.get_Nome() + select x).ToList(); + this.Seguradoras = list1; + this.SeguradorasAnteriores = Recursos.Seguradoras; + List ramos = Recursos.Ramos; + IEnumerable ativo1 = + from x in ramos + where x.get_Ativo() + select x; + List ramos1 = ( + from x in ativo1 + orderby x.get_Nome() + select x).ToList(); + this.Ramos = ramos1; + List produtos = Recursos.Produtos; + List produtos1 = ( + from x in produtos + where x.get_Ativo() + select x).ToList(); + this.Produtos = produtos1; + List status = Recursos.Status; + List statuses = ( + from x in status + where x.get_Ativo() + select x).ToList(); + this.Status = statuses; + DateTime date = Funcoes.GetNetworkTime().Date; + if (!renovar) + { + this.Inclusao = true; + BaseApoliceViewModel baseApoliceViewModel = this; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 20)) + { + List todosVendedores = this.TodosVendedores; + list = todosVendedores.Where((Vendedor x) => { + if (x.get_IdEmpresa() != MainViewModel.ClienteSelecionado.get_IdEmpresa() || !x.get_Ativo()) + { + return false; + } + return !x.get_Corretora(); + }).ToList(); + } + else + { + list = new List(); + } + baseApoliceViewModel.Vendedores = list; + BaseApoliceViewModel baseApoliceViewModel1 = this; + List estipulantes = Recursos.Estipulantes; + baseApoliceViewModel1.Estipulantes = estipulantes.Where((Estipulante x) => { + if (x.get_IdEmpresa() != MainViewModel.ClienteSelecionado.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }).ToList(); + Documento documento1 = new Documento(); + Controle controle = new Controle(); + controle.set_Cliente(MainViewModel.ClienteSelecionado); + controle.set_IdEmpresa(MainViewModel.ClienteSelecionado.get_IdEmpresa()); + documento1.set_Controle(controle); + documento1.set_Ordem(0); + documento1.set_Tipo(0); + documento1.set_NegocioCorretora(new NegocioCorretora?(0)); + documento1.set_Situacao(1); + documento1.set_TipoRecebimento(new TipoRecebimento?(1)); + documento1.set_Vigencia1(date); + documento1.set_Vigencia2(new DateTime?(date.AddYears(1))); + documento1.set_ApoliceConferida(false); + documento1.set_PropostaAssinada(false); + documento1.set_AdicionalComiss(false); + documento1.set_Excluido(false); + nullable1 = null; + documento1.set_FormaPagamento(nullable1); + documento = documento1; + this.Pagamentos = null; + this.Repasses = null; + } + else + { + this.SelectedDocumento = await this.Servico.BuscarApoliceAsync(this.SelectedDocumento.get_Id(), false, false); + this.DocumentoRenovado = this.SelectedDocumento; + if (this.Seguradoras.All((Seguradora x) => x.get_Id() != this.SelectedDocumento.get_Controle().get_Seguradora().get_Id())) + { + this.Seguradoras.Add(this.SelectedDocumento.get_Controle().get_Seguradora()); + } + if (this.SelectedDocumento.get_Controle().get_Produto() != null && this.Produtos.All((Produto x) => x.get_Id() != this.SelectedDocumento.get_Controle().get_Produto().get_Id())) + { + this.Seguradoras.Add(this.SelectedDocumento.get_Controle().get_Seguradora()); + } + if (this.SelectedDocumento.get_Controle().get_Ramo() != null && this.Ramos.All((Ramo x) => x.get_Id() != this.SelectedDocumento.get_Controle().get_Ramo().get_Id())) + { + this.Seguradoras.Add(this.SelectedDocumento.get_Controle().get_Seguradora()); + } + BaseApoliceViewModel baseApoliceViewModel2 = this; + List configuracaoSistemas = Recursos.Configuracoes; + vendedors = (configuracaoSistemas.All((ConfiguracaoSistema x) => x.get_Configuracao() != 20) ? this.TodosVendedores.Where((Vendedor x) => { + if (x.get_IdEmpresa() != this.SelectedDocumento.get_Controle().get_IdEmpresa() || !x.get_Ativo()) + { + return false; + } + return !x.get_Corretora(); + }).ToList() : new List()); + baseApoliceViewModel2.Vendedores = vendedors; + this.Estipulantes = Recursos.Estipulantes.Where((Estipulante x) => { + if (x.get_IdEmpresa() != this.SelectedDocumento.get_Controle().get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }).ToList(); + Documento documento2 = new Documento(); + Controle controle1 = new Controle(); + controle1.set_Cliente(MainViewModel.ClienteSelecionado); + controle1.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + controle1.set_Ramo(this.SelectedDocumento.get_Controle().get_Ramo()); + controle1.set_Seguradora(this.SelectedDocumento.get_Controle().get_Seguradora()); + controle1.set_SeguradoraAnterior(this.SelectedDocumento.get_Controle().get_Seguradora()); + documento2.set_Controle(controle1); + documento2.set_Ordem(0); + documento2.set_Tipo(0); + documento2.set_NegocioCorretora(new NegocioCorretora?(1)); + documento2.set_Situacao(2); + documento2.set_Negocio(new Negocio?(1)); + documento2.set_TipoRecebimento(new TipoRecebimento?(1)); + emissao = this.SelectedDocumento.get_Vigencia2(); + documento2.set_Vigencia1(emissao.GetValueOrDefault(date)); + emissao = this.SelectedDocumento.get_Vigencia2(); + dateTime = (emissao.HasValue ? emissao.GetValueOrDefault().AddYears(1) : date.AddYears(1)); + documento2.set_Vigencia2(new DateTime?(dateTime)); + documento2.set_ApoliceConferida(false); + documento2.set_PropostaAssinada(false); + documento2.set_AdicionalComiss(false); + documento2.set_Excluido(false); + documento2.set_ApoliceAnterior(this.SelectedDocumento.get_Apolice()); + nullable1 = null; + documento2.set_FormaPagamento(nullable1); + documento = documento2; + this.EmissaoDocumento = new DateTime?(date); + this.TransmissaoDocumento = new DateTime?(date); + if (!await base.ShowMessage("DESEJA MANTER OS VENDEDORES DA APÓLICE ANTERIOR?", "SIM", "NÃO", false)) + { + this.Pagamentos = new ObservableCollection() + { + this.PropriaCorretora() + }; + this.Repasses = null; + } + else + { + ObservableCollection pagamentos = this.Pagamentos; + if (pagamentos != null) + { + List vendedorParcelas = pagamentos.ToList(); + vendedorParcelas.ForEach((VendedorParcela x) => { + x.set_Documento(null); + x.set_ValorRepasse(new decimal?(new decimal())); + x.set_ValorTotal(null); + DateTime? nullable = null; + x.set_DataPagamento(nullable); + nullable = null; + x.set_DataPagamento(nullable); + }); + } + else + { + } + } + BaseApoliceViewModel baseApoliceViewModel3 = this; + observableCollection = (this.Pagamentos != null ? new ObservableCollection(this.Pagamentos) : new ObservableCollection()); + baseApoliceViewModel3.Pagamentos = observableCollection; + } + this.IsFatura = false; + this.SelectedParcela = null; + this.SelectedDocumento = null; + this.SelectedPagamento = null; + this.Parcelas = null; + this.SelectedDocumento = documento; + this.IsEndosso = false; + this.NovaApolice = true; + this.Renovar = renovar; + this.EnableAlterarSituacao = true; + this.AllowEditVendedor = !renovar; + this.AllowEditApolice = true; + base.IsEnabledEdit = true; + base.IsEnabledEditEndosso = true; + base.AllowEditParcela = false; + base.EnableFields = true; + base.EnableIncluir = false; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + flag = true; + documento = null; + return flag; + } + + public async Task IncluirEndosso() + { + bool flag; + ObservableCollection observableCollection; + NegocioCorretora valueOrDefault; + TipoEndosso tipoEndosso; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 13) || !string.IsNullOrWhiteSpace(this.SelectedDocumento.get_Apolice())) + { + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2) + { + observableCollection = new ObservableCollection(new List() + { + 2, + 1, + 4 + }); + } + else + { + List tipoEndossos = new List() + { + 0, + 1, + 2, + 4 + }; + observableCollection = new ObservableCollection(tipoEndossos); + } + ObservableCollection observableCollection1 = observableCollection; + if (this.SelectedDocumento.get_Situacao() == 3) + { + observableCollection1 = new ObservableCollection(new List() + { + 3 + }); + } + this.TipoEndossoList = observableCollection1; + Documento documento = new Documento(); + documento.set_Controle(this.SelectedDocumento.get_Controle()); + documento.set_Tipo(1); + IList documentos = this.SelectedDocumento.get_Controle().get_Documentos(); + IEnumerable excluido = + from x in documentos + where !x.get_Excluido() + select x; + documento.set_Ordem(excluido.Max((Documento x) => x.get_Ordem()) + 1); + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + if (negocioCorretora.HasValue) + { + valueOrDefault = negocioCorretora.GetValueOrDefault(); + } + else + { + valueOrDefault = (this.SelectedDocumento.get_Situacao() != 2 || !this.SelectedDocumento.get_Negocio().HasValue || this.SelectedDocumento.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + } + documento.set_NegocioCorretora(new NegocioCorretora?(valueOrDefault)); + documento.set_Situacao(this.SelectedDocumento.get_Situacao()); + documento.set_Negocio(this.SelectedDocumento.get_Negocio()); + documento.set_TipoRecebimento(this.SelectedDocumento.get_TipoRecebimento()); + documento.set_Vigencia1(Funcoes.GetNetworkTime().Date); + documento.set_Vigencia2(this.SelectedDocumento.get_Vigencia2()); + documento.set_ApoliceConferida(false); + documento.set_PropostaAssinada(false); + documento.set_AdicionalComiss(false); + documento.set_Excluido(false); + documento.set_Apolice(this.SelectedDocumento.get_Apolice()); + documento.set_Proposta(this.SelectedDocumento.get_Proposta()); + tipoEndosso = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? 2 : 0); + documento.set_TipoEndosso(new TipoEndosso?(tipoEndosso)); + documento.set_Comissao(this.SelectedDocumento.get_Comissao()); + documento.set_Estipulante1(this.SelectedDocumento.get_Estipulante1()); + documento.set_Estipulante2(this.SelectedDocumento.get_Estipulante2()); + documento.set_Estipulante3(this.SelectedDocumento.get_Estipulante3()); + documento.set_Estipulante4(this.SelectedDocumento.get_Estipulante4()); + documento.set_Estipulante5(this.SelectedDocumento.get_Estipulante5()); + Documento documento1 = documento; + this.SelectedParcela = null; + this.SelectedDocumento = null; + this.SelectedPagamento = null; + if (documento1.get_TipoRecebimento().GetValueOrDefault() != 1) + { + this.Pagamentos = null; + this.Repasses = null; + } + else + { + List repasses = this.Repasses; + List list = ( + from x in repasses + where x.get_Parcela().get_SubTipo() == 1 + select x).ToList(); + List vendedorParcelas = ( + from x in list + group x by x.get_Vendedor().get_Id()).Select, VendedorParcela>((IGrouping x) => { + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(x.First().get_Repasse()); + vendedorParcela.set_Parcela(this.SelectedParcela); + vendedorParcela.set_Documento(this.SelectedDocumento); + vendedorParcela.set_ValorRepasse(new decimal?(new decimal())); + vendedorParcela.set_Vendedor(x.First().get_Vendedor()); + vendedorParcela.set_PorcentagemRepasse(x.First().get_PorcentagemRepasse()); + vendedorParcela.set_TipoVendedor(x.First().get_TipoVendedor()); + return vendedorParcela; + }).ToList(); + this.Pagamentos = new ObservableCollection(vendedorParcelas); + this.Repasses = vendedorParcelas; + } + this.Parcelas = null; + this.SelectedDocumento = documento1; + this.NovaApolice = true; + this.AllowEditVendedor = false; + this.AllowEditApolice = true; + this.IsEndosso = true; + base.IsEnabledEditEndosso = true; + base.EnableFields = true; + base.EnableIncluir = false; + this.AllowEditEmissao = true; + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + flag = true; + } + else + { + await base.ShowMessage("PROPOSTA NÃO PODE SER ENDOSSADA. NECESSÁRIO PREENCHER O NÚMERO DA APÓLICE E DATA DE EMISSÃO ANTES DE PROSSEGUIR.", "OK", "", false); + flag = false; + } + return flag; + } + + public void IncluirFatura() + { + long? nullable1; + int numeroParcela; + decimal comissao; + long id; + long? nullable2; + Parcela parcela = ( + from x in this.Parcelas + orderby x.get_NumeroParcela() + select x).LastOrDefault((Parcela x) => x.get_SubTipo() == 1); + if (parcela != null) + { + numeroParcela = parcela.get_NumeroParcela(); + } + else + { + numeroParcela = 0; + } + int num = numeroParcela + 1; + if (parcela != null) + { + comissao = parcela.get_Comissao(); + } + else + { + comissao = decimal.Zero; + } + decimal num1 = comissao; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela != null) + { + id = selectedParcela.get_Id(); + } + else + { + ObservableCollection parcelas = this.Parcelas; + if (parcelas != null) + { + Parcela parcela1 = ( + from x in parcelas + orderby x.get_NumeroParcela() + select x).LastOrDefault((Parcela x) => x.get_SubTipo() == 1); + if (parcela1 != null) + { + nullable2 = new long?(parcela1.get_Id()); + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + } + else + { + nullable1 = null; + nullable2 = nullable1; + } + nullable1 = nullable2; + id = nullable1.GetValueOrDefault(); + } + long num2 = id; + DateTime networkTime = Funcoes.GetNetworkTime(); + Parcela parcela2 = new Parcela(); + parcela2.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + parcela2.set_Documento(this.SelectedDocumento); + parcela2.set_Vencimento(Funcoes.GetNetworkTime().Date); + parcela2.set_Comissao(num1); + parcela2.set_SubTipo(1); + parcela2.set_NumeroParcela(num); + parcela2.set_DataCriacao(new DateTime?(networkTime)); + parcela2.set_UsuarioCriacao(Recursos.Usuario.get_Id()); + this.SelectedParcela = parcela2; + if (num2 == 0) + { + return; + } + List list = ( + from x in this.Repasses + where x.get_Parcela().get_Id() == num2 + select x).ToList(); + list.ForEach((VendedorParcela x) => { + decimal zero; + x.set_Id((long)0); + x.set_Parcela(this.SelectedParcela); + DateTime? nullable = null; + x.set_DataPrePagamento(nullable); + nullable = null; + x.set_DataPagamento(nullable); + VendedorParcela vendedorParcela = x; + if (x.get_Repasse() != null) + { + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + zero = (negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue ? x.get_Repasse().get_ValorNovo() : x.get_Repasse().get_ValorRenovacao()); + } + else + { + zero = decimal.Zero; + } + vendedorParcela.set_PorcentagemRepasse(new decimal?(zero)); + }); + this.Repasses = list; + this.RecalculaRepasse(); + } + + public void IncluirParcelaEspecial() + { + Parcela parcela; + Parcela parcela1 = new Parcela(); + parcela1.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + parcela1.set_Documento(this.SelectedDocumento); + parcela1.set_Vencimento(Funcoes.GetNetworkTime().Date); + parcela1.set_Comissao(new decimal(100)); + parcela1.set_SubTipo(3); + parcela1.set_NumeroParcela(999); + parcela1.set_DataCriacao(new DateTime?(Funcoes.GetNetworkTime())); + parcela1.set_UsuarioCriacao(Recursos.Usuario.get_Id()); + this.SelectedParcela = parcela1; + ObservableCollection parcelas = this.Parcelas; + if (parcelas != null) + { + parcela = parcelas.FirstOrDefault((Parcela x) => x.get_SubTipo() == 1); + } + else + { + parcela = null; + } + Parcela parcela2 = parcela; + if (parcela2 == null) + { + this.Repasses = new List(); + return; + } + List list = ( + from x in this.Repasses + where x.get_Parcela().get_Id() == parcela2.get_Id() + select x).ToList(); + list.ForEach((VendedorParcela x) => { + x.set_Id((long)0); + x.set_Parcela(this.SelectedParcela); + DateTime? nullable = null; + x.set_DataPrePagamento(nullable); + nullable = null; + x.set_DataPagamento(nullable); + x.set_ValorRepasse(new decimal?(new decimal())); + nullable = null; + x.set_DataPagamento(nullable); + }); + this.Repasses = list; + this.RecalculaRepasse(); + } + + private async Task IncluirPropriaCorretora() + { + VendedorParcela vendedorParcela; + Parcela selectedParcela; + if (this.Parcelas.Count != 0) + { + VendedorParcela vendedorParcela1 = this.PropriaCorretora(); + if (this.SelectedParcela.get_SubTipo() != 1 || this.IsFatura) + { + selectedParcela = this.SelectedParcela; + } + else + { + ObservableCollection parcelas = this.Parcelas; + selectedParcela = parcelas.FirstOrDefault((Parcela x) => x.get_NumeroParcela() == 1); + } + Parcela parcela = selectedParcela; + vendedorParcela1.set_Parcela(parcela); + vendedorParcela1.set_Documento(this.SelectedDocumento); + if (parcela == null || parcela.get_Id() != 0) + { + vendedorParcela = await this.Servico.IncluirVendedor(vendedorParcela1); + } + else + { + vendedorParcela = vendedorParcela1; + } + } + else + { + vendedorParcela = null; + } + return vendedorParcela; + } + + public void IncluirVendedor() + { + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Documento(this.SelectedDocumento); + this.SelectedPagamento = vendedorParcela; + } + + public async Task LimparRepasses() + { + bool count; + bool flag; + if (this.Pagamentos != null) + { + ObservableCollection pagamentos = this.Pagamentos; + if (pagamentos != null) + { + count = pagamentos.Count == 0; + } + else + { + count = false; + } + if (!count && this.Repasses != null) + { + List repasses = this.Repasses; + if (repasses != null) + { + flag = repasses.Count == 0; + } + else + { + flag = false; + } + if (!flag && this.SelectedDocumento.get_Id() == 0) + { + if (!base.EnableFields || !this.AllowEditApolice || !this.AlteracaoEnabled) + { + return; + } + else + { + await base.ShowMessage("REPASSES ADICIONADOS NÃO PERTENCEM AO RAMO SELECIONADO E SERÃO EXCLUÍDOS.", "OK", "", false); + this.Pagamentos.Clear(); + this.Repasses.Clear(); + return; + } + } + } + } + } + + public void ManutecaoItens() + { + if (!this.Invoke) + { + return; + } + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(3, "Manutencao"); + } + + public async Task PagamentoVendedor(Parcela parcela) + { + return await this.ParcelaServico.TemPagamento(parcela.get_Id()); + } + + private void PreLoad() + { + this.Ramos = Recursos.Ramos; + this.Seguradoras = Recursos.Seguradoras; + this.Produtos = Recursos.Produtos; + this.Status = Recursos.Status; + this.SeguradorasAnteriores = Recursos.Seguradoras; + this.TipoEndossoList = new ObservableCollection(new List() + { + 0, + 1, + 2, + 4, + 3 + }); + } + + private VendedorParcela PropriaCorretora() + { + VendedorParcela vendedorParcela = new VendedorParcela(); + vendedorParcela.set_Repasse(null); + decimal num = new decimal(); + vendedorParcela.set_ValorRepasse(new decimal?(num)); + vendedorParcela.set_Documento(this.SelectedDocumento); + vendedorParcela.set_Vendedor(Recursos.Vendedores.FirstOrDefault((Vendedor x) => { + long? nullable; + long? nullable1; + long idEmpresa = x.get_IdEmpresa(); + Documento selectedDocumento = this.SelectedDocumento; + if (selectedDocumento != null) + { + Controle controle = selectedDocumento.get_Controle(); + if (controle != null) + { + nullable1 = new long?(controle.get_IdEmpresa()); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable2 = nullable1; + if (idEmpresa != (nullable2.HasValue ? nullable2.GetValueOrDefault() : Recursos.Empresa.get_Id())) + { + return false; + } + return x.get_Corretora(); + })); + num = new decimal(); + vendedorParcela.set_PorcentagemRepasse(new decimal?(num)); + vendedorParcela.set_TipoVendedor(Recursos.TipoVendedor.First((TipoVendedor x) => x.get_Id() == (long)1)); + return vendedorParcela; + } + + public void RecalculaRepasse() + { + List list; + if (!this.IsFatura && this.BaixarParcelas && this.SelectedParcela.get_SubTipo() == 1) + { + return; + } + if (this.Repasses == null || this.Repasses.Count == 0) + { + return; + } + if (this.SelectedParcela.get_Id() == 0) + { + this.Repasses.ForEach((VendedorParcela x) => { + decimal? porcentagemRepasse; + bool valueOrDefault; + decimal? nullable; + bool flag; + if (x.get_DataPagamento().HasValue) + { + return; + } + Gestor.Model.Domain.Seguros.Repasse repasse = x.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Tipo().GetValueOrDefault() == 3 : false); + if (valueOrDefault) + { + return; + } + Parcela parcela = x.get_Parcela() ?? this.SelectedParcela; + parcela.set_Documento(this.SelectedDocumento); + if (x.get_Repasse() != null) + { + Gestor.Model.Domain.Seguros.Repasse repasse1 = x.get_Repasse(); + porcentagemRepasse = x.get_PorcentagemRepasse(); + repasse1.set_ValorNovo((porcentagemRepasse.HasValue ? porcentagemRepasse.GetValueOrDefault() : x.get_Repasse().get_ValorNovo())); + Gestor.Model.Domain.Seguros.Repasse repasse2 = x.get_Repasse(); + porcentagemRepasse = x.get_PorcentagemRepasse(); + repasse2.set_ValorRenovacao((porcentagemRepasse.HasValue ? porcentagemRepasse.GetValueOrDefault() : x.get_Repasse().get_ValorRenovacao())); + } + decimal num = Funcoes.CalculaRepasse(x.get_Repasse(), parcela, true); + VendedorParcela vendedorParcela = x; + if (this.SelectedDocumento.get_NumeroParcelas() > decimal.Zero && !this.SelectedParcela.get_NumeroParcela().Equals(999)) + { + Gestor.Model.Domain.Seguros.Repasse repasse3 = x.get_Repasse(); + flag = (repasse3 != null ? repasse3.get_Forma().GetValueOrDefault() == 3 : false); + if (!flag) + { + nullable = new decimal?(num); + vendedorParcela.set_ValorRepasse(nullable); + x.set_ValorTotal(new decimal?(num)); + return; + } + porcentagemRepasse = x.get_ValorTotal(); + decimal numeroParcelas = this.SelectedDocumento.get_NumeroParcelas(); + if (porcentagemRepasse.HasValue) + { + nullable = new decimal?(porcentagemRepasse.GetValueOrDefault() / numeroParcelas); + vendedorParcela.set_ValorRepasse(nullable); + x.set_ValorTotal(new decimal?(num)); + return; + } + else + { + nullable = null; + vendedorParcela.set_ValorRepasse(nullable); + x.set_ValorTotal(new decimal?(num)); + return; + } + } + nullable = new decimal?(num); + vendedorParcela.set_ValorRepasse(nullable); + x.set_ValorTotal(new decimal?(num)); + }); + this.Pagamentos = new ObservableCollection(this.Repasses); + return; + } + List repasses = this.Repasses; + if (repasses != null) + { + repasses.Where((VendedorParcela x) => { + if (this.SelectedParcela.get_Id() <= (long)0) + { + return false; + } + return x.get_Parcela().get_Id() == this.SelectedParcela.get_Id(); + }).ToList().ForEach((VendedorParcela x) => { + decimal? porcentagemRepasse; + bool valueOrDefault; + decimal? nullable; + VendedorParcela vendedorParcela; + decimal? nullable1; + bool flag; + if (x.get_DataPagamento().HasValue) + { + return; + } + Gestor.Model.Domain.Seguros.Repasse repasse = x.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Tipo().GetValueOrDefault() == 3 : false); + if (valueOrDefault) + { + return; + } + Parcela selectedParcela = this.SelectedParcela; + selectedParcela.set_Documento(this.SelectedDocumento); + if (x.get_Repasse() != null) + { + Gestor.Model.Domain.Seguros.Repasse repasse1 = x.get_Repasse(); + porcentagemRepasse = x.get_PorcentagemRepasse(); + repasse1.set_ValorNovo((porcentagemRepasse.HasValue ? porcentagemRepasse.GetValueOrDefault() : x.get_Repasse().get_ValorNovo())); + Gestor.Model.Domain.Seguros.Repasse repasse2 = x.get_Repasse(); + porcentagemRepasse = x.get_PorcentagemRepasse(); + repasse2.set_ValorRenovacao((porcentagemRepasse.HasValue ? porcentagemRepasse.GetValueOrDefault() : x.get_Repasse().get_ValorRenovacao())); + } + decimal num = Funcoes.CalculaRepasse(x.get_Repasse(), selectedParcela, true); + VendedorParcela vendedorParcela1 = x; + if (this.SelectedDocumento.get_NumeroParcelas() > decimal.Zero && !this.SelectedParcela.get_NumeroParcela().Equals(999)) + { + Gestor.Model.Domain.Seguros.Repasse repasse3 = x.get_Repasse(); + flag = (repasse3 != null ? repasse3.get_Forma().GetValueOrDefault() == 3 : false); + if (!flag) + { + nullable = new decimal?(num); + vendedorParcela1.set_ValorRepasse(nullable); + vendedorParcela = x; + nullable1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1 || this.SelectedParcela.get_SubTipo() != 1 ? x.get_ValorTotal() : new decimal?(num)); + vendedorParcela.set_ValorTotal(nullable1); + return; + } + porcentagemRepasse = x.get_ValorTotal(); + decimal numeroParcelas = this.SelectedDocumento.get_NumeroParcelas(); + if (porcentagemRepasse.HasValue) + { + nullable = new decimal?(porcentagemRepasse.GetValueOrDefault() / numeroParcelas); + vendedorParcela1.set_ValorRepasse(nullable); + vendedorParcela = x; + nullable1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1 || this.SelectedParcela.get_SubTipo() != 1 ? x.get_ValorTotal() : new decimal?(num)); + vendedorParcela.set_ValorTotal(nullable1); + return; + } + else + { + nullable = null; + vendedorParcela1.set_ValorRepasse(nullable); + vendedorParcela = x; + nullable1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1 || this.SelectedParcela.get_SubTipo() != 1 ? x.get_ValorTotal() : new decimal?(num)); + vendedorParcela.set_ValorTotal(nullable1); + return; + } + } + nullable = new decimal?(num); + vendedorParcela1.set_ValorRepasse(nullable); + vendedorParcela = x; + nullable1 = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1 || this.SelectedParcela.get_SubTipo() != 1 ? x.get_ValorTotal() : new decimal?(num)); + vendedorParcela.set_ValorTotal(nullable1); + }); + } + else + { + } + List vendedorParcelas = this.Repasses; + if (vendedorParcelas != null) + { + list = vendedorParcelas.Where((VendedorParcela x) => { + if (this.SelectedParcela.get_Id() <= (long)0) + { + return false; + } + return x.get_Parcela().get_Id() == this.SelectedParcela.get_Id(); + }).ToList(); + } + else + { + list = null; + } + this.Pagamentos = new ObservableCollection(list); + } + + public async void RecalculaRepasses() + { + bool flag; + if (this.Repasses != null) + { + if (this.SelectedDocumento.get_NegocioCorretora().HasValue) + { + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + flag = negocioCorretora.GetValueOrDefault() == 1; + } + else if (this.SelectedDocumento.get_Situacao() != 2 || !this.SelectedDocumento.get_Negocio().HasValue) + { + flag = false; + } + else + { + Negocio? negocio = this.SelectedDocumento.get_Negocio(); + flag = negocio.GetValueOrDefault() == 1; + } + bool flag1 = flag; + List repasses = this.Repasses; + if (repasses != null) + { + repasses.Where((VendedorParcela x) => { + if (this.NovaApolice) + { + return true; + } + return x.get_Parcela().get_SubTipo() == 1; + }).ToList().ForEach((VendedorParcela x) => { + decimal? valorTotal; + decimal numeroParcelas; + decimal? nullable; + decimal valorRenovacao; + decimal? nullable1; + decimal? nullable2; + decimal? nullable3; + bool valueOrDefault; + if (x.get_Parcela() == null) + { + return; + } + if (x.get_Repasse() == null) + { + return; + } + if (x.get_DataPagamento().HasValue) + { + return; + } + Parcela parcela = x.get_Parcela(); + parcela.set_Documento(this.SelectedDocumento); + decimal num = Funcoes.CalculaRepasse(x.get_Repasse(), parcela, true); + VendedorParcela vendedorParcela = x; + if (flag1) + { + Gestor.Model.Domain.Seguros.Repasse repasse = x.get_Repasse(); + valueOrDefault = (repasse != null ? repasse.get_Tipo().GetValueOrDefault() != 3 : true); + if (!valueOrDefault) + { + goto Label1; + } + valorRenovacao = x.get_Repasse().get_ValorRenovacao(); + goto Label0; + } + Label1: + valorRenovacao = x.get_Repasse().get_ValorNovo(); + Label0: + vendedorParcela.set_PorcentagemRepasse(new decimal?(valorRenovacao)); + if (x.get_Repasse().get_Forma().GetValueOrDefault() == 3) + { + valorTotal = x.get_ValorTotal(); + numeroParcelas = this.SelectedDocumento.get_NumeroParcelas(); + if (valorTotal.HasValue) + { + nullable1 = new decimal?(valorTotal.GetValueOrDefault() / numeroParcelas); + } + else + { + nullable = null; + nullable1 = nullable; + } + } + else + { + nullable1 = new decimal?(num); + } + decimal? nullable4 = nullable1; + if (x.get_CoCorretagem()) + { + numeroParcelas = this.SelectedDocumento.get_PremioLiquido(); + decimal? comissaoTotal = this.SelectedDocumento.get_ComissaoTotal(); + decimal comissao = this.SelectedDocumento.get_Comissao(); + nullable = (comissaoTotal.HasValue ? new decimal?(comissaoTotal.GetValueOrDefault() - comissao) : null); + decimal num1 = 100; + if (nullable.HasValue) + { + nullable2 = new decimal?(nullable.GetValueOrDefault() / num1); + } + else + { + comissaoTotal = null; + nullable2 = comissaoTotal; + } + valorTotal = nullable2; + if (valorTotal.HasValue) + { + nullable3 = new decimal?(numeroParcelas * valorTotal.GetValueOrDefault()); + } + else + { + nullable = null; + nullable3 = nullable; + } + nullable4 = nullable3; + } + x.set_ValorRepasse(nullable4); + x.set_ValorTotal(new decimal?(num)); + }); + } + else + { + } + if (!this.NovaApolice) + { + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela == null) + { + selectedParcela = this.Parcelas.FirstOrDefault(); + } + await baseApoliceViewModel.SelecionaParcela(selectedParcela); + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + } + else + { + BaseApoliceViewModel observableCollection = this; + List vendedorParcelas = this.Repasses; + observableCollection.Pagamentos = new ObservableCollection( + from x in vendedorParcelas + orderby x.get_TipoVendedor().get_Id() + select x); + } + } + } + + public async Task RecusarApolice() + { + bool flag; + IList list; + string str; + string str1; + string str2; + if (this.SelectedDocumento != null) + { + bool[] flagArray = await Funcoes.VerificarPagamento(this.SelectedDocumento.get_Id()); + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 23)) + { + bool[] flagArray1 = flagArray; + if (((IEnumerable)flagArray1).Any((bool x) => x)) + { + await base.ShowMessage("NÃO É POSSÍVEL RECURSAR UM APÓLICE ENQUANTO HOUVER RECEBIMENTO DE COMISSÃO OU PAGAMENTO DE VENDEDORES PARA A APÓLICE", "OK", "", false); + str2 = null; + return; + } + } + List configuracaoSistemas = Recursos.Configuracoes; + flag = (!configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 23) ? false : flagArray[1]); + bool flag1 = flag; + if (flag1) + { + flag1 = await base.ShowMessage("EXISTEM PAGAMENTOS PARA OS VENDEDORES DO CONTRATO, DESEJA CRIAR ESTORNOS PARA ESSES PAGAMENTOS?", "SIM", "NÃO", false); + } + bool flag2 = flag1; + Documento documento = await this.Servico.BuscarApoliceAsync(this.DocumentoSelecionado.get_Id(), false, false); + if (documento.get_Controle().get_Documentos().Count > 1) + { + IList documentos = documento.get_Controle().get_Documentos(); + IEnumerable excluido = + from x in documentos + where !x.get_Excluido() + select x; + list = ( + from x in excluido + orderby x.get_Ordem() + select x).ToList(); + } + else + { + list = documento.get_Controle().get_Documentos(); + } + IList documentos1 = list; + if (documentos1.Count > 1) + { + IList documentos2 = documentos1; + if (documentos2.Last((Documento x) => x.get_Situacao() != 7).get_Id() != this.DocumentoSelecionado.get_Id()) + { + await base.ShowMessage("NÃO É POSSÍVEL RECUSAR UM DOCUMENTO ENQUANTO HOUVER ENDOSSOS EM CIMA DO MESMO.", "OK", "", false); + str2 = null; + return; + } + } + if (documento.get_Situacao() != 7) + { + if (this.SelectedDocumento.get_Tipo() != 0 || !string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str = (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice()) ? "O ENDOSSO SELECIONADO" : "A APÓLICE SELECIONADA"); + } + else + { + str = "A PROPOSTA SELECIONADA"; + } + string str3 = str; + string[] newLine = new string[] { "DESEJA REALMENTE RECUSAR ", str3, "? ", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL." }; + if (await base.ShowMessage(string.Concat(newLine), "SIM", "NÃO", false)) + { + str2 = null; + str2 = await base.ShowObservacaoDialog(); + if (str2 != null) + { + base.Loading(true); + await Funcoes.RecusarApolice(this.SelectedDocumento, str2, flag2); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("A PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("A PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("O ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str1 = string.Concat("A APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str4 = str1; + base.RegistrarAcao(string.Concat("RECUSOU ", str4), this.SelectedDocumento.get_Id(), new TipoTela?(2), string.Concat(this.GerarObs(this.SelectedDocumento), Environment.NewLine, "MOTIVO: ", str2)); + base.Loading(false); + } + } + } + else + { + await base.ShowMessage("NÃO É POSSÍVEL RECUSAR UM DOCUMENTO JÁ RECUSADO.", "OK", "", false); + } + } + str2 = null; + } + + private void RemoverVendedor(long id) + { + ((this.SelectedDocumento.get_Id() == 0 || this.SelectedParcela.get_SubTipo() == 1 && !this.IsFatura ? ( + from x in this.Repasses + where x.get_Vendedor().get_Id() == id + select x).ToList() : this.Repasses.Where((VendedorParcela x) => { + if (x.get_Vendedor().get_Id() != id) + { + return false; + } + return x.get_Parcela().get_Id() == this.SelectedParcela.get_Id(); + }).ToList())).ForEach((VendedorParcela x) => this.Repasses.Remove(x)); + ((this.SelectedDocumento.get_Id() == 0 || this.SelectedParcela.get_SubTipo() == 1 && !this.IsFatura ? ( + from x in this.Pagamentos + where x.get_Vendedor().get_Id() == id + select x).ToList() : this.Pagamentos.Where((VendedorParcela x) => { + long num; + if (x.get_Vendedor().get_Id() != id) + { + return false; + } + Parcela parcela = x.get_Parcela(); + num = (parcela != null ? parcela.get_Id() : (long)0); + return num == this.SelectedParcela.get_Id(); + }).ToList())).ForEach((VendedorParcela x) => this.Pagamentos.Remove(x)); + } + + public async Task ReplicarFatura() + { + DateTime? emissao; + int num; + decimal comissao; + DateTime? vigenciaFinal; + DateTime dateTime; + DateTime? nullable1; + DateTime dateTime1; + DateTime date; + decimal valor; + decimal valorLiquidoFatura; + if (this.Parcelas != null) + { + ObservableCollection parcelas = this.Parcelas; + IOrderedEnumerable numeroParcela = + from x in parcelas + orderby x.get_NumeroParcela() + select x; + Parcela parcela = numeroParcela.LastOrDefault((Parcela x) => x.get_SubTipo() == 1); + if (parcela == null || parcela.get_NumeroParcela() != 999) + { + num = (parcela != null ? parcela.get_NumeroParcela() : 0); + int num1 = num + 1; + Parcela selectedParcela = this.SelectedParcela; + if (selectedParcela != null) + { + comissao = selectedParcela.get_Comissao(); + } + else + { + comissao = decimal.Zero; + } + decimal num2 = comissao; + ObservableCollection observableCollection = this.Parcelas; + Parcela parcela1 = observableCollection.First((Parcela x) => x.get_SubTipo() == 1); + DateTime networkTime = Funcoes.GetNetworkTime(); + Parcela parcela2 = parcela1; + if (parcela2 != null) + { + vigenciaFinal = parcela2.get_VigenciaFinal(); + } + else + { + emissao = null; + vigenciaFinal = emissao; + } + DateTime? nullable2 = vigenciaFinal; + dateTime = (nullable2.HasValue ? nullable2.GetValueOrDefault() : networkTime.Date); + DateTime dateTime2 = dateTime; + Parcela parcela3 = parcela1; + if (parcela3 != null) + { + emissao = parcela3.get_Emissao(); + if (emissao.HasValue) + { + DateTime valueOrDefault = emissao.GetValueOrDefault(); + nullable1 = new DateTime?(valueOrDefault.AddMonths(1)); + } + else + { + nullable1 = null; + } + } + else + { + emissao = null; + nullable1 = emissao; + } + nullable2 = nullable1; + dateTime1 = (nullable2.HasValue ? nullable2.GetValueOrDefault() : networkTime.Date); + DateTime dateTime3 = dateTime1; + Parcela parcela4 = parcela1; + if (parcela4 != null) + { + date = parcela4.get_Vencimento().AddMonths(1); + } + else + { + date = networkTime.Date; + } + DateTime dateTime4 = date; + DateTime dateTime5 = dateTime2.AddMonths(1); + Parcela parcela5 = parcela1; + if (parcela5 != null) + { + valor = parcela5.get_Valor(); + } + else + { + valor = decimal.Zero; + } + decimal num3 = valor; + Parcela parcela6 = parcela1; + if (parcela6 != null) + { + valorLiquidoFatura = parcela6.get_ValorLiquidoFatura(); + } + else + { + valorLiquidoFatura = decimal.Zero; + } + decimal num4 = valorLiquidoFatura; + IEnumerable vendedorParcelas = this.Repasses.Where((VendedorParcela x) => { + if (parcela1 == null) + { + return false; + } + return x.get_Parcela().get_Id() == parcela1.get_Id(); + }); + List list = Funcoes.DistinctBy(vendedorParcelas, (VendedorParcela x) => new { Id = x.get_Parcela().get_Id(), vendedor = x.get_Vendedor().get_Id(), tipovendedor = x.get_TipoVendedor().get_Id() }).ToList(); + Parcela parcela7 = new Parcela(); + parcela7.set_IdEmpresa(this.SelectedDocumento.get_Controle().get_IdEmpresa()); + parcela7.set_Documento(this.SelectedDocumento); + parcela7.set_Vencimento(dateTime4); + parcela7.set_Comissao(num2); + parcela7.set_SubTipo(1); + parcela7.set_NumeroParcela(num1); + parcela7.set_VigenciaIncial(new DateTime?(dateTime2)); + parcela7.set_VigenciaFinal(new DateTime?(dateTime5)); + parcela7.set_Valor(num3); + parcela7.set_Emissao(new DateTime?(dateTime3)); + parcela7.set_DataCriacao(new DateTime?(networkTime)); + parcela7.set_ValorLiquidoFatura(num4); + this.SelectedParcela = parcela7; + list.ForEach((VendedorParcela x) => { + decimal zero; + x.set_Id((long)0); + x.set_Parcela(this.SelectedParcela); + DateTime? nullable = null; + x.set_DataPrePagamento(nullable); + nullable = null; + x.set_DataPagamento(nullable); + VendedorParcela vendedorParcela = x; + if (x.get_Repasse() != null) + { + NegocioCorretora? negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + zero = (negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue ? x.get_Repasse().get_ValorNovo() : x.get_Repasse().get_ValorRenovacao()); + } + else + { + zero = decimal.Zero; + } + vendedorParcela.set_PorcentagemRepasse(new decimal?(zero)); + }); + this.Repasses = list; + } + else + { + await base.ShowMessage("PARCELA ESPECIAL NÃO PODE SER REPLICADA.", "OK", "", false); + return; + } + } + this.RecalculaRepasse(); + } + + public async Task>> Salvar(bool critica = false) + { + List> list; + NegocioCorretora? negocioCorretora; + NegocioCorretora? nullable; + bool id; + bool vendedor; + bool updatePremio; + bool flag2; + bool flag3; + List vendedorParcelas; + bool flag4; + Vendedor vendedor1; + Documento documento; + string str; + string str1; + bool valueOrDefault; + long? nullable1; + bool flag5; + NegocioCorretora negocioCorretora1; + string str2; + NegocioCorretora negocioCorretora2; + FormaPagamento formaPagamento; + bool vendedor2; + Negocio negocio; + object obj = null; + if (this.SelectedDocumento.get_Situacao() == 2) + { + Documento selectedDocumento = this.SelectedDocumento; + negocioCorretora = this.SelectedDocumento.get_NegocioCorretora(); + negocio = (negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue ? 2 : 1); + selectedDocumento.set_Negocio(new Negocio?(negocio)); + } + Gestor.Model.Domain.Seguros.Status status = this.SelectedDocumento.get_Status(); + if (status != null) + { + id = status.get_Id() == (long)0; + } + else + { + id = false; + } + if (id) + { + this.SelectedDocumento.set_Status(null); + } + this.ZerarValores(); + Documento selectedDocumento1 = this.SelectedDocumento; + bool isEndosso = this.IsEndosso; + List configuracaoSistemas1 = Recursos.Configuracoes; + List> keyValuePairs1 = selectedDocumento1.Validate(isEndosso, configuracaoSistemas1.Any((ConfiguracaoSistema c) => c.get_Configuracao() == 11)); + if (this.SelectedDocumento.get_Comissao() > new decimal(100)) + { + this.SelectedDocumento.set_Comissao(new decimal(100)); + } + bool id1 = this.SelectedDocumento.get_Id() == (long)0; + VendedorParcela selectedPagamento = this.SelectedPagamento; + if (selectedPagamento != null) + { + vendedor = selectedPagamento.get_Vendedor(); + } + else + { + vendedor = false; + } + if (vendedor && this.SelectedDocumento.get_Vendedores() == null) + { + Documento documento1 = this.SelectedDocumento; + List vendedors = new List() + { + this.TodosVendedores.First((Vendedor x) => { + if (!x.get_Corretora()) + { + return false; + } + return x.get_IdEmpresa() == this.SelectedDocumento.get_Controle().get_IdEmpresa(); + }) + }; + documento1.set_Vendedores(vendedors); + } + if (id1) + { + VendedorParcela vendedorParcela = this.SelectedPagamento; + if (vendedorParcela != null) + { + vendedor2 = vendedorParcela.get_Vendedor(); + } + else + { + vendedor2 = false; + } + if (vendedor2 && this.SelectedDocumento.get_Vendedores() != null) + { + List> keyValuePairs2 = keyValuePairs1; + List> keyValuePairs3 = await this.AdicionarVendedor(); + List> keyValuePairs4 = keyValuePairs2; + List> keyValuePairs5 = keyValuePairs3; + if (keyValuePairs5 == null) + { + keyValuePairs5 = new List>(); + } + keyValuePairs4.AddRange(keyValuePairs5); + keyValuePairs2 = null; + } + } + if (keyValuePairs1.Count <= 0) + { + bool tipo = this.SelectedDocumento.get_Tipo() == 0; + if (tipo) + { + tipo = !await this.VerificarVigencia(this.SelectedDocumento); + } + if (tipo) + { + if (critica) + { + keyValuePairs1.Add(new KeyValuePair("Vigencia2", "VIGENCIANAOACEITA")); + } + list = keyValuePairs1; + } + else if (this.SelectedDocumento.get_TipoEndosso().GetValueOrDefault() == 3 || this.SelectedDocumento.get_Situacao() != 3 || this.SelectedDocumento.get_Id() != 0) + { + if (this.SelectedDocumento.get_TipoEndosso().HasValue && this.SelectedDocumento.get_TipoEndosso().GetValueOrDefault() == 3) + { + this.SelectedDocumento.set_Situacao(4); + } + Documento selectedDocumento2 = this.SelectedDocumento; + base.Alterar(false); + if (!selectedDocumento2.get_FormaPagamento().HasValue) + { + Documento documento2 = selectedDocumento2; + List configuracaoSistemas2 = Recursos.Configuracoes; + formaPagamento = (configuracaoSistemas2.Any((ConfiguracaoSistema y) => y.get_Configuracao() == 21) ? 4 : 0); + documento2.set_FormaPagamento(new FormaPagamento?(formaPagamento)); + } + this.Acesso = 0; + if (selectedDocumento2.get_Id() <= (long)0 || !this.AllowEditApolice) + { + updatePremio = false; + } + else + { + if (!(this.CancelDocumento.get_PremioLiquido() != selectedDocumento2.get_PremioLiquido()) && this.CancelDocumento.get_AdicionalComiss() == selectedDocumento2.get_AdicionalComiss() && (!selectedDocumento2.get_AdicionalComiss() || !(this.CancelDocumento.get_PremioAdicional() != selectedDocumento2.get_PremioAdicional())) && !(this.CancelDocumento.get_Comissao() != selectedDocumento2.get_Comissao())) + { + negocioCorretora = this.CancelDocumento.get_NegocioCorretora(); + nullable = selectedDocumento2.get_NegocioCorretora(); + if (negocioCorretora.GetValueOrDefault() != nullable.GetValueOrDefault() | negocioCorretora.HasValue != nullable.HasValue || this.CancelDocumento.get_Diferenca() != selectedDocumento2.get_Diferenca() || this.CancelDocumento.get_Iof() != selectedDocumento2.get_Iof()) + { + goto Label1; + } + updatePremio = this.UpdatePremio; + goto Label0; + } + Label1: + updatePremio = true; + } + Label0: + bool flag6 = updatePremio; + if (selectedDocumento2.get_TipoRecebimento().GetValueOrDefault() == 2) + { + flag2 = false; + } + else + { + flag2 = (selectedDocumento2.get_Id() == 0 || this.CancelDocumento.get_NumeroParcelas() != selectedDocumento2.get_NumeroParcelas() ? true : selectedDocumento2.get_NumeroParcelas() != this.Parcelas.Count((Parcela x) => x.get_SubTipo() == 1)); + } + bool flag7 = flag2; + nullable = selectedDocumento2.get_NegocioCorretora(); + bool valueOrDefault1 = nullable.GetValueOrDefault() == 1; + if (flag7 && selectedDocumento2.get_TipoRecebimento().GetValueOrDefault() == 1) + { + this.CriarParcelas(id1); + this.Parcelas.ToList().ForEach((Parcela x) => { + x.set_Documento(selectedDocumento2); + List> keyValuePairs = keyValuePairs1; + Parcela parcela = x; + List configuracoes = Recursos.Configuracoes; + Func u003cu003e9_29911 = BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_11; + if (u003cu003e9_29911 == null) + { + u003cu003e9_29911 = (ConfiguracaoSistema y) => y.get_Configuracao() == 9; + BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_11 = u003cu003e9_29911; + } + bool flag = configuracoes.Any(u003cu003e9_29911); + List configuracaoSistemas = Recursos.Configuracoes; + Func u003cu003e9_29912 = BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_12; + if (u003cu003e9_29912 == null) + { + u003cu003e9_29912 = (ConfiguracaoSistema y) => y.get_Configuracao() == 11; + BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_12 = u003cu003e9_29912; + } + bool flag1 = configuracaoSistemas.Any(u003cu003e9_29912); + bool editandoParcela = this.EditandoParcela; + List configuracoes1 = Recursos.Configuracoes; + Func u003cu003e9_29913 = BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_13; + if (u003cu003e9_29913 == null) + { + u003cu003e9_29913 = (ConfiguracaoSistema r) => r.get_Configuracao() == 16; + BaseApoliceViewModel.u003cu003ec.u003cu003e9__299_13 = u003cu003e9_29913; + } + keyValuePairs.AddRange(parcela.Validate(flag, flag1, editandoParcela, configuracoes1.Any(u003cu003e9_29913))); + }); + if (keyValuePairs1.Count > 0) + { + base.Alterar(true); + list = keyValuePairs1.Distinct>().ToList>(); + return list; + } + } + if (this.Parcelas == null || this.Parcelas.Count == 0) + { + this.Pagamentos = new ObservableCollection(); + } + if (flag6 && !flag7) + { + this.AtualizaValores(valueOrDefault1); + } + if (this.SelectedDocumento.get_Situacao() == 5 && this.SelectedDocumento.get_Controle().get_Documentos() != null && this.SelectedDocumento.get_Controle().get_Documentos().Count > 0) + { + IList documentos = this.SelectedDocumento.get_Controle().get_Documentos(); + foreach (Documento documento3 in documentos.Where((Documento x) => { + if (x.get_Tipo() == 0) + { + return false; + } + return !x.get_Excluido(); + })) + { + if (documento3.get_Situacao() == 3) + { + continue; + } + documento3.set_SituacaoAnterior(new TipoSeguro?(documento3.get_Situacao())); + documento3.set_Situacao(5); + await this.Servico.Save(documento3, false, false); + } + } + if (this.SelectedDocumento.get_Id() != 0 && this.SelectedDocumento.get_Tipo() == 0 && this.SelectedDocumento.get_Controle().get_Documentos() != null && this.SelectedDocumento.get_Controle().get_Documentos().Count > 0) + { + IList documentos1 = this.SelectedDocumento.get_Controle().get_Documentos(); + if (documentos1.Where((Documento x) => { + if (x.get_Tipo() == 0) + { + return false; + } + return !x.get_Excluido(); + }).Any((Documento x) => { + if (x.get_Apolice() != this.SelectedDocumento.get_Apolice()) + { + return true; + } + return x.get_Proposta() != this.SelectedDocumento.get_Proposta(); + })) + { + IList documentos2 = this.SelectedDocumento.get_Controle().get_Documentos(); + foreach (Documento documento4 in documentos2.Where((Documento x) => { + if (x.get_Tipo() == 0) + { + return false; + } + return !x.get_Excluido(); + })) + { + documento4.set_Apolice(this.SelectedDocumento.get_Apolice()); + documento4.set_Proposta(this.SelectedDocumento.get_Proposta()); + await this.Servico.Save(documento4, false, false); + base.ToggleSnackBar("NUMERO DA PROPOSTA/APOLICE ATUALIZADOS NO ENDOSSO", true); + } + } + } + if (this.Renovar) + { + nullable = this.CancelDocumento.get_NegocioCorretora(); + if (!nullable.HasValue) + { + Documento cancelDocumento = this.CancelDocumento; + negocioCorretora2 = (!this.CancelDocumento.get_Negocio().HasValue || this.CancelDocumento.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + cancelDocumento.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora2)); + } + this.CancelDocumento.set_Situacao(5); + IList documentos3 = this.CancelDocumento.get_Controle().get_Documentos(); + IEnumerable documentos4 = documentos3.Where((Documento d) => { + if (d.get_Tipo() != 1) + { + return false; + } + if (d.get_Situacao() == 1 || d.get_Situacao() == 2) + { + return true; + } + return d.get_Situacao() == 4; + }); + foreach (Documento documento5 in documentos4) + { + documento5.set_Situacao(5); + await this.Servico.Save(documento5, false, false); + } + this.Servico.Sucesso = true; + await this.Servico.Save(this.CancelDocumento, false, false); + if (!this.Servico.Sucesso) + { + await base.ShowMessage("NÃO FOI POSSÍVEL ALTERAR O STATUS DO DOCUMENTO RENOVADO, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + str2 = (string.IsNullOrEmpty(this.CancelDocumento.get_Apolice()) ? string.Concat("A PROPOSTA \"", this.CancelDocumento.get_Proposta(), "\"") : string.Concat("A APÓLICE \"", this.CancelDocumento.get_Apolice(), "\"")); + string str3 = str2; + base.RegistrarAcao(string.Concat("RENOVOU ", str3), this.CancelDocumento.get_Id(), new TipoTela?(2), this.GerarObs(this.CancelDocumento)); + } + if (selectedDocumento2.get_TipoEndosso().HasValue && selectedDocumento2.get_TipoEndosso().GetValueOrDefault() == 4 && this.SelectedDocumento.get_Vigencia2().HasValue) + { + ApoliceServico servico = this.Servico; + long num = this.SelectedDocumento.get_Controle().get_Id(); + DateTime? vigencia2 = this.SelectedDocumento.get_Vigencia2(); + if (!await servico.Prorrogar(num, vigencia2.Value)) + { + await base.ShowMessage("NÃO FOI POSSÍVEL ALTERAR A VIGÊNCIA FINAL DA APÓLICE, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + } + if (selectedDocumento2.get_TipoEndosso().HasValue && selectedDocumento2.get_TipoEndosso().GetValueOrDefault() == 3) + { + if (!await this.Servico.Reabilitar(this.SelectedDocumento.get_Controle().get_Id())) + { + await base.ShowMessage("NÃO FOI POSSÍVEL ALTERAR O STATUS DA APÓLICE, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + } + if (selectedDocumento2.get_TipoEndosso().HasValue && selectedDocumento2.get_TipoEndosso().GetValueOrDefault() == 2) + { + IList documentos5 = this.CancelDocumento.get_Controle().get_Documentos(); + Documento documento6 = documentos5.FirstOrDefault((Documento x) => x.get_Tipo() == 0); + documento6.set_Situacao(3); + IList documentos6 = this.CancelDocumento.get_Controle().get_Documentos(); + IEnumerable tipo1 = + from x in documentos6 + where x.get_Tipo() == 1 + select x; + foreach (Documento documento7 in tipo1) + { + documento7.set_Situacao(3); + await this.Servico.Save(documento7, false, false); + } + nullable = documento6.get_NegocioCorretora(); + if (!nullable.HasValue) + { + Documento documento8 = documento6; + negocioCorretora1 = (!documento6.get_Negocio().HasValue || documento6.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + documento8.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora1)); + } + selectedDocumento2.set_Situacao(3); + this.Servico.Sucesso = true; + await this.Servico.Save(documento6, false, false); + if (!this.Servico.Sucesso) + { + await base.ShowMessage("NÃO FOI POSSÍVEL ALTERAR O STATUS DO DOCUMENTO CANCELADO, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + tipo = id1; + if (tipo) + { + tipo = await base.ShowMessage("DESEJA BAIXAR AS PARCELAS PENDENTES ABAIXO DESSE DOCUMENTO?", "SIM", "NÃO", false); + } + if (tipo) + { + bool flag8 = true; + foreach (Documento documento9 in documento6.get_Controle().get_Documentos()) + { + tipo = await this.Servico.BaixarParcelasCancelamento(documento9, false); + flag8 = tipo & flag8; + } + if (!flag8) + { + await base.ShowMessage("NÃO FOI POSSÍVEL AS PARCELAS DO DOCUMENTO CANCELADO, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + } + string str4 = string.Concat("A APÓLICE \"", documento6.get_Apolice(), "\""); + base.RegistrarAcao(string.Concat("CANCELOU ", str4), documento6.get_Id(), new TipoTela?(2), this.GerarObs(documento6)); + documento6 = null; + } + if (this.Parcelas != null) + { + Documento documento10 = selectedDocumento2; + ObservableCollection parcelas = this.Parcelas; + documento10.set_Parcelas(new ObservableCollection( + from x in parcelas + where x.get_SubTipo() == 1 + select x)); + } + if (!string.IsNullOrWhiteSpace(this.Anotacoes)) + { + Documento documento11 = selectedDocumento2; + object[] nome = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), Funcoes.GetNetworkTime(), Environment.NewLine, this.Anotacoes, Environment.NewLine, Environment.NewLine, selectedDocumento2.get_Observacao() }; + documento11.set_Observacao(string.Format("{0}, ID: {1}, {2:g}{3}{4}{5}{6}{7}", nome)); + } + Documento documentoSelecionado = this.DocumentoSelecionado; + if (documentoSelecionado != null) + { + documentoSelecionado.get_Situacao(); + flag3 = true; + } + else + { + flag3 = false; + } + if (flag3 && this.DocumentoSelecionado.get_Situacao() == 7 && this.DocumentoSelecionado.get_Situacao() != selectedDocumento2.get_Situacao()) + { + ObservableCollection observableCollection = selectedDocumento2.get_Parcelas(); + if (observableCollection != null) + { + flag5 = ( + from x in observableCollection + where x.get_DataRecebimento().HasValue + select x).Count() >= 1; + } + else + { + flag5 = false; + } + if (flag5) + { + await base.ShowMessage("O DOCUMENTO TEM PARCELAS BAIXADAS DEVIDO A RECUSA. CASO NECESSÁRIO, REALIZE A EXCLUSÃO DAS BAIXAS MANUALMENTE.", "OK", "", false); + base.Alterar(true); + list = null; + return list; + } + } + this.Servico.Sucesso = true; + if (selectedDocumento2.get_Id() == 0) + { + selectedDocumento2.set_DataCriacao(new DateTime?(Funcoes.GetNetworkTime())); + selectedDocumento2.set_UsuarioCriacao(Recursos.Usuario); + } + selectedDocumento2.set_SituacaoAnterior(new TipoSeguro?(selectedDocumento2.get_Situacao())); + Documento documento12 = await this.Servico.Save(selectedDocumento2, flag6, flag7); + Documento documento13 = documento12; + ObservableCollection pagamentos = this.Pagamentos; + if (pagamentos != null) + { + vendedorParcelas = pagamentos.Where((VendedorParcela p) => { + if (documento13.get_TipoRecebimento().GetValueOrDefault() != 1 || p.get_Repasse() == null || p.get_Repasse().get_Base().GetValueOrDefault() != 1 && p.get_Repasse().get_Base().GetValueOrDefault() != 4 && p.get_Repasse().get_Base().GetValueOrDefault() != 5) + { + return false; + } + return !p.get_DataPagamento().HasValue; + }).ToList(); + } + else + { + vendedorParcelas = null; + } + List vendedorParcelas1 = vendedorParcelas; + if (vendedorParcelas1 != null && vendedorParcelas1.Count > 0) + { + List vendedorParcelas2 = new List(); + if (vendedorParcelas1 != null) + { + vendedorParcelas1.ForEach((VendedorParcela p) => { + DateTime? dataPrePagamento; + DateTime? emissao; + BaseRepasse? @base = p.get_Repasse().get_Base(); + if (@base.HasValue) + { + switch (@base.GetValueOrDefault()) + { + case 1: + { + dataPrePagamento = p.get_DataPrePagamento(); + DateTime vigencia1 = documento13.get_Vigencia1(); + if ((dataPrePagamento.HasValue ? dataPrePagamento.GetValueOrDefault() == vigencia1 : false)) + { + return; + } + p.set_DataPrePagamento(new DateTime?(documento13.get_Vigencia1())); + vendedorParcelas2.Add(p); + return; + } + case 2: + case 3: + { + break; + } + case 4: + { + dataPrePagamento = p.get_DataPrePagamento(); + emissao = documento13.get_Emissao(); + if ((dataPrePagamento.HasValue == emissao.HasValue ? (dataPrePagamento.HasValue ? dataPrePagamento.GetValueOrDefault() == emissao.GetValueOrDefault() : true) : false)) + { + return; + } + p.set_DataPrePagamento(documento13.get_Emissao()); + vendedorParcelas2.Add(p); + return; + } + case 5: + { + emissao = p.get_DataPrePagamento(); + dataPrePagamento = documento13.get_Remessa(); + if ((emissao.HasValue == dataPrePagamento.HasValue ? (emissao.HasValue ? emissao.GetValueOrDefault() == dataPrePagamento.GetValueOrDefault() : true) : false)) + { + return; + } + p.set_DataPrePagamento(documento13.get_Remessa()); + vendedorParcelas2.Add(p); + break; + } + default: + { + return; + } + } + } + }); + } + if (vendedorParcelas2.Count > 0) + { + await (new Gestor.Application.Servicos.ParcelaServico()).SaveRange(vendedorParcelas2.ToList()); + } + } + if (this.Servico.Sucesso) + { + Documento documentoSelecionado1 = this.DocumentoSelecionado; + if (documentoSelecionado1 != null) + { + documentoSelecionado1.get_Situacao(); + flag4 = true; + } + else + { + flag4 = false; + } + if (flag4 && this.DocumentoSelecionado.get_Situacao() == 7 && selectedDocumento2.get_Situacao() != this.DocumentoSelecionado.get_Situacao()) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(21, ""); + } + else + { + } + } + this.SelectedDocumento = await this.Servico.BuscarApoliceAsync(documento13.get_Id(), false, false); + this.SelectedDocumento.Initialize(); + await this.CarregarParcelas(this.SelectedDocumento); + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + this.SelectedParcela = this.Parcelas.FirstOrDefault(); + Documento selectedDocumento3 = this.SelectedDocumento; + List repasses = this.Repasses; + VendedorParcela vendedorParcela1 = repasses.FirstOrDefault((VendedorParcela x) => x.get_TipoVendedor().get_Id() == (long)1); + if (vendedorParcela1 != null) + { + vendedor1 = vendedorParcela1.get_Vendedor(); + } + else + { + vendedor1 = null; + } + selectedDocumento3.set_VendedorPrincipal(vendedor1); + bool renovar = this.Renovar; + documento = (renovar ? this.DocumentoRenovado : ConsultaViewModel.DocumentoSelecionado); + ConsultaViewModel.DocumentoRenovado = documento; + this.NovaApolice = false; + this.Renovar = false; + if (id1) + { + this.AllowEditApolice = true; + base.IsEnabledEdit = true; + base.IsEnabledEditEndosso = true; + if (this.Invoke) + { + ConsultaViewModel.DocumentoSelecionado = this.SelectedDocumento; + } + if (this.Invoke) + { + Action recarregarDocumentos = Gestor.Application.Actions.Actions.RecarregarDocumentos; + if (recarregarDocumentos != null) + { + recarregarDocumentos(this.SelectedDocumento); + } + else + { + } + } + if (this.Invoke) + { + Action updateDocumento = Gestor.Application.Actions.Actions.UpdateDocumento; + if (updateDocumento != null) + { + updateDocumento(this.SelectedDocumento); + } + else + { + } + } + } + else if (this.Invoke) + { + long num1 = this.SelectedDocumento.get_Id(); + Documento documentoSelecionado2 = ConsultaViewModel.DocumentoSelecionado; + if (documentoSelecionado2 != null) + { + nullable1 = new long?(documentoSelecionado2.get_Id()); + } + else + { + nullable1 = null; + } + long? nullable2 = nullable1; + if (num1 != nullable2.GetValueOrDefault() | !nullable2.HasValue) + { + ConsultaViewModel.DocumentoSelecionado = this.SelectedDocumento; + } + } + if (this.Parcelas.Count == 0) + { + this.AllowEditVendedor = false; + } + base.AllowEditParcela = true; + base.ToggleSnackBar("DOCUMENTO SALVO COM SUCESSO", true); + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(true); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(true); + } + else + { + } + if (renovar) + { + if (await base.ShowMessage("DESEJA MANTER OS DADOS DO PERFIL DA APÓLICE ANTERIOR?", "SIM", "NÃO", false)) + { + List perfils = await this.PerfilServico.BuscarPerfis(this.CancelDocumento.get_Controle().get_Id()); + int num2 = 0; + try + { + foreach (Perfil perfil in perfils.ToList()) + { + Perfil perfil1 = new Perfil(); + perfil1.set_Id((long)0); + perfil1.set_AntiFurto(perfil.get_AntiFurto()); + perfil1.set_CepCirculacao(Gestor.Model.Helper.ValidationHelper.FormataCep(perfil.get_CepCirculacao())); + perfil1.set_CepPernoite(Gestor.Model.Helper.ValidationHelper.FormataCep(perfil.get_CepPernoite())); + perfil1.set_Cliente(perfil.get_Cliente()); + Controle controle = new Controle(); + controle.set_AssistenciaId(perfil.get_Controle().get_AssistenciaId()); + controle.set_Cliente(perfil.get_Controle().get_Cliente()); + controle.set_Documentos(perfil.get_Controle().get_Documentos()); + controle.set_Id(this.SelectedDocumento.get_Controle().get_Id()); + controle.set_IdEmpresa(perfil.get_Controle().get_IdEmpresa()); + controle.set_Item(perfil.get_Controle().get_Item()); + controle.set_Produto(perfil.get_Controle().get_Produto()); + controle.set_Ramo(perfil.get_Controle().get_Ramo()); + controle.set_Seguradora(perfil.get_Controle().get_Seguradora()); + controle.set_SeguradoraAnterior(perfil.get_Controle().get_SeguradoraAnterior()); + perfil1.set_Controle(controle); + perfil1.set_Cpf(perfil.get_Cpf()); + perfil1.set_DistanciaResidenciaTrabalho(perfil.get_DistanciaResidenciaTrabalho()); + perfil1.set_EstadoCivil(perfil.get_EstadoCivil()); + perfil1.set_EstenderCobertura(perfil.get_EstenderCobertura()); + perfil1.set_GaragemEstudo(perfil.get_GaragemEstudo()); + perfil1.set_GaragemResidencia(perfil.get_GaragemResidencia()); + perfil1.set_GaragemTrabalho(perfil.get_GaragemTrabalho()); + perfil1.set_Habilitacao(perfil.get_Habilitacao()); + perfil1.set_Isencao(perfil.get_Isencao()); + perfil1.set_KmMensal(perfil.get_KmMensal()); + perfil1.set_Nascimento(perfil.get_Nascimento()); + perfil1.set_Nome(perfil.get_Nome()); + perfil1.set_Ocupacao(perfil.get_Ocupacao()); + perfil1.set_Relacao(perfil.get_Relacao()); + perfil1.set_SeguroVida(perfil.get_SeguroVida()); + perfil1.set_Sexo(perfil.get_Sexo()); + perfil1.set_TempoHabilitacao(perfil.get_TempoHabilitacao()); + perfil1.set_TipoResidencia(perfil.get_TipoResidencia()); + perfil1.set_UsoDependentes(perfil.get_UsoDependentes()); + perfil1.set_UsoProfissional(perfil.get_UsoProfissional()); + perfil1.set_VeiculoResidencia(perfil.get_VeiculoResidencia()); + await this.PerfilServico.Save(perfil1); + } + } + catch (Exception exception) + { + obj = exception; + num2 = 1; + } + if (num2 == 1) + { + Exception exception1 = (Exception)obj; + await base.ShowMessage("NÃO FOI POSSÍVEL MANTER OS DADOS DO PERFIL DA APÓLICE ANTERIOR, POR FAVOR VERIFIQUE APÓS O PROCEDIMENTO SER CONCLUÍDO.", "OK", "", false); + } + obj = null; + } + } + this.CancelDocumento = (Documento)this.SelectedDocumento.Clone(); + BaseApoliceViewModel baseApoliceViewModel = this; + str = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? "EDITAR FATURAS" : "EDITAR PARCELAS"); + baseApoliceViewModel.EditarParcelasLabel = str; + base.EnableFields = false; + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + string str5 = (id1 ? "INCLUIU" : "ALTEROU"); + if (this.SelectedDocumento.get_Tipo() == 0 && string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = string.Concat("A PROPOSTA \"", this.SelectedDocumento.get_Proposta(), "\""); + } + else if (this.SelectedDocumento.get_Tipo() != 0 || string.IsNullOrEmpty(this.SelectedDocumento.get_Apolice())) + { + str1 = (string.IsNullOrEmpty(this.SelectedDocumento.get_Endosso()) ? string.Concat("A PROPOSTA DE ENDOSSO \"", this.SelectedDocumento.get_PropostaEndosso(), "\"") : string.Concat("O ENDOSSO \"", this.SelectedDocumento.get_Endosso(), "\"")); + } + else + { + str1 = string.Concat("A APÓLICE \"", this.SelectedDocumento.get_Apolice(), "\""); + } + string str6 = str1; + base.RegistrarAcao(string.Concat(str5, " ", str6), this.SelectedDocumento.get_Id(), new TipoTela?(2), this.GerarObs(this.SelectedDocumento)); + if (renovar) + { + valueOrDefault = true; + } + else if (!this.IsEndosso) + { + valueOrDefault = false; + } + else + { + TipoEndosso? tipoEndosso = this.SelectedDocumento.get_TipoEndosso(); + valueOrDefault = tipoEndosso.GetValueOrDefault() != 2; + } + if (valueOrDefault & id1) + { + Action action = Gestor.Application.Actions.Actions.AcessaTela; + if (action != null) + { + action(3, (renovar ? "Renovação" : "Endosso")); + } + else + { + } + list = null; + } + else if (this.SelectedDocumento.get_TipoEndosso().GetValueOrDefault() != 2) + { + tipo = (!this.Invoke ? true : !id1); + if (!tipo) + { + tipo = !await base.ShowMessage("DESEJA INCLUIR O ITEM AGORA?", "SIM", "NÃO", false); + } + if (!tipo) + { + Action acessaTela1 = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela1 != null) + { + acessaTela1(3, ""); + } + else + { + } + list = null; + } + else + { + list = null; + } + } + else + { + list = null; + } + } + else + { + base.Alterar(true); + list = null; + } + } + else + { + await base.ShowMessage("EM DOCUMENTOS CANCELADOS SÓ É POSSIVEL INCLUIR ENDOSSO DE REABILITAÇÃO.", "OK", "", false); + base.Alterar(true); + list = null; + } + } + else + { + list = keyValuePairs1; + } + return list; + } + + public async Task>> SalvarParcelas(int tipo) + { + List> keyValuePairs; + decimal num; + int num1; + bool flag; + if (this.SelectedParcela.get_Documento() == null) + { + this.SelectedParcela.set_Documento(this.SelectedDocumento); + } + this.SelectedParcela.get_Documento().set_Parcelas(this.Parcelas); + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 && this.SelectedParcela.get_SubTipo() == 1 && this.SelectedParcela.get_Comissao() == decimal.Zero) + { + this.SelectedParcela.set_Comissao(this.SelectedDocumento.get_Comissao()); + } + Parcela selectedParcela = this.SelectedParcela; + List configuracoes = Recursos.Configuracoes; + bool flag1 = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 9); + List configuracaoSistemas = Recursos.Configuracoes; + bool flag2 = configuracaoSistemas.Any((ConfiguracaoSistema y) => y.get_Configuracao() == 11); + bool editandoParcela = this.EditandoParcela; + List configuracoes1 = Recursos.Configuracoes; + List> keyValuePairs1 = selectedParcela.Validate(flag1, flag2, editandoParcela, configuracoes1.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 16)); + keyValuePairs1.AddRange(this.ValidaParcelaEspecial(tipo)); + num = (this.SelectedParcela.get_ValorExtrato() == decimal.Zero ? this.SelectedParcela.get_ValorLiquidoFatura() : this.SelectedParcela.get_ValorExtrato()); + decimal num2 = num; + num1 = (num2 > decimal.Zero ? num2.CompareTo(this.SelectedParcela.get_ValorComissao()) : this.SelectedParcela.get_ValorComissao().CompareTo(num2)); + int num3 = num1; + flag = (keyValuePairs1.Count != 1 || 2 != this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() ? false : num3 < 0); + bool flag3 = flag; + if (flag3) + { + flag3 = await base.ShowMessage("VALOR RECEBIMENTO MAIOR QUE VALOR PARCELA, CONTINUAR?", "SIM", "NÃO", false); + } + if (flag3) + { + keyValuePairs1.Clear(); + } + if (keyValuePairs1.Count <= 0) + { + this.SelectedParcela.set_Baixando(false); + List configuracaoSistemas1 = Recursos.Configuracoes; + if (!configuracaoSistemas1.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 5) && (this.SelectedParcela.get_Iss() > decimal.Zero || this.SelectedParcela.get_Irr() > decimal.Zero || this.SelectedParcela.get_Outros() > decimal.Zero || this.SelectedParcela.get_Desconto() > decimal.Zero)) + { + this.SelectedParcela.set_Iss(decimal.Zero); + this.SelectedParcela.set_Irr(decimal.Zero); + this.SelectedParcela.set_Outros(decimal.Zero); + this.SelectedParcela.set_Desconto(decimal.Zero); + this.SelectedParcela.set_ValorComDesconto(this.SelectedParcela.get_ValorComissao()); + } + switch (tipo) + { + case 1: + { + await this.AlterarVencimento(); + break; + } + case 2: + { + await this.BaixarComissao(); + break; + } + case 3: + case 4: + { + await this.AdicionarParcelaEspecial(); + break; + } + } + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + public async void Seleciona(Documento documento) + { + base.Loading(true); + await base.PermissaoTela(2); + await base.PermissaoTela(5); + if (documento == null || (object)documento != (object)this.SelectedDocumento) + { + await this.SelecionaDocumento(documento); + } + Action redimencionar = Gestor.Application.Actions.Actions.Redimencionar; + if (redimencionar != null) + { + redimencionar(this.Invoke); + } + else + { + } + base.Loading(false); + } + + public async Task SelecionaDocumento(Documento documento) + { + long? nullable; + base.Loading(true); + base.IsEnabled = false; + await this.BuscarVendedores(false); + List estipulantes = await (new BaseServico()).BuscarEstipulantes(); + BaseApoliceViewModel list = this; + IEnumerable estipulantes1 = estipulantes.Where((Estipulante x) => { + if (documento == null) + { + return x.get_IdEmpresa() == Recursos.Usuario.get_IdEmpresa(); + } + if (x.get_IdEmpresa() != documento.get_Controle().get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }); + list.Estipulantes = ( + from x in estipulantes1 + orderby x.get_Nome() + select x).ToList(); + this.SelectedDocumento = null; + this.PreLoad(); + if (documento != null) + { + await this.WorkOnSelectedDocumento(documento); + if (this.Invoke) + { + long id = this.SelectedDocumento.get_Id(); + Documento documentoSelecionado = ConsultaViewModel.DocumentoSelecionado; + if (documentoSelecionado != null) + { + nullable = new long?(documentoSelecionado.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + if (id != nullable1.GetValueOrDefault() | !nullable1.HasValue) + { + ConsultaViewModel.DocumentoSelecionado = this.SelectedDocumento; + } + } + if (this.Acesso == 1 && this.ParcelaSelecionada != 0) + { + await this.SelecionaParcela(this.Parcelas.FirstOrDefault((Parcela x) => x.get_Id() == this.ParcelaSelecionada)); + } + if (this.Invoke) + { + this.Loaded = true; + } + base.IsEnabled = true; + base.Loading(false); + } + else + { + base.EnableFields = false; + base.Loading(false); + } + } + + public async Task SelecionaParcela(Parcela parcela) + { + bool flag; + bool flag1; + this.SelectedParcela = parcela; + if (parcela != null && parcela.get_Id() != 0 && this.SelectedDocumento != null) + { + if (this.Repasses == null) + { + await this.CarregaRepasse(this.SelectedDocumento.get_Id()); + } + List list = ( + from x in this.Repasses + where x.get_Parcela().get_Id() == parcela.get_Id() + select x).ToList(); + if (this.IsFatura || parcela.get_SubTipo() != 1) + { + BaseApoliceViewModel baseApoliceViewModel = this; + flag = (parcela.get_DataRecebimento().HasValue ? false : list.All((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != parcela.get_Id()) + { + return false; + } + return !x.get_DataPagamento().HasValue; + })); + baseApoliceViewModel.AllowEditVendedor = flag; + } + if (!this.IsFatura && parcela.get_SubTipo() == 1) + { + BaseApoliceViewModel baseApoliceViewModel1 = this; + if (parcela.get_NumeroParcela() != 1 || parcela.get_DataRecebimento().HasValue) + { + flag1 = false; + } + else + { + List vendedorParcelas = list; + flag1 = vendedorParcelas.All((VendedorParcela x) => { + if (x.get_Parcela().get_SubTipo() != 1) + { + return false; + } + return !x.get_DataPagamento().HasValue; + }); + } + baseApoliceViewModel1.AllowEditVendedor = flag1; + } + BaseApoliceViewModel observableCollection = this; + List vendedorParcelas1 = list; + observableCollection.Pagamentos = new ObservableCollection( + from x in vendedorParcelas1 + orderby x.get_TipoVendedor().get_Id() + select x); + } + } + + public void SelecionaPrimeiraParcela() + { + this.SelectedParcela = this.SelectedParcela ?? this.Parcelas.FirstOrDefault(); + } + + public async Task SelecionarParcelaBaixa() + { + bool flag; + decimal num; + decimal num1; + Parcela parcela; + if (this.SelectedParcela == null || this.SelectedDocumento == null) + { + flag = false; + } + else if (this.SelectedParcela.get_SubTipo() != 1 && !this.SelectedParcela.get_DataRecebimento().HasValue) + { + Parcela selectedParcela = this.SelectedParcela; + decimal premioLiquido = this.SelectedDocumento.get_PremioLiquido(); + num1 = (this.SelectedDocumento.get_NumeroParcelas() > decimal.Zero ? this.SelectedDocumento.get_NumeroParcelas() : decimal.One); + selectedParcela.set_ValorLiquidoFatura(premioLiquido / num1); + this.SelectedParcela.set_Baixando(true); + flag = true; + } + else if (this.IsFatura && !this.SelectedParcela.get_DataRecebimento().HasValue) + { + this.SelectedParcela.set_Baixando(true); + flag = true; + } + else if (this.Parcelas == null || !this.Parcelas.Any()) + { + flag = false; + } + else + { + ObservableCollection parcelas = this.Parcelas; + IOrderedEnumerable numeroParcela = + from x in parcelas + orderby x.get_NumeroParcela() + select x; + parcela = numeroParcela.FirstOrDefault((Parcela x) => { + if (x.get_DataRecebimento().HasValue) + { + return false; + } + return x.get_SubTipo() == 1; + }); + if (parcela != null && !this.IsFatura && this.SelectedDocumento.get_NumeroParcelas() > decimal.Zero) + { + Parcela parcela1 = parcela; + num = (this.SelectedDocumento.get_AdicionalComiss() ? (this.SelectedDocumento.get_PremioLiquido() + this.SelectedDocumento.get_PremioAdicional()) / this.SelectedDocumento.get_NumeroParcelas() : this.SelectedDocumento.get_PremioLiquido() / this.SelectedDocumento.get_NumeroParcelas()); + parcela1.set_ValorLiquidoFatura(num); + } + BaseApoliceViewModel baseApoliceViewModel = this; + Parcela selectedParcela1 = parcela; + if (selectedParcela1 == null) + { + selectedParcela1 = this.SelectedParcela; + } + baseApoliceViewModel.SelectedParcela = selectedParcela1; + if (parcela == null) + { + await base.ShowMessage("NÃO HÁ MAIS NENHUMA PARCELA A SER BAIXADA", "OK", "", false); + } + if (parcela != null) + { + this.SelectedParcela.set_Baixando(true); + } + flag = parcela != null; + } + parcela = null; + return flag; + } + + public void SelecionarVendedor() + { + VendedorParcela vendedorParcela; + ObservableCollection pagamentos = this.Pagamentos; + if (pagamentos != null) + { + vendedorParcela = pagamentos.FirstOrDefault(); + } + else + { + vendedorParcela = null; + } + this.SelectedPagamento = vendedorParcela; + } + + public void ToggleSeguradoraAnterior(TipoSeguro situacao) + { + if (situacao != 2) + { + this.IsRenovacaoVisibility = Visibility.Collapsed; + return; + } + this.IsRenovacaoVisibility = Visibility.Visible; + } + + private List> ValidaParcelaEspecial(int tipo) + { + List> keyValuePairs = new List>(); + if (tipo == 4 && this.SelectedParcela.get_SubTipo() == 1) + { + keyValuePairs.Add(new KeyValuePair("SubTipo|TIPO", "A PARCELA ESPECIAL NÃO PODE SER DO TIPO PARCELA NORMAL")); + } + return keyValuePairs; + } + + public List> Validate(VendedorParcela pagamento) + { + long? nullable; + bool count; + List> keyValuePairs = new List>(); + if (pagamento == null || this.SelectedDocumento == null) + { + keyValuePairs.Add(new KeyValuePair("pagamento|PAGAMENTO", "ERRO AO INSERIR VENDEDOR.")); + return keyValuePairs; + } + if (pagamento.get_TipoVendedor() == null || pagamento.get_Vendedor() == null) + { + return keyValuePairs; + } + if (this.Repasses == null) + { + this.Repasses = new List(); + } + if (this.Repasses.Count > 0) + { + if (this.Repasses.All((VendedorParcela x) => x.get_Parcela() == null)) + { + if (this.SelectedDocumento.get_Id() > (long)0) + { + ObservableCollection parcelas = this.Parcelas; + if (parcelas != null) + { + count = parcelas.Count > 0; + } + else + { + count = false; + } + if (count) + { + keyValuePairs.Add(new KeyValuePair("|PARCELA", "PARCELA DEVE SER SELECIONADA PARA A INCLUSÃO DO VENDEDOR.")); + return keyValuePairs; + } + } + if (this.SelectedDocumento.get_Tipo() != 1) + { + goto Label1; + } + keyValuePairs.Add(new KeyValuePair("|PARCELA", "PARCELA DEVE SER SELECIONADA PARA A INCLUSÃO DO VENDEDOR.")); + return keyValuePairs; + } + Label1: + IEnumerable vendedorParcelas = this.Repasses.Where((VendedorParcela x) => { + if (x.get_Parcela().get_SubTipo() != 1) + { + return false; + } + decimal? porcentagemRepasse = x.get_PorcentagemRepasse(); + if ((porcentagemRepasse.GetValueOrDefault() == 100) & porcentagemRepasse.HasValue) + { + return false; + } + return pagamento.get_Repasse().get_Forma().GetValueOrDefault() == 1; + }); + decimal num = vendedorParcelas.Sum((VendedorParcela x) => x.get_ValorRepasse().GetValueOrDefault()) + pagamento.get_ValorRepasse().GetValueOrDefault(); + decimal num1 = ((this.SelectedDocumento.get_AdicionalComiss() ? this.SelectedDocumento.get_PremioLiquido() + this.SelectedDocumento.get_PremioAdicional() : this.SelectedDocumento.get_PremioLiquido()) * this.SelectedDocumento.get_Comissao()) * new decimal(1, 0, 0, false, 2); + if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 15) && Math.Abs(num) > (Math.Abs(num1) + this.Tolerancia)) + { + keyValuePairs.Add(new KeyValuePair("ValorRepasse|VALOR DO REPASSE", "O TOTAL DE COMISSÃO PAGA NÃO PODE SER SUPERIOR A COMISSÃO PREVISTA PARA RECEBIMENTO.")); + } + if (this.Repasses.Where((VendedorParcela vendedorParcela) => { + if (vendedorParcela.get_Repasse() == null) + { + return false; + } + return vendedorParcela.get_Repasse().get_Tipo().GetValueOrDefault() != 3; + }).Any((VendedorParcela x) => { + if (x.get_TipoVendedor().get_Id() != pagamento.get_TipoVendedor().get_Id() || x.get_Vendedor().get_Corretora()) + { + return false; + } + return x.get_Parcela().get_SubTipo() == 1; + })) + { + keyValuePairs.Add(new KeyValuePair("TipoVendedor|TIPO VENDEDOR", string.Concat("JÁ EXISTE UM VENDEDOR DO TIPO ", pagamento.get_TipoVendedor().get_Descricao(), " ADICIONADO AO DOCUMENTO."))); + } + if (this.Repasses.Any((VendedorParcela x) => { + if (x.get_Vendedor().get_Id() != pagamento.get_Vendedor().get_Id()) + { + return false; + } + return x.get_Parcela().get_SubTipo() == 1; + })) + { + keyValuePairs.Add(new KeyValuePair("Nome|VENDEDOR", string.Concat("VENDEDOR ", pagamento.get_Vendedor().get_Nome(), " JÁ ADICIONADO AO DOCUMENTO."))); + } + } + long id = pagamento.get_Vendedor().get_Id(); + Gestor.Model.Domain.Seguros.Repasse repasse = pagamento.get_Repasse(); + if (repasse != null) + { + nullable = new long?(repasse.get_Vendedor().get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + if (id != nullable1.GetValueOrDefault() | !nullable1.HasValue) + { + keyValuePairs.Add(new KeyValuePair("ValorRepasse|VALOR DO REPASSE", "PERCENTUAL DE REPASSE DEVE SER SELECIONADO")); + } + return keyValuePairs; + } + + public List> ValidateEspecial(VendedorParcela pagamento) + { + decimal? nullable2; + List> keyValuePairs = new List>(); + if (this.SelectedParcela == null) + { + keyValuePairs.Add(new KeyValuePair("SelectedParcela|PARCELA", "PARCELA DEVE SER SELECIONADA PARA A INCLUSÃO DO VENDEDOR.")); + return keyValuePairs; + } + if (this.Repasses == null) + { + this.Repasses = new List(); + } + decimal? nullable3 = ( + from x in this.Repasses + where x.get_Parcela().get_Id() == pagamento.get_Parcela().get_Id() + select x).Sum((VendedorParcela x) => x.get_ValorRepasse()); + decimal? valorRepasse = pagamento.get_ValorRepasse(); + if (nullable3.HasValue & valorRepasse.HasValue) + { + nullable2 = new decimal?(nullable3.GetValueOrDefault() + valorRepasse.GetValueOrDefault()); + } + else + { + nullable2 = null; + } + decimal? nullable4 = nullable2; + decimal valor = this.SelectedParcela.get_Valor(); + decimal num = (this.SelectedParcela.get_DataRecebimento().HasValue ? this.SelectedParcela.get_ValorComDesconto() : (valor * this.SelectedParcela.get_Comissao()) * new decimal(1, 0, 0, false, 2)); + if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 15) && nullable4.HasValue && Math.Abs(nullable4.Value) > (Math.Abs(num) + this.Tolerancia)) + { + keyValuePairs.Add(new KeyValuePair("SelectedParcela|VALOR DO REPASSE", "O TOTAL DE COMISSÃO PAGA NÃO PODE SER SUPERIOR A COMISSÃO PREVISTA PARA RECEBIMENTO.")); + } + if (pagamento.get_Parcela() == null) + { + if (this.Repasses.Any((VendedorParcela x) => { + if (x.get_TipoVendedor().get_Id() != pagamento.get_TipoVendedor().get_Id()) + { + return false; + } + return !x.get_Vendedor().get_Corretora(); + })) + { + keyValuePairs.Add(new KeyValuePair("TipoVendedor|TIPO VENDEDOR", string.Concat("JÁ EXISTE UM VENDEDOR DO TIPO ", pagamento.get_TipoVendedor().get_Descricao(), " ADICIONADO AO DOCUMENTO."))); + } + if (this.Repasses.Any((VendedorParcela x) => x.get_Vendedor().get_Id() == pagamento.get_Vendedor().get_Id())) + { + keyValuePairs.Add(new KeyValuePair("Nome|VENDEDOR", string.Concat("VENDEDOR ", pagamento.get_Vendedor().get_Nome(), " JÁ ADICIONADO AO DOCUMENTO"))); + } + return keyValuePairs; + } + if (pagamento.get_Parcela().get_SubTipo() == 1) + { + if (this.Repasses.Any((VendedorParcela x) => { + long? nullable; + long id = x.get_TipoVendedor().get_Id(); + TipoVendedor tipoVendedor = pagamento.get_TipoVendedor(); + if (tipoVendedor != null) + { + nullable = new long?(tipoVendedor.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + if (!(id == nullable1.GetValueOrDefault() & nullable1.HasValue) || x.get_Vendedor().get_Corretora()) + { + return false; + } + return x.get_Parcela().get_Id() == pagamento.get_Parcela().get_Id(); + })) + { + keyValuePairs.Add(new KeyValuePair("TipoVendedor|TIPO VENDEDOR", string.Concat("JÁ EXISTE UM VENDEDOR DO TIPO ", pagamento.get_TipoVendedor().get_Descricao(), " ADICIONADO AO DOCUMENTO."))); + } + if (this.Repasses.Any((VendedorParcela x) => { + if (x.get_Vendedor().get_Id() != pagamento.get_Vendedor().get_Id()) + { + return false; + } + return x.get_Parcela().get_Id() == pagamento.get_Parcela().get_Id(); + })) + { + keyValuePairs.Add(new KeyValuePair("Nome|VENDEDOR", string.Concat("VENDEDOR ", pagamento.get_Vendedor().get_Nome(), " JÁ ADICIONADO AO DOCUMENTO"))); + } + return keyValuePairs; + } + if (this.Repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != pagamento.get_Parcela().get_Id() || x.get_TipoVendedor().get_Id() != pagamento.get_TipoVendedor().get_Id()) + { + return false; + } + return !x.get_Vendedor().get_Corretora(); + })) + { + keyValuePairs.Add(new KeyValuePair("TipoVendedor|TIPO VENDEDOR", string.Concat("JÁ EXISTE UM VENDEDOR DO TIPO ", pagamento.get_TipoVendedor().get_Descricao(), " ADICIONADO A PARCELA."))); + } + if (this.Repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != pagamento.get_Parcela().get_Id()) + { + return false; + } + return x.get_Vendedor().get_Id() == pagamento.get_Vendedor().get_Id(); + })) + { + keyValuePairs.Add(new KeyValuePair("Nome|VENDEDOR", string.Concat("VENDEDOR ", pagamento.get_Vendedor().get_Nome(), " JÁ ADICIONADO A PARCELA"))); + } + return keyValuePairs; + } + + public List VendedorCoCorretagem(bool coCorretagem = false) + { + List vendedors; + if (coCorretagem) + { + List list = this.Vendedores.Where((Vendedor vendedor) => { + List repassesVendedores = this.RepassesVendedores; + if (repassesVendedores == null) + { + return false; + } + return repassesVendedores.FindAll((Gestor.Model.Domain.Seguros.Repasse repasse) => repasse.get_Vendedor().get_Id() == vendedor.get_Id()).Any((Gestor.Model.Domain.Seguros.Repasse x) => x.get_Tipo().GetValueOrDefault() == 3); + }).ToList(); + vendedors = list; + this.Vendedores = list; + return vendedors; + } + List list1 = Recursos.Vendedores.Where((Vendedor vendedor) => { + if (!vendedor.get_Ativo() || vendedor.get_Corretora()) + { + return false; + } + return vendedor.get_IdEmpresa() == Recursos.Usuario.get_IdEmpresa(); + }).OrderBy((Vendedor v) => v.get_Nome()).ToList(); + vendedors = list1; + this.Vendedores = list1; + return vendedors; + } + + public bool VerificaCoCorretagem() + { + List repasses = this.Repasses; + if (repasses == null) + { + return false; + } + return repasses.Any((VendedorParcela x) => x.get_CoCorretagem()); + } + + public async Task VerificarVigencia(Documento documento) + { + bool flag; + string str; + if (documento.get_Vigencia2().HasValue) + { + DateTime? vigencia2 = documento.get_Vigencia2(); + TimeSpan timeSpan = DateTime.Parse(vigencia2.ToString()) - documento.get_Vigencia1(); + if (timeSpan.Days > 366) + { + str = "VIGÊNCIA FINAL MAIOR QUE 365 DIAS.\nDESEJA CONTINUAR?"; + } + else + { + str = (timeSpan.Days < 365 ? "VIGÊNCIA FINAL MENOR QUE 365 DIAS.\nDESEJA CONTINUAR?" : ""); + } + string str1 = str; + if (str1 != "") + { + flag = await base.ShowMessage(str1, "SIM", "NÃO", false); + } + else + { + flag = true; + } + } + else + { + flag = true; + } + return flag; + } + + private async Task WorkOnSelectedDocumento(Documento value) + { + decimal? nullable; + bool flag; + bool flag1; + bool seguradora; + List list; + decimal? tolerancia; + bool flag2; + bool flag3; + bool valueOrDefault; + string str; + NegocioCorretora negocioCorretora; + Documento documento; + BaseApoliceViewModel baseApoliceViewModel = this; + flag = (value == null ? true : value.get_Id() == (long)0); + baseApoliceViewModel.IsEnabledEdit = flag; + BaseApoliceViewModel baseApoliceViewModel1 = this; + flag1 = (value == null ? true : value.get_Id() == (long)0); + baseApoliceViewModel1.IsEnabledEditEndosso = flag1; + if (value != null && value.get_Id() != 0) + { + if (!this.Situacao.All((TipoSeguro x) => x != value.get_Situacao())) + { + this.IsEnableSituacao = true; + } + else + { + List tipoSeguros = new List() + { + 1, + 2, + 5, + value.get_Situacao() + }; + this.Situacao = new ObservableCollection(tipoSeguros); + } + Controle controle = value.get_Controle(); + if (controle != null) + { + seguradora = controle.get_Seguradora(); + } + else + { + seguradora = false; + } + if (seguradora) + { + list = Recursos.Seguradoras.Where((Seguradora x) => { + if (x.get_Ativo()) + { + return true; + } + return x.get_Id() == value.get_Controle().get_Seguradora().get_Id(); + }).ToList(); + } + else + { + List seguradoras = Recursos.Seguradoras; + list = ( + from x in seguradoras + where x.get_Ativo() + select x).ToList(); + } + this.Seguradoras = list; + this.SeguradorasAnteriores = Recursos.Seguradoras; + this.SelectedDocumento = await this.Servico.BuscarApoliceAsync(value.get_Id(), false, false); + if (!this.SelectedDocumento.get_NegocioCorretora().HasValue) + { + Documento selectedDocumento = this.SelectedDocumento; + negocioCorretora = (this.SelectedDocumento.get_Situacao() != 2 || !this.SelectedDocumento.get_Negocio().HasValue || this.SelectedDocumento.get_Negocio().GetValueOrDefault() != 1 ? 0 : 1); + selectedDocumento.set_NegocioCorretora(new NegocioCorretora?(negocioCorretora)); + base.OnPropertyChanged("SelectedDocumento"); + } + BaseApoliceViewModel valueOrDefault1 = this; + Controle controle1 = this.SelectedDocumento.get_Controle(); + if (controle1 != null) + { + Seguradora seguradora1 = controle1.get_Seguradora(); + if (seguradora1 != null) + { + tolerancia = seguradora1.get_Tolerancia(); + } + else + { + nullable = null; + tolerancia = nullable; + } + } + else + { + nullable = null; + tolerancia = nullable; + } + nullable = tolerancia; + valueOrDefault1.Tolerancia = nullable.GetValueOrDefault(new decimal(2)); + List produtos = Recursos.Produtos.Where((Produto x) => { + if (x.get_Ativo()) + { + return true; + } + if (this.SelectedDocumento.get_Controle().get_Produto() == null) + { + return false; + } + return x.get_Id() == this.SelectedDocumento.get_Controle().get_Produto().get_Id(); + }).ToList(); + this.Produtos = produtos; + if (this.Invoke) + { + ConsultaViewModel.DocumentoSelecionado = this.SelectedDocumento; + } + documento = (Documento)this.SelectedDocumento.Clone(); + await this.CarregarParcelas(documento); + await this.CarregaRepasse(documento.get_Id()); + this.SelectedDocumento.Initialize(); + this.Initialized = true; + if (this.Parcelas.Count == 0) + { + this.AllowEditVendedor = false; + } + BaseApoliceViewModel baseApoliceViewModel2 = this; + ObservableCollection parcelas = this.Parcelas; + IEnumerable subTipo = + from x in parcelas + where x.get_SubTipo() == 1 + select x; + if (!subTipo.All((Parcela x) => !x.get_DataRecebimento().HasValue)) + { + flag2 = false; + } + else + { + List repasses = this.Repasses; + IEnumerable vendedorParcelas = + from x in repasses + where x.get_Parcela().get_SubTipo() == 1 + select x; + flag2 = vendedorParcelas.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + baseApoliceViewModel2.AllowEditApolice = flag2; + BaseApoliceViewModel baseApoliceViewModel3 = this; + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2) + { + flag3 = true; + } + else + { + List repasses1 = this.Repasses; + IEnumerable vendedorParcelas1 = repasses1.Where((VendedorParcela x) => { + if (x.get_Repasse() == null) + { + return false; + } + return x.get_Repasse().get_Base().GetValueOrDefault() == 4; + }); + flag3 = vendedorParcelas1.All((VendedorParcela x) => !x.get_DataPagamento().HasValue); + } + baseApoliceViewModel3.AllowEditEmissao = flag3; + this.CalculaComissao(this.SelectedDocumento, this.Parcelas); + this.IsEndosso = this.SelectedDocumento.get_Tipo() != 0; + BaseApoliceViewModel baseApoliceViewModel4 = this; + if (!this.SelectedDocumento.get_TipoEndosso().HasValue) + { + valueOrDefault = true; + } + else if (this.SelectedDocumento.get_TipoEndosso().GetValueOrDefault() == 2) + { + valueOrDefault = false; + } + else + { + TipoEndosso? tipoEndosso = this.SelectedDocumento.get_TipoEndosso(); + valueOrDefault = tipoEndosso.GetValueOrDefault() != 3; + } + baseApoliceViewModel4.EnableAlterarSituacao = valueOrDefault; + BaseApoliceViewModel baseApoliceViewModel5 = this; + str = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2 ? "EDITAR FATURAS" : "EDITAR PARCELAS"); + baseApoliceViewModel5.EditarParcelasLabel = str; + base.AllowEditParcela = true; + this.CancelDocumento = (Documento)this.SelectedDocumento.Clone(); + } + documento = null; + } + + private void WorkOnSelectedParcela(Parcela value) + { + bool? nullable; + string str; + Visibility visibility; + int? nullable1; + bool? nullable2; + if (value == null || value.get_Id() == 0 || this.SelectedDocumento == null) + { + return; + } + bool flag = this.Repasses.Any((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != this.SelectedParcela.get_Id()) + { + return false; + } + return x.get_DataPagamento().HasValue; + }); + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 2) + { + List repasses = this.Repasses; + if (repasses != null) + { + nullable2 = new bool?(repasses.Where((VendedorParcela x) => { + if (x.get_Parcela().get_Id() != this.SelectedParcela.get_Id() || x.get_Repasse() == null) + { + return false; + } + return x.get_Repasse().get_Base().GetValueOrDefault() == 4; + }).All((VendedorParcela x) => !x.get_DataPagamento().HasValue)); + } + else + { + nullable = null; + nullable2 = nullable; + } + nullable = nullable2; + this.AllowEditEmissao = nullable.Value; + } + if (value.get_SubTipo() != 1 || this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 1) + { + this.BaixarParcelaVisibility = (!value.get_DataRecebimento().HasValue ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityExcluirParcela = (flag ? Visibility.Collapsed : Visibility.Visible); + if (value.get_DataRecebimento().HasValue) + { + str = "EXCLUIR BAIXA"; + } + else + { + str = (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 ? "EXCLUIR PARCELA" : "EXCLUIR FATURA"); + } + this.ExcluirParcelaLabel = str; + } + else + { + this.BaixarParcelaVisibility = (this.Parcelas.Any((Parcela x) => { + if (x.get_DataRecebimento().HasValue) + { + return false; + } + return x.get_SubTipo() == 1; + }) ? Visibility.Visible : Visibility.Collapsed); + Parcela parcela = ( + from x in this.Parcelas + orderby x.get_NumeroParcela() + select x).LastOrDefault((Parcela x) => { + if (!x.get_DataRecebimento().HasValue || x.get_SubTipo() != 1) + { + return false; + } + if (x.get_ValorComissao() != decimal.Zero) + { + return true; + } + return x.get_ValorRealizado() != decimal.Zero; + }); + if (flag) + { + visibility = Visibility.Collapsed; + } + else + { + if (!value.get_DataRecebimento().HasValue || parcela != null) + { + if (parcela != null) + { + nullable1 = new int?(parcela.get_NumeroParcela()); + } + else + { + nullable1 = null; + } + int? nullable3 = nullable1; + int numeroParcela = value.get_NumeroParcela(); + if (nullable3.GetValueOrDefault() <= numeroParcela & nullable3.HasValue) + { + goto Label1; + } + visibility = Visibility.Collapsed; + goto Label0; + } + Label1: + visibility = Visibility.Visible; + } + Label0: + this.VisibilityExcluirParcela = visibility; + this.ExcluirParcelaLabel = "EXCLUIR BAIXA"; + } + this.VisibilityReplicarFatura = (this.IsFatura ? Visibility.Visible : Visibility.Collapsed); + } + + private void WorkOnSelectedTipo(bool value) + { + this.Assinada = (value ? "PROPOSTA DE ENDOSSO ASSINADA" : "PROPOSTA ASSINADA"); + this.Conferida = (value ? "ENDOSSO CONFERIDO" : "APÓLICE CONFERIDA"); + this.Transmissao = (value ? "TRANSMISSÃO DA PROPOSTA DE ENDOSSO" : "TRANSMISSÃO DA PROPOSTA"); + this.Emissao = (value ? "EMISSÃO DO ENDOSSO" : "EMISSÃO DA APÓLICE"); + } + + private void ZeraComissao() + { + this.Gerada = decimal.Zero; + this.Recebida = decimal.Zero; + this.Pendente = decimal.Zero; + this.Repasse = decimal.Zero; + this.ComissOriginal = decimal.Zero; + } + + private void ZerarValores() + { + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() != 2) + { + return; + } + this.SelectedDocumento.set_PremioLiquido(decimal.Zero); + this.SelectedDocumento.set_PremioAdicional(decimal.Zero); + this.SelectedDocumento.set_PremioAdicional(decimal.Zero); + this.SelectedDocumento.set_Iof(decimal.Zero); + this.SelectedDocumento.set_Diferenca(decimal.Zero); + this.SelectedDocumento.set_NumeroParcelas(decimal.Zero); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs new file mode 100644 index 0000000..1b8cfbe --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs @@ -0,0 +1,11 @@ +using System; + +namespace Gestor.Application.ViewModels.Generic +{ + public class BaseDialogViewModel : BaseViewModel + { + public BaseDialogViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs new file mode 100644 index 0000000..3e5561d --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs @@ -0,0 +1,512 @@ +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Financeiro; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Financeiro; +using MaterialDesignThemes.Wpf; +using OfxSharpLib; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.ViewModels.Generic +{ + public abstract class BaseFinanceiroViewModel : BaseViewModel + { + public AutoCompleteFilterPredicate BancoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_140 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__14_0; + if (u003cu003e9_140 == null) + { + u003cu003e9_140 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Banco)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__14_0 = u003cu003e9_140; + } + return u003cu003e9_140; + } + } + + public AutoCompleteFilterPredicate BancosContasItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_20 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__2_0; + if (u003cu003e9_20 == null) + { + u003cu003e9_20 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((BancosContas)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__2_0 = u003cu003e9_20; + } + return u003cu003e9_20; + } + } + + public AutoCompleteFilterPredicate FornecedorItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_60 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__6_0; + if (u003cu003e9_60 == null) + { + u003cu003e9_60 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Fornecedor)obj).get_Nome() != null && ((Fornecedor)obj).get_Nome().ToUpper().Contains(searchText.ToUpper()) || ((Fornecedor)obj).get_Documento() != null && ((Fornecedor)obj).get_Documento().ToString().Contains(searchText.ToUpper()) || ((Fornecedor)obj).get_Telefone1() != null && ((Fornecedor)obj).get_Telefone1().ToString().Contains(searchText.ToUpper()) || ((Fornecedor)obj).get_Telefone2() != null && ((Fornecedor)obj).get_Telefone2().ToString().Contains(searchText.ToUpper())) + { + return true; + } + if (((Fornecedor)obj).get_Email() == null) + { + return false; + } + return ((Fornecedor)obj).get_Email().ToString().Contains(searchText.ToUpper()); + }); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__6_0 = u003cu003e9_60; + } + return u003cu003e9_60; + } + } + + public AutoCompleteFilterPredicate LancamentoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_80 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__8_0; + if (u003cu003e9_80 == null) + { + u003cu003e9_80 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + bool historico; + bool plano; + bool centro; + bool fornecedor; + if ((((Lancamento)obj).get_Historico() == null || !((Lancamento)obj).get_Historico().ToUpper().Contains(searchText.ToUpper())) && !((Lancamento)obj).get_Vencimento().ToString().ToUpper().Contains(searchText.ToUpper()) && (!((Lancamento)obj).get_Baixa().HasValue || !((Lancamento)obj).get_Baixa().ToString().ToUpper().Contains(searchText.ToUpper())) && (!((Lancamento)obj).get_Pagamento().HasValue || !((Lancamento)obj).get_Pagamento().ToString().ToUpper().Contains(searchText.ToUpper())) && (((Lancamento)obj).get_Conta() == null || !((Lancamento)obj).get_Conta().get_Descricao().ToString().ToUpper().Contains(searchText.ToUpper()))) + { + ControleFinanceiro controle = ((Lancamento)obj).get_Controle(); + if (controle != null) + { + historico = controle.get_Historico(); + } + else + { + historico = false; + } + if (!historico || !((Lancamento)obj).get_Controle().get_Historico().ToString().ToUpper().Contains(searchText.ToUpper())) + { + ControleFinanceiro controleFinanceiro = ((Lancamento)obj).get_Controle(); + if (controleFinanceiro != null) + { + plano = controleFinanceiro.get_Plano(); + } + else + { + plano = false; + } + if (!plano || !((Lancamento)obj).get_Controle().get_Plano().get_Descricao().ToString().ToUpper().Contains(searchText.ToUpper())) + { + ControleFinanceiro controle1 = ((Lancamento)obj).get_Controle(); + if (controle1 != null) + { + centro = controle1.get_Centro(); + } + else + { + centro = false; + } + if (!centro || !((Lancamento)obj).get_Controle().get_Centro().get_Descricao().ToString().ToUpper().Contains(searchText.ToUpper())) + { + ControleFinanceiro controleFinanceiro1 = ((Lancamento)obj).get_Controle(); + if (controleFinanceiro1 != null) + { + fornecedor = controleFinanceiro1.get_Fornecedor(); + } + else + { + fornecedor = false; + } + if (!fornecedor) + { + return false; + } + return ((Lancamento)obj).get_Controle().get_Fornecedor().get_Nome().ToString().ToUpper().Contains(searchText.ToUpper()); + } + } + } + } + return true; + }); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__8_0 = u003cu003e9_80; + } + return u003cu003e9_80; + } + } + + public AutoCompleteFilterPredicate PlanoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_100 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__10_0; + if (u003cu003e9_100 == null) + { + u003cu003e9_100 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Plano)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Plano)obj).get_Descricao().ToString().Contains(searchText.ToUpper()); + }); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__10_0 = u003cu003e9_100; + } + return u003cu003e9_100; + } + } + + public AutoCompleteFilterPredicate PlanosItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_120 = BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__12_0; + if (u003cu003e9_120 == null) + { + u003cu003e9_120 = new AutoCompleteFilterPredicate(BaseFinanceiroViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Planos)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Planos)obj).get_Descricao().ToString().Contains(searchText.ToUpper()); + }); + BaseFinanceiroViewModel.u003cu003ec.u003cu003e9__12_0 = u003cu003e9_120; + } + return u003cu003e9_120; + } + } + + protected BaseFinanceiroViewModel() + { + } + + internal async Task> BuscarBancosContas(string value) + { + List bancosContas = await Task.Run>(() => (new BaseServico()).BuscarBancosContas(value)); + return bancosContas; + } + + internal async Task> BuscarFornecedor(string value) + { + List fornecedors = await Task.Run>(() => (new BaseServico()).BuscarFornecedor(value, false)); + return fornecedors; + } + + internal async Task> BuscarFornecedorAtivo(string value) + { + List fornecedors = await Task.Run>(() => (new BaseServico()).BuscarFornecedor(value, true)); + return fornecedors; + } + + private string DetectEncodingAndRead(string arquivo) + { + return File.ReadAllText(arquivo, BaseFinanceiroViewModel.DetectTextFileEncoding(arquivo)); + } + + public static Encoding DetectTextFileEncoding(string filePath) + { + byte[] numArray; + using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) + { + int num = (int)Math.Min(fileStream.Length, (long)4096); + numArray = new byte[num]; + fileStream.Read(numArray, 0, num); + } + if ((int)numArray.Length >= 2) + { + if ((int)numArray.Length >= 3 && numArray[0] == 239 && numArray[1] == 187 && numArray[2] == 191) + { + return Encoding.UTF8; + } + if (numArray[0] == 255 && numArray[1] == 254) + { + return Encoding.Unicode; + } + if (numArray[0] == 254 && numArray[1] == 255) + { + return Encoding.BigEndianUnicode; + } + if ((int)numArray.Length >= 4 && numArray[0] == 255 && numArray[1] == 254 && numArray[2] == 0 && numArray[3] == 0) + { + return Encoding.UTF32; + } + if ((int)numArray.Length >= 4 && numArray[0] == 0 && numArray[1] == 0 && numArray[2] == 254 && numArray[3] == 255) + { + return new UTF32Encoding(true, true); + } + } + bool flag = true; + int num1 = 0; + int num2 = 0; + for (int i = 0; i < (int)numArray.Length; i++) + { + if (numArray[i] <= 127) + { + num2++; + } + else if (numArray[i] >= 194 && numArray[i] <= 223 && i + 1 < (int)numArray.Length && numArray[i + 1] >= 128 && numArray[i + 1] <= 191) + { + num1++; + i++; + } + else if (numArray[i] >= 224 && numArray[i] <= 239 && i + 2 < (int)numArray.Length && numArray[i + 1] >= 128 && numArray[i + 1] <= 191 && numArray[i + 2] >= 128 && numArray[i + 2] <= 191) + { + num1++; + i += 2; + } + else if (numArray[i] < 240 || numArray[i] > 244 || i + 3 >= (int)numArray.Length || numArray[i + 1] < 128 || numArray[i + 1] > 191 || numArray[i + 2] < 128 || numArray[i + 2] > 191 || numArray[i + 3] < 128 || numArray[i + 3] > 191) + { + flag = false; + break; + } + else + { + num1++; + i += 3; + } + } + int num3 = 0; + for (int j = 0; j < (int)numArray.Length - 1; j += 2) + { + if (numArray[j] == 0 || numArray[j + 1] == 0) + { + num3++; + } + } + if (flag && num1 > 0) + { + return Encoding.UTF8; + } + if ((double)num2 > (double)((int)numArray.Length) * 0.95) + { + return Encoding.ASCII; + } + if ((double)num3 <= (double)((int)numArray.Length) * 0.4) + { + return Encoding.GetEncoding(1252); + } + int num4 = 0; + int num5 = 0; + for (int k = 0; k < (int)numArray.Length - 1; k += 2) + { + if (numArray[k] == 0 && numArray[k + 1] != 0) + { + num5++; + } + if (numArray[k] != 0 && numArray[k + 1] == 0) + { + num4++; + } + } + if (num4 > num5) + { + return Encoding.Unicode; + } + return Encoding.BigEndianUnicode; + } + + public async Task ExecuteRunExtendedDialogContas(System.Windows.Controls.UserControl dialogControl, string hostName) + { + BancosContas bancosConta; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + bancosConta = (BancosContas)obj; + } + else + { + bancosConta = null; + } + return bancosConta; + } + + public async Task ExecuteRunExtendedDialogTransferencia(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Transferencia transferencium; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + transferencium = (Transferencia)obj; + } + else + { + transferencium = null; + } + return transferencium; + } + + public async Task ExecuteRunExtendedDialogVinculo(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Lancamento lancamento; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + lancamento = (Lancamento)obj; + } + else + { + lancamento = null; + } + return lancamento; + } + + public Encoding GetEncoding(string filename) + { + byte[] numArray = new byte[4]; + using (FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read)) + { + fileStream.Read(numArray, 0, 4); + } + if (numArray[0] == 43 && numArray[1] == 47 && numArray[2] == 118) + { + return Encoding.UTF7; + } + if (numArray[0] == 239 && numArray[1] == 187 && numArray[2] == 191) + { + return Encoding.UTF8; + } + if (numArray[0] == 255 && numArray[1] == 254 && numArray[2] == 0 && numArray[3] == 0) + { + return Encoding.UTF32; + } + if (numArray[0] == 255 && numArray[1] == 254) + { + return Encoding.Unicode; + } + if (numArray[0] == 254 && numArray[1] == 255) + { + return Encoding.BigEndianUnicode; + } + if (numArray[0] != 0 || numArray[1] != 0 || numArray[2] != 254 || numArray[3] != 255) + { + return Encoding.ASCII; + } + return new UTF32Encoding(true, true); + } + + public async Task> ImportarOfx() + { + List ofxDocuments; + BaseFinanceiroViewModel.u003cu003ec__DisplayClass22_0 variable; + List ofxDocuments1 = new List(); + bool flag = false; + List strs = new List(); + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Multiselect = true; + openFileDialog.Filter = "Arquivos OFX|*.ofx"; + openFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString(); + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + strs.AddRange(openFileDialog.FileNames); + } + else + { + ofxDocuments = null; + variable = null; + return ofxDocuments; + } + } + await Task.Run(() => { + OfxDocumentParser ofxDocumentParser = new OfxDocumentParser(); + strs.ForEach((string x) => { + try + { + string str = DateTime.Now.Date.ToString("yyyyMMddHHmmss"); + string str1 = this.DetectEncodingAndRead(x).Replace("00000000", string.Concat("", str)).Replace("00000000000000", string.Concat("", str)).Replace(",", ".").Replace(" ", "."); + if (str1.Contains("336") && !str1.Contains("")) + { + str1 = str1.Replace("UTF - 8", "USASCII").Replace("", "\r\n\r\n0\r\n00000000\r\n").Replace("00000000", string.Concat("", str)).Replace(": ", ":").Replace(" ", "").Replace("", "0"); + } + if (str1.Contains("0403") && !str1.Contains("CHARSET:1252") && str1.Contains("ENCODING:UTF-8")) + { + str1 = str1.Replace("UTF-8", "USASCII\nCHARSET:1252").Replace("00000000", string.Concat("", str)).Replace("[0:GMT]", "").Replace(": ", ":").Replace(" ", ""); + } + if (str1.Contains("260")) + { + str1 = str1.Replace("UTF-8", "USASCII").Replace("CHARSET:NONE", "CHARSET:1252"); + } + if (str1.Contains("")) + { + str1 = str1.Replace("", "SEM INFORMAÇÃO"); + } + if (Regex.IsMatch(str1, "\\s*")) + { + str1 = str1.Replace("\n", "SEM NOME").Replace("", "SEM NOME"); + } + OfxDocument ofxDocument = ofxDocumentParser.Import(str1); + ofxDocuments1.Add(ofxDocument); + } + catch (Exception exception) + { + flag = true; + } + }); + }); + if (flag) + { + await base.ShowMessage("HOUVE PROBLEMAS AO IMPORTAR O OFX, BAIXE-O NOVAMENTE COM UM PERÍODO MENOR.", "OK", "", false); + } + ofxDocuments = ofxDocuments1; + variable = null; + return ofxDocuments; + } + + internal async Task ShowContas(List contas) + { + string str; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + DialogHost dialogHost = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).FirstOrDefault(); + ContasDialog contasDialog = new ContasDialog(contas); + BaseFinanceiroViewModel baseFinanceiroViewModel = this; + ContasDialog contasDialog1 = contasDialog; + str = (dialogHost != null ? dialogHost.get_Identifier().ToString() : "RootDialog"); + return await baseFinanceiroViewModel.ExecuteRunExtendedDialogContas(contasDialog1, str); + } + + internal async Task ShowTransferencia(Transferencia transferencia) + { + string str; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + DialogHost dialogHost = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).FirstOrDefault(); + DialogTransferencia dialogTransferencium = new DialogTransferencia(transferencia); + BaseFinanceiroViewModel baseFinanceiroViewModel = this; + DialogTransferencia dialogTransferencium1 = dialogTransferencium; + str = (dialogHost != null ? dialogHost.get_Identifier().ToString() : "RootDialog"); + return await baseFinanceiroViewModel.ExecuteRunExtendedDialogTransferencia(dialogTransferencium1, str); + } + + internal async Task ShowVinculo(FinanceiroViewModel viewModel) + { + string str; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + DialogHost dialogHost = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).FirstOrDefault(); + VincularLancamentoDialog vincularLancamentoDialog = new VincularLancamentoDialog(viewModel); + BaseFinanceiroViewModel baseFinanceiroViewModel = this; + VincularLancamentoDialog vincularLancamentoDialog1 = vincularLancamentoDialog; + str = (dialogHost != null ? dialogHost.get_Identifier().ToString() : "RootDialog"); + return await baseFinanceiroViewModel.ExecuteRunExtendedDialogVinculo(vincularLancamentoDialog1, str); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs new file mode 100644 index 0000000..8f75310 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs @@ -0,0 +1,1238 @@ +using Agger.Registro; +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Seguros.Itens; +using Gestor.Application.Views.Seguros.Itens; +using Gestor.Model.Common; +using Gestor.Model.Domain.Card; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using MaterialDesignThemes.Wpf; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.ViewModels.Generic +{ + public class BaseSegurosViewModel : BaseViewModel + { + private string _anotacoes; + + private bool _enableEndossar; + + private bool _enableRenovar; + + public AutoCompleteFilterPredicate AgendaItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_80 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__8_0; + if (u003cu003e9_80 == null) + { + u003cu003e9_80 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Agenda)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__8_0 = u003cu003e9_80; + } + return u003cu003e9_80; + } + } + + public string Anotacoes + { + get + { + return this._anotacoes; + } + set + { + this._anotacoes = value; + base.OnPropertyChanged("Anotacoes"); + } + } + + public AutoCompleteFilterPredicate AtividadeItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_400 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__40_0; + if (u003cu003e9_400 == null) + { + u003cu003e9_400 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Atividade)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Atividade)obj).get_Cnac().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__40_0 = u003cu003e9_400; + } + return u003cu003e9_400; + } + } + + public AutoCompleteFilterPredicate BancoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_380 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__38_0; + if (u003cu003e9_380 == null) + { + u003cu003e9_380 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Banco)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Banco)obj).get_Codigo().ToString().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__38_0 = u003cu003e9_380; + } + return u003cu003e9_380; + } + } + + public AutoCompleteFilterPredicate ClienteItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_10 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__1_0; + if (u003cu003e9_10 == null) + { + u003cu003e9_10 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (CultureInfo.InvariantCulture.CompareInfo.IndexOf(((Cliente)obj).get_Nome().ToUpper(), searchText.Trim(), CompareOptions.IgnoreNonSpace) > -1 || ((Cliente)obj).get_Documento() != null && ((Cliente)obj).get_Documento().Contains(searchText.Trim()) || ((Cliente)obj).get_Rne() != null && ((Cliente)obj).get_Rne().Contains(searchText.Trim()) || ((Cliente)obj).get_Cei() != null && ((Cliente)obj).get_Cei().Contains(searchText.Trim()) || ((Cliente)obj).get_NomeSocialRg() != null && ((Cliente)obj).get_NomeSocialRg().ToUpper().Contains(searchText.Trim().ToUpper())) + { + return true; + } + if (((Cliente)obj).get_Telefones() == null || ((Cliente)obj).get_Telefones().Count <= 0) + { + return false; + } + return ((Cliente)obj).get_Telefones().Any((ClienteTelefone x) => x.get_Numero().Contains(searchText.Trim())); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__1_0 = u003cu003e9_10; + } + return u003cu003e9_10; + } + } + + public AutoCompleteFilterPredicate CoberturaPadraoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_580 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__58_0; + if (u003cu003e9_580 == null) + { + u003cu003e9_580 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((CoberturaPadrao)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__58_0 = u003cu003e9_580; + } + return u003cu003e9_580; + } + } + + public AutoCompleteFilterPredicate ConfigItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_460 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__46_0; + if (u003cu003e9_460 == null) + { + u003cu003e9_460 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((ConfigExtratoImport)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__46_0 = u003cu003e9_460; + } + return u003cu003e9_460; + } + } + + public AutoCompleteFilterPredicate EmpresaItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_300 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__30_0; + if (u003cu003e9_300 == null) + { + u003cu003e9_300 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Empresa)obj).get_Nome().ToUpper().Contains(searchText.ToUpper()) || ((Empresa)obj).get_Documento().ToString().Contains(searchText.ToUpper())) + { + return true; + } + return ((Empresa)obj).get_Serial().ToString().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__30_0 = u003cu003e9_300; + } + return u003cu003e9_300; + } + } + + public bool EnableEndossar + { + get + { + return this._enableEndossar; + } + set + { + this._enableEndossar = value; + base.OnPropertyChanged("EnableEndossar"); + } + } + + public bool EnableRenovar + { + get + { + return this._enableRenovar; + } + set + { + this._enableRenovar = value; + base.OnPropertyChanged("EnableRenovar"); + } + } + + public AutoCompleteFilterPredicate EstipulanteItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_140 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__14_0; + if (u003cu003e9_140 == null) + { + u003cu003e9_140 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Estipulante)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Estipulante)obj).get_Documento().ToString().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__14_0 = u003cu003e9_140; + } + return u003cu003e9_140; + } + } + + public AutoCompleteFilterPredicate EtiquetaItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_280 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__28_0; + if (u003cu003e9_280 == null) + { + u003cu003e9_280 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Documento)obj).get_Controle().get_Cliente().get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__28_0 = u003cu003e9_280; + } + return u003cu003e9_280; + } + } + + public AutoCompleteFilterPredicate FabricanteItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_420 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__42_0; + if (u003cu003e9_420 == null) + { + u003cu003e9_420 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Fabricante)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__42_0 = u003cu003e9_420; + } + return u003cu003e9_420; + } + } + + public AutoCompleteFilterPredicate ItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_540 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__54_0; + if (u003cu003e9_540 == null) + { + u003cu003e9_540 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Item)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__54_0 = u003cu003e9_540; + } + return u003cu003e9_540; + } + } + + public AutoCompleteFilterPredicate NomeItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_360 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__36_0; + if (u003cu003e9_360 == null) + { + u003cu003e9_360 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Credencial)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__36_0 = u003cu003e9_360; + } + return u003cu003e9_360; + } + } + + public AutoCompleteFilterPredicate NotaFiscalItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_220 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__22_0; + if (u003cu003e9_220 == null) + { + u003cu003e9_220 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((NotaFiscal)obj).get_Seguradora().get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__22_0 = u003cu003e9_220; + } + return u003cu003e9_220; + } + } + + public AutoCompleteFilterPredicate ParceiroItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_480 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__48_0; + if (u003cu003e9_480 == null) + { + u003cu003e9_480 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Parceiro)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__48_0 = u003cu003e9_480; + } + return u003cu003e9_480; + } + } + + public AutoCompleteFilterPredicate ProdutoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_160 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__16_0; + if (u003cu003e9_160 == null) + { + u003cu003e9_160 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Produto)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__16_0 = u003cu003e9_160; + } + return u003cu003e9_160; + } + } + + public AutoCompleteFilterPredicate ProfissaoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_120 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__12_0; + if (u003cu003e9_120 == null) + { + u003cu003e9_120 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Profissao)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Profissao)obj).get_Codigo().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__12_0 = u003cu003e9_120; + } + return u003cu003e9_120; + } + } + + public AutoCompleteFilterPredicate RamoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_520 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__52_0; + if (u003cu003e9_520 == null) + { + u003cu003e9_520 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Ramo)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__52_0 = u003cu003e9_520; + } + return u003cu003e9_520; + } + } + + public AutoCompleteFilterPredicate ReciboItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_260 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__26_0; + if (u003cu003e9_260 == null) + { + u003cu003e9_260 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Recibo)obj).get_Pagante().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Recibo)obj).get_Recebedor().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__26_0 = u003cu003e9_260; + } + return u003cu003e9_260; + } + } + + public AutoCompleteFilterPredicate SeguradoraItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_440 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__44_0; + if (u003cu003e9_440 == null) + { + u003cu003e9_440 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Seguradora)obj).get_Nome().ToUpper().Contains(searchText.ToUpper()) || ((Seguradora)obj).get_Documento() != null && ((Seguradora)obj).get_Documento().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + if (((Seguradora)obj).get_Susep() == null) + { + return false; + } + return ((Seguradora)obj).get_Susep().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__44_0 = u003cu003e9_440; + } + return u003cu003e9_440; + } + } + + public AutoCompleteFilterPredicate SinitroItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_560 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__56_0; + if (u003cu003e9_560 == null) + { + u003cu003e9_560 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((ControleSinistro)obj).get_DataSinistro().ToString().Contains(searchText)) + { + return true; + } + if (((ControleSinistro)obj).get_Sinistros() == null || ((ControleSinistro)obj).get_Sinistros().Count <= 0) + { + return false; + } + return ((ControleSinistro)obj).get_Sinistros()[0].get_Numero().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__56_0 = u003cu003e9_560; + } + return u003cu003e9_560; + } + } + + public AutoCompleteFilterPredicate SocioItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_320 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__32_0; + if (u003cu003e9_320 == null) + { + u003cu003e9_320 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Socio)obj).get_Nome().ToUpper().Contains(searchText.ToUpper()) || ((Socio)obj).get_Email().ToString().Contains(searchText.ToUpper())) + { + return true; + } + return ((Socio)obj).get_Telefone().ToString().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__32_0 = u003cu003e9_320; + } + return u003cu003e9_320; + } + } + + public AutoCompleteFilterPredicate StatusItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_240 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__24_0; + if (u003cu003e9_240 == null) + { + u003cu003e9_240 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((Status)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__24_0 = u003cu003e9_240; + } + return u003cu003e9_240; + } + } + + public AutoCompleteFilterPredicate StatusProspeccaoItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_200 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__20_0; + if (u003cu003e9_200 == null) + { + u003cu003e9_200 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((StatusDeProspeccao)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__20_0 = u003cu003e9_200; + } + return u003cu003e9_200; + } + } + + public AutoCompleteFilterPredicate TipoTarefaItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_180 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__18_0; + if (u003cu003e9_180 == null) + { + u003cu003e9_180 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((TipoDeTarefa)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__18_0 = u003cu003e9_180; + } + return u003cu003e9_180; + } + } + + public AutoCompleteFilterPredicate TipoVendedorItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_500 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__50_0; + if (u003cu003e9_500 == null) + { + u003cu003e9_500 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((TipoVendedor)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__50_0 = u003cu003e9_500; + } + return u003cu003e9_500; + } + } + + public AutoCompleteFilterPredicate UsuarioItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_340 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__34_0; + if (u003cu003e9_340 == null) + { + u003cu003e9_340 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Usuario)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + return ((Usuario)obj).get_Documento().ToString().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__34_0 = u003cu003e9_340; + } + return u003cu003e9_340; + } + } + + public AutoCompleteFilterPredicate VendedorItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_100 = BaseSegurosViewModel.u003cu003ec.u003cu003e9__10_0; + if (u003cu003e9_100 == null) + { + u003cu003e9_100 = new AutoCompleteFilterPredicate(BaseSegurosViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (((Vendedor)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return true; + } + if (((Vendedor)obj).get_Documento() == null) + { + return false; + } + return ((Vendedor)obj).get_Documento().ToUpper().Contains(searchText.ToUpper()); + }); + BaseSegurosViewModel.u003cu003ec.u003cu003e9__10_0 = u003cu003e9_100; + } + return u003cu003e9_100; + } + } + + public BaseSegurosViewModel() + { + } + + internal async Task> BuscaFabricante(string value) + { + List fabricantes = await Task.Run>(() => (new BaseServico()).BuscarFabricante(value)); + return fabricantes; + } + + internal async Task> BuscarAtividade(string value) + { + List atividades = await Task.Run>(() => (new BaseServico()).BuscarAtividade(value)); + return atividades; + } + + internal async Task> BuscarCliente(string value, List vinculos = null, TipoFiltroCliente tipoFiltroCliente = 2) + { + return await (new ClienteServico()).BuscarCliente(value, vinculos, tipoFiltroCliente); + } + + internal async Task> BuscarClienteEmpresa(string value) + { + List clientes = await Task.Run>(() => (new BaseServico()).BuscarClienteEmpresa(value)); + return clientes; + } + + internal async Task> BuscarClienteVinculo(string value, long id) + { + List clientes = await Task.Run>(() => (new ClienteServico()).BuscarClienteVinculo(value, id)); + return clientes; + } + + internal async Task> BuscarProfissao(string value) + { + List profissaos = await Task.Run>(() => (new BaseServico()).BuscarProfissao(value)); + return profissaos; + } + + internal async Task> BuscarUsuario(string value) + { + List usuarios = await Task.Run>(() => (new BaseServico()).BuscarUsuario(value)); + return usuarios; + } + + public async Task CarregaApolice(long id) + { + return await (new ApoliceServico()).BuscarApoliceAsync(id, false, false); + } + + public async Task CarregaApoliceParcela(long id) + { + return await (new ParcelaServico()).BuscarApolice(id); + } + + public async Task CarregaCliente(long id) + { + return await (new ClienteServico()).BuscarClienteAsync(id); + } + + public async Task CarregaParcela(long id) + { + return await (new ParcelaServico()).BuscarParcela(id); + } + + public async Task> CarregarItem(long id, StatusItem status = 2) + { + List list = await (new ItemServico()).BuscarItens(id, status).ToList(); + return list; + } + + public async Task CarregarProspeccao(long id) + { + return await (new ProspeccaoServico()).BuscarProspeccao(id); + } + + public async Task CarregaSinistroApolice(long id) + { + return await (new SinistroServico()).BuscarSinistro(id); + } + + public async Task CreateCardLogo(Empresa empresa, string id = null) + { + string str; + string str1; + string str2; + if (empresa != null) + { + Logo logo = new Logo(); + logo.set_CustomId(ApplicationHelper.NumeroSerial); + logo.set_Data(empresa.get_Logo()); + str2 = (!string.IsNullOrEmpty(empresa.get_NomeSocial()) ? empresa.get_NomeSocial() : empresa.get_Nome()); + logo.set_Corretora(str2); + logo.set_Whatsapp(empresa.get_Whatsapp()); + logo.set_WhatsappSinistro(empresa.get_WhatsappSinistro()); + Logo logo1 = logo; + str1 = (!string.IsNullOrWhiteSpace(id) ? await Funcoes.Atualizarlogo(logo1, id) : await Funcoes.Criarlogo(logo1)); + id = str1; + str = id; + } + else + { + str = ""; + } + return str; + } + + public async Task CreateLinkAssistencia(Documento documento, string item, bool retorno = true) + { + string str; + str = (documento != null ? string.Format("{0}{1}", Address.get_Assistance(), documento.get_Id().GeraAssistencia()) : ""); + return str; + } + + public async Task CreateSeguradora(Seguradora seguradora, string id = null) + { + string str; + string str1; + if (seguradora != null) + { + int num = 1; + AssistenciaCia assistenciaCium = new AssistenciaCia(); + assistenciaCium.set_Seguradora(seguradora.get_Nome()); + assistenciaCium.set_IdSeguradora(seguradora.get_Id()); + assistenciaCium.set_LinkAppAndroid(seguradora.get_LinkAppAndroid()); + assistenciaCium.set_LinkAppIos(seguradora.get_LinkAppIos()); + assistenciaCium.set_CustomId(ApplicationHelper.NumeroSerial); + AssistenciaCia assistenciaCium1 = assistenciaCium; + List contatos = seguradora.get_Contatos(); + ( + from x in contatos + orderby x.get_Tipo().GetValueOrDefault(7).GetType() + select x).ToList().ForEach((SeguradoraContato x) => { + switch (num) + { + case 2: + { + assistenciaCium1.set_Assistencia2Tipo((!x.get_Tipo().HasValue ? 10 : x.get_Tipo().Value)); + assistenciaCium1.set_Assistencia2((!x.get_Tipo().HasValue || x.get_Tipo().GetValueOrDefault() != 10 ? (x.get_Tipo().GetValueOrDefault() == 11 ? string.Concat("0300-", x.get_Numero()) : (x.get_Tipo().GetValueOrDefault() != 7 || !string.IsNullOrEmpty(x.get_Prefixo()) ? string.Concat("(", x.get_Prefixo(), ") ", x.get_Numero()) : x.get_Numero())) : string.Concat("0800-", x.get_Numero()))); + assistenciaCium1.set_Assistencia2Obs(x.get_NomeContato()); + break; + } + case 3: + { + assistenciaCium1.set_Assistencia3Tipo((!x.get_Tipo().HasValue ? 10 : x.get_Tipo().Value)); + assistenciaCium1.set_Assistencia3((!x.get_Tipo().HasValue || x.get_Tipo().GetValueOrDefault() != 10 ? (x.get_Tipo().GetValueOrDefault() == 11 ? string.Concat("0300-", x.get_Numero()) : (x.get_Tipo().GetValueOrDefault() != 7 || !string.IsNullOrEmpty(x.get_Prefixo()) ? string.Concat("(", x.get_Prefixo(), ") ", x.get_Numero()) : x.get_Numero())) : string.Concat("0800-", x.get_Numero()))); + assistenciaCium1.set_Assistencia3Obs(x.get_NomeContato()); + break; + } + case 4: + { + assistenciaCium1.set_Assistencia4Tipo((!x.get_Tipo().HasValue ? 10 : x.get_Tipo().Value)); + assistenciaCium1.set_Assistencia4((!x.get_Tipo().HasValue || x.get_Tipo().GetValueOrDefault() != 10 ? (x.get_Tipo().GetValueOrDefault() == 11 ? string.Concat("0300-", x.get_Numero()) : (x.get_Tipo().GetValueOrDefault() != 7 || !string.IsNullOrEmpty(x.get_Prefixo()) ? string.Concat("(", x.get_Prefixo(), ") ", x.get_Numero()) : x.get_Numero())) : string.Concat("0800-", x.get_Numero()))); + assistenciaCium1.set_Assistencia4Obs(x.get_NomeContato()); + break; + } + default: + { + assistenciaCium1.set_Assistencia1Tipo((!x.get_Tipo().HasValue ? 10 : x.get_Tipo().Value)); + assistenciaCium1.set_Assistencia1((!x.get_Tipo().HasValue || x.get_Tipo().GetValueOrDefault() != 10 ? (x.get_Tipo().GetValueOrDefault() == 11 ? string.Concat("0300-", x.get_Numero()) : (x.get_Tipo().GetValueOrDefault() != 7 || !string.IsNullOrEmpty(x.get_Prefixo()) ? string.Concat("(", x.get_Prefixo(), ") ", x.get_Numero()) : x.get_Numero())) : string.Concat("0800-", x.get_Numero()))); + assistenciaCium1.set_Assistencia1Obs(x.get_NomeContato()); + break; + } + } + num++; + }); + str1 = (!string.IsNullOrWhiteSpace(id) ? await Funcoes.AtualizarSeguradora(assistenciaCium1, id) : await Funcoes.CriarSeguradora(assistenciaCium1)); + id = str1; + str = id; + } + else + { + str = ""; + } + return str; + } + + public async Task ExecuteRunExtendedDialogBuscaModelo(UserControl dialogControl, string hostName) + { + Fipe fipe; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + fipe = (Fipe)obj; + } + else + { + fipe = null; + } + return fipe; + } + + public async Task, Usuario, List, List, List>> ExecuteRunExtendedDialogCopiarPermiss(UserControl dialogControl, string hostName) + { + Tuple, Usuario, List, List, List> tuple; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + tuple = (Tuple, Usuario, List, List, List>)obj; + } + else + { + tuple = null; + } + return tuple; + } + + public async Task ExecuteRunExtendedDialogDetalheExtrato(UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + } + + public async Task ExecuteRunExtendedDialogEditarParcelas(UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + } + + public async Task ExecuteRunExtendedDialogEnviarEmails(UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + } + + public async Task> ExecuteRunExtendedDialogExportarPermiss(UserControl dialogControl, string hostName) + { + List usuarios; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + usuarios = (List)obj; + } + else + { + usuarios = null; + } + return usuarios; + } + + public async Task ExecuteRunExtendedDialogLogAcesso(UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + } + + public async Task ExecuteRunExtendedDialogObservacao(UserControl dialogControl, string hostName) + { + string str; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + str = (string)obj; + } + else + { + str = null; + } + return str; + } + + public async Task ExecuteRunExtendedDialogPesquisaAvancada(UserControl dialogControl, string hostName) + { + PesquisaAvancada pesquisaAvancada; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + pesquisaAvancada = (PesquisaAvancada)obj; + } + else + { + pesquisaAvancada = null; + } + return pesquisaAvancada; + } + + public async Task> ExecuteRunExtendedDialogProtocolo(UserControl dialogControl, string hostName) + { + List list; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List webEditors = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + webEditors.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (obj == null || obj is bool) + { + list = null; + } + else + { + list = ((ObservableCollection)obj).ToList(); + } + return list; + } + + public async Task> ExecuteRunExtendedDialogReordenarItens(UserControl dialogControl, string hostName) + { + ObservableCollection observableCollection; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (obj == null || obj is bool) + { + observableCollection = null; + } + else + { + observableCollection = (ObservableCollection)obj; + } + return observableCollection; + } + + public async Task> ExecuteRunExtendedDialogSelecionarItens(UserControl dialogControl, string hostName) + { + ObservableCollection observableCollection; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + observableCollection = (ObservableCollection)obj; + } + else + { + observableCollection = null; + } + return observableCollection; + } + + public async Task ExecuteRunExtendedDialogTarefa(UserControl dialogControl, string hostName) + { + Tarefa tarefa; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + tarefa = (Tarefa)obj; + } + else + { + tarefa = null; + } + return tarefa; + } + + public async Task ExecuteRunExtendedDialogVinculo(UserControl dialogControl, string hostName) + { + VinculoRepasse vinculoRepasse; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + vinculoRepasse = (VinculoRepasse)obj; + } + else + { + vinculoRepasse = null; + } + return vinculoRepasse; + } + + public List FilterCliente(List clientes, string searchText) + { + return clientes.Where((Cliente x) => { + if (x.get_Nome().ToUpper().Contains(searchText.ToUpper()) || x.get_Documento() != null && x.get_Documento().Contains(searchText) || x.get_Rne() != null && x.get_Rne().Contains(searchText)) + { + return true; + } + if (x.get_Cei() == null) + { + return false; + } + return x.get_Cei().Contains(searchText); + }).ToList(); + } + + internal async Task ShowBuscaModeloDialog(string modelo, string ano) + { + Fipe fipe; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + BuscarModeloView buscarModeloView = new BuscarModeloView(new BuscarModeloViewModel(modelo, ano)); + BaseSegurosViewModel baseSegurosViewModel = this; + BuscarModeloView buscarModeloView1 = buscarModeloView; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + fipe = await baseSegurosViewModel.ExecuteRunExtendedDialogBuscaModelo(buscarModeloView1, str); + } + else + { + fipe = null; + } + return fipe; + } + + internal async Task, Usuario, List, List, List>> ShowCopiarPermissaoDialog() + { + Tuple, Usuario, List, List, List> tuple; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogCopiarPermissao dialogCopiarPermissao = new DialogCopiarPermissao(new DialogCopiarPermissaoViewModel()); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogCopiarPermissao dialogCopiarPermissao1 = dialogCopiarPermissao; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + tuple = await baseSegurosViewModel.ExecuteRunExtendedDialogCopiarPermiss(dialogCopiarPermissao1, str); + } + else + { + tuple = null; + } + return tuple; + } + + internal async Task ShowDetalheExtrato(List detalhes) + { + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogDetalheExtrato dialogDetalheExtrato = new DialogDetalheExtrato(detalhes); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogDetalheExtrato dialogDetalheExtrato1 = dialogDetalheExtrato; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseSegurosViewModel.ExecuteRunExtendedDialogDetalheExtrato(dialogDetalheExtrato1, str); + } + } + + internal async Task ShowEditarParcelasDialog(Documento documento) + { + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogEditarParcelas dialogEditarParcela = new DialogEditarParcelas(documento); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogEditarParcelas dialogEditarParcela1 = dialogEditarParcela; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseSegurosViewModel.ExecuteRunExtendedDialogEditarParcelas(dialogEditarParcela1, str); + } + } + + internal async Task ShowEnviarEmailsDialog(List lista, bool assinatura, bool original, List arquivosAnexados, string assunto, string corpo, Credencial credencial, FiltroArquivoDigital filtro, bool salvarAd, bool confirmarLeitura) + { + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogEnviarEmails dialogEnviarEmail = new DialogEnviarEmails(new DialogEnviarEmailsViewModel(lista, assinatura, original, arquivosAnexados, assunto, corpo, credencial, filtro, salvarAd, confirmarLeitura)); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogEnviarEmails dialogEnviarEmail1 = dialogEnviarEmail; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseSegurosViewModel.ExecuteRunExtendedDialogEnviarEmails(dialogEnviarEmail1, str); + } + } + + internal async Task> ShowExportarPermissaoDialog(long idUsuario) + { + List usuarios; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogExportarPermissao dialogExportarPermissao = new DialogExportarPermissao(new DialogExportarPermissaoViewModel(idUsuario)); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogExportarPermissao dialogExportarPermissao1 = dialogExportarPermissao; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + usuarios = await baseSegurosViewModel.ExecuteRunExtendedDialogExportarPermiss(dialogExportarPermissao1, str); + } + else + { + usuarios = null; + } + return usuarios; + } + + internal async Task ShowLogAcessoDialog(TipoTela tela, Usuario usuario) + { + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogLogAcesso dialogLogAcesso = new DialogLogAcesso(tela, usuario); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogLogAcesso dialogLogAcesso1 = dialogLogAcesso; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseSegurosViewModel.ExecuteRunExtendedDialogEnviarEmails(dialogLogAcesso1, str); + } + } + + internal async Task ShowObservacaoDialog() + { + string str; + string str1; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogObservacao dialogObservacao = new DialogObservacao(); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogObservacao dialogObservacao1 = dialogObservacao; + str1 = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + str = await baseSegurosViewModel.ExecuteRunExtendedDialogObservacao(dialogObservacao1, str1); + } + else + { + str = null; + } + return str; + } + + internal async Task ShowPesquisaAvancadaDialog() + { + PesquisaAvancada pesquisaAvancada; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel = new DialogPesquisaAvancadaViewModel(); + DialogPesquisaAvancada dialogPesquisaAvancada = new DialogPesquisaAvancada(dialogPesquisaAvancadaViewModel) + { + DataContext = dialogPesquisaAvancadaViewModel + }; + BaseSegurosViewModel baseSegurosViewModel = this; + DialogPesquisaAvancada dialogPesquisaAvancada1 = dialogPesquisaAvancada; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + pesquisaAvancada = await baseSegurosViewModel.ExecuteRunExtendedDialogPesquisaAvancada(dialogPesquisaAvancada1, str); + } + else + { + pesquisaAvancada = null; + } + return pesquisaAvancada; + } + + internal async Task> ShowProtocoloDialog(List itens) + { + List documentos; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogProtocolo dialogProtocolo = new DialogProtocolo(itens); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogProtocolo dialogProtocolo1 = dialogProtocolo; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + documentos = await baseSegurosViewModel.ExecuteRunExtendedDialogProtocolo(dialogProtocolo1, str); + } + else + { + documentos = null; + } + return documentos; + } + + internal async Task> ShowReordenarItensDialog(List ids) + { + ObservableCollection observableCollection; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogReordenarItens dialogReordenarIten = new DialogReordenarItens(ids); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogReordenarItens dialogReordenarIten1 = dialogReordenarIten; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + observableCollection = await baseSegurosViewModel.ExecuteRunExtendedDialogReordenarItens(dialogReordenarIten1, str); + } + else + { + observableCollection = null; + } + return observableCollection; + } + + internal async Task> ShowSelecionarItensDialog(long id) + { + ObservableCollection observableCollection; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogSelecionarItens dialogSelecionarIten = new DialogSelecionarItens(id); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogSelecionarItens dialogSelecionarIten1 = dialogSelecionarIten; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + observableCollection = await baseSegurosViewModel.ExecuteRunExtendedDialogSelecionarItens(dialogSelecionarIten1, str); + } + else + { + observableCollection = null; + } + return observableCollection; + } + + internal async Task ShowTarefaDialog(Tarefa tarefa, bool nota = false, bool agendamento = false) + { + Tarefa tarefa1; + bool idCliente; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + List telefoneBases = new List(); + Tarefa tarefa2 = tarefa; + if (tarefa2 != null) + { + idCliente = tarefa2.get_IdCliente() > (long)0; + } + else + { + idCliente = false; + } + if (idCliente) + { + ObservableCollection observableCollection = await (new ClienteServico()).BuscarTelefonesAsync(tarefa.get_IdCliente()); + IEnumerable clienteTelefones = + from x in observableCollection + where ValidationHelper.ValidacaoTelefone(x.get_Numero()) + select x; + telefoneBases = clienteTelefones.Select((ClienteTelefone x) => { + TelefoneBase telefoneBase = new TelefoneBase(); + telefoneBase.set_Tipo(x.get_Tipo()); + telefoneBase.set_Id(x.get_Id()); + telefoneBase.set_Numero(x.get_Numero()); + telefoneBase.set_Prefixo(x.get_Prefixo()); + return telefoneBase; + }).ToList(); + } + DialogTarefa dialogTarefa = new DialogTarefa(tarefa, telefoneBases, nota, agendamento); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogTarefa dialogTarefa1 = dialogTarefa; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + tarefa1 = await baseSegurosViewModel.ExecuteRunExtendedDialogTarefa(dialogTarefa1, str); + } + else + { + tarefa1 = null; + } + host = null; + return tarefa1; + } + + internal async Task ShowVinculoDialog(VinculoRepasse vinculo, List repasses, Repasse repasse) + { + VinculoRepasse vinculoRepasse; + string str; + DialogHost host = base.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogVinculo dialogVinculo = new DialogVinculo(vinculo, repasses, repasse); + BaseSegurosViewModel baseSegurosViewModel = this; + DialogVinculo dialogVinculo1 = dialogVinculo; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + vinculoRepasse = await baseSegurosViewModel.ExecuteRunExtendedDialogVinculo(dialogVinculo1, str); + } + else + { + vinculoRepasse = null; + } + return vinculoRepasse; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs new file mode 100644 index 0000000..ad8c5a5 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs @@ -0,0 +1,233 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public abstract class BaseTarefaViewModel : BaseSegurosViewModel + { + private ObservableCollection _responsaveis = new ObservableCollection(); + + private bool _hasResponsaveis; + + public abstract bool EnableAlterarTarefa + { + get; + set; + } + + public bool HasResponsaveis + { + get + { + return this._hasResponsaveis; + } + set + { + this._hasResponsaveis = value; + base.OnPropertyChanged("HasResponsaveis"); + } + } + + public ObservableCollection Responsaveis + { + get + { + return this._responsaveis; + } + set + { + this._responsaveis = value; + this.HasResponsaveis = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("Responsaveis"); + } + } + + public abstract Tarefa SelectedTarefa + { + get; + set; + } + + public TarefaServico Servico + { + get; + set; + } + + protected BaseTarefaViewModel() + { + } + + internal async Task BuscaPermisaoUsuario() + { + return await (new PermissaoUsuarioServico()).VerificarPermissao(Recursos.Usuario, 38); + } + + public void ListaUsuariosResponsaveis() + { + bool usuario; + Tarefa selectedTarefa = this.SelectedTarefa; + if (selectedTarefa != null) + { + usuario = selectedTarefa.get_Usuario(); + } + else + { + usuario = false; + } + if (!usuario) + { + return; + } + if (!this.Responsaveis.Any((ResponsavelTarefa r) => r.get_Usuario().get_Id() == this.SelectedTarefa.get_Usuario().get_Id())) + { + ObservableCollection responsaveis = this.Responsaveis; + ResponsavelTarefa responsavelTarefa = new ResponsavelTarefa(); + responsavelTarefa.set_IdTarefa(this.SelectedTarefa.get_Id()); + responsavelTarefa.set_Usuario(this.SelectedTarefa.get_Usuario()); + responsaveis.Insert(0, responsavelTarefa); + } + } + + public async Task ValidaPermissaoParaEditarTarefa() + { + bool flag; + bool flag1; + bool flag2; + bool id; + bool flag3; + bool flag4 = false; + if (this.SelectedTarefa != null) + { + PermissaoUsuario permissaoUsuario = await this.BuscaPermisaoUsuario(); + if (Recursos.Usuario.get_Administrador()) + { + flag4 = true; + } + else if (permissaoUsuario == null && !this.SelectedTarefa.get_Restrito().GetValueOrDefault()) + { + flag4 = true; + } + else if (permissaoUsuario != null && !permissaoUsuario.get_Alterar()) + { + flag4 = false; + } + else if (!this.SelectedTarefa.get_Restrito().GetValueOrDefault()) + { + flag4 = true; + } + else + { + if (this.SelectedTarefa.get_UsuarioCadastro().get_Id() != Recursos.Usuario.get_Id()) + { + List responsaveis = this.SelectedTarefa.get_Responsaveis(); + if (responsaveis != null) + { + flag3 = responsaveis.Any((ResponsavelTarefa x) => x.get_Usuario().get_Id() == Recursos.Usuario.get_Id()); + } + else + { + flag3 = false; + } + if (flag3) + { + goto Label1; + } + id = this.SelectedTarefa.get_Usuario().get_Id() == Recursos.Usuario.get_Id(); + goto Label0; + } + Label1: + id = true; + Label0: + flag4 = id; + } + bool flag5 = flag4; + bool flag6 = flag5; + this.EnableAlterarTarefa = flag5; + bool flag7 = flag6; + flag2 = flag7; + base.EnableExcluir = flag7; + bool flag8 = flag2; + flag1 = flag8; + base.EnableAlterar = flag8; + flag = flag1; + } + else + { + bool flag9 = flag4; + flag2 = flag9; + this.EnableAlterarTarefa = flag9; + bool flag10 = flag2; + flag1 = flag10; + base.EnableExcluir = flag10; + base.EnableAlterar = flag1; + flag = flag4; + } + return flag; + } + + public async Task ValidaPermissaoParaExcluirTarefa(Tarefa tarefa = null) + { + bool id; + bool flag; + if (tarefa != null) + { + this.SelectedTarefa = tarefa; + } + PermissaoUsuario permissaoUsuario = await this.BuscaPermisaoUsuario(); + bool flag1 = false; + if (Recursos.Usuario.get_Administrador()) + { + flag1 = true; + } + else if (permissaoUsuario == null && !this.SelectedTarefa.get_Restrito().GetValueOrDefault()) + { + flag1 = true; + } + else if (permissaoUsuario != null && !permissaoUsuario.get_Excluir()) + { + flag1 = false; + } + else if (!this.SelectedTarefa.get_Restrito().GetValueOrDefault()) + { + flag1 = true; + } + else + { + if (this.SelectedTarefa.get_UsuarioCadastro().get_Id() != Recursos.Usuario.get_Id()) + { + List responsaveis = this.SelectedTarefa.get_Responsaveis(); + if (responsaveis != null) + { + flag = responsaveis.Any((ResponsavelTarefa x) => x.get_Usuario().get_Id() == Recursos.Usuario.get_Id()); + } + else + { + flag = false; + } + if (flag) + { + goto Label1; + } + id = this.SelectedTarefa.get_Usuario().get_Id() == Recursos.Usuario.get_Id(); + goto Label0; + } + Label1: + id = true; + Label0: + flag1 = id; + } + return flag1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/BaseViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/BaseViewModel.cs new file mode 100644 index 0000000..e680922 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/BaseViewModel.cs @@ -0,0 +1,3140 @@ +using Agger.Registro; +using Gestor.Application; +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Application.Properties; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Financeiro; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using MaterialDesignThemes.Wpf; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; +using System.Windows.Input; +using System.Windows.Threading; +using Xceed.Wpf.AvalonDock.Controls; + +namespace Gestor.Application.ViewModels.Generic +{ + public abstract class BaseViewModel : INotifyPropertyChanged + { + public Gestor.Application.Servicos.ArquivoDigitalServico ArquivoDigitalServico; + + public PermissaoArquivoDigitalServico ServicoPermissArquivoDigital; + + public PermissaoUsuarioServico ServicoPermissUsuario; + + public RestricaoUsuarioServico ServicoRestriUsuario; + + public VendedorUsuarioServico ServicoVendedorUsuario; + + public bool _incluirPermissEnabled; + + public bool _alterarPermissEnabled; + + public bool _excluirPermissEnabled; + + public long LastAccessId; + + public TipoTela LastAccessTela; + + private bool _enableButtons = true; + + private bool _enableIncluir = true; + + private bool _isVisibleEmpresa; + + private bool _enableAlterar; + + private bool _enableExcluir; + + private long? _lastId; + + private bool _incluirParcelaEnabled; + + private bool _alterarParcelaEnabled; + + private bool _excluirParcelaEnabled; + + private bool _permissaoWhatsapp; + + public bool Initialized; + + private bool _enableFields; + + private bool _allowEditParcela; + + private bool _isEnableEdit; + + private bool _isEnabledEditEndosso; + + private bool _enableMenu; + + private bool _enableMainMenu; + + private bool _isEnabled; + + private Visibility _isVisible; + + private object _popupContent; + + public bool AllowEditParcela + { + get + { + return this._allowEditParcela; + } + set + { + this._allowEditParcela = value; + this.OnPropertyChanged("AllowEditParcela"); + } + } + + public bool AlterarParcelaEnabled + { + get + { + return this._alterarParcelaEnabled; + } + set + { + this._alterarParcelaEnabled = value; + this.OnPropertyChanged("AlterarParcelaEnabled"); + } + } + + public AutoCompleteFilterPredicate CoberturaItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_1610 = BaseViewModel.u003cu003ec.u003cu003e9__161_0; + if (u003cu003e9_1610 == null) + { + u003cu003e9_1610 = new AutoCompleteFilterPredicate(BaseViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => ((CoberturaPadrao)obj).get_Descricao().ToUpper().Contains(searchText.ToUpper())); + BaseViewModel.u003cu003ec.u003cu003e9__161_0 = u003cu003e9_1610; + } + return u003cu003e9_1610; + } + } + + public bool EnableAlterar + { + get + { + return this._enableAlterar; + } + set + { + this._enableAlterar = this._alterarPermissEnabled & value; + this.OnPropertyChanged("EnableAlterar"); + } + } + + public bool EnableButtons + { + get + { + return this._enableButtons; + } + set + { + this._enableButtons = value; + this.OnPropertyChanged("EnableButtons"); + } + } + + public bool EnableExcluir + { + get + { + return this._enableExcluir; + } + set + { + this._enableExcluir = this._excluirPermissEnabled & value; + this.OnPropertyChanged("EnableExcluir"); + } + } + + public bool EnableFields + { + get + { + return this._enableFields; + } + set + { + this._enableFields = value; + this.OnPropertyChanged("EnableFields"); + } + } + + public bool EnableIncluir + { + get + { + return this._enableIncluir; + } + set + { + this._enableIncluir = this._incluirPermissEnabled & value; + this.OnPropertyChanged("EnableIncluir"); + } + } + + public bool EnableMainMenu + { + get + { + return this._enableMainMenu; + } + set + { + this._enableMainMenu = value; + this.OnPropertyChanged("EnableMainMenu"); + } + } + + public bool EnableMenu + { + get + { + return this._enableMenu; + } + set + { + this._enableMenu = value; + this.OnPropertyChanged("EnableMenu"); + } + } + + public string ErroCamposInvalidos + { + get; + } + + public bool ExcluirParcelaEnabled + { + get + { + return this._excluirParcelaEnabled; + } + set + { + this._excluirParcelaEnabled = value; + this.OnPropertyChanged("ExcluirParcelaEnabled"); + } + } + + public bool IncluirParcelaEnabled + { + get + { + return this._incluirParcelaEnabled; + } + set + { + this._incluirParcelaEnabled = value; + this.OnPropertyChanged("IncluirParcelaEnabled"); + } + } + + public bool IsEnabled + { + get + { + return this._isEnabled; + } + set + { + this._isEnabled = value; + this.OnPropertyChanged("IsEnabled"); + } + } + + public bool IsEnabledEdit + { + get + { + return this._isEnableEdit; + } + set + { + this._isEnableEdit = value; + this.OnPropertyChanged("IsEnabledEdit"); + } + } + + public bool IsEnabledEditEndosso + { + get + { + return this._isEnabledEditEndosso; + } + set + { + this._isEnabledEditEndosso = value; + this.OnPropertyChanged("IsEnabledEditEndosso"); + } + } + + public Visibility IsVisible + { + get + { + return this._isVisible; + } + set + { + this._isVisible = value; + this.OnPropertyChanged("IsVisible"); + } + } + + public bool IsVisibleEmpresa + { + get + { + return this._isVisibleEmpresa; + } + set + { + this._isVisibleEmpresa = value; + this.OnPropertyChanged("IsVisibleEmpresa"); + } + } + + public bool PermissaoWhatsapp + { + get + { + return this._permissaoWhatsapp; + } + set + { + this._permissaoWhatsapp = value; + this.OnPropertyChanged("PermissaoWhatsapp"); + } + } + + public object PopupContent + { + get + { + return this._popupContent; + } + set + { + this._popupContent = value; + this.OnPropertyChanged("PopupContent"); + } + } + + protected BaseViewModel() + { + this._enableButtons = true; + this._enableIncluir = true; + if (LicenseHelper.Produtos != null) + { + if (!LicenseHelper.Produtos.Any((Licenca x) => { + if (x.get_Produto() != 2) + { + return false; + } + return x.get_Status() == 1; + })) + { + goto Label1; + } + Empresa empresa = Recursos.Empresa; + if (empresa != null) + { + id = empresa.get_Id() == (long)1; + goto Label0; + } + else + { + id = false; + goto Label0; + } + } + Label1: + id = false; + Label0: + this._isVisibleEmpresa = id; + this._enableAlterar = true; + this._enableExcluir = true; + this._permissaoWhatsapp = true; + this._allowEditParcela = true; + this._isEnableEdit = true; + this._isEnabledEditEndosso = true; + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + flag = usuario.get_Id() > (long)0; + } + else + { + flag = false; + } + this._enableMenu = flag; + this._enableMainMenu = true; + this._isEnabled = true; + this._isVisible = Visibility.Collapsed; + this.ErroCamposInvalidos = string.Concat("HÁ CAMPOS DESTACADOS QUE DEVEM SER PREENCHIDOS CORRETAMENTE.", Environment.NewLine, "REALIZE A CORREÇÃO E TENTE NOVAMENTE."); + base(); + bool id; + bool flag; + this.ArquivoDigitalServico = new Gestor.Application.Servicos.ArquivoDigitalServico(); + Gestor.Application.Actions.Actions.EnableMainMenu = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnableMainMenu, new Action(this.HabilitarMenu)); + Gestor.Application.Actions.Actions.EnableMenu = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnableMenu, new Action(this.HabilitarMenuSecundario)); + this.ServicoPermissArquivoDigital = new PermissaoArquivoDigitalServico(); + this.ServicoPermissUsuario = new PermissaoUsuarioServico(); + this.ServicoRestriUsuario = new RestricaoUsuarioServico(); + this.ServicoVendedorUsuario = new VendedorUsuarioServico(); + } + + public bool Abrir(IndiceArquivoDigital indice, Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + bool flag; + string tempPath = Path.GetTempPath(); + Guid? azureGuid = arquivo.get_AzureGuid(); + string str = string.Format("{0}{1}{2}", tempPath, (azureGuid.HasValue ? azureGuid.GetValueOrDefault() : Guid.NewGuid()), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivo.get_Extensao())); + try + { + using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(str, FileMode.Create))) + { + binaryWriter.Write(arquivo.get_Arquivo()); + } + Process.Start(str); + return true; + } + catch (Exception exception) + { + flag = false; + } + return flag; + } + + public async void AbrirLog(TipoTela tipoTela, long id) + { + if (Recursos.Usuario.get_Id() != 0) + { + RestricaoUsuario restricaoUsuario = this.ServicoRestriUsuario.BuscarRestricao(Recursos.Usuario, 109); + if (restricaoUsuario == null || !restricaoUsuario.get_Restricao()) + { + this.ShowDrawer(new LogDrawer(tipoTela, id, null, 0), 0, false); + } + else + { + await this.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR OS LOGS", "OK", "", false); + } + } + else + { + this.ShowDrawer(new LogDrawer(tipoTela, id, null, 0), 0, false); + } + } + + public async void AbrirLogEmail(TipoTela tela, long id) + { + if (Recursos.Usuario.get_Id() != 0) + { + RestricaoUsuario restricaoUsuario = this.ServicoRestriUsuario.BuscarRestricao(Recursos.Usuario, 109); + if (restricaoUsuario == null || !restricaoUsuario.get_Restricao()) + { + this.ShowDrawer(new LogEmailDrawer(tela, id, false), 0, false); + } + else + { + await this.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR OS LOGS", "OK", "", false); + } + } + else + { + this.ShowDrawer(new LogEmailDrawer(tela, id, false), 0, false); + } + } + + public async void AbrirLogParcela(List parcelas, long documento, int numparcela = 0) + { + if (Recursos.Usuario.get_Id() != 0) + { + RestricaoUsuario restricaoUsuario = this.ServicoRestriUsuario.BuscarRestricao(Recursos.Usuario, 109); + if (restricaoUsuario == null || !restricaoUsuario.get_Restricao()) + { + this.ShowDrawer(new LogDrawer(5, documento, parcelas, numparcela), 0, false); + } + else + { + await this.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR OS LOGS", "OK", "", false); + } + } + else + { + this.ShowDrawer(new LogDrawer(5, documento, parcelas, numparcela), 0, false); + } + } + + public async Task> AddAttachments(List attachments, List attacheds) + { + List arquivoDigitals; + List arquivoDigitals1; + List strs = new List(); + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Multiselect = true; + openFileDialog.Filter = "Todos os Arquivos|*.pdf;*.jpg;*.jpeg;*.png;*.bmp;*.doc;*.docx;*.xls;*.xlsx;*.json;*.rar;*.zip;*.msg;*.eml;*.txt|Arquivos PDF|*.pdf|Imagens|*.jpg;*.jpeg;*.png;*.bmp|Documentos|*.doc;*.docx;*.msg|Planilhas|*.xls;*.xlsx|Arquivos do Aggilizador|*.json|Arquivos de Áudio|*.amr;*.ogg"; + openFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString(); + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + strs.AddRange(openFileDialog.FileNames); + } + else + { + arquivoDigitals = null; + return arquivoDigitals; + } + } + strs = await this.ValidateAttachment(attachments, strs); + strs = await this.ValidateAttachment(attacheds, strs); + attachments = new List(); + foreach (string str in strs) + { + int num = 0; + try + { + string extension = Path.GetExtension(str); + using (MemoryStream memoryStream = new MemoryStream(File.ReadAllBytes(str))) + { + byte[] numArray = new byte[checked((IntPtr)memoryStream.Length)]; + memoryStream.Position = (long)0; + memoryStream.Read(numArray, 0, (int)numArray.Length); + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = new Gestor.Model.Domain.Common.ArquivoDigital(); + arquivoDigital.set_Arquivo(numArray); + arquivoDigital.set_Descricao(Path.GetFileNameWithoutExtension(str)); + arquivoDigital.set_Extensao(extension); + attachments.Add(arquivoDigital); + } + } + catch (Exception exception) + { + num = 1; + } + if (num != 1) + { + continue; + } + string[] newLine = new string[] { "NÃO FOI POSSÍVEL CARREGAR O ARQUIVO ", str, ".", Environment.NewLine, "O ARQUIVO ESTÁ INACESSÍVEL OU SENDO UTILIZADO POR OUTRO PROCESSO." }; + await this.ShowMessage(string.Concat(newLine), "OK", "", false); + } + if (attachments.Count == 0) + { + arquivoDigitals1 = null; + } + else + { + arquivoDigitals1 = attachments; + } + arquivoDigitals = arquivoDigitals1; + return arquivoDigitals; + } + + public async void Alterar(bool alterar) + { + Action enablePesquisarClientes = Gestor.Application.Actions.Actions.EnablePesquisarClientes; + if (enablePesquisarClientes != null) + { + enablePesquisarClientes(!alterar); + } + else + { + } + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(!alterar); + } + else + { + } + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(!alterar); + } + else + { + } + this.EnableFields = alterar; + this.EnableMenu = !alterar; + if (alterar) + { + this.EnableIncluir = false; + this.EnableAlterar = false; + this.EnableExcluir = false; + this.EnableButtons = false; + } + else + { + this.VerificarEnables(this._lastId); + } + this.AllowEditParcela = !alterar; + this.IsEnabledEdit = !alterar; + this.IsEnabledEditEndosso = !alterar; + if ((Funcoes.GetNetworkTime() - ApplicationHelper.ChecagemVersao).TotalMinutes > 10) + { + await this.VerificarVersao(); + } + } + + public async Task BuscaCep(string cep) + { + return await (new CepService()).SearchDirect(cep); + } + + internal async Task> BuscarBanco(string value) + { + List bancos = await Task.Run>(() => (new BaseServico()).BuscarBanco(value)); + return bancos; + } + + internal void CloseDrawer() + { + Window window = System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive); + DrawerHost drawerHost = Extentions.FindVisualChildren(window).FirstOrDefault(); + Extentions.FindVisualChildren(window).ToList().ForEach((WebEditor x) => x.Visibility = Visibility.Visible); + if (drawerHost == null) + { + return; + } + drawerHost.set_IsBottomDrawerOpen(false); + drawerHost.set_IsTopDrawerOpen(false); + if (drawerHost.get_IsLeftDrawerOpen()) + { + drawerHost.set_IsLeftDrawerOpen(false); + return; + } + drawerHost.set_IsRightDrawerOpen(false); + } + + private void CloseSlackBar() + { + Thread.Sleep(5000); + Dispatcher dispatcher = App.ProgressRing.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.ToggleSnackBar("", false))); + } + + private async Task CreateDialogAdvertising() + { + DialogAdvertising dialogAdvertising; + DateTime? nullable; + DialogAdvertising dialogAdvertising1; + DateTime? nullable1; + DateTime? nullable2; + string str; + bool flag; + bool flag1; + object empty; + JObject jObject = await this.LoadJsonAdvertising(Address.get_SurveyJson()); + if (jObject != null) + { + JToken item = jObject.get_Item("Inicio"); + if (item != null) + { + nullable1 = new DateTime?(Extensions.Value(item)); + } + else + { + nullable = null; + nullable1 = nullable; + } + DateTime? nullable3 = nullable1; + JToken jToken = jObject.get_Item("Fim"); + if (jToken != null) + { + nullable2 = new DateTime?(Extensions.Value(jToken)); + } + else + { + nullable = null; + nullable2 = nullable; + } + DateTime? nullable4 = nullable2; + DateTime networkTime = Funcoes.GetNetworkTime(); + Gestor.Application.Model.Configuracoes configuraco = this.LoadConfiguracoes(); + JToken item1 = jObject.get_Item("UrlPost"); + if (item1 != null) + { + str = Extensions.Value(item1); + } + else + { + str = null; + } + string str1 = str; + if (Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(str1)) + { + JToken jToken1 = jObject.get_Item("UrlFixa"); + if (jToken1 != null) + { + empty = Extensions.Value(jToken1); + } + else + { + empty = null; + } + if (empty == null) + { + empty = string.Empty; + } + str1 = (string)empty; + } + if (configuraco.LinkPromo == str1 || configuraco.NaoverPromo) + { + dialogAdvertising = null; + } + else + { + nullable = nullable4; + DateTime dateTime = networkTime; + flag = (nullable.HasValue ? nullable.GetValueOrDefault() >= dateTime : false); + if (flag) + { + nullable = nullable3; + dateTime = networkTime; + flag1 = (nullable.HasValue ? nullable.GetValueOrDefault() <= dateTime : false); + if (!flag1) + { + goto Label1; + } + dialogAdvertising1 = new DialogAdvertising(jObject, false); + goto Label0; + } + Label1: + dialogAdvertising1 = await this.LoadDialogAdertisingPromo(); + Label0: + dialogAdvertising = dialogAdvertising1; + } + } + else + { + dialogAdvertising = await this.LoadDialogAdertisingPromo(); + } + return dialogAdvertising; + } + + private void CriarConfiguracaoPadrao(string configFile) + { + if (File.Exists(configFile)) + { + return; + } + File.WriteAllText(configFile, JsonConvert.SerializeObject(new Gestor.Application.Model.Configuracoes() + { + LinkPromo = "", + NaoverPromo = false + }, 1)); + } + + public async void Download(IndiceArquivoDigital indice, bool open = true) + { + DateTime valueOrDefault; + bool arquivo; + int? nullable; + bool flag; + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital; + if (indice.get_Id() != 0) + { + arquivoDigital = null; + if (indice.get_Assinado()) + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital1 = await this.ArquivoDigitalServico.BuscarPorId(indice.get_Id()); + if (arquivoDigital1 != null) + { + flag = arquivoDigital1.get_Arquivo(); + } + else + { + flag = false; + } + if (flag) + { + if (!arquivoDigital1.get_Extensao().Contains(".")) + { + arquivoDigital1.set_Extensao(string.Concat(".", arquivoDigital1.get_Extensao())); + } + arquivoDigital = arquivoDigital1; + } + } + if (arquivoDigital == null) + { + arquivoDigital = await this.ArquivoDigitalServico.BuscarPorId(indice.get_IdArquivoDigital(), indice.get_Bd()); + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital2 = arquivoDigital; + if (arquivoDigital2 != null) + { + arquivo = arquivoDigital2.get_Arquivo(); + } + else + { + arquivo = false; + } + if (!arquivo || arquivoDigital.get_Extensao() == null) + { + string str = "DOCUMENTO NÃO POSSUI PDF"; + DateTime? dataCriacao = indice.get_DataCriacao(); + if (dataCriacao.HasValue) + { + valueOrDefault = dataCriacao.GetValueOrDefault(); + nullable = new int?(valueOrDefault.Year); + } + else + { + nullable = null; + } + int? nullable1 = nullable; + valueOrDefault = DateTime.Now; + if (nullable1.GetValueOrDefault() <= valueOrDefault.Year - 5 & nullable1.HasValue) + { + str = string.Concat(str, " OU POR SER UM ARQUIVO ANTIGO, TENTE NOVAMENTE EM ALGUNS MINUTOS"); + } + await this.ShowMessage(string.Concat(str, "."), "OK", "", false); + } + else + { + if (open) + { + if (!this.Abrir(indice, arquivoDigital)) + { + await this.ShowMessage("NÃO FOI POSSÍVEL ABRIR O ARQUIVO. ESCOLHA UM LOCAL PARA SALVAR O ARQUIVO.", "OK", "", false); + } + else + { + arquivoDigital = null; + return; + } + } + using (SaveFileDialog saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.Filter = "All Files|*.*"; + saveFileDialog.FileName = indice.get_Descricao(); + if (DialogResult.OK != saveFileDialog.ShowDialog()) + { + arquivoDigital = null; + return; + } + else if (!File.Exists(string.Concat(saveFileDialog.FileName, Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao())))) + { + using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(string.Concat(saveFileDialog.FileName, Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao())), FileMode.Create))) + { + binaryWriter.Write(arquivoDigital.get_Arquivo()); + } + } + else + { + string[] descricao = new string[] { "JÁ EXISTE UM ARQUIVO COM O NOME DE ", arquivoDigital.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao()), " NA PASTA SELECIONADA. ", Environment.NewLine, "TENTE NOVAMENTE EM OUTRA PASTA." }; + await this.ShowMessage(string.Concat(descricao), "OK", "", false); + arquivoDigital = null; + return; + } + } + saveFileDialog = null; + } + } + arquivoDigital = null; + } + + public async Task DownloadAll(List indices, long id) + { + bool flag; + bool arquivo; + bool arquivo1; + string str; + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + str = string.Format("{0}\\{1}", folderBrowserDialog.SelectedPath, id); + Directory.CreateDirectory(str); + } + else + { + flag = false; + str = null; + return flag; + } + } + int num = 1; + foreach (IndiceArquivoDigital index in indices) + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = null; + if (index.get_Assinado()) + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital1 = await this.ArquivoDigitalServico.BuscarPorId(index.get_Id()); + if (arquivoDigital1 != null) + { + arquivo1 = arquivoDigital1.get_Arquivo(); + } + else + { + arquivo1 = false; + } + if (arquivo1) + { + arquivoDigital = arquivoDigital1; + } + } + if (arquivoDigital == null) + { + arquivoDigital = await this.ArquivoDigitalServico.BuscarPorId(index.get_IdArquivoDigital(), index.get_Bd()); + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital2 = arquivoDigital; + if (arquivoDigital2 != null) + { + arquivo = arquivoDigital2.get_Arquivo(); + } + else + { + arquivo = false; + } + if (!arquivo || arquivoDigital.get_Extensao() == null) + { + flag = false; + str = null; + return flag; + } + else + { + if (File.Exists(Gestor.Common.Validation.ValidationHelper.NormalizePath(string.Concat(str, "\\", index.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao()))))) + { + index.set_Descricao(string.Format("{0}_{1}", index.get_Descricao(), num)); + num++; + } + using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(Gestor.Common.Validation.ValidationHelper.NormalizePath(string.Concat(str, "\\", index.get_Descricao(), Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao()))), FileMode.Create))) + { + binaryWriter.Write(arquivoDigital.get_Arquivo()); + } + arquivoDigital = null; + index = null; + } + } + Process.Start(str); + flag = true; + str = null; + return flag; + } + + public async Task DownloadAll(List ids, TipoArquivoVinculo type) + { + bool arquivo; + string str; + Gestor.Application.Servicos.ArquivoDigitalServico arquivoDigitalServico; + if (ids != null && ids.Count != 0) + { + str = string.Format("{0}{1}", Path.GetTempPath(), Guid.NewGuid()); + BaseServico baseServico = new BaseServico(); + arquivoDigitalServico = new Gestor.Application.Servicos.ArquivoDigitalServico(); + List arquivoVinculos = await baseServico.ArquivoVinculo(ids, type); + int num = 1; + if (!Directory.Exists(str)) + { + Directory.CreateDirectory(str); + } + foreach (ArquivoVinculo arquivoVinculo in await arquivoDigitalServico.BaixarArquivosPendentes(arquivoVinculos)) + { + if (arquivoVinculo != null) + { + arquivo = arquivoVinculo.get_Arquivo(); + } + else + { + arquivo = false; + } + if (!arquivo) + { + continue; + } + string str1 = Guid.NewGuid().ToString(); + if (File.Exists(string.Concat(str, "\\", str1, ".pdf"))) + { + str1 = string.Format("{0}_{1}", str1, num); + num++; + } + using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(string.Concat(str, "\\", str1, ".pdf"), FileMode.Create))) + { + binaryWriter.Write(arquivoVinculo.get_Arquivo()); + } + } + Process.Start(str); + } + str = null; + arquivoDigitalServico = null; + } + + public async Task EmitirCheckList(List documentos) + { + DateTime vencimento; + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + string nome; + ParcelaServico parcelaServico = new ParcelaServico(); + string str8 = "CHECK LIST DE PROTOCOLOS"; + str8 = string.Concat(str8, "
CHECK LIST DE PROTOCOLOS

"); + str8 = string.Concat(str8, "
"); + str8 = string.Concat(str8, ""); + int num = 1; + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + str8 = string.Concat(str8, ""); + List documentos1 = documentos; + documentos = ( + from x in documentos1 + orderby x.get_Controle().get_Cliente().get_Nome() + select x).ToList(); + foreach (Documento documento in documentos) + { + Documento documento1 = documento; + ObservableCollection observableCollection = await parcelaServico.BuscarParcelasAsync(documento.get_Id()); + documento1.set_Parcelas(observableCollection); + documento1 = null; + string[] strArrays = new string[] { str8, ""; + str8 = string.Concat(strArrays); + string[] apolice = new string[] { str8, ""; + str8 = string.Concat(apolice); + if (documento.get_Parcelas() != null) + { + ObservableCollection parcelas = documento.get_Parcelas(); + if (( + from x in parcelas + where x.get_SubTipo() == 1 + select x).ToList().Count <= 0) + { + goto Label1; + } + ObservableCollection parcelas1 = documento.get_Parcelas(); + vencimento = ( + from x in parcelas1 + where x.get_NumeroParcela() == 1 + select x).First().get_Vencimento(); + vencimento = vencimento.Date; + str2 = vencimento.ToString("dd/MM/yyyy"); + goto Label0; + } + Label1: + str2 = ""; + Label0: + string str9 = str2; + string[] strArrays1 = new string[] { str8, ""; + str8 = string.Concat(strArrays1); + if (documento.get_Parcelas() != null) + { + ObservableCollection observableCollection1 = documento.get_Parcelas(); + if (( + from x in observableCollection1 + where x.get_SubTipo() == 1 + select x).ToList().Count <= 1) + { + goto Label3; + } + ObservableCollection parcelas2 = documento.get_Parcelas(); + vencimento = ( + from x in parcelas2 + where x.get_NumeroParcela() == 2 + select x).First().get_Vencimento(); + vencimento = vencimento.Date; + str4 = vencimento.ToString("dd/MM/yyyy"); + goto Label2; + } + Label3: + str4 = ""; + Label2: + str9 = str4; + string[] strArrays2 = new string[] { str8, ""; + str8 = string.Concat(strArrays2); + string str10 = str8; + str6 = (num % 2 == 0 ? "WhiteSmoke" : "White"); + str8 = string.Concat(str10, ""); + string[] strArrays3 = new string[] { str8, ""; + str8 = string.Concat(strArrays3); + if (num != 1) + { + num++; + } + else + { + num = 0; + } + } + DateTime networkTime = Funcoes.GetNetworkTime(); + string nome1 = Recursos.Usuario.get_Nome(); + str8 = string.Concat(str8, "
CLIENTEAPÓLICE1ª PARCELA2ª PARCELARECEBIDA PORVENDEDOR
"; + strArrays[4] = documento.get_Controle().get_Cliente().get_Nome(); + strArrays[5] = ""; + apolice[4] = documento.get_Apolice(); + apolice[5] = ""; + strArrays1[4] = str9; + strArrays1[5] = ""; + strArrays2[4] = str9; + strArrays2[5] = "____________/____/___"; + Vendedor vendedorPrincipal = documento.get_VendedorPrincipal(); + if (vendedorPrincipal != null) + { + nome = vendedorPrincipal.get_Nome(); + } + else + { + nome = null; + } + strArrays3[4] = nome; + strArrays3[5] = "
"); + string str11 = str8; + int count = documentos.Count; + str8 = string.Concat(str11, "
TOTAL DE PROTOCOLOS: ", count.ToString(), "
"); + str8 = string.Concat(str8, string.Format("Emitido pelo usuário: {0}, data e hora: {1}.", nome1, networkTime)); + str8 = string.Concat(str8, ""); + string tempPath = Path.GetTempPath(); + string str12 = string.Format("{0}{1}CheckList_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, networkTime); + StreamWriter streamWriter = new StreamWriter(str12, true, Encoding.UTF8); + streamWriter.Write(str8); + streamWriter.Close(); + Process.Start(str12); + parcelaServico = null; + str8 = null; + } + + public async Task EmitirProtocolos(List> lista, bool doisPorPagina, List protocolo) + { + DateTime vigencia1; + string str; + ClienteEndereco clienteEndereco; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + string str8; + bool flag; + string email; + string str9; + string str10; + string shortDateString; + string shortDateString1; + string shortDateString2; + string str11; + string obsProtocolo; + string str12; + string pasta; + string nome; + string str13; + string str14; + string str15; + object obj; + string shortDateString3; + string shortDateString4; + string str16; + object obj1; + int num = 0; + DateTime networkTime = Funcoes.GetNetworkTime(); + int num1 = 0; + StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder1 = new StringBuilder(); + foreach (Tuple listum in lista) + { + num1++; + ApoliceServico apoliceServico = new ApoliceServico(); + ItemServico itemServico = new ItemServico(); + ClienteServico clienteServico = new ClienteServico(); + ParcelaServico parcelaServico = new ParcelaServico(); + Documento documento = await apoliceServico.BuscarApoliceAsync(listum.Item1, false, false); + Documento documento1 = documento; + documento1.get_Controle().get_Cliente().set_Telefones(clienteServico.BuscarTelefones(documento1.get_Controle().get_Cliente().get_Id())); + Cliente cliente = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection = await clienteServico.BuscarEmailsAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente.set_Emails(observableCollection); + cliente = null; + cliente = documento1.get_Controle().get_Cliente(); + ObservableCollection observableCollection1 = await clienteServico.BuscarEnderecosAsync(documento1.get_Controle().get_Cliente().get_Id()); + cliente.set_Enderecos(observableCollection1); + cliente = null; + if (documento1.get_VendedorPrincipal() == null) + { + Documento documento2 = documento1; + Vendedor vendedor = await apoliceServico.BuscarVendedorPrincipal(documento1.get_Controle().get_Id()); + documento2.set_VendedorPrincipal(vendedor); + documento2 = null; + } + ObservableCollection observableCollection2 = await itemServico.BuscarItems(documento1.get_Id(), 2, false); + if (observableCollection2 == null || observableCollection2.Count == 0) + { + observableCollection2 = await itemServico.BuscarItens(documento1.get_Controle().get_Id(), 3); + } + ObservableCollection observableCollection3 = await parcelaServico.BuscarParcelasAsync(documento1.get_Id()); + documento1.set_ProtocoloEmail(protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloEmail()); + documento1.set_ProtocoloTelefone(protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloTelefone()); + documento1.set_ProtocoloParcela(protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloParcela()); + documento1.set_ProtocoloEndereco(protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloEndereco()); + documento1.set_ProtocoloVendedor(protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloVendedor()); + ObservableCollection telefones = documento1.get_Controle().get_Cliente().get_Telefones(); + if (documento1.get_ProtocoloTelefone() && telefones != null) + { + ObservableCollection observableCollection4 = telefones; + if (!( + from t in observableCollection4 + where !string.IsNullOrEmpty(t.get_Numero()) + select t).Any()) + { + goto Label1; + } + ObservableCollection observableCollection5 = telefones; + IEnumerable clienteTelefones = + from t in observableCollection5 + where !string.IsNullOrEmpty(t.get_Numero()) + select t; + str = string.Join(" | ", ( + from t in clienteTelefones + select string.Concat(t.get_Prefixo(), " ", t.get_Numero())).ToList()); + goto Label0; + } + Label1: + str = null; + Label0: + string str17 = string.Concat("Telefone: ", str, ""); + ObservableCollection enderecos = documento1.get_Controle().get_Cliente().get_Enderecos(); + if (enderecos != null) + { + clienteEndereco = enderecos.FirstOrDefault(); + } + else + { + clienteEndereco = null; + } + ClienteEndereco clienteEndereco1 = clienteEndereco; + if (protocolo.Find((Documento x) => x.get_Id() == documento1.get_Id()).get_ProtocoloEndereco()) + { + string[] strArrays = new string[12]; + str1 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Endereco()) ? "" : clienteEndereco1.get_Endereco()); + strArrays[0] = str1; + strArrays[1] = ", "; + str2 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Numero()) ? "" : clienteEndereco1.get_Numero()); + strArrays[2] = str2; + str3 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Complemento()) ? "" : string.Concat(" - ", clienteEndereco1.get_Complemento())); + strArrays[3] = str3; + strArrays[4] = " - "; + str4 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Bairro()) ? "" : clienteEndereco1.get_Bairro()); + strArrays[5] = str4; + strArrays[6] = " - "; + str5 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Cidade()) ? "" : clienteEndereco1.get_Cidade()); + strArrays[7] = str5; + strArrays[8] = " - "; + str6 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Estado()) ? "" : clienteEndereco1.get_Estado()); + strArrays[9] = str6; + strArrays[10] = ", "; + str7 = (string.IsNullOrWhiteSpace(clienteEndereco1.get_Cep()) ? "" : clienteEndereco1.get_Cep()); + strArrays[11] = str7; + str8 = string.Concat(strArrays); + } + else + { + str8 = null; + } + string str18 = str8; + ObservableCollection emails = documento1.get_Controle().get_Cliente().get_Emails(); + flag = (!documento1.get_ProtocoloEmail() || emails == null || emails.Count <= 0 ? false : !string.IsNullOrEmpty(emails.First().get_Email())); + if (flag) + { + email = emails.First().get_Email(); + } + else + { + email = null; + } + string str19 = string.Concat(" Email: ", email, ""); + str9 = (telefones != null || clienteEndereco1 != null || emails != null ? "" : "style='display:none;'"); + string str20 = str9; + str10 = (string.IsNullOrWhiteSpace(documento1.get_Endosso()) ? ", " : string.Concat(" e
endosso de n° ", documento1.get_Endosso(), ", ")); + string str21 = str10; + string[] strArrays1 = new string[] { "iniciado em ", null, null, null, null }; + if (string.IsNullOrWhiteSpace(documento1.get_Vigencia1().ToShortDateString())) + { + shortDateString = ""; + } + else + { + vigencia1 = documento1.get_Vigencia1(); + shortDateString = vigencia1.ToShortDateString(); + } + strArrays1[1] = shortDateString; + strArrays1[2] = " até "; + DateTime? vigencia2 = documento1.get_Vigencia2(); + if (vigencia2.HasValue) + { + shortDateString1 = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString1 = null; + } + if (string.IsNullOrWhiteSpace(shortDateString1)) + { + shortDateString2 = ""; + } + else + { + vigencia2 = documento1.get_Vigencia2(); + if (vigencia2.HasValue) + { + shortDateString2 = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString2 = null; + } + } + strArrays1[3] = shortDateString2; + strArrays1[4] = ""; + string str22 = string.Concat(strArrays1); + if (observableCollection2 == null || observableCollection2.Count <= 0) + { + str11 = ""; + } + else + { + str16 = (string.IsNullOrWhiteSpace(observableCollection2[0].get_Descricao()) ? "" : observableCollection2[0].get_Descricao()); + str11 = string.Concat("", str16, ""); + } + string str23 = str11; + string str24 = ""; + Documento documento3 = protocolo.FirstOrDefault((Documento x) => x.get_Id() == documento1.get_Id()); + if (documento3 != null) + { + obsProtocolo = documento3.get_ObsProtocolo(); + } + else + { + obsProtocolo = null; + } + string str25 = obsProtocolo; + str12 = (string.IsNullOrEmpty(str25) ? "" : string.Concat("OBSERVAÇÃO: ", str25)); + string str26 = str12; + if (documento1.get_ProtocoloParcela() && observableCollection3 != null && observableCollection3.Count > 0) + { + if (observableCollection3.Count != 1) + { + object count = observableCollection3.Count; + if (string.IsNullOrWhiteSpace(observableCollection3[0].get_Vencimento().ToShortDateString())) + { + obj = ""; + } + else + { + vigencia1 = observableCollection3[0].get_Vencimento(); + obj = vigencia1.ToShortDateString(); + } + string str27 = string.Format("{0} parcelas: vencimento 1ª parcela: {1}, ", count, obj); + if (string.IsNullOrWhiteSpace(observableCollection3[1].get_Vencimento().ToShortDateString())) + { + shortDateString3 = ""; + } + else + { + vigencia1 = observableCollection3[1].get_Vencimento(); + shortDateString3 = vigencia1.ToShortDateString(); + } + str24 = string.Concat(str27, "vencimento 2ª parcela: ", shortDateString3, ", demais parcelas, vide apólice."); + } + else + { + string str28 = str24; + if (string.IsNullOrWhiteSpace(observableCollection3[0].get_Vencimento().ToShortDateString())) + { + shortDateString4 = ""; + } + else + { + vigencia1 = observableCollection3[0].get_Vencimento(); + shortDateString4 = vigencia1.ToShortDateString(); + } + str24 = string.Concat(str28, "1 parcela: vencimento ", shortDateString4, " "); + } + } + if (documento1.get_ProtocoloVendedor()) + { + pasta = documento1.get_Pasta(); + } + else + { + pasta = null; + } + string str29 = pasta; + if (documento1.get_ProtocoloVendedor()) + { + Vendedor vendedorPrincipal = documento1.get_VendedorPrincipal(); + if (vendedorPrincipal != null) + { + nome = vendedorPrincipal.get_Nome(); + } + else + { + nome = null; + } + } + else + { + nome = null; + } + string str30 = nome; + str13 = (str29 != null || str30 != null ? "" : "style = 'display:none;'"); + string str31 = str13; + StringBuilder stringBuilder2 = stringBuilder1; + string protocoloTemplate = Resources.ProtocoloTemplate; + str14 = (doisPorPagina ? "12.2cm" : "24.4cm"); + string str32 = protocoloTemplate.Replace("{Tamanho}", str14).Replace("{Observacao}", str26).Replace("{Nome}", documento1.get_Controle().get_Cliente().get_Nome()).Replace("{Email}", str19).Replace("{DisplayTelefones}", str20); + str15 = (telefones != null ? str17 : ""); + stringBuilder2.Append(str32.Replace("{Telefones}", str15).Replace("{Endereço}", str18).Replace("{Ramo}", documento1.get_Controle().get_Ramo().get_Nome()).Replace("{Apolice}", documento1.get_Apolice()).Replace("{Endosso}", str21).Replace("{Seguradora}", documento1.get_Controle().get_Seguradora().get_Nome()).Replace("{Vigencias}", str22).Replace("{Item}", str23).Replace("{Parcelas}", str24).Replace("{Pasta}", str29).Replace("{Vendedor}", str30).Replace("{DisplayVendedor}", str31).Replace("{NomeCorretora}", Recursos.Empresa.get_Nome()).Replace("{Usuario}", Recursos.Usuario.get_Nome()).Replace("{Emissao}", string.Format("{0}", networkTime))); + num++; + if (!doisPorPagina || num1 == 2) + { + stringBuilder1.Append("
"); + num1 = 0; + } + apoliceServico = null; + itemServico = null; + clienteServico = null; + parcelaServico = null; + observableCollection2 = null; + } + stringBuilder.Append(Resources.ProtocoloPageTemplate.Replace("{Protocolos}", stringBuilder1.ToString())); + string tempPath = Path.GetTempPath(); + string str33 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoExtrato)0, networkTime); + StreamWriter streamWriter = new StreamWriter(str33, true, Encoding.UTF8); + streamWriter.Write(stringBuilder); + streamWriter.Close(); + Process.Start(str33); + BaseViewModel baseViewModel = this; + object count1 = lista.Count; + obj1 = (lista.Count == 1 ? "" : "S"); + string str34 = string.Format("EMITIU PROTOCOLO DE {0} DOCUMENTO{1}", count1, obj1); + long num2 = (long)0; + TipoTela? nullable = new TipoTela?(59); + List> tuples = lista; + baseViewModel.RegistrarAcao(str34, num2, nullable, string.Concat("IDS DOS DOCUMENTOS E SUAS RESPECTIVAS OBSERVAÇÕES:\n", string.Join("\n", + from x in tuples + select string.Concat(x.Item1.ToString(), ": \"", x.Item2, "\"")))); + stringBuilder = null; + stringBuilder1 = null; + } + + public async Task ExecuteRunExtendedDialog(System.Windows.Controls.UserControl dialogControl, string hostName) + { + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + DialogHost.CloseDialogCommand.Execute(null, null); + return (obj == null ? false : (bool)obj); + } + + public async Task ExecuteRunExtendedDialogAdvertising(System.Windows.Controls.UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandlerArquivo)); + } + + public async Task> ExecuteRunExtendedDialogAnexar(System.Windows.Controls.UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + List arquivoDigitals = (List)await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandlerArquivo)); + return arquivoDigitals; + } + + public async Task ExecuteRunExtendedDialogCopia(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Copia copium; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + copium = (Copia)obj; + } + else + { + copium = null; + } + return copium; + } + + public async Task ExecuteRunExtendedDialogCopiarCliente(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Cliente cliente; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + cliente = (Cliente)obj; + } + else + { + cliente = null; + } + return cliente; + } + + public async Task> ExecuteRunExtendedDialogExtratoComissao(System.Windows.Controls.UserControl dialogControl, string hostName) + { + List notaFiscals; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + notaFiscals = (List)obj; + } + else + { + notaFiscals = null; + } + return notaFiscals; + } + + public async Task ExecuteRunExtendedDialogInstalacoes(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Instalacao instalacao; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + object obj1 = obj; + if (obj1 == null || obj1 is bool && !(bool)obj1) + { + instalacao = null; + } + else + { + instalacao = (Instalacao)obj; + } + return instalacao; + } + + public async Task ExecuteRunExtendedDialogPrint(System.Windows.Controls.UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + ConfiguracaoImpressao configuracaoImpressao = (ConfiguracaoImpressao)await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + return configuracaoImpressao; + } + + public async Task ExecuteRunExtendedDialogProspeccao(System.Windows.Controls.UserControl dialogControl, string hostName) + { + Prospeccao prospeccao; + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + object obj = await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + if (!(obj is bool)) + { + prospeccao = (Prospeccao)obj; + } + else + { + prospeccao = null; + } + return prospeccao; + } + + public async Task ExecuteRunExtendedDialogSenha(System.Windows.Controls.UserControl dialogControl, string hostName) + { + IEnumerable windows = System.Windows.Application.Current.Windows.OfType(); + List list = Extentions.FindVisualChildren(windows.SingleOrDefault((Window x) => x.IsActive)).ToList(); + list.ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + bool? nullable = (bool?)await DialogHost.Show(dialogControl, hostName, new DialogOpenedEventHandler(this, BaseViewModel.ExtendedOpenedEventHandler), new DialogClosingEventHandler(this, BaseViewModel.ExtendedClosingEventHandler)); + return nullable; + } + + public void ExtendedClosingEventHandler(object sender, DialogClosingEventArgs eventArgs) + { + this.IsEnabled = true; + Window window = System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive); + Extentions.FindVisualChildren(window).ToList().ForEach((WebEditor x) => { + if (!x.IsReadOnly) + { + x.Visibility = Visibility.Visible; + } + }); + Extentions.FindVisualChildren(window).Any((DrawerHost x) => { + if (x.get_IsLeftDrawerOpen() || x.get_IsBottomDrawerOpen() || x.get_IsRightDrawerOpen()) + { + return true; + } + return x.get_IsTopDrawerOpen(); + }); + } + + public void ExtendedClosingEventHandlerArquivo(object sender, DialogClosingEventArgs eventArgs) + { + this.IsEnabled = true; + Extentions.FindVisualChildren(System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive)).Any((DrawerHost x) => { + if (x.get_IsLeftDrawerOpen() || x.get_IsBottomDrawerOpen() || x.get_IsRightDrawerOpen()) + { + return true; + } + return x.get_IsTopDrawerOpen(); + }); + } + + public void ExtendedOpenedEventHandler(object sender, DialogOpenedEventArgs eventargs) + { + this.IsEnabled = false; + } + + internal DialogHost GetHost() + { + DialogHost dialogHost = Extentions.FindVisualChildren(System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive)).FirstOrDefault(); + if (dialogHost == null) + { + foreach (Window window in System.Windows.Application.Current.Windows.OfType()) + { + dialogHost = Extentions.FindVisualChildren(window).FirstOrDefault(); + if (dialogHost == null || dialogHost.get_IsOpen()) + { + continue; + } + if (dialogHost != null && dialogHost.get_IsOpen()) + { + return null; + } + return dialogHost; + } + } + if (dialogHost != null && dialogHost.get_IsOpen()) + { + return null; + } + return dialogHost; + } + + public double GetWindowHeight() + { + return System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive).ActualHeight; + } + + private void HabilitarMenu(bool enable) + { + this.EnableMainMenu = enable; + } + + private void HabilitarMenuSecundario(bool enable) + { + this.EnableMenu = enable; + } + + public async Task ImprimirFornecedor(List fornecedores) + { + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + ParcelaServico parcelaServico = new ParcelaServico(); + string str6 = "RELATÓRIO DE FORNECEDORES"; + str6 = string.Concat(str6, "
RELATÓRIO DE FORNECEDORES

"); + str6 = string.Concat(str6, "
"); + str6 = string.Concat(str6, ""); + int num = 1; + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + str6 = string.Concat(str6, ""); + foreach (Fornecedor fornecedore in fornecedores) + { + string[] nome = new string[] { str6, ""; + str6 = string.Concat(nome); + string[] documento = new string[] { str6, ""; + str6 = string.Concat(documento); + string[] endereco = new string[] { str6, ""; + str6 = string.Concat(endereco); + string[] email = new string[] { str6, ""; + str6 = string.Concat(email); + if (fornecedore.get_Documento() == null) + { + str4 = ""; + } + else + { + str4 = (Gestor.Common.Validation.ValidationHelper.OnlyNumber(fornecedore.get_Documento()).Length > 11 ? "JURÍDICA" : "FÍSICA"); + } + string str7 = str4; + string[] strArrays = new string[] { str6, ""; + str6 = string.Concat(strArrays); + if (num != 1) + { + num++; + } + else + { + num = 0; + } + } + DateTime networkTime = Funcoes.GetNetworkTime(); + string nome1 = Recursos.Usuario.get_Nome(); + str6 = string.Concat(str6, "
NOMECPF/CNPJENDEREÇOE-MAILTIPO PESSOA
"; + nome[4] = fornecedore.get_Nome(); + nome[5] = ""; + documento[4] = fornecedore.get_Documento(); + documento[5] = ""; + endereco[4] = fornecedore.get_Endereco(); + endereco[5] = ""; + email[4] = fornecedore.get_Email(); + email[5] = ""; + strArrays[4] = str7; + strArrays[5] = "
"); + str6 = string.Concat(str6, string.Format("Emitido pelo usuário: {0}, data e hora: {1}.", nome1, networkTime)); + str6 = string.Concat(str6, ""); + string tempPath = Path.GetTempPath(); + string str8 = string.Format("{0}FORNECEDORES_{1:ddMMyyyyhhmmss}.html", tempPath, networkTime); + StreamWriter streamWriter = new StreamWriter(str8, true, Encoding.UTF8); + streamWriter.Write(str6); + streamWriter.Close(); + Process.Start(str8); + } + + private Gestor.Application.Model.Configuracoes LoadConfiguracoes() + { + this.CriarConfiguracaoPadrao("config.json"); + return JsonConvert.DeserializeObject(File.ReadAllText("config.json")); + } + + private async Task LoadDialogAdertisingPromo() + { + DialogAdvertising dialogAdvertising; + object empty; + Gestor.Application.Model.Configuracoes configuraco = this.LoadConfiguracoes(); + JObject jObject = await this.LoadJsonAdvertising(Address.JsonPromo()); + if (jObject != null) + { + JToken item = jObject.get_Item("Imagem"); + if (item != null) + { + empty = Extensions.Value(item); + } + else + { + empty = null; + } + if (empty == null) + { + empty = string.Empty; + } + string str = (string)empty; + if (configuraco.LinkPromo == str || configuraco.NaoverPromo) + { + dialogAdvertising = null; + } + else + { + dialogAdvertising = new DialogAdvertising(jObject, true); + } + } + else + { + dialogAdvertising = null; + } + configuraco = null; + return dialogAdvertising; + } + + public void Loading(bool isLoading) + { + Grid progressRing = App.ProgressRing; + if (progressRing == null) + { + return; + } + Dispatcher dispatcher = progressRing.Dispatcher; + if (dispatcher == null) + { + return; + } + dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => this.LoadingThread(isLoading))); + } + + public void LoadingThread(bool isLoading) + { + this.IsVisible = (isLoading ? Visibility.Collapsed : Visibility.Visible); + App.ProgressRing.Visibility = (isLoading ? Visibility.Visible : Visibility.Collapsed); + this.IsEnabled = !isLoading; + } + + private async Task LoadJsonAdvertising(Uri location) + { + JObject jObject; + JObject jObject1; + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(20)); + HttpResponseMessage async = await httpClient.GetAsync(location); + if (!async.get_IsSuccessStatusCode()) + { + jObject1 = null; + } + else + { + jObject1 = JObject.Parse(await async.get_Content().ReadAsStringAsync()); + } + jObject = jObject1; + } + return jObject; + } + + public void OnPropertyChanged([CallerMemberName] string name = "") + { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, new PropertyChangedEventArgs(name)); + } + + public bool Permissao(TipoTela tipoTela) + { + if (Recursos.Usuario.get_Id() == 0) + { + return false; + } + PermissaoUsuario permissaoUsuario = this.ServicoPermissUsuario.BuscarPermissao(Recursos.Usuario, tipoTela); + if (permissaoUsuario == null) + { + return true; + } + return permissaoUsuario.get_Consultar(); + } + + public async Task PermissaoArquivoDigital(TipoArquivoDigital tela) + { + bool flag; + bool flag1; + this.EnableIncluir = false; + this.EnableExcluir = false; + if (Recursos.Usuario.get_Id() != 0) + { + PermissaoArquivoDigital permissaoArquivoDigital = await this.ServicoPermissArquivoDigital.VerificarPermissao(Recursos.Usuario, tela); + BaseViewModel baseViewModel = this; + flag = (permissaoArquivoDigital != null ? permissaoArquivoDigital.get_Incluir() : true); + baseViewModel._incluirPermissEnabled = flag; + BaseViewModel baseViewModel1 = this; + flag1 = (permissaoArquivoDigital != null ? permissaoArquivoDigital.get_Excluir() : true); + baseViewModel1._excluirPermissEnabled = flag1; + } + } + + public async Task PermissaoConsultar(TipoTela tela) + { + bool flag; + bool consultar; + if (Recursos.Usuario.get_Id() != 0) + { + PermissaoUsuario permissaoUsuario = await this.ServicoPermissUsuario.VerificarPermissao(Recursos.Usuario, tela); + if (permissaoUsuario != null) + { + consultar = permissaoUsuario.get_Consultar(); + } + else + { + consultar = true; + } + flag = consultar; + } + else + { + flag = true; + } + return flag; + } + + public async Task PermissaoTela(TipoTela tela) + { + bool flag; + bool flag1; + bool flag2; + bool flag3; + bool flag4; + bool flag5; + this.EnableIncluir = false; + this.EnableAlterar = false; + this.EnableExcluir = false; + if (Recursos.Usuario.get_Id() != 0) + { + PermissaoUsuario permissaoUsuario = await this.ServicoPermissUsuario.VerificarPermissao(Recursos.Usuario, tela); + if (tela == 5) + { + BaseViewModel baseViewModel = this; + flag3 = (permissaoUsuario != null ? permissaoUsuario.get_Incluir() : true); + baseViewModel.IncluirParcelaEnabled = flag3; + BaseViewModel baseViewModel1 = this; + flag4 = (permissaoUsuario != null ? permissaoUsuario.get_Alterar() : true); + baseViewModel1.AlterarParcelaEnabled = flag4; + BaseViewModel baseViewModel2 = this; + flag5 = (permissaoUsuario != null ? permissaoUsuario.get_Excluir() : true); + baseViewModel2.ExcluirParcelaEnabled = flag5; + } + else if (tela == 24 || tela == 26 || tela == 29 || tela == 28 || tela == 27) + { + this._incluirPermissEnabled = true; + this._alterarPermissEnabled = true; + this._excluirPermissEnabled = true; + } + else + { + BaseViewModel baseViewModel3 = this; + flag = (permissaoUsuario != null ? permissaoUsuario.get_Incluir() : true); + baseViewModel3._incluirPermissEnabled = flag; + BaseViewModel baseViewModel4 = this; + flag1 = (permissaoUsuario != null ? permissaoUsuario.get_Alterar() : true); + baseViewModel4._alterarPermissEnabled = flag1; + BaseViewModel baseViewModel5 = this; + flag2 = (permissaoUsuario != null ? permissaoUsuario.get_Excluir() : true); + baseViewModel5._excluirPermissEnabled = flag2; + } + } + } + + public void RegistrarAcao(string descricao, long entidadeId, TipoTela? tela = null, object obs = null) + { + RegistroAcao registroAcao = new RegistroAcao(); + registroAcao.set_Descricao(descricao); + registroAcao.set_EntidadeId(entidadeId); + registroAcao.set_Tela(tela); + (new ApoliceServico()).SalvarAcao(registroAcao, obs); + } + + public void RegistrarAcao(string descricao, Relatorio? relatorio, object obs = null) + { + RegistroAcao registroAcao = new RegistroAcao(); + registroAcao.set_Relatorio(relatorio); + registroAcao.set_Descricao(descricao); + (new ApoliceServico()).SalvarAcao(registroAcao, obs); + } + + public bool Restricao(TipoRestricao tipoRestricao) + { + if (Recursos.Usuario.get_Id() == 0) + { + return false; + } + RestricaoUsuario restricaoUsuario = this.ServicoRestriUsuario.BuscarRestricao(Recursos.Usuario, tipoRestricao); + if (restricaoUsuario == null) + { + return false; + } + return restricaoUsuario.get_Restricao(); + } + + public async Task Salvar(IndiceArquivoDigital indice) + { + string str; + bool arquivo; + Guid guid; + if (indice.get_Id() != 0) + { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = await this.ArquivoDigitalServico.BuscarPorId(indice.get_IdArquivoDigital(), indice.get_Bd()); + if (arquivoDigital != null) + { + arquivo = arquivoDigital.get_Arquivo(); + } + else + { + arquivo = false; + } + if (!arquivo || arquivoDigital.get_Extensao() == null) + { + str = null; + } + else + { + string tempPath = Path.GetTempPath(); + Guid? azureGuid = arquivoDigital.get_AzureGuid(); + guid = (azureGuid.HasValue ? azureGuid.GetValueOrDefault() : Guid.NewGuid()); + string str1 = string.Format("{0}{1}{2}", tempPath, guid, Gestor.Common.Validation.ValidationHelper.GetDefaultExtension(arquivoDigital.get_Extensao())); + using (BinaryWriter binaryWriter = new BinaryWriter(File.Open(str1, FileMode.Create))) + { + binaryWriter.Write(arquivoDigital.get_Arquivo()); + } + str = str1; + } + } + else + { + str = null; + } + return str; + } + + public async Task SalvarAttachments(List arquivos, TipoArquivoDigital tipoAd, long id) + { + bool flag; + if (arquivos == null || arquivos.Count == 0) + { + flag = false; + } + else + { + arquivos.ForEach((Gestor.Model.Domain.Common.ArquivoDigital x) => { + x.set_IdCliente((tipoAd == 1 ? id : (long)0)); + x.set_IdDocumento((tipoAd == 2 ? id : (long)0)); + x.set_IdParcela((tipoAd == 3 ? id : (long)0)); + x.set_IdItem((tipoAd == 4 ? id : (long)0)); + x.set_IdSinistro((tipoAd == 5 ? id : (long)0)); + x.set_IdVendedor((tipoAd == 6 ? id : (long)0)); + x.set_IdUsuario((tipoAd == 12 ? id : (long)0)); + x.set_IdSeguradora((tipoAd == 8 ? id : (long)0)); + x.set_IdExtrato((tipoAd == 7 ? id : (long)0)); + x.set_IdLancamento((tipoAd == 9 ? id : (long)0)); + x.set_IdFornecedor((tipoAd == 10 ? id : (long)0)); + x.set_IdProspeccao((tipoAd == 11 ? id : (long)0)); + x.set_IdSocio((tipoAd == 14 ? id : (long)0)); + x.set_IdTarefa((tipoAd == 15 ? id : (long)0)); + x.set_IdNotaFiscal((tipoAd == 16 ? id : (long)0)); + x.set_IdEstipulante((tipoAd == 17 ? id : (long)0)); + x.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + }); + switch (tipoAd) + { + default: + { + break; + } + } + await this.ArquivoDigitalServico.Insert(arquivos); + flag = (this.ArquivoDigitalServico.Sucesso ? true : false); + } + return flag; + } + + public async Task>> SalvarProspeccao(Prospeccao prospecao) + { + List> keyValuePairs; + bool count; + string str; + List anexos; + Prospeccao prospeccao; + List> keyValuePairs1 = prospecao.Validate(); + if (keyValuePairs1.Count <= 0) + { + anexos = prospecao.get_Anexos(); + if (prospecao.get_Tarefa().get_Id() == 0) + { + prospecao.get_Tarefa().set_Cliente(prospecao.get_Nome()); + Tarefa tarefa = prospecao.get_Tarefa(); + DateTime? vigenciaFinal = prospecao.get_VigenciaFinal(); + if (vigenciaFinal.HasValue) + { + str = vigenciaFinal.GetValueOrDefault().ToString("d"); + } + else + { + str = null; + } + tarefa.set_Titulo(string.Concat("PROSPECÇÃO ", str)); + prospecao.get_Tarefa().set_Referencia(prospecao.get_Item()); + Tarefa tarefa1 = prospecao.get_Tarefa(); + object[] nome = new object[] { Recursos.Usuario.get_Nome(), Funcoes.GetNetworkTime(), Environment.NewLine, prospecao.get_Observacao() }; + tarefa1.set_Descricao(string.Format("{0} {1:g} {2}{3}", nome)); + } + prospeccao = await (new ProspeccaoServico()).Salvar(prospecao); + List arquivoDigitals = anexos; + if (arquivoDigitals != null) + { + count = arquivoDigitals.Count > 0; + } + else + { + count = false; + } + if (count) + { + await this.SalvarAttachments(anexos, 11, prospeccao.get_Id()); + } + if (prospeccao.get_Tarefa() != null && prospecao.get_AbrirTarefa() && prospeccao != null && prospeccao.get_Id() > (long)0) + { + Tarefa tarefa2 = prospeccao.get_Tarefa(); + this.ShowDrawer(new TarefaDrawer(tarefa2, true), 0, false); + } + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs1; + } + anexos = null; + prospeccao = null; + return keyValuePairs; + } + + internal async Task ShowCopiaDialog(Copia copia) + { + Copia copium; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogCopia dialogCopium = new DialogCopia(copia); + BaseViewModel baseViewModel = this; + DialogCopia dialogCopium1 = dialogCopium; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + copium = await baseViewModel.ExecuteRunExtendedDialogCopia(dialogCopium1, str); + } + else + { + copium = null; + } + return copium; + } + + internal async Task ShowCopiarCliente() + { + Cliente cliente; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogCopiarCliente dialogCopiarCliente = new DialogCopiarCliente(); + BaseViewModel baseViewModel = this; + DialogCopiarCliente dialogCopiarCliente1 = dialogCopiarCliente; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + cliente = await baseViewModel.ExecuteRunExtendedDialogCopiarCliente(dialogCopiarCliente1, str); + } + else + { + cliente = null; + } + return cliente; + } + + internal async Task ShowDialogAdvertising(bool root = false) + { + string str; + try + { + DialogHost host = null; + if (!root) + { + host = this.GetHost(); + if (host != null && host.get_IsOpen()) + { + return; + } + } + DialogAdvertising dialogAdvertising = await this.CreateDialogAdvertising(); + if (dialogAdvertising != null) + { + BaseViewModel baseViewModel = this; + DialogAdvertising dialogAdvertising1 = dialogAdvertising; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseViewModel.ExecuteRunExtendedDialogAdvertising(dialogAdvertising1, str); + host = null; + } + else + { + return; + } + } + catch + { + } + } + + internal async Task> ShowDialogAnexar(List arquivos, bool root = false) + { + List arquivoDigitals; + string str; + DialogHost host = null; + if (!root) + { + host = this.GetHost(); + if (host != null && host.get_IsOpen()) + { + arquivoDigitals = arquivos; + return arquivoDigitals; + } + } + DialogAnexar dialogAnexar = new DialogAnexar(arquivos); + BaseViewModel baseViewModel = this; + DialogAnexar dialogAnexar1 = dialogAnexar; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + arquivoDigitals = await baseViewModel.ExecuteRunExtendedDialogAnexar(dialogAnexar1, str); + return arquivoDigitals; + } + + internal async Task ShowDialogPrint(Relatorio relatorio, Type tipo) + { + ConfiguracaoImpressao configuracaoImpressao; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogPrint dialogPrint = new DialogPrint(relatorio, tipo); + BaseViewModel baseViewModel = this; + DialogPrint dialogPrint1 = dialogPrint; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + configuracaoImpressao = await baseViewModel.ExecuteRunExtendedDialogPrint(dialogPrint1, str); + } + else + { + configuracaoImpressao = null; + } + return configuracaoImpressao; + } + + internal void ShowDrawer(object content, int position, bool close = true) + { + Window window = System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive); + DrawerHost drawerHost = Extentions.FindVisualChildren(window).FirstOrDefault(); + Extentions.FindVisualChildren(window).ToList().ForEach((WebEditor x) => x.Visibility = Visibility.Collapsed); + if (drawerHost == null) + { + return; + } + switch (position) + { + case 1: + { + drawerHost.set_TopDrawerContent(content); + drawerHost.set_IsTopDrawerOpen(true); + drawerHost.set_TopDrawerCloseOnClickAway(close); + return; + } + case 2: + { + drawerHost.set_LeftDrawerContent(content); + drawerHost.set_IsLeftDrawerOpen(true); + drawerHost.set_LeftDrawerCloseOnClickAway(close); + return; + } + case 3: + { + drawerHost.set_BottomDrawerContent(content); + drawerHost.set_IsBottomDrawerOpen(true); + drawerHost.set_BottomDrawerCloseOnClickAway(close); + return; + } + default: + { + if (!drawerHost.get_IsRightDrawerOpen() || drawerHost.get_RightDrawerContent() != null && !(drawerHost.get_RightDrawerContent().GetType() != content.GetType())) + { + break; + } + else + { + drawerHost.set_LeftDrawerContent(content); + drawerHost.set_IsLeftDrawerOpen(true); + drawerHost.set_LeftDrawerCloseOnClickAway(close); + return; + } + } + } + drawerHost.set_IsRightDrawerOpen(true); + drawerHost.set_RightDrawerContent(content); + drawerHost.set_RightDrawerCloseOnClickAway(close); + } + + internal async Task> ShowExtratoComissaoDialog(List seguradoras) + { + List notaFiscals; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogExtratoComissao dialogExtratoComissao = new DialogExtratoComissao(seguradoras); + BaseViewModel baseViewModel = this; + DialogExtratoComissao dialogExtratoComissao1 = dialogExtratoComissao; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + notaFiscals = await baseViewModel.ExecuteRunExtendedDialogExtratoComissao(dialogExtratoComissao1, str); + } + else + { + notaFiscals = null; + } + return notaFiscals; + } + + internal async Task ShowInstalacoes(List instalacoes) + { + Instalacao instalacao; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogInstalacoes dialogInstalaco = new DialogInstalacoes(instalacoes); + BaseViewModel baseViewModel = this; + DialogInstalacoes dialogInstalaco1 = dialogInstalaco; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + instalacao = await baseViewModel.ExecuteRunExtendedDialogInstalacoes(dialogInstalaco1, str); + } + else + { + instalacao = null; + } + return instalacao; + } + + internal async Task ShowMedalha(int liquido, int comissao, int resultado, int media) + { + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogMedalha dialogMedalha = new DialogMedalha(liquido, comissao, resultado, media); + BaseViewModel baseViewModel = this; + DialogMedalha dialogMedalha1 = dialogMedalha; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + await baseViewModel.ExecuteRunExtendedDialog(dialogMedalha1, str); + } + } + + internal async Task ShowMessage(string message, string accept = "OK", string cancel = "", bool root = false) + { + bool flag; + string str; + DialogHost host = null; + if (!root) + { + host = this.GetHost(); + if (host == null) + { + flag = false; + return flag; + } + } + DefaultDialog defaultDialog = new DefaultDialog(); + DialogViewModel dialogViewModel = new DialogViewModel() + { + AcceptContent = accept, + CancelContent = cancel, + Message = message + }; + defaultDialog.DataContext = dialogViewModel; + DefaultDialog defaultDialog1 = defaultDialog; + BaseViewModel baseViewModel = this; + DefaultDialog defaultDialog2 = defaultDialog1; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + flag = await baseViewModel.ExecuteRunExtendedDialog(defaultDialog2, str); + return flag; + } + + internal async Task ShowMessage(List> pairs, string message, string accept, string cancel = "") + { + bool flag; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + ErrorDialog errorDialog = new ErrorDialog(); + ErrorDialogViewModel errorDialogViewModel = new ErrorDialogViewModel(); + List> keyValuePairs = pairs; + errorDialogViewModel.Erros = ( + from pair in keyValuePairs + select new KeyValuePair((pair.Key.Contains("|") ? pair.Key.Substring(pair.Key.IndexOf("|", StringComparison.Ordinal) + 1) : pair.Key), pair.Value)).ToList>(); + errorDialogViewModel.AcceptContent = accept; + errorDialogViewModel.CancelContent = cancel; + errorDialogViewModel.Message = message; + errorDialog.DataContext = errorDialogViewModel; + ErrorDialog errorDialog1 = errorDialog; + BaseViewModel baseViewModel = this; + ErrorDialog errorDialog2 = errorDialog1; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + flag = await baseViewModel.ExecuteRunExtendedDialog(errorDialog2, str); + } + else + { + flag = false; + } + return flag; + } + + internal async Task ShowProspeccaoDialog(Prospeccao prospecao) + { + Prospeccao prospeccao; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + ProspeccaoDialog prospeccaoDialog = new ProspeccaoDialog(prospecao); + BaseViewModel baseViewModel = this; + ProspeccaoDialog prospeccaoDialog1 = prospeccaoDialog; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + prospeccao = await baseViewModel.ExecuteRunExtendedDialogProspeccao(prospeccaoDialog1, str); + } + else + { + prospeccao = null; + } + return prospeccao; + } + + internal async Task ShowSenha(string mensagem) + { + bool? nullable; + string str; + DialogHost host = this.GetHost(); + if (host == null || !host.get_IsOpen()) + { + DialogSenhaAdm dialogSenhaAdm = new DialogSenhaAdm(mensagem); + BaseViewModel baseViewModel = this; + DialogSenhaAdm dialogSenhaAdm1 = dialogSenhaAdm; + str = (host != null ? host.get_Identifier().ToString() : "RootDialog"); + nullable = await baseViewModel.ExecuteRunExtendedDialogSenha(dialogSenhaAdm1, str); + } + else + { + nullable = new bool?(false); + } + return nullable; + } + + public void ToggleSnackBar(string message, bool active = true) + { + Snackbar snackbar = Extentions.FindVisualChildren(System.Windows.Application.Current.Windows.OfType().SingleOrDefault((Window x) => x.IsActive)).FirstOrDefault(); + if (snackbar == null) + { + return; + } + snackbar.get_Message().Content = message; + snackbar.set_IsActive(active); + if (!active) + { + return; + } + Task.Factory.StartNew(new Action(this.CloseSlackBar)); + } + + public async Task> ValidateAttachment(List attachments, List files) + { + char chr; + bool flag; + string lower; + object obj; + string upper = string.Concat("Os Arquivos Abaixo não podem ser anexados pois não possuem Formatos válidos, são maiores que o permitido ou já foram anexados!", Environment.NewLine, Environment.NewLine).ToUpper(); + List strs = new List(); + bool flag1 = false; + foreach (string file in files) + { + int num = 0; + try + { + flag = (attachments == null ? false : attachments.Exists((Gestor.Model.Domain.Common.ArquivoDigital a) => { + string str; + string str1 = Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(a.get_Descricao().ToUpper()); + string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); + if (fileNameWithoutExtension != null) + { + str = Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(fileNameWithoutExtension.ToUpper()); + } + else + { + str = null; + } + return str1 == str; + })); + if (!flag) + { + FileInfo fileInfo = new FileInfo(file); + if (fileInfo.Length > (long)1024) + { + long length = fileInfo.Length / (long)1024; + obj = (Recursos.Empresa.get_MaxFileSize() > 0 ? Recursos.Empresa.get_MaxFileSize() : 14336); + if (length > (long)obj) + { + upper = string.Concat(upper, Path.GetFileName(file)); + flag1 = true; + continue; + } + } + string extension = Path.GetExtension(file); + if (extension != null) + { + lower = extension.ToLower(); + } + else + { + lower = null; + } + string str2 = lower; + if (str2 != null) + { + int length1 = str2.Length; + if (length1 == 4) + { + chr = str2[1]; + if (chr <= 't') + { + switch (chr) + { + case 'a': + { + if (str2 == ".amr") + { + break; + } + goto Label1; + } + case 'b': + { + if (str2 == ".bmp") + { + break; + } + goto Label1; + } + case 'c': + { + goto Label1; + } + case 'd': + { + if (str2 == ".doc") + { + break; + } + goto Label1; + } + case 'e': + { + if (str2 == ".eml") + { + break; + } + goto Label1; + } + default: + { + switch (chr) + { + case 'j': + { + if (str2 == ".jpg") + { + goto Label2; + } + goto Label1; + } + case 'm': + { + if (str2 == ".msg") + { + goto Label2; + } + goto Label1; + } + case 'o': + { + if (str2 == ".ogg") + { + goto Label2; + } + goto Label1; + } + case 'p': + { + if (str2 == ".png" || str2 == ".pdf") + { + goto Label2; + } + goto Label1; + } + case 'r': + { + if (str2 == ".rar") + { + goto Label2; + } + goto Label1; + } + case 't': + { + if (str2 == ".txt") + { + goto Label2; + } + goto Label1; + } + default: + { + goto Label1; + } + } + break; + } + } + } + else if (chr == 'x') + { + if (str2 == ".xls") + { + goto Label2; + } + goto Label1; + } + else if (chr == 'z') + { + if (str2 == ".zip") + { + goto Label2; + } + goto Label1; + } + else + { + goto Label1; + } + } + else if (length1 == 5) + { + chr = str2[2]; + switch (chr) + { + case 'l': + { + if (str2 == ".xlsx") + { + break; + } + goto Label1; + } + case 'm': + case 'n': + { + goto Label1; + } + case 'o': + { + if (str2 == ".docx") + { + break; + } + goto Label1; + } + case 'p': + { + if (str2 == ".jpeg") + { + break; + } + goto Label1; + } + default: + { + if (chr != 's') + { + goto Label1; + } + else if (str2 == ".json") + { + break; + } + else + { + goto Label1; + } + } + } + } + else + { + goto Label1; + } + Label2: + strs.Add(file); + goto Label0; + } + Label1: + upper = string.Concat(upper, Path.GetFileName(file)); + Label0: + } + else + { + upper = string.Concat(upper, Path.GetFileName(file)); + flag1 = true; + continue; + } + } + catch (Exception exception) + { + num = 1; + } + if (num != 1) + { + continue; + } + string[] newLine = new string[] { "NÃO FOI POSSÍVEL CARREGAR O ARQUIVO ", file, ".", Environment.NewLine, "O ARQUIVO ESTÁ INACESSÍVEL OU SENDO UTILIZADO POR OUTRO PROCESSO." }; + await this.ShowMessage(string.Concat(newLine), "OK", "", false); + } + if (flag1) + { + await this.ShowMessage(string.Concat(upper, Environment.NewLine, Environment.NewLine, "Favor Corrija antes de tentar novamente.").ToUpper(), "OK", "", false); + } + return strs; + } + + public async Task VerificarAcesso(long id) + { + string str; + string str1; + string str2 = null; + Usuario usuario = await (new UsuarioServico()).BuscarUsuarioPorId(id); + if (usuario != null) + { + List strs = new List(); + List strs1 = new List() + { + "SEGUNDAS-FEIRAS", + "TERÇAS-FEIRAS", + "QUARTAS-FEIRAS", + "QUINTAS-FEIRAS", + "SEXTAS-FEIRAS", + "SÁBADOS", + "DOMINGOS" + }; + List strs2 = strs1; + bool? segunda = usuario.get_Segunda(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("SEGUNDAS-FEIRAS"); + strs2.Remove("SEGUNDAS-FEIRAS"); + } + segunda = usuario.get_Terca(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("TERÇAS-FEIRAS"); + strs2.Remove("TERÇAS-FEIRAS"); + } + segunda = usuario.get_Quarta(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("QUARTAS-FEIRAS"); + strs2.Remove("QUARTAS-FEIRAS"); + } + segunda = usuario.get_Quinta(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("QUINTAS-FEIRAS"); + strs2.Remove("QUINTAS-FEIRAS"); + } + segunda = usuario.get_Sexta(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("SEXTAS-FEIRAS"); + strs2.Remove("SEXTAS-FEIRAS"); + } + segunda = usuario.get_Sabado(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("SÁBADOS"); + strs2.Remove("SÁBADOS"); + } + segunda = usuario.get_Domingo(); + if (!segunda.GetValueOrDefault() & segunda.HasValue) + { + strs.Add("DOMINGOS"); + strs2.Remove("DOMINGOS"); + } + if (strs.Count == 7) + { + str1 = "RESTRITO TODOS OS DIAS"; + } + else if (strs.Count > 3) + { + str1 = "APENAS PERMITIDO "; + for (int i = 0; i < strs2.Count; i++) + { + if (i >= strs2.Count - 2) + { + str1 = (i != strs2.Count - 2 ? string.Concat(str1, strs2[i]) : string.Concat(str1, strs2[i], " E ")); + } + else + { + str1 = string.Concat(str1, strs2[i], ", "); + } + } + } + else + { + str1 = "RESTRITO "; + for (int j = 0; j < strs.Count; j++) + { + if (j >= strs.Count - 2) + { + str1 = (j != strs.Count - 2 ? string.Concat(str1, strs[j]) : string.Concat(str1, strs[j], " E ")); + } + else + { + str1 = string.Concat(str1, strs[j], ", "); + } + } + } + DateTime networkTime = Funcoes.GetNetworkTime(); + switch (networkTime.DayOfWeek) + { + case DayOfWeek.Sunday: + { + segunda = usuario.get_Domingo(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Monday: + { + segunda = usuario.get_Segunda(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Tuesday: + { + segunda = usuario.get_Terca(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Wednesday: + { + segunda = usuario.get_Quarta(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Thursday: + { + segunda = usuario.get_Quinta(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Friday: + { + segunda = usuario.get_Sexta(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + case DayOfWeek.Saturday: + { + segunda = usuario.get_Sabado(); + if (!(!segunda.GetValueOrDefault() & segunda.HasValue)) + { + break; + } + str = string.Concat("ACESSO ", str1, ". CONTATE O ADMINISTRADOR DO SISTEMA"); + str2 = null; + return str; + } + } + if (usuario.get_InicioAcesso().HasValue && usuario.get_FimAcesso().HasValue && (networkTime.TimeOfDay <= usuario.get_InicioAcesso().Value.TimeOfDay || networkTime.TimeOfDay >= usuario.get_FimAcesso().Value.TimeOfDay)) + { + DateTime value = usuario.get_InicioAcesso().Value; + string shortTimeString = value.ToShortTimeString(); + value = usuario.get_FimAcesso().Value; + str2 = string.Concat("USUÁRIO COM PERMISSÃO DE ACESSO ENTRE ", shortTimeString, " E ", value.ToShortTimeString()); + } + str = str2; + } + else + { + str = "DADOS DE ACESSO INVÁLIDOS"; + } + str2 = null; + return str; + } + + public async Task VerificarContrato(Gestor.Model.License.Produto produto, bool message = true, bool root = false) + { + bool flag; + Licenca licenca; + string str; + if (produto == 79) + { + List produtos = LicenseHelper.Produtos; + if (!produtos.Exists((Licenca x) => { + if (x.get_Produto() != 91) + { + return false; + } + return x.get_AcessoLiberado(); + })) + { + List licencas = LicenseHelper.Produtos; + if (!licencas.Exists((Licenca x) => { + if (x.get_Produto() != 81) + { + return false; + } + return x.get_AcessoLiberado(); + })) + { + List produtos1 = LicenseHelper.Produtos; + if (produtos1.Exists((Licenca x) => { + if (x.get_Produto() != 77) + { + return false; + } + return x.get_AcessoLiberado(); + })) + { + flag = true; + return flag; + } + } + else + { + flag = true; + return flag; + } + } + else + { + flag = true; + return flag; + } + } + if (LicenseHelper.Produtos == null || !LicenseHelper.Produtos.Exists((Licenca x) => { + if (x.get_Produto() != produto) + { + return false; + } + return x.get_AcessoLiberado(); + })) + { + if (message) + { + List licencas1 = LicenseHelper.Produtos; + if (licencas1 != null) + { + licenca = licencas1.FirstOrDefault((Licenca x) => x.get_Produto() == produto); + } + else + { + licenca = null; + } + Licenca licenca1 = licenca; + BaseViewModel baseViewModel = this; + str = (licenca1 == null ? string.Concat("VOCÊ NÃO POSSUI O MÓDULO ", EnumHelper.GetDescription(produto), " CONTRATADO") : string.Concat("ACESSO AO MÓDULO ", EnumHelper.GetDescription(produto), " INTERROMPIDO")); + await baseViewModel.ShowMessage(str, "OK", "", root); + } + flag = false; + } + else + { + flag = true; + } + return flag; + } + + public void VerificarEnables(long? id) + { + this._lastId = id; + this.EnableIncluir = (!id.HasValue ? true : id.Value >= (long)0); + this.EnableAlterar = (!id.HasValue ? false : id.Value > (long)0); + this.EnableExcluir = (!id.HasValue ? false : id.Value > (long)0); + this.EnableButtons = (!id.HasValue ? false : id.Value > (long)0); + } + + public async Task VerificarPermissao(TipoTela tela, bool root = false) + { + bool flag; + if (!await this.PermissaoConsultar(tela)) + { + await this.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR ESSA TELA. CONTATE O ADIMINSTRADOR DO SISTEMA.", "OK", "", root); + flag = false; + } + else + { + flag = true; + } + return flag; + } + + public async Task VerificarRestricao(TipoRestricao tipoRestricao, bool root = false, bool showmessage = true) + { + bool flag; + if (Recursos.Usuario.get_Id() != 0) + { + RestricaoUsuario restricaoUsuario = this.ServicoRestriUsuario.BuscarRestricao(Recursos.Usuario, tipoRestricao); + if (restricaoUsuario == null || !restricaoUsuario.get_Restricao()) + { + flag = true; + } + else + { + if (showmessage) + { + await this.ShowMessage("VOCÊ NÃO POSSUI PERMISSÃO PARA ACESSAR ESSA TELA. CONTATE O ADMINISTRADOR DO SISTEMA.", "OK", "", root); + } + flag = false; + } + } + else + { + flag = true; + } + return flag; + } + + public async Task VerificarVersao() + { + bool flag; + bool flag1; + try + { + string str = await Gestor.Application.Helpers.Connection.Get(string.Format("Update/Stable?versao={0}", ApplicationHelper.Versao), true, false); + flag1 = (str == null ? false : bool.Parse(str)); + flag = flag1; + } + catch (Exception exception1) + { + Exception exception = exception1; + (new BaseServico()).Registrar(exception, 287, 3, ApplicationHelper.Versao.ToString(), false); + flag = false; + } + if (flag) + { + await this.ShowMessage("HÁ UMA ATUALIZAÇÃO OBRIGATÓRIA A SER FEITA. O PROCESSO SERÁ CANCELADO PARA A ATUALIZAÇÃO", "OK", "", false); + System.Windows.Application.Current.Shutdown(); + } + else + { + ApplicationHelper.ChecagemVersao = Funcoes.GetNetworkTime(); + } + } + + public async Task> VerificaVinculoVendedor(Usuario usuario) + { + List vendedorUsuarios; + if (usuario == null || usuario.get_Id() == 0) + { + vendedorUsuarios = new List(); + } + else + { + vendedorUsuarios = await this.ServicoVendedorUsuario.FindByVinculo(usuario); + } + return vendedorUsuarios; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs new file mode 100644 index 0000000..abd3dde --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs @@ -0,0 +1,292 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogAdvertisingViewModel : BaseViewModel + { + private readonly bool _isPromo; + + private string _urlPesquisa; + + private Visibility _visualizarNaoExibirNovamente = Visibility.Hidden; + + private string _titulo = ""; + + private string _imagem = ""; + + public string Url = ""; + + private bool _naoQuero; + + public string Imagem + { + get + { + return this._imagem; + } + set + { + this._imagem = value; + base.OnPropertyChanged("Imagem"); + } + } + + public bool NaoVer + { + get + { + return this._naoQuero; + } + set + { + this._naoQuero = value; + base.OnPropertyChanged("NaoVer"); + } + } + + public string Titulo + { + get + { + return this._titulo; + } + set + { + this._titulo = value; + base.OnPropertyChanged("Titulo"); + } + } + + public Visibility VisualizarNaoExibirNovamente + { + get + { + return this._visualizarNaoExibirNovamente; + } + set + { + this._visualizarNaoExibirNovamente = value; + base.OnPropertyChanged("VisualizarNaoExibirNovamente"); + } + } + + public DialogAdvertisingViewModel(JObject jsonAd, bool isPromo) + { + bool flag; + bool flag1 = false; + this._isPromo = isPromo; + if (this._isPromo) + { + this.CarregaImagem(jsonAd); + JToken item = jsonAd.get_Item("NaoExibirNovamente"); + if (item != null) + { + flag = Extensions.Value(item); + } + else + { + flag = true; + } + flag1 = flag; + } + else + { + this.CarregaPesquisa(jsonAd); + } + this.VisualizarNaoExibirNovamente = (flag1 ? Visibility.Visible : Visibility.Hidden); + } + + private void CarregaImagem(JObject json) + { + string str; + string str1; + string str2; + if (json == null) + { + return; + } + JToken item = json.get_Item("Titulo"); + if (item != null) + { + str = Extensions.Value(item); + } + else + { + str = null; + } + this.Titulo = str; + JToken jToken = json.get_Item("Url"); + if (jToken != null) + { + str1 = Extensions.Value(jToken); + } + else + { + str1 = null; + } + this.Url = str1; + JToken item1 = json.get_Item("Imagem"); + if (item1 != null) + { + str2 = Extensions.Value(item1); + } + else + { + str2 = null; + } + this.Imagem = str2; + } + + private void CarregaPesquisa(JObject json) + { + string str; + string str1; + string str2; + string str3; + if (json == null) + { + return; + } + JToken item = json.get_Item("Titulo"); + if (item != null) + { + str = Extensions.Value(item); + } + else + { + str = null; + } + this.Titulo = str; + JToken jToken = json.get_Item("Imagem"); + if (jToken != null) + { + str1 = Extensions.Value(jToken); + } + else + { + str1 = null; + } + this.Imagem = str1; + JToken item1 = json.get_Item("UrlPost"); + if (item1 != null) + { + str2 = Extensions.Value(item1); + } + else + { + str2 = null; + } + this._urlPesquisa = str2; + if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this._urlPesquisa)) + { + return; + } + JToken jToken1 = json.get_Item("UrlFixa"); + if (jToken1 != null) + { + str3 = Extensions.Value(jToken1); + } + else + { + str3 = null; + } + this._urlPesquisa = str3; + this.Url = this._urlPesquisa; + } + + public void CriarConfiguracaoPadrao(string configFile) + { + File.WriteAllText(configFile, JsonConvert.SerializeObject(new Gestor.Application.Model.Configuracoes() + { + LinkPromo = "", + NaoverPromo = this.NaoVer + }, 1)); + } + + public void EnviarPesquisa() + { + string str; + try + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(15)); + httpClient.get_DefaultRequestHeaders().TryAddWithoutValidation("company-key", "$2b$10$arV/viDP6N.5KX9sRt/.MOo8Gv5FFvHIx0P6HZyuky51P3ItWBV0u"); + var variable = new { customers = new u003cu003ef__AnonymousType49[] { new { nome = Recursos.Usuario.get_Nome(), email = (Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(Recursos.Usuario.get_Email()) ? string.Format("{0}-{1}@sememail.com", Recursos.Usuario.get_Id(), ApplicationHelper.IdFornecedor) : Recursos.Usuario.get_Email()), corretora = Recursos.Empresa.get_NomeSocial(), produto = "Gestor", idfornecedor = ApplicationHelper.IdFornecedor } } }; + HttpResponseMessage result = httpClient.PostAsync(this._urlPesquisa, variable.ToHttpContent(null, "application/json")).Result; + if (result.get_IsSuccessStatusCode()) + { + JToken item = JObject.Parse(result.get_Content().ReadAsStringAsync().Result).get_Item("customers"); + if (item != null) + { + JToken jToken = item.get_Item(0); + if (jToken != null) + { + JToken item1 = jToken.get_Item("shortUrl"); + if (item1 != null) + { + str = Extensions.Value(item1); + } + else + { + str = null; + } + } + else + { + str = null; + } + } + else + { + str = null; + } + string str1 = str; + if (!Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(str1)) + { + this.Url = str1; + } + else + { + return; + } + } + else + { + return; + } + } + } + catch (Exception exception) + { + } + } + + public void SalvaEditarArquivoConfig(bool visto = false) + { + if (!File.Exists("config.json")) + { + this.CriarConfiguracaoPadrao("config.json"); + } + Gestor.Application.Model.Configuracoes naoVer = JsonConvert.DeserializeObject(File.ReadAllText("config.json")); + naoVer.LinkPromo = (this._isPromo ? this.Imagem : this._urlPesquisa); + naoVer.NaoverPromo = this.NaoVer; + File.WriteAllText("config.json", JsonConvert.SerializeObject(naoVer, 1)); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs new file mode 100644 index 0000000..0e87f86 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs @@ -0,0 +1,44 @@ +using Gestor.Model.Domain.Common; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogAnexarViewModel : BaseViewModel + { + private ObservableCollection _arquivos = new ObservableCollection(); + + public ObservableCollection Arquivos + { + get + { + return this._arquivos; + } + set + { + this._arquivos = value; + base.OnPropertyChanged("Arquivos"); + } + } + + public DialogAnexarViewModel(List arquivos) + { + this.Arquivos = new ObservableCollection(arquivos); + } + + public void Remover(ArquivoDigital removido) + { + IEnumerable arquivoDigitals = this.Arquivos.Where((ArquivoDigital x) => { + if (x.get_Descricao() != removido.get_Descricao()) + { + return false; + } + return (int)x.get_Arquivo().Length == (int)removido.get_Arquivo().Length; + }); + this.Arquivos = new ObservableCollection(arquivoDigitals); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs new file mode 100644 index 0000000..3386705 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs @@ -0,0 +1,168 @@ +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Helper; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogCopiaViewModel : BaseViewModel + { + private List _tipoCopia = new List() + { + "CÓPIA COMUM", + "CÓPIA OCULTA" + }; + + private string _tipo; + + private string _copiarPara; + + private Gestor.Model.Domain.MalaDireta.Copia _copia; + + private string _erro; + + private ObservableCollection _copiasComuns; + + private ObservableCollection _copiasOcultas; + + public Gestor.Model.Domain.MalaDireta.Copia Copia + { + get + { + return this._copia; + } + set + { + this._copia = value; + base.OnPropertyChanged("Copia"); + } + } + + public string CopiarPara + { + get + { + return this._copiarPara; + } + set + { + this._copiarPara = value; + base.OnPropertyChanged("CopiarPara"); + } + } + + public ObservableCollection CopiasComuns + { + get + { + return this._copiasComuns; + } + set + { + this._copiasComuns = value; + base.OnPropertyChanged("CopiasComuns"); + } + } + + public ObservableCollection CopiasOcultas + { + get + { + return this._copiasOcultas; + } + set + { + this._copiasOcultas = value; + base.OnPropertyChanged("CopiasOcultas"); + } + } + + public string Erro + { + get + { + return this._erro; + } + set + { + this._erro = value; + base.OnPropertyChanged("Erro"); + } + } + + public string Tipo + { + get + { + return this._tipo; + } + set + { + this._tipo = value; + base.OnPropertyChanged("Tipo"); + } + } + + public List TipoCopia + { + get + { + return this._tipoCopia; + } + set + { + this._tipoCopia = value; + base.OnPropertyChanged("TipoCopia"); + } + } + + public DialogCopiaViewModel(Gestor.Model.Domain.MalaDireta.Copia copia) + { + this.Tipo = this.TipoCopia.First(); + Gestor.Model.Domain.MalaDireta.Copia copium = copia; + if (copium == null) + { + copium = new Gestor.Model.Domain.MalaDireta.Copia(); + copium.set_CopiaOculta(new List()); + copium.set_CopiaComum(new List()); + } + this.Copia = copium; + this.CopiasComuns = new ObservableCollection(this.Copia.get_CopiaComum()); + this.CopiasOcultas = new ObservableCollection(this.Copia.get_CopiaOculta()); + } + + public void AdicionarCopia() + { + if (!ValidationHelper.ValidacaoEmail(this.CopiarPara)) + { + this.Erro = "E-MAIL INVÁLIDO"; + return; + } + if (this.Copia.get_CopiaOculta().Contains(this.CopiarPara)) + { + this.Erro = "E-MAIL JÁ ADICIONADO"; + return; + } + this.Copia.get_CopiaOculta().Add(this.CopiarPara); + this.CopiasOcultas = new ObservableCollection(this.Copia.get_CopiaOculta()); + this.CopiarPara = string.Empty; + this.Erro = "E-MAIL ADICIONADO COM SUCESSO"; + } + + public void ExcluirCopia(string tipo, string copia) + { + if (tipo == "CÓPIA OCULTA") + { + this.Copia.get_CopiaOculta().Remove(copia); + } + else + { + this.Copia.get_CopiaComum().Remove(copia); + } + this.CopiasComuns = new ObservableCollection(this.Copia.get_CopiaComum()); + this.CopiasOcultas = new ObservableCollection(this.Copia.get_CopiaOculta()); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs new file mode 100644 index 0000000..0ca71be --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs @@ -0,0 +1,350 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogCopiarPermissaoViewModel : BaseSegurosViewModel + { + private Usuario _selectedUsuario; + + private Tuple, Usuario, List, List, List> _usuarioParameter; + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + this.WorkOnSelectedUsuario(value); + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public Tuple, Usuario, List, List, List> UsuarioParameter + { + get + { + return this._usuarioParameter; + } + set + { + this._usuarioParameter = value; + base.OnPropertyChanged("UsuarioParameter"); + } + } + + public DialogCopiarPermissaoViewModel() + { + this.UsuarioParameter = new Tuple, Usuario, List, List, List>(null, null, null, null, null); + } + + private async Task> GetPermissoes(Usuario usuario) + { + List permissaoUsuarios = new List(); + IEnumerable tipoTelas = Enum.GetValues(typeof(TipoTela)).Cast(); + IEnumerable str = + from v in tipoTelas + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List permissaoUsuarios1 = await this.ServicoPermissUsuario.PermissUsuario(usuario); + list.ForEach((string x) => { + TipoTela tipoTela = (TipoTela)Enum.Parse(typeof(TipoTela), x); + if (!string.Equals(ValidationHelper.GetCategory(tipoTela), "seguros", StringComparison.CurrentCultureIgnoreCase) && !string.Equals(ValidationHelper.GetCategory(tipoTela), "ferramentas", StringComparison.CurrentCultureIgnoreCase)) + { + return; + } + long id = (long)0; + bool consultar = true; + bool incluir = true; + bool alterar = true; + bool excluir = true; + if (permissaoUsuarios1.Count > 0 && permissaoUsuarios1.Any((PermissaoUsuario y) => y.get_Tela() == tipoTela)) + { + id = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Id(); + consultar = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Consultar(); + incluir = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Incluir(); + alterar = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Alterar(); + excluir = permissaoUsuarios1.First((PermissaoUsuario y) => y.get_Tela() == tipoTela).get_Excluir(); + } + PermissaoUsuario permissaoUsuario = new PermissaoUsuario(); + permissaoUsuario.set_Id(id); + permissaoUsuario.set_Tela(tipoTela); + permissaoUsuario.set_Consultar(consultar); + permissaoUsuario.set_Incluir(incluir); + permissaoUsuario.set_Alterar(alterar); + permissaoUsuario.set_Excluir(excluir); + permissaoUsuarios.Add(permissaoUsuario); + }); + List permissaoUsuarios2 = permissaoUsuarios; + list = null; + return permissaoUsuarios2; + } + + private async Task> GetPermissoesArquivoDigital(Usuario usuario) + { + List permissaoArquivoDigitals = new List(); + IEnumerable tipoArquivoDigitals = Enum.GetValues(typeof(TipoArquivoDigital)).Cast(); + IEnumerable str = + from v in tipoArquivoDigitals + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List permissaoArquivoDigitals1 = await this.ServicoPermissArquivoDigital.PermissArquivoDigital(usuario); + list.ForEach((string x) => { + TipoArquivoDigital tipoArquivoDigital = (TipoArquivoDigital)Enum.Parse(typeof(TipoArquivoDigital), x); + long id = (long)0; + bool consultar = true; + bool incluir = true; + bool excluir = true; + if (permissaoArquivoDigitals1.Count > 0 && permissaoArquivoDigitals1.Any((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital)) + { + id = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Id(); + consultar = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Consultar(); + incluir = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Incluir(); + excluir = permissaoArquivoDigitals1.First((PermissaoArquivoDigital y) => y.get_Tela() == tipoArquivoDigital).get_Excluir(); + } + PermissaoArquivoDigital permissaoArquivoDigital = new PermissaoArquivoDigital(); + permissaoArquivoDigital.set_Id(id); + permissaoArquivoDigital.set_Tela(tipoArquivoDigital); + permissaoArquivoDigital.set_Consultar(consultar); + permissaoArquivoDigital.set_Incluir(incluir); + permissaoArquivoDigital.set_Excluir(excluir); + permissaoArquivoDigitals.Add(permissaoArquivoDigital); + }); + List permissaoArquivoDigitals2 = permissaoArquivoDigitals; + list = null; + return permissaoArquivoDigitals2; + } + + private async Task> GetRestricoes(Usuario usuario) + { + List restricaoUsuarios = new List(); + IEnumerable tipoRestricaos = Enum.GetValues(typeof(TipoRestricao)).Cast(); + IEnumerable str = + from v in tipoRestricaos + select v.ToString(); + List list = ( + from x in str + orderby x + select x).ToList(); + List restricaoUsuarios1 = await this.ServicoRestriUsuario.BuscarRestricoes(usuario.get_Id()); + List restricaoUsuarios2 = restricaoUsuarios1; + list.ForEach((string x) => { + TipoRestricao tipoRestricao = (TipoRestricao)Enum.Parse(typeof(TipoRestricao), x); + long id = (long)0; + bool restricao = false; + if (restricaoUsuarios2.Count > 0 && restricaoUsuarios2.Any((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao)) + { + id = restricaoUsuarios2.First((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao).get_Id(); + restricao = restricaoUsuarios2.First((RestricaoUsuario y) => y.get_Tipo() == tipoRestricao).get_Restricao(); + } + RestricaoUsuario restricaoUsuario = new RestricaoUsuario(); + restricaoUsuario.set_Id(id); + restricaoUsuario.set_Tipo(tipoRestricao); + restricaoUsuario.set_Restricao(restricao); + restricaoUsuarios.Add(restricaoUsuario); + }); + List restricaoUsuarios3 = restricaoUsuarios; + list = null; + return restricaoUsuarios3; + } + + private async Task> GetRestricoesCamposRelatorios(Usuario usuario) + { + List restricaoUsuarioCamposRelatorios = new List(); + List parametrosRelatorios = new List(); + foreach (Relatorio relatorio in Enum.GetValues(typeof(Relatorio)).Cast()) + { + switch (relatorio) + { + case 0: + case 1: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 2: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 3: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 4: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 5: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 6: + case 16: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 7: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 8: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 9: + case 10: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 11: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 12: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 13: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 14: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 15: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 17: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 18: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 19: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 20: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 23: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 27: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + case 29: + { + parametrosRelatorios.AddRange(Funcoes.ColunasRelatorio(relatorio, new List())); + continue; + } + default: + { + continue; + } + } + } + List restricaoUsuarioCamposRelatorios1 = await this.ServicoRestriUsuario.BuscarRestricoesCamposRelatorios(usuario.get_Id()); + List restricaoUsuarioCamposRelatorios2 = restricaoUsuarioCamposRelatorios1; + parametrosRelatorios.ForEach((ParametrosRelatorio x) => { + long id = (long)0; + bool restricao = false; + if (restricaoUsuarioCamposRelatorios2.Count > 0 && restricaoUsuarioCamposRelatorios2.Any((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + })) + { + id = restricaoUsuarioCamposRelatorios2.First((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + }).get_Id(); + restricao = restricaoUsuarioCamposRelatorios2.First((RestricaoUsuarioCamposRelatorios y) => { + if (y.get_Campo() != x.get_Header()) + { + return false; + } + return y.get_Relatorio() == x.get_Relatorio(); + }).get_Restricao(); + } + RestricaoUsuarioCamposRelatorios restricaoUsuarioCamposRelatorio = new RestricaoUsuarioCamposRelatorios(); + restricaoUsuarioCamposRelatorio.set_Id(id); + restricaoUsuarioCamposRelatorio.set_Campo(x.get_Header()); + restricaoUsuarioCamposRelatorio.set_Relatorio(x.get_Relatorio()); + restricaoUsuarioCamposRelatorio.set_Restricao(restricao); + restricaoUsuarioCamposRelatorios.Add(restricaoUsuarioCamposRelatorio); + }); + List restricaoUsuarioCamposRelatorios3 = restricaoUsuarioCamposRelatorios; + parametrosRelatorios = null; + return restricaoUsuarioCamposRelatorios3; + } + + private async void WorkOnSelectedUsuario(Usuario value) + { + if (value != null && value.get_Id() != 0) + { + List permissoes = await this.GetPermissoes(value); + Usuario usuario = value; + List restricoes = await this.GetRestricoes(value); + List permissoesArquivoDigital = await this.GetPermissoesArquivoDigital(value); + List restricoesCamposRelatorios = await this.GetRestricoesCamposRelatorios(value); + this.UsuarioParameter = new Tuple, Usuario, List, List, List>(permissoes, usuario, restricoes, permissoesArquivoDigital, restricoesCamposRelatorios); + permissoes = null; + usuario = null; + restricoes = null; + permissoesArquivoDigital = null; + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs new file mode 100644 index 0000000..bf96cfe --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs @@ -0,0 +1,342 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Resources; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogEditarParcelasViewModel : BaseViewModel + { + private List _parcelasOriginais; + + internal Gestor.Application.Servicos.ParcelaServico ParcelaServico; + + private ObservableCollection _parcelas; + + private bool _isFatura; + + private string _status; + + private Parcela _selectedParcela; + + private Documento _selectedDocumento; + + public bool IsFatura + { + get + { + return this._isFatura; + } + set + { + this._isFatura = value; + base.OnPropertyChanged("IsFatura"); + } + } + + public ObservableCollection Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + base.OnPropertyChanged("Parcelas"); + } + } + + public Documento SelectedDocumento + { + get + { + return this._selectedDocumento; + } + set + { + this._selectedDocumento = value; + base.OnPropertyChanged("SelectedDocumento"); + } + } + + public Parcela SelectedParcela + { + get + { + return this._selectedParcela; + } + set + { + this._selectedParcela = value; + base.OnPropertyChanged("SelectedParcela"); + } + } + + public string Status + { + get + { + return this._status; + } + set + { + this._status = value; + base.OnPropertyChanged("Status"); + } + } + + public DialogEditarParcelasViewModel(Documento documento) + { + this.SelectedDocumento = documento; + this.ParcelaServico = new Gestor.Application.Servicos.ParcelaServico(); + this.Carregar(documento.get_Id()); + TipoRecebimento? tipoRecebimento = documento.get_TipoRecebimento(); + this.IsFatura = tipoRecebimento.GetValueOrDefault(1) == 2; + } + + public void AlterandoValor() + { + if (this.SelectedParcela.get_Documento() == null) + { + this.SelectedParcela.set_Documento(this.SelectedDocumento); + } + this.SelectedParcela.get_Documento().set_Parcelas(this.Parcelas); + if (this.SelectedDocumento.get_TipoRecebimento().GetValueOrDefault() == 1 && this.SelectedParcela.get_SubTipo() == 1 && this.SelectedParcela.get_Comissao() == decimal.Zero) + { + this.SelectedParcela.set_Comissao(this.SelectedDocumento.get_Comissao()); + } + this.SelectedParcela.set_Baixando(false); + this.AlterarValor(); + } + + public void AlterandoVencimento(Parcela parcela) + { + DateTime vencimento; + ObservableCollection parcelas; + if (Recursos.Configuracoes.All((ConfiguracaoSistema y) => y.get_Configuracao() != 11)) + { + DateTime? vigencia2 = parcela.get_Documento().get_Vigencia2(); + if (vigencia2.HasValue) + { + vencimento = parcela.get_Vencimento(); + vigencia2 = parcela.get_Documento().get_Vigencia2(); + if ((vigencia2.HasValue ? vencimento > vigencia2.GetValueOrDefault() : false) && parcela.get_Documento().get_Controle().get_Ramo().get_Id() != (long)23) + { + Action acionarSnackbar = Gestor.Application.Actions.Actions.AcionarSnackbar; + if (acionarSnackbar != null) + { + acionarSnackbar(string.Concat("DATA INVÁLIDA. ", Messages.get_VencimentoMaior())); + } + else + { + } + parcela.set_Vencimento(this._parcelasOriginais.First((Parcela x) => x.get_Id() == parcela.get_Id()).get_Vencimento()); + } + } + } + if (Recursos.Configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 9)) + { + if (parcela.get_Documento().get_Vigencia1() > DateTime.MinValue && parcela.get_NumeroParcela() == 1) + { + DateTime dateTime = parcela.get_Vencimento(); + vencimento = parcela.get_Documento().get_Vigencia1(); + if (dateTime < vencimento.AddDays(-30)) + { + goto Label0; + } + } + if (parcela.get_NumeroParcela() == 1 || !(parcela.get_Vencimento() < parcela.get_Documento().get_Vigencia1())) + { + parcelas = this.Parcelas; + this.Parcelas = new ObservableCollection( + from x in parcelas + orderby x.get_NumeroParcela() + select x); + return; + } + Label0: + Action action = Gestor.Application.Actions.Actions.AcionarSnackbar; + if (action != null) + { + action(string.Concat("DATA INVÁLIDA. ", Messages.get_VencimentoMenor())); + } + else + { + } + parcela.set_Vencimento(this._parcelasOriginais.First((Parcela x) => x.get_Id() == parcela.get_Id()).get_Vencimento()); + } + parcelas = this.Parcelas; + this.Parcelas = new ObservableCollection( + from x in parcelas + orderby x.get_NumeroParcela() + select x); + } + + public void AlterarValor() + { + if (this.SelectedParcela == null) + { + return; + } + if (this.SelectedParcela.get_SubTipo() != 1 || this.IsFatura) + { + this.SelectedParcela.set_Documento(this.SelectedDocumento); + return; + } + decimal premioTotal = this.SelectedDocumento.get_PremioTotal() - this.Parcelas.Where((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_Id() != this.SelectedParcela.get_Id(); + }).Sum((Parcela x) => x.get_Valor()); + decimal valor = this.SelectedDocumento.get_PremioTotal() - this.Parcelas.Where((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_Id() < this.SelectedParcela.get_Id(); + }).Sum((Parcela x) => x.get_Valor()); + valor -= this.SelectedParcela.get_Valor(); + decimal numeroParcelas = this.SelectedDocumento.get_NumeroParcelas() - this.SelectedParcela.get_NumeroParcela(); + if (numeroParcelas == decimal.Zero) + { + numeroParcelas = decimal.One; + } + decimal num = (numeroParcelas > decimal.Zero ? valor / numeroParcelas : decimal.Zero); + if (num == decimal.Zero) + { + this.SelectedParcela.set_Valor(premioTotal); + } + List parcelas = new List() + { + this.SelectedParcela + }; + decimal num1 = Math.Abs(num); + decimal? tolerancia = this.SelectedDocumento.get_Controle().get_Seguradora().get_Tolerancia(); + if ((num1 > tolerancia.GetValueOrDefault()) & tolerancia.HasValue && !this.Parcelas.Any((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_NumeroParcela() > this.SelectedParcela.get_NumeroParcela(); + })) + { + this.SelectedParcela.set_Valor(premioTotal); + } + this.Parcelas.Where((Parcela x) => { + if (x.get_SubTipo() != 1) + { + return false; + } + return x.get_NumeroParcela() != this.SelectedParcela.get_NumeroParcela(); + }).ToList().ForEach((Parcela x) => { + if (x.get_NumeroParcela() > this.SelectedParcela.get_NumeroParcela()) + { + x.set_Valor((num > decimal.Zero ? num : x.get_Valor())); + x.set_Comissao((x.get_Comissao() == decimal.Zero ? this.SelectedDocumento.get_Comissao() : x.get_Comissao())); + } + parcelas.Add(x); + }); + foreach (Parcela parcela in + from x in parcelas + where x.get_NumeroParcela() >= this.SelectedParcela.get_NumeroParcela() + select x) + { + parcela.set_Documento(this.SelectedDocumento); + if (parcela.get_Id() == this.SelectedParcela.get_Id()) + { + continue; + } + parcela.set_Valor(num); + } + this.Parcelas = new ObservableCollection( + from x in parcelas + orderby x.get_NumeroParcela() + select x); + } + + public async void Carregar(long id) + { + await this.CarregarParcelas(id); + } + + public async Task CarregarParcelas(long id) + { + ObservableCollection observableCollection; + ObservableCollection observableCollection1 = await (new Gestor.Application.Servicos.ParcelaServico()).BuscarParcelasAsync(id); + this._parcelasOriginais = new List(); + foreach (Parcela parcela in observableCollection1) + { + this._parcelasOriginais.Add((Parcela)parcela.Clone()); + } + DialogEditarParcelasViewModel dialogEditarParcelasViewModel = this; + if (this.IsFatura) + { + ObservableCollection observableCollection2 = observableCollection1; + observableCollection = new ObservableCollection( + from x in observableCollection2 + orderby x.get_NumeroParcela() + select x); + } + else + { + observableCollection = observableCollection1; + } + dialogEditarParcelasViewModel.Parcelas = observableCollection; + } + + public async Task SalvarParcelas() + { + bool flag; + foreach (Parcela parcela in this.Parcelas) + { + Parcela parcela1 = this._parcelasOriginais.First((Parcela x) => x.get_Id() == parcela.get_Id()); + if (!(parcela.get_Vencimento() != parcela1.get_Vencimento()) && !(parcela.get_Valor() != parcela1.get_Valor())) + { + continue; + } + parcela1.set_Vencimento(parcela.get_Vencimento()); + parcela1.set_Valor(parcela.get_Valor()); + Parcela selectedParcela = this.SelectedParcela; + List configuracoes = Recursos.Configuracoes; + bool flag1 = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 9); + List configuracaoSistemas = Recursos.Configuracoes; + bool flag2 = configuracaoSistemas.Any((ConfiguracaoSistema y) => y.get_Configuracao() == 11); + List configuracoes1 = Recursos.Configuracoes; + List> keyValuePairs = selectedParcela.Validate(flag1, flag2, true, configuracoes1.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 16)); + if (keyValuePairs.Count <= 0) + { + await (new Gestor.Application.Servicos.ParcelaServico()).Save(parcela1, this._parcelasOriginais, null, true); + } + else + { + List> keyValuePairs1 = keyValuePairs; + string str = string.Join(", ", keyValuePairs1.Select, string>((KeyValuePair x) => { + string[] strArrays = x.Key.Split(new char[] { '|' }); + return string.Concat(((int)strArrays.Length > 1 ? strArrays[1] : x.Key), ": ", x.Value, Environment.NewLine); + })); + this.Status = string.Concat("NÃO FOI POSSÍVEL SALVAR DEVIDO AOS ERROS ABAIXO:", Environment.NewLine, str); + flag = false; + return flag; + } + } + base.RegistrarAcao(string.Format("EDITOU VENCIMENTO E/OU VALORES DAS PARCELAS/FATURAS DO DOCUMENTO DE ID {0}", this.Parcelas[0].get_Documento().get_Id()), this.Parcelas[0].get_Documento().get_Id(), new TipoTela?(5), null); + flag = true; + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs new file mode 100644 index 0000000..646d94e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs @@ -0,0 +1,394 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogEnviarEmailsViewModel : BaseSegurosViewModel + { + private ObservableCollection _listaTela = new ObservableCollection(); + + private string _infoEnvio = "CLIQUE EM ENVIAR PARA INCIAR O ENVIO"; + + private List _arquivosAnexados + { + get; + set; + } + + private bool _assinatura + { + get; + set; + } + + private string _assunto + { + get; + set; + } + + private bool _confirmarLeitura + { + get; + set; + } + + private string _corpo + { + get; + set; + } + + private Credencial _credencial + { + get; + set; + } + + private FiltroArquivoDigital _filtro + { + get; + set; + } + + private bool _original + { + get; + set; + } + + private bool _salvarAd + { + get; + set; + } + + public string InfoEnvio + { + get + { + return this._infoEnvio; + } + set + { + this._infoEnvio = value; + base.OnPropertyChanged("InfoEnvio"); + } + } + + public List Lista + { + get; + set; + } + + public ObservableCollection ListaTela + { + get + { + return this._listaTela; + } + set + { + this._listaTela = value; + base.OnPropertyChanged("ListaTela"); + } + } + + public DialogEnviarEmailsViewModel(List lista, bool assinatura, bool original, List arquivosAnexados, string assunto, string corpo, Credencial credencial, FiltroArquivoDigital filtro, bool salvarAd, bool confirmarLeitura) + { + lista.ForEach((MalaDireta x) => x.set_InfoEnvio(null)); + this.Lista = lista; + this.PrepararLista(); + this._assinatura = assinatura; + this._original = original; + this._arquivosAnexados = arquivosAnexados; + this._assunto = assunto; + this._corpo = corpo; + this._credencial = credencial; + this._filtro = filtro; + this._salvarAd = salvarAd; + this._confirmarLeitura = confirmarLeitura; + } + + public void Enviar() + { + this.Enviar(this._assinatura, this._original, this._arquivosAnexados, this._assunto, this._corpo, this._credencial, this._filtro, this._salvarAd, this._confirmarLeitura); + } + + private async void Enviar(bool assinatura, bool original, List arquivosAnexados, string assunto, string corpo, Credencial credencial, FiltroArquivoDigital filtro, bool salvarAd, bool confirmarLeitura) + { + base.Loading(true); + this.InfoEnvio = "ENVIANDO, AGUARDE ATÉ O PROCESSO TERMINAR."; + await this.EnviarEmails(assinatura, original, arquivosAnexados, assunto, corpo, credencial, filtro, salvarAd, confirmarLeitura); + this.InfoEnvio = "TENTATIVA DE ENVIO CONCLUÍDA, CONFIRA O STATUS ABAIXO."; + base.Loading(false); + } + + private async Task EnviarEmails(bool assinatura, bool original, List arquivosAnexados, string assunto, string corpo, Credencial credencial, FiltroArquivoDigital filtro, bool salvarAd, bool confirmarLeitura) + { + int i; + List arquivoDigitals; + List arquivoDigitals1; + bool flag; + bool arquivoDigital; + List copiaComum; + List copiaOculta; + string str; + long? nullable; + bool valueOrDefault; + List strs = new List(); + VariaveisMalaDireta[] values = (VariaveisMalaDireta[])Enum.GetValues(typeof(VariaveisMalaDireta)); + for (i = 0; i < (int)values.Length; i++) + { + strs.Add(ValidationHelper.GetEntity(values[i])); + } + if (strs.Any(new Func(assunto.Contains)) || strs.Any(new Func(corpo.Contains))) + { + flag = true; + } + else + { + List lista = this.Lista; + flag = lista.Any((MalaDireta x) => { + if (x.get_ArquivoDigital() == null) + { + return false; + } + return x.get_ArquivoDigital().Count > 0; + }); + } + bool flag1 = flag; + Credencial credencial1 = credencial; + MailHelper mailHelper = new MailHelper(); + bool flag2 = false; + if (salvarAd) + { + Gestor.Application.Servicos.ArquivoDigitalServico arquivoDigitalServico = new Gestor.Application.Servicos.ArquivoDigitalServico(); + foreach (MalaDireta listum in this.Lista) + { + arquivosAnexados.ForEach((Gestor.Model.Domain.Common.ArquivoDigital a) => { + a.set_IdCliente((listum.get_Tela() == 1 ? listum.get_Cliente().get_Id() : (long)0)); + a.set_IdDocumento((listum.get_Tela() == 2 ? listum.get_Apolice().get_Id() : (long)0)); + a.set_IdItem((listum.get_Tela() == 3 ? listum.get_Item().get_Id() : (long)0)); + a.set_IdParcela((listum.get_Tela() == 5 ? listum.get_Parcela().get_Id() : (long)0)); + a.set_IdProspeccao((listum.get_Tela() == 33 ? listum.get_Prospeccao().get_Id() : (long)0)); + a.set_IdSinistro((listum.get_Tela() == 7 ? listum.get_Sinistro().get_Id() : (long)0)); + a.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + }); + List indiceArquivoDigitals = await arquivoDigitalServico.Insert(arquivosAnexados.ToList()); + List arquivoDigitals2 = arquivosAnexados; + if (!arquivoDigitals2.Any((Gestor.Model.Domain.Common.ArquivoDigital arquivo) => arquivo.get_Arquivo() == null)) + { + continue; + } + arquivoDigitals = await arquivoDigitalServico.Buscar(indiceArquivoDigitals); + arquivosAnexados = arquivoDigitals; + } + arquivoDigitalServico = null; + } + if (!string.IsNullOrWhiteSpace(credencial.get_Cabecalho())) + { + corpo = string.Concat(credencial.get_Cabecalho(), corpo); + } + if (!string.IsNullOrWhiteSpace(credencial.get_Assinatura())) + { + corpo = string.Concat(corpo, "

", credencial.get_Assinatura()); + } + if (flag1) + { + for (int j = 0; j < this.Lista.Count; j = i + 1) + { + MalaDireta item = this.Lista[j]; + if (item.get_ArquivoDigital() == null) + { + arquivoDigitals = new List(); + } + else + { + if (!(!assinatura | original)) + { + Gestor.Application.Servicos.ArquivoDigitalServico arquivoDigitalServico1 = this.ArquivoDigitalServico; + List arquivoDigital1 = item.get_ArquivoDigital(); + arquivoDigitals1 = await arquivoDigitalServico1.Buscar(( + from x in arquivoDigital1 + where string.IsNullOrWhiteSpace(x.get_UrlAssinatura()) + select x).ToList()); + } + else + { + arquivoDigitals1 = await this.ArquivoDigitalServico.Buscar(item.get_ArquivoDigital().ToList()); + } + arquivoDigitals = arquivoDigitals1; + } + List arquivoDigitals3 = arquivoDigitals; + if (arquivosAnexados != null && arquivosAnexados.Count > 0) + { + arquivoDigitals3.AddRange(arquivosAnexados); + } + MalaDireta malaDiretum = item; + if (malaDiretum != null) + { + arquivoDigital = malaDiretum.get_ArquivoDigital(); + } + else + { + arquivoDigital = false; + } + if (!arquivoDigital) + { + MalaDireta malaDiretum1 = item; + if (malaDiretum1 != null) + { + Documento apolice = malaDiretum1.get_Apolice(); + if (apolice != null) + { + nullable = new long?(apolice.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + valueOrDefault = nullable1.GetValueOrDefault() > num & nullable1.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + MalaDireta malaDiretum2 = item; + List indiceArquivoDigitals1 = await this.ArquivoDigitalServico.BuscarPorTipo(2, item.get_Apolice().get_Id()); + malaDiretum2.set_ArquivoDigital(indiceArquivoDigitals1); + malaDiretum2 = null; + } + } + Destinatario destinatario = new Destinatario(); + destinatario.set_Assunto(Funcoes.SubstituirVariaveis(assunto, item)); + destinatario.set_Corpo(Funcoes.SubstituirVariaveis(corpo, item)); + destinatario.set_Email(item.get_Email()); + Copia copia = item.get_Copia(); + if (copia != null) + { + copiaComum = copia.get_CopiaComum(); + } + else + { + copiaComum = null; + } + destinatario.set_Encaminhar(copiaComum); + Copia copium = item.get_Copia(); + if (copium != null) + { + copiaOculta = copium.get_CopiaOculta(); + } + else + { + copiaOculta = null; + } + destinatario.set_EncaminharOculto(copiaOculta); + destinatario.set_Nome(item.get_Cliente().get_Nome()); + destinatario.set_Anexos(arquivoDigitals3); + Destinatario destinatario1 = destinatario; + List malaDiretas = new List() + { + item + }; + LogEnvio logEnvio = await mailHelper.SendAsync(credencial, destinatario1, filtro, malaDiretas, 0, confirmarLeitura); + item.set_Enviado(new bool?(logEnvio.get_Enviado())); + MalaDireta malaDiretum3 = item; + str = (logEnvio.get_Enviado() ? "ENVIADO COM SUCESSO" : string.Concat("NÃO ENVIADO, ENTRE EM CONTATO COM SEU PROVEDOR/SERVIÇO DE E-MAIL E INFORME OS DADOS ABAIXO: \r\n", logEnvio.get_Erro())); + malaDiretum3.set_InfoEnvio(str); + item.set_ArquivoDigital(null); + this.Lista = this.Lista; + item = null; + arquivoDigitals3 = null; + i = j; + } + } + else + { + while (!flag2) + { + List lista1 = this.Lista; + List list = ( + from x in lista1 + where !x.get_Enviado().HasValue + select x).Take(200).ToList(); + List malaDiretas1 = list; + List list1 = ( + from x in malaDiretas1 + select x.get_Email()).ToList(); + list.ForEach((MalaDireta x) => { + if (x.get_Copia() == null) + { + return; + } + list1.AddRange(x.get_Copia().get_CopiaComum()); + list1.AddRange(x.get_Copia().get_CopiaOculta()); + }); + list1 = list1.Distinct().ToList(); + Destinatario destinatario2 = new Destinatario(); + destinatario2.set_Assunto(assunto); + destinatario2.set_Corpo(corpo); + destinatario2.set_Email(credencial1.get_Email()); + destinatario2.set_Nome(credencial1.get_Descricao()); + destinatario2.set_Encaminhar(new List()); + destinatario2.set_EncaminharOculto(list1); + destinatario2.set_Anexos(arquivosAnexados.ToList()); + Destinatario destinatario3 = destinatario2; + LogEnvio logEnvio1 = await mailHelper.SendAsync(credencial, destinatario3, filtro, this.Lista.ToList(), 0, confirmarLeitura); + LogEnvio logEnvio2 = logEnvio1; + List list2 = this.Lista.ToList(); + list2.ForEach((MalaDireta x) => { + x.set_Enviado(new bool?(logEnvio2.get_Enviado())); + x.set_InfoEnvio((logEnvio2.get_Enviado() ? "ENVIADO COM SUCESSO" : string.Concat("NÃO ENVIADO, ENTRE EM CONTATO COM SEU PROVEDOR/SERVIÇO DE E-MAIL E INFORME OS DADOS ABAIXO: \r\n", logEnvio2.get_Erro()))); + }); + this.Lista = list2; + List lista2 = this.Lista; + flag2 = lista2.All((MalaDireta x) => x.get_Enviado().HasValue); + } + } + this.PrepararLista(); + credencial1 = null; + mailHelper = null; + } + + private void PrepararLista() + { + List malaDiretas = new List(); + this.Lista.ForEach((MalaDireta x) => { + malaDiretas.Add(x); + if (x.get_Copia() == null) + { + return; + } + malaDiretas.AddRange(x.get_Copia().get_CopiaOculta().Select((string c) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Cliente()); + malaDiretum.set_Email(c); + malaDiretum.set_Enviado(x.get_Enviado()); + malaDiretum.set_InfoEnvio(x.get_InfoEnvio()); + return malaDiretum; + }).ToList()); + }); + this.ListaTela = new ObservableCollection(malaDiretas); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs new file mode 100644 index 0000000..dd39cab --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs @@ -0,0 +1,122 @@ +using Gestor.Application.Servicos.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogExportarPermissaoViewModel : BaseSegurosViewModel + { + private bool _enableGrid = true; + + private List _usuarios; + + private ObservableCollection _usuariosFiltrados = new ObservableCollection(); + + public bool EnableGrid + { + get + { + return this._enableGrid; + } + set + { + this._enableGrid = value; + base.OnPropertyChanged("EnableGrid"); + } + } + + public List Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public ObservableCollection UsuariosFiltrados + { + get + { + return this._usuariosFiltrados; + } + set + { + this._usuariosFiltrados = value; + base.OnPropertyChanged("UsuariosFiltrados"); + } + } + + public DialogExportarPermissaoViewModel(long idUsuario) + { + this.Seleciona(idUsuario); + } + + internal async Task> Filtrar(string value) + { + List usuarios = await Task.Run>(() => this.FiltrarUsuario(value)); + return usuarios; + } + + public List FiltrarUsuario(string filter) + { + this.UsuariosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Usuarios) : new ObservableCollection( + from x in this.Usuarios + where ValidationHelper.RemoveDiacritics(x.get_Nome().ToUpper().Trim()).Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby !x.get_Excluido() descending, x.get_Nome() + select x)); + return this.UsuariosFiltrados.ToList(); + } + + private async void Seleciona(long idUsuario) + { + base.Loading(true); + await this.SelecionaUsuarios(idUsuario); + base.Loading(false); + } + + public void Selecionar() + { + if (this.UsuariosFiltrados == null || this.UsuariosFiltrados.Count == 0) + { + return; + } + this.UsuariosFiltrados.ToList().ForEach((Usuario x) => x.set_Selecionado(!x.get_Selecionado())); + this.UsuariosFiltrados = new ObservableCollection(this.UsuariosFiltrados); + } + + private async Task SelecionaUsuarios(long idUsuario) + { + this.EnableGrid = false; + base.Loading(true); + List usuarios = await (new BaseServico()).BuscarUsuariosAsync(); + DialogExportarPermissaoViewModel list = this; + IEnumerable usuarios1 = usuarios.Where((Usuario x) => { + if (x.get_Excluido()) + { + return false; + } + return x.get_Id() != idUsuario; + }); + list.Usuarios = ( + from x in usuarios1 + orderby x.get_Nome() + select x).ToList(); + this.UsuariosFiltrados = new ObservableCollection(this.Usuarios); + base.Loading(false); + this.EnableGrid = true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs new file mode 100644 index 0000000..94b332a --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs @@ -0,0 +1,45 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogGraficoViewModel : INotifyPropertyChanged + { + private SinteticoSource _source; + + public SinteticoSource Source + { + get + { + return this._source; + } + set + { + this.MutateVerbose(ref this._source, value, this.RaisePropertyChanged(), "Source"); + } + } + + public DialogGraficoViewModel(SinteticoSource series) + { + this.Source = series; + } + + private Action RaisePropertyChanged() + { + return (PropertyChangedEventArgs args) => { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, args); + }; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs new file mode 100644 index 0000000..49eb58b --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs @@ -0,0 +1,75 @@ +using System; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogMedalhaViewModel : BaseSegurosViewModel + { + private int _liquido; + + private int _comissao; + + private int _resultado; + + private int _media; + + public int Comissao + { + get + { + return this._comissao; + } + set + { + this._comissao = value; + base.OnPropertyChanged("Comissao"); + } + } + + public int Liquido + { + get + { + return this._liquido; + } + set + { + this._liquido = value; + base.OnPropertyChanged("Liquido"); + } + } + + public int Media + { + get + { + return this._media; + } + set + { + this._media = value; + base.OnPropertyChanged("Media"); + } + } + + public int Resultado + { + get + { + return this._resultado; + } + set + { + this._resultado = value; + base.OnPropertyChanged("Resultado"); + } + } + + public DialogMedalhaViewModel(int liquido, int comissao, int resultado, int media) + { + this.Liquido = liquido; + this.Comissao = comissao; + this.Resultado = resultado; + this.Media = media; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs new file mode 100644 index 0000000..284d821 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs @@ -0,0 +1,604 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogPesquisaAvancadaViewModel : BaseSegurosViewModel + { + private ObservableCollection _pesquisas = new ObservableCollection(); + + private PesquisaAvancada _resultado = new PesquisaAvancada(); + + private string _pesquisa; + + private FiltroStatusDocumento _status; + + private TipoTela _tela; + + private TipoFiltroBusca _tipoFiltro; + + private bool _habilitarFiltroBuscar; + + private FiltroStatusDocumento _oldStatus; + + private bool _enableStatus = true; + + public bool TipoBusca; + + private TipoPesquisa _tipo { get; set; } = 14; + + public bool EnableStatus + { + get + { + return this._enableStatus; + } + set + { + this._enableStatus = value; + base.OnPropertyChanged("EnableStatus"); + } + } + + public bool HabilitarFiltroBuscar + { + get + { + return this._habilitarFiltroBuscar; + } + set + { + this._habilitarFiltroBuscar = value; + base.OnPropertyChanged("HabilitarFiltroBuscar"); + } + } + + public string Informacao + { + get + { + return "O LIMITE DA PESQUISA É EM MIL ITENS,\r\nPARA OBTER UMA EXATIDÃO NA PESQUISA É NECESSÁRIO ESPECIFICAR O ITEM PROCURADO."; + } + } + + public string Pesquisa + { + get + { + return this._pesquisa; + } + set + { + this._pesquisa = value; + base.OnPropertyChanged("Pesquisa"); + } + } + + public ObservableCollection Pesquisas + { + get + { + return this._pesquisas; + } + set + { + this._pesquisas = value; + base.OnPropertyChanged("Pesquisas"); + } + } + + public PesquisaAvancada Resultado + { + get + { + return this._resultado; + } + set + { + if (value != null) + { + value.set_Status(this.Status); + } + this._resultado = value; + base.OnPropertyChanged("Resultado"); + } + } + + public FiltroStatusDocumento Status + { + get + { + return this._status; + } + set + { + this._status = value; + this._oldStatus = value; + if (this.Resultado != null) + { + this.Resultado.set_Status(this.Status); + } + base.OnPropertyChanged("Status"); + } + } + + public TipoTela Tela + { + get + { + return this._tela; + } + set + { + this._tela = value; + base.OnPropertyChanged("Tela"); + } + } + + public TipoPesquisa Tipo + { + get + { + return this._tipo; + } + set + { + if (value == 1 || value == 2 || value == 17 || value == 9) + { + this.EnableStatus = false; + FiltroStatusDocumento filtroStatusDocumento = this._oldStatus; + this.Status = 4; + this._oldStatus = filtroStatusDocumento; + } + else if (this._tipo == 1 || this._tipo == 2) + { + this.EnableStatus = true; + this.Status = this._oldStatus; + } + this._tipo = value; + this.GetTipoTela(); + this.HabilitarBusca(); + base.OnPropertyChanged("Tipo"); + } + } + + public TipoFiltroBusca TipoFiltro + { + get + { + return this._tipoFiltro; + } + set + { + this._tipoFiltro = value; + base.OnPropertyChanged("TipoFiltro"); + } + } + + public DialogPesquisaAvancadaViewModel() + { + } + + public void GetTipoPesquisa() + { + TipoFiltroBusca tipoFiltroBusca = this._tipoFiltro; + if (tipoFiltroBusca == null) + { + this.TipoBusca = false; + return; + } + if (tipoFiltroBusca != 1) + { + return; + } + this.TipoBusca = true; + } + + public void GetTipoTela() + { + switch (this.Tipo) + { + case 0: + case 14: + { + this.Tela = 3; + return; + } + case 1: + case 3: + case 4: + case 5: + case 6: + case 7: + case 8: + case 10: + case 11: + case 12: + case 13: + case 15: + case 16: + case 17: + { + this.Tela = 21; + return; + } + case 2: + case 9: + { + this.Tela = 7; + return; + } + default: + { + return; + } + } + } + + public void HabilitarBusca() + { + switch (this.Tipo) + { + case 0: + case 4: + case 6: + case 8: + case 10: + case 13: + case 14: + { + this.HabilitarFiltroBuscar = true; + return; + } + case 1: + case 2: + { + this.TipoFiltro = 1; + this.HabilitarFiltroBuscar = false; + return; + } + case 3: + case 5: + case 7: + case 9: + case 11: + case 12: + { + this.TipoFiltro = 0; + this.HabilitarFiltroBuscar = false; + return; + } + default: + { + this.TipoFiltro = 0; + this.HabilitarFiltroBuscar = false; + return; + } + } + } + + public async Task Pesquisar() + { + List vendedorUsuarios; + long id; + ObservableCollection observableCollection; + PesquisaAvancada pesquisaAvancada2; + int num; + ObservableCollection observableCollection1; + if (Recursos.Usuario != null) + { + vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + } + else + { + vendedorUsuarios = new List(); + } + List vendedorUsuarios1 = vendedorUsuarios; + this.GetTipoPesquisa(); + switch (this.Tipo) + { + case 0: + { + this.Pesquisas = new ObservableCollection(await (new AutoServico()).BuscarChassi(this.Pesquisa, this.Status, vendedorUsuarios1, this.TipoBusca)); + break; + } + case 1: + { + if (long.TryParse(this.Pesquisa, out id)) + { + Documento documento = await (new ApoliceServico()).BuscarCodDocumento(long.Parse(this.Pesquisa), vendedorUsuarios1); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel = this; + if (documento == null || documento.get_Excluido()) + { + observableCollection1 = new ObservableCollection(); + } + else + { + observableCollection = new ObservableCollection(); + pesquisaAvancada2 = new PesquisaAvancada(); + pesquisaAvancada2.set_Nome(documento.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada2.set_IdDocumento(documento.get_Id()); + string[] proposta = new string[] { "CÓDIGO DO COCUMENTO: ", null, null, null, null, null, null, null }; + id = documento.get_Id(); + proposta[1] = id.ToString(); + proposta[2] = " - NÚMERO DA PROPOSTA: "; + proposta[3] = documento.get_Proposta(); + proposta[4] = " - NÚMERO DA APÓLICE: "; + proposta[5] = documento.get_Apolice(); + proposta[6] = " - NÚMERO DO ENDOSSO: "; + proposta[7] = documento.get_Endosso(); + pesquisaAvancada2.set_Pesquisa(string.Concat(proposta)); + pesquisaAvancada2.set_IdCliente(documento.get_Controle().get_Cliente().get_Id()); + observableCollection.Add(pesquisaAvancada2); + observableCollection1 = observableCollection; + } + dialogPesquisaAvancadaViewModel.Pesquisas = observableCollection1; + break; + } + else + { + return; + } + } + case 2: + { + SinistroServico sinistroServico = new SinistroServico(); + if (int.TryParse(this.Pesquisa, out num)) + { + Sinistro sinistro = await sinistroServico.BuscarSinistro(long.Parse(this.Pesquisa)); + if (sinistro != null) + { + observableCollection = new ObservableCollection(); + pesquisaAvancada2 = new PesquisaAvancada(); + pesquisaAvancada2.set_IdCliente(sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id()); + pesquisaAvancada2.set_IdDocumento(sinistro.get_ControleSinistro().get_Item().get_Documento().get_Id()); + pesquisaAvancada2.set_IdItem(sinistro.get_ControleSinistro().get_Item().get_Id()); + pesquisaAvancada2.set_IdSinistro(sinistro.get_Id()); + pesquisaAvancada2.set_Nome(sinistro.get_ControleSinistro().get_Item().get_Documento().get_NomeProponente()); + string[] itemSinistrado = new string[] { "CÓDIGO DO SINISTRO: ", null, null, null, null, null }; + id = sinistro.get_ControleSinistro().get_Id(); + itemSinistrado[1] = id.ToString(); + itemSinistrado[2] = " - NÚMERO DA APÓLICE: "; + itemSinistrado[3] = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Apolice(); + itemSinistrado[4] = " - ITEM "; + itemSinistrado[5] = sinistro.get_ItemSinistrado(); + pesquisaAvancada2.set_Pesquisa(string.Concat(itemSinistrado)); + observableCollection.Add(pesquisaAvancada2); + this.Pesquisas = observableCollection; + break; + } + else + { + this.Pesquisas = new ObservableCollection(); + break; + } + } + else + { + return; + } + } + case 3: + { + List clienteEmails = await (new EmailServico()).BuscarEmail(this.Pesquisa); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel1 = this; + List clienteEmails1 = clienteEmails; + dialogPesquisaAvancadaViewModel1.Pesquisas = new ObservableCollection(clienteEmails1.Select((ClienteEmail x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_Nome(x.get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("E-MAIL: ", x.get_Email())); + pesquisaAvancada.set_IdCliente(x.get_Cliente().get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 4: + { + List documentos = await (new ApoliceServico()).BuscarApolice(this.Pesquisa, this.Status, vendedorUsuarios1, "Estipulante", this.TipoBusca); + DialogPesquisaAvancadaViewModel observableCollection2 = this; + List documentos1 = documentos; + observableCollection2.Pesquisas = new ObservableCollection(documentos1.Select((Documento x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat(" NÚMERO DA APÓLICE: ", x.get_Apolice())); + return pesquisaAvancada; + }).ToList()); + break; + } + case 5: + { + this.Pesquisas = new ObservableCollection(await (new PatrimonialServico()).BuscarImobiliaria(this.Pesquisa, this.Status, vendedorUsuarios1)); + break; + } + case 6: + { + this.Pesquisas = new ObservableCollection(await (new AutoServico()).BuscarItem(this.Pesquisa, this.Status, vendedorUsuarios1, this.TipoBusca)); + break; + } + case 7: + { + this.Pesquisas = new ObservableCollection(await (new PatrimonialServico()).BuscarLocatario(this.Pesquisa, this.Status, vendedorUsuarios1)); + break; + } + case 8: + { + List documentos2 = await (new ApoliceServico()).BuscarApolice(this.Pesquisa, this.Status, vendedorUsuarios1, "", this.TipoBusca); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel2 = this; + List documentos3 = documentos2; + dialogPesquisaAvancadaViewModel2.Pesquisas = new ObservableCollection(documentos3.Select((Documento x) => { + string str; + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + PesquisaAvancada pesquisaAvancada1 = pesquisaAvancada; + if (!x.get_Vigencia2().HasValue) + { + str = string.Format("NÚMERO DA APÓLICE: {0} - VIGÊNCIA INICIAL: {1:d} - NÚMERO DO ENDOSSO: {2}", x.get_Apolice(), x.get_Vigencia1(), x.get_Endosso()); + } + else + { + object[] apolice = new object[] { x.get_Apolice(), x.get_Vigencia1(), null, null }; + apolice[2] = x.get_Vigencia2().Value; + apolice[3] = x.get_Endosso(); + str = string.Format("NÚMERO DA APÓLICE: {0} - VIGÊNCIA INICIAL: {1:d} - VIGÊNCIA FINAL: {2:d} - NÚMERO DO ENDOSSO: {3}", apolice); + } + pesquisaAvancada1.set_Pesquisa(str); + return pesquisaAvancada; + }).ToList()); + break; + } + case 9: + { + List sinistros = await (new SinistroServico()).BuscarSinistros(this.Pesquisa); + DialogPesquisaAvancadaViewModel observableCollection3 = this; + List sinistros1 = sinistros; + observableCollection3.Pesquisas = new ObservableCollection(sinistros1.Select((Sinistro x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_Nome(x.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat(new string[] { "NÚMERO DO SINISTRO: ", x.get_Numero(), " - NÚMERO DA APÓLICE: ", x.get_ControleSinistro().get_Item().get_Documento().get_Apolice(), " - ITEM: ", x.get_ItemSinistrado() })); + pesquisaAvancada.set_IdCliente(x.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_ControleSinistro().get_Item().get_Documento().get_Id()); + pesquisaAvancada.set_IdItem(x.get_ControleSinistro().get_Item().get_Id()); + pesquisaAvancada.set_IdSinistro(x.get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 10: + { + List documentos4 = await (new ApoliceServico()).BuscarApolice(this.Pesquisa, this.Status, vendedorUsuarios1, "Proposta", this.TipoBusca); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel3 = this; + List documentos5 = documentos4; + dialogPesquisaAvancadaViewModel3.Pesquisas = new ObservableCollection(documentos5.Select((Documento x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat(new string[] { "NÚMERO DA PROPOSTA: ", x.get_Proposta(), " - NÚMERO DA APÓLICE: ", x.get_Apolice(), " - NÚMERO DO ENDOSSO: ", x.get_Endosso() })); + return pesquisaAvancada; + }).ToList()); + break; + } + case 11: + { + List documentos6 = await (new ApoliceServico()).BuscarApolice(this.Pesquisa, this.Status, vendedorUsuarios1, "NumeroEndosso", this.TipoBusca); + DialogPesquisaAvancadaViewModel observableCollection4 = this; + List documentos7 = documentos6; + observableCollection4.Pesquisas = new ObservableCollection(documentos7.Select((Documento x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("NÚMERO DA APÓLICE: ", x.get_Apolice(), " - NÚMERO DO ENDOSSO: ", x.get_Endosso())); + return pesquisaAvancada; + }).ToList()); + break; + } + case 12: + { + List clientes = await (new ClienteServico()).BuscarObsCliente(this.Pesquisa); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel4 = this; + List clientes1 = clientes; + dialogPesquisaAvancadaViewModel4.Pesquisas = new ObservableCollection(clientes1.Select((Cliente x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_Nome(x.get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("OBSERVAÇÃO: ", x.get_Observacao())); + pesquisaAvancada.set_IdCliente(x.get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 13: + { + List clientes2 = await (new ClienteServico()).BuscarPastaCliente(this.Pesquisa, this.TipoBusca); + DialogPesquisaAvancadaViewModel observableCollection5 = this; + List clientes3 = clientes2; + observableCollection5.Pesquisas = new ObservableCollection(clientes3.Select((Cliente x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_Nome(x.get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("PASTA: ", x.get_Pasta())); + pesquisaAvancada.set_IdCliente(x.get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 14: + { + this.Pesquisas = new ObservableCollection(await (new AutoServico()).BuscarPlaca(this.Pesquisa, this.Status, vendedorUsuarios1, this.TipoBusca)); + break; + } + case 15: + { + List documentos8 = await (new ApoliceServico()).BuscarApolice(this.Pesquisa, this.Status, vendedorUsuarios1, "PedidoEndosso", this.TipoBusca); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel5 = this; + List documentos9 = documentos8; + dialogPesquisaAvancadaViewModel5.Pesquisas = new ObservableCollection(documentos9.Select((Documento x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat(new string[] { "PROPOSTA ENDOSSO: ", x.get_PropostaEndosso(), " - NÚMERO DA APÓLICE: ", x.get_Apolice(), " - NÚMERO DO ENDOSSO: ", x.get_Endosso() })); + return pesquisaAvancada; + }).ToList()); + break; + } + case 16: + { + ClienteServico clienteServico = new ClienteServico(); + string str1 = ValidationHelper.FormatarTelefone(this.Pesquisa); + string str2 = str1; + this.Pesquisa = str1; + List clienteTelefones = await clienteServico.BuscarTelefonesClientes(str2); + DialogPesquisaAvancadaViewModel observableCollection6 = this; + List clienteTelefones1 = clienteTelefones; + observableCollection6.Pesquisas = new ObservableCollection(clienteTelefones1.Select((ClienteTelefone x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_Nome(x.get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("TELEFONE: ", x.get_Prefixo(), "-", x.get_Numero())); + pesquisaAvancada.set_IdCliente(x.get_Cliente().get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 17: + { + List documentos10 = await (new ParcelaServico()).BuscarFatura(this.Pesquisa); + DialogPesquisaAvancadaViewModel dialogPesquisaAvancadaViewModel6 = this; + List documentos11 = documentos10; + dialogPesquisaAvancadaViewModel6.Pesquisas = new ObservableCollection(documentos11.Select((Documento x) => { + PesquisaAvancada pesquisaAvancada = new PesquisaAvancada(); + pesquisaAvancada.set_IdDocumento(x.get_Id()); + pesquisaAvancada.set_Nome(x.get_Controle().get_Cliente().get_Nome()); + pesquisaAvancada.set_Pesquisa(string.Concat("CÓDIGO DA FATURA: ", x.get_Endosso())); + pesquisaAvancada.set_IdCliente(x.get_Controle().get_Cliente().get_Id()); + return pesquisaAvancada; + }).ToList()); + break; + } + case 18: + { + this.Pesquisas = new ObservableCollection(await (new ItemServico()).BuscaItensPorObs(this.Pesquisa, this.Status, vendedorUsuarios1, this.TipoBusca)); + break; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs new file mode 100644 index 0000000..f95e6d6 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs @@ -0,0 +1,352 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogProspeccaoViewModel : BaseSegurosViewModel + { + private readonly ClienteServico _servico; + + private Prospeccao _selectedProspeccao; + + private bool _isVisibleAnexos; + + private ObservableCollection _arquivosAnexados = new ObservableCollection(); + + private Gestor.Model.Domain.Common.ArquivoDigital _selectedAnexado = new Gestor.Model.Domain.Common.ArquivoDigital(); + + private ObservableCollection _arquivos = new ObservableCollection(); + + private Visibility _visibilityStatusPersonalizado; + + private ObservableCollection _usuarios; + + private ObservableCollection _vendedores; + + private DateTime _dataAgendamento; + + private DateTime _horaAgendamento; + + private List _produtos = Recursos.Produtos; + + private ObservableCollection _statusProspeccao; + + private List _ramos = Recursos.Ramos; + + public ObservableCollection Arquivos + { + get + { + return this._arquivos; + } + set + { + this._arquivos = value; + base.OnPropertyChanged("Arquivos"); + } + } + + public ObservableCollection ArquivosAnexados + { + get + { + return this._arquivosAnexados; + } + set + { + List list; + this._arquivosAnexados = value; + base.OnPropertyChanged("ArquivosAnexados"); + this.IsVisibleAnexos = (value != null ? value.Count > 0 : false); + Prospeccao selectedProspeccao = this.SelectedProspeccao; + if (value != null) + { + list = value.ToList(); + } + else + { + list = null; + } + selectedProspeccao.set_Anexos(list); + } + } + + public DateTime DataAgendamento + { + get + { + return this._dataAgendamento; + } + set + { + this._dataAgendamento = value; + if (this.SelectedProspeccao.get_Tarefa() != null) + { + this.SelectedProspeccao.get_Tarefa().set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", value, this.SelectedProspeccao.get_Tarefa().get_Agendamento()))); + } + base.OnPropertyChanged("DataAgendamento"); + } + } + + public DateTime HoraAgendamento + { + get + { + return this._horaAgendamento; + } + set + { + this._horaAgendamento = value; + if (this.SelectedProspeccao.get_Tarefa() != null) + { + this.SelectedProspeccao.get_Tarefa().set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", this.SelectedProspeccao.get_Tarefa().get_Agendamento(), value))); + } + base.OnPropertyChanged("HoraAgendamento"); + } + } + + public bool IsVisibleAnexos + { + get + { + return this._isVisibleAnexos; + } + set + { + this._isVisibleAnexos = value; + base.OnPropertyChanged("IsVisibleAnexos"); + } + } + + public List Produtos + { + get + { + return this._produtos; + } + set + { + this._produtos = value; + base.OnPropertyChanged("Produtos"); + } + } + + public List Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public Gestor.Model.Domain.Common.ArquivoDigital SelectedAnexado + { + get + { + return this._selectedAnexado; + } + set + { + this._selectedAnexado = value; + base.OnPropertyChanged("SelectedAnexado"); + } + } + + public Prospeccao SelectedProspeccao + { + get + { + return this._selectedProspeccao; + } + set + { + this._selectedProspeccao = value; + base.OnPropertyChanged("SelectedProspeccao"); + } + } + + public ObservableCollection StatusProspeccao + { + get + { + return this._statusProspeccao; + } + set + { + this._statusProspeccao = value; + base.OnPropertyChanged("StatusProspeccao"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public ObservableCollection Vendedores + { + get + { + return this._vendedores; + } + set + { + this._vendedores = value; + base.OnPropertyChanged("Vendedores"); + } + } + + public Visibility VisibilityStatusPersonalizado + { + get + { + return this._visibilityStatusPersonalizado; + } + set + { + this._visibilityStatusPersonalizado = value; + base.OnPropertyChanged("VisibilityStatusPersonalizado"); + } + } + + public DialogProspeccaoViewModel(Prospeccao prospeccao) + { + DateTime? vigenciaFinal; + DateTime? nullable; + DateTime? nullable1; + this._servico = new ClienteServico(); + this.Usuarios = new ObservableCollection(Recursos.Usuarios.Where((Usuario x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + this.Vendedores = new ObservableCollection(Recursos.Vendedores.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList()); + this.StatusProspeccao = new ObservableCollection(( + from x in Recursos.StatusProspeccao + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList()); + if (this.StatusProspeccao == null || this.StatusProspeccao.Count == 0) + { + this.VisibilityStatusPersonalizado = Visibility.Collapsed; + } + if (prospeccao.get_Vendedor() == null) + { + prospeccao.set_Vendedor(this.Vendedores.First((Vendedor x) => x.get_Corretora())); + } + if (prospeccao.get_Tarefa() == null) + { + Prospeccao prospeccao1 = prospeccao; + Tarefa tarefa = new Tarefa(); + tarefa.set_Titulo("PROSPECÇÃO"); + tarefa.set_Entidade(5); + tarefa.set_IdEntidade(prospeccao.get_Id()); + tarefa.set_Usuario(Recursos.Usuario); + vigenciaFinal = prospeccao.get_VigenciaFinal(); + tarefa.set_Agendamento((vigenciaFinal.HasValue ? vigenciaFinal.GetValueOrDefault() : Funcoes.GetNetworkTime())); + tarefa.set_Cliente(prospeccao.get_Nome()); + prospeccao1.set_Tarefa(tarefa); + } + this.SelectedProspeccao = prospeccao; + Tarefa tarefa1 = prospeccao.get_Tarefa(); + if (tarefa1 != null) + { + nullable = new DateTime?(tarefa1.get_Agendamento()); + } + else + { + vigenciaFinal = null; + nullable = vigenciaFinal; + } + vigenciaFinal = nullable; + this.DataAgendamento = vigenciaFinal.Value; + Tarefa tarefa2 = prospeccao.get_Tarefa(); + if (tarefa2 != null) + { + nullable1 = new DateTime?(tarefa2.get_Agendamento()); + } + else + { + vigenciaFinal = null; + nullable1 = vigenciaFinal; + } + vigenciaFinal = nullable1; + this.HoraAgendamento = vigenciaFinal.Value; + } + + public async void Anexar() + { + ObservableCollection arquivos = this.Arquivos; + List list = arquivos.Select((IndiceArquivoDigital x) => { + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = new Gestor.Model.Domain.Common.ArquivoDigital(); + arquivoDigital.set_Descricao(x.get_Descricao()); + arquivoDigital.set_Extensao(x.get_Extensao()); + return arquivoDigital; + }).ToList(); + List arquivoDigitals = await base.AddAttachments(this.ArquivosAnexados.ToList(), list); + if (arquivoDigitals != null) + { + arquivoDigitals.AddRange(this.ArquivosAnexados); + this.ArquivosAnexados = new ObservableCollection(arquivoDigitals); + } + } + + public async Task BuscarInfoCliente(Cliente cliente) + { + cliente = await this._servico.BuscarCliente(cliente.get_Id()); + Cliente cliente1 = cliente; + ObservableCollection observableCollection = await this._servico.BuscarTelefonesAsync(cliente.get_Id()); + cliente1.set_Telefones(observableCollection); + cliente1 = null; + cliente1 = cliente; + ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(cliente.get_Id()); + cliente1.set_Emails(observableCollection1); + cliente1 = null; + return cliente; + } + + public void Delete(Gestor.Model.Domain.Common.ArquivoDigital arquivo) + { + if (this.SelectedAnexado == null) + { + return; + } + Gestor.Model.Domain.Common.ArquivoDigital arquivoDigital = this.ArquivosAnexados.First((Gestor.Model.Domain.Common.ArquivoDigital x) => x.get_Descricao() == arquivo.get_Descricao()); + this.ArquivosAnexados.Remove(arquivoDigital); + this.ArquivosAnexados = new ObservableCollection(this.ArquivosAnexados); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs new file mode 100644 index 0000000..9041cd3 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs @@ -0,0 +1,296 @@ +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Windows; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogTarefaViewModel : BaseSegurosViewModel + { + private bool _showPublica; + + private bool _nota; + + private Visibility _cabecalho; + + private Visibility _agendamento; + + private Visibility _status; + + private List _telefones; + + private ObservableCollection _usuarios; + + private Gestor.Model.Domain.Ferramentas.Tarefa _tarefa; + + private DateTime _dataAgendamento = Funcoes.GetNetworkTime(); + + private DateTime _horaAgendamento = Funcoes.GetNetworkTime(); + + private ObservableCollection _responsaveis = new ObservableCollection(); + + private Usuario _selectedUsuario; + + private bool _isAnotacoes = true; + + public Visibility Agendamento + { + get + { + return this._agendamento; + } + set + { + this._agendamento = value; + this.MutateVerbose(ref this._agendamento, value, this.OnRaisePropertyChanged(), "Agendamento"); + } + } + + public Visibility Cabecalho + { + get + { + return this._cabecalho; + } + set + { + this._cabecalho = value; + this.MutateVerbose(ref this._cabecalho, value, this.OnRaisePropertyChanged(), "Cabecalho"); + } + } + + public DateTime DataAgendamento + { + get + { + return this._dataAgendamento; + } + set + { + this._dataAgendamento = value; + if (this.Tarefa != null) + { + this.Tarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", value, this.Tarefa.get_Agendamento()))); + } + this.MutateVerbose(ref this._dataAgendamento, value, this.OnRaisePropertyChanged(), "DataAgendamento"); + } + } + + public DateTime HoraAgendamento + { + get + { + return this._horaAgendamento; + } + set + { + this._horaAgendamento = value; + if (this.Tarefa != null) + { + this.Tarefa.set_Agendamento(DateTime.Parse(string.Format("{0:d} {1:T}", this.Tarefa.get_Agendamento(), value))); + } + this.MutateVerbose(ref this._horaAgendamento, value, this.OnRaisePropertyChanged(), "HoraAgendamento"); + } + } + + public bool IsAnotacoes + { + get + { + return this._isAnotacoes; + } + set + { + this._isAnotacoes = value; + base.OnPropertyChanged("IsAnotacoes"); + } + } + + public bool Nota + { + get + { + return this._nota; + } + set + { + this._nota = value; + if (!value) + { + return; + } + this.Cabecalho = Visibility.Collapsed; + this.Status = Visibility.Collapsed; + } + } + + public ObservableCollection Responsaveis + { + get + { + return this._responsaveis; + } + set + { + this._responsaveis = value; + base.OnPropertyChanged("Responsaveis"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public bool ShowPublica + { + get + { + return this._showPublica; + } + set + { + this._showPublica = value; + base.OnPropertyChanged("ShowPublica"); + } + } + + public Visibility Status + { + get + { + return this._status; + } + set + { + this._status = value; + this.MutateVerbose(ref this._status, value, this.OnRaisePropertyChanged(), "Status"); + } + } + + public Gestor.Model.Domain.Ferramentas.Tarefa Tarefa + { + get + { + return this._tarefa; + } + set + { + DateTime networkTime = Funcoes.GetNetworkTime(); + this.DataAgendamento = (value != null ? value.get_Agendamento() : networkTime); + this.HoraAgendamento = (value != null ? value.get_Agendamento() : networkTime); + this.MutateVerbose(ref this._tarefa, value, this.OnRaisePropertyChanged(), "Tarefa"); + } + } + + public List Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + this.MutateVerbose>(ref this._telefones, value, this.OnRaisePropertyChanged(), "Telefones"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + this.MutateVerbose>(ref this._usuarios, value, this.OnRaisePropertyChanged(), "Usuarios"); + } + } + + public DialogTarefaViewModel(Gestor.Model.Domain.Ferramentas.Tarefa tarefa, List telefones, bool nota = false, bool agendamento = false) + { + this.ShowPublica = (!nota ? false : tarefa.get_HabilitarPublica()); + this.Telefones = telefones; + this.Usuarios = new ObservableCollection(Recursos.Usuarios.Where((Usuario x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + this.Nota = nota; + if (tarefa.get_Entidade() == 1) + { + tarefa.set_Anotacoes(tarefa.get_Descricao()); + tarefa.set_Descricao(string.Empty); + } + if (agendamento) + { + this.Agendamento = Visibility.Collapsed; + } + if (tarefa.get_UsuariosVinculados() != null) + { + ExtensionMethods.AddRange(this.Responsaveis, tarefa.get_UsuariosVinculados()); + } + this.Responsaveis.ToList().ForEach((Usuario x) => this.Usuarios.Remove(this.Usuarios.FirstOrDefault((Usuario u) => u.get_Id() == x.get_Id()))); + this.Tarefa = tarefa; + } + + public void AdcionarResponsavel() + { + if (this.SelectedUsuario == null || this.Responsaveis.Any((Usuario x) => (object)x == (object)this.SelectedUsuario)) + { + return; + } + this.Responsaveis.Add(this.SelectedUsuario); + this.Tarefa.set_UsuariosVinculados(this.Responsaveis.ToList()); + this.Usuarios.Remove(this.SelectedUsuario); + this.SelectedUsuario = null; + } + + private Action OnRaisePropertyChanged() + { + return (PropertyChangedEventArgs args) => { + PropertyChangedEventHandler propertyChangedEventHandler = this.RaisePropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, args); + }; + } + + public void RemoverResponsavel(Usuario selectedUsuario) + { + if (selectedUsuario == null) + { + return; + } + this.Responsaveis.Remove(selectedUsuario); + this.Tarefa.set_UsuariosVinculados(this.Responsaveis.ToList()); + this.Usuarios.Add(selectedUsuario); + selectedUsuario = null; + } + + public event PropertyChangedEventHandler RaisePropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs new file mode 100644 index 0000000..1735419 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs @@ -0,0 +1,102 @@ +using Gestor.Application.Helpers; +using Gestor.Model.Domain.Ferramentas; +using System; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogTrilhaViewModel : INotifyPropertyChanged + { + private Gestor.Model.Domain.Ferramentas.Trilha _trilha; + + private ObservableCollection _fases; + + private Fase _selectedFase; + + public ObservableCollection Fases + { + get + { + return this._fases; + } + set + { + this.MutateVerbose>(ref this._fases, value, this.RaisePropertyChanged(), "Fases"); + } + } + + public Fase SelectedFase + { + get + { + return this._selectedFase; + } + set + { + this.MutateVerbose(ref this._selectedFase, value, this.RaisePropertyChanged(), "SelectedFase"); + } + } + + public Gestor.Model.Domain.Ferramentas.Trilha Trilha + { + get + { + return this._trilha; + } + set + { + this.MutateVerbose(ref this._trilha, value, this.RaisePropertyChanged(), "Trilha"); + } + } + + public DialogTrilhaViewModel() + { + } + + public void AdicionarFase() + { + if (this.Fases == null) + { + this.Fases = new ObservableCollection(); + } + ObservableCollection fases = this.Fases; + Fase fase = new Fase(); + fase.set_Titulo("TÍTULO"); + fase.set_Descricao("DESCRIÇÃO"); + fases.Add(fase); + this.Fases = new ObservableCollection(this.Fases); + this.Trilha.set_Fases(this.Fases.ToList()); + } + + public void ExcluirFase(Fase fase) + { + this.Fases.RemoveAt(this.Fases.IndexOf(fase)); + this.Fases = new ObservableCollection(this.Fases); + this.Trilha.set_Fases(this.Fases.ToList()); + } + + private Action RaisePropertyChanged() + { + return (PropertyChangedEventArgs args) => { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, args); + }; + } + + public void UpdateFase(int index) + { + this.Fases[index] = this.SelectedFase; + this.Trilha.set_Fases(this.Fases.ToList()); + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogViewModel.cs new file mode 100644 index 0000000..523b64f --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogViewModel.cs @@ -0,0 +1,87 @@ +using Gestor.Application.Helpers; +using System; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; +using System.Windows; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogViewModel : INotifyPropertyChanged + { + private string _message; + + private string _acceptContent; + + private string _cancelContent; + + private Visibility _cancelVisibility; + + public string AcceptContent + { + get + { + return this._acceptContent; + } + set + { + this.MutateVerbose(ref this._acceptContent, value, this.RaisePropertyChanged(), "AcceptContent"); + } + } + + public string CancelContent + { + get + { + return this._cancelContent; + } + set + { + this.CancelVisibility = (string.IsNullOrEmpty(value) ? Visibility.Collapsed : Visibility.Visible); + this.MutateVerbose(ref this._cancelContent, value, this.RaisePropertyChanged(), "CancelContent"); + } + } + + public Visibility CancelVisibility + { + get + { + return this._cancelVisibility; + } + set + { + this.MutateVerbose(ref this._cancelVisibility, value, this.RaisePropertyChanged(), "CancelVisibility"); + } + } + + public string Message + { + get + { + return this._message; + } + set + { + this.MutateVerbose(ref this._message, value, this.RaisePropertyChanged(), "Message"); + } + } + + public DialogViewModel() + { + } + + private Action RaisePropertyChanged() + { + return (PropertyChangedEventArgs args) => { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, args); + }; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs new file mode 100644 index 0000000..1d526ea --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs @@ -0,0 +1,257 @@ +using Gestor.Application.Helpers; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels.Generic +{ + public class DialogVinculoViewModel : BaseViewModel + { + private Gestor.Model.Domain.Seguros.Repasse _repasse; + + private List _tiposVendedor; + + private ObservableCollection _vendedoresAtivos; + + private Vendedor _selectedVendedor; + + private ObservableCollection _repassesVinculo; + + private Gestor.Model.Domain.Seguros.Repasse _selectedRepasse; + + private TipoVendedor _selectedTipo; + + private TipoVendedor _selectedTipoVinculo; + + public Gestor.Model.Domain.Seguros.Repasse Repasse + { + get + { + return this._repasse; + } + set + { + this._repasse = value; + base.OnPropertyChanged("Repasse"); + } + } + + public List Repasses + { + get; + set; + } + + public ObservableCollection RepassesVinculo + { + get + { + return this._repassesVinculo; + } + set + { + this._repassesVinculo = value; + base.OnPropertyChanged("RepassesVinculo"); + } + } + + public Gestor.Model.Domain.Seguros.Repasse SelectedRepasse + { + get + { + return this._selectedRepasse; + } + set + { + this._selectedRepasse = value; + this.Vinculo.set_RepasseVinculo(value); + base.OnPropertyChanged("SelectedRepasse"); + } + } + + public TipoVendedor SelectedTipo + { + get + { + return this._selectedTipo; + } + set + { + this._selectedTipo = value; + this.Vinculo.set_TipoVendedor(value); + base.OnPropertyChanged("SelectedTipo"); + } + } + + public TipoVendedor SelectedTipoVinculo + { + get + { + return this._selectedTipoVinculo; + } + set + { + this._selectedTipoVinculo = value; + this.Vinculo.set_TipoVendedorVinculo(value); + base.OnPropertyChanged("SelectedTipoVinculo"); + } + } + + public Vendedor SelectedVendedor + { + get + { + return this._selectedVendedor; + } + set + { + ObservableCollection observableCollection; + this._selectedVendedor = value; + if (value == null) + { + observableCollection = null; + } + else + { + observableCollection = new ObservableCollection( + from x in this.Repasses + where x.get_Vendedor().get_Id() == value.get_Id() + select x); + } + this.RepassesVinculo = observableCollection; + base.OnPropertyChanged("SelectedVendedor"); + } + } + + public List TiposVendedor + { + get + { + return this._tiposVendedor; + } + set + { + this._tiposVendedor = value; + base.OnPropertyChanged("TiposVendedor"); + } + } + + public List Vendedores + { + get; + set; + } + + public ObservableCollection VendedoresAtivos + { + get + { + return this._vendedoresAtivos; + } + set + { + this._vendedoresAtivos = value; + base.OnPropertyChanged("VendedoresAtivos"); + } + } + + public VinculoRepasse Vinculo + { + get; + set; + } + + public DialogVinculoViewModel(VinculoRepasse vinculo, List repasses, Gestor.Model.Domain.Seguros.Repasse repasse) + { + List tipoVendedor = Recursos.TipoVendedor; + if (tipoVendedor != null) + { + list = tipoVendedor.Where((TipoVendedor x) => { + if (!x.get_Ativo().HasValue) + { + return true; + } + return x.get_Ativo().Value; + }).ToList(); + } + else + { + list = null; + } + this._tiposVendedor = list; + this._vendedoresAtivos = new ObservableCollection(); + this._selectedVendedor = new Vendedor(); + this._repassesVinculo = new ObservableCollection(); + this._selectedRepasse = new Gestor.Model.Domain.Seguros.Repasse(); + this._selectedTipo = new TipoVendedor(); + this._selectedTipoVinculo = new TipoVendedor(); + base(); + List list; + Vendedor vendedor; + Gestor.Model.Domain.Seguros.Repasse repasse1; + TipoVendedor tipoVendedor1; + TipoVendedor tipoVendedor2; + DialogVinculoViewModel dialogVinculoViewModel = this; + this.Repasse = repasse; + this.Repasses = repasses; + VinculoRepasse vinculoRepasse = new VinculoRepasse(); + vinculoRepasse.set_IdRepasse(vinculo.get_IdRepasse()); + vinculoRepasse.set_Id(vinculo.get_Id()); + this.Vinculo = vinculoRepasse; + this.Vendedores = ( + from x in this.Repasses + group x by x.get_Vendedor().get_Id() into x + select x.First().get_Vendedor() into x + orderby x.get_Nome() + select x).ToList(); + long id = this.Repasses.First((Gestor.Model.Domain.Seguros.Repasse x) => x.get_Id() == dialogVinculoViewModel.Vinculo.get_IdRepasse()).get_Vendedor().get_Id(); + this.VendedoresAtivos = new ObservableCollection(this.Vendedores.Where((Vendedor x) => { + if (x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa() || !x.get_Ativo() || x.get_Corretora()) + { + return false; + } + return x.get_Id() != id; + })); + if (vinculo.get_RepasseVinculo() != null) + { + vendedor = this.VendedoresAtivos.FirstOrDefault((Vendedor x) => x.get_Id() == vinculo.get_RepasseVinculo().get_Vendedor().get_Id()); + } + else + { + vendedor = null; + } + this.SelectedVendedor = vendedor; + if (vinculo.get_RepasseVinculo() != null) + { + repasse1 = this.RepassesVinculo.FirstOrDefault((Gestor.Model.Domain.Seguros.Repasse x) => x.get_Id() == vinculo.get_RepasseVinculo().get_Id()); + } + else + { + repasse1 = null; + } + this.SelectedRepasse = repasse1; + if (vinculo.get_TipoVendedor() != null) + { + tipoVendedor1 = this.TiposVendedor.FirstOrDefault((TipoVendedor x) => x.get_Id() == vinculo.get_TipoVendedor().get_Id()); + } + else + { + tipoVendedor1 = null; + } + this.SelectedTipo = tipoVendedor1; + if (vinculo.get_TipoVendedorVinculo() != null) + { + tipoVendedor2 = this.TiposVendedor.FirstOrDefault((TipoVendedor x) => x.get_Id() == vinculo.get_TipoVendedorVinculo().get_Id()); + } + else + { + tipoVendedor2 = null; + } + this.SelectedTipoVinculo = tipoVendedor2; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs new file mode 100644 index 0000000..0a9224b --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs @@ -0,0 +1,49 @@ +using Gestor.Application.Helpers; +using System; +using System.Collections.Generic; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Threading; + +namespace Gestor.Application.ViewModels.Generic +{ + public class ErrorDialogViewModel : DialogViewModel, INotifyPropertyChanged + { + private List> _erros; + + public List> Erros + { + get + { + List> keyValuePairs = new List>(); + foreach (KeyValuePair _erro in this._erros) + { + keyValuePairs.Add(new KeyValuePair(_erro.Key.ToUpper(), _erro.Value.ToUpper())); + } + return keyValuePairs; + } + set + { + this.MutateVerbose>>(ref this._erros, value, this.RaisePropertyChanged(), "Erros"); + } + } + + public ErrorDialogViewModel() + { + } + + private Action RaisePropertyChanged() + { + return (PropertyChangedEventArgs args) => { + PropertyChangedEventHandler propertyChangedEventHandler = this.PropertyChanged; + if (propertyChangedEventHandler == null) + { + return; + } + propertyChangedEventHandler(this, args); + }; + } + + public event PropertyChangedEventHandler PropertyChanged; + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs new file mode 100644 index 0000000..7630bbd --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs @@ -0,0 +1,147 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class ExtratoComissaoViewModel : BaseViewModel + { + private ServicoExtrato _servico; + + private bool _apelido; + + private List _seguradoras; + + private DateTime _inicio; + + private DateTime _fim; + + private ObservableCollection _extratos; + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public ObservableCollection Extratos + { + get + { + return this._extratos; + } + set + { + this._extratos = value; + base.OnPropertyChanged("Extratos"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public List Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public ExtratoComissaoViewModel(List seguradoras) + { + DateTime date = Funcoes.GetNetworkTime().Date; + int year = date.Year; + date = Funcoes.GetNetworkTime().Date; + this._inicio = new DateTime(year, date.Month, 1); + this._fim = Funcoes.GetNetworkTime().Date; + base(); + this._servico = new ServicoExtrato(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + this.Seguradoras = seguradoras; + } + + public async Task CarregarExtratos(Seguradora seguradora, DateTime inicio, DateTime fim) + { + this.Extratos = new ObservableCollection(await this._servico.BuscarExtrato(seguradora.get_Id(), (long)0, 4, inicio, fim)); + } + + internal List Selecionar() + { + if (this.Extratos == null) + { + return null; + } + return ( + from x in this.Extratos + where x.get_Selecionado() + select x).Select((Extrato x) => { + NotaFiscal notaFiscal = new NotaFiscal(); + notaFiscal.set_IdExtrato(new long?(x.get_Id())); + notaFiscal.set_Seguradora(x.get_Seguradora()); + notaFiscal.set_Data(x.get_Data()); + notaFiscal.set_Iss(x.get_Iss().GetValueOrDefault()); + notaFiscal.set_Ir(x.get_Ir().GetValueOrDefault()); + notaFiscal.set_ValorBruto(x.get_Bruto().GetValueOrDefault()); + notaFiscal.set_ValorLiquido(x.get_Liquido().GetValueOrDefault()); + notaFiscal.set_Extrato(x.get_Numero()); + return notaFiscal; + }).ToList(); + } + + internal void SelecionarTudo() + { + if (this.Extratos == null) + { + return; + } + this.Extratos.ToList().ForEach((Extrato x) => x.set_Selecionado(!x.get_Selecionado())); + this.Extratos = new ObservableCollection(this.Extratos); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/ItemViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/ItemViewModel.cs new file mode 100644 index 0000000..b8c015a --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/ItemViewModel.cs @@ -0,0 +1,843 @@ +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Microsoft.CSharp.RuntimeBinder; +using Microsoft.Office.Interop.Excel; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Data; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; + +namespace Gestor.Application.ViewModels.Generic +{ + public class ItemViewModel : BaseSegurosViewModel + { + private bool _alterandoFiltros; + + public Gestor.Application.ViewModels.CoberturaViewModel CoberturaViewModel; + + public ItemServico _itemServico; + + private Visibility _alteracaoTitularesVisibility = Visibility.Collapsed; + + private bool _enableAlterarExcluirTitulares; + + private List _excluirTlitulares = new List(); + + private TitularesVida _titularAlteracao = new TitularesVida(); + + private bool _codigo; + + private bool _inicio; + + private bool _fim; + + private bool _fatura; + + private bool _nome; + + private bool _observacao; + + private bool _nascimento; + + private bool _cpf; + + private bool _matricula; + + private bool _premio; + + private bool _capital; + + private bool _tipo; + + private ObservableCollection _titulares = new ObservableCollection(); + + private bool? _allSelected = new bool?(false); + + private bool _allSelectedChanging; + + private List _oldTitulares = new List(); + + public bool? AllSelected + { + get + { + return this._allSelected; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelected; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + nullable1 = value; + bool flag = false; + this.EnableAlterarExcluirTitulares = !(nullable1.GetValueOrDefault() == flag & nullable1.HasValue); + nullable1 = value; + if (!nullable1.GetValueOrDefault() & nullable1.HasValue) + { + this.AlteracaoTitularesVisibility = Visibility.Collapsed; + } + this._allSelected = value; + this.AllSelectedChanged(); + this.Titulares = new ObservableCollection(this.Titulares); + base.OnPropertyChanged("AllSelected"); + } + } + + public Visibility AlteracaoTitularesVisibility + { + get + { + return this._alteracaoTitularesVisibility; + } + set + { + this._alteracaoTitularesVisibility = value; + base.OnPropertyChanged("AlteracaoTitularesVisibility"); + } + } + + public bool Capital + { + get + { + return this._capital; + } + set + { + this._capital = value; + base.OnPropertyChanged("Capital"); + } + } + + public bool Codigo + { + get + { + return this._codigo; + } + set + { + this._codigo = value; + base.OnPropertyChanged("Codigo"); + } + } + + public bool Cpf + { + get + { + return this._cpf; + } + set + { + this._cpf = value; + base.OnPropertyChanged("Cpf"); + } + } + + public AutoCompleteFilterPredicate DependenteItemFilter + { + get + { + AutoCompleteFilterPredicate u003cu003e9_980 = ItemViewModel.u003cu003ec.u003cu003e9__98_0; + if (u003cu003e9_980 == null) + { + u003cu003e9_980 = new AutoCompleteFilterPredicate(ItemViewModel.u003cu003ec.u003cu003e9, (string searchText, object obj) => { + if (!((TitularesVida)obj).get_Nome().ToUpper().Contains(searchText.ToUpper())) + { + return false; + } + return ((TitularesVida)obj).get_Tipo().GetValueOrDefault() != 2; + }); + ItemViewModel.u003cu003ec.u003cu003e9__98_0 = u003cu003e9_980; + } + return u003cu003e9_980; + } + } + + public bool EnableAlterarExcluirTitulares + { + get + { + return this._enableAlterarExcluirTitulares; + } + set + { + this._enableAlterarExcluirTitulares = value; + base.OnPropertyChanged("EnableAlterarExcluirTitulares"); + } + } + + public List ExcluirTitulares + { + get + { + return this._excluirTlitulares; + } + set + { + this._excluirTlitulares = value; + base.OnPropertyChanged("ExcluirTitulares"); + } + } + + public bool Fatura + { + get + { + return this._fatura; + } + set + { + this._fatura = value; + base.OnPropertyChanged("Fatura"); + } + } + + public bool Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public bool Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public Item ItemSubstituido + { + get; + set; + } + + public bool Mantido + { + get; + set; + } + + public bool Matricula + { + get + { + return this._matricula; + } + set + { + this._matricula = value; + base.OnPropertyChanged("Matricula"); + } + } + + public bool Nascimento + { + get + { + return this._nascimento; + } + set + { + this._nascimento = value; + base.OnPropertyChanged("Nascimento"); + } + } + + public bool Nome + { + get + { + return this._nome; + } + set + { + this._nome = value; + base.OnPropertyChanged("Nome"); + } + } + + public bool Observacao + { + get + { + return this._observacao; + } + set + { + this._observacao = value; + base.OnPropertyChanged("Observacao"); + } + } + + public List OldTitulares + { + get + { + return this._oldTitulares; + } + set + { + this._oldTitulares = value; + base.OnPropertyChanged("OldTitulares"); + } + } + + public bool Premio + { + get + { + return this._premio; + } + set + { + this._premio = value; + base.OnPropertyChanged("Premio"); + } + } + + public bool Tipo + { + get + { + return this._tipo; + } + set + { + this._tipo = value; + base.OnPropertyChanged("Tipo"); + } + } + + public TitularesVida TitularAlteracao + { + get + { + return this._titularAlteracao; + } + set + { + this._titularAlteracao = value; + base.OnPropertyChanged("TitularAlteracao"); + } + } + + public ObservableCollection Titulares + { + get + { + return this._titulares; + } + set + { + this._titulares = value; + foreach (TitularesVida titulare in this.Titulares) + { + titulare.add_PropertyChanged(new PropertyChangedEventHandler(this.TitularesOnPropertyChanged)); + } + base.OnPropertyChanged("Titulares"); + } + } + + public ItemViewModel() + { + this.CoberturaViewModel = new Gestor.Application.ViewModels.CoberturaViewModel(null, null); + this._itemServico = new ItemServico(); + } + + private void AllSelectedChanged() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._alterandoFiltros = true; + this._allSelectedChanging = true; + if (this.AllSelected.HasValue) + { + foreach (TitularesVida titulare in this.Titulares) + { + titulare.set_Selecionado(this.AllSelected.Value); + } + this._alterandoFiltros = false; + } + } + finally + { + this._allSelectedChanging = false; + } + } + + public void AlterarTitular() + { + if (this.AlteracaoTitularesVisibility == Visibility.Visible) + { + this.AlteracaoTitularesVisibility = Visibility.Collapsed; + return; + } + this.TitularAlteracao = new TitularesVida(); + this.Codigo = false; + this.Inicio = false; + this.Fim = false; + this.Fatura = false; + this.Nome = false; + this.Nascimento = false; + this.Cpf = false; + this.Matricula = false; + this.Premio = false; + this.Capital = false; + this.Tipo = false; + this.AlteracaoTitularesVisibility = Visibility.Visible; + } + + public void AplicarTitular() + { + foreach (TitularesVida list in ( + from x in this.Titulares + where x.get_Selecionado() + select x).ToList()) + { + if (this.Codigo) + { + list.set_Codigo(this.TitularAlteracao.get_Codigo()); + } + if (this.Inicio) + { + list.set_Inicio(this.TitularAlteracao.get_Inicio()); + } + if (this.Fim) + { + list.set_Fim(this.TitularAlteracao.get_Fim()); + } + if (this.Fatura) + { + list.set_Fatura(this.TitularAlteracao.get_Fatura()); + } + if (this.Nome) + { + list.set_Nome(this.TitularAlteracao.get_Nome()); + } + if (this.Observacao) + { + list.set_Observacao(this.TitularAlteracao.get_Observacao()); + } + if (this.Nascimento) + { + list.set_Nascimento(this.TitularAlteracao.get_Nascimento()); + } + if (this.Cpf) + { + list.set_Cpf(this.TitularAlteracao.get_Cpf()); + } + if (this.Matricula) + { + list.set_Matricula(this.TitularAlteracao.get_Matricula()); + } + if (this.Premio) + { + list.set_Premio(this.TitularAlteracao.get_Premio()); + } + if (this.Capital) + { + list.set_Capital(this.TitularAlteracao.get_Capital()); + } + if (!this.Tipo) + { + continue; + } + list.set_Tipo(this.TitularAlteracao.get_Tipo()); + } + this.Titulares = new ObservableCollection(this.Titulares); + this.AlteracaoTitularesVisibility = Visibility.Collapsed; + } + + internal async Task> BuscarTitulares(string value) + { + Func func1 = null; + List titularesVidas = await Task.Run>(() => { + ObservableCollection titulares = this.Titulares; + Func u003cu003e9_1 = func1; + if (u003cu003e9_1 == null) + { + Func valueOrDefault = (TitularesVida x) => { + if (x.get_Tipo().GetValueOrDefault() == 2 || x.get_Nome() == null) + { + return false; + } + return ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(value.ToUpper()); + }; + Func func = valueOrDefault; + func1 = valueOrDefault; + u003cu003e9_1 = func; + } + return titulares.Where(u003cu003e9_1).ToList(); + }); + return titularesVidas; + } + + public async Task CarregarTitulares(long id) + { + this.Titulares = new ObservableCollection(await this._itemServico.BuscaTitularesVida(id)); + ItemViewModel list = this; + List titularesVidas = this.Titulares.ToList(); + list.OldTitulares = titularesVidas.Select((TitularesVida x) => { + TitularesVida titularesVida = new TitularesVida(); + titularesVida.set_Id(x.get_Id()); + titularesVida.set_IdItem(x.get_IdItem()); + titularesVida.set_Codigo(x.get_Codigo()); + titularesVida.set_Inicio(x.get_Inicio()); + titularesVida.set_Fim(x.get_Fim()); + titularesVida.set_Fatura(x.get_Fatura()); + titularesVida.set_Nome(x.get_Nome()); + titularesVida.set_Observacao(x.get_Observacao()); + titularesVida.set_Nascimento(x.get_Nascimento()); + titularesVida.set_Cpf(x.get_Cpf()); + titularesVida.set_Matricula(x.get_Matricula()); + titularesVida.set_Premio(x.get_Premio()); + titularesVida.set_Capital(x.get_Capital()); + titularesVida.set_Tipo(x.get_Tipo()); + titularesVida.set_Dependente(x.get_Dependente()); + return titularesVida; + }).ToList(); + } + + public void ExcluirTitular() + { + List list = ( + from x in this.Titulares + where x.get_Selecionado() + select x).ToList(); + this.ExcluirTitulares.AddRange( + from x in list + where x.get_Id() > (long)0 + select x); + foreach (TitularesVida titularesVida in list) + { + this.Titulares.Remove(titularesVida); + } + this.AllSelected = new bool?(false); + } + + public async Task ImportarTitulares() + { + string fileName; + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Filter = "Excel|*.xls;*.xlsx"; + openFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString(); + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + fileName = openFileDialog.FileName; + } + else + { + return; + } + } + base.Loading(true); + int num1 = 0; + try + { + List titularesVidas2 = await Task.Run>(() => { + string shortDateString; + DateTime dateTime; + Microsoft.Office.Interop.Excel.Application variable = (Microsoft.Office.Interop.Excel.Application)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("00024500-0000-0000-C000-000000000046"))); + Workbook variable1 = variable.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); + List strs = new List() + { + "codigo", + "inicio", + "fim", + "fatura", + "nome", + "nascimento", + "cpf", + "matricula", + "premio", + "capital", + "tipo", + "observacao", + "titulardependente" + }; + List dataTables = new List(); + foreach (object worksheet in variable1.Worksheets) + { + DataTable dataTable = new DataTable(); + Microsoft.Office.Interop.Excel.Range usedRange = ((Worksheet)worksheet).UsedRange; + if (ItemViewModel.u003cu003eo__93.u003cu003ep__0 == null) + { + ItemViewModel.u003cu003eo__93.u003cu003ep__0 = CallSite>.Create(Binder.Convert(CSharpBinderFlags.None, typeof(object[,]), typeof(ItemViewModel))); + } + object[,] target = ItemViewModel.u003cu003eo__93.u003cu003ep__0.Target(ItemViewModel.u003cu003eo__93.u003cu003ep__0, usedRange.Value2); + int num = 0; + if (target == null) + { + continue; + } + for (int i = 0; i <= usedRange.Columns.Count - 1; i++) + { + if (target[1, i + 1] == null || !strs.Contains(Funcoes.RemoverAcentos(target[1, i + 1].ToString().ToLower().Trim()))) + { + num--; + } + else + { + DataColumn dataColumn = new DataColumn() + { + DataType = Type.GetType("System.String"), + ColumnName = Funcoes.RemoverAcentos(target[1, i + 1].ToString().ToLower().Trim()) + }; + dataTable.Columns.Add(dataColumn); + for (int j = 0; j <= usedRange.Rows.Count - 2; j++) + { + object obj = target[j + 2, i + 1]; + target[1, i + 1].ToString().ToLower(); + if (Funcoes.RemoverAcentos(target[1, i + 1].ToString().Trim().ToLower()) != "inicio" && Funcoes.RemoverAcentos(target[1, i + 1].ToString().Trim().ToLower()) != "fim" && Funcoes.RemoverAcentos(target[1, i + 1].ToString().Trim().ToLower()) != "nascimento") + { + string str = obj as string; + shortDateString = (str != null ? Funcoes.RemoverAcentos(str).ToUpper().Trim() : (!(obj is double) ? (!(obj is bool) ? "" : ((bool)obj ? "1" : "0")) : ((double)obj).ToString(CultureInfo.InvariantCulture))); + } + else if (obj is double) + { + dateTime = DateTime.FromOADate((double)obj); + shortDateString = dateTime.ToShortDateString(); + } + else if (!DateTime.TryParse((string)obj, out dateTime)) + { + shortDateString = ""; + } + else + { + dateTime = DateTime.Parse((string)obj); + shortDateString = dateTime.ToShortDateString(); + } + if (i + num != 0) + { + dataTable.Rows[j][i + num] = shortDateString; + } + else + { + dataTable.Rows.Add(dataTable.NewRow()); + dataTable.Rows[j][i + num] = shortDateString; + } + } + } + } + dataTables.Add(dataTable); + } + variable.Quit(); + List titularesVidas = new List(); + foreach (DataTable dataTable1 in dataTables) + { + List titularesVidas1 = titularesVidas; + EnumerableRowCollection dataRows = dataTable1.AsEnumerable(); + Func u003cu003e9_931 = ItemViewModel.u003cu003ec.u003cu003e9__93_1; + if (u003cu003e9_931 == null) + { + u003cu003e9_931 = (DataRow x) => { + if (x.Field("nome") == null) + { + return false; + } + return !string.IsNullOrEmpty(x.Field("nome").ToString()); + }; + ItemViewModel.u003cu003ec.u003cu003e9__93_1 = u003cu003e9_931; + } + titularesVidas1.AddRange(dataRows.Where(u003cu003e9_931).ToList().Select((DataRow x) => { + DateTime? nullable; + decimal? nullable1; + TipoTitular? nullable2; + DateTime? nullable3; + DateTime? nullable4; + DateTime? nullable5; + decimal? nullable6; + decimal? nullable7; + TipoTitular? nullable8; + TitularesVida titularesVida = new TitularesVida(); + titularesVida.set_Codigo((!dataTable1.Columns.Contains("codigo") || string.IsNullOrWhiteSpace(x.Field("codigo").ToString()) ? null : x.Field("codigo").ToString().ToUpper())); + if (!dataTable1.Columns.Contains("inicio") || string.IsNullOrWhiteSpace(x.Field("inicio").ToString())) + { + nullable = null; + nullable3 = nullable; + } + else + { + nullable3 = new DateTime?(DateTime.Parse(x.Field("inicio").ToString())); + } + titularesVida.set_Inicio(nullable3); + if (!dataTable1.Columns.Contains("fim") | string.IsNullOrWhiteSpace(x.Field("fim").ToString())) + { + nullable = null; + nullable4 = nullable; + } + else + { + nullable4 = new DateTime?(DateTime.Parse(x.Field("fim").ToString())); + } + titularesVida.set_Fim(nullable4); + titularesVida.set_Fatura((!dataTable1.Columns.Contains("fatura") || string.IsNullOrWhiteSpace(x.Field("fatura").ToString()) ? null : x.Field("fatura").ToString().ToUpper())); + titularesVida.set_Nome((!dataTable1.Columns.Contains("nome") || string.IsNullOrWhiteSpace(x.Field("nome").ToString()) ? null : x.Field("nome").ToString().ToUpper())); + titularesVida.set_Observacao((!dataTable1.Columns.Contains("observacao") || string.IsNullOrWhiteSpace(x.Field("observacao").ToString()) ? null : x.Field("observacao").ToString().ToUpper())); + if (!dataTable1.Columns.Contains("nascimento") || string.IsNullOrWhiteSpace(x.Field("nascimento").ToString())) + { + nullable = null; + nullable5 = nullable; + } + else + { + nullable5 = new DateTime?(DateTime.Parse(x.Field("nascimento").ToString())); + } + titularesVida.set_Nascimento(nullable5); + titularesVida.set_Cpf((!dataTable1.Columns.Contains("cpf") || string.IsNullOrWhiteSpace(x.Field("cpf").ToString()) ? null : x.Field("cpf").ToString())); + titularesVida.set_Matricula((!dataTable1.Columns.Contains("matricula") || string.IsNullOrWhiteSpace(x.Field("matricula").ToString()) ? null : x.Field("matricula").ToString().ToUpper())); + if (!dataTable1.Columns.Contains("premio") || string.IsNullOrWhiteSpace(x.Field("premio").ToString())) + { + nullable1 = null; + nullable6 = nullable1; + } + else + { + nullable6 = new decimal?(decimal.Parse(x.Field("premio").ToString(), NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.InvariantCulture)); + } + titularesVida.set_Premio(nullable6); + if (!dataTable1.Columns.Contains("capital") || string.IsNullOrWhiteSpace(x.Field("capital").ToString())) + { + nullable1 = null; + nullable7 = nullable1; + } + else + { + nullable7 = new decimal?(decimal.Parse(x.Field("capital").ToString(), NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands, CultureInfo.InvariantCulture)); + } + titularesVida.set_Capital(nullable7); + if (!dataTable1.Columns.Contains("tipo") || string.IsNullOrWhiteSpace(x.Field("tipo").ToString())) + { + nullable2 = null; + nullable8 = nullable2; + } + else if (x.Field("tipo").ToString() == "SOCIO") + { + nullable8 = new TipoTitular?(0); + } + else if (x.Field("tipo").ToString() == "FUNCIONARIO") + { + nullable8 = new TipoTitular?(1); + } + else + { + nullable2 = null; + nullable8 = nullable2; + } + titularesVida.set_Tipo(nullable8); + return titularesVida; + }).ToList()); + } + return titularesVidas; + }); + base.Loading(false); + if (titularesVidas2.Count != 0) + { + ExtensionMethods.AddRange(this.Titulares, titularesVidas2); + } + else + { + await base.ShowMessage("NENHUMA COLUNA FOI ENCONTRADA", "OK", "", false); + return; + } + } + catch + { + num1 = 1; + } + if (num1 == 1) + { + base.Loading(false); + await base.ShowMessage("FALHA AO IMPORTAR O EXCEL, VERIFIQUE SE O ARQUIVO POSSUI ALGUM ERRO.", "OK", "", false); + } + } + + public void IncluirTitular() + { + this.Titulares.Insert(0, new TitularesVida()); + this.Titulares = new ObservableCollection(this.Titulares); + } + + public async Task QuantidadeDeItens(long id) + { + return await (new ItemServico()).BuscarProximoItem(id); + } + + public void RecheckAllSelected() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.Titulares.All((TitularesVida e) => e.get_Selecionado())) + { + this.AllSelected = new bool?(true); + } + else if (!this.Titulares.All((TitularesVida e) => !e.get_Selecionado())) + { + this.AllSelected = null; + } + else + { + this.AllSelected = new bool?(false); + } + } + finally + { + this._allSelectedChanging = false; + } + } + + private void TitularesOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs new file mode 100644 index 0000000..d1d8836 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs @@ -0,0 +1,30 @@ +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; + +namespace Gestor.Application.ViewModels.Generic +{ + public class ProtocoloViewModel : BaseSegurosViewModel + { + private ObservableCollection _itens = new ObservableCollection(); + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public ProtocoloViewModel(List itens) + { + this.Itens = new ObservableCollection(itens); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs new file mode 100644 index 0000000..f44c811 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs @@ -0,0 +1,68 @@ +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class ReordenarItensViewModel : BaseSegurosViewModel + { + private readonly ItemServico _itemServico; + + private bool _carregando; + + private ObservableCollection _itens = new ObservableCollection(); + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.OnPropertyChanged("Carregando"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public ReordenarItensViewModel(List ids) + { + this._itemServico = new ItemServico(); + this.CarregarItens(ids); + } + + private async void CarregarItens(List ids) + { + this.Carregando = true; + this.Itens = await this._itemServico.BuscarItens(ids); + this.Carregando = false; + } + + public void ReordenarAutomaticamente() + { + foreach (Item iten in this.Itens) + { + iten.set_Ordem(new int?(this.Itens.IndexOf(iten) + 1)); + } + this.Itens = new ObservableCollection(this.Itens); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs new file mode 100644 index 0000000..852bedd --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs @@ -0,0 +1,89 @@ +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Generic +{ + public class SelecionarItensViewModel : BaseSegurosViewModel + { + private ItemServico _itemServico; + + private ObservableCollection _itens = new ObservableCollection(); + + private bool? _allSelected; + + private bool _allSelectedChanging; + + public bool? AllSelected + { + get + { + return this._allSelected; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelected; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelected = value; + this.AllSelectedChanged(); + base.OnPropertyChanged("AllSelected"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public SelecionarItensViewModel(long id) + { + this._itemServico = new ItemServico(); + this.CarregarItens(id); + } + + private void AllSelectedChanged() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.AllSelected.HasValue) + { + foreach (Item iten in this.Itens) + { + iten.set_Selecionado(this.AllSelected.Value); + } + } + } + finally + { + this._allSelectedChanging = false; + } + } + + private async void CarregarItens(long id) + { + this.Itens = await this._itemServico.BuscarItens(id, 0); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/ImportViewModel.cs b/Codemerx/Gestor.Application/ViewModels/ImportViewModel.cs new file mode 100644 index 0000000..48249e7 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/ImportViewModel.cs @@ -0,0 +1,105 @@ +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Generic; +using Microsoft.Win32; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels +{ + public class ImportViewModel : BaseViewModel + { + private ObservableCollection _arquivos = new ObservableCollection(); + + public ObservableCollection Arquivos + { + get + { + return this._arquivos; + } + set + { + this._arquivos = value; + base.OnPropertyChanged("Arquivos"); + } + } + + public ImportViewModel() + { + } + + public void CarregarArquivos() + { + OpenFileDialog openFileDialog = new OpenFileDialog() + { + Title = "Selecione o PDF", + Filter = "Arquivos PDF|*.pdf", + Multiselect = true + }; + if (!openFileDialog.ShowDialog().GetValueOrDefault()) + { + return; + } + this.Arquivos = new ObservableCollection(); + openFileDialog.FileNames.ToList().ForEach((string x) => this.Arquivos.Add(new Arquivo() + { + Nome = x, + Processo = 0 + })); + } + + public async Task Import(Arquivo arquivo) + { + await Task.Run(() => { + try + { + Process process = new Process() + { + StartInfo = new ProcessStartInfo() + { + FileName = "C:\\AggerSeguros\\Agger.Import201911261630\\Agger.ImportPDF.exe", + Arguments = string.Format(" {0} {1} NOVOGESTOR {2}", Recursos.Empresa.get_Id(), Recursos.Usuario.get_Id(), arquivo.Nome), + UseShellExecute = false, + RedirectStandardOutput = true, + CreateNoWindow = true + } + }; + process.Start(); + process.WaitForExit(); + string end = process.StandardError.ReadToEnd(); + string str = process.StandardOutput.ReadToEnd(); + if (process.ExitCode != 0) + { + string[] strArrays = new string[] { "netsh exit code: ", null, null, null, null, null }; + strArrays[1] = process.ExitCode.ToString(); + strArrays[2] = " "; + strArrays[3] = (!string.IsNullOrEmpty(end) ? string.Concat(" ", end) : ""); + strArrays[4] = " "; + strArrays[5] = (!string.IsNullOrEmpty(str) ? string.Concat(" ", str) : ""); + throw new Exception(string.Concat(strArrays)); + } + } + catch (Exception exception) + { + } + }); + } + + public void Importar() + { + (new TaskFactory()).StartNew>(() => this.Importar(this.Arquivos.ToList())); + } + + public async Task Importar(List arquivos) + { + arquivos.ForEach(async (Arquivo x) => await this.Import(x)); + return true; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/LoginImageModel.cs b/Codemerx/Gestor.Application/ViewModels/LoginImageModel.cs new file mode 100644 index 0000000..36f880e --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/LoginImageModel.cs @@ -0,0 +1,24 @@ +using System; +using System.Runtime.CompilerServices; + +namespace Gestor.Application.ViewModels +{ + public class LoginImageModel + { + public string Imagem + { + get; + set; + } + + public string UrlFixa + { + get; + set; + } + + public LoginImageModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/LoginViewModel.cs b/Codemerx/Gestor.Application/ViewModels/LoginViewModel.cs new file mode 100644 index 0000000..8981f60 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/LoginViewModel.cs @@ -0,0 +1,1495 @@ +using Agger.Registro; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Command; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using Newtonsoft.Json.Linq; +using System; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Input; + +namespace Gestor.Application.ViewModels +{ + internal class LoginViewModel : BaseSegurosViewModel + { + private bool _enableRegistro; + + private bool _enableTrocaSenha; + + private bool _aggerUser; + + private string _imagemLink = "https://calendly.com/treinamentocs"; + + private string _imagem = "https://docs.agger.com.br/treinamentoprimeirasemana.png"; + + private string _head; + + private string _login; + + private string _novaNovaSenha; + + private string _senha; + + private string _confirmacaoSenha; + + private Gestor.Model.Domain.Seguros.Usuario _usuario; + + private string userJson = string.Concat(AppDomain.CurrentDomain.BaseDirectory, "user.json"); + + private LoginImageModel _selectedImage; + + private int _selectedIndex; + + private string _version; + + private string _labelVersion = ""; + + private bool _loadingVisibility; + + private bool _fieldsVisibility; + + private string _errorLogin = "DADOS DE ACESSO INVÁLIDOS"; + + private Visibility _errorLoginVisibility = Visibility.Hidden; + + private Visibility _acessoVisibility = Visibility.Collapsed; + + private Visibility _trocaSenhaVisibility = Visibility.Collapsed; + + private Visibility _loginVisibility; + + private Visibility _registrarVisibility = Visibility.Collapsed; + + private Visibility _visibilityCancelarRegitro = Visibility.Collapsed; + + private string _chave; + + private string _mensagem; + + private string _centralAtendimento = Address.get_CentralAtendimento().ToString(); + + public Visibility AcessoVisibility + { + get + { + return this._acessoVisibility; + } + set + { + this._acessoVisibility = value; + base.OnPropertyChanged("AcessoVisibility"); + } + } + + public bool AggerUser + { + get + { + return this._aggerUser; + } + set + { + this._aggerUser = value; + base.OnPropertyChanged("AggerUser"); + } + } + + public string CentralAtendimento + { + get + { + return this._centralAtendimento; + } + set + { + this._centralAtendimento = value; + base.OnPropertyChanged("CentralAtendimento"); + } + } + + public string Chave + { + get + { + return this._chave; + } + set + { + this._chave = value; + this.EnableRegistro = Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.Chave); + base.OnPropertyChanged("Chave"); + } + } + + public string ConfirmacaoSenha + { + get + { + return this._confirmacaoSenha; + } + set + { + this._confirmacaoSenha = value; + this.EnableTrocaSenha = (!Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.NovaSenha) || !Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.ConfirmacaoSenha) ? false : this.NovaSenha.Equals(this.ConfirmacaoSenha)); + base.OnPropertyChanged("ConfirmacaoSenha"); + } + } + + public bool EnableRegistro + { + get + { + return this._enableRegistro; + } + set + { + this._enableRegistro = value; + base.OnPropertyChanged("EnableRegistro"); + } + } + + public bool EnableTrocaSenha + { + get + { + return this._enableTrocaSenha; + } + set + { + this._enableTrocaSenha = value; + base.OnPropertyChanged("EnableTrocaSenha"); + } + } + + public string ErrorLogin + { + get + { + return this._errorLogin; + } + set + { + this._errorLogin = value; + base.OnPropertyChanged("ErrorLogin"); + } + } + + public Visibility ErrorLoginVisibility + { + get + { + return this._errorLoginVisibility; + } + set + { + this._errorLoginVisibility = value; + base.OnPropertyChanged("ErrorLoginVisibility"); + } + } + + public bool FieldsVisibility + { + get + { + return this._fieldsVisibility; + } + set + { + this._fieldsVisibility = value; + base.OnPropertyChanged("FieldsVisibility"); + } + } + + public string Head + { + get + { + return this._head; + } + set + { + string upper; + if (value != null) + { + upper = value.ToUpper(); + } + else + { + upper = null; + } + this._head = upper; + base.OnPropertyChanged("Head"); + } + } + + public ICommand ImageClickCommand + { + get + { + return new RelayCommand(() => { + bool flag; + LoginImageModel selectedImage = this.SelectedImage; + flag = (selectedImage != null ? Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(selectedImage.UrlFixa) : false); + if (flag) + { + Process.Start(new ProcessStartInfo() + { + FileName = this.SelectedImage.UrlFixa, + UseShellExecute = true + }); + } + }); + } + } + + public string Imagem + { + get + { + return this._imagem; + } + set + { + this._imagem = value; + base.OnPropertyChanged("Imagem"); + } + } + + public string ImagemLink + { + get + { + return this._imagemLink; + } + set + { + this._imagemLink = value; + base.OnPropertyChanged("ImagemLink"); + } + } + + public string LabelVersion + { + get + { + return this._labelVersion; + } + set + { + this._labelVersion = value; + base.OnPropertyChanged("LabelVersion"); + } + } + + public bool LoadingVisibility + { + get + { + return this._loadingVisibility; + } + set + { + this._loadingVisibility = value; + base.OnPropertyChanged("LoadingVisibility"); + } + } + + public string Login + { + get + { + return this._login; + } + set + { + bool flag; + bool flag1; + this._login = value; + string login = this.Login; + if (login != null) + { + flag = login.ToUpper().StartsWith("AGGER@"); + } + else + { + flag = false; + } + if (flag) + { + flag1 = true; + } + else + { + string senha = this.Senha; + if (senha != null) + { + flag1 = senha.ToUpper().StartsWith("AGGER@"); + } + else + { + flag1 = false; + } + } + this.AggerUser = flag1; + base.OnPropertyChanged("Login"); + } + } + + public ObservableCollection LoginImages { get; set; } = new ObservableCollection(); + + public Visibility LoginVisibility + { + get + { + return this._loginVisibility; + } + set + { + this._loginVisibility = value; + base.OnPropertyChanged("LoginVisibility"); + } + } + + public string Mensagem + { + get + { + return this._mensagem; + } + set + { + this._mensagem = value; + base.OnPropertyChanged("Mensagem"); + } + } + + public string NovaSenha + { + get + { + return this._novaNovaSenha; + } + set + { + this._novaNovaSenha = value; + this.EnableTrocaSenha = (!Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.NovaSenha) || !Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.ConfirmacaoSenha) ? false : this.NovaSenha.Equals(this.ConfirmacaoSenha)); + base.OnPropertyChanged("NovaSenha"); + } + } + + public Visibility RegistrarVisibility + { + get + { + return this._registrarVisibility; + } + set + { + this._registrarVisibility = value; + base.OnPropertyChanged("RegistrarVisibility"); + } + } + + public LoginImageModel SelectedImage + { + get + { + return this._selectedImage; + } + set + { + this._selectedImage = value; + base.OnPropertyChanged("SelectedImage"); + } + } + + public int SelectedIndex + { + get + { + return this._selectedIndex; + } + set + { + this._selectedIndex = value; + this.SelectedImage = this.LoginImages.ElementAtOrDefault(value); + base.OnPropertyChanged("SelectedIndex"); + } + } + + public string Senha + { + get + { + return this._senha; + } + set + { + bool flag; + bool flag1; + this._senha = value; + string login = this.Login; + if (login != null) + { + flag = login.ToUpper().StartsWith("AGGER@"); + } + else + { + flag = false; + } + if (flag) + { + flag1 = true; + } + else + { + string senha = this.Senha; + if (senha != null) + { + flag1 = senha.ToUpper().StartsWith("AGGER@"); + } + else + { + flag1 = false; + } + } + this.AggerUser = flag1; + base.OnPropertyChanged("Senha"); + } + } + + public Visibility TrocaSenhaVisibility + { + get + { + return this._trocaSenhaVisibility; + } + set + { + this._trocaSenhaVisibility = value; + base.OnPropertyChanged("TrocaSenhaVisibility"); + } + } + + public Gestor.Model.Domain.Seguros.Usuario Usuario + { + get + { + return this._usuario; + } + set + { + this._usuario = value; + base.OnPropertyChanged("Usuario"); + } + } + + public static string VersaoAtual + { + get; + set; + } + + public string Version + { + get + { + return this._version; + } + set + { + this._version = value; + base.OnPropertyChanged("Version"); + } + } + + public Visibility VisibilityCancelarRegitro + { + get + { + return this._visibilityCancelarRegitro; + } + set + { + this._visibilityCancelarRegitro = value; + base.OnPropertyChanged("VisibilityCancelarRegitro"); + } + } + + public LoginViewModel() + { + string login; + base.EnableButtons = true; + ApplicationHelper.Versao = Assembly.GetExecutingAssembly().GetName().Version; + this.Version = ApplicationHelper.Versao.ToString(); + this.LabelVersion = string.Concat("Gestor ", this.Version); + LoginViewModel.VersaoAtual = this.LabelVersion; + if (!File.Exists(this.userJson)) + { + return; + } + Gestor.Model.Domain.Seguros.Usuario usuario = JsonConvert.DeserializeObject(File.ReadAllText(this.userJson)); + if (usuario != null) + { + login = usuario.get_Login(); + } + else + { + login = null; + } + this.Login = login; + } + + public void AbrirRegistro() + { + this.LoginVisibility = Visibility.Collapsed; + this.AcessoVisibility = Visibility.Collapsed; + this.RegistrarVisibility = Visibility.Visible; + this.VisibilityCancelarRegitro = (ApplicationHelper.IdFornecedor == 0 ? Visibility.Collapsed : Visibility.Visible); + this.Chave = string.Empty; + } + + public async Task AbrirTrocaSenha() + { + bool flag; + UsuarioServico usuarioServico = new UsuarioServico(); + flag = (Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(this.Senha) ? true : Gestor.Common.Validation.ValidationHelper.IsNullOrEmpty(this.Login)); + bool flag1 = flag; + if (!flag1) + { + bool flag2 = Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.Login); + if (flag2) + { + Gestor.Model.Domain.Seguros.Usuario usuario = await usuarioServico.BuscarLogin(this.Login); + Gestor.Model.Domain.Seguros.Usuario usuario1 = usuario; + this.Usuario = usuario; + flag2 = usuario1 == null; + } + flag1 = flag2; + } + if (!flag1) + { + this.TrocaSenhaVisibility = Visibility.Visible; + this.LoginVisibility = Visibility.Collapsed; + } + else + { + await base.ShowMessage("NECESSÁRIO INSERIR UM USUÁRIO E SENHA VÁLIDOS PARA REALIZAR A TROCA DE SENHA.", "OK", "", false); + } + } + + public void AcessoNegado(string message) + { + this.Mensagem = message; + this.RegistrarVisibility = Visibility.Collapsed; + this.LoginVisibility = Visibility.Collapsed; + this.AcessoVisibility = Visibility.Visible; + } + + public void FecharRegistro() + { + this.RegistrarVisibility = Visibility.Collapsed; + this.LoginVisibility = Visibility.Visible; + this.Chave = string.Empty; + } + + public async Task GetCfgJson() + { + bool flag; + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + string str8; + string str9; + string str10; + string str11; + string str12; + string str13; + string str14; + string str15; + string str16; + object uri; + object apiGestorBeta; + object assinadorApiOficial; + object assinadorApiBeta; + object card; + object assistance; + object apiAD; + object apiArquivo; + object apiFipe; + object apiSso; + object apiMonitor; + object apiCep; + object loginJson; + object surveyJson; + object promo; + object betaPromo; + object centralAtendimento; + HttpResponseMessage async = null; + try + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(30)); + int num = 0; + try + { + async = await httpClient.GetAsync(Address.get_JsonGestor()); + async.EnsureSuccessStatusCode(); + } + catch + { + num = 1; + } + if (num == 1) + { + async = await httpClient.GetAsync(Address.get_JsonGestorAzure()); + } + if (!async.get_IsSuccessStatusCode()) + { + async = null; + } + else + { + JObject jObject = JObject.Parse(await async.get_Content().ReadAsStringAsync()); + JToken item = jObject.get_Item("ApiGestor"); + if (item != null) + { + str = Extensions.Value(item); + } + else + { + str = null; + } + string str17 = str; + JToken jToken = jObject.get_Item("ApiGestorBeta"); + if (jToken != null) + { + str1 = Extensions.Value(jToken); + } + else + { + str1 = null; + } + string str18 = str1; + JToken item1 = jObject.get_Item("ApiAssinador"); + if (item1 != null) + { + str2 = Extensions.Value(item1); + } + else + { + str2 = null; + } + string str19 = str2; + JToken jToken1 = jObject.get_Item("ApiAssinadorBeta"); + if (jToken1 != null) + { + str3 = Extensions.Value(jToken1); + } + else + { + str3 = null; + } + string str20 = str3; + JToken item2 = jObject.get_Item("ApiCard"); + if (item2 != null) + { + str4 = Extensions.Value(item2); + } + else + { + str4 = null; + } + string str21 = str4; + JToken jToken2 = jObject.get_Item("ApiAssistencia"); + if (jToken2 != null) + { + str5 = Extensions.Value(jToken2); + } + else + { + str5 = null; + } + string str22 = str5; + JToken item3 = jObject.get_Item("ApiAD"); + if (item3 != null) + { + str6 = Extensions.Value(item3); + } + else + { + str6 = null; + } + string str23 = str6; + JToken jToken3 = jObject.get_Item("ApiAttachment"); + if (jToken3 != null) + { + str7 = Extensions.Value(jToken3); + } + else + { + str7 = null; + } + string str24 = str7; + JToken item4 = jObject.get_Item("ApiFipe"); + if (item4 != null) + { + str8 = Extensions.Value(item4); + } + else + { + str8 = null; + } + string str25 = str8; + JToken jToken4 = jObject.get_Item("ApiSso"); + if (jToken4 != null) + { + str9 = Extensions.Value(jToken4); + } + else + { + str9 = null; + } + string str26 = str9; + JToken item5 = jObject.get_Item("ApiCep"); + if (item5 != null) + { + str10 = Extensions.Value(item5); + } + else + { + str10 = null; + } + string str27 = str10; + JToken jToken5 = jObject.get_Item("ApiMonitor"); + if (jToken5 != null) + { + str11 = Extensions.Value(jToken5); + } + else + { + str11 = null; + } + string str28 = str11; + JToken item6 = jObject.get_Item("LoginJson"); + if (item6 != null) + { + str12 = Extensions.Value(item6); + } + else + { + str12 = null; + } + string str29 = str12; + JToken jToken6 = jObject.get_Item("PromoJson"); + if (jToken6 != null) + { + str13 = Extensions.Value(jToken6); + } + else + { + str13 = null; + } + string str30 = str13; + JToken item7 = jObject.get_Item("BetaPromoJson"); + if (item7 != null) + { + str14 = Extensions.Value(item7); + } + else + { + str14 = null; + } + string str31 = str14; + JToken jToken7 = jObject.get_Item("SurveyJson"); + if (jToken7 != null) + { + str15 = Extensions.Value(jToken7); + } + else + { + str15 = null; + } + string str32 = str15; + JToken item8 = jObject.get_Item("CentralAtendimento"); + if (item8 != null) + { + str16 = Extensions.Value(item8); + } + else + { + str16 = null; + } + string str33 = str16; + JToken jToken8 = jObject.get_Item("UsarApis"); + if (jToken8 != null) + { + Extensions.Value(jToken8); + } + else + { + } + if (str17 != null) + { + uri = str17.ToUri(); + } + else + { + uri = null; + } + if (uri == null) + { + uri = Address.get_ApiGestorOficial(); + } + Address.set_ApiGestorOficial((Uri)uri); + if (str18 != null) + { + apiGestorBeta = str18.ToUri(); + } + else + { + apiGestorBeta = null; + } + if (apiGestorBeta == null) + { + apiGestorBeta = Address.get_ApiGestorBeta(); + } + Address.set_ApiGestorBeta((Uri)apiGestorBeta); + if (str19 != null) + { + assinadorApiOficial = str19.ToUri(); + } + else + { + assinadorApiOficial = null; + } + if (assinadorApiOficial == null) + { + assinadorApiOficial = Address.get_AssinadorApiOficial(); + } + Address.set_AssinadorApiOficial((Uri)assinadorApiOficial); + if (str20 != null) + { + assinadorApiBeta = str20.ToUri(); + } + else + { + assinadorApiBeta = null; + } + if (assinadorApiBeta == null) + { + assinadorApiBeta = Address.get_AssinadorApiBeta(); + } + Address.set_AssinadorApiBeta((Uri)assinadorApiBeta); + if (str21 != null) + { + card = str21.ToUri(); + } + else + { + card = null; + } + if (card == null) + { + card = Address.get_Card(); + } + Address.set_Card((Uri)card); + if (str22 != null) + { + assistance = str22.ToUri(); + } + else + { + assistance = null; + } + if (assistance == null) + { + assistance = Address.get_Assistance(); + } + Address.set_Assistance((Uri)assistance); + if (str23 != null) + { + apiAD = str23.ToUri(); + } + else + { + apiAD = null; + } + if (apiAD == null) + { + apiAD = Address.get_ApiAD(); + } + Address.set_ApiAD((Uri)apiAD); + if (str24 != null) + { + apiArquivo = str24.ToUri(); + } + else + { + apiArquivo = null; + } + if (apiArquivo == null) + { + apiArquivo = Address.get_ApiArquivo(); + } + Address.set_ApiArquivo((Uri)apiArquivo); + if (str25 != null) + { + apiFipe = str25.ToUri(); + } + else + { + apiFipe = null; + } + if (apiFipe == null) + { + apiFipe = Address.get_ApiFipe(); + } + Address.set_ApiFipe((Uri)apiFipe); + if (str26 != null) + { + apiSso = str26.ToUri(); + } + else + { + apiSso = null; + } + if (apiSso == null) + { + apiSso = Address.get_ApiSso(); + } + Address.set_ApiSso((Uri)apiSso); + if (str28 != null) + { + apiMonitor = str28.ToUri(); + } + else + { + apiMonitor = null; + } + if (apiMonitor == null) + { + apiMonitor = Address.get_ApiMonitor(); + } + Address.set_ApiMonitor((Uri)apiMonitor); + if (str27 != null) + { + apiCep = str27.ToUri(); + } + else + { + apiCep = null; + } + if (apiCep == null) + { + apiCep = Address.get_ApiCep(); + } + Address.set_ApiCep((Uri)apiCep); + if (str29 != null) + { + loginJson = str29.ToUri(); + } + else + { + loginJson = null; + } + if (loginJson == null) + { + loginJson = Address.get_LoginJson(); + } + Address.set_LoginJson((Uri)loginJson); + if (str32 != null) + { + surveyJson = str32.ToUri(); + } + else + { + surveyJson = null; + } + if (surveyJson == null) + { + surveyJson = Address.get_SurveyJson(); + } + Address.set_SurveyJson((Uri)surveyJson); + if (str30 != null) + { + promo = str30.ToUri(); + } + else + { + promo = null; + } + if (promo == null) + { + promo = Address.Promo; + } + Address.Promo = (Uri)promo; + if (str31 != null) + { + betaPromo = str31.ToUri(); + } + else + { + betaPromo = null; + } + if (betaPromo == null) + { + betaPromo = Address.BetaPromo; + } + Address.BetaPromo = (Uri)betaPromo; + if (str33 != null) + { + centralAtendimento = str33.ToUri(); + } + else + { + centralAtendimento = null; + } + if (centralAtendimento == null) + { + centralAtendimento = Address.get_CentralAtendimento(); + } + Address.set_CentralAtendimento((Uri)centralAtendimento); + flag = true; + return flag; + } + } + httpClient = null; + } + catch + { + } + flag = false; + return flag; + } + + public async Task GetImagesFromJson() + { + HttpResponseMessage async; + string str; + string str1; + try + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(30)); + try + { + async = await httpClient.GetAsync(Address.get_LoginJson()); + async.EnsureSuccessStatusCode(); + } + catch + { + return; + } + if (async.get_IsSuccessStatusCode()) + { + JObject jObject = JObject.Parse(await async.get_Content().ReadAsStringAsync()); + JToken item = jObject.get_Item("Imagem"); + if (item != null) + { + str = Extensions.Value(item); + } + else + { + str = null; + } + string str2 = str; + JToken jToken = jObject.get_Item("Url"); + if (jToken != null) + { + str1 = Extensions.Value(jToken); + } + else + { + str1 = null; + } + string str3 = str1; + if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(str2) && Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(str3)) + { + this.Imagem = str2; + this.ImagemLink = str3; + } + } + } + httpClient = null; + } + catch + { + } + } + + public async Task Load() + { + bool flag1 = await Task.Run(async () => { + bool flag; + try + { + flag = await (new BaseServico()).LoadInicialParameters(); + } + catch (Exception exception) + { + flag = false; + } + return flag; + }); + return flag1; + } + + public async Task TrocaSenha() + { + bool flag; + long? nullable; + bool valueOrDefault; + object obj = null; + if (string.IsNullOrEmpty(this.Senha)) + { + await base.ShowMessage("NECESSÁRIO PREENCHER A SENHA ANTERIOR PARA REALIZAR A TROCA DE SENHA.", "OK", "", false); + flag = false; + } + else if (!string.IsNullOrEmpty(this.NovaSenha)) + { + Token token = new Token(); + if (this.Senha == this.NovaSenha) + { + await base.ShowMessage("A NOVA SENHA NÃO PODE SER IGUAL A SENHA ANTERIOR.", "OK", "", false); + flag = false; + } + else if (this.NovaSenha == this.ConfirmacaoSenha) + { + if (this.Senha.ToUpper().Contains("AGGER@")) + { + string senha = this.Senha; + string[] strArrays = senha.Split(new char[] { '@' }); + if ((int)strArrays.Length >= 3) + { + LoginViewModel.AggerAccess aggerAccess = new LoginViewModel.AggerAccess(); + LoginViewModel.Client client = new LoginViewModel.Client() + { + Login = strArrays[1].ToUpper(), + Password = (new Token()).AggerEncrypt(strArrays[2]) + }; + aggerAccess.Usuario = client; + aggerAccess.Acao = string.Format("TrocaSenha - {0}|{1}", this.Usuario.get_Id(), this.Usuario.get_Login()); + aggerAccess.Log = string.Concat("ANG - ", ApplicationHelper.NumeroSerial); + aggerAccess.Serial = ApplicationHelper.NumeroSerial; + LoginViewModel.AggerAccess aggerAccess1 = aggerAccess; + LoginViewModel.AggerAccess aggerAccess2 = null; + int num = 0; + try + { + aggerAccess2 = await Gestor.Application.Helpers.Connection.Post("Access/AggerLogin", aggerAccess1); + } + catch (Exception exception) + { + obj = exception; + num = 1; + } + if (num != 1) + { + obj = null; + LoginViewModel.AggerAccess aggerAccess3 = aggerAccess2; + if (aggerAccess3 != null) + { + LoginViewModel.Client usuario = aggerAccess3.Usuario; + if (usuario != null) + { + nullable = new long?(usuario.Id); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num1 = (long)0; + valueOrDefault = nullable1.GetValueOrDefault() > num1 & nullable1.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + aggerAccess2 = null; + } + else + { + await base.ShowMessage("SENHA ANTERIOR INVÁLIDA.", "OK", "", false); + flag = false; + return flag; + } + } + else + { + Exception exception1 = (Exception)obj; + await base.ShowMessage("SENHA ANTERIOR INVÁLIDA.", "OK", "", false); + flag = false; + return flag; + } + } + else + { + await base.ShowMessage("SENHA ANTERIOR INVÁLIDA.", "OK", "", false); + flag = false; + return flag; + } + } + else if (Gestor.Common.Validation.ValidationHelper.IsNotNullOrEmpty(this.Usuario.get_Senha()) && this.Senha != token.AggerDecrypt(this.Usuario.get_Senha())) + { + await base.ShowMessage("SENHA ANTERIOR INVÁLIDA.", "OK", "", false); + flag = false; + return flag; + } + UsuarioServico usuarioServico = new UsuarioServico(); + this.Usuario.set_SenhaAnterior(token.AggerEncrypt(this.Senha)); + this.Usuario.set_Senha(token.AggerEncrypt(this.NovaSenha)); + await usuarioServico.Save(this.Usuario); + if (!usuarioServico.Sucesso) + { + this.Usuario.set_SenhaAnterior(string.Empty); + this.Usuario.set_Senha(string.Empty); + await base.ShowMessage("VERIFIQUE OS DADOS DIGITADOS E TENTE NOVAMENTE.", "OK", "", false); + flag = false; + } + else + { + this.Senha = this.NovaSenha; + flag = true; + } + } + else + { + await base.ShowMessage("A SENHA E A CONFIRMAÇÃO DA SENHA DEVEM SER IGUAIS.", "OK", "", false); + flag = false; + } + } + else + { + await base.ShowMessage("NECESSÁRIO PREENCHER A NOVA SENHA PARA REALIZAR A TROCA DE SENHA.", "OK", "", false); + flag = false; + } + return flag; + } + + public async Task Validate(string login, string password) + { + bool flag; + string str; + long? nullable; + Gestor.Model.Domain.Seguros.Usuario usuario; + this.ErrorLoginVisibility = Visibility.Hidden; + if (!login.Contains("AGGER@")) + { + usuario = await (new BaseServico()).BuscarUsuario(login, password); + if (usuario != null) + { + str = await base.VerificarAcesso(usuario.get_Id()); + } + else + { + str = "DADOS DE ACESSO INVÁLIDOS"; + } + string str1 = str; + if (str1 == null) + { + Recursos.Usuario = usuario; + Recursos.Empresa = (new BaseServico()).BuscarEmpresa(Recursos.Usuario.get_IdEmpresa()); + Recursos.Usuario.set_Senha(string.Empty); + File.WriteAllText(this.userJson, JsonConvert.SerializeObject(usuario)); + flag = true; + } + else + { + this.ErrorLogin = str1; + this.ErrorLoginVisibility = Visibility.Visible; + flag = false; + } + } + else + { + string[] strArrays = login.Split(new char[] { '@' }); + LoginViewModel.AggerAccess aggerAccess = new LoginViewModel.AggerAccess(); + LoginViewModel.Client client = new LoginViewModel.Client() + { + Login = strArrays[1], + Password = (new Token()).AggerEncrypt(password) + }; + aggerAccess.Usuario = client; + aggerAccess.Acao = "AggerAccessNovoGestor"; + aggerAccess.Log = string.Concat("ANG - ", ApplicationHelper.NumeroSerial); + aggerAccess.Serial = ApplicationHelper.NumeroSerial; + LoginViewModel.AggerAccess aggerAccess1 = await Gestor.Application.Helpers.Connection.Post("Access/AggerLogin", aggerAccess); + if (aggerAccess1 != null) + { + LoginViewModel.Client usuario1 = aggerAccess1.Usuario; + if (usuario1 != null) + { + nullable = new long?(usuario1.Id); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + if (nullable1.GetValueOrDefault() > num & nullable1.HasValue) + { + Gestor.Model.Domain.Seguros.Usuario usuario2 = new Gestor.Model.Domain.Seguros.Usuario(); + usuario2.set_Nome(string.Concat("ACESSO AGGER - USUÁRIO ", aggerAccess1.Usuario.Name)); + usuario2.set_Login(aggerAccess1.Usuario.Login); + usuario2.set_IdEmpresa((long)1); + usuario2.set_PermissaoAggilizador(new long?((long)1)); + Recursos.Usuario = usuario2; + Recursos.Empresa = (new BaseServico()).BuscarEmpresa(Recursos.Usuario.get_IdEmpresa()); + flag = true; + usuario = null; + return flag; + } + } + this.ErrorLoginVisibility = Visibility.Visible; + flag = false; + } + usuario = null; + return flag; + } + + private class AggerAccess + { + public string Acao + { + get; + set; + } + + public DateTime? Data + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string Ip + { + get; + set; + } + + public string Log + { + get; + set; + } + + public string Serial + { + get; + set; + } + + public LoginViewModel.Client Usuario + { + get; + set; + } + + public AggerAccess() + { + } + } + + private class Client + { + public bool AttendancePrivate + { + get; + set; + } + + public DateTime? DateLoginFinal + { + get; + set; + } + + public DateTime? DateLoginStart + { + get; + set; + } + + public bool Deleted + { + get; + set; + } + + public string Email + { + get; + set; + } + + public DateTime? ExpirationPassDate + { + get; + set; + } + + public long Id + { + get; + set; + } + + public string Login + { + get; + set; + } + + public string Name + { + get; + set; + } + + public string Password + { + get; + set; + } + + public Client() + { + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/MainViewModel.cs b/Codemerx/Gestor.Application/ViewModels/MainViewModel.cs new file mode 100644 index 0000000..26324af --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/MainViewModel.cs @@ -0,0 +1,1273 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Financeiro; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Card; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Media; +using System.Windows.Media.Imaging; +using System.Windows.Threading; + +namespace Gestor.Application.ViewModels +{ + public class MainViewModel : BaseSegurosViewModel + { + public Gestor.Application.Views.Financeiro.FinanceiroView FinanceiroView; + + public Gestor.Application.ViewModels.Seguros.ConsultaViewModel ConsultaViewModel; + + public Gestor.Application.ViewModels.Seguros.ClienteViewModel ClienteViewModel; + + private readonly ClienteServico _servico; + + public Gestor.Application.ViewModels.DashboardViewModel DashboardViewModel; + + private List _boletos; + + private BitmapImage _qrCode; + + private string _code; + + private Geometry _maximizeRestore = Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]); + + private object _content; + + private double _headMaxWidth; + + private string _head; + + private string _tela; + + private TipoTela? _telaAberta; + + private string _versao; + + private long _selectedRamo = (long)5; + + public bool PesquisaAvançada; + + private Cliente _selectedCliente; + + private bool _isEnableDocumento; + + private bool _isEnableItens; + + private Gestor.Model.Common.TipoDocumento _tipoDocumento; + + private string _documentoPrincipal = ""; + + private ObservableCollection _ajuda = new ObservableCollection(); + + private bool _matrizFilial = LicenseHelper.Produtos.Any(new Func((Licenca x) => { + if (x.get_Produto() != 2) + { + return false; + } + return x.get_Status() == 1; + })); + + private readonly bool _temEpic = LicenseHelper.Produtos.Any(new Func((Licenca produto) => { + if (produto.get_Produto() != 83) + { + return false; + } + return produto.get_Status() == 1; + })); + + private bool _carregandoAjuda; + + private string _empresa = ""; + + private ObservableCollection _contatos = new ObservableCollection(); + + private int _liquido; + + private int _mediaComissao; + + private int _resultado; + + private Visibility _visibleChaveInstalacao = Visibility.Collapsed; + + private Visibility _visibleSeguros = Visibility.Collapsed; + + private Visibility _visibleBi = Visibility.Collapsed; + + private FiltroStatusDocumento _selectedStatus; + + private TipoFiltroCliente _selectedFiltroCliente = 1; + + private bool _buscaNome = true; + + private bool _enableSeguros; + + private bool _enableBuscar; + + private Visibility _visibilityVoltar = Visibility.Collapsed; + + private int _notasBadge; + + private int _tarefasBadge; + + private int _badges; + + private int _ultimoUpdate; + + private Visibility _mensagemTarefasVisibility = Visibility.Collapsed; + + private string _mensagemTarefas = ""; + + private string _pesquisa = ""; + + private int _medalhaCor; + + private Visibility _medalhaVisibility = Visibility.Collapsed; + + private string _placeHolderAutoComplete = "PESQUISAR CLIENTE POR NOME OU NOME SOCIAL"; + + public ObservableCollection Ajuda + { + get + { + return this._ajuda; + } + set + { + this._ajuda = value; + base.OnPropertyChanged("Ajuda"); + } + } + + public int Badges + { + get + { + return this._badges; + } + set + { + this._badges = value; + base.OnPropertyChanged("Badges"); + } + } + + public List Boletos + { + get + { + return this._boletos; + } + set + { + this._boletos = value; + base.OnPropertyChanged("Boletos"); + } + } + + public bool BuscaNome + { + get + { + return this._buscaNome; + } + set + { + this._buscaNome = value; + base.OnPropertyChanged("BuscaNome"); + } + } + + public bool CarregandoAjuda + { + get + { + return this._carregandoAjuda; + } + set + { + this._carregandoAjuda = value; + base.OnPropertyChanged("CarregandoAjuda"); + } + } + + public static Cliente ClienteSelecionado + { + get; + set; + } + + public List ClientesEncontrados + { + get; + set; + } + + public List ClientesFiltrados + { + get; + set; + } + + public string Code + { + get + { + return this._code; + } + set + { + this._code = value; + base.OnPropertyChanged("Code"); + } + } + + public ObservableCollection Contatos + { + get + { + return this._contatos; + } + set + { + this._contatos = value; + base.OnPropertyChanged("Contatos"); + } + } + + public object Content + { + get + { + return this._content; + } + set + { + this._content = value; + base.OnPropertyChanged("Content"); + } + } + + public string DocumentoPrincipal + { + get + { + return this._documentoPrincipal; + } + set + { + this._documentoPrincipal = value; + base.OnPropertyChanged("DocumentoPrincipal"); + } + } + + public string Empresa + { + get + { + return this._empresa; + } + set + { + this._empresa = value; + base.OnPropertyChanged("Empresa"); + } + } + + public bool EnableBuscar + { + get + { + return this._enableBuscar; + } + set + { + this._enableBuscar = value; + base.OnPropertyChanged("EnableBuscar"); + } + } + + public bool EnableSeguros + { + get + { + return this._enableSeguros; + } + set + { + this._enableSeguros = value; + base.OnPropertyChanged("EnableSeguros"); + } + } + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public double HeadMaxWidth + { + get + { + return this._headMaxWidth; + } + set + { + this._headMaxWidth = value; + base.OnPropertyChanged("HeadMaxWidth"); + } + } + + public bool Invoke { get; set; } = true; + + public bool Isdropped + { + get; + set; + } + + public bool IsEnableDocumento + { + get + { + return this._isEnableDocumento; + } + set + { + this._isEnableDocumento = value; + base.OnPropertyChanged("IsEnableDocumento"); + } + } + + public bool IsEnableItens + { + get + { + return this._isEnableItens; + } + set + { + this._isEnableItens = value; + base.OnPropertyChanged("IsEnableItens"); + } + } + + public bool IsPopulating + { + get; + set; + } + + public bool MatrizFilial + { + get + { + return this._matrizFilial; + } + set + { + this._matrizFilial = value; + base.OnPropertyChanged("MatrizFilial"); + } + } + + public Geometry MaximizeRestore + { + get + { + return this._maximizeRestore; + } + set + { + this._maximizeRestore = value; + base.OnPropertyChanged("MaximizeRestore"); + } + } + + public int MedalhaCor + { + get + { + return this._medalhaCor; + } + set + { + this._medalhaCor = value; + base.OnPropertyChanged("MedalhaCor"); + } + } + + public Visibility MedalhaVisibility + { + get + { + return this._medalhaVisibility; + } + set + { + this._medalhaVisibility = value; + base.OnPropertyChanged("MedalhaVisibility"); + } + } + + public string MensagemTarefas + { + get + { + return this._mensagemTarefas; + } + set + { + this._mensagemTarefas = value; + base.OnPropertyChanged("MensagemTarefas"); + } + } + + public Visibility MensagemTarefasVisibility + { + get + { + return this._mensagemTarefasVisibility; + } + set + { + this._mensagemTarefasVisibility = value; + base.OnPropertyChanged("MensagemTarefasVisibility"); + } + } + + public int NotasBadge + { + get + { + return this._notasBadge; + } + set + { + this._notasBadge = value; + this.Badges = value + this.TarefasBadge; + base.OnPropertyChanged("NotasBadge"); + } + } + + public string Pesquisa + { + get + { + return this._pesquisa; + } + set + { + this._pesquisa = value; + base.OnPropertyChanged("Pesquisa"); + } + } + + public string PlaceHolderAutoComplete + { + get + { + return this._placeHolderAutoComplete; + } + set + { + this._placeHolderAutoComplete = value; + base.OnPropertyChanged("PlaceHolderAutoComplete"); + } + } + + public BitmapImage QrCode + { + get + { + return this._qrCode; + } + set + { + this._qrCode = value; + base.OnPropertyChanged("QrCode"); + } + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + long? nullable; + if (this.Invoke) + { + if (value != null) + { + long id = value.get_Id(); + Cliente selectedCliente = this.SelectedCliente; + if (selectedCliente != null) + { + nullable = new long?(selectedCliente.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + if (id == nullable1.GetValueOrDefault() & nullable1.HasValue) + { + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + return; + } + } + MainViewModel.ClienteSelecionado = value; + } + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public TipoFiltroCliente SelectedFiltroCliente + { + get + { + return this._selectedFiltroCliente; + } + set + { + this._selectedFiltroCliente = value; + this.BuscaNome = value == 1; + this.PlaceHolderAutoComplete = (this._selectedFiltroCliente == null ? "PESQUISAR CLIENTE POR NOME OU SOBRENOME" : "PESQUISAR CLIENTE POR NOME OU DOCUMENTO"); + base.OnPropertyChanged("SelectedFiltroCliente"); + } + } + + public long SelectedRamo + { + get + { + return this._selectedRamo; + } + set + { + this._selectedRamo = value; + base.OnPropertyChanged("SelectedRamo"); + } + } + + public FiltroStatusDocumento SelectedStatus + { + get + { + return this._selectedStatus; + } + set + { + this._selectedStatus = value; + this.WorkOnSelectedStatus(value); + base.OnPropertyChanged("SelectedStatus"); + } + } + + public static FiltroStatusDocumento StatusSelecionado + { + get; + set; + } + + public int TarefasBadge + { + get + { + return this._tarefasBadge; + } + set + { + this._tarefasBadge = value; + this.Badges = value + this.NotasBadge; + base.OnPropertyChanged("TarefasBadge"); + } + } + + public string Tela + { + get + { + return this._tela; + } + set + { + this._tela = value; + base.OnPropertyChanged("Tela"); + } + } + + public TipoTela? TelaAberta + { + get + { + return this._telaAberta; + } + set + { + this._telaAberta = value; + base.OnPropertyChanged("TelaAberta"); + } + } + + public Visibility TemEpic + { + get + { + if (!this._temEpic) + { + return Visibility.Collapsed; + } + return Visibility.Visible; + } + } + + public Gestor.Model.Common.TipoDocumento TipoDocumento + { + get + { + return this._tipoDocumento; + } + set + { + this._tipoDocumento = value; + base.OnPropertyChanged("TipoDocumento"); + } + } + + public List VendedorUsuario + { + get; + set; + } + + public string Versao + { + get + { + return this._versao; + } + set + { + this._versao = value; + base.OnPropertyChanged("Versao"); + } + } + + public static string ViewAberta + { + get; + set; + } + + public Visibility VisibilityVoltar + { + get + { + return this._visibilityVoltar; + } + set + { + this._visibilityVoltar = value; + base.OnPropertyChanged("VisibilityVoltar"); + } + } + + public Visibility VisibleBi + { + get + { + return this._visibleBi; + } + set + { + this._visibleBi = value; + base.OnPropertyChanged("VisibleBi"); + } + } + + public Visibility VisibleChaveInstalacao + { + get + { + return this._visibleChaveInstalacao; + } + set + { + this._visibleChaveInstalacao = value; + base.OnPropertyChanged("VisibleChaveInstalacao"); + } + } + + public Visibility VisibleSeguros + { + get + { + return this._visibleSeguros; + } + set + { + this._visibleSeguros = value; + base.OnPropertyChanged("VisibleSeguros"); + } + } + + public MainViewModel() + { + TipoFiltroCliente? nullable; + TipoFiltroCliente? filtroInicial; + Gestor.Application.Actions.Actions.AtualizaBadges = new Action(this.AtualizarBadges); + Gestor.Application.Actions.Actions.LimparCliente = new Action(this.LimparCliente); + this._servico = new ClienteServico(); + Gestor.Application.Actions.Actions.UpdateDocumento = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.UpdateDocumento, new Action(this.UpdateRamoIcon)); + Gestor.Application.Actions.Actions.SelectCliente = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.SelectCliente, new Action(this.SelectCliente)); + Gestor.Application.Actions.Actions.AtualizaContatos = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.AtualizaContatos, new Action(this.AtualizarContatos)); + Gestor.Application.Actions.Actions.EnableItens = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnableItens, new Action(this.EnableItens)); + Gestor.Application.Actions.Actions.EnableDocumento = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.EnableDocumento, new Action(this.EnableDocumento)); + this.Versao = string.Concat(Recursos.Empresa.get_Nome(), " | ", LoginViewModel.VersaoAtual); + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + filtroInicial = usuario.get_FiltroInicial(); + } + else + { + nullable = null; + filtroInicial = nullable; + } + nullable = filtroInicial; + this.SelectedFiltroCliente = nullable.GetValueOrDefault(); + (new DispatcherTimer(TimeSpan.FromHours(1), DispatcherPriority.Background, (object sender, EventArgs args) => this.AtualizarBadges(), System.Windows.Application.Current.Dispatcher)).Start(); + } + + private async void AtualizarBadges() + { + object obj; + object obj1; + try + { + int[] numArray = await (new TarefaServico()).AtualizarNotasTarefas(); + this.NotasBadge = numArray[0]; + this.TarefasBadge = numArray[1]; + if (numArray[1] > this._ultimoUpdate) + { + MainViewModel mainViewModel = this; + object obj2 = numArray[1]; + obj = (numArray[1] > 1 ? "S" : ""); + obj1 = (numArray[1] > 1 ? "S" : ""); + mainViewModel.MensagemTarefas = string.Format("{0} NOVA{1} TAREFA{2}", obj2, obj, obj1); + this.MensagemTarefasVisibility = Visibility.Visible; + } + this._ultimoUpdate = numArray[1]; + } + catch + { + } + } + + private async void AtualizarContatos() + { + ObservableCollection observableCollection; + List contatos = new List(); + if (this.SelectedCliente != null) + { + observableCollection = await this._servico.BuscarTelefonesAsync(this.SelectedCliente.get_Id()); + ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(this.SelectedCliente.get_Id()); + if (observableCollection != null) + { + List contatos1 = contatos; + ObservableCollection observableCollection2 = observableCollection; + contatos1.AddRange(observableCollection2.Select((ClienteTelefone x) => { + Contato contato = new Contato(); + contato.set_Tipo(0); + contato.set_TipoTelefone(new TipoTelefone?(x.get_Tipo().GetValueOrDefault(1))); + contato.set_Numero(string.Concat(x.get_Prefixo(), " ", x.get_Numero())); + return contato; + }).Take(2).ToList()); + } + if (observableCollection1 != null) + { + List contatos2 = contatos; + ObservableCollection observableCollection3 = observableCollection1; + contatos2.AddRange(observableCollection3.Select((ClienteEmail x) => { + Contato contato = new Contato(); + contato.set_Tipo(1); + contato.set_TipoTelefone(null); + contato.set_Numero(x.get_Email()); + return contato; + }).Take(1).ToList()); + } + this.Contatos = new ObservableCollection(contatos); + } + contatos = null; + observableCollection = null; + } + + private async void AtualizarMedalha(List apolices) + { + decimal zero; + Qualificacao qualificacao = await this._servico.BuscarQualificacaoAsync(); + if (qualificacao.get_Id() == 0) + { + Qualificacao qualificacao1 = new Qualificacao(); + qualificacao1.set_Liquido1(decimal.Zero); + qualificacao1.set_Liquido2(new decimal(1000)); + qualificacao1.set_Liquido3(new decimal(5000)); + qualificacao1.set_Comissao1(new decimal(10)); + qualificacao1.set_Comissao2(new decimal(15)); + qualificacao1.set_Comissao3(new decimal(20)); + qualificacao1.set_Resultado1(new decimal(100)); + qualificacao1.set_Resultado2(new decimal(200)); + qualificacao1.set_Resultado3(new decimal(300)); + qualificacao1.set_Id((long)1); + qualificacao = qualificacao1; + } + this._liquido = 0; + this._mediaComissao = 0; + this._resultado = 0; + List documentos = apolices; + decimal num = documentos.Sum((Documento p) => p.get_PremioLiquido()); + if (num >= qualificacao.get_Liquido3()) + { + this._liquido = 3; + } + else if (num >= qualificacao.get_Liquido2()) + { + this._liquido = 2; + } + else if (num >= qualificacao.get_Liquido1()) + { + this._liquido = 1; + } + List documentos1 = apolices; + if (documentos1.Any((Documento c) => c.get_Comissao() > decimal.Zero)) + { + List documentos2 = apolices; + decimal num1 = documentos2.Sum((Documento c) => c.get_Comissao()); + zero = decimal.Round(num1 / apolices.Count((Documento c) => c.get_Comissao() > decimal.Zero), 2); + } + else + { + zero = decimal.Zero; + } + decimal num2 = zero; + if (num2 >= qualificacao.get_Comissao3()) + { + this._mediaComissao = 3; + } + else if (num2 >= qualificacao.get_Comissao2()) + { + this._mediaComissao = 2; + } + else if (num2 >= qualificacao.get_Comissao1()) + { + this._mediaComissao = 1; + } + List documentos3 = apolices; + decimal num3 = documentos3.Sum((Documento p) => ((p.get_PremioLiquido() + (p.get_AdicionalComiss() ? p.get_PremioAdicional() : decimal.Zero)) * p.get_Comissao()) * new decimal(1, 0, 0, false, 2)); + if (num3 >= qualificacao.get_Resultado3()) + { + this._resultado = 3; + } + else if (num3 >= qualificacao.get_Resultado2()) + { + this._resultado = 2; + } + else if (num3 >= qualificacao.get_Resultado1()) + { + this._resultado = 1; + } + this.MedalhaCor = (int)Math.Round((double)(((float)this._liquido + (float)this._mediaComissao + (float)this._resultado) / 3f)); + this.MedalhaVisibility = Visibility.Visible; + } + + public async Task CarregarAjuda() + { + if (this.TelaAberta.HasValue) + { + if (!this.Ajuda.Any((AjudaTela x) => { + TipoTela tela = x.get_Tela(); + TipoTela? telaAberta = this.TelaAberta; + return tela == telaAberta.GetValueOrDefault() & telaAberta.HasValue; + })) + { + this.CarregandoAjuda = true; + TipoTela? nullable = this.TelaAberta; + this.Ajuda = new ObservableCollection(await Connection.Get>(string.Format("Help/{0}", (int)nullable.Value), true, false)); + this.CarregandoAjuda = false; + } + } + } + + private void EnableDocumento(bool enabled) + { + this.IsEnableDocumento = enabled; + } + + private void EnableItens(bool enabled) + { + this.IsEnableItens = enabled; + } + + public List FiltrarClientes(string value) + { + return base.FilterCliente(this.ClientesEncontrados, value); + } + + private void LimparCliente() + { + this.SelectedCliente = null; + this.Contatos = null; + this.DocumentoPrincipal = ""; + this.Pesquisa = ""; + } + + public async void LimparDocumentos() + { + Task task; + this.Contatos = null; + this.DocumentoPrincipal = ""; + string viewAberta = MainViewModel.ViewAberta; + if (viewAberta != "ConsultaOriginalView") + { + if (viewAberta == "ClienteView") + { + Gestor.Application.ViewModels.Seguros.ClienteViewModel clienteViewModel = this.ClienteViewModel; + if (clienteViewModel != null) + { + clienteViewModel.SelecionaCliente(null); + } + else + { + } + } + } + else if (this.ConsultaViewModel != null) + { + Gestor.Application.ViewModels.Seguros.ConsultaViewModel consultaViewModel = this.ConsultaViewModel; + if (consultaViewModel != null) + { + task = consultaViewModel.SelecionaCliente(null, true); + } + else + { + task = null; + } + await task; + } + } + + public async void Medalha() + { + await base.ShowMedalha(this._liquido, this._mediaComissao, this._resultado, this.MedalhaCor); + } + + public async Task SelecionarCliente(Cliente value) + { + this.IsEnableDocumento = false; + this.IsEnableItens = false; + this.LimparDocumentos(); + if (value != null) + { + if (this.Invoke) + { + MainViewModel.ClienteSelecionado = value; + } + await this.WorkOnSelectedCliente(value); + this.IsEnableDocumento = true; + } + } + + private void SelectCliente(Cliente cliente) + { + string str; + string str1; + this.SelectedCliente = cliente; + string pesquisa = this.Pesquisa; + if (cliente != null) + { + string nomeSocial = cliente.get_NomeSocial(); + if (nomeSocial != null) + { + str = nomeSocial.Trim(); + } + else + { + str = null; + } + } + else + { + str = null; + } + if (pesquisa != str) + { + if (cliente != null) + { + string nomeSocial1 = cliente.get_NomeSocial(); + if (nomeSocial1 != null) + { + str1 = nomeSocial1.Trim(); + } + else + { + str1 = null; + } + } + else + { + str1 = null; + } + this.Pesquisa = str1; + } + } + + private void UpdateRamoIcon(Documento documento) + { + if (documento == null || documento.get_Id() == 0) + { + return; + } + this.SelectedRamo = documento.get_Controle().get_Ramo().get_Id(); + } + + public async void VerificarLogo() + { + if (string.IsNullOrEmpty(Recursos.Empresa.get_LogoId()) && Recursos.Empresa.get_Logo() != null) + { + Logo logo = new Logo(); + logo.set_CustomId(ApplicationHelper.NumeroSerial); + logo.set_Data(Recursos.Empresa.get_Logo()); + Gestor.Model.Domain.Common.Empresa empresa = Recursos.Empresa; + empresa.set_LogoId(await Funcoes.Criarlogo(logo)); + empresa = null; + (new EmpresaServico()).AtualizarLogoId(Recursos.Empresa.get_Id(), Recursos.Empresa.get_LogoId()); + } + } + + private async Task WorkOnSelectedCliente(Cliente value) + { + object nome; + string nomeSocial; + Task task; + long? nullable; + base.IsEnabled = false; + List contatos = new List(); + ObservableCollection observableCollection = await this._servico.BuscarTelefonesAsync(value.get_Id()); + ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(value.get_Id()); + if (observableCollection != null) + { + List contatos1 = contatos; + ObservableCollection observableCollection2 = observableCollection; + contatos1.AddRange(observableCollection2.Select((ClienteTelefone x) => { + Contato contato = new Contato(); + contato.set_Tipo(0); + contato.set_TipoTelefone(new TipoTelefone?(x.get_Tipo().GetValueOrDefault(1))); + contato.set_Numero(string.Concat(x.get_Prefixo(), " ", x.get_Numero())); + return contato; + }).Take(2).ToList()); + } + if (observableCollection1 != null) + { + List contatos2 = contatos; + ObservableCollection observableCollection3 = observableCollection1; + contatos2.AddRange(observableCollection3.Select((ClienteEmail x) => { + Contato contato = new Contato(); + contato.set_Tipo(1); + contato.set_TipoTelefone(null); + contato.set_Numero(x.get_Email()); + return contato; + }).Take(1).ToList()); + } + this.Contatos = new ObservableCollection(contatos); + this.TipoDocumento = value.get_DocumentoPrincipal().GetValueOrDefault(); + MainViewModel mainViewModel = this; + Gestor.Model.Domain.Common.Empresa empresa = Recursos.Empresas.FirstOrDefault((Gestor.Model.Domain.Common.Empresa x) => x.get_Id() == value.get_IdEmpresa()); + if (empresa != null) + { + nome = empresa.get_Nome(); + } + else + { + nome = null; + } + if (nome == null) + { + nome = Recursos.Empresa.get_Nome(); + } + mainViewModel.Empresa = (string)nome; + switch (this.TipoDocumento) + { + case 0: + { + MainViewModel mainViewModel1 = this; + string documento = value.get_Documento(); + if (documento == null) + { + documento = ""; + } + mainViewModel1.DocumentoPrincipal = documento; + break; + } + case 1: + { + MainViewModel mainViewModel2 = this; + string rne = value.get_Rne(); + if (rne == null) + { + rne = ""; + } + mainViewModel2.DocumentoPrincipal = rne; + break; + } + case 2: + { + MainViewModel mainViewModel3 = this; + string cei = value.get_Cei(); + if (cei == null) + { + cei = ""; + } + mainViewModel3.DocumentoPrincipal = cei; + break; + } + case 3: + { + MainViewModel mainViewModel4 = this; + string caepf = value.get_Caepf(); + if (caepf == null) + { + caepf = ""; + } + mainViewModel4.DocumentoPrincipal = caepf; + break; + } + } + if (MainViewModel.ClienteSelecionado != null) + { + MainViewModel.ClienteSelecionado.set_Telefones(observableCollection); + MainViewModel.ClienteSelecionado.set_Emails(observableCollection1); + } + string viewAberta = MainViewModel.ViewAberta; + if (viewAberta != "ConsultaOriginalView") + { + if (viewAberta == "ClienteView") + { + Gestor.Application.ViewModels.Seguros.ClienteViewModel clienteViewModel = this.ClienteViewModel; + if (clienteViewModel != null) + { + clienteViewModel.SelecionaCliente(this.SelectedCliente); + } + else + { + } + MainViewModel mainViewModel5 = this; + string str = string.Concat("ACESSOU CLIENTE \"", this.SelectedCliente.get_Nome(), "\""); + long id = this.SelectedCliente.get_Id(); + TipoTela? nullable1 = new TipoTela?(1); + Cliente selectedCliente = this.SelectedCliente; + if (selectedCliente != null) + { + nullable = new long?(selectedCliente.get_Id()); + } + else + { + nullable = null; + } + mainViewModel5.RegistrarAcao(str, id, nullable1, string.Format("ID CLIENTE: {0}", nullable)); + } + } + else if (this.ConsultaViewModel != null) + { + Gestor.Application.ViewModels.Seguros.ConsultaViewModel consultaViewModel = this.ConsultaViewModel; + if (consultaViewModel != null) + { + task = consultaViewModel.SelecionaCliente(value, true); + } + else + { + task = null; + } + await task; + this.AtualizarMedalha(this.ConsultaViewModel.Apolices.ToList()); + } + base.IsEnabled = true; + MainViewModel mainViewModel6 = this; + Cliente cliente = this.SelectedCliente; + if (cliente != null) + { + nomeSocial = cliente.get_NomeSocial(); + } + else + { + nomeSocial = null; + } + mainViewModel6.Pesquisa = nomeSocial; + contatos = null; + observableCollection = null; + } + + private void WorkOnSelectedStatus(FiltroStatusDocumento value) + { + MainViewModel.StatusSelecionado = value; + if (this.SelectedCliente == null) + { + return; + } + if (!this.Invoke) + { + return; + } + string viewAberta = MainViewModel.ViewAberta; + if (viewAberta == "ConsultaOriginalView") + { + Gestor.Application.ViewModels.Seguros.ConsultaViewModel consultaViewModel = this.ConsultaViewModel; + if (consultaViewModel == null) + { + return; + } + consultaViewModel.SelecionarCliente(this.SelectedCliente); + return; + } + if (viewAberta != "ClienteView") + { + return; + } + Gestor.Application.ViewModels.Seguros.ClienteViewModel clienteViewModel = this.ClienteViewModel; + if (clienteViewModel == null) + { + return; + } + clienteViewModel.SelecionaCliente(this.SelectedCliente); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/MenuBIViewModel.cs b/Codemerx/Gestor.Application/ViewModels/MenuBIViewModel.cs new file mode 100644 index 0000000..9114678 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/MenuBIViewModel.cs @@ -0,0 +1,12 @@ +using Gestor.Application.ViewModels.Generic; +using System; + +namespace Gestor.Application.ViewModels +{ + public class MenuBIViewModel : BaseSegurosViewModel + { + public MenuBIViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/MenuFerramentasViewModel.cs b/Codemerx/Gestor.Application/ViewModels/MenuFerramentasViewModel.cs new file mode 100644 index 0000000..abbe3b1 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/MenuFerramentasViewModel.cs @@ -0,0 +1,88 @@ +using Gestor.Application.ViewModels.Ferramentas; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Runtime.CompilerServices; +using System.Windows; + +namespace Gestor.Application.ViewModels +{ + internal class MenuFerramentasViewModel : BaseSegurosViewModel + { + private Usuario _selectedUsuario = new Usuario(); + + private Visibility _visibilityUsuario; + + private Visibility _visibilityEmpresa; + + private object _content; + + public object Content + { + get + { + return this._content; + } + set + { + this._content = value; + base.OnPropertyChanged("Content"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public static Usuario UsuarioSelecionado + { + get; + set; + } + + public Gestor.Application.ViewModels.Ferramentas.UsuarioViewModel UsuarioViewModel + { + get; + set; + } + + public Visibility VisibilityEmpresa + { + get + { + return this._visibilityEmpresa; + } + set + { + this._visibilityEmpresa = value; + base.OnPropertyChanged("VisibilityEmpresa"); + } + } + + public Visibility VisibilityUsuario + { + get + { + return this._visibilityUsuario; + } + set + { + this._visibilityUsuario = value; + base.OnPropertyChanged("VisibilityUsuario"); + } + } + + public MenuFerramentasViewModel() + { + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/MenuItemViewModel.cs b/Codemerx/Gestor.Application/ViewModels/MenuItemViewModel.cs new file mode 100644 index 0000000..e51f2f6 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/MenuItemViewModel.cs @@ -0,0 +1,1048 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Application.Views.Seguros.Itens; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels +{ + public class MenuItemViewModel : BaseSegurosViewModel + { + private readonly ItemServico _servico; + + private string _acaoItens = "MANTER"; + + private readonly Documento _documentoSelecionado; + + public bool AlterandoSelectedItem; + + private bool _endossoRenovacao; + + private ObservableCollection _itens = new ObservableCollection(); + + private ObservableCollection _itensFiltrados = new ObservableCollection(); + + private Item _selectedItem = new Item(); + + private bool _mostrarLista; + + private bool _isExpanded = true; + + private ManutencaoItem _manutencao; + + private object _view; + + private bool _allSelectedChanging; + + private bool? _allSelected = new bool?(false); + + private string _manterTodosText = "MANTER TODOS OS ITENS"; + + private string _manterText = "MANTER ITENS"; + + public bool? AllSelected + { + get + { + return this._allSelected; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelected; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelected = value; + this.AllSelectedChanged(); + this.Itens = new ObservableCollection(this.Itens); + base.OnPropertyChanged("AllSelected"); + } + } + + private bool Carregando + { + get; + set; + } + + public bool EndossoRenovacao + { + get + { + return this._endossoRenovacao; + } + set + { + this._endossoRenovacao = value; + base.OnPropertyChanged("EndossoRenovacao"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public ObservableCollection ItensFiltrados + { + get + { + return this._itensFiltrados; + } + set + { + this._itensFiltrados = value; + this.IsExpanded = (value != null ? value.Count > 0 : false); + foreach (Item itensFiltrado in this.ItensFiltrados) + { + itensFiltrado.add_PropertyChanged(new PropertyChangedEventHandler(this.EntryOnPropertyChanged)); + } + base.OnPropertyChanged("ItensFiltrados"); + } + } + + public string ManterText + { + get + { + return this._manterText; + } + set + { + this._manterText = value; + base.OnPropertyChanged("ManterText"); + } + } + + public string ManterTodosText + { + get + { + return this._manterTodosText; + } + set + { + this._manterTodosText = value; + base.OnPropertyChanged("ManterTodosText"); + } + } + + public ManutencaoItem Manutencao + { + get + { + return this._manutencao; + } + set + { + this._manutencao = value; + base.OnPropertyChanged("Manutencao"); + } + } + + public bool MostrarLista + { + get + { + return this._mostrarLista; + } + set + { + this._mostrarLista = value; + base.OnPropertyChanged("MostrarLista"); + } + } + + public long Ramo + { + get; + set; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + this.WorkOnSelectedItem(value); + this._selectedItem = value; + base.OnPropertyChanged("SelectedItem"); + } + } + + public object View + { + get + { + return this._view; + } + set + { + this._view = value; + base.OnPropertyChanged("View"); + } + } + + public MenuItemViewModel(long ramo, ManutencaoItem manutencao) + { + if (ramo == (long)6 || ramo == (long)7 || ramo == (long)9 || ramo == (long)10 || ramo == (long)53 || ramo == (long)66) + { + this._acaoItens = "MOVER"; + } + this._manterTodosText = string.Concat(this._acaoItens, " TODOS OS ITENS"); + this._manterText = string.Concat(this._acaoItens, " ITEM"); + this.Ramo = ramo; + this._servico = new ItemServico(); + this._documentoSelecionado = (manutencao == null ? ConsultaViewModel.DocumentoSelecionado : manutencao.get_Documento()); + if (manutencao != null && manutencao.get_Tipo() == 2) + { + ConsultaViewModel.FiltrarItens = 4; + } + this.Seleciona(manutencao == null); + if (manutencao == null) + { + return; + } + this.Manutencao = manutencao; + this.MostrarLista = true; + } + + private void AllSelectedChanged() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.AllSelected.HasValue) + { + this.ManterTodosText = (this.AllSelected.Value ? string.Concat(this._acaoItens, " ITENS SELECIONADOS") : string.Concat(this._acaoItens, " TODOS OS ITENS")); + foreach (Item iten in this.Itens) + { + iten.set_Selecionado(this.AllSelected.Value); + } + } + } + finally + { + this._allSelectedChanging = false; + } + } + + public async void CancelarItem(Item item) + { + if (item != null) + { + base.Loading(true); + await this._servico.Cancelar(item, string.Format("CANCELADO NO ENDOSSO ORDEM {0}", this.Manutencao.get_Documento().get_Ordem()), this.Manutencao.get_Documento().get_Id()); + base.ToggleSnackBar("ITEM CANCELADO COM SUCESSO", true); + base.Loading(false); + this.RecarregarItens(item); + } + } + + private void EntryOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (args.PropertyName == "Selecionado") + { + this.RecheckAllSelected(); + } + } + + internal async Task> Filtrar(string value) + { + List items = await Task.Run>(() => this.FiltrarItem(value)); + return items; + } + + public List FiltrarItem(string filter) + { + this.ItensFiltrados = (string.IsNullOrWhiteSpace(filter) ? this.Itens : new ObservableCollection( + from x in this.Itens + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ordem() + select x)); + return this.ItensFiltrados.ToList(); + } + + private async void Load(bool substituir = false, ManutencaoItem manutencao = null) + { + long ramo = this.Ramo; + if (ramo <= (long)38) + { + long num = ramo - (long)1; + if (num <= (long)19) + { + switch ((uint)num) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + goto Label3; + } + case 3: + case 7: + case 10: + case 11: + case 13: + case 15: + case 16: + case 18: + { + if (this.View == null || !(this.View.GetType() == typeof(RiscosDiversosView))) + { + this.View = new RiscosDiversosView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + } + else + { + await ((RiscosDiversosView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((RiscosDiversosView)this.View).Substituir(); + } + if (manutencao != null) + { + ((RiscosDiversosView)this.View).Manter(manutencao); + } + return; + } + base.IsVisible = Visibility.Visible; + return; + } + case 4: + { + goto Label5; + } + case 5: + case 6: + case 8: + case 9: + { + goto Label0; + } + case 12: + { + if (this.View == null || !(this.View.GetType() == typeof(AeronauticoView))) + { + this.View = new AeronauticoView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((AeronauticoView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((AeronauticoView)this.View).Substituir(); + } + if (manutencao != null) + { + ((AeronauticoView)this.View).Manter(manutencao); + } + return; + } + } + case 19: + { + if (this.View == null || !(this.View.GetType() == typeof(GranizoView))) + { + this.View = new GranizoView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((GranizoView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((GranizoView)this.View).Substituir(); + } + if (manutencao != null) + { + ((GranizoView)this.View).Manter(manutencao); + } + return; + } + } + } + } + else + { + } + if (ramo != (long)30) + { + long num1 = ramo - (long)36; + if (num1 <= (long)2) + { + switch ((uint)num1) + { + case 0: + { + if (this.View == null || !(this.View.GetType() == typeof(ConsorcioView))) + { + this.View = new ConsorcioView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((ConsorcioView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((ConsorcioView)this.View).Substituir(); + } + if (manutencao != null) + { + ((ConsorcioView)this.View).Manter(manutencao); + } + return; + } + } + case 1: + { + goto Label5; + } + case 2: + { + break; + } + default: + { + if (this.View == null || !(this.View.GetType() == typeof(RiscosDiversosView))) + { + this.View = new RiscosDiversosView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + } + else + { + await ((RiscosDiversosView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((RiscosDiversosView)this.View).Substituir(); + } + if (manutencao != null) + { + ((RiscosDiversosView)this.View).Manter(manutencao); + } + return; + } + base.IsVisible = Visibility.Visible; + return; + } + } + } + else + { + if (this.View == null || !(this.View.GetType() == typeof(RiscosDiversosView))) + { + this.View = new RiscosDiversosView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + } + else + { + await ((RiscosDiversosView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((RiscosDiversosView)this.View).Substituir(); + } + if (manutencao != null) + { + ((RiscosDiversosView)this.View).Manter(manutencao); + } + return; + } + base.IsVisible = Visibility.Visible; + return; + } + } + Label3: + if (this.View == null || !(this.View.GetType() == typeof(PatrimonialView))) + { + this.View = new PatrimonialView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((PatrimonialView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((PatrimonialView)this.View).Substituir(); + } + if (manutencao != null) + { + ((PatrimonialView)this.View).Manter(manutencao); + } + return; + } + } + else if (ramo == (long)47 || ramo == (long)53 || ramo == (long)66) + { + goto Label0; + } + if (this.View == null || !(this.View.GetType() == typeof(RiscosDiversosView))) + { + this.View = new RiscosDiversosView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + } + else + { + await ((RiscosDiversosView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((RiscosDiversosView)this.View).Substituir(); + } + if (manutencao != null) + { + ((RiscosDiversosView)this.View).Manter(manutencao); + } + return; + } + base.IsVisible = Visibility.Visible; + return; + Label0: + if (this.View == null || !(this.View.GetType() == typeof(VidaView))) + { + this.View = new VidaView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((VidaView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((VidaView)this.View).Substituir(); + } + if (manutencao != null) + { + ((VidaView)this.View).Manter(manutencao); + } + return; + } + Label5: + if (this.View == null || !(this.View.GetType() == typeof(AutoView))) + { + this.View = new AutoView(this, false, substituir, manutencao, null, null, this.EndossoRenovacao); + base.IsVisible = Visibility.Visible; + return; + } + else + { + await ((AutoView)this.View).Selecionar(ConsultaViewModel.ItemSelecionado); + if (substituir) + { + ((AutoView)this.View).Substituir(); + } + if (manutencao != null) + { + ((AutoView)this.View).Manter(manutencao); + } + return; + } + } + + public void Manter(Item item) + { + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + ConsultaViewModel.ItemSelecionado = item; + this.Load(false, this.Manutencao); + } + + public async void ManterItens() + { + Item item; + List items; + Item item1; + bool flag; + Item item2; + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + Action enableMainMenu = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu != null) + { + enableMainMenu(false); + } + else + { + } + base.Loading(true); + int num = 1; + if (this.ManterTodosText == string.Concat(this._acaoItens, " TODOS OS ITENS")) + { + items = new List(this.Itens); + } + else + { + ObservableCollection itens = this.Itens; + items = new List( + from x in itens + where x.get_Selecionado() + select x); + } + Label6: + foreach (Item item3 in items) + { + item = await this._servico.BuscarItemPorIdAsync(item3.get_Id()); + item2 = item; + item1 = item2; + ObservableCollection observableCollection = await this._servico.BuscarCoberturasPorItemAsync(item3.get_Id()); + item1.set_Coberturas(observableCollection); + item1 = null; + flag = false; + item2.set_Id((long)0); + item2.set_Sinistrado(false); + item2.set_Sinistros(null); + item2.set_Documento(ConsultaViewModel.DocumentoSelecionado); + item2.set_Ordem(new int?(num)); + num++; + foreach (Cobertura cobertura in item2.get_Coberturas()) + { + cobertura.set_Id((long)0); + cobertura.set_Item(item2); + } + long ramo = this.Ramo; + if (ramo > (long)36) + { + if (ramo == (long)37) + { + goto Label1; + } + if (ramo == (long)53 || ramo == (long)66) + { + goto Label2; + } + } + else + { + long num1 = ramo - (long)1; + if (num1 <= (long)19) + { + switch ((uint)num1) + { + case 0: + case 1: + case 2: + case 14: + case 17: + { + item1 = item2; + Patrimonial patrimonial = await this._servico.BuscaPatrimonial(item3.get_Id()); + item1.set_Patrimonial(patrimonial); + item1 = null; + item2.get_Patrimonial().set_Item(item2); + item2.get_Patrimonial().set_Id((long)0); + goto Label3; + } + case 3: + case 7: + case 10: + case 11: + case 13: + case 15: + case 16: + case 18: + { + goto Label4; + } + case 4: + { + goto Label1; + } + case 5: + case 6: + case 8: + case 9: + { + goto Label2; + } + case 12: + { + item1 = item2; + Aeronautico aeronautico = await this._servico.BuscaAeronautico(item3.get_Id()); + item1.set_Aeronautico(aeronautico); + item1 = null; + item2.get_Aeronautico().set_Item(item2); + item2.get_Aeronautico().set_Id((long)0); + goto Label3; + } + case 19: + { + item1 = item2; + Granizo granizo = await this._servico.BuscaGranizo(item3.get_Id()); + item1.set_Granizo(granizo); + item1 = null; + item2.get_Granizo().set_Item(item2); + item2.get_Granizo().set_Id((long)0); + goto Label3; + } + } + } + else + { + } + if (ramo != (long)36) + { + goto Label4; + } + item1 = item2; + Consorcio consorcio = await this._servico.BuscaConsorcio(item3.get_Id()); + item1.set_Consorcio(consorcio); + item1 = null; + item2.get_Consorcio().set_Item(item2); + item2.get_Consorcio().set_Id((long)0); + goto Label3; + } + Label4: + item1 = item2; + RiscosDiversos riscosDiverso = await this._servico.BuscaRiscosDiversos(item3.get_Id()); + item1.set_RiscosDiversos(riscosDiverso); + item1 = null; + item2.get_RiscosDiversos().set_Item(item2); + item2.get_RiscosDiversos().set_Id((long)0); + goto Label3; + } + base.Loading(false); + Action action = Gestor.Application.Actions.Actions.EnableMenu; + if (action != null) + { + action(true); + } + else + { + } + Action enableMainMenu1 = Gestor.Application.Actions.Actions.EnableMainMenu; + if (enableMainMenu1 != null) + { + enableMainMenu1(true); + } + else + { + } + if (this.ItensFiltrados.Count != 0) + { + this.AllSelected = new bool?(false); + this.ManterTodosText = string.Concat(this._acaoItens, " TODOS OS ITENS"); + this.SelecionaItem(this.ItensFiltrados.First()); + } + else + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(21, ""); + } + else + { + } + } + return; + Label1: + item1 = item2; + Auto auto = await this._servico.BuscaAuto(item3.get_Id()); + item1.set_Auto(auto); + item1 = null; + item2.get_Auto().set_Item(item2); + item2.get_Auto().set_Id((long)0); + if (item2.get_Auto() != null && item2.get_Auto().get_Placa() == null) + { + await base.ShowMessage(string.Format("ITEM {0} ENCONTRADO SEM PLACA.", item2.get_Ordem()), "OK", "", false); + base.Loading(false); + Action enableMenu1 = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu1 != null) + { + enableMenu1(true); + } + else + { + } + Action action1 = Gestor.Application.Actions.Actions.EnableMainMenu; + if (action1 != null) + { + action1(true); + } + else + { + } + return; + } + Label3: + item2.set_Status(""); + item3.set_Substituido(null); + item = await this._servico.Save(item2); + item2 = item; + if (flag && item2.get_Id() != item3.get_Id()) + { + List titularesVidas = await this._servico.BuscaTitularesVida(item3.get_Id()); + if (titularesVidas.Count > 0) + { + titularesVidas.ForEach((TitularesVida t) => t.set_IdItem(this.itemManter.get_Id())); + await this._servico.SaveTitulares(titularesVidas); + } + } + this.ItensFiltrados.Remove(item3); + this.Itens.Remove(item3); + item3 = null; + goto Label6; + Label2: + item1 = item2; + Vida vida = await this._servico.BuscaVida(item3.get_Id()); + item1.set_Vida(vida); + item1 = null; + item2.get_Vida().set_Item(item2); + item2.get_Vida().set_Id((long)0); + flag = true; + goto Label3; + goto Label4; + } + + public async void Reativar(Item item) + { + if (item != null) + { + base.Loading(true); + await this._servico.Reativar(item, string.Concat("ITEM REATIVADO PELO USUARIO ", Recursos.Usuario.get_Nome())); + base.ToggleSnackBar("ITEM REATIVADO COM SUCESSO", true); + base.Loading(false); + this.RecarregarItens(item); + } + } + + public async void RecarregarItens(Item item) + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.MenuItemViewModel::RecarregarItens(Gestor.Model.Domain.Seguros.Item) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void RecarregarItens(Gestor.Model.Domain.Seguros.Item) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // 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.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 104 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 155 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 76 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 36 + // 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 + + } + + private void RecheckAllSelected() + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + if (this.Itens.All((Item e) => e.get_Selecionado())) + { + this.AllSelected = new bool?(true); + this.ManterTodosText = string.Concat(this._acaoItens, " ITENS SELECIONADOS"); + } + else if (!this.Itens.All((Item e) => !e.get_Selecionado())) + { + this.AllSelected = null; + this.ManterTodosText = string.Concat(this._acaoItens, " ITENS SELECIONADOS"); + } + else + { + this.AllSelected = new bool?(false); + this.ManterTodosText = string.Concat(this._acaoItens, " TODOS OS ITENS"); + } + } + finally + { + this._allSelectedChanging = false; + } + } + + public async void Seleciona(bool item = true) + { + if (!item || ConsultaViewModel.ItemSelecionado != null) + { + await this.SelecionaItens(ConsultaViewModel.FiltrarItens, ConsultaViewModel.ItemSelecionado); + } + else + { + this.Load(false, null); + } + } + + public void SelecionaItem(Item item) + { + if (this.Carregando) + { + return; + } + this.AlterandoSelectedItem = true; + this.SelectedItem = item; + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + this.AlterandoSelectedItem = false; + } + + public async Task SelecionaItens(int type, Item item = null) + { + bool count; + Item item1; + base.Loading(true); + this.Carregando = true; + switch (type) + { + case 1: + case 2: + { + this.Itens = await this._servico.BuscarItens(this._documentoSelecionado.get_Id(), 2); + break; + } + case 3: + { + this.Itens = await this._servico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 1); + break; + } + case 4: + { + this.Itens = await this._servico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 3); + break; + } + default: + { + this.Itens = await this._servico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 0); + break; + } + } + this.ItensFiltrados = this.Itens; + if (item != null && item.get_Id() > (long)0) + { + this.AlterandoSelectedItem = true; + MenuItemViewModel menuItemViewModel = this; + if (this.ItensFiltrados == null || this.ItensFiltrados.Count <= 0) + { + item1 = null; + } + else + { + item1 = this.ItensFiltrados.FirstOrDefault((Item x) => x.get_Id() == item.get_Id()); + } + menuItemViewModel.SelectedItem = item1; + Action scrollToItem = Gestor.Application.Actions.Actions.ScrollToItem; + if (scrollToItem != null) + { + scrollToItem(); + } + else + { + } + this.AlterandoSelectedItem = false; + } + MenuItemViewModel menuItemViewModel1 = this; + if (this.MostrarLista) + { + count = true; + } + else + { + ObservableCollection itens = this.Itens; + if (itens != null) + { + count = itens.Count > 1; + } + else + { + count = false; + } + } + menuItemViewModel1.MostrarLista = count; + this.Carregando = false; + base.Loading(false); + } + + public void Substituir(Item item) + { + Action enableMenu = Gestor.Application.Actions.Actions.EnableMenu; + if (enableMenu != null) + { + enableMenu(false); + } + else + { + } + ConsultaViewModel.ItemSelecionado = item; + this.Load(true, null); + } + + private void WorkOnSelectedItem(Item value) + { + ConsultaViewModel.ItemSelecionado = value; + this.Load(false, null); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Relatorios/DialogPrintViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Relatorios/DialogPrintViewModel.cs new file mode 100644 index 0000000..537bed2 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Relatorios/DialogPrintViewModel.cs @@ -0,0 +1,193 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Configuracoes; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Relatorios; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Relatorios +{ + public class DialogPrintViewModel : BaseViewModel + { + private bool _carregando; + + private ConfiguracaoImpressao _configuracoes; + + private List _tamanhos = new List() + { + "GRANDE", + "MÉDIO", + "PEQUENO" + }; + + private bool _orientacaoImpressaoPortrait; + + private bool _orientacaoImpressaoLandscape; + + private string _tamanhoFonte = "PEQUENO"; + + private Relatorio _relatorio + { + get; + set; + } + + private Type _tipo + { + get; + set; + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.OnPropertyChanged("Carregando"); + } + } + + public ConfiguracaoImpressao Configuracoes + { + get + { + return this._configuracoes; + } + set + { + this._configuracoes = value; + base.OnPropertyChanged("Configuracoes"); + } + } + + public bool OrientacaoImpressao + { + get; + set; + } + + public bool OrientacaoImpressaoLandscape + { + get + { + return this._orientacaoImpressaoLandscape; + } + set + { + this._orientacaoImpressaoLandscape = value; + base.OnPropertyChanged("OrientacaoImpressaoLandscape"); + } + } + + public bool OrientacaoImpressaoPortrait + { + get + { + return this._orientacaoImpressaoPortrait; + } + set + { + this._orientacaoImpressaoPortrait = value; + base.OnPropertyChanged("OrientacaoImpressaoPortrait"); + } + } + + public string TamanhoFonte + { + get + { + return this._tamanhoFonte; + } + set + { + this._tamanhoFonte = value; + if (value == "MÉDIO") + { + this.Configuracoes.set_TamanhoFonte(6); + } + else if (value == "GRANDE") + { + this.Configuracoes.set_TamanhoFonte(5); + } + else + { + this.Configuracoes.set_TamanhoFonte(7); + } + base.OnPropertyChanged("TamanhoFonte"); + } + } + + public List Tamanhos + { + get + { + return this._tamanhos; + } + set + { + this._tamanhos = value; + base.OnPropertyChanged("Tamanhos"); + } + } + + public DialogPrintViewModel(Relatorio relatorio, Type tipo) + { + this._relatorio = relatorio; + this._tipo = tipo; + } + + public async Task Carregar() + { + List list = await (new ConfuguracoesServico()).BuscarParametros(this._relatorio); + if (list == null || list.Count == 0) + { + list = this._tipo.GetProperties(BindingFlags.Instance | BindingFlags.Public).Select((PropertyInfo x) => { + ParametrosRelatorio parametrosRelatorio = new ParametrosRelatorio(); + parametrosRelatorio.set_Campo(x.Name); + parametrosRelatorio.set_Header(x.GetDescriptionAttribute()); + parametrosRelatorio.set_Tipo(x.GetTypeAttribute()); + parametrosRelatorio.set_Relatorio(this._relatorio); + parametrosRelatorio.set_Width(0); + parametrosRelatorio.set_Ordem(0); + return parametrosRelatorio; + }).ToList(); + } + List parametrosRelatorios = list; + parametrosRelatorios.ForEach((ParametrosRelatorio x) => x.set_Selecionado(true)); + ConfiguracaoImpressao configuracaoImpressao = new ConfiguracaoImpressao(); + configuracaoImpressao.set_TamanhoFonte(7); + configuracaoImpressao.set_Campos(list); + configuracaoImpressao.set_OrientacaoImpressao(new bool?(false)); + this.Configuracoes = configuracaoImpressao; + } + + public void Selecionar() + { + if (this.Carregando) + { + return; + } + ConfiguracaoImpressao configuracoes = this.Configuracoes; + if (configuracoes == null) + { + return; + } + List campos = configuracoes.get_Campos(); + if (campos == null) + { + return; + } + campos.ForEach((ParametrosRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Relatorios/RelatorioViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Relatorios/RelatorioViewModel.cs new file mode 100644 index 0000000..f85b039 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Relatorios/RelatorioViewModel.cs @@ -0,0 +1,14619 @@ +using Agger.Registro; +using ClosedXML.Excel; +using CsQuery.ExtensionMethods; +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Configuracoes; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.BI; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Application.Views.Relatorios; +using Gestor.Common.Converters; +using Gestor.Common.Helpers; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Aggilizador; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Relatorios; +using Gestor.Model.Domain.Relatorios.ApolicePendente; +using Gestor.Model.Domain.Relatorios.Auditoria; +using Gestor.Model.Domain.Relatorios.Classificacao; +using Gestor.Model.Domain.Relatorios.Cliente; +using Gestor.Model.Domain.Relatorios.ClientesAtivosInativos; +using Gestor.Model.Domain.Relatorios.Comissao; +using Gestor.Model.Domain.Relatorios.CriticaApolice; +using Gestor.Model.Domain.Relatorios.EndossoCancelamento; +using Gestor.Model.Domain.Relatorios.ExtratoBaixado; +using Gestor.Model.Domain.Relatorios.FaturaPendente; +using Gestor.Model.Domain.Relatorios.Fechamento; +using Gestor.Model.Domain.Relatorios.Licenciamento; +using Gestor.Model.Domain.Relatorios.Log; +using Gestor.Model.Domain.Relatorios.LogsEnvio; +using Gestor.Model.Domain.Relatorios.MetaSeguradora; +using Gestor.Model.Domain.Relatorios.MetaVendedor; +using Gestor.Model.Domain.Relatorios.NotaFiscal; +using Gestor.Model.Domain.Relatorios.Pagamento; +using Gestor.Model.Domain.Relatorios.Pendente; +using Gestor.Model.Domain.Relatorios.Placa; +using Gestor.Model.Domain.Relatorios.PrevisaoPagamentoComissao; +using Gestor.Model.Domain.Relatorios.Producao; +using Gestor.Model.Domain.Relatorios.Renovacao; +using Gestor.Model.Domain.Relatorios.Sinistro; +using Gestor.Model.Domain.Relatorios.Tarefa; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using MaterialDesignThemes.Wpf; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Net.Http; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Forms; +using System.Windows.Threading; + +namespace Gestor.Application.ViewModels.Relatorios +{ + public class RelatorioViewModel : BaseSegurosViewModel + { + private bool _alterandoFiltros; + + private readonly ApoliceServico _apoliceServico; + + private readonly ParcelaServico _parcelaServico; + + private readonly SinistroServico _sinistroServico; + + private readonly ClienteServico _clienteServico; + + private readonly LogServico _logServico; + + private readonly CriticaApoliceServico _criticaServico; + + private readonly ServicoExtrato _extratoServico; + + private readonly MetaSeguradoraServico _metaSeguradoraServico; + + private readonly MetaVendedorServico _metaVendedorServico; + + private readonly NotaFiscalServico _notaFiscalServico; + + private readonly Func funcProducaoDistinctByDocumentoId = new Func((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Id()); + + private readonly Func funcProducaoSegurosNovos = new Func((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Situacao() == 1); + + private readonly Func funcProducaoSegurosRenovacao = new Func((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Situacao() == 2); + + private readonly Func funcProducaoNegociosNovos = new Func((Gestor.Model.Domain.Relatorios.Producao.Producao p) => { + NegocioCorretora? negocioCorretora = p.get_Documento().get_NegocioCorretora(); + return negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue; + }); + + private readonly Func funcProducaoNegociosProprios = new Func((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_NegocioCorretora().GetValueOrDefault() == 1); + + private bool _totalizacao = true; + + private bool _enableEmpresa; + + private bool _apelido; + + private List _empresas; + + private Gestor.Model.Domain.Common.Empresa _empresa; + + private bool? _allSelectedSeguradora; + + private bool? _allSelectedRamo; + + private bool? _allSelectedVendedor; + + private bool? _allSelectedTipoVendedor; + + private bool? _allSelectedStatus; + + private bool? _allSelectedNegocio; + + private bool? _allSelectedEstipulante; + + private bool? _allSelectedProduto; + + private bool _allSelectedChanging; + + private string _filtro; + + private bool _visibilityHtml; + + private bool _relatorioVisibility; + + private string _htmlContent; + + private List _relatorios = new List(); + + private Gestor.Model.Common.Relatorio _relatorio = 2; + + private bool _extratosEnabled; + + private Visibility _planilhaVisibility; + + private object _report; + + private bool _permitirFiltrosPersonalizados; + + private Visibility _filtrosPersonalizados = Visibility.Collapsed; + + private bool _somenteNaoPagos; + + private bool _visibilityDesconsiderarNegativos = Recursos.Configuracoes.Any(new Func((ConfiguracaoSistema x) => x.get_Configuracao() == 50)); + + private bool _desconsiderarNegativos; + + private bool _segundaViaReciboPagamento; + + private bool _documentosEmitidos; + + private bool _sinteticosPagamento; + + private bool _visibilityUsuarios; + + private Visibility _visibilityDocumentoAtivo; + + private Visibility _visibilityReferencia = Visibility.Collapsed; + + private Visibility _visibilityOrdem = Visibility.Collapsed; + + private string _referencia; + + private ObservableCollection _referencias = new ObservableCollection(); + + private ObservableCollection _ordens = new ObservableCollection(); + + private string _ordemSelecionada; + + private DateTime _inicio = Funcoes.GetNetworkTime().Date.AddMonths(-1); + + private DateTime _fim = Funcoes.GetNetworkTime().Date; + + private int _inicioValor; + + private int _fimValor; + + private Gestor.Model.Common.Agrupamento _agrupamento; + + private List _producao; + + private List _licenciamento; + + private List _placas; + + private List _tarefa; + + private List _endosso; + + private List _classificacao; + + private ObservableCollection _licenciamentoFiltrado; + + private ObservableCollection _placaFiltrado; + + private ObservableCollection _tarefaFiltrado; + + private List _renovacao; + + private List _faturaPendente; + + private ObservableCollection _faturaPendenteFiltrado; + + private List _sinistro; + + private List _comissao; + + private List _pendente; + + private List _pagamentos; + + private List _pagamentosSintetico; + + private List _clientesAtivosInativos; + + private List _logsEnvio; + + private ObservableCollection _apoliceCriticaFiltrado; + + private ObservableCollection _logUtilizacaoFiltrado; + + private ObservableCollection _fechamento; + + private ObservableCollection _previsao; + + private ObservableCollection _previsaoSintetico; + + private List _auditoria; + + private ObservableCollection _auditoriaFiltrado; + + private List _apolicePendente; + + private List _extratos; + + private ObservableCollection _apolicePendenteFiltrado; + + private ObservableCollection _extratosFiltrado; + + private List _metaSeguradora; + + private List _metaVendedor; + + private ObservableCollection _metaSeguradoraFiltrado; + + private ObservableCollection _metaVendedorFiltrado; + + private ObservableCollection _producaoFiltrado; + + private ObservableCollection _endossoFiltrado; + + private ObservableCollection _notaFiscalFiltrado; + + private ObservableCollection _renovacaoFiltrado; + + private ObservableCollection _sinistroFiltrado; + + private ObservableCollection _comissaoFiltrado; + + private ObservableCollection _pendenteFiltrado; + + private ObservableCollection _clientesAtivosInativosFiltrado; + + private ObservableCollection _classificacaoFiltrado; + + private ObservableCollection _logsEnvioFiltrado; + + private ObservableCollection _fechamentoFiltrado; + + private ObservableCollection _previsaoFiltrado; + + private bool _totais; + + private ObservableCollection _sinteticoRelatorio; + + private SinteticoClientes _sinteticoCliente; + + private ObservableCollection _sintetic; + + private bool _comparativo; + + private bool _completo; + + private bool _notaFiscalPorSeguradora; + + private Mes _selectedMes; + + private int _selectedAno; + + private Visibility _infoVisibility = Visibility.Collapsed; + + private string _info; + + private string _erroRelatorio = "NÃO HÁ DADOS NO PERÍODO E FILTROS SELECIONADOS."; + + private bool _carregando; + + private bool _documentosAtivos; + + private List _seguradoras = Recursos.Seguradoras.Where(new Func((Seguradora x) => x.get_Ativo())).OrderBy(new Func((Seguradora x) => x.get_Nome())).ToList(); + + private List _ramos = Recursos.Ramos.Where(new Func((Ramo x) => x.get_Ativo())).OrderBy(new Func((Ramo x) => x.get_Nome())).ToList(); + + private List _notasFiscais = new List(); + + private bool _inativo = true; + + private List _vendedores = new List(); + + private List _tipoVendedor = Recursos.TipoVendedor.Where(new Func((Gestor.Model.Domain.Seguros.TipoVendedor x) => x.get_Ativo().GetValueOrDefault())).OrderBy(new Func((Gestor.Model.Domain.Seguros.TipoVendedor x) => x.get_Descricao())).ToList(); + + private List _produtos = Recursos.Produtos.Where(new Func((Gestor.Model.Domain.Seguros.Produto x) => x.get_Ativo())).OrderBy(new Func((Gestor.Model.Domain.Seguros.Produto x) => x.get_Nome())).ToList(); + + private List _estipulantes = Recursos.Estipulantes.Where(new Func((Estipulante x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && Recursos.Usuario.get_IdEmpresa() != x.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + })).OrderBy(new Func((Estipulante x) => x.get_Nome())).ToList(); + + private readonly static List NegocioList; + + private List _negocios = RelatorioViewModel.NegocioList; + + private readonly static List TipoSegurosList; + + private List _tipoSeguros = RelatorioViewModel.TipoSegurosList; + + private bool _isVisibleGrid1 = true; + + private bool _isVisibleGrid2 = true; + + private bool _isVisibleGrid3 = true; + + private bool _isVisibleGrid4 = true; + + private List _filtroRelatorioPersonalizado; + + private Gestor.Model.Domain.Relatorios.FiltroPersonalizado _filtroPersonalizado; + + private Type _tipoString = typeof(string); + + private Type _tipoEnum = typeof(Enum); + + private Type _tipoDateTime = typeof(DateTime); + + private Type _tipoDecimal = typeof(decimal); + + private Type _tipoInt = typeof(int); + + private Type _tipoLong = typeof(long); + + private ObservableCollection _ramosSelecionados; + + private bool _novosNegocios; + + private Ramo _ramoSelecionado; + + private string _valorIncial = ""; + + private string _valorFinal = ""; + + private bool _semValor; + + private bool _valorIgual; + + private Visibility _visibilitySemValor = Visibility.Collapsed; + + private Visibility _visibilityOpcoesFiltros = Visibility.Collapsed; + + private ObservableCollection _filtroPersonalizadoSelecionado; + + private ObservableCollection _filtroRelatorioSelecionado = new ObservableCollection(); + + private Visibility _visibilityFiltros; + + private Visibility _visibilityEtiqueta; + + private Visibility _visibiltyProtocolo; + + private Visibility _visibiltySincronizar; + + private Visibility _visibilityEmail; + + private Visibility _visibilityApolice; + + private Visibility _visibilityExtratos; + + private Visibility _visibilityData; + + private Visibility _visibilityMeta; + + private Visibility _visibilityMaisFiltros; + + private Visibility _visibilityGridFiltros; + + private Visibility _visibilityAgrupamento; + + private Visibility _visibilityOlho; + + private Visibility _visibilityEspecial; + + private Visibility _visibilityComparativo; + + private Visibility _visibilityCompleto; + + private Visibility _visibilityNotaFiscalPorSeguradora; + + private Visibility _visibilityPagamento; + + private Visibility _visibilitySintetizar; + + private Visibility _visibilityConfigurar; + + private Visibility _visibilityFiltroPersonalizadoButton; + + private Visibility _visibilityTarefas; + + private Visibility _visibilityAcompanhamento; + + private Visibility _visibilityValor; + + private Visibility _visibilityFiltroPersonalizado = Visibility.Collapsed; + + private string _head; + + private List _parcelasEspeciais; + + private ObservableCollection _ajuda; + + private bool _carregandoAjuda; + + private ObservableCollection _parametrosRelatorio; + + private ObservableCollection _parametrosRelatorioAdicionados; + + private ObservableCollection _parametrosTotalizacao; + + private ObservableCollection _parametrosTotalizacaoAdicionados; + + private bool _isCampo; + + private Gestor.Model.Domain.Relatorios.ParametrosRelatorio _selectedParametrosRelatorio; + + private Gestor.Model.Domain.Relatorios.ParametrosTotalizacao _selectedParametrosTotalizacao; + + private ObservableCollection _usuariosFiltrados; + + public Gestor.Model.Common.Agrupamento Agrupamento + { + get + { + return this._agrupamento; + } + set + { + this._agrupamento = value; + base.OnPropertyChanged("Agrupamento"); + } + } + + public ObservableCollection Ajuda + { + get + { + return this._ajuda; + } + set + { + this._ajuda = value; + base.OnPropertyChanged("Ajuda"); + } + } + + public bool? AllSelectedEstipulante + { + get + { + return this._allSelectedEstipulante; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedEstipulante; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedEstipulante = value; + this.AllSelectedChanged(7); + this.Estipulantes = new List(this.Estipulantes); + base.OnPropertyChanged("AllSelectedEstipulante"); + } + } + + public bool? AllSelectedNegocio + { + get + { + return this._allSelectedNegocio; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedNegocio; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedNegocio = value; + this.AllSelectedChanged(5); + this.Negocios = new List(this.Negocios); + base.OnPropertyChanged("AllSelectedNegocio"); + } + } + + public bool? AllSelectedProduto + { + get + { + return this._allSelectedProduto; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedProduto; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedProduto = value; + this.AllSelectedChanged(6); + this.Produtos = new List(this.Produtos); + base.OnPropertyChanged("AllSelectedProduto"); + } + } + + public bool? AllSelectedRamo + { + get + { + return this._allSelectedRamo; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedRamo; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedRamo = value; + this.AllSelectedChanged(1); + this.Ramos = new List(this.Ramos); + base.OnPropertyChanged("AllSelectedRamo"); + } + } + + public bool? AllSelectedSeguradora + { + get + { + return this._allSelectedSeguradora; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedSeguradora; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedSeguradora = value; + this.AllSelectedChanged(0); + this.Seguradoras = new List(this.Seguradoras); + base.OnPropertyChanged("AllSelectedSeguradora"); + } + } + + public bool? AllSelectedStatus + { + get + { + return this._allSelectedStatus; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedStatus; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedStatus = value; + this.AllSelectedChanged(3); + this.TipoSeguros = new List(this.TipoSeguros); + base.OnPropertyChanged("AllSelectedStatus"); + } + } + + public bool? AllSelectedTipoVendedor + { + get + { + return this._allSelectedTipoVendedor; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedTipoVendedor; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedTipoVendedor = value; + this.AllSelectedChanged(4); + this.TipoVendedor = new List(this.TipoVendedor); + base.OnPropertyChanged("AllSelectedTipoVendedor"); + } + } + + public bool? AllSelectedVendedor + { + get + { + return this._allSelectedVendedor; + } + set + { + bool? nullable = value; + bool? nullable1 = this._allSelectedVendedor; + if (nullable.GetValueOrDefault() == nullable1.GetValueOrDefault() & nullable.HasValue == nullable1.HasValue) + { + return; + } + this._allSelectedVendedor = value; + this.AllSelectedChanged(2); + this.Vendedores = new List(this.Vendedores); + base.OnPropertyChanged("AllSelectedVendedor"); + } + } + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public List ApoliceCritica + { + get; + set; + } + + public ObservableCollection ApoliceCriticaFiltrado + { + get + { + return this._apoliceCriticaFiltrado; + } + set + { + this._apoliceCriticaFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ApoliceCriticaFiltrado"); + } + } + + public List ApolicePendente + { + get + { + return this._apolicePendente; + } + set + { + this._apolicePendente = value; + base.OnPropertyChanged("ApolicePendente"); + } + } + + public ObservableCollection ApolicePendenteFiltrado + { + get + { + return this._apolicePendenteFiltrado; + } + set + { + this._apolicePendenteFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ApolicePendenteFiltrado"); + } + } + + public List Auditoria + { + get + { + return this._auditoria; + } + set + { + this._auditoria = value; + base.OnPropertyChanged("Auditoria"); + } + } + + public ObservableCollection AuditoriaFiltrado + { + get + { + return this._auditoriaFiltrado; + } + set + { + this._auditoriaFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("AuditoriaFiltrado"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + base.OnPropertyChanged("Carregando"); + } + } + + public bool CarregandoAjuda + { + get + { + return this._carregandoAjuda; + } + set + { + this._carregandoAjuda = value; + base.OnPropertyChanged("CarregandoAjuda"); + } + } + + public List Classificacao + { + get + { + return this._classificacao; + } + set + { + this._classificacao = value; + base.OnPropertyChanged("Classificacao"); + } + } + + public ObservableCollection ClassificacaoFiltrado + { + get + { + return this._classificacaoFiltrado; + } + set + { + this._classificacaoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ClassificacaoFiltrado"); + } + } + + public List ClientesAtivosInativos + { + get + { + return this._clientesAtivosInativos; + } + set + { + this._clientesAtivosInativos = value; + SinteticoClientes sinteticoCliente = new SinteticoClientes(); + sinteticoCliente.set_Total((value != null ? value.Count : 0)); + this.SinteticoCliente = sinteticoCliente; + base.OnPropertyChanged("ClientesAtivosInativos"); + } + } + + public ObservableCollection ClientesAtivosInativosFiltrado + { + get + { + return this._clientesAtivosInativosFiltrado; + } + set + { + this._clientesAtivosInativosFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ClientesAtivosInativosFiltrado"); + } + } + + public List ColunasOcultas { get; set; } = new List(); + + public List Comissao + { + get + { + return this._comissao; + } + set + { + this._comissao = value; + base.OnPropertyChanged("Comissao"); + } + } + + public ObservableCollection ComissaoFiltrado + { + get + { + return this._comissaoFiltrado; + } + set + { + this._comissaoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ComissaoFiltrado"); + } + } + + public bool Comparativo + { + get + { + return this._comparativo; + } + set + { + this._comparativo = value; + base.OnPropertyChanged("Comparativo"); + } + } + + public bool Completo + { + get + { + return this._completo; + } + set + { + this._completo = value; + base.OnPropertyChanged("Completo"); + } + } + + public bool DesconsiderarNegativos + { + get + { + return this._desconsiderarNegativos; + } + set + { + this.LimparRelatorio(); + this._desconsiderarNegativos = value; + base.OnPropertyChanged("DesconsiderarNegativos"); + } + } + + public bool DocumentosAtivos + { + get + { + return this._documentosAtivos; + } + set + { + this._documentosAtivos = value; + base.OnPropertyChanged("DocumentosAtivos"); + } + } + + public bool DocumentosEmitidos + { + get + { + return this._documentosEmitidos; + } + set + { + this.LimparRelatorio(); + this._documentosEmitidos = value; + base.OnPropertyChanged("DocumentosEmitidos"); + } + } + + public static DrawerHost Drawer + { + get; + set; + } + + public Gestor.Model.Domain.Common.Empresa Empresa + { + get + { + return this._empresa; + } + set + { + this._empresa = value; + base.OnPropertyChanged("Empresa"); + } + } + + public List Empresas + { + get + { + return this._empresas; + } + set + { + this._empresas = value; + base.OnPropertyChanged("Empresas"); + } + } + + public bool EnableEmpresa + { + get + { + return this._enableEmpresa; + } + set + { + this._enableEmpresa = value; + base.OnPropertyChanged("EnableEmpresa"); + } + } + + public ObservableCollection EndossoFiltrado + { + get + { + return this._endossoFiltrado; + } + set + { + this._endossoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("EndossoFiltrado"); + } + } + + public List Endossoo + { + get + { + return this._endosso; + } + set + { + this._endosso = value; + base.OnPropertyChanged("Endossoo"); + } + } + + public string ErroRelatorio + { + get + { + return this._erroRelatorio; + } + set + { + this._erroRelatorio = value; + base.OnPropertyChanged("ErroRelatorio"); + } + } + + public List Estipulantes + { + get + { + return this._estipulantes; + } + set + { + this._estipulantes = value; + foreach (Estipulante estipulante in this.Estipulantes) + { + estipulante.add_PropertyChanged(new PropertyChangedEventHandler(this.EstipulanteOnPropertyChanged)); + } + base.OnPropertyChanged("Estipulantes"); + } + } + + public List Extratos + { + get + { + return this._extratos; + } + set + { + this._extratos = value; + base.OnPropertyChanged("Extratos"); + } + } + + public bool ExtratosEnabled + { + get + { + return this._extratosEnabled; + } + set + { + this._extratosEnabled = value; + base.OnPropertyChanged("ExtratosEnabled"); + } + } + + public ObservableCollection ExtratosFiltrado + { + get + { + return this._extratosFiltrado; + } + set + { + this._extratosFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ExtratosFiltrado"); + } + } + + public List FaturaPendente + { + get + { + return this._faturaPendente; + } + set + { + this._faturaPendente = value; + base.OnPropertyChanged("FaturaPendente"); + } + } + + public ObservableCollection FaturaPendenteFiltrado + { + get + { + return this._faturaPendenteFiltrado; + } + set + { + this._faturaPendenteFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("FaturaPendenteFiltrado"); + } + } + + public ObservableCollection Fechamento + { + get + { + return this._fechamento; + } + set + { + this._fechamento = value; + this.Sintetic = null; + base.OnPropertyChanged("Fechamento"); + } + } + + public ObservableCollection FechamentoFiltrado + { + get + { + return this._fechamentoFiltrado; + } + set + { + this._fechamentoFiltrado = value; + this.SintetizarRelatorio(); + this.Sintetic = null; + base.OnPropertyChanged("FechamentoFiltrado"); + } + } + + public string Filtro + { + get + { + return this._filtro; + } + set + { + this._filtro = value; + this.Filtrar(); + base.OnPropertyChanged("Filtro"); + } + } + + public Gestor.Model.Domain.Relatorios.FiltroPersonalizado FiltroPersonalizado + { + get + { + return this._filtroPersonalizado; + } + set + { + char chr; + this._filtroPersonalizado = value; + this.VisibilitySemValor = (value != null ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityOpcoesFiltros = Visibility.Collapsed; + base.OnPropertyChanged("FiltroPersonalizado"); + if (value == null) + { + return; + } + string name = value.get_Tipo().Name; + if (name != null) + { + switch (name.Length) + { + case 3: + { + if (name == "int") + { + break; + } + return; + } + case 4: + { + chr = name[0]; + if (chr == 'E') + { + if (name == "Enum") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + else + { + if (chr != 'l') + { + return; + } + if (name == "long") + { + break; + } + return; + } + } + case 5: + { + chr = name[3]; + if (chr == '3') + { + if (name == "int32") + { + break; + } + return; + } + else + { + if (chr != '6') + { + return; + } + if (name == "int64") + { + break; + } + return; + } + } + case 6: + { + if (name != "String") + { + return; + } + this.ValorInicial = ""; + this.ValorFinal = ""; + this.VisibilityOpcoesFiltros = (value != null ? Visibility.Visible : Visibility.Collapsed); + return; + } + case 7: + { + if (name != "Decimal") + { + return; + } + this.ValorInicial = "0,00"; + this.ValorFinal = "0,00"; + return; + } + case 8: + { + if (name == "DateTime") + { + this.ValorInicial = null; + this.ValorFinal = null; + return; + } + return; + } + default: + { + return; + } + } + this.ValorInicial = "0"; + this.ValorFinal = "0"; + } + } + } + + public ObservableCollection FiltroPersonalizadoSelecionado + { + get + { + return this._filtroPersonalizadoSelecionado; + } + set + { + this._filtroPersonalizadoSelecionado = value; + base.OnPropertyChanged("FiltroPersonalizadoSelecionado"); + } + } + + public ObservableCollection FiltroRelatorioSelecionado + { + get + { + return this._filtroRelatorioSelecionado; + } + set + { + this._filtroRelatorioSelecionado = value; + base.OnPropertyChanged("FiltroRelatorioSelecionado"); + } + } + + public Gestor.Model.Domain.Relatorios.Filtros Filtros + { + get; + set; + } + + public Visibility FiltrosPersonalizados + { + get + { + return this._filtrosPersonalizados; + } + set + { + this._filtrosPersonalizados = value; + base.OnPropertyChanged("FiltrosPersonalizados"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + if (value < new DateTime(1754, 1, 1)) + { + value = new DateTime(1754, 1, 1); + } + if (value > new DateTime(9999, 12, 31)) + { + value = new DateTime(9999, 12, 31); + } + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public int FimValor + { + get + { + return this._fimValor; + } + set + { + this._fimValor = value; + base.OnPropertyChanged("FimValor"); + } + } + + public string Head + { + get + { + return this._head; + } + set + { + this._head = value; + base.OnPropertyChanged("Head"); + } + } + + public string HtmlContent + { + get + { + return this._htmlContent; + } + set + { + this._htmlContent = value; + base.OnPropertyChanged("HtmlContent"); + } + } + + public bool Inativo + { + get + { + return this._inativo; + } + set + { + this._inativo = value; + this.ReloadVendedores(); + base.OnPropertyChanged("Inativo"); + } + } + + public string Info + { + get + { + return this._info; + } + set + { + this._info = value; + base.OnPropertyChanged("Info"); + } + } + + public Visibility InfoVisibility + { + get + { + return this._infoVisibility; + } + set + { + this._infoVisibility = value; + base.OnPropertyChanged("InfoVisibility"); + } + } + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + if (value < new DateTime(1754, 1, 1)) + { + value = new DateTime(1754, 1, 1); + } + if (value > new DateTime(9999, 12, 31)) + { + value = new DateTime(9999, 12, 31); + } + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public int InicioValor + { + get + { + return this._inicioValor; + } + set + { + this._inicioValor = value; + base.OnPropertyChanged("InicioValor"); + } + } + + public bool IsCampo + { + get + { + return this._isCampo; + } + set + { + this._isCampo = value; + base.OnPropertyChanged("IsCampo"); + } + } + + public bool IsVisibleGrid1 + { + get + { + return this._isVisibleGrid1; + } + set + { + this._isVisibleGrid1 = value; + base.OnPropertyChanged("IsVisibleGrid1"); + } + } + + public bool IsVisibleGrid2 + { + get + { + return this._isVisibleGrid2; + } + set + { + this._isVisibleGrid2 = value; + base.OnPropertyChanged("IsVisibleGrid2"); + } + } + + public bool IsVisibleGrid3 + { + get + { + return this._isVisibleGrid3; + } + set + { + this._isVisibleGrid3 = value; + base.OnPropertyChanged("IsVisibleGrid3"); + } + } + + public bool IsVisibleGrid4 + { + get + { + return this._isVisibleGrid4; + } + set + { + this._isVisibleGrid4 = value; + base.OnPropertyChanged("IsVisibleGrid4"); + } + } + + public List Licenciamento + { + get + { + return this._licenciamento; + } + set + { + this._licenciamento = value; + base.OnPropertyChanged("Licenciamento"); + } + } + + public ObservableCollection LicenciamentoFiltrado + { + get + { + return this._licenciamentoFiltrado; + } + set + { + this._licenciamentoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("LicenciamentoFiltrado"); + } + } + + public List LogsEnvio + { + get + { + return this._logsEnvio; + } + set + { + this._logsEnvio = value; + base.OnPropertyChanged("LogsEnvio"); + } + } + + public ObservableCollection LogsEnvioFiltrado + { + get + { + return this._logsEnvioFiltrado; + } + set + { + this._logsEnvioFiltrado = value; + this.Sintetic = null; + base.OnPropertyChanged("LogsEnvioFiltrado"); + } + } + + public List LogUtilizacao + { + get; + set; + } + + public ObservableCollection LogUtilizacaoFiltrado + { + get + { + return this._logUtilizacaoFiltrado; + } + set + { + this._logUtilizacaoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("LogUtilizacaoFiltrado"); + } + } + + public List MetaSeguradora + { + get + { + return this._metaSeguradora; + } + set + { + this._metaSeguradora = value; + base.OnPropertyChanged("MetaSeguradora"); + } + } + + public ObservableCollection MetaSeguradoraFiltrado + { + get + { + return this._metaSeguradoraFiltrado; + } + set + { + this._metaSeguradoraFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("MetaSeguradoraFiltrado"); + } + } + + public List MetaVendedor + { + get + { + return this._metaVendedor; + } + set + { + this._metaVendedor = value; + base.OnPropertyChanged("MetaVendedor"); + } + } + + public ObservableCollection MetaVendedorFiltrado + { + get + { + return this._metaVendedorFiltrado; + } + set + { + this._metaVendedorFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("MetaVendedorFiltrado"); + } + } + + public List Negocios + { + get + { + return this._negocios; + } + set + { + this._negocios = value; + foreach (NegocioRelatorio negocio in this.Negocios) + { + negocio.add_PropertyChanged(new PropertyChangedEventHandler(this.NegocioOnPropertyChanged)); + } + base.OnPropertyChanged("Negocios"); + } + } + + public ObservableCollection NotaFiscalFiltrado + { + get + { + return this._notaFiscalFiltrado; + } + set + { + this._notaFiscalFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("NotaFiscalFiltrado"); + } + } + + public bool NotaFiscalPorSeguradora + { + get + { + return this._notaFiscalPorSeguradora; + } + set + { + this._notaFiscalPorSeguradora = value; + base.OnPropertyChanged("NotaFiscalPorSeguradora"); + } + } + + public List NotasFiscais + { + get + { + return this._notasFiscais; + } + set + { + this._notasFiscais = value; + base.OnPropertyChanged("NotasFiscais"); + } + } + + public bool NovosNegocios + { + get + { + return this._novosNegocios; + } + set + { + this._novosNegocios = value; + base.OnPropertyChanged("NovosNegocios"); + } + } + + public string OrdemSelecionada + { + get + { + return this._ordemSelecionada; + } + set + { + this._ordemSelecionada = value; + base.OnPropertyChanged("OrdemSelecionada"); + } + } + + public ObservableCollection Ordens + { + get + { + return this._ordens; + } + set + { + this._ordens = value; + base.OnPropertyChanged("Ordens"); + } + } + + public List Pagamentos + { + get + { + return this._pagamentos; + } + set + { + this._pagamentos = value; + this.Sintetic = null; + base.OnPropertyChanged("Pagamentos"); + } + } + + public List PagamentosSintetico + { + get + { + return this._pagamentosSintetico; + } + set + { + this._pagamentosSintetico = value; + this.Sintetic = null; + base.OnPropertyChanged("PagamentosSintetico"); + } + } + + public ObservableCollection ParametrosRelatorio + { + get + { + return this._parametrosRelatorio; + } + set + { + if (value == null) + { + value = new ObservableCollection(); + } + Gestor.Model.Domain.Relatorios.ParametrosRelatorio parametrosRelatorio = new Gestor.Model.Domain.Relatorios.ParametrosRelatorio(); + parametrosRelatorio.set_Id((long)0); + parametrosRelatorio.set_Header("SELECIONE UM CAMPO"); + value.Insert(0, parametrosRelatorio); + this._parametrosRelatorio = value; + this.SelectedParametrosRelatorio = value[0]; + base.OnPropertyChanged("ParametrosRelatorio"); + } + } + + public ObservableCollection ParametrosRelatorioAdicionados + { + get + { + return this._parametrosRelatorioAdicionados; + } + set + { + this._parametrosRelatorioAdicionados = value; + base.OnPropertyChanged("ParametrosRelatorioAdicionados"); + } + } + + public ObservableCollection ParametrosTotalizacao + { + get + { + return this._parametrosTotalizacao; + } + set + { + if (value == null) + { + value = new ObservableCollection(); + } + Gestor.Model.Domain.Relatorios.ParametrosTotalizacao parametrosTotalizacao = new Gestor.Model.Domain.Relatorios.ParametrosTotalizacao(); + parametrosTotalizacao.set_Id((long)0); + parametrosTotalizacao.set_Header("SELECIONE UMA TOTALIZAÇÃO"); + value.Insert(0, parametrosTotalizacao); + this._parametrosTotalizacao = value; + this.SelectedParametrosTotalizacao = value[0]; + base.OnPropertyChanged("ParametrosTotalizacao"); + } + } + + public ObservableCollection ParametrosTotalizacaoAdicionados + { + get + { + return this._parametrosTotalizacaoAdicionados; + } + set + { + this._parametrosTotalizacaoAdicionados = value; + base.OnPropertyChanged("ParametrosTotalizacaoAdicionados"); + } + } + + public List ParcelasEspeciais + { + get + { + return this._parcelasEspeciais; + } + set + { + this._parcelasEspeciais = value; + base.OnPropertyChanged("ParcelasEspeciais"); + } + } + + public List Pendente + { + get + { + return this._pendente; + } + set + { + this._pendente = value; + base.OnPropertyChanged("Pendente"); + } + } + + public ObservableCollection PendenteFiltrado + { + get + { + return this._pendenteFiltrado; + } + set + { + this._pendenteFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("PendenteFiltrado"); + } + } + + public bool PermitirFiltrosPersonalizados + { + get + { + return this._permitirFiltrosPersonalizados; + } + set + { + this._permitirFiltrosPersonalizados = value; + base.OnPropertyChanged("PermitirFiltrosPersonalizados"); + } + } + + public ObservableCollection PlacaFiltrado + { + get + { + return this._placaFiltrado; + } + set + { + this._placaFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("PlacaFiltrado"); + } + } + + public List Placas + { + get + { + return this._placas; + } + set + { + this._placas = value; + base.OnPropertyChanged("Placas"); + } + } + + public Visibility PlanilhaVisibility + { + get + { + return this._planilhaVisibility; + } + set + { + this._planilhaVisibility = value; + base.OnPropertyChanged("PlanilhaVisibility"); + } + } + + public ObservableCollection Previsao + { + get + { + return this._previsao; + } + set + { + this._previsao = value; + this.Sintetic = null; + base.OnPropertyChanged("Previsao"); + } + } + + public ObservableCollection PrevisaoFiltrado + { + get + { + return this._previsaoFiltrado; + } + set + { + this._previsaoFiltrado = value; + this.SintetizarRelatorio(); + this.Sintetic = null; + base.OnPropertyChanged("PrevisaoFiltrado"); + } + } + + public ObservableCollection PrevisaoSintetico + { + get + { + return this._previsaoSintetico; + } + set + { + this._previsaoSintetico = value; + this.Sintetic = null; + base.OnPropertyChanged("PrevisaoSintetico"); + } + } + + public List Producao + { + get + { + return this._producao; + } + set + { + this._producao = value; + base.OnPropertyChanged("Producao"); + } + } + + public ObservableCollection ProducaoFiltrado + { + get + { + return this._producaoFiltrado; + } + set + { + this._producaoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("ProducaoFiltrado"); + } + } + + public List Produtos + { + get + { + return this._produtos; + } + set + { + this._produtos = value; + foreach (Gestor.Model.Domain.Seguros.Produto produto in this.Produtos) + { + produto.add_PropertyChanged(new PropertyChangedEventHandler(this.ProdutoOnPropertyChanged)); + } + base.OnPropertyChanged("Produtos"); + } + } + + public List Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + foreach (Ramo ramo in this.Ramos) + { + ramo.add_PropertyChanged(new PropertyChangedEventHandler(this.RamoOnPropertyChanged)); + } + base.OnPropertyChanged("Ramos"); + } + } + + public Ramo RamoSelecionado + { + get + { + return this._ramoSelecionado; + } + set + { + this._ramoSelecionado = value; + base.OnPropertyChanged("RamoSelecionado"); + } + } + + public ObservableCollection RamosSelecionados + { + get + { + return this._ramosSelecionados; + } + set + { + this._ramosSelecionados = value; + base.OnPropertyChanged("RamosSelecionados"); + } + } + + private bool ReciboPagamento + { + get; + set; + } + + public string Referencia + { + get + { + return this._referencia; + } + set + { + this._referencia = value; + base.OnPropertyChanged("Referencia"); + } + } + + public ObservableCollection Referencias + { + get + { + return this._referencias; + } + set + { + this._referencias = value; + base.OnPropertyChanged("Referencias"); + } + } + + public Gestor.Model.Common.Relatorio Relatorio + { + get + { + return this._relatorio; + } + set + { + this._relatorio = value; + this.WorkOnRelatorio(value); + base.OnPropertyChanged("Relatorio"); + } + } + + public List RelatorioFiltroPersonalizado + { + get + { + return this._filtroRelatorioPersonalizado; + } + set + { + this._filtroRelatorioPersonalizado = value; + base.OnPropertyChanged("RelatorioFiltroPersonalizado"); + } + } + + public List Relatorios + { + get + { + return this._relatorios; + } + set + { + this._relatorios = value; + base.OnPropertyChanged("Relatorios"); + } + } + + public bool RelatorioVisibility + { + get + { + return this._relatorioVisibility; + } + set + { + this._relatorioVisibility = value; + base.OnPropertyChanged("RelatorioVisibility"); + } + } + + public List Renovacao + { + get + { + return this._renovacao; + } + set + { + this._renovacao = value; + base.OnPropertyChanged("Renovacao"); + } + } + + public ObservableCollection RenovacaoFiltrado + { + get + { + return this._renovacaoFiltrado; + } + set + { + this._renovacaoFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("RenovacaoFiltrado"); + } + } + + public object Report + { + get + { + return this._report; + } + set + { + this._report = value; + this.FiltrosPersonalizados = (value == null || !this.PermitirFiltrosPersonalizados ? Visibility.Collapsed : Visibility.Visible); + base.OnPropertyChanged("Report"); + } + } + + public bool SegundaViaReciboPagamento + { + get + { + return this._segundaViaReciboPagamento; + } + set + { + this.LimparRelatorio(); + this._segundaViaReciboPagamento = value; + if (value) + { + this.SomenteNaoPagos = false; + } + base.OnPropertyChanged("SegundaViaReciboPagamento"); + } + } + + public List Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + foreach (Seguradora seguradora in this.Seguradoras) + { + seguradora.add_PropertyChanged(new PropertyChangedEventHandler(this.SeguradoraOnPropertyChanged)); + } + base.OnPropertyChanged("Seguradoras"); + } + } + + public int SelectedAno + { + get + { + return this._selectedAno; + } + set + { + this._selectedAno = value; + base.OnPropertyChanged("SelectedAno"); + } + } + + public Mes SelectedMes + { + get + { + return this._selectedMes; + } + set + { + this._selectedMes = value; + base.OnPropertyChanged("SelectedMes"); + } + } + + public Gestor.Model.Domain.Relatorios.ParametrosRelatorio SelectedParametrosRelatorio + { + get + { + return this._selectedParametrosRelatorio; + } + set + { + this._selectedParametrosRelatorio = value; + base.OnPropertyChanged("SelectedParametrosRelatorio"); + } + } + + public Gestor.Model.Domain.Relatorios.ParametrosTotalizacao SelectedParametrosTotalizacao + { + get + { + return this._selectedParametrosTotalizacao; + } + set + { + this._selectedParametrosTotalizacao = value; + base.OnPropertyChanged("SelectedParametrosTotalizacao"); + } + } + + public bool SemValor + { + get + { + return this._semValor; + } + set + { + this._semValor = value; + if (value) + { + this.ValorInicial = null; + this.ValorFinal = null; + } + base.OnPropertyChanged("SemValor"); + } + } + + public string Sessao + { + get; + set; + } + + public List Sinistro + { + get + { + return this._sinistro; + } + set + { + this._sinistro = value; + base.OnPropertyChanged("Sinistro"); + } + } + + public ObservableCollection SinistroFiltrado + { + get + { + return this._sinistroFiltrado; + } + set + { + this._sinistroFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("SinistroFiltrado"); + } + } + + public ObservableCollection Sintetic + { + get + { + return this._sintetic; + } + set + { + this._sintetic = value; + base.OnPropertyChanged("Sintetic"); + } + } + + public SinteticoClientes SinteticoCliente + { + get + { + return this._sinteticoCliente; + } + set + { + this._sinteticoCliente = value; + base.OnPropertyChanged("SinteticoCliente"); + } + } + + public ObservableCollection SinteticoRelatorio + { + get + { + return this._sinteticoRelatorio; + } + set + { + this._sinteticoRelatorio = value; + base.OnPropertyChanged("SinteticoRelatorio"); + this.Totais = (value == null ? false : value.Count > 0); + if (value == null || value.Count == 0) + { + return; + } + List sinteticModels = value.FirstOrDefault().ConstruirSintetico(this.Relatorio); + this.Sintetic = new ObservableCollection(sinteticModels); + } + } + + public bool SinteticosPagamento + { + get + { + return this._sinteticosPagamento; + } + set + { + this._sinteticosPagamento = value; + base.OnPropertyChanged("SinteticosPagamento"); + } + } + + public bool SomenteNaoPagos + { + get + { + return this._somenteNaoPagos; + } + set + { + this.LimparRelatorio(); + this._somenteNaoPagos = value; + if (value) + { + this.SegundaViaReciboPagamento = false; + } + base.OnPropertyChanged("SomenteNaoPagos"); + } + } + + public List Tarefa + { + get + { + return this._tarefa; + } + set + { + this._tarefa = value; + base.OnPropertyChanged("Tarefa"); + } + } + + public ObservableCollection TarefaFiltrado + { + get + { + return this._tarefaFiltrado; + } + set + { + this._tarefaFiltrado = value; + this.SintetizarRelatorio(); + base.OnPropertyChanged("TarefaFiltrado"); + } + } + + public Type TipoDateTime + { + get + { + return this._tipoDateTime; + } + set + { + this._tipoDateTime = value; + base.OnPropertyChanged("TipoDateTime"); + } + } + + public Type TipoDecimal + { + get + { + return this._tipoDecimal; + } + set + { + this._tipoDecimal = value; + base.OnPropertyChanged("TipoDecimal"); + } + } + + public Type TipoEnum + { + get + { + return this._tipoEnum; + } + set + { + this._tipoEnum = value; + base.OnPropertyChanged("TipoEnum"); + } + } + + public Type TipoInt + { + get + { + return this._tipoInt; + } + set + { + this._tipoInt = value; + base.OnPropertyChanged("TipoInt"); + } + } + + public Type TipoLong + { + get + { + return this._tipoLong; + } + set + { + this._tipoLong = value; + base.OnPropertyChanged("TipoLong"); + } + } + + public List TipoSeguros + { + get + { + return this._tipoSeguros; + } + set + { + this._tipoSeguros = value; + foreach (StatusRelatorio tipoSeguro in this.TipoSeguros) + { + tipoSeguro.add_PropertyChanged(new PropertyChangedEventHandler(this.StatusOnPropertyChanged)); + } + base.OnPropertyChanged("TipoSeguros"); + } + } + + public Type TipoString + { + get + { + return this._tipoString; + } + set + { + this._tipoString = value; + base.OnPropertyChanged("TipoString"); + } + } + + public List TipoVendedor + { + get + { + return this._tipoVendedor; + } + set + { + this._tipoVendedor = value; + foreach (Gestor.Model.Domain.Seguros.TipoVendedor tipoVendedor in this.TipoVendedor) + { + tipoVendedor.add_PropertyChanged(new PropertyChangedEventHandler(this.TipoVendedorOnPropertyChanged)); + } + base.OnPropertyChanged("TipoVendedor"); + } + } + + public bool Totais + { + get + { + return this._totais; + } + set + { + this._totais = value; + base.OnPropertyChanged("Totais"); + } + } + + public bool Totalizacao + { + get + { + return this._totalizacao; + } + set + { + this._totalizacao = value; + base.OnPropertyChanged("Totalizacao"); + } + } + + public List Usuarios + { + get; + set; + } + + public ObservableCollection UsuariosFiltrados + { + get + { + return this._usuariosFiltrados; + } + set + { + this._usuariosFiltrados = value; + base.OnPropertyChanged("UsuariosFiltrados"); + } + } + + public string ValorFinal + { + get + { + return this._valorFinal; + } + set + { + this._valorFinal = value; + base.OnPropertyChanged("ValorFinal"); + } + } + + public bool ValorIgual + { + get + { + return this._valorIgual; + } + set + { + this._valorIgual = value; + base.OnPropertyChanged("ValorIgual"); + } + } + + public string ValorInicial + { + get + { + return this._valorIncial; + } + set + { + this._valorIncial = value; + base.OnPropertyChanged("ValorInicial"); + } + } + + public List Vendedores + { + get + { + return this._vendedores; + } + set + { + this._vendedores = value; + foreach (Vendedor vendedore in this.Vendedores) + { + vendedore.add_PropertyChanged(new PropertyChangedEventHandler(this.VendedorOnPropertyChanged)); + } + base.OnPropertyChanged("Vendedores"); + } + } + + private List Vinculo + { + get; + set; + } + + public Visibility VisibilityAcompanhamento + { + get + { + return this._visibilityAcompanhamento; + } + set + { + this._visibilityAcompanhamento = value; + base.OnPropertyChanged("VisibilityAcompanhamento"); + } + } + + public Visibility VisibilityAgrupamento + { + get + { + return this._visibilityAgrupamento; + } + set + { + this._visibilityAgrupamento = value; + base.OnPropertyChanged("VisibilityAgrupamento"); + } + } + + public Visibility VisibilityApolice + { + get + { + return this._visibilityApolice; + } + set + { + this._visibilityApolice = value; + base.OnPropertyChanged("VisibilityApolice"); + } + } + + public Visibility VisibilityComparativo + { + get + { + return this._visibilityComparativo; + } + set + { + this._visibilityComparativo = value; + base.OnPropertyChanged("VisibilityComparativo"); + } + } + + public Visibility VisibilityCompleto + { + get + { + return this._visibilityCompleto; + } + set + { + this._visibilityCompleto = value; + base.OnPropertyChanged("VisibilityCompleto"); + } + } + + public Visibility VisibilityConfigurar + { + get + { + return this._visibilityConfigurar; + } + set + { + this._visibilityConfigurar = value; + base.OnPropertyChanged("VisibilityConfigurar"); + } + } + + public Visibility VisibilityData + { + get + { + return this._visibilityData; + } + set + { + this._visibilityData = value; + base.OnPropertyChanged("VisibilityData"); + } + } + + public bool VisibilityDesconsiderarNegativos + { + get + { + return this._visibilityDesconsiderarNegativos; + } + set + { + this._visibilityDesconsiderarNegativos = value; + base.OnPropertyChanged("VisibilityDesconsiderarNegativos"); + } + } + + public Visibility VisibilityDocumentoAtivo + { + get + { + return this._visibilityDocumentoAtivo; + } + set + { + this._visibilityDocumentoAtivo = value; + base.OnPropertyChanged("VisibilityDocumentoAtivo"); + } + } + + public Visibility VisibilityEmail + { + get + { + return this._visibilityEmail; + } + set + { + this._visibilityEmail = value; + base.OnPropertyChanged("VisibilityEmail"); + } + } + + public Visibility VisibilityEspecial + { + get + { + return this._visibilityEspecial; + } + set + { + this._visibilityEspecial = value; + base.OnPropertyChanged("VisibilityEspecial"); + } + } + + public Visibility VisibilityEtiqueta + { + get + { + return this._visibilityEtiqueta; + } + set + { + this._visibilityEtiqueta = value; + base.OnPropertyChanged("VisibilityEtiqueta"); + } + } + + public Visibility VisibilityExtratos + { + get + { + return this._visibilityExtratos; + } + set + { + this._visibilityExtratos = value; + base.OnPropertyChanged("VisibilityExtratos"); + } + } + + public Visibility VisibilityFiltroPersonalizado + { + get + { + return this._visibilityFiltroPersonalizado; + } + set + { + this._visibilityFiltroPersonalizado = value; + base.OnPropertyChanged("VisibilityFiltroPersonalizado"); + } + } + + public Visibility VisibilityFiltroPersonalizadoButton + { + get + { + return this._visibilityFiltroPersonalizadoButton; + } + set + { + this._visibilityFiltroPersonalizadoButton = value; + base.OnPropertyChanged("VisibilityFiltroPersonalizadoButton"); + } + } + + public Visibility VisibilityFiltros + { + get + { + return this._visibilityFiltros; + } + set + { + this._visibilityFiltros = value; + base.OnPropertyChanged("VisibilityFiltros"); + } + } + + public Visibility VisibilityGridFiltros + { + get + { + return this._visibilityGridFiltros; + } + set + { + this._visibilityGridFiltros = value; + base.OnPropertyChanged("VisibilityGridFiltros"); + } + } + + public bool VisibilityHtml + { + get + { + return this._visibilityHtml; + } + set + { + this._visibilityHtml = value; + base.OnPropertyChanged("VisibilityHtml"); + } + } + + public Visibility VisibilityMaisFiltros + { + get + { + return this._visibilityMaisFiltros; + } + set + { + this._visibilityMaisFiltros = value; + base.OnPropertyChanged("VisibilityMaisFiltros"); + } + } + + public Visibility VisibilityMeta + { + get + { + return this._visibilityMeta; + } + set + { + this._visibilityMeta = value; + base.OnPropertyChanged("VisibilityMeta"); + } + } + + public Visibility VisibilityNotaFiscalPorSeguradora + { + get + { + return this._visibilityNotaFiscalPorSeguradora; + } + set + { + this._visibilityNotaFiscalPorSeguradora = value; + base.OnPropertyChanged("VisibilityNotaFiscalPorSeguradora"); + } + } + + public Visibility VisibilityOlho + { + get + { + return this._visibilityOlho; + } + set + { + this._visibilityOlho = value; + base.OnPropertyChanged("VisibilityOlho"); + } + } + + public Visibility VisibilityOpcoesFiltros + { + get + { + return this._visibilityOpcoesFiltros; + } + set + { + this._visibilityOpcoesFiltros = value; + base.OnPropertyChanged("VisibilityOpcoesFiltros"); + } + } + + public Visibility VisibilityOrdem + { + get + { + return this._visibilityOrdem; + } + set + { + this._visibilityOrdem = value; + base.OnPropertyChanged("VisibilityOrdem"); + } + } + + public Visibility VisibilityPagamento + { + get + { + return this._visibilityPagamento; + } + set + { + this._visibilityPagamento = value; + base.OnPropertyChanged("VisibilityPagamento"); + } + } + + public Visibility VisibilityReferencia + { + get + { + return this._visibilityReferencia; + } + set + { + this._visibilityReferencia = value; + base.OnPropertyChanged("VisibilityReferencia"); + } + } + + public Visibility VisibilitySemValor + { + get + { + return this._visibilitySemValor; + } + set + { + this._visibilitySemValor = value; + base.OnPropertyChanged("VisibilitySemValor"); + } + } + + public Visibility VisibilitySintetizar + { + get + { + return this._visibilitySintetizar; + } + set + { + this._visibilitySintetizar = value; + base.OnPropertyChanged("VisibilitySintetizar"); + } + } + + public Visibility VisibilityTarefas + { + get + { + return this._visibilityTarefas; + } + set + { + this._visibilityTarefas = value; + base.OnPropertyChanged("VisibilityTarefas"); + } + } + + public bool VisibilityUsuarios + { + get + { + return this._visibilityUsuarios; + } + set + { + this._visibilityUsuarios = value; + base.OnPropertyChanged("VisibilityUsuarios"); + } + } + + public Visibility VisibilityValor + { + get + { + return this._visibilityValor; + } + set + { + this._visibilityValor = value; + base.OnPropertyChanged("VisibilityValor"); + } + } + + public Visibility VisibiltyProtocolo + { + get + { + return this._visibiltyProtocolo; + } + set + { + this._visibiltyProtocolo = value; + base.OnPropertyChanged("VisibiltyProtocolo"); + } + } + + public Visibility VisibiltySincronizar + { + get + { + return this._visibiltySincronizar; + } + set + { + this._visibiltySincronizar = value; + base.OnPropertyChanged("VisibiltySincronizar"); + } + } + + static RelatorioViewModel() + { + List negocioRelatorios = new List(); + NegocioRelatorio negocioRelatorio = new NegocioRelatorio(); + negocioRelatorio.set_Id(0); + negocioRelatorio.set_Selecionado(false); + negocioRelatorio.set_Negocio(0); + negocioRelatorios.Add(negocioRelatorio); + NegocioRelatorio negocioRelatorio1 = new NegocioRelatorio(); + negocioRelatorio1.set_Id(1); + negocioRelatorio1.set_Selecionado(false); + negocioRelatorio1.set_Negocio(1); + negocioRelatorios.Add(negocioRelatorio1); + RelatorioViewModel.NegocioList = negocioRelatorios; + List statusRelatorios = new List(); + StatusRelatorio statusRelatorio = new StatusRelatorio(); + statusRelatorio.set_Id(1); + statusRelatorio.set_Selecionado(false); + statusRelatorio.set_Status(1); + statusRelatorios.Add(statusRelatorio); + StatusRelatorio statusRelatorio1 = new StatusRelatorio(); + statusRelatorio1.set_Id(2); + statusRelatorio1.set_Selecionado(false); + statusRelatorio1.set_Status(2); + statusRelatorios.Add(statusRelatorio1); + StatusRelatorio statusRelatorio2 = new StatusRelatorio(); + statusRelatorio2.set_Id(3); + statusRelatorio2.set_Selecionado(false); + statusRelatorio2.set_Status(3); + statusRelatorios.Add(statusRelatorio2); + StatusRelatorio statusRelatorio3 = new StatusRelatorio(); + statusRelatorio3.set_Id(4); + statusRelatorio3.set_Selecionado(false); + statusRelatorio3.set_Status(7); + statusRelatorios.Add(statusRelatorio3); + StatusRelatorio statusRelatorio4 = new StatusRelatorio(); + statusRelatorio4.set_Id(5); + statusRelatorio4.set_Selecionado(false); + statusRelatorio4.set_Status(5); + statusRelatorios.Add(statusRelatorio4); + StatusRelatorio statusRelatorio5 = new StatusRelatorio(); + statusRelatorio5.set_Id(6); + statusRelatorio5.set_Selecionado(false); + statusRelatorio5.set_Status(6); + statusRelatorios.Add(statusRelatorio5); + StatusRelatorio statusRelatorio6 = new StatusRelatorio(); + statusRelatorio6.set_Id(7); + statusRelatorio6.set_Selecionado(false); + statusRelatorio6.set_Status(4); + statusRelatorios.Add(statusRelatorio6); + RelatorioViewModel.TipoSegurosList = statusRelatorios; + } + + public RelatorioViewModel(string opcao) + { + this.funcProducaoDistinctByDocumentoId = (Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Id(); + this.funcProducaoSegurosNovos = (Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Situacao() == 1; + this.funcProducaoSegurosRenovacao = (Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_Situacao() == 2; + this.funcProducaoNegociosNovos = (Gestor.Model.Domain.Relatorios.Producao.Producao p) => { + NegocioCorretora? negocioCorretora = p.get_Documento().get_NegocioCorretora(); + return negocioCorretora.GetValueOrDefault() == 0 & negocioCorretora.HasValue; + }; + this.funcProducaoNegociosProprios = (Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_Documento().get_NegocioCorretora().GetValueOrDefault() == 1; + this._totalizacao = true; + this._relatorios = new List(); + this._relatorio = 2; + this._filtrosPersonalizados = Visibility.Collapsed; + this._visibilityDesconsiderarNegativos = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 50); + this._visibilityReferencia = Visibility.Collapsed; + this._visibilityOrdem = Visibility.Collapsed; + this._referencias = new ObservableCollection(); + this._ordens = new ObservableCollection(); + DateTime date = Funcoes.GetNetworkTime().Date; + this._inicio = date.AddMonths(-1); + this._fim = Funcoes.GetNetworkTime().Date; + this._infoVisibility = Visibility.Collapsed; + this._erroRelatorio = "NÃO HÁ DADOS NO PERÍODO E FILTROS SELECIONADOS."; + this.ColunasOcultas = new List(); + this._seguradoras = ( + from x in Recursos.Seguradoras + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList(); + this._ramos = ( + from x in Recursos.Ramos + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList(); + this._notasFiscais = new List(); + this._inativo = true; + this._vendedores = new List(); + this._tipoVendedor = ( + from x in Recursos.TipoVendedor + where x.get_Ativo().GetValueOrDefault() + orderby x.get_Descricao() + select x).ToList(); + this._produtos = ( + from x in Recursos.Produtos + where x.get_Ativo() + orderby x.get_Nome() + select x).ToList(); + this._estipulantes = Recursos.Estipulantes.Where((Estipulante x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && Recursos.Usuario.get_IdEmpresa() != x.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }).OrderBy((Estipulante x) => x.get_Nome()).ToList(); + this._negocios = RelatorioViewModel.NegocioList; + this._tipoSeguros = RelatorioViewModel.TipoSegurosList; + this._isVisibleGrid1 = true; + this._isVisibleGrid2 = true; + this._isVisibleGrid3 = true; + this._isVisibleGrid4 = true; + this._tipoString = typeof(string); + this._tipoEnum = typeof(Enum); + this._tipoDateTime = typeof(DateTime); + this._tipoDecimal = typeof(decimal); + this._tipoInt = typeof(int); + this._tipoLong = typeof(long); + this._valorIncial = ""; + this._valorFinal = ""; + this._visibilitySemValor = Visibility.Collapsed; + this._visibilityOpcoesFiltros = Visibility.Collapsed; + this._filtroRelatorioSelecionado = new ObservableCollection(); + this._visibilityFiltroPersonalizado = Visibility.Collapsed; + List filtroTipoParcelas = new List(); + FiltroTipoParcela filtroTipoParcela = new FiltroTipoParcela(); + filtroTipoParcela.set_Selecionado(true); + filtroTipoParcela.set_Tipo(1); + filtroTipoParcelas.Add(filtroTipoParcela); + FiltroTipoParcela filtroTipoParcela1 = new FiltroTipoParcela(); + filtroTipoParcela1.set_Selecionado(true); + filtroTipoParcela1.set_Tipo(6); + filtroTipoParcelas.Add(filtroTipoParcela1); + FiltroTipoParcela filtroTipoParcela2 = new FiltroTipoParcela(); + filtroTipoParcela2.set_Selecionado(true); + filtroTipoParcela2.set_Tipo(3); + filtroTipoParcelas.Add(filtroTipoParcela2); + FiltroTipoParcela filtroTipoParcela3 = new FiltroTipoParcela(); + filtroTipoParcela3.set_Selecionado(true); + filtroTipoParcela3.set_Tipo(2); + filtroTipoParcelas.Add(filtroTipoParcela3); + FiltroTipoParcela filtroTipoParcela4 = new FiltroTipoParcela(); + filtroTipoParcela4.set_Selecionado(true); + filtroTipoParcela4.set_Tipo(5); + filtroTipoParcelas.Add(filtroTipoParcela4); + FiltroTipoParcela filtroTipoParcela5 = new FiltroTipoParcela(); + filtroTipoParcela5.set_Selecionado(true); + filtroTipoParcela5.set_Tipo(4); + filtroTipoParcelas.Add(filtroTipoParcela5); + this._parcelasEspeciais = filtroTipoParcelas; + this._ajuda = new ObservableCollection(); + this._isCampo = true; + this._usuariosFiltrados = new ObservableCollection(); + base(); + this._apoliceServico = new ApoliceServico(); + this._parcelaServico = new ParcelaServico(); + this._sinistroServico = new SinistroServico(); + this._clienteServico = new ClienteServico(); + this._logServico = new LogServico(); + this._extratoServico = new ServicoExtrato(); + this._metaSeguradoraServico = new MetaSeguradoraServico(); + this._metaVendedorServico = new MetaVendedorServico(); + this._notaFiscalServico = new NotaFiscalServico(); + this._criticaServico = new CriticaApoliceServico(); + this.Sessao = Guid.NewGuid().ToString(); + base.IsEnabled = true; + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + List list = ( + from x in Recursos.Empresas + orderby x.get_Id() + select x).ToList(); + Gestor.Model.Domain.Common.Empresa empresa = new Gestor.Model.Domain.Common.Empresa(); + empresa.set_Id((long)0); + empresa.set_Nome("TODAS, MATRIZ E FILIAIS"); + list.Insert(0, empresa); + this.Empresas = list; + this.Empresa = (Recursos.Usuario.get_IdEmpresa() <= (long)1 ? this.Empresas.First() : this.Empresas.Find((Gestor.Model.Domain.Common.Empresa x) => x.get_Id() == Recursos.Usuario.get_IdEmpresa())); + this.EnableEmpresa = Recursos.Usuario.get_IdEmpresa() <= (long)1; + base.EnableMenu = true; + this.LoadVendedores(); + this.PopularRelatorio(opcao); + } + + public async Task Acompanhamento() + { + Trilha trilha; + List tarefas; + if (this.RenovacaoFiltrado != null && this.RenovacaoFiltrado.Count != 0) + { + ObservableCollection renovacaoFiltrado = this.RenovacaoFiltrado; + if (!renovacaoFiltrado.All((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => !x.get_Selecionado())) + { + Trilha trilha1 = new Trilha(); + trilha1.set_Ativo(true); + trilha1.set_Titulo("ACOMPANHAMENTO DE RENOVAÇÃO"); + trilha1.set_Tipo(0); + List fases = new List(); + Fase fase = new Fase(); + fase.set_Titulo("A RENOVAR"); + fases.Add(fase); + Fase fase1 = new Fase(); + fase1.set_Titulo("EM RENOVAÇÃO"); + fases.Add(fase1); + Fase fase2 = new Fase(); + fase2.set_Titulo("RENOVADOS"); + fases.Add(fase2); + Fase fase3 = new Fase(); + fase3.set_Titulo("PERDIDOS"); + fases.Add(fase3); + trilha1.set_Fases(fases); + trilha = trilha1; + trilha = await this.SalvarTrilha(trilha); + if (trilha != null) + { + tarefas = await (new TarefaServico()).BuscarTarefas(trilha.get_Id()); + ObservableCollection observableCollection = this.RenovacaoFiltrado; + foreach (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao renovacao in + from x in observableCollection + where x.get_Selecionado() + select x) + { + if (tarefas.Any((Gestor.Model.Domain.Ferramentas.Tarefa x) => x.get_IdEntidade() == renovacao.get_Documento().get_Id())) + { + continue; + } + Gestor.Model.Domain.Ferramentas.Tarefa tarefa = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa.set_Entidade(0); + tarefa.set_IdEntidade(renovacao.get_Documento().get_Id()); + tarefa.set_IdCliente(renovacao.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa.set_Cliente(renovacao.get_Cliente()); + tarefa.set_Titulo(string.Concat("APÓLICE NÚMERO ", renovacao.get_Apolice())); + tarefa.set_Usuario(Recursos.Usuario); + tarefa.set_Agendamento(Funcoes.GetNetworkTime()); + tarefa.set_Trilha(trilha); + tarefa.set_Fase(trilha.get_Fases().First()); + object[] vigenciaFinal = new object[] { renovacao.get_VigenciaFinal(), renovacao.get_Seguradora(), renovacao.get_Ramo(), renovacao.get_Item() }; + tarefa.set_Referencia(string.Format("VIGÊNCIA FINAL: {0}\nSEGURADORA: {1}\nRAMO: {2}\nITEM: {3}", vigenciaFinal)); + await (new TarefaServico()).Salvar(tarefa); + } + if (Funcoes.IsWindowOpen("ACOMPANHAMENTO DE RENOVAÇÃO")) + { + Funcoes.Destroy("ACOMPANHAMENTO DE RENOVAÇÃO"); + } + (new HosterWindow(new AcompanhamentoView(), "ACOMPANHAMENTO DE RENOVAÇÃO", new double?((double)910), new double?((double)600), true)).Show(); + trilha = null; + tarefas = null; + return; + } + else + { + trilha = null; + tarefas = null; + return; + } + } + } + await base.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM ITEM NA LISTA PARA GERAR O ACOMPANHAMENTO.", "OK", "", false); + trilha = null; + tarefas = null; + } + + public async void AdcionarFiltroPersonalizado() + { + string str; + DateTime dateTime; + decimal num; + int num1; + long num2; + List filtroPersonalizados; + List filtroPersonalizados1; + if (this.FiltroPersonalizado != null) + { + if (this.SemValor) + { + filtroPersonalizados = (this.FiltroPersonalizadoSelecionado == null ? new List() : ( + from x in this.FiltroPersonalizadoSelecionado + where x.get_Propriedade() == this.FiltroPersonalizado.get_Propriedade() + select x).ToList()); + List filtroPersonalizados2 = filtroPersonalizados; + if (filtroPersonalizados2.Count > 0) + { + filtroPersonalizados2.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.FiltroPersonalizadoSelecionado.Remove(x)); + } + str = string.Concat(this.FiltroPersonalizado.get_Nome(), ": EM BRANCO"); + } + else + { + filtroPersonalizados1 = (this.FiltroPersonalizadoSelecionado == null ? new List() : this.FiltroPersonalizadoSelecionado.Where((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => { + if (x.get_Propriedade() != this.FiltroPersonalizado.get_Propriedade()) + { + return false; + } + return x.get_SemValor(); + }).ToList()); + List filtroPersonalizados3 = filtroPersonalizados1; + if (filtroPersonalizados3.Count > 0) + { + filtroPersonalizados3.ForEach((Gestor.Model.Domain.Relatorios.FiltroPersonalizado x) => this.FiltroPersonalizadoSelecionado.Remove(x)); + } + string name = this.FiltroPersonalizado.get_Tipo().Name; + if (name == "DateTime") + { + if (!DateTime.TryParse(this.ValorInicial, out dateTime) || !DateTime.TryParse(this.ValorFinal, out dateTime) || DateTime.Parse(this.ValorInicial) > DateTime.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:d} até {2:d}", this.FiltroPersonalizado.get_Nome(), DateTime.Parse(this.ValorInicial), DateTime.Parse(this.ValorFinal)); + } + } + else if (name == "Decimal") + { + if (!decimal.TryParse(this.ValorInicial, out num) || !decimal.TryParse(this.ValorFinal, out num) || decimal.Parse(this.ValorInicial) > decimal.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n2} até {2:n2}", this.FiltroPersonalizado.get_Nome(), decimal.Parse(this.ValorInicial), decimal.Parse(this.ValorFinal)); + } + } + else if (name == "Int32") + { + if (!int.TryParse(this.ValorInicial, out num1) || !int.TryParse(this.ValorFinal, out num1) || int.Parse(this.ValorInicial) > int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.FiltroPersonalizado.get_Nome(), int.Parse(this.ValorInicial), int.Parse(this.ValorFinal)); + } + } + else if (name != "Int64") + { + if (!string.IsNullOrEmpty(this.ValorInicial)) + { + str = string.Concat(this.FiltroPersonalizado.get_Nome(), " = ", this.ValorInicial); + } + else + { + await base.ShowMessage("O VALOR DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + } + else if (!long.TryParse(this.ValorInicial, out num2) || !long.TryParse(this.ValorFinal, out num2) || long.Parse(this.ValorInicial) > (long)int.Parse(this.ValorFinal)) + { + await base.ShowMessage("O VALOR DE INTERVALO DEVE SER PREENCHIDO CORRETAMENTE.", "OK", "", false); + return; + } + else + { + str = string.Format("{0}: {1:n0} até {2:n0}", this.FiltroPersonalizado.get_Nome(), long.Parse(this.ValorInicial), long.Parse(this.ValorFinal)); + } + } + if (this.FiltroPersonalizadoSelecionado == null) + { + this.FiltroPersonalizadoSelecionado = new ObservableCollection(); + } + ObservableCollection filtroPersonalizadoSelecionado = this.FiltroPersonalizadoSelecionado; + Gestor.Model.Domain.Relatorios.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Relatorios.FiltroPersonalizado(); + filtroPersonalizado.set_Nome(this.FiltroPersonalizado.get_Nome()); + filtroPersonalizado.set_Propriedade(this.FiltroPersonalizado.get_Propriedade()); + filtroPersonalizado.set_Tipo(this.FiltroPersonalizado.get_Tipo()); + filtroPersonalizado.set_ValorIncial(this.ValorInicial); + filtroPersonalizado.set_ValorFinal(this.ValorFinal); + filtroPersonalizado.set_SemValor(this.SemValor); + filtroPersonalizado.set_Descricao(str); + filtroPersonalizadoSelecionado.Add(filtroPersonalizado); + this.FiltroPersonalizado = null; + this.ValorInicial = string.Empty; + this.ValorFinal = string.Empty; + this.PesquisaPersonalizada(); + } + } + + public void AdicionarFiltro(FiltroRelatorio filtro) + { + if (filtro == null) + { + return; + } + if (this.FiltroRelatorioSelecionado == null) + { + this.FiltroRelatorioSelecionado = new ObservableCollection(); + } + if (this.FiltroRelatorioSelecionado.Any((FiltroRelatorio x) => { + if (x.get_Id() != filtro.get_Id()) + { + return false; + } + return x.get_Tipo() == filtro.get_Tipo(); + })) + { + return; + } + this.FiltroRelatorioSelecionado.Add(filtro); + switch (filtro.get_Tipo()) + { + case 0: + { + Seguradora seguradora = this.Seguradoras.FirstOrDefault((Seguradora x) => x.get_Id() == filtro.get_Id()); + if (seguradora == null) + { + break; + } + seguradora.set_Selecionado(true); + return; + } + case 1: + { + Ramo ramo = this.Ramos.FirstOrDefault((Ramo x) => x.get_Id() == filtro.get_Id()); + if (ramo == null) + { + break; + } + ramo.set_Selecionado(true); + return; + } + case 2: + { + Vendedor vendedor = this.Vendedores.FirstOrDefault((Vendedor x) => x.get_Id() == filtro.get_Id()); + if (vendedor == null) + { + break; + } + vendedor.set_Selecionado(true); + return; + } + case 3: + { + Estipulante estipulante = this.Estipulantes.FirstOrDefault((Estipulante x) => x.get_Id() == filtro.get_Id()); + if (estipulante == null) + { + break; + } + estipulante.set_Selecionado(true); + return; + } + case 4: + { + Gestor.Model.Domain.Seguros.Produto produto = this.Produtos.FirstOrDefault((Gestor.Model.Domain.Seguros.Produto x) => x.get_Id() == filtro.get_Id()); + if (produto == null) + { + break; + } + produto.set_Selecionado(true); + return; + } + case 5: + { + StatusRelatorio statusRelatorio = this.TipoSeguros.FirstOrDefault((StatusRelatorio x) => (long)x.get_Status() == filtro.get_Id()); + if (statusRelatorio == null) + { + break; + } + statusRelatorio.set_Selecionado(true); + return; + } + case 6: + { + Gestor.Model.Domain.Seguros.TipoVendedor tipoVendedor = this.TipoVendedor.FirstOrDefault((Gestor.Model.Domain.Seguros.TipoVendedor x) => x.get_Id() == filtro.get_Id()); + if (tipoVendedor == null) + { + break; + } + tipoVendedor.set_Selecionado(true); + return; + } + case 7: + { + NegocioRelatorio negocioRelatorio = this.Negocios.FirstOrDefault((NegocioRelatorio x) => (long)x.get_Id() == filtro.get_Id()); + if (negocioRelatorio == null) + { + break; + } + negocioRelatorio.set_Selecionado(true); + break; + } + default: + { + return; + } + } + } + + public void AdicionarFiltros() + { + List filtroRelatorios = new List(); + List list = ( + from x in this.Seguradoras + where x.get_Selecionado() + select x).Select((Seguradora x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Nome()); + filtroRelatorio.set_Tipo(0); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.Ramos + where x.get_Selecionado() + select x).Select((Ramo x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Nome()); + filtroRelatorio.set_Tipo(1); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.Vendedores + where x.get_Selecionado() + select x).Select((Vendedor x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Nome()); + filtroRelatorio.set_Tipo(2); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.TipoVendedor + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Seguros.TipoVendedor x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Descricao()); + filtroRelatorio.set_Tipo(6); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.Estipulantes + where x.get_Selecionado() + select x).Select((Estipulante x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Nome()); + filtroRelatorio.set_Tipo(3); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.Produtos + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Seguros.Produto x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id(x.get_Id()); + filtroRelatorio.set_Descricao(x.get_Nome()); + filtroRelatorio.set_Tipo(4); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.TipoSeguros + where x.get_Selecionado() + select x).Select((StatusRelatorio x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id((long)x.get_Status()); + filtroRelatorio.set_Descricao(EnumHelper.GetDescription(x.get_Status())); + filtroRelatorio.set_Tipo(5); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + list = ( + from x in this.Negocios + where x.get_Selecionado() + select x).Select((NegocioRelatorio x) => { + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id((long)x.get_Negocio()); + filtroRelatorio.set_Descricao(EnumHelper.GetDescription(x.get_Negocio())); + filtroRelatorio.set_Tipo(7); + return filtroRelatorio; + }).ToList(); + filtroRelatorios.AddRange(list); + this.FiltroRelatorioSelecionado = new ObservableCollection(filtroRelatorios); + } + + public void AdicionarParametro(Gestor.Model.Domain.Relatorios.ParametrosRelatorio parametro) + { + if (parametro != null && parametro.get_Header() != "SELECIONE UM CAMPO") + { + this.ParametrosRelatorio.Remove(parametro); + this.ParametrosRelatorioAdicionados.Add(parametro); + this.SelectedParametrosRelatorio = this.ParametrosRelatorio[0]; + } + } + + public void AdicionarRamo() + { + if (this.RamoSelecionado == null) + { + return; + } + if (this.RamosSelecionados == null) + { + this.RamosSelecionados = new ObservableCollection(); + } + if (this.RamosSelecionados.All((Ramo x) => x.get_Id() != this.RamoSelecionado.get_Id())) + { + this.RamosSelecionados.Add(this.RamoSelecionado); + } + this.RamoSelecionado = null; + this.FiltrarRamo(); + } + + public void AdicionarTotalizacao(Gestor.Model.Domain.Relatorios.ParametrosTotalizacao parametro) + { + if (parametro != null && parametro.get_Header() != "SELECIONE UMA TOTALIZAÇÃO") + { + this.ParametrosTotalizacao.Remove(parametro); + this.ParametrosTotalizacaoAdicionados.Add(parametro); + this.SelectedParametrosTotalizacao = this.ParametrosTotalizacao[0]; + } + } + + private void AllSelectedChanged(int tipo) + { + if (this._allSelectedChanging) + { + return; + } + try + { + this._alterandoFiltros = true; + this._allSelectedChanging = true; + switch (tipo) + { + case 0: + { + if (this.AllSelectedSeguradora.HasValue) + { + List.Enumerator enumerator = this.Seguradoras.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + enumerator.Current.set_Selecionado(this.AllSelectedSeguradora.Value); + } + break; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + } + else + { + return; + } + break; + } + case 1: + { + if (this.AllSelectedRamo.HasValue) + { + List.Enumerator enumerator1 = this.Ramos.GetEnumerator(); + try + { + while (enumerator1.MoveNext()) + { + enumerator1.Current.set_Selecionado(this.AllSelectedRamo.Value); + } + break; + } + finally + { + ((IDisposable)enumerator1).Dispose(); + } + } + else + { + return; + } + break; + } + case 2: + { + if (this.AllSelectedVendedor.HasValue) + { + List.Enumerator enumerator2 = this.Vendedores.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + enumerator2.Current.set_Selecionado(this.AllSelectedVendedor.Value); + } + break; + } + finally + { + ((IDisposable)enumerator2).Dispose(); + } + } + else + { + return; + } + break; + } + case 3: + { + if (this.AllSelectedStatus.HasValue) + { + List.Enumerator enumerator3 = this.TipoSeguros.GetEnumerator(); + try + { + while (enumerator3.MoveNext()) + { + enumerator3.Current.set_Selecionado(this.AllSelectedStatus.Value); + } + break; + } + finally + { + ((IDisposable)enumerator3).Dispose(); + } + } + else + { + return; + } + break; + } + case 4: + { + if (this.AllSelectedTipoVendedor.HasValue) + { + List.Enumerator enumerator4 = this.TipoVendedor.GetEnumerator(); + try + { + while (enumerator4.MoveNext()) + { + enumerator4.Current.set_Selecionado(this.AllSelectedTipoVendedor.Value); + } + break; + } + finally + { + ((IDisposable)enumerator4).Dispose(); + } + } + else + { + return; + } + break; + } + case 5: + { + if (this.AllSelectedNegocio.HasValue) + { + List.Enumerator enumerator5 = this.Negocios.GetEnumerator(); + try + { + while (enumerator5.MoveNext()) + { + enumerator5.Current.set_Selecionado(this.AllSelectedNegocio.Value); + } + break; + } + finally + { + ((IDisposable)enumerator5).Dispose(); + } + } + else + { + return; + } + break; + } + case 6: + { + if (this.AllSelectedProduto.HasValue) + { + List.Enumerator enumerator6 = this.Produtos.GetEnumerator(); + try + { + while (enumerator6.MoveNext()) + { + enumerator6.Current.set_Selecionado(this.AllSelectedProduto.Value); + } + break; + } + finally + { + ((IDisposable)enumerator6).Dispose(); + } + } + else + { + return; + } + break; + } + case 7: + { + if (this.AllSelectedEstipulante.HasValue) + { + List.Enumerator enumerator7 = this.Estipulantes.GetEnumerator(); + try + { + while (enumerator7.MoveNext()) + { + enumerator7.Current.set_Selecionado(this.AllSelectedEstipulante.Value); + } + break; + } + finally + { + ((IDisposable)enumerator7).Dispose(); + } + } + else + { + return; + } + break; + } + } + this._alterandoFiltros = false; + this.AdicionarFiltros(); + } + finally + { + this._allSelectedChanging = false; + } + } + + public void Bind() + { + ((GridRelatorio)this.Report).DataGrid.CancelEdit(); + ((GridRelatorio)this.Report).DataGrid.CancelEdit(); + switch (this.Relatorio) + { + case 0: + case 1: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ClientesAtivosInativosFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 2: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ProducaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 3: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ApolicePendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 4: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.RenovacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 5: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ComissaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 6: + case 16: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.PendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 7: + case 11: + case 20: + case 21: + case 22: + { + return; + } + case 8: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.AuditoriaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 9: + case 10: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.SinistroFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 12: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.FaturaPendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 13: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ExtratosFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 14: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.MetaSeguradoraFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 15: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.MetaVendedorFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 17: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LicenciamentoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 18: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.TarefaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 19: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.NotaFiscalFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 23: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LogsEnvioFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 24: + case 25: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LogUtilizacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 26: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ApoliceCriticaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 27: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.PlacaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 28: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.EndossoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 29: + { + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ClassificacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + default: + { + return; + } + } + } + + public async Task CarregarAjuda() + { + if (!this.Ajuda.Any((AjudaTela x) => x.get_Tela() == int.Parse(EnumHelper.GetOldValue(this.Relatorio)))) + { + this.CarregandoAjuda = true; + List ajudaTelas = await Gestor.Application.Helpers.Connection.Get>(string.Format("Help/{0}", int.Parse(EnumHelper.GetOldValue(this.Relatorio))), true, false); + if (ajudaTelas != null) + { + this.Ajuda = new ObservableCollection(ajudaTelas); + this.CarregandoAjuda = false; + } + } + } + + public async Task CarregarConfiguracoes() + { + List parametrosRelatorios = new List(); + List parametrosRelatorios1 = await (new ConfuguracoesServico()).BuscarParametros(this.Relatorio); + switch (this.Relatorio) + { + case 0: + case 1: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 2: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 3: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 4: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 5: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 6: + case 16: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 7: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 8: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 9: + case 10: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 11: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 12: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 13: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 14: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 15: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 17: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 18: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 19: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 20: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 21: + case 22: + { + this.ParametrosRelatorio = new ObservableCollection(parametrosRelatorios); + RelatorioViewModel observableCollection = this; + List parametrosRelatorios2 = parametrosRelatorios1; + observableCollection.ParametrosRelatorioAdicionados = new ObservableCollection( + from x in parametrosRelatorios2 + orderby x.get_Ordem() + select x); + List parametrosTotalizacaos = await (new ConfuguracoesServico()).BuscarParametroTotalizacaoAsync(this.Relatorio); + this.ParametrosTotalizacao = new ObservableCollection(Funcoes.TotalizacoesRelatorio(this.Relatorio, parametrosTotalizacaos)); + this.ParametrosTotalizacaoAdicionados = new ObservableCollection(parametrosTotalizacaos); + break; + } + case 23: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 24: + case 25: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 26: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 27: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 28: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + case 29: + { + parametrosRelatorios = Funcoes.ColunasRelatorio(this.Relatorio, parametrosRelatorios1); + goto case 22; + } + default: + { + goto case 22; + } + } + parametrosRelatorios = null; + } + + public async Task> CriarLista() + { + List malaDiretas1 = await Task.Run>(() => { + Gestor.Model.Common.Relatorio relatorio = this.Relatorio; + switch (relatorio) + { + case 0: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + return ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + MalaDireta malaDiretum = new MalaDireta(); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Id()); + cliente.set_Nome(x.get_Nome()); + cliente.set_Nascimento(x.get_Nascimento()); + cliente.set_Documento(x.get_Documento()); + cliente.set_VencimentoHabilitacao(x.get_VencimentoCnh()); + cliente.set_NomeSocialRg(x.get_EntidadeCliente().get_NomeSocialRg()); + cliente.set_MalaDireta(x.get_EntidadeCliente().get_MalaDireta()); + malaDiretum.set_Cliente(cliente); + malaDiretum.set_Tela(1); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 1: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + return ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + MalaDireta malaDiretum = new MalaDireta(); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Id()); + cliente.set_Nome(x.get_Nome()); + cliente.set_Nascimento(x.get_Nascimento()); + cliente.set_Documento(x.get_Documento()); + cliente.set_VencimentoHabilitacao(x.get_VencimentoCnh()); + cliente.set_MalaDireta(x.get_EntidadeCliente().get_MalaDireta()); + malaDiretum.set_Cliente(cliente); + malaDiretum.set_Tela(1); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 2: + { + if (this.ProducaoFiltrado != null && this.ProducaoFiltrado.Count != 0) + { + if (this.ProducaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + })) + { + return this.ProducaoFiltrado.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + }).Select((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Tela(2); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 3: + { + if (this.ApolicePendenteFiltrado != null && this.ApolicePendenteFiltrado.Count != 0) + { + if (this.ApolicePendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + })) + { + return this.ApolicePendenteFiltrado.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + }).Select((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Tela(2); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 4: + { + if (this.RenovacaoFiltrado != null && this.RenovacaoFiltrado.Count != 0) + { + if (this.RenovacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List list = this.RenovacaoFiltrado.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + }).Select((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + malaDiretum.set_Tela(2); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + List malaDiretas = this.RenovacaoFiltrado.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Prospeccao() != null; + }).Select((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + MalaDireta malaDiretum = new MalaDireta(); + Cliente cliente = new Cliente(); + cliente.set_Nome(x.get_Prospeccao().get_Nome()); + cliente.set_Id((long)0); + malaDiretum.set_Cliente(cliente); + malaDiretum.set_Prospeccao(x.get_Prospeccao()); + malaDiretum.set_Tela(33); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + if (malaDiretas.Count > 0) + { + list.AddRange(malaDiretas); + } + return list; + } + } + return new List(); + } + case 5: + { + if (this.ComissaoFiltrado != null && this.ComissaoFiltrado.Count != 0) + { + if (this.ComissaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + })) + { + return this.ComissaoFiltrado.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + }).Select((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + malaDiretum.set_Parcela(x.get_ParcelaEntity()); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Tela(5); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 6: + case 16: + { + if (this.PendenteFiltrado != null && this.PendenteFiltrado.Count != 0) + { + if (this.PendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + })) + { + return this.PendenteFiltrado.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Documento() != null; + }).Select((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Parcela(x.get_ParcelaEntity()); + malaDiretum.set_Tela(5); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 7: + case 8: + case 11: + case 12: + case 13: + case 14: + case 15: + { + return null; + } + case 9: + case 10: + { + if (this.SinistroFiltrado != null && this.SinistroFiltrado.Count != 0) + { + if (this.SinistroFiltrado.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + return ( + from x in this.SinistroFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + malaDiretum.set_Item(item); + malaDiretum.set_Sinistro(x.get_EntidadeSinistro()); + malaDiretum.set_Tela(7); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + case 17: + { + if (this.LicenciamentoFiltrado != null && this.LicenciamentoFiltrado.Count != 0) + { + if (this.LicenciamentoFiltrado.Any((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => x.get_Selecionado())) + { + return ( + from x in this.LicenciamentoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Documento()); + malaDiretum.set_Item(x.get_EntidadeItem()); + malaDiretum.set_Tela(3); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + default: + { + if (relatorio == 26) + { + if (this.ApoliceCriticaFiltrado != null && this.ApoliceCriticaFiltrado.Count != 0) + { + if (this.ApoliceCriticaFiltrado.Any((Gestor.Model.Domain.Relatorios.CriticaApolice.ApoliceCritica x) => x.get_Selecionado())) + { + return ( + from x in this.ApoliceCriticaFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.CriticaApolice.ApoliceCritica x) => { + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(x.get_Critica().get_Documento().get_Controle().get_Cliente()); + malaDiretum.set_Apolice(x.get_Critica().get_Documento()); + malaDiretum.set_Tela(2); + Item item = new Item(); + item.set_Descricao((x.get_Critica().get_Documento().get_ItensAtivo() != null ? (x.get_Critica().get_Documento().get_ItensAtivo().Count > 1 ? "APÓLICE COLETIVA" : (x.get_Critica().get_Documento().get_ItensAtivo().Count == 1 ? x.get_Critica().get_Documento().get_ItensAtivo().First().get_Descricao() : "")) : "")); + malaDiretum.set_Item(item); + malaDiretum.set_Relatorio(this.Relatorio); + return malaDiretum; + }).ToList(); + } + } + return new List(); + } + return null; + } + } + }); + return malaDiretas1; + } + + public async Task> CriarListaEtiqueta() + { + List documentos = await Task.Run>(() => { + switch (this.Relatorio) + { + case 0: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + return ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + Documento documento = new Documento(); + Controle controle = new Controle(); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Id()); + cliente.set_Nome(x.get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 1: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + return ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + Documento documento = new Documento(); + Controle controle = new Controle(); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Id()); + cliente.set_Nome(x.get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 2: + { + if (this.Producao != null && this.Producao.Count != 0) + { + if (this.Producao.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + return ( + from x in this.Producao + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 3: + { + if (this.ApolicePendente != null && this.ApolicePendente.Count != 0) + { + if (this.ApolicePendente.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + return ( + from x in this.ApolicePendente + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 4: + { + if (this.RenovacaoFiltrado != null && this.RenovacaoFiltrado.Count != 0) + { + if (this.RenovacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + return ( + from x in this.RenovacaoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + Vendedor vendedor; + Seguradora seguradora; + Ramo ramo; + Cliente cliente; + Documento documento = new Documento(); + documento.set_Id((x.get_Apolice() == "PROSPECÇÃO" ? x.get_Prospeccao().get_Id() : x.get_Documento().get_Id())); + documento.set_Vigencia1((x.get_Apolice() == "PROSPECÇÃO" ? new DateTime() : x.get_Documento().get_Vigencia1())); + documento.set_Vigencia2(x.get_VigenciaFinal()); + documento.set_Apolice(x.get_Apolice()); + documento.set_Endosso((x.get_Apolice() == "PROSPECÇÃO" ? "" : x.get_Documento().get_Endosso())); + if (x.get_Apolice() == "PROSPECÇÃO") + { + vendedor = new Vendedor(); + vendedor.set_Nome(x.get_Vendedor()); + } + else + { + vendedor = x.get_Documento().get_VendedorPrincipal(); + } + documento.set_VendedorPrincipal(vendedor); + Controle controle = new Controle(); + if (x.get_Apolice() == "PROSPECÇÃO") + { + seguradora = new Seguradora(); + } + else + { + seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + } + controle.set_Seguradora(seguradora); + if (x.get_Apolice() == "PROSPECÇÃO") + { + ramo = new Ramo(); + } + else + { + ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + } + controle.set_Ramo(ramo); + if (x.get_Apolice() == "PROSPECÇÃO") + { + cliente = new Cliente(); + cliente.set_Nome(x.get_Cliente()); + } + else + { + cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + } + controle.set_Cliente(cliente); + documento.set_Controle(controle); + List items = new List(); + Item item = new Item(); + item.set_Descricao(x.get_Item()); + items.Add(item); + documento.set_ItensAtivo(items); + return documento; + }).ToList(); + } + } + return null; + } + case 5: + { + if (this.ComissaoFiltrado != null && this.ComissaoFiltrado.Count != 0) + { + if (this.ComissaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + return ( + from x in this.ComissaoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 6: + case 16: + { + if (this.PendenteFiltrado != null && this.PendenteFiltrado.Count != 0) + { + if (this.PendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + return ( + from x in this.PendenteFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 7: + case 11: + case 13: + case 14: + case 15: + { + return null; + } + case 8: + { + if (this.Auditoria != null && this.Auditoria.Count != 0) + { + if (this.Auditoria.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + return ( + from x in this.Auditoria + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 9: + { + if (this.Sinistro != null && this.Sinistro.Count != 0) + { + if (this.Sinistro.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + return ( + from x in this.Sinistro + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 10: + { + if (this.Sinistro != null && this.Sinistro.Count != 0) + { + if (this.Sinistro.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + return ( + from x in this.Sinistro + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + case 12: + { + if (this.FaturaPendenteFiltrado != null && this.FaturaPendenteFiltrado.Count != 0) + { + if (this.FaturaPendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => x.get_Selecionado())) + { + return ( + from x in this.FaturaPendenteFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => { + Documento documento = new Documento(); + documento.set_Id(x.get_Documento().get_Id()); + documento.set_Vigencia1(x.get_Documento().get_Vigencia1()); + documento.set_Vigencia2(x.get_Documento().get_Vigencia2()); + documento.set_Apolice(x.get_Documento().get_Apolice()); + documento.set_Endosso(x.get_Documento().get_Endosso()); + documento.set_VendedorPrincipal(x.get_Documento().get_VendedorPrincipal()); + Controle controle = new Controle(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id(x.get_Documento().get_Controle().get_Seguradora().get_Id()); + seguradora.set_Nome(x.get_Documento().get_Controle().get_Seguradora().get_Nome()); + controle.set_Seguradora(seguradora); + Ramo ramo = new Ramo(); + ramo.set_Id(x.get_Documento().get_Controle().get_Ramo().get_Id()); + ramo.set_Nome(x.get_Documento().get_Controle().get_Ramo().get_Nome()); + controle.set_Ramo(ramo); + Cliente cliente = new Cliente(); + cliente.set_Id(x.get_Documento().get_Controle().get_Cliente().get_Id()); + cliente.set_Nome(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + controle.set_Cliente(cliente); + documento.set_Controle(controle); + return documento; + }).ToList(); + } + } + return null; + } + default: + { + return null; + } + } + }); + return documentos; + } + + public void DescerParametro(Gestor.Model.Domain.Relatorios.ParametrosRelatorio parametro) + { + if (parametro == null) + { + return; + } + int num = this.ParametrosRelatorioAdicionados.IndexOf(parametro); + if (num == this.ParametrosRelatorioAdicionados.Count - 1) + { + return; + } + this.ParametrosRelatorioAdicionados.Move(num, num + 1); + } + + private void EstipulanteOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(6); + } + + public void ExcluirParametro(Gestor.Model.Domain.Relatorios.ParametrosRelatorio parametro) + { + if (parametro == null) + { + return; + } + this.ParametrosRelatorioAdicionados.Remove(parametro); + this.ParametrosRelatorio.Add(parametro); + this.ParametrosRelatorio = new ObservableCollection( + from x in this.ParametrosRelatorio + orderby x.get_Header() + select x); + } + + public void ExcluirTotalizacao(Gestor.Model.Domain.Relatorios.ParametrosTotalizacao parametro) + { + if (parametro == null) + { + return; + } + this.ParametrosTotalizacaoAdicionados.Remove(parametro); + this.ParametrosTotalizacao.Add(parametro); + this.ParametrosTotalizacao = new ObservableCollection( + from x in this.ParametrosTotalizacao + orderby x.get_Header() + select x); + } + + public async void ExibirExtratoDrawer() + { + List documentos = new List(); + List prospeccaos = new List(); + List clientesAtivosInativos = new List(); + List nums = new List(); + List nums1 = new List(); + switch (this.Relatorio) + { + case 0: + { + foreach (Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos list in ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList()) + { + Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos clientesAtivosInativo = new Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos(); + clientesAtivosInativo.set_Id(list.get_Id()); + clientesAtivosInativo.set_Nome(list.get_Nome()); + clientesAtivosInativo.set_Documento(list.get_Documento()); + clientesAtivosInativo.set_Selecionado(list.get_Selecionado()); + clientesAtivosInativos.Add(clientesAtivosInativo); + } + base.ShowDrawer(new ExtratosDrawer(clientesAtivosInativos, null, new Gestor.Model.Common.Relatorio?(this.Relatorio), null, null, null), 0, false); + break; + } + case 1: + case 3: + { + if (nums.Count != 0 || nums1.Count != 0) + { + base.ShowDrawer(new ExtratosDrawer(null, documentos, new Gestor.Model.Common.Relatorio?(this.Relatorio), nums, nums1, prospeccaos), 0, false); + break; + } + else + { + await base.ShowMessage("É NECESSÁRIO HAVER AO MENOS UM DOCUMENTO SELECIONADO", "OK", "", false); + break; + } + } + case 2: + { + List.Enumerator enumerator = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList().GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + Gestor.Model.Domain.Relatorios.Producao.Producao current = enumerator.Current; + documentos.Add(current.get_Documento()); + if (!current.get_Selecionado()) + { + continue; + } + nums.Add(current.get_Documento().get_Id()); + } + goto case 3; + } + finally + { + ((IDisposable)enumerator).Dispose(); + } + break; + } + case 4: + { + List.Enumerator enumerator1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList().GetEnumerator(); + try + { + while (enumerator1.MoveNext()) + { + Gestor.Model.Domain.Relatorios.Renovacao.Renovacao renovacao = enumerator1.Current; + if (renovacao.get_Documento() != null) + { + documentos.Add(renovacao.get_Documento()); + if (renovacao.get_Selecionado()) + { + nums.Add(renovacao.get_Documento().get_Id()); + } + } + if (renovacao.get_Prospeccao() == null) + { + continue; + } + prospeccaos.Add(renovacao.get_Prospeccao()); + if (!renovacao.get_Selecionado()) + { + continue; + } + nums1.Add(renovacao.get_Prospeccao().get_Id()); + } + goto case 3; + } + finally + { + ((IDisposable)enumerator1).Dispose(); + } + break; + } + default: + { + goto case 3; + } + } + } + + private void Filtrar() + { + this.Seguradoras = Recursos.Seguradoras.Where((Seguradora x) => { + if (!x.get_Ativo()) + { + return false; + } + return x.get_Nome().Contains(this.Filtro); + }).OrderBy((Seguradora x) => x.get_Nome()).ToList(); + this.Ramos = Recursos.Ramos.Where((Ramo x) => { + if (!x.get_Ativo()) + { + return false; + } + return x.get_Nome().Contains(this.Filtro); + }).OrderBy((Ramo x) => x.get_Nome()).ToList(); + this.Estipulantes = Recursos.Estipulantes.Where((Estipulante x) => { + if (!x.get_Ativo()) + { + return false; + } + return x.get_Nome().Contains(this.Filtro); + }).OrderBy((Estipulante x) => x.get_Nome()).ToList(); + this.Vendedores = (this.Vinculo.Count > 0 ? Recursos.Vendedores.Where((Vendedor x) => { + if (!this.Vinculo.Any((VendedorUsuario y) => y.get_Vendedor().get_Id() == x.get_Id()) || !x.get_Nome().Contains(this.Filtro)) + { + return false; + } + return x.get_Ativo(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList() : Recursos.Vendedores.Where((Vendedor x) => { + if (!x.get_Nome().Contains(this.Filtro)) + { + return false; + } + if (this.Inativo) + { + return true; + } + return x.get_Ativo(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList()); + this.TipoVendedor = Recursos.TipoVendedor.Where((Gestor.Model.Domain.Seguros.TipoVendedor x) => { + if (!x.get_Ativo().GetValueOrDefault()) + { + return false; + } + return x.get_Descricao().Contains(this.Filtro); + }).OrderBy((Gestor.Model.Domain.Seguros.TipoVendedor x) => x.get_Descricao()).ToList(); + this.Produtos = Recursos.Produtos.Where((Gestor.Model.Domain.Seguros.Produto x) => { + if (!x.get_Ativo()) + { + return false; + } + return x.get_Nome().Contains(this.Filtro); + }).OrderBy((Gestor.Model.Domain.Seguros.Produto x) => x.get_Nome()).ToList(); + this.TipoSeguros = ( + from x in RelatorioViewModel.TipoSegurosList + where EnumHelper.GetDescription(x.get_Status()).Contains(this.Filtro) + orderby x.get_Status() + select x).ToList(); + this.Negocios = ( + from x in RelatorioViewModel.NegocioList + where EnumHelper.GetDescription(x.get_Negocio()).Contains(this.Filtro) + orderby x.get_Negocio() + select x).ToList(); + } + + internal async Task> Filtrar(string value) + { + List usuarios = await Task.Run>(() => this.FiltrarUsuario(value)); + return usuarios; + } + + private void FiltrarRamo() + { + List filtroPersonalizados = (this.RamosSelecionados == null ? new List() : this.RamosSelecionados.Select((Ramo x) => { + Gestor.Model.Domain.Relatorios.FiltroPersonalizado filtroPersonalizado = new Gestor.Model.Domain.Relatorios.FiltroPersonalizado(); + filtroPersonalizado.set_Nome(x.get_Nome()); + filtroPersonalizado.set_Propriedade("Ramo"); + filtroPersonalizado.set_Tipo(typeof(string)); + filtroPersonalizado.set_ValorIncial(x.get_Nome()); + filtroPersonalizado.set_SemValor(false); + filtroPersonalizado.set_Descricao(x.get_Nome()); + filtroPersonalizado.set_Diferente(true); + return filtroPersonalizado; + }).ToList()); + this.ClientesAtivosInativosFiltrado = new ObservableCollection(this.ClientesAtivosInativos.CustomNot(filtroPersonalizados)); + if (this.FiltroPersonalizadoSelecionado != null) + { + this.ClientesAtivosInativosFiltrado = new ObservableCollection(this.ClientesAtivosInativosFiltrado.ToList().CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), false)); + } + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ClientesAtivosInativosFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + } + + public List FiltrarUsuario(string filter) + { + this.UsuariosFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection(this.Usuarios) : new ObservableCollection( + from x in this.Usuarios + where Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(x.get_Nome().Trim()).ToUpper().Contains(Gestor.Common.Validation.ValidationHelper.RemoveDiacritics(filter)) + orderby !x.get_Excluido() descending, x.get_Nome() + select x)); + return this.UsuariosFiltrados.ToList(); + } + + public async Task GerarExcel() + { + string str; + Gestor.Model.Common.Agrupamento agrupamento; + Gestor.Model.Common.Agrupamento agrupamento1; + List list; + List producaos; + List list1; + List producaos1; + List list2; + List producaos2; + List list3; + List producaos3; + List list4; + List producaos4; + List list5; + List producaos5; + List apolicePendentes; + List apolicePendentes1; + List apolicePendentes2; + List apolicePendentes3; + List apolicePendentes4; + List apolicePendentes5; + List list6; + List apolicePendentes6; + List list7; + List apolicePendentes7; + List list8; + List renovacaos; + List renovacaos1; + List renovacaos2; + List renovacaos3; + List renovacaos4; + List renovacaos5; + List renovacaos6; + List renovacaos7; + List renovacaos8; + List list9; + List renovacaos9; + List comissaos; + List comissaos1; + List comissaos2; + List comissaos3; + List comissaos4; + List comissaos5; + List comissaos6; + List comissaos7; + List comissaos8; + List comissaos9; + List list10; + List pendentes; + List pendentes1; + List pendentes2; + List pendentes3; + List pendentes4; + List pendentes5; + List pendentes6; + List pendentes7; + List pendentes8; + List pendentes9; + List pendentes10; + List auditorias; + List auditorias1; + List auditorias2; + List auditorias3; + List auditorias4; + List auditorias5; + List auditorias6; + List auditorias7; + List auditorias8; + List auditorias9; + List auditorias10; + List sinistros; + List sinistros1; + List sinistros2; + List sinistros3; + List sinistros4; + List sinistros5; + List sinistros6; + List sinistros7; + List sinistros8; + List sinistros9; + List sinistros10; + List faturaPendentes; + List extratoBaixadoRelatorios; + List metaSeguradoraRelatorios; + List metaVendedorRelatorios; + List licenciamentos; + List tarefas; + List notaFiscalRelatorios; + List logsEnvios; + List logAcaoRelatorios; + List apoliceCriticas; + List placas; + List placas1; + List placas2; + List placas3; + List placas4; + List placas5; + List placas6; + List placas7; + List placas8; + List endossos; + List classificacaos; + XLWorkbook xLWorkbook; + List producaos6; + List strs; + List apolicePendentes8; + List renovacaos10; + List comissaos10; + List list11; + List auditorias11; + List sinistros11; + List placas9; + string tempPath = ""; + string str1 = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str1 = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + str1 = null; + xLWorkbook = null; + strs = null; + return; + } + } + string[] description = new string[] { tempPath, EnumHelper.GetDescription(this.Relatorio), " ", null, null }; + DateTime date = Functions.GetNetworkTime().Date; + description[3] = date.ToShortDateString().Replace("/", ""); + description[4] = ".xlsx"; + str1 = string.Concat(description); + } + xLWorkbook = new XLWorkbook(); + int num = 1; + switch (this.Relatorio) + { + case 0: + case 1: + { + List clientesAtivosInativos = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ClientesAtivosInativosFiltrado == null || clientesAtivosInativos.Count == 0) + { + break; + } + else + { + List clientesAtivosInativos1 = clientesAtivosInativos; + if (clientesAtivosInativos1.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + List clientesAtivosInativos2 = clientesAtivosInativos; + list = ( + from x in clientesAtivosInativos2 + where x.get_Selecionado() + select x).ToList(); + } + else + { + list = clientesAtivosInativos; + } + List clientesAtivosInativos3 = list; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", clientesAtivosInativos3, this.Relatorio, true); + goto case 22; + } + } + case 2: + { + producaos6 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ProducaoFiltrado == null || producaos6.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List producaos7 = producaos6; + IOrderedEnumerable seguradora = + from x in producaos7 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str2 in strs) + { + if (string.IsNullOrWhiteSpace(str2)) + { + continue; + } + List producaos8 = producaos6; + if (producaos8.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + IEnumerable producaos9 = producaos6.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str2; + }); + producaos = ( + from x in producaos9 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable seguradora1 = + from x in producaos6 + where x.get_Seguradora() == str2 + select x; + producaos = ( + from x in seguradora1 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos10 = producaos; + if (producaos10.Count == 0) + { + continue; + } + string str3 = str2; + agrupamento1 = this.Agrupamento; + str = str3.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, producaos10, this.Relatorio, true); + } + goto Label1; + } + else + { + List producaos11 = producaos6; + if (producaos11.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos12 = producaos6; + List list12 = ( + from x in producaos12 + where x.get_Selecionado() + select x).ToList(); + list1 = ( + from x in list12 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos13 = producaos6; + list1 = ( + from x in producaos13 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos14 = list1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos14, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List producaos15 = producaos6; + IOrderedEnumerable ramo = + from x in producaos15 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str4 in strs) + { + if (string.IsNullOrWhiteSpace(str4)) + { + continue; + } + List producaos16 = producaos6; + if (producaos16.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + IEnumerable producaos17 = producaos6.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str4; + }); + producaos1 = ( + from x in producaos17 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable ramo1 = + from x in producaos6 + where x.get_Ramo() == str4 + select x; + producaos1 = ( + from x in ramo1 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos18 = producaos1; + if (producaos18.Count == 0) + { + continue; + } + string str5 = str4; + agrupamento1 = this.Agrupamento; + str = str5.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, producaos18, this.Relatorio, true); + } + goto Label1; + } + else + { + List producaos19 = producaos6; + if (producaos19.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos20 = producaos6; + List list13 = ( + from x in producaos20 + where x.get_Selecionado() + select x).ToList(); + list2 = ( + from x in list13 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos21 = producaos6; + list2 = ( + from x in producaos21 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos22 = list2; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos22, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List producaos23 = producaos6; + IOrderedEnumerable vendedor = + from x in producaos23 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str6 in strs) + { + if (string.IsNullOrWhiteSpace(str6)) + { + continue; + } + List producaos24 = producaos6; + if (producaos24.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + IEnumerable producaos25 = producaos6.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str6; + }); + producaos2 = ( + from x in producaos25 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable vendedor1 = + from x in producaos6 + where x.get_Vendedor() == str6 + select x; + producaos2 = ( + from x in vendedor1 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos26 = producaos2; + if (producaos26.Count == 0) + { + continue; + } + string str7 = str6; + agrupamento1 = this.Agrupamento; + str = str7.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, producaos26, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List producaos27 = producaos6; + if (producaos27.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos28 = producaos6; + List list14 = ( + from x in producaos28 + where x.get_Selecionado() + select x).ToList(); + list3 = ( + from x in list14 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos29 = producaos6; + list3 = ( + from x in producaos29 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos30 = list3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos30, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List producaos31 = producaos6; + IOrderedEnumerable estipulante = + from x in producaos31 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str8 in strs) + { + if (string.IsNullOrWhiteSpace(str8)) + { + continue; + } + List producaos32 = producaos6; + if (producaos32.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + IEnumerable producaos33 = producaos6.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str8; + }); + producaos3 = ( + from x in producaos33 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable estipulante1 = + from x in producaos6 + where x.get_Estipulante() == str8 + select x; + producaos3 = ( + from x in estipulante1 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos34 = producaos3; + if (producaos34.Count == 0) + { + continue; + } + string str9 = str8; + agrupamento1 = this.Agrupamento; + str = str9.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, producaos34, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List producaos35 = producaos6; + if (producaos35.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos36 = producaos6; + List list15 = ( + from x in producaos36 + where x.get_Selecionado() + select x).ToList(); + list4 = ( + from x in list15 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos37 = producaos6; + list4 = ( + from x in producaos37 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos38 = list4; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos38, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + List producaos39 = producaos6; + IOrderedEnumerable status = + from x in producaos39 + orderby x.get_Status() + select x; + strs = ( + from x in status + select x.get_Status()).Distinct().ToList(); + this.ColunasOcultas = await Funcoes.OcultarColunas(this.Relatorio); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str10 in strs) + { + if (string.IsNullOrWhiteSpace(str10)) + { + continue; + } + List producaos40 = producaos6; + if (producaos40.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + IEnumerable producaos41 = producaos6.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str10; + }); + producaos4 = ( + from x in producaos41 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable status1 = + from x in producaos6 + where x.get_Status() == str10 + select x; + producaos4 = ( + from x in status1 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos42 = producaos4; + if (producaos42.Count == 0) + { + continue; + } + string str11 = str10; + agrupamento1 = this.Agrupamento; + str = str11.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, producaos42, this.ColunasOcultas); + } + goto Label1; + } + else + { + List producaos43 = producaos6; + if (producaos43.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos44 = producaos6; + List list16 = ( + from x in producaos44 + where x.get_Selecionado() + select x).ToList(); + list5 = ( + from x in list16 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos45 = producaos6; + list5 = ( + from x in producaos45 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos46 = list5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos46, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List producaos47 = producaos6; + if (producaos47.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + List producaos48 = producaos6; + IEnumerable selecionado = + from x in producaos48 + where x.get_Selecionado() + select x; + producaos5 = ( + from x in selecionado + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + List producaos49 = producaos6; + producaos5 = ( + from x in producaos49 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List producaos50 = producaos5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", producaos50.ToList(), this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 3: + { + apolicePendentes8 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ApolicePendenteFiltrado == null || apolicePendentes8.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List apolicePendentes9 = apolicePendentes8; + IOrderedEnumerable seguradora2 = + from x in apolicePendentes9 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora2 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str12 in strs) + { + if (string.IsNullOrWhiteSpace(str12)) + { + continue; + } + List apolicePendentes10 = apolicePendentes8; + if (apolicePendentes10.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + IEnumerable apolicePendentes11 = apolicePendentes8.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str12; + }); + apolicePendentes = ( + from x in apolicePendentes11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable seguradora3 = + from x in apolicePendentes8 + where x.get_Seguradora() == str12 + select x; + apolicePendentes = ( + from x in seguradora3 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List apolicePendentes12 = apolicePendentes; + if (apolicePendentes12.Count == 0) + { + continue; + } + string str13 = str12; + agrupamento1 = this.Agrupamento; + str = str13.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, apolicePendentes12, this.Relatorio, true); + } + goto Label1; + } + else + { + List apolicePendentes13 = apolicePendentes8; + if (apolicePendentes13.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes14 = apolicePendentes8; + apolicePendentes1 = ( + from x in apolicePendentes14 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apolicePendentes1 = apolicePendentes8; + } + List apolicePendentes15 = apolicePendentes1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes15, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List apolicePendentes16 = apolicePendentes8; + IOrderedEnumerable ramo2 = + from x in apolicePendentes16 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo2 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str14 in strs) + { + if (string.IsNullOrWhiteSpace(str14)) + { + continue; + } + List apolicePendentes17 = apolicePendentes8; + if (apolicePendentes17.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + IEnumerable apolicePendentes18 = apolicePendentes8.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str14; + }); + apolicePendentes2 = ( + from x in apolicePendentes18 + orderby x.get_Seguradora() + select x).ToList(); + } + else + { + IEnumerable ramo3 = + from x in apolicePendentes8 + where x.get_Ramo() == str14 + select x; + apolicePendentes2 = ( + from x in ramo3 + orderby x.get_Seguradora() + select x).ToList(); + } + List apolicePendentes19 = apolicePendentes2; + if (apolicePendentes19.Count == 0) + { + continue; + } + string str15 = str14; + agrupamento1 = this.Agrupamento; + str = str15.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, apolicePendentes19, this.Relatorio, true); + } + goto Label1; + } + else + { + List apolicePendentes20 = apolicePendentes8; + if (apolicePendentes20.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes21 = apolicePendentes8; + apolicePendentes3 = ( + from x in apolicePendentes21 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apolicePendentes3 = apolicePendentes8; + } + List apolicePendentes22 = apolicePendentes3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes22, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List apolicePendentes23 = apolicePendentes8; + IOrderedEnumerable vendedor2 = + from x in apolicePendentes23 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor2 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str16 in strs) + { + if (string.IsNullOrWhiteSpace(str16)) + { + continue; + } + List apolicePendentes24 = apolicePendentes8; + if (apolicePendentes24.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + IEnumerable apolicePendentes25 = apolicePendentes8.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str16; + }); + apolicePendentes4 = ( + from x in apolicePendentes25 + orderby x.get_Seguradora() + select x).ToList(); + } + else + { + IEnumerable vendedor3 = + from x in apolicePendentes8 + where x.get_Vendedor() == str16 + select x; + apolicePendentes4 = ( + from x in vendedor3 + orderby x.get_Seguradora() + select x).ToList(); + } + List apolicePendentes26 = apolicePendentes4; + if (apolicePendentes26.Count == 0) + { + continue; + } + string str17 = str16; + agrupamento1 = this.Agrupamento; + str = str17.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, apolicePendentes26, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List apolicePendentes27 = apolicePendentes8; + if (apolicePendentes27.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes28 = apolicePendentes8; + apolicePendentes5 = ( + from x in apolicePendentes28 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apolicePendentes5 = apolicePendentes8; + } + List apolicePendentes29 = apolicePendentes5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes29, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List apolicePendentes30 = apolicePendentes8; + IOrderedEnumerable estipulante2 = + from x in apolicePendentes30 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante2 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str18 in strs) + { + if (string.IsNullOrWhiteSpace(str18)) + { + continue; + } + List apolicePendentes31 = apolicePendentes8; + if (apolicePendentes31.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + IEnumerable apolicePendentes32 = apolicePendentes8.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str18; + }); + list6 = ( + from x in apolicePendentes32 + orderby x.get_Seguradora() + select x).ToList(); + } + else + { + IEnumerable estipulante3 = + from x in apolicePendentes8 + where x.get_Estipulante() == str18 + select x; + list6 = ( + from x in estipulante3 + orderby x.get_Seguradora() + select x).ToList(); + } + List apolicePendentes33 = list6; + if (apolicePendentes33.Count == 0) + { + continue; + } + string str19 = str18; + agrupamento1 = this.Agrupamento; + str = str19.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, apolicePendentes33, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List apolicePendentes34 = apolicePendentes8; + if (apolicePendentes34.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes35 = apolicePendentes8; + apolicePendentes6 = ( + from x in apolicePendentes35 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apolicePendentes6 = apolicePendentes8; + } + List apolicePendentes36 = apolicePendentes6; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes36, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + List apolicePendentes37 = apolicePendentes8; + IOrderedEnumerable status2 = + from x in apolicePendentes37 + orderby x.get_Status() + select x; + strs = ( + from x in status2 + select x.get_Status()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str20 in strs) + { + if (string.IsNullOrWhiteSpace(str20)) + { + continue; + } + List apolicePendentes38 = apolicePendentes8; + if (apolicePendentes38.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + IEnumerable apolicePendentes39 = apolicePendentes8.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str20; + }); + list7 = ( + from x in apolicePendentes39 + orderby x.get_Seguradora() + select x).ToList(); + } + else + { + IEnumerable status3 = + from x in apolicePendentes8 + where x.get_Status() == str20 + select x; + list7 = ( + from x in status3 + orderby x.get_Seguradora() + select x).ToList(); + } + List apolicePendentes40 = list7; + if (apolicePendentes40.Count == 0) + { + continue; + } + string str21 = str20; + agrupamento1 = this.Agrupamento; + str = str21.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, apolicePendentes40, this.ColunasOcultas); + } + goto Label1; + } + else + { + List apolicePendentes41 = apolicePendentes8; + if (apolicePendentes41.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes42 = apolicePendentes8; + apolicePendentes7 = ( + from x in apolicePendentes42 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apolicePendentes7 = apolicePendentes8; + } + List apolicePendentes43 = apolicePendentes7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes43, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List apolicePendentes44 = apolicePendentes8; + if (apolicePendentes44.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + List apolicePendentes45 = apolicePendentes8; + list8 = ( + from x in apolicePendentes45 + where x.get_Selecionado() + select x).ToList(); + } + else + { + list8 = apolicePendentes8; + } + List apolicePendentes46 = list8; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apolicePendentes46, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 4: + { + renovacaos10 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.RenovacaoFiltrado == null || renovacaos10.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List renovacaos11 = renovacaos10; + IOrderedEnumerable seguradora4 = + from x in renovacaos11 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora4 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str22 in strs) + { + if (string.IsNullOrWhiteSpace(str22)) + { + continue; + } + List renovacaos12 = renovacaos10; + if (renovacaos12.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaos13 = renovacaos10.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str22; + }); + renovacaos = ( + from x in renovacaos13 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + IEnumerable seguradora5 = + from x in renovacaos10 + where x.get_Seguradora() == str22 + select x; + renovacaos = ( + from x in seguradora5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + List renovacaos14 = renovacaos; + if (renovacaos14.Count == 0) + { + continue; + } + string str23 = str22; + agrupamento1 = this.Agrupamento; + str = str23.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, renovacaos14, this.Relatorio, true); + } + goto Label1; + } + else + { + List renovacaos15 = renovacaos10; + if (renovacaos15.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos16 = renovacaos10; + renovacaos1 = ( + from x in renovacaos16 + where x.get_Selecionado() + select x).ToList(); + } + else + { + renovacaos1 = renovacaos10.ToList(); + } + List renovacaos17 = renovacaos1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos17, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List renovacaos18 = renovacaos10; + IOrderedEnumerable ramo4 = + from x in renovacaos18 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo4 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str24 in strs) + { + if (string.IsNullOrWhiteSpace(str24)) + { + continue; + } + List renovacaos19 = renovacaos10; + if (renovacaos19.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaos20 = renovacaos10.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str24; + }); + renovacaos2 = ( + from x in renovacaos20 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + IEnumerable ramo5 = + from x in renovacaos10 + where x.get_Ramo() == str24 + select x; + renovacaos2 = ( + from x in ramo5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + List renovacaos21 = renovacaos2; + if (renovacaos21.Count == 0) + { + continue; + } + string str25 = str24; + agrupamento1 = this.Agrupamento; + str = str25.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, renovacaos21, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List renovacaos22 = renovacaos10; + if (renovacaos22.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos23 = renovacaos10; + renovacaos3 = ( + from x in renovacaos23 + where x.get_Selecionado() + select x).ToList(); + } + else + { + renovacaos3 = renovacaos10.ToList(); + } + List renovacaos24 = renovacaos3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos24, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List renovacaos25 = renovacaos10; + IOrderedEnumerable vendedor4 = + from x in renovacaos25 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor4 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str26 in strs) + { + if (string.IsNullOrWhiteSpace(str26)) + { + continue; + } + List renovacaos26 = renovacaos10; + if (renovacaos26.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaos27 = renovacaos10.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str26; + }); + renovacaos4 = ( + from x in renovacaos27 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + IEnumerable vendedor5 = + from x in renovacaos10 + where x.get_Vendedor() == str26 + select x; + renovacaos4 = ( + from x in vendedor5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + List renovacaos28 = renovacaos4; + if (renovacaos28.Count == 0) + { + continue; + } + string str27 = str26; + agrupamento1 = this.Agrupamento; + str = str27.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, renovacaos28, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List renovacaos29 = renovacaos10; + if (renovacaos29.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos30 = renovacaos10; + renovacaos5 = ( + from x in renovacaos30 + where x.get_Selecionado() + select x).ToList(); + } + else + { + renovacaos5 = renovacaos10.ToList(); + } + List renovacaos31 = renovacaos5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos31, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List renovacaos32 = renovacaos10; + IOrderedEnumerable estipulante4 = + from x in renovacaos32 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante4 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str28 in strs) + { + if (string.IsNullOrWhiteSpace(str28)) + { + continue; + } + List renovacaos33 = renovacaos10; + if (renovacaos33.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaos34 = renovacaos10.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str28; + }); + renovacaos6 = ( + from x in renovacaos34 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + IEnumerable estipulante5 = + from x in renovacaos10 + where x.get_Estipulante() == str28 + select x; + renovacaos6 = ( + from x in estipulante5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + List renovacaos35 = renovacaos6; + if (renovacaos35.Count == 0) + { + continue; + } + string str29 = str28; + agrupamento1 = this.Agrupamento; + str = str29.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, renovacaos35, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List renovacaos36 = renovacaos10; + if (renovacaos36.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos37 = renovacaos10; + renovacaos7 = ( + from x in renovacaos37 + where x.get_Selecionado() + select x).ToList(); + } + else + { + renovacaos7 = renovacaos10.ToList(); + } + List renovacaos38 = renovacaos7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos38, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + this.ColunasOcultas = await Funcoes.OcultarColunas(this.Relatorio); + List renovacaos39 = renovacaos10; + IOrderedEnumerable status4 = + from x in renovacaos39 + orderby x.get_Status() + select x; + strs = ( + from x in status4 + select x.get_Status()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str30 in strs) + { + if (string.IsNullOrWhiteSpace(str30)) + { + continue; + } + List renovacaos40 = renovacaos10; + if (renovacaos40.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaos41 = renovacaos10.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str30; + }); + renovacaos8 = ( + from x in renovacaos41 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + IEnumerable status5 = + from x in renovacaos10 + where x.get_Status() == str30 + select x; + renovacaos8 = ( + from x in status5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + List renovacaos42 = renovacaos8; + if (renovacaos42.Count == 0) + { + continue; + } + string str31 = str30; + agrupamento1 = this.Agrupamento; + str = str31.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, renovacaos42, this.Relatorio, true); + } + goto Label1; + } + else + { + List renovacaos43 = renovacaos10; + if (renovacaos43.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos44 = renovacaos10; + list9 = ( + from x in renovacaos44 + where x.get_Selecionado() + select x).ToList(); + } + else + { + list9 = renovacaos10.ToList(); + } + List renovacaos45 = list9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos45, this.Relatorio, true); + goto Label1; + } + } + default: + { + List renovacaos46 = renovacaos10; + if (renovacaos46.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + List renovacaos47 = renovacaos10; + renovacaos9 = ( + from x in renovacaos47 + where x.get_Selecionado() + select x).ToList(); + } + else + { + renovacaos9 = renovacaos10.ToList(); + } + List renovacaos48 = renovacaos9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", renovacaos48, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 5: + { + comissaos10 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ComissaoFiltrado == null || comissaos10.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List comissaos11 = comissaos10; + IOrderedEnumerable seguradora6 = + from x in comissaos11 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora6 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str32 in strs) + { + if (string.IsNullOrWhiteSpace(str32)) + { + continue; + } + List comissaos12 = comissaos10; + if (comissaos12.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + IEnumerable comissaos13 = comissaos10.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str32; + }); + comissaos = ( + from x in comissaos13 + orderby x.get_Recebimento() + select x).ToList(); + } + else + { + IEnumerable seguradora7 = + from x in comissaos10 + where x.get_Seguradora() == str32 + select x; + comissaos = ( + from x in seguradora7 + orderby x.get_Recebimento() + select x).ToList(); + } + List comissaos14 = comissaos; + if (comissaos14.Count == 0) + { + continue; + } + string str33 = str32; + agrupamento1 = this.Agrupamento; + str = str33.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, comissaos14, this.Relatorio, true); + } + goto Label1; + } + else + { + List comissaos15 = comissaos10; + if (comissaos15.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos16 = comissaos10; + comissaos1 = ( + from x in comissaos16 + where x.get_Selecionado() + select x).ToList(); + } + else + { + comissaos1 = comissaos10; + } + List comissaos17 = comissaos1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos17, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List comissaos18 = comissaos10; + IOrderedEnumerable ramo6 = + from x in comissaos18 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo6 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str34 in strs) + { + if (string.IsNullOrWhiteSpace(str34)) + { + continue; + } + List comissaos19 = comissaos10; + if (comissaos19.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + IEnumerable comissaos20 = comissaos10.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str34; + }); + comissaos2 = ( + from x in comissaos20 + orderby x.get_Recebimento() + select x).ToList(); + } + else + { + IEnumerable ramo7 = + from x in comissaos10 + where x.get_Ramo() == str34 + select x; + comissaos2 = ( + from x in ramo7 + orderby x.get_Recebimento() + select x).ToList(); + } + List comissaos21 = comissaos2; + if (comissaos21.Count == 0) + { + continue; + } + string str35 = str34; + agrupamento1 = this.Agrupamento; + str = str35.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, comissaos21, this.Relatorio, true); + } + goto Label1; + } + else + { + List comissaos22 = comissaos10; + if (comissaos22.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos23 = comissaos10; + comissaos3 = ( + from x in comissaos23 + where x.get_Selecionado() + select x).ToList(); + } + else + { + comissaos3 = comissaos10; + } + List comissaos24 = comissaos3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos24, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List comissaos25 = comissaos10; + IOrderedEnumerable vendedor6 = + from x in comissaos25 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor6 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str36 in strs) + { + if (string.IsNullOrWhiteSpace(str36)) + { + continue; + } + List comissaos26 = comissaos10; + if (comissaos26.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + IEnumerable comissaos27 = comissaos10.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str36; + }); + comissaos4 = ( + from x in comissaos27 + orderby x.get_Recebimento() + select x).ToList(); + } + else + { + IEnumerable vendedor7 = + from x in comissaos10 + where x.get_Vendedor() == str36 + select x; + comissaos4 = ( + from x in vendedor7 + orderby x.get_Recebimento() + select x).ToList(); + } + List comissaos28 = comissaos4; + if (comissaos28.Count == 0) + { + continue; + } + string str37 = str36; + agrupamento1 = this.Agrupamento; + str = str37.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, comissaos28, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List comissaos29 = comissaos10; + if (comissaos29.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos30 = comissaos10; + comissaos5 = ( + from x in comissaos30 + where x.get_Selecionado() + select x).ToList(); + } + else + { + comissaos5 = comissaos10; + } + List comissaos31 = comissaos5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos31, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List comissaos32 = comissaos10; + IOrderedEnumerable estipulante6 = + from x in comissaos32 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante6 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str38 in strs) + { + if (string.IsNullOrWhiteSpace(str38)) + { + continue; + } + List comissaos33 = comissaos10; + if (comissaos33.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + IEnumerable comissaos34 = comissaos10.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str38; + }); + comissaos6 = ( + from x in comissaos34 + orderby x.get_Recebimento() + select x).ToList(); + } + else + { + IEnumerable estipulante7 = + from x in comissaos10 + where x.get_Estipulante() == str38 + select x; + comissaos6 = ( + from x in estipulante7 + orderby x.get_Recebimento() + select x).ToList(); + } + List comissaos35 = comissaos6; + if (comissaos35.Count == 0) + { + continue; + } + string str39 = str38; + agrupamento1 = this.Agrupamento; + str = str39.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, comissaos35, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List comissaos36 = comissaos10; + if (comissaos36.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos37 = comissaos10; + comissaos7 = ( + from x in comissaos37 + where x.get_Selecionado() + select x).ToList(); + } + else + { + comissaos7 = comissaos10; + } + List comissaos38 = comissaos7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos38, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + List comissaos39 = comissaos10; + IOrderedEnumerable status6 = + from x in comissaos39 + orderby x.get_Status() + select x; + strs = ( + from x in status6 + select x.get_Status()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str40 in strs) + { + if (string.IsNullOrWhiteSpace(str40)) + { + continue; + } + List comissaos40 = comissaos10; + if (comissaos40.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + IEnumerable comissaos41 = comissaos10.Where((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str40; + }); + comissaos8 = ( + from x in comissaos41 + orderby x.get_Recebimento() + select x).ToList(); + } + else + { + IEnumerable status7 = + from x in comissaos10 + where x.get_Status() == str40 + select x; + comissaos8 = ( + from x in status7 + orderby x.get_Recebimento() + select x).ToList(); + } + List comissaos42 = comissaos8; + if (comissaos42.Count == 0) + { + continue; + } + string str41 = str40; + agrupamento1 = this.Agrupamento; + str = str41.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, comissaos42, this.ColunasOcultas); + } + goto Label1; + } + else + { + List comissaos43 = comissaos10; + if (comissaos43.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos44 = comissaos10; + comissaos9 = ( + from x in comissaos44 + where x.get_Selecionado() + select x).ToList(); + } + else + { + comissaos9 = comissaos10; + } + List comissaos45 = comissaos9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos45, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List comissaos46 = comissaos10; + if (comissaos46.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + List comissaos47 = comissaos10; + list10 = ( + from x in comissaos47 + where x.get_Selecionado() + select x).ToList(); + } + else + { + list10 = comissaos10; + } + List comissaos48 = list10; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", comissaos48, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 6: + case 16: + { + list11 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.PendenteFiltrado == null || list11.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List pendentes11 = list11; + IOrderedEnumerable seguradora8 = + from x in pendentes11 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora8 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str42 in strs) + { + if (string.IsNullOrWhiteSpace(str42)) + { + continue; + } + List pendentes12 = list11; + if (pendentes12.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + IEnumerable pendentes13 = list11.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str42; + }); + pendentes = ( + from x in pendentes13 + orderby x.get_Vencimento() + select x).ToList(); + } + else + { + IEnumerable seguradora9 = + from x in list11 + where x.get_Seguradora() == str42 + select x; + pendentes = ( + from x in seguradora9 + orderby x.get_Vencimento() + select x).ToList(); + } + List pendentes14 = pendentes; + if (pendentes14.Count == 0) + { + continue; + } + string str43 = str42; + agrupamento1 = this.Agrupamento; + str = str43.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, pendentes14, this.Relatorio, true); + } + goto Label1; + } + else + { + List pendentes15 = list11; + if (pendentes15.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes16 = list11; + pendentes1 = ( + from x in pendentes16 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes1 = list11; + } + List pendentes17 = pendentes1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes17, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List pendentes18 = list11; + IOrderedEnumerable ramo8 = + from x in pendentes18 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo8 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str44 in strs) + { + if (string.IsNullOrWhiteSpace(str44)) + { + continue; + } + List pendentes19 = list11; + if (pendentes19.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + IEnumerable pendentes20 = list11.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str44; + }); + pendentes2 = ( + from x in pendentes20 + orderby x.get_Vencimento() + select x).ToList(); + } + else + { + IEnumerable ramo9 = + from x in list11 + where x.get_Ramo() == str44 + select x; + pendentes2 = ( + from x in ramo9 + orderby x.get_Vencimento() + select x).ToList(); + } + List pendentes21 = pendentes2; + if (pendentes21.Count == 0) + { + continue; + } + string str45 = str44; + agrupamento1 = this.Agrupamento; + str = str45.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, pendentes21, this.Relatorio, true); + } + goto Label1; + } + else + { + List pendentes22 = list11; + if (pendentes22.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes23 = list11; + pendentes3 = ( + from x in pendentes23 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes3 = list11; + } + List pendentes24 = pendentes3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes24, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List pendentes25 = list11; + IOrderedEnumerable vendedor8 = + from x in pendentes25 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor8 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str46 in strs) + { + if (string.IsNullOrWhiteSpace(str46)) + { + continue; + } + List pendentes26 = list11; + if (pendentes26.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + IEnumerable pendentes27 = list11.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str46; + }); + pendentes4 = ( + from x in pendentes27 + orderby x.get_Vencimento() + select x).ToList(); + } + else + { + IEnumerable vendedor9 = + from x in list11 + where x.get_Vendedor() == str46 + select x; + pendentes4 = ( + from x in vendedor9 + orderby x.get_Vencimento() + select x).ToList(); + } + List pendentes28 = pendentes4; + if (pendentes28.Count == 0) + { + continue; + } + string str47 = str46; + agrupamento1 = this.Agrupamento; + str = str47.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, pendentes28, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List pendentes29 = list11; + if (pendentes29.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes30 = list11; + pendentes5 = ( + from x in pendentes30 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes5 = list11; + } + List pendentes31 = pendentes5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes31, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List pendentes32 = list11; + IOrderedEnumerable estipulante8 = + from x in pendentes32 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante8 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str48 in strs) + { + if (string.IsNullOrWhiteSpace(str48)) + { + continue; + } + List pendentes33 = list11; + if (pendentes33.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + IEnumerable pendentes34 = list11.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str48; + }); + pendentes6 = ( + from x in pendentes34 + orderby x.get_Vencimento() + select x).ToList(); + } + else + { + IEnumerable estipulante9 = + from x in list11 + where x.get_Estipulante() == str48 + select x; + pendentes6 = ( + from x in estipulante9 + orderby x.get_Vencimento() + select x).ToList(); + } + List pendentes35 = pendentes6; + if (pendentes35.Count == 0) + { + continue; + } + string str49 = str48; + agrupamento1 = this.Agrupamento; + str = str49.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, pendentes35, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List pendentes36 = list11; + if (pendentes36.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes37 = list11; + pendentes7 = ( + from x in pendentes37 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes7 = list11; + } + List pendentes38 = pendentes7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes38, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + List pendentes39 = list11; + IOrderedEnumerable status8 = + from x in pendentes39 + orderby x.get_Status() + select x; + strs = ( + from x in status8 + select x.get_Status()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str50 in strs) + { + if (string.IsNullOrWhiteSpace(str50)) + { + continue; + } + List pendentes40 = list11; + if (pendentes40.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + IEnumerable pendentes41 = list11.Where((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str50; + }); + pendentes8 = ( + from x in pendentes41 + orderby x.get_Vencimento() + select x).ToList(); + } + else + { + IEnumerable status9 = + from x in list11 + where x.get_Status() == str50 + select x; + pendentes8 = ( + from x in status9 + orderby x.get_Vencimento() + select x).ToList(); + } + List pendentes42 = pendentes8; + if (pendentes42.Count == 0) + { + continue; + } + string str51 = str50; + agrupamento1 = this.Agrupamento; + str = str51.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, pendentes42, this.ColunasOcultas); + } + goto Label1; + } + else + { + List pendentes43 = list11; + if (pendentes43.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes44 = list11; + pendentes9 = ( + from x in pendentes44 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes9 = list11; + } + List pendentes45 = pendentes9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes45, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List pendentes46 = list11; + if (pendentes46.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + List pendentes47 = list11; + pendentes10 = ( + from x in pendentes47 + where x.get_Selecionado() + select x).ToList(); + } + else + { + pendentes10 = list11; + } + List pendentes48 = pendentes10; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", pendentes48, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 7: + { + if (this.Pagamentos != null) + { + List pagamentosSintetico = this.PagamentosSintetico; + List pagamentoSinteticos = ( + from x in pagamentosSintetico + orderby x.get_Titulo() descending + select x).ToList(); + foreach (PagamentoSintetico pagamentoSintetico in pagamentoSinteticos) + { + string titulo = pagamentoSintetico.get_Titulo(); + agrupamento = this.Agrupamento; + string str52 = titulo.ValidaNomePlanilha(agrupamento.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str52, pagamentoSintetico.get_Agrupamento().ToList(), this.Relatorio, true); + } + num = 1; + List pagamentos = this.Pagamentos; + List pagamentos1 = ( + from x in pagamentos + orderby x.get_Title() descending + select x).ToList(); + foreach (Pagamento pagamento in pagamentos1) + { + string title = pagamento.get_Title(); + agrupamento = this.Agrupamento; + string str53 = title.ValidaNomePlanilha(agrupamento.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str53, pagamento.get_Dados().ToList(), this.Relatorio, true); + num++; + } + List agrupamentoVendedors = new List(); + List pagamentos2 = this.Pagamentos; + foreach (Pagamento pagamento1 in + from x in pagamentos2 + orderby x.get_Title() + select x) + { + agrupamentoVendedors.Add(pagamento1.get_Vendedores()); + } + List agrupamentoVendedors1 = agrupamentoVendedors; + AgrupamentoVendedor agrupamentoVendedor = new AgrupamentoVendedor(); + agrupamentoVendedor.set_Vendedor("TOTAL"); + List agrupamentoVendedors2 = agrupamentoVendedors; + agrupamentoVendedor.set_Repasse(agrupamentoVendedors2.Sum((AgrupamentoVendedor p) => p.get_Repasse())); + List agrupamentoVendedors3 = agrupamentoVendedors; + agrupamentoVendedor.set_Debito(agrupamentoVendedors3.Sum((AgrupamentoVendedor p) => p.get_Debito())); + List agrupamentoVendedors4 = agrupamentoVendedors; + agrupamentoVendedor.set_Credito(agrupamentoVendedors4.Sum((AgrupamentoVendedor p) => p.get_Credito())); + List agrupamentoVendedors5 = agrupamentoVendedors; + agrupamentoVendedor.set_Desconto(agrupamentoVendedors5.Sum((AgrupamentoVendedor p) => p.get_Desconto())); + List agrupamentoVendedors6 = agrupamentoVendedors; + agrupamentoVendedor.set_Adiantamento(agrupamentoVendedors6.Sum((AgrupamentoVendedor p) => p.get_Adiantamento())); + List agrupamentoVendedors7 = agrupamentoVendedors; + agrupamentoVendedor.set_ValorLiquido(agrupamentoVendedors7.Sum((AgrupamentoVendedor p) => p.get_ValorLiquido())); + agrupamentoVendedors1.Add(agrupamentoVendedor); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "DADOS BANCÁRIOS", agrupamentoVendedors, this.Relatorio, false); + goto case 22; + } + else + { + break; + } + } + case 8: + { + auditorias11 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.AuditoriaFiltrado == null || auditorias11.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List auditorias12 = auditorias11; + IOrderedEnumerable seguradora10 = + from x in auditorias12 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora10 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str54 in strs) + { + if (string.IsNullOrWhiteSpace(str54)) + { + continue; + } + List auditorias13 = auditorias11; + if (auditorias13.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + IEnumerable auditorias14 = auditorias11.Where((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str54; + }); + auditorias = ( + from x in auditorias14 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable seguradora11 = + from x in auditorias11 + where x.get_Seguradora() == str54 + select x; + auditorias = ( + from x in seguradora11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List auditorias15 = auditorias; + if (auditorias15.Count == 0) + { + continue; + } + string str55 = str54; + agrupamento1 = this.Agrupamento; + str = str55.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, auditorias15, this.Relatorio, true); + } + goto Label1; + } + else + { + List auditorias16 = auditorias11; + if (auditorias16.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias17 = auditorias11; + auditorias1 = ( + from x in auditorias17 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias1 = auditorias11; + } + List auditorias18 = auditorias1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias18, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List auditorias19 = auditorias11; + IOrderedEnumerable ramo10 = + from x in auditorias19 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo10 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str56 in strs) + { + if (string.IsNullOrWhiteSpace(str56)) + { + continue; + } + List auditorias20 = auditorias11; + if (auditorias20.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + IEnumerable auditorias21 = auditorias11.Where((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str56; + }); + auditorias2 = ( + from x in auditorias21 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable ramo11 = + from x in auditorias11 + where x.get_Ramo() == str56 + select x; + auditorias2 = ( + from x in ramo11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List auditorias22 = auditorias2; + if (auditorias22.Count == 0) + { + continue; + } + string str57 = str56; + agrupamento1 = this.Agrupamento; + str = str57.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, auditorias22, this.Relatorio, true); + } + goto Label1; + } + else + { + List auditorias23 = auditorias11; + if (auditorias23.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias24 = auditorias11; + auditorias3 = ( + from x in auditorias24 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias3 = auditorias11; + } + List auditorias25 = auditorias3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias25, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List auditorias26 = auditorias11; + IOrderedEnumerable vendedor10 = + from x in auditorias26 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor10 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str58 in strs) + { + if (string.IsNullOrWhiteSpace(str58)) + { + continue; + } + List auditorias27 = auditorias11; + if (auditorias27.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + IEnumerable auditorias28 = auditorias11.Where((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str58; + }); + auditorias4 = ( + from x in auditorias28 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable vendedor11 = + from x in auditorias11 + where x.get_Vendedor() == str58 + select x; + auditorias4 = ( + from x in vendedor11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List auditorias29 = auditorias4; + if (auditorias29.Count == 0) + { + continue; + } + string str59 = str58; + agrupamento1 = this.Agrupamento; + str = str59.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, auditorias29, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List auditorias30 = auditorias11; + if (auditorias30.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias31 = auditorias11; + auditorias5 = ( + from x in auditorias31 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias5 = auditorias11; + } + List auditorias32 = auditorias5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias32, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List auditorias33 = auditorias11; + IOrderedEnumerable estipulante10 = + from x in auditorias33 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante10 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str60 in strs) + { + if (string.IsNullOrWhiteSpace(str60)) + { + continue; + } + List auditorias34 = auditorias11; + if (auditorias34.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + IEnumerable auditorias35 = auditorias11.Where((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str60; + }); + auditorias6 = ( + from x in auditorias35 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable estipulante11 = + from x in auditorias11 + where x.get_Estipulante() == str60 + select x; + auditorias6 = ( + from x in estipulante11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List auditorias36 = auditorias6; + if (auditorias36.Count == 0) + { + continue; + } + string str61 = str60; + agrupamento1 = this.Agrupamento; + str = str61.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, auditorias36, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List auditorias37 = auditorias11; + if (auditorias37.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias38 = auditorias11; + auditorias7 = ( + from x in auditorias38 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias7 = auditorias11; + } + List auditorias39 = auditorias7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias39, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + List auditorias40 = auditorias11; + IOrderedEnumerable status10 = + from x in auditorias40 + orderby x.get_Status() + select x; + strs = ( + from x in status10 + select x.get_Status()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str62 in strs) + { + if (string.IsNullOrWhiteSpace(str62)) + { + continue; + } + List auditorias41 = auditorias11; + if (auditorias41.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + IEnumerable auditorias42 = auditorias11.Where((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Status() == str62; + }); + auditorias8 = ( + from x in auditorias42 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + else + { + IEnumerable status11 = + from x in auditorias11 + where x.get_Status() == str62 + select x; + auditorias8 = ( + from x in status11 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + List auditorias43 = auditorias8; + if (auditorias43.Count == 0) + { + continue; + } + string str63 = str62; + agrupamento1 = this.Agrupamento; + str = str63.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, auditorias43, this.ColunasOcultas); + } + goto Label1; + } + else + { + List auditorias44 = auditorias11; + if (auditorias44.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias45 = auditorias11; + auditorias9 = ( + from x in auditorias45 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias9 = auditorias11; + } + List auditorias46 = auditorias9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias46, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List auditorias47 = auditorias11; + if (auditorias47.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + List auditorias48 = auditorias11; + auditorias10 = ( + from x in auditorias48 + where x.get_Selecionado() + select x).ToList(); + } + else + { + auditorias10 = auditorias11; + } + List auditorias49 = auditorias10; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", auditorias49, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 9: + case 10: + { + sinistros11 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.SinistroFiltrado == null || sinistros11.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + IEnumerable sinistros12 = ((GridRelatorio)this.Report).DataGrid.Items.Cast(); + IOrderedEnumerable seguradora12 = + from x in sinistros12 + orderby x.get_Seguradora() + select x; + strs = ( + from x in seguradora12 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str64 in strs) + { + if (string.IsNullOrWhiteSpace(str64)) + { + continue; + } + List sinistros13 = sinistros11; + if (sinistros13.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + IEnumerable sinistros14 = sinistros11.Where((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str64; + }); + sinistros = ( + from x in sinistros14 + orderby x.get_DataSinistro() + select x).ToList(); + } + else + { + IEnumerable seguradora13 = + from x in sinistros11 + where x.get_Seguradora() == str64 + select x; + sinistros = ( + from x in seguradora13 + orderby x.get_DataSinistro() + select x).ToList(); + } + List sinistros15 = sinistros; + if (sinistros15.Count == 0) + { + continue; + } + string str65 = str64; + agrupamento1 = this.Agrupamento; + str = str65.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, sinistros15, this.Relatorio, true); + } + goto Label1; + } + else + { + List sinistros16 = sinistros11; + if (sinistros16.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros17 = sinistros11; + sinistros1 = ( + from x in sinistros17 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros1 = sinistros11; + } + List sinistros18 = sinistros1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros18, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + IEnumerable sinistros19 = ((GridRelatorio)this.Report).DataGrid.Items.Cast(); + IOrderedEnumerable ramo12 = + from x in sinistros19 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo12 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str66 in strs) + { + if (string.IsNullOrWhiteSpace(str66)) + { + continue; + } + List sinistros20 = sinistros11; + if (sinistros20.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + IEnumerable sinistros21 = sinistros11.Where((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str66; + }); + sinistros2 = ( + from x in sinistros21 + orderby x.get_DataSinistro() + select x).ToList(); + } + else + { + IEnumerable ramo13 = + from x in sinistros11 + where x.get_Ramo() == str66 + select x; + sinistros2 = ( + from x in ramo13 + orderby x.get_DataSinistro() + select x).ToList(); + } + List sinistros22 = sinistros2; + if (sinistros22.Count == 0) + { + continue; + } + string str67 = str66; + agrupamento1 = this.Agrupamento; + str = str67.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, sinistros22, this.Relatorio, true); + } + goto Label1; + } + else + { + List sinistros23 = sinistros11; + if (sinistros23.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros24 = sinistros11; + sinistros3 = ( + from x in sinistros24 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros3 = sinistros11; + } + List sinistros25 = sinistros3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros25, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + IEnumerable sinistros26 = ((GridRelatorio)this.Report).DataGrid.Items.Cast(); + IOrderedEnumerable vendedor12 = + from x in sinistros26 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor12 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str68 in strs) + { + if (string.IsNullOrWhiteSpace(str68)) + { + continue; + } + List sinistros27 = sinistros11; + if (sinistros27.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + IEnumerable sinistros28 = sinistros11.Where((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str68; + }); + sinistros4 = ( + from x in sinistros28 + orderby x.get_DataSinistro() + select x).ToList(); + } + else + { + IEnumerable vendedor13 = + from x in sinistros11 + where x.get_Vendedor() == str68 + select x; + sinistros4 = ( + from x in vendedor13 + orderby x.get_DataSinistro() + select x).ToList(); + } + List sinistros29 = sinistros4; + if (sinistros29.Count == 0) + { + continue; + } + string str69 = str68; + agrupamento1 = this.Agrupamento; + str = str69.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, sinistros29, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List sinistros30 = sinistros11; + if (sinistros30.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros31 = sinistros11; + sinistros5 = ( + from x in sinistros31 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros5 = sinistros11; + } + List sinistros32 = sinistros5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros32, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + IEnumerable sinistros33 = ((GridRelatorio)this.Report).DataGrid.Items.Cast(); + IOrderedEnumerable estipulante12 = + from x in sinistros33 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante12 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str70 in strs) + { + if (string.IsNullOrWhiteSpace(str70)) + { + continue; + } + List sinistros34 = sinistros11; + if (sinistros34.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + IEnumerable sinistros35 = sinistros11.Where((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str70; + }); + sinistros6 = ( + from x in sinistros35 + orderby x.get_DataSinistro() + select x).ToList(); + } + else + { + IEnumerable estipulante13 = + from x in sinistros11 + where x.get_Estipulante() == str70 + select x; + sinistros6 = ( + from x in estipulante13 + orderby x.get_DataSinistro() + select x).ToList(); + } + List sinistros36 = sinistros6; + if (sinistros36.Count == 0) + { + continue; + } + string str71 = str70; + agrupamento1 = this.Agrupamento; + str = str71.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, sinistros36, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List sinistros37 = sinistros11; + if (sinistros37.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros38 = sinistros11; + sinistros7 = ( + from x in sinistros38 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros7 = sinistros11; + } + List sinistros39 = sinistros7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros39, this.Relatorio, true); + goto Label1; + } + } + case 5: + { + IEnumerable sinistros40 = ((GridRelatorio)this.Report).DataGrid.Items.Cast(); + IOrderedEnumerable statusApolice = + from x in sinistros40 + orderby x.get_StatusApolice() + select x; + strs = ( + from x in statusApolice + select EnumHelper.GetDescription(x.get_StatusSinistro())).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str72 in strs) + { + if (string.IsNullOrWhiteSpace(str72)) + { + continue; + } + List sinistros41 = sinistros11; + if (sinistros41.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + IEnumerable sinistros42 = sinistros11.Where((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_StatusApolice() == str72; + }); + sinistros8 = ( + from x in sinistros42 + orderby x.get_DataSinistro() + select x).ToList(); + } + else + { + IEnumerable statusApolice1 = + from x in sinistros11 + where x.get_StatusApolice() == str72 + select x; + sinistros8 = ( + from x in statusApolice1 + orderby x.get_DataSinistro() + select x).ToList(); + } + List sinistros43 = sinistros8; + if (sinistros43.Count == 0) + { + continue; + } + string str73 = str72; + agrupamento1 = this.Agrupamento; + str = str73.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, sinistros43, this.ColunasOcultas); + } + goto Label1; + } + else + { + List sinistros44 = sinistros11; + if (sinistros44.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros45 = sinistros11; + sinistros9 = ( + from x in sinistros45 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros9 = sinistros11; + } + List sinistros46 = sinistros9; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros46, this.ColunasOcultas); + goto Label1; + } + } + default: + { + List sinistros47 = sinistros11; + if (sinistros47.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + List sinistros48 = sinistros11; + sinistros10 = ( + from x in sinistros48 + where x.get_Selecionado() + select x).ToList(); + } + else + { + sinistros10 = sinistros11; + } + List sinistros49 = sinistros10; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", sinistros49, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 11: + { + List fechamentos = new List(); + if ((GridRelatorio)this.Report != null) + { + fechamentos = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + } + if (this.FechamentoFiltrado == null || fechamentos.Count == 0 && (GridRelatorio)this.Report != null) + { + break; + } + else + { + num = 1; + foreach (Fechamentos fechamento in this.Fechamento) + { + string title1 = fechamento.get_Title(); + agrupamento = this.Agrupamento; + string str74 = title1.ValidaNomePlanilha(agrupamento.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str74, fechamento.get_Fechamento().ToList(), this.Relatorio, true); + num++; + } + goto case 22; + } + } + case 12: + { + List faturaPendentes1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.FaturaPendenteFiltrado == null || faturaPendentes1.Count == 0) + { + break; + } + else + { + List faturaPendentes2 = faturaPendentes1; + if (faturaPendentes2.Any((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => x.get_Selecionado())) + { + List faturaPendentes3 = faturaPendentes1; + faturaPendentes = ( + from x in faturaPendentes3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + faturaPendentes = faturaPendentes1; + } + List faturaPendentes4 = faturaPendentes; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", faturaPendentes4, this.Relatorio, true); + goto case 22; + } + } + case 13: + { + List extratoBaixadoRelatorios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ExtratosFiltrado == null || extratoBaixadoRelatorios1.Count == 0) + { + break; + } + else + { + List extratoBaixadoRelatorios2 = extratoBaixadoRelatorios1; + if (extratoBaixadoRelatorios2.Any((ExtratoBaixadoRelatorio x) => x.get_Selecionado())) + { + List extratoBaixadoRelatorios3 = extratoBaixadoRelatorios1; + extratoBaixadoRelatorios = ( + from x in extratoBaixadoRelatorios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + extratoBaixadoRelatorios = extratoBaixadoRelatorios1; + } + List extratoBaixadoRelatorios4 = extratoBaixadoRelatorios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", extratoBaixadoRelatorios4, this.Relatorio, true); + goto case 22; + } + } + case 14: + { + List metaSeguradoraRelatorios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.MetaSeguradoraFiltrado == null || metaSeguradoraRelatorios1.Count == 0) + { + break; + } + else + { + List metaSeguradoraRelatorios2 = metaSeguradoraRelatorios1; + if (metaSeguradoraRelatorios2.Any((MetaSeguradoraRelatorio x) => x.get_Selecionado())) + { + List metaSeguradoraRelatorios3 = metaSeguradoraRelatorios1; + metaSeguradoraRelatorios = ( + from x in metaSeguradoraRelatorios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + metaSeguradoraRelatorios = metaSeguradoraRelatorios1; + } + List metaSeguradoraRelatorios4 = metaSeguradoraRelatorios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", metaSeguradoraRelatorios4, this.Relatorio, true); + goto case 22; + } + } + case 15: + { + List metaVendedorRelatorios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.MetaVendedorFiltrado == null || metaVendedorRelatorios1.Count == 0) + { + break; + } + else + { + List metaVendedorRelatorios2 = metaVendedorRelatorios1; + if (metaVendedorRelatorios2.Any((MetaVendedorRelatorio x) => x.get_Selecionado())) + { + List metaVendedorRelatorios3 = metaVendedorRelatorios1; + metaVendedorRelatorios = ( + from x in metaVendedorRelatorios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + metaVendedorRelatorios = metaVendedorRelatorios1; + } + List metaVendedorRelatorios4 = metaVendedorRelatorios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", metaVendedorRelatorios4, this.Relatorio, true); + goto case 22; + } + } + case 17: + { + List licenciamentos1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.LicenciamentoFiltrado == null || licenciamentos1.Count == 0) + { + break; + } + else + { + List licenciamentos2 = licenciamentos1; + if (licenciamentos2.Any((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => x.get_Selecionado())) + { + List licenciamentos3 = licenciamentos1; + licenciamentos = ( + from x in licenciamentos3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + licenciamentos = licenciamentos1; + } + List licenciamentos4 = licenciamentos; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", licenciamentos4, this.Relatorio, true); + goto case 22; + } + } + case 18: + { + List tarefas1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.TarefaFiltrado == null || tarefas1.Count == 0) + { + break; + } + else + { + List tarefas2 = tarefas1; + if (tarefas2.Any((Gestor.Model.Domain.Relatorios.Tarefa.Tarefa x) => x.get_Selecionado())) + { + List tarefas3 = tarefas1; + tarefas = ( + from x in tarefas3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + tarefas = tarefas1; + } + List tarefas4 = tarefas; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", tarefas4, this.Relatorio, true); + goto case 22; + } + } + case 19: + { + List notaFiscalRelatorios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.NotaFiscalFiltrado == null || notaFiscalRelatorios1.Count == 0) + { + break; + } + else + { + List notaFiscalRelatorios2 = notaFiscalRelatorios1; + if (notaFiscalRelatorios2.Any((NotaFiscalRelatorio x) => x.get_Selecionado())) + { + List notaFiscalRelatorios3 = notaFiscalRelatorios1; + notaFiscalRelatorios = ( + from x in notaFiscalRelatorios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + notaFiscalRelatorios = notaFiscalRelatorios1; + } + List notaFiscalRelatorios4 = notaFiscalRelatorios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", notaFiscalRelatorios4, this.Relatorio, true); + goto case 22; + } + } + case 20: + { + if (this.PrevisaoFiltrado != null) + { + ObservableCollection previsaoSintetico = this.PrevisaoSintetico; + List previsaoPagamentoComissaoSinteticos = ( + from x in previsaoSintetico + orderby x.get_Titulo() descending + select x).ToList(); + foreach (PrevisaoPagamentoComissaoSintetico previsaoPagamentoComissaoSintetico in previsaoPagamentoComissaoSinteticos) + { + string titulo1 = previsaoPagamentoComissaoSintetico.get_Titulo(); + agrupamento = this.Agrupamento; + string str75 = titulo1.ValidaNomePlanilha(agrupamento.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str75, previsaoPagamentoComissaoSintetico.get_Agrupamento().ToList(), this.Relatorio, false); + } + num = 1; + foreach (PrevisaoPagamentoComissao previsao in this.Previsao) + { + string vendedor14 = previsao.get_Vendedor(); + agrupamento = this.Agrupamento; + string str76 = vendedor14.ValidaNomePlanilha(agrupamento.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str76, previsao.get_PrevisaoPagamento().ToList(), this.Relatorio, true); + num++; + } + goto case 22; + } + else + { + break; + } + } + case 21: + case 22: + { + Label1: + renovacaos10 = null; + producaos6 = null; + apolicePendentes8 = null; + comissaos10 = null; + list11 = null; + sinistros11 = null; + auditorias11 = null; + placas9 = null; + if (this.SinteticoRelatorio != null && this.SinteticoRelatorio.Count > 0) + { + xLWorkbook = await Funcoes.GerarXlsSintetico(xLWorkbook, "SINTÉTICO", this.Sintetic.ToList()); + } + if (this.FiltroRelatorioSelecionado != null && this.FiltroRelatorioSelecionado.Count > 0) + { + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "FILTROS", this.FiltroRelatorioSelecionado.ToList(), this.ColunasOcultas); + } + base.RegistrarAcao(string.Format("EMITIU EXCEL DO RELATÓRIO PERÍODO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim), new Gestor.Model.Common.Relatorio?(this.Relatorio), this.Filtros); + xLWorkbook.SaveAs(str1); + Process.Start(str1); + break; + } + case 23: + { + List logsEnvios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.LogsEnvioFiltrado == null || logsEnvios1.Count == 0) + { + break; + } + else + { + List logsEnvios2 = logsEnvios1; + if (logsEnvios2.Any((Gestor.Model.Domain.Relatorios.LogsEnvio.LogsEnvio x) => x.get_Selecionado())) + { + List logsEnvios3 = logsEnvios1; + logsEnvios = ( + from x in logsEnvios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + logsEnvios = logsEnvios1; + } + List logsEnvios4 = logsEnvios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", logsEnvios4, this.Relatorio, true); + goto case 22; + } + } + case 24: + case 25: + { + List logAcaoRelatorios1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.LogUtilizacaoFiltrado == null || logAcaoRelatorios1.Count == 0) + { + break; + } + else + { + List logAcaoRelatorios2 = logAcaoRelatorios1; + if (logAcaoRelatorios2.Any((LogAcaoRelatorio x) => x.get_Selecionado())) + { + List logAcaoRelatorios3 = logAcaoRelatorios1; + logAcaoRelatorios = ( + from x in logAcaoRelatorios3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + logAcaoRelatorios = logAcaoRelatorios1; + } + List logAcaoRelatorios4 = logAcaoRelatorios; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", logAcaoRelatorios4, this.Relatorio, true); + goto case 22; + } + } + case 26: + { + List apoliceCriticas1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ApoliceCriticaFiltrado == null || apoliceCriticas1.Count == 0) + { + break; + } + else + { + List apoliceCriticas2 = apoliceCriticas1; + if (apoliceCriticas2.Any((Gestor.Model.Domain.Relatorios.CriticaApolice.ApoliceCritica x) => x.get_Selecionado())) + { + List apoliceCriticas3 = apoliceCriticas1; + apoliceCriticas = ( + from x in apoliceCriticas3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + apoliceCriticas = apoliceCriticas1; + } + List apoliceCriticas4 = apoliceCriticas; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", apoliceCriticas4, this.Relatorio, true); + goto case 22; + } + } + case 27: + { + placas9 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.PlacaFiltrado == null || placas9.Count == 0) + { + break; + } + else + { + switch (this.Agrupamento) + { + case 1: + { + List placas10 = placas9; + IOrderedEnumerable placas11 = + from x in placas10 + orderby x.get_Seguradora() + select x; + strs = ( + from x in placas11 + select x.get_Seguradora()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str77 in strs) + { + if (string.IsNullOrWhiteSpace(str77)) + { + continue; + } + List placas12 = placas9; + placas = (placas12.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado()) ? placas9.Where((Gestor.Model.Domain.Relatorios.Placa.Placas x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Seguradora() == str77; + }).ToList() : ( + from x in placas9 + where x.get_Seguradora() == str77 + select x).ToList()); + List placas13 = placas; + if (placas13.Count == 0) + { + continue; + } + string str78 = str77; + agrupamento1 = this.Agrupamento; + str = str78.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, placas13, this.Relatorio, true); + } + goto Label1; + } + else + { + List placas14 = placas9; + if (placas14.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado())) + { + List placas15 = placas9; + placas1 = ( + from x in placas15 + where x.get_Selecionado() + select x).ToList(); + } + else + { + placas1 = placas9; + } + List placas16 = placas1; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", placas16, this.Relatorio, true); + goto Label1; + } + } + case 2: + { + List placas17 = placas9; + IOrderedEnumerable ramo14 = + from x in placas17 + orderby x.get_Ramo() + select x; + strs = ( + from x in ramo14 + select x.get_Ramo()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + foreach (string str79 in strs) + { + if (string.IsNullOrWhiteSpace(str79)) + { + continue; + } + List placas18 = placas9; + placas2 = (placas18.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado()) ? placas9.Where((Gestor.Model.Domain.Relatorios.Placa.Placas x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Ramo() == str79; + }).ToList() : ( + from x in placas9 + where x.get_Ramo() == str79 + select x).ToList()); + List placas19 = placas2; + if (placas19.Count == 0) + { + continue; + } + string str80 = str79; + agrupamento1 = this.Agrupamento; + str = str80.ValidaNomePlanilha(agrupamento1.ToString(), 0); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, placas19, this.Relatorio, true); + } + goto Label1; + } + else + { + List placas20 = placas9; + if (placas20.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado())) + { + List placas21 = placas9; + placas3 = ( + from x in placas21 + where x.get_Selecionado() + select x).ToList(); + } + else + { + placas3 = placas9; + } + List placas22 = placas3; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", placas22, this.Relatorio, true); + goto Label1; + } + } + case 3: + { + List placas23 = placas9; + IOrderedEnumerable vendedor15 = + from x in placas23 + orderby x.get_Vendedor() + select x; + strs = ( + from x in vendedor15 + select x.get_Vendedor()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str81 in strs) + { + if (string.IsNullOrWhiteSpace(str81)) + { + continue; + } + List placas24 = placas9; + placas4 = (placas24.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado()) ? placas9.Where((Gestor.Model.Domain.Relatorios.Placa.Placas x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Vendedor() == str81; + }).ToList() : ( + from x in placas9 + where x.get_Vendedor() == str81 + select x).ToList()); + List placas25 = placas4; + if (placas25.Count == 0) + { + continue; + } + string str82 = str81; + agrupamento1 = this.Agrupamento; + str = str82.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, placas25, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List placas26 = placas9; + if (placas26.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado())) + { + List placas27 = placas9; + placas5 = ( + from x in placas27 + where x.get_Selecionado() + select x).ToList(); + } + else + { + placas5 = placas9; + } + List placas28 = placas5; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", placas28, this.Relatorio, true); + goto Label1; + } + } + case 4: + { + List placas29 = placas9; + IOrderedEnumerable estipulante14 = + from x in placas29 + orderby x.get_Estipulante() + select x; + strs = ( + from x in estipulante14 + select x.get_Estipulante()).Distinct().ToList(); + if ((strs.Count != 2 || strs[0] != null || !(strs[1] == "")) && (strs.Count != 1 || strs[0] != null) && (strs.Count != 1 || !(strs[0] == ""))) + { + num = 1; + foreach (string str83 in strs) + { + if (string.IsNullOrWhiteSpace(str83)) + { + continue; + } + List placas30 = placas9; + placas6 = (placas30.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado()) ? placas9.Where((Gestor.Model.Domain.Relatorios.Placa.Placas x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Estipulante() == str83; + }).ToList() : ( + from x in placas9 + where x.get_Estipulante() == str83 + select x).ToList()); + List placas31 = placas6; + if (placas31.Count == 0) + { + continue; + } + string str84 = str83; + agrupamento1 = this.Agrupamento; + str = str84.ValidaNomePlanilha(agrupamento1.ToString(), num); + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, str, placas31, this.Relatorio, true); + num++; + } + goto Label1; + } + else + { + List placas32 = placas9; + if (placas32.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado())) + { + List placas33 = placas9; + placas7 = ( + from x in placas33 + where x.get_Selecionado() + select x).ToList(); + } + else + { + placas7 = placas9; + } + List placas34 = placas7; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", placas34, this.Relatorio, true); + goto Label1; + } + } + default: + { + List placas35 = placas9; + if (placas35.Any((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.get_Selecionado())) + { + List placas36 = placas9; + placas8 = ( + from x in placas36 + where x.get_Selecionado() + select x).ToList(); + } + else + { + placas8 = placas9; + } + List placas37 = placas8; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", placas37, this.Relatorio, true); + goto Label1; + } + } + } + break; + } + case 28: + { + List endossos1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.EndossoFiltrado == null || endossos1.Count == 0) + { + break; + } + else + { + List endossos2 = endossos1; + if (endossos2.Any((Endosso x) => x.get_Selecionado())) + { + List endossos3 = endossos1; + endossos = ( + from x in endossos3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + endossos = endossos1; + } + List endossos4 = endossos; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", endossos4, this.Relatorio, true); + goto case 22; + } + } + case 29: + { + List classificacaos1 = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ClassificacaoFiltrado == null || classificacaos1.Count == 0) + { + break; + } + else + { + List classificacaos2 = classificacaos1; + if (classificacaos2.Any((Gestor.Model.Domain.Relatorios.Classificacao.Classificacao x) => x.get_Selecionado())) + { + List classificacaos3 = classificacaos1; + classificacaos = ( + from x in classificacaos3 + where x.get_Selecionado() + select x).ToList(); + } + else + { + classificacaos = classificacaos1; + } + List classificacaos4 = classificacaos; + xLWorkbook = await Funcoes.GerarXls(xLWorkbook, "ANALÍTICO", classificacaos4, this.Relatorio, true); + goto case 22; + } + } + default: + { + goto case 22; + } + } + str1 = null; + xLWorkbook = null; + strs = null; + } + + public async Task GerarHtml(bool screen = false, bool pageBreak = false, ConfiguracaoImpressao config = null, bool portrait = false) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.ViewModels.Relatorios.RelatorioViewModel::GerarHtml(System.Boolean,System.Boolean,Gestor.Model.Common.ConfiguracaoImpressao,System.Boolean) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task GerarHtml(System.Boolean,System.Boolean,Gestor.Model.Common.ConfiguracaoImpressao,System.Boolean) + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 526 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // 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.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 112 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 161 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 76 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 36 + // 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 + + } + + private async Task GerarPagamento(List pagamentos) + { + ParcelaServico parcelaServico = new ParcelaServico(); + List pagamentos1 = pagamentos; + List list = pagamentos1.SelectMany((Pagamento x) => x.get_Dados()).ToList(); + List dadosRelatorios = list; + IEnumerable entidadeVendedorParcela = + from x in dadosRelatorios + where x.get_EntidadeVendedorParcela() != null + select x; + if (await parcelaServico.GerarPagamento(( + from x in entidadeVendedorParcela + select x.get_EntidadeVendedorParcela()).ToList())) + { + AdiantamentoServico adiantamentoServico = new AdiantamentoServico(); + List dadosRelatorios1 = list; + IEnumerable dadosRelatorios2 = dadosRelatorios1.Where((DadosRelatorio x) => { + if (x.get_EntidadeAdiantamento() == null) + { + return false; + } + return !x.get_DataPagamento().HasValue; + }); + await adiantamentoServico.GerarPagamento(( + from x in dadosRelatorios2 + select x.get_EntidadeAdiantamento()).ToList()); + base.RegistrarAcao(string.Format("GEROU EMISSÃO DE RECIBO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim), new Gestor.Model.Common.Relatorio?(this.Relatorio), this.Filtros); + } + list = null; + } + + public async Task GerarPlanilhaCompleta() + { + List nums; + List planilhaCompletas; + bool restricao; + object list; + object obj; + bool count; + bool flag; + bool count1; + List list1; + object nums1; + object obj1; + object list2; + List nums2; + List nums3; + List planilhaCompletas1; + List planilhaCompletas2; + string str; + List restricaoUsuarios = await this.ServicoRestriUsuario.BuscarRestricoes(Recursos.Usuario.get_Id()); + RestricaoUsuario restricaoUsuario = restricaoUsuarios.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 99); + if (restricaoUsuario != null) + { + restricao = restricaoUsuario.get_Restricao(); + } + else + { + restricao = false; + } + if (restricao) + { + await base.ShowMessage("VOCÊ NÃO TEM PERMISSÃO PARA ACESSAR O PLANILHA COMPLETA", "OK", "", false); + } + else if ((this.Fim - this.Inicio).TotalDays <= 31) + { + base.Loading(true); + nums2 = new List(); + nums3 = new List(); + List configuracoes = Recursos.Configuracoes; + bool flag1 = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 40); + bool flag2 = false; + Gestor.Model.Common.Relatorio relatorio = this.Relatorio; + if (relatorio == 2) + { + ObservableCollection producaoFiltrado = this.ProducaoFiltrado; + if (producaoFiltrado != null) + { + IEnumerable producaos = producaoFiltrado.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Tipo() != 2; + }); + list = ( + from x in producaos + select x.get_Documento().get_Id()).ToList(); + } + else + { + list = null; + } + if (list == null) + { + list = new List(); + } + nums = (List)list; + ObservableCollection observableCollection = this.ProducaoFiltrado; + if (observableCollection != null) + { + IEnumerable producaos1 = observableCollection.Where((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Tipo() == 2; + }); + obj = ( + from x in producaos1 + select x.get_Documento().get_Id()).ToList(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = new List(); + } + nums3 = (List)obj; + if (nums.Count == 0 && nums3.Count == 0) + { + await base.ShowMessage("É NECESSÁRIO SELECIONAR AO MENOS UM DOCUMENTO", "OK", "", false); + nums2 = null; + nums3 = null; + planilhaCompletas1 = null; + planilhaCompletas2 = null; + str = null; + return; + } + } + else if (relatorio == 4) + { + List configuracaoSistemas = Recursos.Configuracoes; + flag2 = configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 31); + ObservableCollection renovacaoFiltrado = this.RenovacaoFiltrado; + if (renovacaoFiltrado != null) + { + ( + from x in renovacaoFiltrado + where x.get_Selecionado() + select x).ToList(); + } + else + { + } + ObservableCollection renovacaoFiltrado1 = this.RenovacaoFiltrado; + if (renovacaoFiltrado1 != null) + { + IEnumerable renovacaos = renovacaoFiltrado1.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado() || x.get_Documento() == null) + { + return false; + } + return !x.get_TipoPagamento().Equals("FATURA"); + }); + nums1 = ( + from x in renovacaos + select x.get_Documento().get_Id()).ToList(); + } + else + { + nums1 = null; + } + if (nums1 == null) + { + nums1 = new List(); + } + nums = (List)nums1; + ObservableCollection observableCollection1 = this.RenovacaoFiltrado; + if (observableCollection1 != null) + { + IEnumerable renovacaos1 = observableCollection1.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado() || x.get_Documento() == null) + { + return false; + } + return x.get_TipoPagamento().Equals("FATURA"); + }); + obj1 = ( + from x in renovacaos1 + select x.get_Documento().get_Id()).ToList(); + } + else + { + obj1 = null; + } + if (obj1 == null) + { + obj1 = new List(); + } + nums3 = (List)obj1; + ObservableCollection renovacaoFiltrado2 = this.RenovacaoFiltrado; + if (renovacaoFiltrado2 != null) + { + IEnumerable renovacaos2 = renovacaoFiltrado2.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (!x.get_Selecionado()) + { + return false; + } + return x.get_Prospeccao() != null; + }); + list2 = ( + from x in renovacaos2 + select x.get_Prospeccao().get_Id()).ToList(); + } + else + { + list2 = null; + } + if (list2 == null) + { + list2 = new List(); + } + nums2 = (List)list2; + if (nums.Count == 0 && nums3.Count == 0 && nums2.Count == 0) + { + await base.ShowMessage("É NECESSÁRIO SELECIONAR AO MENOS UM DOCUMENTO", "OK", "", false); + nums2 = null; + nums3 = null; + planilhaCompletas1 = null; + planilhaCompletas2 = null; + str = null; + return; + } + } + else + { + base.Loading(false); + nums2 = null; + nums3 = null; + planilhaCompletas1 = null; + planilhaCompletas2 = null; + str = null; + return; + } + if (nums == null || nums.Count <= 0) + { + planilhaCompletas = new List(); + } + else + { + planilhaCompletas = await this._apoliceServico.BuscarPlanilhaCompleta(nums, flag1, flag2); + } + planilhaCompletas1 = planilhaCompletas; + List nums4 = nums3; + if (nums4 != null) + { + count = nums4.Count > 0; + } + else + { + count = false; + } + if (!count) + { + planilhaCompletas = new List(); + } + else + { + planilhaCompletas = await this._apoliceServico.BuscarPlanilhaCompletaFatura(nums3, this.Relatorio, this.Filtros.get_Inicio(), this.Filtros.get_Fim(), flag1, flag2); + } + planilhaCompletas2 = planilhaCompletas; + List nums5 = nums2; + if (nums5 != null) + { + flag = nums5.Count > 0; + } + else + { + flag = false; + } + if (!flag) + { + planilhaCompletas = new List(); + } + else + { + planilhaCompletas = await this._apoliceServico.BuscarPlanilhaCompletaProspeccao(nums2); + } + List planilhaCompletas3 = planilhaCompletas; + if (planilhaCompletas1 == null || planilhaCompletas2 == null || planilhaCompletas3 == null) + { + await base.ShowMessage("ERRO AO GERAR PLANILHA COMPLETA, TENTE NOVAMENTE MAIS TARDE.", "OK", "", false); + base.Loading(false); + } + else + { + planilhaCompletas1.AddRange(planilhaCompletas2); + planilhaCompletas1.AddRange(planilhaCompletas3); + List planilhaCompletas4 = planilhaCompletas1; + if (planilhaCompletas4 != null) + { + count1 = planilhaCompletas4.Count == 0; + } + else + { + count1 = false; + } + if (!count1) + { + if (this.Relatorio == 4) + { + List planilhaCompletas5 = planilhaCompletas1; + list1 = ( + from x in planilhaCompletas5 + orderby x.get_VigenciaFinal() + select x).ToList(); + } + else + { + List planilhaCompletas6 = planilhaCompletas1; + list1 = ( + from x in planilhaCompletas6 + orderby x.get_VigenciaInicial() + select x).ToList(); + } + planilhaCompletas1 = list1; + string tempPath = ""; + str = ""; + List configuracoes1 = Recursos.Configuracoes; + if (!configuracoes1.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + nums2 = null; + nums3 = null; + planilhaCompletas1 = null; + planilhaCompletas2 = null; + str = null; + return; + } + } + string[] description = new string[] { tempPath, EnumHelper.GetDescription(this.Relatorio), " ", null, null }; + DateTime date = Functions.GetNetworkTime().Date; + description[3] = date.ToShortDateString().Replace("/", ""); + description[4] = ".xlsx"; + str = string.Concat(description); + } + await Funcoes.GerarXls(new XLWorkbook(), "PLANILHA COMPLETA", planilhaCompletas1, new List()).SaveAs(str); + Process.Start(str); + base.Loading(false); + } + else + { + await base.ShowMessage("NÃO HÁ DADOS PARA EMISSÃO DA PLANILHA COMPLETA.", "OK", "", false); + base.Loading(false); + } + } + } + else + { + await base.ShowMessage("NÃO É POSSÍVEL GERAR A PLANILHA COMPLETA COM INTERVALO MAIOR QUE 31 DIAS FILTRADOS.", "OK", "", false); + } + nums2 = null; + nums3 = null; + planilhaCompletas1 = null; + planilhaCompletas2 = null; + str = null; + } + + public async Task GerarRelatorio(DateTime? inicio, DateTime? fim) + { + // + // Current member / type: System.Threading.Tasks.Task`1 Gestor.Application.ViewModels.Relatorios.RelatorioViewModel::GerarRelatorio(System.Nullable`1,System.Nullable`1) + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Threading.Tasks.Task GerarRelatorio(System.Nullable,System.Nullable) + // + // An item with the same key has already been added. Key: Label0 + // at System.Collections.Generic.Dictionary`2.TryInsert(TKey key, TValue value, InsertionBehavior behavior) + // at System.Collections.Generic.Dictionary`2.System.Collections.Generic.ICollection>.Add(KeyValuePair`2 keyValuePair) + // at Telerik.JustDecompiler.Common.Extensions.AddRange[TKey,TValue](IDictionary`2 self, IDictionary`2 source) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Common\Extensions.cs:line 101 + // at Telerik.JustDecompiler.Steps.RebuildAnonymousDelegatesStep.AnonymousDelegateRebuilder.VisitObjectCreationExpression(ObjectCreationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAnonymousDelegatesStep.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit[TCollection,TElement](TCollection original) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 312 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.VisitMethodInvocationExpression(MethodInvocationExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 500 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 273 + // at Telerik.JustDecompiler.Ast.BaseCodeTransformer.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.VisitBinaryExpression(BinaryExpression node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 531 + // 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.VisitConditionCase(ConditionCase node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 452 + // 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.VisitSwitchStatement(SwitchStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeTransformer.cs:line 470 + // 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.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.VisitTryStatement(TryStatement node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 510 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(ICodeNode node) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 351 + // at Telerik.JustDecompiler.Ast.BaseCodeVisitor.Visit(IEnumerable collection) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Ast\BaseCodeVisitor.cs:line 384 + // 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 GerarTarefas(Gestor.Model.Domain.Ferramentas.Tarefa tarefa) + { + List tarefas = new List(); + Usuario usuario = tarefa.get_Usuario(); + switch (this.Relatorio) + { + case 0: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa1 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa1.set_Entidade(2); + tarefa1.set_IdEntidade(x.get_Id()); + tarefa1.set_Agendamento(tarefa.get_Agendamento()); + tarefa1.set_Titulo(tarefa.get_Titulo()); + tarefa1.set_Descricao(tarefa.get_Anotacoes()); + tarefa1.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa1.set_Usuario(usuario); + tarefa1.set_UsuarioCadastro(Recursos.Usuario); + tarefa1.set_Cliente(x.get_Nome()); + tarefa1.set_IdCliente(x.get_Id()); + return tarefa1; + }).ToList(); + return tarefas; + } + } + return null; + } + case 1: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + if (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa2 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa2.set_Entidade(2); + tarefa2.set_IdEntidade(x.get_Id()); + tarefa2.set_Agendamento(tarefa.get_Agendamento()); + tarefa2.set_Titulo(tarefa.get_Titulo()); + tarefa2.set_Descricao(tarefa.get_Anotacoes()); + tarefa2.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa2.set_Usuario(usuario); + tarefa2.set_UsuarioCadastro(Recursos.Usuario); + tarefa2.set_Cliente(x.get_Nome()); + tarefa2.set_IdCliente(x.get_Id()); + return tarefa2; + }).ToList(); + return tarefas; + } + } + return null; + } + case 2: + case 7: + case 11: + case 12: + case 13: + { + if (this.ProducaoFiltrado != null && this.ProducaoFiltrado.Count != 0) + { + if (this.ProducaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.ProducaoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa3 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa3.set_Entidade(0); + tarefa3.set_IdEntidade(x.get_Documento().get_Id()); + tarefa3.set_Agendamento(tarefa.get_Agendamento()); + tarefa3.set_Titulo(tarefa.get_Titulo()); + tarefa3.set_Descricao(tarefa.get_Anotacoes()); + tarefa3.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa3.set_Usuario(usuario); + tarefa3.set_UsuarioCadastro(Recursos.Usuario); + tarefa3.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa3.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa3.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice(), " ENDOSSO ", x.get_Documento().get_Endosso()) : string.Concat("PROPOSTA NÚMERO ", x.get_Documento().get_Proposta())) : string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice()))); + return tarefa3; + }).ToList(); + return tarefas; + } + } + return null; + } + case 3: + { + if (this.ApolicePendenteFiltrado != null && this.ApolicePendenteFiltrado.Count != 0) + { + if (this.ApolicePendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.ApolicePendenteFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa4 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa4.set_Entidade(0); + tarefa4.set_IdEntidade(x.get_Documento().get_Id()); + tarefa4.set_Agendamento(tarefa.get_Agendamento()); + tarefa4.set_Titulo(tarefa.get_Titulo()); + tarefa4.set_Descricao(tarefa.get_Anotacoes()); + tarefa4.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa4.set_Usuario(usuario); + tarefa4.set_UsuarioCadastro(Recursos.Usuario); + tarefa4.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa4.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa4.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice(), " ENDOSSO ", x.get_Documento().get_Endosso()) : string.Concat("PROPOSTA NÚMERO ", x.get_Documento().get_Proposta())) : string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice()))); + return tarefa4; + }).ToList(); + return tarefas; + } + } + return null; + } + case 4: + { + if (this.RenovacaoFiltrado != null && this.RenovacaoFiltrado.Count != 0) + { + if (this.RenovacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + IEnumerable renovacaoFiltrado = + from x in this.RenovacaoFiltrado + where x.get_Documento() != null + select x; + IEnumerable renovacaos = + from x in this.RenovacaoFiltrado + where x.get_Prospeccao() != null + select x; + List list = new List(); + List tarefas1 = new List(); + Gestor.Model.Domain.Relatorios.Renovacao.Renovacao[] array = renovacaoFiltrado as Gestor.Model.Domain.Relatorios.Renovacao.Renovacao[] ?? renovacaoFiltrado.ToArray(); + if (array.Any()) + { + list = ( + from x in array + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa5 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa5.set_Entidade(0); + tarefa5.set_IdEntidade(x.get_Documento().get_Id()); + tarefa5.set_Agendamento(tarefa.get_Agendamento()); + tarefa5.set_Titulo(tarefa.get_Titulo()); + tarefa5.set_Descricao(tarefa.get_Anotacoes()); + tarefa5.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa5.set_Usuario(usuario); + tarefa5.set_UsuarioCadastro(Recursos.Usuario); + tarefa5.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa5.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa5.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice(), " ENDOSSO ", x.get_Documento().get_Endosso()) : string.Concat("PROPOSTA NÚMERO ", x.get_Documento().get_Proposta())) : string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice()))); + return tarefa5; + }).ToList(); + } + Gestor.Model.Domain.Relatorios.Renovacao.Renovacao[] renovacaoArray = renovacaos as Gestor.Model.Domain.Relatorios.Renovacao.Renovacao[] ?? renovacaos.ToArray(); + if (renovacaoArray.Any()) + { + tarefas1 = ( + from x in renovacaoArray + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa6 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa6.set_Entidade(5); + tarefa6.set_IdEntidade(x.get_Prospeccao().get_Id()); + tarefa6.set_Agendamento(tarefa.get_Agendamento()); + tarefa6.set_Titulo(tarefa.get_Titulo()); + tarefa6.set_Descricao(tarefa.get_Anotacoes()); + tarefa6.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa6.set_Usuario(usuario); + tarefa6.set_UsuarioCadastro(Recursos.Usuario); + tarefa6.set_Cliente(x.get_Prospeccao().get_Nome()); + DateTime? vigenciaFinal = x.get_VigenciaFinal(); + tarefa6.set_Referencia(string.Concat("PROSPECÇÃO ", (vigenciaFinal.HasValue ? vigenciaFinal.GetValueOrDefault().ToString("d") : null))); + return tarefa6; + }).ToList(); + } + tarefas.AddRange(list); + tarefas.AddRange(tarefas1); + if (tarefas.Count <= 0) + { + return null; + } + return tarefas; + } + } + return null; + } + case 5: + { + if (this.ComissaoFiltrado != null && this.ComissaoFiltrado.Count != 0) + { + if (this.ComissaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.ComissaoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa7 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa7.set_Entidade(3); + tarefa7.set_IdEntidade(x.get_ParcelaEntity().get_Id()); + tarefa7.set_Agendamento(tarefa.get_Agendamento()); + tarefa7.set_Titulo(tarefa.get_Titulo()); + tarefa7.set_Descricao(tarefa.get_Anotacoes()); + tarefa7.set_Usuario(usuario); + tarefa7.set_UsuarioCadastro(Recursos.Usuario); + tarefa7.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa7.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa7.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Concat(new string[] { "PARCELA ", x.get_Parcela(), " DA APÓLICE ", x.get_Documento().get_Apolice(), " ENDOSSO ", x.get_Documento().get_Endosso() }) : string.Concat("PARCELA ", x.get_Parcela(), " DA PROPOSTA ", x.get_Documento().get_Proposta())) : string.Concat("PARCELA ", x.get_Parcela(), " DA APÓLICE ", x.get_Documento().get_Apolice()))); + tarefa7.set_Responsaveis(tarefa.get_Responsaveis()); + return tarefa7; + }).ToList(); + return tarefas; + } + } + return null; + } + case 6: + case 16: + { + if (this.PendenteFiltrado != null && this.PendenteFiltrado.Count != 0) + { + if (this.PendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.PendenteFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa8 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa8.set_Entidade(3); + tarefa8.set_IdEntidade(x.get_ParcelaEntity().get_Id()); + tarefa8.set_Agendamento(tarefa.get_Agendamento()); + tarefa8.set_Titulo(tarefa.get_Titulo()); + tarefa8.set_Descricao(tarefa.get_Anotacoes()); + tarefa8.set_Usuario(usuario); + tarefa8.set_UsuarioCadastro(Recursos.Usuario); + tarefa8.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa8.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa8.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Format("PARCELA {0} DA APÓLICE {1} ENDOSSO {2}", x.get_ParcelaEntity().get_NumeroParcela(), x.get_Documento().get_Apolice(), x.get_Documento().get_Endosso()) : string.Format("PARCELA {0} DA PROPOSTA {1}", x.get_ParcelaEntity().get_NumeroParcela(), x.get_Documento().get_Proposta())) : string.Format("PARCELA {0} DA APÓLICE {1}", x.get_ParcelaEntity().get_NumeroParcela(), x.get_Documento().get_Apolice()))); + tarefa8.set_Responsaveis(tarefa.get_Responsaveis()); + return tarefa8; + }).ToList(); + return tarefas; + } + } + return null; + } + case 8: + { + if (this.AuditoriaFiltrado != null && this.AuditoriaFiltrado.Count != 0) + { + if (this.AuditoriaFiltrado.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.AuditoriaFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa9 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa9.set_Entidade(0); + tarefa9.set_IdEntidade(x.get_Documento().get_Id()); + tarefa9.set_Agendamento(tarefa.get_Agendamento()); + tarefa9.set_Titulo(tarefa.get_Titulo()); + tarefa9.set_Descricao(tarefa.get_Anotacoes()); + tarefa9.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa9.set_Usuario(usuario); + tarefa9.set_UsuarioCadastro(Recursos.Usuario); + tarefa9.set_Cliente(x.get_Documento().get_Controle().get_Cliente().get_Nome()); + tarefa9.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa9.set_Referencia((x.get_Documento().get_Tipo() != 0 || string.IsNullOrWhiteSpace(x.get_Documento().get_Apolice()) ? (x.get_Documento().get_Tipo() > 0 ? string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice(), " ENDOSSO ", x.get_Documento().get_Endosso()) : string.Concat("PROPOSTA NÚMERO ", x.get_Documento().get_Proposta())) : string.Concat("APÓLICE NÚMERO ", x.get_Documento().get_Apolice()))); + return tarefa9; + }).ToList(); + return tarefas; + } + } + return null; + } + case 9: + case 10: + { + if (this.SinistroFiltrado != null && this.SinistroFiltrado.Count != 0) + { + if (this.SinistroFiltrado.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.SinistroFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa10 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa10.set_Entidade(4); + tarefa10.set_IdEntidade(x.get_EntidadeSinistro().get_Id()); + tarefa10.set_Agendamento(tarefa.get_Agendamento()); + tarefa10.set_Titulo(tarefa.get_Titulo()); + tarefa10.set_Descricao(tarefa.get_Anotacoes()); + tarefa10.set_Usuario(usuario); + tarefa10.set_UsuarioCadastro(Recursos.Usuario); + tarefa10.set_Cliente(x.get_Nome()); + tarefa10.set_IdCliente(x.get_EntidadeSinistro().get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa10.set_Referencia(string.Concat("SINISTRO ", x.get_NumeroSinistro(), " - ITEM ", x.get_Item())); + tarefa10.set_Responsaveis(tarefa.get_Responsaveis()); + return tarefa10; + }).ToList(); + return tarefas; + } + } + return null; + } + case 14: + { + if (this.MetaSeguradoraFiltrado != null && this.MetaSeguradoraFiltrado.Count != 0) + { + if (this.MetaSeguradoraFiltrado.Any((MetaSeguradoraRelatorio x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.MetaSeguradoraFiltrado + where x.get_Selecionado() + select x).Select((MetaSeguradoraRelatorio x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa11 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa11.set_Entidade(7); + tarefa11.set_IdEntidade(x.get_Id()); + tarefa11.set_Agendamento(tarefa.get_Agendamento()); + tarefa11.set_Titulo(tarefa.get_Titulo()); + tarefa11.set_Descricao(tarefa.get_Anotacoes()); + tarefa11.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa11.set_Usuario(usuario); + tarefa11.set_UsuarioCadastro(Recursos.Usuario); + tarefa11.set_Cliente(x.get_Seguradora()); + tarefa11.set_Referencia(string.Concat("SEGURADORA ", x.get_Seguradora())); + return tarefa11; + }).ToList(); + return tarefas; + } + } + return null; + } + case 15: + { + if (this.MetaVendedorFiltrado != null && this.MetaVendedorFiltrado.Count != 0) + { + if (this.MetaVendedorFiltrado.Any((MetaVendedorRelatorio x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.MetaVendedorFiltrado + where x.get_Selecionado() + select x).Select((MetaVendedorRelatorio x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa12 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa12.set_Entidade(6); + tarefa12.set_IdEntidade(x.get_Id()); + tarefa12.set_Agendamento(tarefa.get_Agendamento()); + tarefa12.set_Titulo(tarefa.get_Titulo()); + tarefa12.set_Descricao(tarefa.get_Anotacoes()); + tarefa12.set_Responsaveis(tarefa.get_Responsaveis()); + tarefa12.set_Usuario(usuario); + tarefa12.set_UsuarioCadastro(Recursos.Usuario); + tarefa12.set_Cliente(x.get_Vendedor()); + tarefa12.set_Referencia(string.Concat("VENDEDOR ", x.get_Vendedor())); + return tarefa12; + }).ToList(); + return tarefas; + } + } + return null; + } + case 17: + { + if (this.LicenciamentoFiltrado != null && this.LicenciamentoFiltrado.Count != 0) + { + if (this.LicenciamentoFiltrado.Any((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => x.get_Selecionado())) + { + tarefas = ( + from x in this.LicenciamentoFiltrado + where x.get_Selecionado() + select x).Select((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => { + Gestor.Model.Domain.Ferramentas.Tarefa tarefa13 = new Gestor.Model.Domain.Ferramentas.Tarefa(); + tarefa13.set_Entidade(2); + tarefa13.set_IdEntidade(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa13.set_Agendamento(tarefa.get_Agendamento()); + tarefa13.set_Titulo(tarefa.get_Titulo()); + tarefa13.set_Descricao(tarefa.get_Anotacoes()); + tarefa13.set_Usuario(usuario); + tarefa13.set_UsuarioCadastro(Recursos.Usuario); + tarefa13.set_Cliente(x.get_Cliente()); + tarefa13.set_IdCliente(x.get_Documento().get_Controle().get_Cliente().get_Id()); + tarefa13.set_Referencia(string.Concat("VENCIMENTO CRLV ", x.get_Placa(), " - ITEM ", x.get_Item())); + tarefa13.set_Responsaveis(tarefa.get_Responsaveis()); + return tarefa13; + }).ToList(); + return tarefas; + } + } + return null; + } + default: + { + goto case 13; + } + } + } + + private static string JoinEmails(List emails) + { + if (emails == null) + { + return ""; + } + return string.Join(" | ", ( + from v in emails + where !string.IsNullOrEmpty(v.get_Email()) + select v.get_Email()).Distinct()); + } + + private static string JoinTelefones(List telefones) + { + if (telefones == null) + { + return ""; + } + return string.Join(" | ", + from v in telefones + select string.Concat(v.get_Prefixo(), " ", v.get_Numero())); + } + + public void LimparFiltros() + { + this._alterandoFiltros = true; + this.FiltroRelatorioSelecionado = null; + foreach (StatusRelatorio statusRelatorio in + from x in this.TipoSeguros + where x.get_Selecionado() + select x) + { + statusRelatorio.set_Selecionado(false); + } + foreach (Seguradora seguradora in + from x in this.Seguradoras + where x.get_Selecionado() + select x) + { + seguradora.set_Selecionado(false); + } + foreach (Ramo ramo in + from x in this.Ramos + where x.get_Selecionado() + select x) + { + ramo.set_Selecionado(false); + } + foreach (Estipulante estipulante in + from x in this.Estipulantes + where x.get_Selecionado() + select x) + { + estipulante.set_Selecionado(false); + } + foreach (Vendedor vendedor in + from x in this.Vendedores + where x.get_Selecionado() + select x) + { + vendedor.set_Selecionado(false); + } + foreach (Gestor.Model.Domain.Seguros.TipoVendedor tipoVendedor in + from x in this.TipoVendedor + where x.get_Selecionado() + select x) + { + tipoVendedor.set_Selecionado(false); + } + foreach (Gestor.Model.Domain.Seguros.Produto produto in + from x in this.Produtos + where x.get_Selecionado() + select x) + { + produto.set_Selecionado(false); + } + foreach (NegocioRelatorio negocioRelatorio in + from x in this.Negocios + where x.get_Selecionado() + select x) + { + negocioRelatorio.set_Selecionado(false); + } + this._alterandoFiltros = false; + } + + private void LimparFiltroUsuario() + { + ExtensionMethods.ForEach(this.UsuariosFiltrados, (Usuario x) => x.set_Selecionado(false)); + } + + public void LimparRelatorio() + { + this.RelatorioVisibility = false; + this.VisibilityFiltroPersonalizado = Visibility.Collapsed; + } + + private async Task LoadVendedores() + { + List list; + this.Vinculo = await base.VerificaVinculoVendedor(Recursos.Usuario); + RelatorioViewModel relatorioViewModel = this; + if (this.Vinculo.Count > 0) + { + IEnumerable vendedores = + from x in Recursos.Vendedores + where this.Vinculo.Any((VendedorUsuario y) => y.get_Vendedor().get_Id() == x.get_Id()) + select x; + list = ( + from x in vendedores + orderby x.get_Nome() + select x).ToList(); + } + else + { + List vendedors = Recursos.Vendedores; + IEnumerable vendedors1 = vendedors.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() == (long)1) + { + return true; + } + return x.get_IdEmpresa() == Recursos.Usuario.get_IdEmpresa(); + }); + list = ( + from x in vendedors1 + orderby x.get_Nome() + select x).ToList(); + } + relatorioViewModel.Vendedores = list; + RelatorioViewModel list1 = this; + List usuarios = Recursos.Usuarios; + IEnumerable excluido = + from x in usuarios + where !x.get_Excluido() + select x; + list1.Usuarios = ( + from x in excluido + orderby x.get_Nome() + select x).ToList(); + this.UsuariosFiltrados = new ObservableCollection(this.Usuarios); + } + + public async void MostrarProtocolo() + { + switch (this.Relatorio) + { + case 2: + { + ObservableCollection producaoFiltrado = this.ProducaoFiltrado; + if (producaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado())) + { + RelatorioViewModel relatorioViewModel = this; + ObservableCollection observableCollection = this.ProducaoFiltrado; + IEnumerable selecionado = + from x in observableCollection + where x.get_Selecionado() + select x; + this.PrepararProtocolo(await relatorioViewModel.ShowProtocoloDialog(( + from x in selecionado + select x.get_Documento()).ToList())); + break; + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR OS DOCUMENTOS PARA EMISSÃO DE PROTOCOLO", "OK", "", false); + break; + } + } + case 3: + { + ObservableCollection apolicePendenteFiltrado = this.ApolicePendenteFiltrado; + if (apolicePendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado())) + { + RelatorioViewModel relatorioViewModel1 = this; + ObservableCollection apolicePendenteFiltrado1 = this.ApolicePendenteFiltrado; + IEnumerable apolicePendentes = + from x in apolicePendenteFiltrado1 + where x.get_Selecionado() + select x; + this.PrepararProtocolo(await relatorioViewModel1.ShowProtocoloDialog(( + from x in apolicePendentes + select x.get_Documento()).ToList())); + break; + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR OS DOCUMENTOS PARA EMISSÃO DE PROTOCOLO", "OK", "", false); + break; + } + } + case 4: + { + ObservableCollection renovacaoFiltrado = this.RenovacaoFiltrado; + if (renovacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado())) + { + RelatorioViewModel relatorioViewModel2 = this; + ObservableCollection renovacaoFiltrado1 = this.RenovacaoFiltrado; + IEnumerable renovacaos = + from x in renovacaoFiltrado1 + where x.get_Selecionado() + select x; + this.PrepararProtocolo(await relatorioViewModel2.ShowProtocoloDialog(( + from x in renovacaos + select x.get_Documento()).ToList())); + break; + } + else + { + await base.ShowMessage("NECESSÁRIO SELECIONAR OS DOCUMENTOS PARA EMISSÃO DE PROTOCOLO", "OK", "", false); + break; + } + } + } + } + + private void NegocioOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(9); + } + + public void PesquisaPersonalizada() + { + switch (this.Relatorio) + { + case 0: + { + this.FiltrarRamo(); + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 1: + { + this.ClientesAtivosInativosFiltrado = new ObservableCollection(this.ClientesAtivosInativos.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ClientesAtivosInativosFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 2: + { + this.ProducaoFiltrado = new ObservableCollection(this.Producao.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ProducaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 3: + { + this.ApolicePendenteFiltrado = new ObservableCollection(this.ApolicePendente.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ApolicePendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 4: + { + this.RenovacaoFiltrado = new ObservableCollection(this.Renovacao.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.RenovacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 5: + { + this.ComissaoFiltrado = new ObservableCollection(this.Comissao.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ComissaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 6: + case 16: + { + this.PendenteFiltrado = new ObservableCollection(this.Pendente.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.PendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 7: + case 11: + case 20: + case 21: + case 22: + { + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 8: + { + this.AuditoriaFiltrado = new ObservableCollection(this.Auditoria.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.AuditoriaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 9: + case 10: + { + this.SinistroFiltrado = new ObservableCollection(this.Sinistro.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.SinistroFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 12: + { + this.FaturaPendenteFiltrado = new ObservableCollection(this.FaturaPendente.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.FaturaPendenteFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 13: + { + this.ExtratosFiltrado = new ObservableCollection(this.Extratos.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ExtratosFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 14: + { + this.MetaSeguradoraFiltrado = new ObservableCollection(this.MetaSeguradora.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.MetaSeguradoraFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 15: + { + this.MetaVendedorFiltrado = new ObservableCollection(this.MetaVendedor.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.MetaVendedorFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 17: + { + this.LicenciamentoFiltrado = new ObservableCollection(this.Licenciamento.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LicenciamentoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 18: + { + this.TarefaFiltrado = new ObservableCollection(this.Tarefa.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.TarefaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 19: + { + this.NotaFiscalFiltrado = new ObservableCollection(this.NotasFiscais.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.NotaFiscalFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 23: + { + this.LogsEnvioFiltrado = new ObservableCollection(this.LogsEnvio.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LogsEnvioFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 24: + case 25: + { + this.LogUtilizacaoFiltrado = new ObservableCollection(this.LogUtilizacao.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.LogUtilizacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 26: + { + this.ApoliceCriticaFiltrado = new ObservableCollection(this.ApoliceCritica.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ApoliceCriticaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 27: + { + this.PlacaFiltrado = new ObservableCollection(this.Placas.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.PlacaFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 28: + { + this.EndossoFiltrado = new ObservableCollection(this.Endossoo.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.EndossoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + case 29: + { + this.ClassificacaoFiltrado = new ObservableCollection(this.Classificacao.CustomWhere(this.FiltroPersonalizadoSelecionado.ToList(), this.ValorIgual)); + ((GridRelatorio)this.Report).DataGrid.ItemsSource = this.ClassificacaoFiltrado; + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + default: + { + ((GridRelatorio)this.Report).SinteticoGrid.ItemsSource = this.Sintetic; + return; + } + } + } + + private async void PopularRelatorio(string opcao) + { + bool restricao; + bool flag; + bool restricao1; + bool flag1; + bool restricao2; + bool flag2; + bool restricao3; + bool flag3; + bool restricao4; + bool flag4; + bool restricao5; + bool flag5; + bool restricao6; + bool flag6; + bool restricao7; + bool flag7; + bool restricao8; + bool flag8; + bool restricao9; + bool flag9; + bool restricao10; + bool flag10; + bool restricao11; + bool flag11; + bool restricao12; + bool flag12; + bool restricao13; + bool flag13; + this.Relatorios = new List(); + List restricaoUsuarios = await this.ServicoRestriUsuario.BuscarRestricoes(Recursos.Usuario.get_Id()); + Gestor.Model.Common.Relatorio[] values = (Gestor.Model.Common.Relatorio[])Enum.GetValues(typeof(Gestor.Model.Common.Relatorio)); + foreach (Gestor.Model.Common.Relatorio relatorio in + from x in values + orderby EnumHelper.GetDescription(x) + select x) + { + if (Gestor.Common.Validation.ValidationHelper.GetTipo(relatorio) != opcao) + { + continue; + } + switch (relatorio) + { + case 0: + { + List restricaoUsuarios1 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario = restricaoUsuarios1.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 30); + if (restricaoUsuario != null) + { + restricao = restricaoUsuario.get_Restricao(); + } + else + { + restricao = false; + } + if (restricao) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 1: + { + List restricaoUsuarios2 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario1 = restricaoUsuarios2.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 49); + if (restricaoUsuario1 != null) + { + flag = restricaoUsuario1.get_Restricao(); + } + else + { + flag = false; + } + if (flag) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 2: + { + List restricaoUsuarios3 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario2 = restricaoUsuarios3.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 23); + if (restricaoUsuario2 != null) + { + restricao1 = restricaoUsuario2.get_Restricao(); + } + else + { + restricao1 = false; + } + if (restricao1) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 3: + { + List restricaoUsuarios4 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario3 = restricaoUsuarios4.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 34); + if (restricaoUsuario3 != null) + { + flag1 = restricaoUsuario3.get_Restricao(); + } + else + { + flag1 = false; + } + if (flag1) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 4: + { + List restricaoUsuarios5 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario4 = restricaoUsuarios5.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 24); + if (restricaoUsuario4 != null) + { + restricao2 = restricaoUsuario4.get_Restricao(); + } + else + { + restricao2 = false; + } + if (restricao2) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 5: + { + List restricaoUsuarios6 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario5 = restricaoUsuarios6.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 27); + if (restricaoUsuario5 != null) + { + flag2 = restricaoUsuario5.get_Restricao(); + } + else + { + flag2 = false; + } + if (flag2) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 6: + { + List restricaoUsuarios7 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario6 = restricaoUsuarios7.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 29); + if (restricaoUsuario6 != null) + { + restricao3 = restricaoUsuario6.get_Restricao(); + } + else + { + restricao3 = false; + } + if (restricao3) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 7: + { + List restricaoUsuarios8 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario7 = restricaoUsuarios8.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 28); + if (restricaoUsuario7 != null) + { + flag3 = restricaoUsuario7.get_Restricao(); + } + else + { + flag3 = false; + } + if (flag3) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 8: + { + List restricaoUsuarios9 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario8 = restricaoUsuarios9.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 46); + if (restricaoUsuario8 != null) + { + restricao4 = restricaoUsuario8.get_Restricao(); + } + else + { + restricao4 = false; + } + if (restricao4) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 9: + { + List restricaoUsuarios10 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario9 = restricaoUsuarios10.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 25); + if (restricaoUsuario9 != null) + { + flag4 = restricaoUsuario9.get_Restricao(); + } + else + { + flag4 = false; + } + if (flag4) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 10: + { + List restricaoUsuarios11 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario10 = restricaoUsuarios11.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 26); + if (restricaoUsuario10 != null) + { + restricao5 = restricaoUsuario10.get_Restricao(); + } + else + { + restricao5 = false; + } + if (restricao5) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 11: + { + List restricaoUsuarios12 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario11 = restricaoUsuarios12.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 41); + if (restricaoUsuario11 != null) + { + flag5 = restricaoUsuario11.get_Restricao(); + } + else + { + flag5 = false; + } + if (flag5) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 12: + { + List restricaoUsuarios13 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario12 = restricaoUsuarios13.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 51); + if (restricaoUsuario12 != null) + { + restricao6 = restricaoUsuario12.get_Restricao(); + } + else + { + restricao6 = false; + } + if (restricao6) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 13: + { + List restricaoUsuarios14 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario13 = restricaoUsuarios14.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 50); + if (restricaoUsuario13 != null) + { + flag6 = restricaoUsuario13.get_Restricao(); + } + else + { + flag6 = false; + } + if (flag6) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 14: + { + List restricaoUsuarios15 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario14 = restricaoUsuarios15.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 52); + if (restricaoUsuario14 != null) + { + restricao7 = restricaoUsuario14.get_Restricao(); + } + else + { + restricao7 = false; + } + if (restricao7) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 15: + { + List restricaoUsuarios16 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario15 = restricaoUsuarios16.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 53); + if (restricaoUsuario15 != null) + { + flag7 = restricaoUsuario15.get_Restricao(); + } + else + { + flag7 = false; + } + if (flag7) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 16: + { + List restricaoUsuarios17 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario16 = restricaoUsuarios17.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 62); + if (restricaoUsuario16 != null) + { + restricao8 = restricaoUsuario16.get_Restricao(); + } + else + { + restricao8 = false; + } + if (restricao8) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 17: + { + List restricaoUsuarios18 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario17 = restricaoUsuarios18.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 63); + if (restricaoUsuario17 != null) + { + flag8 = restricaoUsuario17.get_Restricao(); + } + else + { + flag8 = false; + } + if (flag8) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 18: + { + List restricaoUsuarios19 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario18 = restricaoUsuarios19.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 31); + if (restricaoUsuario18 != null) + { + restricao9 = restricaoUsuario18.get_Restricao(); + } + else + { + restricao9 = false; + } + if (restricao9) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 19: + { + List restricaoUsuarios20 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario19 = restricaoUsuarios20.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 90); + if (restricaoUsuario19 != null) + { + flag9 = restricaoUsuario19.get_Restricao(); + } + else + { + flag9 = false; + } + if (flag9) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 20: + { + List restricaoUsuarios21 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario20 = restricaoUsuarios21.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 91); + if (restricaoUsuario20 != null) + { + restricao10 = restricaoUsuario20.get_Restricao(); + } + else + { + restricao10 = false; + } + if (restricao10) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 23: + { + List restricaoUsuarios22 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario21 = restricaoUsuarios22.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 96); + if (restricaoUsuario21 != null) + { + flag10 = restricaoUsuario21.get_Restricao(); + } + else + { + flag10 = false; + } + if (flag10) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 24: + { + List restricaoUsuarios23 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario22 = restricaoUsuarios23.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 98); + if (restricaoUsuario22 != null) + { + restricao11 = restricaoUsuario22.get_Restricao(); + } + else + { + restricao11 = false; + } + if (restricao11) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 25: + { + List restricaoUsuarios24 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario23 = restricaoUsuarios24.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 98); + if (restricaoUsuario23 != null) + { + flag11 = restricaoUsuario23.get_Restricao(); + } + else + { + flag11 = false; + } + if (flag11) + { + continue; + } + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 22)) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 26: + { + List restricaoUsuarios25 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario24 = restricaoUsuarios25.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 107); + if (restricaoUsuario24 != null) + { + restricao12 = restricaoUsuario24.get_Restricao(); + } + else + { + restricao12 = false; + } + if (restricao12) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 27: + { + List restricaoUsuarios26 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario25 = restricaoUsuarios26.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 111); + if (restricaoUsuario25 != null) + { + flag12 = restricaoUsuario25.get_Restricao(); + } + else + { + flag12 = false; + } + if (flag12) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 28: + { + List restricaoUsuarios27 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario26 = restricaoUsuarios27.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 112); + if (restricaoUsuario26 != null) + { + restricao13 = restricaoUsuario26.get_Restricao(); + } + else + { + restricao13 = false; + } + if (restricao13) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + case 29: + { + List restricaoUsuarios28 = restricaoUsuarios; + RestricaoUsuario restricaoUsuario27 = restricaoUsuarios28.FirstOrDefault((RestricaoUsuario x) => x.get_Tipo() == 30); + if (restricaoUsuario27 != null) + { + flag13 = restricaoUsuario27.get_Restricao(); + } + else + { + flag13 = false; + } + if (flag13) + { + continue; + } + this.Relatorios.Add(relatorio); + continue; + } + default: + { + continue; + } + } + } + this.Relatorio = this.Relatorios.FirstOrDefault(); + } + + private async Task PostMonitor() + { + try + { + using (HttpClient httpClient = new HttpClient()) + { + ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; + httpClient.set_Timeout(TimeSpan.FromSeconds(10)); + object idFornecedor = ApplicationHelper.IdFornecedor; + object relatorio = (int)this.Relatorio; + DateTime universalTime = Funcoes.GetNetworkTime().ToUniversalTime(); + string str = string.Format("{0}:{1}:{2}", idFornecedor, relatorio, universalTime.Ticks).EncodeBase64(); + Uri apiMonitor = Address.get_ApiMonitor(); + string[] strArrays = new string[] { "report" }; + Uri uri = apiMonitor.Append(strArrays).AddQuery("reportQuery", str); + await httpClient.GetAsync(uri); + } + httpClient = null; + } + catch + { + } + } + + public async void PrepararProtocolo(List itens) + { + List> tuples; + if (itens != null) + { + this.Carregando = true; + base.IsEnabled = false; + if (await base.ShowMessage("DESEJA EMITIR O CHECKLIST?", "SIM", "NÃO", false)) + { + await base.EmitirCheckList(itens); + } + tuples = new List>(); + foreach (Documento iten in itens) + { + tuples.Add(new Tuple(iten.get_Id(), iten.get_ObsProtocolo())); + } + bool flag = await base.ShowMessage(string.Concat("DESEJA EMITIR DOIS PROTOCOLOS POR PÁGINA?", Environment.NewLine, "A QUANTIDADE DE INFORMÃÇÕES PODE IMPEDIR QUE ESSA FUNÇÃO FUNCIONE CORRETAMENTE"), "SIM", "NÃO", false); + await base.EmitirProtocolos(tuples, flag, itens); + base.IsEnabled = true; + this.Carregando = false; + } + tuples = null; + } + + public async Task Print(bool pageBreak = false) + { + bool flag; + ConfiguracaoImpressao configuracaoImpressao; + string str = ""; + switch (this.Relatorio) + { + case 0: + case 1: + { + if (this.ClientesAtivosInativosFiltrado == null || this.ClientesAtivosInativosFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ClientesAtivosInativosFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 2: + { + if (this.ProducaoFiltrado == null || this.ProducaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ProducaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 3: + { + if (this.ApolicePendenteFiltrado == null || this.ApolicePendenteFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ApolicePendenteFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 4: + { + if (this.RenovacaoFiltrado == null || this.RenovacaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.RenovacaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 5: + { + if (this.ComissaoFiltrado == null || this.ComissaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ComissaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 6: + case 16: + { + if (this.PendenteFiltrado == null || this.PendenteFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.PendenteFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 7: + { + if (this.Pagamentos == null || this.Pagamentos.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.Pagamentos.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + List pagamentos = this.Pagamentos; + flag = (!pagamentos.All((Pagamento x) => x.get_Dados().Any((DadosRelatorio p) => !p.get_DataPagamento().HasValue)) ? false : this.SomenteNaoPagos); + bool flag1 = flag; + if (flag1) + { + flag1 = await base.ShowMessage(string.Concat("DESEJA REALMENTE EMITIR O RECIBO DE PAGAMENTO DOS VENDEDORES LISTADOS?", Environment.NewLine, "ESSE PROCEDIMENTO IRÁ GERAR O PAGAMENTO DO REPASSE DAS PARCELAS PRESENTES NA LISTAGEM."), "SIM", "NÃO", false); + } + if (flag1) + { + this.ReciboPagamento = true; + } + this.Carregando = true; + base.IsEnabled = false; + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + if (this.ReciboPagamento) + { + await this.GerarPagamento(this.Pagamentos.ToList()); + } + this.ReciboPagamento = false; + goto case 22; + } + } + } + case 8: + { + if (this.AuditoriaFiltrado == null || this.AuditoriaFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.AuditoriaFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 9: + case 10: + { + if (this.SinistroFiltrado == null || this.SinistroFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.SinistroFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 11: + { + if (this.FechamentoFiltrado == null || this.FechamentoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.FechamentoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 12: + { + if (this.FaturaPendenteFiltrado == null || this.FaturaPendenteFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.FaturaPendenteFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 13: + { + if (this.ExtratosFiltrado == null || this.ExtratosFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ExtratosFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 14: + { + if (this.MetaSeguradoraFiltrado == null || this.MetaSeguradoraFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.MetaSeguradoraFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 15: + { + if (this.MetaVendedorFiltrado == null || this.MetaVendedorFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.MetaVendedorFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 17: + { + if (this.LicenciamentoFiltrado == null || this.LicenciamentoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.LicenciamentoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 18: + { + if (this.TarefaFiltrado == null || this.TarefaFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.TarefaFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 19: + { + if (this.NotaFiscalFiltrado == null || this.NotaFiscalFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.NotaFiscalFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 20: + { + if (this.PrevisaoFiltrado == null || this.PrevisaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.PrevisaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 21: + case 22: + { + if (!string.IsNullOrEmpty(str)) + { + base.RegistrarAcao(string.Format("IMPRIMIU RELATÓRIO PERÍODO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim), new Gestor.Model.Common.Relatorio?(this.Relatorio), this.Filtros); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(EnumHelper.GetDescription(this.Relatorio), ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + int num = 0; + try + { + Process.Start(str1); + } + catch + { + num = 1; + } + if (num == 1) + { + await base.ShowMessage("NÃO FOI ENCONTRADO O APLICATIVO PADRÃO DE HTML. \nACESSE AS CONFIGURAÇÕES DO SISTEMA OPERACIONAL PARA CONFIGURAR OU CONTATE UM TÉCNICO PARA AUXILIÁ-LO.", "OK", "", false); + } + break; + } + else + { + break; + } + } + case 23: + { + if (this.LogsEnvioFiltrado == null || this.LogsEnvioFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.LogsEnvioFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 24: + case 25: + { + if (this.LogUtilizacaoFiltrado == null || this.LogUtilizacaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.LogUtilizacaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 26: + { + if (this.ApoliceCriticaFiltrado == null || this.ApoliceCriticaFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ApoliceCriticaFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 27: + { + if (this.PlacaFiltrado == null || this.PlacaFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.PlacaFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 28: + { + if (this.EndossoFiltrado == null || this.EndossoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.EndossoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + case 29: + { + if (this.ClassificacaoFiltrado == null || this.ClassificacaoFiltrado.Count == 0) + { + break; + } + else + { + configuracaoImpressao = await base.ShowDialogPrint(this.Relatorio, this.ClassificacaoFiltrado.First().GetType()); + if (configuracaoImpressao == null || !configuracaoImpressao.get_Campos().Any()) + { + break; + } + else + { + str = await this.GerarHtml(false, pageBreak, configuracaoImpressao, false); + goto case 22; + } + } + } + default: + { + goto case 22; + } + } + } + + private void ProdutoOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(5); + } + + private void RamoOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(1); + } + + public void RecheckAllLists() + { + for (int i = 0; i <= 9; i++) + { + this.RecheckAllSelected(i); + } + } + + public void RecheckAllSelected(int tipo) + { + bool? nullable; + if (this._allSelectedChanging) + { + return; + } + try + { + this._allSelectedChanging = true; + switch (tipo) + { + case 0: + { + if (this.Seguradoras.All((Seguradora e) => e.get_Selecionado())) + { + this.AllSelectedSeguradora = new bool?(true); + break; + } + else if (!this.Seguradoras.All((Seguradora e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedSeguradora = nullable; + break; + } + else + { + this.AllSelectedSeguradora = new bool?(false); + break; + } + } + case 1: + { + if (this.Ramos.All((Ramo e) => e.get_Selecionado())) + { + this.AllSelectedRamo = new bool?(true); + break; + } + else if (!this.Ramos.All((Ramo e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedRamo = nullable; + break; + } + else + { + this.AllSelectedRamo = new bool?(false); + break; + } + } + case 2: + { + if (this.Vendedores.All((Vendedor e) => e.get_Selecionado())) + { + this.AllSelectedVendedor = new bool?(true); + break; + } + else if (!this.Vendedores.All((Vendedor e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedVendedor = nullable; + break; + } + else + { + this.AllSelectedVendedor = new bool?(false); + break; + } + } + case 3: + { + if (this.TipoSeguros.All((StatusRelatorio e) => e.get_Selecionado())) + { + this.AllSelectedStatus = new bool?(true); + break; + } + else if (!this.TipoSeguros.All((StatusRelatorio e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedStatus = nullable; + break; + } + else + { + this.AllSelectedStatus = new bool?(false); + break; + } + } + case 4: + { + if (this.TipoVendedor.All((Gestor.Model.Domain.Seguros.TipoVendedor e) => e.get_Selecionado())) + { + this.AllSelectedTipoVendedor = new bool?(true); + break; + } + else if (!this.TipoVendedor.All((Gestor.Model.Domain.Seguros.TipoVendedor e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedTipoVendedor = nullable; + break; + } + else + { + this.AllSelectedTipoVendedor = new bool?(false); + break; + } + } + case 5: + { + if (this.Negocios.All((NegocioRelatorio e) => e.get_Selecionado())) + { + this.AllSelectedNegocio = new bool?(true); + break; + } + else if (!this.Negocios.All((NegocioRelatorio e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedNegocio = nullable; + break; + } + else + { + this.AllSelectedNegocio = new bool?(false); + break; + } + } + case 6: + { + if (this.Produtos.All((Gestor.Model.Domain.Seguros.Produto e) => e.get_Selecionado())) + { + this.AllSelectedProduto = new bool?(true); + break; + } + else if (!this.Produtos.All((Gestor.Model.Domain.Seguros.Produto e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedProduto = nullable; + break; + } + else + { + this.AllSelectedProduto = new bool?(false); + break; + } + } + case 7: + { + if (this.Estipulantes.All((Estipulante e) => e.get_Selecionado())) + { + this.AllSelectedEstipulante = new bool?(true); + break; + } + else if (!this.Estipulantes.All((Estipulante e) => !e.get_Selecionado())) + { + nullable = null; + this.AllSelectedEstipulante = nullable; + break; + } + else + { + this.AllSelectedEstipulante = new bool?(false); + break; + } + } + } + this.AdicionarFiltros(); + } + finally + { + this._allSelectedChanging = false; + } + } + + public void ReloadVendedores() + { + if (this.Inativo) + { + this.Vendedores = (this.Vinculo.Count > 0 ? ( + from x in Recursos.Vendedores + where this.Vinculo.Any((VendedorUsuario y) => y.get_Vendedor().get_Id() == x.get_Id()) + orderby x.get_Nome() + select x).ToList() : Recursos.Vendedores.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() == (long)1) + { + return true; + } + return x.get_IdEmpresa() == Recursos.Usuario.get_IdEmpresa(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList()); + } + else + { + this.Vendedores = (this.Vinculo.Count > 0 ? Recursos.Vendedores.Where((Vendedor x) => { + if (!this.Vinculo.Any((VendedorUsuario y) => y.get_Vendedor().get_Id() == x.get_Id())) + { + return false; + } + return x.get_Ativo(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList() : Recursos.Vendedores.Where((Vendedor x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return x.get_Ativo(); + }).OrderBy((Vendedor x) => x.get_Nome()).ToList()); + } + base.OnPropertyChanged("ReloadVendedores"); + } + + public void RemoverRamo(Ramo ramo) + { + if (ramo == null) + { + return; + } + if (this.RamosSelecionados.Any((Ramo x) => x.get_Id() == ramo.get_Id())) + { + this.RamosSelecionados.Remove(ramo); + } + this.FiltrarRamo(); + } + + internal async Task RemoverVinculo(Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente pendencia) + { + base.Loading(true); + VinculoDocumento vinculo = pendencia.get_Documento().get_Vinculo(); + if (vinculo != null && vinculo.get_Id() != 0) + { + await this._apoliceServico.ExcluirVinculo(vinculo.get_Id()); + Action recarregarRelatorios = Gestor.Application.Actions.Actions.RecarregarRelatorios; + if (recarregarRelatorios != null) + { + recarregarRelatorios(this.Sessao); + } + else + { + } + base.Loading(false); + } + } + + public async Task SalvarParametros() + { + bool flag; + if (!await (new ConfuguracoesServico()).Salvar(this.ParametrosRelatorioAdicionados.ToList(), this.ParametrosRelatorio.ToList())) + { + flag = false; + } + else if (await (new ConfuguracoesServico()).SalvarTotalizacoes(this.ParametrosTotalizacaoAdicionados.ToList(), this.ParametrosTotalizacao.ToList())) + { + base.RegistrarAcao("SALVOU CONFIGURAÇÃO DO RELATORIO", new Gestor.Model.Common.Relatorio?(this.Relatorio), this.Filtros); + await this.CarregarConfiguracoes(); + flag = true; + } + else + { + flag = false; + } + return flag; + } + + public async Task SalvarTarefas(List tarefas) + { + await (new TarefaServico()).Salvar(tarefas); + } + + public async Task SalvarTrilha(Trilha destino) + { + Trilha trilha; + List fases = destino.get_Fases(); + TarefaServico tarefaServico = new TarefaServico(); + List trilhas = await tarefaServico.BuscarTrilhas(); + if (!trilhas.Any((Trilha x) => x.get_Tipo() == destino.get_Tipo())) + { + Trilha trilha1 = await tarefaServico.Salvar(destino); + if (tarefaServico.Sucesso) + { + fases.ForEach((Fase x) => x.set_Trilha(trilha1)); + fases = await tarefaServico.Salvar(fases); + if (tarefaServico.Sucesso) + { + trilha1.set_Fases(fases); + trilha = trilha1; + } + else + { + trilha = null; + } + } + else + { + trilha = null; + } + } + else + { + Trilha trilha2 = trilhas.First((Trilha x) => x.get_Tipo() == destino.get_Tipo()); + Trilha trilha3 = trilha2; + List fases1 = await tarefaServico.BuscarFases(trilha2.get_Id()); + trilha3.set_Fases(fases1); + trilha3 = null; + trilha = trilha2; + } + fases = null; + tarefaServico = null; + return trilha; + } + + private void SeguradoraOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(0); + } + + public async Task Selecionar() + { + await Task.Run(() => { + Dispatcher dispatcher; + Dispatcher dispatcher1; + DispatcherOperation dispatcherOperation; + switch (this.Relatorio) + { + case 0: + case 1: + { + if (this.ClientesAtivosInativosFiltrado == null || this.ClientesAtivosInativosFiltrado.Count == 0) + { + return; + } + this.ClientesAtivosInativosFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.set_Selecionado(!x.get_Selecionado())); + this.ClientesAtivosInativosFiltrado = new ObservableCollection(this.ClientesAtivosInativosFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 2: + { + if (this.ProducaoFiltrado == null || this.ProducaoFiltrado.Count == 0) + { + return; + } + this.ProducaoFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.set_Selecionado(!x.get_Selecionado())); + this.ProducaoFiltrado = new ObservableCollection(this.ProducaoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 3: + { + if (this.ApolicePendenteFiltrado == null || this.ApolicePendenteFiltrado.Count == 0) + { + return; + } + this.ApolicePendenteFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.set_Selecionado(!x.get_Selecionado())); + this.ApolicePendenteFiltrado = new ObservableCollection(this.ApolicePendenteFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 4: + { + if (this.RenovacaoFiltrado == null || this.RenovacaoFiltrado.Count == 0) + { + return; + } + this.RenovacaoFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.set_Selecionado(!x.get_Selecionado())); + this.RenovacaoFiltrado = new ObservableCollection(this.RenovacaoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 5: + { + if (this.ComissaoFiltrado == null || this.ComissaoFiltrado.Count == 0) + { + return; + } + this.ComissaoFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.set_Selecionado(!x.get_Selecionado())); + this.ComissaoFiltrado = new ObservableCollection(this.ComissaoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 6: + case 16: + { + if (this.PendenteFiltrado == null || this.PendenteFiltrado.Count == 0) + { + return; + } + this.PendenteFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.set_Selecionado(!x.get_Selecionado())); + this.PendenteFiltrado = new ObservableCollection(this.PendenteFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 7: + case 11: + case 20: + case 21: + case 22: + { + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 8: + { + if (this.AuditoriaFiltrado == null || this.AuditoriaFiltrado.Count == 0) + { + return; + } + this.AuditoriaFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.set_Selecionado(!x.get_Selecionado())); + this.AuditoriaFiltrado = new ObservableCollection(this.AuditoriaFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 9: + case 10: + { + if (this.SinistroFiltrado == null || this.SinistroFiltrado.Count == 0) + { + return; + } + this.SinistroFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.set_Selecionado(!x.get_Selecionado())); + this.SinistroFiltrado = new ObservableCollection(this.SinistroFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 12: + { + if (this.FaturaPendenteFiltrado == null || this.FaturaPendenteFiltrado.Count == 0) + { + return; + } + this.FaturaPendenteFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => x.set_Selecionado(!x.get_Selecionado())); + this.FaturaPendenteFiltrado = new ObservableCollection(this.FaturaPendenteFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 13: + { + if (this.ExtratosFiltrado == null || this.ExtratosFiltrado.Count == 0) + { + return; + } + this.ExtratosFiltrado.ToList().ForEach((ExtratoBaixadoRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + this.ExtratosFiltrado = new ObservableCollection(this.ExtratosFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 14: + { + if (this.MetaSeguradoraFiltrado == null || this.MetaSeguradoraFiltrado.Count == 0) + { + return; + } + this.MetaSeguradoraFiltrado.ToList().ForEach((MetaSeguradoraRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + this.MetaSeguradoraFiltrado = new ObservableCollection(this.MetaSeguradoraFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 15: + { + if (this.MetaVendedorFiltrado == null || this.MetaVendedorFiltrado.Count == 0) + { + return; + } + this.MetaVendedorFiltrado.ToList().ForEach((MetaVendedorRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + this.MetaVendedorFiltrado = new ObservableCollection(this.MetaVendedorFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 17: + { + if (this.LicenciamentoFiltrado == null || this.LicenciamentoFiltrado.Count == 0) + { + return; + } + this.LicenciamentoFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => x.set_Selecionado(!x.get_Selecionado())); + this.LicenciamentoFiltrado = new ObservableCollection(this.LicenciamentoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 18: + { + if (this.TarefaFiltrado == null || this.TarefaFiltrado.Count == 0) + { + return; + } + this.TarefaFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Tarefa.Tarefa x) => x.set_Selecionado(!x.get_Selecionado())); + this.TarefaFiltrado = new ObservableCollection(this.TarefaFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 19: + { + if (this.NotaFiscalFiltrado == null || this.NotaFiscalFiltrado.Count == 0) + { + return; + } + this.NotaFiscalFiltrado.ToList().ForEach((NotaFiscalRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + this.NotaFiscalFiltrado = new ObservableCollection(this.NotaFiscalFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 23: + { + if (this.LogsEnvioFiltrado == null || this.LogsEnvioFiltrado.Count == 0) + { + return; + } + this.LogsEnvioFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.LogsEnvio.LogsEnvio x) => x.set_Selecionado(!x.get_Selecionado())); + this.LogsEnvioFiltrado = new ObservableCollection(this.LogsEnvioFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 24: + case 25: + { + if (this.LogUtilizacaoFiltrado == null || this.LogUtilizacaoFiltrado.Count == 0) + { + return; + } + this.LogUtilizacaoFiltrado.ToList().ForEach((LogAcaoRelatorio x) => x.set_Selecionado(!x.get_Selecionado())); + this.LogUtilizacaoFiltrado = new ObservableCollection(this.LogUtilizacaoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 26: + { + if (this.ApoliceCriticaFiltrado == null || this.ApoliceCriticaFiltrado.Count == 0) + { + return; + } + this.ApoliceCriticaFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.CriticaApolice.ApoliceCritica x) => x.set_Selecionado(!x.get_Selecionado())); + this.ApoliceCriticaFiltrado = new ObservableCollection(this.ApoliceCriticaFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 27: + { + if (this.PlacaFiltrado == null || this.PlacaFiltrado.Count == 0) + { + return; + } + this.PlacaFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Placa.Placas x) => x.set_Selecionado(!x.get_Selecionado())); + this.PlacaFiltrado = new ObservableCollection(this.PlacaFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 28: + { + if (this.EndossoFiltrado == null || this.EndossoFiltrado.Count == 0) + { + return; + } + this.EndossoFiltrado.ToList().ForEach((Endosso x) => x.set_Selecionado(!x.get_Selecionado())); + this.EndossoFiltrado = new ObservableCollection(this.EndossoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + case 29: + { + if (this.ClassificacaoFiltrado == null || this.ClassificacaoFiltrado.Count == 0) + { + return; + } + this.ClassificacaoFiltrado.ToList().ForEach((Gestor.Model.Domain.Relatorios.Classificacao.Classificacao x) => x.set_Selecionado(!x.get_Selecionado())); + this.ClassificacaoFiltrado = new ObservableCollection(this.ClassificacaoFiltrado); + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + default: + { + dispatcher = System.Windows.Application.Current.Dispatcher; + if (dispatcher == null) + { + dispatcher1 = dispatcher; + return; + } + dispatcherOperation = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(this.Bind)); + return; + } + } + }); + } + + public async Task Sincronizar() + { + List produtos = LicenseHelper.Produtos; + if (produtos.All((Licenca x) => x.get_Produto() != 77)) + { + List licencas = LicenseHelper.Produtos; + if (licencas.All((Licenca x) => x.get_Produto() != 84)) + { + await base.ShowMessage("VOCÊ AINDA NÃO POSSUI O AGGILIZADOR DE DOCUMENTOS, NAVEGUE POR NOSSO PORTAL E ENCONTRE A OFERTA QUE MAIS ENCAIXE EM SEU DIA-A-DIA.", "OK", "", false); + Process.Start("https://agger.com.br"); + return; + } + } + Gestor.Model.Common.Relatorio relatorio = this.Relatorio; + if (relatorio != 3) + { + if (relatorio == 16) + { + if (this.PendenteFiltrado == null || !this.PendenteFiltrado.Any()) + { + await base.ShowMessage("NÃO HÁ DADOS PARA SINCRONIZAÇÃO", "OK", "", false); + return; + } + else + { + ObservableCollection pendenteFiltrado = this.PendenteFiltrado; + List list = ( + from x in pendenteFiltrado + select x.get_ParcelaEntity().get_Id()).ToList(); + int[] numArray = await this._parcelaServico.Sincronizar(this.Inicio, list); + if (numArray[0] == 0) + { + await base.ShowMessage("NÃO HÁ PARCELAS PENDENTES NO PERIODO SELECIONADO.", "OK", "", false); + return; + } + else if (numArray[0] <= 0 || numArray[1] != 0) + { + Action recarregarRelatorios = Gestor.Application.Actions.Actions.RecarregarRelatorios; + if (recarregarRelatorios != null) + { + recarregarRelatorios(this.Sessao); + } + else + { + } + base.ToggleSnackBar(string.Format("{0} PARCELAS VINCULADAS", numArray[1]), true); + } + else + { + return; + } + } + } + } + else if (this.ApolicePendenteFiltrado == null || !this.ApolicePendenteFiltrado.Any()) + { + await base.ShowMessage("NÃO HÁ DADOS PARA SINCRONIZAÇÃO", "OK", "", false); + return; + } + else + { + ObservableCollection apolicePendenteFiltrado = this.ApolicePendenteFiltrado; + IEnumerable apolicePendentes = apolicePendenteFiltrado.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + long? idAggilizador; + bool hasValue; + bool vinculo; + long? nullable; + Documento documento = x.get_Documento(); + if (documento != null) + { + Controle controle = documento.get_Controle(); + if (controle != null) + { + Seguradora seguradora = controle.get_Seguradora(); + if (seguradora != null) + { + idAggilizador = seguradora.get_IdAggilizador(); + hasValue = idAggilizador.HasValue; + } + else + { + hasValue = false; + } + } + else + { + hasValue = false; + } + } + else + { + hasValue = false; + } + if (!hasValue) + { + return false; + } + Documento documento1 = x.get_Documento(); + if (documento1 != null) + { + vinculo = documento1.get_Vinculo(); + } + else + { + vinculo = false; + } + if (!vinculo) + { + return true; + } + Documento documento2 = x.get_Documento(); + if (documento2 == null) + { + return false; + } + VinculoDocumento vinculoDocumento = documento2.get_Vinculo(); + if (vinculoDocumento != null) + { + nullable = new long?(vinculoDocumento.get_IdApoliceDigital()); + } + else + { + nullable = null; + } + idAggilizador = nullable; + long num = (long)0; + return idAggilizador.GetValueOrDefault() == num & idAggilizador.HasValue; + }); + List dadosVinculos = apolicePendentes.Select((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + string proposta; + object placa; + DadosVinculo dadosVinculo = new DadosVinculo(); + dadosVinculo.set_Id(x.get_Documento().get_Id()); + if (x.get_Documento().get_Controle().get_Seguradora().get_IdAggilizador().Value != (long)1 || x.get_Documento().get_Controle().get_Ramo().get_Id() != (long)5) + { + proposta = x.get_Documento().get_Proposta(); + } + else + { + ObservableCollection result = Task.Run>(() => (new ItemServico()).BuscarItems(x.get_Documento().get_Id(), 2, false)).Result; + if (result != null) + { + Item item = result.FirstOrDefault(); + if (item != null) + { + placa = item.get_Auto().get_Placa(); + } + else + { + placa = null; + } + } + else + { + placa = null; + } + if (placa != null) + { + proposta = ((string)placa).Replace("-", string.Empty); + } + else + { + proposta = null; + } + } + dadosVinculo.set_Proposta(proposta); + dadosVinculo.set_Apolice(x.get_Documento().get_Apolice()); + dadosVinculo.set_Documento(x.get_Documento().get_Controle().get_Cliente().get_Documento()); + dadosVinculo.set_Endosso(x.get_Documento().get_PropostaEndosso()); + dadosVinculo.set_IdSeguradora(x.get_Documento().get_Controle().get_Seguradora().get_IdAggilizador().Value); + dadosVinculo.set_VigenciaInicial(x.get_Documento().get_Vigencia1()); + dadosVinculo.set_Vigenciafinal(x.get_Documento().get_Vigencia2()); + dadosVinculo.set_Vinculo(x.get_Documento().get_Vinculo()); + return dadosVinculo; + }).ToList(); + Gestor.Model.Domain.Relatorios.Filtros filtro = new Gestor.Model.Domain.Relatorios.Filtros(); + filtro.set_Inicio(this.Inicio); + filtro.set_Fim(this.Fim); + int num1 = await this._apoliceServico.Sincronizar(dadosVinculos, filtro); + Action action = Gestor.Application.Actions.Actions.RecarregarRelatorios; + if (action != null) + { + action(this.Sessao); + } + else + { + } + ObservableCollection observableCollection = this.ApolicePendenteFiltrado; + if (!observableCollection.All((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + long? nullable; + Documento documento = x.get_Documento(); + if (documento == null) + { + return false; + } + VinculoDocumento vinculo = documento.get_Vinculo(); + if (vinculo != null) + { + nullable = new long?(vinculo.get_IdApoliceDigital()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + return nullable1.GetValueOrDefault() == num & nullable1.HasValue; + })) + { + if (num1 != 0) + { + base.ToggleSnackBar(string.Format("{0} DOCUMENTOS SINCRONIZADOS", num1), true); + RelatorioViewModel relatorioViewModel = this; + ObservableCollection apolicePendenteFiltrado1 = this.ApolicePendenteFiltrado; + if (!await relatorioViewModel.ShowMessage(string.Format("{0} DOCUMENTOS SINCRONIZADOS, DESEJA INICIAR A IMPORTAÇÃO DESSES DOCUMENTOS?", apolicePendenteFiltrado1.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + long? nullable; + Documento documento = x.get_Documento(); + if (documento == null) + { + return false; + } + VinculoDocumento vinculo = documento.get_Vinculo(); + if (vinculo != null) + { + nullable = new long?(vinculo.get_IdApoliceDigital()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + return nullable1.GetValueOrDefault() > num & nullable1.HasValue; + })), "SIM", "NÃO", false)) + { + return; + } + } + else if (!await base.ShowMessage("NENHUM NOVO DOCUMENTO FOI SINCRONIZADO, DESEJA IMPORTAR OS DOCUMENTOS ANTERIORMENTE SINCRONIZADOS?", "SIM", "NÃO", false)) + { + return; + } + ObservableCollection observableCollection1 = this.ApolicePendenteFiltrado; + IEnumerable apolicePendentes1 = observableCollection1.Where((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + long? nullable; + Documento documento = x.get_Documento(); + if (documento == null) + { + return false; + } + VinculoDocumento vinculo = documento.get_Vinculo(); + if (vinculo != null) + { + nullable = new long?(vinculo.get_IdApoliceDigital()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long num = (long)0; + return nullable1.GetValueOrDefault() > num & nullable1.HasValue; + }); + List nums = ( + from x in apolicePendentes1 + select x.get_Documento().get_Vinculo().get_IdApoliceDigital()).ToList(); + await base.DownloadAll(nums, 1); + Parameters parameter = new Parameters(); + parameter.set_Beta(false); + parameter.set_Type(4); + parameter.set_Application("Agger.ImportPDF.exe"); + parameter.set_Directory("Agger.Import"); + object[] id = new object[] { Recursos.Empresa.get_Id(), Recursos.Usuario.get_Id(), ApplicationHelper.Subkey, ApplicationHelper.NumeroSerial }; + parameter.set_Arguments(string.Format("{0} {1} NOVOGESTOR PERFIL:{2} SERIAL:{3}", id)); + parameter.set_Run(true); + (new DownloadWindow(parameter)).Show(); + } + else + { + await base.ShowMessage("NENHUM NOVO DOCUMENTO FOI SINCRONIZADO", "OK", "", false); + return; + } + } + } + + public async Task Sintetico() + { + List list = null; + if ((GridRelatorio)this.Report != null || this.Relatorio == 7 || this.Relatorio == 11) + { + switch (this.Relatorio) + { + case 2: + { + List producaos = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ProducaoFiltrado == null || producaos.Count == 0) + { + break; + } + else + { + if (this.Agrupamento == 3) + { + List producaos1 = producaos; + producaos = ( + from producao in producaos1 + where producao.get_Vendedor() != null + select producao).ToList(); + } + list = producaos.GroupBy((Gestor.Model.Domain.Relatorios.Producao.Producao x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }).Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_PremioTotal(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_PremioTotal()))); + sintetico.set_PremioLiquido(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()))); + sintetico.set_MediaComissao(new decimal?((x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao()) > decimal.Zero ? decimal.Round(x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao()) / x.Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao() > decimal.Zero), 2) * new decimal(100) : decimal.Zero))); + sintetico.set_ComissaoGerada(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoNegociosNovos))); + sintetico.set_NegociosProprios(new int?(Funcoes.DistinctBy(x, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoNegociosProprios))); + sintetico.set_SegurosNovos(new int?(Funcoes.DistinctBy(x, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoSegurosNovos))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoSegurosRenovacao))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_TotalLiquido(new int?(x.Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Situacao() != 3))); + sintetico.set_TotalGeral(new int?(x.Count())); + sintetico.set_MediaPonderada(new decimal?((x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()) > decimal.Zero ? decimal.Round(x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => (c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) / x.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()), 2) * new decimal(100) : decimal.Zero))); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 3: + { + List apolicePendentes = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ApolicePendenteFiltrado == null || apolicePendentes.Count == 0) + { + break; + } + else + { + IEnumerable> groupings = apolicePendentes.GroupBy((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }); + list = groupings.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_TotalGeral(new int?(x.Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 4: + { + List renovacaos = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.RenovacaoFiltrado == null || renovacaos.Count == 0) + { + break; + } + else + { + List renovacaos1 = renovacaos; + IEnumerable> groupings1 = ( + from x in renovacaos1 + where x.get_Documento() != null + select x).GroupBy((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }); + list = groupings1.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_PremioTotal(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_PremioTotal()))); + sintetico.set_PremioLiquido(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao p) => p.get_PremioLiquido()))); + sintetico.set_MediaComissao(new decimal?((x.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao()) > decimal.Zero ? decimal.Round(x.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao()) / x.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao() > decimal.Zero), 2) * new decimal(100) : decimal.Zero))); + sintetico.set_ComissaoGerada(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_TotalProspeccao(new int?(x.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Tipo() == 3))); + sintetico.set_TotalGeral(new int?(x.Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 5: + { + List comissaos = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.ComissaoFiltrado == null || comissaos.Count == 0) + { + break; + } + else + { + IEnumerable> groupings2 = comissaos.GroupBy((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }); + list = groupings2.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => { + if (c.get_Documento().get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => { + if (c.get_Documento().get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_ComissaoRecebidaBruta(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ComissaoBruta()))); + sintetico.set_ComissaoRecebidaLiquida(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ComissaoRecebida()))); + sintetico.set_Repasse(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_Repasse()))); + sintetico.set_MediaComissao(new decimal?((x.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ComissaoPerc() > decimal.Zero) ? decimal.Round(x.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ComissaoPerc()) / x.Count((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ComissaoPerc() > decimal.Zero), 2) : decimal.Zero) * new decimal(100))); + sintetico.set_ComissaoPrevista(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao c) => c.get_ValorLiquido()))); + sintetico.set_TotalGeral(new int?(x.Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 6: + case 16: + { + if (this.PendenteFiltrado == null || this.PendenteFiltrado.Count == 0) + { + break; + } + else + { + IEnumerable> groupings3 = this.PendenteFiltrado.GroupBy((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }); + list = groupings3.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => { + if (c.get_Documento().get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => { + if (c.get_Documento().get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_ComissaoPrevista(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_ComissaoPrevista()))); + sintetico.set_TotalPrevista(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Pendente.Pendente c) => c.get_TotalPrevisto()))); + sintetico.set_TotalGeral(new int?(x.Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 7: + { + if (this.Pagamentos == null || this.Pagamentos.Count == 0) + { + break; + } + else + { + List pagamentos = this.Pagamentos; + list = pagamentos.Select((Pagamento x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.get_Vendedores().get_Vendedor()); + sintetico.set_ValorLiquido(new decimal?(( + from c in x.get_Dados() + where c.get_Id() != (long)0 + select c).Sum((DadosRelatorio c) => c.get_ValorLiquido()))); + sintetico.set_ValorParcela(( + from c in x.get_Dados() + where c.get_Id() != (long)0 + select c).Sum((DadosRelatorio c) => c.get_ValorParcela())); + sintetico.set_Repasse(new decimal?(( + from c in x.get_Dados() + where c.get_Id() != (long)0 + select c).Sum((DadosRelatorio c) => c.get_Repasse()))); + sintetico.set_TotalGeral(new int?(x.get_Dados().Count((DadosRelatorio c) => c.get_Id() != (long)0))); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 8: + { + List auditorias = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.AuditoriaFiltrado == null || auditorias.Count == 0) + { + break; + } + else + { + IEnumerable> groupings4 = auditorias.GroupBy((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento != 4) + { + return x.get_Status(); + } + return x.get_Estipulante(); + }); + list = groupings4.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_PremioTotal(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_PremioTotal()))); + sintetico.set_PremioLiquido(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria p) => p.get_PremioLiquido()))); + sintetico.set_MediaComissao(new decimal?((x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao()) > decimal.Zero ? decimal.Round(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao()) / x.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao() > decimal.Zero), 2) : decimal.Zero) * new decimal(100))); + sintetico.set_ComissaoGerada(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico.set_ComissaoPrevista(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_ComissaoPrevista()))); + sintetico.set_ComissaoRecebidaBruta(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_ComissaoRecebida()))); + sintetico.set_ComissaoPendente(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_ComissaoPendente()))); + sintetico.set_Cancelamentos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Situacao() == 3))); + sintetico.set_Novos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico.set_Renovacoes(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico.set_Apolices(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Endossos(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico.set_Faturas(new int?(Funcoes.DistinctBy(x, (Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico.set_TotalLiquido(new int?(x.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Situacao() != 3))); + sintetico.set_TotalGeral(new int?(x.Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 9: + case 10: + { + List sinistros = ((GridRelatorio)this.Report).DataGrid.Items.Cast().ToList(); + if (this.SinistroFiltrado == null || sinistros.Count == 0) + { + break; + } + else + { + list = sinistros.GroupBy((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (this.Agrupamento == 1) + { + return x.get_Seguradora(); + } + if (this.Agrupamento == 2) + { + return x.get_Ramo(); + } + if (this.Agrupamento == 3) + { + return x.get_Vendedor(); + } + if (this.Agrupamento == 4) + { + return x.get_Estipulante(); + } + return EnumHelper.GetDescription(x.get_StatusSinistro()); + }).Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Liquidado((this.Relatorio == 9 ? null : new int?(( + from s in x + where s.get_Liquidacao().HasValue + select s.get_EntidadeSinistro().get_ControleSinistro().get_Id()).Distinct().Count()))); + sintetico.set_Valor(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_Valor()))); + sintetico.set_ValorOrcado(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorOrcado()))); + sintetico.set_ValorLiberado(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorLiberado()))); + sintetico.set_ValorPago(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorPago()))); + sintetico.set_ValorLiquidado((this.Relatorio == 9 ? null : new decimal?(( + from s in x + where s.get_Liquidacao().HasValue + select s).Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorPago())))); + sintetico.set_ValorSalvado(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorSalvado()))); + sintetico.set_ValorFranquia(new decimal?(x.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro s) => s.get_ValorFranquia()))); + sintetico.set_Pendente(new int?(( + from s in x + where !s.get_Liquidacao().HasValue + select s.get_EntidadeSinistro().get_ControleSinistro().get_Id()).Distinct().Count())); + sintetico.set_TotalGeral(new int?(( + from s in x + select s.get_EntidadeSinistro().get_ControleSinistro().get_Id()).Distinct().Count())); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 11: + { + if (this.FechamentoFiltrado == null || this.FechamentoFiltrado.Count == 0) + { + break; + } + else + { + list = new List(); + Gestor.Model.Domain.Relatorios.Fechamento.Fechamento fechamento = this.FechamentoFiltrado.First().get_Fechamento().Last(); + Sintetico sintetico1 = new Sintetico(); + int year = this.Inicio.Year; + sintetico1.set_Agrupamento(string.Concat("ATUAL: ", year.ToString())); + sintetico1.set_TotalGeral(new int?(fechamento.get_Apolice())); + sintetico1.set_ValorPago(new decimal?(fechamento.get_Paga())); + sintetico1.set_ComissaoRecebidaBruta(new decimal?(fechamento.get_Recebida())); + sintetico1.set_ComissaoGerada(new decimal?(fechamento.get_Gerada())); + sintetico1.set_PremioLiquido(new decimal?(fechamento.get_PremioLiquido())); + sintetico1.set_PremioTotal(new decimal?(fechamento.get_PremioTotal())); + list.Add(sintetico1); + Sintetico sintetico2 = new Sintetico(); + year = this.Inicio.Year - 1; + sintetico2.set_Agrupamento(string.Concat("ANTERIOR: ", year.ToString())); + sintetico2.set_TotalGeral(new int?(fechamento.get_ApoliceAnterior())); + sintetico2.set_ValorPago(new decimal?(fechamento.get_PagaAnterior())); + sintetico2.set_ComissaoRecebidaBruta(new decimal?(fechamento.get_RecebidaAnterior())); + sintetico2.set_ComissaoGerada(new decimal?(fechamento.get_GeradaAnterior())); + sintetico2.set_PremioLiquido(new decimal?(fechamento.get_PremioLiquidoAnterior())); + sintetico2.set_PremioTotal(new decimal?(fechamento.get_PremioTotalAnterior())); + list.Add(sintetico2); + goto case 13; + } + } + case 12: + case 13: + { + if (list != null) + { + (new SinteticoView(list, EnumHelper.GetDescription(this.Relatorio), new DateTime?(this.Inicio), new DateTime?(this.Fim))).Show(); + break; + } + else + { + break; + } + } + case 14: + { + if (this.MetaSeguradora == null || this.MetaSeguradora.Count == 0) + { + break; + } + else + { + List metaSeguradora = this.MetaSeguradora; + IEnumerable> seguradora = + from g in metaSeguradora + group g by g.get_Seguradora(); + list = seguradora.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Meta(new decimal?(Math.Round(( + from m in x + where m.get_MetaAtingir() > decimal.Zero + select m).Sum((MetaSeguradoraRelatorio m) => (m.get_MetaCumprida() * new decimal(100)) / m.get_MetaAtingir()) * new decimal(100), 2))); + sintetico.set_MetaAtingir(new decimal?(Math.Round(x.Sum((MetaSeguradoraRelatorio m) => m.get_MetaAtingir()), 2))); + sintetico.set_MetaCumprida(new decimal?(Math.Round(x.Sum((MetaSeguradoraRelatorio m) => m.get_MetaCumprida()), 2))); + return sintetico; + }).ToList(); + goto case 13; + } + } + case 15: + { + if (this.MetaVendedor == null || this.MetaVendedor.Count == 0) + { + break; + } + else + { + List metaVendedor = this.MetaVendedor; + IEnumerable> vendedor = + from g in metaVendedor + group g by g.get_Vendedor(); + list = vendedor.Select, Sintetico>((IGrouping x) => { + Sintetico sintetico = new Sintetico(); + sintetico.set_Agrupamento(x.Key); + sintetico.set_Meta(new decimal?(Math.Round(( + from m in x + where m.get_MetaAtingir() > decimal.Zero + select m).Sum((MetaVendedorRelatorio m) => (m.get_MetaCumprida() * new decimal(100)) / m.get_MetaAtingir()) * new decimal(100), 2))); + sintetico.set_MetaAtingir(new decimal?(Math.Round(x.Sum((MetaVendedorRelatorio m) => m.get_MetaAtingir()), 2))); + sintetico.set_MetaCumprida(new decimal?(Math.Round(x.Sum((MetaVendedorRelatorio m) => m.get_MetaCumprida()), 2))); + return sintetico; + }).ToList(); + goto case 13; + } + } + default: + { + goto case 13; + } + } + } + else + { + await base.ShowMessage("NECESSARIO GERAR UM RELATÓRIO COM DADOS PARA SINTETIZAR", "OK", "", false); + } + } + + public void SintetizarRelatorio() + { + this.SinteticoRelatorio = new ObservableCollection(); + switch (this.Relatorio) + { + case 0: + case 1: + { + if (this.ClientesAtivosInativosFiltrado == null || this.ClientesAtivosInativosFiltrado.Count == 0) + { + return; + } + List clientesAtivosInativos = (this.ClientesAtivosInativosFiltrado.Any((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Selecionado()) ? ( + from x in this.ClientesAtivosInativosFiltrado + where x.get_Selecionado() + select x).ToList() : this.ClientesAtivosInativosFiltrado.ToList()); + List sinteticos = new List(); + Sintetico sintetico = new Sintetico(); + sintetico.set_TotalClientes(new int?(clientesAtivosInativos.Count)); + sintetico.set_TotalClientesAtivos(new int?(clientesAtivosInativos.Count((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Ativo() == "SIM"))); + sintetico.set_TotalClientesInativos(new int?(clientesAtivosInativos.Count((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => x.get_Ativo() == "NÃO"))); + sinteticos.Add(sintetico); + this.SinteticoRelatorio = new ObservableCollection(sinteticos); + return; + } + case 2: + { + if (this.ProducaoFiltrado == null || this.ProducaoFiltrado.Count == 0) + { + return; + } + List producaos = (this.ProducaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Selecionado()) ? ( + from x in this.ProducaoFiltrado + where x.get_Selecionado() + select x).ToList() : this.ProducaoFiltrado.ToList()); + List sinteticos1 = new List(); + Sintetico sintetico1 = new Sintetico(); + sintetico1.set_PremioTotal(new decimal?(producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_PremioTotal()))); + sintetico1.set_PremioLiquido(new decimal?(producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()))); + sintetico1.set_MediaPonderada(new decimal?((producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()) > decimal.Zero ? decimal.Round(producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => (c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) / producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao p) => p.get_PremioLiquido()), 2) : decimal.Zero))); + sintetico1.set_MediaComissao(new decimal?((producaos.Any((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao() > decimal.Zero) ? decimal.Round(producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao()) / producaos.Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Comissao() > decimal.Zero), 2) : decimal.Zero))); + sintetico1.set_ComissaoGerada(new decimal?(producaos.Sum((Gestor.Model.Domain.Relatorios.Producao.Producao c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico1.set_Cancelamentos(new int?(Funcoes.DistinctBy(producaos, (Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Documento().get_Controle().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Situacao() == 3))); + sintetico1.set_Novos(new int?(Funcoes.DistinctBy(producaos, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoNegociosNovos))); + sintetico1.set_NegociosProprios(new int?(Funcoes.DistinctBy(producaos, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoNegociosProprios))); + sintetico1.set_SegurosNovos(new int?(Funcoes.DistinctBy(producaos, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoSegurosNovos))); + sintetico1.set_Renovacoes(new int?(Funcoes.DistinctBy(producaos, this.funcProducaoDistinctByDocumentoId).Count(this.funcProducaoSegurosRenovacao))); + sintetico1.set_Apolices(new int?(Funcoes.DistinctBy(producaos, (Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico1.set_Endossos(new int?(Funcoes.DistinctBy(producaos, (Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico1.set_Faturas(new int?(Funcoes.DistinctBy(producaos, (Gestor.Model.Domain.Relatorios.Producao.Producao x) => x.get_Documento().get_Id()).Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico1.set_TotalGeral(new int?(producaos.Count)); + sintetico1.set_TotalLiquido(new int?(producaos.Count((Gestor.Model.Domain.Relatorios.Producao.Producao c) => c.get_Documento().get_Situacao() != 3))); + sinteticos1.Add(sintetico1); + this.SinteticoRelatorio = new ObservableCollection(sinteticos1); + return; + } + case 3: + { + if (this.ApolicePendenteFiltrado == null || this.ApolicePendenteFiltrado.Count == 0) + { + return; + } + List apolicePendentes = (this.ApolicePendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_Selecionado()) ? ( + from x in this.ApolicePendenteFiltrado + where x.get_Selecionado() + select x).ToList() : this.ApolicePendenteFiltrado.ToList()); + List sinteticos2 = new List(); + Sintetico sintetico2 = new Sintetico(); + sintetico2.set_PremioTotal(new decimal?(apolicePendentes.Sum((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => x.get_PremioTotal()))); + sintetico2.set_PremioLiquido(new decimal?(apolicePendentes.Sum((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente p) => p.get_PremioLiquido()))); + sintetico2.set_MediaComissao(new decimal?((apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Comissao() > decimal.Zero) > 0 ? decimal.Round(apolicePendentes.Sum((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Comissao()) / apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Comissao() > decimal.Zero), 2) : decimal.Zero))); + sintetico2.set_ComissaoGerada(new decimal?(apolicePendentes.Sum((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico2.set_Cancelamentos(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_Situacao() == 3))); + sintetico2.set_Novos(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico2.set_Renovacoes(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico2.set_Apolices(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico2.set_Endossos(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico2.set_Faturas(new int?(apolicePendentes.Count((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico2.set_TotalGeral(new int?(apolicePendentes.Count)); + sinteticos2.Add(sintetico2); + this.SinteticoRelatorio = new ObservableCollection(sinteticos2); + return; + } + case 4: + { + if (this.RenovacaoFiltrado == null || this.RenovacaoFiltrado.Count == 0) + { + return; + } + List renovacaos = (this.RenovacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_Selecionado()) ? ( + from x in this.RenovacaoFiltrado + where x.get_Selecionado() + select x).ToList() : this.RenovacaoFiltrado.ToList()); + List sinteticos3 = new List(); + Sintetico sintetico3 = new Sintetico(); + sintetico3.set_PremioTotal(new decimal?(renovacaos.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => x.get_PremioTotal()))); + sintetico3.set_PremioLiquido(new decimal?(renovacaos.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao p) => p.get_PremioLiquido()))); + sintetico3.set_MediaComissao(new decimal?((renovacaos.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao()) > decimal.Zero ? decimal.Round(renovacaos.Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao()) / renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Comissao() > decimal.Zero), 2) : decimal.Zero))); + sintetico3.set_ComissaoGerada(new decimal?(renovacaos.Where((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => { + if (x.get_Tipo() == 3) + { + return false; + } + return x.get_Comissao() > decimal.Zero; + }).Sum((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => ((c.get_PremioLiquido() + (c.get_Documento().get_AdicionalComiss() ? c.get_Documento().get_PremioAdicional() : decimal.Zero)) * c.get_Comissao()) * new decimal(1, 0, 0, false, 2)))); + sintetico3.set_Cancelamentos(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3) + { + return false; + } + return c.get_Documento().get_Situacao() == 3; + }))); + sintetico3.set_Novos(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() != 3 && c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Tipo() == 3 || c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico3.set_Renovacoes(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3 || c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico3.set_Apolices(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico3.set_Endossos(null); + sintetico3.set_Faturas(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2; + }))); + sintetico3.set_TotalProspeccao(new int?(renovacaos.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Tipo() == 3))); + sintetico3.set_TotalGeral(new int?(renovacaos.Count)); + sinteticos3.Add(sintetico3); + this.SinteticoRelatorio = new ObservableCollection(sinteticos3); + return; + } + case 5: + { + if (this.ComissaoFiltrado == null || this.ComissaoFiltrado.Count == 0) + { + return; + } + List comissaos = (this.ComissaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Selecionado()) ? ( + from x in this.ComissaoFiltrado + where x.get_Selecionado() + select x).ToList() : this.ComissaoFiltrado.ToList()); + List sinteticos4 = new List(); + Sintetico sintetico4 = new Sintetico(); + sintetico4.set_ComissaoRecebidaBruta(new decimal?(comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_ComissaoBruta()))); + sintetico4.set_ComissaoRecebidaLiquida(new decimal?(comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_ComissaoRecebida()))); + sintetico4.set_Impostos(new decimal?((comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Ir()) + comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Iss())) + comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Outros()))); + sintetico4.set_PremioLiquido(new decimal?(Funcoes.DistinctBy(comissaos, (Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Documento().get_Id()).Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_PremioLiquido()))); + sintetico4.set_PremioTotal(new decimal?(Funcoes.DistinctBy(comissaos, (Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Documento().get_Id()).Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_PremioTotal()))); + sintetico4.set_ComissaoPrevista(new decimal?(comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_ValorLiquido()))); + sintetico4.set_Repasse(new decimal?(comissaos.Sum((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => x.get_Repasse()))); + sinteticos4.Add(sintetico4); + this.SinteticoRelatorio = new ObservableCollection(sinteticos4); + return; + } + case 6: + case 16: + { + if (this.PendenteFiltrado == null || this.PendenteFiltrado.Count == 0) + { + return; + } + List pendentes = (this.PendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Selecionado()) ? ( + from x in this.PendenteFiltrado + where x.get_Selecionado() + select x).ToList() : this.PendenteFiltrado.ToList()); + List sinteticos5 = new List(); + Sintetico sintetico5 = new Sintetico(); + sintetico5.set_ComissaoPrevista(new decimal?(pendentes.Sum((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_ComissaoPrevista()))); + sintetico5.set_TotalPrevista(new decimal?(Funcoes.DistinctBy(pendentes, (Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_Documento().get_Id()).Sum((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_TotalPrevisto()))); + sintetico5.set_TotalGeral(new int?(pendentes.Count)); + sintetico5.set_TotalParcela(new decimal?(pendentes.Sum((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => x.get_ValorParcela()))); + sinteticos5.Add(sintetico5); + this.SinteticoRelatorio = new ObservableCollection(sinteticos5); + return; + } + case 7: + case 11: + case 20: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + case 27: + case 28: + { + return; + } + case 8: + { + if (this.AuditoriaFiltrado == null || this.AuditoriaFiltrado.Count == 0) + { + return; + } + List auditorias = (this.AuditoriaFiltrado.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_Selecionado()) ? ( + from x in this.AuditoriaFiltrado + where x.get_Selecionado() + select x).ToList() : this.AuditoriaFiltrado.ToList()); + List sinteticos6 = new List(); + Sintetico sintetico6 = new Sintetico(); + sintetico6.set_PremioTotal(new decimal?(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => x.get_PremioTotal()))); + sintetico6.set_PremioLiquido(new decimal?(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria p) => p.get_PremioLiquido()))); + sintetico6.set_ComissaoRecebidaBruta(new decimal?(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria p) => p.get_ComissaoRecebida()))); + sintetico6.set_MediaComissao(new decimal?((auditorias.Any((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao() > decimal.Zero) ? decimal.Round(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao()) / auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Comissao() > decimal.Zero), 2) : decimal.Zero))); + sintetico6.set_ComissaoPrevista(new decimal?(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_ComissaoPrevista()))); + sintetico6.set_ComissaoPendente(new decimal?(auditorias.Sum((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_ComissaoPendente()))); + sintetico6.set_Cancelamentos(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_Situacao() == 3))); + sintetico6.set_Novos(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico6.set_Renovacoes(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico6.set_Apolices(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico6.set_Endossos(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => { + if (c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico6.set_Faturas(new int?(auditorias.Count((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico6.set_TotalGeral(new int?(auditorias.Count)); + sinteticos6.Add(sintetico6); + this.SinteticoRelatorio = new ObservableCollection(sinteticos6); + return; + } + case 9: + case 10: + { + if (this.SinistroFiltrado == null || this.SinistroFiltrado.Count == 0) + { + return; + } + List sinistros = (this.SinistroFiltrado.Any((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Selecionado()) ? ( + from x in this.SinistroFiltrado + where x.get_Selecionado() + select x).ToList() : this.SinistroFiltrado.ToList()); + List sinteticos7 = new List(); + Sintetico sintetico7 = new Sintetico(); + sintetico7.set_Liquidado(new int?(sinistros.Count((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => { + if (x.get_StatusSinistro() != 2) + { + return false; + } + return x.get_TipoSinistro() == 0; + }))); + sintetico7.set_Valor(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_Valor()))); + sintetico7.set_ValorOrcado(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorOrcado()))); + sintetico7.set_ValorLiberado(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorLiberado()))); + sintetico7.set_ValorPago(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorPago()))); + sintetico7.set_ValorLiquidado(new decimal?(( + from x in sinistros + where x.get_StatusSinistro() == 2 + select x).Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorPago()))); + sintetico7.set_ValorSalvado(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorSalvado()))); + sintetico7.set_ValorFranquia(new decimal?(sinistros.Sum((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_ValorFranquia()))); + sintetico7.set_Pendente(new int?(sinistros.Count((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => !x.get_Liquidacao().HasValue))); + sintetico7.set_TotalGeral(new int?(sinistros.Distinct().Count())); + sintetico7.set_TotalClientes(new int?(sinistros.Count((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_TipoSinistro() == 0))); + sintetico7.set_TotalTerceiros(new int?(sinistros.Count((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => x.get_TipoSinistro() == 1))); + sinteticos7.Add(sintetico7); + this.SinteticoRelatorio = new ObservableCollection(sinteticos7); + return; + } + case 12: + { + if (this.FaturaPendenteFiltrado == null || this.FaturaPendenteFiltrado.Count == 0) + { + return; + } + List faturaPendentes = (this.FaturaPendenteFiltrado.Any((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => x.get_Selecionado()) ? ( + from x in this.FaturaPendenteFiltrado + where x.get_Selecionado() + select x).ToList() : this.FaturaPendenteFiltrado.ToList()); + List sinteticos8 = new List(); + Sintetico sintetico8 = new Sintetico(); + sintetico8.set_TotalClientes(new int?(( + from x in faturaPendentes + select x.get_Cliente()).Distinct().Count())); + sintetico8.set_Cancelamentos(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => c.get_Documento().get_Situacao() == 3))); + sintetico8.set_Novos(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => { + if (c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico8.set_Renovacoes(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => { + if (c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico8.set_Apolices(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => { + if (c.get_Documento().get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico8.set_Endossos(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => { + if (c.get_Documento().get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico8.set_Faturas(new int?(faturaPendentes.Count((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente c) => c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2))); + sintetico8.set_TotalGeral(new int?(faturaPendentes.Count)); + sinteticos8.Add(sintetico8); + this.SinteticoRelatorio = new ObservableCollection(sinteticos8); + return; + } + case 13: + { + if (this.ExtratosFiltrado == null || this.ExtratosFiltrado.Count == 0) + { + return; + } + List extratoBaixadoRelatorios = (this.ExtratosFiltrado.Any((ExtratoBaixadoRelatorio x) => x.get_Selecionado()) ? ( + from x in this.ExtratosFiltrado + where x.get_Selecionado() + select x).ToList() : this.ExtratosFiltrado.ToList()); + List sinteticos9 = new List(); + Sintetico sintetico9 = new Sintetico(); + sintetico9.set_TotalGeral(new int?(extratoBaixadoRelatorios.Count)); + sinteticos9.Add(sintetico9); + this.SinteticoRelatorio = new ObservableCollection(sinteticos9); + return; + } + case 14: + { + if (this.MetaSeguradoraFiltrado == null || this.MetaSeguradoraFiltrado.Count == 0) + { + return; + } + List metaSeguradoraRelatorios = (this.MetaSeguradoraFiltrado.Any((MetaSeguradoraRelatorio x) => x.get_Selecionado()) ? ( + from x in this.MetaSeguradoraFiltrado + where x.get_Selecionado() + select x).ToList() : this.MetaSeguradoraFiltrado.ToList()); + List sinteticos10 = new List(); + Sintetico sintetico10 = new Sintetico(); + sintetico10.set_MetaAtingir(new decimal?(metaSeguradoraRelatorios.Sum((MetaSeguradoraRelatorio x) => x.get_MetaAtingir()))); + sintetico10.set_MetaCumprida(new decimal?(metaSeguradoraRelatorios.Sum((MetaSeguradoraRelatorio p) => p.get_MetaCumprida()))); + sinteticos10.Add(sintetico10); + this.SinteticoRelatorio = new ObservableCollection(sinteticos10); + return; + } + case 15: + { + if (this.MetaVendedorFiltrado == null || this.MetaVendedorFiltrado.Count == 0) + { + return; + } + List metaVendedorRelatorios = (this.MetaVendedorFiltrado.Any((MetaVendedorRelatorio x) => x.get_Selecionado()) ? ( + from x in this.MetaVendedorFiltrado + where x.get_Selecionado() + select x).ToList() : this.MetaVendedorFiltrado.ToList()); + List sinteticos11 = new List(); + Sintetico sintetico11 = new Sintetico(); + sintetico11.set_MetaAtingir(new decimal?(metaVendedorRelatorios.Sum((MetaVendedorRelatorio x) => x.get_MetaAtingir()))); + sintetico11.set_MetaCumprida(new decimal?(metaVendedorRelatorios.Sum((MetaVendedorRelatorio p) => p.get_MetaCumprida()))); + sinteticos11.Add(sintetico11); + this.SinteticoRelatorio = new ObservableCollection(sinteticos11); + return; + } + case 17: + { + if (this.LicenciamentoFiltrado == null || this.LicenciamentoFiltrado.Count == 0) + { + return; + } + List licenciamentos = (this.LicenciamentoFiltrado.Any((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => x.get_Selecionado()) ? ( + from x in this.LicenciamentoFiltrado + where x.get_Selecionado() + select x).ToList() : this.LicenciamentoFiltrado.ToList()); + List sinteticos12 = new List(); + Sintetico sintetico12 = new Sintetico(); + sintetico12.set_TotalClientes(new int?(licenciamentos.Count)); + sinteticos12.Add(sintetico12); + this.SinteticoRelatorio = new ObservableCollection(sinteticos12); + return; + } + case 18: + { + if (this.TarefaFiltrado == null || this.TarefaFiltrado.Count == 0) + { + return; + } + List tarefas = (this.TarefaFiltrado.Any((Gestor.Model.Domain.Relatorios.Tarefa.Tarefa x) => x.get_Selecionado()) ? ( + from x in this.TarefaFiltrado + where x.get_Selecionado() + select x).ToList() : this.TarefaFiltrado.ToList()); + List sinteticos13 = new List(); + Sintetico sintetico13 = new Sintetico(); + sintetico13.set_TotalTarefas(new int?(tarefas.Count)); + sinteticos13.Add(sintetico13); + this.SinteticoRelatorio = new ObservableCollection(sinteticos13); + return; + } + case 19: + { + if (this.NotaFiscalFiltrado == null || this.NotaFiscalFiltrado.Count == 0) + { + return; + } + List notaFiscalRelatorios = (this.NotaFiscalFiltrado.Any((NotaFiscalRelatorio x) => x.get_Selecionado()) ? ( + from x in this.NotaFiscalFiltrado + where x.get_Selecionado() + select x).ToList() : this.NotaFiscalFiltrado.ToList()); + List sinteticos14 = new List(); + Sintetico sintetico14 = new Sintetico(); + sintetico14.set_PremioLiquido(new decimal?(notaFiscalRelatorios.Sum((NotaFiscalRelatorio p) => p.get_Liquido()))); + sintetico14.set_Iss(new decimal?(notaFiscalRelatorios.Sum((NotaFiscalRelatorio p) => p.get_Iss()))); + sintetico14.set_PremioTotal(new decimal?(notaFiscalRelatorios.Sum((NotaFiscalRelatorio x) => x.get_Bruto()))); + sintetico14.set_TotalGeral(new int?(notaFiscalRelatorios.Count)); + sinteticos14.Add(sintetico14); + this.SinteticoRelatorio = new ObservableCollection(sinteticos14); + return; + } + case 29: + { + if (this.ClassificacaoFiltrado == null || this.ClassificacaoFiltrado.Count == 0) + { + return; + } + if (this.ClassificacaoFiltrado.Any((Gestor.Model.Domain.Relatorios.Classificacao.Classificacao x) => x.get_Selecionado())) + { + ( + from x in this.ClassificacaoFiltrado + where x.get_Selecionado() + select x).ToList(); + } + else + { + this.ClassificacaoFiltrado.ToList(); + } + List sinteticos15 = new List(); + Sintetico sintetico15 = new Sintetico(); + sintetico15.set_TotalClientes(new int?(this.ClassificacaoFiltrado.Count())); + sinteticos15.Add(sintetico15); + this.SinteticoRelatorio = new ObservableCollection(sinteticos15); + return; + } + default: + { + return; + } + } + } + + private static Sintetico SintetizarRenovacao(string grupo, List sintetico) + { + Sintetico sintetico1 = new Sintetico(); + sintetico1.set_Agrupamento(grupo); + sintetico1.set_Cancelamentos(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3) + { + return false; + } + return c.get_Documento().get_Situacao() == 3; + }))); + sintetico1.set_Novos(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() != 3 && c.get_Documento().get_Situacao() == 1) + { + return true; + } + if (c.get_Tipo() == 3 || c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 2; + }))); + sintetico1.set_Renovacoes(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3 || c.get_Documento().get_Situacao() != 2) + { + return false; + } + return c.get_Documento().get_Negocio().GetValueOrDefault() == 1; + }))); + sintetico1.set_Apolices(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3 || c.get_Tipo() != 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico1.set_Endossos(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3 || c.get_Tipo() == 0) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 1; + }))); + sintetico1.set_Faturas(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => { + if (c.get_Tipo() == 3) + { + return false; + } + return c.get_Documento().get_TipoRecebimento().GetValueOrDefault() == 2; + }))); + sintetico1.set_TotalProspeccao(new int?(sintetico.Count((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao c) => c.get_Tipo() == 3))); + sintetico1.set_TotalGeral(new int?(sintetico.Count)); + return sintetico1; + } + + private void StatusOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(3); + } + + public void SubirParametro(Gestor.Model.Domain.Relatorios.ParametrosRelatorio parametro) + { + if (parametro == null) + { + return; + } + int num = this.ParametrosRelatorioAdicionados.IndexOf(parametro); + if (num == 0) + { + return; + } + this.ParametrosRelatorioAdicionados.Move(num, num - 1); + } + + private void TipoVendedorOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(4); + } + + private static string UltimaMovimentacaoSinistro(Gestor.Model.Domain.Seguros.Sinistro x) + { + x.get_IdUsuarioAlteracao(); + if (x.get_IdUsuarioAlteracao() != 0) + { + return string.Format("{0} / {1}", x.get_DataAlteracao(), Recursos.Usuarios.First((Usuario usuario) => usuario.get_Id() == x.get_IdUsuarioAlteracao()).get_Nome()); + } + x.get_IdUsuarioCriacao(); + if (x.get_IdUsuarioCriacao() == 0) + { + return ""; + } + return string.Format("{0} / {1}", x.get_DataCriacao(), Recursos.Usuarios.First((Usuario usuario) => usuario.get_Id() == x.get_IdUsuarioCriacao()).get_Nome()); + } + + public async Task ValidateTarefa() + { + bool flag; + bool flag1 = false; + await this.ServicoRestriUsuario.BuscarRestricoes(Recursos.Usuario.get_Id()); + switch (this.Relatorio) + { + case 0: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + ObservableCollection clientesAtivosInativosFiltrado = this.ClientesAtivosInativosFiltrado; + if (!clientesAtivosInativosFiltrado.All((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 1: + { + if (this.ClientesAtivosInativosFiltrado != null && this.ClientesAtivosInativosFiltrado.Count != 0) + { + ObservableCollection observableCollection = this.ClientesAtivosInativosFiltrado; + if (!observableCollection.All((Gestor.Model.Domain.Relatorios.ClientesAtivosInativos.ClientesAtivosInativos x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 2: + { + if (this.ProducaoFiltrado != null && this.ProducaoFiltrado.Count != 0) + { + ObservableCollection producaoFiltrado = this.ProducaoFiltrado; + if (!producaoFiltrado.All((Gestor.Model.Domain.Relatorios.Producao.Producao x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 3: + { + if (this.ApolicePendenteFiltrado != null && this.ApolicePendenteFiltrado.Count != 0) + { + ObservableCollection apolicePendenteFiltrado = this.ApolicePendenteFiltrado; + if (!apolicePendenteFiltrado.All((Gestor.Model.Domain.Relatorios.ApolicePendente.ApolicePendente x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 4: + { + if (this.RenovacaoFiltrado != null && this.RenovacaoFiltrado.Count != 0) + { + ObservableCollection renovacaoFiltrado = this.RenovacaoFiltrado; + if (!renovacaoFiltrado.All((Gestor.Model.Domain.Relatorios.Renovacao.Renovacao x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 5: + { + if (this.ComissaoFiltrado != null && this.ComissaoFiltrado.Count != 0) + { + ObservableCollection comissaoFiltrado = this.ComissaoFiltrado; + if (!comissaoFiltrado.All((Gestor.Model.Domain.Relatorios.Comissao.Comissao x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 6: + case 16: + { + if (this.PendenteFiltrado != null && this.PendenteFiltrado.Count != 0) + { + ObservableCollection pendenteFiltrado = this.PendenteFiltrado; + if (!pendenteFiltrado.All((Gestor.Model.Domain.Relatorios.Pendente.Pendente x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 7: + { + flag1 = true; + goto case 26; + } + case 8: + { + if (this.Auditoria != null && this.Auditoria.Count != 0) + { + List auditoria = this.Auditoria; + if (!auditoria.All((Gestor.Model.Domain.Relatorios.Auditoria.Auditoria x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 9: + case 10: + { + if (this.SinistroFiltrado != null && this.SinistroFiltrado.Count != 0) + { + ObservableCollection sinistroFiltrado = this.SinistroFiltrado; + if (!sinistroFiltrado.All((Gestor.Model.Domain.Relatorios.Sinistro.Sinistro x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 11: + case 20: + { + flag1 = true; + goto case 26; + } + case 12: + { + if (this.FaturaPendente != null && this.FaturaPendente.Count != 0) + { + List faturaPendente = this.FaturaPendente; + if (!faturaPendente.All((Gestor.Model.Domain.Relatorios.FaturaPendente.FaturaPendente x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 13: + { + if (this.ExtratosFiltrado != null && this.ExtratosFiltrado.Count != 0) + { + ObservableCollection extratosFiltrado = this.ExtratosFiltrado; + if (!extratosFiltrado.All((ExtratoBaixadoRelatorio x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 14: + { + if (this.MetaSeguradoraFiltrado != null && this.MetaSeguradoraFiltrado.Count != 0) + { + ObservableCollection metaSeguradoraFiltrado = this.MetaSeguradoraFiltrado; + if (!metaSeguradoraFiltrado.All((MetaSeguradoraRelatorio x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 15: + { + if (this.MetaVendedorFiltrado != null && this.MetaVendedorFiltrado.Count != 0) + { + ObservableCollection metaVendedorFiltrado = this.MetaVendedorFiltrado; + if (!metaVendedorFiltrado.All((MetaVendedorRelatorio x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 17: + { + if (this.LicenciamentoFiltrado != null && this.LicenciamentoFiltrado.Count != 0) + { + ObservableCollection licenciamentoFiltrado = this.LicenciamentoFiltrado; + if (!licenciamentoFiltrado.All((Gestor.Model.Domain.Relatorios.Licenciamento.Licenciamento x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + case 18: + case 19: + case 21: + case 22: + case 23: + case 24: + case 25: + case 26: + { + if (flag1) + { + await base.ShowMessage("NECESSÁRIO SELECIONAR AO MENOS UM ITEM NA LISTA PARA GERAR TAREFAS.", "OK", "", false); + } + flag = flag1; + break; + } + case 27: + { + if (this.PlacaFiltrado != null && this.PlacaFiltrado.Count != 0) + { + ObservableCollection placaFiltrado = this.PlacaFiltrado; + if (!placaFiltrado.All((Gestor.Model.Domain.Relatorios.Placa.Placas x) => !x.get_Selecionado())) + { + goto case 26; + } + } + flag1 = true; + goto case 26; + } + default: + { + goto case 26; + } + } + return flag; + } + + private void VendedorOnPropertyChanged(object sender, PropertyChangedEventArgs args) + { + if (this._alterandoFiltros) + { + return; + } + this.RecheckAllSelected(2); + } + + private void WorkOnRelatorio(Gestor.Model.Common.Relatorio value) + { + bool id; + bool flag; + this.HtmlContent = string.Empty; + this.VisibilityHtml = false; + this.FiltroRelatorioSelecionado = new ObservableCollection(); + this.LimparFiltros(); + this.VisibilityFiltros = Visibility.Visible; + this.VisibilityMaisFiltros = Visibility.Visible; + this.VisibilityGridFiltros = Visibility.Collapsed; + this.VisibilityData = Visibility.Visible; + this.VisibilityOlho = Visibility.Visible; + this.VisibilityEspecial = Visibility.Collapsed; + this.VisibilityPagamento = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Visible; + this.VisibilityEtiqueta = Visibility.Visible; + this.VisibilityEmail = Visibility.Visible; + this.VisibilityAgrupamento = Visibility.Visible; + this.VisibilitySintetizar = Visibility.Visible; + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + this.VisibilityTarefas = (id ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityAcompanhamento = Visibility.Collapsed; + this.VisibilityReferencia = Visibility.Collapsed; + this.VisibiltyProtocolo = Visibility.Collapsed; + this.VisibilityMeta = Visibility.Collapsed; + this.VisibilityApolice = Visibility.Collapsed; + this.VisibiltySincronizar = (value == 3 || value == 16 ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityComparativo = Visibility.Collapsed; + this.VisibilityCompleto = Visibility.Collapsed; + this.VisibilityNotaFiscalPorSeguradora = Visibility.Collapsed; + this.Agrupamento = 0; + this.NovosNegocios = false; + this.ExtratosEnabled = false; + this.PermitirFiltrosPersonalizados = (value == 11 ? false : value != 7); + this.VisibilityFiltroPersonalizadoButton = Visibility.Visible; + Usuario usuario1 = Recursos.Usuario; + if (usuario1 != null) + { + flag = usuario1.get_Id() > (long)0; + } + else + { + flag = false; + } + this.VisibilityConfigurar = (flag ? Visibility.Visible : Visibility.Collapsed); + this.VisibilityUsuarios = false; + this.VisibilityOrdem = Visibility.Collapsed; + this.VisibilityValor = Visibility.Collapsed; + this.PlanilhaVisibility = Visibility.Collapsed; + this.VisibilityDocumentoAtivo = Visibility.Collapsed; + this.LimparFiltroUsuario(); + this.InicioValor = 0; + this.FimValor = 0; + switch (value) + { + case 0: + { + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityData = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityFiltros = Visibility.Collapsed; + this.VisibilityCompleto = Visibility.Visible; + this.InfoVisibility = Visibility.Collapsed; + return; + } + case 1: + { + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityFiltros = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + this.Info = "O RELATÓRIO DE ANIVERSARIANTE CONSIDERA O DIA E MÊS FILTRADOS E DESCONSIDERA O ANO INFORMADO NA PESQUISA."; + this.InfoVisibility = Visibility.Visible; + return; + } + case 2: + { + this.VisibiltyProtocolo = Visibility.Visible; + FiltroRelatorio filtroRelatorio = new FiltroRelatorio(); + filtroRelatorio.set_Id((long)1); + filtroRelatorio.set_Descricao(EnumHelper.GetDescription(1)); + filtroRelatorio.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio); + FiltroRelatorio filtroRelatorio1 = new FiltroRelatorio(); + filtroRelatorio1.set_Id((long)2); + filtroRelatorio1.set_Descricao(EnumHelper.GetDescription(2)); + filtroRelatorio1.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio1); + this.Referencias = new ObservableCollection(new List() + { + "VIGÊNCIA INICIAL", + "EMISSÃO", + "TRANSMISSÃO PROPOSTA", + "DATA DE CADASTRO" + }); + this.Referencia = this.Referencias.First(); + this.VisibilityReferencia = Visibility.Visible; + this.VisibilityGridFiltros = Visibility.Visible; + this.VisibilityOlho = Visibility.Collapsed; + this.PlanilhaVisibility = Visibility.Visible; + return; + } + case 3: + { + this.VisibiltyProtocolo = Visibility.Visible; + this.VisibiltySincronizar = Visibility.Visible; + this.VisibilityExtratos = Visibility.Collapsed; + return; + } + case 4: + { + this.VisibiltyProtocolo = Visibility.Visible; + this.VisibilityAcompanhamento = Visibility.Visible; + this.PlanilhaVisibility = Visibility.Visible; + return; + } + case 5: + { + this.VisibilityExtratos = Visibility.Collapsed; + return; + } + case 6: + case 9: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.PlanilhaVisibility = Visibility.Collapsed; + return; + } + case 7: + { + this.ParcelasEspeciais[0].set_IsEnable(true); + this.VisibilityEspecial = Visibility.Visible; + this.VisibilityPagamento = Visibility.Visible; + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.SomenteNaoPagos = true; + this.ReciboPagamento = false; + this.VisibilityOrdem = (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 8) ? Visibility.Visible : Visibility.Collapsed); + this.Ordens = new ObservableCollection(new List() + { + "DATA RECEBIMENTO", + "NOME CLIENTE", + "SEGURADORA, RAMO" + }); + this.OrdemSelecionada = this.Ordens.First(); + this.VisibilityHtml = true; + return; + } + case 8: + { + this.ParcelasEspeciais[0].set_IsEnable(false); + this.VisibilityEspecial = Visibility.Visible; + this.VisibilityExtratos = Visibility.Collapsed; + this.Info = "AGORA O RELATÓRIO DE AUDITORIA SELECIONA TODOS OS SEGUROS, MESMO TENDO PARCELAS PENDENTES, PARA FILTRAR APENAS OS SEGUROS SEM PARCELAS PENDENTES, BASTA UTILIZAR O FILTRO PERSONALIZADO 'RECEBIDO POR COMPLETO', PREENCHER 'SIM' EM SEU VALOR E APLICAR O FILTRO"; + this.InfoVisibility = Visibility.Visible; + FiltroRelatorio filtroRelatorio2 = new FiltroRelatorio(); + filtroRelatorio2.set_Id((long)1); + filtroRelatorio2.set_Descricao(EnumHelper.GetDescription(1)); + filtroRelatorio2.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio2); + FiltroRelatorio filtroRelatorio3 = new FiltroRelatorio(); + filtroRelatorio3.set_Id((long)2); + filtroRelatorio3.set_Descricao(EnumHelper.GetDescription(2)); + filtroRelatorio3.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio3); + FiltroRelatorio filtroRelatorio4 = new FiltroRelatorio(); + filtroRelatorio4.set_Id((long)3); + filtroRelatorio4.set_Descricao(EnumHelper.GetDescription(3)); + filtroRelatorio4.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio4); + FiltroRelatorio filtroRelatorio5 = new FiltroRelatorio(); + filtroRelatorio5.set_Id((long)4); + filtroRelatorio5.set_Descricao(EnumHelper.GetDescription(4)); + filtroRelatorio5.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio5); + FiltroRelatorio filtroRelatorio6 = new FiltroRelatorio(); + filtroRelatorio6.set_Id((long)5); + filtroRelatorio6.set_Descricao(EnumHelper.GetDescription(5)); + filtroRelatorio6.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio6); + FiltroRelatorio filtroRelatorio7 = new FiltroRelatorio(); + filtroRelatorio7.set_Id((long)6); + filtroRelatorio7.set_Descricao(EnumHelper.GetDescription(6)); + filtroRelatorio7.set_Tipo(5); + this.AdicionarFiltro(filtroRelatorio7); + return; + } + case 10: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityReferencia = Visibility.Visible; + this.Referencias = new ObservableCollection(new List() + { + "DATA SINISTRO", + "DATA LIQUIDAÇÃO", + "DATA RECLAMAÇÃO" + }); + this.Referencia = this.Referencias.First(); + return; + } + case 11: + { + this.VisibilityComparativo = Visibility.Visible; + this.VisibilityEspecial = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Visible; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityReferencia = Visibility.Visible; + this.Referencias = new ObservableCollection(new List() + { + "VIGÊNCIA INICIAL", + "EMISSÃO" + }); + this.Referencia = this.Referencias.First(); + return; + } + case 12: + { + this.Referencias = new ObservableCollection(new List() + { + "VIGÊNCIA", + "VENCIMENTO" + }); + this.Referencia = this.Referencias.First(); + this.VisibilityReferencia = Visibility.Visible; + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + return; + } + case 13: + case 20: + { + this.Referencias = new ObservableCollection(new List() + { + "DATA IMPORTAÇÃO", + "DATA DO EXTRATO", + "DATA DO CRÉDITO" + }); + this.Referencia = this.Referencias.First(); + if (this.Relatorio == 13) + { + this.VisibilityReferencia = Visibility.Visible; + this.VisibilityMaisFiltros = Visibility.Collapsed; + } + this.VisibilityEspecial = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + return; + } + case 14: + case 15: + { + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityData = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Visible; + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityMeta = Visibility.Visible; + this.Agrupamento = (this.Relatorio == 15 ? 3 : 1); + DateTime date = Funcoes.GetNetworkTime().Date; + this.SelectedMes = date.Month; + this.SelectedAno = date.Year; + return; + } + case 16: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.PlanilhaVisibility = Visibility.Collapsed; + this.VisibilityDocumentoAtivo = Visibility.Visible; + return; + } + case 17: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityData = Visibility.Collapsed; + this.VisibilityValor = Visibility.Visible; + this.InfoVisibility = Visibility.Collapsed; + return; + } + case 18: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + return; + } + case 19: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityNotaFiscalPorSeguradora = Visibility.Visible; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + return; + } + case 21: + case 22: + { + return; + } + case 23: + { + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + return; + } + case 24: + case 25: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Visible; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + return; + } + case 26: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.PlanilhaVisibility = Visibility.Collapsed; + return; + } + case 27: + { + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + return; + } + case 28: + { + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityEtiqueta = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityTarefas = Visibility.Collapsed; + this.VisibilityEmail = Visibility.Collapsed; + this.VisibilityExtratos = Visibility.Collapsed; + this.Referencias = new ObservableCollection(new List() + { + "VIGÊNCIA INICIAL", + "EMISSÃO", + "TRANSMISSÃO PROPOSTA", + "DATA DE CADASTRO" + }); + this.Referencia = this.Referencias.First(); + this.VisibilityReferencia = Visibility.Visible; + this.VisibilityGridFiltros = Visibility.Visible; + this.PlanilhaVisibility = Visibility.Visible; + return; + } + case 29: + { + this.VisibilityExtratos = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityAgrupamento = Visibility.Collapsed; + this.VisibilityData = Visibility.Collapsed; + this.VisibilitySintetizar = Visibility.Collapsed; + this.VisibilityMaisFiltros = Visibility.Collapsed; + this.VisibilityFiltros = Visibility.Collapsed; + this.VisibilityCompleto = Visibility.Collapsed; + this.InfoVisibility = Visibility.Collapsed; + this.Info = ""; + return; + } + default: + { + return; + } + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Relatorios/SinteticoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Relatorios/SinteticoViewModel.cs new file mode 100644 index 0000000..6adc8e5 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Relatorios/SinteticoViewModel.cs @@ -0,0 +1,424 @@ +using ClosedXML.Excel; +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Helpers; +using Gestor.Model.Attributes; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Relatorios; +using LiveCharts; +using LiveCharts.Definitions.Series; +using LiveCharts.Helpers; +using LiveCharts.Wpf; +using NReco.PdfGenerator; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.ComponentModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; +using System.Windows.Media; + +namespace Gestor.Application.ViewModels.Relatorios +{ + public class SinteticoViewModel : BaseSegurosViewModel + { + private Visibility _unicaPaginaVisibility = Visibility.Collapsed; + + private Geometry _maximizeRestore = Geometry.Parse((string)System.Windows.Application.Current.Resources["Restore"]); + + private ObservableCollection _series; + + private string _titulotela = string.Format("RELATÓRIO SINTÉTICO | VERSÃO GESTOR {0}", ApplicationHelper.Versao); + + public Geometry MaximizeRestore + { + get + { + return this._maximizeRestore; + } + set + { + this._maximizeRestore = value; + base.OnPropertyChanged("MaximizeRestore"); + } + } + + public string Relatorio + { + get; + set; + } + + public ObservableCollection Series + { + get + { + return this._series; + } + set + { + this._series = value; + base.OnPropertyChanged("Series"); + } + } + + public string Titulotela + { + get + { + return this._titulotela; + } + set + { + this._titulotela = value; + base.OnPropertyChanged("Titulotela"); + } + } + + public Visibility UnicaPaginaVisibility + { + get + { + return this._unicaPaginaVisibility; + } + set + { + this._unicaPaginaVisibility = value; + base.OnPropertyChanged("UnicaPaginaVisibility"); + } + } + + public SinteticoViewModel(List sintetico, string relatorio) + { + this.Relatorio = relatorio; + this.GerarSintetico(sintetico); + } + + public async Task GerarExcel(SinteticoSource sintetico) + { + List listagems = SinteticoViewModel.GerarRelacao(sintetico.Lista.ToList()); + string tempPath = ""; + string str = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + str = null; + return; + } + } + DateTime date = Functions.GetNetworkTime().Date; + str = string.Concat(tempPath, "SINTETICO ", date.ToShortDateString().Replace("/", ""), ".xlsx"); + } + await Funcoes.GerarXls(new XLWorkbook(), "SINTÉTICO", listagems, null).SaveAs(str); + Process.Start(str); + str = null; + } + + public async Task GerarPdf(SinteticoSource sintetico) + { + string str = await Funcoes.GenerateTable(SinteticoViewModel.GerarRelacao(sintetico.Lista.ToList()), new List(), false, false, "", null); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome(sintetico.Titulo); + tipoRelatorio.set_Inicio(DateTime.MinValue); + tipoRelatorio.set_Fim(DateTime.MinValue); + string str1 = Funcoes.ExportarHtml(tipoRelatorio, str, "60", "landscape", false, ""); + NRecoHtmlToPdfConverter nRecoHtmlToPdfConverter = new NRecoHtmlToPdfConverter(); + ((HtmlToPdfConverter)nRecoHtmlToPdfConverter).set_Orientation(1); + ((HtmlToPdfConverter)nRecoHtmlToPdfConverter).set_Zoom(0.5f); + byte[] numArray = ((HtmlToPdfConverter)nRecoHtmlToPdfConverter).GeneratePdf(str1); + using (SaveFileDialog saveFileDialog = new SaveFileDialog()) + { + saveFileDialog.Filter = "All Files|*.*"; + saveFileDialog.FileName = string.Format("RELATORIO FINANCEIRO_{0:ddMMyyyyhhmmss}", Funcoes.GetNetworkTime()); + if (DialogResult.OK != saveFileDialog.ShowDialog()) + { + return; + } + else if (!File.Exists(string.Concat(saveFileDialog.FileName, ".pdf"))) + { + File.WriteAllBytes(string.Concat(saveFileDialog.FileName, ".pdf"), numArray); + Process.Start(string.Concat(saveFileDialog.FileName, ".pdf")); + } + else + { + string[] fileName = new string[] { "JÁ EXISTE UM ARQUIVO COM O NOME DE ", saveFileDialog.FileName, ".pdf NA PASTA SELECIONADA. ", Environment.NewLine, "TENTE NOVAMENTE EM OUTRA PASTA." }; + await base.ShowMessage(string.Concat(fileName), "OK", "", false); + return; + } + } + saveFileDialog = null; + } + + private static List GerarRelacao(List lista) + { + return lista.Select((ValorSintetico x) => { + Listagem listagem = new Listagem(); + listagem.set_Agrupamento(x.get_Indice()); + listagem.set_Valor((x.get_Formato() == "VALOR" ? x.get_Valor().ToString("c2") : (x.get_Formato() == "PERCENTUAL" ? x.get_Valor().ToString("p2") : x.get_Valor().ToString(new CultureInfo("pt-BR"))))); + listagem.set_NomeRelatorio(x.get_NomeRelatorio()); + return listagem; + }).ToList(); + } + + private static List> GerarRelacao(List> listas) + { + List> lists = new List>(); + foreach (List lista in listas) + { + lists.Add(SinteticoViewModel.GerarRelacao(lista)); + } + return lists; + } + + private void GerarSintetico(List sintetico) + { + IChartValues chartValue; + decimal num; + this.UnicaPaginaVisibility = (this.Relatorio == "RELATÓRIO DE FECHAMENTO" ? Visibility.Visible : Visibility.Collapsed); + this.Series = new ObservableCollection(); + PropertyInfo[] properties = sintetico.First().GetType().GetProperties(); + for (int i = 0; i < (int)properties.Length; i++) + { + PropertyInfo propertyInfo = properties[i]; + if (!(propertyInfo.Name == "ValidationEvent") && !(propertyInfo.Name == "Agrupamento") && !sintetico.All((Sintetico s) => { + object value; + PropertyInfo property = s.GetType().GetProperty(propertyInfo.Name); + value = (property != null ? property.GetValue(s, null) : null); + return value == null; + })) + { + object obj = propertyInfo.GetCustomAttributes(typeof(DescriptionAttribute), true).FirstOrDefault(); + if (obj != null) + { + string description = ((DescriptionAttribute)obj).Description; + SinteticoSource sinteticoSource = new SinteticoSource() + { + Titulo = description, + Colecao = new SeriesCollection(), + Lista = new ObservableCollection() + }; + object obj1 = propertyInfo.GetCustomAttributes(typeof(TipoAttribute), true).FirstOrDefault(); + string str = ""; + if (obj1 != null) + { + str = ((TipoAttribute)obj1).get_Description(); + } + sintetico = ( + from x in sintetico + orderby propertyInfo.GetValue(x, null) descending + select x).ToList(); + foreach (Sintetico sintetico1 in sintetico) + { + bool flag = false; + PieSeries pieSeries = new PieSeries(); + pieSeries.set_Title(sintetico1.get_Agrupamento()); + pieSeries.set_DataLabels(false); + PieSeries pieSeries1 = pieSeries; + if (str == "PERCENTUAL") + { + flag = (decimal)propertyInfo.GetValue(sintetico1) < decimal.Zero; + ChartValues chartValue1 = new ChartValues(); + chartValue1.Add(Math.Abs((decimal)propertyInfo.GetValue(sintetico1))); + chartValue = chartValue1; + ObservableCollection lista = sinteticoSource.Lista; + ValorSintetico valorSintetico = new ValorSintetico(); + valorSintetico.set_Indice(string.Concat(sintetico1.get_Agrupamento(), (flag ? " (-)" : ""))); + valorSintetico.set_Valor(Math.Round((decimal)propertyInfo.GetValue(sintetico1) * new decimal(1, 0, 0, false, 2), 2)); + valorSintetico.set_Unidate("%"); + valorSintetico.set_Sinal((flag ? 1 : 0)); + valorSintetico.set_NomeRelatorio(description); + lista.Add(valorSintetico); + pieSeries1.set_LabelPoint((ChartPoint chartPoint) => ((decimal)propertyInfo.GetValue(sintetico1)).ToString("n2")); + } + else if (str == "VALOR") + { + flag = (decimal)propertyInfo.GetValue(sintetico1) < decimal.Zero; + ChartValues chartValue2 = new ChartValues(); + chartValue2.Add(Math.Abs((decimal)propertyInfo.GetValue(sintetico1))); + chartValue = chartValue2; + ObservableCollection observableCollection = sinteticoSource.Lista; + ValorSintetico valorSintetico1 = new ValorSintetico(); + valorSintetico1.set_Indice(string.Concat(sintetico1.get_Agrupamento(), (flag ? " (-)" : ""))); + valorSintetico1.set_Valor(Math.Round((decimal)propertyInfo.GetValue(sintetico1), 2)); + valorSintetico1.set_Formato(str); + valorSintetico1.set_Unidate("R$"); + valorSintetico1.set_Sinal((flag ? 1 : 0)); + valorSintetico1.set_NomeRelatorio(description); + observableCollection.Add(valorSintetico1); + pieSeries1.set_LabelPoint((ChartPoint chartPoint) => ((decimal)propertyInfo.GetValue(sintetico1)).ToString("n2")); + } + else + { + flag = (int)propertyInfo.GetValue(sintetico1) < 0; + ChartValues chartValue3 = new ChartValues(); + chartValue3.Add(Math.Abs((int)propertyInfo.GetValue(sintetico1))); + chartValue = chartValue3; + ObservableCollection lista1 = sinteticoSource.Lista; + ValorSintetico valorSintetico2 = new ValorSintetico(); + valorSintetico2.set_Indice(string.Concat(sintetico1.get_Agrupamento(), (flag ? " (-)" : ""))); + valorSintetico2.set_Valor(decimal.Parse(propertyInfo.GetValue(sintetico1).ToString())); + valorSintetico2.set_Formato(str); + valorSintetico2.set_Sinal((flag ? 1 : 0)); + valorSintetico2.set_NomeRelatorio(description); + lista1.Add(valorSintetico2); + pieSeries1.set_LabelPoint((ChartPoint chartPoint) => ((int)propertyInfo.GetValue(sintetico1)).ToString("n")); + } + pieSeries1.set_Values(chartValue); + sinteticoSource.Colecao.Add(pieSeries1); + } + if (obj1 != null && !(str == "PERCENTUAL")) + { + if (str != "VALOR") + { + if (this.Relatorio.Equals("RELATÓRIO DE FECHAMENTO")) + { + int num1 = sintetico.Sum((Sintetico x) => (int)propertyInfo.GetValue(x, null)); + if (num1 != 0) + { + foreach (ValorSintetico listum in sinteticoSource.Lista) + { + num = (new decimal(100) * listum.get_Valor()) / num1; + listum.set_Porcentagem(string.Concat(num.ToString("F"), "%")); + } + } + } + else + { + int num2 = sintetico.Sum((Sintetico x) => (int)propertyInfo.GetValue(x, null)); + if (num2 != 0) + { + foreach (ValorSintetico listum1 in sinteticoSource.Lista) + { + num = (new decimal(100) * listum1.get_Valor()) / num2; + listum1.set_Porcentagem(string.Concat(num.ToString("F"), "%")); + } + } + ObservableCollection observableCollection1 = sinteticoSource.Lista; + ValorSintetico valorSintetico3 = new ValorSintetico(); + valorSintetico3.set_Indice("TOTAL"); + valorSintetico3.set_Valor(num2); + valorSintetico3.set_Formato(str); + valorSintetico3.set_Sinal((sintetico.Sum((Sintetico x) => (int)propertyInfo.GetValue(x, null)) < 0 ? 1 : 0)); + valorSintetico3.set_Porcentagem("100%"); + observableCollection1.Add(valorSintetico3); + } + } + else if (this.Relatorio.Equals("RELATÓRIO DE FECHAMENTO")) + { + decimal num3 = Math.Round(sintetico.Sum((Sintetico x) => (decimal)propertyInfo.GetValue(x, null)), 2); + if (num3 != decimal.Zero) + { + foreach (ValorSintetico listum2 in sinteticoSource.Lista) + { + num = (new decimal(100) * listum2.get_Valor()) / num3; + listum2.set_Porcentagem(string.Concat(num.ToString("F"), "%")); + } + } + } + else + { + decimal num4 = Math.Round(sintetico.Sum((Sintetico x) => (decimal)propertyInfo.GetValue(x, null)), 2); + if (num4 != decimal.Zero) + { + foreach (ValorSintetico listum3 in sinteticoSource.Lista) + { + num = (new decimal(100) * listum3.get_Valor()) / num4; + listum3.set_Porcentagem(string.Concat(num.ToString("F"), "%")); + } + } + ObservableCollection lista2 = sinteticoSource.Lista; + ValorSintetico valorSintetico4 = new ValorSintetico(); + valorSintetico4.set_Indice("TOTAL"); + valorSintetico4.set_Valor(num4); + valorSintetico4.set_Unidate("R$"); + valorSintetico4.set_Formato(str); + valorSintetico4.set_Sinal((sintetico.Sum((Sintetico x) => (decimal)propertyInfo.GetValue(x, null)) < decimal.Zero ? 1 : 0)); + valorSintetico4.set_Porcentagem("100%"); + lista2.Add(valorSintetico4); + } + } + this.Series.Add(sinteticoSource); + } + } + } + } + + public async Task Print(SinteticoSource sintetico) + { + DateTime dateTime; + DateTime dateTime1; + string str = Funcoes.GerarGrafico(sintetico.Lista.ToList()); + string str1 = await Funcoes.GenerateTable(SinteticoViewModel.GerarRelacao(sintetico.Lista.ToList()), new List(), true, false, "", null); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome(sintetico.Titulo); + DateTime? dateStart = sintetico.DateStart; + dateTime = (dateStart.HasValue ? dateStart.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Inicio(dateTime); + dateStart = sintetico.DateFinal; + dateTime1 = (dateStart.HasValue ? dateStart.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Fim(dateTime1); + string str2 = Funcoes.ExportarHtml(tipoRelatorio, str1, "60", "landscape", false, str); + string tempPath = Path.GetTempPath(); + string str3 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(this.Relatorio, ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str3, true, Encoding.UTF8); + streamWriter.Write(str2); + streamWriter.Close(); + Process.Start(str3); + str = null; + } + + public async Task PrintUnica(SinteticoSource sintetico) + { + DateTime dateTime; + DateTime dateTime1; + List> lists = new List>(); + foreach (SinteticoSource series in this.Series) + { + lists.Add(series.Lista.ToList()); + } + string str = Funcoes.GerarGraficoUnico(lists); + string str1 = await Funcoes.GenerateMultipleTable(SinteticoViewModel.GerarRelacao(lists), new List(), true, false, "", null); + TipoRelatorio tipoRelatorio = new TipoRelatorio(); + tipoRelatorio.set_Nome("RELATÓRIOS"); + DateTime? dateStart = sintetico.DateStart; + dateTime = (dateStart.HasValue ? dateStart.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Inicio(dateTime); + dateStart = sintetico.DateFinal; + dateTime1 = (dateStart.HasValue ? dateStart.GetValueOrDefault() : DateTime.MinValue); + tipoRelatorio.set_Fim(dateTime1); + string str2 = Funcoes.ExportarMultipleHtml(tipoRelatorio, str1, "60", "landscape", false, str); + string tempPath = Path.GetTempPath(); + string str3 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (new Regex(string.Concat("[", Regex.Escape(string.Concat(new string(Path.GetInvalidFileNameChars()), new string(Path.GetInvalidPathChars()))), "]"))).Replace(this.Relatorio, ""), Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str3, true, Encoding.UTF8); + streamWriter.Write(str2); + streamWriter.Close(); + Process.Start(str3); + str = null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/ApoliceViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/ApoliceViewModel.cs new file mode 100644 index 0000000..94fc4be --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/ApoliceViewModel.cs @@ -0,0 +1,124 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class ApoliceViewModel : BaseApoliceViewModel + { + private bool _documentoExcluido; + + public bool DocumentoExcluido + { + get + { + return this._documentoExcluido; + } + set + { + this._documentoExcluido = value; + base.OnPropertyChanged("DocumentoExcluido"); + } + } + + public ApoliceViewModel(AcessoApolice acesso, Documento documentoSelecionado, bool invoke = true, long idparcela = 0L) + { + long id; + base.Invoke = invoke; + base.Acesso = acesso; + base.DocumentoSelecionado = documentoSelecionado; + if (invoke) + { + Parcela parcelaSelecionada = ConsultaViewModel.ParcelaSelecionada; + if (parcelaSelecionada != null) + { + id = parcelaSelecionada.get_Id(); + } + else + { + id = (long)0; + } + } + else + { + id = idparcela; + } + base.ParcelaSelecionada = id; + this.DocumentoExcluido = (base.DocumentoSelecionado != null ? base.DocumentoSelecionado.get_Excluido() : false); + base.Seleciona(base.DocumentoSelecionado); + } + + public void AbrirInfo() + { + base.ShowDrawer(new InfoDrawer(base.SelectedDocumento, true), 0, false); + } + + public async Task Alteracao(bool alterar) + { + if (base.AllowEditApolice) + { + ObservableCollection parcelas = base.Parcelas; + if (!parcelas.Any((Parcela x) => x.get_DataRecebimento().HasValue)) + { + List repasses = base.Repasses; + if (!repasses.Any((VendedorParcela x) => x.get_DataPagamento().HasValue)) + { + List list = Recursos.Seguradoras.Where((Seguradora x) => { + if (x.get_Ativo()) + { + return true; + } + return x.get_Id() == base.SelectedDocumento.get_Controle().get_Seguradora().get_Id(); + }).ToList(); + base.Seguradoras = list; + base.SeguradorasAnteriores = Recursos.Seguradoras; + List ramos = Recursos.Ramos.Where((Ramo x) => { + if (x.get_Ativo()) + { + return true; + } + return x.get_Id() == base.SelectedDocumento.get_Controle().get_Ramo().get_Id(); + }).ToList(); + base.Ramos = ramos; + List produtos = Recursos.Produtos.Where((Produto x) => { + if (x.get_Ativo()) + { + return true; + } + if (base.SelectedDocumento.get_Controle().get_Produto() == null) + { + return false; + } + return x.get_Id() == base.SelectedDocumento.get_Controle().get_Produto().get_Id(); + }).ToList(); + base.Produtos = produtos; + List statuses = Recursos.Status.Where((Gestor.Model.Domain.Seguros.Status x) => { + if (x.get_Ativo()) + { + return true; + } + if (base.SelectedDocumento.get_Status() == null) + { + return false; + } + return x.get_Id() == base.SelectedDocumento.get_Status().get_Id(); + }).ToList(); + base.Status = statuses; + return; + } + } + } + await base.ShowMessage("DOCUMENTO POSSUI BAIXAS DE COMISSÃO OU PAGAMENTO DE VENDEDORES.\nNÃO SERÁ POSSÍVEL ALTERAR ALGUMAS INFORMAÇÕES DO DOCUMENTO.\nPARA ISSO, EXCLUA AS BAIXAS E O PAGAMENTO DO VENDEDOR", "OK", "", false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/ClienteViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/ClienteViewModel.cs new file mode 100644 index 0000000..b68e57d --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/ClienteViewModel.cs @@ -0,0 +1,1787 @@ +using Agger.Registro; +using Gestor.Application.Actions; +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Command; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Security; +using Gestor.Common.Validation; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Newtonsoft.Json; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Net.Http; +using System.Runtime.CompilerServices; +using System.Text; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Input; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class ClienteViewModel : BaseSegurosViewModel + { + private const int NumeroMaximoCadastros = 9; + + private readonly ClienteServico _servico; + + private const string AddCentralSegurado = "ADICIONAR CENTRAL SEGURADO"; + + private const string UpdateCentralSegurado = "ALTERAR DADOS/SENHA CENTRAL SEGURADO"; + + private bool _visibilityLogAntigo = Recursos.Configuracoes.Any(new Func((ConfiguracaoSistema x) => x.get_Configuracao() == 22)); + + private ObservableCollection _telefones = new ObservableCollection(); + + private ObservableCollection _emails = new ObservableCollection(); + + private ObservableCollection _enderecos = new ObservableCollection(); + + private ObservableCollection _contatos = new ObservableCollection(); + + private ObservableCollection _vinculos = new ObservableCollection(); + + private Cliente _vinculo; + + private bool _isLoading; + + private bool _clienteExcluido; + + private DateTime? _nascimentoCliente; + + private DateTime? _habilitaCliente; + + private DateTime? _vencimentoHabCliente; + + private DateTime? _expedicaoCliente; + + private Cliente _selectedCliente; + + private string _fieldNascimento = "NASCIMENTO"; + + private string _fieldDocumento = "CPF"; + + private Visibility _visibilityJuridica = Visibility.Collapsed; + + private Visibility _visibilityFisica = Visibility.Collapsed; + + private bool _enableAddTelephone = true; + + private bool _enableAddAddress = true; + + private bool _enableAddEmail = true; + + private bool _enableAddContact = true; + + private string _profissaoText; + + private string _atividadeText; + + private bool _saving; + + private ObservableCollection _origens; + + private OrigemCliente _selectedOrigem; + + public Visibility AddUsuarioCentralSeguradoVisibility { get; set; } = (string.IsNullOrEmpty(Connection.UrlCentralSegurado) ? Visibility.Collapsed : Visibility.Visible); + + public string AtividadeText + { + get + { + return this._atividadeText; + } + set + { + this._atividadeText = value; + base.OnPropertyChanged("AtividadeText"); + } + } + + public bool ClienteExcluido + { + get + { + return this._clienteExcluido; + } + set + { + this._clienteExcluido = value; + base.OnPropertyChanged("ClienteExcluido"); + } + } + + private Cliente ClienteSelecionado + { + get; + set; + } + + public ICommand CommandAddUsuarioCentralSegurado + { + get; + set; + } + + public ObservableCollection Contatos + { + get + { + return this._contatos; + } + set + { + this._contatos = value; + base.OnPropertyChanged("Contatos"); + } + } + + public ObservableCollection Emails + { + get + { + return this._emails; + } + set + { + this._emails = value; + base.OnPropertyChanged("Emails"); + } + } + + public bool EnableAddAddress + { + get + { + return this._enableAddAddress; + } + set + { + this._enableAddAddress = value; + base.OnPropertyChanged("EnableAddAddress"); + } + } + + public bool EnableAddContact + { + get + { + return this._enableAddContact; + } + set + { + this._enableAddContact = value; + base.OnPropertyChanged("EnableAddContact"); + } + } + + public bool EnableAddEmail + { + get + { + return this._enableAddEmail; + } + set + { + this._enableAddEmail = value; + base.OnPropertyChanged("EnableAddEmail"); + } + } + + public bool EnableAddTelephone + { + get + { + return this._enableAddTelephone; + } + set + { + this._enableAddTelephone = value; + base.OnPropertyChanged("EnableAddTelephone"); + } + } + + public ObservableCollection Enderecos + { + get + { + return this._enderecos; + } + set + { + this._enderecos = value; + base.OnPropertyChanged("Enderecos"); + } + } + + public DateTime? ExpedicaoCliente + { + get + { + return this._expedicaoCliente; + } + set + { + this._expedicaoCliente = value; + base.OnPropertyChanged("ExpedicaoCliente"); + } + } + + public string FieldDocumento + { + get + { + return this._fieldDocumento; + } + set + { + this._fieldDocumento = value; + base.OnPropertyChanged("FieldDocumento"); + } + } + + public string FieldNascimento + { + get + { + return this._fieldNascimento; + } + set + { + this._fieldNascimento = value; + base.OnPropertyChanged("FieldNascimento"); + } + } + + public DateTime? HabilitaCliente + { + get + { + return this._habilitaCliente; + } + set + { + this._habilitaCliente = value; + base.OnPropertyChanged("HabilitaCliente"); + } + } + + private bool Invoke + { + get; + } + + private bool IsJuridica + { + get; + set; + } + + public bool IsLoading + { + get + { + return this._isLoading; + } + set + { + this._isLoading = value; + base.OnPropertyChanged("IsLoading"); + } + } + + public string LabelAddUsuarioCentralSegurado + { + get + { + if (this.SelectedCliente != null && this.SelectedCliente.get_EstaNaCentralSegurado()) + { + return "ALTERAR DADOS/SENHA CENTRAL SEGURADO"; + } + return "ADICIONAR CENTRAL SEGURADO"; + } + } + + public DateTime? NascimentoCliente + { + get + { + return this._nascimentoCliente; + } + set + { + this._nascimentoCliente = value; + base.OnPropertyChanged("NascimentoCliente"); + } + } + + public ObservableCollection Origens + { + get + { + return this._origens; + } + set + { + this._origens = value; + base.OnPropertyChanged("Origens"); + if (this.Origens != null) + { + this.SelectedOrigem = this.Origens.FirstOrDefault(); + } + } + } + + public string ProfissaoText + { + get + { + return this._profissaoText; + } + set + { + this._profissaoText = value; + base.OnPropertyChanged("ProfissaoText"); + } + } + + public bool Salvando + { + get; + set; + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + long? nullable; + this._selectedCliente = value; + this.WorkOnSelectedCliente(value); + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedCliente"); + base.OnPropertyChanged("LabelAddUsuarioCentralSegurado"); + } + } + + public OrigemCliente SelectedOrigem + { + get + { + return this._selectedOrigem; + } + set + { + this._selectedOrigem = value; + base.OnPropertyChanged("SelectedOrigem"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public DateTime? VencimentoHabCliente + { + get + { + return this._vencimentoHabCliente; + } + set + { + this._vencimentoHabCliente = value; + base.OnPropertyChanged("VencimentoHabCliente"); + } + } + + public Cliente Vinculo + { + get + { + return this._vinculo; + } + set + { + this._vinculo = value; + base.OnPropertyChanged("Vinculo"); + } + } + + public ObservableCollection Vinculos + { + get + { + return this._vinculos; + } + set + { + if (value != null && value.Count > 0 && this.SelectedCliente != null) + { + foreach (ClienteVinculo clienteVinculo in value) + { + if (clienteVinculo.get_Cliente2().get_Id() != this.SelectedCliente.get_Id()) + { + continue; + } + clienteVinculo.set_Parentesco(Funcoes.ParentescoInverso(clienteVinculo.get_Parentesco())); + } + } + this._vinculos = value; + base.OnPropertyChanged("Vinculos"); + } + } + + public Visibility VisibilityFisica + { + get + { + return this._visibilityFisica; + } + set + { + this._visibilityFisica = value; + base.OnPropertyChanged("VisibilityFisica"); + } + } + + public Visibility VisibilityJuridica + { + get + { + return this._visibilityJuridica; + } + set + { + this._visibilityJuridica = value; + base.OnPropertyChanged("VisibilityJuridica"); + } + } + + public bool VisibilityLogAntigo + { + get + { + return this._visibilityLogAntigo; + } + set + { + this._visibilityLogAntigo = value; + base.OnPropertyChanged("VisibilityLogAntigo"); + } + } + + public ClienteViewModel(Cliente cliente = null, bool invoke = true) + { + this.Invoke = invoke; + this._servico = new ClienteServico(); + this.ClienteSelecionado = cliente ?? MainViewModel.ClienteSelecionado; + this.SelecionaCliente(this.ClienteSelecionado); + this.CommandAddUsuarioCentralSegurado = new RelayCommand(() => this.AddUsuarioCentralSegurado()); + } + + public async void AbrirLogAntigo() + { + base.Loading(true); + string str = await this._servico.BuscarLogAntigo(this.SelectedCliente.get_Id()); + base.Loading(false); + if (!string.IsNullOrEmpty(str)) + { + base.ShowDrawer(new LogSistemaAntigo(this.SelectedCliente.get_Id(), str), 0, false); + } + else + { + await base.ShowMessage("NÃO HÁ LOG PARA ESSE CLIENTE", "OK", "", false); + } + } + + public async void AddUsuarioCentralSegurado() + { + string str; + string str1; + string str2; + string str3; + string str4; + string str5; + string str6; + string str7; + if (this.SelectedCliente != null && this.SelectedCliente.get_Emails().Count != 0) + { + base.Loading(true); + str7 = "CLIENTE CADASTRADO/ALTERADO COM SUCESSO!"; + try + { + str = (this.SelectedCliente.get_Telefones().Count == 0 ? string.Empty : string.Concat("(", this.SelectedCliente.get_Telefones()[0].get_Prefixo(), ") ", this.SelectedCliente.get_Telefones()[0].get_Numero())); + string str8 = str; + bool count = this.SelectedCliente.get_Enderecos().Count > 0; + Token token = new Token(); + UsuarioCentralSegurado usuarioCentralSegurado = new UsuarioCentralSegurado(); + usuarioCentralSegurado.set_Id(""); + usuarioCentralSegurado.set_Senha(""); + usuarioCentralSegurado.set_Serial(token.Encrypt(Recursos.Empresa.get_Serial())); + usuarioCentralSegurado.set_FornecedorId(ApplicationHelper.IdFornecedor); + usuarioCentralSegurado.set_Nome(token.Encrypt(this.SelectedCliente.get_Nome())); + usuarioCentralSegurado.set_Documento(token.Encrypt(this.SelectedCliente.get_Documento().Clear())); + usuarioCentralSegurado.set_Email(token.Encrypt(this.SelectedCliente.get_Emails()[0].get_Email())); + usuarioCentralSegurado.set_IdEmpresa(this.SelectedCliente.get_IdEmpresa()); + usuarioCentralSegurado.set_Telefone(token.Encrypt(str8)); + str1 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Endereco()) : string.Empty); + usuarioCentralSegurado.set_Rua(str1); + str2 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Numero()) : string.Empty); + usuarioCentralSegurado.set_Numero(str2); + str3 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Bairro()) : string.Empty); + usuarioCentralSegurado.set_Bairro(str3); + str4 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Cidade()) : string.Empty); + usuarioCentralSegurado.set_Cidade(str4); + str5 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Estado()) : string.Empty); + usuarioCentralSegurado.set_Estado(str5); + str6 = (count ? token.Encrypt(this.SelectedCliente.get_Enderecos()[0].get_Cep()) : string.Empty); + usuarioCentralSegurado.set_Cep(str6); + usuarioCentralSegurado.set_Corretora(token.Encrypt(Recursos.Empresa.get_Nome())); + usuarioCentralSegurado.set_UriCorretora(token.Encrypt(Connection.UrlCentralSegurado)); + UsuarioCentralSegurado usuarioCentralSegurado1 = usuarioCentralSegurado; + using (HttpClient httpClient = new HttpClient()) + { + StringContent stringContent = new StringContent(JsonConvert.SerializeObject(usuarioCentralSegurado1), Encoding.UTF8, "application/json"); + Uri centralSegurado = Address.get_CentralSegurado(); + string[] strArrays = new string[] { "Usuario" }; + Uri uri = centralSegurado.Append(strArrays); + string[] strArrays1 = new string[] { "AddAggerApp" }; + Uri uri1 = uri.Append(strArrays1); + HttpResponseMessage httpResponseMessage = await httpClient.PostAsync(uri1, stringContent); + await this._servico.AddCentralSegurado(this.SelectedCliente.get_Id(), httpResponseMessage.get_IsSuccessStatusCode()); + if (!httpResponseMessage.get_IsSuccessStatusCode()) + { + string str9 = await httpResponseMessage.get_Content().ReadAsStringAsync(); + str7 = string.Concat("HOUVE(RAM) O(S) SEGUINTE(S) ERROS: ", str9.Replace(";", ", ").ToUpper()); + } + httpResponseMessage = null; + } + httpClient = null; + } + catch + { + str7 = "HOUVERAM ERROS AO CADASTRAR/ALTERAR O CLIENTE!"; + } + base.OnPropertyChanged("LabelAddUsuarioCentralSegurado"); + base.Loading(false); + await base.ShowMessage(str7, "OK", "", false); + } + str7 = null; + } + + public async void CancelarAlteracao() + { + base.Loading(true); + this.IsLoading = true; + base.Alterar(false); + await this.CarregaCliente(this.ClienteSelecionado); + this.Salvando = false; + this.IsLoading = false; + base.Loading(false); + } + + public async Task CarregaCliente(Cliente value) + { + bool count; + bool flag; + bool count1; + bool flag1; + bool count2; + bool flag2; + bool count3; + Cliente cliente; + if (value == null || value.get_Id() == 0) + { + this.SelectedCliente = null; + this.Telefones = null; + this.Enderecos = null; + this.Emails = null; + this.Contatos = null; + this.Vinculos = null; + this.Origens = null; + } + else + { + cliente = value; + if (value.get_Id() != 0) + { + cliente = await this._servico.BuscarCliente(value.get_Id()); + Cliente cliente1 = cliente; + ObservableCollection observableCollection = await this._servico.BuscarTelefonesAsync(value.get_Id()); + cliente1.set_Telefones(observableCollection); + cliente1 = null; + ClienteViewModel clienteViewModel = this; + ObservableCollection telefones = cliente.get_Telefones(); + if (telefones != null) + { + count = telefones.Count <= 9; + } + else + { + count = false; + } + clienteViewModel.EnableAddTelephone = count; + cliente1 = cliente; + ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(value.get_Id()); + cliente1.set_Emails(observableCollection1); + cliente1 = null; + ClienteViewModel clienteViewModel1 = this; + ObservableCollection emails = cliente.get_Emails(); + if (emails != null) + { + flag = emails.Count <= 9; + } + else + { + flag = false; + } + clienteViewModel1.EnableAddEmail = flag; + cliente1 = cliente; + ObservableCollection observableCollection2 = await this._servico.BuscarEnderecosAsync(value.get_Id()); + cliente1.set_Enderecos(observableCollection2); + cliente1 = null; + ClienteViewModel clienteViewModel2 = this; + ObservableCollection enderecos = cliente.get_Enderecos(); + if (enderecos != null) + { + count1 = enderecos.Count <= 9; + } + else + { + count1 = false; + } + clienteViewModel2.EnableAddAddress = count1; + cliente1 = cliente; + ObservableCollection observableCollection3 = await this._servico.BuscarContatosAsync(value.get_Id()); + cliente1.set_Contatos(observableCollection3); + cliente1 = null; + ClienteViewModel clienteViewModel3 = this; + ObservableCollection contatos = cliente.get_Contatos(); + if (contatos != null) + { + flag1 = contatos.Count <= 9; + } + else + { + flag1 = false; + } + clienteViewModel3.EnableAddContact = flag1; + cliente1 = cliente; + ObservableCollection observableCollection4 = await this._servico.BuscarVinculosAsync(value.get_Id()); + cliente1.set_Vinculos(observableCollection4); + cliente1 = null; + this.Origens = await this._servico.BuscarOrigens(value.get_Id()); + this.Telefones = cliente.get_Telefones(); + ObservableCollection telefones1 = this.Telefones; + if (telefones1 != null) + { + count2 = telefones1.Count == 0; + } + else + { + count2 = false; + } + if (count2) + { + this.IncluirTelefone(); + } + this.Emails = cliente.get_Emails(); + ObservableCollection emails1 = this.Emails; + if (emails1 != null) + { + flag2 = emails1.Count == 0; + } + else + { + flag2 = false; + } + if (flag2) + { + this.IncluirEmail(); + } + this.Enderecos = cliente.get_Enderecos(); + ObservableCollection enderecos1 = this.Enderecos; + if (enderecos1 != null) + { + count3 = enderecos1.Count == 0; + } + else + { + count3 = false; + } + if (count3) + { + this.IncluirEndereco(); + } + this.Contatos = cliente.get_Contatos(); + this.Vinculos = cliente.get_Vinculos(); + } + if (!cliente.get_DocumentoPrincipal().HasValue) + { + cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); + } + if (cliente.get_ResponsavelAssinatura() == null) + { + Cliente cliente2 = cliente; + ResponsavelAssinatura responsavelAssinatura = new ResponsavelAssinatura(); + responsavelAssinatura.set_IdCliente(cliente.get_Id()); + cliente2.set_ResponsavelAssinatura(responsavelAssinatura); + } + this.SelectedCliente = cliente; + this.JuridicaouFisica(this.SelectedCliente.get_Documento()); + this.SelectedCliente.Initialize(); + ObservableCollection telefones2 = this.SelectedCliente.get_Telefones(); + if (telefones2 != null) + { + List list = telefones2.ToList(); + list.ForEach((ClienteTelefone telefone) => telefone.Initialize()); + } + else + { + } + ObservableCollection enderecos2 = this.SelectedCliente.get_Enderecos(); + if (enderecos2 != null) + { + List clienteEnderecos = enderecos2.ToList(); + clienteEnderecos.ForEach((ClienteEndereco endereco) => endereco.Initialize()); + } + else + { + } + ObservableCollection contatos1 = this.SelectedCliente.get_Contatos(); + if (contatos1 != null) + { + List maisContatos = contatos1.ToList(); + maisContatos.ForEach((MaisContato contato) => contato.Initialize()); + } + else + { + } + ObservableCollection emails2 = this.SelectedCliente.get_Emails(); + if (emails2 != null) + { + List clienteEmails = emails2.ToList(); + clienteEmails.ForEach((ClienteEmail email) => email.Initialize()); + } + else + { + } + ObservableCollection vinculos = this.SelectedCliente.get_Vinculos(); + if (vinculos != null) + { + List clienteVinculos = vinculos.ToList(); + clienteVinculos.ForEach((ClienteVinculo vinculo) => vinculo.Initialize()); + } + else + { + } + this.Initialized = true; + } + cliente = null; + } + + public async void Excluir() + { + Cliente selectedCliente; + if (this.SelectedCliente != null && this.SelectedCliente.get_Id() != 0) + { + if (await (new ApoliceServico()).BuscarApolicesAsync(this.SelectedCliente.get_Id(), 4, null).Count > 0) + { + await base.ShowMessage("NÃO É POSSÍVEL EXCLUIR O CLIENTE POIS POSSUI APÓLICES CADASTRADAS.", "OK", "", false); + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + selectedCliente = this.SelectedCliente; + selectedCliente.set_Excluido(true); + if (await this._servico.Delete(selectedCliente)) + { + this.ClienteSelecionado = null; + MainViewModel.ClienteSelecionado = null; + Action limparCliente = Gestor.Application.Actions.Actions.LimparCliente; + if (limparCliente != null) + { + limparCliente(); + } + else + { + } + Cliente cliente = new Cliente(); + cliente.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); + cliente.set_ClienteDesde(new DateTime?(Funcoes.GetNetworkTime().Date)); + this.SelectedCliente = cliente; + ObservableCollection observableCollection = new ObservableCollection(); + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Cliente(this.SelectedCliente); + clienteTelefone.set_Tipo(new TipoTelefone?(1)); + clienteTelefone.set_Ordem(new int?(1)); + observableCollection.Add(clienteTelefone); + this.Telefones = observableCollection; + ObservableCollection observableCollection1 = new ObservableCollection(); + ClienteEndereco clienteEndereco = new ClienteEndereco(); + clienteEndereco.set_Cliente(this.SelectedCliente); + clienteEndereco.set_Ordem(new int?(1)); + observableCollection1.Add(clienteEndereco); + this.Enderecos = observableCollection1; + ObservableCollection observableCollection2 = new ObservableCollection(); + ClienteEmail clienteEmail = new ClienteEmail(); + clienteEmail.set_Cliente(this.SelectedCliente); + clienteEmail.set_Ordem(new int?(1)); + observableCollection2.Add(clienteEmail); + this.Emails = observableCollection2; + this.Contatos = new ObservableCollection(); + this.Vinculos = new ObservableCollection(); + this.Origens = new ObservableCollection(); + string str = string.Format("EXCLUIU CLIENTE \"{0}\", ID: {1}", selectedCliente.get_Nome(), selectedCliente.get_Id()); + base.RegistrarAcao(str, selectedCliente.get_Id(), new TipoTela?(1), string.Format("CLIENTE \"{0}\", ID: {1}", this.SelectedCliente.get_Nome(), this.SelectedCliente.get_Id())); + base.ToggleSnackBar("CLIENTE EXCLUÍDO COM SUCESSO", true); + } + } + } + selectedCliente = null; + } + + public void ExcluirContato(MaisContato contato) + { + this.EnableAddContact = this.Contatos.Count <= 9; + this.Contatos.Remove(contato); + } + + public async void ExcluirEmail(ClienteEmail email) + { + if (this.Emails.Count < 2) + { + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 29)) + { + await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM CONTATO DE E-MAIL CADASTRADO.", "OK", "", false); + return; + } + } + this.EnableAddEmail = this.Emails.Count <= 9; + this.Emails.Remove(email); + } + + public async void ExcluirEndereco(ClienteEndereco endereco) + { + if (this.Enderecos.Count >= 2) + { + this.EnableAddAddress = this.Enderecos.Count <= 9; + this.Enderecos.Remove(endereco); + } + else + { + await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM ENDEREÇO CADASTRADO.", "OK", "", false); + } + } + + public async Task ExcluirOrigem(OrigemCliente origem) + { + ClienteViewModel clienteViewModel = this; + clienteViewModel.Origens.Remove(origem); + clienteViewModel.OnPropertyChanged("Origens"); + } + + public async void ExcluirTelefone(ClienteTelefone telefone) + { + if (this.Telefones.Count >= 2) + { + this.EnableAddTelephone = this.Telefones.Count <= 9; + this.Telefones.Remove(telefone); + } + else + { + await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM CONTATO TELEFÔNICO CADASTRADO.", "OK", "", false); + } + } + + public void ExcluirVinculo(ClienteVinculo vinculo) + { + this.Vinculos.Remove(vinculo); + } + + public void IncluirCliente() + { + DateTime date = Funcoes.GetNetworkTime().Date; + Cliente cliente = new Cliente(); + cliente.set_IdEmpresa(Recursos.Usuario.get_IdEmpresa()); + cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); + cliente.set_ClienteDesde(new DateTime?(date)); + cliente.set_ResponsavelAssinatura(new ResponsavelAssinatura()); + this.SelectedCliente = cliente; + this.NascimentoCliente = new DateTime?(date); + this.HabilitaCliente = new DateTime?(date); + this.VencimentoHabCliente = new DateTime?(date); + this.ExpedicaoCliente = new DateTime?(date); + ObservableCollection observableCollection = new ObservableCollection(); + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Cliente(this.SelectedCliente); + clienteTelefone.set_Tipo(new TipoTelefone?(1)); + clienteTelefone.set_Ordem(new int?(1)); + observableCollection.Add(clienteTelefone); + this.Telefones = observableCollection; + ObservableCollection observableCollection1 = new ObservableCollection(); + ClienteEndereco clienteEndereco = new ClienteEndereco(); + clienteEndereco.set_Cliente(this.SelectedCliente); + clienteEndereco.set_Ordem(new int?(1)); + observableCollection1.Add(clienteEndereco); + this.Enderecos = observableCollection1; + ObservableCollection observableCollection2 = new ObservableCollection(); + ClienteEmail clienteEmail = new ClienteEmail(); + clienteEmail.set_Cliente(this.SelectedCliente); + clienteEmail.set_Ordem(new int?(1)); + observableCollection2.Add(clienteEmail); + this.Emails = observableCollection2; + this.Contatos = new ObservableCollection(); + this.Vinculos = new ObservableCollection(); + this.Origens = new ObservableCollection(); + this.Salvando = true; + base.Alterar(true); + } + + public void IncluirContato() + { + if (this.SelectedCliente == null) + { + return; + } + if (this.Contatos == null) + { + this.Contatos = new ObservableCollection(); + } + MaisContato maisContato = new MaisContato(); + maisContato.set_Cliente(this.SelectedCliente); + MaisContato maisContato1 = maisContato; + this.EnableAddContact = this.Contatos.Count < 9; + this.Contatos.Add(maisContato1); + base.OnPropertyChanged("IncluirContato"); + } + + public void IncluirEmail() + { + if (this.SelectedCliente == null) + { + return; + } + if (this.Emails == null) + { + this.Emails = new ObservableCollection(); + } + this.EnableAddEmail = this.Emails.Count < 9; + ClienteEmail clienteEmail = new ClienteEmail(); + clienteEmail.set_Cliente(this.SelectedCliente); + clienteEmail.set_Ordem(new int?(this.Emails.Count + 1)); + this.Emails.Add(clienteEmail); + base.OnPropertyChanged("IncluirEmail"); + } + + public void IncluirEndereco() + { + if (this.SelectedCliente == null) + { + return; + } + if (this.Enderecos == null) + { + this.Enderecos = new ObservableCollection(); + } + this.EnableAddAddress = this.Enderecos.Count < 9; + ClienteEndereco clienteEndereco = new ClienteEndereco(); + clienteEndereco.set_Cliente(this.SelectedCliente); + clienteEndereco.set_Ordem(new int?(this.Enderecos.Count + 1)); + this.Enderecos.Add(clienteEndereco); + base.OnPropertyChanged("IncluirEndereco"); + } + + public async Task IncluirOrigem(string name) + { + if (this.SelectedCliente != null && !string.IsNullOrWhiteSpace(name)) + { + if (this.Origens == null) + { + this.Origens = new ObservableCollection(); + } + if (!this.Origens.Any((OrigemCliente x) => { + string str; + string nome = x.get_Nome(); + if (nome != null) + { + str = nome.Trim(); + } + else + { + str = null; + } + return str == name.Trim(); + })) + { + ObservableCollection origens = this.Origens; + OrigemCliente origemCliente = new OrigemCliente(); + origemCliente.set_Cliente(this.SelectedCliente); + origemCliente.set_Nome(name); + origemCliente.set_TipoOrigem((long)1); + origens.Insert(0, origemCliente); + base.OnPropertyChanged("Origens"); + } + else + { + await base.ShowMessage(string.Concat("JÁ EXISTE UMA ORIGEM ", name, ". PROCESSO CANCELADO."), "OK", "", false); + } + } + } + + public void IncluirTelefone() + { + if (this.SelectedCliente == null) + { + return; + } + if (this.Telefones == null) + { + this.Telefones = new ObservableCollection(); + } + this.EnableAddTelephone = this.Telefones.Count < 9; + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Cliente(this.SelectedCliente); + clienteTelefone.set_Tipo(new TipoTelefone?(1)); + clienteTelefone.set_Ordem(new int?(this.Telefones.Count + 1)); + this.Telefones.Add(clienteTelefone); + base.OnPropertyChanged("IncluirTelefone"); + } + + public bool IncluirVinculo() + { + if (this.Vinculo == null || this.Vinculo.get_Id() == this.SelectedCliente.get_Id()) + { + return false; + } + if (this.Vinculos == null) + { + this.Vinculos = new ObservableCollection(); + } + if (this.Vinculos.Any((ClienteVinculo x) => { + if (x.get_Cliente1().get_Id() == this.Vinculo.get_Id()) + { + return true; + } + return x.get_Cliente2().get_Id() == this.Vinculo.get_Id(); + })) + { + return false; + } + ClienteVinculo clienteVinculo = new ClienteVinculo(); + clienteVinculo.set_Cliente1(this.SelectedCliente); + clienteVinculo.set_Cliente2(this.Vinculo); + this.Vinculos.Add(clienteVinculo); + this.Vinculo = null; + base.OnPropertyChanged("IncluirVinculo"); + return true; + } + + public void JuridicaouFisica(string documento) + { + if (this.SelectedCliente == null) + { + return; + } + this.ProfissaoText = ""; + this.AtividadeText = ""; + if (documento != null && ValidationHelper.OnlyNumber(documento).Length <= 11) + { + this.VisibilityJuridica = Visibility.Collapsed; + this.VisibilityFisica = Visibility.Visible; + this.FieldNascimento = "NASCIMENTO"; + this.FieldDocumento = "CPF"; + this.SelectedCliente.set_Atividade(null); + this.IsJuridica = false; + return; + } + this.VisibilityJuridica = Visibility.Visible; + this.VisibilityFisica = Visibility.Collapsed; + this.FieldNascimento = "FUNDAÇÃO"; + this.FieldDocumento = "CNPJ"; + this.SelectedCliente.set_Profissao(null); + this.IsJuridica = true; + } + + public async Task>> Salvar() + { + List> keyValuePairs; + long num; + long? nullable; + List list; + List clienteVinculos; + ObservableCollection observableCollection; + ObservableCollection observableCollection1; + List origemClientes; + bool id; + bool salvando; + long? nullable1; + long? nullable2; + ClienteViewModel.u003cu003ec__DisplayClass146_0 variable; + Cliente selectedCliente; + Func func = null; + ObservableCollection telefones = this.Telefones; + List clienteTelefones = ( + from x in telefones + where !string.IsNullOrEmpty(x.get_Numero()) + select x).ToList(); + ObservableCollection enderecos = this.Enderecos; + List clienteEnderecos = ( + from x in enderecos + where !string.IsNullOrEmpty(x.get_Endereco()) + select x).ToList(); + ObservableCollection contatos = this.Contatos; + if (contatos != null) + { + list = ( + from x in contatos + where !string.IsNullOrEmpty(x.get_Nome()) + select x).ToList(); + } + else + { + list = null; + } + List maisContatos = list; + ObservableCollection emails = this.Emails; + List clienteEmails = ( + from x in emails + where !string.IsNullOrEmpty(x.get_Email()) + select x).ToList(); + ObservableCollection vinculos = this.Vinculos; + if (vinculos != null) + { + clienteVinculos = vinculos.Where((ClienteVinculo x) => { + if (x.get_Cliente2() == null) + { + return false; + } + return x.get_Parentesco().HasValue; + }).ToList(); + } + else + { + clienteVinculos = null; + } + List clienteVinculos1 = clienteVinculos; + if (clienteVinculos1 != null && this.ClienteSelecionado != null) + { + List clienteVinculos2 = clienteVinculos1; + Func func1 = func; + if (func1 == null) + { + Func id1 = (ClienteVinculo c) => c.get_Cliente2().get_Id() == this.ClienteSelecionado.get_Id(); + Func func2 = id1; + func = id1; + func1 = func2; + } + foreach (ClienteVinculo clienteVinculo in clienteVinculos2.Where(func1)) + { + clienteVinculo.set_Parentesco(Funcoes.ParentescoInverso(clienteVinculo.get_Parentesco())); + } + } + this.SelectedCliente.set_Telefones(new ObservableCollection(clienteTelefones)); + this.SelectedCliente.set_Enderecos(new ObservableCollection(clienteEnderecos)); + Cliente cliente = this.SelectedCliente; + if (maisContatos != null) + { + observableCollection = new ObservableCollection(maisContatos); + } + else + { + observableCollection = null; + } + cliente.set_Contatos(observableCollection); + this.SelectedCliente.set_Emails(new ObservableCollection(clienteEmails)); + Cliente selectedCliente1 = this.SelectedCliente; + if (clienteVinculos1 != null) + { + observableCollection1 = new ObservableCollection(clienteVinculos1); + } + else + { + observableCollection1 = null; + } + selectedCliente1.set_Vinculos(observableCollection1); + Cliente cliente1 = this.SelectedCliente; + ObservableCollection origens = this.Origens; + if (origens != null) + { + origemClientes = origens.ToList(); + } + else + { + origemClientes = null; + } + cliente1.set_Origens(origemClientes); + if (ValidationHelper.OnlyNumber(this.SelectedCliente.get_Documento()).Length <= 11 && !string.IsNullOrWhiteSpace(this.ProfissaoText) && this.SelectedCliente.get_Profissao() == null) + { + ProfissaoServico profissaoServico = new ProfissaoServico(); + selectedCliente = this.SelectedCliente; + ProfissaoServico profissaoServico1 = profissaoServico; + Profissao profissao = new Profissao(); + profissao.set_Nome(this.ProfissaoText); + profissao.set_Codigo("0"); + Profissao profissao1 = profissao; + num = await profissaoServico.FindLastId(); + profissao1.set_Id(num + (long)1); + Profissao profissao2 = await profissaoServico1.Save(profissao); + profissaoServico1 = null; + profissao1 = null; + profissao = null; + selectedCliente.set_Profissao(profissao2); + selectedCliente = null; + if (profissaoServico.Sucesso) + { + profissaoServico = null; + } + else + { + keyValuePairs = null; + variable = null; + clienteEmails = null; + return keyValuePairs; + } + } + if (ValidationHelper.OnlyNumber(this.SelectedCliente.get_Documento()).Length > 11 && !string.IsNullOrWhiteSpace(this.AtividadeText) && this.SelectedCliente.get_Atividade() == null) + { + AtividadeServico atividadeServico = new AtividadeServico(); + selectedCliente = this.SelectedCliente; + AtividadeServico atividadeServico1 = atividadeServico; + Atividade atividade = new Atividade(); + atividade.set_Nome(this.AtividadeText); + atividade.set_Cnac("0"); + Atividade atividade1 = atividade; + num = await atividadeServico.FindLastId(); + atividade1.set_Id(num + (long)1); + Atividade atividade2 = await atividadeServico1.Save(atividade); + atividadeServico1 = null; + atividade1 = null; + atividade = null; + selectedCliente.set_Atividade(atividade2); + selectedCliente = null; + if (atividadeServico.Sucesso) + { + atividadeServico = null; + } + else + { + keyValuePairs = null; + variable = null; + clienteEmails = null; + return keyValuePairs; + } + } + if (this.IsJuridica) + { + this.SelectedCliente.set_Cei(null); + this.SelectedCliente.set_Rne(null); + this.SelectedCliente.set_Caepf(null); + } + List> keyValuePairs1 = this.SelectedCliente.Validate(); + clienteEmails.ForEach((ClienteEmail x) => keyValuePairs1.AddRange(x.Validate())); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + foreach (MaisContato contato in this.Contatos) + { + keyValuePairs1.AddRange(contato.Validate()); + } + foreach (ClienteVinculo vinculo in this.Vinculos) + { + keyValuePairs1.AddRange(vinculo.Validate()); + } + if (keyValuePairs1.Count <= 0) + { + bool flag = this.SelectedCliente.get_Id() == (long)0; + this._saving = true; + Cliente clienteSelecionado = this.ClienteSelecionado; + if (clienteSelecionado != null) + { + id = clienteSelecionado.get_Id() != (long)0; + } + else + { + id = true; + } + if (id) + { + Cliente clienteSelecionado1 = this.ClienteSelecionado; + if (clienteSelecionado1 != null) + { + nullable1 = new long?(clienteSelecionado1.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + long? nullable3 = nullable1; + Cliente selectedCliente2 = this.SelectedCliente; + if (selectedCliente2 != null) + { + nullable2 = new long?(selectedCliente2.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + long? nullable4 = nullable2; + if (nullable3.GetValueOrDefault() != nullable4.GetValueOrDefault() | nullable3.HasValue != nullable4.HasValue) + { + goto Label2; + } + salvando = this.Salvando; + goto Label1; + } + Label2: + salvando = false; + Label1: + bool flag1 = salvando; + if (flag1) + { + flag1 = await base.ShowMessage("NÃO FOI POSSIVEL INCLUIR UM NOVO SEGURADO, TENTE NOVAMENTE", "OK", "", false); + } + if (!flag1) + { + this.SelectedCliente = await this._servico.Save(this.SelectedCliente, this.Salvando); + if (this._servico.Sucesso) + { + if (this.Invoke) + { + Action selectCliente = Gestor.Application.Actions.Actions.SelectCliente; + if (selectCliente != null) + { + selectCliente(this.SelectedCliente); + } + else + { + } + } + await this.CarregaCliente(this.SelectedCliente); + string str = (flag ? "INCLUIU" : "ALTEROU"); + base.RegistrarAcao(string.Concat(str, " CLIENTE \"", this.SelectedCliente.get_Nome(), "\""), this.SelectedCliente.get_Id(), new TipoTela?(1), string.Format("CLIENTE \"{0}\", ID: {1}", this.SelectedCliente.get_Nome(), this.SelectedCliente.get_Id())); + base.ToggleSnackBar("CLIENTE SALVO COM SUCESSO", true); + if (this.Invoke) + { + ConsultaViewModel.DocumentoSelecionado = null; + Action atualizaContatos = Gestor.Application.Actions.Actions.AtualizaContatos; + if (atualizaContatos != null) + { + atualizaContatos(); + } + else + { + } + if (flag) + { + MainViewModel.ClienteSelecionado = this.SelectedCliente; + if (await base.ShowMessage("DESEJA INCLUIR UMA APÓLICE AGORA?", "SIM", "NÃO", false)) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(2, ""); + } + else + { + } + } + } + } + this.Salvando = false; + base.Alterar(false); + this._saving = false; + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + variable = null; + clienteEmails = null; + return keyValuePairs; + } + + public async void SelecionaCliente(Cliente value) + { + if (!this._saving || !this.Invoke) + { + if (value == null) + { + this.ClienteSelecionado = new Cliente(); + value = this.ClienteSelecionado; + } + base.Loading(true); + await base.PermissaoTela(1); + await this.CarregaCliente(value); + base.Loading(false); + } + } + + public async Task Validate(ClienteEmail item) + { + bool flag; + if (!ValidationHelper.ValidateMail(item.get_Email())) + { + await base.ShowMessage("ENDEREÇO DE E-MAIL INVÁLIDO", "OK", "", false); + flag = false; + } + else + { + flag = true; + } + return flag; + } + + private async Task>> Validate() + { + List clientes; + long id; + List> keyValuePairs = new List>(); + bool flag = !string.IsNullOrEmpty(this.SelectedCliente.get_Nome()); + TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + switch (documentoPrincipal.GetValueOrDefault()) + { + case 0: + { + if (ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) + { + break; + } + flag = false; + break; + } + case 1: + { + if (ValidationHelper.ValidateRne(this.SelectedCliente.get_Rne())) + { + break; + } + flag = false; + break; + } + case 2: + { + if (ValidationHelper.ValidateCei(this.SelectedCliente.get_Cei())) + { + break; + } + flag = false; + break; + } + case 3: + { + if (ValidationHelper.ValidateCaepf(this.SelectedCliente.get_Caepf())) + { + break; + } + flag = false; + break; + } + } + } + if (ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) + { + documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.GetValueOrDefault() == 0 & documentoPrincipal.HasValue) + { + this.SelectedCliente.set_Documento(ValidationHelper.FormatDocument(this.SelectedCliente.get_Documento())); + } + } + if (!ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) + { + clientes = new List(); + } + else + { + clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Documento(), null, 2); + } + List clientes1 = clientes; + if (!this.IsJuridica) + { + if (!ValidationHelper.ValidateCei(this.SelectedCliente.get_Cei())) + { + clientes = new List(); + } + else + { + clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Cei(), null, 2); + } + List clientes2 = clientes; + if (!ValidationHelper.ValidateRne(this.SelectedCliente.get_Rne())) + { + clientes = new List(); + } + else + { + clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Rne(), null, 2); + } + List clientes3 = clientes; + if (!ValidationHelper.ValidateCaepf(this.SelectedCliente.get_Caepf())) + { + clientes = new List(); + } + else + { + clientes = await (new ClienteServico()).BuscarCliente(this.SelectedCliente.get_Caepf(), null, 2); + } + List clientes4 = clientes; + List clientes5 = clientes1; + List clientes6 = clientes2; + if (clientes6 == null) + { + clientes6 = new List(); + } + clientes5.AddRange(clientes6); + List clientes7 = clientes1; + List clientes8 = clientes3; + if (clientes8 == null) + { + clientes8 = new List(); + } + clientes7.AddRange(clientes8); + List clientes9 = clientes1; + List clientes10 = clientes4; + if (clientes10 == null) + { + clientes10 = new List(); + } + clientes9.AddRange(clientes10); + clientes2 = null; + clientes3 = null; + } + string nome = ""; + string str = ""; + if (clientes1.Count > 0) + { + clientes1.ForEach((Cliente x) => { + if (x.get_Id() == this.SelectedCliente.get_Id()) + { + return; + } + if (x.get_IdEmpresa() != this.SelectedCliente.get_IdEmpresa()) + { + return; + } + if (!string.IsNullOrEmpty(this.SelectedCliente.get_Documento()) && x.get_Documento() == this.SelectedCliente.get_Documento()) + { + flag = false; + nome = x.get_Nome(); + } + if (!string.IsNullOrEmpty(this.SelectedCliente.get_Cei()) && x.get_Cei() == this.SelectedCliente.get_Cei()) + { + str = " (CEI)"; + flag = false; + nome = x.get_Nome(); + } + if (!string.IsNullOrEmpty(this.SelectedCliente.get_Rne()) && x.get_Rne() == this.SelectedCliente.get_Rne()) + { + str = " (RNE)"; + flag = false; + nome = x.get_Nome(); + } + if (!string.IsNullOrEmpty(this.SelectedCliente.get_Caepf()) && x.get_Caepf() == this.SelectedCliente.get_Caepf()) + { + str = " (CAEPF)"; + flag = false; + nome = x.get_Nome(); + } + }); + } + if (!flag && clientes1.Count((Cliente x) => x.get_Id() != this.SelectedCliente.get_Id()) > 0) + { + if (await (new VendedorUsuarioServico()).FindVinculoByUsuario(Recursos.Usuario.get_Id())) + { + Cliente cliente = clientes1.FirstOrDefault(); + if (cliente != null) + { + id = cliente.get_Id(); + } + else + { + id = (long)0; + } + List vendedors = await (new VendedorServico()).BuscarVinculosCliente(id); + string str1 = string.Join("|", + from vendedor in vendedors + select vendedor.get_Nome()); + List> keyValuePairs1 = keyValuePairs; + string[] strArrays = new string[] { "O DOCUMENTO", str, " JÁ ESTÁ CADASTRADO PARA O CLIENTE ", nome, ".\nEXISTENTE NO VINCULO COM VENDEDORES: ", str1, " " }; + keyValuePairs1.Add(new KeyValuePair("Documento", string.Concat(strArrays))); + } + else + { + keyValuePairs.Add(new KeyValuePair("Documento", string.Concat("O DOCUMENTO", str, " JÁ ESTÁ CADASTRADO PARA O CLIENTE ", nome))); + } + } + if (this.SelectedCliente.get_Telefones() == null || this.SelectedCliente.get_Telefones().Count == 0) + { + keyValuePairs.Add(new KeyValuePair("Telefones", "NECESSITA-SE AO MENOS UM TELEFONE VÁLIDO.")); + } + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 29) && (this.SelectedCliente.get_Emails() == null || this.SelectedCliente.get_Emails().Count == 0)) + { + keyValuePairs.Add(new KeyValuePair("Emails|E-MAILS", "NECESSITA-SE AO MENOS UM E-MAIL VÁLIDO.")); + } + if (this.SelectedCliente.get_Enderecos() == null || this.SelectedCliente.get_Enderecos().Count == 0) + { + keyValuePairs.Add(new KeyValuePair("Enderecos|ENDEREÇOS", "NECESSITA-SE AO MENOS UM ENDEREÇO VÁLIDO.")); + } + List> keyValuePairs2 = keyValuePairs; + keyValuePairs = null; + clientes1 = null; + return keyValuePairs2; + } + + private async void WorkOnSelectedCliente(Cliente value) + { + DateTime networkTime; + DateTime? nullable; + DateTime? primeiraHabilitacao; + DateTime? vencimentoHabilitacao; + DateTime? expedicao; + Cliente cliente; + if (value != null && value.get_Id() != 0 && !this.IsLoading) + { + base.Loading(true); + cliente = await this._servico.BuscarCliente(value.get_Id()); + if (cliente.get_ResponsavelAssinatura() == null) + { + Cliente cliente1 = cliente; + ResponsavelAssinatura responsavelAssinatura = new ResponsavelAssinatura(); + responsavelAssinatura.set_IdCliente(cliente.get_Id()); + cliente1.set_ResponsavelAssinatura(responsavelAssinatura); + } + Cliente cliente2 = cliente; + ObservableCollection observableCollection = await this._servico.BuscarTelefonesAsync(value.get_Id()); + cliente2.set_Telefones(observableCollection); + cliente2 = null; + cliente2 = cliente; + ObservableCollection observableCollection1 = await this._servico.BuscarEmailsAsync(value.get_Id()); + cliente2.set_Emails(observableCollection1); + cliente2 = null; + cliente2 = cliente; + ObservableCollection observableCollection2 = await this._servico.BuscarEnderecosAsync(value.get_Id()); + cliente2.set_Enderecos(observableCollection2); + cliente2 = null; + cliente2 = cliente; + ObservableCollection observableCollection3 = await this._servico.BuscarContatosAsync(value.get_Id()); + cliente2.set_Contatos(observableCollection3); + cliente2 = null; + cliente2 = cliente; + ObservableCollection observableCollection4 = await this._servico.BuscarVinculosAsync(value.get_Id()); + cliente2.set_Vinculos(observableCollection4); + cliente2 = null; + this.Origens = await this._servico.BuscarOrigens(value.get_Id()); + Cliente cliente3 = cliente; + TipoDocumento? documentoPrincipal = cliente.get_DocumentoPrincipal(); + cliente3.set_DocumentoPrincipal(new TipoDocumento?(documentoPrincipal.GetValueOrDefault())); + this.ClienteExcluido = cliente.get_Excluido(); + if (this.SelectedCliente != null) + { + DomainBase.Copy(this.SelectedCliente, cliente); + this.JuridicaouFisica(this.SelectedCliente.get_Documento()); + this.SelectedCliente.Initialize(); + this.ClienteSelecionado = cliente; + } + ClienteViewModel clienteViewModel = this; + if (value == null || !value.get_Nascimento().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + nullable = new DateTime?(networkTime.Date); + } + else + { + nullable = value.get_Nascimento(); + } + clienteViewModel.NascimentoCliente = nullable; + ClienteViewModel clienteViewModel1 = this; + if (value == null || !value.get_PrimeiraHabilitacao().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + primeiraHabilitacao = new DateTime?(networkTime.Date); + } + else + { + primeiraHabilitacao = value.get_PrimeiraHabilitacao(); + } + clienteViewModel1.HabilitaCliente = primeiraHabilitacao; + ClienteViewModel clienteViewModel2 = this; + if (value == null || !value.get_VencimentoHabilitacao().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + vencimentoHabilitacao = new DateTime?(networkTime.Date); + } + else + { + vencimentoHabilitacao = value.get_VencimentoHabilitacao(); + } + clienteViewModel2.VencimentoHabCliente = vencimentoHabilitacao; + ClienteViewModel clienteViewModel3 = this; + if (value == null || !value.get_Expedicao().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + expedicao = new DateTime?(networkTime.Date); + } + else + { + expedicao = value.get_Expedicao(); + } + clienteViewModel3.ExpedicaoCliente = expedicao; + this.Initialized = true; + base.Loading(false); + } + cliente = null; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/ConsultaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/ConsultaViewModel.cs new file mode 100644 index 0000000..ad65045 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/ConsultaViewModel.cs @@ -0,0 +1,2425 @@ +using Assinador.Infrastructure.Helpers; +using ClosedXML.Excel; +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Model; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; +using System.Windows.Threading; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class ConsultaViewModel : BaseSegurosViewModel + { + private readonly ApoliceServico _apoliceServico; + + private readonly ParcelaServico _parcelaServico; + + private readonly ItemServico _itemServico; + + private readonly VendedorServico _vendedorServico; + + public bool UpdatingScroll; + + public static Parcela ParcelaSelecionada; + + public static Item ItemSelecionado; + + private static Documento _documentoSelecionado; + + private bool _apelido; + + private Visibility _semDocumentos = Visibility.Collapsed; + + private Cliente _selectedCliente = new Cliente(); + + private bool _carregando; + + private bool _isLoading; + + private Visibility _visibilityParcelasVendedores; + + private ObservableCollection _apolices = new ObservableCollection(); + + private ObservableCollection _endossos = new ObservableCollection(); + + private Documento _selectedEndosso = new Documento(); + + private string _parcelasLabel = "PARCELAS"; + + private Documento _selectedControle = new Documento(); + + private bool _isFatura; + + private bool _isEnabledParcelaItem = true; + + private Item _selectedItem = new Item(); + + private ObservableCollection _itens = new ObservableCollection(); + + private Parcela _selectedParcela = new Parcela(); + + private ObservableCollection _parcelas = new ObservableCollection(); + + private Visibility _isVisibleRadioEndosso = Visibility.Collapsed; + + private Visibility _isVisibleEndosso = Visibility.Collapsed; + + private Visibility _isVisibleApolice; + + private string _pendenciaApolice = ""; + + private Visibility _isVisiblePendenciaApolice = Visibility.Collapsed; + + private decimal _gerada; + + private decimal _recebida; + + private decimal _pendente; + + private bool _isLoadingParcelas = true; + + private bool _isLoadingItens = true; + + private int _filterItens; + + private int _filterDocumento; + + private Visibility _manutencaoItemVisibility; + + private Visibility _recusaVisibility; + + private Visibility _renovarVisibility; + + private Visibility _endossarVisibility; + + private Visibility _trocarClienteVisibility; + + private Visibility _tarefasVisibility; + + private Visibility _comissaoVisibility; + + private Visibility _comissaoValorVisibility; + + private Visibility _mostrarItensVisibility = Visibility.Collapsed; + + private Visibility _mostrarSinistroVisibility; + + private ObservableCollection _telefones = new ObservableCollection(); + + public bool Apelido + { + get + { + return this._apelido; + } + set + { + this._apelido = value; + base.OnPropertyChanged("Apelido"); + } + } + + public ObservableCollection Apolices + { + get + { + return this._apolices; + } + set + { + this._apolices = value; + base.OnPropertyChanged("Apolices"); + } + } + + public bool Carregando + { + get + { + return this._carregando; + } + set + { + this._carregando = value; + this.SemDocumentos = (value || this.Apolices != null && this.Apolices.Count != 0 ? Visibility.Collapsed : Visibility.Visible); + } + } + + public Visibility ComissaoValorVisibility + { + get + { + return this._comissaoValorVisibility; + } + set + { + this._comissaoValorVisibility = (!base.Restricao(14) ? value : Visibility.Collapsed); + base.OnPropertyChanged("ComissaoValorVisibility"); + } + } + + public Visibility ComissaoVisibility + { + get + { + return this._comissaoVisibility; + } + set + { + this._comissaoVisibility = (!base.Restricao(95) ? value : Visibility.Collapsed); + base.OnPropertyChanged("ComissaoVisibility"); + } + } + + public static Documento DocumentoRenovado + { + get; + set; + } + + public static Documento DocumentoSelecionado + { + get + { + return ConsultaViewModel._documentoSelecionado; + } + set + { + ConsultaViewModel._documentoSelecionado = value; + Action enableItens = Gestor.Application.Actions.Actions.EnableItens; + if (enableItens != null) + { + enableItens((value == null ? false : value.get_Id() > (long)0)); + } + else + { + } + Action enableDocumento = Gestor.Application.Actions.Actions.EnableDocumento; + if (enableDocumento == null) + { + return; + } + enableDocumento((value == null ? false : value.get_Id() > (long)0)); + } + } + + public Visibility EndossarVisibility + { + get + { + return this._endossarVisibility; + } + set + { + this._endossarVisibility = (!base.Restricao(33) ? value : Visibility.Collapsed); + base.OnPropertyChanged("EndossarVisibility"); + } + } + + public ObservableCollection Endossos + { + get + { + return this._endossos; + } + set + { + this._endossos = value; + base.OnPropertyChanged("Endossos"); + } + } + + public int FilterDocumento + { + get + { + return this._filterDocumento; + } + set + { + this._filterDocumento = value; + Action updateRadioApolice = Gestor.Application.Actions.Actions.UpdateRadioApolice; + if (updateRadioApolice != null) + { + updateRadioApolice(this._filterDocumento); + } + else + { + } + base.OnPropertyChanged("FilterDocumento"); + } + } + + public int FilterItens + { + get + { + return this._filterItens; + } + set + { + this._filterItens = value; + ConsultaViewModel.FiltrarItens = value; + base.OnPropertyChanged("FilterItens"); + } + } + + public static int FiltrarItens + { + get; + set; + } + + public decimal Gerada + { + get + { + return this._gerada; + } + set + { + this._gerada = value; + base.OnPropertyChanged("Gerada"); + } + } + + public bool IsEnabledParcelaItem + { + get + { + return this._isEnabledParcelaItem; + } + set + { + this._isEnabledParcelaItem = value; + base.OnPropertyChanged("IsEnabledParcelaItem"); + } + } + + public bool IsFatura + { + get + { + return this._isFatura; + } + set + { + if (!value) + { + value = this.ComissaoValorVisibility == Visibility.Collapsed; + } + this._isFatura = value; + base.OnPropertyChanged("IsFatura"); + } + } + + public bool IsLoading + { + get + { + return this._isLoading; + } + set + { + this._isLoading = value; + base.OnPropertyChanged("IsLoading"); + } + } + + public bool IsLoadingItens + { + get + { + return this._isLoadingItens; + } + set + { + this._isLoadingItens = value; + base.OnPropertyChanged("IsLoadingItens"); + } + } + + public bool IsLoadingParcelas + { + get + { + return this._isLoadingParcelas; + } + set + { + this._isLoadingParcelas = value; + base.OnPropertyChanged("IsLoadingParcelas"); + } + } + + public Visibility IsVisibleApolice + { + get + { + return this._isVisibleApolice; + } + set + { + this._isVisibleApolice = value; + base.OnPropertyChanged("IsVisibleApolice"); + } + } + + public Visibility IsVisibleEndosso + { + get + { + return this._isVisibleEndosso; + } + set + { + this._isVisibleEndosso = value; + base.OnPropertyChanged("IsVisibleEndosso"); + } + } + + public Visibility IsVisiblePendenciaApolice + { + get + { + return this._isVisiblePendenciaApolice; + } + set + { + this._isVisiblePendenciaApolice = value; + base.OnPropertyChanged("IsVisiblePendenciaApolice"); + } + } + + public Visibility IsVisibleRadioEndosso + { + get + { + return this._isVisibleRadioEndosso; + } + set + { + this._isVisibleRadioEndosso = value; + base.OnPropertyChanged("IsVisibleRadioEndosso"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public bool ItensRevelados + { + get; + set; + } + + public Visibility ManutencaoItemVisibility + { + get + { + return this._manutencaoItemVisibility; + } + set + { + this._manutencaoItemVisibility = (!base.Restricao(22) ? value : Visibility.Collapsed); + base.OnPropertyChanged("ManutencaoItemVisibility"); + } + } + + public Visibility MostrarItensVisibility + { + get + { + return this._mostrarItensVisibility; + } + set + { + this._mostrarItensVisibility = value; + base.OnPropertyChanged("MostrarItensVisibility"); + } + } + + public Visibility MostrarSinistroVisibility + { + get + { + return this._mostrarSinistroVisibility; + } + set + { + this._mostrarSinistroVisibility = value; + base.OnPropertyChanged("MostrarSinistroVisibility"); + } + } + + public ObservableCollection Parcelas + { + get + { + return this._parcelas; + } + set + { + this._parcelas = value; + base.OnPropertyChanged("Parcelas"); + } + } + + public string ParcelasLabel + { + get + { + return this._parcelasLabel; + } + set + { + this._parcelasLabel = value; + base.OnPropertyChanged("ParcelasLabel"); + } + } + + public string PendenciaApolice + { + get + { + return this._pendenciaApolice; + } + set + { + this._pendenciaApolice = value; + this.IsVisiblePendenciaApolice = (string.IsNullOrEmpty(this._pendenciaApolice) ? Visibility.Collapsed : Visibility.Visible); + base.OnPropertyChanged("PendenciaApolice"); + } + } + + public decimal Pendente + { + get + { + return this._pendente; + } + set + { + this._pendente = value; + base.OnPropertyChanged("Pendente"); + } + } + + public bool Pesquisando + { + get; + set; + } + + public bool Recarregando + { + get; + set; + } + + public decimal Recebida + { + get + { + return this._recebida; + } + set + { + this._recebida = value; + base.OnPropertyChanged("Recebida"); + } + } + + public Visibility RecusaVisibility + { + get + { + return this._recusaVisibility; + } + set + { + this._recusaVisibility = (!base.Restricao(18) ? value : Visibility.Collapsed); + base.OnPropertyChanged("RecusaVisibility"); + } + } + + public Visibility RenovarVisibility + { + get + { + return this._renovarVisibility; + } + set + { + this._renovarVisibility = (!base.Restricao(17) ? value : Visibility.Collapsed); + base.OnPropertyChanged("RenovarVisibility"); + } + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public Documento SelectedControle + { + get + { + return this._selectedControle; + } + set + { + bool id; + bool flag; + Visibility visibility; + string apolice; + this._selectedControle = value; + if (value == null || value.get_Id() <= (long)0) + { + id = false; + } + else + { + Usuario usuario = Recursos.Usuario; + if (usuario != null) + { + id = usuario.get_Id() > (long)0; + } + else + { + id = false; + } + } + base.EnableButtons = id; + bool flag1 = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 13); + if (value == null || value.get_Id() <= (long)0) + { + flag = false; + } + else if (flag1) + { + flag = true; + } + else + { + flag = (string.IsNullOrWhiteSpace(value.get_Apolice()) || string.IsNullOrWhiteSpace(value.get_Proposta()) ? false : value.get_Emissao().HasValue); + } + base.EnableEndossar = flag; + base.EnableRenovar = (value == null || value.get_Id() <= (long)0 || !value.get_Vigencia2().HasValue ? false : !string.IsNullOrWhiteSpace(value.get_Apolice())); + this.WorkOnSelectedDocumento(value); + if (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 19)) + { + if (value != null) + { + apolice = value.get_Apolice(); + } + else + { + apolice = null; + } + if (string.IsNullOrWhiteSpace(apolice) || !value.get_Emissao().HasValue) + { + visibility = Visibility.Visible; + this.RecusaVisibility = visibility; + this.ItensRevelados = false; + this.MostrarItensVisibility = Visibility.Collapsed; + this.MostrarSinistroVisibility = Visibility.Visible; + base.OnPropertyChanged("SelectedControle"); + return; + } + visibility = Visibility.Collapsed; + this.RecusaVisibility = visibility; + this.ItensRevelados = false; + this.MostrarItensVisibility = Visibility.Collapsed; + this.MostrarSinistroVisibility = Visibility.Visible; + base.OnPropertyChanged("SelectedControle"); + return; + } + visibility = Visibility.Visible; + this.RecusaVisibility = visibility; + this.ItensRevelados = false; + this.MostrarItensVisibility = Visibility.Collapsed; + this.MostrarSinistroVisibility = Visibility.Visible; + base.OnPropertyChanged("SelectedControle"); + } + } + + public Documento SelectedEndosso + { + get + { + return this._selectedEndosso; + } + set + { + this._selectedEndosso = value; + this.WorkOnSelectedDocumento(value); + base.OnPropertyChanged("SelectedEndosso"); + } + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + this._selectedItem = value; + ConsultaViewModel.WorkOnSelectedItem(value); + base.OnPropertyChanged("SelectedItem"); + } + } + + public Parcela SelectedParcela + { + get + { + return this._selectedParcela; + } + set + { + this._selectedParcela = value; + base.OnPropertyChanged("SelectedParcela"); + } + } + + public Visibility SemDocumentos + { + get + { + return this._semDocumentos; + } + set + { + this._semDocumentos = value; + base.OnPropertyChanged("SemDocumentos"); + } + } + + public Visibility TarefasVisibility + { + get + { + return this._tarefasVisibility; + } + set + { + this._tarefasVisibility = (base.Permissao(38) ? value : Visibility.Collapsed); + base.OnPropertyChanged("TarefasVisibility"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public Visibility TrocarClienteVisibility + { + get + { + return this._trocarClienteVisibility; + } + set + { + this._trocarClienteVisibility = (!base.Restricao(21) ? value : Visibility.Collapsed); + base.OnPropertyChanged("TrocarClienteVisibility"); + } + } + + public Visibility VisibilityParcelasVendedores + { + get + { + return this._visibilityParcelasVendedores; + } + set + { + this._visibilityParcelasVendedores = value; + base.OnPropertyChanged("VisibilityParcelasVendedores"); + } + } + + public ConsultaViewModel() + { + this._apoliceServico = new ApoliceServico(); + this._parcelaServico = new ParcelaServico(); + this._vendedorServico = new VendedorServico(); + this._itemServico = new ItemServico(); + this.Apelido = Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 6); + this.SemDocumentos = Visibility.Visible; + base.EnableButtons = false; + if (MainViewModel.ClienteSelecionado != null && MainViewModel.ClienteSelecionado.get_Id() > (long)0) + { + this.SelecionarCliente(MainViewModel.ClienteSelecionado); + } + } + + public async Task AbrirDetalhes() + { + Documento selectedControle = this.SelectedControle; + if (this.FilterDocumento == 1) + { + Documento selectedEndosso = this.SelectedEndosso; + if (selectedEndosso == null) + { + selectedEndosso = this.SelectedControle; + } + selectedControle = selectedEndosso; + } + Documento documento = selectedControle; + List vendedorParcelas = await this._vendedorServico.BuscaRepasse(selectedControle.get_Id()); + documento.set_Pagamentos(vendedorParcelas); + documento = null; + documento = selectedControle; + ObservableCollection observableCollection = await this._parcelaServico.BuscarParcelasAsync(selectedControle.get_Id()); + documento.set_Parcelas(observableCollection); + documento = null; + Documento documento1 = selectedControle; + selectedControle = null; + return documento1; + } + + public async Task AbrirDetalhesParcela() + { + Parcela selectedParcela = this.SelectedParcela; + List vendedorParcelas = await this._vendedorServico.BuscaRepasseParcela(selectedParcela.get_Id()); + selectedParcela.set_Vendedores(new ObservableCollection(vendedorParcelas)); + Parcela parcela = selectedParcela; + selectedParcela = null; + return parcela; + } + + private void CalculaComissao(Documento documento, ObservableCollection parcelas) + { + decimal num = (documento.get_AdicionalComiss() ? documento.get_PremioLiquido() + documento.get_PremioAdicional() : documento.get_PremioLiquido()); + decimal comissao = documento.get_Comissao() * new decimal(1, 0, 0, false, 2); + this.Gerada = num * comissao; + this.Recebida = (Recursos.Configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 32) ? parcelas.Where((Parcela x) => { + if (x.get_SubTipo() == 1) + { + return true; + } + return x.get_SubTipo() == 6; + }).Sum((Parcela x) => x.get_ValorComissao()) : ( + from x in parcelas + where x.get_SubTipo() == 1 + select x).Sum((Parcela x) => x.get_ValorComissao())); + this.Pendente = this.Gerada - this.Recebida; + this.Pendente = (this.Pendente < new decimal(1, 0, 0, false, 2) ? new decimal(0, 0, 0, false, 2) : this.Pendente); + } + + public void CarregaDocumentos(int type) + { + this.IsVisibleApolice = Visibility.Collapsed; + this.IsVisibleEndosso = Visibility.Collapsed; + if (type != 1) + { + this.IsVisibleApolice = Visibility.Visible; + return; + } + this.IsVisibleEndosso = Visibility.Visible; + } + + public async Task CarregaItens(int type, Documento documento) + { + this.FilterItens = 0; + switch (type) + { + case 0: + { + this.Itens = await this._itemServico.BuscarItens(documento.get_Controle().get_Id(), 0); + break; + } + case 1: + { + this.FilterItens = 1; + this.Itens = await this._itemServico.BuscarItens(documento.get_Id(), 2); + break; + } + case 2: + { + this.FilterItens = 2; + Documento selectedEndosso = this.SelectedEndosso; + if (selectedEndosso == null) + { + selectedEndosso = documento; + } + documento = selectedEndosso; + this.Itens = await this._itemServico.BuscarItens(documento.get_Id(), 2); + break; + } + case 3: + { + this.FilterItens = 3; + this.Itens = await this._itemServico.BuscarItens(documento.get_Controle().get_Id(), 1); + break; + } + } + } + + private void Clear() + { + this.Apolices = null; + this.Parcelas = null; + this.Itens = null; + } + + public async Task CreateLink(Documento documento) + { + string str; + string descricao; + if (documento == null || this.SelectedCliente == null) + { + str = ""; + } + else + { + this.Telefones = new ObservableCollection((IEnumerable)await (new ClienteServico()).BuscarTelefonesAsync(this.SelectedCliente.get_Id())); + if (this.Itens == null) + { + descricao = ""; + } + else if (this.Itens.Count > 1) + { + descricao = "APÓLICE COLETIVA"; + } + else + { + Item item = this.Itens.FirstOrDefault(); + if (item != null) + { + descricao = item.get_Descricao(); + } + else + { + descricao = null; + } + } + str = await base.CreateLinkAssistencia(documento, descricao, true); + } + return str; + } + + public async Task EditarParcelas() + { + await base.ShowEditarParcelasDialog(ConsultaViewModel.DocumentoSelecionado); + await this.SelecionaParcelas(ConsultaViewModel.DocumentoSelecionado); + } + + public async Task GerarExcel(int type) + { + ObservableCollection observableCollection; + string str1; + ConsultaViewModel.u003cu003ec__DisplayClass212_0 variable; + string str2; + string str3; + if (this.SelectedControle != null) + { + base.Loading(true); + bool typeFromProgID = Type.GetTypeFromProgID("Excel.Application") != null; + str2 = "ATIVOS"; + switch (type) + { + case 1: + { + str2 = "DA APÓLICE"; + observableCollection = await this._itemServico.BuscarItems(this.SelectedControle.get_Id(), 2, true); + break; + } + case 2: + { + Documento selectedEndosso = this.SelectedEndosso; + if (selectedEndosso == null) + { + selectedEndosso = this.SelectedControle; + } + Documento documento = selectedEndosso; + str2 = (this.SelectedEndosso == null ? "DA APÓLICE" : "DO ENDOSSO"); + observableCollection = await this._itemServico.BuscarItems(documento.get_Id(), 2, true); + break; + } + case 3: + { + str2 = "INATIVOS"; + observableCollection = await this._itemServico.BuscarItems(this.SelectedControle.get_Controle().get_Id(), 1, true); + break; + } + default: + { + observableCollection = await this._itemServico.BuscarItems(this.SelectedControle.get_Controle().get_Id(), 0, true); + break; + } + } + if (observableCollection == null || observableCollection.Count == 0) + { + base.Loading(false); + await base.ShowMessage("NÃO HÁ ITENS PARA EXIBIR A RELAÇÃO", "OK", "", false); + } + else + { + List relacaoItens = new List(); + observableCollection.ToList().ForEach((Item x) => { + DateTime? nullable; + StatusSinistro? nullable1; + decimal? nullable2; + DateTime? dataSinistro; + string numero; + StatusSinistro? statusSinistro; + string itemSinistrado; + decimal? nullable3; + DateTime? dataLiquidacao; + DateTime? dataReclamacao; + string motivo; + string descricao; + string str = ""; + if (x.get_Coberturas().Count() > 0) + { + x.get_Coberturas().ToList().ForEach((Cobertura c) => str = string.Concat(str, string.Format("Cobertura: {0} | Premio: {1} | Franquia: {2} | LMI: {3}\n", new object[] { c.get_Observacao(), c.get_Premio(), c.get_Franquia(), c.get_Lmi() }))); + } + RelacaoItens relacaoIten = new RelacaoItens() + { + Nome = this.SelectedCliente.get_Nome(), + Documento = this.SelectedCliente.get_Documento(), + Apolice = this.SelectedControle.get_Apolice(), + VigenciaInicial = this.SelectedControle.get_Vigencia1(), + VigenciaFinal = this.SelectedControle.get_Vigencia2(), + Ordem = x.get_Ordem(), + Sinistrado = (x.get_Sinistrado() ? "SIM" : "NÃO") + }; + ControleSinistro controleSinistro = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro != null) + { + dataSinistro = controleSinistro.get_DataSinistro(); + } + else + { + nullable = null; + dataSinistro = nullable; + } + relacaoIten.DataSinistro = dataSinistro; + ControleSinistro controleSinistro1 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro1 != null) + { + Sinistro sinistro = controleSinistro1.get_Sinistros().FirstOrDefault(); + if (sinistro != null) + { + numero = sinistro.get_Numero(); + } + else + { + numero = null; + } + } + else + { + numero = null; + } + relacaoIten.NumSinistro = numero; + ControleSinistro controleSinistro2 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro2 != null) + { + Sinistro sinistro1 = controleSinistro2.get_Sinistros().FirstOrDefault(); + if (sinistro1 != null) + { + statusSinistro = sinistro1.get_StatusSinistro(); + } + else + { + nullable1 = null; + statusSinistro = nullable1; + } + } + else + { + nullable1 = null; + statusSinistro = nullable1; + } + relacaoIten.StatusSinistro = statusSinistro; + ControleSinistro controleSinistro3 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro3 != null) + { + Sinistro sinistro2 = controleSinistro3.get_Sinistros().FirstOrDefault(); + if (sinistro2 != null) + { + itemSinistrado = sinistro2.get_ItemSinistrado(); + } + else + { + itemSinistrado = null; + } + } + else + { + itemSinistrado = null; + } + relacaoIten.ItemSinistrado = itemSinistrado; + ControleSinistro controleSinistro4 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro4 != null) + { + Sinistro sinistro3 = controleSinistro4.get_Sinistros().FirstOrDefault(); + if (sinistro3 != null) + { + nullable3 = new decimal?(sinistro3.get_Valor()); + } + else + { + nullable2 = null; + nullable3 = nullable2; + } + } + else + { + nullable2 = null; + nullable3 = nullable2; + } + relacaoIten.Valor = nullable3; + ControleSinistro controleSinistro5 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro5 != null) + { + Sinistro sinistro4 = controleSinistro5.get_Sinistros().FirstOrDefault(); + if (sinistro4 != null) + { + dataLiquidacao = sinistro4.get_DataLiquidacao(); + } + else + { + nullable = null; + dataLiquidacao = nullable; + } + } + else + { + nullable = null; + dataLiquidacao = nullable; + } + relacaoIten.DataLiq = dataLiquidacao; + ControleSinistro controleSinistro6 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro6 != null) + { + Sinistro sinistro5 = controleSinistro6.get_Sinistros().FirstOrDefault(); + if (sinistro5 != null) + { + dataReclamacao = sinistro5.get_DataReclamacao(); + } + else + { + nullable = null; + dataReclamacao = nullable; + } + } + else + { + nullable = null; + dataReclamacao = nullable; + } + relacaoIten.DataRec = dataReclamacao; + ControleSinistro controleSinistro7 = x.get_Sinistros().FirstOrDefault(); + if (controleSinistro7 != null) + { + Sinistro sinistro6 = controleSinistro7.get_Sinistros().FirstOrDefault(); + if (sinistro6 != null) + { + motivo = sinistro6.get_Motivo(); + } + else + { + motivo = null; + } + } + else + { + motivo = null; + } + relacaoIten.Motivo = motivo; + relacaoIten.Status = (string.IsNullOrEmpty(x.get_Status()) ? x.get_StatusInclusao() : x.get_Status()); + relacaoIten.Cobertura = (str.Length > 4000 ? str.Substring(0, 4000) : str); + RelacaoItens endereco = relacaoIten; + long id = this.SelectedControle.get_Controle().get_Ramo().get_Id(); + if (id > (long)5) + { + if (id == (long)18) + { + endereco.Endereco = x.get_Patrimonial().get_Endereco(); + endereco.Numero = x.get_Patrimonial().get_Numero(); + endereco.Bairro = x.get_Patrimonial().get_Bairro(); + endereco.Cidade = x.get_Patrimonial().get_Cidade(); + endereco.Estado = x.get_Patrimonial().get_Estado(); + endereco.Cep = x.get_Patrimonial().get_Cep(); + endereco.Complemento = x.get_Patrimonial().get_Complemento(); + endereco.Bens = x.get_Patrimonial().get_Bens(); + endereco.Descricao = x.get_Descricao(); + relacaoItens.Add(endereco); + return; + } + if (id == (long)37) + { + goto Label1; + } + } + else + { + if (id - (long)1 <= (long)2) + { + endereco.Endereco = x.get_Patrimonial().get_Endereco(); + endereco.Numero = x.get_Patrimonial().get_Numero(); + endereco.Bairro = x.get_Patrimonial().get_Bairro(); + endereco.Cidade = x.get_Patrimonial().get_Cidade(); + endereco.Estado = x.get_Patrimonial().get_Estado(); + endereco.Cep = x.get_Patrimonial().get_Cep(); + endereco.Complemento = x.get_Patrimonial().get_Complemento(); + endereco.Bens = x.get_Patrimonial().get_Bens(); + endereco.Descricao = x.get_Descricao(); + relacaoItens.Add(endereco); + return; + } + if (id == (long)5) + { + goto Label1; + } + } + endereco.Descricao = x.get_Descricao(); + relacaoItens.Add(endereco); + return; + Label1: + endereco.Fipe = x.get_Auto().get_Fipe(); + RelacaoItens relacaoIten1 = endereco; + Fabricante fabricante = x.get_Auto().get_Fabricante(); + if (fabricante != null) + { + descricao = fabricante.get_Descricao(); + } + else + { + descricao = null; + } + relacaoIten1.Fabricante = descricao; + endereco.Modelo = x.get_Auto().get_Modelo(); + endereco.AnoFab = x.get_Auto().get_AnoFabricacao(); + endereco.AnoMod = x.get_Auto().get_AnoModelo(); + endereco.Chassi = x.get_Auto().get_Chassi(); + endereco.Placa = x.get_Auto().get_Placa(); + endereco.RegiaoCirculacao = x.get_Auto().get_RegiaoCirculacao(); + endereco.Bonus = x.get_Auto().get_Bonus(); + endereco.Descricao = x.get_Descricao(); + relacaoItens.Add(endereco); + }); + string tempPath = ""; + str3 = ""; + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 41)) + { + tempPath = Path.GetTempPath(); + str3 = string.Format("{0}{1}.xlsx", tempPath, Guid.NewGuid()); + } + else + { + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + if (DialogResult.OK == folderBrowserDialog.ShowDialog()) + { + tempPath = string.Concat(folderBrowserDialog.SelectedPath, "\\"); + Directory.CreateDirectory(tempPath); + } + else + { + variable = null; + str2 = null; + str3 = null; + return; + } + } + object[] objArray = new object[] { tempPath, str2, this.SelectedControle.get_Apolice().Replace("/", ""), Guid.NewGuid() }; + str3 = string.Format("{0}ITENS - {1} {2} {3}.xlsx", objArray); + } + XLWorkbook xLWorkbook = new XLWorkbook(); + string apolice = this.SelectedControle.get_Apolice(); + if (apolice != null) + { + str1 = apolice.Replace("/", ""); + } + else + { + str1 = null; + } + await Funcoes.GerarXls(xLWorkbook, string.Concat("ITENS - ", str1), relacaoItens, null).SaveAs(str3); + if (!typeFromProgID) + { + await base.ShowMessage(string.Concat("ARQUIVO SALVO NO CAMINHO ", str3), "OK", "", false); + } + else + { + Process.Start(str3); + } + base.RegistrarAcao(string.Format("GEROU A RELAÇÃO DOS ITENS DO DOCUMENTO DE ID {0}", this.SelectedControle.get_Id()), this.SelectedControle.get_Id(), new TipoTela?(21), null); + base.Loading(false); + } + } + variable = null; + str2 = null; + str3 = null; + } + + public void ManutecaoItens() + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela == null) + { + return; + } + acessaTela(3, "Manutencao"); + } + + public async Task MostrarItens(int type = 0) + { + bool count; + Item item; + this.IsLoadingItens = false; + this.MostrarItensVisibility = Visibility.Collapsed; + this.MostrarSinistroVisibility = Visibility.Visible; + this.ItensRevelados = true; + Documento documentoSelecionado = ConsultaViewModel.DocumentoSelecionado; + if (type == 1 && ConsultaViewModel.DocumentoSelecionado.get_Tipo() == 1) + { + documentoSelecionado = this.SelectedControle; + } + await this.CarregaItens(type, documentoSelecionado); + ObservableCollection itens = this.Itens; + if (itens != null) + { + count = itens.Count > 1; + } + else + { + count = false; + } + if (count) + { + ConsultaViewModel consultaViewModel = this; + ObservableCollection observableCollection = this.Itens; + if (observableCollection != null) + { + item = observableCollection.FirstOrDefault(); + } + else + { + item = null; + } + consultaViewModel.SelectedItem = item; + } + this.IsLoadingItens = true; + } + + public async Task Pesquisar(PesquisaAvancada pesquisa) + { + TimeSpan vigencia1; + string str; + Visibility visibility; + int num; + int num1; + string str1; + ConsultaViewModel.u003cu003ec__DisplayClass24_0 variable; + MainViewModel.StatusSelecionado = pesquisa.get_Status(); + if (pesquisa.get_IdDocumento() != 0) + { + this.Pesquisando = true; + await this.SelecionarCliente(pesquisa.get_IdCliente(), false); + base.Loading(true); + Documento documento = await this._apoliceServico.BuscarApoliceAsync(pesquisa.get_IdDocumento(), false, false); + Documento documento1 = documento; + if (documento1 == null || this.Apolices.Count == 0 || this.Apolices == null) + { + this.Pesquisando = false; + base.Loading(false); + } + else + { + Documento documento2 = this.Apolices.FirstOrDefault((Documento x) => x.get_Controle().get_Id() == documento1.get_Controle().get_Id()); + if (documento2 == null && documento1.get_Tipo() == 1) + { + documento2 = documento1; + documento2.set_TemEndosso(true); + if (documento2 == null) + { + this.Pesquisando = false; + base.Loading(false); + variable = null; + return; + } + } + this.SelectedControle = documento2; + this.IsVisibleApolice = Visibility.Visible; + this.VisibilityParcelasVendedores = Visibility.Collapsed; + DateTime date = Funcoes.GetNetworkTime().Date; + ConsultaViewModel consultaViewModel = this; + if (string.IsNullOrEmpty(documento2.get_Apolice())) + { + vigencia1 = date - documento2.get_Vigencia1(); + str = string.Format("{0} DIAS DE PENDÊNCIA", vigencia1.TotalDays); + } + else + { + str = ""; + } + consultaViewModel.PendenciaApolice = str; + ConsultaViewModel consultaViewModel1 = this; + visibility = (documento2.get_TemEndosso() ? Visibility.Visible : Visibility.Collapsed); + consultaViewModel1.IsVisibleRadioEndosso = visibility; + if (documento2.get_TemEndosso()) + { + this.IsVisibleRadioEndosso = Visibility.Visible; + ConsultaViewModel observableCollection = this; + IList documentos = documento2.get_Controle().get_Documentos(); + observableCollection.Endossos = new ObservableCollection(documentos.Where((Documento x) => { + if (x.get_Tipo() != 1) + { + return false; + } + return !x.get_Excluido(); + })); + } + if (documento1.get_Tipo() == 1) + { + documento1 = this.Endossos.First((Documento x) => x.get_Id() == documento1.get_Id()); + this.FilterDocumento = 1; + this.IsVisibleEndosso = Visibility.Visible; + this.SelectedEndosso = documento1; + ConsultaViewModel consultaViewModel2 = this; + if (string.IsNullOrEmpty(documento1.get_Endosso())) + { + vigencia1 = date - documento1.get_Vigencia1(); + str1 = string.Format("{0} DIAS DE PENDÊNCIA", vigencia1.TotalDays); + } + else + { + str1 = ""; + } + consultaViewModel2.PendenciaApolice = str1; + } + this.CarregaDocumentos(documento1.get_Tipo()); + await this.SelecionaParcelas(documento1); + this.VisibilityParcelasVendedores = Visibility.Visible; + this.Pesquisando = false; + if (pesquisa.get_IdItem() != 0) + { + ConsultaViewModel consultaViewModel3 = this; + num = (documento1.get_Tipo() == 0 ? 1 : 2); + await consultaViewModel3.SelecionaItens(num, documento1, pesquisa.get_IdItem(), true); + this.SelecionaItem(this.Itens.FirstOrDefault((Item x) => x.get_Id() == pesquisa.get_IdItem())); + base.Loading(false); + if (pesquisa.get_IdSinistro() != 0) + { + Action acessaTela = Gestor.Application.Actions.Actions.AcessaTela; + if (acessaTela != null) + { + acessaTela(7, ""); + } + else + { + } + } + } + else + { + ConsultaViewModel consultaViewModel4 = this; + num1 = (documento1.get_Tipo() == 0 ? 1 : 2); + await consultaViewModel4.SelecionaItens(num1, documento1, (long)0, false); + base.Loading(false); + } + } + } + else + { + await this.SelecionarCliente(pesquisa.get_IdCliente(), true); + } + variable = null; + } + + public async Task RecusarDocumento() + { + bool flag; + IList list; + string str; + Documento documento; + if (ConsultaViewModel.DocumentoSelecionado != null) + { + bool[] flagArray = await Funcoes.VerificarPagamento(ConsultaViewModel.DocumentoSelecionado.get_Id()); + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 23)) + { + bool[] flagArray1 = flagArray; + if (((IEnumerable)flagArray1).Any((bool x) => x)) + { + await base.ShowMessage("NÃO É POSSÍVEL RECUSAR UMA APÓLICE ENQUANTO HOUVER RECEBIMENTO DE COMISSÃO OU PAGAMENTO DE VENDEDORES", "OK", "", false); + documento = null; + return; + } + } + List configuracaoSistemas = Recursos.Configuracoes; + flag = (!configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 23) ? false : flagArray[1]); + bool flag1 = flag; + if (flag1) + { + flag1 = await base.ShowMessage("EXISTEM PAGAMENTOS PARA OS VENDEDORES DO CONTRATO, DESEJA CRIAR ESTORNOS PARA ESSES PAGAMENTOS?", "SIM", "NÃO", false); + } + bool flag2 = flag1; + documento = await this._apoliceServico.BuscarApoliceAsync(ConsultaViewModel.DocumentoSelecionado.get_Id(), false, false); + if (documento.get_Controle().get_Documentos().Count > 1) + { + IList documentos = documento.get_Controle().get_Documentos(); + IEnumerable excluido = + from x in documentos + where !x.get_Excluido() + select x; + list = ( + from x in excluido + orderby x.get_Ordem() + select x).ToList(); + } + else + { + list = documento.get_Controle().get_Documentos(); + } + IList documentos1 = list; + if (documentos1.Count > 1) + { + IList documentos2 = documentos1; + if (documentos2.Last((Documento x) => x.get_Situacao() != 7).get_Id() != ConsultaViewModel.DocumentoSelecionado.get_Id()) + { + await base.ShowMessage("NÃO É POSSÍVEL RECUSAR UM DOCUMENTO ENQUANTO HOUVER ENDOSSOS EM CIMA DO MESMO.", "OK", "", false); + documento = null; + return; + } + } + if (documento.get_Situacao() != 7) + { + if (documento.get_Tipo() != 0 || !string.IsNullOrEmpty(documento.get_Apolice())) + { + str = (documento.get_Tipo() != 0 || string.IsNullOrEmpty(documento.get_Apolice()) ? "O ENDOSSO SELECIONADO" : "A APÓLICE SELECIONADA"); + } + else + { + str = "A PROPOSTA SELECIONADA"; + } + string str1 = str; + if (await base.ShowMessage(string.Concat("DESEJA REALMENTE RECUSAR ", str1, "?"), "SIM", "NÃO", false)) + { + string str2 = null; + str2 = await base.ShowObservacaoDialog(); + if (str2 != null) + { + base.Loading(true); + await Funcoes.RecusarApolice(documento, str2, flag2); + ConsultaViewModel.DocumentoSelecionado = null; + await this.SelecionaCliente(this.SelectedCliente, true); + base.Loading(false); + } + } + } + else + { + await base.ShowMessage("NÃO É POSSÍVEL RECUSAR UM DOCUMENTO JÁ RECUSADO.", "OK", "", false); + } + } + documento = null; + } + + public async void SalvarOrdem(ObservableCollection itens) + { + if (itens != null) + { + ObservableCollection observableCollection = itens; + if (!observableCollection.Any((Item x) => { + int? ordem = x.get_Ordem(); + return ordem.GetValueOrDefault() == 0 & ordem.HasValue; + })) + { + ObservableCollection observableCollection1 = itens; + IEnumerable> groupings = + from item in observableCollection1 + group item by item.get_Ordem(); + if (!groupings.Any>((IGrouping x) => x.Count() > 1)) + { + base.Loading(true); + foreach (Item iten in itens) + { + await this._itemServico.Save(iten); + } + await this.SelecionaItens(this.FilterItens, null, (long)0, false); + base.Loading(false); + } + else + { + await base.ShowMessage("EXISTEM ITENS COM ORDEM REPETIDA. \nDEFINA UMA SEQUÊNCIA DIFERENTE PARA CADA ITEM.", "OK", "", false); + } + } + else + { + await base.ShowMessage("O CAMPO ORDEM DEVE SER MAIOR QUE ZERO.", "OK", "", false); + } + } + } + + public void ScrollDocumento() + { + if (this.UpdatingScroll) + { + return; + } + this.UpdatingScroll = true; + Task.Run(async () => { + await Task.Delay(300); + System.Windows.Application.Current.Dispatcher.Invoke(() => { + Action scrollDocumento = Gestor.Application.Actions.Actions.ScrollDocumento; + if (scrollDocumento == null) + { + return; + } + scrollDocumento(); + }); + }); + } + + public async Task SelecionaCliente(Cliente value, bool selecionar = true) + { + List vendedorUsuarios; + long? nullable1; + long? nullable2; + string str; + long? nullable3; + Documento documento; + long? nullable4; + long? nullable5; + long? nullable6; + bool flag; + Documento documento1; + this.Clear(); + if (value == null || value.get_Id() == 0) + { + base.IsVisible = Visibility.Collapsed; + } + else + { + try + { + this.Carregando = true; + base.Loading(true); + this.SelectedCliente = value; + ApoliceServico apoliceServico = this._apoliceServico; + long num = value.get_Id(); + FiltroStatusDocumento statusSelecionado = MainViewModel.StatusSelecionado; + if (Recursos.Usuario != null) + { + vendedorUsuarios = await base.VerificaVinculoVendedor(Recursos.Usuario); + } + else + { + vendedorUsuarios = new List(); + } + ObservableCollection observableCollection = await apoliceServico.BuscarApolicesAsync(num, statusSelecionado, vendedorUsuarios); + apoliceServico = null; + this.Apolices = observableCollection; + ConsultaViewModel consultaViewModel = this; + string[] nome = new string[] { "CONSULTOU ", null, null, null, null }; + str = (MainViewModel.StatusSelecionado != 4 ? string.Concat("OS ", Functions.GetDescription(MainViewModel.StatusSelecionado)) : "TODOS OS DOCUMENTOS"); + nome[1] = str; + nome[2] = " DO CLIENTE \""; + nome[3] = this.SelectedCliente.get_Nome(); + nome[4] = "\""; + string str1 = string.Concat(nome); + long num1 = this.SelectedCliente.get_Id(); + TipoTela? nullable7 = new TipoTela?(21); + Cliente selectedCliente = this.SelectedCliente; + if (selectedCliente != null) + { + nullable3 = new long?(selectedCliente.get_Id()); + } + else + { + nullable1 = null; + nullable3 = nullable1; + } + consultaViewModel.RegistrarAcao(str1, num1, nullable7, string.Format("ID CLIENTE: {0}", nullable3)); + if (this.Apolices == null || this.Apolices.Count <= 0) + { + this.SelectedControle = null; + this.SelectedEndosso = null; + this.SelectedItem = null; + this.SelectedParcela = null; + ConsultaViewModel.DocumentoSelecionado = null; + ConsultaViewModel.ItemSelecionado = null; + this.FilterDocumento = 0; + this.IsVisibleRadioEndosso = Visibility.Collapsed; + Action updateDocumento = Gestor.Application.Actions.Actions.UpdateDocumento; + if (updateDocumento != null) + { + updateDocumento(null); + } + else + { + } + } + else if (selecionar) + { + if (ConsultaViewModel.DocumentoSelecionado != null && ConsultaViewModel.DocumentoSelecionado.get_Tipo() != 0) + { + Controle controle = ConsultaViewModel.DocumentoSelecionado.get_Controle(); + if (controle != null) + { + Cliente cliente = controle.get_Cliente(); + if (cliente != null) + { + nullable4 = new long?(cliente.get_Id()); + } + else + { + nullable2 = null; + nullable4 = nullable2; + } + } + else + { + nullable2 = null; + nullable4 = nullable2; + } + nullable1 = nullable4; + long num2 = value.get_Id(); + if (nullable1.GetValueOrDefault() != num2 | !nullable1.HasValue) + { + goto Label2; + } + Controle controle1 = ConsultaViewModel.DocumentoSelecionado.get_Controle(); + if (controle1 != null) + { + IList documentos = controle1.get_Documentos(); + if (documentos != null) + { + Documento documento2 = documentos.FirstOrDefault((Documento x) => x.get_Tipo() == 0); + if (documento2 != null) + { + nullable5 = new long?(documento2.get_Id()); + } + else + { + nullable1 = null; + nullable5 = nullable1; + } + } + else + { + nullable1 = null; + nullable5 = nullable1; + } + } + else + { + nullable1 = null; + nullable5 = nullable1; + } + nullable1 = nullable5; + long valueOrDefault = nullable1.GetValueOrDefault(); + Documento documentoSelecionado = ConsultaViewModel.DocumentoSelecionado; + if (documentoSelecionado != null) + { + nullable6 = new long?(documentoSelecionado.get_Id()); + } + else + { + nullable1 = null; + nullable6 = nullable1; + } + long? nullable8 = nullable6; + if (valueOrDefault > (long)0) + { + flag = this.Apolices.FirstOrDefault((Documento x) => x.get_Id() == valueOrDefault); + } + else + { + flag = false; + } + if (!flag) + { + ConsultaViewModel consultaViewModel1 = this; + if (ConsultaViewModel.DocumentoSelecionado != null) + { + ObservableCollection apolices = this.Apolices; + documento1 = apolices.FirstOrDefault((Documento x) => x.get_Id() == ConsultaViewModel.DocumentoSelecionado.get_Id()); + if (documento1 == null) + { + documento1 = this.Apolices.FirstOrDefault(); + } + } + else + { + documento1 = this.Apolices.FirstOrDefault(); + } + await consultaViewModel1.SelecionaDocumento(0, documento1); + this.CarregaDocumentos(0); + } + else + { + await this.SelecionaDocumento(0, this.Apolices.FirstOrDefault((Documento x) => x.get_Id() == valueOrDefault)); + this.FilterDocumento = 1; + this.IsVisibleEndosso = Visibility.Visible; + ConsultaViewModel consultaViewModel2 = this; + Documento item = this.Endossos.FirstOrDefault((Documento x) => { + long id = x.get_Id(); + long? nullable = nullable8; + return id == nullable.GetValueOrDefault() & nullable.HasValue; + }); + if (item == null) + { + item = this.Endossos[0]; + } + consultaViewModel2.SelectedEndosso = item; + this.IsLoading = false; + await this.WorkOnSelectedEndosso(this.SelectedEndosso); + this.CarregaDocumentos(1); + } + goto Label1; + } + Label2: + ConsultaViewModel consultaViewModel3 = this; + if (ConsultaViewModel.DocumentoSelecionado != null) + { + ObservableCollection apolices1 = this.Apolices; + documento = apolices1.FirstOrDefault((Documento x) => x.get_Id() == ConsultaViewModel.DocumentoSelecionado.get_Id()); + if (documento == null) + { + documento = this.Apolices.FirstOrDefault(); + } + } + else + { + documento = this.Apolices.FirstOrDefault(); + } + await consultaViewModel3.SelecionaDocumento(0, documento); + this.CarregaDocumentos(0); + } + else + { + base.Loading(false); + this.Carregando = false; + return; + } + Label1: + this.ManutencaoItemVisibility = Visibility.Visible; + this.RenovarVisibility = Visibility.Visible; + this.TrocarClienteVisibility = Visibility.Visible; + this.TarefasVisibility = Visibility.Visible; + this.EndossarVisibility = Visibility.Visible; + this.ComissaoVisibility = Visibility.Visible; + base.Loading(false); + } + catch (Exception exception1) + { + Exception exception = exception1; + this.Clear(); + this.SelectedControle = null; + this.SelectedEndosso = null; + this.SelectedItem = null; + this.SelectedParcela = null; + ConsultaViewModel.DocumentoSelecionado = null; + ConsultaViewModel.ItemSelecionado = null; + this.FilterDocumento = 0; + this.IsVisibleRadioEndosso = Visibility.Collapsed; + Action action = Gestor.Application.Actions.Actions.UpdateDocumento; + if (action != null) + { + action(null); + } + else + { + } + (new BaseServico()).Registrar(exception, 1, 3, new { @value = value, selecionar = selecionar }, true); + } + this.Carregando = false; + } + } + + public async Task SelecionaDocumento(int type, Documento documento) + { + if (!this.Pesquisando) + { + if (documento != null) + { + documento.get_Controle().get_Cliente().set_Nome(this.SelectedCliente.get_Nome()); + if (type == 1) + { + this.FilterDocumento = 1; + this.IsVisibleEndosso = Visibility.Visible; + this.SelectedEndosso = documento; + await this.WorkOnSelectedEndosso(documento); + } + else + { + this.FilterDocumento = 0; + this.IsVisibleRadioEndosso = Visibility.Collapsed; + this.IsVisibleApolice = Visibility.Visible; + this.SelectedControle = documento; + await this.WorkOnSelectedControle(documento); + if (documento.get_TemEndosso()) + { + this.IsVisibleRadioEndosso = Visibility.Visible; + ConsultaViewModel observableCollection = this; + IList documentos = documento.get_Controle().get_Documentos(); + observableCollection.Endossos = new ObservableCollection(documentos.Where((Documento x) => { + if (x.get_Tipo() != 1) + { + return false; + } + if (Recursos.Usuario.get_Id() == 0) + { + return true; + } + return !x.get_Excluido(); + })); + } + else + { + return; + } + } + } + else + { + this.FilterDocumento = 0; + this.IsVisibleRadioEndosso = Visibility.Collapsed; + this.IsVisibleApolice = Visibility.Visible; + } + } + } + + public void SelecionaItem(Item item) + { + int num; + if (item == null || item.get_Id() == 0) + { + return; + } + if (item != null) + { + long? substituido = item.get_Substituido(); + long num1 = (long)0; + if (substituido.GetValueOrDefault() <= num1 | !substituido.HasValue) + { + num = 0; + this.FilterItens = num; + this.SelectedItem = item; + return; + } + num = 3; + this.FilterItens = num; + this.SelectedItem = item; + return; + } + num = 0; + this.FilterItens = num; + this.SelectedItem = item; + } + + public async Task SelecionaItens(int type, Documento documento = null, long iditem = 0L, bool pesquisaAvancada = false) + { + long? substituido; + long num; + Item item; + Item item1; + bool valueOrDefault; + Item item2; + Item item3; + bool flag; + Item item4; + Item item5; + if (documento == null) + { + documento = this.SelectedControle; + } + if (documento != null) + { + this.IsLoadingItens = false; + bool flag1 = !pesquisaAvancada; + if (flag1) + { + flag1 = await this.VerificaItens(documento); + } + if (!flag1) + { + await this.CarregaItens(type, documento); + int filterItens = this.FilterItens; + if (iditem == 0 && filterItens != 2) + { + ObservableCollection itens = this.Itens; + if (itens != null) + { + item = itens.FirstOrDefault((Item i) => { + long? nullable; + long id = i.get_Id(); + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + nullable = new long?(selectedItem.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + } + else + { + item = null; + } + Item item6 = item; + if (item6 != null || filterItens == 0) + { + ConsultaViewModel consultaViewModel = this; + if (item6 != null) + { + item1 = item6; + } + else + { + ObservableCollection observableCollection = this.Itens; + if (observableCollection != null) + { + item1 = observableCollection.FirstOrDefault(); + } + else + { + item1 = null; + } + } + consultaViewModel.SelectedItem = item1; + } + else if (item6 == null && filterItens == 1) + { + Item item7 = this.SelectedItem; + if (item7 != null) + { + substituido = item7.get_Substituicao(); + num = (long)0; + flag = substituido.GetValueOrDefault() > num & substituido.HasValue; + } + else + { + flag = false; + } + if (flag) + { + ObservableCollection itens1 = this.Itens; + if (itens1 != null) + { + item5 = itens1.FirstOrDefault((Item i) => { + long? substituicao; + long id = i.get_Id(); + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + substituicao = selectedItem.get_Substituicao(); + } + else + { + substituicao = null; + } + long? nullable = substituicao; + return id == nullable.GetValueOrDefault() & nullable.HasValue; + }); + } + else + { + item5 = null; + } + item6 = item5; + } + ConsultaViewModel consultaViewModel1 = this; + if (item6 != null) + { + item4 = item6; + } + else + { + ObservableCollection observableCollection1 = this.Itens; + if (observableCollection1 != null) + { + item4 = observableCollection1.FirstOrDefault(); + } + else + { + item4 = null; + } + } + consultaViewModel1.SelectedItem = item4; + } + Item item8 = this.SelectedItem; + if (item8 != null) + { + substituido = item8.get_Substituido(); + num = (long)0; + valueOrDefault = substituido.GetValueOrDefault() > num & substituido.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault && filterItens != 1) + { + this.FilterItens = 3; + this.Itens = await this._itemServico.BuscarItens(documento.get_Controle().get_Id(), 1); + ObservableCollection itens2 = this.Itens; + if (itens2 != null) + { + item2 = itens2.FirstOrDefault((Item i) => { + long? nullable; + long id = i.get_Id(); + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + nullable = new long?(selectedItem.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + } + else + { + item2 = null; + } + item6 = item2; + ConsultaViewModel consultaViewModel2 = this; + if (item6 != null) + { + item3 = item6; + } + else + { + ObservableCollection observableCollection2 = this.Itens; + if (observableCollection2 != null) + { + item3 = observableCollection2.FirstOrDefault(); + } + else + { + item3 = null; + } + } + consultaViewModel2.SelectedItem = item3; + } + } + this.IsLoadingItens = true; + } + } + } + + public async Task SelecionaParcelas(Documento documento = null) + { + ObservableCollection observableCollection; + Parcela item; + if (documento == null) + { + documento = this.SelectedControle; + } + ObservableCollection observableCollection1 = await this._parcelaServico.BuscarParcelasPorDocumento(documento); + ConsultaViewModel consultaViewModel = this; + if (documento.get_TipoRecebimento().GetValueOrDefault() == 2) + { + ObservableCollection observableCollection2 = observableCollection1; + observableCollection = new ObservableCollection( + from x in observableCollection2 + orderby x.get_NumeroParcela() descending + select x); + } + else + { + observableCollection = observableCollection1; + } + consultaViewModel.Parcelas = observableCollection; + ConsultaViewModel consultaViewModel1 = this; + if (this.Parcelas == null || this.Parcelas.Count <= 0) + { + item = null; + } + else + { + item = this.Parcelas[0]; + } + consultaViewModel1.SelectedParcela = item; + this.CalculaComissao(documento, this.Parcelas); + this.IsLoadingParcelas = true; + } + + public async void SelecionarCliente(Cliente cliente) + { + await this.SelecionaCliente(cliente, true); + this.ScrollDocumento(); + } + + public async Task SelecionarCliente(long id, bool selecionar) + { + Cliente cliente = await (new ClienteServico()).BuscarCliente(id); + await this.SelecionaCliente(cliente, selecionar); + } + + public async Task VerificaItens(Documento documento) + { + bool flag; + if (!this.ItensRevelados) + { + if (await this._itemServico.ChecarQuantidade(documento.get_Id()) > 2) + { + this.Itens = new ObservableCollection(); + ObservableCollection itens = this.Itens; + Item item = new Item(); + item.set_Id((long)0); + item.set_Descricao("Item - Apólice Coletiva"); + itens.Add(item); + this.MostrarItensVisibility = Visibility.Visible; + this.MostrarSinistroVisibility = Visibility.Collapsed; + flag = true; + return flag; + } + } + flag = false; + return flag; + } + + private async Task WorkOnSelectedControle(Documento value) + { + string str; + Visibility visibility; + long id; + if (value != null && value.get_Id() != 0 && !this.IsLoading) + { + ConsultaViewModel.DocumentoSelecionado = value; + this.IsEnabledParcelaItem = false; + this.IsLoading = true; + this.VisibilityParcelasVendedores = Visibility.Collapsed; + ConsultaViewModel consultaViewModel = this; + if (string.IsNullOrEmpty(value.get_Apolice())) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + TimeSpan date = networkTime.Date - value.get_Vigencia1(); + str = string.Format("{0} DIAS DE PENDÊNCIA", date.TotalDays); + } + else + { + str = ""; + } + consultaViewModel.PendenciaApolice = str; + ConsultaViewModel consultaViewModel1 = this; + visibility = (value.get_TemEndosso() ? Visibility.Visible : Visibility.Collapsed); + consultaViewModel1.IsVisibleRadioEndosso = visibility; + await this.SelecionaParcelas(value); + this.VisibilityParcelasVendedores = Visibility.Visible; + this.FilterItens = 0; + Item itemSelecionado = ConsultaViewModel.ItemSelecionado; + if (itemSelecionado != null) + { + id = itemSelecionado.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + await this.SelecionaItens(this.FilterItens, value, (long)0, false); + if (num > (long)0 && this.Itens != null && this.Itens.Any((Item x) => x.get_Id() == num)) + { + ConsultaViewModel.ItemSelecionado = this.Itens.First((Item x) => x.get_Id() == num); + this.SelecionaItem(ConsultaViewModel.ItemSelecionado); + Action scrollToItem = Gestor.Application.Actions.Actions.ScrollToItem; + if (scrollToItem != null) + { + scrollToItem(); + } + else + { + } + } + this.IsLoading = false; + this.IsEnabledParcelaItem = true; + } + } + + private void WorkOnSelectedDocumento(Documento value) + { + if (value == null || value.get_Id() == 0 || this.Recarregando) + { + return; + } + ConsultaViewModel.DocumentoSelecionado = value; + this.ParcelasLabel = (ConsultaViewModel.DocumentoSelecionado.get_TipoRecebimento().GetValueOrDefault() == 2 ? "FATURAS" : "PARCELAS"); + TipoRecebimento? tipoRecebimento = ConsultaViewModel.DocumentoSelecionado.get_TipoRecebimento(); + this.IsFatura = tipoRecebimento.GetValueOrDefault() == 2; + Action updateDocumento = Gestor.Application.Actions.Actions.UpdateDocumento; + if (updateDocumento == null) + { + return; + } + updateDocumento(value); + } + + private async Task WorkOnSelectedEndosso(Documento value) + { + string str; + long id; + Visibility visibility; + string apolice; + if (value != null && value.get_Id() != 0 && !this.IsLoading) + { + ConsultaViewModel.DocumentoSelecionado = value; + base.IsEnabled = false; + this.IsLoading = true; + this.VisibilityParcelasVendedores = Visibility.Collapsed; + ConsultaViewModel consultaViewModel = this; + if (string.IsNullOrEmpty(value.get_Endosso())) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + TimeSpan date = networkTime.Date - value.get_Vigencia1(); + str = string.Format("{0} DIAS DE PENDÊNCIA", date.TotalDays); + } + else + { + str = ""; + } + consultaViewModel.PendenciaApolice = str; + await this.SelecionaParcelas(value); + Item itemSelecionado = ConsultaViewModel.ItemSelecionado; + if (itemSelecionado != null) + { + id = itemSelecionado.get_Id(); + } + else + { + id = (long)0; + } + long num = id; + await this.SelecionaItens(this.FilterItens, null, (long)0, false); + if (num > (long)0 && this.Itens != null && this.Itens.Any((Item x) => x.get_Id() == num)) + { + ConsultaViewModel.ItemSelecionado = this.Itens.First((Item x) => x.get_Id() == num); + this.SelecionaItem(ConsultaViewModel.ItemSelecionado); + Action scrollToItem = Gestor.Application.Actions.Actions.ScrollToItem; + if (scrollToItem != null) + { + scrollToItem(); + } + else + { + } + } + this.VisibilityParcelasVendedores = Visibility.Visible; + ConsultaViewModel consultaViewModel1 = this; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 19)) + { + Documento documento = value; + if (documento != null) + { + apolice = documento.get_Apolice(); + } + else + { + apolice = null; + } + if (string.IsNullOrWhiteSpace(apolice) || !value.get_Emissao().HasValue) + { + goto Label1; + } + visibility = Visibility.Collapsed; + goto Label0; + } + Label1: + visibility = Visibility.Visible; + Label0: + consultaViewModel1.RecusaVisibility = visibility; + base.IsEnabled = true; + this.IsLoading = false; + } + } + + private static void WorkOnSelectedItem(Item value) + { + long? nullable; + if (value != null) + { + Item itemSelecionado = ConsultaViewModel.ItemSelecionado; + if (itemSelecionado != null) + { + nullable = new long?(itemSelecionado.get_Id()); + } + else + { + nullable = null; + } + long? nullable1 = nullable; + long id = value.get_Id(); + if (nullable1.GetValueOrDefault() == id & nullable1.HasValue) + { + return; + } + } + ConsultaViewModel.ItemSelecionado = value; + Action updateItem = Gestor.Application.Actions.Actions.UpdateItem; + if (updateItem == null) + { + return; + } + updateItem(value); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/CriticaApoliceViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/CriticaApoliceViewModel.cs new file mode 100644 index 0000000..7ec09a7 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/CriticaApoliceViewModel.cs @@ -0,0 +1,1486 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class CriticaApoliceViewModel : BaseApoliceViewModel + { + private readonly CriticaApoliceServico _criticaServico; + + private readonly ClienteServico _clienteServico; + + private readonly ItemServico _itemServico; + + private List Vinculos; + + private ObservableCollection _usuarios = new ObservableCollection(); + + private ObservableCollection _seguradorasFiltro = new ObservableCollection(); + + private string _fieldNascimento = "NASCIMENTO"; + + private bool _isExpanded = true; + + private DateTime _inicio = Funcoes.GetNetworkTime().Date.AddDays(-7); + + private DateTime _fim = Funcoes.GetNetworkTime().Date; + + private Usuario _selectedUsuario; + + private Seguradora _selectedSeguradora; + + private bool _criticado; + + private ObservableCollection _criticas = new ObservableCollection(); + + private ObservableCollection _criticaFiltrada = new ObservableCollection(); + + private bool _isCriticaSelected; + + private CriticaApolice _selectedCritica; + + private bool _hasChange; + + private bool _isParcela; + + private DateTime? _emissaoCritica; + + private DateTime? _transmissaoCritica; + + private DateTime? _nascimentoCritica; + + private TipoSeguro? _situacao; + + private Cliente _selectedCliente; + + private string _documentoPrincipal; + + private Visibility _visibilityFisica = Visibility.Collapsed; + + private ObservableCollection _telefones = new ObservableCollection(); + + private ObservableCollection _emails = new ObservableCollection(); + + private ObservableCollection _itens = new ObservableCollection(); + + private bool _enableGrid = true; + + private string _pesquisa = ""; + + private ObservableCollection _pesquisaCritica = new ObservableCollection(); + + private string _profissaoText; + + private string _atividadeText; + + private Visibility _visibilityJuridica = Visibility.Collapsed; + + private string _fieldDocumento = "CPF"; + + private Visibility _valorComissao; + + public string AtividadeText + { + get + { + return this._atividadeText; + } + set + { + this._atividadeText = value; + base.OnPropertyChanged("AtividadeText"); + } + } + + public bool BuscaInicial { get; set; } = true; + + public bool Criticado + { + get + { + return this._criticado; + } + set + { + this._criticado = value; + base.OnPropertyChanged("Criticado"); + } + } + + public ObservableCollection CriticaFiltrada + { + get + { + return this._criticaFiltrada; + } + set + { + this._criticaFiltrada = value; + base.OnPropertyChanged("CriticaFiltrada"); + } + } + + public ObservableCollection Criticas + { + get + { + return this._criticas; + } + set + { + this._criticas = value; + base.OnPropertyChanged("Criticas"); + } + } + + public string DocumentoPrincipal + { + get + { + return this._documentoPrincipal; + } + set + { + if (value == null || ValidationHelper.OnlyNumber(value).Length > 11) + { + this.VisibilityFisica = Visibility.Collapsed; + this.FieldNascimento = "FUNDAÇÃO"; + } + else + { + this.VisibilityFisica = Visibility.Visible; + this.FieldNascimento = "NASCIMENTO"; + } + this._documentoPrincipal = value; + if (this.SelectedCliente != null) + { + TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + TipoDocumento valueOrDefault = documentoPrincipal.GetValueOrDefault(); + if (valueOrDefault == 1) + { + this.SelectedCliente.set_Rne(value); + base.OnPropertyChanged("DocumentoPrincipal"); + return; + } + else + { + if (valueOrDefault != 2) + { + goto Label1; + } + this.SelectedCliente.set_Cei(value); + base.OnPropertyChanged("DocumentoPrincipal"); + return; + } + } + Label1: + this.SelectedCliente.set_Documento(value); + } + base.OnPropertyChanged("DocumentoPrincipal"); + } + } + + public ObservableCollection Emails + { + get + { + return this._emails; + } + set + { + this._emails = value; + base.OnPropertyChanged("Emails"); + } + } + + public DateTime? EmissaoCritica + { + get + { + return this._emissaoCritica; + } + set + { + this._emissaoCritica = value; + base.OnPropertyChanged("EmissaoCritica"); + } + } + + public bool EnableGrid + { + get + { + return this._enableGrid; + } + set + { + this._enableGrid = value; + base.OnPropertyChanged("EnableGrid"); + } + } + + public string FieldDocumento + { + get + { + return this._fieldDocumento; + } + set + { + this._fieldDocumento = value; + base.OnPropertyChanged("FieldDocumento"); + } + } + + public string FieldNascimento + { + get + { + return this._fieldNascimento; + } + set + { + this._fieldNascimento = value; + base.OnPropertyChanged("FieldNascimento"); + } + } + + public DateTime Fim + { + get + { + return this._fim; + } + set + { + this._fim = value; + base.OnPropertyChanged("Fim"); + } + } + + public bool HasChange + { + get + { + return this._hasChange; + } + set + { + this._hasChange = value; + base.OnPropertyChanged("HasChange"); + } + } + + public int Index { get; set; } = -1; + + public DateTime Inicio + { + get + { + return this._inicio; + } + set + { + this._inicio = value; + base.OnPropertyChanged("Inicio"); + } + } + + public bool IsCriticaSelected + { + get + { + return this._isCriticaSelected; + } + set + { + this._isCriticaSelected = value; + base.OnPropertyChanged("IsCriticaSelected"); + } + } + + public bool IsExpanded + { + get + { + return this._isExpanded; + } + set + { + this._isExpanded = value; + base.OnPropertyChanged("IsExpanded"); + } + } + + public bool IsLoading + { + get; + set; + } + + public bool IsParcela + { + get + { + return this._isParcela; + } + set + { + this._isParcela = value; + base.OnPropertyChanged("IsParcela"); + } + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public DateTime? NascimentoCritica + { + get + { + return this._nascimentoCritica; + } + set + { + this._nascimentoCritica = value; + base.OnPropertyChanged("NascimentoCritica"); + } + } + + public string Pesquisa + { + get + { + return this._pesquisa; + } + set + { + this._pesquisa = value; + base.OnPropertyChanged("Pesquisa"); + } + } + + public ObservableCollection PesquisaCritica + { + get + { + return this._pesquisaCritica; + } + set + { + this._pesquisaCritica = value; + base.OnPropertyChanged("PesquisaCritica"); + } + } + + public string ProfissaoText + { + get + { + return this._profissaoText; + } + set + { + this._profissaoText = value; + base.OnPropertyChanged("ProfissaoText"); + } + } + + public ObservableCollection SeguradorasFiltro + { + get + { + return this._seguradorasFiltro; + } + set + { + this._seguradorasFiltro = value; + this.SelectedSeguradora = this.SelectedSeguradora ?? value.FirstOrDefault(); + base.OnPropertyChanged("SeguradorasFiltro"); + } + } + + public bool SeguroCombinado + { + get; + set; + } + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + this._selectedCliente = value; + base.OnPropertyChanged("SelectedCliente"); + } + } + + public CriticaApolice SelectedCritica + { + get + { + return this._selectedCritica; + } + set + { + this._selectedCritica = value; + this.IsCriticaSelected = value != null; + base.OnPropertyChanged("SelectedCritica"); + } + } + + public Seguradora SelectedSeguradora + { + get + { + return this._selectedSeguradora; + } + set + { + this._selectedSeguradora = value; + base.OnPropertyChanged("SelectedSeguradora"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + public TipoSeguro? StatusDocumento + { + get + { + return this._situacao; + } + set + { + this._situacao = value; + base.OnPropertyChanged("StatusDocumento"); + } + } + + public ObservableCollection Telefones + { + get + { + return this._telefones; + } + set + { + this._telefones = value; + base.OnPropertyChanged("Telefones"); + } + } + + public DateTime? TransmissaoCritica + { + get + { + return this._transmissaoCritica; + } + set + { + this._transmissaoCritica = value; + base.OnPropertyChanged("TransmissaoCritica"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + this.SelectedUsuario = this.SelectedUsuario ?? value.FirstOrDefault(); + base.OnPropertyChanged("Usuarios"); + } + } + + public Visibility ValorComissao + { + get + { + return this._valorComissao; + } + set + { + this._valorComissao = value; + base.OnPropertyChanged("ValorComissao"); + } + } + + public Visibility VisibilityFisica + { + get + { + return this._visibilityFisica; + } + set + { + this._visibilityFisica = value; + base.OnPropertyChanged("VisibilityFisica"); + } + } + + public Visibility VisibilityJuridica + { + get + { + return this._visibilityJuridica; + } + set + { + this._visibilityJuridica = value; + base.OnPropertyChanged("VisibilityJuridica"); + } + } + + public CriticaApoliceViewModel() + { + base.Invoke = false; + this._criticaServico = new CriticaApoliceServico(); + this._clienteServico = new ClienteServico(); + this._itemServico = new ItemServico(); + } + + public void AdcionarFiltro() + { + if (string.IsNullOrEmpty(this.Pesquisa)) + { + return; + } + if (string.IsNullOrWhiteSpace(this.Pesquisa.Replace("+", ""))) + { + return; + } + if (this.PesquisaCritica == null) + { + this.PesquisaCritica = new ObservableCollection(); + } + this.PesquisaCritica.Add(this.Pesquisa); + this.Pesquisa = string.Empty; + this.Pesquisar(); + } + + public void AlteraDocumentoPrincipal() + { + if (this.SelectedCliente == null) + { + return; + } + TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + TipoDocumento valueOrDefault = documentoPrincipal.GetValueOrDefault(); + if (valueOrDefault == 1) + { + this.DocumentoPrincipal = this.SelectedCliente.get_Rne(); + return; + } + if (valueOrDefault == 2) + { + this.DocumentoPrincipal = this.SelectedCliente.get_Cei(); + return; + } + } + this.DocumentoPrincipal = this.SelectedCliente.get_Documento(); + this.SelectedCliente.set_DocumentoPrincipal(new TipoDocumento?(0)); + } + + public async Task CarregaCritica(long usuario, long seguradora, bool criticado = false) + { + bool count; + Usuario usuario1; + Seguradora seguradora1; + object nome; + long num; + object obj; + long num1; + object obj1; + object obj2; + object nome1; + long num2; + object nome2; + long num3; + object obj3; + if (!this.IsLoading || this.BuscaInicial) + { + this.BuscaInicial = false; + this.EnableGrid = false; + base.Loading(true); + this.Criticado = criticado; + await this.CarregarUsuarios(usuario, this.Criticado); + List criticaApolices = await this._criticaServico.BuscarCritica(usuario, this.Inicio, this.Fim, (long)0, this.Criticado, this.Vinculos); + CriticaApoliceViewModel observableCollection = this; + IEnumerable criticaApolices1 = criticaApolices.Where((CriticaApolice x) => { + if (usuario != 0 && x.get_UsuarioImportacao().get_Id() != usuario) + { + return false; + } + if (seguradora == 0) + { + return true; + } + return x.get_Documento().get_Controle().get_Seguradora().get_Id() == seguradora; + }); + IOrderedEnumerable dataImportacao = + from x in criticaApolices1 + orderby x.get_DataImportacao() + select x; + observableCollection.Criticas = new ObservableCollection(dataImportacao.ThenByDescending((CriticaApolice x) => x.get_Documento().get_Controle().get_Cliente().get_Nome())); + this.CriticaFiltrada = this.Criticas; + if (this.CriticaFiltrada == null || this.CriticaFiltrada.Count <= 0) + { + this.IsCriticaSelected = false; + } + else + { + await this.SelecionaCritica(this.CriticaFiltrada.First()); + } + CriticaApoliceViewModel criticaApoliceViewModel = this; + ObservableCollection criticaFiltrada = this.CriticaFiltrada; + if (criticaFiltrada != null) + { + count = criticaFiltrada.Count > 0; + } + else + { + count = false; + } + criticaApoliceViewModel.IsExpanded = count; + base.Loading(false); + ObservableCollection usuarios = this.Usuarios; + if (usuarios != null) + { + usuario1 = usuarios.FirstOrDefault((Usuario x) => x.get_Id() == usuario); + } + else + { + usuario1 = null; + } + Usuario usuario2 = usuario1; + List seguradoras = base.Seguradoras; + if (seguradoras != null) + { + seguradora1 = seguradoras.FirstOrDefault((Seguradora x) => x.get_Id() == seguradora); + } + else + { + seguradora1 = null; + } + Seguradora seguradora2 = seguradora1; + CriticaApoliceViewModel criticaApoliceViewModel1 = this; + string str = string.Format("CONSULTOU CRÍTICAS NO PERÍODO ENTRE {0:d} E {1:d}", this.Inicio, this.Fim); + long num4 = (long)0; + TipoTela? nullable = new TipoTela?(20); + if (this.PesquisaCritica == null || this.PesquisaCritica.Count <= 0) + { + object[] objArray = new object[5]; + if (usuario2 != null) + { + nome = usuario2.get_Nome(); + } + else + { + nome = null; + } + if (nome == null) + { + nome = "TODOS USUÁRIOS"; + } + objArray[0] = nome; + num = (usuario2 != null ? usuario2.get_Id() : (long)0); + objArray[1] = num; + if (seguradora2 != null) + { + obj = seguradora2.get_Nome(); + } + else + { + obj = null; + } + if (obj == null) + { + obj = "TODAS AS SEGURADORAS"; + } + objArray[2] = obj; + num1 = (seguradora2 != null ? seguradora2.get_Id() : (long)0); + objArray[3] = num1; + obj1 = (this.Criticado ? "SIM" : "NÃO"); + objArray[4] = obj1; + obj2 = string.Format("USUÁRIO IMPORTAÇÃO: {0} ({1})\nSEGURADORA: {2} ({3})\nCRITICADOS: {4}", objArray); + } + else + { + object[] objArray1 = new object[6]; + if (usuario2 != null) + { + nome1 = usuario2.get_Nome(); + } + else + { + nome1 = null; + } + if (nome1 == null) + { + nome1 = "TODOS USUÁRIOS"; + } + objArray1[0] = nome1; + num2 = (usuario2 != null ? usuario2.get_Id() : (long)0); + objArray1[1] = num2; + if (seguradora2 != null) + { + nome2 = seguradora2.get_Nome(); + } + else + { + nome2 = null; + } + if (nome2 == null) + { + nome2 = "TODAS AS SEGURADORAS"; + } + objArray1[2] = nome2; + num3 = (seguradora2 != null ? seguradora2.get_Id() : (long)0); + objArray1[3] = num3; + obj3 = (this.Criticado ? "SIM" : "NÃO"); + objArray1[4] = obj3; + objArray1[5] = ValidationHelper.Join(this.PesquisaCritica, ", "); + obj2 = string.Format("USUÁRIO IMPORTAÇÃO: {0} ({1})\nSEGURADORA: {2} ({3})\nCRITICADOS: {4}\nPESQUISA PERSONALIZADA: \"{5}\"", objArray1); + } + criticaApoliceViewModel1.RegistrarAcao(str, num4, nullable, obj2); + this.EnableGrid = true; + } + } + + public async Task CarregarSeguradoras() + { + this.IsLoading = true; + List list = await this._criticaServico.BuscarSeguradorasAsync(); + List seguradoras = list; + list = ( + from x in seguradoras + orderby x.get_Nome() + select x).ToList(); + Seguradora seguradora = new Seguradora(); + seguradora.set_Id((long)0); + seguradora.set_Nome("TODAS AS SEGURADORAS"); + seguradora.set_Ativo(true); + list.Insert(0, seguradora); + CriticaApoliceViewModel observableCollection = this; + List seguradoras1 = list; + observableCollection.SeguradorasFiltro = new ObservableCollection( + from x in seguradoras1 + where x.get_Ativo() + select x); + this.SelectedSeguradora = this.SeguradorasFiltro.FirstOrDefault(); + this.IsLoading = false; + } + + public async Task CarregarUsuarios(long selected = 0L, bool criticado = false) + { + bool count; + this.IsLoading = true; + this.Criticado = criticado; + List usuarios = new List(); + List vinculos = this.Vinculos; + if (vinculos != null) + { + count = vinculos.Count > 0; + } + else + { + count = false; + } + if (!count) + { + usuarios = await this._criticaServico.BuscarUsuarioCritica(this.Inicio, this.Fim, this.Criticado); + Usuario usuario = new Usuario(); + usuario.set_Id((long)0); + usuario.set_Nome("TODOS OS USUÁRIOS"); + usuarios.Insert(0, usuario); + } + else + { + Usuario usuario1 = new Usuario(); + usuario1.set_Id(Recursos.Usuario.get_Id()); + usuario1.set_Nome(Recursos.Usuario.get_Nome()); + usuarios.Insert(0, usuario1); + } + this.Usuarios = new ObservableCollection(usuarios); + CriticaApoliceViewModel criticaApoliceViewModel = this; + Usuario usuario2 = this.Usuarios.FirstOrDefault((Usuario x) => x.get_Id() == selected); + if (usuario2 == null) + { + usuario2 = this.Usuarios.FirstOrDefault(); + } + criticaApoliceViewModel.SelectedUsuario = usuario2; + this.IsLoading = false; + } + + public async Task ConcluirCritica() + { + List criticaApolices; + string str; + string descricao; + DateTime networkTime = Funcoes.GetNetworkTime(); + this.SelectedCritica.set_Critica(new bool?(true)); + this.SelectedCritica.set_DataCritica(new DateTime?(networkTime)); + this.SelectedCritica.set_UsuarioCritica(new long?(Recursos.Usuario.get_Id())); + foreach (CriticaApolice criticaApolouse in await this._criticaServico.BuscarCritica(this.SelectedCritica.get_Documento().get_Id())) + { + criticaApolouse.set_Critica(new bool?(true)); + criticaApolouse.set_DataCritica(new DateTime?(networkTime)); + criticaApolouse.set_UsuarioCritica(new long?(Recursos.Usuario.get_Id())); + await this._criticaServico.Save(criticaApolouse); + } + if (this.SeguroCombinado) + { + List list = ((IEnumerable)await this._criticaServico.BuscarSeguroCombinado(this.SelectedCritica.get_Documento().get_Controle().get_Cliente().get_Id(), this.SelectedCritica.get_Documento().get_Vigencia1())).Where((CriticaApolice duo) => { + if (duo.get_Documento().get_Controle().get_Seguradora().get_Id() == this.SelectedCritica.get_Documento().get_Controle().get_Seguradora().get_Id() && duo.get_Documento().get_Controle().get_Cliente().get_Id() == this.SelectedCritica.get_Documento().get_Controle().get_Cliente().get_Id() && duo.get_Documento().get_Vigencia1() == this.SelectedCritica.get_Documento().get_Vigencia1()) + { + DateTime? vigencia2 = duo.get_Documento().get_Vigencia2(); + DateTime? nullable = this.SelectedCritica.get_Documento().get_Vigencia2(); + if ((vigencia2.HasValue == nullable.HasValue ? (vigencia2.HasValue ? vigencia2.GetValueOrDefault() == nullable.GetValueOrDefault() : true) : false) && duo.get_Documento().get_Id() != this.SelectedCritica.get_Documento().get_Id() && duo.get_Documento().get_Apolice() == this.SelectedCritica.get_Documento().get_Apolice() && duo.get_Documento().get_Proposta() == null) + { + return true; + } + } + return Regex.Replace(duo.get_Documento().get_Proposta(), "[^.'-,/]", "") == Regex.Replace(this.SelectedCritica.get_Documento().get_Proposta(), "[^.'-,/]", ""); + }).ToList(); + if (list == null || list.Count() <= 0) + { + criticaApolices = null; + } + else + { + criticaApolices = await this._criticaServico.BuscarCritica(list.FirstOrDefault().get_Documento().get_Id()); + } + list = criticaApolices; + if (list != null && list.Any()) + { + foreach (CriticaApolice criticaApolouse1 in list) + { + criticaApolouse1.set_Critica(new bool?(true)); + criticaApolouse1.set_DataCritica(new DateTime?(networkTime)); + criticaApolouse1.get_Documento().set_PremioLiquido(new decimal(1, 0, 0, false, 2)); + criticaApolouse1.get_Documento().set_PremioTotal(new decimal(1, 0, 0, false, 2)); + criticaApolouse1.get_Documento().set_Comissao(new decimal(1, 0, 0, false, 2)); + criticaApolouse1.set_UsuarioCritica(new long?(Recursos.Usuario.get_Id())); + await this._criticaServico.Save(criticaApolouse1); + await this.Servico.Save(criticaApolouse1.get_Documento(), false, false); + } + } + } + if (this.SelectedCritica.get_Tipo() == "0") + { + str = string.Concat("A PROPOSTA \"", this.CancelDocumento.get_Proposta(), "\""); + } + else + { + str = (this.SelectedCritica.get_Tipo() == "1" ? string.Concat("A APÓLICE \"", this.CancelDocumento.get_Apolice(), "\"") : string.Concat("O ENDOSSO \"", this.CancelDocumento.get_Endosso(), "\"")); + } + string str1 = str; + base.RegistrarAcao(string.Concat("CONCLUIU A CRÍTICA D", str1), this.SelectedCritica.get_Id(), new TipoTela?(20), null); + if (this.Itens == null) + { + descricao = ""; + } + else if (this.Itens.Count > 1) + { + descricao = "APÓLICE COLETIVA"; + } + else + { + Item item = this.Itens.FirstOrDefault(); + if (item != null) + { + descricao = item.get_Descricao(); + } + else + { + descricao = null; + } + } + string str2 = descricao; + try + { + if (string.IsNullOrEmpty(base.SelectedDocumento.get_Controle().get_AssistenciaId())) + { + await base.CreateLinkAssistencia(base.SelectedDocumento, str2, false); + } + } + catch (Exception exception) + { + } + base.SelectedDocumento = null; + this.SelectedCliente = null; + this.Telefones = null; + this.Emails = null; + this.Itens = null; + await this.CarregaCritica(this.SelectedUsuario.get_Id(), this.SelectedSeguradora.get_Id(), this.Criticado); + } + + public async void ExcluirEmail(ClienteEmail email) + { + if (this.Emails.Count >= 2) + { + this.HasChange = true; + int? nullable = email.get_Ordem(); + int count = this.Emails.Count; + int count1 = this.Emails.Count; + this.Emails.Remove(email); + if (!(nullable.GetValueOrDefault() == count & nullable.HasValue)) + { + if (this.Emails.FirstOrDefault((ClienteEmail x) => { + int? ordem = x.get_Ordem(); + int num = count1; + return ordem.GetValueOrDefault() == num & ordem.HasValue; + }) != null) + { + this.Emails.First((ClienteEmail x) => { + int? ordem = x.get_Ordem(); + int num = count1; + return ordem.GetValueOrDefault() == num & ordem.HasValue; + }).set_Ordem(email.get_Ordem()); + CriticaApoliceViewModel observableCollection = this; + ObservableCollection emails = this.Emails; + observableCollection.Emails = new ObservableCollection( + from x in emails + orderby x.get_Ordem() + select x); + } + } + } + else + { + await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM CONTATO DE E-MAIL CADASTRADO.", "OK", "", false); + } + } + + public async void ExcluirTelefone(ClienteTelefone telefone) + { + if (this.Telefones.Count >= 2) + { + this.HasChange = true; + int? nullable = telefone.get_Ordem(); + int count = this.Telefones.Count; + int count1 = this.Telefones.Count; + this.Telefones.Remove(telefone); + if (!(nullable.GetValueOrDefault() == count & nullable.HasValue)) + { + if (this.Telefones.FirstOrDefault((ClienteTelefone x) => { + int? ordem = x.get_Ordem(); + int num = count1; + return ordem.GetValueOrDefault() == num & ordem.HasValue; + }) != null) + { + this.Telefones.First((ClienteTelefone x) => { + int? ordem = x.get_Ordem(); + int num = count1; + return ordem.GetValueOrDefault() == num & ordem.HasValue; + }).set_Ordem(telefone.get_Ordem()); + CriticaApoliceViewModel observableCollection = this; + ObservableCollection telefones = this.Telefones; + observableCollection.Telefones = new ObservableCollection( + from x in telefones + orderby x.get_Ordem() + select x); + } + } + } + else + { + await base.ShowMessage("É NECESSÁRIO TER AO MENOS UM TELEFONE CADASTRADO.", "OK", "", false); + } + } + + public async Task InitialLoad() + { + long id; + this.IsLoading = true; + base.Loading(true); + await base.PermissaoTela(2); + await this.SelecionaUsuario(); + await this.CarregarUsuarios((long)0, false); + await this.CarregarSeguradoras(); + CriticaApoliceViewModel criticaApoliceViewModel = this; + Usuario selectedUsuario = this.SelectedUsuario; + if (selectedUsuario != null) + { + id = selectedUsuario.get_Id(); + } + else + { + id = (long)0; + } + await criticaApoliceViewModel.CarregaCritica(id, (long)0, false); + base.Loading(false); + this.IsLoading = false; + } + + public void JuridicaouFisica(string documento) + { + if (this.SelectedCliente == null) + { + return; + } + this.ProfissaoText = ""; + this.AtividadeText = ""; + if (documento != null && ValidationHelper.OnlyNumber(documento).Length <= 11) + { + this.VisibilityJuridica = Visibility.Collapsed; + this.VisibilityFisica = Visibility.Visible; + this.FieldNascimento = "NASCIMENTO"; + this.FieldDocumento = "CPF"; + this.SelectedCliente.set_Atividade(null); + return; + } + this.VisibilityJuridica = Visibility.Visible; + this.VisibilityFisica = Visibility.Collapsed; + this.FieldNascimento = "FUNDAÇÃO"; + this.FieldDocumento = "CNPJ"; + this.SelectedCliente.set_Profissao(null); + } + + public async void Pesquisar() + { + this.EnableGrid = false; + if (this.PesquisaCritica == null || this.PesquisaCritica.Count == 0) + { + this.CriticaFiltrada = new ObservableCollection(this.Criticas); + } + else + { + CriticaApoliceViewModel observableCollection = this; + IEnumerable criticaApolices = this.Criticas.Where((CriticaApolice x) => { + Func func2 = null; + return this.PesquisaCritica.All((string s) => { + List list = s.Split(new char[] { '+' }).ToList(); + Func u003cu003e9_1484 = CriticaApoliceViewModel.u003cu003ec.u003cu003e9__148_4; + if (u003cu003e9_1484 == null) + { + u003cu003e9_1484 = (string f) => !string.IsNullOrWhiteSpace(f); + CriticaApoliceViewModel.u003cu003ec.u003cu003e9__148_4 = u003cu003e9_1484; + } + IEnumerable strs = list.Where(u003cu003e9_1484); + Func u003cu003e9_5 = func2; + if (u003cu003e9_5 == null) + { + Func func = (string f) => { + if (ValidationHelper.RemoveDiacritics(x.get_Documento().get_Controle().get_Cliente().get_Nome()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(f)) || x.get_Documento().get_Controle().get_Cliente().get_Documento() != null && x.get_Documento().get_Controle().get_Cliente().get_Documento().Contains(f) || x.get_Documento().get_Controle().get_Cliente().get_Cei() != null && x.get_Documento().get_Controle().get_Cliente().get_Cei().Contains(f) || x.get_Documento().get_Controle().get_Cliente().get_Rne() != null && x.get_Documento().get_Controle().get_Cliente().get_Rne().Contains(f) || x.get_UsuarioImportacao() != null && x.get_UsuarioImportacao().get_Nome().Contains(f) || x.get_DataImportacao().HasValue && x.get_DataImportacao().ToString().Contains(f) || x.get_Documento().get_Apolice() != null && x.get_Documento().get_Apolice().ToUpper().Contains(f.ToUpper())) + { + return true; + } + if (x.get_Documento().get_Proposta() == null) + { + return false; + } + return x.get_Documento().get_Proposta().ToUpper().Contains(f.ToUpper()); + }; + Func func1 = func; + func2 = func; + u003cu003e9_5 = func1; + } + return strs.Any(u003cu003e9_5); + }); + }); + IOrderedEnumerable dataImportacao = + from x in criticaApolices + orderby x.get_DataImportacao() + select x; + observableCollection.CriticaFiltrada = new ObservableCollection(dataImportacao.ThenByDescending((CriticaApolice x) => x.get_Documento().get_Controle().get_Cliente().get_Nome())); + } + await this.SelecionaCritica(this.CriticaFiltrada.FirstOrDefault()); + this.EnableGrid = true; + } + + public async Task>> SalvarCliente() + { + List> keyValuePairs; + List> keyValuePairs1; + Cliente cliente; + CriticaApoliceViewModel.u003cu003ec__DisplayClass132_0 variable; + List> keyValuePairs2; + List> keyValuePairs3; + if (!this.HasChange && !this.SelectedCliente.HasChange()) + { + ObservableCollection telefones = this.Telefones; + if (telefones.All((ClienteTelefone x) => !x.HasChange())) + { + ObservableCollection emails = this.Emails; + if (emails.All((ClienteEmail x) => !x.HasChange())) + { + keyValuePairs = null; + variable = null; + return keyValuePairs; + } + } + } + ObservableCollection observableCollection = this.Telefones; + List list = ( + from x in observableCollection + where !string.IsNullOrEmpty(x.get_Numero()) + select x).ToList(); + ObservableCollection emails1 = this.Emails; + List clienteEmails = ( + from x in emails1 + where !string.IsNullOrEmpty(x.get_Email()) + select x).ToList(); + this.SelectedCliente.set_Telefones(new ObservableCollection(list)); + this.SelectedCliente.set_Emails(new ObservableCollection(clienteEmails)); + TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + TipoDocumento valueOrDefault = documentoPrincipal.GetValueOrDefault(); + if (valueOrDefault == 1) + { + this.SelectedCliente.set_Rne(this.DocumentoPrincipal); + keyValuePairs3 = this.SelectedCliente.Validate(); + list.ForEach((ClienteTelefone x) => keyValuePairs3.AddRange(x.Validate())); + clienteEmails.ForEach((ClienteEmail x) => keyValuePairs3.AddRange(x.Validate())); + keyValuePairs2 = keyValuePairs3; + keyValuePairs1 = await this.Validate(); + keyValuePairs2.AddRange(keyValuePairs1); + keyValuePairs2 = null; + if (keyValuePairs3.Count <= 0) + { + cliente = await this._clienteServico.Save(this.SelectedCliente, false); + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs3; + } + variable = null; + return keyValuePairs; + } + else + { + if (valueOrDefault != 2) + { + goto Label2; + } + this.SelectedCliente.set_Cei(this.DocumentoPrincipal); + keyValuePairs3 = this.SelectedCliente.Validate(); + list.ForEach((ClienteTelefone x) => keyValuePairs3.AddRange(x.Validate())); + clienteEmails.ForEach((ClienteEmail x) => keyValuePairs3.AddRange(x.Validate())); + keyValuePairs2 = keyValuePairs3; + keyValuePairs1 = await this.Validate(); + keyValuePairs2.AddRange(keyValuePairs1); + keyValuePairs2 = null; + if (keyValuePairs3.Count <= 0) + { + cliente = await this._clienteServico.Save(this.SelectedCliente, false); + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs3; + } + variable = null; + return keyValuePairs; + } + } + Label2: + this.SelectedCliente.set_Documento(this.DocumentoPrincipal); + keyValuePairs3 = this.SelectedCliente.Validate(); + list.ForEach((ClienteTelefone x) => keyValuePairs3.AddRange(x.Validate())); + clienteEmails.ForEach((ClienteEmail x) => keyValuePairs3.AddRange(x.Validate())); + keyValuePairs2 = keyValuePairs3; + keyValuePairs1 = await this.Validate(); + keyValuePairs2.AddRange(keyValuePairs1); + keyValuePairs2 = null; + if (keyValuePairs3.Count <= 0) + { + cliente = await this._clienteServico.Save(this.SelectedCliente, false); + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs3; + } + variable = null; + return keyValuePairs; + } + + public async Task SelecionaCliente(Cliente cliente) + { + DateTime? nullable; + TipoDocumento? documentoPrincipal = cliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + TipoDocumento valueOrDefault = documentoPrincipal.GetValueOrDefault(); + if (valueOrDefault == 1) + { + this.DocumentoPrincipal = cliente.get_Rne(); + goto Label0; + } + else + { + if (valueOrDefault != 2) + { + goto Label1; + } + this.DocumentoPrincipal = cliente.get_Cei(); + goto Label0; + } + } + Label1: + this.DocumentoPrincipal = cliente.get_Documento(); + cliente.set_DocumentoPrincipal(new TipoDocumento?(0)); + Label0: + CriticaApoliceViewModel criticaApoliceViewModel = this; + nullable = (cliente == null || !cliente.get_Nascimento().HasValue ? new DateTime?(Funcoes.GetNetworkTime().Date) : cliente.get_Nascimento()); + criticaApoliceViewModel.NascimentoCritica = nullable; + this.SelectedCliente = cliente; + this.SelectedCliente.Initialize(); + this.Telefones = await this._clienteServico.BuscarTelefonesAsync(this.SelectedCliente.get_Id()); + if (this.Telefones.Count == 0) + { + ObservableCollection telefones = this.Telefones; + ClienteTelefone clienteTelefone = new ClienteTelefone(); + clienteTelefone.set_Cliente(this.SelectedCliente); + telefones.Add(clienteTelefone); + } + List list = this.Telefones.ToList(); + list.ForEach((ClienteTelefone x) => x.Initialize()); + this.Emails = await this._clienteServico.BuscarEmailsAsync(this.SelectedCliente.get_Id()); + if (this.Emails.Count == 0) + { + ObservableCollection emails = this.Emails; + ClienteEmail clienteEmail = new ClienteEmail(); + clienteEmail.set_Cliente(this.SelectedCliente); + emails.Add(clienteEmail); + } + List clienteEmails = this.Emails.ToList(); + clienteEmails.ForEach((ClienteEmail x) => x.Initialize()); + } + + public async Task SelecionaCritica(CriticaApolice critica) + { + DateTime networkTime; + DateTime? nullable; + DateTime? remessa; + TipoSeguro? nullable1; + if (critica != null && !this.IsLoading) + { + this.IsLoading = true; + base.Loading(true); + CriticaApolice criticaApolouse = critica; + Documento documento = await this.Servico.BuscarApoliceAsync(critica.get_Documento().get_Id(), false, false); + criticaApolouse.set_Documento(documento); + criticaApolouse = null; + base.SelectedDocumento = null; + base.Repasses = null; + base.Parcelas = null; + base.Pagamentos = null; + base.SelectedParcela = null; + base.SelectedPagamento = null; + this.SelectedCritica = critica; + await base.SelecionaDocumento(critica.get_Documento()); + CriticaApoliceViewModel criticaApoliceViewModel = this; + if (critica.get_Documento() == null || !critica.get_Documento().get_Emissao().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + nullable = new DateTime?(networkTime.Date); + } + else + { + nullable = critica.get_Documento().get_Emissao(); + } + criticaApoliceViewModel.EmissaoCritica = nullable; + CriticaApoliceViewModel criticaApoliceViewModel1 = this; + if (critica.get_Documento() == null || !critica.get_Documento().get_Remessa().HasValue) + { + networkTime = Funcoes.GetNetworkTime(); + remessa = new DateTime?(networkTime.Date); + } + else + { + remessa = critica.get_Documento().get_Remessa(); + } + criticaApoliceViewModel1.TransmissaoCritica = remessa; + CriticaApoliceViewModel criticaApoliceViewModel2 = this; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 3)) + { + nullable1 = new TipoSeguro?(base.SelectedDocumento.get_Situacao()); + } + else + { + nullable1 = null; + } + criticaApoliceViewModel2.StatusDocumento = nullable1; + if (base.SelectedDocumento != null) + { + TipoRecebimento? tipoRecebimento = base.SelectedDocumento.get_TipoRecebimento(); + this.IsParcela = tipoRecebimento.GetValueOrDefault() == 1; + await this.SelecionaCliente(base.SelectedDocumento.get_Controle().get_Cliente()); + await this.SelecionaItens(base.SelectedDocumento.get_Controle().get_Id()); + this.HasChange = false; + base.Loading(false); + this.IsLoading = false; + } + else + { + this.IsParcela = true; + this.HasChange = false; + base.Loading(false); + } + } + } + + public async Task SelecionaItens(long id) + { + this.Itens = await this._itemServico.BuscarItens(id, 0); + } + + public async Task SelecionaUsuario() + { + this.IsLoading = true; + List configuracoes = Recursos.Configuracoes; + if (configuracoes.Any((ConfiguracaoSistema x) => { + if (x.get_Configuracao() == 38) + { + return true; + } + return x.get_Configuracao() == 43; + }) && Recursos.Usuario.get_Id() != 0) + { + this.Vinculos = await base.VerificaVinculoVendedor(Recursos.Usuario); + } + this.IsLoading = false; + } + + private async Task>> Validate() + { + List clientes; + List> keyValuePairs = new List>(); + bool flag = !string.IsNullOrEmpty(this.SelectedCliente.get_Nome()); + TipoDocumento? documentoPrincipal = this.SelectedCliente.get_DocumentoPrincipal(); + if (documentoPrincipal.HasValue) + { + switch (documentoPrincipal.GetValueOrDefault()) + { + case 0: + { + if (ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) + { + break; + } + flag = false; + break; + } + case 1: + { + if (ValidationHelper.ValidateRne(this.SelectedCliente.get_Rne())) + { + break; + } + flag = false; + break; + } + case 2: + { + if (ValidationHelper.ValidateCei(this.SelectedCliente.get_Cei())) + { + break; + } + flag = false; + break; + } + } + } + if (!ValidationHelper.ValidateDocument(this.SelectedCliente.get_Documento())) + { + clientes = new List(); + } + else + { + clientes = await (new ClienteServico()).BuscarClientePorDocumento(this.SelectedCliente.get_Documento()); + } + List clientes1 = clientes; + string nome = ""; + if (clientes1.Count > 0) + { + clientes1.ForEach((Cliente x) => { + if (x.get_Id() == this.SelectedCliente.get_Id()) + { + return; + } + if (this.SelectedCliente.get_IdEmpresa() != x.get_IdEmpresa()) + { + return; + } + if (!string.IsNullOrEmpty(this.SelectedCliente.get_Documento()) && x.get_Documento() == this.SelectedCliente.get_Documento()) + { + flag = false; + nome = x.get_Nome(); + } + }); + } + if (!flag) + { + keyValuePairs.Add(new KeyValuePair("Documento", string.Concat("O DOCUMENTO JÁ ESTÁ CADASTRADO PARA O CLIENTE ", nome, "."))); + } + if (this.SelectedCliente.get_Telefones() == null || this.SelectedCliente.get_Telefones().Count == 0) + { + keyValuePairs.Add(new KeyValuePair("Telefones", "NECESSITA-SE AO MENOS UM TELEFONE VÁLIDO.")); + } + List configuracoes = Recursos.Configuracoes; + if (configuracoes.All((ConfiguracaoSistema x) => x.get_Configuracao() != 29) && (this.SelectedCliente.get_Emails() == null || this.SelectedCliente.get_Emails().Count == 0)) + { + keyValuePairs.Add(new KeyValuePair("Emails", "NECESSITA-SE AO MENOS UM E-MAIL VÁLIDO.")); + } + List> keyValuePairs1 = keyValuePairs; + keyValuePairs = null; + return keyValuePairs1; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AeronauticoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AeronauticoViewModel.cs new file mode 100644 index 0000000..ded661f --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AeronauticoViewModel.cs @@ -0,0 +1,554 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class AeronauticoViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly AeronauticoServico _servico; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + private bool _aero = true; + + private string _serie = "REGISTRO"; + + private string _prefixo = "PREFIXO"; + + private string _marinaAero = "AERÓDROMO"; + + public bool Aero + { + get + { + return this._aero; + } + set + { + this._aero = value; + base.OnPropertyChanged("Aero"); + } + } + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + set; + } + + public string MarinaAero + { + get + { + return this._marinaAero; + } + set + { + this._marinaAero = value; + base.OnPropertyChanged("MarinaAero"); + } + } + + public string Prefixo + { + get + { + return this._prefixo; + } + set + { + this._prefixo = value; + base.OnPropertyChanged("Prefixo"); + } + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public string Serie + { + get + { + return this._serie; + } + set + { + this._serie = value; + base.OnPropertyChanged("Serie"); + } + } + + public AeronauticoViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new AeronauticoServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + Item item2 = item; + Aeronautico aeronautico = new Aeronautico(); + aeronautico.set_Tipo(1); + item2.set_Aeronautico(aeronautico); + Item item3 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item3.set_Substituicao(nullable); + Item item4 = item; + item1 = null; + item = null; + ordem = item4.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item4 = null; + return; + } + } + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item4; + this.SelectedItem.get_Aeronautico().set_Item(item4); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item4.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item4 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Aeronautico().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + string str2; + string str3; + this.SelectedItem.set_Descricao(string.Format("{0} - FABRICANTE: {1} - MODELO: {2}", this.SelectedItem.get_Aeronautico().get_Tipo(), this.SelectedItem.get_Aeronautico().get_Fabricante(), this.SelectedItem.get_Aeronautico().get_Modelo())); + List> keyValuePairs1 = this.SelectedItem.Validate(); + if (keyValuePairs1.Count <= 0) + { + Item selectedItem = this.SelectedItem; + selectedItem.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + selectedItem = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str = ""; + } + else if (base.Mantido) + { + str = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str4 = str; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str4); + } + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str1; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str2 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str5 = str2; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str5); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str6 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str6, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + List nums = new List() + { + (long)13 + }; + if (nums.Contains(this.Ramo.get_Id())) + { + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Aeronautico aeronautico = await this._itemServico.BuscaAeronautico(item.get_Id()); + item1.set_Aeronautico(aeronautico); + item1 = null; + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + + public void UpdateAero() + { + this.Aero = ValidationHelper.GetCategory(this.SelectedItem.get_Aeronautico().get_Tipo()) == "Aero"; + this.Serie = (this.Aero ? "REGISTRO" : "SÉRIE"); + this.Prefixo = (this.Aero ? "PREFIXO" : "NOME"); + this.MarinaAero = (this.Aero ? "AERÓDROMO" : "MARINA"); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AutoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AutoViewModel.cs new file mode 100644 index 0000000..735d4a7 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/AutoViewModel.cs @@ -0,0 +1,3018 @@ +using ClosedXML.Excel; +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Microsoft.CSharp.RuntimeBinder; +using Microsoft.Office.Interop.Excel; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Data; +using System.Diagnostics; +using System.Globalization; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; +using System.Windows.Forms; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class AutoViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly AutoServico _servico; + + private bool _allowAlterarExcluir = true; + + private Visibility _isVisiblePorcentagemReferencia = Visibility.Collapsed; + + private Visibility _isVisibleValorDeterminado = Visibility.Collapsed; + + private object _cobertura; + + private List _combustivel = ((Gestor.Model.Common.Combustivel[])Enum.GetValues(typeof(Gestor.Model.Common.Combustivel))).OrderBy(new Func((Gestor.Model.Common.Combustivel x) => Gestor.Common.Validation.ValidationHelper.GetCategory(x))).ToList(); + + private Item _selectedItem = new Item(); + + private List _fabricantes; + + private Fabricante _selectedFabricante; + + private string _codigoItem; + + private Gestor.Model.Common.Categoria? _categocia; + + private Gestor.Model.Common.UsoVeiculo? _usoVeiculo; + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public Gestor.Model.Common.Categoria? Categoria + { + get + { + return this._categocia; + } + set + { + bool auto; + this._categocia = value; + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + auto = selectedItem.get_Auto(); + } + else + { + auto = false; + } + if (auto) + { + this.SelectedItem.get_Auto().set_Categoria(value); + } + base.OnPropertyChanged("Categoria"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public List Combustivel + { + get + { + return this._combustivel; + } + set + { + this._combustivel = value; + base.OnPropertyChanged("Combustivel"); + } + } + + public List Fabricantes + { + get + { + return this._fabricantes; + } + set + { + this._fabricantes = value; + base.OnPropertyChanged("Fabricantes"); + } + } + + public bool Invoke + { + get; + set; + } + + public Visibility IsVisiblePorcentagemReferencia + { + get + { + return this._isVisiblePorcentagemReferencia; + } + set + { + this._isVisiblePorcentagemReferencia = value; + base.OnPropertyChanged("IsVisiblePorcentagemReferencia"); + } + } + + public Visibility IsVisibleValorDeterminado + { + get + { + return this._isVisibleValorDeterminado; + } + set + { + this._isVisibleValorDeterminado = value; + base.OnPropertyChanged("IsVisibleValorDeterminado"); + } + } + + private Item ItemSelecionado + { + get; + set; + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Fabricante SelectedFabricante + { + get + { + return this._selectedFabricante; + } + set + { + this._selectedFabricante = value; + base.OnPropertyChanged("SelectedFabricante"); + } + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public Gestor.Model.Common.UsoVeiculo? UsoVeiculo + { + get + { + return this._usoVeiculo; + } + set + { + bool auto; + if (value.GetValueOrDefault() == 2 || value.GetValueOrDefault() == 3) + { + this.SelectedItem.get_Auto().set_Categoria(new Gestor.Model.Common.Categoria?(3)); + this.Categoria = new Gestor.Model.Common.Categoria?(3); + } + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + auto = selectedItem.get_Auto(); + } + else + { + auto = false; + } + if (auto && value.HasValue) + { + this.SelectedItem.get_Auto().set_UsoVeiculo(value); + } + this._usoVeiculo = value; + base.OnPropertyChanged("UsoVeiculo"); + } + } + + public AutoViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new AutoServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + } + + public void Atualiza(string valorSelecionado) + { + if (valorSelecionado == "MERCADO") + { + this.IsVisiblePorcentagemReferencia = Visibility.Visible; + this.IsVisibleValorDeterminado = Visibility.Collapsed; + return; + } + this.IsVisiblePorcentagemReferencia = Visibility.Collapsed; + this.IsVisibleValorDeterminado = Visibility.Visible; + } + + public async void BaixarXls() + { + char chr; + object obj; + object obj1; + object obj2; + object obj3; + object obj4; + object obj5; + object obj6; + object obj7; + object obj8; + object obj9; + object obj10; + object obj11; + object obj12; + object obj13; + object obj14; + object obj15; + object obj16; + object obj17; + object obj18; + object obj19; + object obj20; + object obj21; + object obj22; + object obj23; + object obj24; + object obj25; + object obj26; + object obj27; + object obj28; + object obj29; + object obj30; + object obj31; + object obj32; + object obj33; + object obj34; + object obj35; + object obj36; + object obj37; + object obj38; + object obj39; + object obj40; + object obj41; + object obj42; + object obj43; + object obj44; + object obj45; + object obj46; + object obj47; + object obj48; + object obj49; + object obj50; + object obj51; + object obj52; + object obj53; + object obj54; + object obj55; + object obj56; + object obj57; + object obj58; + object obj59; + object obj60; + object obj61; + object obj62; + object obj63; + object obj64; + object obj65; + object obj66; + object obj67; + object obj68; + object obj69; + object obj70; + object obj71; + object obj72; + using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog()) + { + folderBrowserDialog.SelectedPath = Environment.SpecialFolder.Desktop.ToString(); + if (folderBrowserDialog.ShowDialog() == DialogResult.OK && !string.IsNullOrWhiteSpace(folderBrowserDialog.SelectedPath)) + { + XLWorkbook xLWorkbook = new XLWorkbook(); + DataTable dataTable = new DataTable(); + List strs = new List() + { + "placa", + "fabricante", + "modelo", + "fipe", + "chassi", + "anofabricacao", + "anomodelo", + "cor", + "categoria", + "combustivel", + "zerokm", + "renavam", + "capacidade", + "portas", + "bonus", + "ceppernoite", + "ci", + "financiado", + "correcao", + "isencao", + "pcd", + "cepcirculacao", + "tipocobertura", + "porcentagemreferencia", + "tabelareferencia", + "valordeterminado", + "observacao", + "pr casco", + "fr casco", + "lmi casco", + "obs casco", + "pr dm", + "fr dm", + "lmi dm", + "obs dm", + "pr dc", + "fr dc", + "lmi dc", + "obs dc", + "pr morte", + "fr morte", + "lmi morte", + "obs morte", + "pr invalidez", + "fr invalidez", + "lmi invalidez", + "obs invalidez", + "pr carro reserva", + "fr carro reserva", + "lmi carro reserva", + "obs carro reserva", + "pr vidros", + "fr vidros", + "lmi vidros", + "obs vidros", + "pr carroceria", + "fr carroceria", + "lmi carroceria", + "obs carroceria", + "pr Ass 24Horas", + "fr Ass 24Horas", + "lmi Ass 24Horas", + "obs Ass 24Horas", + "pr Danos Morais", + "fr Danos Morais", + "lmi Danos Morais", + "obs Danos Morais", + "pr app", + "fr app", + "lmi app", + "obs app", + "pr equipamentos", + "fr equipamentos", + "lmi equipamentos", + "obs equipamentos" + }; + List strs1 = strs; + List> lists = new List>(); + List strs2 = new List() + { + "XXX0X00", + "FORD", + "MODELO", + "000000-0", + "75F 8C33MP Y2 W12900", + "2000", + "2001", + "PRETO", + "PASSEIO", + "FLEX", + "SIM", + "00000000000", + "5", + "5", + "100", + "00.000-000", + "000000", + "NÃO", + "MERCADO", + "SEM", + "NÃO", + "00.000-000", + "COMPREENSIVA", + "100", + "FIPE", + "", + "OBSERVAÇÕES", + "1000", + "2000", + "3000", + "teste obs", + "", + "", + "", + "", + "2000", + "3000", + "4000", + "teste obs", + "100000", + "200000", + "300000", + "teste obs", + "2000", + "3000", + "4000", + "teste obs", + "", + "", + "", + "", + "1000", + "2000", + "3000", + "teste obs", + "2000", + "3000", + "4000", + "teste obs", + "", + "", + "", + "", + "1000", + "2000", + "3000", + "teste obs", + "", + "", + "", + "", + "2000", + "3000", + "4000", + "teste obs", + "1000", + "2000", + "3000", + "teste obs" + }; + lists.Add(strs2); + List strs3 = new List() + { + "XXX0X01", + "CHEVROLET", + "MODELO", + "000000-1", + "4EL ZBE75H B5 A65693", + "2000", + "2001", + "VERDE", + "PICKUP", + "GASOLINA/ÁLCOOL/GNV", + "NÃO", + "00000000000", + "5", + "2", + "100", + "00.000-000", + "000000", + "SIM", + "DETERMINADO", + "IPI E ICMS", + "NÃO", + "00.000-000", + "INCÊNDIO E ROUBO/FURTO", + "100", + "MOLICAR", + "19767,34", + "OBSERVAÇÕES", + "1000", + "2000", + "3000", + "teste obs", + "", + "", + "", + "", + "2000", + "3000", + "4000", + "teste obs", + "100000", + "200000", + "300000", + "teste obs", + "2000", + "3000", + "4000", + "teste obs", + "", + "", + "", + "", + "1000", + "2000", + "3000", + "teste obs", + "2000", + "3000", + "4000", + "teste obs", + "", + "", + "", + "", + "1000", + "2000", + "3000", + "teste obs", + "", + "", + "", + "", + "2000", + "3000", + "4000", + "teste obs", + "1000", + "2000", + "3000", + "teste obs" + }; + lists.Add(strs3); + List> lists1 = lists; + List strs4 = new List() + { + "BRANCO", + "CINZA", + "PRATA", + "VERMELHO", + "AMARELO", + "OURO", + "LARANJA", + "ROSA", + "VERDE", + "AZUL", + "VINHO", + "MARROM", + "BEGE", + "DOURADO", + "OUTROS" + }; + List strs5 = strs4; + List strs6 = new List() + { + "PICKUP", + "OUTROS", + "PASSEIO", + "CAMINHÃO", + "CAMINHONETE", + "ÔNIBUS", + "UTILITÁRIO", + "CARGA", + "MOTOCICLETA", + "TAXI", + "UBER", + "REBOCADOR", + "REBOQUE/SEMI REBOQUE" + }; + List strs7 = strs6; + List strs8 = new List() + { + "ÁLCOOL", + "GASOLINA", + "DIESEL", + "FLEX", + "GNV", + "OUTROS", + "GASOLINA/GNV", + "GASOLINA/ÁLCOOL/GNV", + "GASOLINA/ELÉTRICO", + "HÍBRIDO", + "ELÉTRICO", + "GASOLINA/ÁLCOOL/ELÉTRICO" + }; + List strs9 = strs8; + List strs10 = new List() + { + "MERCADO", + "DETERMINADO" + }; + List strs11 = new List() + { + "SEM ISENÇÃO", + "ICMS", + "IPI", + "IPI E ICMS" + }; + List strs12 = new List() + { + "COMPREENSIVA", + "INCÊNDIO E ROUBO/FURTO", + "DANOS A TERCEIROS", + "PASSAGEIROS", + "ROUBO/FURTO" + }; + List strs13 = new List() + { + "MOLICAR", + "FIPE" + }; + List strs14 = new List() + { + "SIM", + "NÃO" + }; + foreach (string str in strs1) + { + DataColumn dataColumn = new DataColumn() + { + DataType = Type.GetType("System.String"), + ColumnName = str + }; + dataTable.Columns.Add(dataColumn); + } + foreach (List strs15 in lists1) + { + DataRow item = dataTable.NewRow(); + foreach (string str1 in strs1) + { + item[str1] = strs15[strs1.IndexOf(str1)]; + } + dataTable.Rows.Add(item); + } + xLWorkbook.get_Worksheets().Add(dataTable, "EXEMPLO AUTO EXCEL"); + xLWorkbook.SaveAs(string.Concat(folderBrowserDialog.SelectedPath, "\\EXEMPLO AUTO EXCEL.xlsx")); + xLWorkbook = new XLWorkbook(); + dataTable = new DataTable(); + foreach (string str2 in strs1) + { + DataColumn dataColumn1 = new DataColumn() + { + DataType = Type.GetType("System.String"), + ColumnName = str2 + }; + dataTable.Columns.Add(dataColumn1); + } + foreach (string str3 in strs5) + { + DataRow dataRow = dataTable.NewRow(); + Label2: + foreach (string str4 in strs1) + { + int num = strs5.IndexOf(str3); + if (str4 == null) + { + continue; + } + switch (str4.Length) + { + case 2: + { + if (str4 == "ci") + { + DataRow dataRow1 = dataRow; + string str5 = str4; + obj = (num == 0 ? "000000" : ""); + dataRow1[str5] = obj; + continue; + } + else + { + continue; + } + } + case 3: + { + chr = str4[0]; + if (chr != 'c') + { + if (chr == 'p') + { + if (str4 == "pcd") + { + break; + } + continue; + } + else + { + continue; + } + } + else if (str4 == "cor") + { + DataRow dataRow2 = dataRow; + string str6 = str4; + obj1 = (strs5.Count >= num + 1 ? strs5[num] : ""); + dataRow2[str6] = obj1; + continue; + } + else + { + continue; + } + } + case 4: + { + if (str4 == "fipe") + { + DataRow dataRow3 = dataRow; + string str7 = str4; + obj3 = (num == 0 ? "000000-0" : ""); + dataRow3[str7] = obj3; + continue; + } + else + { + continue; + } + } + case 5: + { + chr = str4[4]; + if (chr > 'c') + { + if (chr != 'm') + { + if (chr != 's') + { + continue; + } + else if (str4 == "bonus") + { + DataRow dataRow4 = dataRow; + string str8 = str4; + obj6 = (num == 0 ? "0" : ""); + dataRow4[str8] = obj6; + continue; + } + else + { + continue; + } + } + else if (str4 == "pr dm") + { + DataRow dataRow5 = dataRow; + string str9 = str4; + obj4 = (num == 0 ? "0" : ""); + dataRow5[str9] = obj4; + continue; + } + else if (str4 == "fr dm") + { + DataRow dataRow6 = dataRow; + string str10 = str4; + obj5 = (num == 0 ? "0" : ""); + dataRow6[str10] = obj5; + continue; + } + else + { + continue; + } + } + else if (chr == 'a') + { + if (str4 == "placa") + { + DataRow dataRow7 = dataRow; + string str11 = str4; + obj7 = (num == 0 ? "XXX0X00" : ""); + dataRow7[str11] = obj7; + continue; + } + else + { + continue; + } + } + else if (chr != 'c') + { + continue; + } + else if (str4 == "pr dc") + { + DataRow dataRow8 = dataRow; + string str12 = str4; + obj8 = (num == 0 ? "0" : ""); + dataRow8[str12] = obj8; + continue; + } + else if (str4 == "fr dc") + { + DataRow dataRow9 = dataRow; + string str13 = str4; + obj9 = (num == 0 ? "0" : ""); + dataRow9[str13] = obj9; + continue; + } + else + { + continue; + } + } + case 6: + { + chr = str4[0]; + if (chr > 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi dm") + { + DataRow dataRow10 = dataRow; + string str14 = str4; + obj10 = (num == 0 ? "0" : ""); + dataRow10[str14] = obj10; + continue; + } + else if (str4 == "lmi dc") + { + DataRow dataRow11 = dataRow; + string str15 = str4; + obj11 = (num == 0 ? "0" : ""); + dataRow11[str15] = obj11; + continue; + } + else + { + continue; + } + } + case 'm': + { + if (str4 == "modelo") + { + DataRow dataRow12 = dataRow; + string str16 = str4; + obj12 = (num == 0 ? "MODELO" : ""); + dataRow12[str16] = obj12; + continue; + } + else + { + continue; + } + } + case 'n': + { + continue; + } + case 'o': + { + if (str4 == "obs dm") + { + DataRow dataRow13 = dataRow; + string str17 = str4; + obj13 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow13[str17] = obj13; + continue; + } + else if (str4 == "obs dc") + { + DataRow dataRow14 = dataRow; + string str18 = str4; + obj14 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow14[str18] = obj14; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "portas") + { + DataRow dataRow15 = dataRow; + string str19 = str4; + obj15 = (num == 0 ? "00" : ""); + dataRow15[str19] = obj15; + continue; + } + else if (str4 == "pr app") + { + DataRow dataRow16 = dataRow; + string str20 = str4; + obj16 = (num == 0 ? "0" : ""); + dataRow16[str20] = obj16; + continue; + } + else + { + continue; + } + } + default: + { + if (chr == 'z') + { + if (str4 == "zerokm") + { + goto Label0; + } + continue; + } + else + { + continue; + } + } + } + } + else if (chr == 'c') + { + if (str4 == "chassi") + { + DataRow dataRow17 = dataRow; + string str21 = str4; + obj17 = (num == 0 ? "XXX XXXXXX XX XXXXXX" : ""); + dataRow17[str21] = obj17; + continue; + } + else + { + continue; + } + } + else if (chr != 'f') + { + continue; + } + else if (str4 == "fr app") + { + DataRow dataRow18 = dataRow; + string str22 = str4; + obj18 = (num == 0 ? "0" : ""); + dataRow18[str22] = obj18; + continue; + } + else + { + continue; + } + break; + } + case 7: + { + chr = str4[0]; + if (chr <= 'l') + { + if (chr == 'i') + { + if (str4 == "isencao") + { + DataRow dataRow19 = dataRow; + string str23 = str4; + obj21 = (strs11.Count >= num + 1 ? strs11[num] : ""); + dataRow19[str23] = obj21; + continue; + } + else + { + continue; + } + } + else if (chr != 'l') + { + continue; + } + else if (str4 == "lmi app") + { + DataRow dataRow20 = dataRow; + string str24 = str4; + obj22 = (num == 0 ? "0" : ""); + dataRow20[str24] = obj22; + continue; + } + else + { + continue; + } + } + else if (chr == 'o') + { + if (str4 == "obs app") + { + DataRow dataRow21 = dataRow; + string str25 = str4; + obj19 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow21[str25] = obj19; + continue; + } + else + { + continue; + } + } + else if (chr != 'r') + { + continue; + } + else if (str4 == "renavam") + { + DataRow dataRow22 = dataRow; + string str26 = str4; + obj20 = (num == 0 ? "00000000000" : ""); + dataRow22[str26] = obj20; + continue; + } + else + { + continue; + } + } + case 8: + { + chr = str4[0]; + if (chr == 'c') + { + if (str4 == "correcao") + { + DataRow dataRow23 = dataRow; + string str27 = str4; + obj23 = (strs10.Count >= num + 1 ? strs10[num] : ""); + dataRow23[str27] = obj23; + continue; + } + else + { + continue; + } + } + else if (chr == 'f') + { + if (str4 == "fr casco") + { + DataRow dataRow24 = dataRow; + string str28 = str4; + obj24 = (num == 0 ? "0" : ""); + dataRow24[str28] = obj24; + continue; + } + else if (str4 == "fr morte") + { + DataRow dataRow25 = dataRow; + string str29 = str4; + obj25 = (num == 0 ? "0" : ""); + dataRow25[str29] = obj25; + continue; + } + else + { + continue; + } + } + else if (chr != 'p') + { + continue; + } + else if (str4 == "pr casco") + { + DataRow dataRow26 = dataRow; + string str30 = str4; + obj26 = (num == 0 ? "0" : ""); + dataRow26[str30] = obj26; + continue; + } + else if (str4 == "pr morte") + { + DataRow dataRow27 = dataRow; + string str31 = str4; + obj27 = (num == 0 ? "0" : ""); + dataRow27[str31] = obj27; + continue; + } + else + { + continue; + } + } + case 9: + { + chr = str4[0]; + if (chr > 'c') + { + if (chr != 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi casco") + { + DataRow dataRow28 = dataRow; + string str32 = str4; + obj29 = (num == 0 ? "0" : ""); + dataRow28[str32] = obj29; + continue; + } + else if (str4 == "lmi morte") + { + DataRow dataRow29 = dataRow; + string str33 = str4; + obj30 = (num == 0 ? "0" : ""); + dataRow29[str33] = obj30; + continue; + } + else + { + continue; + } + } + case 'o': + { + if (str4 == "obs casco") + { + DataRow dataRow30 = dataRow; + string str34 = str4; + obj31 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow30[str34] = obj31; + continue; + } + else if (str4 == "obs morte") + { + DataRow dataRow31 = dataRow; + string str35 = str4; + obj32 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow31[str35] = obj32; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "pr vidros") + { + DataRow dataRow32 = dataRow; + string str36 = str4; + obj33 = (num == 0 ? "0" : ""); + dataRow32[str36] = obj33; + continue; + } + else + { + continue; + } + } + default: + { + continue; + } + } + } + else if (str4 == "fr vidros") + { + DataRow dataRow33 = dataRow; + string str37 = str4; + obj28 = (num == 0 ? "0" : ""); + dataRow33[str37] = obj28; + continue; + } + else + { + continue; + } + } + else if (chr == 'a') + { + if (str4 == "anomodelo") + { + DataRow dataRow34 = dataRow; + string str38 = str4; + obj34 = (num == 0 ? "0000" : ""); + dataRow34[str38] = obj34; + continue; + } + else + { + continue; + } + } + else if (chr != 'c') + { + continue; + } + else if (str4 == "categoria") + { + DataRow dataRow35 = dataRow; + string str39 = str4; + obj35 = (strs7.Count >= num + 1 ? strs7[num] : ""); + dataRow35[str39] = obj35; + continue; + } + else + { + continue; + } + break; + } + case 10: + { + chr = str4[2]; + if (chr <= 'i') + { + if (chr == 'b') + { + if (str4 == "fabricante") + { + DataRow dataRow36 = dataRow; + string str40 = str4; + obj39 = (num == 0 ? "FABRICANTE" : ""); + dataRow36[str40] = obj39; + continue; + } + else + { + continue; + } + } + else if (chr != 'i') + { + continue; + } + else if (str4 == "lmi vidros") + { + DataRow dataRow37 = dataRow; + string str41 = str4; + obj40 = (num == 0 ? "0" : ""); + dataRow37[str41] = obj40; + continue; + } + else + { + continue; + } + } + else if (chr == 'n') + { + if (str4 == "financiado") + { + break; + } + continue; + } + else if (chr == 'p') + { + if (str4 == "capacidade") + { + DataRow dataRow38 = dataRow; + string str42 = str4; + obj36 = (num == 0 ? "000" : ""); + dataRow38[str42] = obj36; + continue; + } + else + { + continue; + } + } + else if (chr != 's') + { + continue; + } + else if (str4 == "observacao") + { + DataRow dataRow39 = dataRow; + string str43 = str4; + obj37 = (num == 0 ? "OBSERVAÇÕES" : ""); + dataRow39[str43] = obj37; + continue; + } + else if (str4 == "obs vidros") + { + DataRow dataRow40 = dataRow; + string str44 = str4; + obj38 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow40[str44] = obj38; + continue; + } + else + { + continue; + } + } + case 11: + { + chr = str4[1]; + if (chr == 'e') + { + if (str4 == "ceppernoite") + { + DataRow dataRow41 = dataRow; + string str45 = str4; + obj41 = (num == 0 ? "00.000-000" : ""); + dataRow41[str45] = obj41; + continue; + } + else + { + continue; + } + } + else if (chr != 'o') + { + continue; + } + else if (str4 == "combustivel") + { + DataRow dataRow42 = dataRow; + string str46 = str4; + obj42 = (strs9.Count >= num + 1 ? strs9[num] : ""); + dataRow42[str46] = obj42; + continue; + } + else + { + continue; + } + } + case 12: + { + chr = str4[0]; + if (chr == 'f') + { + if (str4 == "fr invalidez") + { + DataRow dataRow43 = dataRow; + string str47 = str4; + obj43 = (num == 0 ? "0" : ""); + dataRow43[str47] = obj43; + continue; + } + else + { + continue; + } + } + else if (chr != 'p') + { + continue; + } + else if (str4 == "pr invalidez") + { + DataRow dataRow44 = dataRow; + string str48 = str4; + obj44 = (num == 0 ? "0" : ""); + dataRow44[str48] = obj44; + continue; + } + else + { + continue; + } + } + case 13: + { + chr = str4[0]; + if (chr > 'c') + { + if (chr != 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi invalidez") + { + DataRow dataRow45 = dataRow; + string str49 = str4; + obj46 = (num == 0 ? "0" : ""); + dataRow45[str49] = obj46; + continue; + } + else + { + continue; + } + } + case 'm': + case 'n': + { + continue; + } + case 'o': + { + if (str4 == "obs invalidez") + { + DataRow dataRow46 = dataRow; + string str50 = str4; + obj47 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow46[str50] = obj47; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "pr carroceria") + { + DataRow dataRow47 = dataRow; + string str51 = str4; + obj48 = (num == 0 ? "0" : ""); + dataRow47[str51] = obj48; + continue; + } + else + { + continue; + } + } + default: + { + if (chr == 't') + { + break; + } + else + { + goto Label2; + } + } + } + if (str4 == "tipocobertura") + { + DataRow dataRow48 = dataRow; + string str52 = str4; + obj49 = (strs12.Count >= num + 1 ? strs12[num] : ""); + dataRow48[str52] = obj49; + continue; + } + else + { + continue; + } + } + else if (str4 == "fr carroceria") + { + DataRow dataRow49 = dataRow; + string str53 = str4; + obj45 = (num == 0 ? "0" : ""); + dataRow49[str53] = obj45; + continue; + } + else + { + continue; + } + } + else if (chr == 'a') + { + if (str4 == "anofabricacao") + { + DataRow dataRow50 = dataRow; + string str54 = str4; + obj50 = (num == 0 ? "0000" : ""); + dataRow50[str54] = obj50; + continue; + } + else + { + continue; + } + } + else if (chr != 'c') + { + continue; + } + else if (str4 == "cepcirculacao") + { + DataRow dataRow51 = dataRow; + string str55 = str4; + obj51 = (num == 0 ? "00.000-000" : ""); + dataRow51[str55] = obj51; + continue; + } + else + { + continue; + } + } + case 14: + { + chr = str4[0]; + if (chr != 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi carroceria") + { + DataRow dataRow52 = dataRow; + string str56 = str4; + obj53 = (num == 0 ? "0" : ""); + dataRow52[str56] = obj53; + continue; + } + else + { + continue; + } + } + case 'o': + { + if (str4 == "obs carroceria") + { + DataRow dataRow53 = dataRow; + string str57 = str4; + obj54 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow53[str57] = obj54; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "pr Ass 24Horas") + { + DataRow dataRow54 = dataRow; + string str58 = str4; + obj55 = (num == 0 ? "0" : ""); + dataRow54[str58] = obj55; + continue; + } + else + { + continue; + } + } + default: + { + continue; + } + } + } + else if (str4 == "fr Ass 24Horas") + { + DataRow dataRow55 = dataRow; + string str59 = str4; + obj52 = (num == 0 ? "0" : ""); + dataRow55[str59] = obj52; + continue; + } + else + { + continue; + } + break; + } + case 15: + { + chr = str4[0]; + if (chr != 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi Ass 24Horas") + { + DataRow dataRow56 = dataRow; + string str60 = str4; + obj58 = (num == 0 ? "0" : ""); + dataRow56[str60] = obj58; + continue; + } + else + { + continue; + } + } + case 'o': + { + if (str4 == "obs Ass 24Horas") + { + DataRow dataRow57 = dataRow; + string str61 = str4; + obj59 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow57[str61] = obj59; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "pr Danos Morais") + { + DataRow dataRow58 = dataRow; + string str62 = str4; + obj60 = (num == 0 ? "0" : ""); + dataRow58[str62] = obj60; + continue; + } + else if (str4 == "pr equipamentos") + { + DataRow dataRow59 = dataRow; + string str63 = str4; + obj61 = (num == 0 ? "0" : ""); + dataRow59[str63] = obj61; + continue; + } + else + { + continue; + } + } + default: + { + continue; + } + } + } + else if (str4 == "fr Danos Morais") + { + DataRow dataRow60 = dataRow; + string str64 = str4; + obj56 = (num == 0 ? "0" : ""); + dataRow60[str64] = obj56; + continue; + } + else if (str4 == "fr equipamentos") + { + DataRow dataRow61 = dataRow; + string str65 = str4; + obj57 = (num == 0 ? "0" : ""); + dataRow61[str65] = obj57; + continue; + } + else + { + continue; + } + break; + } + case 16: + { + chr = str4[0]; + if (chr <= 'p') + { + if (chr != 'f') + { + switch (chr) + { + case 'l': + { + if (str4 == "lmi Danos Morais") + { + DataRow dataRow62 = dataRow; + string str66 = str4; + obj65 = (num == 0 ? "0" : ""); + dataRow62[str66] = obj65; + continue; + } + else if (str4 == "lmi equipamentos") + { + DataRow dataRow63 = dataRow; + string str67 = str4; + obj66 = (num == 0 ? "0" : ""); + dataRow63[str67] = obj66; + continue; + } + else + { + continue; + } + } + case 'o': + { + if (str4 == "obs Danos Morais") + { + DataRow dataRow64 = dataRow; + string str68 = str4; + obj67 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow64[str68] = obj67; + continue; + } + else if (str4 == "obs equipamentos") + { + DataRow dataRow65 = dataRow; + string str69 = str4; + obj68 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow65[str69] = obj68; + continue; + } + else + { + continue; + } + } + case 'p': + { + if (str4 == "pr carro reserva") + { + DataRow dataRow66 = dataRow; + string str70 = str4; + obj69 = (num == 0 ? "0" : ""); + dataRow66[str70] = obj69; + continue; + } + else + { + continue; + } + } + default: + { + continue; + } + } + } + else if (str4 == "fr carro reserva") + { + DataRow dataRow67 = dataRow; + string str71 = str4; + obj64 = (num == 0 ? "0" : ""); + dataRow67[str71] = obj64; + continue; + } + else + { + continue; + } + } + else if (chr == 't') + { + if (str4 == "tabelareferencia") + { + DataRow dataRow68 = dataRow; + string str72 = str4; + obj62 = (strs13.Count >= num + 1 ? strs13[num] : ""); + dataRow68[str72] = obj62; + continue; + } + else + { + continue; + } + } + else if (chr != 'v') + { + continue; + } + else if (str4 == "valordeterminado") + { + DataRow dataRow69 = dataRow; + string str73 = str4; + obj63 = (num == 0 ? "000000" : ""); + dataRow69[str73] = obj63; + continue; + } + else + { + continue; + } + break; + } + case 17: + { + chr = str4[0]; + if (chr == 'l') + { + if (str4 == "lmi carro reserva") + { + DataRow dataRow70 = dataRow; + string str74 = str4; + obj70 = (num == 0 ? "0" : ""); + dataRow70[str74] = obj70; + continue; + } + else + { + continue; + } + } + else if (chr != 'o') + { + continue; + } + else if (str4 == "obs carro reserva") + { + DataRow dataRow71 = dataRow; + string str75 = str4; + obj71 = (num == 0 ? "OBSERVAÇÃO" : ""); + dataRow71[str75] = obj71; + continue; + } + else + { + continue; + } + } + case 21: + { + if (str4 == "porcentagemreferencia") + { + DataRow dataRow72 = dataRow; + string str76 = str4; + obj72 = (num == 0 ? "000" : ""); + dataRow72[str76] = obj72; + continue; + } + else + { + continue; + } + } + default: + { + continue; + } + } + Label0: + DataRow dataRow73 = dataRow; + string str77 = str4; + obj2 = (strs14.Count >= num + 1 ? strs14[num] : ""); + dataRow73[str77] = obj2; + } + dataTable.Rows.Add(dataRow); + } + xLWorkbook.get_Worksheets().Add(dataTable, "VALORES PERMITIDOS AUTO EXCEL"); + xLWorkbook.SaveAs(string.Concat(folderBrowserDialog.SelectedPath, "\\VALORES PERMITIDOS AUTO EXCEL.xlsx")); + } + await base.ShowMessage(string.Concat("\"EXEMPLO AUTO EXCEL.xlsx\" E \"VALORES PERMITIDOS AUTO EXCEL.xlsx\"\nFORAM SALVOS EM \"", folderBrowserDialog.SelectedPath, "\""), "OK", "", false); + } + folderBrowserDialog = null; + return; + goto Label2; + } + + public async Task BuscaModelo(string fipe) + { + return await this._itemServico.BuscarModelo(fipe); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public List Coberturas(DataRow row) + { + char chr; + List coberturas = new List(); + foreach (DataColumn column in row.Table.Columns) + { + if (!Regex.IsMatch(column.ColumnName, "pr .+")) + { + continue; + } + string value = Regex.Match(column.ColumnName, "pr (.+)").Groups[1].Value; + if (value != "casco" && value != "dm" && value != "dc" && value != "morte" && value != "invalidez" && value != "carro reserva" && value != "vidros" && value != "carroceria" && value != "ass 24horas" && value != "danos morais" && value != "app" && value != "equipamentos") + { + continue; + } + int num = 0; + string str = ""; + if (value != null) + { + switch (value.Length) + { + case 2: + { + chr = value[1]; + if (chr == 'c') + { + if (value == "dc") + { + num = 3; + str = "Danos Corporais"; + break; + } + else + { + break; + } + } + else if (chr != 'm') + { + break; + } + else if (value == "dm") + { + num = 2; + str = "Danos Materiais"; + break; + } + else + { + break; + } + } + case 3: + { + if (value == "app") + { + num = 53; + str = "Acidentes Pessoais"; + break; + } + else + { + break; + } + } + case 5: + { + chr = value[0]; + if (chr == 'c') + { + if (value == "casco") + { + num = 1; + str = "Veiculo (Casco)"; + break; + } + else + { + break; + } + } + else if (chr != 'm') + { + break; + } + else if (value == "morte") + { + num = 4; + str = "Morte"; + break; + } + else + { + break; + } + } + case 6: + { + if (value == "vidros") + { + num = 6; + str = "Vidros"; + break; + } + else + { + break; + } + } + case 9: + { + if (value == "invalidez") + { + num = 5; + str = "Invalidez"; + break; + } + else + { + break; + } + } + case 10: + { + if (value == "carroceria") + { + num = 25; + str = "Carroceria"; + break; + } + else + { + break; + } + } + case 11: + { + if (value == "ass 24horas") + { + num = 19; + str = "Assistência (Guincho)"; + break; + } + else + { + break; + } + } + case 12: + { + chr = value[0]; + if (chr == 'd') + { + if (value == "danos morais") + { + num = 17; + str = "Danos Morais"; + break; + } + else + { + break; + } + } + else if (chr != 'e') + { + break; + } + else if (value == "equipamentos") + { + num = 54; + str = "Equipamentos"; + break; + } + else + { + break; + } + } + case 13: + { + if (value == "carro reserva") + { + num = 7; + str = "Carro Reserva"; + break; + } + else + { + break; + } + } + } + } + decimal num1 = (string.IsNullOrWhiteSpace(row.Field(string.Concat("pr ", value)).ToString()) ? decimal.Zero : Gestor.Model.Helper.ValidationHelper.ToDecimal(row.Field(string.Concat("pr ", value)).ToString(), "pt-BR")); + decimal num2 = (string.IsNullOrWhiteSpace(row.Field(string.Concat("lmi ", value)).ToString()) ? decimal.Zero : Gestor.Model.Helper.ValidationHelper.ToDecimal(row.Field(string.Concat("lmi ", value)).ToString(), "pt-BR")); + decimal num3 = (string.IsNullOrWhiteSpace(row.Field(string.Concat("fr ", value)).ToString()) ? decimal.Zero : Gestor.Model.Helper.ValidationHelper.ToDecimal(row.Field(string.Concat("fr ", value)).ToString(), "pt-BR")); + string str1 = (string.IsNullOrWhiteSpace(row.Field(string.Concat("obs ", value)).ToString()) ? "" : row.Field(string.Concat("obs ", value)).ToString()); + if (!(num2 > decimal.Zero) && !(num3 > decimal.Zero) && !(num1 > decimal.Zero)) + { + continue; + } + Gestor.Model.Domain.Seguros.Cobertura cobertura = new Gestor.Model.Domain.Seguros.Cobertura(); + CoberturaPadrao coberturaPadrao = new CoberturaPadrao(); + coberturaPadrao.set_Id((long)num); + cobertura.set_CoberturaPadrao(coberturaPadrao); + cobertura.set_Observacao(string.Concat(str, " - ", str1)); + cobertura.set_Premio(num1); + cobertura.set_Lmi(num2); + cobertura.set_Franquia(num3); + coberturas.Add(cobertura); + } + return coberturas; + } + + public void Descarregar() + { + this.Cobertura = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task>> ImportarXls() + { + List> keyValuePairs; + string fileName; + List> keyValuePairs1 = new List>(); + using (OpenFileDialog openFileDialog = new OpenFileDialog()) + { + openFileDialog.Filter = "Excel|*.xls;*.xlsx"; + openFileDialog.InitialDirectory = Environment.SpecialFolder.Desktop.ToString(); + if (DialogResult.OK == openFileDialog.ShowDialog()) + { + fileName = openFileDialog.FileName; + } + else + { + keyValuePairs1.Add(new KeyValuePair("EXCEL", "ERRO AO SELECIONAR DOCUMENTO")); + keyValuePairs = keyValuePairs1; + keyValuePairs1 = null; + return keyValuePairs; + } + } + try + { + List> tasks1 = await Task.Run>>(() => { + string upper; + Microsoft.Office.Interop.Excel.Application variable = (Microsoft.Office.Interop.Excel.Application)Activator.CreateInstance(Marshal.GetTypeFromCLSID(new Guid("00024500-0000-0000-C000-000000000046"))); + Workbook variable1 = variable.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); + List strs = new List() + { + "placa", + "fabricante", + "modelo", + "fipe", + "chassi", + "anofabricacao", + "anomodelo", + "cor", + "categoria", + "combustivel", + "zerokm", + "renavam", + "capacidade", + "portas", + "bonus", + "ceppernoite", + "ci", + "financiado", + "correcao", + "isencao", + "pcd", + "cepcirculacao", + "tipocobertura", + "porcentagemreferencia", + "tabelareferencia", + "valordeterminado", + "observacao", + "usoveiculos" + }; + List dataTables = new List(); + foreach (object worksheet in variable1.Worksheets) + { + DataTable dataTable = new DataTable(); + Microsoft.Office.Interop.Excel.Range usedRange = ((Worksheet)worksheet).UsedRange; + if (AutoViewModel.u003cu003eo__77.u003cu003ep__0 == null) + { + AutoViewModel.u003cu003eo__77.u003cu003ep__0 = CallSite>.Create(Binder.Convert(CSharpBinderFlags.None, typeof(object[,]), typeof(AutoViewModel))); + } + object[,] target = AutoViewModel.u003cu003eo__77.u003cu003ep__0.Target(AutoViewModel.u003cu003eo__77.u003cu003ep__0, usedRange.Value2); + int num1 = 0; + for (int i = 0; i <= usedRange.Columns.Count - 1; i++) + { + if (target[1, i + 1] != null) + { + DataColumn dataColumn = new DataColumn() + { + DataType = Type.GetType("System.String"), + ColumnName = Funcoes.RemoverAcentos(target[1, i + 1].ToString().ToLower()) + }; + dataTable.Columns.Add(dataColumn); + for (int j = 0; j <= usedRange.Rows.Count - 2; j++) + { + object obj = target[j + 2, i + 1]; + string str = obj as string; + if (str != null) + { + upper = Funcoes.RemoverAcentos(str).ToUpper(); + } + else if (!(obj is double)) + { + upper = (!(obj is bool) ? "" : ((bool)obj ? "1" : "0")); + } + else + { + double num2 = (double)obj; + upper = (!num2.ToString(CultureInfo.InvariantCulture).Contains("+") ? num2.ToString(CultureInfo.InvariantCulture) : "."); + } + if (i + num1 != 0) + { + dataTable.Rows[j][i + num1] = upper; + } + else + { + dataTable.Rows.Add(dataTable.NewRow()); + dataTable.Rows[j][i + num1] = upper; + } + } + } + else + { + num1--; + } + } + dataTables.Add(dataTable); + } + variable.Quit(); + List> tasks = new List>(); + foreach (DataTable dataTable1 in dataTables) + { + for (int k = dataTable1.Rows.Count - 1; k >= 0; k--) + { + object[] itemArray = dataTable1.Rows[k].ItemArray; + Func u003cu003e9_772 = AutoViewModel.u003cu003ec.u003cu003e9__77_2; + if (u003cu003e9_772 == null) + { + u003cu003e9_772 = (object item) => string.IsNullOrEmpty((item != null ? item.ToString() : null)); + AutoViewModel.u003cu003ec.u003cu003e9__77_2 = u003cu003e9_772; + } + if (((IEnumerable)itemArray).All(u003cu003e9_772)) + { + dataTable1.Rows.RemoveAt(k); + } + } + tasks.AddRange(dataTable1.AsEnumerable().ToList().Select>(async (DataRow x) => { + decimal num; + bool? nullable; + bool? nullable1; + bool? nullable2; + bool? nullable3; + bool? nullable4; + Item item2 = new Item(); + Item item1 = item2; + Auto auto = new Auto(); + auto.set_Placa((!dataTable1.Columns.Contains("placa") || string.IsNullOrWhiteSpace(x.Field("placa").ToString()) ? null : x.Field("placa").ToString().ToUpper())); + auto.set_AnoFabricacao((!dataTable1.Columns.Contains("anofabricacao") || string.IsNullOrWhiteSpace(x.Field("anofabricacao").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("anofabricacao").ToString(), ""))); + auto.set_AnoModelo((!dataTable1.Columns.Contains("anomodelo") || string.IsNullOrWhiteSpace(x.Field("anomodelo").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("anomodelo").ToString(), ""))); + auto.set_Bonus((!dataTable1.Columns.Contains("bonus") || string.IsNullOrWhiteSpace(x.Field("bonus").ToString()) ? null : new int?(int.Parse((new Regex("[^0-9]")).Replace(x.Field("bonus").ToString(), ""))))); + auto.set_Capacidade((!dataTable1.Columns.Contains("capacidade") || string.IsNullOrWhiteSpace(x.Field("capacidade").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("capacidade").ToString(), ""))); + auto.set_CepPernoite((!dataTable1.Columns.Contains("ceppernoite") || string.IsNullOrWhiteSpace(x.Field("ceppernoite").ToString()) ? Gestor.Common.Validation.ValidationHelper.FormatPostCode((new Regex("[^0-9]")).Replace(x.Field("cepcirculacao").ToString(), "")) : Gestor.Common.Validation.ValidationHelper.FormatPostCode((new Regex("[^0-9]")).Replace(x.Field("ceppernoite").ToString(), "")))); + auto.set_Chassi((!dataTable1.Columns.Contains("chassi") || string.IsNullOrWhiteSpace(x.Field("chassi").ToString()) ? null : x.Field("chassi").ToString())); + auto.set_Ci((!dataTable1.Columns.Contains("ci") || string.IsNullOrWhiteSpace(x.Field("ci").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("ci").ToString(), ""))); + auto.set_Observacao((!dataTable1.Columns.Contains("observacao") || string.IsNullOrWhiteSpace(x.Field("observacao").ToString()) ? null : x.Field("observacao").ToString())); + auto.set_Cor((!dataTable1.Columns.Contains("cor") || string.IsNullOrWhiteSpace(x.Field("cor").ToString()) ? null : Funcoes.GetCor(x.Field("cor").ToString().ToLower()))); + Auto auto1 = auto; + if (!dataTable1.Columns.Contains("financiado") || string.IsNullOrWhiteSpace(x.Field("financiado").ToString())) + { + nullable = null; + nullable1 = nullable; + } + else + { + nullable1 = new bool?(x.Field("financiado").ToString().ToLower() == "sim"); + } + auto1.set_Financiado(nullable1); + Auto auto2 = auto; + if (!dataTable1.Columns.Contains("zerokm") || string.IsNullOrWhiteSpace(x.Field("zerokm").ToString())) + { + nullable = null; + nullable2 = nullable; + } + else + { + nullable2 = new bool?(x.Field("zerokm").ToString().ToLower() == "sim"); + } + auto2.set_ZeroKm(nullable2); + auto.set_Combustivel((!dataTable1.Columns.Contains("combustivel") || string.IsNullOrWhiteSpace(x.Field("combustivel").ToString()) ? null : Funcoes.GetCombustivel(x.Field("combustivel").ToString().ToLower()))); + auto.set_Correcao((!dataTable1.Columns.Contains("correcao") || string.IsNullOrWhiteSpace(x.Field("correcao").ToString()) ? null : Funcoes.GetCorrecao(x.Field("correcao").ToString().ToLower()))); + auto.set_Fabricante((!dataTable1.Columns.Contains("fabricante") || string.IsNullOrWhiteSpace(x.Field("fabricante").ToString()) ? null : await Funcoes.GetFabricante(x.Field("fabricante").ToString().ToLower()))); + auto.set_Fipe((!dataTable1.Columns.Contains("fipe") || string.IsNullOrWhiteSpace(x.Field("fipe").ToString()) ? null : Gestor.Model.Helper.ValidationHelper.FormataFipe((new Regex("[^0-9]")).Replace(x.Field("fipe").ToString(), "")))); + auto.set_Isencao((!dataTable1.Columns.Contains("isencao") || string.IsNullOrWhiteSpace(x.Field("isencao").ToString()) ? null : Funcoes.GetIsencao(x.Field("isencao").ToString().ToLower()))); + auto.set_Modelo((!dataTable1.Columns.Contains("modelo") || string.IsNullOrWhiteSpace(x.Field("modelo").ToString()) ? null : x.Field("modelo").ToString())); + Auto auto3 = auto; + if (!dataTable1.Columns.Contains("pcd") || string.IsNullOrWhiteSpace(x.Field("pcd").ToString())) + { + nullable = null; + nullable3 = nullable; + } + else + { + nullable3 = new bool?(x.Field("pcd").ToString().ToLower() == "sim"); + } + auto3.set_Pcd(nullable3); + auto.set_PorcentagemReferencia((!dataTable1.Columns.Contains("porcentagemreferencia") || string.IsNullOrWhiteSpace(x.Field("porcentagemreferencia").ToString()) ? decimal.Zero : (decimal.TryParse(x.Field("porcentagemreferencia").ToString(), out num) ? decimal.Parse(x.Field("porcentagemreferencia").ToString()) : decimal.Zero))); + auto.set_Portas((!dataTable1.Columns.Contains("portas") || string.IsNullOrWhiteSpace(x.Field("portas").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("portas").ToString(), ""))); + auto.set_RegiaoCirculacao((!dataTable1.Columns.Contains("cepcirculacao") || string.IsNullOrWhiteSpace(x.Field("cepcirculacao").ToString()) ? null : Gestor.Common.Validation.ValidationHelper.FormatPostCode((new Regex("[^0-9]")).Replace(x.Field("cepcirculacao").ToString(), "")))); + auto.set_Renavam((!dataTable1.Columns.Contains("renavam") || string.IsNullOrWhiteSpace(x.Field("renavam").ToString()) ? null : (new Regex("[^0-9]")).Replace(x.Field("renavam").ToString(), ""))); + auto.set_TabelaReferencia((!dataTable1.Columns.Contains("tabelareferencia") || string.IsNullOrWhiteSpace(x.Field("tabelareferencia").ToString()) ? null : Funcoes.GetTabelaReferencia(x.Field("tabelareferencia").ToString().ToLower()))); + auto.set_TipoCobertura((!dataTable1.Columns.Contains("tipocobertura") || string.IsNullOrWhiteSpace(x.Field("tipocobertura").ToString()) ? null : Funcoes.GetTipoCobertura(x.Field("tipocobertura").ToString().ToLower()))); + auto.set_ValorDeterminado((!dataTable1.Columns.Contains("valordeterminado") || string.IsNullOrWhiteSpace(x.Field("valordeterminado").ToString()) || !Gestor.Common.Validation.ValidationHelper.ValidateValor(x.Field("valordeterminado").ToString()) ? decimal.Zero : decimal.Parse(x.Field("valordeterminado").ToString()))); + auto.set_Categoria((!dataTable1.Columns.Contains("categoria") || string.IsNullOrWhiteSpace(x.Field("categoria").ToString()) ? null : Funcoes.GetCategoria(x.Field("categoria").ToString().ToLower()))); + auto.set_UsoVeiculo((!dataTable1.Columns.Contains("usoveiculo") || string.IsNullOrWhiteSpace(x.Field("usoveiculo").ToString()) ? null : Funcoes.GetUsoveiculo(x.Field("usoveiculo").ToString().ToUpper()))); + Auto auto4 = auto; + if (!dataTable1.Columns.Contains("KitGas") || string.IsNullOrWhiteSpace(x.Field("KitGas").ToString())) + { + nullable = null; + nullable4 = nullable; + } + else + { + nullable4 = new bool?(x.Field("KitGas").ToString().ToLower() == "sim"); + } + auto4.set_KitGas(nullable4); + item1.set_Auto(auto); + item2.set_Coberturas(this.Coberturas(x)); + item2.set_Documento(this.ItemSelecionado.get_Documento()); + item2.set_Substituicao(null); + return item2; + }).ToList>()); + } + return tasks; + }); + if (tasks1.Count != 0) + { + Item[] itemArray1 = await Task.WhenAll(tasks1); + keyValuePairs1 = await this.SalvarRange(itemArray1); + } + else + { + keyValuePairs1.Add(new KeyValuePair("EXCEL", "NENHUMA COLUNA FOI ENCONTRADA")); + keyValuePairs = keyValuePairs1; + keyValuePairs1 = null; + return keyValuePairs; + } + } + catch (Exception exception) + { + keyValuePairs1.Add(new KeyValuePair("EXCEL", "FALHA AO IMPORTAR O EXCEL,\nVERIFIQUE SE O ARQUIVO POSSUI ALGUM ERRO")); + } + keyValuePairs = keyValuePairs1; + keyValuePairs1 = null; + return keyValuePairs; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + long? nullable; + List coberturas; + long? nullable1; + long? nullable2; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + Item item2 = item; + Auto auto = new Auto(); + auto.set_Isencao(new Isencao?(0)); + auto.set_ZeroKm(new bool?(false)); + auto.set_Financiado(new bool?(false)); + auto.set_UsoVeiculo(new Gestor.Model.Common.UsoVeiculo?(0)); + auto.set_Categoria(new Gestor.Model.Common.Categoria?(3)); + item2.set_Auto(auto); + Item item3 = item; + if (substituir) + { + nullable1 = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + nullable1 = nullable; + } + item3.set_Substituicao(nullable1); + Item item4 = item; + item1 = null; + item = null; + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item4; + this.SelectedItem.get_Auto().set_Item(item4); + this.UsoVeiculo = this.SelectedItem.get_Auto().get_UsoVeiculo(); + this.Categoria = this.SelectedItem.get_Auto().get_Categoria(); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Auto().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable2 = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + nullable2 = nullable; + } + selectedItem.set_Substituicao(nullable2); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item4.get_Ordem(); + if (ordem.GetValueOrDefault() == 2 && !substituir) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item4 = null; + return; + } + } + ordem = item4.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item4 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Auto().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string descricao; + string str1; + string str2; + string str3; + string str4; + Auto auto = this.SelectedItem.get_Auto(); + str = (!string.IsNullOrEmpty(this.SelectedItem.get_Auto().get_Placa()) ? Gestor.Model.Helper.ValidationHelper.FormataPlaca(this.SelectedItem.get_Auto().get_Placa()) : string.Empty); + auto.set_Placa(str); + Item selectedItem = this.SelectedItem; + string[] modelo = new string[7]; + Fabricante fabricante = this.SelectedItem.get_Auto().get_Fabricante(); + if (fabricante != null) + { + descricao = fabricante.get_Descricao(); + } + else + { + descricao = null; + } + modelo[0] = descricao; + modelo[1] = " "; + modelo[2] = this.SelectedItem.get_Auto().get_Modelo(); + modelo[3] = " / "; + modelo[4] = this.SelectedItem.get_Auto().get_Chassi(); + modelo[5] = " / "; + modelo[6] = this.SelectedItem.get_Auto().get_Placa(); + selectedItem.set_Descricao(string.Concat(modelo)); + Item item = this.SelectedItem; + List configuracoes = Recursos.Configuracoes; + bool flag = configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 18); + List configuracaoSistemas = Recursos.Configuracoes; + List> keyValuePairs1 = item.Validate(flag, configuracaoSistemas.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 27)); + List> keyValuePairs2 = keyValuePairs1; + keyValuePairs2.AddRange(await this.Validate()); + keyValuePairs2 = null; + if (keyValuePairs1.Count <= 0) + { + Item selectedItem1 = this.SelectedItem; + selectedItem1.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + selectedItem1 = null; + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str4 = str1; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str2 = ""; + } + else if (base.Mantido) + { + str2 = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str2 = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str5 = str2; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str5); + } + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str3 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str6 = str3; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str6); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str7 = string.Concat(str4, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str7, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + str4 = null; + return keyValuePairs; + } + + public async Task>> SalvarRange(IEnumerable list) + { + List> keyValuePairs; + string str; + string descricao; + string str1; + string str2; + Item item = null; + Item item1 = new Item(); + List> keyValuePairs1 = new List>(); + int num = await base.QuantidadeDeItens(list.First().get_Documento().get_Controle().get_Id()); + foreach (Item item in list) + { + if (!item.get_Auto().get_Isencao().HasValue) + { + item.get_Auto().set_Isencao(new Isencao?(0)); + } + if (!item.get_Auto().get_ZeroKm().HasValue) + { + item.get_Auto().set_ZeroKm(new bool?(false)); + } + if (!item.get_Auto().get_Financiado().HasValue) + { + item.get_Auto().set_Financiado(new bool?(false)); + } + if (!item.get_Auto().get_UsoVeiculo().HasValue) + { + item.get_Auto().set_UsoVeiculo(new Gestor.Model.Common.UsoVeiculo?(0)); + } + item.set_Ordem(new int?(num)); + num++; + item.get_Auto().set_Item(item); + Auto auto = item.get_Auto(); + str = (!string.IsNullOrEmpty(item.get_Auto().get_Placa()) ? Gestor.Model.Helper.ValidationHelper.FormataPlaca(item.get_Auto().get_Placa()) : string.Empty); + auto.set_Placa(str); + Item item2 = item; + string[] modelo = new string[7]; + Fabricante fabricante = item.get_Auto().get_Fabricante(); + if (fabricante != null) + { + descricao = fabricante.get_Descricao(); + } + else + { + descricao = null; + } + modelo[0] = descricao; + modelo[1] = " "; + modelo[2] = item.get_Auto().get_Modelo(); + modelo[3] = " / "; + modelo[4] = item.get_Auto().get_Chassi(); + modelo[5] = " / "; + modelo[6] = item.get_Auto().get_Placa(); + item2.set_Descricao(string.Concat(modelo)); + Item item3 = item; + List configuracoes = Recursos.Configuracoes; + List> keyValuePairs2 = item3.Validate(configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 18), false); + List> keyValuePairs3 = keyValuePairs2; + keyValuePairs3.AddRange(await this.Validate(item)); + keyValuePairs3 = null; + Item item4 = item; + str1 = (item.get_Documento().get_Ordem() > 0 ? string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", item.get_Documento().get_Ordem()) : ""); + item4.set_Status(str1); + if (keyValuePairs2.Count <= 0) + { + continue; + } + keyValuePairs1.Add(new KeyValuePair("", item.get_Descricao())); + keyValuePairs1.AddRange(keyValuePairs2); + keyValuePairs2 = null; + } + if (keyValuePairs1.Count <= 0) + { + foreach (Item item5 in list) + { + str2 = (item5.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + string str3 = str2; + item1 = await this._itemServico.Save(item5); + string str4 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", item5.get_Descricao(), "\""); + long id = item5.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { item5.get_Id(), item5.get_Documento().get_Id(), item5.get_Documento().get_Controle().get_Ramo().get_Nome(), item5.get_Documento().get_Controle().get_Cliente().get_Nome(), item5.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str4, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + str3 = null; + } + this.SelectedItem = item1; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar("ITENS SALVOS COM SUCESSO", true); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = keyValuePairs1; + } + item1 = null; + keyValuePairs1 = null; + return keyValuePairs; + } + + public async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + this.Fabricantes = Recursos.Fabricantes; + List nums = new List() + { + (long)5, + (long)37 + }; + if (nums.Contains(this.Ramo.get_Id())) + { + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Auto auto = await this._itemServico.BuscaAuto(item.get_Id()); + item1.set_Auto(auto); + item1 = null; + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.WorkOnSelectedAuto(this.SelectedItem.get_Auto()); + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + this.UsoVeiculo = this.SelectedItem.get_Auto().get_UsoVeiculo(); + this.Categoria = this.SelectedItem.get_Auto().get_Categoria(); + base.Loading(false); + } + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + + public async Task>> Validate() + { + List> keyValuePairs; + List> keyValuePairs1 = new List>(); + if (!string.IsNullOrEmpty(this.SelectedItem.get_Auto().get_Chassi())) + { + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 26)) + { + Documento documento = await (new AutoServico()).BuscarAuto(this.SelectedItem.get_Auto().get_Chassi(), this.SelectedItem.get_Auto().get_Id(), this.SelectedItem.get_Documento().get_Vigencia1(), this.SelectedItem.get_Documento().get_Vigencia2(), this.SelectedItem.get_Documento().get_Controle().get_Seguradora().get_Id()); + if (documento == null) + { + keyValuePairs = keyValuePairs1; + } + else if (this.AllowAlterarExcluir || this.SelectedItem.get_Documento().get_Controle().get_Id() != documento.get_Controle().get_Id()) + { + List> keyValuePairs2 = keyValuePairs1; + string[] apolice = new string[] { "CHASSI JÁ CADASTRADO NA APÓLICE ", documento.get_Apolice(), " DO CLIENTE ", documento.get_Controle().get_Cliente().get_Nome(), "." }; + keyValuePairs2.Add(new KeyValuePair("Chassi", string.Concat(apolice))); + keyValuePairs = keyValuePairs1; + } + else + { + keyValuePairs = keyValuePairs1; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + public async Task>> Validate(Item item) + { + List> keyValuePairs; + List> keyValuePairs1 = new List>(); + if (!string.IsNullOrEmpty(item.get_Auto().get_Chassi())) + { + List configuracoes = Recursos.Configuracoes; + if (!configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 26)) + { + Documento documento = await (new AutoServico()).BuscarAuto(item.get_Auto().get_Chassi(), item.get_Auto().get_Id(), item.get_Documento().get_Vigencia1(), item.get_Documento().get_Vigencia2(), item.get_Documento().get_Controle().get_Seguradora().get_Id()); + if (documento == null) + { + keyValuePairs = keyValuePairs1; + } + else if (this.AllowAlterarExcluir || item.get_Documento().get_Controle().get_Id() != documento.get_Controle().get_Id()) + { + List> keyValuePairs2 = keyValuePairs1; + string[] apolice = new string[] { "CHASSI JÁ CADASTRADO NA APÓLICE ", documento.get_Apolice(), " DO CLIENTE ", documento.get_Controle().get_Cliente().get_Nome(), "." }; + keyValuePairs2.Add(new KeyValuePair("Chassi", string.Concat(apolice))); + keyValuePairs = keyValuePairs1; + } + else + { + keyValuePairs = keyValuePairs1; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + keyValuePairs1 = null; + return keyValuePairs; + } + + private void WorkOnSelectedAuto(Auto value) + { + if (value == null || value.get_Id() == 0) + { + return; + } + this.SelectedFabricante = this.Fabricantes.FirstOrDefault((Fabricante x) => { + int? nullable; + int id = x.get_Id(); + Fabricante fabricante = value.get_Fabricante(); + if (fabricante != null) + { + nullable = new int?(fabricante.get_Id()); + } + else + { + nullable = null; + } + int? nullable1 = nullable; + return id == nullable1.GetValueOrDefault() & nullable1.HasValue; + }); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/BuscarModeloViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/BuscarModeloViewModel.cs new file mode 100644 index 0000000..b97c9ea --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/BuscarModeloViewModel.cs @@ -0,0 +1,95 @@ +using CsQuery.ExtensionMethods.Internal; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class BuscarModeloViewModel : BaseSegurosViewModel + { + private Auto _selectedBuscaModelo = new Auto(); + + private ObservableCollection _modelosAutos = new ObservableCollection(); + + private Fipe _resultado = new Fipe(); + + public ObservableCollection ModelosAutos + { + get + { + return this._modelosAutos; + } + set + { + this._modelosAutos = value; + base.OnPropertyChanged("ModelosAutos"); + } + } + + public Fipe Resultado + { + get + { + return this._resultado; + } + set + { + this._resultado = value; + base.OnPropertyChanged("Resultado"); + } + } + + public Auto SelectedBuscaModelo + { + get + { + return this._selectedBuscaModelo; + } + set + { + this._selectedBuscaModelo = value; + base.OnPropertyChanged("SelectedBuscaModelo"); + } + } + + public BuscarModeloViewModel(string modelo, string ano) + { + Auto auto = new Auto(); + auto.set_AnoModelo(ano); + auto.set_Modelo(modelo); + this.SelectedBuscaModelo = auto; + } + + public async void Pesquisar() + { + string modelo = this.SelectedBuscaModelo.get_Modelo(); + int num = ValidationHelper.ToInt(this.SelectedBuscaModelo.get_AnoModelo()); + List list = await (new ItemServico()).BuscarPorModelo(modelo); + if ((this.SelectedBuscaModelo.get_AnoModelo() != null || ExtensionMethods.IsNullOrEmpty(list)) && this.SelectedBuscaModelo.get_Id() != 0) + { + list = list.Where((Fipe x) => { + if (x.get_AnoMinimo() > num) + { + return false; + } + return x.get_AnoMaximo() >= num; + }).ToList(); + this.ModelosAutos = new ObservableCollection(list); + } + else + { + this.ModelosAutos = new ObservableCollection(list); + } + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/ConsorcioViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/ConsorcioViewModel.cs new file mode 100644 index 0000000..0470058 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/ConsorcioViewModel.cs @@ -0,0 +1,520 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class ConsorcioViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly ConsorcioServico _servico; + + private bool _visibilityTitulares; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private object _sinistro; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + set; + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public object Sinistro + { + get + { + return this._sinistro; + } + set + { + this._sinistro = value; + base.OnPropertyChanged("Sinistro"); + } + } + + public bool VisibilityTitulares + { + get + { + return this._visibilityTitulares; + } + set + { + this._visibilityTitulares = value; + base.OnPropertyChanged("VisibilityTitulares"); + } + } + + public ConsorcioViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new ConsorcioServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + this.VisibilityTitulares = this.Ramo.get_Id() == (long)31; + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + this.Sinistro = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + item.set_Consorcio(new Consorcio()); + Item item2 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item2.set_Substituicao(nullable); + Item item3 = item; + item1 = null; + item = null; + base.Titulares = new ObservableCollection(); + ordem = item3.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item3 = null; + return; + } + } + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item3; + this.SelectedItem.get_Consorcio().set_Item(item3); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item3.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item3 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Consorcio().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + string str2; + string str3; + this.SelectedItem.set_Descricao(this.SelectedItem.get_Consorcio().get_BensConsorcio()); + List> keyValuePairs1 = this.SelectedItem.Validate(); + if (keyValuePairs1.Count <= 0) + { + Item selectedItem = this.SelectedItem; + selectedItem.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + selectedItem = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str = ""; + } + else if (base.Mantido) + { + str = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str4 = str; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str4); + } + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str1; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str2 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str5 = str2; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str5); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str6 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str6, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + base.Titulares = new ObservableCollection(); + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Consorcio consorcio = await this._itemServico.BuscaConsorcio(item.get_Id()); + Item item2 = item1; + Consorcio consorcio1 = consorcio; + if (consorcio1 == null) + { + consorcio1 = new Consorcio(); + consorcio1.set_Item(item); + } + item2.set_Consorcio(consorcio1); + item1 = null; + if (this.VisibilityTitulares) + { + await base.CarregarTitulares(item.get_Id()); + } + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/GranizoViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/GranizoViewModel.cs new file mode 100644 index 0000000..b40ea83 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/GranizoViewModel.cs @@ -0,0 +1,500 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class GranizoViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly GranizoServico _servico; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + private Visibility _visibilityMaisInformacoes = Visibility.Collapsed; + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public Visibility VisibilityMaisInformacoes + { + get + { + return this._visibilityMaisInformacoes; + } + set + { + this._visibilityMaisInformacoes = value; + base.OnPropertyChanged("VisibilityMaisInformacoes"); + } + } + + public GranizoViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new GranizoServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task IncluirItem(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + Item item2 = item; + Granizo granizo = new Granizo(); + granizo.set_Item(this.SelectedItem); + item2.set_Granizo(granizo); + Item item3 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item3.set_Substituicao(nullable); + Item item4 = item; + item1 = null; + item = null; + ordem = item4.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item4 = null; + return; + } + } + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item4; + this.SelectedItem.get_Granizo().set_Item(item4); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item4.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item4 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Granizo().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + string str1; + string str2; + string str3; + string str4; + Item selectedItem = this.SelectedItem; + string cultura = this.SelectedItem.get_Granizo().get_Cultura(); + string sitio = this.SelectedItem.get_Granizo().get_Sitio(); + str = (ValidationHelper.IsNotNullOrEmpty(this.SelectedItem.get_Granizo().get_Area()) ? "" : string.Concat(" / ", this.SelectedItem.get_Granizo().get_Area())); + selectedItem.set_Descricao(string.Concat(cultura, " ", sitio, str)); + List> keyValuePairs1 = this.SelectedItem.get_Granizo().Validate(); + if (keyValuePairs1.Count <= 0) + { + Item item = this.SelectedItem; + item.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + item = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str1 = ""; + } + else if (base.Mantido) + { + str1 = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str1 = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str5 = str1; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str5); + } + str2 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str4 = str2; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str3 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str6 = str3; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str6); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str7 = string.Concat(str4, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str7, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str4 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + List nums = new List() + { + (long)20 + }; + if (nums.Contains(this.Ramo.get_Id())) + { + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Granizo granizo = await this._itemServico.BuscaGranizo(item.get_Id()); + item1.set_Granizo(granizo); + item1 = null; + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.IncluirItem(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/PatrimonialViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/PatrimonialViewModel.cs new file mode 100644 index 0000000..caf28fa --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/PatrimonialViewModel.cs @@ -0,0 +1,678 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class PatrimonialViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly PatrimonialServico _servico; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + private Visibility _visibilityTipoMoradia = Visibility.Collapsed; + + private Visibility _visibilityFianca = Visibility.Collapsed; + + private Visibility _visibilityPatrimonial; + + private string _bensInformacoes = "BENS/INFORMAÇÕES"; + + private string _locatarioTomador1 = "LOCATÁRIO 1:"; + + private string _locatarioTomador2 = "LOCATÁRIO 2:"; + + private string _locatarioTomador3 = "LOCATÁRIO 3:"; + + private Visibility _visibilityDescricao = Visibility.Collapsed; + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public string BensInformacoes + { + get + { + return this._bensInformacoes; + } + set + { + this._bensInformacoes = value; + base.OnPropertyChanged("BensInformacoes"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Garantia + { + get; + set; + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + set; + } + + public string LocatarioTomador1 + { + get + { + return this._locatarioTomador1; + } + set + { + this._locatarioTomador1 = value; + base.OnPropertyChanged("LocatarioTomador1"); + } + } + + public string LocatarioTomador2 + { + get + { + return this._locatarioTomador2; + } + set + { + this._locatarioTomador2 = value; + base.OnPropertyChanged("LocatarioTomador2"); + } + } + + public string LocatarioTomador3 + { + get + { + return this._locatarioTomador3; + } + set + { + this._locatarioTomador3 = value; + base.OnPropertyChanged("LocatarioTomador3"); + } + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public Visibility VisibilityDescricao + { + get + { + return this._visibilityDescricao; + } + set + { + this._visibilityDescricao = value; + base.OnPropertyChanged("VisibilityDescricao"); + } + } + + public Visibility VisibilityFianca + { + get + { + return this._visibilityFianca; + } + set + { + this._visibilityFianca = value; + base.OnPropertyChanged("VisibilityFianca"); + } + } + + public Visibility VisibilityPatrimonial + { + get + { + return this._visibilityPatrimonial; + } + set + { + this._visibilityPatrimonial = value; + base.OnPropertyChanged("VisibilityPatrimonial"); + } + } + + public Visibility VisibilityTipoMoradia + { + get + { + return this._visibilityTipoMoradia; + } + set + { + this._visibilityTipoMoradia = value; + base.OnPropertyChanged("VisibilityTipoMoradia"); + } + } + + public PatrimonialViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new PatrimonialServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + private void HabilitaCamposGarantia() + { + this.VisibilityPatrimonial = (this.Ramo.get_Id() == (long)38 ? Visibility.Collapsed : Visibility.Visible); + this.BensInformacoes = "OBSERVAÇÕES"; + this.LocatarioTomador1 = "TOMADOR 1:"; + this.LocatarioTomador2 = "TOMADOR 2:"; + this.LocatarioTomador3 = "TOMADOR 3:"; + this.VisibilityDescricao = Visibility.Visible; + this.Garantia = true; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + Patrimonial patrimonial1; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + Item item2 = item; + Patrimonial patrimonial2 = new Patrimonial(); + patrimonial2.set_Item(this.SelectedItem); + item2.set_Patrimonial(patrimonial2); + Item item3 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item3.set_Substituicao(nullable); + Item item4 = item; + item1 = null; + item = null; + bool garantia = !this.Garantia; + if (garantia) + { + garantia = await base.ShowMessage("COPIAR OS DADOS DE ENDEREÇO DO CLIENTE?", "SIM", "NÃO", false); + } + if (garantia) + { + ObservableCollection observableCollection = await (new ClienteServico()).BuscarEnderecosAsync(item4.get_Documento().get_Controle().get_Cliente().get_Id()); + if (observableCollection != null && observableCollection.Any()) + { + ObservableCollection observableCollection1 = observableCollection; + IOrderedEnumerable valueOrDefault = + from x in observableCollection1 + orderby x.get_Ordem().GetValueOrDefault() == 1 + select x; + List list = valueOrDefault.Select((ClienteEndereco e) => { + Patrimonial patrimonial = new Patrimonial(); + patrimonial.set_Endereco(e.get_Endereco()); + patrimonial.set_Numero(e.get_Numero()); + patrimonial.set_Complemento(e.get_Complemento()); + patrimonial.set_Bairro(e.get_Bairro()); + patrimonial.set_Cidade(e.get_Cidade()); + patrimonial.set_Estado(e.get_Estado()); + patrimonial.set_Cep(e.get_Cep()); + return patrimonial; + }).ToList(); + Item item5 = item4; + if (list.Any()) + { + patrimonial1 = list.Last(); + } + else + { + patrimonial1 = null; + } + item5.set_Patrimonial(patrimonial1); + } + } + ordem = item4.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item4 = null; + return; + } + } + this.SelectedItem = item4; + this.SelectedItem.get_Patrimonial().set_Item(item4); + ordem = item4.get_Ordem(); + int num = 1; + garantia = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (garantia) + { + garantia = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!garantia) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item4 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Patrimonial().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string descricao; + string str; + string str1; + string str2; + string str3; + Item selectedItem = this.SelectedItem; + if (this.VisibilityPatrimonial == Visibility.Visible) + { + string[] endereco = new string[] { this.SelectedItem.get_Patrimonial().get_Endereco(), ", ", this.SelectedItem.get_Patrimonial().get_Numero(), " - ", this.SelectedItem.get_Patrimonial().get_Complemento(), " - ", this.SelectedItem.get_Patrimonial().get_Bairro(), ", ", this.SelectedItem.get_Patrimonial().get_Cidade(), " / ", this.SelectedItem.get_Patrimonial().get_Estado() }; + descricao = string.Concat(endereco); + } + else + { + descricao = this.SelectedItem.get_Descricao(); + } + selectedItem.set_Descricao(descricao); + List> keyValuePairs1 = this.SelectedItem.Validate(); + if (keyValuePairs1.Count <= 0) + { + Item item = this.SelectedItem; + item.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + item = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str = ""; + } + else if (base.Mantido) + { + str = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str4 = str; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str4); + } + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str1; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str2 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str5 = str2; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str5); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str6 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str6, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + Visibility visibility; + Visibility visibility1; + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + List nums = new List() + { + (long)1, + (long)2, + (long)3, + (long)15, + (long)18, + (long)30, + (long)38 + }; + if (nums.Contains(this.Ramo.get_Id())) + { + PatrimonialViewModel patrimonialViewModel = this; + visibility = (this.Ramo.get_Id() == (long)1 ? Visibility.Visible : Visibility.Collapsed); + patrimonialViewModel.VisibilityTipoMoradia = visibility; + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + PatrimonialViewModel patrimonialViewModel1 = this; + visibility1 = (this.Ramo.get_Id() == (long)15 || this.Ramo.get_Id() == (long)38 ? Visibility.Visible : Visibility.Collapsed); + patrimonialViewModel1.VisibilityFianca = visibility1; + if (this.Ramo.get_Id() == (long)38) + { + this.HabilitaCamposGarantia(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Patrimonial patrimonial = await this._itemServico.BuscaPatrimonial(item.get_Id()); + item1.set_Patrimonial(patrimonial); + item1 = null; + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/RiscosDiversosViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/RiscosDiversosViewModel.cs new file mode 100644 index 0000000..7469ac9 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/RiscosDiversosViewModel.cs @@ -0,0 +1,626 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class RiscosDiversosViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly RiscosDiversosServico _servico; + + private bool _visibilityTitulares; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private object _sinistro; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + public Visibility _visibilityMultRisco { get; set; } = Visibility.Collapsed; + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + set; + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public object Sinistro + { + get + { + return this._sinistro; + } + set + { + this._sinistro = value; + base.OnPropertyChanged("Sinistro"); + } + } + + public Visibility VisibilityMultRisco + { + get + { + return this._visibilityMultRisco; + } + set + { + this._visibilityMultRisco = value; + base.OnPropertyChanged("VisibilityMultRisco"); + } + } + + public bool VisibilityTitulares + { + get + { + return this._visibilityTitulares; + } + set + { + this._visibilityTitulares = value; + base.OnPropertyChanged("VisibilityTitulares"); + } + } + + public RiscosDiversosViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new RiscosDiversosServico(); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + this.VisibilityTitulares = this.Ramo.get_Id() == (long)31; + this.VisibilityMultRisco = (this.Ramo.get_Id() == (long)33 ? Visibility.Visible : Visibility.Collapsed); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + this.Sinistro = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + item.set_RiscosDiversos(new RiscosDiversos()); + Item item2 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item2.set_Substituicao(nullable); + Item item3 = item; + item1 = null; + item = null; + base.Titulares = new ObservableCollection(); + ordem = item3.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item3 = null; + return; + } + } + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item3; + this.SelectedItem.get_RiscosDiversos().set_Item(item3); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item3.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item3 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_RiscosDiversos().set_Id((long)0); + Item selectedItem = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + selectedItem.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar(List titularesGrid) + { + List> keyValuePairs; + string str; + string str1; + string str2; + bool flag; + bool flag1; + bool flag2; + string str3; + if (this.VisibilityTitulares) + { + this.SelectedItem.set_Titulares(titularesGrid); + } + List> keyValuePairs1 = this.SelectedItem.Validate(); + if (keyValuePairs1.Count <= 0) + { + Item selectedItem = this.SelectedItem; + selectedItem.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + selectedItem = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str = ""; + } + else if (base.Mantido) + { + str = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str4 = str; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str4); + } + if (this.VisibilityTitulares) + { + await this._itemServico.DeleteTitulares(base.ExcluirTitulares); + base.ExcluirTitulares = new List(); + } + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str1; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + if (this.VisibilityTitulares) + { + foreach (TitularesVida titularesVida in titularesGrid) + { + titularesVida.set_IdItem(this.SelectedItem.get_Id()); + } + List titularesVidas = new List(); + foreach (TitularesVida titularesVida1 in titularesGrid) + { + if (titularesVida1.get_Id() != 0) + { + TitularesVida titularesVida2 = base.OldTitulares.First((TitularesVida x) => x.get_Id() == titularesVida1.get_Id()); + if (titularesVida1.get_Codigo() == titularesVida2.get_Codigo()) + { + DateTime? inicio = titularesVida1.get_Inicio(); + DateTime? fim = titularesVida2.get_Inicio(); + if (inicio.HasValue == fim.HasValue) + { + flag = (inicio.HasValue ? inicio.GetValueOrDefault() != fim.GetValueOrDefault() : false); + } + else + { + flag = true; + } + if (!flag) + { + fim = titularesVida1.get_Fim(); + inicio = titularesVida2.get_Fim(); + if (fim.HasValue == inicio.HasValue) + { + flag1 = (fim.HasValue ? fim.GetValueOrDefault() != inicio.GetValueOrDefault() : false); + } + else + { + flag1 = true; + } + if (!flag1 && !(titularesVida1.get_Fatura() != titularesVida2.get_Fatura()) && !(titularesVida1.get_Nome() != titularesVida2.get_Nome()) && !(titularesVida1.get_Observacao() != titularesVida2.get_Observacao())) + { + inicio = titularesVida1.get_Nascimento(); + fim = titularesVida2.get_Nascimento(); + if (inicio.HasValue == fim.HasValue) + { + flag2 = (inicio.HasValue ? inicio.GetValueOrDefault() != fim.GetValueOrDefault() : false); + } + else + { + flag2 = true; + } + if (!flag2 && !(titularesVida1.get_Cpf() != titularesVida2.get_Cpf()) && !(titularesVida1.get_Matricula() != titularesVida2.get_Matricula())) + { + decimal? premio = titularesVida1.get_Premio(); + decimal? capital = titularesVida2.get_Premio(); + if ((premio.GetValueOrDefault() == capital.GetValueOrDefault()) & premio.HasValue == capital.HasValue) + { + capital = titularesVida1.get_Capital(); + premio = titularesVida2.get_Capital(); + if ((capital.GetValueOrDefault() == premio.GetValueOrDefault()) & capital.HasValue == premio.HasValue) + { + TipoTitular? tipo = titularesVida1.get_Tipo(); + TipoTitular? nullable = titularesVida2.get_Tipo(); + if (tipo.GetValueOrDefault() == nullable.GetValueOrDefault() & tipo.HasValue == nullable.HasValue && (object)titularesVida1.get_Dependente() == (object)titularesVida2.get_Dependente()) + { + continue; + } + } + } + } + } + } + } + titularesVidas.Add(titularesVida1); + } + else + { + titularesVidas.Add(titularesVida1); + } + } + base.Titulares = new ObservableCollection(await this._itemServico.SaveTitulares(titularesVidas)); + } + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str2 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str5 = str2; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str5); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str6 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable1 = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str6, id, nullable1, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + base.Titulares = new ObservableCollection(); + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + RiscosDiversos riscosDiverso = await this._itemServico.BuscaRiscosDiversos(item.get_Id()); + Item item2 = item1; + RiscosDiversos riscosDiverso1 = riscosDiverso; + if (riscosDiverso1 == null) + { + riscosDiverso1 = new RiscosDiversos(); + riscosDiverso1.set_Item(item); + } + item2.set_RiscosDiversos(riscosDiverso1); + item1 = null; + if (this.VisibilityTitulares) + { + await base.CarregarTitulares(item.get_Id()); + } + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/VidaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/VidaViewModel.cs new file mode 100644 index 0000000..e128b48 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/Itens/VidaViewModel.cs @@ -0,0 +1,661 @@ +using Gestor.Application.Actions; +using Gestor.Application.Componentes; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.ViewModels.Seguros; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros.Itens +{ + public class VidaViewModel : ItemViewModel, IDisposable + { + private readonly ItemServico _itemServico; + + private readonly VidaServico _servico; + + private bool _allowAlterarExcluir = true; + + private object _cobertura; + + private string _codigoItem; + + private Item _selectedItem = new Item(); + + private Visibility _atualizarCamposSaude; + + public bool AllowAlterarExcluir + { + get + { + return this._allowAlterarExcluir; + } + set + { + this._allowAlterarExcluir = value; + base.OnPropertyChanged("AllowAlterarExcluir"); + } + } + + public Visibility AtualizarCamposSaude + { + get + { + return this._atualizarCamposSaude; + } + set + { + this._atualizarCamposSaude = value; + base.OnPropertyChanged("AtualizarCamposSaude"); + } + } + + public object Cobertura + { + get + { + return this._cobertura; + } + set + { + this._cobertura = value; + base.OnPropertyChanged("Cobertura"); + } + } + + public string CodigoItem + { + get + { + return this._codigoItem; + } + set + { + this._codigoItem = value; + base.OnPropertyChanged("CodigoItem"); + } + } + + public bool Invoke + { + get; + set; + } + + private Item ItemSelecionado + { + get; + set; + } + + private Gestor.Model.Domain.Seguros.Ramo Ramo + { + get; + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public VidaViewModel(bool substituir = false, ManutencaoItem manutencao = null, Item itemSelecionado = null, Gestor.Model.Domain.Seguros.Ramo ramo = null, bool endossoRenovacao = false) + { + this.Invoke = itemSelecionado == null; + this.ItemSelecionado = itemSelecionado ?? ConsultaViewModel.ItemSelecionado; + this.Ramo = ramo ?? ConsultaViewModel.DocumentoSelecionado.get_Controle().get_Ramo(); + if (this.Invoke) + { + this.ItemSelecionado = this.ItemSelecionado ?? new Item(); + this.ItemSelecionado.set_Documento(ConsultaViewModel.DocumentoSelecionado); + } + this._itemServico = new ItemServico(); + this._servico = new VidaServico(); + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + this.Seleciona(this.ItemSelecionado); + if (substituir) + { + this.Substituir(this.ItemSelecionado); + } + if (manutencao != null) + { + this.Manter(this.ItemSelecionado, manutencao); + } + this.AllowAlterarExcluir = !endossoRenovacao; + this.CarregaCobertura(); + } + + public async void CancelarAlteracao() + { + base.Loading(true); + base.AllSelected = new bool?(false); + await this.SelecionaItem(this.ItemSelecionado, false); + await this.CoberturaViewModel.CancelarAlteracao(); + base.Alterar(false); + base.Loading(false); + } + + public void CarregaCobertura() + { + this.CoberturaViewModel.Item = this.ItemSelecionado; + this.CoberturaViewModel.Ramo = this.Ramo; + this.Cobertura = new CoberturaView(this.CoberturaViewModel); + } + + public void Descarregar() + { + this.Cobertura = null; + } + + public void Dispose() + { + Gestor.Application.Actions.Actions.UpdateItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.UpdateItem, new Action(this.Seleciona)); + Gestor.Application.Actions.Actions.SubstituirItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.SubstituirItem, new Action(this.Substituir)); + Gestor.Application.Actions.Actions.ManterItem = (Action)Delegate.Remove(Gestor.Application.Actions.Actions.ManterItem, new Action(this.Manter)); + } + + public async Task Excluir() + { + bool flag; + if (this.SelectedItem == null || this.SelectedItem.get_Id() == 0) + { + flag = false; + } + else if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool flag1 = await this._servico.Delete(this.SelectedItem); + base.Loading(false); + if (flag1) + { + string str = string.Concat("EXCLUIU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " EXCLUÍDO COM SUCESSO"), true); + flag = true; + } + else + { + await base.ShowMessage("NÃO POSSÍVEL EXCLUIR O ITEM", "OK", "", false); + flag = false; + } + } + else + { + flag = false; + } + return flag; + } + + public async Task Incluir(bool substituir = false) + { + int? ordem; + List coberturas; + long? nullable; + coberturas = (this.CoberturaViewModel.Coberturas == null ? this.CoberturaViewModel.CarregaCoberturaPadrao().ToList() : this.CoberturaViewModel.Coberturas.ToList()); + List coberturas1 = coberturas; + Item item = new Item(); + item.set_Documento(this.ItemSelecionado.get_Documento()); + Item item1 = item; + ordem = (substituir ? base.ItemSubstituido.get_Ordem() : new int?(await base.QuantidadeDeItens(this.ItemSelecionado.get_Documento().get_Controle().get_Id()))); + item1.set_Ordem(ordem); + Item item2 = item; + Vida vida = new Vida(); + vida.set_Item(this.SelectedItem); + item2.set_Vida(vida); + Item item3 = item; + if (substituir) + { + nullable = new long?(base.ItemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item3.set_Substituicao(nullable); + Item item4 = item; + item1 = null; + item = null; + base.Titulares = new ObservableCollection(); + ordem = item4.get_Ordem(); + if (ordem.GetValueOrDefault() == 2) + { + if (!await base.ShowMessage("ESTA APÓLICE SERÁ UMA FROTA, DESEJA CONTINUAR?", "SIM", "NÃO", false)) + { + coberturas1 = null; + item4 = null; + return; + } + } + bool valueOrDefault = substituir; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA COPIAR OS DADOS DO ITEM?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.SelectedItem = item4; + this.SelectedItem.get_Vida().set_Item(item4); + } + else + { + this.SelectedItem.set_Id((long)0); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + } + ordem = item4.get_Ordem(); + int num = 1; + valueOrDefault = ordem.GetValueOrDefault() > num & ordem.HasValue; + if (valueOrDefault) + { + valueOrDefault = await base.ShowMessage("DESEJA REPLICAR AS COBERTURAS DO ITEM SELECIONADO?", "SIM", "NÃO", false); + } + if (!valueOrDefault) + { + this.CoberturaViewModel.CarregaPadrao(); + } + else + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + if (substituir) + { + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + coberturas1.ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + base.Alterar(true); + coberturas1 = null; + item4 = null; + } + + public void Manter(Item item, ManutencaoItem manutencao) + { + if (manutencao.get_Tipo() == 1) + { + base.ItemSubstituido = item; + } + this.Manter(manutencao); + base.Mantido = true; + } + + public void Manter(ManutencaoItem manutencao) + { + long? nullable; + object list; + bool flag; + ObservableCollection coberturas = this.CoberturaViewModel.Coberturas; + if (coberturas != null) + { + list = coberturas.ToList(); + } + else + { + list = null; + } + List nums = new List() + { + (long)6, + (long)7, + (long)9, + (long)10, + (long)47, + (long)53, + (long)66 + }; + if (this.SelectedItem.get_Vida() == null) + { + this.SelectedItem.set_Vida(new Vida()); + } + if (this.ItemSelecionado.get_Documento().get_Controle().get_Id() != this.SelectedItem.get_Documento().get_Controle().get_Id()) + { + Item selectedItem = this.SelectedItem; + if (selectedItem != null) + { + flag = selectedItem.get_Sinistros().Count() > 0; + } + else + { + flag = false; + } + if (flag && manutencao.get_Tipo() == null) + { + goto Label1; + } + if (!nums.Contains(this.Ramo.get_Id())) + { + this.SelectedItem.set_Id((long)0); + goto Label0; + } + else + { + goto Label0; + } + } + Label1: + this.SelectedItem.set_Id((long)0); + this.SelectedItem.get_Vida().set_Id((long)0); + Label0: + Item item = this.SelectedItem; + Item itemSubstituido = base.ItemSubstituido; + if (itemSubstituido != null) + { + nullable = new long?(itemSubstituido.get_Id()); + } + else + { + nullable = null; + } + item.set_Substituicao(nullable); + this.SelectedItem.set_Documento(this.ItemSelecionado.get_Documento()); + if (manutencao.get_Tipo() == null) + { + this.SelectedItem.set_Sinistrado(false); + this.SelectedItem.set_Status(""); + this.SelectedItem.set_Sinistro(null); + this.SelectedItem.set_Sinistros(null); + } + this.CoberturaViewModel.CarregaPadrao(); + this.CoberturaViewModel.Coberturas = new ObservableCollection(); + if (list != null) + { + ((List)list).ForEach((Gestor.Model.Domain.Seguros.Cobertura x) => { + x.set_Item(this.SelectedItem); + this.CoberturaViewModel.Coberturas.Add(x); + }); + } + else + { + } + base.Alterar(true); + } + + public async Task>> Salvar(List titularesGrid) + { + List> keyValuePairs; + DateTime? inicio; + string plano; + string str; + string str1; + bool flag; + bool flag1; + bool flag2; + string str2; + string str3; + Item selectedItem = this.SelectedItem; + if (string.IsNullOrWhiteSpace(this.SelectedItem.get_Descricao())) + { + plano = this.SelectedItem.get_Vida().get_Plano(); + if (plano == null) + { + plano = ""; + } + } + else + { + plano = this.SelectedItem.get_Descricao(); + } + selectedItem.set_Descricao(plano); + this.SelectedItem.set_Titulares(titularesGrid); + List> keyValuePairs1 = this.SelectedItem.Validate(); + if (keyValuePairs1.Count <= 0) + { + Item item = this.SelectedItem; + item.set_Coberturas(await this.CoberturaViewModel.LimpaCoberturas()); + item = null; + if (this.SelectedItem.get_Documento().get_Ordem() <= 0) + { + str = ""; + } + else if (base.Mantido) + { + str = string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()); + } + else + { + str = (base.ItemSubstituido != null ? string.Format("SUBSTITUIÇÃO DO ITEM {0} NO ENDOSSO ORDEM {1}", base.ItemSubstituido.get_Ordem(), this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM INCLUÍDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + } + string str4 = str; + if (this.SelectedItem.get_Id() == 0) + { + this.SelectedItem.set_Status(str4); + } + await this._itemServico.DeleteTitulares(base.ExcluirTitulares); + base.ExcluirTitulares = new List(); + str1 = (this.SelectedItem.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str3 = str1; + this.SelectedItem = await this._itemServico.Save(this.SelectedItem); + foreach (TitularesVida titularesVida in titularesGrid) + { + titularesVida.set_IdItem(this.SelectedItem.get_Id()); + } + List titularesVidas = new List(); + foreach (TitularesVida titularesVida1 in titularesGrid) + { + if (titularesVida1.get_Id() != 0) + { + TitularesVida titularesVida2 = base.OldTitulares.First((TitularesVida x) => x.get_Id() == titularesVida1.get_Id()); + if (titularesVida1.get_Codigo() == titularesVida2.get_Codigo()) + { + inicio = titularesVida1.get_Inicio(); + DateTime? fim = titularesVida2.get_Inicio(); + if (inicio.HasValue == fim.HasValue) + { + flag = (inicio.HasValue ? inicio.GetValueOrDefault() != fim.GetValueOrDefault() : false); + } + else + { + flag = true; + } + if (!flag) + { + fim = titularesVida1.get_Fim(); + inicio = titularesVida2.get_Fim(); + if (fim.HasValue == inicio.HasValue) + { + flag1 = (fim.HasValue ? fim.GetValueOrDefault() != inicio.GetValueOrDefault() : false); + } + else + { + flag1 = true; + } + if (!flag1 && !(titularesVida1.get_Fatura() != titularesVida2.get_Fatura()) && !(titularesVida1.get_Nome() != titularesVida2.get_Nome()) && !(titularesVida1.get_Observacao() != titularesVida2.get_Observacao())) + { + inicio = titularesVida1.get_Nascimento(); + fim = titularesVida2.get_Nascimento(); + if (inicio.HasValue == fim.HasValue) + { + flag2 = (inicio.HasValue ? inicio.GetValueOrDefault() != fim.GetValueOrDefault() : false); + } + else + { + flag2 = true; + } + if (!flag2 && !(titularesVida1.get_Cpf() != titularesVida2.get_Cpf()) && !(titularesVida1.get_Matricula() != titularesVida2.get_Matricula())) + { + decimal? premio = titularesVida1.get_Premio(); + decimal? capital = titularesVida2.get_Premio(); + if ((premio.GetValueOrDefault() == capital.GetValueOrDefault()) & premio.HasValue == capital.HasValue) + { + capital = titularesVida1.get_Capital(); + premio = titularesVida2.get_Capital(); + if ((capital.GetValueOrDefault() == premio.GetValueOrDefault()) & capital.HasValue == premio.HasValue) + { + TipoTitular? tipo = titularesVida1.get_Tipo(); + TipoTitular? nullable = titularesVida2.get_Tipo(); + if (tipo.GetValueOrDefault() == nullable.GetValueOrDefault() & tipo.HasValue == nullable.HasValue && (object)titularesVida1.get_Dependente() == (object)titularesVida2.get_Dependente()) + { + continue; + } + } + } + } + } + } + } + titularesVidas.Add(titularesVida1); + } + else + { + inicio = titularesVida1.get_Inicio(); + if (!inicio.HasValue) + { + continue; + } + titularesVidas.Add(titularesVida1); + } + } + base.Titulares = new ObservableCollection(await this._itemServico.SaveTitulares(titularesVidas)); + if (this._itemServico.Sucesso) + { + if (base.ItemSubstituido != null) + { + str2 = (base.Mantido ? string.Format("ITEM ALTERADO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem()) : string.Format("ITEM SUBSTITUIDO NO ENDOSSO ORDEM {0}", this.SelectedItem.get_Documento().get_Ordem())); + string str5 = str2; + await this._itemServico.Substituir(base.ItemSubstituido, this.SelectedItem.get_Id(), str5); + } + base.Mantido = false; + await this.SelecionaItem(this.SelectedItem, false); + this.ItemSelecionado = this.SelectedItem; + if (this.Invoke) + { + ConsultaViewModel.ItemSelecionado = this.SelectedItem; + } + base.ToggleSnackBar(string.Concat(this.Ramo.get_Nome(), " SALVO COM SUCESSO"), true); + string str6 = string.Concat(str3, " ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable1 = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str6, id, nullable1, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str3 = null; + return keyValuePairs; + } + + private async void Seleciona(Item item) + { + base.Loading(true); + await base.PermissaoTela(3); + await this.SelecionaItem(item, true); + base.Loading(false); + } + + public async Task SelecionaItem(Item item, bool registrar = true) + { + Visibility visibility; + if (item == null || this.LastAccessId != item.get_Id() || this.LastAccessTela != 9) + { + base.Mantido = false; + List nums = new List() + { + (long)6, + (long)7, + (long)9, + (long)10, + (long)47, + (long)53, + (long)66 + }; + if (nums.Contains(this.Ramo.get_Id())) + { + VidaViewModel vidaViewModel = this; + visibility = (this.Ramo.get_Id() == (long)9 ? Visibility.Collapsed : Visibility.Visible); + vidaViewModel.AtualizarCamposSaude = visibility; + this.CoberturaViewModel.Ramo = this.Ramo; + if (this.CoberturaViewModel.CoberturasPadrao == null) + { + await this.CoberturaViewModel.SelectionaCoberturas(); + } + if (item == null || item.get_Id() == 0) + { + this.SelectedItem = null; + this.CoberturaViewModel.Coberturas = null; + base.IsVisible = Visibility.Visible; + base.Titulares = new ObservableCollection(); + } + else + { + base.Loading(true); + item = await this._itemServico.BuscarItemPorIdAsync(item.get_Id()); + Item item1 = item; + Vida vida = await this._itemServico.BuscaVida(item.get_Id()); + item1.set_Vida(vida); + item1 = null; + await base.CarregarTitulares(item.get_Id()); + this.SelectedItem = item; + this.SelectedItem.Initialize(); + this.Initialized = true; + this.CoberturaViewModel.Item = item; + await this.CoberturaViewModel.CancelarAlteracao(); + if (registrar) + { + string str = string.Concat("ACESSOU ITEM DE DESCRIÇÃO \"", this.SelectedItem.get_Descricao(), "\""); + long id = this.SelectedItem.get_Id(); + TipoTela? nullable = new TipoTela?(3); + object[] objArray = new object[] { this.SelectedItem.get_Id(), this.SelectedItem.get_Documento().get_Id(), this.SelectedItem.get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedItem.get_Documento().get_Controle().get_Cliente().get_Id() }; + base.RegistrarAcao(str, id, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}", objArray)); + } + this.LastAccessId = this.SelectedItem.get_Id(); + this.LastAccessTela = 3; + this.CodigoItem = this.SelectedItem.get_Id().ToString(); + base.Loading(false); + } + } + } + } + + public async void Substituir(Item item) + { + base.ItemSubstituido = item; + await this.Incluir(true); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilEmpresaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilEmpresaViewModel.cs new file mode 100644 index 0000000..0c116ab --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilEmpresaViewModel.cs @@ -0,0 +1,274 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.Helper; +using Gestor.Model.Resources; +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class PerfilEmpresaViewModel : BaseViewModel + { + private readonly PerfilEmpresaServico _servico; + + private readonly Controle _controle; + + private Visibility _ativaCampos = Visibility.Collapsed; + + private string _equipamentoSeguranca = ""; + + private string _equipamentoIncendio = ""; + + private bool _enableIncluirPerfil; + + private string _dataConstrucao; + + public long CancelPerfil; + + private PerfilEmpresa _selectedPerfilEmpresa = new PerfilEmpresa(); + + public Visibility AtivaCampos + { + get + { + return this._ativaCampos; + } + set + { + this._ativaCampos = value; + base.OnPropertyChanged("AtivaCampos"); + } + } + + public string DataConstrucao + { + get + { + return this._dataConstrucao; + } + set + { + string str; + if (value != null) + { + str = value.Replace(" ", ""); + } + else + { + str = null; + } + this._dataConstrucao = str; + base.OnPropertyChanged("DataConstrucao"); + } + } + + public bool EnableIncluirPerfil + { + get + { + return this._enableIncluirPerfil; + } + set + { + this._enableIncluirPerfil = value; + base.OnPropertyChanged("EnableIncluirPerfil"); + } + } + + public string EquipamentoIncendio + { + get + { + return this._equipamentoIncendio; + } + set + { + this._equipamentoIncendio = value; + base.OnPropertyChanged("EquipamentoIncendio"); + } + } + + public string EquipamentoSeguranca + { + get + { + return this._equipamentoSeguranca; + } + set + { + this._equipamentoSeguranca = value; + base.OnPropertyChanged("EquipamentoSeguranca"); + } + } + + public PerfilEmpresa SelectedPerfilEmpresa + { + get + { + return this._selectedPerfilEmpresa; + } + set + { + long? nullable; + this._selectedPerfilEmpresa = value; + if (value != null && value.get_Id() > (long)0) + { + this.CancelPerfil = value.get_Id(); + } + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedPerfilEmpresa"); + } + } + + public PerfilEmpresaViewModel(Controle controle) + { + this._servico = new PerfilEmpresaServico(); + this._controle = controle; + this.Seleciona(controle.get_Id()); + } + + public void CancelarAlteracao() + { + base.Loading(true); + base.Alterar(false); + base.Loading(false); + } + + public async Task Excluir() + { + if (this.SelectedPerfilEmpresa != null && this.SelectedPerfilEmpresa.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + if (await this._servico.Delete(this.SelectedPerfilEmpresa)) + { + await this.SelecionaPerfil(this._controle.get_Id()); + base.Loading(false); + this.EnableIncluirPerfil = true; + this.AtivaCampos = Visibility.Collapsed; + this.DataConstrucao = null; + base.ToggleSnackBar("PERFIL EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public void Incluir() + { + PerfilEmpresa perfilEmpresa = new PerfilEmpresa(); + perfilEmpresa.set_Controle(this._controle); + perfilEmpresa.set_Cliente(this._controle.get_Cliente()); + perfilEmpresa.set_ExclusivoDeposito(new bool?(false)); + perfilEmpresa.set_DivisaTerrenoBaldio(new bool?(false)); + perfilEmpresa.set_PatrimonioHistorio(new bool?(false)); + perfilEmpresa.set_PossuiTelhado(new bool?(false)); + perfilEmpresa.set_CaixasEletronicos(new bool?(false)); + perfilEmpresa.set_Isopainel(new bool?(false)); + perfilEmpresa.set_ConstrucaoReforma(new bool?(false)); + this.SelectedPerfilEmpresa = perfilEmpresa; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedPerfilEmpresa.Validate(); + keyValuePairs1 = this.ValidateCampos(keyValuePairs1); + if (keyValuePairs1.Count <= 0) + { + if (this.DataConstrucao != null && this.DataConstrucao != "") + { + this.SelectedPerfilEmpresa.set_AnoConstrucao(new DateTime?(DateTime.Parse(string.Concat("01/01/", this.DataConstrucao)))); + } + this.SelectedPerfilEmpresa = await this._servico.Save(this.SelectedPerfilEmpresa); + if (this._servico.Sucesso) + { + await this.SelecionaPerfil(this._controle.get_Id()); + base.ToggleSnackBar("PERFIL SALVO COM SUCESSO", true); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + private async void Seleciona(long id) + { + base.Loading(true); + await base.PermissaoTela(32); + await this.SelecionaPerfil(id); + base.Loading(false); + } + + private async Task SelecionaPerfil(long id) + { + base.Loading(true); + this.SelectedPerfilEmpresa = await this._servico.BuscarPerfis(id); + if (this.SelectedPerfilEmpresa == null) + { + this.EnableIncluirPerfil = true; + this.EquipamentoSeguranca = ""; + this.EquipamentoIncendio = ""; + } + else + { + this.EquipamentoSeguranca = BindingEnumHelper.ConcatenarDescricoesEnum(this.SelectedPerfilEmpresa.get_EquipamentoSeguranca()); + this.EquipamentoIncendio = BindingEnumHelper.ConcatenarDescricoesEnum(this.SelectedPerfilEmpresa.get_EquipamentoIncendio()); + if (this.SelectedPerfilEmpresa.get_AnoConstrucao().HasValue) + { + DateTime? anoConstrucao = this.SelectedPerfilEmpresa.get_AnoConstrucao(); + this.DataConstrucao = anoConstrucao.Value.Year.ToString(); + } + } + base.Loading(false); + } + + private List> ValidateCampos(List> errorMessages) + { + int num; + int num1; + if (this.DataConstrucao == null) + { + ValidationHelper.AddValue(errorMessages, "ANO DA CONSTRUÇÃO", Messages.get_DataInvalida(), true); + } + if (!int.TryParse(this.DataConstrucao, out num)) + { + ValidationHelper.AddValue(errorMessages, "ANO DA CONSTRUÇÃO", Messages.get_DataInvalida(), true); + } + if (this.DataConstrucao != null && int.TryParse(this.DataConstrucao, out num1) && (int.Parse(this.DataConstrucao) <= 1755 || int.Parse(this.DataConstrucao) >= 9999)) + { + ValidationHelper.AddValue(errorMessages, "ANO DA CONSTRUÇÃO", Messages.get_DataInvalida(), true); + } + return errorMessages; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilViewModel.cs new file mode 100644 index 0000000..dd3313a --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/PerfilViewModel.cs @@ -0,0 +1,183 @@ +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class PerfilViewModel : BaseViewModel + { + private readonly PerfilServico _servico; + + private readonly Controle _controle; + + public long CancelPerfil; + + private Perfil _selectedPerfil = new Perfil(); + + private ObservableCollection _perfis; + + public ObservableCollection Perfis + { + get + { + return this._perfis; + } + set + { + this._perfis = value; + base.OnPropertyChanged("Perfis"); + } + } + + public Perfil SelectedPerfil + { + get + { + return this._selectedPerfil; + } + set + { + long? nullable; + this._selectedPerfil = value; + if (value != null && value.get_Id() > (long)0) + { + this.CancelPerfil = value.get_Id(); + } + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedPerfil"); + } + } + + public PerfilViewModel(Controle controle) + { + this._servico = new PerfilServico(); + this._controle = controle; + this.Seleciona(controle.get_Id()); + } + + public void CancelarAlteracao() + { + base.Loading(true); + if (this.CancelPerfil > (long)0) + { + this.SelectedPerfil = this.Perfis.FirstOrDefault((Perfil x) => x.get_Id() == this.CancelPerfil); + } + base.Alterar(false); + base.Loading(false); + } + + public async Task Excluir() + { + if (this.SelectedPerfil != null && this.SelectedPerfil.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + bool selectedPerfil = (object)this.SelectedPerfil == (object)this.Perfis.Last(); + if (await this._servico.Delete(this.SelectedPerfil)) + { + if (selectedPerfil) + { + int num = this.Perfis.IndexOf(this.SelectedPerfil); + if (num <= 0) + { + await this.SelecionaPerfis(this._controle.get_Id(), (long)0); + } + else + { + await this.SelecionaPerfis(this._controle.get_Id(), this.Perfis[num - 1].get_Id()); + } + } + else if (this.Perfis.Count > 0) + { + await this.SelecionaPerfis(this._controle.get_Id(), this.Perfis[this.Perfis.IndexOf(this.SelectedPerfil) + 1].get_Id()); + } + base.Loading(false); + base.ToggleSnackBar("PERFIL EXCLUÍDO COM SUCESSO", true); + } + else + { + base.Loading(false); + } + } + } + } + + public void Incluir() + { + Perfil perfil = new Perfil(); + perfil.set_Controle(this._controle); + perfil.set_Cliente(this._controle.get_Cliente()); + perfil.set_UsoProfissional(new bool?(false)); + perfil.set_AntiFurto(new Antifurto?(0)); + perfil.set_Isencao(new bool?(false)); + perfil.set_SeguroVida(new bool?(false)); + perfil.set_EstenderCobertura(new bool?(false)); + this.SelectedPerfil = perfil; + base.Alterar(true); + } + + public async Task>> Salvar() + { + List> keyValuePairs; + List> keyValuePairs1 = this.SelectedPerfil.Validate(); + if (keyValuePairs1.Count <= 0) + { + this.SelectedPerfil = await this._servico.Save(this.SelectedPerfil); + if (this._servico.Sucesso) + { + await this.SelecionaPerfis(this._controle.get_Id(), this.SelectedPerfil.get_Id()); + base.ToggleSnackBar("PERFIL SALVO COM SUCESSO", true); + base.Alterar(false); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + private async void Seleciona(long id) + { + base.Loading(true); + await base.PermissaoTela(32); + await this.SelecionaPerfis(id, (long)0); + base.Loading(false); + } + + private async Task SelecionaPerfis(long id, long perfilId = 0L) + { + Perfil perfil; + base.Loading(true); + this.Perfis = new ObservableCollection(await this._servico.BuscarPerfis(id)); + PerfilViewModel perfilViewModel = this; + perfil = (perfilId == 0 ? this.Perfis.FirstOrDefault() : this.Perfis.First((Perfil x) => x.get_Id() == perfilId)); + perfilViewModel.SelectedPerfil = perfil; + base.Loading(false); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/SinistroViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/SinistroViewModel.cs new file mode 100644 index 0000000..c7359e8 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/SinistroViewModel.cs @@ -0,0 +1,2104 @@ +using Gestor.Application.Drawers; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.Servicos.Seguros.Itens; +using Gestor.Application.ViewModels.Generic; +using Gestor.Application.Views.Ferramentas; +using Gestor.Application.Views.Generic; +using Gestor.Common.Validation; +using Gestor.Model.Common; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.MalaDireta; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Windows; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class SinistroViewModel : BaseSegurosViewModel + { + private readonly SinistroServico _servico; + + private readonly ItemServico _itemServico; + + private readonly Documento _documentoSelecionado; + + private readonly ClienteServico _clienteServico; + + private bool _editarObservacao = Recursos.Configuracoes.Any(new Func((ConfiguracaoSistema x) => x.get_Configuracao() == 49)); + + private bool _isAnotacoes = true; + + private List _tipoPerdaAuto = new List() + { + 1, + 2, + 4, + 3, + 8 + }; + + private List _tipoPerdaVida = new List() + { + 5, + 6, + 7, + 8 + }; + + private Credencial _selectedCredencial = new Credencial(); + + private List _credenciais = new List(); + + private ObservableCollection _itens = new ObservableCollection(); + + private ObservableCollection _itensFiltrados = new ObservableCollection(); + + private ObservableCollection _parceiros = new ObservableCollection(SinistroViewModel.GerarParceiros()); + + private bool _habilitarImprimirHistorico; + + private bool _habilitarEnviarHistorico; + + private Visibility _isVisibleImprimirHistorico; + + private Visibility _isVisibleIncluir; + + private Visibility _isVisibleTerceiro = Visibility.Collapsed; + + private Visibility _visibilityAuto = Visibility.Collapsed; + + private Visibility _visibilityVida = Visibility.Collapsed; + + private Visibility _liquidacaoVisibility; + + private bool _isReadOnlyItem = true; + + private bool _tipoSinistroEnabled; + + private Item _selectedItem = new Item(); + + private bool _mostrarLista; + + private bool _isExpandedItem = true; + + private bool _isExpandedSinistro = true; + + private List _controles = new List(); + + private ObservableCollection _controlesFiltrados = new ObservableCollection(); + + private ControleSinistro _selectedControle = new ControleSinistro(); + + private Sinistro _selectedSinistro; + + private string _codigoSinistro; + + private string _anotacoes; + + private string _anotacoesInternas; + + private string _telefonesMecanica; + + private string _telefonesFunileiro; + + public new string Anotacoes + { + get + { + return this._anotacoes; + } + set + { + this._anotacoes = value; + base.OnPropertyChanged("Anotacoes"); + } + } + + public string AnotacoesInternas + { + get + { + return this._anotacoesInternas; + } + set + { + this._anotacoesInternas = value; + base.OnPropertyChanged("AnotacoesInternas"); + } + } + + private bool Carregando + { + get; + set; + } + + public string CodigoSinistro + { + get + { + return this._codigoSinistro; + } + set + { + this._codigoSinistro = value; + base.OnPropertyChanged("CodigoSinistro"); + } + } + + public List Controles + { + get + { + return this._controles; + } + set + { + this._controles = value; + base.EnableIncluir = (value == null ? true : value.Count == 0); + base.OnPropertyChanged("Controles"); + } + } + + public ObservableCollection ControlesFiltrados + { + get + { + return this._controlesFiltrados; + } + set + { + this._controlesFiltrados = value; + this.IsExpandedSinistro = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("ControlesFiltrados"); + } + } + + public List Credenciais + { + get + { + return this._credenciais; + } + set + { + this._credenciais = value; + base.OnPropertyChanged("Credenciais"); + } + } + + public bool EditarObservacao + { + get + { + return this._editarObservacao; + } + set + { + this._editarObservacao = value; + base.OnPropertyChanged("EditarObservacao"); + } + } + + public int FiltroItens + { + get; + set; + } + + public bool HabilitarEnviarHistorico + { + get + { + return this._habilitarEnviarHistorico; + } + set + { + this._habilitarEnviarHistorico = value; + base.OnPropertyChanged("HabilitarEnviarHistorico"); + } + } + + public bool HabilitarImprimirHistorico + { + get + { + return this._habilitarImprimirHistorico; + } + set + { + this._habilitarImprimirHistorico = value; + base.OnPropertyChanged("HabilitarImprimirHistorico"); + } + } + + public bool IsAnotacoes + { + get + { + return this._isAnotacoes; + } + set + { + this._isAnotacoes = value; + base.OnPropertyChanged("IsAnotacoes"); + } + } + + public bool IsExpandedItem + { + get + { + return this._isExpandedItem; + } + set + { + this._isExpandedItem = value; + base.OnPropertyChanged("IsExpandedItem"); + } + } + + public bool IsExpandedSinistro + { + get + { + return this._isExpandedSinistro; + } + set + { + this._isExpandedSinistro = value; + base.OnPropertyChanged("IsExpandedSinistro"); + } + } + + public bool IsReadOnlyItem + { + get + { + return this._isReadOnlyItem; + } + set + { + this._isReadOnlyItem = value; + base.OnPropertyChanged("IsReadOnlyItem"); + } + } + + public Visibility IsVisibleImprimirHistorico + { + get + { + return this._isVisibleImprimirHistorico; + } + set + { + this._isVisibleImprimirHistorico = value; + base.OnPropertyChanged("IsVisibleImprimirHistorico"); + } + } + + public Visibility IsVisibleIncluir + { + get + { + return this._isVisibleIncluir; + } + set + { + this._isVisibleIncluir = value; + base.OnPropertyChanged("IsVisibleIncluir"); + } + } + + public Visibility IsVisibleTerceiro + { + get + { + return this._isVisibleTerceiro; + } + set + { + this._isVisibleTerceiro = value; + base.OnPropertyChanged("IsVisibleTerceiro"); + } + } + + public Item ItemSelecionado + { + get; + set; + } + + public ObservableCollection Itens + { + get + { + return this._itens; + } + set + { + this._itens = value; + base.OnPropertyChanged("Itens"); + } + } + + public ObservableCollection ItensFiltrados + { + get + { + return this._itensFiltrados; + } + set + { + this._itensFiltrados = value; + this.IsExpandedItem = (value != null ? value.Count > 0 : false); + base.OnPropertyChanged("ItensFiltrados"); + } + } + + public Visibility LiquidacaoVisibility + { + get + { + return this._liquidacaoVisibility; + } + set + { + this._liquidacaoVisibility = value; + base.OnPropertyChanged("LiquidacaoVisibility"); + } + } + + public bool MostrarLista + { + get + { + return this._mostrarLista; + } + set + { + this._mostrarLista = value; + base.OnPropertyChanged("MostrarLista"); + } + } + + public ObservableCollection Parceiros + { + get + { + return this._parceiros; + } + set + { + this._parceiros = value; + base.OnPropertyChanged("Parceiros"); + } + } + + public ControleSinistro SelectedControle + { + get + { + return this._selectedControle; + } + set + { + bool count; + this._selectedControle = value; + if (value != null) + { + base.EnableButtons = value.get_Id() > (long)0; + base.EnableIncluir = value.get_Id() > (long)0; + this.IsVisibleTerceiro = (value.get_Sinistros() == null || value.get_Sinistros() != null && value.get_Sinistros().Count < 2 ? Visibility.Collapsed : Visibility.Visible); + this.IsVisibleIncluir = (value.get_Sinistros() == null || !value.get_Sinistros().Any() ? Visibility.Visible : Visibility.Collapsed); + if (this.MostrarLista) + { + count = true; + } + else + { + List controles = this.Controles; + if (controles != null) + { + count = controles.Count > 1; + } + else + { + count = false; + } + } + this.MostrarLista = count; + } + base.OnPropertyChanged("SelectedControle"); + } + } + + public Credencial SelectedCredencial + { + get + { + return this._selectedCredencial; + } + set + { + this._selectedCredencial = value; + base.OnPropertyChanged("SelectedCredencial"); + } + } + + public Item SelectedItem + { + get + { + return this._selectedItem; + } + set + { + long? nullable; + this._selectedItem = value; + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedItem"); + } + } + + public Sinistro SelectedSinistro + { + get + { + return this._selectedSinistro; + } + set + { + long? nullable; + this._selectedSinistro = value; + this.Anotacoes = string.Empty; + this.AnotacoesInternas = string.Empty; + this.HabilitarImprimirHistorico = value != null; + this.HabilitarEnviarHistorico = value != null; + this.CodigoSinistro = (this.SelectedSinistro == null || this.SelectedSinistro.get_Id() == 0 ? "" : string.Format("CÓDIGO SINISTRO {0}", this.SelectedSinistro.get_Id())); + if (value != null && value.get_Id() != 0 && (this.LastAccessId != value.get_Id() || this.LastAccessTela != 7)) + { + base.RegistrarAcao(string.Format("ACESSOU SINISTRO DE ID \"{0}\"", value.get_Id()), value.get_Id(), new TipoTela?(7), string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}\nDESCRIÇÃO: \"{5}\"", new object[] { value.get_ControleSinistro().get_Item().get_Id(), value.get_ControleSinistro().get_Item().get_Documento().get_Id(), value.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Ramo().get_Nome(), value.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome(), value.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id(), value.get_Descricao() })); + this.LastAccessId = value.get_Id(); + this.LastAccessTela = 7; + } + if (value != null) + { + nullable = new long?(value.get_Id()); + } + else + { + nullable = null; + } + base.VerificarEnables(nullable); + base.OnPropertyChanged("SelectedSinistro"); + } + } + + public string TelefonesFunileiro + { + get + { + return this._telefonesFunileiro; + } + set + { + this._telefonesFunileiro = value; + base.OnPropertyChanged("TelefonesFunileiro"); + } + } + + public string TelefonesMecanica + { + get + { + return this._telefonesMecanica; + } + set + { + this._telefonesMecanica = value; + base.OnPropertyChanged("TelefonesMecanica"); + } + } + + public List TipoPerdaAuto + { + get + { + return this._tipoPerdaAuto; + } + set + { + this._tipoPerdaAuto = value; + base.OnPropertyChanged("TipoPerdaAuto"); + } + } + + public List TipoPerdaVida + { + get + { + return this._tipoPerdaVida; + } + set + { + this._tipoPerdaVida = value; + base.OnPropertyChanged("TipoPerdaVida"); + } + } + + public bool TipoSinistroEnabled + { + get + { + return this._tipoSinistroEnabled; + } + set + { + this._tipoSinistroEnabled = value; + base.OnPropertyChanged("TipoSinistroEnabled"); + } + } + + public Visibility VisibilityAuto + { + get + { + return this._visibilityAuto; + } + set + { + this._visibilityAuto = value; + base.OnPropertyChanged("VisibilityAuto"); + } + } + + public Visibility VisibilityVida + { + get + { + return this._visibilityVida; + } + set + { + this._visibilityVida = value; + base.OnPropertyChanged("VisibilityVida"); + } + } + + public SinistroViewModel(Item item, bool attached) + { + bool documento; + bool vendedorPrincipal; + this._servico = new SinistroServico(); + this._itemServico = new ItemServico(); + this._clienteServico = new ClienteServico(); + this._documentoSelecionado = (attached ? ConsultaViewModel.DocumentoSelecionado : item.get_Documento()); + this.FiltroItens = ConsultaViewModel.FiltrarItens; + this.ItemSelecionado = ConsultaViewModel.ItemSelecionado; + if (!attached) + { + this.FiltroItens = 4; + this.ItemSelecionado = item; + } + if (item != null) + { + documento = item.get_Documento(); + } + else + { + documento = false; + } + if (documento) + { + Documento documentoSelecionado = ConsultaViewModel.DocumentoSelecionado; + if (documentoSelecionado != null) + { + vendedorPrincipal = documentoSelecionado.get_VendedorPrincipal(); + } + else + { + vendedorPrincipal = false; + } + if (vendedorPrincipal) + { + item.get_Documento().set_VendedorPrincipal(ConsultaViewModel.DocumentoSelecionado.get_VendedorPrincipal()); + } + } + this.Seleciona(item); + } + + public void AbrirInfo() + { + base.ShowDrawer(new InfoDrawer(this._documentoSelecionado, false), 0, false); + } + + public async Task BuscarClienteSinistro() + { + Cliente cliente = await this._itemServico.BuscarCliente(this.SelectedItem.get_Id()); + return cliente; + } + + public async void CancelarAlteracao() + { + // + // Current member / type: System.Void Gestor.Application.ViewModels.Seguros.SinistroViewModel::CancelarAlteracao() + // File path: C:\AggerSeguros\Gestor.Application.exe + // + // Product version: 0.0.0.0 + // Exception in: System.Void CancelarAlteracao() + // + // Object reference not set to an instance of an object. + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.FindLowestCommonAncestor(ICollection`1 typeNodes) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 515 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.MergeWithLowestCommonAncestor() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 459 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.ProcessSingleConstraints() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 378 + // at Telerik.JustDecompiler.Decompiler.TypeInference.TypeInferer.InferTypes() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\TypeInference\TypeInferer.cs:line 331 + // at Telerik.JustDecompiler.Decompiler.ExpressionDecompilerStep.Process(DecompilationContext theContext, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\ExpressionDecompilerStep.cs:line 104 + // 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.DecompileStateMachine(MethodBody body, DecompilationContext enclosingContext, BaseStateMachineRemoverStep removeStateMachineStep, Func`2 stateMachineDataSelector, DecompilationContext& decompilationContext) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 112 + // at Telerik.JustDecompiler.Decompiler.Extensions.DecompileAsyncStateMachine(MethodBody body, DecompilationContext enclosingContext, AsyncData& asyncData) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Decompiler\Extensions.cs:line 150 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.GetMoveNextStatements() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 161 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Match() in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 76 + // at Telerik.JustDecompiler.Steps.RebuildAsyncStatementsStep.Process(DecompilationContext context, BlockStatement body) in D:\a\CodemerxDecompile\CodemerxDecompile\src\JustDecompileEngine\src\JustDecompiler.Shared\Steps\RebuildAsyncStatementsStep.cs:line 36 + // 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 + + } + + private async Task CarregarControles(Item item) + { + List controleSinistros = await this._servico.BuscarControles(item.get_Id()); + SinistroViewModel list = this; + List controleSinistros1 = controleSinistros; + list.Controles = ( + from x in controleSinistros1 + orderby x.get_DataSinistro() descending + select x).ToList(); + this.ControlesFiltrados = new ObservableCollection(this.Controles); + } + + public void CarregarParceiros() + { + List parceiros = new List(); + Parceiro parceiro = new Parceiro(); + parceiro.set_Nome("NENHUM"); + parceiros.Add(parceiro); + List parceiros1 = parceiros; + parceiros1.AddRange( + from x in Recursos.Parceiros + orderby x.get_Nome() + select x); + this.Parceiros = new ObservableCollection(parceiros1); + } + + public async void EnviarLogEmail() + { + int? nullable; + string nome; + string email; + int? ordem; + List credenciais = this.Credenciais; + if (credenciais == null) + { + credenciais = await (new BaseServico()).BuscarCredenciais(); + } + this.Credenciais = credenciais; + SinistroViewModel sinistroViewModel = this; + List credencials = this.Credenciais; + Credencial credencial = credencials.FirstOrDefault((Credencial x) => x.get_IdUsuario() == Recursos.Usuario.get_Id()); + if (credencial == null) + { + credencial = this.Credenciais.FirstOrDefault(); + } + sinistroViewModel.SelectedCredencial = credencial; + ObservableCollection observableCollection = await this._clienteServico.BuscarEmailsAsync(this.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id()); + if (observableCollection.Count != 0) + { + Documento documento = await (new ApoliceServico()).BuscarApoliceAsync(this._documentoSelecionado.get_Id(), false, false); + SinistroViewModel sinistroViewModel1 = this; + Vendedor vendedorPrincipal = documento.get_VendedorPrincipal(); + if (vendedorPrincipal != null) + { + nome = vendedorPrincipal.get_Nome(); + } + else + { + nome = null; + } + string str = sinistroViewModel1.GerarHtmlSinistro(nome); + string str1 = (new Regex(".*<\\/title>")).Replace(str, " ").Trim(); + str1 = (new Regex("(<[^>]*>)|(p\\s?{[^}]*})|(\\r)|(\\n)")).Replace(str1, " ").Trim(); + str1 = str1.Replace("@page{ size: A4;} body; -webkit-print-color-adjust: exact; }", " "); + str1 = str1.Replace("NEW P { MARGIN-BOTTOM: 0; MARGIN-TOP: 0; }", " "); + MalaDireta malaDiretum = new MalaDireta(); + malaDiretum.set_Cliente(documento.get_Controle().get_Cliente()); + malaDiretum.set_ArquivoDigital(null); + malaDiretum.set_Sinistro(this.SelectedSinistro); + malaDiretum.set_Item(this.SelectedItem); + malaDiretum.set_Apolice(documento); + malaDiretum.set_Tela(7); + ClienteEmail clienteEmail = observableCollection.FirstOrDefault<ClienteEmail>(); + if (clienteEmail != null) + { + email = clienteEmail.get_Email(); + } + else + { + email = null; + } + malaDiretum.set_Email(email); + ClienteEmail clienteEmail1 = observableCollection.FirstOrDefault<ClienteEmail>(); + if (clienteEmail1 != null) + { + ordem = clienteEmail1.get_Ordem(); + } + else + { + nullable = null; + ordem = nullable; + } + nullable = ordem; + malaDiretum.set_Ordem(nullable.GetValueOrDefault()); + MalaDireta malaDiretum1 = malaDiretum; + if (Funcoes.IsWindowOpen<HosterWindow>("ENVIO DE E-MAIL")) + { + Funcoes.Destroy<HosterWindow>("ENVIO DE E-MAIL"); + } + List<MalaDireta> malaDiretas = new List<MalaDireta>() + { + malaDiretum1 + }; + (new HosterWindow(new MalaDiretaView(malaDiretas, string.Concat("HISTÓRICO DO SINISTRO DO ITEM ", this.SelectedItem.get_Descricao()), str, null), "ENVIO DE E-MAIL", new double?((double)1200), new double?((double)600), true)).ShowDialog(); + } + else + { + await base.ShowMessage("O CLIENTE NÃO POSSUI NENHUM E-MAIL CADASTRADO", "OK", "", false); + } + observableCollection = null; + } + + public async void Excluir() + { + Sinistro sinistro; + int? nullable; + bool valueOrDefault; + bool flag; + Sinistro sinistro1; + int num; + ControleSinistro controleSinistro; + if (this.SelectedSinistro != null && this.SelectedSinistro.get_Id() != 0) + { + if (await base.ShowMessage("DESEJA EXCLUIR?", "SIM", "NÃO", false)) + { + base.Loading(true); + string str = string.Format("EXCLUIU SINISTRO DE ID \"{0}\"", this.SelectedSinistro.get_Id()); + long id = this.SelectedSinistro.get_Id(); + TipoTela? nullable1 = new TipoTela?(7); + object[] objArray = new object[] { this.SelectedSinistro.get_ControleSinistro().get_Item().get_Id(), this.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Id(), this.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Ramo().get_Nome(), this.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome(), this.SelectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id(), this.SelectedSinistro.get_Id() }; + base.RegistrarAcao(str, id, nullable1, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}\nDESCRIÇÃO: {5}", objArray)); + if (this.SelectedControle.get_Sinistros().Count == 1) + { + List<ControleSinistro> controles = this.Controles; + controles.Remove(this.SelectedControle); + SinistroServico sinistroServico = this._servico; + ControleSinistro selectedControle = this.SelectedControle; + flag = (controles == null ? true : controles.Count == 0); + if (await sinistroServico.DeleteControle(selectedControle, flag)) + { + int num1 = this.ControlesFiltrados.IndexOf(this.SelectedControle); + this.Controles.Remove(this.SelectedControle); + this.ControlesFiltrados.Remove(this.SelectedControle); + this.ControlesFiltrados = new ObservableCollection<ControleSinistro>(this.ControlesFiltrados); + if (this.ControlesFiltrados.Count <= 0) + { + this.SelectedControle = new ControleSinistro(); + base.Alterar(false); + base.EnableMenu = false; + } + else + { + SinistroViewModel sinistroViewModel = this; + if (num1 < this.ControlesFiltrados.Count) + { + ObservableCollection<ControleSinistro> controlesFiltrados = this.ControlesFiltrados; + num = (num1 == 0 ? 1 : num1); + controleSinistro = controlesFiltrados.ElementAt<ControleSinistro>(num - 1); + } + else + { + controleSinistro = this.ControlesFiltrados.Last<ControleSinistro>(); + } + sinistroViewModel.SelectedControle = controleSinistro; + } + SinistroViewModel sinistroViewModel1 = this; + ControleSinistro selectedControle1 = this.SelectedControle; + if (selectedControle1 != null) + { + List<Sinistro> sinistros = selectedControle1.get_Sinistros(); + if (sinistros != null) + { + sinistro1 = sinistros.FirstOrDefault<Sinistro>(); + } + else + { + sinistro1 = null; + } + } + else + { + sinistro1 = null; + } + sinistroViewModel1.SelectedSinistro = sinistro1; + } + else + { + return; + } + } + else if (await this._servico.Delete(this.SelectedSinistro)) + { + int num2 = this.SelectedControle.get_Sinistros().IndexOf(this.SelectedSinistro); + this.SelectedControle.get_Sinistros().Remove(this.SelectedSinistro); + long id1 = this.SelectedControle.get_Id(); + this.SelectedControle = null; + this.SelectedControle = this.ControlesFiltrados.First<ControleSinistro>((ControleSinistro x) => x.get_Id() == id1); + SinistroViewModel sinistroViewModel2 = this; + sinistro = (num2 < this.SelectedControle.get_Sinistros().Count ? this.SelectedControle.get_Sinistros().ElementAt<Sinistro>(num2) : this.SelectedControle.get_Sinistros().Last<Sinistro>()); + sinistroViewModel2.SelectedSinistro = sinistro; + } + else + { + return; + } + if (this.Controles == null || this.Controles.Count == 0) + { + ItemServico itemServico = new ItemServico(); + Item item = await itemServico.BuscarItemPorIdAsync(this.SelectedItem.get_Id()); + item.set_Sinistrado(false); + await itemServico.Save(item); + itemServico = null; + } + if (this.ItensFiltrados.Count > 0 && this.ItensFiltrados != null) + { + Item item1 = this.ItensFiltrados.First<Item>((Item x) => x.get_Id() == this.SelectedItem.get_Id()); + ControleSinistro controleSinistro1 = this.SelectedControle; + if (controleSinistro1 != null) + { + List<Sinistro> sinistros1 = controleSinistro1.get_Sinistros(); + if (sinistros1 != null) + { + nullable = new int?(sinistros1.Count); + } + else + { + nullable = null; + } + int? nullable2 = nullable; + int num3 = 0; + valueOrDefault = nullable2.GetValueOrDefault() > num3 & nullable2.HasValue; + } + else + { + valueOrDefault = false; + } + item1.set_Sinistrado(valueOrDefault); + } + this.ItensFiltrados = new ObservableCollection<Item>(this.ItensFiltrados); + base.Loading(false); + base.ToggleSnackBar("SINISTRO EXCLUÍDO COM SUCESSO", true); + } + } + } + + public List<Item> FiltrarItem(string filter) + { + this.ItensFiltrados = (string.IsNullOrWhiteSpace(filter) ? this.Itens : new ObservableCollection<Item>( + from x in this.Itens + where ValidationHelper.RemoveDiacritics(x.get_Descricao().Trim()).ToUpper().Contains(ValidationHelper.RemoveDiacritics(filter)) + orderby x.get_Ordem() + select x)); + return this.ItensFiltrados.ToList<Item>(); + } + + public List<ControleSinistro> FiltrarSinistro(string filter) + { + ControleSinistro controleSinistro; + this.ControlesFiltrados = (string.IsNullOrWhiteSpace(filter) ? new ObservableCollection<ControleSinistro>(this.Controles) : new ObservableCollection<ControleSinistro>(this.Controles.Where<ControleSinistro>((ControleSinistro x) => { + if (ValidationHelper.RemoveDiacritics(x.get_DataSinistro().ToString().Trim()).Contains(filter)) + { + return true; + } + if (x.get_Sinistros() == null || x.get_Sinistros().Count <= 0) + { + return false; + } + return ValidationHelper.RemoveDiacritics(x.get_Sinistros()[0].get_Numero().Trim()).Contains(filter); + }).OrderBy<ControleSinistro, DateTime?>((ControleSinistro x) => x.get_DataSinistro()))); + if (this.ControlesFiltrados.Count > 0) + { + controleSinistro = this.ControlesFiltrados.First<ControleSinistro>(); + } + else + { + controleSinistro = null; + } + this.SelectedControle = controleSinistro; + return this.ControlesFiltrados.ToList<ControleSinistro>(); + } + + public string GerarHtmlSinistro(string vendedorPrincipal = "") + { + DateTime? vigencia2; + bool? culpado; + string shortDateString; + string shortTimeString; + string str; + string str1; + string str2; + bool valueOrDefault; + string shortDateString1; + string str3 = "<html><head><meta http-equiv='Content-Type' content='text/html; charset=UTF-8'><meta http-equiv='Content-Language' content='pt-br'><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1, shrink-to-fit=yes'><link rel='stylesheet' href='https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css' integrity='sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T' crossorigin='anonymous'><style type='text/css' media='print'>@page{ size: A4;} body; -webkit-print-color-adjust: exact; }</style><title> HISTÓRICO DO SINISTRO
"; + string str4 = ""; + foreach (Sinistro sinistro in + from x in this.SelectedControle.get_Sinistros() + orderby x.get_TipoSinistro() + select x) + { + str3 = string.Concat(str3, "

"); + str4 = (string.IsNullOrEmpty(str4) ? "CLIENTE" : string.Concat("TERCEIRO Nº ", sinistro.get_Numero())); + str3 = string.Concat(str3, str4, "

"); + str3 = string.Concat(str3, "
"); + int num = 0; + if (str4 == "CLIENTE") + { + string[] nome = new string[] { str3, ""; + str3 = string.Concat(nome); + num = 1; + string[] documento = new string[] { str3, ""; + str3 = string.Concat(documento); + num = 0; + string[] apolice = new string[] { str3, ""; + str3 = string.Concat(apolice); + num = 1; + string[] strArrays = new string[] { str3, ""; + str3 = string.Concat(strArrays); + num = 0; + vigencia2 = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Vigencia2(); + if (vigencia2.GetValueOrDefault().ToString(new CultureInfo("pt-BR")) != "01/01/0001 00:00:00") + { + vigencia2 = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Vigencia2(); + if (vigencia2.HasValue) + { + shortDateString1 = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString1 = null; + } + } + else + { + shortDateString1 = "NÃO POSSUI"; + } + string str5 = shortDateString1; + string[] strArrays1 = new string[] { str3, ""; + str3 = string.Concat(strArrays1); + num = 1; + vendedorPrincipal = (sinistro.get_ControleSinistro().get_Item().get_Documento().get_VendedorPrincipal() == null ? vendedorPrincipal : sinistro.get_ControleSinistro().get_Item().get_Documento().get_VendedorPrincipal().get_Nome()); + string[] strArrays2 = new string[] { str3, ""; + str3 = string.Concat(strArrays2); + num = 0; + string[] nome1 = new string[] { str3, ""; + str3 = string.Concat(nome1); + } + num = 1; + string[] numero = new string[] { str3, ""; + str3 = string.Concat(numero); + num = 0; + string[] strArrays3 = new string[] { str3, ""; + str3 = string.Concat(strArrays3); + num = 1; + string[] strArrays4 = new string[] { str3, ""; + str3 = string.Concat(strArrays4); + num = 0; + string[] strArrays5 = new string[] { str3, ""; + str3 = string.Concat(strArrays5); + num = 1; + string[] str6 = new string[] { str3, ""; + str3 = string.Concat(str6); + num = 0; + string[] itemSinistrado = new string[] { str3, ""; + str3 = string.Concat(itemSinistrado); + num = 1; + string[] strArrays6 = new string[] { str3, ""; + str3 = string.Concat(strArrays6); + num = 0; + string[] str7 = new string[] { str3, ""; + str3 = string.Concat(str7); + num = 1; + string[] strArrays7 = new string[] { str3, ""; + str3 = string.Concat(strArrays7); + num = 0; + string[] str8 = new string[] { str3, ""; + str3 = string.Concat(str8); + num = 1; + string[] description = new string[] { str3, ""; + str3 = string.Concat(description); + str3 = string.Concat(str3, "
CLIENTE: "; + nome[4] = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome(); + nome[5] = "
DOCUMENTO DO SEGURADO: "; + documento[4] = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Documento(); + documento[5] = "
APÓLICE: "; + apolice[4] = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Apolice(); + apolice[5] = "
VIGÊNCIA INICIAL: "; + DateTime vigencia1 = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Vigencia1(); + strArrays[4] = vigencia1.ToShortDateString(); + strArrays[5] = "
VIGÊNCIA FINAL: "; + strArrays1[4] = str5; + strArrays1[5] = "
VENDEDOR PRINCIPAL: "; + strArrays2[4] = vendedorPrincipal; + strArrays2[5] = "
SEGURADORA: "; + nome1[4] = sinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Seguradora().get_Nome(); + nome1[5] = "
NÚMERO SINISTRO: "; + numero[4] = sinistro.get_Numero(); + numero[5] = "
DATA DO SINISTRO: "; + vigencia2 = sinistro.get_ControleSinistro().get_DataSinistro(); + if (vigencia2.HasValue) + { + shortDateString = vigencia2.GetValueOrDefault().ToShortDateString(); + } + else + { + shortDateString = null; + } + strArrays3[4] = shortDateString; + strArrays3[5] = "
HORA DO SINISTRO: "; + vigencia2 = sinistro.get_ControleSinistro().get_HoraSinistro(); + if (vigencia2.HasValue) + { + shortTimeString = vigencia2.GetValueOrDefault().ToShortTimeString(); + } + else + { + shortTimeString = null; + } + strArrays4[4] = shortTimeString; + strArrays4[5] = "
DATA/HORA ABERTURA: "; + vigencia2 = sinistro.get_DataReclamacao(); + strArrays5[4] = vigencia2.ToString(); + strArrays5[5] = "
DATA LIQUIDAÇÃO: "; + vigencia2 = sinistro.get_DataLiquidacao(); + str6[4] = vigencia2.ToString(); + str6[5] = "
DESCRIÇÃO DO BEM SINISTRADO: "; + itemSinistrado[4] = sinistro.get_ItemSinistrado(); + itemSinistrado[5] = "
VALOR ORÇADO: "; + decimal valorOrcado = sinistro.get_ValorOrcado(); + strArrays6[4] = valorOrcado.ToString("C", new CultureInfo("pt-BR", false)); + strArrays6[5] = "
VALOR LIBERADO: "; + valorOrcado = sinistro.get_ValorLiberado(); + str7[4] = valorOrcado.ToString("C", new CultureInfo("pt-BR", false)); + str7[5] = "
VALOR PAGO: "; + valorOrcado = sinistro.get_ValorPago(); + strArrays7[4] = valorOrcado.ToString("C", new CultureInfo("pt-BR", false)); + strArrays7[5] = "
VALOR FRANQUIA: "; + valorOrcado = sinistro.get_ValorFranquia(); + str8[4] = valorOrcado.ToString("C", new CultureInfo("pt-BR", false)); + str8[5] = "
SITUAÇÃO: "; + description[4] = ValidationHelper.GetDescription(sinistro.get_StatusSinistro()); + description[5] = "
"); + if (sinistro.get_SinistroAuto() != null) + { + str3 = string.Concat(str3, "
"); + num = 0; + string[] numeroBo = new string[] { str3, ""; + str3 = string.Concat(numeroBo); + num = 1; + string[] description1 = new string[] { str3, ""; + str3 = string.Concat(description1); + num = 0; + string str9 = str3; + str1 = (num % 2 == 0 ? "WhiteSmoke" : "White"); + culpado = sinistro.get_SinistroAuto().get_Culpado(); + if (string.Concat(""; + goto Label0; + } + Label1: + str2 = "NÃO"; + Label0: + str3 = string.Concat(str9, str2); + num = 1; + string[] strArrays8 = new string[] { str3, ""; + str3 = string.Concat(strArrays8); + num = 0; + string[] endereco = new string[] { str3, ""; + str3 = string.Concat(endereco); + num = 1; + string[] envolvido = new string[] { str3, ""; + str3 = string.Concat(envolvido); + num = 0; + string[] motorista = new string[] { str3, ""; + str3 = string.Concat(motorista); + num = 1; + string[] ddd = new string[] { str3, ""; + str3 = string.Concat(ddd); + num = 0; + string[] email = new string[] { str3, ""; + str3 = string.Concat(email); + str3 = string.Concat(str3, "
NÚMERO B.O.: "; + numeroBo[4] = sinistro.get_SinistroAuto().get_NumeroBo(); + numeroBo[5] = "
TIPO PERDA: "; + description1[4] = ValidationHelper.GetDescription(sinistro.get_SinistroAuto().get_TipoPerda()); + description1[5] = "
CONSIDERA-SE CULPADO? ", culpado.ToString()) != null) + { + SinistroAuto sinistroAuto = sinistro.get_SinistroAuto(); + if (sinistroAuto != null) + { + culpado = sinistroAuto.get_Culpado(); + bool flag = false; + valueOrDefault = culpado.GetValueOrDefault() == flag & culpado.HasValue; + } + else + { + valueOrDefault = false; + } + if (valueOrDefault) + { + goto Label1; + } + str2 = "SIM
ÚLTIMO DOC. ENVIADO: "; + strArrays8[4] = string.Format("{0:dd/MM/yyyy}", sinistro.get_SinistroAuto().get_UltimoDocEnviado()); + strArrays8[5] = "
ENDEREÇO: "; + endereco[4] = sinistro.get_SinistroAuto().get_Endereco(); + endereco[5] = "
ENVOLVIDO/PROPRIETÁRIO: "; + envolvido[4] = sinistro.get_SinistroAuto().get_Envolvido(); + envolvido[5] = "
MOTORISTA: "; + motorista[4] = sinistro.get_SinistroAuto().get_Motorista(); + motorista[5] = "
TELEFONE: ("; + ddd[4] = sinistro.get_SinistroAuto().get_Ddd(); + ddd[5] = ") "; + ddd[6] = sinistro.get_SinistroAuto().get_Telefone(); + ddd[7] = "
E-MAIL: "; + email[4] = sinistro.get_SinistroAuto().get_Email(); + email[5] = "
"); + str3 = string.Concat(str3, "
"); + num = 1; + string str10 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() != null ? sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Nome() : ""); + string[] strArrays9 = new string[] { str3, ""; + str3 = string.Concat(strArrays9); + num = 0; + string str11 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd1()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone1()) ? "" : string.Concat("(", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd1(), ") ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone1())); + string str12 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd2()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone2()) ? "" : string.Concat(" / (", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd2(), ") ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone2())); + string str13 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd3()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone3()) ? "" : string.Concat(" / (", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Ddd3(), ") ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Telefone3())); + string[] strArrays10 = new string[] { str3, ""; + str3 = string.Concat(strArrays10); + num = 1; + string str14 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null ? "" : sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Email()); + string[] strArrays11 = new string[] { str3, ""; + str3 = string.Concat(strArrays11); + num = 0; + string str15 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Endereco()) ? "" : sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Endereco() ?? ""); + string str16 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Numero()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Numero())); + string str17 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Complemento()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Complemento())); + string str18 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Bairro()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Bairro())); + string str19 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Cidade()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Cidade())); + string str20 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Uf()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Uf())); + string str21 = (sinistro.get_SinistroAuto().get_ParceiroMecanica() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Cep()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroMecanica().get_Cep())); + string[] strArrays12 = new string[] { str3, ""; + str3 = string.Concat(strArrays12); + str3 = string.Concat(str3, "
PARCEIRO MECÂNICA: "; + strArrays9[4] = str10; + strArrays9[5] = "
CONTATOS: "; + strArrays10[4] = str11; + strArrays10[5] = str12; + strArrays10[6] = str13; + strArrays10[7] = "
EMAIL: "; + strArrays11[4] = str14; + strArrays11[5] = "
ENDEREÇO: "; + strArrays12[4] = str15; + strArrays12[5] = str16; + strArrays12[6] = str17; + strArrays12[7] = str18; + strArrays12[8] = str19; + strArrays12[9] = str20; + strArrays12[10] = str21; + strArrays12[11] = "
"); + str3 = string.Concat(str3, "
"); + num = 1; + str10 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() != null ? sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Nome() : ""); + string[] strArrays13 = new string[] { str3, ""; + str3 = string.Concat(strArrays13); + num = 0; + str11 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd1()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone1()) ? "" : string.Concat("(", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd1(), ") ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone1())); + str12 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd2()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone2()) ? "" : string.Concat(" / (", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd2(), ") ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone2())); + str13 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd3()) && string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone3()) ? "" : string.Concat(" / (", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Ddd3(), ") ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Telefone3())); + string[] strArrays14 = new string[] { str3, ""; + str3 = string.Concat(strArrays14); + num = 1; + str14 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null ? "" : sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Email()); + string[] strArrays15 = new string[] { str3, ""; + str3 = string.Concat(strArrays15); + num = 0; + str15 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Endereco()) ? "" : sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Endereco() ?? ""); + str16 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Numero()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Numero())); + str17 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Complemento()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Complemento())); + str18 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Bairro()) ? "" : string.Concat(", ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Bairro())); + str19 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Cidade()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Cidade())); + str20 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Uf()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Uf())); + str21 = (sinistro.get_SinistroAuto().get_ParceiroFunilaria() == null || string.IsNullOrEmpty(sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Cep()) ? "" : string.Concat(" - ", sinistro.get_SinistroAuto().get_ParceiroFunilaria().get_Cep())); + string[] strArrays16 = new string[] { str3, ""; + str3 = string.Concat(strArrays16); + str3 = string.Concat(str3, "
PARCEIRO FUNILARIA: "; + strArrays13[4] = str10; + strArrays13[5] = "
CONTATOS: "; + strArrays14[4] = str11; + strArrays14[5] = str12; + strArrays14[6] = str13; + strArrays14[7] = "
EMAIL: "; + strArrays15[4] = str14; + strArrays15[5] = "
ENDEREÇO: "; + strArrays16[4] = str15; + strArrays16[5] = str16; + strArrays16[6] = str17; + strArrays16[7] = str18; + strArrays16[8] = str19; + strArrays16[9] = str20; + strArrays16[10] = str21; + strArrays16[11] = "
"); + } + if (sinistro.get_SinistroVida() != null) + { + str3 = string.Concat(str3, "
"); + num = 1; + string[] description2 = new string[] { str3, ""; + str3 = string.Concat(description2); + num = 0; + string[] strArrays17 = new string[] { str3, ""; + str3 = string.Concat(strArrays17); + num = 1; + string[] description3 = new string[] { str3, ""; + str3 = string.Concat(description3); + num = 0; + string[] certObito = new string[] { str3, ""; + str3 = string.Concat(certObito); + num = 1; + string[] beneficiario = new string[] { str3, ""; + str3 = string.Concat(beneficiario); + str3 = string.Concat(str3, "
TIPO PERDA: "; + description2[4] = ValidationHelper.GetDescription(sinistro.get_SinistroVida().get_TipoPerda()); + description2[5] = "
AUXÍLIO FUNERAL: "; + culpado = sinistro.get_SinistroVida().get_AuxFuneral(); + if (culpado.HasValue) + { + culpado = sinistro.get_SinistroVida().get_AuxFuneral(); + if (!culpado.Value) + { + goto Label3; + } + str = "SIM"; + goto Label2; + } + Label3: + str = "NÃO"; + Label2: + strArrays17[4] = str; + strArrays17[5] = "
ESTADO CIVIL: "; + description3[4] = ValidationHelper.GetDescription(sinistro.get_SinistroVida().get_EstadoCivil()); + description3[5] = "
CERTIDÃO DE ÓBITO: "; + certObito[4] = sinistro.get_SinistroVida().get_CertObito(); + certObito[5] = "
BENEFICIÁRIO: "; + beneficiario[4] = sinistro.get_SinistroVida().get_Beneficiario(); + beneficiario[5] = "
"); + } + if (!string.IsNullOrWhiteSpace(sinistro.get_Descricao())) + { + str3 = string.Concat(str3, "
"); + str3 = string.Concat(str3, "

DESCRIÇÃO

"); + str3 = string.Concat(str3, "
"); + str3 = string.Concat(str3, "
", sinistro.get_Descricao(), "
"); + } + if (string.IsNullOrWhiteSpace(sinistro.get_Observacao())) + { + continue; + } + str3 = string.Concat(str3, "
"); + str3 = string.Concat(str3, "

HISTÓRICO

"); + str3 = string.Concat(str3, "
"); + str3 = string.Concat(str3, "
", sinistro.get_Observacao().Replace("", "").Replace("", ""), "
"); + } + str3 = string.Concat(str3, "
"); + return str3; + } + + private static List GerarParceiros() + { + List parceiros = new List(); + Parceiro parceiro = new Parceiro(); + parceiro.set_Nome("NENHUM"); + parceiros.Add(parceiro); + parceiros.AddRange( + from x in Recursos.Parceiros + orderby x.get_Nome() + select x); + return parceiros; + } + + internal void ImprimirHistorico() + { + string nome; + Vendedor vendedorPrincipal = this._documentoSelecionado.get_VendedorPrincipal(); + if (vendedorPrincipal != null) + { + nome = vendedorPrincipal.get_Nome(); + } + else + { + nome = null; + } + string str = this.GerarHtmlSinistro(nome); + string tempPath = Path.GetTempPath(); + string str1 = string.Format("{0}{1}_{2:ddMMyyyyhhmmss}.html", tempPath, (TipoTela)7, Funcoes.GetNetworkTime()); + StreamWriter streamWriter = new StreamWriter(str1, true, Encoding.UTF8); + streamWriter.Write(str); + streamWriter.Close(); + Process.Start(str1); + } + + public async void IncluirEnvolvido() + { + Sinistro sinistro = new Sinistro(); + sinistro.set_ControleSinistro(this.SelectedControle); + sinistro.set_TipoSinistro(new TipoSinistro?(1)); + sinistro.set_Ativo(true); + sinistro.set_StatusSinistro(new StatusSinistro?(1)); + Sinistro sinistro1 = sinistro; + long id = this._documentoSelecionado.get_Controle().get_Ramo().get_Id(); + long num = id - (long)5; + if (num <= (long)5) + { + switch ((uint)num) + { + case 0: + { + sinistro1.set_SinistroAuto(new SinistroAuto()); + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + } + case 1: + case 2: + case 4: + case 5: + { + sinistro1.set_SinistroVida(new SinistroVida()); + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + } + case 3: + { + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + } + } + } + else + { + } + if (id != (long)37) + { + goto Label3; + } + sinistro1.set_SinistroAuto(new SinistroAuto()); + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + sinistro1.set_SinistroVida(new SinistroVida()); + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + Label3: + if (id != (long)53) + { + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + } + else + { + sinistro1.set_SinistroVida(new SinistroVida()); + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + return; + } + if (!await base.ShowMessage("VOCÊ DESEJA COPIAR OS DADOS DO SINISTRADO PARA O TERCEIRO?", "SIM", "NÃO", false)) + { + sinistro1.set_DataReclamacao(new DateTime?(Funcoes.GetNetworkTime())); + } + else + { + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + sinistro1.set_Descricao(this.SelectedSinistro.get_Descricao()); + sinistro1.set_DataReclamacao(this.SelectedSinistro.get_DataReclamacao()); + if (sinistro1.get_SinistroAuto() != null) + { + if (this.SelectedSinistro.get_SinistroAuto() == null) + { + this.SelectedSinistro.set_SinistroAuto(new SinistroAuto()); + } + sinistro1.get_SinistroAuto().set_Endereco(this.SelectedSinistro.get_SinistroAuto().get_Endereco()); + } + } + this.IsReadOnlyItem = false; + this.SelectedSinistro = sinistro1; + base.Alterar(true); + sinistro1 = null; + } + + public async Task IncluirSinistro() + { + Sinistro sinistro; + long id; + decimal num; + ControleSinistro controleSinistro; + if (this.SelectedItem != null) + { + DateTime networkTime = Funcoes.GetNetworkTime(); + ControleSinistro controleSinistro1 = new ControleSinistro(); + controleSinistro1.set_DataSinistro(new DateTime?(networkTime)); + controleSinistro1.set_Item(this.SelectedItem); + controleSinistro = controleSinistro1; + ObservableCollection observableCollection = await this._itemServico.BuscarCoberturasPorItemAsync(this.SelectedItem.get_Id()); + Cobertura cobertura = observableCollection.FirstOrDefault((Cobertura x) => { + if (x.get_CoberturaPadrao() == null) + { + return false; + } + return x.get_CoberturaPadrao().get_Id() == (long)1; + }); + Sinistro sinistro1 = new Sinistro(); + sinistro1.set_ControleSinistro(controleSinistro); + sinistro1.set_TipoSinistro(new TipoSinistro?(0)); + sinistro1.set_Ativo(true); + sinistro1.set_DataReclamacao(new DateTime?(networkTime)); + sinistro1.set_StatusSinistro(new StatusSinistro?(1)); + sinistro1.set_ItemSinistrado(this.SelectedItem.get_Descricao()); + num = (cobertura != null ? cobertura.get_Franquia() : decimal.Zero); + sinistro1.set_ValorFranquia(num); + sinistro = sinistro1; + id = this._documentoSelecionado.get_Controle().get_Ramo().get_Id(); + long num1 = id - (long)5; + if (num1 <= (long)5) + { + switch ((uint)num1) + { + case 0: + { + goto Label0; + } + case 1: + case 2: + case 4: + case 5: + { + goto Label1; + } + case 3: + { + goto Label2; + } + } + } + else + { + } + if (id != (long)37) + { + goto Label3; + } + Label0: + SinistroAuto sinistroAuto = new SinistroAuto(); + sinistroAuto.set_Culpado(new bool?(false)); + sinistro.set_SinistroAuto(sinistroAuto); + Label2: + this.IsReadOnlyItem = true; + this.SelectedControle = controleSinistro; + this.SelectedSinistro = sinistro; + base.Alterar(true); + } + else + { + await base.ShowMessage("NECESSÁRIO INCLUIR O ITEM ANTES DE INCLUIR UM SINISTRO.", "OK", "", false); + } + controleSinistro = null; + return; + Label1: + sinistro.set_SinistroVida(new SinistroVida()); + goto Label2; + Label3: + if (id != (long)53) + { + goto Label2; + } + else + { + goto Label1; + } + goto Label2; + } + + internal async Task> ItemFiltrar(string value) + { + List items = await Task.Run>(() => this.FiltrarItem(value)); + return items; + } + + public async Task>> Salvar() + { + List> keyValuePairs; + string str; + bool id; + bool flag; + string str1; + List> keyValuePairs1 = this.SelectedSinistro.Validate(); + if (keyValuePairs1.Count <= 0) + { + Sinistro selectedSinistro = this.SelectedSinistro; + if (selectedSinistro.get_SinistroAuto() != null) + { + Parceiro parceiroFunilaria = selectedSinistro.get_SinistroAuto().get_ParceiroFunilaria(); + if (parceiroFunilaria != null) + { + id = parceiroFunilaria.get_Id() == (long)0; + } + else + { + id = false; + } + if (id) + { + selectedSinistro.get_SinistroAuto().set_ParceiroFunilaria(null); + } + Parceiro parceiroMecanica = selectedSinistro.get_SinistroAuto().get_ParceiroMecanica(); + if (parceiroMecanica != null) + { + flag = parceiroMecanica.get_Id() == (long)0; + } + else + { + flag = false; + } + if (flag) + { + selectedSinistro.get_SinistroAuto().set_ParceiroMecanica(null); + } + } + DateTime networkTime = Funcoes.GetNetworkTime(); + if (!string.IsNullOrWhiteSpace(this.Anotacoes) && !this.Anotacoes.IsEmpty()) + { + Sinistro sinistro = selectedSinistro; + object[] nome = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), networkTime, this.Anotacoes, selectedSinistro.get_Observacao() }; + sinistro.set_Observacao(string.Format("

{0}, ID: {1}, {2:g}
{3}



{4}", nome)); + } + if (!string.IsNullOrWhiteSpace(this.AnotacoesInternas) && !this.AnotacoesInternas.IsEmpty()) + { + Sinistro sinistro1 = selectedSinistro; + object[] objArray = new object[] { Recursos.Usuario.get_Nome(), Recursos.Usuario.get_Id(), networkTime, this.AnotacoesInternas, selectedSinistro.get_ObservacaoInterna() }; + sinistro1.set_ObservacaoInterna(string.Format("

{0}, ID: {1}, {2:g}
{3}



{4}", objArray)); + } + if (selectedSinistro.get_Id() != 0) + { + selectedSinistro.set_DataAlteracao(new DateTime?(DateTime.Now)); + selectedSinistro.set_IdUsuarioAlteracao(Recursos.Usuario.get_Id()); + } + else + { + selectedSinistro.set_DataCriacao(new DateTime?(DateTime.Now)); + selectedSinistro.set_IdUsuarioCriacao(Recursos.Usuario.get_Id()); + } + str = (selectedSinistro.get_Id() == 0 ? "INCLUIU" : "ALTEROU"); + str1 = str; + Sinistro sinistro2 = await this._servico.Save(selectedSinistro, this._documentoSelecionado.get_Controle().get_Ramo().get_Id()); + selectedSinistro = sinistro2; + if (this._servico.Sucesso) + { + await this.CarregarControles(selectedSinistro.get_ControleSinistro().get_Item()); + this.SelectedControle = this.ControlesFiltrados.First((ControleSinistro x) => x.get_Id() == selectedSinistro.get_ControleSinistro().get_Id()); + this.SelectedSinistro = this.SelectedControle.get_Sinistros().First((Sinistro x) => x.get_Id() == selectedSinistro.get_Id()); + Recursos.Parceiros = this.Parceiros.ToList(); + base.Alterar(false); + base.ToggleSnackBar("SINISTRO SALVO COM SUCESSO", true); + string str2 = string.Format("{0} SINISTRO DE ID \"{1}\"", str1, selectedSinistro.get_Id()); + long num = selectedSinistro.get_Id(); + TipoTela? nullable = new TipoTela?(7); + object[] id1 = new object[] { selectedSinistro.get_ControleSinistro().get_Item().get_Id(), selectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Id(), selectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Ramo().get_Nome(), selectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Nome(), selectedSinistro.get_ControleSinistro().get_Item().get_Documento().get_Controle().get_Cliente().get_Id(), selectedSinistro.get_Descricao() }; + base.RegistrarAcao(str2, num, nullable, string.Format("ID ITEM: {0}\nID DOCUMENTO: {1}\nRAMO: {2}\nCLIENTE: {3}\nID CLIENTE: {4}\nDESCRIÇÃO: \"{5}\"", id1)); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + str1 = null; + return keyValuePairs; + } + + public async void Seleciona(Item item) + { + Visibility visibility; + Visibility visibility1; + base.Loading(true); + await base.PermissaoTela(7); + this.SelectedItem = this.ItemSelecionado; + SinistroViewModel sinistroViewModel = this; + visibility = (this._documentoSelecionado.get_Controle().get_Ramo().get_Id() == (long)5 ? Visibility.Visible : Visibility.Collapsed); + sinistroViewModel.VisibilityAuto = visibility; + SinistroViewModel sinistroViewModel1 = this; + visibility1 = (this._documentoSelecionado.get_Controle().get_Ramo().get_Id() == (long)6 ? Visibility.Visible : Visibility.Collapsed); + sinistroViewModel1.VisibilityVida = visibility1; + if (item != null) + { + await this.SelecionaControles(item); + base.Loading(false); + } + else + { + base.Loading(false); + } + } + + public void SelecionaControle(ControleSinistro controle) + { + List list; + bool sinistros; + if (this.Carregando) + { + return; + } + this.SelectedControle = controle; + ControleSinistro selectedControle = this.SelectedControle; + ControleSinistro controleSinistro = this.SelectedControle; + if (controleSinistro != null) + { + List sinistros1 = controleSinistro.get_Sinistros(); + if (sinistros1 != null) + { + list = ( + from x in sinistros1 + orderby x.get_Id() + select x).ToList(); + } + else + { + list = null; + } + } + else + { + list = null; + } + selectedControle.set_Sinistros(list); + if (this.Carregando) + { + return; + } + if (controle.get_Id() != this.SelectedControle.get_Id()) + { + this.SelectedControle = controle; + } + ControleSinistro selectedControle1 = this.SelectedControle; + if (selectedControle1 != null) + { + sinistros = selectedControle1.get_Sinistros(); + } + else + { + sinistros = false; + } + if (sinistros) + { + this.TipoSinistroEnabled = (!this.SelectedControle.get_Sinistros().Any((Sinistro x) => { + TipoSinistro? tipoSinistro = x.get_TipoSinistro(); + return tipoSinistro.GetValueOrDefault() == 0 & tipoSinistro.HasValue; + }) ? true : this.SelectedControle.get_Sinistros().Count <= 1); + } + } + + public async Task SelecionaControles(Item item) + { + Sinistro sinistro; + base.Loading(true); + await this.CarregarControles(item); + if (this.ControlesFiltrados.Count <= 0) + { + this.SelectedControle = new ControleSinistro(); + base.Alterar(false); + } + else + { + this.SelectedControle = this.ControlesFiltrados.FirstOrDefault(); + } + SinistroViewModel sinistroViewModel = this; + ControleSinistro selectedControle = this.SelectedControle; + if (selectedControle != null) + { + List sinistros = selectedControle.get_Sinistros(); + if (sinistros != null) + { + sinistro = sinistros.FirstOrDefault(); + } + else + { + sinistro = null; + } + } + else + { + sinistro = null; + } + sinistroViewModel.SelectedSinistro = sinistro; + base.Loading(false); + } + + public async void SelecionaItem(Item item) + { + if (!this.Carregando) + { + this.SelectedItem = item; + if (this.SelectedItem != null) + { + if (!this.Carregando) + { + if (item.get_Id() != this.SelectedItem.get_Id()) + { + this.SelectedItem = this.ItensFiltrados.FirstOrDefault((Item x) => x.get_Id() == item.get_Id()); + } + await this.SelecionaControles(item); + } + } + } + } + + public async Task SelecionaItens(int type, Item item = null) + { + bool count; + Item item1; + base.Loading(true); + this.Carregando = true; + switch (type) + { + case 1: + case 2: + { + this.Itens = await this._itemServico.BuscarItens(this._documentoSelecionado.get_Id(), 2); + break; + } + case 3: + { + this.Itens = await this._itemServico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 1); + break; + } + case 4: + { + this.Itens = await this._itemServico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 3); + break; + } + default: + { + this.Itens = await this._itemServico.BuscarItens(this._documentoSelecionado.get_Controle().get_Id(), 0); + break; + } + } + this.ItensFiltrados = this.Itens; + if (item != null && item.get_Id() > (long)0) + { + SinistroViewModel sinistroViewModel = this; + if (this.ItensFiltrados == null || this.ItensFiltrados.Count <= 0) + { + item1 = null; + } + else + { + item1 = this.ItensFiltrados.FirstOrDefault((Item x) => x.get_Id() == item.get_Id()); + } + sinistroViewModel.SelectedItem = item1; + } + SinistroViewModel sinistroViewModel1 = this; + if (this.MostrarLista) + { + count = true; + } + else + { + ObservableCollection itens = this.Itens; + if (itens != null) + { + count = itens.Count > 1; + } + else + { + count = false; + } + } + sinistroViewModel1.MostrarLista = count; + this.Carregando = false; + base.Loading(false); + } + + internal async Task> SinistroFiltrar(string value) + { + List controleSinistros = await Task.Run>(() => this.FiltrarSinistro(value)); + return controleSinistros; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/Seguros/TrocarClienteViewModel.cs b/Codemerx/Gestor.Application/ViewModels/Seguros/TrocarClienteViewModel.cs new file mode 100644 index 0000000..35881fd --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/Seguros/TrocarClienteViewModel.cs @@ -0,0 +1,92 @@ +using Gestor.Application.Servicos.Generic; +using Gestor.Application.Servicos.Seguros; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Diagnostics; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels.Seguros +{ + public class TrocarClienteViewModel : BaseSegurosViewModel + { + private readonly ApoliceServico _apoliceServico; + + private readonly ClienteServico _clienteServico; + + private Documento _selectedDocumento; + + private Cliente _selectedCliente; + + public Cliente SelectedCliente + { + get + { + return this._selectedCliente; + } + set + { + base.OnPropertyChanged("SelectedCliente"); + this._selectedCliente = value; + } + } + + public Documento SelectedDocumento + { + get + { + return this._selectedDocumento; + } + set + { + base.OnPropertyChanged("SelectedDocumento"); + this._selectedDocumento = value; + } + } + + public TrocarClienteViewModel() + { + this._apoliceServico = new ApoliceServico(); + this._clienteServico = new ClienteServico(); + } + + public async Task Salvar() + { + bool flag; + Cliente cliente; + Documento selectedDocumento; + if (this.SelectedCliente == null) + { + flag = false; + } + else if (this.SelectedCliente.get_Id() != this.SelectedDocumento.get_Controle().get_Cliente().get_Id()) + { + cliente = await this._clienteServico.BuscarCliente(this.SelectedDocumento.get_Controle().get_Cliente().get_Id()); + selectedDocumento = this.SelectedDocumento; + this._apoliceServico.Sucesso = true; + await this._apoliceServico.Save(selectedDocumento.get_Controle(), this.SelectedCliente); + if (this._apoliceServico.Sucesso) + { + base.RegistrarAcao(string.Format("TROCOU O CLIENTE DO DOCUMENTO DE ID {0}", this.SelectedDocumento.get_Id()), this.SelectedDocumento.get_Id(), new TipoTela?(41), string.Format("CLIENTE ANTIGO: {0}\nNOVO CLIENTE: {1} ({2})", cliente.get_Nome(), this.SelectedCliente.get_Nome(), this.SelectedCliente.get_Id())); + this.SelectedCliente = selectedDocumento.get_Controle().get_Cliente(); + this.SelectedDocumento = selectedDocumento; + flag = true; + } + else + { + flag = false; + } + } + else + { + flag = false; + } + cliente = null; + selectedDocumento = null; + return flag; + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/TrilhaViewModel.cs b/Codemerx/Gestor.Application/ViewModels/TrilhaViewModel.cs new file mode 100644 index 0000000..a818704 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/TrilhaViewModel.cs @@ -0,0 +1,284 @@ +using Gestor.Application.Actions; +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Model.Domain.Configuracoes; +using Gestor.Model.Domain.Ferramentas; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels +{ + public class TrilhaViewModel : BaseSegurosViewModel + { + private ObservableCollection _trilhas = new ObservableCollection(); + + private ObservableCollection _fases = new ObservableCollection(); + + private Trilha _selectedTrilha = new Trilha(); + + private Tarefa _selectedTarefa; + + private ObservableCollection _usuarios; + + private Usuario _selectedUsuario = new Usuario(); + + public ObservableCollection Fases + { + get + { + return this._fases; + } + set + { + this._fases = value; + base.OnPropertyChanged("Fases"); + } + } + + public Tarefa SelectedTarefa + { + get + { + return this._selectedTarefa; + } + set + { + this._selectedTarefa = value; + base.OnPropertyChanged("SelectedTarefa"); + } + } + + public Trilha SelectedTrilha + { + get + { + return this._selectedTrilha; + } + set + { + this._selectedTrilha = value; + base.OnPropertyChanged("SelectedTrilha"); + } + } + + public Usuario SelectedUsuario + { + get + { + return this._selectedUsuario; + } + set + { + this._selectedUsuario = value; + base.OnPropertyChanged("SelectedUsuario"); + } + } + + private TarefaServico Servico + { + get; + } + + public ObservableCollection Trilhas + { + get + { + return this._trilhas; + } + set + { + this._trilhas = value; + base.OnPropertyChanged("Trilhas"); + } + } + + public ObservableCollection Usuarios + { + get + { + return this._usuarios; + } + set + { + this._usuarios = value; + base.OnPropertyChanged("Usuarios"); + } + } + + public TrilhaViewModel() + { + this.Servico = new TarefaServico(); + List usuarios = new List(); + Usuario usuario = new Usuario(); + usuario.set_Id((long)0); + usuario.set_Nome("TODOS OS USUÁRIOS"); + usuarios.Add(usuario); + List usuarios1 = usuarios; + usuarios1.AddRange(Recursos.Usuarios.Where((Usuario x) => { + if (Recursos.Usuario.get_IdEmpresa() != (long)1 && x.get_IdEmpresa() != Recursos.Usuario.get_IdEmpresa()) + { + return false; + } + return !x.get_Excluido(); + }).OrderBy((Usuario x) => x.get_Nome()).ToList()); + this.Usuarios = new ObservableCollection(usuarios1); + this.SelectedUsuario = this.Usuarios.First(); + Gestor.Application.Actions.Actions.AtualizaTrilhas = (Action)Delegate.Combine(Gestor.Application.Actions.Actions.AtualizaTrilhas, new Action(this.AtualizarTrilhas)); + this.CarregaTrilhas(); + } + + public void AtualizarTrilhas() + { + this.CarregaTrilhas(); + } + + public async Task Cancelar() + { + await this.CarregarTrilha(this.SelectedTrilha); + base.Alterar(false); + } + + public async Task CarregarTrilha(Trilha trilha) + { + if (trilha != null && trilha.get_Id() != 0) + { + this.SelectedTrilha = trilha; + List tarefas = await this.Servico.BuscarTarefas(trilha.get_Id()); + List tarefas1 = tarefas; + List fases = await this.Servico.BuscarFases(trilha.get_Id()); + this.Fases = new ObservableCollection(); + fases.ForEach((Fase x) => { + x.set_Tarefas(tarefas1.Where((Tarefa t) => { + if (this.SelectedUsuario != null && this.SelectedUsuario.get_Id() != 0 && this.SelectedUsuario.get_Id() != t.get_Usuario().get_Id() || t.get_Fase().get_Id() != x.get_Id()) + { + return false; + } + return t.get_Status() != 2; + }).ToList()); + this.Fases.Add(x); + }); + } + } + + public async Task CarregarTrilhas(Trilha trilha = null) + { + Trilha trilha1; + List trilhas = await this.Servico.BuscarTrilhas(); + this.Trilhas = new ObservableCollection(trilhas); + TrilhaViewModel trilhaViewModel = this; + trilha1 = (trilha != null ? this.Trilhas.FirstOrDefault((Trilha x) => x.get_Id() == trilha.get_Id()) : trilhas.FirstOrDefault()); + await trilhaViewModel.CarregarTrilha(trilha1); + } + + public async void CarregaTrilhas() + { + await this.CarregarTrilhas(null); + } + + public void Excluir(Fase origem, Tarefa data) + { + Tarefa tarefa = this.Fases.First((Fase x) => x.get_Id() == origem.get_Id()).get_Tarefas().First((Tarefa x) => x.get_Id() == data.get_Id()); + this.Fases.First((Fase x) => x.get_Id() == origem.get_Id()).get_Tarefas().Remove(tarefa); + } + + public async Task Excluir(Tarefa tarefa) + { + if (tarefa.get_Id() != 0) + { + string[] titulo = new string[] { "DESEJA REALMENTE EXCLUIR A TAREFA ", tarefa.get_Titulo(), "?", Environment.NewLine, "ESSE PROCEDIMENTO É IRREVERSÍVEL" }; + if (await base.ShowMessage(string.Concat(titulo), "SIM", "NÃO", false)) + { + if (await this.Servico.Excluir(tarefa.get_Id())) + { + await this.CarregarTrilha(this.SelectedTrilha); + base.Alterar(false); + } + else + { + base.Alterar(false); + } + } + } + } + + public void Inserir(Fase origem, Tarefa data, int index, bool aberto = false) + { + data.set_Aberto(aberto); + data.set_Fase(origem); + this.Fases.First((Fase x) => x.get_Id() == origem.get_Id()).get_Tarefas().Insert((index == -1 ? 0 : index), data); + this.TrocarFase(data); + } + + public async Task>> Salvar(Tarefa destino) + { + List> keyValuePairs; + Tarefa tarefa = destino; + List configuracoes = Recursos.Configuracoes; + tarefa.set_AgendamentoRetroativo(configuracoes.Any((ConfiguracaoSistema x) => x.get_Configuracao() == 45)); + List> keyValuePairs1 = destino.Validate(); + if (keyValuePairs1.Count <= 0) + { + await this.Servico.Salvar(destino); + if (this.Servico.Sucesso) + { + await this.CarregarTrilha(this.SelectedTrilha); + keyValuePairs = null; + } + else + { + keyValuePairs = null; + } + } + else + { + keyValuePairs = keyValuePairs1; + } + return keyValuePairs; + } + + public async Task Salvar(Trilha destino) + { + TrilhaViewModel.u003cu003ec__DisplayClass37_0 variable; + this.SelectedTrilha = null; + this.Fases = null; + List fases = destino.get_Fases(); + Trilha trilha = await this.Servico.Salvar(destino); + if (this.Servico.Sucesso) + { + if (fases != null) + { + fases.ForEach((Fase x) => x.set_Trilha(trilha)); + await this.Servico.Salvar(fases); + if (!this.Servico.Sucesso) + { + variable = null; + fases = null; + return; + } + } + await this.CarregarTrilhas(trilha); + } + variable = null; + fases = null; + } + + private async void TrocarFase(Tarefa tarefa) + { + await this.Servico.Salvar(tarefa); + } + + public void Update() + { + this.Fases = new ObservableCollection(this.Fases); + } + } +} \ No newline at end of file diff --git a/Codemerx/Gestor.Application/ViewModels/TutorialViewModel.cs b/Codemerx/Gestor.Application/ViewModels/TutorialViewModel.cs new file mode 100644 index 0000000..d027b83 --- /dev/null +++ b/Codemerx/Gestor.Application/ViewModels/TutorialViewModel.cs @@ -0,0 +1,612 @@ +using Gestor.Application.Helpers; +using Gestor.Application.Servicos; +using Gestor.Application.Servicos.Ajuda; +using Gestor.Application.Servicos.Ferramentas; +using Gestor.Application.Servicos.Generic; +using Gestor.Application.ViewModels.Generic; +using Gestor.Common.Security; +using Gestor.Model.API; +using Gestor.Model.Common; +using Gestor.Model.Domain.Common; +using Gestor.Model.Domain.Generic; +using Gestor.Model.Domain.Seguros; +using Gestor.Model.License; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Diagnostics; +using System.Linq; +using System.Runtime.CompilerServices; +using System.Text.RegularExpressions; +using System.Threading.Tasks; + +namespace Gestor.Application.ViewModels +{ + public class TutorialViewModel : BaseViewModel + { + private bool _fase1; + + private bool _fase2; + + private bool _fase3; + + private string _mensagem = "ESTAMOS PREPARANDO TUDO PRA VOCÊ INICIAR"; + + private string _nome; + + private string _usuario; + + private string _senha; + + private string _confirmacaoSenha; + + private ObservableCollection _seguradoras = new ObservableCollection(); + + private ObservableCollection _ramos = new ObservableCollection(); + + private bool _loadingVisibility; + + private long _idUsuario { get; set; } = (long)-1; + + public string ConfirmacaoSenha + { + get + { + return this._confirmacaoSenha; + } + set + { + this._confirmacaoSenha = value; + base.OnPropertyChanged("ConfirmacaoSenha"); + } + } + + private Customer Empresa + { + get; + set; + } + + public bool Fase1 + { + get + { + return this._fase1; + } + set + { + this._fase1 = value; + base.OnPropertyChanged("Fase1"); + } + } + + public bool Fase2 + { + get + { + return this._fase2; + } + set + { + this._fase2 = value; + base.OnPropertyChanged("Fase2"); + } + } + + public bool Fase3 + { + get + { + return this._fase3; + } + set + { + this._fase3 = value; + base.OnPropertyChanged("Fase3"); + } + } + + public bool LoadingVisibility + { + get + { + return this._loadingVisibility; + } + set + { + this._loadingVisibility = value; + base.OnPropertyChanged("LoadingVisibility"); + } + } + + public string Mensagem + { + get + { + return this._mensagem; + } + set + { + this._mensagem = value; + base.OnPropertyChanged("Mensagem"); + } + } + + public string Nome + { + get + { + return this._nome; + } + set + { + this._nome = value; + base.OnPropertyChanged("Nome"); + } + } + + public ObservableCollection Ramos + { + get + { + return this._ramos; + } + set + { + this._ramos = value; + base.OnPropertyChanged("Ramos"); + } + } + + public ObservableCollection Seguradoras + { + get + { + return this._seguradoras; + } + set + { + this._seguradoras = value; + base.OnPropertyChanged("Seguradoras"); + } + } + + public string Senha + { + get + { + return this._senha; + } + set + { + this._senha = value; + base.OnPropertyChanged("Senha"); + } + } + + public string Usuario + { + get + { + return this._usuario; + } + set + { + this._usuario = value; + base.OnPropertyChanged("Usuario"); + } + } + + public TutorialViewModel() + { + base.EnableFields = true; + } + + public async Task Concluir() + { + bool flag; + SeguradoraServico seguradoraServico; + RamoServico ramoServico; + this.Fase3 = false; + ObservableCollection ramos = this.Ramos; + if (!ramos.All((Ramo x) => !x.get_Ativo())) + { + this.Mensagem = "ESTAMOS TERMINANDO AS CONFIGURAÇÕES INICIAIS E LOGO MAIS VOCÊ PODERÁ UTILIZAR."; + if (await this.UsuarioInicial()) + { + seguradoraServico = new SeguradoraServico(); + foreach (Seguradora seguradora in this.Seguradoras) + { + await seguradoraServico.Save(seguradora, null, true); + if (seguradoraServico.Sucesso) + { + continue; + } + flag = false; + seguradoraServico = null; + ramoServico = null; + return flag; + } + ramoServico = new RamoServico(); + foreach (Ramo ramo in this.Ramos) + { + await ramoServico.Save(ramo, null); + if (ramoServico.Sucesso) + { + continue; + } + flag = false; + seguradoraServico = null; + ramoServico = null; + return flag; + } + await (new BaseServico()).LoadInicialParameters(); + flag = true; + } + else + { + flag = false; + } + } + else + { + await base.ShowMessage("NECESSÁRIO AO MENOS UM RAMO ATIVO PARA PROSSEGUIR.", "OK", "", false); + this.Fase3 = true; + flag = false; + } + seguradoraServico = null; + ramoServico = null; + return flag; + } + + public async Task CriarBanco() + { + string str; + string str1 = await (new ConnectionHelper()).VerifyConnection(); + if (str1 != null) + { + str = str1; + } + else + { + Instancia.ExcluirCfg(); + str = await this.VerificaEmpresa(); + } + return str; + } + + public void DesativarRamos() + { + foreach (Ramo ramo in this.Ramos) + { + ramo.set_Ativo(false); + } + this.Ramos = new ObservableCollection(this.Ramos); + } + + public void DesativarSeguradoras() + { + foreach (Seguradora seguradora in this.Seguradoras) + { + seguradora.set_Ativo(false); + } + this.Seguradoras = new ObservableCollection(this.Seguradoras); + } + + public async Task IniciarConfiguracoes() + { + List seguradoras; + base.EnableButtons = false; + ConnectionHelper connectionHelper = new ConnectionHelper(); + EmpresaServico empresaServico = new EmpresaServico(); + Gestor.Model.Domain.Common.Empresa empresa = await empresaServico.BuscarEmpresaPorId((long)1); + this.Empresa = await Connection.Get(string.Format("Customer/{0}", ApplicationHelper.IdFornecedor), true, false); + if (empresa == null) + { + await empresaServico.Save(this.Empresa); + } + BaseServico baseServico = new BaseServico(); + ControleArquivoDigital controleArquivoDigital = await baseServico.BuscarControle(); + if (controleArquivoDigital == null) + { + controleArquivoDigital = new ControleArquivoDigital(); + controleArquivoDigital.set_Catalogo(Connection.Catalog); + controleArquivoDigital.set_Tabela("Arquivos"); + } + ControleArquivoDigital controleArquivoDigital1 = controleArquivoDigital; + if (controleArquivoDigital1.get_Id() == 0) + { + await baseServico.SalvarControle(controleArquivoDigital1); + } + VendedorServico vendedorServico = new VendedorServico(); + Vendedor vendedor = await vendedorServico.BuscarCorretora(); + if (vendedor == null) + { + vendedor = new Vendedor(); + vendedor.set_IdEmpresa((long)1); + vendedor.set_Nome(this.Empresa.get_Name()); + vendedor.set_Ativo(true); + vendedor.set_Corretora(true); + } + Vendedor vendedor1 = vendedor; + if (vendedor1.get_Id() == 0) + { + Repasse repasse = new Repasse(); + repasse.set_Forma(new FormaRepasse?(1)); + repasse.set_Incidencia(new TipoIncidencia?(1)); + repasse.set_Ativo(true); + repasse.set_Tipo(new TipoRepasse?(2)); + repasse.set_ValorNovo(decimal.Zero); + repasse.set_ValorRenovacao(decimal.Zero); + await vendedorServico.Save(vendedor1, repasse); + if (!vendedorServico.Sucesso) + { + connectionHelper = null; + empresaServico = null; + empresa = null; + baseServico = null; + vendedorServico = null; + seguradoras = null; + return; + } + } + await (new Gestor.Application.Servicos.ArquivoDigitalServico()).Criar(); + string str = await connectionHelper.AtualizarBanco(); + if (str == null) + { + seguradoras = await (new SeguradoraServico()).BuscarSeguradoras(); + List ramos = await (new RamoServico()).BuscarRamos(); + TutorialViewModel observableCollection = this; + List seguradoras1 = seguradoras; + observableCollection.Seguradoras = new ObservableCollection( + from x in seguradoras1 + orderby x.get_Nome() + select x); + TutorialViewModel tutorialViewModel = this; + List ramos1 = ramos; + tutorialViewModel.Ramos = new ObservableCollection( + from x in ramos1 + orderby x.get_Nome() + select x); + base.EnableButtons = true; + } + else + { + await base.ShowMessage(str, "OK", "", false); + } + connectionHelper = null; + empresaServico = null; + empresa = null; + baseServico = null; + vendedorServico = null; + seguradoras = null; + } + + private async Task SalvarUsuario(Gestor.Model.Domain.Seguros.Usuario verificaUsuario) + { + long id; + string ssoId; + TutorialViewModel tutorialViewModel = this; + Gestor.Model.Domain.Seguros.Usuario usuario = verificaUsuario; + if (usuario != null) + { + id = usuario.get_Id(); + } + else + { + id = (long)0; + } + tutorialViewModel._idUsuario = id; + Gestor.Model.Domain.Seguros.Usuario usuario1 = new Gestor.Model.Domain.Seguros.Usuario(); + usuario1.set_Id(this._idUsuario); + usuario1.set_Nome(this.Nome); + usuario1.set_Login(this.Usuario); + usuario1.set_Senha((new Token()).AggerEncrypt(this.Senha)); + usuario1.set_Administrador(true); + usuario1.set_Excluido(false); + usuario1.set_IdEmpresa((long)1); + usuario1.set_PermissaoAggilizador(new long?((long)1)); + Gestor.Model.Domain.Seguros.Usuario usuario2 = verificaUsuario; + if (usuario2 != null) + { + ssoId = usuario2.get_SsoId(); + } + else + { + ssoId = null; + } + usuario1.set_SsoId(ssoId); + Gestor.Model.Domain.Seguros.Usuario usuario3 = usuario1; + usuario3 = await (new UsuarioServico()).Save(usuario3); + this._idUsuario = usuario3.get_Id(); + Recursos.Usuario = usuario3; + } + + public async Task UsuarioInicial() + { + bool flag; + Gestor.Model.Domain.Seguros.Usuario usuario = await (new UsuarioServico()).BuscaUsuarioInicial(this.Usuario, this.Senha); + if (usuario != null) + { + await this.SalvarUsuario(usuario); + flag = true; + } + else + { + await base.ShowMessage("USUÁRIO JÁ EXISTE E A SENHA ESTÁ INCORRETA, REINICIE O SISTEMA!", "OK", "", false); + flag = false; + } + return flag; + } + + public async Task ValidarLogin() + { + bool flag; + this.Fase1 = false; + this.Mensagem = "ESTAMOS VALIDANDO AS INFORMAÇÕES"; + if (string.IsNullOrEmpty(this.Usuario) || string.IsNullOrEmpty(this.Senha) || string.IsNullOrEmpty(this.ConfirmacaoSenha) || string.IsNullOrEmpty(this.Nome)) + { + await base.ShowMessage("NECESSÁRIO PREENCHER O NOME COMPLETO, USUÁRIO, SENHA E CONFIRMAÇÃO DA SENHA PARA PROSSEGUIR.", "OK", "", false); + this.Fase1 = true; + flag = true; + } + else if (!string.IsNullOrEmpty(this.Usuario) && !Regex.IsMatch(this.Usuario, "^(?!.*(@.*@|@\\.|\\.@|--|\\.\\.|-\\.|\\.-|-@|@-))[a-zA-Z0-9](?:[a-zA-Z0-9@.-]*[a-zA-Z0-9])?(?: [a-zA-Z0-9](?:[a-zA-Z0-9@.-]*[a-zA-Z0-9])?)?$")) + { + string[] newLine = new string[] { "USUÁRIO DEVE CONTER APENAS LETRAS E NÚMEROS,", Environment.NewLine, "NÃO DEVE CONTER MAIS DE UM ESPAÇO,", Environment.NewLine, "NÃO DEVE TER ESPAÇO NO INICIO E NO FIM.", Environment.NewLine, "EXEMPLO VALIDO:", Environment.NewLine, "USUARIO01 OU USUARIO 02 OU USUARIO.03" }; + await base.ShowMessage(string.Concat(newLine), "OK", "", false); + this.Fase1 = true; + flag = true; + } + else if (this.Usuario.Length > 30) + { + await base.ShowMessage("USUÁRIO SOMENTE DEVE CONTER NO MÁXIMO 30 CARACTERES", "OK", "", false); + this.Fase1 = true; + flag = true; + } + else if (this.Senha != this.ConfirmacaoSenha) + { + await base.ShowMessage("A SENHA E A CONFIRMAÇÃO DA SENHA ESTÃO DIFERENTES, CORRIJA PARA PROSSEGUIR.", "OK", "", false); + this.Fase1 = true; + flag = true; + } + else if (await this.UsuarioInicial()) + { + while (this.Seguradoras.Count == 0) + { + await Task.Delay(25); + } + this.Fase1 = false; + this.Fase2 = true; + flag = true; + } + else + { + flag = false; + } + return flag; + } + + public async Task ValidarSeguradoras() + { + this.Fase2 = false; + ObservableCollection seguradoras = this.Seguradoras; + if (!seguradoras.All((Seguradora x) => !x.get_Ativo())) + { + this.Fase2 = false; + this.Fase3 = true; + } + else + { + await base.ShowMessage("NECESSÁRIO AO MENOS UMA SEGURADORA ATIVA PARA PROSSEGUIR.", "OK", "", false); + this.Fase2 = true; + } + } + + public async Task VerificaAcesso() + { + bool flag; + Instalacao instalacao; + LicenseHelper licenseHelper = new LicenseHelper(); + bool flag1 = false; + if (!await licenseHelper.VerificarMaquina()) + { + base.Loading(false); + while (!flag1) + { + List instalacoes = await licenseHelper.GetInstalacoes(); + if (instalacoes.Count != 0) + { + List instalacaos = instalacoes; + IOrderedEnumerable ultimoAcesso = + from x in instalacaos + orderby x.get_UltimoAcesso() descending + select x; + Instalacao instalacao1 = ultimoAcesso.FirstOrDefault((Instalacao x) => x.get_UsuarioId() == Recursos.Usuario.get_Id()); + bool flag2 = instalacao1 != null; + if (flag2) + { + flag2 = await base.ShowMessage(string.Concat("SEU ULTIMO ACESSO FOI NA MAQUINA ", instalacao1.get_NomeMaquina(), ". DESEJA SUBSTITUIR A LICENÇA PARA ESSA MAQUINA?"), "SIM", "NÃO", false); + } + if (!flag2) + { + instalacao = await base.ShowInstalacoes(instalacoes); + } + else + { + instalacao = instalacao1; + } + Instalacao instalacao2 = instalacao; + if (instalacao2 != null) + { + await (new AjudaServico()).ExcluirInstalacao(instalacao2.get_Id()); + flag2 = await licenseHelper.VerificarMaquina(); + flag1 = flag2; + instalacoes = null; + instalacao1 = null; + } + else + { + await base.ShowMessage("MÁQUINA NÃO REGISTRADA", "OK", "", false); + flag = false; + licenseHelper = null; + return flag; + } + } + else + { + await base.ShowMessage("ACESSO NEGADO, NÃO EXISTEM LICENÇAS VÁLIDAS.", "OK", "", false); + flag = false; + licenseHelper = null; + return flag; + } + } + } + flag = true; + licenseHelper = null; + return flag; + } + + public async Task VerificaEmpresa() + { + string str; + ConnectionHelper connectionHelper = new ConnectionHelper(); + this.Empresa = await Connection.Get(string.Format("Customer/{0}", ApplicationHelper.IdFornecedor), true, false); + EmpresaServico empresaServico = new EmpresaServico(); + if (!connectionHelper.ExisteEmpresa()) + { + await empresaServico.Save(this.Empresa); + if (!empresaServico.Sucesso) + { + str = "ERRO AO CRIAR BANCO DE DADOS"; + connectionHelper = null; + empresaServico = null; + return str; + } + } + else if (!connectionHelper.BDConvertido()) + { + str = "HOUVE UM ERRO NO ACESSO! REINICIE O SISTEMA!"; + connectionHelper = null; + empresaServico = null; + return str; + } + str = null; + connectionHelper = null; + empresaServico = null; + return str; + } + + public async Task VerificarUsuario() + { + Instancia.ExcluirCfg(); + Gestor.Model.Domain.Seguros.Usuario usuario = await (new UsuarioServico()).BuscarUsuarioPorId((long)1); + if (usuario != null) + { + this.Nome = usuario.get_Nome(); + this.Usuario = usuario.get_Login(); + this._idUsuario = usuario.get_Id(); + } + } + } +} \ No newline at end of file -- cgit v1.2.3