public IHttpActionResult DeductStock(JObject jsonBody) { JObject products = (JObject)jsonBody["ProductInProductStockWasted"]; // this variable must be present in the javascript jsonBody.Remove("ProductInProductStockWasted"); ProductStockWasted stockWasted = jsonBody.ToObject <ProductStockWasted>(); // the job card object\ stockWasted.ApplicationUserId = User.Identity.GetUserId(); db.ProductStockWasteds.Add(stockWasted); db.SaveChanges(); // save it to db, to get the new stock id for further processing int productStockWastedId = stockWasted.ProductStockWastedId; // the foregin key to be used for the -> proudcts JEnumerable <JToken> tokens = (JEnumerable <JToken>)products.Children <JToken>(); foreach (JToken token in tokens) { JToken productJson = token.Children().First(); ProductInProductStockWasted productInstance = productJson.ToObject <ProductInProductStockWasted>(); productInstance.ProductStockWastedId = productStockWastedId; // add a product in wasted stock to the db db.ProductInProductStockWasteds.Add(productInstance); // decrease quantity in the products table Product product = db.Products.Find(productInstance.ProductId); if (product.StocksQuantity - productInstance.Quantity < 0) { // delete the already added stock wasted infor and return, user is trying to mess with us. db.ProductStockWasteds.Remove(stockWasted); db.SaveChanges(); return(StatusCode(HttpStatusCode.NotAcceptable)); } else { // reduce the stock from products table product.StocksQuantity = product.StocksQuantity - productInstance.Quantity; db.Entry(product).State = EntityState.Modified; } } db.SaveChanges(); return(StatusCode(HttpStatusCode.Created)); }
public IHttpActionResult DeductStock(JObject jsonBody) { JObject products = (JObject)jsonBody["ProductInProductStockWasted"]; // this variable must be present in the javascript jsonBody.Remove("ProductInProductStockWasted"); // get rid of extra data JEnumerable <JToken> tokens = (JEnumerable <JToken>)products.Children <JToken>(); // update each product in the stock foreach (JToken token in tokens) { JToken productJson = token.Children().First(); ProductInProductStockWasted productInstance = productJson.ToObject <ProductInProductStockWasted>(); // add a product in wasted stock to the db db.ProductInProductStockWasteds.Add(productInstance); // decrease quantity in the products table Product product = db.Products.Find(productInstance.ProductId); if (product.StocksQuantity - productInstance.Quantity < 0) { // as a business rule.. if the enterprise tried to deduct product's quantity to a negative value // let the product stock quantity be zero product.StocksQuantity = 0; db.Entry(product).State = EntityState.Modified; } else { // reduce the stock from products table product.StocksQuantity = product.StocksQuantity - productInstance.Quantity; db.Entry(product).State = EntityState.Modified; } } db.SaveChanges(); return(StatusCode(HttpStatusCode.Created)); }