public IHttpActionResult AddItemToOrder(long userId, long productId) { var cart = db.Orders.FirstOrDefault(it => it.StatusUpdates.Count == 1 && it.UserID == userId); if (cart == null) { var user = db.Users.FirstOrDefault(it => it.UserID == userId); if (user == null) { return(NotFound()); } var status = new StatusUpdate { Date = DateTime.Now, Status = Status.Cart }; var newOrder = new Core.Model.Order { User = user }; newOrder.StatusUpdates.Add(status); db.Orders.Add(newOrder); db.SaveChanges(); cart = db.Orders.FirstOrDefault(it => it.StatusUpdates.Count == 1 && it.UserID == userId); } if (cart.ConvertToDTO().Status != Status.Cart) { return(Ok("Order is already completed")); } var product = db.Products.FirstOrDefault(it => it.ProductId == productId); if (cart == null) { return(NotFound()); } var orderItem = cart.OrderItems.FirstOrDefault(it => it.ProductId == productId); if (orderItem != null) { orderItem.Count++; db.SaveChanges(); return(Ok(new { order = cart.ConvertToDTO() })); } var newOrderItem = new BB.Core.Model.OrderItem(); newOrderItem.Order = cart; newOrderItem.Product = product; newOrderItem.Count = 1; newOrderItem.PricePerItem = product.Price; db.OrderItems.Add(newOrderItem); db.SaveChanges(); return(Ok(new { order = cart.ConvertToDTO() })); }
public static OrderItem ConvertToDTO(this BB.Core.Model.OrderItem entity) { return(new OrderItem() { OrderId = entity.OrderId, ProductId = entity.ProductId, Count = entity.Count, PricePerItem = entity.PricePerItem, Product = entity.Product.ConvertToShortDTO(), }); }
public IHttpActionResult GetUpdateOrder(Guid orderId, long productId, int?ammount) { if (ammount.HasValue && ammount.Value == 0) { return(Ok("Cannot order zero items")); } var order = db.Orders.FirstOrDefault(it => it.OrderId == orderId); if (order == null) { return(Ok("No order found")); } if (order.ConvertToDTO().Status != Status.Cart) { return(Ok("Order is already completed")); } var product = db.Products.FirstOrDefault(it => it.ProductId == productId); if (order == null) { return(Ok("No product found")); } var orderItem = order.OrderItems.FirstOrDefault(it => it.ProductId == productId); if (orderItem != null) { orderItem.Count = ammount.HasValue ? ammount.Value : 1; return(Ok(new { order = order.ConvertToDTO() })); } var newOrder = new BB.Core.Model.OrderItem(); newOrder.Order = order; newOrder.Product = product; newOrder.Count = ammount.HasValue ? ammount.Value : 1; newOrder.PricePerItem = product.Price; db.OrderItems.Add(newOrder); db.SaveChanges(); return(Ok(new { order = newOrder.Order.ConvertToDTO() })); }