public async Task Handle(OrderPaymentFailedIntegrationEvent @event)
        {
            _logger.LogInformation(" [x] OrderPaymentFailedIntegrationEvent: Creating new CancelOrderCommand.");

            var command = new CancelOrderCommand(orderId: @event.OrderId, reason: "Payment failed");
            await _mediator.Send(command);
        }
Exemplo n.º 2
0
        public async Task <IActionResult> CancelOrderAsync([FromBody] CancelOrderCommand command, [FromHeader(Name = "x-requestid")] string requestId)
        {
            bool commandResult = false;

            if (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty)
            {
                var requestCancelOrder = new IdentifiedCommand <CancelOrderCommand, bool>(command, guid);

                _logger.LogInformation(
                    "----- Sending command: {CommandName} - {IdProperty}: {CommandId} ({@Command})",
                    requestCancelOrder.GetGenericTypeName(),
                    nameof(requestCancelOrder.Command.OrderNumber),
                    requestCancelOrder.Command.OrderNumber,
                    requestCancelOrder);

                commandResult = await _mediator.Send(requestCancelOrder);
            }

            if (!commandResult)
            {
                return(BadRequest());
            }

            return(Ok());
        }
Exemplo n.º 3
0
        public async Task CalcelOrderAsync(string id)
        {
            validator.VerifyId(id);

            var command = new CancelOrderCommand(Guid.Parse(id));
            await commandBus.SendAsync(command);
        }
Exemplo n.º 4
0
        public void Handle_OrderNull_ThrowException()
        {
            var command = new CancelOrderCommand();

            command.Order = null;
            Assert.ThrowsExceptionAsync <ArgumentNullException>(async() => await _handler.Handle(command, default));
        }
        public bool ValidateCancelOrderCommand(CancelOrderCommand orderCommand)
        {
            var order = _orderRepository.GetOrderById(orderCommand.OrderId.Id.ToString());

            if (order != null)
            {
                if (order.TraderId.Equals(orderCommand.TraderId.Id.ToString(), StringComparison.InvariantCultureIgnoreCase))
                {
                    //check if order is already cancelled
                    if (order.Status.Equals(OrderState.Cancelled.ToString()))
                    {
                        throw new InvalidOperationException("Order is already cancelled");
                    }
                    //check if order is already filled
                    if (order.Status.Equals(OrderState.Complete.ToString()))
                    {
                        throw new InvalidOperationException("Order is filled, cannot be cancelled");
                    }
                    //this means command is valid
                    return(true);
                }
                throw new InvalidOperationException("Order id doest not belong to the trader id.");
            }
            throw new ArgumentException("Invalid order id");
        }
Exemplo n.º 6
0
        public void DispatchShouldExecuteHandler()
        {
            // Arrange.
            var command = new CancelOrderCommand();

            var executed = false;
            var handler  = A.Fake <ICommandHandler <CancelOrderCommand> >();

            A.CallTo(() => handler.Handle(command)).Invokes(c => { executed = true; }).Returns(Task.FromResult(0));

            var map = new MessageHandlerMap();

            map.Add(typeof(CancelOrderCommand), handler.GetType());

            var container = A.Fake <IContainer>();

            A.CallTo(() => container.Resolve(handler.GetType())).Returns(handler);

            var dispatcher = new MessageDispatcher(container, map);

            // Act.
            dispatcher.Dispatch("CreateOrder", new Envelope <CancelOrderCommand>(command)).Wait();

            // Assert.
            A.CallTo(() => handler.Handle(command)).MustHaveHappened(Repeated.Exactly.Once);
            Assert.True(executed);
        }
Exemplo n.º 7
0
        public async Task <IActionResult> CancelOrderAsync(
            [FromBody] CancelOrderCommand command,
            CancellationToken cancellationToken = default)
        {
            var commandResult = await _commandDispatcher.SendAsync <CancelOrderCommand, CancelOrderCommandResult>(command, cancellationToken);

            return(Ok(commandResult));
        }
Exemplo n.º 8
0
        public async Task <ActionResult <CancelOrderCommandResponse> > CancelOrderAsync(Guid id)
        {
            var request = new CancelOrderCommand {
                Id = id
            };
            var response = await _messageBus.SendAsync(request);

            return(Ok(response));
        }
Exemplo n.º 9
0
        public async Task <ActionResult> CancelOrder([FromQuery] Guid id)
        {
            var command = new CancelOrderCommand(id);
            // Send the command
            await _endpointInstance.Send("Assignment.Orders", command);

            // Return the order
            return(Ok(id));
        }
Exemplo n.º 10
0
        public void ShouldThrowOrderNotFoundException()
        {
            // Cancel Order Command
            var cancelOrderCommand = new CancelOrderCommand {
                OrderId = Guid.NewGuid().ToString()
            };

            FluentActions.Invoking(() => SendAsync(cancelOrderCommand)).Should().Throw <OrderNotFoundException>();
        }
Exemplo n.º 11
0
        public void ShouldRequireMinimumFields()
        {
            var command = new CancelOrderCommand();

            FluentActions.Invoking(() =>
                                   SendAsync(command))
            .Should()
            .Throw <BaseValidationException>();
        }
Exemplo n.º 12
0
        /// <summary>
        /// Cancels the order.
        /// </summary>
        /// <param name="cancelOrder">The cancel order.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">cancelOrder</exception>
        public static void CancelOrder(OsEngine.Entity.Order order)
        {
            List<string> transactions = new List<string>();
            transactions.Add(order.NumberMarket);

            CancelOrderCommand canselOrder = new CancelOrderCommand(_token.Token, transactions);

            clientTwo.CancelOrder(canselOrder);
        }
Exemplo n.º 13
0
        public async Task <IActionResult> Cancel([FromBody] CancelOrderCommand cmd)
        {
            Order order = await this._repository.Get(cmd.OrderId);

            order.Cancel();
            await this._repository.SaveChanges(order);

            return(new OkResult());
        }
Exemplo n.º 14
0
        public override async Task HandleAsync(CancelOrderIntegrationEvent @event)
        {
            var command = new CancelOrderCommand
            {
                OrderId = @event.OrderId
            };

            await _bus.SendAsync(command);
        }
Exemplo n.º 15
0
        public void Handle_AlreadyCancelled_ThrowException()
        {
            var command = new CancelOrderCommand();

            command.Order = new Order()
            {
                OrderStatusId = (int)OrderStatusSystem.Cancelled
            };
            Assert.ThrowsExceptionAsync <Exception>(async() => await _handler.Handle(command, default));
        }
Exemplo n.º 16
0
        public async Task <IActionResult> CancelOrderAsync(Guid orderId)
        {
            var command = new CancelOrderCommand {
                OrderId = orderId
            };

            await SendCommandAsync(command);

            return(Ok());
        }
Exemplo n.º 17
0
        /// <summary>
        /// Cancels the order.
        /// </summary>
        /// <param name="cancelOrder">The cancel order.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">cancelOrder</exception>
        public Task CancelOrder(CancelOrderCommand cancelOrder)
        {
            if (cancelOrder == null)
            {
                logger.LogError("No cancelOrder command provided");
                throw new ArgumentNullException(nameof(cancelOrder));
            }

            return(CancelOrderInternal(cancelOrder));
        }
Exemplo n.º 18
0
        public async Task <IActionResult> Cancel(string id)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var command = new CancelOrderCommand(id);

            return(await QueueCommandAsync(command));
        }
Exemplo n.º 19
0
        public async Task Handle(CancelOrderCommand message, IMessageHandlerContext context)
        {
            var @event = mapper.Map <CancelOrderEvent>(message);

            var result = await eventContext.AddAsync($"Order {message.OrderId}", @event);

            @event.LogPosition         = result.LogPosition;
            @event.NextExpectedVersion = result.NextExpectedVersion;

            await context.Publish(@event);
        }
Exemplo n.º 20
0
        public async Task <IActionResult> CancelOrderAsync([FromBody] CancelOrderCommand command, [FromHeader(Name = "x-requestid")] string requestId)
        {
            var commandResult = await _commandSender.SendCommand(command);

            if (!commandResult)
            {
                return(BadRequest());
            }

            return(Ok());
        }
Exemplo n.º 21
0
        public async Task <IActionResult> CancelOrder([FromBody] CancelOrderCommand command, [FromHeader(Name = "x-requestid")] string requestId)
        {
            bool commandResult = false;

            if (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty)
            {
                var requestCancelOrder = new IdentifiedCommand <CancelOrderCommand, bool>(command, guid);
                commandResult = await _mediator.Send(requestCancelOrder);
            }

            return(commandResult ? (IActionResult)Ok() : (IActionResult)BadRequest());
        }
        public void ValidateCancelOrderCommand_IfOrderIdAndTraderIdIsValidAndOrderStatusIsNotCompleteOrCancelled_CommandWillBeValidated()
        {
            Order order = OrderFactory.CreateOrder("1234", "XBTUSD", "limit", "buy", 5, 10,
                                                   new StubbedOrderIdGenerator());
            OrderReadModel model = ReadModelAdapter.GetOrderReadModel(order);

            _persistanceRepository.SaveOrUpdate(model);
            CancelOrderCommand            command    = new CancelOrderCommand(order.OrderId, order.TraderId);
            ICancelOrderCommandValidation validation = new CancelOrderCommandValidation(_orderRepository);

            Assert.True(validation.ValidateCancelOrderCommand(command));
        }
Exemplo n.º 23
0
        public async Task <IActionResult> CancelOrder([FromBody] CancelOrderCommand command, [FromHeader(Name = "x-requestid")] string requestId)
        {
            IExecutionResult result = ExecutionResult.Failed();

            if (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty)
            {
                var order = await _queryProcessor.ProcessAsync(new GetOrderByOrderNumberQuery(command.OrderNumber), CancellationToken.None).ConfigureAwait(false);

                await _commandBus.PublishAsync(new CancelOrderCommand(new OrderId(order.OrderId), order.OrderNumber), CancellationToken.None);
            }

            return(result.IsSuccess ? (IActionResult)Ok() : (IActionResult)BadRequest());
        }
Exemplo n.º 24
0
        public async Task <ActionResult <Result> > CancelOrderAsync([FromBody] CancelOrderDTO cancelOrderDTO)
        {
            var command = new CancelOrderCommand(cancelOrderDTO.OrderNumber);

            var commandResult = await _mediator.Send(command);

            if (commandResult.IsFailure)
            {
                return(BadRequest());
            }

            return(Ok());
        }
Exemplo n.º 25
0
        public async Task HandleAsync(CancelOrderCommand command)
        {
            var order = await _eventRepository.GetByIdAsync <Order>(command.OrderId);

            if (order == null)
            {
                throw new StocqresException("Order does not exist");
            }

            order.CancelOrder(command.CancelReason);

            await _eventRepository.SaveAsync(order);
        }
        public void Serialize_CancelOrderCommand()
        {
            var cancelOrder = new CancelOrderCommand("0000000000000000000000000000000000000000", new[] { "ID1" })
            {
                RequestId = 123,
            };

            var cancelOrderJson = instance.Serialize(cancelOrder);

            Assert.Contains(@"""event"":""cancelOrder""", cancelOrderJson);
            Assert.Contains(@"""token"":""0000000000000000000000000000000000000000""", cancelOrderJson);
            Assert.Contains(@"""reqid"":123", cancelOrderJson);
            Assert.Contains(@"""txid"":[""ID1""]", cancelOrderJson);
        }
        public void ValidateCancelOrderCommand_IfOrderIdAndTraderIdIsValidAndOrderStatusIsCancelled_InvalidOperationException()
        {
            Order order = OrderFactory.CreateOrder("1234", "XBTUSD", "limit", "buy", 5, 10,
                                                   new StubbedOrderIdGenerator());

            order.OrderState = OrderState.Cancelled;
            OrderReadModel model = ReadModelAdapter.GetOrderReadModel(order);

            _persistanceRepository.SaveOrUpdate(model);
            CancelOrderCommand            command    = new CancelOrderCommand(order.OrderId, order.TraderId);
            ICancelOrderCommandValidation validation = new CancelOrderCommandValidation(_orderRepository);

            validation.ValidateCancelOrderCommand(command);
        }
Exemplo n.º 28
0
        private void RaiseCanExecuteChanged()
        {
            // order commands
            CancelOrderCommand.RaiseCanExecuteChanged();
            HoldOrderCommand.RaiseCanExecuteChanged();
            ReleaseHoldCommand.RaiseCanExecuteChanged();
            CreateRmaRequestCommand.RaiseCanExecuteChanged();
            CreateExchangeCommand.RaiseCanExecuteChanged();
            CreateRefundCommand.RaiseCanExecuteChanged();

            OnPropertyChanged("IconSource");

            // shipment and RmaRequest commands
            OrderShipmentViewModels.ToList().ForEach(x => x.RaiseCanExecuteChanged());
            // InnerItem.RmaRequests.ToList().ForEach(x => x.RaiseCanExecuteChanged());
        }
Exemplo n.º 29
0
        public async Task <IActionResult> CancelOrderAsync([FromBody] CancelOrderCommand command, [FromHeader(Name = "x-requestid")] string requestId)
        {
            bool commandResult = false;

            if (Guid.TryParse(requestId, out Guid guid) && guid != Guid.Empty)
            {
                commandResult = await _mediator.Send(command);
            }

            if (!commandResult)
            {
                return(BadRequest());
            }

            return(Ok());
        }
Exemplo n.º 30
0
        public async Task Handle_InvokeExpectedMethods()
        {
            var command = new CancelOrderCommand();

            command.Order = new Order()
            {
                Id = "id"
            };
            _shipmentServiceMock.Setup(c => c.GetShipmentsByOrder("id")).ReturnsAsync(new List <Shipment>());
            await _handler.Handle(command, default);

            _productReservationMock.Verify(c => c.CancelReservationsByOrderId("id"), Times.Once);
            _auctionMock.Verify(c => c.CancelBidByOrder("id"), Times.Once);
            _discountServiceMock.Verify(c => c.CancelDiscount("id"), Times.Once);
            _mediatorMock.Verify(c => c.Publish <OrderCancelledEvent>(It.IsAny <OrderCancelledEvent>(), default));
        }