using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Text.RegularExpressions; using System.Threading.Tasks; using Gestor.Application.Helpers; using Gestor.Application.Servicos; using Gestor.Application.Servicos.Ajuda; using Gestor.Application.Servicos.Ferramentas; using Gestor.Application.Servicos.Generic; using Gestor.Application.ViewModels.Generic; using Gestor.Common.Security; using Gestor.Model.API; using Gestor.Model.Common; using Gestor.Model.Domain.Common; using Gestor.Model.Domain.Generic; using Gestor.Model.Domain.Seguros; using Gestor.Model.License; namespace Gestor.Application.ViewModels; public class TutorialViewModel : BaseViewModel { private bool _fase1; private bool _fase2; private bool _fase3; private string _mensagem = "ESTAMOS PREPARANDO TUDO PRA VOCÊ INICIAR"; private string _nome; private string _usuario; private string _senha; private string _confirmacaoSenha; private ObservableCollection _seguradoras = new ObservableCollection(); private ObservableCollection _ramos = new ObservableCollection(); private bool _loadingVisibility; public bool Fase1 { get { return _fase1; } set { _fase1 = value; OnPropertyChanged("Fase1"); } } public bool Fase2 { get { return _fase2; } set { _fase2 = value; OnPropertyChanged("Fase2"); } } public bool Fase3 { get { return _fase3; } set { _fase3 = value; OnPropertyChanged("Fase3"); } } public string Mensagem { get { return _mensagem; } set { _mensagem = value; OnPropertyChanged("Mensagem"); } } private long _idUsuario { get; set; } = -1L; public string Nome { get { return _nome; } set { _nome = value; OnPropertyChanged("Nome"); } } public string Usuario { get { return _usuario; } set { _usuario = value; OnPropertyChanged("Usuario"); } } public string Senha { get { return _senha; } set { _senha = value; OnPropertyChanged("Senha"); } } public string ConfirmacaoSenha { get { return _confirmacaoSenha; } set { _confirmacaoSenha = value; OnPropertyChanged("ConfirmacaoSenha"); } } public ObservableCollection Seguradoras { get { return _seguradoras; } set { _seguradoras = value; OnPropertyChanged("Seguradoras"); } } public ObservableCollection Ramos { get { return _ramos; } set { _ramos = value; OnPropertyChanged("Ramos"); } } private Customer Empresa { get; set; } public bool LoadingVisibility { get { return _loadingVisibility; } set { _loadingVisibility = value; OnPropertyChanged("LoadingVisibility"); } } public TutorialViewModel() { base.EnableFields = true; } public async Task IniciarConfiguracoes() { base.EnableButtons = false; ConnectionHelper connectionHelper = new ConnectionHelper(); EmpresaServico servicoEmpresa = new EmpresaServico(); Empresa savedEmpresa = await servicoEmpresa.BuscarEmpresaPorId(1L); Empresa = await Connection.Get($"Customer/{ApplicationHelper.IdFornecedor}"); if (savedEmpresa == null) { await servicoEmpresa.Save(Empresa); } BaseServico servico = new BaseServico(); ControleArquivoDigital val = (ControleArquivoDigital)(((object)(await servico.BuscarControle())) ?? ((object)new ControleArquivoDigital { Catalogo = Connection.Catalog, Tabela = "Arquivos" })); if (((DomainBase)val).Id == 0L) { await servico.SalvarControle(val); } VendedorServico vendedorServico = new VendedorServico(); Vendedor val2 = (Vendedor)(((object)(await vendedorServico.BuscarCorretora())) ?? ((object)new Vendedor { IdEmpresa = 1L, Nome = Empresa.Name, Ativo = true, Corretora = true })); if (((DomainBase)val2).Id == 0L) { Repasse repasse = new Repasse { Forma = (FormaRepasse)1, Incidencia = (TipoIncidencia)1, Ativo = true, Tipo = (TipoRepasse)2, ValorNovo = 0m, ValorRenovacao = 0m }; await vendedorServico.Save(val2, repasse); if (!vendedorServico.Sucesso) { return; } } await new ArquivoDigitalServico().Criar(); string text = await connectionHelper.AtualizarBanco(); if (text != null) { await ShowMessage(text); return; } List seguradora = await new SeguradoraServico().BuscarSeguradoras(); List source = await new RamoServico().BuscarRamos(); Seguradoras = new ObservableCollection(seguradora.OrderBy((Seguradora x) => x.Nome)); Ramos = new ObservableCollection(source.OrderBy((Ramo x) => x.Nome)); base.EnableButtons = true; } public async Task ValidarLogin() { Fase1 = false; Mensagem = "ESTAMOS VALIDANDO AS INFORMAÇÕES"; if (string.IsNullOrEmpty(Usuario) || string.IsNullOrEmpty(Senha) || string.IsNullOrEmpty(ConfirmacaoSenha) || string.IsNullOrEmpty(Nome)) { await ShowMessage("NECESSÁRIO PREENCHER O NOME COMPLETO, USUÁRIO, SENHA E CONFIRMAÇÃO DA SENHA PARA PROSSEGUIR."); Fase1 = true; return true; } if (!string.IsNullOrEmpty(Usuario) && !Regex.IsMatch(Usuario, "^(?!.*(@.*@|@\\.|\\.@|--|\\.\\.|-\\.|\\.-|-@|@-))[a-zA-Z0-9](?:[a-zA-Z0-9@.-]*[a-zA-Z0-9])?(?: [a-zA-Z0-9](?:[a-zA-Z0-9@.-]*[a-zA-Z0-9])?)?$")) { await ShowMessage("USUÁRIO DEVE CONTER APENAS LETRAS E NÚMEROS," + Environment.NewLine + "NÃO DEVE CONTER MAIS DE UM ESPAÇO," + Environment.NewLine + "NÃO DEVE TER ESPAÇO NO INICIO E NO FIM." + Environment.NewLine + "EXEMPLO VALIDO:" + Environment.NewLine + "USUARIO01 OU USUARIO 02 OU USUARIO.03"); Fase1 = true; return true; } if (Usuario.Length > 30) { await ShowMessage("USUÁRIO SOMENTE DEVE CONTER NO MÁXIMO 30 CARACTERES"); Fase1 = true; return true; } if (Senha != ConfirmacaoSenha) { await ShowMessage("A SENHA E A CONFIRMAÇÃO DA SENHA ESTÃO DIFERENTES, CORRIJA PARA PROSSEGUIR."); Fase1 = true; return true; } if (!(await UsuarioInicial())) { return false; } while (Seguradoras.Count == 0) { await Task.Delay(25); } Fase1 = false; Fase2 = true; return true; } public async Task CriarBanco() { string text = await new ConnectionHelper().VerifyConnection(); if (text == null) { Instancia.ExcluirCfg(); return await VerificaEmpresa(); } return text; } public async Task VerificaEmpresa() { ConnectionHelper connectionHelper = new ConnectionHelper(); Empresa = await Connection.Get($"Customer/{ApplicationHelper.IdFornecedor}"); EmpresaServico servico = new EmpresaServico(); if (!connectionHelper.ExisteEmpresa()) { await servico.Save(Empresa); if (!servico.Sucesso) { return "ERRO AO CRIAR BANCO DE DADOS"; } } else if (!connectionHelper.BDConvertido()) { return "HOUVE UM ERRO NO ACESSO! REINICIE O SISTEMA!"; } return null; } public void DesativarRamos() { foreach (Ramo ramo in Ramos) { ramo.Ativo = false; } Ramos = new ObservableCollection(Ramos); } public void DesativarSeguradoras() { foreach (Seguradora seguradora in Seguradoras) { seguradora.Ativo = false; } Seguradoras = new ObservableCollection(Seguradoras); } public async Task Concluir() { Fase3 = false; if (Ramos.All((Ramo x) => !x.Ativo)) { await ShowMessage("NECESSÁRIO AO MENOS UM RAMO ATIVO PARA PROSSEGUIR."); Fase3 = true; return false; } Mensagem = "ESTAMOS TERMINANDO AS CONFIGURAÇÕES INICIAIS E LOGO MAIS VOCÊ PODERÁ UTILIZAR."; if (!(await UsuarioInicial())) { return false; } SeguradoraServico seguradoraServico = new SeguradoraServico(); foreach (Seguradora seguradora in Seguradoras) { await seguradoraServico.Save(seguradora, null, primeiroAcesso: true); if (!seguradoraServico.Sucesso) { return false; } } RamoServico ramoServico = new RamoServico(); foreach (Ramo ramo in Ramos) { await ramoServico.Save(ramo, null); if (!ramoServico.Sucesso) { return false; } } await new BaseServico().LoadInicialParameters(); return true; } public async Task UsuarioInicial() { Usuario val = await new UsuarioServico().BuscaUsuarioInicial(Usuario, Senha); if (val == null) { await ShowMessage("USUÁRIO JÁ EXISTE E A SENHA ESTÁ INCORRETA, REINICIE O SISTEMA!"); return false; } await SalvarUsuario(val); return true; } private async Task SalvarUsuario(Usuario verificaUsuario) { _idUsuario = ((verificaUsuario != null) ? ((DomainBase)verificaUsuario).Id : 0); Usuario val = new Usuario { Id = _idUsuario, Nome = Nome, Login = Usuario, Senha = new Token().AggerEncrypt(Senha), Administrador = true, Excluido = false, IdEmpresa = 1L, PermissaoAggilizador = 1L }; val.SsoId = ((verificaUsuario != null) ? verificaUsuario.SsoId : null); Usuario usuario = val; usuario = await new UsuarioServico().Save(usuario); _idUsuario = ((DomainBase)usuario).Id; Recursos.Usuario = usuario; } public async Task ValidarSeguradoras() { Fase2 = false; if (Seguradoras.All((Seguradora x) => !x.Ativo)) { await ShowMessage("NECESSÁRIO AO MENOS UMA SEGURADORA ATIVA PARA PROSSEGUIR."); Fase2 = true; } else { Fase2 = false; Fase3 = true; } } public async Task VerificarUsuario() { Instancia.ExcluirCfg(); Usuario val = await new UsuarioServico().BuscarUsuarioPorId(1L); if (val != null) { Nome = val.Nome; Usuario = val.Login; _idUsuario = ((DomainBase)val).Id; } } public async Task VerificaAcesso() { LicenseHelper license = new LicenseHelper(); bool registrar = false; if (!(await license.VerificarMaquina())) { Loading(isLoading: false); while (!registrar) { List licencas = await license.GetInstalacoes(); if (licencas.Count == 0) { await ShowMessage("ACESSO NEGADO, NÃO EXISTEM LICENÇAS VÁLIDAS."); return false; } Instalacao instalacaoUsuario = ((IEnumerable)licencas.OrderByDescending((Instalacao x) => x.UltimoAcesso)).FirstOrDefault((Func)((Instalacao x) => x.UsuarioId == ((DomainBase)Recursos.Usuario).Id)); bool flag = instalacaoUsuario != null; if (flag) { flag = await ShowMessage("SEU ULTIMO ACESSO FOI NA MAQUINA " + instalacaoUsuario.NomeMaquina + ". DESEJA SUBSTITUIR A LICENÇA PARA ESSA MAQUINA?", "SIM", "NÃO"); } Instalacao val = ((!flag) ? (await ShowInstalacoes(licencas)) : instalacaoUsuario); Instalacao val2 = val; if (val2 == null) { await ShowMessage("MÁQUINA NÃO REGISTRADA"); return false; } await new AjudaServico().ExcluirInstalacao(((DomainBase)val2).Id); registrar = await license.VerificarMaquina(); } } return true; } }