示例#1
0
        public JsonResult AddToCart(int id)
        {
            // get book
            var getMovieById = _movieService.GetMovieById(id);
            // get logged in user id
            var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            // get other data ids
            var movieId     = getMovieById.Id;
            var directorId  = getMovieById.DirectorID;
            var producerId  = getMovieById.ProducerID;
            var publisherId = getMovieById.PublisherID;
            var genreId     = getMovieById.GenreID;

            // init shopping cart obj
            var shoppingCart = new ShoppingCart
            {
                UserId    = userId,
                MovieId   = movieId,
                Price     = getMovieById.PriceForRent,
                DateAdded = DateTime.Now
            };

            // add to shopping cart
            _shoppingCartService.Add(shoppingCart);

            return(new JsonResult(new { data = shoppingCart }));
        }
        public bool Add(ShoppingCartModelView ShoppingCart) //Bu metodu bozmayalım
        {
            ShoppingCart newShoppingCart = new ShoppingCart();

            newShoppingCart.UserID    = ShoppingCart.UserID;
            newShoppingCart.ProductID = ShoppingCart.ProductID;
            newShoppingCart.Quantity  = ShoppingCart.Quantity;

            ShoppingCart existShoppingCart = _shoppingCartService.GetByFilter(a => a.UserID == newShoppingCart.UserID & a.ProductID == newShoppingCart.ProductID);

            if (existShoppingCart == null)
            {
                if (_shoppingCartService.Add(newShoppingCart))
                {
                    return(true);
                }

                return(false);
            }
            else
            {
                existShoppingCart.Quantity += newShoppingCart.Quantity;

                if (_shoppingCartService.Update(existShoppingCart))
                {
                    return(true);
                }

                return(false);
            }
        }
示例#3
0
        public ShoppingCartViewModel Add(ShoppingCartViewModel shoppingCartViewModel)
        {
            var shoppingCart = new ShoppingCart
            {
                Id     = shoppingCartViewModel.Id,
                Active = shoppingCartViewModel.Active,
                Number = shoppingCartViewModel.Number
            };

            foreach (var item in shoppingCartViewModel.ItemsViewModel)
            {
                ShoppingCartItem shoppingCartItem = new ShoppingCartItem {
                    Id = item.Id, ProductId = item.ProductId, ShoppingCartId = item.ShoppingCartId
                };
                shoppingCart.AddItem(shoppingCartItem);
            }

            BeginTransaction();

            _shoppingCartService.Add(shoppingCart);

            Commit();

            return(shoppingCartViewModel);
        }
        public virtual ActionResult AddToCart(int courseId)
        {
            var course = coursesService.GetCourseById(courseId);

            shoppingCartService.Add(course);
            return(RedirectToAction(MVC.ShoppingCart.Index()));
        }
        public JsonResult AddToCartFromWishlist(List <string> movieIds)
        {
            // add to temporary list
            List <string> movieIds_temp = movieIds;

            foreach (var movie in movieIds_temp)
            {
                var getMovie = _movieService.GetMovieById(int.Parse(movie));

                // get logged in user id
                var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
                // get other data ids
                var movieId = getMovie.Id;

                // init shopping cart obj
                var shoppingCart = new ShoppingCart
                {
                    UserId  = userId,
                    MovieId = movieId,
                    //      Price = getMovie.PriceForRent,
                    DateAdded = DateTime.Now
                };

                // add single movie from wishlist to shopping cart
                _shoppingCartService.Add(shoppingCart);
            }

            // remove all selected items from wishlist
            foreach (var selectedItem in movieIds)
            {
                _wishlistService.DeleteByMovieId(int.Parse(selectedItem));
            }

            return(new JsonResult(new { data = "" }));
        }
示例#6
0
        public JsonResult AddToCart(int id)
        {
            // get book
            var getBookById = _bookService.GetBookById(id);
            // get logged in user id
            var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
            // get other data ids
            var bookId      = getBookById.Id;
            var publisherId = getBookById.PublisherID;
            var authorId    = getBookById.AuthorID;
            var categoryId  = getBookById.CategoryID;

            // init shopping cart obj
            var shoppingCart = new ShoppingCart
            {
                UserId    = userId,
                BookId    = bookId,
                Price     = getBookById.Price,
                DateAdded = DateTime.Now
            };

            // add to shopping cart
            _shoppingCartService.Add(shoppingCart);

            return(new JsonResult(new { data = shoppingCart }));
        }
        public virtual async Task <ActionResult> AddToCart(long?productId, decimal?value)
        {
            if (productId == null)
            {
                return(Content(null));
            }
            var product = _productService.GetById(productId.Value);

            if (product == null)
            {
                return(Content(null));
            }
            var count  = value ?? product.Ratio;
            var result = decimal.Remainder(count, product.Ratio);

            if (result != decimal.Zero)
            {
                return(Content(null));
            }

            if (!_productService.CanAddToShoppingCart(productId.Value, count))
            {
                return(Content("nok"));
            }

            var cartItem = _shoppingCartService.GetCartItem(productId.Value, User.Identity.Name);

            product.Reserve += count;

            if (cartItem == null)
            {
                _shoppingCartService.Add(new ShoppingCart
                {
                    CartNumber = User.Identity.Name,
                    Quantity   = count,
                    ProductId  = productId.Value,
                    CreateDate = DateTime.Now
                });
            }
            else
            {
                cartItem.Quantity += count;
            }

            await _unitOfWork.SaveAllChangesAsync(false);

            var totalValueInCart = _shoppingCartService.TotalValueInCart(User.Identity.Name);

            if (string.IsNullOrEmpty(HttpContext.GetCookieValue(TotalInCartCookieName)))
            {
                HttpContext.AddCookie(TotalInCartCookieName, totalValueInCart.ToString(CultureInfo.InvariantCulture), DateTime.Now.AddDays(1));
            }
            else
            {
                HttpContext.UpdateCookie(TotalInCartCookieName, totalValueInCart.ToString(CultureInfo.InvariantCulture));
            }

            return(Content("ok"));
        }
示例#8
0
        public IActionResult PostShoppingItem(ShoppingItem shoppingItem)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var item = _service.Add(shoppingItem);

            return(CreatedAtAction("Get", new { id = item.Id }, item));
        }
        public ActionResult Post([FromBody] CartItem value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            _service.Add(value);
            return(CreatedAtAction("Get", new { id = value.Id }, value));
        }
        public ActionResult Post([FromBody] ShoppingItem value)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            var item = _service.Add(value);

            return(CreatedAtAction("Get", new { id = item.Id }, item));
        }
        public IActionResult Add(ShoppingCartProductDTO shoppingCartProduct)
        {
            //todo : login servise  checktoken ı cagır
            //eğer ilgili token gecersizse login api hata doner bizde sepete ekleme işlemini iptal ederiz.,
            //checktoken başarılı dondugu varsayıp devam ediyoruz. (****eklenecek)
            //checktoken userın idsini donsun
            ShoppingCartResponse response = new ShoppingCartResponse();

            response = _service.Add(shoppingCartProduct.Token, shoppingCartProduct.UserID, shoppingCartProduct.ProductID, shoppingCartProduct.ProductCount);
            return(response.Code != (int)Constants.ResponseCode.SUCCESS ? StatusCode(500, response) : StatusCode(201, response));
        }
        public ShoppingCartViewModel Add(ShoppingCartViewModel shoppingCartViewModel)
        {
            var shoppingCart = Mapper.Map <ShoppingCartViewModel, ShoppingCart>(shoppingCartViewModel);

            BeginTransaction();

            _shoppingCartService.Add(shoppingCart);

            Commit();

            return(shoppingCartViewModel);
        }
示例#13
0
 private void AddShoppingCartForm_Load(object sender, EventArgs e)
 {
     _shoppingCart = new DataContextModel.Models.ShoppingCart()
     {
         ClientId  = _clientId,
         Date      = DateTime.Now,
         Delivered = false,
         Number    = "1"
     };
     _cartService.Add(_shoppingCart);
     comboBoxProduct.DataSource = _productService.GetAllNames().ToArray();
     dataGridCart.DataSource    = _bindingListCart;
 }
        public ActionResult Add([FromRoute] string sku)
        {
            var product = _repository.GetById(sku);

            if (product == null)
            {
                string msg = "SKU not found: " + sku;
                _logger.LogError(msg);
                return(BadRequest(msg));
            }

            var cartEntry = _service.Add(product.SKU, product.UnitPrice);

            return(this.CreatedAtAction(nameof(this.Get), new { cartEntry.SKU }, cartEntry));
        }
示例#15
0
        public TModel <bool> AddProductToCart(int productId)
        {
            string token = Request.Cookies["access_token"];

            if (string.IsNullOrEmpty(token))
            {
                return(new TModel <bool>()
                {
                    status = 10,
                    message = "token过期",
                    Data = false
                });
            }

            //方式一:JwtSecurityTokenHandler中的ReadJwtToken()方法获取
            JwtSecurityTokenHandler handler          = new JwtSecurityTokenHandler();
            JwtSecurityToken        jwtSecurityToken = handler.ReadJwtToken(token);
            //string userId = jwtSecurityToken["sub"];
            string userId = string.Empty;

            jwtSecurityToken.Claims.ToList().ForEach(item =>
            {
                if (item.Type == JwtRegisteredClaimNames.Sub)
                {
                    userId = item.Value;
                }
            });

            int i = _shoppingCartService.Add(new ShoppingCart()
            {
                Num       = 1,
                ProductId = productId,
                UserId    = int.Parse(userId)
            }).Result;

            return(new TModel <bool>()
            {
                status = 0,
                message = "success",
                Data = i > 0
            });
        }
        public JsonResult AddToCart(int articleId)
        {
            var article = _articleService.Get(articleId);

            if (article == null)
            {
                return(Json(new
                {
                    success = false,
                    message = "No article found with the specified ID"
                }));
            }
            var result = _shoppingCartService.Add(_workContext.CurrentCustomer, article);

            return(Json(new
            {
                success = result,
                message = result ? "The article added to the cart" : "The article didn't add to the cart"
            }));
        }
示例#17
0
        public ActionResult Create(ShoppingCartModel AVM)
        {
            try
            {
                // TODO: Add insert logic here
                ShoppingCart A = new ShoppingCart();
                A.Id          = AVM.Id;
                A.idQuotation = AVM.idQuotation;
                A.idCLient    = AVM.idCLient;
                A.ListProduct = AVM.ListProductModel;
                A.ListPack    = AVM.ListPackModel;


                ShoppingCartService.Add(A);
                ShoppingCartService.Commit();

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
示例#18
0
        public ActionResult <string> Post(long customerId)
        {
            try
            {
                _logger.LogInformation("Received post request");

                if (ModelState.IsValid)
                {
                    _service.Add(customerId);

                    return(Ok("success"));
                }
                else
                {
                    return(BadRequest(ModelState));
                }
            }
            catch (Exception exception)
            {
                _logger.LogError(exception, exception.Message);
                return(new StatusCodeResult(500));
            }
        }
示例#19
0
        public JsonResult AddToCartFromWishlist(List <string> bookIds)
        {
            // add to temporary list
            List <string> bookIds_temp = bookIds;

            // get all book ids from bookIds / wishlist
            // and add to shopping cart table
            foreach (var book in bookIds_temp)
            {
                var getBook = _bookService.GetBookById(int.Parse(book));

                // get logged in user id
                var userId = _httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;
                // get other data ids
                var bookId = getBook.Id;

                // init shopping cart obj
                var shoppingCart = new ShoppingCart
                {
                    UserId    = userId,
                    BookId    = bookId,
                    Price     = getBook.Price,
                    DateAdded = DateTime.Now
                };

                // add single book from wishlist to shopping cart
                _shoppingCartService.Add(shoppingCart);
            }

            // remove all selected items from wishlist
            foreach (var selectedItem in bookIds)
            {
                _wishlistService.DeleteByBookId(int.Parse(selectedItem));
            }

            return(new JsonResult(new { data = "" }));
        }
示例#20
0
        public ActionResult Commit(CartViewModel viewModel)
        {
            var pricmodel = _productSevice.GetAttribute("Price");

            if (viewModel.Products == null)
            {
                viewModel.Products = new List <CartItemViewModel>();
            }

            foreach (var it in viewModel.Products)
            {
                var pr = _productSevice.Get(it.Id);
                if (pr != null)
                {
                    it.name  = pr.Name;
                    it.Image = pr.Image;
                    it.link  = AppHelpers.ProductUrls(pr.Category_Id, pr.Slug);

                    var price = _productSevice.GetAttributeValue(it.Id, pricmodel.Id);
                    if (price != null)
                    {
                        try
                        {
                            int p = int.Parse(price.Value);
                            it.Priceint           = p;
                            it.Price              = p.ToString("N0").Replace(",", ".");
                            viewModel.TotalMoney += p * it.Count;
                        }
                        catch
                        {
                            it.Price = "Liên hệ";
                        }
                    }
                    else
                    {
                        it.Price = "Liên hệ";
                    }
                }
            }

            if (ModelState.IsValid)
            {
                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    try
                    {
                        var shop = new ShoppingCart
                        {
                            Name       = viewModel.Name,
                            Phone      = viewModel.Phone,
                            Email      = viewModel.Email,
                            Addren     = viewModel.Addren,
                            ShipName   = viewModel.Ship_Name,
                            ShipAddren = viewModel.Ship_Addren,
                            ShipPhone  = viewModel.Ship_Phone,
                            ShipNote   = viewModel.Ship_Note,
                            TotalMoney = viewModel.TotalMoney.ToString("N0").Replace(",", "."),
                        };
                        _shoppingCartService.Add(shop);

                        foreach (var it in viewModel.Products)
                        {
                            var cartproduct = new ShoppingCartProduct
                            {
                                CountProduct   = (int)it.Count,
                                Price          = it.Price,
                                ProductId      = it.Id,
                                ShoppingCartId = shop.Id
                            };

                            _shoppingCartProductService.Add(cartproduct);
                        }

                        unitOfWork.Commit();
                        // We use temp data because we are doing a redirect
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = "Đặt hàng thành công",
                            MessageType = GenericMessages.success
                        };

                        var list = GetShoppingCart();
                        list.Clear();

                        return(View("Success"));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex.Message);
                        ModelState.AddModelError(string.Empty, LocalizationService.GetResourceString("Errors.ShoppingCartMessage"));
                    }
                }
            }

            return(View(viewModel));
        }
示例#21
0
        public ApiResultModel <bool> AddOrUpdateCart(int customerId, string sku, int quantity)
        {
            ////validate params
            ValidateParams(customerId, sku, quantity, out ApiResultModel <bool> result);
            if (result.Status == ResultStatusEnum.ValidationError)
            {
                return(result);
            }

            ////validate customer data
            var customer = ValidateCustomer(customerId, out result);

            if (result.Status == ResultStatusEnum.ValidationError)
            {
                return(result);
            }

            ////validate product data
            var product = ValidateProduct(sku, quantity, out result);

            if (result.Status == ResultStatusEnum.ValidationError)
            {
                return(result);
            }

            ////eğer sepette varsa ürün
            var isAddedBefore = customer.ShoppingCarts.Any(x => x.ProductId == product.Id);

            ////stock check or update cart
            if (isAddedBefore)
            {
                var shoppingCartProduct = customer.ShoppingCarts.FirstOrDefault(x => x.ProductId == product.Id);
                if (shoppingCartProduct.Quantity + quantity > product.StockQuantity)
                {
                    result.Message = "Yeterli stok bulunmuyor.";
                    return(result);
                }
                if (shoppingCartProduct.Quantity + quantity > product.MaxSaleableQuantity)
                {
                    result.Message = "Yeterli stok bulunmuyor.";
                    return(result);
                }
                ////update cart
                shoppingCartProduct.Quantity   += quantity;
                shoppingCartProduct.UpdatedDate = DateTime.Now;
                _shoppingCartService.Update(shoppingCartProduct);
                ////for cache
                customer.ShoppingCarts.FirstOrDefault(x => x.ProductId == product.Id).Quantity   += quantity;
                customer.ShoppingCarts.FirstOrDefault(x => x.ProductId == product.Id).UpdatedDate = DateTime.Now;
            }
            else
            {
                ////add to cart
                _shoppingCartService.Add(new ShoppingCartModel {
                    ProductId = product.Id, CartType = (int)ShoppingCartType.Cart, CustomerId = customerId, Quantity = quantity, CreatedDate = DateTime.Now
                });
                ////for cache
                customer.ShoppingCarts.Add(
                    new ShoppingCartModel {
                    ProductId = product.Id, CartType = (int)ShoppingCartType.Cart, CustomerId = customerId, Quantity = quantity, CreatedDate = DateTime.Now
                });
            }

            ////cache set
            var cacheExpirationOptions =
                new MemoryCacheEntryOptions
            {
                AbsoluteExpiration = DateTime.Now.AddMinutes(30),
                Priority           = CacheItemPriority.Normal
            };

            cache.Set(cacheKey, customer, cacheExpirationOptions);

            result.Message = "Eklendi";
            result.Status  = ResultStatusEnum.Success;
            return(result);
        }
示例#22
0
        public async Task <ShoppingCartItems> AddItemToCart(ShoppingCartAddItemDto dto, int userId)
        {
            try
            {
                var cartList = await _shoppingCartService.GetListWithShoppingCartItems_ShoppingCarts(x => x.User_Id == userId && x.Status && !x.Is_Deleted);

                var cart    = cartList.FirstOrDefault();
                var product = await _productService.Get(x => x.Id == dto.productId);

                if (product.InStock < dto.quantity)
                {
                    throw new Exception("no stock");
                }
                else
                {
                    if (cart != null)
                    {
                        var cartItems = cart.ShoppingCartItems;
                        if (cartItems != null && cartItems.Any(x => x.Product_Id == dto.productId))
                        {
                            var cartProduct = await _shoppingCartItemService.Get(x => x.Product_Id == dto.productId && x.ShoppingCart_Id == cart.Id);

                            cartProduct.Quantity += dto.quantity;
                            if (product.InStock < cartProduct.Quantity)
                            {
                                throw new Exception("no stock");
                            }
                            return(await _shoppingCartItemService.Update(cartProduct));
                        }
                        else
                        {
                            var itemCartItem = new ShoppingCartItems()
                            {
                                Product_Id      = dto.productId,
                                Quantity        = dto.quantity,
                                ShoppingCart_Id = cart.Id,
                            };
                            return(await _shoppingCartItemService.Add(itemCartItem));
                        }
                    }
                    else
                    {
                        var itemCart = new ShoppingCarts()
                        {
                            User_Id    = userId,
                            Status     = true,
                            Is_Deleted = false,
                        };
                        var newCart = await _shoppingCartService.Add(itemCart);

                        var itemCartItem = new ShoppingCartItems()
                        {
                            Product_Id      = dto.productId,
                            Quantity        = dto.quantity,
                            ShoppingCart_Id = newCart.Id,
                        };
                        return(await _shoppingCartItemService.Add(itemCartItem));
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
示例#23
0
        public ActionResult Add(int id, int quantity = 1, string itemType = ProductPart.PartItemType, string returnUrl = null)
        {
            _shoppingCartService.Add(id, itemType, quantity);

            return(ReturnOrIndex(returnUrl));
        }