public async Task<int> CreateOrderFromCart(string cartId, Order order, string stripeToken, string stripeSecretKey, CancellationToken cancellationToken = new CancellationToken()) { Serilog.Log.Logger.Debug($"{nameof(this.EmptyCart)} for cart id '{cartId}'"); using (var unitOfWork = this.unitOfWorkFunc()) { var orderRepository = unitOfWork.Value.Repository<Order>(); var orderDetailsRepository = unitOfWork.Value.Repository<OrderDetail>(); var cartItemsRepository = unitOfWork.Value.Repository<CartItem>(); var albumRepository = unitOfWork.Value.Repository<Album>(); decimal orderTotal = 0; orderRepository.Add(order); var cartItems = await cartItemsRepository.Get(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 albumRepository.Get().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; orderDetailsRepository.Add(orderDetail); } // Set the order's total to the orderTotal count order.Total = orderTotal; order.TransactionId = await ExecuteTransaction(stripeToken, stripeSecretKey, Convert.ToInt32(orderTotal*100)); // Empty the shopping cart var cartItemsToClear = await cartItemsRepository.Get(cart => cart.CartId == cartId).ToArrayAsync(cancellationToken); cartItemsRepository.DeleteRange(cartItemsToClear); // Save all the changes await unitOfWork.Value.SaveChangesAsync(cancellationToken); return order.OrderId; } }
public async Task<IActionResult> CreateOrderFromCart([FromBody] OrderViewModel 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 ?? "NA", Username = GetCartId(), Total = 0 }; // Add it to the order var viewModel = await _cartCommandService.CreateOrderFromCart(GetCartId(), addedOrder, order.StripeToken, _appSettings.Stripe.SecretKey); // Return the order json return Json(viewModel); }