public async Task <IActionResult> CreateOrderAsync( [FromBody] CreateOrderCommand createOrderCommand, [FromHeader(Name = "x-request-id")] string requestId, [FromHeader(Name = "jwt-extracted-sub")] string customerId) { _logger.LogInformation("CreateOrderAsync: {requestId}", requestId); var hasRequestGuid = Guid.TryParse(requestId, out Guid requestIdGuid) && requestIdGuid != Guid.Empty; if (!hasRequestGuid) { return(BadRequest()); } var hasCustomerGuid = Guid.TryParse(customerId, out Guid customerIdGuid) && customerIdGuid != Guid.Empty; if (!hasCustomerGuid) { return(BadRequest()); } createOrderCommand.OrderId = requestIdGuid; createOrderCommand.CustomerId = customerIdGuid; var requestCreateOrder = new IdempotentCommand <CreateOrderCommand, bool>(createOrderCommand, requestIdGuid); var result = await _mediator.Send(requestCreateOrder); if (!result) { return(BadRequest()); } return(Ok(new { OrderId = requestCreateOrder.Command.OrderId })); }
private async void handleCreateOrderCommand(CreateOrderCommand createOrderCommand) { OrderCreatedEvent orderCreatedEvent = Order.processCreateOrderCommand(createOrderCommand); #if (!DEBUG) try { await _orderRepository.InsertOneAsync(orderCreatedEvent.order); } catch (Exception ex) { Console.WriteLine($"Error occured with MongoDB: {ex}"); } #endif orderCreatedEvent.getEvents().ForEach(e => { if (e.eventType == EventType.BEVERAGE_ORDER_IN) { sendBaristaOrder(e); } else if (e.eventType == EventType.KITCHEN_ORDER_IN) { sendKitchenOrder(e); } }); }
public async Task <bool> TryHandleAsync(UserCheckoutAcceptedIntegrationEvent @event) { var result = false; // Send Integration event to clean basket once basket is converted to Order and before starting with the order creation process var orderStartedIntegrationEvent = new OrderStartedIntegrationEvent(@event.UserId); _orderingIntegrationEventService.PublishThroughEventBus(orderStartedIntegrationEvent); if (@event.RequestId != Guid.Empty) { var createOrderCommand = new CreateOrderCommand(@event.Basket.Items, @event.UserId, @event.UserName, @event.City, @event.Street, @event.State, @event.Country, @event.ZipCode, @event.CardNumber, @event.CardHolderName, @event.CardExpiration, @event.CardSecurityNumber, @event.CardTypeId); var requestCreateOrder = new IdentifiedCommand <CreateOrderCommand, bool>(createOrderCommand, @event.RequestId); try { result = await _mediator.Send(requestCreateOrder); } catch (Exception ex) { _logger.LogCritical(ex.ToString()); } } _logger.LogInformation(result ? $"UserCheckoutAccepted integration event has been received and a create new order process is started with requestId: {@event.RequestId}" : $"UserCheckoutAccepted integration event has been received but a new order process has failed with requestId: {@event.RequestId}"); return(true); }
private async Task ReserveItemsAsync(string transactionId, CreateOrderCommand command, CancellationToken cancellationToken) { await PerformTransactionStepAsync( transactionId, t => t.InventoryReservationStepDetails, async ct => { try { var reservationsRequest = ReservationsMapper.ToReservationsApiContract(command.Order); await reservationsApiClient.ReserveItemsAsync(transactionId, reservationsRequest, ct).ConfigureAwait(false); return(StepResult.Successful); } catch (SwaggerException <InventoryAPI.ApiClient.ValidationProblemDetails> ) { // Permanent error. Can set step state to rolled back since if a validation error occurs, then no // change has occured in the inventory API so there is nothing to roll back. return(StepResult.Abort); } }, cancellationToken) .ConfigureAwait(false); }
public static async Task CreateOrder([ActivityTrigger] CreateOrderCommand command, ILogger logger) { logger.LogWarning("Creating order"); // Simulate a hard work ordering the item await Task.Delay(100); }
private async Task Fill(Guid orderId, CreateOrderCommand createOrderCommand, KeyValuePair <string, ICommandQueueClient> orderServiceCqc) { var price = RandomDecimal(0.1M, 3.25M); if (!FillPartial()) { var fillOrderCommand = new FillOrderCommand(orderId, Guid.NewGuid(), createOrderCommand.Quantity, price); await DispatchCommand(fillOrderCommand, orderServiceCqc); System.Console.WriteLine($"Sent FillOrderCommand (0%->100%), OrderId=[{orderId}]"); System.Console.ReadKey(); return; } var fillOrderCommand1 = new FillOrderCommand(orderId, Guid.NewGuid(), createOrderCommand.Quantity / 2, price); await DispatchCommand(fillOrderCommand1, orderServiceCqc); System.Console.WriteLine($"Sent FillOrderCommand (0%->50%), OrderId=[{orderId}]"); System.Console.ReadKey(); var fillOrderCommand2 = new FillOrderCommand(orderId, Guid.NewGuid(), createOrderCommand.Quantity - fillOrderCommand1.Quantity, price); await DispatchCommand(fillOrderCommand2, orderServiceCqc); System.Console.WriteLine($"Sent FillOrderCommand (50%->100%), OrderId=[{orderId}]"); System.Console.ReadKey(); }
public async Task Consume(ConsumeContext <UserCheckoutAcceptedIntegrationEvent> context) { IExecutionResult result = ExecutionResult.Failed(); var orderId = OrderId.New; // Send Integration event to clean basket once basket is converted to Order and before starting with the order creation process var orderItems = from orderItem in context.Message.Basket.Items select new OrderStockItem(int.Parse(orderItem.ProductId), orderItem.Quantity); if (context.Message.RequestId != Guid.Empty) { var createOrderCommand = new CreateOrderCommand(orderId, new SourceId(context.Message.RequestId.ToString()), context.Message.Basket.Items, context.Message.UserId, context.Message.UserName, context.Message.City, context.Message.Street, context.Message.State, context.Message.Country, context.Message.ZipCode, context.Message.CardNumber, context.Message.CardHolderName, context.Message.CardExpiration, context.Message.CardSecurityNumber, context.Message.CardTypeId); result = await _commandBus.PublishAsync(createOrderCommand, CancellationToken.None).ConfigureAwait(false); if (result.IsSuccess) { var orderStartedIntegrationEvent = new OrderStartedIntegrationEvent(context.Message.UserId, orderId.Value, orderItems.ToList(), context.Message.RequestId); await _endpoint.Publish(orderStartedIntegrationEvent); } } }
public Order Create(CreateOrderCommand command, string email) { var user = _userRepository.GetByEmail(email); var orderItems = new List <OrderItem>(); foreach (var item in command.OrderItems) { var orderItem = new OrderItem(); var product = _productRepository.Get(item.Product); orderItem.AddProduct(product, item.Quantity, item.Price); orderItems.Add(orderItem); } var order = new Order(orderItems, user.Id); order.Place(); _orderRepository.Create(order); if (Commit()) { return(order); } return(null); }
public void ProcessMessage(IProcessHandlerContext <AcceptOrderProcessCommand> context) { if (context.Stream.IsEmpty) { return; } context.Stream.AddEvent(ChangeStatus("Order Accepted")); var command = new CreateOrderCommand { OrderNumber = _initialized.OrderNumber, OrderDate = _initialized.DateRegistered, CustomerName = _customerAssigned.CustomerName, CustomerEMail = _customerAssigned.CustomerEMail }; foreach (var itemAdded in _items) { command.Items.Add(new MessageOrderItem { Description = itemAdded.Description, Price = itemAdded.Price }); } context.Send(command); context.Publish(new OrderProcessAcceptedEvent { OrderProcessId = CorrelationId }); }
public async Task Handle_success() { //arrange var order = new Order( new List <OrderItem> { new OrderItem("001", "product 001", 1, 12.34m), new OrderItem("002", "product 002", 2, 23.45m) }, "customerId", "customerName", "*****@*****.**", "phone", "address", "additionalAddress", "district", "city", "state", "12345-678"); CancellationToken token = default(CancellationToken); CreateOrderCommand command = new CreateOrderCommand(new List <CreateOrderCommandItem> { new CreateOrderCommandItem("001", "product 001", 1, 12.34m), new CreateOrderCommandItem("002", "product 002", 2, 23.45m) } , "customerId", "customerName", "*****@*****.**", "phone", "address", "additionalAddress", "district", "city", "state", "12345-678"); IdentifiedCommand <CreateOrderCommand, bool> request = new IdentifiedCommand <CreateOrderCommand, bool>(command, Guid.NewGuid()); orderRepositoryMock .Setup(r => r.CreateOrUpdate(It.IsAny <Order>())) .ReturnsAsync(order) .Verifiable(); var handler = new CreateOrderCommandHandler(loggerMock.Object, orderRepositoryMock.Object, busMock.Object, configurationMock.Object); //act bool result = await handler.Handle(request, token); //assert Assert.True(result); orderRepositoryMock.Verify(); }
private async Task JoinRunInternalAsync(long userId, Run run, long optionId, CallbackData callbackData) { BaseCommand command; if (run.Ended) { throw new SlackTeaTimeException(ErrorStrings.JoinRun_RunEnded()); } //check if we need to join or update var existingOrder = await _mediator.Send(new GetUserOrderQuery(run.Id, userId)).ConfigureAwait(false); if (existingOrder == null) { command = new CreateOrderCommand( id: await _idGenerator.GenerateAsync().ConfigureAwait(false), runId: run.Id, userId: userId, optionId: optionId); } else { //we need to update the existing order command = new UpdateOrderOptionCommand(existingOrder.Id, userId, optionId); } command.AddCallbackState(callbackData); await _mediator.Send(command).ConfigureAwait(false); }
public async Task <IActionResult> CreateOrder([FromBody] NewOrderDto data) { var command = new CreateOrderCommand(data); var result = await _mediator.Send(command); return(CreatedAtAction("GetOrder", new { orderId = result.Id }, result)); }
public async Task <IActionResult> CreateOrder([FromBody] CreateOrderCommand command) { var result = await _mediator.Send(command); //return CreatedAtAction("GetOrder", new { orderId = result.OrderId }, result); return(Ok(result)); }
public async Task <IHttpActionResult> Buy(int id, [FromUri] string email) { return(await this.Try( async() => { PersonDto dto; try { var personAuthDto = await this.GetAuthorizedMember(this._authRepository); dto = personAuthDto.PersonDto; if (email != dto.Email) { throw new BadRequestException("The email was not identical with the email of the person logged in"); } } catch (InvalidAccessTokenException) { dto = await this._personRepository.CreatePersonIfNotExists(email); } var command = new CreateOrderCommand { BookId = id, Status = BookOrderStatus.Sold, PersonId = dto.Id }; await this._bookOrderRepository.CreateOrder(command); })); }
public OrdersController(CreateOrderCommand createOrderCommand, AddProductToOrderCommand addProductToOrderCommand, GetOrderByIdQuery getOrderByIdQuery, AddBundleToOrderCommand addBundleToOrderCommand) { _createOrderCommand = createOrderCommand; _addProductToOrderCommand = addProductToOrderCommand; _getOrderByIdQuery = getOrderByIdQuery; _addBundleToOrderCommand = addBundleToOrderCommand; }
public async Task <ActionResult> Submit(SubmitOrderRequest request) { // TODO: Validate SubmitOrderRequest // TODO: Retrieve desk, ownerId from user context // TODO: Retrieve currency from Instrument // TODO: Ensure user has Sales role var orderId = Guid.NewGuid(); var command = new CreateOrderCommand( Guid.NewGuid(), orderId, null, request.Instrument, Guid.NewGuid(), request.Quantity, request.Side, request.Type, request.LimitPrice, "GBP", request.Markup.Unit, request.Markup.Value, request.Expiry.GoodTillDate, request.Expiry.Type); await _queueClient.Send(_configuration.CommandQueueName, command); return(Ok(new SubmitOrderResponse(orderId))); }
public void Handle(CreateOrderCommand message) { Data.CustomerId = new CustomerId(message.CustomerId.ToString()); Data.Email = message.Email; Data.FirstName = message.FirstName; Data.LastName = message.LastName; Data.OrderId = message.OrderId; // ensure the customer exists, if not, create it var customer = Repository.Load <Customer>(x => x.CustomerId == new CustomerId(message.CustomerId.ToString())); if (customer == null) { Bus.Send(new CreateCustomerCommand { CustomerId = Guid.Parse(Data.CustomerId.ToString()), Email = Data.Email, FirstName = Data.FirstName, LastName = Data.LastName }); return; } CreateOrder(); EndOrderProcess(); }
public async Task Handle_GivenValidRequest_ShouldCreateOrder() { // Arrange var command = new CreateOrderCommand { Description = "Desc", Price = "123", Quantity = "123", Status = "Active", }; var customersRepository = new EfDeletableEntityRepository <Customer>(this.dbContext); var sut = new CreateOrderCommandHandler( this.deletableEntityRepository, customersRepository); // Act var id = await sut.Handle(command, It.IsAny <CancellationToken>()); // Assert var createdOrder = this.deletableEntityRepository .AllAsNoTracking() .SingleOrDefault(x => x.Description == "Desc"); createdOrder.CustomerId.ShouldBe(1); createdOrder.Description.ShouldBe("Desc"); createdOrder.TotalAmount.ShouldBe(123); }
public CreateOrderTransaction(CreateOrderCommand cmd) : base(cmd.CorrelationId , new SaveOrderActivity() , new SaveUserAddressActivity() ) { SetState(CONSTANTS.TRANSACTIONS.EntryCommand, cmd); }
public async Task <IActionResult> Checkout([FromBody] dynamic body) { var cartId = (Guid)body.CartId; // Search for a cart that has the given ID and the status is 'Normal'. var cart = (await this.dataAccessObject.FindBySpecificationAsync <Cart>(c => c.Id == cartId && c.Status == CartStatus.Normal)) .FirstOrDefault(); if (cart == null) { return(NotFound("No available shopping cart found.")); } // Update the found cart's status to Checkout. cart.Status = CartStatus.Checkout; await this.dataAccessObject.UpdateByIdAsync(cartId, cart); // Send the CreateOrder command to create the sales order. var createOrderCommand = new CreateOrderCommand(cart.CustomerId, cartId, cart.CartItems.Select(item => new CreateOrderLine { ProductId = item.ProductId, Price = item.Price, Quantity = item.Quantity })); await this.commandBus.PublishAsync(createOrderCommand); return(Ok()); }
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); }
public void Order_Must_Be_Sent_Successfully( string timeOfDay, int[] inputDishes, string outputFoods) { var command = new CreateOrderCommand { TimeOfDay = timeOfDay }; var dishes = new List <int>(); foreach (var dish in inputDishes) { dishes.Add(dish); } command.Dishes = dishes; var handler = new OrderHandler( new Repository( new DishRepository(new DishTypeRepository(), new TimeOfDayRepository()), new TimeOfDayRepository(), new DishTypeRepository())); var result = (CommandResult)handler.Handle(command); Assert.AreEqual(outputFoods, result.Foods); }
public async Task Create_order_command() { //Arrange's var uow = new Mock <IUnitOfWork>(); var mediator = new Mock <IMediatorHandler>(); var orderRepository = new Mock <IOrderRepository>(); var notificationHandler = new Mock <DomainNotificationHandler>(); var logger = new Mock <ILogger <CreateOrderCommand> >(); var handler = new OrdersCommandHandler(mediator.Object, notificationHandler.Object, orderRepository.Object, logger.Object); //Stub's orderRepository.SetupGet(x => x.UnitOfWork).Returns(uow.Object); var command = new CreateOrderCommand() { Address = Builder <OrderAddressMessageResponse> .CreateNew().Build(), Items = Builder <OrderItemMessageResponse> .CreateListOfSize(1).Build().ToArray(), UserId = Guid.NewGuid() }; //Act await handler.Handle(command, CancellationToken.None); //Assert's orderRepository.Verify(x => x.Save(It.Is <Order>(it => !string.IsNullOrEmpty(it.OrderNumber))), Times.Once); orderRepository.Verify(x => x.UnitOfWork.SaveEntitiesAsync(CancellationToken.None), Times.Once); mediator.Verify(x => x.RaiseEvent(It.IsAny <DomainNotification>()), Times.Never()); }
string BuildOrder() { List <OrderItemDTO> orderItemsList = new List <OrderItemDTO>(); orderItemsList.Add(new OrderItemDTO() { ProductId = 1, Discount = 8M, UnitPrice = 10, Units = 1, ProductName = "Some name" } ); var order = new CreateOrderCommand( orderItemsList, cardExpiration: DateTime.UtcNow.AddYears(1), cardNumber: "5145-555-5555", cardHolderName: "Jhon Senna", cardSecurityNumber: "232", cardTypeId: 1, city: "Redmon", country: "USA", state: "WA", street: "One way", zipcode: "zipcode", paymentId: 1, buyerId: 3 ); return(JsonConvert.SerializeObject(order)); }
public CreateOrderCommandTests() { _dapperService = A.Fake <DapperService>(); _createOrderCommand = new CreateOrderCommand(A.Fake <IOptions <ApplicationConfiguration> >(), _dapperService); }
public async Task <string> Post(CreateOrderCommand command) { //return await Task.FromResult("Success"); var result = await Mediator.Send(command); return(result); }
void ConsumeWebInKafka(ConsumerConfig consumerConfig, CancellationToken cancellationToken) { using (var c = new ConsumerBuilder <Ignore, string>(consumerConfig).Build()) { string topic = "web-in"; c.Subscribe(topic); Console.WriteLine(DateTime.Now + " - Counter Service Listening to: " + topic); try { while (!cancellationToken.IsCancellationRequested) { try { var cr = c.Consume(cancellationToken); Console.WriteLine(DateTime.Now + " - " + topic + ":" + cr.Message.Value); CreateOrderCommand orderCommand = JsonUtil.createOrderCommandFromJson(cr.Message.Value); handleCreateOrderCommand(orderCommand); } catch (ConsumeException e) { Console.WriteLine($"Error occured: {e.Error.Reason}"); } } } catch (OperationCanceledException) { // Ensure the consumer leaves the group cleanly and final offsets are committed. c.Close(); } } }
/// <summary> /// Integration event handler which starts the create order process /// </summary> /// <param name="eventMsg"> /// Integration event message which is sent by the /// basket.api once it has successfully process the /// order items. /// </param> /// <returns></returns> public async Task Handle(UserCheckoutAcceptedIntegrationEvent eventMsg) { var result = false; // Send Integration event to clean basket once basket is converted to Order and before starting with the order creation process var orderStartedIntegrationEvent = new OrderStartedIntegrationEvent(eventMsg.UserId); await _orderingIntegrationEventService.PublishThroughEventBusAsync(0, "Order Started", orderStartedIntegrationEvent); if (eventMsg.RequestId != Guid.Empty) { var createOrderCommand = new CreateOrderCommand(eventMsg.Basket.Items, eventMsg.UserId, eventMsg.UserName, eventMsg.City, eventMsg.Street, eventMsg.State, eventMsg.Country, eventMsg.ZipCode, eventMsg.CardNumber, eventMsg.CardHolderName, eventMsg.CardExpiration, eventMsg.CardSecurityNumber, eventMsg.CardTypeId); var requestCreateOrder = new IdentifiedCommand <CreateOrderCommand, bool>(createOrderCommand, eventMsg.RequestId); result = await _mediator.Send(requestCreateOrder); } _logger.CreateLogger(nameof(UserCheckoutAcceptedIntegrationEventHandler)) .LogTrace(result ? $"UserCheckoutAccepted integration event has been received and a create new order process is started with requestId: {eventMsg.RequestId}" : $"UserCheckoutAccepted integration event has been received but a new order process has failed with requestId: {eventMsg.RequestId}"); }
public async Task <bool> CreateAsync(CreateOrderCommand command) { try { var order = new OnlineShop.Domain.Entities.Order { UserId = command.UserId, Total = command.Total, InvoiceDate = command.InvoiceDate, }; var orderDetails = command.OrderDetails.Select(c => new OrderDetails { Discount = c.Discount, Qty = c.Qty, ProductId = c.ProductId, Price = c.Price, TaxId = c.TaxId }).ToList(); order.OrderDetails = orderDetails; await _dbContext.Orders.AddAsync(order); await _cacheService.DeleteKeyAsync(string.Format(RedisDefaultKeys.GetAllOrdersByUser, command.UserId)); await _cacheService.DeleteKeyAsync(RedisDefaultKeys.GetAllOrders); return(await _dbContext.SaveChangesAsync() > 0); } catch (Exception ex) { return(false); } }
public async Task <IActionResult> PlaceOrder([FromBody] CreateOrderCommand createOrderCommand) { var tasks = createOrderCommand.OrderItems .Select(item => _productQueries.GetProductBySKUAsync(item.SKU) .ContinueWith((productAsync) => { var product = productAsync.Result; if (product != null) { item.ProductId = product.Id; item.UnitPrice = product.UnitPrice; item.ProductName = product.ProductName; } })); await Task.WhenAll(tasks); var commandResult = await _mediator.Send(createOrderCommand); if (!commandResult) { return(BadRequest()); } return(Ok()); }
List<CommandRouteItem> GetCreateOrderCommandRoutes(CreateOrderCommand createOrderCommand) { List<CommandRouteItem> commandRouteItems = new List<CommandRouteItem>(); string serializedCommand = JsonConvert.SerializeObject(createOrderCommand); List<Guid> destinationIds = GetDestinationApplicationIdsForCostCentres(createOrderCommand.DocumentIssuerCostCentreId, createOrderCommand.DocumentRecipientCostCentreId); Guid[] _destinationIds = RemoveSourceCCAppId(destinationIds.ToArray(), createOrderCommand); foreach (Guid appId in _destinationIds) commandRouteItems.Add(CreateRouteItem(createOrderCommand, "CreateOrder", appId, serializedCommand)); return commandRouteItems; }