public async Task ItShouldReturnSuccess() { _uow.Setup(x => x.OrderItemTypeRepository.IsQuantityProductValid(It.IsAny <long>(), It.IsAny <int>())).ReturnsAsync(true); _uow.Setup(x => x.OrderRepository.Add(It.IsAny <Order>())).ReturnsAsync(OrderRepositoryFake.OrderValid()); _uow.Setup(x => x.ProductRepository.GetProductById(It.IsAny <long>())).ReturnsAsync(ProductRepositoryFake.GetById()); _uow.Setup(x => x.UserRepository.GetById(It.IsAny <long>())).ReturnsAsync(new User()); _orderService.Setup(x => x.AddOrder(It.IsAny <decimal>())).ReturnsAsync(OrderRepositoryFake.OrderValid()); AddOrderCommand command = new AddOrderCommand(); command.UserID = 1; command.OrderItems.Add(new OrderItemModel() { Description = "", OrderItemTypeID = 1, Products = { 1, 2 } }); var result = await _handler.Handle(command, CancellationToken.None); foreach (var item in result.Errors) { _output.WriteLine(item); } Assert.True(result.Success); }
public void Throw_ArgumentException_When_ProductCount_IsNegative() { // Arrange var fakeProductName = "testProduct"; var fakeProductCount = "-2"; var orderServiceStub = new Mock <IOrderService>(); var productServiceStub = new Mock <IProductService>(); var userSessionStub = new Mock <IUserSession>(); var dtoFactoryStub = new Mock <IDataTransferObjectFactory>(); var validatorStub = new Mock <IValidator>(); var writerStub = new Mock <IWriter>(); var readerStub = new Mock <IReader>(); var dateTimeStub = new Mock <DatetimeProvider>(); var productModelStub = new Mock <IProductModel>(); var addOrderCmd = new AddOrderCommand(orderServiceStub.Object, productServiceStub.Object, userSessionStub.Object, dtoFactoryStub.Object, validatorStub.Object, writerStub.Object, readerStub.Object, dateTimeStub.Object); productModelStub.SetupGet(pm => pm.Name) .Returns(fakeProductName); userSessionStub.Setup(us => us.HasSomeoneLogged()).Returns(true); readerStub.SetupSequence(r => r.Read()) .Returns(fakeProductName) .Returns(fakeProductCount); productServiceStub.Setup(ps => ps.FindProductByName(fakeProductName)).Returns(productModelStub.Object); Action executingAddOrderCmd = () => addOrderCmd.ExecuteThisCommand(); // Act & Assert Assert.ThrowsException <ArgumentException>(executingAddOrderCmd); }
public void ItShouldSuccess() { _uow.Setup(x => x.OrderItemTypeRepository.IsQuantityProductValid(It.IsAny <long>(), It.IsAny <int>())).ReturnsAsync(true); _uow.Setup(x => x.UserRepository.GetById(It.IsAny <long>())).ReturnsAsync(new User()); AddOrderCommand command = new AddOrderCommand(); command.UserID = 1; command.OrderItems.Add( new OrderItemModel() { Description = "", OrderItemTypeID = 2, Products = { 1 } } ); var result = _validator.Validate(command); foreach (var item in result.Errors) { _output.WriteLine(item.ErrorMessage); } Assert.True(result.IsValid); }
public void Create_order_fail() { //Arrange AddOrderCommand command = null; //Act - Assert Assert.Throws <ArgumentNullException>(() => Order.CreateNew(command)); }
public async Task <ActionResult <string> > CreateOrder(int userId, NewOrderViewModel order) { AddOrderCommand newOrder = new AddOrderCommand(userId, order.Products, order.Payment, order.contactMail); var result = await memoryBus.Send(newOrder); return(Ok(result)); }
public OrderViewModel(IOrderRepository orderRepository, IEmployeeRepository employeeRepository) { AddOrderCommand = new AddOrderCommand(this); DeleteOrderCommand = new DeleteOrderCommand(this, orderRepository); SaveOrdersCommand = new SaveOrdersCommand(this, orderRepository); RefreshOrdersCommand = new RefreshOrdersCommand(this, orderRepository, employeeRepository); RefreshOrdersCommand.Execute(null); }
public static Order CreateNew(AddOrderCommand newOrder) { if (newOrder == null) { throw new ArgumentNullException(nameof(newOrder)); } return(new Order(DateTime.UtcNow, newOrder.State)); }
/// <summary> /// Adds the order. /// </summary> /// <param name="addOrderCommand">The add order message.</param> /// <exception cref="ArgumentNullException">addOrderMessage</exception> public Task AddOrder(AddOrderCommand addOrderCommand) { if (addOrderCommand == null) { logger.LogError("No add order command provided"); throw new ArgumentNullException(nameof(addOrderCommand)); } return(AddOrderInternal(addOrderCommand)); }
public async Task <ActionResult <Guid> > AddOrder([FromBody] AddOrderCommand addOrderCommand) { _logger.LogInformation( "----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})", nameof(addOrderCommand), nameof(addOrderCommand.Description), addOrderCommand.Description, addOrderCommand); return(await _mediator.Send(addOrderCommand)); }
public async Task <IActionResult> Add([FromBody] AddOrderCommand command) { var response = await _mediator.Send(command); if (response.Errors.Any()) { return(BadRequest(response.Errors)); } return(Response(response)); }
public async Task <ActionResult <CommandResult <IdentifierResponse> > > Add([FromBody] AddOrderCommand command) { var result = await _mediator.Send(command); if (result.IsSuccess) { return(Ok(result.Payload)); } return(BadRequest(result.FailureReason)); }
private void lstUpgrades_MouseDown(object sender, MouseEventArgs e) { var item = lstUpgrades.GetItemAt(e.X, e.Y); if (item != null) { if (e.Button == MouseButtons.Left) { // how many to add? var amount = 1; if (ModifierKeys.HasFlag(Keys.Shift)) { amount *= 10; } if (ModifierKeys.HasFlag(Keys.Control)) { amount *= 100; } var upgrade = (FacilityUpgrade)item.Tag; for (int i = 0; i < amount; i++) { var order = new UpgradeFacilityOrder(upgrade); ConstructionQueue.Orders.Add(order); var cmd = new AddOrderCommand ( ConstructionQueue, order ); newCommands.Add(cmd); } BindQueueListView(); IEnumerable <FacilityTemplate> templates; if (chkOnlyLatest.Checked) { templates = Empire.Current.UnlockedItems.OfType <FacilityTemplate>().Where(f => f.Cost.Any()).OnlyLatestVersions(f => f.Family); } else { templates = Empire.Current.UnlockedItems.OfType <FacilityTemplate>().Where(f => f.Cost.Any()); } BindUpgradeListView(templates); } else if (e.Button == MouseButtons.Right) { var facil = (FacilityUpgrade)item.Tag; var report = new FacilityReport(facil); var form = report.CreatePopupForm(facil.New.Name); FindForm().ShowChildForm(form); } } }
public void Invoke_OrderService_MakeOrder_WithValid_OrderModel() { // Arrange var fakeProductName = "testProduct"; var fakeProductCount = "4"; var rejectMoreProducts = "n"; var mockOrderService = new Mock <IOrderService>(); var productServiceStub = new Mock <IProductService>(); var userSessionStub = new Mock <IUserSession>(); var dtoFactoryStub = new Mock <IDataTransferObjectFactory>(); var validatorStub = new Mock <IValidator>(); var writerStub = new Mock <IWriter>(); var readerStub = new Mock <IReader>(); var dateTimeStub = new Mock <DatetimeProvider>(); var productModelStub = new Mock <IProductModel>(); var orderModelStub = new Mock <IOrderMakeModel>(); var addOrderCmd = new AddOrderCommand(mockOrderService.Object, productServiceStub.Object, userSessionStub.Object, dtoFactoryStub.Object, validatorStub.Object, writerStub.Object, readerStub.Object, dateTimeStub.Object); productModelStub .SetupGet(pm => pm.Name) .Returns(fakeProductName); userSessionStub .Setup(us => us.HasSomeoneLogged()) .Returns(true); readerStub .SetupSequence(r => r.Read()) .Returns(fakeProductName) .Returns(fakeProductCount) .Returns(rejectMoreProducts); productServiceStub .Setup(ps => ps.FindProductByName(fakeProductName)) .Returns(productModelStub.Object); dtoFactoryStub .Setup(dtoFac => dtoFac.CreateOrderMakeModel(It.IsAny <IDictionary <string, int> >(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>())) .Returns(orderModelStub.Object); validatorStub .Setup(v => v.IsValid(orderModelStub.Object)) .Returns(true); // Act addOrderCmd.ExecuteThisCommand(); // Assert mockOrderService.Verify(os => os.MakeOrder(orderModelStub.Object), Times.Once); }
public void Create_order_success() { //Arrange var command = new AddOrderCommand { State = OrderState.Waiting }; //Act var order = Order.CreateNew(command); //Assert Assert.NotNull(order); }
public async Task <IActionResult> Add([FromBody] AddOrderCommand cmd) { Order order = new Order(); order.Create( Guid.NewGuid().ToString(), cmd.ServerName, cmd.Details.Select(o => new OrderDetail(o.ItemName, o.Quntity, o.Price)) ); await this._repository.SaveChanges(order); return(new OkObjectResult(order.Id)); }
public async Task <Response <bool> > Handle(AddOrderCommand request, CancellationToken cancellationToken) { var order = new Order { ProductId = request.ProductId, UserId = request.Userid, CreatedDate = DateTime.UtcNow, status = OrderStatusEnum.ADDED }; await orderRepo.AddAsync(order); return(Response.Ok()); }
public void ItShouldReturnErrorWhenQtdOrderIsLessOne() { AddOrderCommand command = new AddOrderCommand(); var result = _validator.Validate(command); foreach (var item in result.Errors) { _output.WriteLine(item.ErrorMessage); } Assert.False(result.IsValid); }
public async Task <string> CreateNewOrder(OrderInfo orderInfo) { validator.VerifyOrderInfo(orderInfo); var command = new AddOrderCommand( orderInfo.PairSymbols, orderInfo.Price, orderInfo.Amount, orderInfo.Exchange, orderInfo.Type); var id = await commandBus.SendAsync(command); var result = id.ToString(); return(result); }
public async Task AddOrderCommandHandle_AddsOrder() { //Arrange Shop seller = new Shop { Address = "aaaaa", Comments = null, CUI = "aaaaddd", IBAN = "aaaaa", Orders = null, PhoneNumber = "0123654789", ProductCategories = null, ShopCategoryLink = null, SocialCapital = 4 }; Customer buyer = new Customer(); AllMarktContextIM.Customers.Add(buyer); AllMarktContextIM.Shops.Add(seller); await AllMarktContextIM.SaveChangesAsync(); var addOrderCommand = new AddOrderCommand { ShopId = seller.Id, CustomerId = buyer.Id, DeliveryAddress = "Test Address", AWB = "Test AWB", OrderItems = new List <OrderItemViewModel>() { new OrderItemViewModel { Id = 1, Name = "Test Item", Amount = 1 } } }; //Act await _addOrderCommandHandler.Handle(addOrderCommand, CancellationToken.None); //Assert AllMarktContextIM.Orders .Should() .Contain(order => order.Seller.Id == addOrderCommand.ShopId && order.Buyer.Id == addOrderCommand.CustomerId && order.DeliveryAddress == addOrderCommand.DeliveryAddress && order.AWB == addOrderCommand.AWB); }
public async Task AddOrderCommand_ReturnsOkResponse(AddOrderCommand command) { var jsonContent = JsonConvert.SerializeObject(command); var contentString = new StringContent(jsonContent, Encoding.UTF8, "application/json"); var response = await Client.PostAsync(PathURL.ORDER_USER, contentString); var result = response.EnsureSuccessStatusCode(); response.StatusCode.Should().Be(HttpStatusCode.OK); var json = await response.Content.ReadAsStringAsync(); _output.WriteLine(json); }
private void lstShips_MouseDown(object sender, MouseEventArgs e) { var item = lstShips.GetItemAt(e.X, e.Y); if (item != null) { var design = (IDesign)item.Tag; if (e.Button == MouseButtons.Left) { // how many to add? var amount = 1; if (ModifierKeys.HasFlag(Keys.Shift)) { amount *= 10; } if (ModifierKeys.HasFlag(Keys.Control)) { amount *= 100; } // is this a new design we've never built before? then tell the server about it if (design.IsNew && !BuildingAnywhere(design)) { Empire.Current.Commands.Add(design.CreateCreationCommand()); } for (int i = 0; i < amount; i++) { // add to queue var order = design.CreateConstructionOrder(ConstructionQueue); ConstructionQueue.Orders.Add(order); var cmd = new AddOrderCommand ( ConstructionQueue, order ); newCommands.Add(cmd); } BindQueueListView(); } else if (e.Button == MouseButtons.Right) { // display detailed report var report = new DesignReport(design); this.ShowChildForm(report.CreatePopupForm(design.Name)); } } }
public bool AddOrder(AddOrderCommand newOrder) { using (var db = new SqlConnection(_connectionString)) { var sql = @"INSERT INTO [dbo].[Order] ([CustomerId] ,[Total] ,[CustomerPaymentTypeId]) VALUES (@customerId ,@total ,@customerPaymentTypeId)"; return(db.Execute(sql, newOrder) == 1); } }
public IActionResult CreateOrder(AddOrderCommand newOrderCommand) { var userRepo = new UserRepository(); var user = userRepo.GetByUid(FirebaseUserId); var newOrder = new Order { CustomerId = user.Id, Date = DateTime.Now, Total = newOrderCommand.Total, Status = newOrderCommand.Status }; var repo = new OrderRepository(); var orderToBeAdded = repo.CreateOrder(newOrder); return(Created($"api/Order/{orderToBeAdded.Id}", orderToBeAdded)); }
public void AddOrder_AddressDoesntExist_Exception(int _clientId) { var testSessionToken = SessionRepository.StartNewSession(_clientId); DatabaseQueryProcessor.Erase(); Shared.FillTheDatabase(); var testOrderEntry = new OrderEntryDto { key = 0, name = "Lavazza", quantity = 1, price = 15 }; var testOrderEntries = new OrderEntryDto[1]; testOrderEntries[0] = testOrderEntry; var testAddress = new AddressDto { key = 0, country = "Poland", city = "Gdansk", street = "Rzemieslnicza", ZIPCode = 30445, buildingNumber = 12, apartmentNumber = "1a" }; var addOrderCommand = new AddOrderCommand { sessionToken = testSessionToken, orderEntries = testOrderEntries, totalPrice = "15.00", address = testAddress }; var handler = new AddOrderCommandHandler(); TestDelegate result = () => handler.Handle(addOrderCommand); DatabaseQueryProcessor.Erase(); SessionRepository.RemoveSession(testSessionToken); Assert.Throws <Exception>(result); }
public void ItShouldReturnErrorWhenQtdOrderIsMoreTen() { AddOrderCommand command = new AddOrderCommand(); for (int i = 0; i < 10; i++) { command.OrderItems.Add(new OrderItemModel()); } var result = _validator.Validate(command); foreach (var item in result.Errors) { _output.WriteLine(item.ErrorMessage); } Assert.False(result.IsValid); }
public async Task <ActionResult> AddOrder([CustomizeValidator(Interceptor = typeof(API.Middleware.ValidatorInterceptor))] OrderViewModel order) { var loggedUserQuery = new LoggedUserQuery(); User user = await Mediator.Send(loggedUserQuery); var getClientQuery = new GetContactByNameQuery(order.ClientName); var client = await Mediator.Send(getClientQuery); if (client == null) { return(NotFound("Client not found.")); } var addOrderCommand = new AddOrderCommand(client, order.Type, order.Product, order.Amount, order.Price, order.Notes); await Mediator.Send(addOrderCommand); return(NoContent()); }
private void lstFacilities_MouseDown(object sender, MouseEventArgs e) { var item = lstFacilities.GetItemAt(e.X, e.Y); if (item != null) { if (e.Button == MouseButtons.Left) { // how many to add? var amount = 1; if (ModifierKeys.HasFlag(Keys.Shift)) { amount *= 10; } if (ModifierKeys.HasFlag(Keys.Control)) { amount *= 100; } var template = (FacilityTemplate)item.Tag; for (int i = 0; i < amount; i++) { var order = new ConstructionOrder <Facility, FacilityTemplate> { Template = template }; ConstructionQueue.Orders.Add(order); var cmd = new AddOrderCommand ( ConstructionQueue, order ); newCommands.Add(cmd); } BindQueueListView(); } else if (e.Button == MouseButtons.Right) { var facil = (FacilityTemplate)item.Tag; var report = new FacilityReport(facil); var form = report.CreatePopupForm(facil.Name); FindForm().ShowChildForm(form); } } }
public async Task <Response <OrderVm> > Handle(AddOrderCommand request, CancellationToken cancellationToken) { var order = new CreateOrder { Products = request.Products.Select(p => new ProductOrder { ProductId = p.ProductId, Price = p.Price, Quantity = p.Quantity }).ToList(), UserId = request.UserId }; var newOrder = await _orderService.CreateOrder(order); if (newOrder == default) { return(Response.Fail500ServiceError <OrderVm>("Order Service Fail")); } return(Response.Ok200(new OrderVm { OrderId = newOrder, ProductOrders = request.Products, UserId = request.UserId })); }
public void Serialize_AddOrderMessage() { var addOrder = new AddOrderCommand("0000000000000000000000000000000000000000", OrderType.Limit, Side.Buy, "XBT/USD", 10) { RequestId = 123, Price = 123.5M, Price2 = 125M, Leverage = 123.456M, Oflags = "viqc,fcib", Starttm = "+100", Expiretm = "+150", Userref = "123456", Validate = "true", CloseOrderType = OrderType.Market, ClosePrice = 123.5M, ClosePrice2 = 125M, TradingAgreement = "agree" }; var addOrderString = instance.Serialize(addOrder); Assert.Contains(@"""event"":""addOrder""", addOrderString); Assert.Contains(@"""token"":""0000000000000000000000000000000000000000""", addOrderString); Assert.Contains(@"""reqid"":123", addOrderString); Assert.Contains(@"""ordertype"":""limit""", addOrderString); Assert.Contains(@"""type"":""buy""", addOrderString); Assert.Contains(@"""pair"":""XBT/USD""", addOrderString); Assert.Contains(@"""price"":""123.5""", addOrderString); Assert.Contains(@"""price2"":""125""", addOrderString); Assert.Contains(@"""volume"":""10""", addOrderString); Assert.Contains(@"""leverage"":""123.456""", addOrderString); Assert.Contains(@"""oflags"":""viqc,fcib""", addOrderString); Assert.Contains(@"""starttm"":""+100""", addOrderString); Assert.Contains(@"""expiretm"":""+150""", addOrderString); Assert.Contains(@"""userref"":""123456""", addOrderString); Assert.Contains(@"""validate"":""true""", addOrderString); Assert.Contains(@"""close[ordertype]"":""market""", addOrderString); Assert.Contains(@"""close[price]"":""123.5""", addOrderString); Assert.Contains(@"""close[price2]"":""125""", addOrderString); Assert.Contains(@"""trading_agreement"":""agree""", addOrderString); }
public void Throw_ArgumentException_When_OrderModel_IsInvalid() { // Arrange var fakeProductName = "testProduct"; var fakeProductCount = "4"; var rejectMoreProducts = "n"; var productModelStub = new Mock <IProductModel>(); var orderModelStub = new Mock <IOrderMakeModel>(); var orderServiceStub = new Mock <IOrderService>(); var productServiceStub = new Mock <IProductService>(); var userSessionStub = new Mock <IUserSession>(); var dtoFactoryStub = new Mock <IDataTransferObjectFactory>(); var validatorStub = new Mock <IValidator>(); var writerStub = new Mock <IWriter>(); var readerStub = new Mock <IReader>(); var dateTimeStub = new Mock <DatetimeProvider>(); var addOrderCmd = new AddOrderCommand(orderServiceStub.Object, productServiceStub.Object, userSessionStub.Object, dtoFactoryStub.Object, validatorStub.Object, writerStub.Object, readerStub.Object, dateTimeStub.Object); productModelStub.SetupGet(pm => pm.Name) .Returns(fakeProductName); userSessionStub.Setup(us => us.HasSomeoneLogged()).Returns(true); readerStub.SetupSequence(r => r.Read()) .Returns(fakeProductName) .Returns(fakeProductCount) .Returns(rejectMoreProducts); productServiceStub.Setup(ps => ps.FindProductByName(fakeProductName)).Returns(productModelStub.Object); dtoFactoryStub.Setup(dtoFac => dtoFac.CreateOrderMakeModel(It.IsAny <IDictionary <string, int> >(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <DateTime>())).Returns(orderModelStub.Object); validatorStub.Setup(v => v.IsValid(orderModelStub.Object)).Returns(false); Action executingAddOrderCmd = () => addOrderCmd.ExecuteThisCommand(); // Act & Assert Assert.ThrowsException <ArgumentException>(executingAddOrderCmd); }
public void TestAddOrderUsingService() { Order order1 = new Order(); Order order2 = new Order(); Order order3 = new Order(); AddOrderCommand addCommand1 = new AddOrderCommand(order1); AddOrderCommand addCommand2 = new AddOrderCommand(order2); AddOrderCommand addCommand3 = new AddOrderCommand(order3); CommanndServiceReference.CommandServiceClient service = new OrderProcessing.Tests.CommanndServiceReference.CommandServiceClient(); AssignContextId(service.InnerChannel); addCommand1 = (AddOrderCommand)service.ExecuteCommand(addCommand1); addCommand2 = (AddOrderCommand)service.ExecuteCommand(addCommand2); addCommand3 = (AddOrderCommand)service.ExecuteCommand(addCommand3); ICommand command = (ICommand)service.Undo(); Order deletedOrder = command.CommandParams[0] as Order; Assert.That(((Order)addCommand3.CommandParams[0]).OrderId, Is.EqualTo(deletedOrder.OrderId)); }
public void TestAddOrder() { Order order1 = new Order(); Order order2 = new Order(); Order order3 = new Order(); AddOrderCommand addCommand1 = new AddOrderCommand(order1); AddOrderCommand addCommand2 = new AddOrderCommand(order2); AddOrderCommand addCommand3 = new AddOrderCommand(order3); CommandService service = new CommandService(); service.ExecuteCommand(addCommand1); service.ExecuteCommand(addCommand2); service.ExecuteCommand(addCommand3); ICommand command = service.Undo(); Order deletedOrder = command.CommandParams[0] as Order; Assert.That(order3.OrderId,Is.EqualTo(deletedOrder.OrderId)); Repositiory.Close(Common.Util.GetContextId()); }