public async Task<IHttpActionResult> PutCartContent(int userId, CartContentModel cartContent) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (userId != cartContent.userId) { return BadRequest("You are not authorized to access to this user's basket"); } if (!CartContentExists(userId, cartContent.productId)) { return NotFound(); } if (cartContent.productQuantity < 1) return BadRequest("Please choose a positive product quantity!"); //Verify if the quantity in the cartContent if inferior to the available quantity for the product int enoughProductInStock = db.product.Where(p => p.productId == cartContent.productId).FirstAsync().Result.availableQty.Value; if (cartContent.productQuantity > enoughProductInStock) { return BadRequest(string.Format("There are only {0} products left!", enoughProductInStock)); } db.Entry(new CartContent() { userId = cartContent.userId, productId = cartContent.productId, productQuantity = cartContent.productQuantity }).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { throw; } return StatusCode(HttpStatusCode.NoContent); }
public async Task<IHttpActionResult> PostCartContent(int userId,CartContentModel cartContent) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (userId != cartContent.userId) //verify that we are creating a cartcontent into the rigth user's basket { return BadRequest(); } if (cartContent.productQuantity < 0) return BadRequest("Please choose a positive product quantity!"); if (!CartContentExists(userId, cartContent.productId)) { //Verify if the quantity in the cartContent if inferior to the available quantity for the product int enoughProductInStock = db.product.Where(p => p.productId == cartContent.productId).FirstAsync().Result.availableQty.Value; if (cartContent.productQuantity > enoughProductInStock) { return BadRequest(string.Format("There are only {0} products left!", enoughProductInStock)); } db.CartContent.Add(new CartContent() { userId = cartContent.userId, productId = cartContent.productId, productQuantity = cartContent.productQuantity }); } else return BadRequest("This product is already in your cart"); try { await db.SaveChangesAsync(); } catch (DbUpdateException) { throw; } return Created("api/users/basket", cartContent); }