public string ListShoppingCart(int customerId) { var shoppingCart = _shoppingCarts.FirstOrDefault(s => s.CustomerId == customerId); if (shoppingCart == null) { throw new InvalidOperationException("Cannot find the related shopping cart."); } if (shoppingCart.ProductItems == null || shoppingCart.ProductItems.Count <= 0) { throw new InvalidOperationException("There is nothing in the shopping cart."); } InMemorySuperMarketRepository superMarketRepository = new InMemorySuperMarketRepository(); List <string> results = new List <string>(); foreach (ProductItem s in shoppingCart.ProductItems) { var product = superMarketRepository.FindProduct(s.ProductId); results.Add($"{product?.ToString() ?? "Product Info : Unknown"} Count = {s.Count}"); } return(results.Count > 0 ? string.Join(Environment.NewLine, results) : ""); }
public void AddToCart(int customerId, int productId, int count) { if (count <= 0) { throw new ArgumentOutOfRangeException($"Cannot add {count} product to cart."); } InMemorySuperMarketRepository _superMarketRepository = new InMemorySuperMarketRepository(); var stockCount = _superMarketRepository.GetStock(productId); if (count > stockCount) { throw new InvalidOperationException($"Product {productId} is out of stock or not enough."); } lock (_shoppingCartsLocker) { var shoppingCart = _shoppingCarts.FirstOrDefault(s => s.CustomerId == customerId); if (shoppingCart == null) { throw new InvalidOperationException("Cannot find the related shopping cart."); } var item = shoppingCart.ProductItems.FirstOrDefault(i => i.ProductId == productId); if (item == null) { shoppingCart.ProductItems.Add(new ProductItem() { ProductId = productId, Count = count }); } else { item.Count += count; } } }
public Receipt CheckOut(int customerId) { lock (_shoppingCartsLocker) { var shoppingCart = _shoppingCarts.FirstOrDefault(s => s.CustomerId == customerId); if (shoppingCart == null) { throw new InvalidOperationException("Cannot find the related shopping cart."); } if (shoppingCart.ProductItems == null || shoppingCart.ProductItems.Count <= 0) { throw new InvalidOperationException("There is nothing in the shopping cart."); } InMemorySuperMarketRepository superMarketRepository = new InMemorySuperMarketRepository(); var receipt = superMarketRepository.Checkout(shoppingCart.ProductItems); shoppingCart.ProductItems.Clear(); return(receipt); } }