public ActionResult AddProductToCart(int productId, FormCollection form) { var parentProductId = productId; var cartType = ShoppingCartType.ShoppingCart; foreach (string formKey in form.AllKeys) { if (formKey.StartsWith("addtocartbutton-")) { cartType = ShoppingCartType.ShoppingCart; int.TryParse(formKey.Replace("addtocartbutton-", ""), out productId); } else if (formKey.StartsWith("addtowishlistbutton-")) { cartType = ShoppingCartType.Wishlist; int.TryParse(formKey.Replace("addtowishlistbutton-", ""), out productId); } } var product = _productService.GetProductById(productId); if (product == null || product.Deleted || !product.Published) return RedirectToRoute("HomePage"); var parentProduct = (parentProductId == productId ? product : _productService.GetProductById(parentProductId)); decimal customerEnteredPrice = decimal.Zero; decimal customerEnteredPriceConverted = decimal.Zero; if (product.CustomerEntersPrice) { foreach (string formKey in form.AllKeys) { if (formKey.Equals(string.Format("addtocart_{0}.CustomerEnteredPrice", productId), StringComparison.InvariantCultureIgnoreCase)) { if (decimal.TryParse(form[formKey], out customerEnteredPrice)) customerEnteredPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(customerEnteredPrice, _services.WorkContext.WorkingCurrency); break; } } } int quantity = 1; foreach (string formKey in form.AllKeys) { if (formKey.Equals(string.Format("addtocart_{0}.AddToCart.EnteredQuantity", productId), StringComparison.InvariantCultureIgnoreCase)) { int.TryParse(form[formKey], out quantity); break; } } var addToCartContext = new AddToCartContext { Product = product, AttributeForm = form, CartType = cartType, CustomerEnteredPrice = customerEnteredPrice, Quantity = quantity, AddRequiredProducts = true }; _shoppingCartService.AddToCart(addToCartContext); if (addToCartContext.Warnings.Count == 0) { switch (cartType) { case ShoppingCartType.Wishlist: { if (_shoppingCartSettings.DisplayWishlistAfterAddingProduct) { //redirect to the wishlist page return RedirectToRoute("Wishlist"); } else { //redisplay the page with "Product has been added to the wishlist" notification message var model = _helper.PrepareProductDetailsPageModel(parentProduct); this.NotifySuccess(T("Products.ProductHasBeenAddedToTheWishlist"), false); //activity log _services.CustomerActivity.InsertActivity("PublicStore.AddToWishlist", T("ActivityLog.PublicStore.AddToWishlist"), product.Name); return View(model.ProductTemplateViewPath, model); } } case ShoppingCartType.ShoppingCart: default: { if (_shoppingCartSettings.DisplayCartAfterAddingProduct) { //redirect to the shopping cart page return RedirectToRoute("ShoppingCart"); } else { //redisplay the page with "Product has been added to the cart" notification message var model = _helper.PrepareProductDetailsPageModel(parentProduct); this.NotifySuccess(T("Products.ProductHasBeenAddedToTheCart"), false); //activity log _services.CustomerActivity.InsertActivity("PublicStore.AddToShoppingCart", T("ActivityLog.PublicStore.AddToShoppingCart"), product.Name); return View(model.ProductTemplateViewPath, model); } } } } else { //Errors foreach (string error in addToCartContext.Warnings) ModelState.AddModelError("", error); //If we got this far, something failed, redisplay form var model = _helper.PrepareProductDetailsPageModel(parentProduct); return View(model.ProductTemplateViewPath, model); } }
public ActionResult AddProduct(int productId, int shoppingCartTypeId, FormCollection form) { var product = _productService.GetProductById(productId); if (product == null) { return Json(new { redirect = Url.RouteUrl("HomePage"), }); } #region Customer entered price decimal customerEnteredPriceConverted = decimal.Zero; if (product.CustomerEntersPrice) { foreach (string formKey in form.AllKeys) { if (formKey.Equals(string.Format("addtocart_{0}.CustomerEnteredPrice", productId), StringComparison.InvariantCultureIgnoreCase)) { decimal customerEnteredPrice = decimal.Zero; if (decimal.TryParse(form[formKey], out customerEnteredPrice)) customerEnteredPriceConverted = _currencyService.ConvertToPrimaryStoreCurrency(customerEnteredPrice, _workContext.WorkingCurrency); break; } } } #endregion #region Quantity int quantity = 1; string key1 = "addtocart_{0}.EnteredQuantity".FormatWith(productId); string key2 = "addtocart_{0}.AddToCart.EnteredQuantity".FormatWith(productId); if (form.AllKeys.Contains(key1)) int.TryParse(form[key1], out quantity); else if (form.AllKeys.Contains(key2)) int.TryParse(form[key2], out quantity); #endregion //save item var cartType = (ShoppingCartType)shoppingCartTypeId; var addToCartContext = new AddToCartContext { Product = product, AttributeForm = form, CartType = cartType, CustomerEnteredPrice = customerEnteredPriceConverted, Quantity = quantity, AddRequiredProducts = true }; _shoppingCartService.AddToCart(addToCartContext); #region Return result if (addToCartContext.Warnings.Count > 0) { //cannot be added to the cart/wishlist //let's display warnings return Json(new { success = false, message = addToCartContext.Warnings.ToArray() }); } //added to the cart/wishlist switch (cartType) { case ShoppingCartType.Wishlist: { //activity log _customerActivityService.InsertActivity("PublicStore.AddToWishlist", _localizationService.GetResource("ActivityLog.PublicStore.AddToWishlist"), product.Name); if (_shoppingCartSettings.DisplayWishlistAfterAddingProduct) { //redirect to the wishlist page return Json(new { redirect = Url.RouteUrl("Wishlist"), }); } else { return Json(new { success = true, message = string.Format(_localizationService.GetResource("Products.ProductHasBeenAddedToTheWishlist.Link"), Url.RouteUrl("Wishlist")), }); } } case ShoppingCartType.ShoppingCart: default: { //activity log _customerActivityService.InsertActivity("PublicStore.AddToShoppingCart", _localizationService.GetResource("ActivityLog.PublicStore.AddToShoppingCart"), product.Name); if (_shoppingCartSettings.DisplayCartAfterAddingProduct) { //redirect to the shopping cart page return Json(new { redirect = Url.RouteUrl("ShoppingCart"), }); } else { return Json(new { success = true, message = string.Format(_localizationService.GetResource("Products.ProductHasBeenAddedToTheCart.Link"), Url.RouteUrl("ShoppingCart")) }); } } } #endregion }
public ActionResult AddProductSimple(int productId, bool forceredirection = false) { //current we support only ShoppingCartType.ShoppingCart const ShoppingCartType shoppingCartType = ShoppingCartType.ShoppingCart; var product = _productService.GetProductById(productId); if (product == null) { return Json(new { success = false, message = "No product found with the specified ID" }); } // filter out cases where a product cannot be added to cart if (product.ProductType == ProductType.GroupedProduct || product.CustomerEntersPrice || product.IsGiftCard) { return Json(new { redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName() }), }); } //quantity to add var qtyToAdd = product.OrderMinimumQuantity > 0 ? product.OrderMinimumQuantity : 1; var allowedQuantities = product.ParseAllowedQuatities(); if (allowedQuantities.Length > 0) { //cannot be added to the cart (requires a customer to select a quantity from dropdownlist) return Json(new { redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName() }), }); } //get standard warnings without attribute validations //first, try to find existing shopping cart item var cart = _workContext.CurrentCustomer.GetCartItems(shoppingCartType, _storeContext.CurrentStore.Id); var shoppingCartItem = _shoppingCartService.FindShoppingCartItemInTheCart(cart, shoppingCartType, product); //if we already have the same product in the cart, then use the total quantity to validate var quantityToValidate = shoppingCartItem != null ? shoppingCartItem.Item.Quantity + qtyToAdd : qtyToAdd; var addToCartWarnings = (List<string>)_shoppingCartService.GetShoppingCartItemWarnings(_workContext.CurrentCustomer, shoppingCartType, product, _storeContext.CurrentStore.Id, string.Empty, decimal.Zero, quantityToValidate, false, true, false, false, false, false); if (addToCartWarnings.Count > 0) { //cannot be added to the cart //let's display standard warnings return Json(new { success = false, message = addToCartWarnings.ToArray() }); } //now let's try adding product to the cart (now including product attribute validation, etc) var addToCartContext = new AddToCartContext { Product = product, CartType = shoppingCartType, Quantity = qtyToAdd, AddRequiredProducts = true }; _shoppingCartService.AddToCart(addToCartContext); if (addToCartContext.Warnings.Count > 0) { //cannot be added to the cart //but we do not display attribute and gift card warnings here. let's do it on the product details page return Json(new { redirect = Url.RouteUrl("Product", new { SeName = product.GetSeName() }), }); } //now product is in the cart //activity log _customerActivityService.InsertActivity("PublicStore.AddToShoppingCart", _localizationService.GetResource("ActivityLog.PublicStore.AddToShoppingCart"), product.Name); if (_shoppingCartSettings.DisplayCartAfterAddingProduct || forceredirection) { //redirect to the shopping cart page return Json(new { redirect = Url.RouteUrl("ShoppingCart"), }); } return Json(new { success = true, message = string.Format(_localizationService.GetResource("Products.ProductHasBeenAddedToTheCart.Link"), Url.RouteUrl("ShoppingCart")) }); }
/// <summary> /// Place order items in current user shopping cart. /// </summary> /// <param name="order">The order</param> public virtual void ReOrder(Order order) { if (order == null) throw new ArgumentNullException("order"); foreach (var orderItem in order.OrderItems) { bool isBundle = (orderItem.Product.ProductType == ProductType.BundledProduct); var addToCartContext = new AddToCartContext(); addToCartContext.Warnings = _shoppingCartService.AddToCart(order.Customer, orderItem.Product, ShoppingCartType.ShoppingCart, order.StoreId, orderItem.AttributesXml, isBundle ? decimal.Zero : orderItem.UnitPriceExclTax, orderItem.Quantity, false, addToCartContext); if (isBundle && orderItem.BundleData.HasValue() && addToCartContext.Warnings.Count == 0) { foreach (var bundleData in orderItem.GetBundleData()) { var bundleItem = _productService.GetBundleItemById(bundleData.BundleItemId); addToCartContext.BundleItem = bundleItem; addToCartContext.Warnings = _shoppingCartService.AddToCart(order.Customer, bundleItem.Product, ShoppingCartType.ShoppingCart, order.StoreId, bundleData.AttributesXml, decimal.Zero, bundleData.Quantity, false, addToCartContext); } } _shoppingCartService.AddToCartStoring(addToCartContext); } }
/// <summary> /// Add product to cart /// </summary> /// <param name="customer">The customer</param> /// <param name="product">The product</param> /// <param name="cartType">Cart type</param> /// <param name="storeId">Store identifier</param> /// <param name="selectedAttributes">Selected attributes</param> /// <param name="customerEnteredPrice">Price entered by customer</param> /// <param name="quantity">Quantity</param> /// <param name="automaticallyAddRequiredProductsIfEnabled">Whether to add required products</param> /// <param name="ctx">Add to cart context</param> /// <returns>List with warnings</returns> public virtual List<string> AddToCart(Customer customer, Product product, ShoppingCartType cartType, int storeId, string selectedAttributes, decimal customerEnteredPrice, int quantity, bool automaticallyAddRequiredProductsIfEnabled, AddToCartContext ctx = null) { if (customer == null) throw new ArgumentNullException("customer"); if (product == null) throw new ArgumentNullException("product"); var warnings = new List<string>(); var bundleItem = (ctx == null ? null : ctx.BundleItem); if (ctx != null && bundleItem != null && ctx.Warnings.Count > 0) return ctx.Warnings; // warnings while adding bundle items to cart -> no need for further processing if (cartType == ShoppingCartType.ShoppingCart && !_permissionService.Authorize(StandardPermissionProvider.EnableShoppingCart, customer)) { warnings.Add("Shopping cart is disabled"); return warnings; } if (cartType == ShoppingCartType.Wishlist && !_permissionService.Authorize(StandardPermissionProvider.EnableWishlist, customer)) { warnings.Add("Wishlist is disabled"); return warnings; } if (quantity <= 0) { warnings.Add(_localizationService.GetResource("ShoppingCart.QuantityShouldPositive")); return warnings; } //if (parentItemId.HasValue && (parentItemId.Value == 0 || bundleItem == null || bundleItem.Id == 0)) //{ // warnings.Add(_localizationService.GetResource("ShoppingCart.Bundle.BundleItemNotFound").FormatWith(bundleItem.GetLocalizedName())); // return warnings; //} //reset checkout info _customerService.ResetCheckoutData(customer, storeId); var cart = customer.GetCartItems(cartType, storeId); OrganizedShoppingCartItem existingCartItem = null; if (bundleItem == null) { existingCartItem = FindShoppingCartItemInTheCart(cart, cartType, product, selectedAttributes, customerEnteredPrice); } if (existingCartItem != null) { //update existing shopping cart item int newQuantity = existingCartItem.Item.Quantity + quantity; warnings.AddRange( GetShoppingCartItemWarnings(customer, cartType, product, storeId, selectedAttributes, customerEnteredPrice, newQuantity, automaticallyAddRequiredProductsIfEnabled, bundleItem: bundleItem) ); if (warnings.Count == 0) { existingCartItem.Item.AttributesXml = selectedAttributes; existingCartItem.Item.Quantity = newQuantity; existingCartItem.Item.UpdatedOnUtc = DateTime.UtcNow; _customerService.UpdateCustomer(customer); //event notification _eventPublisher.EntityUpdated(existingCartItem.Item); } } else { //new shopping cart item warnings.AddRange( GetShoppingCartItemWarnings(customer, cartType, product, storeId, selectedAttributes, customerEnteredPrice, quantity, automaticallyAddRequiredProductsIfEnabled, bundleItem: bundleItem) ); if (warnings.Count == 0) { //maximum items validation if (cartType == ShoppingCartType.ShoppingCart && cart.Count >= _shoppingCartSettings.MaximumShoppingCartItems) { warnings.Add(_localizationService.GetResource("ShoppingCart.MaximumShoppingCartItems")); return warnings; } else if (cartType == ShoppingCartType.Wishlist && cart.Count >= _shoppingCartSettings.MaximumWishlistItems) { warnings.Add(_localizationService.GetResource("ShoppingCart.MaximumWishlistItems")); return warnings; } var now = DateTime.UtcNow; var cartItem = new ShoppingCartItem() { ShoppingCartType = cartType, StoreId = storeId, Product = product, AttributesXml = selectedAttributes, CustomerEnteredPrice = customerEnteredPrice, Quantity = quantity, CreatedOnUtc = now, UpdatedOnUtc = now, ParentItemId = null //parentItemId }; if (bundleItem != null) cartItem.BundleItemId = bundleItem.Id; if (ctx == null) { customer.ShoppingCartItems.Add(cartItem); _customerService.UpdateCustomer(customer); _eventPublisher.EntityInserted(cartItem); } else { if (bundleItem == null) { Debug.Assert(ctx.Item == null, "Add to cart item already specified"); ctx.Item = cartItem; } else { ctx.ChildItems.Add(cartItem); } } } } return warnings; }
/// <summary> /// Copies a shopping cart item. /// </summary> /// <param name="sci">Shopping cart item</param> /// <param name="customer">The customer</param> /// <param name="cartType">Shopping cart type</param> /// <param name="storeId">Store Id</param> /// <param name="addRequiredProductsIfEnabled">Add required products if enabled</param> /// <returns>List with add-to-cart warnings.</returns> public virtual IList<string> Copy(OrganizedShoppingCartItem sci, Customer customer, ShoppingCartType cartType, int storeId, bool addRequiredProductsIfEnabled) { if (customer == null) throw new ArgumentNullException("customer"); if (sci == null) throw new ArgumentNullException("item"); var addToCartContext = new AddToCartContext { Customer = customer }; addToCartContext.Warnings = AddToCart(customer, sci.Item.Product, cartType, storeId, sci.Item.AttributesXml, sci.Item.CustomerEnteredPrice, sci.Item.Quantity, addRequiredProductsIfEnabled, addToCartContext); if (addToCartContext.Warnings.Count == 0 && sci.ChildItems != null) { foreach (var childItem in sci.ChildItems) { addToCartContext.BundleItem = childItem.Item.BundleItem; addToCartContext.Warnings = AddToCart(customer, childItem.Item.Product, cartType, storeId, childItem.Item.AttributesXml, childItem.Item.CustomerEnteredPrice, childItem.Item.Quantity, false, addToCartContext); } } AddToCartStoring(addToCartContext); return addToCartContext.Warnings; }
/// <summary> /// Stores the shopping card items in the database /// </summary> /// <param name="ctx">Add to cart context</param> public virtual void AddToCartStoring(AddToCartContext ctx) { if (ctx.Warnings.Count == 0 && ctx.Item != null) { var customer = ctx.Customer ?? _workContext.CurrentCustomer; customer.ShoppingCartItems.Add(ctx.Item); _customerService.UpdateCustomer(customer); _eventPublisher.EntityInserted(ctx.Item); foreach (var childItem in ctx.ChildItems) { childItem.ParentItemId = ctx.Item.Id; customer.ShoppingCartItems.Add(childItem); _customerService.UpdateCustomer(customer); _eventPublisher.EntityInserted(childItem); } } }
/// <summary> /// Add product to cart /// </summary> /// <param name="ctx">Add to cart context</param> public virtual void AddToCart(AddToCartContext ctx) { var customer = ctx.Customer ?? _workContext.CurrentCustomer; int storeId = ctx.StoreId ?? _storeContext.CurrentStore.Id; var cart = customer.GetCartItems(ctx.CartType, storeId); _customerService.ResetCheckoutData(customer, storeId); if (ctx.AttributeForm != null) { var attributes = _productAttributeService.GetProductVariantAttributesByProductId(ctx.Product.Id); ctx.Attributes = ctx.AttributeForm.CreateSelectedAttributesXml(ctx.Product.Id, attributes, _productAttributeParser, _localizationService, _downloadService, _catalogSettings, null, ctx.Warnings, true, ctx.BundleItemId); if (ctx.Product.ProductType == ProductType.BundledProduct && ctx.Attributes.HasValue()) ctx.Warnings.Add(_localizationService.GetResource("ShoppingCart.Bundle.NoAttributes")); if (ctx.Product.IsGiftCard) ctx.Attributes = ctx.AttributeForm.AddGiftCardAttribute(ctx.Attributes, ctx.Product.Id, _productAttributeParser, ctx.BundleItemId); } ctx.Warnings.AddRange( AddToCart(_workContext.CurrentCustomer, ctx.Product, ctx.CartType, storeId, ctx.Attributes, ctx.CustomerEnteredPrice, ctx.Quantity, ctx.AddRequiredProducts, ctx) ); if (ctx.Product.ProductType == ProductType.BundledProduct && ctx.Warnings.Count <= 0 && ctx.BundleItem == null) { foreach (var bundleItem in _productService.GetBundleItems(ctx.Product.Id).Select(x => x.Item)) { AddToCart(new AddToCartContext { BundleItem = bundleItem, Warnings = ctx.Warnings, Item = ctx.Item, ChildItems = ctx.ChildItems, Product = bundleItem.Product, Customer = customer, AttributeForm = ctx.AttributeForm, CartType = ctx.CartType, Quantity = bundleItem.Quantity, AddRequiredProducts = ctx.AddRequiredProducts, StoreId = storeId }); if (ctx.Warnings.Count > 0) { ctx.ChildItems.Clear(); break; } } } if (ctx.BundleItem == null) { AddToCartStoring(ctx); } }