public string ListShoppingCart(int customerId) { FileStream locker = _FileLocker.LockObj(_customerAndCartLockerFile); try { GetShoppingCarts(); 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."); } JsonSuperMarketRepository superMarketRepository = new JsonSuperMarketRepository(); 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) : ""); } finally { _FileLocker.UnlockObj(locker); } }
public Receipt CheckOut(int customerId) { var locker = _FileLocker.LockObj(_customerAndCartLockerFile); try { GetShoppingCarts(); 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."); } JsonSuperMarketRepository superMarketRepository = new JsonSuperMarketRepository(); var receipt = superMarketRepository.Checkout(shoppingCart.ProductItems); shoppingCart.ProductItems.Clear(); _jsonHandler.SaveRecords(_shoppingCartJsonFile, ShoppingCarts); return(receipt); } finally { _FileLocker.UnlockObj(locker); } }
public void AddToCart(int customerId, int productId, int count) { if (count <= 0) { throw new ArgumentOutOfRangeException($"Cannot add {count} product to cart."); } JsonSuperMarketRepository jsonSuperMarketRepository = new JsonSuperMarketRepository(); var stockCount = jsonSuperMarketRepository.GetStock(productId); if (count > stockCount) { throw new InvalidOperationException($"Product {productId} is out of stock or not enough."); } FileStream locker = _FileLocker.LockObj(_customerAndCartLockerFile); try { GetShoppingCarts(); 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; } _jsonHandler.SaveRecords(_shoppingCartJsonFile, ShoppingCarts); } finally { _FileLocker.UnlockObj(locker); } }