public async Task<IActionResult> CreateOrderFromCart([FromBody] OrderViewModel order, CancellationToken requestAborted) { _logger.LogInformation("POST request for 'api/order/'"); var addedOrder = new Order { Address = order.Address, City = order.City, Country = order.Country, Email = order.Email, FirstName = order.FirstName, LastName = order.LastName, OrderDate = DateTime.Today, Phone = order.Phone, PostalCode = order.PostalCode, State = order.State, Username = GetCartId(), Total = 0 }; // Add it to the order var viewModel = await _cartCommandService.CreateOrderFromCart(GetCartId(), addedOrder, requestAborted); // Return the order json return Json(viewModel); }
public async Task<int> CreateOrderFromCart(string cartId, Order order, CancellationToken cancellationToken = new CancellationToken()) { Serilog.Log.Logger.Debug($"{nameof(this.CreateOrderFromCart)} for cart id '{cartId}' and order dated {order.OrderDate.ToShortDateString()}"); using (var dbContext = this._dbContextFactory.Create()) { decimal orderTotal = 0; dbContext.Orders.Add(order); var cartItems = await dbContext.CartItems.Where(cart => cart.CartId == cartId).Include(c => c.Album).ToListAsync(cancellationToken); // Iterate over the items in the cart, adding the order details for each foreach (var item in cartItems) { //var album = _db.Albums.Find(item.AlbumId); var album = await dbContext.Albums.SingleAsync(a => a.AlbumId == item.AlbumId, cancellationToken); var orderDetail = new OrderDetail { AlbumId = item.AlbumId, OrderId = order.OrderId, UnitPrice = album.Price, Quantity = item.Count, }; // Set the order total of the shopping cart orderTotal += (item.Count * album.Price); dbContext.OrderDetails.Add(orderDetail); } // Set the order's total to the orderTotal count order.Total = orderTotal; // Empty the shopping cart var cartItemsToClear = await dbContext.CartItems.Where(cart => cart.CartId == cartId).ToArrayAsync(cancellationToken); dbContext.CartItems.RemoveRange(cartItemsToClear); // Save all the changes await dbContext.SaveChangesAsync(cancellationToken); return order.OrderId; } }