Ejemplo n.º 1
0
        public UrlData Post(UrlDataEntryModel entryValue)
        {
            if (!Uri.IsWellFormedUriString(entryValue.Url, UriKind.Absolute))
            {
                //throw new HttpRequestException("Bad url");

                _notification.AddNotification("Bad url - The url is not valid");
                return(null);
            }

            UrlData entry = _mapper.Map <UrlData>(entryValue);

            // if no id -> generate a random one
            // if id -> check if exist before insert
            if (string.IsNullOrEmpty(entry.Id))
            {
                entry.Id = IdGenerator.GenerateId();
                _context.UrlData.InsertOne(entry);
                return(entry);
            }

            if (_context.UrlData.Find(x => x.Id == entry.Id).Any())
            {
                _notification.AddNotification("Id already exist");
                return(null);
            }
            _context.UrlData.InsertOne(entry);
            return(entry);
        }
Ejemplo n.º 2
0
        public async Task <Unit> Handle(LoanGameCommand request, CancellationToken cancellationToken)
        {
            _logger.LogInformation($"CreateGameLoanCommandHandler was called Request.GameId: {request.GameId} Request.FriendId: {request.FriendId}");

            var game = await _gameRepository.GetByIdAsync(request.GameId);

            if (game == null)
            {
                _notificationContext.AddNotification("Jogo não encontrado", $"O jogo com o id:{request.GameId} não foi encontrado.");
                return(await Unit.Task);
            }

            var friend = await _friendRepository.GetByIdAsync(request.FriendId);

            if (friend == null)
            {
                _notificationContext.AddNotification("Amigo não encontrado", $"O amigo com o id:{request.FriendId} não foi encontrado.");
                return(await Unit.Task);
            }

            game.LoanGame();
            await _gameRepository.ReplaceOneAsync(game, cancellationToken);

            await _mediator.Publish(new GameLoanedEvent(game.Id, game.Name, friend.Id, game.LoanedAt.Value));

            _logger.LogInformation("CreateGameLoanCommandHandler end of execution");

            return(await Unit.Task);
        }
Ejemplo n.º 3
0
        public void Armazenar(CargoDto dto)
        {
            Cargo cargo;

            if (dto.Id == 0)
            {
                cargo = CargoBuilder.Novo().ComDescricao(dto.Descricao).Build();
            }
            else
            {
                cargo = _cargoRepositorio.ObterPorId(dto.Id);
                if (cargo == null)
                {
                    _notificationContext.AddNotification(TipoDeNotificacao.ErroDeServico, "Cargo não encontrado");
                    return;
                }

                List <Cargo> cargos = _cargoRepositorio.ObterPorDescricao(dto.Descricao);

                if (cargos.Count > 0 && cargos.Any(x => x.Id != cargo.Id))
                {
                    _notificationContext.AddNotification(TipoDeNotificacao.ErroDeServico, "Descrição utilizada");
                    return;
                }

                cargo.Descricao = dto.Descricao;

                _cargoRepositorio.Put(cargo);
            }

            if (!cargo.Validar())
            {
                _notificationContext.AddNotification(TipoDeNotificacao.ErroDeServico, "Cargo inválido");
                return;
            }

            if (dto.Id == 0)
            {
                List <Cargo> cargos = _cargoRepositorio.ObterPorDescricao(dto.Descricao);

                if (cargos.Count > 0)
                {
                    _notificationContext.AddNotification(TipoDeNotificacao.ErroDeServico, "Descrição utilizada");
                    return;
                }

                _cargoRepositorio.Post(cargo);
            }
        }
Ejemplo n.º 4
0
        public async Task <UpdateFornecedorCommandResult> Handle(UpdateFornecedorCommand request, CancellationToken cancellationToken)
        {
            var empresa = await _empresaQueryStore.ObterEmpresaPeloId(Guid.Parse(request.EmpresaId));

            if (empresa is null || empresa.Id == Guid.Empty)
            {
                _notificationContext.AddNotification(new Notification(Mensagens.EmpresaNaoEncontradaTitulo, Mensagens.EmpresaNaoEncontradaTexto));
                return(null);
            }

            var fornecedorAtualizado = await _fornecedorService.Atualizar(new Fornecedor(empresa, request.Nome, request.DataCadastro,
                                                                                         request.DadosPessoais, request.IdentificadorReceitaFederal)
            {
                Id = Guid.Parse(request.Id)
            });

            return(new UpdateFornecedorCommandResult()
            {
                Empresa = new EmpresaResult()
                {
                    NomeFantasia = fornecedorAtualizado.Empresa.NomeFantasia,
                    CNPJ = fornecedorAtualizado.Empresa.CNPJ,
                    UF = fornecedorAtualizado.Empresa.UF
                },
                DadosPessoais = fornecedorAtualizado.DadosPessoais,
                DataCadastro = fornecedorAtualizado.DataCadastro,
                IdentificadorReceitaFederal = fornecedorAtualizado.IdentificadorReceitaFederal,
                Nome = fornecedorAtualizado.Nome
            });
        }
        public async Task <IEnumerable <User> > Handle(PutUserCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.GetByid(request.Id);

            user.Nome           = request.Nome;
            user.CPF            = request.CPF;
            user.Email          = request.Email;
            user.Telefone       = request.Telefone;
            user.Sexo           = request.Sexo;
            user.DataNascimento = request.DataNascimento;
            user.DataAlteracao  = DateTime.Now;
            user.UserGithub     = request.UserGithub;

            await _userRepository.PutAsync(user);

            try
            {
                await _uow.CommitAsync();
            }
            catch (Exception e)
            {
                _notificationContext.AddNotification("error", e.Message);
            }

            var listUser = await _userRepository.GetAll();

            return(listUser);
        }
Ejemplo n.º 6
0
 public async Task Handle(Notification notification, CancellationToken cancellationToken)
 {
     await Task.Run(() =>
     {
         _notificationContext.AddNotification(notification);
     });
 }
        public async Task <IEnumerable <User> > Handle(AddUserCommand request, CancellationToken cancellationToken)
        {
            var user = new User
            {
                Nome           = request.Nome,
                CPF            = request.CPF,
                Email          = request.Email,
                Telefone       = request.Telefone,
                Sexo           = request.Sexo,
                DataNascimento = request.DataNascimento,
                UserGithub     = request.UserGithub
            };

            await _userRepository.AddAsync(user);

            try
            {
                await _uow.CommitAsync();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                _notificationContext.AddNotification("error", e.Message);
            }

            var listUser = await _userRepository.GetAll();

            return(listUser);
        }
        public async Task <FiltrarFornecedorPorIdQueryResponse> Handle(FiltrarFornecedorPorIdQuery request, CancellationToken cancellationToken)
        {
            var fornecedor = await _fornecedorQueryStore.FiltrarFornecedorPeloId(Guid.Parse(request.Id));

            if (fornecedor is null)
            {
                _notificationContext.AddNotification(new Notification(Mensagens.FornecedorNaoEncontraoTitulo, Mensagens.FornecedorNaoEncontradoTexto));
                return(null);
            }

            return(new FiltrarFornecedorPorIdQueryResponse()
            {
                Fornecedor = new FornecedoresResponse()
                {
                    Id = fornecedor.Id,
                    IdentificadorReceitaFederal = fornecedor.IdentificadorReceitaFederal,
                    Nome = fornecedor.Nome,
                    Empresa = new EmpresaResult()
                    {
                        Id = fornecedor.Empresa.Id,
                        CNPJ = fornecedor.Empresa.CNPJ,
                        NomeFantasia = fornecedor.Empresa.NomeFantasia,
                        UF = fornecedor.Empresa.UF.ToString()
                    },
                    DadosPessoais = fornecedor.DadosPessoais,
                    DataCadastro = fornecedor.DataCadastro
                }
            });
        }
Ejemplo n.º 9
0
        public async Task <Unit> Handle(PatchFriendCommand request, CancellationToken cancellationToken)
        {
            _logger.LogInformation($"PatchFriendCommandHandler was called Request.Id: {request.Id}");

            var friend = await _repository.GetByIdAsync(request.Id);

            if (friend == null)
            {
                _notificationContext.AddNotification("Amigo não encontrado", $"O amigo com o id:{request.Id} não foi encontrado.");
                return(await Unit.Task);
            }

            if (!string.IsNullOrWhiteSpace(request.Name) && !friend.Name.Equals(request.Name, System.StringComparison.OrdinalIgnoreCase))
            {
                friend.SetName(request.Name);
            }

            if (!string.IsNullOrWhiteSpace(request.CellPhoneNumber) && !friend.CellPhoneNumber.Equals(request.CellPhoneNumber, System.StringComparison.OrdinalIgnoreCase))
            {
                friend.SetCellPhoneNumber(request.CellPhoneNumber);
            }

            await _repository.ReplaceOneAsync(friend, cancellationToken);

            _logger.LogInformation("PatchFriendCommandHandler end of execution");

            return(await Unit.Task);
        }
Ejemplo n.º 10
0
        public async Task <IEnumerable <GetFriendsResponse> > Handle(GetFriendsQuery request, CancellationToken cancellationToken)
        {
            _logger.LogInformation("GetFriendsQueryHandler was called");

            var friends = await _repository.FindAsync(cancellationToken);

            if (!friends.Any())
            {
                _notificationContext.AddNotification("Nenhum Amigo Encontrado", "Não existe nenhum amigo no Banco de Dados :(");
                return(default);
        public async Task <GetFriendByIdResponse> Handle(GetFriendByIdQuery request, CancellationToken cancellationToken)
        {
            _logger.LogInformation("GetFriendByIdQueryHandler was called");

            var friend = await _repository.GetByIdAsync(request.Id, cancellationToken);

            if (friend == null)
            {
                _notificationContext.AddNotification("Amigo não encontrado", $"O amigo com o id:{request.Id} não foi encontrado.");
                return(default);
Ejemplo n.º 12
0
        private bool PodeCadastrarNessaEmpresa(Fornecedor fornecedor)
        {
            if (fornecedor.IdentificadorReceitaFederal.IsCPF() && fornecedor.Empresa.UF == EnumUF.PR && fornecedor.DadosPessoais.Idade < 18)
            {
                _notificationContext.AddNotification(new Notification(Mensagens.FornecedorMenorIdadePRTitulo, Mensagens.FornecedorMenorIdadePRTexto));
                return(false);
            }

            return(true);
        }
Ejemplo n.º 13
0
        public bool Excluir(int id)
        {
            Empresa empresa = _empresaRepositorio.ObterPorId(id);

            if (empresa == null)
            {
                _notificationContext.AddNotification(TipoDeNotificacao.ErroDeServico, "Empresa não encontrada");
                return(false);
            }

            if (empresa.Funcionarios.Count > 0)
            {
                _notificationContext.AddNotification(TipoDeNotificacao.ErroDeServico, "Existem funcionários associados a essa empresa");
                return(false);
            }

            _empresaRepositorio.Delete(empresa);

            return(true);
        }
Ejemplo n.º 14
0
        public bool Excluir(int id)
        {
            var cargo = _cargoRepositorio.ObterPorId(id);

            if (cargo == null)
            {
                _notificationContext.AddNotification(TipoDeNotificacao.ErroDeServico, "Cargo não encontrado");
                return(false);
            }

            if (cargo.Funcionarios.Count > 0)
            {
                _notificationContext.AddNotification(TipoDeNotificacao.ErroDeServico, "Existem funcionários associados ao cargo");
                return(false);
            }

            _cargoRepositorio.Delete(cargo);

            return(true);
        }
Ejemplo n.º 15
0
        public async Task <Unit> Handle(DeleteFornecedorCommand request, CancellationToken cancellationToken)
        {
            var removido = await _fornecedorCommandStore.Remover(request.Id);

            //Caso não encontre o registro para realizar a exclusão adiciona uma notificação para exibir a mensagem de erro.
            if (!removido)
            {
                _notificationContext.AddNotification(Mensagens.ErroAoExcluirTitulo, string.Format(Mensagens.ErroAoExcluirTexto, request.Id.ToString()));
            }

            return(Unit.Value);
        }
Ejemplo n.º 16
0
        private async Task <SegmentDto> OnExecutingAsync(long segmentId, decimal exchangeRate, CancellationToken cancellationToken)
        {
            try
            {
                var segment = await _mediator.Send(new GetSegmentByIdQuery(segmentId), cancellationToken);

                if (segment is null)
                {
                    _notificationContext.AddNotification(ApplicationMessages.UpdateSegmentExchangeRateUseCase_Segmento_Not_Found);
                    return(null);
                }

                segment.SetExchangeRate(exchangeRate);
                if (!segment.Valid)
                {
                    _notificationContext.AddNotifications(segment.ValidationResult);
                    return(null);
                }

                await _mediator.Send(new UpdateSegmentCommand(segment), cancellationToken);

                if (_notificationContext.HasNotifications)
                {
                    return(null);
                }

                return(new SegmentDto
                {
                    Id = segment.Id,
                    Name = segment.Name,
                    ExchangeRate = segment.ExchangeRate
                });
            }
            catch (Exception ex)
            {
                _notificationContext.AddNotification(ex);
            }

            return(null);
        }
Ejemplo n.º 17
0
        public async Task <Associado> CadastrarAssociado(Associado associado)
        {
            //Validação genérica para exemplificação de adição de uma notificação de domínio, não externalizando uma exception.
            if (associado.Idade < 18)
            {
                _notificationContext.AddNotification(new Notification("Associado menor de idade", "Não é possível cadastrar um associado menor de idade"));
                return(null);
            }

            var associadoCadastrado = await _associadoStore.Save(associado);

            return(associadoCadastrado);
        }
Ejemplo n.º 18
0
        public Task <IEnumerable <SegmentDto> > ExecuteAsync(CancellationToken cancellationToken)
        {
            try
            {
                return(_mediator.Send(new GetSegmentsQuery()));
            }
            catch (Exception ex)
            {
                _notificationContext.AddNotification(ex);
            }

            return(Task.FromResult <IEnumerable <SegmentDto> >(null));
        }
        public async Task <ConvertCoinBySegmentResultDto> ExecuteAsync(ConvertCoinBySegmentDto dto, CancellationToken cancellationToken)
        {
            try
            {
                var convertionResult = await _mediator.Send(new ConvertCoinQuery(dto.CoinFrom, dto.Amount, DateTime.Today), cancellationToken);

                if (convertionResult is null)
                {
                    _notificationContext.AddNotification(ApplicationMessages.ConvertCoinBySegmentUseCase_Coin_Convertion_Is_Not_Possible);
                    return(null);
                }

                var segment = await _mediator.Send(new GetSegmentByIdQuery(dto.SegmentId), cancellationToken);

                if (segment is null)
                {
                    _notificationContext.AddNotification(ApplicationMessages.ConvertCoinBySegmentUseCase_Segment_Not_Found);
                    return(null);
                }

                var convertedAmount = segment.ApplyExchangeRate(convertionResult.ResultAmount);
                return(new ConvertCoinBySegmentResultDto
                {
                    Amount = convertionResult.Amount,
                    CoinFrom = convertionResult.CoinFrom,
                    CoinTo = convertionResult.CoinTo,
                    ConvertedAmount = convertedAmount,
                    SegmentId = segment.Id,
                    SegmentName = segment.Name
                });
            }
            catch (Exception ex)
            {
                _notificationContext.AddNotification(ex);
            }

            return(null);
        }
Ejemplo n.º 20
0
        public async Task <ResponseProduto> ExecuteAsync(RequestProduto produto)
        {
            ProdutoEntity produtoEntity = new ProdutoEntity(produto.Nome);

            var produtoIncluido = await _repoProduto.CriarProduto(produtoEntity);

            if (produtoIncluido.Id == 0)
            {
                _fluntcontext.AddNotification(new Flunt.Notifications.Notification("nome_produto", "produto já existe"));
                return(null);
            }

            return(_mapper.Map <ResponseProduto>(produtoIncluido));
        }
Ejemplo n.º 21
0
        public async Task <LearningPath> LoadById(Guid Id)
        {
            var ret = await _collection.FindAsync(x => x.Id == Id);

            var result = await ret.FirstOrDefaultAsync();

            if (result is null)
            {
                _notificationContext.AddNotification("NO_LEARNING_PATH_FOUND.", "No Learning Path was found with this Id.", EStatusCodeNotification.NotFound);
                return(null);
            }

            return(result);
        }
Ejemplo n.º 22
0
        public bool Excluir(int id)
        {
            Funcionario funcionario = _funcionarioRepositorio.ObterPorId(id);

            if (funcionario == null)
            {
                _notificationContext.AddNotification(TipoDeNotificacao.ErroDeServico, "Funcionário não encontrado");
                return(false);
            }

            _funcionarioRepositorio.Delete(funcionario);

            return(true);
        }
        public async Task <Unit> Handle(DeleteGameCommand request, CancellationToken cancellationToken)
        {
            _logger.LogInformation($"DeleteGameCommandHandler was called Request.Id: {request.Id}");

            var game = await _repository.GetByIdAsync(request.Id);

            if (game == null)
            {
                _notificationContext.AddNotification("Jogo não encontrado", $"O jogo com o id:{request.Id} não foi encontrado.");
                return(await Unit.Task);
            }

            await _repository.DeleteOneAsync(game, cancellationToken);

            _logger.LogInformation("DeleteGameCommandHandler end of execution");

            return(await Unit.Task);
        }
        public CadastrarContaCorrenteResult Executar(CadastrarContaCorrenteRequest request)
        {
            if (_contaCorrenteRepositorio.Obter(request.Conta) != null)
            {
                _notificationContext.AddNotification(nameof(request.Conta), "Conta já cadastrada");
                return(new CadastrarContaCorrenteResult());
            }

            ContaCorrente conta = new ContaCorrente(Guid.NewGuid(), request.Agencia, request.Conta);

            if (conta.Invalid)
            {
                _notificationContext.AddNotifications(conta.Notifications);
                return(new CadastrarContaCorrenteResult());
            }

            _contaCorrenteRepositorio.Salvar(conta);
            return(CadastrarContaCorrenteResult.FromDomain(conta));
        }
        public async Task <Unit> Handle(ReturnGameCommand request, CancellationToken cancellationToken)
        {
            _logger.LogInformation($"ReturnGameCommandHandler was called Request.GameId: {request.GameId}");

            var game = await _repository.GetByIdAsync(request.GameId);

            if (game == null)
            {
                _notificationContext.AddNotification("Jogo não encontrado", $"O jogo com o id:{request.GameId} não foi encontrado.");
                return(await Unit.Task);
            }

            game.ReturnGame();
            await _repository.ReplaceOneAsync(game, cancellationToken);

            await _mediator.Publish(new GameReturnedEvent(game.Id));

            _logger.LogInformation("ReturnGameCommandHandler end of execution");

            return(await Unit.Task);
        }
Ejemplo n.º 26
0
        public async Task <DetailCourseDTO> GetCourseById(Guid id)
        {
            var ret = await _collection.FindAsync(x => x.Id == id);

            var result = await ret.FirstOrDefaultAsync();

            if (result is null)
            {
                _notificationContext.AddNotification("NO_COURSE_FOUND.", "No course was found with this Id.", EStatusCodeNotification.NotFound);
                return(default(DetailCourseDTO));
            }

            return(new DetailCourseDTO()
            {
                Title = result.Title,
                Description = result.Title,
                FirstClass = result.FirstClass,
                Instructors = result.Instructors.Select(x => x.Name),
                Score = result.Score
            });
        }
        public async Task <EmpresaFindByIdQueryResult> Handle(EmpresaFindByIdQuery request, CancellationToken cancellationToken)
        {
            var empresa = await _empresaQueryStore.ObterEmpresaPeloId(request.Id);

            if (empresa is null)
            {
                _notificationContext.AddNotification(new Notification(Mensagens.EmpresaNaoEncontradaTitulo, Mensagens.EmpresaNaoEncontradaTexto));
                return(null);
            }

            return(new EmpresaFindByIdQueryResult()
            {
                Empresa = new EmpresaResult()
                {
                    Id = empresa.Id,
                    CNPJ = empresa.CNPJ,
                    NomeFantasia = empresa.NomeFantasia,
                    UF = empresa.UF.ToString()
                }
            });
        }
        public async Task <IEnumerable <User> > Handle(DelUserCommand request, CancellationToken cancellationToken)
        {
            var user = await _userRepository.GetByid(request.Id);

            user.DataAlteracao = DateTime.Now;
            user.Ativo         = false;

            await _userRepository.Remove(user);

            try
            {
                await _uow.CommitAsync();
            }
            catch (Exception e)
            {
                _notificationContext.AddNotification("error", e.Message);
            }

            var listUser = await _userRepository.GetAll();

            return(listUser);
        }
Ejemplo n.º 29
0
 protected Unit Fail(string message)
 {
     _notificationContext.AddNotification(message);
     return(Unit.Value);
 }
Ejemplo n.º 30
0
 protected void SetValidationError(string mensagem)
 {
     _domainNotificationContext.AddNotification(mensagem);
 }