/// <summary>
    /// Reload data for UniSelector.
    /// </summary>
    /// <param name="forceReload">Force Reload Option</param>
    private void ReloadUniSelectorData(bool forceReload)
    {
        if (ProductID > 0)
        {
            currentValues = string.Empty;

            // Get categories assigned to product
            DataSet ds = OptionCategoryInfoProvider.GetProductOptionCategories(ProductID, false);
            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                currentValues = TextHelper.Join(";", DataHelper.GetStringValues(ds.Tables[0], "CategoryID"));
            }

            uniSelector.WhereCondition = GetWhereCondition();

            if (forceReload || !RequestHelper.IsPostBack())
            {
                uniSelector.Value = currentValues;
            }

            if (forceReload)
            {
                uniSelector.Reload(true);
            }
        }
    }
    /// <summary>
    /// On BtnAdd click event.
    /// </summary>
    protected void BtnAdd_Click(object sender, EventArgs e)
    {
        // Check 'EcommerceModify' permission
        if (!ECommerceContext.IsUserAuthorizedForPermission("ModifyOrders"))
        {
            RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyOrders");
        }

        string allUnits = null;
        string allSkuId = null;

        foreach (KeyValuePair <int, TextBox> item in quantityControls)
        {
            // Get params
            int     skuId    = item.Key;
            TextBox txtUnits = item.Value;

            // Get unit count
            int units = ValidationHelper.GetInteger(txtUnits.Text, 0);

            if (units > 0)
            {
                // Get product and localized name
                SKUInfo product = SKUInfoProvider.GetSKUInfo(skuId);
                if (product != null)
                {
                    string skuName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(product.SKUName));

                    // Abort inserting products to the shopping cart ifIf product has some product options
                    if (!DataHelper.DataSourceIsEmpty(OptionCategoryInfoProvider.GetProductOptionCategories(skuId, true)))
                    {
                        // Show error message
                        ShowError(string.Format(GetString("Order_Edit_AddItems.ProductOptionsRequired"), skuName));

                        return;
                    }

                    // If selected product is a donation
                    if (product.SKUProductType == SKUProductTypeEnum.Donation)
                    {
                        // If donation is customizable
                        if (product.SKUPrivateDonation || !((product.SKUMinPrice == product.SKUPrice) && (product.SKUMaxPrice == product.SKUPrice)))
                        {
                            // Show error message
                            ShowError(string.Format(GetString("order_edit_additems.donationpropertiesrequired"), skuName));

                            return;
                        }
                    }

                    // Create strings with SKU IDs and units separated by ';'
                    allSkuId += skuId + ";";
                    allUnits += units + ";";
                }
            }
        }

        // Close this modal window and refresh parent values in window
        CloseWindow(allSkuId, allUnits);
    }
    /// <summary>
    /// Checks if user is able to generate variants. Returns warning message if validation failed, empty string if it passed.
    /// </summary>
    private string VariantsCanBeGenerated()
    {
        // Inform user about need to change product type to be able to generate variants, it is allowed only for a standard product
        if (Product.SKUProductType != SKUProductTypeEnum.Product)
        {
            return(String.Format(GetString("com.variant.notstandardproduct"), GetString("com.producttype.product")));
        }

        // Data set with option categories assigned to the product
        DataSet optionCategories = OptionCategoryInfoProvider.GetProductOptionCategories(ProductID, true, OptionCategoryTypeEnum.Attribute);
        // List of assigned Category IDs
        IList <int> categoryIDs = DataHelper.GetIntegerValues(optionCategories.Tables[0], "CategoryID");

        // Inform that attribute option category does not exist for this product
        if (DataHelper.DataSourceIsEmpty(optionCategories))
        {
            return(GetString("com.variant.nooptioncategorycreated"));
        }

        bool variantsCannotBeGenerated = true;

        foreach (int categoryId in categoryIDs)
        {
            var enabledAllowedOptions = SKUInfoProvider.GetSKUOptionsForProduct(Product.SKUID, categoryId, true).TopN(1);

            if (!DataHelper.DataSourceIsEmpty(enabledAllowedOptions))
            {
                variantsCannotBeGenerated = false;
                break;
            }
        }

        // Inform that any option is selected,created or enabled in assigned option category
        if (variantsCannotBeGenerated)
        {
            return(GetString("com.variant.nooptionselectedforproduct"));
        }

        var bundles = SKUInfoProvider.GetSKUs()
                      .Column("SKUName")
                      .WhereIn("SKUID", BundleInfoProvider.GetBundles()
                               .Column("BundleID")
                               .WhereEquals("SKUID", Product.SKUID)
                               )
                      .GetListResult <string>();

        if (bundles.Count > 0)
        {
            return(String.Format(GetString("com.variant.productusedinbundle"), HTMLHelper.HTMLEncode(ResHelper.LocalizeString(string.Join(", ", bundles)))));
        }

        return("");
    }
    /// <summary>
    /// Gets the categories with names from external data source or database.
    /// </summary>
    /// <param name="skuIdOfProductWithCategories">Id of product with categories.</param>
    private Dictionary <int, string> GetCategoriesWithNames(int skuIdOfProductWithCategories)
    {
        Dictionary <int, string> categoriesWithName = new Dictionary <int, string>();

        if ((ExternalDataSource != null) && (ExternalDataSource.Count > 0))
        {
            // External data
            foreach (OptionCategoryInfo info in ExternalDataSource.Keys)
            {
                // Use category live site display name in case it is available, otherwise category display name
                categoriesWithName.Add(info.CategoryID, info.CategoryTitle);
            }

            return(categoriesWithName);
        }
        // Load data from DB
        DataSet dsOptionCategories;

        // If ShowOnlyUsedCategories is true, dataset will contain only already used categories in variants
        if (ShowOnlyUsedCategories)
        {
            dsOptionCategories = VariantHelper.GetProductVariantsCategories(skuIdOfProductWithCategories);
        }
        else
        {
            dsOptionCategories = OptionCategoryInfoProvider.GetProductOptionCategories(skuIdOfProductWithCategories, true, OptionCategoryTypeEnum.Attribute);
        }

        if (DataHelper.DataSourceIsEmpty(dsOptionCategories))
        {
            return(categoriesWithName);
        }

        foreach (DataRow catDr in dsOptionCategories.Tables[0].Rows)
        {
            int    categoryId   = ValidationHelper.GetInteger(catDr["CategoryID"], 0);
            string categoryName = ValidationHelper.GetString(catDr["CategoryLiveSiteDisplayName"], String.Empty);

            if (string.IsNullOrEmpty(categoryName))
            {
                categoryName = ValidationHelper.GetString(catDr["CategoryDisplayName"], String.Empty);
            }

            categoriesWithName.Add(categoryId, categoryName);
        }

        return(categoriesWithName);
    }
    private void btnAddOneUnit_Click(object sender, EventArgs e)
    {
        // Get SKU ID
        int skuId = ValidationHelper.GetInteger(((LinkButton)sender).CommandArgument, 0);

        // Get product
        SKUInfo product = SKUInfoProvider.GetSKUInfo(skuId);

        bool hasProductOptions      = !DataHelper.DataSourceIsEmpty(OptionCategoryInfoProvider.GetProductOptionCategories(skuId, true));
        bool isCustomizableDonation = ((product != null) && (product.SKUProductType == SKUProductTypeEnum.Donation)) &&
                                      (product.SKUPrivateDonation || !((product.SKUMinPrice == product.SKUPrice) && (product.SKUMaxPrice == product.SKUPrice)) || (product.SKUPrice == 0.0));

        // If product has product options or product is a customizable donation
        // -> abort inserting products to the shopping cart
        if (hasProductOptions || isCustomizableDonation)
        {
            // Set title message per specific case
            if (hasProductOptions && isCustomizableDonation)
            {
                lblTitle.ResourceString = "order_edit_additems.donationpropertiesproductoptions";
            }
            else if (hasProductOptions)
            {
                lblTitle.ResourceString = "order_edit_additems.productoptions";
            }
            else
            {
                lblTitle.ResourceString = "order_edit_additems.donationproperties";
            }

            // Save SKU ID to the viewstate
            SKUID = skuId;

            // Initialize shopping cart item selector
            cartItemSelector.SKUID = SKUID;
            cartItemSelector.ShowProductOptions     = hasProductOptions;
            cartItemSelector.ShowDonationProperties = isCustomizableDonation;
            cartItemSelector.ReloadData();

            SwitchToOptions();
        }
        else
        {
            // Add product to shopping cart and close dialog window
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "addproduct", ScriptHelper.GetScript("AddProducts(" + skuId + ", 1);"));
        }
    }
Ejemplo n.º 6
0
    /// <summary>
    /// Handles <see cref="CMSModalPage.Save"/> event.
    /// </summary>
    private void OnSave(object sender, EventArgs e)
    {
        // Check 'EcommerceModify' permission
        if (!ECommerceContext.IsUserAuthorizedForPermission(EcommercePermissions.ORDERS_MODIFY))
        {
            RedirectToAccessDenied(ModuleName.ECOMMERCE, "EcommerceModify OR ModifyOrders");
        }

        string allUnits = null;
        string allSkuId = null;

        foreach (KeyValuePair <int, TextBox> item in quantityControls)
        {
            // Get params
            int     skuId    = item.Key;
            TextBox txtUnits = item.Value;

            // Get unit count
            int units = ValidationHelper.GetInteger(txtUnits.Text, 0);

            if (units > 0)
            {
                // Get product and localized name
                SKUInfo product = SKUInfo.Provider.Get(skuId);
                if (product != null)
                {
                    string skuName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(product.SKUName));

                    // Abort inserting products to the shopping cart ifIf product has some product options
                    if (!DataHelper.DataSourceIsEmpty(OptionCategoryInfoProvider.GetProductOptionCategories(skuId, true)))
                    {
                        // Show error message
                        ShowError(string.Format(GetString("Order_Edit_AddItems.ProductOptionsRequired"), skuName));

                        return;
                    }

                    // Create strings with SKU IDs and units separated by ';'
                    allSkuId += skuId + ";";
                    allUnits += units + ";";
                }
            }
        }

        // Close this modal window and refresh parent values in window
        CloseWindow(allSkuId, allUnits);
    }
    /// <summary>
    /// Loads control.
    /// </summary>
    private void LoadControl()
    {
        // Get all product categories with options which are already in variants
        if (VariantCategoriesOptions.Count == 0)
        {
            DataSet variantCategoriesDS = VariantHelper.GetProductVariantsCategories(ProductID);
            FillCategoriesOptionsDictionary(VariantCategoriesOptions, variantCategoriesDS);
        }

        // Get all product attribute categories with options
        if (AllCategoriesOptions.Count == 0)
        {
            DataSet allCategoriesDS = OptionCategoryInfoProvider.GetProductOptionCategories(ProductID, true, OptionCategoryTypeEnum.Attribute);
            FillCategoriesOptionsDictionary(AllCategoriesOptions, allCategoriesDS);
        }

        foreach (KeyValuePair <OptionCategoryInfo, List <SKUInfo> > keyValuePair in AllCategoriesOptions)
        {
            if (keyValuePair.Value.Count > 0)
            {
                OptionCategoryInfo optionCategory = keyValuePair.Key;

                // Create new instance of CheckBoxWithDropDown control and prefill all necessary values
                CheckBoxWithDropDown checkBoxWithDropDown = new CheckBoxWithDropDown();
                checkBoxWithDropDown.ID    = ValidationHelper.GetString(optionCategory.CategoryID, string.Empty);
                checkBoxWithDropDown.Value = optionCategory.CategoryID;
                // Use live site display name instead of category display name in case it is available
                checkBoxWithDropDown.CheckboxText = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(optionCategory.CategoryTitle));

                // Attach listeners
                checkBoxWithDropDown.OnCheckBoxSelectionChanged += checkBoxWithDropDown_OnCheckBoxSelectionChanged;
                checkBoxWithDropDown.OnDropDownSelectionChanged += checkBoxWithDropDown_OnDropDownSelectionChanged;

                // Option category is in variants too
                if (VariantCategoriesOptions.Keys.Any(c => ValidationHelper.GetInteger(c["categoryId"], 0) == optionCategory.CategoryID))
                {
                    // Check and disable checkbox
                    checkBoxWithDropDown.CheckboxChecked = true;
                    checkBoxWithDropDown.Enabled         = false;

                    // Already existing variants add to selected categories too
                    if (!SelectedCategories.ContainsKey(optionCategory.CategoryID))
                    {
                        SelectedCategories.Add(optionCategory.CategoryID, VariantOptionInfo.ExistingSelectedOption);
                    }
                }
                // Option category is not in variant, but some categories in variants already exists
                else if (VariantCategoriesOptions.Count > 0)
                {
                    // Set prompt message and visibility
                    checkBoxWithDropDown.DropDownPrompt  = GetString("general.pleaseselect");
                    checkBoxWithDropDown.DropDownLabel   = GetString("com.variants.dropdownlabel");
                    checkBoxWithDropDown.DropDownVisible = true;

                    // Get all product options and bind them to dropdownlist
                    var options       = SKUInfoProvider.GetSKUOptionsForProduct(ProductID, optionCategory.CategoryID, true).OrderBy("SKUOrder");
                    var dropDownItems = new ListItemCollection();

                    foreach (var option in options)
                    {
                        dropDownItems.Add(new ListItem(option.SKUName, option.SKUID.ToString()));
                    }

                    checkBoxWithDropDown.DropDownItems = dropDownItems;
                }

                // Finally bind this control to parent
                chboxPanel.Controls.Add(checkBoxWithDropDown);
            }
        }
    }
    /// <summary>
    /// Loads product options.
    /// </summary>
    private void LoadProductOptions()
    {
        DataSet dsCategories = null;

        if (IsLiveSite)
        {
            // Get cache minutes
            int cacheMinutes = SettingsKeyInfoProvider.GetIntValue(SiteContext.CurrentSiteName + ".CMSCacheMinutes");

            // Try to get data from cache
            using (var cs = new CachedSection <DataSet>(ref dsCategories, cacheMinutes, true, null, "skuoptioncategories", SKUID))
            {
                if (cs.LoadData)
                {
                    // Get all option categories for SKU
                    dsCategories = OptionCategoryInfoProvider.GetProductOptionCategories(SKUID, false);

                    // Save to the cache
                    if (cs.Cached)
                    {
                        // Get dependencies
                        var dependencies = new List <string>
                        {
                            "ecommerce.sku|byid|" + SKUID,
                            "ecommerce.optioncategory|all"
                        };

                        // Set dependencies
                        cs.CacheDependency = CacheHelper.GetCacheDependency(dependencies);
                    }

                    cs.Data = dsCategories;
                }
            }
        }
        else
        {
            // Get all option categories for SKU
            dsCategories = OptionCategoryInfoProvider.GetProductOptionCategories(SKUID, false);
        }

        // Initialize product option selectors
        if (!DataHelper.DataSourceIsEmpty(dsCategories))
        {
            mProductOptions = new Hashtable();

            // Is only one option category available for variants?
            var variantCategories = Variants.Any() ? Variants.First().ProductAttributes.CategoryIDs.ToList() : null;
            mOneCategoryUsed = variantCategories != null && variantCategories.Count == 1;

            foreach (DataRow dr in dsCategories.Tables[0].Rows)
            {
                try
                {
                    // Load control for selection product options
                    ProductOptionSelector selector = (ProductOptionSelector)LoadUserControl("~/CMSModules/Ecommerce/Controls/ProductOptions/ProductOptionSelector.ascx");

                    // Add control to the collection
                    var categoryID = ValidationHelper.GetInteger(dr["CategoryID"], 0);
                    selector.ID = "opt" + categoryID;

                    // Init selector
                    selector.LocalShoppingCartObj = ShoppingCart;
                    selector.IsLiveSite           = IsLiveSite;
                    selector.CssClassFade         = CssClassFade;
                    selector.CssClassNormal       = CssClassNormal;
                    selector.SKUID          = SKUID;
                    selector.OptionCategory = new OptionCategoryInfo(dr);

                    // If one category is used, fix the one selector with options to use only options which are not in disabled variants
                    if (mOneCategoryUsed && variantCategories.Contains(categoryID))
                    {
                        var disabled = from variant in Variants
                                       where !variant.Variant.SKUEnabled
                                       from productAttributes in variant.ProductAttributes
                                       select productAttributes.SKUID;

                        var disabledList = disabled.ToList();

                        selector.ProductOptionsInDisabledVariants = disabledList.Any() ? disabledList : null;
                    }

                    // Load all product options
                    foreach (DictionaryEntry entry in selector.ProductOptions)
                    {
                        mProductOptions[entry.Key] = entry.Value;
                    }

                    var lc = selector.SelectionControl as ListControl;
                    if (lc != null)
                    {
                        // Add Index change handler
                        lc.AutoPostBack = true;
                    }

                    pnlSelectors.Controls.Add(selector);
                }
                catch
                {
                }
            }
        }
    }
    /// <summary>
    /// Adds product to the shopping cart.
    /// </summary>
    private void AddProductToShoppingCart()
    {
        SKUID = hdnSKUID.Value.ToInteger(0);

        // Validate input data
        if (!IsValid() || (SKU == null))
        {
            // Do not process
            return;
        }

        // Try to redirect before any currently selected variant checks (selector in listings issue)
        if (RedirectToDetailsEnabled)
        {
            if (!ShowProductOptions)
            {
                // Does product have some enabled product option categories?
                bool hasOptions = !DataHelper.DataSourceIsEmpty(OptionCategoryInfoProvider.GetProductOptionCategories(SKUID, true));

                if (hasOptions)
                {
                    // Redirect to product details
                    URLHelper.Redirect("~/CMSPages/Ecommerce/GetProduct.aspx?productid=" + SKUID);
                }
            }
        }

        if (SKU.HasVariants)
        {
            // Check if configured variant is available
            if ((SelectedVariant == null) || !SelectedVariant.Variant.SKUEnabled)
            {
                ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartAddItemErrorAlert", ScriptHelper.GetAlertScript(GetString("com.cartcontent.nonexistingvariantselected")));
                return;
            }
        }

        // Get cart item parameters
        var cartItemParams = GetShoppingCartItemParameters();

        string error = null;

        // Check if it is possible to add this item to shopping cart
        if (!Service.Resolve <ICartItemChecker>().CheckNewItem(cartItemParams, ShoppingCart))
        {
            error = String.Format(GetString("ecommerce.cartcontent.productdisabled"), SKU.SKUName);
        }

        if (!string.IsNullOrEmpty(error))
        {
            // Show error message and cancel adding the product to shopping cart
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartAddItemErrorAlert", ScriptHelper.GetAlertScript(error));
            return;
        }

        // Fire on add to shopping cart event
        var eventArgs = new CancelEventArgs();

        OnAddToShoppingCart?.Invoke(this, eventArgs);

        // If adding to shopping cart was canceled
        if (eventArgs.Cancel)
        {
            return;
        }

        // Get cart item parameters in case something changed
        cartItemParams = GetShoppingCartItemParameters();

        var shoppingService = Service.Resolve <IShoppingService>();

        var addedItem = shoppingService.AddItemToCart(cartItemParams);

        if (addedItem == null)
        {
            return;
        }

        if (TrackAddToShoppingCartConversion)
        {
            // Track 'Add to shopping cart' conversion
            ECommerceHelper.TrackAddToShoppingCartConversion(addedItem);
        }

        if (RedirectToShoppingCart)
        {
            // Set shopping cart referrer
            SessionHelper.SetValue("ShoppingCartUrlReferrer", RequestContext.CurrentURL);

            // Ensure shopping cart update
            SessionHelper.SetValue("checkinventory", true);

            // Redirect to shopping cart
            URLHelper.Redirect(UrlResolver.ResolveUrl(ShoppingCartUrl));
        }
        else
        {
            // Localize SKU name
            string skuName = (addedItem.SKU != null) ? ResHelper.LocalizeString(addedItem.SKU.SKUName) : String.Empty;

            // Validate inventory
            string validateInventoryMessage = String.Empty;

            var validationErrors = ShoppingCartInfoProvider.ValidateShoppingCart(ShoppingCart);
            if (validationErrors.Any())
            {
                validateInventoryMessage = validationErrors
                                           .Select(e => HTMLHelper.HTMLEncode(e.GetMessage()))
                                           .Join("<br />");
            }

            // Get product added message
            string message = String.Format(GetString("com.productadded"), skuName);

            // Add inventory check message
            if (!String.IsNullOrEmpty(validateInventoryMessage))
            {
                message += "\n\n" + validateInventoryMessage;
            }

            // Count and show total price with options
            CalculateTotalPrice();

            // Register the call of JS handler informing about added product
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "ShoppingCartItemAddedHandler", "if (typeof ShoppingCartItemAddedHandler == 'function') { ShoppingCartItemAddedHandler(" + ScriptHelper.GetString(message) + "); }", true);
        }
    }
    /// <summary>
    /// Loads product options.
    /// </summary>
    private void LoadProductOptions()
    {
        // Get all option categories for SKU
        DataSet dsCategories = OptionCategoryInfoProvider.GetProductOptionCategories(SKUID, false);

        // Initialize product option selectors
        if (!DataHelper.DataSourceIsEmpty(dsCategories))
        {
            mProductOptions = new Hashtable();

            // Is only one option category available for variants?
            var variantCategories = Variants.Any() ? Variants.First().ProductAttributes.CategoryIDs.ToList() : null;
            mOneCategoryUsed = variantCategories != null && variantCategories.Count == 1;

            foreach (DataRow dr in dsCategories.Tables[0].Rows)
            {
                try
                {
                    // Load control for selection product options
                    ProductOptionSelector selector = (ProductOptionSelector)LoadUserControl("~/CMSModules/Ecommerce/Controls/ProductOptions/ProductOptionSelector.ascx");

                    // Add control to the collection
                    var categoryID = ValidationHelper.GetInteger(dr["CategoryID"], 0);
                    selector.ID = "opt" + categoryID;

                    // Init selector
                    selector.LocalShoppingCartObj = ShoppingCart;
                    selector.IsLiveSite           = false;
                    selector.CssClassFade         = "text-muted";
                    selector.CssClassNormal       = "normal";
                    selector.SKUID          = SKUID;
                    selector.OptionCategory = new OptionCategoryInfo(dr);

                    // If one category is used, fix the one selector with options to use only options which are not in disabled variants
                    if (mOneCategoryUsed && variantCategories.Contains(categoryID))
                    {
                        var disabled = from variant in Variants
                                       where !variant.Variant.SKUEnabled
                                       from productAttributes in variant.ProductAttributes
                                       select productAttributes.SKUID;

                        var disabledList = disabled.ToList();

                        selector.ProductOptionsInDisabledVariants = disabledList.Any() ? disabledList : null;
                    }

                    // Load all product options
                    foreach (DictionaryEntry entry in selector.ProductOptions)
                    {
                        mProductOptions[entry.Key] = entry.Value;
                    }

                    var lc = selector.SelectionControl as ListControl;
                    if (lc != null)
                    {
                        // Add Index change handler
                        lc.AutoPostBack = true;
                    }

                    pnlSelectors.Controls.Add(selector);
                }
                catch
                {
                }
            }
        }
    }