Esempio n. 1
0
        public async Task GivenValidCreateCustomerCommand_ReturnsValidCustomerViewModel()
        {
            // Arrange
            var command = new CreateCustomerCommand
            {
                FirstName  = "Leonardo",
                MiddleName = "Da",
                LastName   = "Vinci",
                Amount     = "104.58"
            };

            var content = Utilities.GetRequestContent(command);

            // Act
            var response = await _client.PostAsync($"{Utilities.AKQAApiURL}/api/customer/process", content);

            // Assert
            response.EnsureSuccessStatusCode();

            var vm = await Utilities.GetResponseContent <CustomerViewModel>(response);

            Assert.NotNull(vm);
            Assert.IsType <CustomerViewModel>(vm);
            Assert.NotEmpty(vm.FullName);
            Assert.NotEmpty(vm.FormattedAmount);
        }
Esempio n. 2
0
        public async Task CreateCustomer_When_request_is_not_authenticated_It_should_return_statuscode_Unauthorized()
        {
            // Arrange
            var client = Factory
                         .WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    var serviceDescriptor = services
                                            .Where(x => x.ServiceType == typeof(IAuthorizationHandler))
                                            .Where(x => x.ImplementationType == typeof(AllowUnauthorizedAuthorizationHandler))
                                            .Single();
                    services.Remove(serviceDescriptor);
                });
            })
                         .CreateClient();
            var command = new CreateCustomerCommand
            {
                Name = "Test"
            };

            // Act
            var response = await client.CustomersController().CreateAsync(command);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.Unauthorized);
        }
        public CustomersController(
            ICustomerRepository sqLiteRepository,
            IDBCustomerRepository <CustomerObject> mongoRepository,
            ICommandHandler <Command> commandHandler
            )
        {
            _commandHandler   = commandHandler;
            _sqLiteRepository = sqLiteRepository;
            _mongoRepository  = mongoRepository;

            if (_mongoRepository.GetCustomers().Count == 0)
            {
                var customerCmd = new CreateCustomerCommand
                {
                    Name   = "Prénom NOM",
                    Email  = "prenomnom.com",
                    Age    = 23,
                    Phones = new List <CreatePhoneCommand>
                    {
                        new CreatePhoneCommand {
                            Type = PhoneType.CELLPHONE, AreaCode = 123, Number = 7543010
                        }
                    }
                };
                _commandHandler.Execute(customerCmd);
            }
        }
Esempio n. 4
0
        public async Task Handle_ValidCommand_CustomerRepositoryCalled()
        {
            // Arrange
            var customerId = Guid.Parse("B83806BA-41D7-4412-B20A-3E65518C970A");
            var command    = new CreateCustomerCommand
            {
                Name = "John Doe",
                Age  = 30
            };

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

            this.repositoryMock
            .Setup(r => r.CreateCustomerAsync(
                       It.Is <Customer>(c => c.Name == command.Name && c.Age == command.Age)))
            .ReturnsAsync(customerId);

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

            // Assert
            result.Should().Be(customerId);
            this.identityServiceMock.VerifyAll();
            this.repositoryMock.VerifyAll();
        }
Esempio n. 5
0
        public async Task CreateCustomer_When_a_domainentity_hook_throws_a_DomainException_It_should_return_statuscode_BadRequest()
        {
            var client = Factory
                         .WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    var mock = new Mock <IAfterCreate <Customer> >();
                    mock.Setup(x => x.ExecuteAsync(It.IsAny <HookType>(), It.IsAny <IDomainEntityContext <Customer> >(), It.IsAny <CancellationToken>()))
                    .Throws(new DomainException("TestMessage"));

                    services.AddSingleton(mock.Object);
                });
            })
                         .CreateClient();

            var command = new CreateCustomerCommand
            {
                Name = "Test"
            };

            // Act
            var response = await client.CustomersController().CreateAsync(command);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);

            var content = await response.Content.ReadFromJsonAsync <ValidationProblemDetails>();

            content.Should().NotBeNull();
            content !.Type.Should().Be(nameof(DomainException));
            content !.Title.Should().Be("TestMessage");
        }
Esempio n. 6
0
        public async Task ShouldThrowEmptyShoppingVanException()
        {
            // Arrange
            var accountId = await RunAsDefaultUserAsync();

            var createCustomerCommand = new CreateCustomerCommand
            {
                AccountId     = accountId,
                ShopName      = "Test Shop Name",
                ShopAddress   = "Test Shop address",
                LocationOnMap = "Test LocationOnMap"
            };

            await SendAsync(createCustomerCommand);

            // Act

            // Place Order Command
            var placeOrderCommand = new PlaceOrderCommand();

            // Assert

            // Shipp Order Command
            FluentActions.Invoking(() => SendAsync(placeOrderCommand)).Should().Throw <EmptyShoppingVanException>();
        }
Esempio n. 7
0
        public async Task <IActionResult> Post([FromBody] CreateCustomerCommand command)
        {
            var user   = User;
            var result = await Mediator.Send(command);

            return(Ok(result));
        }
Esempio n. 8
0
        public async Task Handle_GivenValidRequest_ShouldReturnCustomerId()
        {
            // Arrange
            var command = new CreateCustomerCommand
            {
                FirstName   = "John",
                LastName    = "Doe",
                Gender      = "Male",
                PhoneNumber = "0885359164",
                Status      = "Active",
            };
            var sut = new CreateCustomerCommandHandler(this.deletableEntityRepository);

            // Act
            var id = await sut.Handle(command, It.IsAny <CancellationToken>());

            // Assert
            var customer = await this.dbContext.Customers.SingleOrDefaultAsync(x => x.Id == id);

            customer.ShouldNotBeNull();
            customer.FirstName.ShouldBe("John");
            customer.LastName.ShouldBe("Doe");
            customer.Gender.ShouldBe("Male");
            customer.PhoneNumber.ShouldBe("0885359164");
            customer.Status.ShouldBe("Active");
        }
Esempio n. 9
0
        public async Task <ICommandResult> Handle(CreateCustomerCommand command)
        {
            var isEmailInUse = _repository.IsEmailInUse(command.Email);

            var name     = new Name(command.FirstName, command.LastName);
            var email    = new Email(command.Email);
            var customer = new Customer(name, email);

            AddNotifications(name.Notifications);
            AddNotifications(email.Notifications);
            AddNotifications(customer.Notifications);

            if (await isEmailInUse)
            {
                AddNotification(nameof(command.Email), "This email is already in use.");
            }

            if (!IsValid)
            {
                return(CreateGenericErrorCommandResult());
            }

            int customerId = await _repository.Create(customer);

            return(new SuccessCommandResult("Customer created.", customerId));
        }
Esempio n. 10
0
        public async Task <IActionResult> Post(CreateCustomerCommand customer)
        {
            //var context = GetContext(customer.Id);
            await _mediator.Send(customer);

            return(Accepted());
        }
Esempio n. 11
0
        public async Task <IActionResult> Post(CreateCustomerCommand command)
        {
            var context = GetContext();
            await _busPublisher.SendAsync(command, context);

            return(Accepted());
        }
Esempio n. 12
0
    public async Task <Result <Unit> > Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
    {
        var customerDto = request.CustomerToCreateDto;

        bool customerExists = await _context.Customers.AnyAsync(c => c.PhoneNumber == customerDto.PhoneNumber ||
                                                                c.Identification == customerDto.Identification);

        if (customerExists == true)
        {
            return(Result <Unit> .Failure("This Phone Number or Identification has been used already."));
        }

        var customer = _mapper.Map <Customer>(customerDto);

        customer.Identification = customer.Identification.ToLower();

        _context.Customers.Add(customer);

        if (await _context.SaveChangesAsync() > 0)
        {
            return(Result <Unit> .CreatedAtRoute(Unit.Value, "GetCustomer"));
        }

        return(Result <Unit> .Failure("Unknown error."));
    }
        public async Task <ActionResult <GenericCommandResult> > Create(
            [FromBody] CreateCustomerCommand command,
            [FromServices] CustomerHandler handler,
            [FromServices] UserHandler userHandler
            )
        {
            var validationResult = command.Validate();

            if (!validationResult.Success)
            {
                return(BadRequest(validationResult));
            }

            var userResult = (GenericCommandResult)userHandler.Handle(new CreateUserCommand(command.Email, command.Password, "customer"));

            if (userResult.Success)
            {
                var user = (User)userResult.Data;
                command.SetUserId(user.Id);


                var result = handler.Handle(command);
                return(Ok(result));
            }

            return(BadRequest(userResult));
        }
        public async void Handle_GivenCustomerWithInSufficientBalance_ShouldThrowBadRequest()
        {
            // Arrange

            // Create Customer
            var customerCreation          = new CreateCustomerCommandHandler(_customerLogger, _mapper, _customerRepository);
            var newCustomerCommandRequest = new CreateCustomerCommand {
                Email = "*****@*****.**", MonthlyIncome = 2000, MonthlyExpense = 1200
            };
            var customerCreationResult = await customerCreation.Handle(newCustomerCommandRequest, CancellationToken.None);

            var newAccountCommandRequest = new CreateAccountCommand {
                Email = customerCreationResult.Email, customerId = customerCreationResult.Id
            };

            // Act
            var accountCreationSUT = new CreateAccountCommandHandler(_accountLogger, _mapper, _accountRepository, _customerRepository);

            var accountCreationExceptionResult = await Assert.ThrowsAsync <BadRequestException>(async() => await accountCreationSUT.Handle(newAccountCommandRequest, CancellationToken.None));

            var accountFromDb = _accountRepository.GetAccountByEmail(customerCreationResult.Email);

            // Assert
            Assert.Null(accountFromDb);
        }
Esempio n. 15
0
        public async void Handle_GivenValidCustomer_ShouldCreateCustomer()
        {
            // Arrange

            var sut = new CreateCustomerCommandHandler(_logger, _mapper, _customerRepository);

            var newCustomerCommandRequest = new CreateCustomerCommand {
                Email = "*****@*****.**", MonthlyIncome = 20000, MonthlyExpense = 200
            };

            // Act
            var result = await sut.Handle(newCustomerCommandRequest, CancellationToken.None);

            var customerFromDb = _customerDbContext.Customers.Find(result.Id);

            // Assert
            Assert.NotNull(result);
            Assert.IsType <Guid>(result.Id);
            Assert.Equal(newCustomerCommandRequest.Email, result.Email);
            Assert.Equal(newCustomerCommandRequest.MonthlyExpense, result.MonthlyExpense);
            Assert.Equal(newCustomerCommandRequest.MonthlyIncome, result.MonthlyIncome);

            Assert.NotNull(customerFromDb);
            Assert.Equal(result.Id, customerFromDb.Id);
            Assert.Equal(newCustomerCommandRequest.Email, customerFromDb.Email);
            Assert.Equal(newCustomerCommandRequest.MonthlyExpense, customerFromDb.MonthlyExpense);
            Assert.Equal(newCustomerCommandRequest.MonthlyIncome, customerFromDb.MonthlyIncome);
        }
        public ICommandResult Post([FromBody] CreateCustomerCommand command)
        {
            // var result = (CreateCustomerCommandResult)_handler.Handler(command);
            var result = _handler.Handler(command);

            return(result);
        }
Esempio n. 17
0
 public CustomersController(ICommandHandler <Command> commandHandler,
                            CustomerSQLiteRepository sqliteRepository,
                            CustomerMongoRepository repository,
                            CustomerMessageListener listener)
 {
     _commandHandler   = commandHandler;
     _sqliteRepository = sqliteRepository;
     _mongoRepository  = repository;
     if (_mongoRepository.GetCustomers().Count == 0)
     {
         var customerCmd = new CreateCustomerCommand
         {
             Name   = "George Michaels",
             Email  = "*****@*****.**",
             Age    = 23,
             Phones = new List <CreatePhoneCommand>
             {
                 new CreatePhoneCommand {
                     Type = PhoneType.CELLPHONE, AreaCode = 123, Number = 7543010
                 }
             }
         };
         _commandHandler.Execute(customerCmd);
     }
 }
        public async Task <CommandResult <CreateCustomerCommandResponse> > Handle(CreateCustomerCommand request, CancellationToken cancellationToken)
        {
            request.Validate();

            if (!request.Valid)
            {
                if (request.Notifications.Any())
                {
                    return(CommandResult <CreateCustomerCommandResponse> .Failed(HttpStatusCode.PreconditionFailed, "Pre condition failed", request.Notifications));
                }
            }

            var entityCreated = new CustomerEntity();

            entityCreated.New(request.Name, request.LastName, request.Email);
            await _customerRepository.CreateAsync(entityCreated);

            return(CommandResult <CreateCustomerCommandResponse> .Succeeded(new CreateCustomerCommandResponse()
            {
                Id = entityCreated.Id.ToString(),
                Name = entityCreated.Name,
                LastName = entityCreated.LastName,
                Email = entityCreated.Email
            }, HttpStatusCode.Created));
        }
Esempio n. 19
0
        public async Task CreateOrderAsync()
        {
            var order = new CreateOrderCommand
            {
                Id         = Guid.NewGuid(),
                CustomerId = Guid.NewGuid(),
                ItemsCount = 0,
                Total      = 0,
                Vat        = 0,
                Status     = 1
            };

            var customer = new CreateCustomerCommand()
            {
                Id          = order.CustomerId,
                Email       = $"{order.CustomerId}@test.com",
                CreatedDate = DateTime.Now,
                FullName    = $"{order.CustomerId}",
                Phone       = "+380631472589"
            };

            await messageSession.Send(customer);

            Thread.Sleep(2000);

            await messageSession.Send(order);

            orderPersistence.Add(order.Id);
        }
Esempio n. 20
0
 //noteToSelf = FromForm means from the bloody form not [FromBody]
 public async Task <IActionResult> NewCustomer([FromForm] CreateCustomerCommand command)
 {
     //sets the accountCreation before it is populated at database level
     command.AccountCreated = DateTime.Now;
     Ok(await Mediator.Send(command));
     return(RedirectToAction("ViewCustomers"));
 }
Esempio n. 21
0
        public CreateCustomerCommandTests()
        {
            _dapperService = A.Fake <DapperService>();

            _createCustomerCommand =
                new CreateCustomerCommand(A.Fake <IOptions <ApplicationConfiguration> >(), _dapperService);
        }
        public void Deve_retornar_falso_ao_criar_um_createCutomerCAT_com_dados_invalidos()
        {
            var createCustomerCommand = new CreateCustomerCommand("1", "222", "11", Guid.NewGuid());

            createCustomerCommand.Validate();
            Assert.AreEqual(false, createCustomerCommand.IsValid);
        }
Esempio n. 23
0
        public async Task CreateCustomer_When_a_command_validator_throws_a_ValidationException_It_should_return_statuscode_BadRequest()
        {
            // Arrange
            //var client = _factory
            //    .WithWebHostBuilder(builder =>
            //    {
            //        builder.ConfigureTestServices(services =>
            //        {
            //            var mock = new Mock<IValidator<CreateCustomerCommand>>();
            //            mock.Setup(x => x.Validate(It.IsAny<CreateCustomerCommand>())).Throws(new ValidationException("'Name' must not be empty"));

            //            services.AddSingleton(mock.Object);
            //        });
            //    })
            //    .CreateClient();

            var command = new CreateCustomerCommand
            {
                Name = string.Empty
            };

            // Act
            var response = await Client.CustomersController().CreateAsync(command);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.BadRequest);

            var content = await response.Content.ReadFromJsonAsync <ValidationProblemDetails>();

            content.Should().NotBeNull();
            content !.Type.Should().Be(nameof(ValidationException));
            content !.Detail.Should().Contain("'Name' must not be empty");
        }
        public void Deve_retornar_falso_ao_criar_um_createCutomerCAT_com_id_CAT_invalido()
        {
            var createCustomerCommand = new CreateCustomerCommand("Empresa Teste", "Empresa Teste", "30560346000105", Guid.Empty);

            createCustomerCommand.Validate();
            Assert.AreEqual(false, createCustomerCommand.IsValid);
        }
Esempio n. 25
0
        public async Task CreateCustomer_When_an_unhandled_exception_occurs_It_should_return_statuscode_InternalServerError()
        {
            // Arrange
            var client = Factory
                         .WithWebHostBuilder(builder =>
            {
                builder.ConfigureTestServices(services =>
                {
                    var mock = new Mock <ICustomerDomainEntity>();
                    mock.Setup(x => x.CreateAsync(It.IsAny <CancellationToken>()))
                    .Throws(new ArgumentException("TestException"));

                    services.AddSingleton(mock.Object);
                });
            })
                         .CreateClient();

            var command = new CreateCustomerCommand
            {
                Name = "Test"
            };

            // Act
            var response = await client.CustomersController().CreateAsync(command);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.InternalServerError);

            var content = await response.Content.ReadFromJsonAsync <ValidationProblemDetails>();

            content.Should().NotBeNull();
            content !.Type.Should().Be(nameof(ArgumentException));
            content !.Title.Should().Be("TestException");
        }
Esempio n. 26
0
        public async Task <IActionResult> AddCustomer([FromBody] CustomerDto customer, CancellationToken cancellationToken)
        {
            var command = new CreateCustomerCommand
            {
                FirstName    = customer.FirstName,
                LastName     = customer.LastName,
                EmailAddress = customer.EmailAddress
            };

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            await _commands.Execute(command, cancellationToken).ConfigureAwait(false);

            if (command.CreatedEntity == null)
            {
                return(BadRequest());
            }

            var contract = new CustomerDto
            {
                Id           = command.CreatedEntity.Id,
                FirstName    = command.CreatedEntity.FirstName,
                LastName     = command.CreatedEntity.LastName,
                EmailAddress = command.CreatedEntity.EmailAddress
            };

            return(CreatedAtAction(
                       "GetCustomer",
                       new { id = command.CreatedEntity.Id },
                       contract));
        }
Esempio n. 27
0
        public async Task CreateCustomer_When_a_customer_is_created_It_should_publish_a_CustomerCreated_event()
        {
            // Arrange
            var command = new CreateCustomerCommand
            {
                Name = "Test"
            };

            var idFromEvent = Guid.Empty;

            using var subscription = HubConnection.On(nameof(ICustomerEventHub.CustomerCreated), (Guid id, string _) =>
            {
                idFromEvent = id;
            });

            // Act
            var response = await Client.CustomersController().CreateAsync(command);

            // Assert
            response.StatusCode.Should().Be(HttpStatusCode.Created);

            var content = await response.Content.ReadFromJsonAsync <CreateCustomerResponse>();

            content.Should().NotBeNull();
            content !.Id.Should().NotBeEmpty();

            WithRetry(() => idFromEvent.Should().Be(content.Id), 1.Seconds(), 10.Milliseconds(), $"Didnt receive {nameof(ICustomerEventHub.CustomerCreated)} event for created entity");
        }
        public async Task <IResult <Guid> > CreateCustomer(CreateCustomerCommand createCommand)
        {
            if (createCommand == null)
            {
                return(await Result <Guid> .FailAsync("customer fields"));
            }

            var validator = createCommand.Validate();

            if (!validator.IsValid)
            {
                return(await Result <Guid> .FailValidationAsync(validator.Errors));
            }

            var customer = await _service.GetCustomerByEmail(createCommand.Email);

            if (customer != null)
            {
                return(await Result <Guid> .FailAsync("customer already exists"));
            }

            var id = await _service.CreateCustomer(createCommand);

            if (id == Guid.Empty)
            {
                return(await Result <Guid> .FailAsync("unable to create customer"));
            }

            return(await Result <Guid> .CreatedAsync(id));
        }
Esempio n. 29
0
        public async Task <IActionResult> CreateCustomer(CustomerDto customerDto)
        {
            var request  = new CreateCustomerCommand(customerDto);
            var response = await _mediator.Send(request);

            return(RedirectToAction(nameof(Index)));
        }
        public async Task ShouldCreateTodoItem()
        {
            var userId = await RunAsDefaultUserAsync();

            var listId = await SendAsync(new CreateTodoListCommand
            {
                Title = "New List"
            });

            var command = new CreateCustomerCommand
            {
                ListId = listId,
                Title  = "Tasks"
            };

            var itemId = await SendAsync(command);

            var item = await FindAsync <TodoItem>(itemId);

            item.Should().NotBeNull();
            item.ListId.Should().Be(command.ListId);
            item.Title.Should().Be(command.Title);
            item.CreatedBy.Should().Be(userId);
            item.Created.Should().BeCloseTo(DateTime.Now, 10000);
            item.LastModifiedBy.Should().BeNull();
            item.LastModified.Should().BeNull();
        }