Пример #1
0
        public async Task <IActionResult> Create(int customerID, [FromForm] CartViewModel cartVm)
        {
            try
            {
                if (customerID == 0)
                {
                    User user = await _userManager.GetUserAsync(User);

                    customerID = user.CustomerID.Value;
                }

                Invoice invoice = new Invoice
                {
                    CustomerID = customerID
                };

                foreach (var cartItem in cartVm.Items)
                {
                    int?songID  = null;
                    int?albumID = null;

                    switch (cartItem.Category)
                    {
                    case nameof(Song):
                        songID = cartItem.ItemID;
                        break;

                    case nameof(Album):
                        albumID = cartItem.ItemID;
                        break;

                    default:
                        break;
                    }

                    invoice.AddInvoiceDetail(songID, albumID, cartItem.Price);
                }

                await _context.AddAsync(invoice);


                var page = (string)TempData["previousPage"];
                if (page.Equals("checkoutFromCart", StringComparison.OrdinalIgnoreCase))
                {
                    var cartItems = _context.Customers.Where(c => c.ID == customerID).SelectMany(c => c.Cart.CartItems);
                    _context.RemoveRange(cartItems);
                }
                else
                {
                    HttpContext.Session.Remove(SESSION_KEY);
                }



                await _context.SaveChangesAsync();

                return(RedirectToAction("Success", new { invoiceID = invoice.ID }));
            }
            catch (Exception e)
            {
                return(RedirectToAction("Create"));
            }
        }