public async Task <IActionResult> CreateOrder([FromBody] MakeOrderRootObjectDTO model) { var email = model.Info.Email; var currentUser = userManager.Users.SingleOrDefault(e => e.Email == email); if (currentUser == null) { ModelState.AddModelError(string.Empty, "PleaseLogin"); return(Unauthorized()); } var order = new Order { ReservationTime = model.Info.ReservationTime, TakeAway = false, ApplicationUserId = currentUser.Id }; context.Orders.Add(order); foreach (var product in model.Products) { var productId = product.Id; var productQ = product.Quantity; var currentProduct = context.Products.Where(e => e.Id == productId).SingleOrDefault(); var currentProduct2 = context.Products.Where(e => e.Id == productId) .Select(p => new { Id = p.Id, Name = p.Name, Price = p.Price, DiscountPrice = p.Discount != null ? p.Discount.DiscountedPrice : 0, }).SingleOrDefault(); var orderProductItem = new OrderProduct() { Order = order, ProductId = currentProduct2.Id, NetPrice = currentProduct2.DiscountPrice > 0 ? currentProduct2.DiscountPrice : currentProduct2.Price, Quantity = productQ }; await context.OrderProducts.AddAsync(orderProductItem); } order.TotalPrice = order.OrderProducts.Sum(op => op.CalculatedPrice); context.SaveChanges(); return(Created("GetOrder", new { id = order.Id })); }
public async Task <IActionResult> PostOrder([FromBody] MakeOrderRootObjectDTO model) { var currentUser = await userManager.GetUserAsync(HttpContext.User); if (currentUser == null) { ModelState.AddModelError(string.Empty, "PleaseLogin"); return(Unauthorized()); } var currentUserId = userManager.GetUserId(HttpContext.User); //Create an order and assign the user to it var order = new Order { ReservationTime = model.Info.ReservationTime, TakeAway = false, ApplicationUserId = currentUser.Id }; _context.Orders.Add(order); var listOfOrderProducts = new List <OrderProduct>(); //Iteratate selected products by the user, check quantity and discount prices and map them with the order foreach (var product in model.Products) { var productId = product.Id; var productQ = product.Quantity; var currentProduct = _context.Products.Where(e => e.Id == productId) .Select(p => new { Id = p.Id, Name = p.Name, Price = p.Price, DiscountPrice = p.Discount != null ? p.Discount.DiscountedPrice : 0 }).SingleOrDefault(); if (currentProduct == null) { return(BadRequest("No product with such Id was found.")); } var orderProductItem = new OrderProduct() { Order = order, ProductId = currentProduct.Id, NetPrice = currentProduct.DiscountPrice > 0 ? currentProduct.DiscountPrice : currentProduct.Price, Quantity = productQ }; listOfOrderProducts.Add(orderProductItem); } await _context.OrderProducts.AddRangeAsync(listOfOrderProducts); //Sum the Total Price for the Order order.TotalPrice = order.OrderProducts.Sum(op => op.CalculatedPrice); _context.SaveChanges(); return(Created("GetOrder", new { id = order.Id })); }