Exemplo n.º 1
0
 protected void NotificarValidacoesErro(ValidationResult validationResult)
 {
     foreach (var error in validationResult.Errors)
     {
         _mediator.PublishEvent(new DomainNotification(error.PropertyName, error.ErrorMessage));
     }
 }
        public Task <bool> Handle(RegisterTicketCommand message, CancellationToken cancellationToken)
        {
            var ticket = new Ticket(message.Id, message.Description, message.Localization, message.TicketStatusId, message.TicketTypeId, message.DateRegister);

            if (!TicketIsValid(ticket))
            {
                return(Task.FromResult(false));
            }

            var ticketRegistred = _ticketRepository.Find(c => c.Id == ticket.Id);

            if (ticketRegistred.Any())
            {
                _mediator.PublishEvent(new DomainNotification(message.MessageType, "Já existe um ticket com esse Id"));
            }

            _ticketRepository.Add(ticket);

            if (Commit())
            {
                _mediator.PublishEvent(new TicketRegisteredEvent(ticket.Id, ticket.Description, ticket.Localization, ticket.TicketStatusId, ticket.TicketTypeId, ticket.DateRegister));
            }

            return(Task.FromResult(true));
        }
Exemplo n.º 3
0
        private async Task <ResponseMessage> CreateCustomer(CreateNewUserCommand message)
        {
            var user = await _userRegisterProvider.FindByEmailAsync(message.Email).ConfigureAwait(false);

            var userSaved = new UserSaveIntegrationEvent(Guid.Parse(user.Id), message.Name, user.Email, message.IdentityNumber);

            try
            {
                var result = await _messageBus.RequestAsync <UserSaveIntegrationEvent, ResponseMessage>(userSaved).ConfigureAwait(false);

                if (!result.IsValid())
                {
                    var @event = new UserCanceledEvent(Guid.Parse(user.Id), message.IdentityNumber, message.Name, message.Email);
                    @event.ValidationResult = result.ValidResult;
                    await _mediator.PublishEvent(@event);

                    return(result);
                }
                await _mediator.PublishEvent(new CustomerCreatedEvent(result.AggregateId, message.Name, message.Email)).ConfigureAwait(false);

                return(result);
            }
            catch (Exception ex)
            {
                var @event = new UserCanceledEvent(Guid.Parse(user.Id), message.IdentityNumber, message.Name, message.Email);
                @event.ValidationResult.Errors.Add(new FluentValidation.Results.ValidationFailure(string.Empty, ex.Message));
                await _mediator.PublishEvent(@event).ConfigureAwait(false);

                return(new ResponseMessage(@event.ValidationResult));
            }
        }
Exemplo n.º 4
0
        public async Task <PurchaseViewModel> Add(AddPurchaseViewModel addPurchaseViewModel)
        {
            var currentDealer = await _dealerApplication.GetByCpf(addPurchaseViewModel.Cpf);

            if (currentDealer == null)
            {
                await _mediator.PublishEvent(new ApplicationNotification($"Não foi encontrado nenhum revendedor com o cpf: {addPurchaseViewModel.Cpf}"));

                return(null);
            }

            var purchase = currentDealer.IsAproved() ? new Purchase(currentDealer.Id, addPurchaseViewModel.Code, addPurchaseViewModel.Value, "Aprovado", addPurchaseViewModel.Date)
                                              : new Purchase(currentDealer.Id, addPurchaseViewModel.Code, addPurchaseViewModel.Value, "Em validação", addPurchaseViewModel.Date);

            if (!purchase.IsValid())
            {
                foreach (var error in purchase.ValidationResult.Errors)
                {
                    await _mediator.PublishEvent(new ApplicationNotification(error.ErrorMessage));
                }

                return(null);
            }

            await _purchaseRepository.AddAsync(purchase);

            await base.Commit();

            return(_mapper.Map <PurchaseViewModel>(purchase));
        }
Exemplo n.º 5
0
        public Task <bool> Handle(RegisterCitizenCommand message, CancellationToken cancellationToken)
        {
            var citizen = new Citizen(message.Id, message.Name, message.NickName, message.Document, message.Email, message.Gender, message.DateRegister);

            if (!CitizenIsValid(citizen))
            {
                return(Task.FromResult(false));
            }

            var citizenRegistred = _citizenRepository.Find(c => c.Document == citizen.Document || c.Email == citizen.Email);

            if (citizenRegistred.Any())
            {
                _mediator.PublishEvent(new DomainNotification(message.MessageType, "CPF ou e-mail já utilizados"));
            }

            _citizenRepository.Add(citizen);

            if (Commit())
            {
                _mediator.PublishEvent(new CitizenRegisteredEvent(citizen.Id, citizen.Name, citizen.NickName, citizen.Document, citizen.Email, citizen.Gender, citizen.DateRegister));
            }

            return(Task.FromResult(true));
        }
        public Task <Unit> Handle(RegisterOrganizerCommand message, CancellationToken cancellationToken)
        {
            var organizer = new Organizer(message.Id, message.Name, message.Email, message.DocumentId);

            if (!organizer.IsValid())
            {
                NotifyValidationError(organizer.ValidationResult);
                return(Task.FromResult(Unit.Value));
            }

            var organizerExists = _organizerRepository.Search(o => o.DocumentId == organizer.DocumentId || o.Email == organizer.Email);

            if (organizerExists.Any())
            {
                _mediator.PublishEvent(new DomainNotification(message.MessageType, "Document ID or Email already registered"));
            }

            _organizerRepository.Add(organizer);

            if (Commit())
            {
                _mediator.PublishEvent(new OrganizerRegisteredEvent(organizer.Id, organizer.Name, organizer.Email, organizer.DocumentId));
            }

            return(Task.FromResult(Unit.Value));
        }
Exemplo n.º 7
0
        public Task <Unit> Handle(RegisterConferenceCommand message, CancellationToken cancellationToken)
        {
            var address = new Address(message.Address.Id, message.Address.Address1, message.Address.Address2, message.Address.Address3,
                                      message.Address.Number, message.Address.Postcode, message.Address.City, message.Address.County, message.Address.ConferenceId.Value);

            var conference = Conference.ConferenceFactory.NewConferenceComplety(message.Id, message.Name, message.ShortDescription,
                                                                                message.LongDescription, message.StartDate, message.EndDate, message.Free, message.Value,
                                                                                message.Online, message.CompanyName, _user.GetUserId(), address, message.CategoryId);

            if (!IsConferenceValid(conference))
            {
                return(Task.FromResult(Unit.Value));
            }

            // TODO:
            // Validate business
            // Organizer can register conference?

            _conferenceRepository.Add(conference);

            if (Commit())
            {
                _mediator.PublishEvent(new ConferenceRegisteredEvent(conference.Id, conference.Name, conference.StartDate, conference.EndDate,
                                                                     conference.Free, conference.Value, conference.Online, conference.CompanyName));
            }

            return(Task.FromResult(Unit.Value));
        }
Exemplo n.º 8
0
        public async Task <CommandResult <ValidationResult> > Handle(TestCommand request, CancellationToken cancellationToken)
        {
            var result = new TestCommandResult {
                Result = "Result Command"
            };
            var a = new CommandResult <TestCommandResult>(result);

            await _mediatorHandler.PublishEvent(new ExampleEvent(Guid.Empty));

            return(null);
        }
Exemplo n.º 9
0
        public async Task Handle(PedidoIniciadoEvent message, CancellationToken cancellationToken)
        {
            var result = await _estoqueService.DebitarListaProdutosPedido(message.ProdutosPedido);

            if (result)
            {
                await _mediatorHandler.PublishEvent(new PedidoEstoqueConfirmadoEvent(message.PedidoId, message.ClienteId, message.Total, message.ProdutosPedido, message.NomeCartao, message.NumeroCartao, message.ExpiracaoCartao, message.CvvCartao));
            }
            else
            {
                await _mediatorHandler.PublishEvent(new PedidoEstoqueRejeitadoEvent(message.PedidoId, message.ClienteId));
            }
        }
Exemplo n.º 10
0
        public async Task Handle(OrderCreatedEvent message, CancellationToken cancellationToken)
        {
            var result = await _inventoryService.DebitOrderProducts(message.OrderProducts);

            if (result)
            {
                await _mediatorHandler.PublishEvent(new OrderInventoryConfirmedEvent(message.OrderId, message.CustomerId, message.Total, message.OrderProducts, message.CardName, message.CardNumber, message.CardExpiryDate, message.CardCvvCode));
            }
            else
            {
                await _mediatorHandler.PublishEvent(new OrderInventoryRejectedEvent(message.OrderId, message.CustomerId));
            }
        }
Exemplo n.º 11
0
        public async Task Handle(AddTradeCommand notification)
        {
            var entityCurrent = Mapper.Map <TradeModel, Trade>(notification.TradeModel);

            if (!IsEntityValid(entityCurrent))
            {
                return;
            }

            var userEntity = GetUserEntityTrade(notification.UserLoggedIn, entityCurrent.UserGet, entityCurrent.UserLet);

            if (userEntity == null)
            {
                return;
            }
            if (!IsUsersValid(notification.UserLoggedIn, userEntity, entityCurrent.UserGet, entityCurrent.UserLet))
            {
                return;
            }

            await _tradeRepository.AddAsync(entityCurrent);

            if (Commit())
            {
                await _mediator.PublishEvent(new TradeAddedEvent(_logger, Mapper.Map <TradeModel>(notification.TradeModel)));
            }
        }
Exemplo n.º 12
0
        protected void NotifyError(Exception ex, string key, string value)
        {
            var valueLocalized = _localizer[value];

            _logger.LogError(ex, string.Concat(key, "::", valueLocalized));
            _mediator.PublishEvent(new DomainNotification(_logger, key, valueLocalized));
        }
Exemplo n.º 13
0
 protected void RaiseEvents(IReadOnlyList <INotification> events)
 {
     foreach (var @event in events)
     {
         _mediator.PublishEvent(@event);
     }
 }
Exemplo n.º 14
0
        public async Task Handle(AddImageProcessCommand notification)
        {
            var entityCurrent = Mapper.Map <ImageProcessModel, ImageProcess>(notification.ImageProcessModel);

            if (!IsEntityValid(entityCurrent))
            {
                return;
            }

            await _imageProcessRepository.AddAsync(entityCurrent);

            if (Commit())
            {
                await _mediator.PublishEvent(new ImageProcessAddedEvent(_logger, Mapper.Map <ImageProcessModel>(notification.ImageProcessModel)));
            }
        }
Exemplo n.º 15
0
        public async Task <bool> Debit(Guid productId, int quantity)
        {
            var product = await _productRepository.GetById(productId);

            if (product == null)
            {
                return(false);
            }

            if (!product.HasStock(quantity))
            {
                return(false);
            }

            product.StockDebit(quantity);

            //TODO: parametrize this value
            if (product.StockQuantity < 5)
            {
                await _mediatorHandler.PublishEvent(new LowStockEvent(product.Id, product.StockQuantity));
            }

            _productRepository.Update(product);
            return(await _productRepository.UnitOfWork.Commit());
        }
Exemplo n.º 16
0
        public async Task <object> GetApiClient()
        {
            using (var client = new HttpClient())
            {
                var url = "https://mdaqk8ek5j.execute-api.us-east-1.amazonaws.com/v1/cashback?cpf=12312312323";
                client.DefaultRequestHeaders.Add("token", "ZXPURQOARHiMc6Y0flhRC1LVlZQVFRnm");
                //client.DefaultRequestHeaders.Add("Authorization", "Bearer ZXPURQOARHiMc6Y0flhRC1LVlZQVFRnm");
                var response = await client.GetAsync(url);


                if (!response.IsSuccessStatusCode)
                {
                    await _mediator.PublishEvent(new ApplicationNotification($"Falha ao fazer a requisição status: {response.StatusCode}"));

                    return(null);
                }
                else
                {
                    var json = await response.Content.ReadAsStringAsync();

                    var responseCashback = JsonConvert.DeserializeObject <ResponseCashbackViewModel>(json);

                    return(new { responseCashback?.Body?.Credit });
                }
            }
        }
Exemplo n.º 17
0
        private async Task <bool> DebitarItemEstoque(Guid produtoId, int quantidade)
        {
            var produto = await _produtoRepository.GetById(produtoId);

            if (produto == null)
            {
                return(false);
            }

            if (!produto.PossuiEstoqueSuficiente(quantidade))
            {
                await _mediatorHandler.PublishNotification(new DomainNotification("Estoque", $"Produto - {produto.Nome} sem estoque"));

                return(false);
            }

            produto.DebitarEstoque(quantidade);

            // TODO: 10 pode ser parametrizavel em arquivo de configuração
            if (produto.QuantidadeEstoque < 10)
            {
                await _mediatorHandler.PublishEvent(new ProdutoAbaixoEstoqueEvent(produto.Id, produto.QuantidadeEstoque));
            }

            _produtoRepository.Update(produto);
            return(true);
        }
Exemplo n.º 18
0
        public async Task <bool> Commit()
        {
            foreach (var entry in ChangeTracker.Entries()
                     .Where(entry => entry.Entity.GetType().GetProperty("CreatedDate") != null))
            {
                if (entry.State == EntityState.Added)
                {
                    entry.Property("CreatedDate").CurrentValue = DateTime.Now;
                }

                if (entry.State == EntityState.Modified)
                {
                    entry.Property("CreatedDate").IsModified = false;
                }
            }

            var success = await base.SaveChangesAsync() > 0;

            if (success)
            {
                await _mediatorHandler.PublishEvent(this);
            }

            return(success);
        }
Exemplo n.º 19
0
        public async Task OnPostLike(string id, PostLike postLike)
        {
            postLike.Like();

            await _mediatorHandler.PublishEvent(new PostLikedEvent(postLike.LikeCounter));

            await _repository.OnPostLike(id, postLike);
        }
Exemplo n.º 20
0
        public async Task Handle(OrderStartedEvent message, CancellationToken cancellationToken)
        {
            var result = await _courseService.EnrolCourse(message.CoursesOrder);

            if (result)
            {
                await _mediatorHandler.PublishEvent(new OrderEnrolledAcceptedEvent(message.OrderId,
                                                                                   message.ClientId,
                                                                                   message.Total,
                                                                                   message.CoursesOrder,
                                                                                   message.NameCard,
                                                                                   message.NumberCard,
                                                                                   message.ExpirationDateCard,
                                                                                   message.CvvCard));
            }
            else
            {
                await _mediatorHandler.PublishEvent(new OrderEnrolledRejectedEvent(message.OrderId, message.ClientId));
            }
        }
Exemplo n.º 21
0
        public static async Task PublishEvents <T>(this IMediatorHandler mediatorHandler, T context) where T : DbContext
        {
            var domainEntities = context.ChangeTracker.Entries <Entity>().Where(e => e.Entity.Events.Any()).ToList();

            var domainEvents = domainEntities.SelectMany(e => e.Entity.Events).ToList();

            domainEntities.ForEach(e => e.Entity.ClearEvents());

            var tasks = domainEvents.Select(async(domainEvent) => { await mediatorHandler.PublishEvent(domainEvent); });

            await Task.WhenAll(tasks);
        }
Exemplo n.º 22
0
        public async Task <bool> Handle(RequestTenantCommand message, CancellationToken cancellationToken)
        {
            await _mediatorHandler.PublishEvent(new TenantRequestedEvent(message.Name,
                                                                         message.Email,
                                                                         message.Cpnj));

            if (!ValidateCommand(message))
            {
                await _mediatorHandler.SendCommand(new RejectTenantRegisterCommand(message.Name,
                                                                                   message.Email,
                                                                                   message.Cpnj));

                return(false);//TODO Comando executado com sucesso, deveria ser true ?
            }

            await _mediatorHandler.SendCommand(new RegisterTenantCommand(message.Name,
                                                                         message.Email,
                                                                         message.Cpnj));

            return(true);
        }
Exemplo n.º 23
0
        private bool EmployeeExists(Guid id, string messageType)
        {
            var employee = _employeeRepository.GetById(id);

            if (employee != null)
            {
                return(true);
            }

            _mediator.PublishEvent(new DomainNotification(messageType, "Funcionário não encontrado."));
            return(false);
        }
Exemplo n.º 24
0
        public async Task Handle(AddUserCommand notification)
        {
            var entityCurrent = Mapper.Map <UserModel, User>(notification.UserModel);

            if (!IsEntityValid(entityCurrent))
            {
                return;
            }

            if (!IsUsersValid(notification.UserLoggedIn, entityCurrent))
            {
                return;
            }

            await _userRepository.AddAsync(entityCurrent);

            await _userRepository.AddSystemAsync(entityCurrent.IdUserIdentity, entityCurrent.IdSystems);

            if (Commit())
            {
                await _mediator.PublishEvent(new UserAddedEvent(_logger, Mapper.Map <UserModel>(notification.UserModel)));
            }
        }
        public static Task PublishEvents <T>(this IMediatorHandler mediatorHandler, T context) where T : DbContext
        {
            var entities = context.ChangeTracker.Entries <Entity>().Where(e => e.Entity.Events != null && e.Entity.Events.Any());

            var events = entities.SelectMany(e => e.Entity.Events).ToList();

            entities.ToList().ForEach(e => e.Entity.ClearEventList());

            var tasks = events.Select(async(eventObj) => {
                await mediatorHandler.PublishEvent(eventObj);
            });

            return(Task.WhenAll(tasks));
        }
Exemplo n.º 26
0
        public Task Handle(RegisterAppUserCommand message, CancellationToken cancellationToken)
        {
            var appUser = new AppUser(message.Id, message.Email);

            if (!appUser.IsValid())
            {
                NotificarValidacoesErro(appUser.ValidationResult);
                return(Task.CompletedTask);
            }

            var appUserCore = _appUserRepository.GetById(appUser.Id);

            if (appUserCore != null && appUserCore.Id == appUser.Id)
            {
                _mediator.PublishEvent(new DomainNotification(message.MessageType, "An user with this email already exists."));
                return(Task.CompletedTask);
            }

            _appUserRepository.Add(appUser);
            _mediator.PublishEvent(new AppUserRegisteredEvent(appUser.Id, appUser.Email));

            return(Task.CompletedTask);
        }
Exemplo n.º 27
0
        public async Task Handle(AddVideoCameraCommand notification)
        {
            var entityCurrent = Mapper.Map <VideoCameraModel, VideoCamera>(notification.VideoCameraModel);

            if (!IsEntityValid(entityCurrent))
            {
                return;
            }

            var personGroup = await _personRepository.GetPersonGroupByIdAsync(notification.VideoCameraModel.IdPersonGroups);

            if (personGroup == null)
            {
                NotifyErrorValidations("AddVideoCameraCommand", "PersonGroup not found");
                return;
            }

            await _videoCameraRepository.AddAsync(entityCurrent);

            if (Commit())
            {
                await _mediator.PublishEvent(new VideoCameraAddedEvent(_logger, Mapper.Map <VideoCameraModel>(notification.VideoCameraModel)));
            }
        }
Exemplo n.º 28
0
        protected async Task <bool> Commit()
        {
            if (_notifications.HasNotifications())
            {
                return(false);
            }

            if (_uow.Commit())
            {
                return(true);
            }

            await _mediator.PublishEvent(new ApplicationNotification("Ocorreu um erro ao salvar os dados"));

            return(false);
        }
Exemplo n.º 29
0
        public async Task <CommandResult <UserLoginResponse> > Handle(TokenRefreshCommand command, CancellationToken cancellationToken)
        {
            var token = await _userLoginProvider.GetRefreshToken(command.TokenId).ConfigureAwait(false);

            if (token == null)
            {
                var @event = new TokenRefreshInvalidEvent();

                await _mediatorHandler.PublishEvent(@event).ConfigureAwait(false);

                return(new CommandResult <UserLoginResponse>(@event.ValidationResult));
            }

            var jsonToken = await _userLoginProvider.TokenGenerator(token.Username, _userProvider.Issuer, _userProvider.RefreshTokenExpiration).ConfigureAwait(false);

            return(new CommandResult <UserLoginResponse>(jsonToken));
        }
Exemplo n.º 30
0
        /// <summary>
        /// This extension will publish the event after the commit of Unit of Work is sucessfull
        /// </summary>
        /// <param name="mediator"></param>
        /// <param name="ctx"></param>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static async Task PublishEvents <T>(this IMediatorHandler mediator, T ctx) where T : HydraDbContext
        {
            var domainEntities = ctx.ChangeTracker
                                 .Entries <Entity>()
                                 .Where(x => x.Entity.Notifications != null && x.Entity.Notifications.Any());

            var domainEvents = domainEntities
                               .SelectMany(x => x.Entity.Notifications)
                               .ToList();

            domainEntities.ToList()
            .ForEach(entity => entity.Entity.ClearEvents());

            var tasks = domainEvents
                        .Select(async(domainEvent) => await mediator.PublishEvent(domainEvent));

            await Task.WhenAll(tasks);
        }