public decimal GetDrinkItemPrice(DrinkCartDetail drinkCartDetail) { var vendingItems = JsonConvert .DeserializeObject <VendingMachineViewModel>(File.ReadAllText(_productConfig.Value.BaseAddress)); var sizePrice = vendingItems.Drink.Sizes .Where(x => x.Code == drinkCartDetail.SizeCode) .FirstOrDefault().Price; var creamPrice = vendingItems.Drink.Cream.Price; var sugarPrice = vendingItems.Drink.Sugar.Price; return(sizePrice + (creamPrice * drinkCartDetail.CreamQuantity) + (sugarPrice * drinkCartDetail.SugarQuantity)); }
public IActionResult AddToCart(AddToCartModel model) { var cart = new CartViewModel(); var drinkItem = new DrinkCartDetail { DrinkType = model.DrinkType, SizeCode = model.Size, CreamQuantity = model.CreamQuantity, SugarQuantity = model.SugarQuantity }; // Check if cart cookie exists var cookieKey = Constants.CookieName; var cookie = HttpContext.Request.Cookies.ContainsKey(cookieKey) ? HttpContext.Request.Cookies[cookieKey] : string.Empty; // If cookie exists - check if drink combination exists // Yes - Add to quantity // No - Add to cart if (!string.IsNullOrEmpty(cookie)) { cart = JsonConvert.DeserializeObject <CartViewModel>(cookie); var sameCartItem = cart.CartItems .Where(x => x.DrinkDetails.CreamQuantity == drinkItem.CreamQuantity && x.DrinkDetails.DrinkType == drinkItem.DrinkType && x.DrinkDetails.SizeCode == drinkItem.SizeCode && x.DrinkDetails.SugarQuantity == drinkItem.SugarQuantity); if (sameCartItem != null && sameCartItem.Count() > 0) { cart.CartItems.Where(x => x.DrinkDetails.CreamQuantity == drinkItem.CreamQuantity && x.DrinkDetails.DrinkType == drinkItem.DrinkType && x.DrinkDetails.SizeCode == drinkItem.SizeCode && x.DrinkDetails.SugarQuantity == drinkItem.SugarQuantity).FirstOrDefault().Quantity += model.Quantity; } else { cart.CartItems.Add(new CartItem { DrinkDetails = drinkItem, SubTotal = _homeService.GetDrinkItemPrice(drinkItem), Quantity = model.Quantity }); } } else { // Add to new cart item if no cart exists cart.CartItems.Add(new CartItem { DrinkDetails = drinkItem, SubTotal = _homeService.GetDrinkItemPrice(drinkItem), Quantity = model.Quantity }); } // Get cart total cart.TotalCost = cart.CartItems.Sum(x => x.Total); // Create/Update Cookie var cartJson = JsonConvert.SerializeObject(cart); HttpContext.Response.Cookies.Append(cookieKey, cartJson); var vendingMachine = _homeService.GetVendingItems(); vendingMachine.Cart = cart; return(View("Views/Home/Index.cshtml", vendingMachine)); }