From 674ca83ba9243a9e95a7568c797668dab6aee26a Mon Sep 17 00:00:00 2001 From: Lucas Faria Mendes Date: Mon, 30 Mar 2026 10:35:25 -0300 Subject: feat: upload files --- .../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 + 27 files changed, 16783 insertions(+) create mode 100644 Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/BaseViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/ItemViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs create mode 100644 Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs (limited to 'Gestor.Application/ViewModels/Generic') diff --git a/Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs b/Gestor.Application/ViewModels/Generic/BaseApoliceViewModel.cs new file mode 100644 index 0000000..5bb2e93 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs b/Gestor.Application/ViewModels/Generic/BaseDialogViewModel.cs new file mode 100644 index 0000000..1b8cfbe --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs b/Gestor.Application/ViewModels/Generic/BaseFinanceiroViewModel.cs new file mode 100644 index 0000000..3e5561d --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs b/Gestor.Application/ViewModels/Generic/BaseSegurosViewModel.cs new file mode 100644 index 0000000..8f75310 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs b/Gestor.Application/ViewModels/Generic/BaseTarefaViewModel.cs new file mode 100644 index 0000000..ad8c5a5 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/BaseViewModel.cs b/Gestor.Application/ViewModels/Generic/BaseViewModel.cs new file mode 100644 index 0000000..e680922 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogAdvertisingViewModel.cs new file mode 100644 index 0000000..abd3dde --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogAnexarViewModel.cs new file mode 100644 index 0000000..0e87f86 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogCopiaViewModel.cs new file mode 100644 index 0000000..3386705 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogCopiarPermissaoViewModel.cs new file mode 100644 index 0000000..0ca71be --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogEditarParcelasViewModel.cs new file mode 100644 index 0000000..bf96cfe --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogEnviarEmailsViewModel.cs new file mode 100644 index 0000000..646d94e --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogExportarPermissaoViewModel.cs new file mode 100644 index 0000000..dd39cab --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogGraficoViewModel.cs new file mode 100644 index 0000000..94b332a --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogMedalhaViewModel.cs new file mode 100644 index 0000000..49eb58b --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogPesquisaAvancadaViewModel.cs new file mode 100644 index 0000000..284d821 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogProspeccaoViewModel.cs new file mode 100644 index 0000000..f95e6d6 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogTarefaViewModel.cs new file mode 100644 index 0000000..9041cd3 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogTrilhaViewModel.cs new file mode 100644 index 0000000..1735419 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogViewModel.cs new file mode 100644 index 0000000..523b64f --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs b/Gestor.Application/ViewModels/Generic/DialogVinculoViewModel.cs new file mode 100644 index 0000000..1d526ea --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs b/Gestor.Application/ViewModels/Generic/ErrorDialogViewModel.cs new file mode 100644 index 0000000..0a9224b --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs b/Gestor.Application/ViewModels/Generic/ExtratoComissaoViewModel.cs new file mode 100644 index 0000000..7630bbd --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/ItemViewModel.cs b/Gestor.Application/ViewModels/Generic/ItemViewModel.cs new file mode 100644 index 0000000..b8c015a --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs b/Gestor.Application/ViewModels/Generic/ProtocoloViewModel.cs new file mode 100644 index 0000000..d1d8836 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs b/Gestor.Application/ViewModels/Generic/ReordenarItensViewModel.cs new file mode 100644 index 0000000..f44c811 --- /dev/null +++ b/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/Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs b/Gestor.Application/ViewModels/Generic/SelecionarItensViewModel.cs new file mode 100644 index 0000000..852bedd --- /dev/null +++ b/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 -- cgit v1.2.3