public void TestOrderDispatchedHandler() { //SETUP var options = SqliteInMemory.CreateOptions <ExampleDbContext>(); var context = options.CreateAndSeedDbWithDiForHandlers <OrderCreatedHandler>(); { var itemDto = new BasketItemDto { ProductName = context.ProductStocks.OrderBy(x => x.NumInStock).First().ProductName, NumOrdered = 2, ProductPrice = 123 }; var order = new Order("test", DateTime.Now, new List <BasketItemDto> { itemDto }); context.Add(order); context.SaveChanges(); //ATTEMPT order.OrderReadyForDispatch(DateTime.Now.AddDays(10)); context.SaveChanges(); //VERIFY order.TotalPriceNoTax.ShouldEqual(2 * 123); order.TaxRatePercent.ShouldEqual(9); order.GrandTotalPrice.ShouldEqual(order.TotalPriceNoTax * (1 + order.TaxRatePercent / 100)); context.ProductStocks.OrderBy(x => x.NumInStock).First().NumAllocated.ShouldEqual(0); context.ProductStocks.OrderBy(x => x.NumInStock).First().NumInStock.ShouldEqual(3); } }
public override async Task <ActionResult <BasketDto> > Handle(CreateOrGetUnconfirmedBasketCommand command) { var basket = await _createOrGetUnconfirmedBasketQuery.Query(command); if (basket == null) { // if basket is null then send user is not authenticated error // TODO: take this info from phrases return(Error()); } var basketDto = new BasketDto(); basketDto.Id = basket.Id; if (basket.BasketItems.IsNullOrEmpty()) { return(Ok(basketDto)); } foreach (var basketItem in basket.BasketItems) { var basketItemDto = new BasketItemDto(); var productDto = (await _getProductQueryHandler.Handle(new GetProductCommand(basketItem.ProductId.Value, _workContext.WorkingLanguageId))).Object; basketItemDto.Id = basketItem.Id; basketItemDto.Product = productDto; basketItemDto.Price = basketItem.Price; basketItemDto.ProductDetailId = basketItem.ProductDetailId; basketItemDto.Quantity = basketItem.Quantity; basketDto.BasketItems.Add(basketItemDto); } return(Ok(basketDto)); }
public void TestOrderCreatedHandlerLogs() { //SETUP var options = SqliteInMemory.CreateOptions <ExampleDbContext>(); var logs = new List <LogOutput>(); var context = options.CreateAndSeedDbWithDiForHandlers <OrderCreatedHandler>(logs); { var itemDto = new BasketItemDto { ProductName = context.ProductStocks.OrderBy(x => x.NumInStock).First().ProductName, NumOrdered = 2, ProductPrice = 123 }; //ATTEMPT var order = new Order("test", DateTime.Now, new List <BasketItemDto> { itemDto }); context.Add(order); context.SaveChanges(); //VERIFY logs.Count.ShouldEqual(3); logs[0].Message.ShouldEqual("B1: About to run a BeforeSave event handler Infrastructure.BeforeEventHandlers.OrderCreatedHandler."); logs[1].Message.ShouldEqual("B1: About to run a BeforeSave event handler Infrastructure.BeforeEventHandlers.AllocateProductHandler."); logs[2].Message.ShouldEqual("B2: About to run a BeforeSave event handler Infrastructure.BeforeEventHandlers.TaxRateChangedHandler."); } }
public async Task TestOrderCreatedHandlerNotEnoughStockStatus() { //SETUP var options = SqliteInMemory.CreateOptions <ExampleDbContext>(); var context = options.CreateAndSeedDbWithDiForHandlers <OrderCreatedHandler>(); { var itemDto = new BasketItemDto { ProductName = context.ProductStocks.OrderBy(x => x.NumInStock).First().ProductName, NumOrdered = 10, ProductPrice = 123 }; //ATTEMPT var order = new Order("test", DateTime.Now, new List <BasketItemDto> { itemDto }); context.Add(order); var status = await context.SaveChangesWithStatusAsync(); //VERIFY status.IsValid.ShouldBeFalse(); status.GetAllErrors().ShouldEqual("I could not accept this order because there wasn't enough Product1 in stock."); } }
public async Task TestOrderCreatedHandlerExceptionNotEnoughStock() { //SETUP var options = SqliteInMemory.CreateOptions <ExampleDbContext>(); var context = options.CreateAndSeedDbWithDiForHandlers <OrderCreatedHandler>(); { var itemDto = new BasketItemDto { ProductName = context.ProductStocks.OrderBy(x => x.NumInStock).First().ProductName, NumOrdered = 10, ProductPrice = 123 }; //ATTEMPT var order = new Order("test", DateTime.Now, new List <BasketItemDto> { itemDto }); context.Add(order); var ex = await Assert.ThrowsAsync <GenericEventRunnerStatusException>(async() => await context.SaveChangesAsync()); //VERIFY ex.Message.ShouldEqual(@"Failed with 1 error I could not accept this order because there wasn't enough Product1 in stock."); } }
public async Task AddToBasketAsync(BasketItemDto basketItemDto) { try { var request = _daprClient.CreateInvokeMethodRequest( HttpMethod.Post, _configuration["DaprConfiguration:AppId_Basket"], _basketApiDefaultMethod, basketItemDto ); var response = await _daprClient.InvokeMethodWithResponseAsync(request); if (!response.IsSuccessStatusCode) { _logger.LogCritical("Failed to add items to the basket.", response); throw new Exception($"Failed to add items to the basket.: \n {response.StatusCode} : {response.ReasonPhrase}"); } } catch (Exception ex) { throw; } _logger.LogInformation("An item was added to the basket.", basketItemDto); }
public async Task TestOrderCreatedHandler() { //SETUP var options = SqliteInMemory.CreateOptions <ExampleDbContext>(); var context = options.CreateAndSeedDbWithDiForHandlers <OrderCreatedHandler>(); { var itemDto = new BasketItemDto { ProductName = context.ProductStocks.OrderBy(x => x.NumInStock).First().ProductName, NumOrdered = 2, ProductPrice = 123 }; //ATTEMPT var order = new Order("test", DateTime.Now, new List <BasketItemDto> { itemDto }); context.Add(order); var numUpdates = await context.SaveChangesAsync(); //VERIFY numUpdates.ShouldEqual(3); order.TotalPriceNoTax.ShouldEqual(2 * 123); order.TaxRatePercent.ShouldEqual(4); order.GrandTotalPrice.ShouldEqual(order.TotalPriceNoTax * (1 + order.TaxRatePercent / 100)); context.ProductStocks.OrderBy(x => x.NumInStock).First().NumAllocated.ShouldEqual(2); } }
public async Task TestOrderDispatchedHandlerLogs() { //SETUP var options = SqliteInMemory.CreateOptions <ExampleDbContext>(); var logs = new List <LogOutput>(); var context = options.CreateAndSeedDbWithDiForHandlers <OrderCreatedHandler>(logs); { var itemDto = new BasketItemDto { ProductName = context.ProductStocks.OrderBy(x => x.NumInStock).First().ProductName, NumOrdered = 2, ProductPrice = 123 }; var order = new Order("test", DateTime.Now, new List <BasketItemDto> { itemDto }); context.Add(order); await context.SaveChangesAsync();; logs.Clear(); //ATTEMPT order.OrderReadyForDispatch(DateTime.Now.AddDays(10)); await context.SaveChangesAsync();; //VERIFY logs.Count.ShouldEqual(3); logs[0].Message.ShouldEqual("B1: About to run a BeforeSave event handler Infrastructure.BeforeEventHandlers.OrderDispatchedBeforeHandler."); logs[1].Message.ShouldEqual("B2: About to run a BeforeSave event handler Infrastructure.BeforeEventHandlers.TaxRateChangedHandler."); logs[2].Message.ShouldEqual("A1: About to run a AfterSave event handler Infrastructure.AfterEventHandlers.OrderReadyToDispatchAfterHandler."); } }
private async Task <bool> IsBasketItemValid(BasketItemDto newItem) { if (newItem != null && NameIsValid(newItem.ProductName) && PriceIsValid(newItem.Price) && QuantityIsValid(newItem.Quantity)) { return(true); } return(false); }
public async Task UpdateAsync(BasketItemDto basket) { var filter = Builders <BasketItem> .Filter.Eq("productId", basket.ProductId); var update = Builders <BasketItem> .Update .Set("productName", basket.ProductName) .Set("quantity", basket.Quantity) .Set("unitPrice", basket.UnitPrice); await Collection.UpdateOneAsync(filter, update); }
public async Task <IActionResult> AddItem([Bind("ProductId,Quantity")] BasketItemDto newItem) { try { await _basketFacade.AddItem(newItem); } catch (HttpRequestException) { _logger.LogWarning("Exception Occured using Basket Facade"); } return(RedirectToAction("Items", "Products")); }
public async Task <ActionResult <FoodItemViewModel> > RemoveOneItem(BasketItemDto basketItem) { var userId = this.User.FindFirst(ClaimTypes.NameIdentifier).Value; switch (basketItem.Type.ToLower()) { case "drink": return(await this.basketService.RemoveDrinkAsync(basketItem.Id, userId, 1)); case "dish": return(await this.basketService.RemoveDishAsync(basketItem.Id, userId, 1)); } return(null); }
public BasketDto BuildBasketDto(StormBasket basket) { BasketDto dto = new BasketDto(); dto.ExternalId = basket.Id.ToString(); dto.Items = new List <IBasketItem>(); dto.Shipping = basket.Summary.Freigt.Amount; dto.ShippingInclVat = basket.Summary.Freigt.Amount + basket.Summary.Freigt.Vat; dto.Total = basket.Summary.Total.Amount; dto.TotalInclVat = basket.Summary.Total.Vat + dto.Total; dto.TotalVat = basket.Summary.Total.Vat; dto.NumberOfItems = 0; foreach (var stormItem in basket.Items) { if (stormItem.Type.HasValue && _configuration["Storm:ExcludeTypeFromBasket"].Contains(stormItem.Type.Value.ToString())) { continue; } decimal?priceStandard = null; if (stormItem.PriceStandard.HasValue && stormItem.PriceStandard.Value > 0) { priceStandard = stormItem.PriceStandard.Value; } BasketItemDto itemdto = new BasketItemDto(); itemdto.ExternalId = stormItem.Id.ToString(); itemdto.ImageUrl = _configuration["Storm:ImagePrefix"] + stormItem.ImageKey; itemdto.Name = stormItem.Name; itemdto.PartNo = stormItem.PartNo; itemdto.Quantity = Convert.ToInt32(stormItem.Quantity); itemdto.Price = stormItem.PriceDisplay.Value; itemdto.PricePrevious = priceStandard; itemdto.VatRate = stormItem.VatRate.Value; itemdto.Url = stormItem.UniqueName; dto.NumberOfItems += Convert.ToInt32(itemdto.Quantity); dto.Items.Add(itemdto); } return(dto); }
private async Task <IActionResult> CreateOrEditBasketItem(BasketItemDto basketItem) { if (await _orderRepository.CustomerExists(basketItem.CustomerId)) { if (await _orderRepository.IsCustomerActive(basketItem.CustomerId)) { bool itemIsInBasket = await _orderRepository.IsItemInBasket(basketItem.CustomerId, basketItem.ProductId); if (itemIsInBasket && basketItem.Quantity == 0) { return(await Delete(basketItem.CustomerId, basketItem.ProductId)); } if (await IsBasketItemValid(basketItem)) { if (await _orderRepository.ProductExists(basketItem.ProductId)) { if (itemIsInBasket) { if (await _orderRepository.EditBasketItem(_mapper.Map <BasketItemRepoModel>(basketItem))) { return(Ok()); } } else { if (await _orderRepository.AddBasketItem(_mapper.Map <BasketItemRepoModel>(basketItem))) { return(Ok()); } } return(NotFound()); } return(NotFound()); } return(UnprocessableEntity()); } return(Forbid()); } return(NotFound()); }
public async Task TestOrderCreatedHandlerNotEnoughStockStatusThenAgainToCheckOriginalEventsCleared() { //SETUP var options = SqliteInMemory.CreateOptions <ExampleDbContext>(); var logs = new List <LogOutput>(); var context = options.CreateAndSeedDbWithDiForHandlers <OrderCreatedHandler>(logs); { var itemDto = new BasketItemDto { ProductName = context.ProductStocks.OrderBy(x => x.NumInStock).First().ProductName, NumOrdered = 10, ProductPrice = 123 }; var order1 = new Order("test", DateTime.Now, new List <BasketItemDto> { itemDto }); context.Add(order1); (await context.SaveChangesWithStatusAsync()).IsValid.ShouldBeFalse(); //ATTEMPT logs.Clear(); itemDto.NumOrdered = 2; var order2 = new Order("test", DateTime.Now, new List <BasketItemDto> { itemDto }); context.Add(order2); var status = await context.SaveChangesWithStatusAsync(); //VERIFY status.IsValid.ShouldBeTrue(status.GetAllErrors()); logs.Count.ShouldEqual(3); logs[0].Message.ShouldEqual("B1: About to run a BeforeSave event handler Infrastructure.BeforeEventHandlers.OrderCreatedHandler."); logs[1].Message.ShouldEqual("B1: About to run a BeforeSave event handler Infrastructure.BeforeEventHandlers.AllocateProductHandler."); logs[2].Message.ShouldEqual("B2: About to run a BeforeSave event handler Infrastructure.BeforeEventHandlers.TaxRateChangedHandler."); } }
public void TestCreateOrderCheckEventsProduced() { //SETUP var options = SqliteInMemory.CreateOptions <ExampleDbContext>(); var context = options.CreateAndSeedDbWithDiForHandlers <OrderCreatedHandler>(); { var itemDto = new BasketItemDto { ProductName = context.ProductStocks.OrderBy(x => x.NumInStock).First().ProductName, NumOrdered = 2, ProductPrice = 123 }; //ATTEMPT var order = new Order("test", DateTime.Now, new List <BasketItemDto> { itemDto }); //VERIFY order.TotalPriceNoTax.ShouldEqual(2 * 123); order.GetBeforeSaveEventsThenClear().Select(x => x.GetType()) .ShouldEqual(new [] { typeof(OrderCreatedEvent), typeof(AllocateProductEvent) }); } }
/// <summary> /// /// </summary> /// <param name="request"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task <IResponse> Handle(RedisAddBasketItemCommand request, CancellationToken cancellationToken) { var productId = request.Product.Product.Id; var stock = await _stockProvider.GetStockForProduct(productId); var quantity = request.Quantity; if (quantity > stock) { return(new ErrorResponse(HttpStatusCode.BadRequest, _localized.GetString("CannotGreaterThanTheStock"))); } var basketExpiryDate = TimeSpan.FromDays(_basketRules.ExpirationDurationInDays); var basketItems = await _cacheService.GetAsync <List <BasketItemDto> >(request.CustomerId); if (basketItems != null && basketItems.Any()) { var basketQuantity = basketItems.Where(x => x.Product.Product.Id.Equals(productId)) .Sum(x => x.Quantity) + quantity; if (basketQuantity > stock) { return(new ErrorResponse(HttpStatusCode.BadRequest, _localized.GetString("CannotGreaterThanTheStock"))); } var existItem = basketItems.SingleOrDefault(x => x.Product.Product.Id.Equals(productId)); if (existItem != null) { existItem.Quantity += quantity; } else { var productInfo = _mapper.Map <ProductInfoDto>(request.Product); var item = new BasketItemDto { Product = productInfo, Quantity = quantity }; basketItems.Add(item); } var set = _cacheService.Set(request.CustomerId, basketItems, basketExpiryDate); if (set) { return(new SuccessResponse(HttpStatusCode.OK, _localized.GetString("SuccessfullyAdded"))); } return(new ErrorResponse(HttpStatusCode.BadRequest, _localized.GetString("NotAdded"))); } var basketItem = _mapper.Map <BasketItemDto>(request.Product); basketItem.Quantity = quantity; var setItem = _cacheService.Set(request.CustomerId, basketItem, basketExpiryDate); if (setItem) { return(new SuccessResponse(HttpStatusCode.OK, _localized.GetString("SuccessfullyAdded"))); } return(new ErrorResponse(HttpStatusCode.BadRequest, _localized.GetString("NotAdded"))); }
public async Task <IActionResult> Edit([FromRoute] int customerId, [FromBody] BasketItemDto editedItem) { return(await CreateOrEditBasketItem(editedItem)); }
public async Task <IActionResult> Create([FromBody] BasketItemDto newItem) { return(await CreateOrEditBasketItem(newItem)); }
public Task AddAsync(BasketItemDto basket) { throw new NotImplementedException(); }