/// <summary>
        /// Handles the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public async Task <Unit> Handle(UpdateCustomerCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                foreach (var error in request.ValidationResult.Errors)
                {
                    await _eventDispatcher.RaiseEvent(new DomainNotification(request.MessageType, error.ErrorMessage));
                }
                return(Unit.Value);
            }

            var existingCustomer = _customerRepository.FindOne(request.Id);

            if (existingCustomer == null)
            {
                await _eventDispatcher.RaiseEvent(new DomainNotification(request.MessageType, @"The customer does not exit in system"));

                return(Unit.Value);
            }

            var customer = new Customer();

            if (string.IsNullOrEmpty(request.Email) && string.IsNullOrEmpty(request.Password))
            {
                customer = Customer.UpdateWithoutEmailAndPassword(request.Id, request.FirstName, request.LastName);
                _customerRepository.UpdateWithoutEmailAndPassword(customer);
            }
            else
            {
                customer = Customer.Update(request.Id, request.FirstName, request.LastName, request.Email, request.Password);
                _customerRepository.Update(customer);
            }

            _unitOfWork.Commit();

            await _eventDispatcher.RaiseEvent(new CustomerUpdatedEvent { Customer = customer });

            return(Unit.Value);
        }
        public async Task <ApiResponse <CustomerDetailVm> > UpdateCustomer(CustomerDetailVm customerDetailViewModel)
        {
            try
            {
                ApiResponse <CustomerDetailVm> apiResponse           = new ApiResponse <CustomerDetailVm>();
                UpdateCustomerCommand          updateCustomerCommand = _mapper.Map <UpdateCustomerCommand>(customerDetailViewModel);

                var updateCustomerCommandResponse = await _client.UpdateCustomerAsync(updateCustomerCommand);

                if (updateCustomerCommandResponse.Success)
                {
                    apiResponse.Data    = _mapper.Map <CustomerDetailVm>(updateCustomerCommandResponse.Customer);
                    apiResponse.Success = true;
                }

                return(apiResponse);
            }
            catch (ApiException ex)
            {
                return(ConvertApiExceptions <CustomerDetailVm>(ex));
            }
        }
Exemplo n.º 3
0
        public async Task GivenUpdateCustomerCommand_ReturnsSuccessStatusCode()
        {
            var command = new UpdateCustomerCommand
            {
                Id           = "ALFKI",
                Address      = "Obere Str. 57",
                City         = "Berlin",
                CompanyName  = "Alfreds Futterkiste",
                ContactName  = "Maria Anders",
                ContactTitle = "Sales Representative",
                Country      = "Germany",
                Fax          = "030-0076545",
                Phone        = "030-0074321",
                PostalCode   = "12209"
            };

            var content = Utilities.GetRequestContent(obj: command);

            var response = await _client.PutAsync($"/api/customers/update/{command.Id}", content : content);

            response.EnsureSuccessStatusCode();
        }
Exemplo n.º 4
0
        public async Task GivenUpdateCustomerCommandWithInvalidId_ReturnsNotFoundStatusCode()
        {
            var client = await _factory.GetAuthenticatedClientAsync();

            var invalidCommand = new UpdateCustomerCommand
            {
                Id           = 0,
                Active       = false,
                Person       = new Person("Jos", "Jossian", Domain.Enums.GenderType.Male),
                CustomerType = Domain.Enums.CustomerType.Private,
                Address      = new Address("Stationstraat", "10", "Zaventem", "West-Vlaanderen", null, null),
                ContactData  = new ContactData("*****@*****.**", null, "+324700706043", null, null)
            };



            var content = Utilities.GetRequestContent(invalidCommand);

            var response = await client.PutAsync($"/api/customers/update/{invalidCommand.Id}", content);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
        public async Task GivenUpdateCustomerCommandWithInvalidId_ReturnsNotFoundStatusCode()
        {
            var invalidCommand = new UpdateCustomerCommand
            {
                Id           = "AAAAA",
                Address      = "Obere Str. 57",
                City         = "Berlin",
                CompanyName  = "Alfreds Futterkiste",
                ContactName  = "Maria Anders",
                ContactTitle = "Sales Representative",
                Country      = "Germany",
                Fax          = "030-0076545",
                Phone        = "030-0074321",
                PostalCode   = "12209"
            };

            var content = Utilities.GetRequestContent(invalidCommand);

            var response = await _client.PutAsync($"/api/customers/update/{invalidCommand.Id}", content);

            Assert.Equal(HttpStatusCode.NotFound, response.StatusCode);
        }
        /// <summary>
        /// Handles the specified request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns>Task.</returns>
        public Task Handle(UpdateCustomerCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                foreach (var error in request.ValidationResult.Errors)
                {
                    _eventDispatcher.RaiseEvent(new DomainNotification(request.MessageType, error.ErrorMessage));
                }
                return(Task.CompletedTask);
            }

            var country = _countryRepository.FindById(request.CountryId);

            if (country == null)
            {
                _eventDispatcher.RaiseEvent(new DomainNotification(request.MessageType, @"Country id does not exit in system"));
                return(Task.CompletedTask);
            }

            var existingCustomer = _customerRepository.FindOne(request.Id);

            if (existingCustomer == null)
            {
                _eventDispatcher.RaiseEvent(new DomainNotification(request.MessageType, @"The customer does not exit in system"));
                return(Task.CompletedTask);
            }

            //edit customer
            var customer = Customer.UpdateWithoutEmailAndPassword(request.Id, request.FirstName, request.LastName, country);

            _customerRepository.UpdateWithoutEmailAndPassword(customer);
            _unitOfWork.Commit();

            _eventDispatcher.RaiseEvent(new CustomerUpdatedEvent {
                Customer = customer
            });

            return(Task.CompletedTask);
        }
Exemplo n.º 7
0
        public ICommandResult Handle(UpdateCustomerCommand command)
        {
            Customer customer = null;

            if (_repository.CheckEmailUpdate(command.Email, command.Id))
            {
                AddNotification("Email", "Este Email já está em uso");
            }

            var   currentCustomer = _repository.GetById(command.Id);
            Name  name            = new Name(command.FirstName, command.LastName);
            Email email           = new Email(command.Email);

            if (currentCustomer == null)
            {
                AddNotification("Id", "Cadastro não encontrado");
            }
            else
            {
                customer = new Customer(currentCustomer, command.Id);
                customer.Update(name, email, command.Phone);
                AddNotifications(customer);
            }

            if (Invalid)
            {
                return(new UpdateCustomerCommandResult(false, "Por favor, corrija os campos abaixo", Notifications));
            }

            _repository.Update(customer);
            _emailService.Send(email.Address, "*****@*****.**", "Bem vindo", "Alteração de cadastro realizada com sucesso");

            return(new UpdateCustomerCommandResult(true, "Alteração de cadastro realizada com sucesso", new {
                Id = customer.Id,
                Name = customer.Name,
                Email = customer.Email,
                Phone = customer.Phone
            }));
        }
        public async Task <IActionResult> Edit(UpdateCustomerCommand command)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var result = await Mediator.Send(command);

                    if (result.IsSuccess)
                    {
                        TempData["Message"] = result.Success;
                    }

                    return(RedirectToAction(nameof(CustomerDetails), new { id = command.Profile.CustomerId }));
                }
                catch (NotFoundException ex)
                {
                    return(NotFound(ex.Message));
                }
            }
            return(View(command));
        }
Exemplo n.º 9
0
        public async Task Handle_ValidCommand_CustomerRepositoryCalled()
        {
            // Arrange
            var customerId = Guid.Parse("B83806BA-41D7-4412-B20A-3E65518C970A");
            var command    = new UpdateCustomerCommand
            {
                Id          = customerId,
                PhoneNumber = 123456789,
                Website     = "https://www.example.com"
            };
            var customer = this.fixture
                           .Build <Customer>()
                           .With(c => c.Id, customerId)
                           .Create();

            this.identityServiceMock
            .Setup(s => s.GetUserIdentifierAsync())
            .ReturnsAsync(customerId);

            this.repositoryMock
            .Setup(r => r.GetCustomerAsync(command.Id))
            .ReturnsAsync(customer);

            this.repositoryMock
            .Setup(r => r.UpdateCustomerAsync(
                       It.Is <Customer>(
                           c => c.Id == command.Id &&
                           c.PhoneNumber == command.PhoneNumber &&
                           c.Website.OriginalString == command.Website)))
            .Returns(Task.CompletedTask);

            // Act
            await this.handler.Handle(command, CancellationToken.None);

            // Assert
            this.identityServiceMock.VerifyAll();
            this.repositoryMock.VerifyAll();
        }
Exemplo n.º 10
0
        public ICommandResult Handler(UpdateCustomerCommand command)
        {
            command.Validate();
            if (!command.IsValid)
            {
                return(new GenericCommandResult(false, "Ops! Operação não pode ser realizada. Cheque as informações retornadas.", command.Notifications));
            }

            if (_repository.Search(x => x.CNPJ == command.CNPJ && x.Id != command.Id).Any())
            {
                return(new GenericCommandResult(false, "CNPJ pertence a outro cliente", null));
            }

            var customer = _repository.GetById(command.Id);

            if (customer == null)
            {
                return(new GenericCommandResult(false, "Cliente não encontrado", null));
            }

            if (customer.Active == true && command.Active == false)
            {
                customer.MarkInactive();
            }
            if (!customer.IsValid)
            {
                return(new GenericCommandResult(false, "Ops! Operação não pode ser realizada. Cheque as informações retornadas.", customer.Notifications));
            }

            if (customer.Active == false && command.Active == true)
            {
                customer.MarkActive();
            }

            _repository.Update(customer);

            return(new GenericCommandResult(true, "Cliente atualizado com sucesso", customer));
        }
Exemplo n.º 11
0
        public void TestValidate_ValidCommand_NoValidationError(
            [Frozen] Mock <IRepository <Entities.Customer> > customerRepoMock,
            Entities.StoreCustomer customer,
            UpdateCustomerCommandValidator sut,
            UpdateCustomerCommand command
            )
        {
            //Arrange
            command.Customer.AccountNumber = "1";

            customerRepoMock.Setup(x => x.GetBySpecAsync(
                                       It.IsAny <GetCustomerSpecification>(),
                                       It.IsAny <CancellationToken>()
                                       ))
            .ReturnsAsync(customer);

            //Act
            var result = sut.TestValidate(command);

            //Assert
            result.ShouldNotHaveValidationErrorFor(command => command.Customer);
            result.ShouldNotHaveValidationErrorFor(command => command.Customer.AccountNumber);
        }
Exemplo n.º 12
0
        public async Task Should_Not_Update_Customer_When_Id_Is_Invalid_And_Return_NotFoundStatusCode()
        {
            //var client = await _factory.GetAuthenticatedClientAsync();

            var invalidCommand = new UpdateCustomerCommand
            {
                Id           = 0,
                Address      = "...",
                City         = "Berlin",
                CompanyName  = "Benz",
                ContactName  = "Test",
                ContactTitle = "Test",
                Country      = "Germany",
                Fax          = "32323232",
                Phone        = "333333",
                PostalCode   = "44444"
            };
            var content = E2ETestsUtilities.GetRequestContent(invalidCommand);

            var response = await _authenticatedClient.PutAsync($"/api/customers/update/{invalidCommand.Id}", content);

            response.StatusCode.ShouldBe(HttpStatusCode.NotFound);
        }
Exemplo n.º 13
0
        public void ShouldUpdateCustomerWhenCommandIsValid()
        {
            var ad = new AddAddressCommand("Rua dona mariinha", "96", "Casa 2", "Santo Antonio", "Viçosa", "MG", "Brasil"
                                           , "36570000", EAddressType.Shipping);
            var ad2 = new AddAddressCommand("Rua dona mariinha", "96", "Casa 2", "Santo Antonio", "Viçosa", "MG", "Brasil"
                                            , "36570000", EAddressType.Shipping);

            var address = new List <AddAddressCommand>();

            address.Add(ad);
            address.Add(ad2);

            var command = new UpdateCustomerCommand(Guid.NewGuid(), "Douglas", "Rocha", "09752725600", "*****@*****.**", "38914821", address);

            var handler = new CustomerHandlers(new FakeCustomerRepository(), new FakeEmailService());

            var result = handler.Handle(command);

            Console.WriteLine(result);

            Assert.AreNotEqual(false, result.Success);
            Assert.AreEqual(true, handler.IsValid);
        }
Exemplo n.º 14
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            UpdateCustomerCommand cust = new UpdateCustomerCommand
            {
                Id   = Customer.Id,
                Name = Customer.Name
            };

            var isUpdated = await _mediator.Send(cust);

            if (isUpdated)
            {
                return(RedirectToPage("./Index"));
            }
            else
            {
                return(Page());
            }
        }
 public void Handle(UpdateCustomerCommand command)
 {
     _CustomerService.Update(command.Customer);
     _CustomerService.Complete();
 }
Exemplo n.º 16
0
        public async Task <IActionResult> Update(string id, [FromBody] UpdateCustomerCommand command)
        {
            await _mediator.Send(command);

            return(NoContent());
        }
Exemplo n.º 17
0
        public void Update(CustomerViewModel CustomerViewModel)
        {
            UpdateCustomerCommand updateCustomerCommand = new UpdateCustomerCommand(_mapper.Map <Customer>(CustomerViewModel));

            QueueSender.Send(updateCustomerCommand);
        }
Exemplo n.º 18
0
 public EventList Handle(UpdateCustomerCommand cmd)
 {
     return(new EventList(new UpdateCustomerEvent(cmd.AggregateId, cmd.Name, cmd.Email)));
 }
Exemplo n.º 19
0
        public async Task <IHttpActionResult> Put(UpdateCustomerCommand command)
        {
            var response = await Bus.Send <UpdateCustomerCommand, UpdateCustomerCommandResponse>(command);

            return(Ok(response));
        }
Exemplo n.º 20
0
        public async Task <ActionResult> UpdateCustomer([FromBody] UpdateCustomerCommand command)
        {
            await _Mediator.Send(command);

            return(NoContent());
        }
Exemplo n.º 21
0
 public IActionResult Put([FromBody] UpdateCustomerCommand command)
 {
     _updateCustomerCommandHandler.Handle(command);
     return(Ok());
 }
        public async Task <ActionResult <UpdateCustomerCommandResponse> > Update([FromBody] UpdateCustomerCommand updateCustomerCommand)
        {
            var response = await _mediator.Send(updateCustomerCommand);

            return(Ok(response));
        }
Exemplo n.º 23
0
        public async Task <IActionResult> Put([FromBody] UpdateCustomerCommand command)
        {
            var result = await Mediator.Send(command);

            return(Ok(result));
        }
Exemplo n.º 24
0
        public ICommandResult PutCustomer([FromBody] UpdateCustomerCommand customer)
        {
            var result = _handle.Handle(customer);

            return(result);
        }
Exemplo n.º 25
0
    public async Task <IActionResult> Update([FromRoute] Guid customerId, [FromBody] UpdateCustomerRequest request)
    {
        var command = new UpdateCustomerCommand(customerId, request.Name);

        return(await Response(command));
    }
Exemplo n.º 26
0
        public async Task <ActionResult> UpdateCustomer(uint id, [FromBody] UpdateCustomerCommand updatedCustomer)
        {
            await _Mediator.Send(updatedCustomer);

            return(StatusCode(204));
        }
Exemplo n.º 27
0
        public async Task <IActionResult> UpdateCustomer([FromBody] Customer customer, [FromServices] UpdateCustomerCommand command)
        {
            if (customer == null)
            {
                throw new MissingRequestBodyException();
            }

            if (!TryValidateModel(customer))
            {
                return(new UnprocessableEntityResult());
            }

            await command.Execute(customer);

            return(Ok());
        }
Exemplo n.º 28
0
 /// <summary>
 /// Initializes a new instance of CustomerViewModel class.
 /// </summary>
 public CustomerViewModel()
 {
     this.Customer  = new Customer("David");
     childViewModel = new CustomerInfoViewModel();
     UpdateCommand  = new UpdateCustomerCommand(this);
 }
 public async Task <IActionResult> Update([FromBody] UpdateCustomerCommand updateCustomerCommand)
 => base.Ok(await mediator.Send <bool>(updateCustomerCommand));
Exemplo n.º 30
0
        public async Task <IActionResult> Update([FromBody] UpdateCustomerCommand command)
        {
            await Mediator.Send(request : command);

            return(NoContent());
        }