Example #1
0
        public Tests()
        {
            _mediator      = new Mock <IMediator>();
            _emailMock     = new Mock <IEmailService>();
            _orderRepoMock = new Mock <IOrderRepository>();
            _mockMediatr   = new Mock <IMediator>();

            _order = new Order()
            {
                UserName = "******"
            };
            _orders = new List <Order>()
            {
                new() {
                    UserName = "******"
                }
            };

            _updateOrderCommand = new UpdateOrderCommand()
            {
                UserName   = "******",
                TotalPrice = 0
            };
        }
Example #2
0
        public async Task Handle_GivenValidRequest_ShouldReturnOrderId()
        {
            // Arrange
            var command = new UpdateOrderCommand
            {
                Id          = 1,
                Description = "NewDesc",
                Quantity    = "321",
                Status      = "Tested",
            };

            var sut = new UpdateOrderCommandHandler(this.deletableEntityRepository);

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

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

            order.ShouldNotBeNull();
            order.Description.ShouldBe("NewDesc");
            order.Quantity.ShouldBe(321);
            order.Status.ShouldBe("Tested");
        }
Example #3
0
        public async Task <ActionResult <bool> > UpdateOrder([FromBody] UpdateOrderCommand command)
        {
            bool status = await _mediator.Send(command);

            return(Ok(status));
        }
        public async Task <ActionResult> UpdateOrder([FromBody] UpdateOrderCommand cmd)
        {
            await _mediator.Send(cmd);

            return(Ok());
        }
Example #5
0
        public async Task <IActionResult> UpdateOrder(UpdateOrderCommand command)
        {
            await _mediator.Send(command);

            return(NoContent());
        }
Example #6
0
        public async Task <ActionResult> UpdateOrder([FromBody] UpdateOrderCommand command)
        {
            await mediator.Send(command);

            return(NoContent());
        }
        public void Description_not_empty_success()
        {
            var order = new UpdateOrderCommand(Guid.Empty, Guid.Empty, new DateTime(), "Description");

            validator.ShouldNotHaveValidationErrorFor(p => p.Description, order);
        }
        public void Product_id_empty_fail()
        {
            var order = new UpdateOrderCommand(Guid.Empty, Guid.Empty, new DateTime(), string.Empty);

            validator.ShouldHaveValidationErrorFor(p => p.ProductId, order);
        }
Example #9
0
 public Task <int> Update(UpdateOrderCommand updateOrderCommand)
 {
     throw new NotImplementedException();
 }
 /// <summary>
 /// 更新
 /// </summary>
 /// <param name="request"></param>
 /// <param name="cancellationToken"></param>
 /// <returns></returns>
 public Task <Unit> Handle(UpdateOrderCommand request, CancellationToken cancellationToken)
 {
     throw new System.NotImplementedException();
 }
        public async Task <IActionResult> UpdateAsync([FromBody] UpdateOrderCommand command)
        {
            var response = await _mediator.Send(command);

            return(Json(response));
        }
 public void Run(UpdateOrderCommand command)
 {
     _service.When(command);
 }
Example #13
0
        public async Task ShouldUpdateOrder()
        {
            // 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);

            // Create product brand
            var brandCommand = new CreateBrandCommand {
                Name = "Test Brand"
            };
            var brandId = await SendAsync(brandCommand);

            // Create product category
            var productCategoryCommand = new CreateProductCategoryCommand {
                Name = "Test Product Category"
            };
            var productCategoryId = await SendAsync(productCategoryCommand);

            // Create product
            var createProductCommand = new CreateProductCommand
            {
                AvailableToSell = true,
                // created brand id
                BrandId = brandId,
                // created product category id
                ProductCategoryId = productCategoryId,
                Name     = "Test Product",
                PhotoUrl = "Test Product",
                Barcode  = "Test Product"
            };

            var productId = await SendAsync(createProductCommand);

            // Add first unit to product
            var addFirstUnitCommand = new AddUnitCommand
            {
                ProductId    = productId,
                SellingPrice = 92,
                ContentCount = 2,
                Price        = 33,
                Count        = 6,
                IsAvailable  = true,
                Name         = "Test First Unit",
                Weight       = 44
            };

            var firstUnitId = await SendAsync(addFirstUnitCommand);

            // Add first unit to product
            var addSecondUnitCommand = new AddUnitCommand
            {
                ProductId    = productId,
                SellingPrice = 342,
                ContentCount = 24,
                Price        = 323,
                Count        = 64,
                IsAvailable  = true,
                Name         = "Test Second Unit",
                Weight       = 94
            };

            var secondUnitId = await SendAsync(addSecondUnitCommand);

            // AddItem To Shopping Van
            var addItemToVanCommand = new AddItemToVanCommand
            {
                ProductId = productId,
                UnitId    = firstUnitId
            };

            await SendAsync(addItemToVanCommand);
            await SendAsync(addItemToVanCommand);

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

            // Get Order By Id Query
            var orderByIdQuery = new OrderByIdQuery {
                OrderId = orderId
            };
            var order = await SendAsync(orderByIdQuery);

            // Act

            var updateOrderCommand = new UpdateOrderCommand
            {
                OrderId     = orderId,
                OrderItemId = order.OrderItems.FirstOrDefault(x => x.UnitId == firstUnitId).Id,
                UnitId      = secondUnitId,
                UnitCount   = 10,
                UnitName    = addSecondUnitCommand.Name
            };

            await SendAsync(updateOrderCommand);

            // Get Order By Id Query
            var orderAfterUpdate = await SendAsync(orderByIdQuery);


            // Assert
            order.Should().NotBeNull();
            order.OrderItems.Count.Should().Be(1);
            order.OrderItems.FirstOrDefault(x => x.UnitId == firstUnitId).UnitName.Should().Be(addFirstUnitCommand.Name);
            orderAfterUpdate.OrderItems.FirstOrDefault(x => x.UnitId == secondUnitId).UnitName.Should().Be(addSecondUnitCommand.Name);
        }
Example #14
0
 public static Order ToEntity(this UpdateOrderCommand model, Order destination)
 {
     return(model.MapTo(destination));
 }
 partial void OnUpdatedOrder(IServiceRequestWithData <Cqrs.Authentication.ISingleSignOnToken, Entities.OrderEntity> serviceRequest, ref UpdateOrderCommand command, Entities.OrderEntity locatedItem, ref ServiceResponseStateType?serviceResponseStateType);
 public Task <ActionResult> Update(UpdateOrderCommand command) => throw new NotImplementedException();
        public async Task <OrderDTO> UpdateOrderAsync(OrderDTO orderDTO)
        {
            var query = new UpdateOrderCommand(orderDTO);

            return(await _mediator.Send(query));
        }
        public async Task <UpdateOrderValidationResult> Validate(UpdateOrderCommand order, string subject)
        {
            if (order == null)
            {
                throw new ArgumentNullException(nameof(order));
            }

            if (string.IsNullOrWhiteSpace(subject))
            {
                throw new ArgumentNullException(nameof(subject));
            }

            var record = await _orderRepository.Get(order.Id);

            if (record == null)
            {
                return(new UpdateOrderValidationResult(ErrorDescriptions.TheOrderDoesntExist));
            }

            if (record.Status == OrderAggregateStatus.Received) // Cannot update received order.
            {
                return(new UpdateOrderValidationResult(ErrorDescriptions.TheReceivedOrderCannotBeUpdated));
            }

            if (record.Status != OrderAggregateStatus.Created && record.Status == order.Status) // Confirmed & received order cannot be updated.
            {
                return(new UpdateOrderValidationResult(string.Format(ErrorDescriptions.TheOrderCannotBeUpdatedBecauseOfItsState, Enum.GetName(typeof(OrderAggregateStatus), order.Status))));
            }

            if (record.Status != order.Status)
            {
                if (record.Status == OrderAggregateStatus.Created && order.Status != OrderAggregateStatus.Confirmed) // created => confirmed.
                {
                    return(new UpdateOrderValidationResult(string.Format(ErrorDescriptions.TheOrderStateCannotBeUpdated, Enum.GetName(typeof(OrderAggregateStatus), record.Status), Enum.GetName(typeof(OrderAggregateStatus), order))));
                }

                if (record.Status == OrderAggregateStatus.Confirmed && order.Status != OrderAggregateStatus.Received) // confirmed => received
                {
                    return(new UpdateOrderValidationResult(string.Format(ErrorDescriptions.TheOrderStateCannotBeUpdated, Enum.GetName(typeof(OrderAggregateStatus), record.Status), Enum.GetName(typeof(OrderAggregateStatus), order))));
                }
            }

            if (order.TransportMode == OrderTransportModes.Manual && order.Status == OrderAggregateStatus.Received && record.Subject != subject)  // Only the creator can confirm the order.
            {
                return(new UpdateOrderValidationResult(ErrorDescriptions.TheOrderReceptionCanBeConfirmedOnlyByItsCreator));
            }

            IEnumerable <ProductAggregate> prods = null;

            if (order.OrderLines != null && order.OrderLines.Any()) // Check the lines.
            {
                var productIds = order.OrderLines.Select(o => o.ProductId);
                var products   = await _productRepository.Search(new SearchProductsParameter { ProductIds = productIds });

                if (products.Content.Count() != productIds.Count())
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheOrderLineProductIsInvalid));
                }

                if (order.OrderLines.Any(o => o.Quantity <= 0))
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheOrderLineQuantityIsInvalid));
                }

                foreach (var orderLine in order.OrderLines)
                {
                    var product = products.Content.First(p => p.Id == orderLine.ProductId);
                    if (orderLine.Quantity > product.AvailableInStock && product.AvailableInStock.HasValue)
                    {
                        return(new UpdateOrderValidationResult(ErrorDescriptions.TheOrderLineQuantityIsTooMuch));
                    }
                }

                prods = products.Content;
                var discountCodes = order.OrderLines.Select(o => o.DiscountCode).Where(dc => !string.IsNullOrEmpty(dc));
                if (discountCodes.Any()) // Check discounts.
                {
                    var discounts = await _discountRepository.Search(new SearchDiscountsParameter
                    {
                        IsPagingEnabled = false,
                        DiscountCodes   = discountCodes
                    });

                    if (discounts.Content == null || !discounts.Content.Any() || discounts.Content.Count() != discountCodes.Count())
                    {
                        return(new UpdateOrderValidationResult(ErrorDescriptions.TheDiscountCodesAreNotValid));
                    }

                    foreach (var orderLine in order.OrderLines)
                    {
                        if (string.IsNullOrWhiteSpace(orderLine.DiscountCode))
                        {
                            continue;
                        }

                        var discount = discounts.Content.First(c => c.Code == orderLine.DiscountCode);
                        if (discount.Products == null || !discount.Products.Any(p => p.ProductId == orderLine.ProductId)) // Check discount is valid for the product.
                        {
                            return(new UpdateOrderValidationResult(string.Format(ErrorDescriptions.TheDiscountCannotBeUsedForThisProduct, orderLine.ProductId)));
                        }

                        if (!discount.IsValid()) // Check discount is valid.
                        {
                            return(new UpdateOrderValidationResult(string.Format(ErrorDescriptions.TheProductDiscountIsInvalid, orderLine.DiscountCode)));
                        }

                        orderLine.DiscountId = discount.Id;
                    }
                }
            }

            double shippingPrice = 0;
            string payerEmail    = string.Empty;
            string sellerEmail   = string.Empty;

            if (order.Status == OrderAggregateStatus.Confirmed && order.TransportMode == OrderTransportModes.Packet)
            {
                if (order.OrderParcel == null)
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheParcelDoesntExist));
                }

                var payer = await _openidClient.GetPublicClaims(_settingsProvider.GetBaseOpenidUrl(), subject);

                if (payer == null)
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.ThePayerPaypalAccountNotExist));
                }

                var seller = await _openidClient.GetPublicClaims(_settingsProvider.GetBaseOpenidUrl(), record.SellerId);

                if (seller == null)
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheSellerPaypalAccountNotExist));
                }

                var paypalBuyer  = payer.Claims.FirstOrDefault(c => c.Type == "paypal_email");
                var paypalSeller = seller.Claims.FirstOrDefault(c => c.Type == "paypal_email");
                if (paypalBuyer == null || string.IsNullOrWhiteSpace(paypalBuyer.Value))
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.ThePayerPaypalAccountNotExist));
                }

                if (paypalSeller == null || string.IsNullOrWhiteSpace(paypalSeller.Value))
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheSellerPaypalAccountNotExist));
                }

                if (order.OrderParcel.Transporter == Transporters.Dhl)
                {
                    return(new UpdateOrderValidationResult(ErrorDescriptions.TheTransporterDhlIsNotSupported));
                }

                if (order.OrderParcel.Transporter == Transporters.Ups)
                {
                    var buyerName  = payer.Claims.First(c => c.Type == SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Name).Value;
                    var sellerName = seller.Claims.First(c => c.Type == SimpleIdentityServer.Core.Jwt.Constants.StandardResourceOwnerClaimNames.Name).Value;
                    var parameter  = new GetUpsRatingsParameter
                    {
                        Credentials = new UpsCredentials
                        {
                            LicenseNumber = _settingsProvider.GetUpsLicenseNumber(),
                            Password      = _settingsProvider.GetUpsPassword(),
                            UserName      = _settingsProvider.GetUpsUsername()
                        },
                        Shipper = new UpsShipperParameter
                        {
                            Name    = buyerName,
                            Address = new UpsAddressParameter
                            {
                                AddressLine = order.OrderParcel.BuyerAddressLine,
                                City        = order.OrderParcel.BuyerCity,
                                Country     = order.OrderParcel.BuyerCountryCode,
                                PostalCode  = order.OrderParcel.BuyerPostalCode.ToString()
                            }
                        },
                        ShipFrom = new UpsShipParameter
                        {
                            Name          = buyerName,
                            AttentionName = buyerName,
                            CompanyName   = buyerName,
                            Address       = new UpsAddressParameter
                            {
                                AddressLine = order.OrderParcel.BuyerAddressLine,
                                City        = order.OrderParcel.BuyerCity,
                                Country     = order.OrderParcel.BuyerCountryCode,
                                PostalCode  = order.OrderParcel.BuyerPostalCode.ToString()
                            }
                        },
                        ShipTo = new UpsShipParameter
                        {
                            Name          = sellerName,
                            AttentionName = sellerName,
                            CompanyName   = sellerName,
                            Address       = new UpsAddressParameter
                            {
                                AddressLine = order.OrderParcel.SellerAddressLine,
                                City        = order.OrderParcel.SellerCity,
                                Country     = order.OrderParcel.SellerCountryCode,
                                PostalCode  = order.OrderParcel.SellerPostalCode.ToString()
                            }
                        },
                        Package = new UpsPackageParameter
                        {
                            Height = Constants.PackageInfo.Height,
                            Length = Constants.PackageInfo.Length,
                            Weight = Constants.PackageInfo.Weight,
                            Width  = Constants.PackageInfo.Width
                        },
                        AlternateDeliveryAddress = new UpsAlternateDeliveryAddressParameter
                        {
                            Name    = order.OrderParcel.ParcelShopName,
                            Address = new UpsAddressParameter
                            {
                                AddressLine = order.OrderParcel.ParcelShopAddressLine,
                                City        = order.OrderParcel.ParcelShopCity,
                                Country     = order.OrderParcel.ParcelShopCountryCode,
                                PostalCode  = order.OrderParcel.ParcelShopPostalCode.ToString()
                            }
                        },
                        UpsService = CommonBuilder.MappingBothUpsServices.First(kvp => kvp.Key == order.OrderParcel.UpsServiceCode).Value
                    };
                    var ratingsResponse = await _upsClient.GetRatings(parameter);

                    if (ratingsResponse.Response.Error != null)
                    {
                        return(new UpdateOrderValidationResult(ratingsResponse.Response.Error.ErrorDescription));
                    }

                    shippingPrice = ratingsResponse.RatedShipment.TotalCharges.MonetaryValue;
                    payerEmail    = paypalBuyer.Value;
                    sellerEmail   = paypalSeller.Value;
                }
            }

            return(new UpdateOrderValidationResult(record, prods, payerEmail, sellerEmail, shippingPrice));
        }
        public void Product_id_not_empty_success()
        {
            var order = new UpdateOrderCommand(Guid.Empty, Guid.NewGuid(), new DateTime(), string.Empty);

            validator.ShouldNotHaveValidationErrorFor(p => p.ProductId, order);
        }
Example #20
0
 public async Task UpdateOrder(UpdateOrderCommand command)
 {
     await CommandBus.Execute(command);
 }
        public void Order_date_not_empty_success()
        {
            var order = new UpdateOrderCommand(Guid.Empty, Guid.Empty, DateTime.Now, string.Empty);

            validator.ShouldNotHaveValidationErrorFor(p => p.OrderDate, order);
        }
Example #22
0
        public async Task <IActionResult> Index(RaffleOrderViewModel model)
        {
            RaffleOrder order       = null;
            var         raffleEvent = raffleEventRepository.GetById(1);

            if (DateTime.UtcNow >= raffleEvent.CloseDate)
            {
                return(RedirectToAction("Index"));
            }

            if (HttpContext.Request.Cookies.ContainsKey(CookieKeys.RaffleOrderId))
            {
                var orderId = int.Parse(HttpContext.Request.Cookies[CookieKeys.RaffleOrderId]);
                order = (await mediator.Send(new GetRaffleOrderQuery {
                    OrderId = orderId
                }));
            }

            if ((order != null && !order.Lines.Any(x => x.Count > 0)) &&
                !model.RaffleItems.Any(x => x.Amount > 0))
            {
                var raffleItems = raffleItemRepository.GetAll()
                                  .Select(x => new RaffleItemModel
                {
                    Id                  = x.Id,
                    ItemNumber          = x.ItemNumber,
                    Title               = x.Title,
                    Description         = x.Description,
                    Category            = x.Category,
                    Sponsor             = x.Sponsor,
                    Cost                = x.Cost,
                    Value               = x.ItemValue,
                    ForOver21           = x.ForOver21,
                    LocalPickupOnly     = x.LocalPickupOnly,
                    NumberOfDraws       = x.NumberOfDraws,
                    IsAvailable         = x.IsAvailable,
                    TotalTicketsEntered = x.TotalTicketsEntered,
                    Pictures            = x.ImageUrls
                }).ToList();
                model = new RaffleOrderViewModel
                {
                    StartDate    = raffleEvent.StartDate,
                    CloseDate    = raffleEvent.CloseDate.Value.ToUniversalTime(),
                    Categories   = raffleItemRepository.GetUsedCategories().OrderBy(x => x).ToList(),
                    RaffleItems  = raffleItems,
                    ErrorMessage = "A raffle needs to be selected."
                };

                return(View(model));
            }

            if (ModelState.IsValid)
            {
                if (order != null)
                {
                    var lineItems = order.Lines.Select(x => new UpdateOrderCommand.RaffleOrderItem
                    {
                        RaffleItemId = x.RaffleItemId,
                        Name         = x.Name,
                        Price        = x.Price,
                        Count        = x.Count
                    }).ToList();
                    var newLineItems = model.RaffleItems
                                       .Where(x => x.Amount > 0)
                                       .Select(x => new UpdateOrderCommand.RaffleOrderItem
                    {
                        RaffleItemId = x.Id,
                        Name         = $"#{x.ItemNumber} {x.Title}",
                        Price        = x.Cost,
                        Count        = x.Amount
                    }).ToList();

                    lineItems.AddRange(newLineItems.Where(x => !lineItems.Any(y => y.RaffleItemId == x.RaffleItemId)));
                    foreach (var item in lineItems)
                    {
                        var newItem = newLineItems.FirstOrDefault(x => x.RaffleItemId == item.RaffleItemId);
                        if (newItem == null)
                        {
                            continue;
                        }

                        item.Price = newItem.Price;
                        item.Count = newItem.Count;
                    }

                    var updateOrder = new UpdateOrderCommand
                    {
                        OrderId          = order.Id,
                        ReplaceAll       = true,
                        RaffleOrderItems = lineItems
                    };
                    await mediator.Publish(updateOrder);
                }
                else
                {
                    var startRaffleOrder = new StartRaffleOrderQuery
                    {
                        RaffleOrderItems = model.RaffleItems
                                           .Where(x => x.Amount > 0)
                                           .Select(x => new StartRaffleOrderQuery.RaffleOrderItem
                        {
                            RaffleItemId = x.Id,
                            Name         = $"#{x.ItemNumber} {x.Title}",
                            Price        = x.Cost,
                            Count        = x.Amount
                        }).ToList()
                    };

                    var orderId = (await mediator.Send(startRaffleOrder));
                    order = (await mediator.Send(new GetRaffleOrderQuery {
                        OrderId = orderId
                    }));
                }

                HttpContext.Response.Cookies.Append(
                    CookieKeys.RaffleOrderId,
                    order.Id.ToString(),
                    new CookieOptions
                {
                    Secure   = true,
                    SameSite = SameSiteMode.Strict,
                    Expires  = new DateTimeOffset(DateTime.Now.AddDays(7))
                });

                return(RedirectToAction("CompleteRaffle", new { orderId = order.Id }));
            }

            return(View(model));
        }
        public void Description_empty_fail()
        {
            var order = new UpdateOrderCommand(Guid.Empty, Guid.Empty, new DateTime(), string.Empty);

            validator.ShouldHaveValidationErrorFor(p => p.Description, order);
        }
Example #24
0
        public async Task <IActionResult> Put([FromBody] UpdateOrderCommand command)
        {
            var result = await Mediator.Send(command);

            return(Ok(result));
        }
 public Task <string> UpdateOrder(UpdateOrderCommand updateRequest)
 {
     return(Task.FromResult(updateOrderInDatabase(updateRequest)));
 }
        public async Task <ActionResult <Unit> > Update(UpdateOrderCommand command)
        {
            await Mediator.Send(command);

            return(NoContent());
        }