Exemplo n.º 1
0
        public IActionResult CheckOut(ShoppingCartViewModel scvm)
        {
            double totalPrice = scvm.TotalPrice();

            if (!ModelState.IsValid)
            {
                return(View("ShoppingCart", scvm));
            }

            Address billAdd = scvm.Order.BillingAddress;

            scvm.Order.BillingAddressId = Helper.AddAddressToDbOrGetID(_dbContext, billAdd);

            if (scvm.ShippingEqualBilling || scvm.Order.BillingAddress == scvm.Order.ShippingAddress)
            {
                scvm.Order.ShippingAddressId = scvm.Order.BillingAddressId;
            }
            else
            {
                Address shipAdd = scvm.Order.ShippingAddress;
                scvm.Order.ShippingAddressId = Helper.AddAddressToDbOrGetID(_dbContext, shipAdd);
            }

            User user = scvm.Order.User;

            /*int? userId = _dbContext.Users
             *  .Where(u => u.UserName.Equals(user.UserName) && u.Email.Equals(user.Email) && u.Phone.Equals(user.Phone))
             *  .Select(u => (int?)u.UserId)
             *  .FirstOrDefault();*/

            var userAuthId = HttpContext.Session.Get <string>("userId");

            scvm.Order.UserId = Helper.GetUserIdById(_dbContext, userAuthId);

            /*if (userId.HasValue)
             *  //scvm.Order.UserId = userId.Value;
             * {
             *  var userAuthId = HttpContext.Session.Get<string>("userId");
             *  scvm.Order.UserId = Helper.GetUserIdById(_dbContext, userAuthId);
             * }
             * else
             * {
             *  _dbContext.Users.Add(user);
             *  _dbContext.SaveChanges();
             *  _dbContext.Entry(user).GetDatabaseValues();
             *  scvm.Order.UserId = user.UserId;
             * }*/

            (int orderId, bool updated) = Helper.AddOrderToDbOrGetId(_dbContext, scvm.Order);

            _myLogger.Add(orderId, "Order data accepted");

            if (updated)
            {
                Helper.UpdateOrderedBooksInDb(_dbContext, orderId, scvm.Basket);
            }
            else
            {
                Helper.AddOrderedBooksToDb(_dbContext, orderId, scvm.Basket);
            }

            return(RedirectToAction("Payment", new
            {
                orderId = orderId,
                totalPrice = scvm.TotalPrice()
            }));
        }