Example #1
0
        public JsonResult createProduct(int id)
        {
            // lúc này thêm bao nhiêu nữa thì nó cũng thêm vào cái list lưu seesion nên sẽ lấy được
            var product = db.SANPHAMs.
                          Include(t => t.HINHs).Where(x => x.Id_SanPham == id).SingleOrDefault();
            List <ProductCart> productCarts = GetProductCarts();

            // tao moi mot san pham
            ProductCart productCart = new ProductCart();

            if (product != null)
            {
                var gia      = db.GIASANPHAMs.Where(g => g.TrangThai != false && g.Id_SanPham == product.Id_SanPham).OrderByDescending(g => g.NgayLap).Select(g => g.GiaBan).FirstOrDefault();
                var phantram = db.KHUYENMAIs.Where(k => k.Id_KhuyenMai == product.Id_KhuyenMai).OrderByDescending(k => k.NgayKetThuc).Select(g => g.GiaTriKhuyenMai).FirstOrDefault();
                productCart = new ProductCart()
                {
                    Id_SanPham      = product.Id_SanPham,
                    TenSanPham      = product.TenSanPham,
                    HinhAnh         = product.HinhAnh ?? product.HINHs.FirstOrDefault().Link,
                    loaisp          = product.LOAISANPHAM.TenLoai,
                    giagoc          = gia,
                    KichThuoc       = product.KichThuoc,
                    MauSac          = product.MauSac,
                    soluong         = 1,
                    phantramgiamgia = phantram,
                    giagiam         = gia * ((100 - phantram) / 100)
                };
            }

            var productIncart = productCarts.Where(p => p.Id_SanPham == id).SingleOrDefault();

            if (productIncart == null)
            {
                productCarts.Add(productCart);
            }
            else
            {
                productIncart.soluong += 1;
            }
            var totatQuantity = totalQuantity();

            return(Json(new { productCart = productCart, totalQuantity = totatQuantity }, JsonRequestBehavior.AllowGet));
        }
Example #2
0
        public JsonResult AddCart(int ProductID, int Quanlity)
        {
            var product      = new ProductCart().ViewDetail(ProductID);
            var session_cart = Session["CartItem"];

            if (session_cart != null)
            {
                var list = (List <CartModel>)session_cart;

                if (list.Exists(x => x.Product.ProductID == ProductID))
                {
                    foreach (var item in list)
                    {
                        if (item.Product.ProductID == ProductID)
                        {
                            item.Quanlity += Quanlity;
                        }
                    }
                }
                else
                {
                    var item = new CartModel();
                    item.Product  = product;
                    item.Quanlity = Quanlity;
                    list.Add(item);
                }
                Session["CartItem"] = list;
            }
            else
            {
                var item = new CartModel();
                item.Product  = product;
                item.Quanlity = Quanlity;
                var list = new List <CartModel>();

                list.Add(item);

                Session["CartItem"] = list;
            }

            return(null);
        }
Example #3
0
        // Delete Productfrom Cart
        // http://localhost:13149/api/Cart?Product_id=1
        public IHttpActionResult Delete_Product(int Product_id)
        {
            var user_id      = User.Identity.GetUserId();
            var product_Cart = db.ProductCarts.Where(pc => pc.Cart_Id == user_id).ToList();

            foreach (var item in product_Cart)
            {
                if (item.Product_Id == Product_id)
                {
                    ProductCart proCart = db.ProductCarts.Find(item.Id);
                    if (proCart == null)
                    {
                        return(NotFound());
                    }
                    db.ProductCarts.Remove(proCart);
                    db.SaveChanges();
                }
            }
            return(Ok("Product Deleted"));
        }
        public HttpResponseMessage GetProductCart(string key)
        {
            HttpResponseMessage response           = new HttpResponseMessage(HttpStatusCode.Unused);
            ProductCartService  productcartservice = new ProductCartService();
            List <ProductCart>  productcart        = productcartservice.Read();
            int id = productcartservice.GetProductCartIndex(key);

            if (id != -1)
            {
                ProductCart pc = productcart[id];
                string      productcartJSON = JsonConvert.SerializeObject(pc, Formatting.Indented);
                response         = new HttpResponseMessage(HttpStatusCode.OK);
                response.Content = new StringContent(productcartJSON, Encoding.UTF8, "application/json");
            }
            else
            {
                response = new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
            }
            return(response);
        }
        public JsonResult List()
        {
            if (Session["sepet"] != null)
            {
                ProductCart      cart        = Session["sepet"] as ProductCart;
                List <ProductVM> productList = cart.CartProductList.Select(x => new ProductVM
                {
                    ID          = x.ID,
                    ProductName = x.ProductName,
                    UnitPrice   = x.UnitPrice,
                    UnitInStock = x.UnitInStock,
                    Quantity    = x.Quantity,
                    ImagePath   = x.ImagePath
                }).ToList();

                return(Json(productList, JsonRequestBehavior.AllowGet));
            }

            return(Json("Empty", JsonRequestBehavior.AllowGet));
        }
        public ActionResult ViewOrders()
        {
            List <ViewOrderList> orderList = new List <ViewOrderList>();

            foreach (Order item in orderRepo.GetAll())
            {
                Buyer       buyer = buyerRepo.Get(item.BuyerId);
                ProductCart cart  = cartRepo.Get(item.CartId);

                if (!item.Delivered)
                {
                    orderList.Add(new ViewOrderList()
                    {
                        Id = item.OrderId, BuyerName = buyer.FirstName + " " + buyer.LastName, OrderDate = cart.OrderTime, DeliveryStatus = "Not Delivered"
                    });
                }
            }

            return(View(orderList));
        }
Example #7
0
        public bool SaveNewProductToCart(int Product_id, int Quentity, string user_ID)
        {
            var Checkcart = TheUnitOfWork.Cart.GetById(user_ID);

            if (Checkcart == null)
            {
                Cart cart = new Cart {
                    User_Id = user_ID
                };
                if (TheUnitOfWork.Cart.Insert(cart))
                {
                    TheUnitOfWork.Commit();
                }
            }
            bool result        = false;
            var  productInCart = TheUnitOfWork.ProductCart.GetWhere(p => p.Cart_Id == user_ID && p.Product_Id == Product_id).FirstOrDefault();

            if (productInCart != null)
            {
                productInCart.Quntity += Quentity;
                TheUnitOfWork.ProductCart.Update(productInCart);
                TheUnitOfWork.Commit();
                return(result);
            }
            else
            {
                var         product  = TheUnitOfWork.Product.GetById(Product_id);
                ProductCart pro_cart = new ProductCart {
                    Cart_Id = user_ID, Product_Id = Product_id, Quntity = Quentity, Product = product
                };



                //var product = Mapper.Map<Product>(productViewModel);
                if (TheUnitOfWork.ProductCart.Insert(pro_cart))
                {
                    result = TheUnitOfWork.Commit() > new int();
                }
                return(result);
            }
        }
Example #8
0
        public bool ToCart(Product product, Cart cart, int quantity)
        {
            using (var _context = new ShoppingListContext())
            {
                var entity = _context.ProductCart.FirstOrDefault(p => p.Product_ProductId == product.Id);
                if (entity == null)
                {
                    entity = new ProductCart()
                    {
                        Cart_CartId = cart.Id, Product_ProductId = product.Id, Quantity = quantity
                    };
                    _context.ProductCart.Add(entity);
                }

                entity.Quantity += quantity;

                DbContextHelper.HandleUniqueKeyViolation(() => _context.SaveChanges());

                return(true);
            }
        }
Example #9
0
        public async Task <ProductCart> AddToCart(ProductCart productCart, int quantity, string userId)
        {
            var cart = await GetByUser(userId);

            var existingProductCart = cart.ProductCarts.FirstOrDefault(x => x.ProductId == productCart.Product.Id);

            if (existingProductCart != null)
            {
                existingProductCart.Quantity += quantity;
                _productCartRepository.Update(existingProductCart);
                return(existingProductCart);
            }
            else
            {
                var newProductCart = new ProductCart {
                    ProductId = productCart.Product.Id, CartId = cart.Id, Quantity = quantity
                };
                await _productCartRepository.Add(newProductCart);

                return(newProductCart);
            }
        }
Example #10
0
        public ActionResult List()
        {
            //Sepet varsa. Session içerisinde sepet isminde bir değer varsa, o zaman sepetteki tüm ürünleri bir liste halinde istemciye gönderiyoruz.
            if (Session["sepet"] != null)
            {
                ProductCart cart = Session["sepet"] as ProductCart;

                List <CartProductVM> productList = cart.CartProductList.Select(x => new CartProductVM
                {
                    ID          = x.ID,
                    ProductName = x.ProductName,
                    UnitPrice   = x.UnitPrice,
                    Quantity    = x.Quantity
                }).ToList();

                return(Json(productList, JsonRequestBehavior.AllowGet));
            }
            else
            {
                return(Json("Empty", JsonRequestBehavior.AllowGet));
            }
        }
        public async Task <ActionResult <ProductCart> > PostProductCart(ProductCart productCart)
        {
            try
            {
                var productCount = _context.ProductCart.Where(x => x.UserId == productCart.UserId && x.CartProductId == productCart.CartProductId).Select(x => x.ProductCount).FirstOrDefault();



                if (productCount != 0)
                {
                    var CartId = _context.ProductCart.Where(x => x.UserId == productCart.UserId && x.CartProductId == productCart.CartProductId).Select(x => x.Id).FirstOrDefault();
                    var pCart  = await _context.ProductCart.FindAsync(CartId);

                    productCount = productCount + 1;

                    pCart.ProductCount = productCount;
                    _context.ProductCart.Update(pCart);
                    _context.SaveChanges();
                    return(pCart);
                }
                else
                {
                    var pCart = new ProductCart
                    {
                        UserId        = productCart.UserId,
                        CartProductId = productCart.CartProductId,
                        ProductCount  = 1
                    };
                    _context.ProductCart.Add(pCart);
                    _context.SaveChanges();
                    return(pCart);
                }
            }
            catch (DbUpdateConcurrencyException)
            {
                throw;
            }
        }
        public ActionResult Order(Order order)
        {
            int      restId   = order.RestaurantID;
            int      cookId   = order.CookID;
            int      paymetId = order.PaymentID;
            string   adres    = order.Address;
            DateTime dateTime = order.RequestedDate;

            ProductCart      cart        = Session["sepet"] as ProductCart;
            List <ProductVM> productList = cart.ChartProductList.Select(x => new ProductVM
            {
                Id           = x.Id,
                ProductName  = x.ProductName,
                UnitPrice    = x.UnitPrice,
                UnitsInstock = x.UnitsInstock,
                Quantity     = x.Quantity
            }).ToList();

            foreach (ProductVM item in productList)
            {
                order.RestaurantID  = restId;
                order.CookID        = cookId;
                order.PaymentID     = paymetId;
                order.Address       = adres;
                order.RequestedDate = dateTime;
                order.RecipeID      = item.Id;
                order.Quantity      = item.Quantity;
                order.OrderPrice    = (decimal)item.UnitPrice * item.Quantity;
                order.UserID        = ((User)Session["user"]).UserID;
                order.OrderDate     = DateTime.Now;
                order.IsActive      = true;
                order.CreateDate    = DateTime.Now;
                order.OrderStatus   = "Onaylanmadı";
                _orderService.Insert(order);
                order = new Order();
            }
            return(RedirectToAction("Index", "Home"));
        }
Example #13
0
        public ActionResult Add(Guid id)
        {
            //gelen id'ye ait ürünü yakalıyoruz.
            Product sepeteEklenecekUrun = _productService.GetById(id);

            CartProductVM model = new CartProductVM
            {
                ID          = sepeteEklenecekUrun.ID,
                ProductCode = sepeteEklenecekUrun.ProductCode,
                Name        = sepeteEklenecekUrun.Name,
                Quantity    = 1
            };

            //Session Nedir ?
            //Server taraflı verileri tutmak için tasarlanmış bir yapıdır.
            //Kullanıcı oturumlarını, sepet vb yapıları client-server iletişimi sırasında saklamamıza yarar.
            //Session object tipinde değer tutar bu nedenle cast etmek gereklidir.
            if (Session["sepet"] != null)
            {
                //Eğer sepet varsa, session içerisinden o sepeti getiriyorum.
                ProductCart cart = Session["sepet"] as ProductCart;
                cart.AddCart(model);

                //Ürün eklendikten sonra yeni sepeti tekrar session'a atıyoruz
                Session["sepet"] = cart;
            }
            else
            {
                //eğer session içerisinde sepet yoksa yenisi oluşturulur.
                ProductCart cart = new ProductCart();
                cart.AddCart(model);
                Session.Add("sepet", cart);
                Session["sepet"] = cart;
            }

            //İsterseniz mesaj gönderebilirsiniz.
            return(Json("Sepete başarıyla eklendi!"));
        }
        public HttpResponseMessage UpdateProductCart(Object content, string key)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unused);

            try
            {
                ProductCart        productcart = JsonConvert.DeserializeObject <ProductCart>(content.ToString());
                ProductCartService pcs         = new ProductCartService();
                if (pcs.Update(key, productcart))
                {
                    response = new HttpResponseMessage(HttpStatusCode.OK);
                }
                else
                {
                    response = new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
                }
            }
            catch
            {
                response = Request.CreateResponse(HttpStatusCode.Unused);
            }
            return(response);
        }
Example #15
0
        //Sepete Ekleme
        public ActionResult Add(Guid id)
        {
            //gelen idye ait ürünü yakalıyoruz.
            Product       sepeteEklenecekurun = _productService.GetById(id);
            CartProductVM model = new CartProductVM();

            model.ID          = sepeteEklenecekurun.ID;
            model.ProductName = sepeteEklenecekurun.Name;
            model.UnitPrice   = sepeteEklenecekurun.Price;
            model.Quantity    = 1;


            //Session Nedir ?
            //Server taraflı verileri tutmak için tasarlanmış bir yapıdır.
            //Kullanıcı oturumlarını, sepet vb yapıları client-server iletişimi sırasında saklamamıza yarar.
            //Session object tipinde değer tutar bu nedenle cast etmek gereklidir.
            if (Session["sepet"] != null)
            {
                //Session içerisinde bir sepet varsa
                ProductCart cart = Session["sepet"] as ProductCart;
                cart.AddCart(model);
                //Ürün eklendikten sonra sepetin son halini sessiona at
                Session["sepet"] = cart;
            }
            else
            {
                //Session içerisinde bir sepet yoksa
                ProductCart cart = new ProductCart();
                cart.AddCart(model);
                //Session'ı ilk kez oluşturuyoruz.
                Session.Add("sepet", cart);
            }

            ProductCart cartSon = Session["sepet"] as ProductCart;

            return(Json(cartSon.CartProductList.Count));
        }
Example #16
0
        private List <ShoppingItem> UpdateCartItems()
        {
            var cart = new ProductCart();

            string cartGuid = cart.GetCartGuid();

            ProductCart.ShoppingCartUpdates[] cartUpdates = new ProductCart.ShoppingCartUpdates[CartList.Rows.Count];
            for (int i = 0; i < CartList.Rows.Count; i++)
            {
                var rowValue = GetValues(CartList.Rows[i]);
                cartUpdates[i].ProductId = int.Parse(rowValue["ProductId"].ToString());

                var cbRemove = (CheckBox)CartList.Rows[i].FindControl("Remove");
                cartUpdates[i].RemoveItem = cbRemove.Checked;

                var quantityTextBox = (TextBox)CartList.Rows[i].FindControl("PurchaseQuantity");
                cartUpdates[i].PurchaseQuantity = int.Parse(quantityTextBox.Text);
            }

            cart.UpdateShoppingCart(cartGuid, cartUpdates);
            CartList.DataBind();
            lblTotal.Text = $"{cart.GetTotal():c}";
            return(cart.GetCartItems());
        }
        public HttpResponseMessage PostCart(Object content)
        {
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unused);

            try
            {
                String             productcartJSON = content.ToString();
                ProductCart        productcart     = JsonConvert.DeserializeObject <ProductCart>(productcartJSON);
                ProductCartService pcs             = new ProductCartService();
                if (pcs.Create(productcart))
                {
                    response = new HttpResponseMessage(HttpStatusCode.OK);
                }
                else
                {
                    response = new HttpResponseMessage(HttpStatusCode.ExpectationFailed);
                }
            }
            catch
            {
                response = new HttpResponseMessage(HttpStatusCode.Unused);
            }
            return(response);
        }
Example #18
0
        public int AddProductToShoppingCart(int id, int quantity)
        {
            try
            {
                List <ProductCart> _lstProductCart = GetShoppingCart();

                ProductCart _ProductCart = _lstProductCart.Find(n => n.PRODUCT_ID == id);
                if (_ProductCart == null)
                {
                    _ProductCart = new ProductCart(id, quantity);
                    _lstProductCart.Add(_ProductCart);
                }
                else
                {
                    _ProductCart.QUANTITY += quantity;
                }

                return(GetTotalQuantity());
            }
            catch (Exception ex)
            {
                return(0);
            }
        }
Example #19
0
        public async Task <ActionResult <ProductCart> > AddProductInProductCart(int userId, int bookId, [FromQuery(Name = "quantity")] int quantity)
        {
            if (UserExists(userId))
            {
                var CheckUser = await _context.Users.FindAsync(userId);

                if (BookExists(bookId))
                {
                    var CheckBook = await _context.Books.FindAsync(bookId);

                    if (CheckBook.Quantity >= quantity)
                    {
                        if (ProductCartExists(CheckUser.Id, CheckBook.Id, true))
                        {
                            var ProductCart = _context.ProductCarts.Where(s => s.UserId.Equals(CheckUser.Id) && s.BookId.Equals(CheckBook.Id) && s.Status.Equals(true)).FirstOrDefault();
                            if (ProductCart.Quantity + quantity <= CheckBook.Quantity)
                            {
                                _context.Entry(ProductCart).State = EntityState.Modified;
                                try
                                {
                                    ProductCart.Quantity = ProductCart.Quantity + quantity;
                                    await _context.SaveChangesAsync();
                                }
                                catch (DbUpdateConcurrencyException)
                                {
                                    throw;
                                }

                                return(Ok("Add product in product cart successful!"));
                            }
                            else
                            {
                                return(BadRequest("Quantity product is not enough to add to cart product!"));
                            }
                        }
                        else
                        {
                            var ProductCart = new ProductCart();
                            ProductCart.UserId   = CheckUser.Id;
                            ProductCart.User     = CheckUser;
                            ProductCart.BookId   = CheckBook.Id;
                            ProductCart.Book     = CheckBook;
                            ProductCart.Quantity = quantity;
                            _context.ProductCarts.Add(ProductCart);
                            await _context.SaveChangesAsync();

                            return(Ok("Add product in product cart successfull"));
                        }
                    }
                    else
                    {
                        return(BadRequest("Quantity product is not enough to add to cart product!"));
                    }
                }
                else
                {
                    return(NotFound("Book can not found by book id!"));
                }
            }
            else
            {
                return(NotFound("User can not found by userId!"));
            }
        }
Example #20
0
 public ProductCart RemoveCartItem(ProductCart productCart)
 {
     return(_productCartRepository.Remove(productCart));
 }
Example #21
0
        public int Insert(ProductCart cart)
        {
            context.ProductCarts.Add(cart);

            return(context.SaveChanges());
        }
Example #22
0
 public ProductCart UpdateCartItem(ProductCart productCart)
 {
     return(_productCartRepository.Update(productCart));
 }
Example #23
0
        public async Task <IActionResult> Create([Bind("Id,ProductId,Amount,FinalPrice")] ProductCart productCart)
        {
            productCart.Product = _context.Product.Where(p => p.Id == productCart.ProductId).FirstOrDefault();
            if (HttpContext.Session.GetString("userId") == null)
            {
                return(View("../users/Login"));
            }
            if (ModelState.IsValid)
            {
                var myShoppingCartId = HttpContext.Session.GetString("CartId");
                if (myShoppingCartId == null || myShoppingCartId == "Deleted")
                {
                    var myNewShoppingCart = new Cart()
                    {
                        DateCreate   = DateTime.Now,
                        ProductsCart = new System.Collections.ObjectModel.ObservableCollection <ProductCart>(),
                        UserId       = int.Parse(HttpContext.Session.GetString("userId")),
                        User         = _context.User.Where(u => u.Id == int.Parse(HttpContext.Session.GetString("userId"))).FirstOrDefault()
                    };
                    //myNewShoppingCart.ProductsCart.Add(productCart);
                    // myNewShoppingCart.Id = int.Parse(myShoppingCartId);
                    _context.Add(myNewShoppingCart);
                    await _context.SaveChangesAsync();

                    myShoppingCartId = myNewShoppingCart.Id.ToString();
                    HttpContext.Session.SetString("CartId", myShoppingCartId);
                }

                ProductCart test = _context.ProductCart.Include(pc => pc.Product).Include(pc => pc.Cart).Where(pc => pc.Product.Name == productCart.Product.Name)
                                   .Where(pc => pc.Cart.Id == Int32.Parse(myShoppingCartId)).FirstOrDefault();
                if (test == null)
                {
                    var newProductInCart = new ProductCart()
                    {
                        Amount     = productCart.Amount,
                        Product    = _context.Product.Where(p => p.Id == productCart.ProductId).FirstOrDefault(),
                        ProductId  = productCart.ProductId,
                        FinalPrice = (productCart.Amount * productCart.Product.Price),
                        Cart       = _context.Cart.Where(S => S.Id == int.Parse(myShoppingCartId)).FirstOrDefault(),
                        CartId     = int.Parse(myShoppingCartId)
                    };

                    _context.Add(newProductInCart);
                    await _context.SaveChangesAsync();

                    return(View("../Products/Index", _context.Product));
                }
                else
                {
                    test.Amount     += productCart.Amount;
                    test.FinalPrice += productCart.Product.Price * productCart.Amount;
                    _context.Update(test);
                    await _context.SaveChangesAsync();

                    return(View("../Products/Index", _context.Product));
                }
            }
            // ViewData["ProductId"] = new SelectList(_context.Product, "Id", productCart.ProductId);
            ViewData["ProductId"] = new SelectList(_context.Product, "Id");
            return(View(productCart));
        }
Example #24
0
 public ProductCart Remove(ProductCart productCart)
 {
     _context.Entry(productCart).State = EntityState.Deleted;
     _context.SaveChanges();
     return(productCart);
 }
Example #25
0
 public ActionResult Edit(ProductCart productCart)
 {
     productCartAppService.UpdateProductCart(productCart);
     return(Redirect("Index"));
 }
Example #26
0
        public ActionResult Edit(int ProductCart_Id)
        {
            ProductCart productCart = productCartAppService.GetById(ProductCart_Id);

            return(View(productCart));
        }
 public bool UpdateProductCart(ProductCart productCart)
 {
     TheUnitOfWork.ProductCart.Update(productCart);
     TheUnitOfWork.Commit();
     return(true);
 }
        public async Task <JsonResult> ProductOfCart(int?id)
        {
            try
            {
                if (id != null)
                {
                    if (HttpContext.User.Identity.IsAuthenticated)
                    {
                        string name = HttpContext.User.Identity.Name;

                        AppUser appUser = await _baselDb.AppUsers
                                          .Where(x => x.UserName == name)
                                          .Include(x => x.Cart)
                                          .SingleOrDefaultAsync();

                        Product product = null;

                        product = await _baselDb.Products.Where(x => x.Stock > 0)
                                  .Where(x => x.Id == id).SingleOrDefaultAsync();

                        if (await _signInManager.CanSignInAsync(appUser))
                        {
                            if (product != null)
                            {
                                int?CartId = null;

                                if (appUser.Cart != null)
                                {
                                    CartId = appUser.CartId;

                                    Cart cart = _baselDb.Carts.Where(x => x.Id == CartId)
                                                .Include(x => x.ProductCarts).SingleOrDefault();

                                    int ProductId = cart.ProductCarts
                                                    .Where(x => x.ProductId == id)
                                                    .Select(x => x.ProductId)
                                                    .SingleOrDefault();

                                    if (ProductId == id)
                                    {
                                        int ProductCount = cart.ProductCarts
                                                           .Where(x => x.ProductId == id)
                                                           .Select(x => x.ProductCount)
                                                           .SingleOrDefault();

                                        ProductCount++;

                                        cart.ProductCarts.Where(x => x.ProductId == id)
                                        .Select(c => { c.ProductCount = ProductCount; return(c); }).ToList();
                                    }
                                    else
                                    {
                                        ProductCart productCart = new ProductCart()
                                        {
                                            ProductId    = (int)id,
                                            CartId       = (int)CartId,
                                            ProductCount = 1
                                        };

                                        cart.ProductCarts.Add(productCart);
                                    }

                                    int productStock = product.Stock;

                                    productStock--;

                                    product.Stock = productStock;

                                    await _baselDb.SaveChangesAsync();
                                }
                                else
                                {
                                    List <ProductCart> productCarts = new List <ProductCart>()
                                    {
                                        new ProductCart()
                                        {
                                            ProductId    = (int)id,
                                            ProductCount = 1
                                        }
                                    };

                                    Cart cart = new Cart()
                                    {
                                        AppUser      = appUser,
                                        ProductCarts = productCarts
                                    };

                                    int productStock = product.Stock;

                                    productStock--;

                                    product.Stock = productStock;

                                    _baselDb.Carts.Add(cart);

                                    _baselDb.SaveChanges();

                                    Cart cartDb = _baselDb.Carts.Where(x => x.AppUserId == appUser.Id).SingleOrDefault();

                                    appUser.CartId = cartDb.Id;
                                    appUser.Cart   = cartDb;

                                    await _userManager.UpdateAsync(appUser);
                                }

                                List <Product> productsAll = await _baselDb.Products
                                                             .Include(x => x.ProductCarts)
                                                             .Where(x => x.ProductCarts.Any(z => z.CartId == CartId))
                                                             .Include(x => x.ProductLanguages)
                                                             .Include(x => x.Images)
                                                             .ToListAsync();

                                if (productsAll != null)
                                {
                                    int?cultures = HttpContext.Session.GetInt32("culture");

                                    if (cultures == null)
                                    {
                                        cultures = GetLanguage
                                                   .GetLangId();
                                    }

                                    List <object> list = new List <object>();

                                    foreach (Product item in productsAll)
                                    {
                                        list.Add(new
                                        {
                                            item.Id,
                                            Name  = item.ProductLanguages.Where(x => x.LanguageId == cultures).Select(x => x.Name).SingleOrDefault(),
                                            Count = item.ProductCarts.Where(x => x.CartId == CartId).Select(x => x.ProductCount).SingleOrDefault(),
                                            Image = ConvertImage(item.Images.Select(x => x.FileName).FirstOrDefault()),
                                            item.Price
                                        });
                                    }

                                    return(new JsonResult(list));
                                }
                            }
                            return(Json("Product is not found"));
                        }
                    }
                    return(Json("Please, Sign In to the Site"));
                }
                return(Json("Product Id is not found"));
            }
            catch (Exception exp)
            {
                return(Json(exp.Message));
            }
        }
Example #29
0
        public IHttpActionResult Post_Pro(int Product_id)
        {
            string userID         = "";
            var    claimsIdentity = User.Identity as ClaimsIdentity;

            if (claimsIdentity != null)
            {
                var userIdClaim = claimsIdentity.Claims.FirstOrDefault(y => y.Type == ClaimTypes.NameIdentifier);

                if (userIdClaim != null)
                {
                    userID = userIdClaim.Value;
                }
            }


            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var Checkcart = db.Carts.Find(userID);

            if (Checkcart == null)
            {
                Cart cart = new Cart {
                    AccountID = userID
                };
                db.Carts.Add(cart);
                db.SaveChanges();
            }

            var productInCart = db.ProductCarts.Where(p => p.Cart_Id == userID && p.Product_Id == Product_id).FirstOrDefault();

            if (productInCart != null)
            {
                productInCart.Quntity        += 1;
                db.Entry(productInCart).State = EntityState.Modified;
                try
                {
                    db.SaveChanges();
                    return(Ok("Product Added To cart"));
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!CategoryExists(Product_id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
            }
            ProductCart pro_cart = new ProductCart {
                Cart_Id = userID, Product_Id = Product_id, Quntity = 1
            };

            db.ProductCarts.Add(pro_cart);
            db.SaveChanges();



            //return CreatedAtRoute("DefaultApi", new { id = pro_cart.Id }, pro_cart);
            return(Ok("Product Add To cart"));
        }
Example #30
0
 public ProductCart Update(ProductCart productCart)
 {
     _context.Entry(productCart).State = EntityState.Modified;
     _context.SaveChanges();
     return(productCart);
 }