public IActionResult TestMethod(CartDetail cd)
 {
     @ViewBag.Message = "Hello from the test controller" + cd.CartDetailID;
     return(View());
 }
Exemplo n.º 2
0
        public async Task <IActionResult> DeleteItem(int id)
        {
            List <CartItemViewModel> cartItem = new List <CartItemViewModel>();

            //đã đăng nhập
            if (HttpContext.Session.GetInt32("IdTaiKhoan").HasValue)
            {
                CartDetail cartDetail = await(from c in _context.Carts
                                              join cd in _context.CartDetails
                                              on c.Id equals cd.Cart_Id
                                              where cd.Id == id & c.User_Id == HttpContext.Session.GetInt32("IdTaiKhoan").Value
                                              select cd).SingleOrDefaultAsync();
                if (cartDetail != null)
                {
                    if (cartDetail.Quantity >= 1)
                    {
                        Cart cart = await(from c in _context.Carts
                                          where c.User_Id == HttpContext.Session.GetInt32("IdTaiKhoan").Value
                                          select c).SingleOrDefaultAsync();
                        cart.TotalQuantity -= cartDetail.Quantity;
                        cart.TotalPrice    -= cartDetail.PriceTotal;
                        _context.Carts.Update(cart);
                        _context.SaveChanges();

                        _context.CartDetails.Remove(cartDetail);
                        _context.SaveChanges();
                    }
                    cartItem = await(from d in _context.CartDetails
                                     join c in _context.Carts
                                     on d.Cart_Id equals c.Id
                                     join p in _context.Products
                                     on d.Product_Id equals p.Id
                                     where c.User_Id == HttpContext.Session.GetInt32("IdTaiKhoan") & d.Quantity > 0
                                     select new CartItemViewModel
                    {
                        Id         = d.Id,
                        Name       = p.Name,
                        Quantity   = d.Quantity,
                        Price      = d.PriceSingle,
                        TotalPrice = d.PriceTotal
                    }).ToListAsync();
                    return(PartialView("Users/_CartItemPartial", cartItem));
                }
                return(PartialView("Users/_CartItemPartial", cartItem));
            }
            //chưa đăng nhập
            else
            {
                AnoCartDetail anoCartDetail = await(from c in _context.AnoCarts
                                                    join cd in _context.AnoCartDetails
                                                    on c.Id equals cd.Cart_Id
                                                    where cd.Id == id & c.Id == HttpContext.Session.GetInt32("IdCart").Value
                                                    select cd).SingleOrDefaultAsync();
                if (anoCartDetail != null)
                {
                    if (anoCartDetail.Quantity >= 1)
                    {
                        AnoCart anoCart = await(from c in _context.AnoCarts
                                                where c.Id == HttpContext.Session.GetInt32("IdCart").Value
                                                select c).SingleOrDefaultAsync();
                        anoCart.TotalQuantity -= anoCartDetail.Quantity;
                        anoCart.TotalPrice    -= anoCartDetail.PriceTotal;
                        _context.AnoCarts.Update(anoCart);
                        _context.SaveChanges();

                        _context.AnoCartDetails.Remove(anoCartDetail);
                        _context.SaveChanges();
                    }
                    cartItem = await(from d in _context.AnoCartDetails
                                     join c in _context.AnoCarts
                                     on d.Cart_Id equals c.Id
                                     join p in _context.Products
                                     on d.Product_Id equals p.Id
                                     where c.Id == HttpContext.Session.GetInt32("IdCart") & d.Quantity > 0
                                     select new CartItemViewModel
                    {
                        Id         = d.Id,
                        Name       = p.Name,
                        Quantity   = d.Quantity,
                        Price      = d.PriceSingle,
                        TotalPrice = d.PriceTotal
                    }).ToListAsync();
                    return(PartialView("Users/_CartItemPartial", cartItem));
                }
                return(PartialView("Users/_CartItemPartial", cartItem));
            }
        }
Exemplo n.º 3
0
        public string SaveUserDetails(UserDetails userDetails)
        {
            using (var db = new ObickeEntities())
            {
                using (var transaction = db.Database.BeginTransaction())
                {
                    try
                    {
                        var IsAlreadyExists = db.UserDetails.Where(a => a.SecretToken == userDetails.SecretToken).FirstOrDefault();
                        if (IsAlreadyExists != null)
                        {
                            IsAlreadyExists.Fullname         = userDetails.FullName;
                            IsAlreadyExists.UserEmailId      = userDetails.UserEmailId;
                            IsAlreadyExists.MobileNo         = userDetails.MobileNo;
                            IsAlreadyExists.CurrentLocation  = userDetails.Address;
                            IsAlreadyExists.AddressType      = userDetails.AddressType;
                            IsAlreadyExists.LandMark         = userDetails.LandMark;
                            IsAlreadyExists.TimeFrom         = Convert.ToInt32(userDetails.TimeFrom);
                            IsAlreadyExists.TimeTo           = Convert.ToInt32(userDetails.TimeTo);
                            IsAlreadyExists.AMPM             = userDetails.AMPM;
                            IsAlreadyExists.City             = userDetails.City;
                            IsAlreadyExists.Pincode          = userDetails.Pincode;
                            IsAlreadyExists.ModifiedDateTime = DateTime.Now;
                            db.SaveChanges();
                        }
                        else
                        {
                            UserDetail userD = new UserDetail()
                            {
                                Fullname         = userDetails.FullName,
                                UserEmailId      = userDetails.UserEmailId,
                                MobileNo         = userDetails.MobileNo,
                                SecretToken      = userDetails.SecretToken,
                                CurrentLocation  = userDetails.Address,
                                AddressType      = userDetails.AddressType,
                                LandMark         = userDetails.LandMark,
                                IsVerified       = true,
                                IsActive         = true,
                                TimeFrom         = Convert.ToInt32(userDetails.TimeFrom),
                                TimeTo           = Convert.ToInt32(userDetails.TimeTo),
                                AMPM             = userDetails.AMPM,
                                City             = userDetails.City,
                                Pincode          = userDetails.Pincode,
                                CreatedDateTime  = DateTime.Now,
                                ModifiedDateTime = DateTime.Now
                            };
                            db.UserDetails.Add(userD);
                            db.SaveChanges();
                        }

                        var userCartDetailsCount = db.CartDetails.Where(a => a.SecretToken == userDetails.SecretToken).Count();
                        if (userCartDetailsCount != 0)
                        {
                            var alreadyExists = db.CartDetails.Where(a => a.SecretToken == userDetails.SecretToken).ToList();
                            db.CartDetails.RemoveRange(alreadyExists);
                            db.SaveChanges();
                        }
                        foreach (var bikeId in userDetails.BikecartlistIds)
                        {
                            var cartD = new CartDetail()
                            {
                                BikeId             = bikeId.BikeId,
                                SecretToken        = userDetails.SecretToken,
                                RequestGeneratedBy = "mobile",
                                CreatedDateTime    = DateTime.Now,
                                ModifiedDateTime   = DateTime.Now
                            };
                            db.CartDetails.Add(cartD);
                            db.SaveChanges();
                        }
                        transaction.Commit();
                        return("Success");
                    }
                    catch (Exception Ex)
                    {
                        string msg = Ex.ToString();
                        transaction.Rollback();
                        return(msg);
                    }
                }
            }
        }
Exemplo n.º 4
0
        public async Task <ActionResult> AddToCart(CartItem item)
        {
            if (ModelState.IsValid)
            {
                Cart       cart   = null;
                CartDetail detail = null;

                if (UserManager.User != null)
                {
                    // get existing Cart
                    cart = (from c in db.Carts
                            where c.UserId == UserManager.User.Id
                            select c).FirstOrDefault();

                    // there is no existing Shopping Cart for this user -> create new Shopping Cart
                    if (cart == null)
                    {
                        // create new Shopping Cart
                        cart          = new Cart();
                        cart.DateOpen = System.DateTime.Now;
                        cart.UserId   = UserManager.User.Id;
                        db.Carts.Add(cart);

                        // save Cart Item
                        detail        = new CartDetail();
                        detail.Amount = item.Amount;
                        db.CartDetails.Add(detail);
                    }
                    else  // there is already an existing Shopping Cart for this user
                    {
                        // get Cart Item for this ProductDetailId
                        detail = (from cd in db.CartDetails
                                  where cd.CartId == cart.CartId && cd.ProductDetailsId == item.ProductDetailsId
                                  select cd).FirstOrDefault();
                        if (detail == null)
                        {
                            detail        = new CartDetail();
                            detail.Amount = item.Amount;
                            db.CartDetails.Add(detail);
                        }
                        else
                        {
                            detail.Amount = (short)(detail.Amount + item.Amount);
                        }
                    }

                    detail.ExtendedPrice    = item.Price;
                    detail.ProductDetailsId = item.ProductDetailsId;
                    detail.CartId           = cart.CartId;

                    await db.SaveChangesAsync();
                }
                else
                {
                    // get tmp Cart in cookie
                    string     dateOfOpen = string.Empty;
                    HttpCookie reqCookies = Request.Cookies["CartInfo"];
                    if (reqCookies != null)  // there is a temporary Cart in cookies
                    {
                        dateOfOpen = reqCookies["DateOfOpen"].ToString();

                        /* save Cart Item in cookie */
                        // read saved cart item for given ProductDetailId
                        HttpCookie reqCartItemCookies = Request.Cookies["CartItems[" + item.ProductDetailsId.ToString() + "]"]; // cartItem from request
                        HttpCookie respCartItemCookie;                                                                          // cartItem in response
                        if (reqCartItemCookies != null)
                        {
                            CartItem mItem = new JavaScriptSerializer().Deserialize <CartItem>(reqCartItemCookies.Value);
                            mItem.Amount = (short)(mItem.Amount + item.Amount);
                            string myObjectJson = new JavaScriptSerializer().Serialize(mItem);
                            respCartItemCookie = new HttpCookie("CartItems[" + item.ProductDetailsId.ToString() + "]", myObjectJson)
                            {
                                Expires = DateTime.Now.AddDays(1)
                            };
                        }
                        else
                        {
                            item.Amount = 1;
                            string myObjectJson = new JavaScriptSerializer().Serialize(item);
                            respCartItemCookie = new HttpCookie("CartItems[" + item.ProductDetailsId + "]", myObjectJson)
                            {
                                Expires = DateTime.Now.AddDays(1)
                            };
                        }
                        HttpContext.Response.Cookies.Add(respCartItemCookie);

                        /* add productDetailID in cookies */
                        HttpCookie reqIDListCookies = Request.Cookies["ProductDetailIDlist"];
                        if (reqIDListCookies != null)
                        {
                            string     yourListString = string.Empty;
                            string     dataAsString   = reqIDListCookies.Value;
                            List <int> listdata       = new List <int>();
                            if (!dataAsString.Equals(string.Empty))
                            {
                                listdata = dataAsString.Split(',').Select(x => Convert.ToInt32(x)).ToList();
                            }
                            if (!listdata.Contains(item.ProductDetailsId))
                            {
                                listdata.Add(item.ProductDetailsId);
                            }
                            // Stringify your list
                            yourListString = String.Join(",", listdata);
                            HttpCookie IDListCookies = new HttpCookie("ProductDetailIDlist", yourListString)
                            {
                                Expires = DateTime.Now.AddDays(1)
                            };
                            HttpContext.Response.Cookies.Add(IDListCookies);
                        }
                        else
                        {
                            List <int> listdata = new List <int>();
                            listdata.Add(item.ProductDetailsId);

                            // Stringify your list
                            var        yourListString = String.Join(",", listdata);
                            HttpCookie IDListCookies  = new HttpCookie("ProductDetailIDlist", yourListString)
                            {
                                Expires = DateTime.Now.AddDays(1)
                            };
                            HttpContext.Response.Cookies.Add(IDListCookies);
                        }
                    }
                    else  // There is not any tmp Shopping Cart for this user
                    {
                        // create new Shopping Cart in Cookie
                        HttpCookie cartCookie = new HttpCookie("CartInfo")
                        {
                            Expires = DateTime.Now.AddYears(1)
                        };
                        cartCookie["DateOfOpen"] = DateTime.Now.ToString();
                        HttpContext.Response.Cookies.Add(cartCookie);

                        // save Cart Item in cookie
                        item.Amount = 1;
                        string     myObjectJson   = new JavaScriptSerializer().Serialize(item);
                        HttpCookie cartItemCookie = new HttpCookie("CartItems[" + item.ProductDetailsId + "]", myObjectJson)
                        {
                            Expires = DateTime.Now.AddDays(1)
                        };
                        HttpContext.Response.Cookies.Add(cartItemCookie);

                        /* add productDetailID into cookies */
                        List <int> listdata = new List <int>();
                        listdata.Add(item.ProductDetailsId);
                        // Stringify your list
                        var        yourListString = String.Join(",", listdata);
                        HttpCookie IDListCookies  = new HttpCookie("ProductDetailIDlist", yourListString)
                        {
                            Expires = DateTime.Now.AddDays(1)
                        };
                        HttpContext.Response.Cookies.Add(IDListCookies);
                    }
                }

                ModelState.Clear();
                return(this.Json(new
                {
                    EnableSuccess = true,
                    SuccessTitle = "Successful!",
                    SuccessMsg = "Add cart successfully order!"
                }));
            }

            return(this.Json(new
            {
                EnableError = true,
                ErrorTitle = "Error",
                ErrorMsg = "Something goes wrong, please try again later"
            }));
        }
        public IActionResult Authenticate(string username, string password)
        {
            User user = db.Users.FirstOrDefault(x => x.Username == username && x.Password == password);

            if (user == null)
            {
                ViewData["lasttypedusername"] = username;
                ViewData["errMsg"]            = "Incorrect username or password.";
                ViewData["Is_Login"]          = "******";
                return(View("Index"));
            }
            else
            {
                Session session = new Session()
                {
                    Id        = Guid.NewGuid().ToString(),
                    UserId    = user.Id,
                    Timestamp = DateTimeOffset.Now.ToUnixTimeSeconds()
                };
                db.Sessions.Add(session);
                db.SaveChanges();

                Response.Cookies.Append("sessionId", session.Id);

                string currentGuestId   = Request.Cookies["guestId"];
                User   currentGuestUser = db.Users.FirstOrDefault(x => x.Id == currentGuestId);

                Cart cartMadeByGuest = db.Carts.FirstOrDefault(x => x.UserId == currentGuestUser.Id);

                //if guest user did have items in cart
                if (cartMadeByGuest != null)
                {
                    List <CartDetail> cartDetailsMadeByGuest = cartMadeByGuest.CartDetails.ToList();

                    Cart existingCart = db.Carts.FirstOrDefault(x => x.UserId == user.Id);

                    //if logged in user does not have existing cart
                    if (existingCart == null)
                    {
                        //assign logged in user id to the cart made originally as guest
                        cartMadeByGuest.UserId = user.Id;

                        foreach (CartDetail cd in cartDetailsMadeByGuest)
                        {
                            cd.UserId = user.Id;
                        }
                    }

                    //logged in user has an existing cart
                    else
                    {
                        //retrieve all cart details of the existing cart
                        List <CartDetail> cartDetailsOfExistingCart = existingCart.CartDetails.ToList();

                        //compare cart details in existing cart and cart details in cart made while as guest
                        //and merge into one cart
                        foreach (CartDetail cd1 in cartDetailsOfExistingCart)
                        {
                            foreach (CartDetail cd2 in cartDetailsMadeByGuest)
                            {
                                if (cd1.ProductId == cd2.ProductId)
                                {
                                    cd1.Quantity = cd1.Quantity + cd2.Quantity;

                                    //product in cart made while as guest has been combined to user's existing cart
                                    //remove this product/cart detail from the database
                                    db.Remove(cd2);
                                    db.SaveChanges();
                                    break;
                                }
                            }
                        }


                        //as user's existing cart may not have all products same as products in cart made while as guest
                        //account for the remaining products in the cart made while as guest
                        List <CartDetail> remainingCartDetailsMadeByGuest = cartMadeByGuest.CartDetails.ToList();
                        foreach (CartDetail cd in remainingCartDetailsMadeByGuest)
                        {
                            int tempProductId = cd.ProductId;
                            int tempQuantity  = cd.Quantity;
                            db.Remove(cd);
                            db.SaveChanges();
                            CartDetail temp = new CartDetail
                            {
                                CartId    = existingCart.Id,
                                ProductId = tempProductId,
                                Quantity  = tempQuantity,
                                UserId    = user.Id
                            };
                            db.Add(temp);
                            db.SaveChanges();
                        }
                        db.Remove(cartMadeByGuest);
                    }
                }

                db.Remove(currentGuestUser);
                db.SaveChanges();

                Response.Cookies.Delete("guestId");

                return(RedirectToAction("Index", "Home"));
            }
        }
Exemplo n.º 6
0
        public async Task <IActionResult> AddToCart(int productDetailId, int quantity)
        {
            User user = await userManager.GetUserAsync(User); // Get current user

            string     userId;                                // Get Id of current user
            Cart       existCart;                             // User has a cart
            Cart       newCart;                               // User has not a cart
            int        cartID;                                // Id of new cart
            CartDetail newCartDetail;                         // list cart detail
            int        result = 0;                            // Check add cart is success

            if (user == null)
            {
                return(Json(new
                {
                    isSuccess = false,
                    message = "null",
                    url = Url.Action("SignIn", "Login")
                }));
            }
            userId = user.Id;

            existCart = cartService.Get(userId);
            if (existCart == null) // If user has not a cart, create a new cart
            {
                // Add new cart
                newCart = new Cart {
                    UserId = userId, State = 1
                };
                result = cartService.Create(newCart);
                if (result <= 0)
                {
                    return(Json(new
                    {
                        isSuccess = false,
                        message = "cart-error"
                    }));
                }

                // Add new cart detail to cart
                cartID        = newCart.Id;
                newCartDetail = new CartDetail
                {
                    CartId          = cartID,
                    ProductDetailId = productDetailId,
                    State           = 1
                };
                result = cartDetailService.Create(newCartDetail);
                if (result <= 0)
                {
                    return(Json(new
                    {
                        isSuccess = false,
                        message = "cart-detail-error"
                    }));
                }
            }
            else // User has a cart, add new product to cart
            {
                newCartDetail = new CartDetail
                {
                    CartId          = existCart.Id,
                    ProductDetailId = productDetailId,
                    State           = 1
                };
                result = cartDetailService.Create(newCartDetail);
                if (result <= 0)
                {
                    return(Json(new
                    {
                        isSuccess = false,
                        message = "cart-detail-error"
                    }));
                }
            }

            return(Json(new { isSuccess = true, message = "success" }));
        }
Exemplo n.º 7
0
        //再見積
        public ActionResult ReShoppingCart(List <ShoppingCartViewModel> cdList)
        {
            if (Session["Customer"] == null)
            {
                return(Redirect("/CustomerLogin/CustomerLoginIndex"));
            }
            using (var db = new ModelContext())
            {
                foreach (var item in cdList)
                {
                    if (!ModelState.IsValid)
                    {
                        return(View("ShoppingCart", cdList));
                    }
                    //数量ゼロチェック
                    if (item.Quantity <= 0)
                    {
                        ViewBag.N = false;
                        return(View("ShoppingCart", cdList));
                    }

                    //在庫不足チェック
                    int ctmId = item.CustomerId;

                    var s = (from v in cdList
                             group v by v.ItemNo).ToList();

                    for (int i = 0; i < s.Count(); i++)
                    {
                        var w = (from q in s[i]
                                 select q).ToList();
                        //注文しようとしている数量
                        var o = (from q in s[i]
                                 select q.Quantity).Sum();

                        //在庫から未発送を引く
                        var stock = db.Products.Find(w[0].ItemNo);

                        var y = (from a in db.OrderDetails
                                 where a.ItemNo == stock.ItemNo && a.Status == 1
                                 select(int?) a.Quantity).Sum() ?? 0;

                        int n = stock.Stock - y;
                        if (n < o)
                        {
                            ViewBag.Z = false;
                            return(View("ShoppingCart", cdList));
                        }
                    }


                    //希望納期チェック(過去or90日未来)
                    DateTime dfrom    = DateTime.Now;
                    DateTime dto      = item.DeliveryDate;
                    double   interval = (dto - dfrom).TotalDays;
                    if (interval < 0 || interval > 90)
                    {
                        ViewBag.X = false;
                        return(View("ShoppingCart", cdList));
                    }
                }

                //再見積
                foreach (var item in cdList)
                {
                    if (item.IsChecked == true)
                    {
                        var x = db.CartDetails.Find(item.CartNo);
                        db.CartDetails.Remove(x);
                        db.SaveChanges();
                    }
                    else
                    {
                        CartDetail y = db.CartDetails.Find(item.CartNo);
                        y.Quantity     = item.Quantity;
                        y.DeliveryDate = item.DeliveryDate;
                        db.SaveChanges();
                    }
                }

                return(Redirect("ShoppingCart"));
            }
        }
Exemplo n.º 8
0
        //public IActionResult AddToCart([Bind("Quantity")]CartDetail od, int? id)
        public IActionResult AddToCart([Bind("CartDetailID, Quantity")] CartDetail cd, int?id)
        {
            //store user's name
            string userName = User.Identity.Name;
            //find the user in the database
            AppUser user = _context.Users.FirstOrDefault(u => u.UserName == userName);

            //find an uncompleted cart associated with the user
            Cart cart = _context.Carts.Include(u => u.Customer).FirstOrDefault(u => u.Customer.UserID == user.UserID && u.Status == false);

            // if an uncompleted cart does not exist -> create a new cart for the user
            if (cart == null)
            {
                //create a new cart bc couldn't find an cart associated with that user
                cart = new Cart()
                {
                    Customer = user, CartDate = System.DateTime.Today
                };
                _context.Carts.Add(cart);

                _context.SaveChanges();
            }

            //Find the book
            Book book = _context.Books.Find(id);

            //check if book is in stock
            if (book.CopiesOnHand < 1)
            {
                return(View("Error", new String[] { "This book is out of stock" }));
            }

            //check if book is still active - still for sale
            //if (book.Active == false)
            //{
            //return View("Error", new String[] { "This book is no longer for sale" });
            //}

            //check if book already exists in cart
            foreach (CartDetail cdb in cart.CartDetails)
            {
                if (cdb.Book.BookID == id)
                {
                    return(View("Error", new String[] { "This book already is in your cart." }));
                }
            }

            CartDetail orderdetail = new CartDetail()
            {
                Cart = cart, Book = book
            };

            //od.Cart = cart;
            //od.Book = book;

            ////updating prop for cartdetails
            orderdetail.Quantity      = cd.Quantity;
            orderdetail.Title         = book.Title;
            orderdetail.Price         = book.Price;
            orderdetail.ExtendedPrice = cd.Quantity * book.Price;
            orderdetail.CustomerName  = user.FirstName + " " + user.LastName;
            orderdetail.TotalCost     = book.Cost * cd.Quantity;

            //update prop for carts
            orderdetail.Cart.CustomerName = user.FirstName + " " + user.LastName;
            //orderdetail.Cart.TotalQuantity += cd.Quantity;



            if (ModelState.IsValid)
            {
                _context.CartDetails.Add(orderdetail);
                _context.SaveChanges();
                _context.Update(orderdetail);
                return(RedirectToAction("Details", new { id = orderdetail.Cart.CartID }));
            }

            //ViewBag.AllProducts = GetAllBooks();
            return(View(orderdetail));
        }
Exemplo n.º 9
0
        //public ActionResult Login(String username, String password)
        public async Task <ActionResult> Login([Bind(Include = "Username,Password")] Logon logon)
        {
            if (ModelState.IsValid)
            {
                // Authenticate the user.
                if (UserManager.ValidateUser(logon, Response))
                {
                    /* move temporary shopping cart to DB */
                    string dateOfOpen = string.Empty;

                    // get tmp Cart in cookie
                    HttpCookie reqCartInfoCookies = HttpContext.Request.Cookies["CartInfo"];
                    if (reqCartInfoCookies != null)  // there is a temporary Cart in cookies
                    {
                        dateOfOpen = reqCartInfoCookies["DateOfOpen"].ToString();

                        Cart cart = null;
                        // get existing Cart
                        cart = (from c in db.Carts
                                where c.UserId == UserManager.User.Id
                                select c).FirstOrDefault();

                        // there is no existing Shopping Cart for this user -> create new Shopping Cart
                        if (cart == null)
                        {
                            cart          = new Cart();
                            cart.UserId   = UserManager.User.Id;
                            cart.DateOpen = DateTime.Parse(dateOfOpen);
                            db.Carts.Add(cart);
                        }

                        HttpCookie reqIDListCookies = Request.Cookies["ProductDetailIDlist"];
                        if (reqIDListCookies != null)
                        {
                            string dataAsString = reqIDListCookies.Value;
                            if (!dataAsString.Equals(string.Empty))
                            {
                                List <int> listdata = new List <int>();
                                //List<CartItem> listCartItem = new List<CartItem>();
                                listdata = dataAsString.Split(',').Select(x => Int32.Parse(x)).ToList();
                                for (int i = 0; i < listdata.Count(); i++)
                                {
                                    HttpCookie reqCartItemCookies = Request.Cookies["CartItems[" + listdata[i].ToString() + "]"];
                                    if (reqCartItemCookies != null)
                                    {
                                        CartItem cookiesItem = new JavaScriptSerializer().Deserialize <CartItem>(reqCartItemCookies.Value);

                                        // get Cart Item for this ProductDetailId in DB
                                        CartDetail detail;
                                        int        productDetailId = listdata[i];
                                        detail = (from cd in db.CartDetails
                                                  where cd.CartId == cart.CartId && cd.ProductDetailsId == productDetailId
                                                  select cd).FirstOrDefault();
                                        if (detail == null)
                                        {
                                            detail                  = new CartDetail();
                                            detail.Amount           = (short)cookiesItem.Amount;
                                            detail.ExtendedPrice    = cookiesItem.Price;
                                            detail.Type             = 0;
                                            detail.ProductDetailsId = listdata[i];
                                            detail.CartId           = cart.CartId;
                                            db.CartDetails.Add(detail);
                                        }
                                        else
                                        {
                                            detail.Amount += (short)cookiesItem.Amount;
                                        }

                                        await db.SaveChangesAsync();

                                        /* remove cart item of this ProductDetailId in cookies */
                                        var respCartItemscookies = new HttpCookie("CartItems[" + listdata[i].ToString() + "]");
                                        respCartItemscookies.Expires = DateTime.Now.AddDays(-1D);
                                        Response.Cookies.Add(respCartItemscookies);
                                    }
                                }

                                /* update productDetailID list in cookies */
                                HttpCookie respIDListCookies = new HttpCookie("ProductDetailIDlist", "")
                                {
                                    Expires = DateTime.Now.AddDays(1)
                                };
                                HttpContext.Response.Cookies.Add(respIDListCookies);
                            }
                        }
                    }

                    // Redirect to the secure area.
                    return(RedirectToAction("Index", "Category"));
                }
            }

            ViewBag.LoginFailure = 1;
            return(View());
        }
 public bool UpdateCartDetail([FromBody] CartDetail CartDetail)
 {
     return(_CartDetailRepository.UpdateCartDetail(CartDetail));
 }
        public CartDetail SepeteUrunEkle(Guid userId, SepeteEkleViewModel sepeteEkle)
        {
            Cart          cart          = unitOfWork.Repository <Cart>().Find(x => x.User.id == userId);
            VotedressUser votedressUser = unitOfWork.Repository <VotedressUser>().Find(x => x.id == userId);
            Product       product       = unitOfWork.Repository <Product>().Find(x => x.id == sepeteEkle.productId);

            CartDetail cartDetail = null;

            if (cart != null)
            {
                bool varmi = false;

                if (cart.CartDetail == null)
                {
                    cartDetail = new CartDetail()
                    {
                        AddToCartDate  = DateTime.Now,
                        Cart           = cart,
                        Product        = product,
                        ProductColorId = sepeteEkle.productColorId,
                        ProductCount   = sepeteEkle.productCount,
                        Size           = sepeteEkle.productSize
                    };

                    unitOfWork.Repository <CartDetail>().Insert(cartDetail);
                    unitOfWork.SaveChanges();
                }
                else
                {
                    for (int i = 0; i < cart.CartDetail.Count; i++)
                    {
                        if (cart.CartDetail[i].Product.id == sepeteEkle.productId && cart.CartDetail[i].ProductColorId == sepeteEkle.productColorId && cart.CartDetail[i].Size == sepeteEkle.productSize)
                        {
                            cart.CartDetail[i].ProductCount = cart.CartDetail[i].ProductCount + sepeteEkle.productCount;
                            varmi = true;
                            unitOfWork.SaveChanges();

                            cartDetail = cart.CartDetail[i];

                            break;
                        }
                    }

                    if (varmi == false)
                    {
                        cartDetail = new CartDetail()
                        {
                            AddToCartDate  = DateTime.Now,
                            Cart           = cart,
                            Product        = product,
                            ProductColorId = sepeteEkle.productColorId,
                            ProductCount   = sepeteEkle.productCount,
                            Size           = sepeteEkle.productSize
                        };

                        unitOfWork.Repository <CartDetail>().Insert(cartDetail);
                        unitOfWork.SaveChanges();
                    }
                }
            }
            else
            {
                cart = new Cart()
                {
                    User = votedressUser,
                };

                cartDetail = new CartDetail()
                {
                    AddToCartDate  = DateTime.Now,
                    Cart           = cart,
                    Product        = product,
                    ProductColorId = sepeteEkle.productColorId,
                    ProductCount   = sepeteEkle.productCount,
                    Size           = sepeteEkle.productSize
                };
                unitOfWork.Repository <Cart>().Insert(cart);
                cartDetail = unitOfWork.Repository <CartDetail>().Insert(cartDetail);
                unitOfWork.SaveChanges();
            }

            return(cartDetail);
        }
 public bool AddCartDetail([FromBody] CartDetail CartDetail)
 {
     return(_CartDetailRepository.AddCartDetail(CartDetail));
 }
Exemplo n.º 13
0
        public IActionResult UpdateCart([FromBody] UpdateCartInput input)
        {
            Session session   = db.Sessions.FirstOrDefault(x => x.Id == Request.Cookies["sessionId"]);
            User    guestUser = db.Users.FirstOrDefault(x => x.Id == Request.Cookies["guestId"]);

            if ((session != null || guestUser != null) && !(session != null && guestUser != null))
            {
                if (session != null)
                {
                    //retrieve existing cart from db
                    Cart existingCart = db.Carts.FirstOrDefault(x => (x.UserId == session.UserId));

                    //no existing cart; create new cart for user
                    if (existingCart == null)
                    {
                        Cart newCart = new Cart
                        {
                            Id     = Guid.NewGuid().ToString(),
                            UserId = session.UserId
                        };
                        db.Add(newCart);
                        db.SaveChanges();

                        CartDetail newCartDetail = new CartDetail
                        {
                            CartId    = newCart.Id,
                            ProductId = int.Parse(input.ProductId),
                            UserId    = session.UserId,
                            Quantity  = 1
                        };
                        db.Add(newCartDetail);
                        db.SaveChanges();

                        //count number of products in cart
                        ViewData["numberOfProductsInCart"] = newCart.CartDetails.ToList().Sum(x => x.Quantity);
                    }

                    //cart exists, retrieve existing cart details
                    else
                    {
                        List <CartDetail> existingCartDetails = existingCart.CartDetails.ToList();

                        //check if existing cart already has selected product
                        CartDetail cartDetailWithThisProduct = existingCartDetails.Find(x => x.ProductId == int.Parse(input.ProductId));

                        //if selected product does not exist in cart, create new cartdetail
                        if (cartDetailWithThisProduct == null)
                        {
                            CartDetail newCartDetail = new CartDetail
                            {
                                CartId    = existingCart.Id,
                                ProductId = int.Parse(input.ProductId),
                                UserId    = session.UserId,
                                Quantity  = 1
                            };
                            db.Add(newCartDetail);
                            db.SaveChanges();

                            ViewData["numberOfProductsInCart"] = existingCart.CartDetails.ToList().Sum(x => x.Quantity);
                        }

                        //selected product already exists, increase qty by 1
                        else
                        {
                            cartDetailWithThisProduct.Quantity = cartDetailWithThisProduct.Quantity + 1;
                            db.SaveChanges();

                            //update no. of products in cart
                            ViewData["numberOfProductsInCart"] = existingCart.CartDetails.ToList().Sum(x => x.Quantity);
                        }
                    }
                }

                else
                {
                    Cart existingCart = db.Carts.FirstOrDefault(x => (x.UserId == guestUser.Id));
                    if (existingCart == null)
                    {
                        Cart newCart = new Cart
                        {
                            Id     = Guid.NewGuid().ToString(),
                            UserId = guestUser.Id
                        };
                        db.Add(newCart);
                        db.SaveChanges();

                        CartDetail newCartDetail = new CartDetail
                        {
                            CartId    = newCart.Id,
                            ProductId = int.Parse(input.ProductId),
                            UserId    = guestUser.Id,
                            Quantity  = 1
                        };
                        db.Add(newCartDetail);
                        db.SaveChanges();

                        ViewData["numberOfProductsInCart"] = newCart.CartDetails.ToList().Sum(x => x.Quantity);
                    }
                    else
                    {
                        List <CartDetail> existingCartDetails = existingCart.CartDetails.ToList();

                        CartDetail cartDetailWithThisProduct = existingCartDetails.Find(x => x.ProductId == int.Parse(input.ProductId));

                        if (cartDetailWithThisProduct == null)
                        {
                            CartDetail newCartDetail = new CartDetail
                            {
                                CartId    = existingCart.Id,
                                ProductId = int.Parse(input.ProductId),
                                UserId    = guestUser.Id,
                                Quantity  = 1
                            };
                            db.Add(newCartDetail);
                            db.SaveChanges();

                            ViewData["numberOfProductsInCart"] = existingCart.CartDetails.ToList().Sum(x => x.Quantity);
                        }
                        else
                        {
                            cartDetailWithThisProduct.Quantity = cartDetailWithThisProduct.Quantity + 1;
                            db.SaveChanges();

                            ViewData["numberOfProductsInCart"] = existingCart.CartDetails.ToList().Sum(x => x.Quantity);
                        }
                    }
                }
            }
            return(Json(new { status = "success", cartNumber = ViewData["numberOfProductsInCart"].ToString() }));
        }
Exemplo n.º 14
0
        protected void input_number_TextChanged(object sender, EventArgs e)
        {
            var chk         = (TextBox)sender;
            var CommandName = chk.Attributes["CommandName"];
            int id          = int.Parse(CommandName);
            var number      = chk.Text;
            int quantity    = int.Parse(number);

            if (quantity <= 0)
            {
                Functions.EnqueueNewNotifications(new Notifications(
                                                      Notifications.ERROR_TYPE,
                                                      "Quantity out of bound!!",
                                                      "you must enter the quantity that more than 0 !!"));
                return;
            }

            using (ArtShopEntities db = new ArtShopEntities())
            {
                try
                {
                    CartDetail cd = db.Carts.Find(cart_id).CartDetails.Where(c => c.art_id == id).FirstOrDefault();

                    if (cd.Art.@virtual == false)
                    {
                        if (quantity > cd.Art.Painting.quantity)
                        {
                            Functions.EnqueueNewNotifications(new Notifications(
                                                                  Notifications.ERROR_TYPE,
                                                                  "Out of stocks!!",
                                                                  "The following product is out of stocks !! seller only provide " + cd.Art.Painting.quantity + " items!!"));
                        }
                        else
                        {
                            cd.availability = quantity;
                            db.CartDetails.AddOrUpdate(cd);
                            db.SaveChanges();

                            total        = 0;
                            totalCount   = 0;
                            checkedCount = 0;
                            if (check_cart_count(db))
                            {
                                retriveDataAndAnalysis(db);
                            }
                            Functions.EnqueueNewNotifications(new Notifications(
                                                                  Notifications.SUCCESS_TYPE,
                                                                  "Updates complete!!",
                                                                  ""));
                        }
                    }
                    else
                    {
                        Functions.EnqueueNewNotifications(new Notifications(
                                                              Notifications.ERROR_TYPE,
                                                              "Non virtul type",
                                                              "Virtual products cannot select quantity!!"));
                    }
                }
                catch (Exception ex)
                {
                    Functions.EnqueueNewNotifications(new Notifications(
                                                          Notifications.ERROR_TYPE,
                                                          "Deleted Failed!!",
                                                          "you have following exception : " + ex.Message + " !!"));
                }
            }

            Repeater2.DataBind();
        }
Exemplo n.º 15
0
 public void CreateCartDetail(CartDetail cartDetail)
 {
     _cartDetailRepository.Add(cartDetail);
     Commit();
 }
Exemplo n.º 16
0
 public bool AddNewCartDeailt(CartDetail cartDetail)
 {
     return(_Services.AddNewCartDeailt(cartDetail));
 }
Exemplo n.º 17
0
        public IActionResult OnPostAddToCart([FromBody] CartDetail model)
        {
            if (!ModelState.IsValid)
            {
                //IEnumerable<ModelError> allErrors = ModelState.Values.SelectMany(v => v.Errors);
                return(new BadRequestObjectResult("Đã xãy ra lỗi"));
            }

            var user  = _userManager.GetUserAsync(HttpContext.User).Result;
            var cart  = _cartRepository.GetCartByCustomerId(user.Id);
            var _item = _itemRepository.Find(model.ItemId);

            if (model.Quantity <= 0)
            {
                return(new BadRequestObjectResult("Số lượng sản phẩm không hợp lệ"));
            }

            if (model.Quantity > _item.Quantity)
            {
                return(new BadRequestObjectResult("Số lượng sản phẩm trong giỏ vượt quá số lượng cho phép là: " + _item.Quantity.ToString()));
            }

            if (cart == null)
            {
                var newCart = new DAL.Data.Entities.Cart
                {
                    CustomerId = _userManager.GetUserAsync(HttpContext.User).Result.Id,
                };
                _cartRepository.Add(newCart);

                _cartDetailRepository.Add(new CartDetail
                {
                    CartId   = newCart.Id,
                    ItemId   = model.ItemId,
                    Quantity = model.Quantity
                });
            }
            else
            {
                var  cartDetails = cart.CartDetails.Where(cd => cd.IsDeleted == false);
                bool isMatch     = false;
                foreach (var item in cart.CartDetails)
                {
                    if (item.ItemId == model.ItemId)
                    {
                        item.Quantity = item.IsDeleted == true ? model.Quantity : item.Quantity + model.Quantity;
                        if (_item.Quantity == 0)
                        {
                            return(new BadRequestObjectResult("Sản phẩm đã hết hàng"));
                        }
                        if (item.Quantity > _item.Quantity)
                        {
                            return(new BadRequestObjectResult("Số lượng sản phẩm trong giỏ vượt quá số lượng cho phép là: " + _item.Quantity.ToString()));
                        }
                        item.IsDeleted = false;
                        _cartDetailRepository.Update(item);
                        isMatch = true;
                    }
                }
                if (!isMatch)
                {
                    _cartDetailRepository.Add(new CartDetail
                    {
                        CartId   = cart.Id,
                        ItemId   = model.ItemId,
                        Quantity = model.Quantity
                    });
                }
            }
            return(new OkObjectResult(model));
        }
Exemplo n.º 18
0
 public void SetShow(Good good, CartDetail cd)
 {
     cartDetail   = cd;
     goodInfo     = good;
     nameStr.text = good.name;
 }
        public async Task <AddToCartResult> AddProductToCartAsync(CartDetail cartDetail)
        {
            cartDetail.CreatedAt = DateTime.UtcNow;
            cartDetail.UpdatedAt = DateTime.UtcNow;

            // check product exists
            var productTier = await _context.ProductTiers
                              .Where(p =>
                                     p.Id == cartDetail.ProductTierId &&
                                     p.IsDeleted == false)
                              .Include(pt => pt.Product)
                              .FirstOrDefaultAsync();

            if (productTier == null)
            {
                return(new AddToCartResult
                {
                    IsSuccess = false,
                    Errors = new[] { "Sản phẩm này không tồn tại" }
                });
            }

            // check cart exists
            var cart = await _context.Carts
                       .SingleOrDefaultAsync(c =>
                                             c.Id == cartDetail.CartId);

            if (cart == null)
            {
                return(new AddToCartResult
                {
                    IsSuccess = false,
                    Errors = new[] { "Giỏ hàng của khách hàng không tồn tại" }
                });
            }

            // validate valid quantity
            if (cartDetail.Quantity > productTier.Quantity)
            {
                return(new AddToCartResult
                {
                    IsSuccess = false,
                    Errors = new[] { "Số lượng hiện tại của sản phẩm không đủ" }
                });
            }

            // validate valid product status
            if (productTier.Product.Status == ProductStatus.OutOfStock)
            {
                return(new AddToCartResult
                {
                    IsSuccess = false,
                    Errors = new[] { "Sản phẩm này đã hết hàng, không thể thêm vào giỏ" }
                });
            }

            /** If new item has productId and cartId match the existing item
             * then update the quantity of the old item instead of create the new item
             */
            var handleAddExistedItemResult = await handleAddExistedItem(cartDetail, productTier);

            if (handleAddExistedItemResult != null)
            {
                /** Get created cart detail again include full product information
                 * for FE to display in cart
                 */
                var detailAndFullProductInfo = await _context.CartDetails
                                               .Where(cd => cd.Id == handleAddExistedItemResult.Id)
                                               .Include(cd => cd.ProductTier)
                                               .ThenInclude(pt => pt.Product)
                                               .ThenInclude(p => p.ProductImages)
                                               .FirstOrDefaultAsync();

                return(new AddToCartResult
                {
                    IsSuccess = true,
                    CartDetail = detailAndFullProductInfo
                });
            }


            await _context.CartDetails.AddAsync(cartDetail);

            var created = await _context.SaveChangesAsync();

            if (!(created > 0))
            {
                return(new AddToCartResult
                {
                    IsSuccess = false,
                    Errors = new[] { "Thêm sản phẩm vào giỏ thất bại" }
                });
            }

            /** Get created cart detail again include full product information
             * for FE to display in cart
             */
            var createdCartDetailAndProductInfo = await _context.CartDetails
                                                  .Where(cd => cd.Id == cartDetail.Id)
                                                  .Include(cd => cd.ProductTier)
                                                  .ThenInclude(pt => pt.Product)
                                                  .ThenInclude(p => p.ProductImages)
                                                  .FirstOrDefaultAsync();

            return(new AddToCartResult
            {
                IsSuccess = true,
                CartDetail = createdCartDetailAndProductInfo
            });
        }
Exemplo n.º 20
0
 private int VariantStock(CartDetail cartDetail)
 {
     return(_context.Variants.Where(v => v.ID == cartDetail.VariantID).Select(v => v.Stock).FirstOrDefault());
 }
        public ActionResult ProductAddResult(ProductAddViewModel pro)
        {
            if (Session["Customer"] == null)
            {
                return(Redirect("/CustomerLogin/CustomerLoginIndex"));
            }
            using (var db = new ModelContext())
            {
                //空欄、形式チェック
                if (!ModelState.IsValid)
                {
                    return(View("List", pro));
                }
                //数量ゼロチェック
                if (pro.Quantity <= 0)
                {
                    ViewBag.N = false;
                    return(View("List", pro));
                }
                //在庫チェック
                int x     = pro.ItemNo;
                var stock = db.Products.Find(x);
                var y     = (from a in db.OrderDetails
                             where a.ItemNo == x && a.Status == 1
                             select(int?) a.Quantity).Sum() ?? 0;

                int s = stock.Stock - y;
                if (s < pro.Quantity)
                {
                    ViewBag.E = false;
                    return(View("List", pro));
                }

                //希望納期チェック(過去or90日以上未来)
                DateTime dfrom    = DateTime.Now;
                DateTime dto      = pro.DeliveryDate;
                double   interval = (dto - dfrom).TotalDays;
                if (interval < 0 || interval > 90)
                {
                    ViewBag.D = false;
                    return(View("List", pro));
                }

                //カートへ追加
                var u = new CartDetail
                {
                    ItemNo       = pro.ItemNo,
                    Quantity     = pro.Quantity,
                    DeliveryDate = pro.DeliveryDate,
                    CustomerId   = (int)Session["Customer"]
                };

                //時刻除外)
                string result = pro.DeliveryDate.ToString();
                ViewBag.Date = result.Substring(0, 10);
                //単価を三桁区切り
                ViewBag.UnitP = String.Format("{0:#,0}", pro.UnitPrice);
                //合計金額を三桁区切り
                var price = pro.UnitPrice * pro.Quantity;
                ViewBag.Price = String.Format("{0:#,0}", price);

                ViewBag.ItemN  = pro.ItemName;
                ViewBag.Result = u;
                ViewBag.Url    = stock.PhotoUrl;

                db.CartDetails.Add(u);
                db.SaveChanges();

                return(View());
            }
        }
Exemplo n.º 22
0
        public JsonResult AddToCart(long productId, long sizeId, int quantity, long colorId)
        {
            try
            {
                using (_db)
                {
                    var cartCookie = CookieHelper.Get(StaticValues.CookieNameCartCookie);

                    if (string.IsNullOrWhiteSpace(cartCookie))
                    {
                        //Create a cookie
                        cartCookie = Guid.NewGuid().ToString();
                        CookieHelper.Set(StaticValues.CookieNameCartCookie, cartCookie);
                    }
                    var size    = _db.Sizes.FirstOrDefault(s => s.SizeId == sizeId);
                    var product = _db.Products.FirstOrDefault(s => s.ProductId == productId);

                    if (product != null && size != null)
                    {
                        //Check that product is available on cart
                        var availability = _db.CartDetails.FirstOrDefault(s => s.ProductId == productId && s.CartCookie == cartCookie && s.ColorId != colorId && s.SizeName != size.Name);

                        if (availability != null)
                        {
                            //Remove existing data
                            _db.CartDetails.Remove(availability);
                        }

                        var cartDetail = new CartDetail
                        {
                            CartCookie  = cartCookie,
                            Quantity    = quantity,
                            SizeName    = size.Name,
                            ColorId     = colorId,
                            ProductId   = productId,
                            Price       = product.Price,
                            ContactId   = 0,
                            CreatedDate = DateTime.UtcNow,
                            MRP         = product.MRP,
                            TAX         = product.TAX,
                            Discount    = 0
                        };
                        cartDetail.CreatedDate = DateTime.UtcNow;

                        _db.CartDetails.Add(cartDetail);
                        _db.SaveChanges();

                        return(Json(new { status = true, cartItems = _db.CartDetails.Count(s => s.CartCookie == cartCookie), JsonRequestBehavior.AllowGet }));
                    }
                    else
                    {
                        return(Json(new { status = false, JsonRequestBehavior.AllowGet }));
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Exemplo n.º 23
0
 public void TestInsertCart()
 {
     var usoEntities = new USOEntities();
     var cartDetail  = new CartDetail {
     };
 }
Exemplo n.º 24
0
        public ActionResult ChangeCart(int id = 0, int quantity = 0)
        {
            CartDetail        cartdetail     = new CartDetail();
            List <CartDetail> cartdetaillist = new List <CartDetail>();
            CartSummary       cartsummary    = new CartSummary();
            Cart     cart     = new Cart();
            FoodItem foodItem = db.FoodItems.Single(fi => fi.FoodItemId == id);

            cartdetail.FoodItemId = id;
            cartdetail.FoodItem   = foodItem.FoodItemName;
            cartdetail.Rate       = (decimal)foodItem.FoodItemRate;
            cartdetail.Quantity   = quantity;
            cartdetail.Total      = (decimal)foodItem.FoodItemRate * quantity;
            bool       isAdded        = false;
            int        servicePercent = 0;
            int        vatpercent     = 0;
            decimal    subtotal       = 0;
            decimal    service        = 0;
            decimal    vat            = 0;
            decimal    deliverycharge = 0;
            decimal    gtotal         = 0;
            Restaurant restaurant     = (Restaurant)Session["Restaurant"];

            if (restaurant.IsServiceChargeApplicable == true)
            {
                servicePercent = Convert.ToInt32(restaurant.ServiceChargePercent);
            }
            if (restaurant.IsVatApplicable == true)
            {
                vatpercent = Convert.ToInt32(restaurant.VATPercent);
            }
            if (Session["Cart"] != null)
            {
                cart           = (Cart)Session["Cart"];
                cartdetaillist = cart.cartDetail;
                foreach (var c in cartdetaillist)
                {
                    if (c.FoodItemId == id && quantity == 0)
                    {
                        c.Quantity = 1;
                    }
                    else
                    {
                        if (c.FoodItemId == id)
                        {
                            c.Quantity = quantity;
                            c.Total    = c.Rate * c.Quantity;
                            isAdded    = true;
                        }
                    }
                }

                foreach (var c in cartdetaillist)
                {
                    subtotal = subtotal + c.Rate * c.Quantity;
                }

                cartsummary.SubTotal = subtotal;
                service = (subtotal) * servicePercent / 100;
                cartsummary.ServiceCharge = service;
                vat                              = (service + subtotal) * vatpercent / 100;
                cartsummary.VAT                  = vat;
                cartsummary.GrossTotal           = subtotal + service + vat + deliverycharge;
                cartsummary.ServiceChargePercent = servicePercent;
                cartsummary.VATPercent           = vatpercent;
                cart.cartSummary                 = cartsummary;
            }
            else
            {
                cartdetaillist.Add(cartdetail);
                cart.cartDetail      = cartdetaillist;
                subtotal             = cartdetail.Rate * cartdetail.Quantity;
                cartsummary.SubTotal = subtotal;
                service = (subtotal) * servicePercent / 100;
                cartsummary.ServiceCharge = service;
                vat = (service + subtotal) * vatpercent / 100;

                cartsummary.VAT                  = vat;
                cartsummary.GrossTotal           = subtotal + service + vat + deliverycharge;
                cart.cartSummary                 = cartsummary;
                cartsummary.VATPercent           = vatpercent;
                cartsummary.ServiceChargePercent = servicePercent;
                cart.cartSummary                 = cartsummary;
            }
            Session["Cart"] = cart;
            ViewBag.message = "Updated";
            return(RedirectToAction("Index", new { message = ViewData["message"] }));
        }
Exemplo n.º 25
0
        // nhận từ ajax?
        public async Task <int> AddItem(int id)
        {
            AnoCartDetail anoCartDetail;
            AnoCart       anoCart;

            Cart       cart;
            CartDetail cartDetail;
            Product    product = await(from p in _context.Products
                                       where p.Id == id
                                       select p).FirstOrDefaultAsync();

            if (product == null)
            {
                return(-1);
            }

            //tai khoan chua dang nhap
            if (HttpContext.Session.GetInt32("IdTaiKhoan") == null)
            {
                //khởi tạo cart lần đầu
                if (HttpContext.Session.GetInt32("IdCart") == null)
                {
                    anoCart = new AnoCart
                    {
                        CartStatus_Id = 2,
                        TotalPrice    = product.Price - (int)(product.Price * product.Saleoff) / 100,
                        TotalQuantity = 1,
                        DateCreate    = DateTime.Now,
                        DateModify    = DateTime.Now
                    };

                    //thêm cart vào database
                    _context.AnoCarts.Add(anoCart);
                    _context.SaveChanges();

                    //lấy và set id cart vừa tạo vào session
                    int idCart = await(from a in _context.AnoCarts select a.Id).MaxAsync();
                    HttpContext.Session.SetInt32("IdCart", idCart);

                    //tạo mới anoCartDetail
                    anoCartDetail = new AnoCartDetail
                    {
                        Cart_Id     = HttpContext.Session.GetInt32("IdCart").Value,
                        Product_Id  = id,
                        Quantity    = 1,
                        PriceTotal  = product.Price - (int)(product.Price * product.Saleoff) / 100,
                        PriceSingle = product.Price - (int)(product.Price * product.Saleoff) / 100,
                        DateCreate  = DateTime.Now,
                        DateModify  = DateTime.Now
                    };
                    _context.AnoCartDetails.Add(anoCartDetail);
                    _context.SaveChanges();

                    return(1);
                }

                //thêm sản phẩm theo id khi cart đã được tạo
                else
                {
                    //lấy anoCartDetail theo id sản phẩm và id cart
                    anoCartDetail = await(from d in _context.AnoCartDetails
                                          where d.Product_Id == id & d.Cart_Id == HttpContext.Session.GetInt32("IdCart")
                                          select d).SingleOrDefaultAsync();

                    //nếu chưa có anoCartDetail theo sản phẩm và cart
                    //tạo mới
                    if (anoCartDetail == null)
                    {
                        anoCartDetail = new AnoCartDetail
                        {
                            Cart_Id     = HttpContext.Session.GetInt32("IdCart").Value,
                            Product_Id  = product.Id,
                            Quantity    = 1,
                            PriceTotal  = product.Price - (int)(product.Price * product.Saleoff) / 100,
                            PriceSingle = product.Price - (int)(product.Price * product.Saleoff) / 100,
                            DateCreate  = DateTime.Now,
                            DateModify  = DateTime.Now
                        };

                        //thêm anoCartDrtail vào database
                        _context.AnoCartDetails.Add(anoCartDetail);
                        _context.SaveChanges();

                        //cập nhật anoCart
                        anoCart                = await(from c in _context.AnoCarts where c.Id == HttpContext.Session.GetInt32("IdCart") select c).SingleOrDefaultAsync();
                        anoCart.TotalPrice    += (product.Price - (int)(product.Price * product.Saleoff) / 100);
                        anoCart.TotalQuantity += 1;
                        _context.AnoCarts.Update(anoCart);
                        _context.SaveChanges();

                        return(1);
                    }
                    //đã có anoCartDetail tang so luong, gia tien (anoCart, anoCartDetails)
                    else
                    {
                        //Cap nhat anoCartDetails
                        anoCartDetail = await(from d in _context.AnoCartDetails
                                              where d.Product_Id == id & d.Cart_Id == HttpContext.Session.GetInt32("IdCart")
                                              select d).SingleOrDefaultAsync();
                        anoCartDetail.Quantity  += 1;
                        anoCartDetail.PriceTotal = anoCartDetail.Quantity * anoCartDetail.PriceSingle;

                        //cap nhat anoCart
                        anoCart                = await(from c in _context.AnoCarts where c.Id == HttpContext.Session.GetInt32("IdCart") select c).SingleOrDefaultAsync();
                        anoCart.TotalPrice    += (product.Price - (int)(product.Price * product.Saleoff) / 100);
                        anoCart.TotalQuantity += 1;
                        _context.AnoCarts.Update(anoCart);
                        _context.SaveChanges();

                        return(1);
                    }
                }
            }

            //tai khoan da dang nhap
            else
            {
                cart = await(from c in _context.Carts
                             where c.User_Id == HttpContext.Session.GetInt32("IdTaiKhoan")
                             select c).SingleOrDefaultAsync();

                //tai khoan nay chua co cart , thi tao moi
                if (cart == null)
                {
                    //them moi cart
                    cart = new Cart
                    {
                        CartStatus_Id = 2,
                        User_Id       = HttpContext.Session.GetInt32("IdTaiKhoan").Value,
                        TotalPrice    = product.Price - (int)(product.Price * product.Saleoff) / 100,
                        TotalQuantity = 1,
                        DateCreate    = DateTime.Now,
                        DateModify    = DateTime.Now
                    };
                    _context.Carts.Add(cart);
                    _context.SaveChanges();

                    //them moi cartDetail
                    cartDetail = new CartDetail
                    {
                        Cart_Id     = cart.Id,
                        Product_Id  = id,
                        Quantity    = 1,
                        PriceTotal  = product.Price - (int)(product.Price * product.Saleoff) / 100,
                        PriceSingle = product.Price - (int)(product.Price * product.Saleoff) / 100,
                        DateCreate  = DateTime.Now,
                        DateModify  = DateTime.Now
                    };
                    _context.CartDetails.Add(cartDetail);
                    _context.SaveChanges();

                    return(1);
                }
                //tai khoan nay da tao cart
                else if (cart != null)
                {
                    //lấy cartDetail theo id sản phẩm và id cart
                    cartDetail = await(from d in _context.CartDetails
                                       where d.Product_Id == id & d.Cart_Id == cart.Id
                                       select d).SingleOrDefaultAsync();

                    //Chua co cartDetail them moi
                    if (cartDetail == null)
                    {
                        cartDetail = new CartDetail
                        {
                            Cart_Id     = cart.Id,
                            Product_Id  = product.Id,
                            Quantity    = 1,
                            PriceTotal  = product.Price - (int)(product.Price * product.Saleoff) / 100,
                            PriceSingle = product.Price - (int)(product.Price * product.Saleoff) / 100,
                            DateCreate  = DateTime.Now,
                            DateModify  = DateTime.Now
                        };

                        //thêm cartDrtail vào database
                        _context.CartDetails.Add(cartDetail);
                        _context.SaveChanges();

                        //cập nhật Cart
                        cart                = await(from c in _context.Carts where c.Id == cart.Id select c).SingleOrDefaultAsync();
                        cart.TotalPrice    += (product.Price - (int)(product.Price * product.Saleoff) / 100);
                        cart.TotalQuantity += 1;
                        _context.Carts.Update(cart);
                        _context.SaveChanges();

                        return(1);
                    }

                    //đã có cartDetail tang so luong, gia tien (cart, cartDetails)
                    else
                    {
                        //Cap nhat CartDetails
                        cartDetail = await(from d in _context.CartDetails
                                           where d.Product_Id == id & d.Cart_Id == cart.Id
                                           select d).SingleOrDefaultAsync();
                        cartDetail.Quantity  += 1;
                        cartDetail.PriceTotal = cartDetail.Quantity * cartDetail.PriceSingle;

                        //cap nhat Cart
                        cart                = await(from c in _context.Carts where c.Id == cart.Id select c).SingleOrDefaultAsync();
                        cart.TotalPrice    += (product.Price - (int)(product.Price * product.Saleoff) / 100);
                        cart.TotalQuantity += 1;
                        _context.Carts.Update(cart);
                        _context.SaveChanges();

                        return(1);
                    }
                }
            }
            return(0);
        }
Exemplo n.º 26
0
        public ActionResult AddToCart(int id = 0, int quantity = 0) //Get Cart Collection
        {
            CartDetail        cartdetail     = new CartDetail();
            List <CartDetail> cartdetaillist = new List <CartDetail>();
            CartSummary       cartsummary    = new CartSummary();
            Cart     cart     = new Cart();
            FoodItem foodItem = db.FoodItems.Single(fi => fi.FoodItemId == id);

            Session["Restaurant"] = db.Restaurants.Single(f => f.RestaurantId == foodItem.RestaurantId);
            cartdetail.FoodItemId = id;
            cartdetail.FoodItem   = foodItem.FoodItemName;
            cartdetail.Rate       = (decimal)foodItem.FoodItemRate;
            cartdetail.Quantity   = quantity;
            cartdetail.Total      = (decimal)foodItem.FoodItemRate * quantity;
            bool       isAdded        = false;
            int        servicePercent = 0;
            int        vatpercent     = 0;
            decimal    subtotal       = 0;
            decimal    service        = 0;
            decimal    vat            = 0;
            decimal    deliverycharge = 0;
            decimal    gtotal         = 0;
            Restaurant restaurant     = (Restaurant)Session["Restaurant"];

            ViewBag.message = "Added";
            if (restaurant.IsServiceChargeApplicable == true)
            {
                servicePercent = Convert.ToInt32(restaurant.ServiceChargePercent);
            }
            if (restaurant.IsVatApplicable == true)
            {
                vatpercent = Convert.ToInt32(restaurant.VATPercent);
            }
            if (Session["Cart"] != null)
            {
                Restaurant sesrest = ((Cart)Session["Cart"]).restaurantsess;
                if (sesrest != null)
                {
                    if (sesrest.RestaurantId != restaurant.RestaurantId)
                    {
                        //MessageBox.Show("Alert");
                        Session["Cart"] = null;
                        cartdetaillist.Add(cartdetail);
                        cart.cartDetail     = cartdetaillist;
                        ViewData["message"] = "RestaurantChanged";
                        //subtotal = cartdetail.Rate * cartdetail.Quantity;
                        //cartsummary.SubTotal = subtotal;
                        //service = (subtotal) * servicePercent / 100;
                        //cartsummary.ServiceCharge = service;
                        //vat = (service + subtotal) * vatpercent / 100;

                        //cartsummary.VAT = vat;
                        //cartsummary.GrossTotal = subtotal + service + vat + deliverycharge;
                        //cart.cartSummary = cartsummary;
                        //cartsummary.VATPercent = vatpercent;
                        //cartsummary.ServiceChargePercent = servicePercent;
                        //cart.cartSummary = cartsummary;

                        cart.restaurantsess = (Restaurant)Session["Restaurant"];
                        Session["Cart"]     = cart;
                        isAdded             = true;
                    }
                }
                else
                {
                    cart.restaurantsess = restaurant;
                }
                cart           = (Cart)Session["Cart"];
                cartdetaillist = cart.cartDetail;
                foreach (var c in cartdetaillist)
                {
                    if (isAdded == false)
                    {
                        if (c.FoodItemId == id)
                        {
                            c.Quantity = c.Quantity + quantity;
                            c.Total    = c.Rate * c.Quantity;
                            isAdded    = true;
                        }
                    }
                }
                if (isAdded == false)
                {
                    cartdetaillist.Add(cartdetail);
                }
                foreach (var c in cartdetaillist)
                {
                    subtotal = subtotal + c.Rate * c.Quantity;
                }

                cartsummary.SubTotal = subtotal;
                service = (subtotal) * servicePercent / 100;
                cartsummary.ServiceCharge = service;
                vat                              = (service + subtotal) * vatpercent / 100;
                cartsummary.VAT                  = vat;
                cartsummary.GrossTotal           = subtotal + service + vat + deliverycharge;
                cartsummary.ServiceChargePercent = servicePercent;
                cartsummary.VATPercent           = vatpercent;
                cart.cartSummary                 = cartsummary;
            }
            else
            {
                cartdetaillist.Add(cartdetail);
                cart.cartDetail      = cartdetaillist;
                subtotal             = cartdetail.Rate * cartdetail.Quantity;
                cartsummary.SubTotal = subtotal;
                service = (subtotal) * servicePercent / 100;
                cartsummary.ServiceCharge = service;
                vat = (service + subtotal) * vatpercent / 100;

                cartsummary.VAT                  = vat;
                cartsummary.GrossTotal           = subtotal + service + vat + deliverycharge;
                cart.cartSummary                 = cartsummary;
                cartsummary.VATPercent           = vatpercent;
                cartsummary.ServiceChargePercent = servicePercent;
                cart.cartSummary                 = cartsummary;
            }
            cart.restaurantsess = restaurant;
            Session["Cart"]     = cart;
            return(RedirectToAction("Index", new { message = ViewData["message"] }));
        }
Exemplo n.º 27
0
 public bool AddNewCartDeailt(CartDetail cartDetail)
 {
     return(CartDetailDAO.Instance.AddNewCartDeailt(cartDetail));
 }
Exemplo n.º 28
0
 public void UpdateCartDetail(CartDetail cartDetail)
 {
     _cartDetailRepository.Update(cartDetail);
     Commit();
 }
Exemplo n.º 29
0
 public int Add(CartDetail entity, bool persist = true)
 {
     Table.Add(entity);
     return(persist ? SaveChanges() : 0);
 }
Exemplo n.º 30
0
        public static void addToCart(string productId, HttpResponse Response, int quantity = 1)
        {
            CartDetail cd = new CartDetail();

            if (HttpContext.Current.User.Identity.IsAuthenticated)
            {
                using (ArtShopEntities db = new ArtShopEntities())
                {
                    Cart cart    = null;
                    Guid user_id = (Guid)Functions.getLoginUser().ProviderUserKey;

                    if (user_id == null)
                    {
                        Response.Redirect(Constant.LOGIN_URL);
                    }

                    IQueryable <Cart> carts = db.Carts.Where(
                        s => s.user_id == user_id
                        );

                    if (carts.Count() <= 0)
                    {
                        cart = Functions.CreateCart();
                    }
                    else
                    {
                        cart = carts.FirstOrDefault();
                    }

                    if (cart != null)
                    {
                        //string userid = Session["UserId"].ToString(); //user id for the logged in user
                        string productid    = productId; //get product id from the selected product
                        int    pidininteger = Int32.Parse(productid);
                        Art    product      = db.Arts.Find(pidininteger);

                        cd.art_id       = pidininteger;                  //art id
                        cd.availability = product.@virtual? 1: quantity; //1 means available
                        cd.add_date     = DateTime.Now;                  //added item must be recorded on real time\
                        cd.cart_id      = cart.id;

                        CartDetail old_details = db.CartDetails.Find(cart.id, cd.art_id);
                        if (old_details != null)
                        {
                            if (old_details.Art.@virtual)
                            {
                                Functions.EnqueueNewNotifications(new Notifications(
                                                                      Notifications.ERROR_TYPE,
                                                                      "Art already existed in your cart",
                                                                      "This art that you are trying to add is already existed in your shopping cart"));
                            }
                            else
                            {
                                old_details.availability = old_details.availability + quantity;
                                db.CartDetails.AddOrUpdate(old_details);
                                try
                                {
                                    db.SaveChanges();
                                    Functions.EnqueueNewNotifications(new Notifications(
                                                                          Notifications.SUCCESS_TYPE,
                                                                          "Successfully update the quantity!",
                                                                          "You have successful updates \"" + old_details.Art.title + "\" to your shopping cart to " + old_details.availability + " !"));
                                }
                                catch (Exception)
                                {
                                    Functions.EnqueueNewNotifications(new Notifications(
                                                                          Notifications.ERROR_TYPE,
                                                                          "Art already existed in your cart",
                                                                          "This art that you are trying to add is already existed in your shopping cart"));
                                }
                            }
                        }
                        else
                        {
                            db.CartDetails.Add(cd);
                            try
                            {
                                db.SaveChanges();
                                Functions.EnqueueNewNotifications(new Notifications(
                                                                      Notifications.SUCCESS_TYPE,
                                                                      "Successfully added to shopping cart!",
                                                                      "You have successful added " + db.Arts.Find(cd.art_id).title + " to your shopping cart!"));
                            }
                            catch (Exception)
                            {
                                Functions.EnqueueNewNotifications(new Notifications(
                                                                      Notifications.ERROR_TYPE,
                                                                      "Art already existed in your cart",
                                                                      "This art that you are trying to add is already existed in your shopping cart"));
                            }
                        }
                    }
                }
            }
            else
            {
                Functions.EnqueueNewNotifications(new Notifications(
                                                      Notifications.ERROR_TYPE,
                                                      "Login required!",
                                                      "You must login before trying to add in new item to cart !!"));


                Response.Redirect(Constant.LOGIN_URL);
            }
        }